@parcha/agentrun-kernel 0.1.0-beta.31 → 0.1.0-beta.32
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 +64 -0
- package/README.md +5 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +10 -0
- package/dist/host/box.d.ts +0 -58
- package/dist/host/box.js +7 -0
- package/dist/host/index.d.ts +4 -10
- package/dist/host/index.js +2 -5
- package/dist/host/mcp-route.d.ts +3 -0
- package/dist/host/mcp-route.js +6 -2
- package/dist/host/proxy.d.ts +96 -5
- package/dist/host/proxy.js +518 -43
- package/dist/host/serial.js +2 -1
- package/dist/index.d.ts +5 -4
- package/dist/index.js +3 -2
- package/dist/kernel/cap/admit.d.ts +35 -0
- package/dist/kernel/cap/admit.js +186 -0
- package/dist/kernel/cap/errors.d.ts +20 -0
- package/dist/kernel/cap/errors.js +25 -0
- package/dist/kernel/cap/index.d.ts +14 -0
- package/dist/kernel/cap/index.js +15 -0
- package/dist/kernel/cap/ledger.d.ts +37 -0
- package/dist/kernel/cap/ledger.js +83 -0
- package/dist/kernel/cap/marks.d.ts +50 -0
- package/dist/kernel/cap/marks.js +28 -0
- package/dist/kernel/cap/park.d.ts +80 -0
- package/dist/kernel/cap/park.js +57 -0
- package/dist/kernel/cap/port.d.ts +21 -0
- package/dist/kernel/cap/port.js +95 -0
- package/dist/kernel/cap/price.d.ts +54 -0
- package/dist/kernel/cap/price.js +117 -0
- package/dist/kernel/cap/recover.d.ts +18 -0
- package/dist/kernel/cap/recover.js +71 -0
- package/dist/kernel/cap/rule.d.ts +55 -0
- package/dist/kernel/cap/rule.js +93 -0
- package/dist/kernel/cap/run-cap.d.ts +80 -0
- package/dist/kernel/cap/run-cap.js +132 -0
- package/dist/kernel/cap/steps.d.ts +36 -0
- package/dist/kernel/cap/steps.js +64 -0
- package/dist/kernel/cap/stopped.d.ts +17 -0
- package/dist/kernel/cap/stopped.js +34 -0
- package/dist/kernel/cap/types.d.ts +151 -0
- package/dist/kernel/cap/types.js +1 -0
- package/dist/kernel/cap/words.d.ts +39 -0
- package/dist/kernel/cap/words.js +75 -0
- package/dist/kernel/cap/wrap-up.d.ts +17 -0
- package/dist/kernel/cap/wrap-up.js +37 -0
- package/dist/kernel/drive.d.ts +0 -1
- package/dist/kernel/drive.js +9 -2
- package/dist/kernel/index.d.ts +1 -0
- package/dist/kernel/index.js +1 -0
- package/dist/kernel/registry/background.d.ts +12 -0
- package/dist/kernel/registry/background.js +342 -0
- package/dist/kernel/registry/bash.d.ts +3 -0
- package/dist/kernel/registry/bash.js +23 -0
- package/dist/kernel/registry/browser.d.ts +11 -0
- package/dist/kernel/registry/browser.js +14 -0
- package/dist/kernel/registry/defs.d.ts +42 -0
- package/dist/kernel/registry/defs.js +153 -0
- package/dist/kernel/registry/desktop.d.ts +11 -0
- package/dist/kernel/registry/desktop.js +90 -0
- package/dist/kernel/registry/gate.d.ts +20 -0
- package/dist/kernel/registry/gate.js +32 -0
- package/dist/kernel/registry/handoff.d.ts +11 -0
- package/dist/kernel/registry/handoff.js +51 -0
- package/dist/kernel/registry/hands.d.ts +280 -0
- package/dist/kernel/registry/hands.js +28 -0
- package/dist/kernel/registry/index.d.ts +17 -0
- package/dist/kernel/registry/index.js +14 -0
- package/dist/kernel/registry/limits.d.ts +27 -0
- package/dist/kernel/registry/limits.js +29 -0
- package/dist/kernel/registry/phone.d.ts +15 -0
- package/dist/kernel/registry/phone.js +135 -0
- package/dist/kernel/registry/registry.d.ts +22 -0
- package/dist/kernel/registry/registry.js +75 -0
- package/dist/kernel/types.d.ts +0 -7
- package/dist/process/builtins.js +1 -1
- package/dist/process/index.d.ts +1 -0
- package/dist/process/index.js +1 -0
- package/dist/process/journal.js +1 -1
- package/dist/process/recovery.js +1 -1
- package/dist/process/resume.d.ts +20 -0
- package/dist/process/resume.js +16 -0
- package/dist/process/tail.js +1 -1
- package/dist/process/tools.d.ts +8 -1
- package/dist/process/tools.js +20 -3
- package/dist/process/zod.js +1 -1
- package/dist/run-booking.d.ts +9 -0
- package/dist/run-booking.js +50 -0
- package/dist/runner.d.ts +91 -17
- package/dist/runner.js +132 -41
- package/dist/testing.d.ts +79 -12
- package/dist/testing.js +106 -13
- package/dist/types.d.ts +204 -10
- package/package.json +8 -4
- package/vendor/durable-harness/UPSTREAM.json +0 -9
- package/dist/host/box-slot.d.ts +0 -26
- package/dist/host/box-slot.js +0 -112
- package/dist/host/egress-proxy.d.ts +0 -45
- package/dist/host/egress-proxy.js +0 -416
- package/dist/host/egress-table.d.ts +0 -24
- package/dist/host/egress-table.js +0 -165
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { CAP_TOLERANCE } from "./price.js";
|
|
2
|
+
import { CAP_REFUSAL_CODE, money, suggestedRaise } from "./words.js";
|
|
3
|
+
const micro = (usd) => Math.round(usd * 1e6) / 1e6;
|
|
4
|
+
/** A bound to a millionth, rounded up (never under what it bounds), as main's overshoot bound is (run-view.ts microUp);
|
|
5
|
+
* no bound is 0, never -0 (the ceiling of a hair under 0 is -0, which a card would print as "-0"). */
|
|
6
|
+
const microUp = (usd) => Math.ceil(usd * 1e6 - 1e-9) / 1e6 + 0;
|
|
7
|
+
/** The run's end for `refusal` under `capUsd`. */
|
|
8
|
+
export function parkOf(refusal, capUsd) {
|
|
9
|
+
if (refusal.forGood || !refusal.figures)
|
|
10
|
+
return { outcome: "failed", error: refusal.message };
|
|
11
|
+
const { spentUsd, needsUsd, leastCapUsd, boundUsd } = refusal.figures;
|
|
12
|
+
const words = refusal.message.startsWith(CAP_REFUSAL_CODE) ? refusal.message.slice(CAP_REFUSAL_CODE.length) : refusal.message;
|
|
13
|
+
return {
|
|
14
|
+
outcome: "parked",
|
|
15
|
+
pending: { kind: "budget", cap_usd: capUsd, spent_usd: micro(spentUsd), needs_usd: micro(needsUsd), least_cap_usd: leastCapUsd, suggested_cap_usd: suggestedRaise(capUsd, spentUsd, needsUsd), bound_usd: microUp(boundUsd ?? 0) },
|
|
16
|
+
words,
|
|
17
|
+
event: { kind: "pause", text: words },
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export function checkRaise(state, raiseUsd) {
|
|
21
|
+
const from = state.capUsd;
|
|
22
|
+
if (from === undefined)
|
|
23
|
+
return { refused: "This run has no cap to raise: a cap is named when a run starts." };
|
|
24
|
+
if (state.final)
|
|
25
|
+
return { refused: "This run has ended: it takes no raise." };
|
|
26
|
+
if (typeof raiseUsd !== "number" || !Number.isFinite(raiseUsd))
|
|
27
|
+
return { refused: "A raise is a number of dollars." };
|
|
28
|
+
const last = state.lastRaise;
|
|
29
|
+
// The same raise again (a retry): what the first did stands. Resumed, as the first answer said, unless the run has
|
|
30
|
+
// since parked anew at another refusal: that pause is not this raise's.
|
|
31
|
+
if (Math.abs(raiseUsd - from) <= CAP_TOLERANCE && last && Math.abs(last.to - raiseUsd) <= CAP_TOLERANCE) {
|
|
32
|
+
return { retry: true, resumed: last.pause !== undefined && (state.pause === undefined || state.pause === last.pause) };
|
|
33
|
+
}
|
|
34
|
+
if (!(raiseUsd > from + CAP_TOLERANCE))
|
|
35
|
+
return { refused: `A cap is only raised: name more than the run's ${money(from)}.` };
|
|
36
|
+
return state.pause === undefined ? { raised: true, resumes: false } : { raised: true, resumes: true, pause: state.pause };
|
|
37
|
+
}
|
|
38
|
+
/** The follow-up a raised parked run goes on with: the server's words, never the person's. */
|
|
39
|
+
export const followUpOf = (capUsd) => ({ text: `The cap was raised to ${money(capUsd)}; continue the task.`, author: "server", reason: "cap_raised" });
|
|
40
|
+
/** Raise commands taken together (in id order, by the claim that wakes the run): each checked against the state the ones
|
|
41
|
+
* before it left; the run resumes once, at the latest cap, with one follow-up. */
|
|
42
|
+
export function takeRaises(state, raises) {
|
|
43
|
+
let current = { ...state };
|
|
44
|
+
let resumes = false;
|
|
45
|
+
const results = [];
|
|
46
|
+
for (const raise of raises) {
|
|
47
|
+
const check = checkRaise(current, raise.usd);
|
|
48
|
+
results.push({ id: raise.id, ...check });
|
|
49
|
+
if (check.raised) {
|
|
50
|
+
resumes ||= check.resumes;
|
|
51
|
+
current = { ...current, capUsd: raise.usd, lastRaise: { to: raise.usd, pause: current.pause } };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const capUsd = current.capUsd;
|
|
55
|
+
const followUp = resumes && capUsd !== undefined ? followUpOf(capUsd) : undefined;
|
|
56
|
+
return { capUsd, results, followUps: followUp ? 1 : 0, ...(followUp ? { followUp } : {}) };
|
|
57
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { BeforeRequest } from "../../runner.js";
|
|
2
|
+
import type { CapMode, CapModel, Previous } from "./types.js";
|
|
3
|
+
export interface BeforeRequestOptions {
|
|
4
|
+
/** The run's cap, read before every request. Undefined: no cap, nothing refused. */
|
|
5
|
+
capUsd(): number | undefined;
|
|
6
|
+
/** A model as the cap prices it, by its id; undefined: a model with no price here. */
|
|
7
|
+
modelOf(id: string): CapModel | undefined;
|
|
8
|
+
/** The session's previous request on a model, as its usage reported it: none prices the input uncached. */
|
|
9
|
+
previousOf?(model: string): Previous | undefined;
|
|
10
|
+
/** What the run spent beside the session's model requests, which the runner's booking does not hold: its priced tools'
|
|
11
|
+
* charges (null: unknown). The run's spend is the runner's plus this. A figure that is not finite and 0 or more is
|
|
12
|
+
* unknown too. */
|
|
13
|
+
spentUsd?(): number | null;
|
|
14
|
+
/** What the run's priced tools under way hold, beside the session's requests in flight (null: unknown). A figure that is
|
|
15
|
+
* not finite and 0 or more is unknown too: the request is refused, never judged as $0 held. */
|
|
16
|
+
heldUsd?(): number | null;
|
|
17
|
+
mode?: CapMode;
|
|
18
|
+
now?: () => number;
|
|
19
|
+
}
|
|
20
|
+
/** The host's beforeRequest for a CLI harness's session: the runner's spend and holds, judged by the one rule. */
|
|
21
|
+
export declare function beforeRequestOf(options: BeforeRequestOptions): BeforeRequest;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { CapRefused } from "./errors.js";
|
|
2
|
+
import { inputBound, pricingOf } from "./price.js";
|
|
3
|
+
import { capRule, isFigure } from "./rule.js";
|
|
4
|
+
import { unmeasured } from "./words.js";
|
|
5
|
+
/** A model the host has no price for: refused under a cap, by the rule. */
|
|
6
|
+
const unpriced = (id) => ({ id, api: "unknown", price: null, outputCeiling: null });
|
|
7
|
+
/** The host's beforeRequest for a CLI harness's session: the runner's spend and holds, judged by the one rule. */
|
|
8
|
+
export function beforeRequestOf(options) {
|
|
9
|
+
const mode = options.mode ?? "expected";
|
|
10
|
+
const now = options.now ?? Date.now;
|
|
11
|
+
return (request) => {
|
|
12
|
+
const capUsd = options.capUsd();
|
|
13
|
+
if (capUsd === undefined)
|
|
14
|
+
return undefined;
|
|
15
|
+
const model = options.modelOf(request.model) ?? unpriced(request.model);
|
|
16
|
+
// A request the host sends beside the harness's own (its host label: a learned workflow's node) is another
|
|
17
|
+
// conversation's prompt: nothing of the session's cache is read for it, so it is priced as a cache miss.
|
|
18
|
+
const previous = request.host === undefined ? options.previousOf?.(request.model) : undefined;
|
|
19
|
+
const asked = {
|
|
20
|
+
kind: "model",
|
|
21
|
+
id: `turn-${request.turn}`,
|
|
22
|
+
model,
|
|
23
|
+
inputTokens: request.inputTokensMax,
|
|
24
|
+
...(request.outputTokensAsked === undefined ? {} : { outputAsked: request.outputTokensAsked }),
|
|
25
|
+
...(request.outputTokensLeast === undefined ? {} : { outputTokensLeast: request.outputTokensLeast }),
|
|
26
|
+
...(previous ? { previous } : {}),
|
|
27
|
+
...(isFigure(request.feeUsd) && request.feeUsd > 0 ? { feeUsd: request.feeUsd } : {}),
|
|
28
|
+
...(request.side ? { side: true } : {}),
|
|
29
|
+
};
|
|
30
|
+
// Each request in flight at what the host held for it, else its worst case at the limit it was admitted with; one with
|
|
31
|
+
// neither (no hold, no price or no measure) cannot be kept within the cap: refused for good, as an unmeasured input.
|
|
32
|
+
let inFlight = 0;
|
|
33
|
+
for (const flight of request.inFlight) {
|
|
34
|
+
const figure = isFigure(flight.holdUsd) ? flight.holdUsd : worstOf(options.modelOf(flight.model), flight.inputTokensMax, flight.outputTokensMax);
|
|
35
|
+
if (figure === undefined)
|
|
36
|
+
return { refuse: unmeasured(capUsd) };
|
|
37
|
+
inFlight += figure;
|
|
38
|
+
}
|
|
39
|
+
// The run's spend and holds: the runner's (its model requests) and the host's (its priced tools).
|
|
40
|
+
// $0 only with no hook: a figure that is not one (null, undefined, NaN, Infinity, below 0), the runner's or a hook's,
|
|
41
|
+
// makes the run's spend or holds unknown, refused by the rule, never free and never room. Each part is checked before
|
|
42
|
+
// it is summed: a positive part would hide a negative one in the sum ($1 and -$0.50 read as a valid $0.50).
|
|
43
|
+
const toolSpent = options.spentUsd ? options.spentUsd() : 0;
|
|
44
|
+
const spentUsd = isFigure(request.spentUsd) && isFigure(toolSpent) ? request.spentUsd + toolSpent : null;
|
|
45
|
+
const toolHeld = options.heldUsd ? options.heldUsd() : 0;
|
|
46
|
+
const heldUsd = isFigure(toolHeld) ? inFlight + toolHeld : null;
|
|
47
|
+
// A paid tool call (a web search's request, a monid call): held at its price, by the rule's tool judgement (main's
|
|
48
|
+
// paidCall), its words naming it, beside the run's spend and holds.
|
|
49
|
+
if (request.paid) {
|
|
50
|
+
try {
|
|
51
|
+
const judged = capRule.judge({ kind: "tool", id: `turn-${request.turn}`, name: request.paid.name, holdUsd: request.feeUsd ?? 0, basis: request.paid.basis }, { capUsd, spentUsd, heldUsd, mode, now: now() });
|
|
52
|
+
return { holdUsd: judged.heldUsd };
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (error instanceof CapRefused)
|
|
56
|
+
return { refuse: error.message, forGood: error.forGood, ...(error.figures ? { figures: error.figures } : {}) };
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const judge = (input) => {
|
|
61
|
+
try {
|
|
62
|
+
const judged = capRule.judge({ ...asked, inputTokens: input }, { capUsd, spentUsd, heldUsd, mode, now: now() });
|
|
63
|
+
return { holdUsd: judged.heldUsd, boundUsd: judged.boundUsd, ...(judged.outputTokensMax === undefined ? {} : { outputTokensMax: judged.outputTokensMax }), stoppedUsd: judged.stoppedUsd };
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
// Its words, and what the run's end is decided from (parkOf): for good, or for room with its figures.
|
|
67
|
+
if (error instanceof CapRefused)
|
|
68
|
+
return { refuse: error.message, forGood: error.forGood, ...(error.figures ? { figures: error.figures } : {}) };
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
// A request carrying the wrap-up's note is judged as its client sent it first (inputTokensMaxWithoutNote): refused so,
|
|
73
|
+
// it is refused in those words; admitted so, it goes with the note when the note's bytes fit too, and otherwise
|
|
74
|
+
// without it (withoutNote), the note left for another request. The note never refuses what fits.
|
|
75
|
+
if (request.noted && typeof request.inputTokensMaxWithoutNote === "number") {
|
|
76
|
+
const plain = judge(request.inputTokensMaxWithoutNote);
|
|
77
|
+
if ("refuse" in plain)
|
|
78
|
+
return plain;
|
|
79
|
+
const full = judge(request.inputTokensMax);
|
|
80
|
+
return "refuse" in full ? { ...plain, withoutNote: true } : full;
|
|
81
|
+
}
|
|
82
|
+
return judge(request.inputTokensMax);
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** A request in flight with no figure held for it: its input uncached and its output limit at its model's price; no price,
|
|
86
|
+
* no measure, or priced output with neither a limit nor a ceiling (as the rule's noCeiling): undefined (it cannot be
|
|
87
|
+
* counted), never 0 and never Infinity. */
|
|
88
|
+
function worstOf(model, inputTokens, outputTokens) {
|
|
89
|
+
if (!model?.price || inputTokens === undefined)
|
|
90
|
+
return undefined;
|
|
91
|
+
if (outputTokens === undefined && model.outputCeiling === null && model.price.output > 0)
|
|
92
|
+
return undefined;
|
|
93
|
+
const bound = inputBound({ kind: "model", id: "", model, inputTokens });
|
|
94
|
+
return pricingOf(model.price)({ cached: 0, fresh: bound ?? inputTokens }, outputTokens ?? model.outputCeiling ?? 0);
|
|
95
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { CapMode, ModelCapRequest, ModelPrice, PriceRates, Previous } from "./types.js";
|
|
2
|
+
/** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
|
|
3
|
+
* Anthropic's 5. */
|
|
4
|
+
export declare const CACHE_WARM_MS: number;
|
|
5
|
+
/** The tokens a limited request keeps for its answer. */
|
|
6
|
+
export declare const ANSWER_TOKENS_LEAST = 1024;
|
|
7
|
+
/** The least thinking budget Anthropic takes. */
|
|
8
|
+
export declare const THINKING_BUDGET_LEAST = 1024;
|
|
9
|
+
/** What a stopped request counts beyond what it streamed: what the provider may have produced after the last word read. */
|
|
10
|
+
export declare const STOP_ALLOWANCE_TOKENS = 1024;
|
|
11
|
+
/** How far past what is left a sum may read and still fit it: a float's own tail, never a spend past the cap. */
|
|
12
|
+
export declare const FIT_TOLERANCE = 1e-12;
|
|
13
|
+
/** How near two caps are the same cap: a raise must be above a run's cap by more. */
|
|
14
|
+
export declare const CAP_TOLERANCE = 1e-9;
|
|
15
|
+
/** A request's input as it is priced: `cached` tokens at the cache-read price, `fresh` at the dearer of input and cache write. */
|
|
16
|
+
export type InputParts = {
|
|
17
|
+
cached: number;
|
|
18
|
+
fresh: number;
|
|
19
|
+
};
|
|
20
|
+
/** A price as a function of its input parts and its output tokens, in USD. */
|
|
21
|
+
export type Pricing = (input: InputParts, output: number) => number;
|
|
22
|
+
/** The rates of `price` for a request of `inputTokens` in all (fresh and cached): its tier with the highest threshold
|
|
23
|
+
* that input is above, else its base rates. pi-ai's calculateCost picks them so, on the same table (the catalog's), and
|
|
24
|
+
* then prices the whole request at them; serve's kernel-cap-tiers-parity test holds the two together. */
|
|
25
|
+
export declare function ratesFor(price: ModelPrice, inputTokens: number): PriceRates;
|
|
26
|
+
/** `price` as the cap prices with it: a request's cached input at the cache-read rate, its fresh input at the dearer of
|
|
27
|
+
* the input and cache-write rates, and its output at the output rate, each at the rates of the tier its whole input
|
|
28
|
+
* passes (ratesFor). A hold, a worst case and a booking the cap prices are so never under what the provider bills. */
|
|
29
|
+
export declare function pricingOf(price: ModelPrice): Pricing;
|
|
30
|
+
/** The input of a request of `bound` tokens on `model` expected after `previous`, at `now`: its cache read, and its input
|
|
31
|
+
* after the cache plus what the body grew by at full price. Undefined (all of it uncached) with no previous request, one
|
|
32
|
+
* on another model, one that ended CACHE_WARM_MS or more ago, or a clock that reads before its end. */
|
|
33
|
+
export declare function expectedInput(bound: number, previous: Previous | undefined, now: number, model: string): InputParts | undefined;
|
|
34
|
+
/** A request priced under `mode`: `cost(output)`, what it is held at (its expected input, never more than uncached), and
|
|
35
|
+
* `worst(output)`, its input uncached; each with its hosted tools' most fee. */
|
|
36
|
+
export declare function requestPrice(pricing: Pricing, bound: number, previous: Previous | undefined, now: number, mode: CapMode, model: string, feeUsd?: number): {
|
|
37
|
+
cost(output: number): number;
|
|
38
|
+
worst(output: number): number;
|
|
39
|
+
};
|
|
40
|
+
/** A request's whole input bound: its measured bytes, what its provider adds for what it carries, and what its hosted tools
|
|
41
|
+
* read. Undefined when its bytes were not measured. */
|
|
42
|
+
export declare function inputBound(request: ModelCapRequest): number | undefined;
|
|
43
|
+
/** The output a request is sent with at most: what it asks (its model's ceiling when it says none), and its thinking budget
|
|
44
|
+
* on an API whose thinking takes one, within the ceiling. Undefined: no ceiling and none asked. */
|
|
45
|
+
export declare function outputAsked(request: ModelCapRequest): number | undefined;
|
|
46
|
+
/** The least output a request may be limited to and still answer: what its body says, else the answer's 1,024 tokens and
|
|
47
|
+
* its thinking's least (the least budget where thinking takes one, else its whole budget, which then shares the limit);
|
|
48
|
+
* never more than it asks. */
|
|
49
|
+
export declare function outputLeast(request: ModelCapRequest, asked: number): number;
|
|
50
|
+
/** The thinking budget a request limited to `output` keeps: its own, squeezed so the answer keeps its 1,024 tokens. */
|
|
51
|
+
export declare function thinkingWithin(request: ModelCapRequest, output: number): number | undefined;
|
|
52
|
+
/** The most output tokens from `least` to `asked` whose request costs no more than `left`; undefined when even `least`
|
|
53
|
+
* costs more. A search, so a price with tiers is exact. */
|
|
54
|
+
export declare function mostOutput(cost: (output: number) => number, least: number, asked: number, left: number): number | undefined;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// The kernel cap's one pricing rule, the same for every harness. A request's input bound (its measured bytes, what its
|
|
2
|
+
// provider adds, what its hosted tools read) is priced at the dearer of the input and cache-write prices; under "expected"
|
|
3
|
+
// the previous request's cache counts at the cache-read price when it ended under CACHE_WARM_MS ago on the same model, so
|
|
4
|
+
// only a cache miss can pass the cap, by at most the request's bound; under "strict" every token uncached. Its output is
|
|
5
|
+
// held at what it is sent with, its thinking budget included.
|
|
6
|
+
import { providerInputOverhead } from "../../host/overhead.js";
|
|
7
|
+
/** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
|
|
8
|
+
* Anthropic's 5. */
|
|
9
|
+
export const CACHE_WARM_MS = 4 * 60_000;
|
|
10
|
+
/** The tokens a limited request keeps for its answer. */
|
|
11
|
+
export const ANSWER_TOKENS_LEAST = 1_024;
|
|
12
|
+
/** The least thinking budget Anthropic takes. */
|
|
13
|
+
export const THINKING_BUDGET_LEAST = 1_024;
|
|
14
|
+
/** What a stopped request counts beyond what it streamed: what the provider may have produced after the last word read. */
|
|
15
|
+
export const STOP_ALLOWANCE_TOKENS = 1_024;
|
|
16
|
+
/** How far past what is left a sum may read and still fit it: a float's own tail, never a spend past the cap. */
|
|
17
|
+
export const FIT_TOLERANCE = 1e-12;
|
|
18
|
+
/** How near two caps are the same cap: a raise must be above a run's cap by more. */
|
|
19
|
+
export const CAP_TOLERANCE = 1e-9;
|
|
20
|
+
/** The APIs whose thinking takes a token budget added to the request's own output limit. */
|
|
21
|
+
const BUDGET_APIS = new Set(["anthropic-messages", "bedrock-converse-stream"]);
|
|
22
|
+
/** The rates of `price` for a request of `inputTokens` in all (fresh and cached): its tier with the highest threshold
|
|
23
|
+
* that input is above, else its base rates. pi-ai's calculateCost picks them so, on the same table (the catalog's), and
|
|
24
|
+
* then prices the whole request at them; serve's kernel-cap-tiers-parity test holds the two together. */
|
|
25
|
+
export function ratesFor(price, inputTokens) {
|
|
26
|
+
let rates = price;
|
|
27
|
+
let threshold = -1;
|
|
28
|
+
for (const tier of price.tiers ?? []) {
|
|
29
|
+
if (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > threshold) {
|
|
30
|
+
rates = tier;
|
|
31
|
+
threshold = tier.inputTokensAbove;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return rates;
|
|
35
|
+
}
|
|
36
|
+
/** `price` as the cap prices with it: a request's cached input at the cache-read rate, its fresh input at the dearer of
|
|
37
|
+
* the input and cache-write rates, and its output at the output rate, each at the rates of the tier its whole input
|
|
38
|
+
* passes (ratesFor). A hold, a worst case and a booking the cap prices are so never under what the provider bills. */
|
|
39
|
+
export function pricingOf(price) {
|
|
40
|
+
return (parts, output) => {
|
|
41
|
+
const rates = ratesFor(price, parts.cached + parts.fresh);
|
|
42
|
+
const read = rates.cacheRead ?? rates.input;
|
|
43
|
+
const fresh = Math.max(rates.input, rates.cacheWrite ?? rates.input);
|
|
44
|
+
return (parts.cached * read + parts.fresh * fresh + output * rates.output) / 1e6;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** The input of a request of `bound` tokens on `model` expected after `previous`, at `now`: its cache read, and its input
|
|
48
|
+
* after the cache plus what the body grew by at full price. Undefined (all of it uncached) with no previous request, one
|
|
49
|
+
* on another model, one that ended CACHE_WARM_MS or more ago, or a clock that reads before its end. */
|
|
50
|
+
export function expectedInput(bound, previous, now, model) {
|
|
51
|
+
if (!previous || previous.model !== model)
|
|
52
|
+
return undefined;
|
|
53
|
+
const gap = now - previous.endedAt;
|
|
54
|
+
if (!(gap >= 0 && gap < CACHE_WARM_MS))
|
|
55
|
+
return undefined;
|
|
56
|
+
return { cached: previous.cachedTokens, fresh: previous.inputTokens + Math.max(0, bound - previous.boundTokens) };
|
|
57
|
+
}
|
|
58
|
+
/** A request priced under `mode`: `cost(output)`, what it is held at (its expected input, never more than uncached), and
|
|
59
|
+
* `worst(output)`, its input uncached; each with its hosted tools' most fee. */
|
|
60
|
+
export function requestPrice(pricing, bound, previous, now, mode, model, feeUsd = 0) {
|
|
61
|
+
const worst = (output) => pricing({ cached: 0, fresh: bound }, output) + feeUsd;
|
|
62
|
+
const parts = mode === "strict" ? undefined : expectedInput(bound, previous, now, model);
|
|
63
|
+
if (!parts)
|
|
64
|
+
return { cost: worst, worst };
|
|
65
|
+
return { cost: (output) => Math.min(pricing(parts, output) + feeUsd, worst(output)), worst };
|
|
66
|
+
}
|
|
67
|
+
/** A request's whole input bound: its measured bytes, what its provider adds for what it carries, and what its hosted tools
|
|
68
|
+
* read. Undefined when its bytes were not measured. */
|
|
69
|
+
export function inputBound(request) {
|
|
70
|
+
const measured = request.inputTokens;
|
|
71
|
+
if (typeof measured !== "number" || !Number.isFinite(measured) || measured < 0)
|
|
72
|
+
return undefined;
|
|
73
|
+
const added = request.shape ? providerInputOverhead(request.model.api, request.shape) : 0;
|
|
74
|
+
return measured + added + (request.extraInputTokens ?? 0);
|
|
75
|
+
}
|
|
76
|
+
/** The output a request is sent with at most: what it asks (its model's ceiling when it says none), and its thinking budget
|
|
77
|
+
* on an API whose thinking takes one, within the ceiling. Undefined: no ceiling and none asked. */
|
|
78
|
+
export function outputAsked(request) {
|
|
79
|
+
const ceiling = request.model.outputCeiling ?? undefined;
|
|
80
|
+
const asked = request.outputAsked ?? ceiling;
|
|
81
|
+
if (asked === undefined)
|
|
82
|
+
return undefined;
|
|
83
|
+
const withThinking = asked + (thinks(request) && BUDGET_APIS.has(request.model.api) ? request.thinkingBudget : 0);
|
|
84
|
+
return ceiling === undefined ? withThinking : Math.min(withThinking, ceiling);
|
|
85
|
+
}
|
|
86
|
+
/** The least output a request may be limited to and still answer: what its body says, else the answer's 1,024 tokens and
|
|
87
|
+
* its thinking's least (the least budget where thinking takes one, else its whole budget, which then shares the limit);
|
|
88
|
+
* never more than it asks. */
|
|
89
|
+
export function outputLeast(request, asked) {
|
|
90
|
+
const least = request.outputTokensLeast ?? ANSWER_TOKENS_LEAST + (thinks(request) ? (BUDGET_APIS.has(request.model.api) ? THINKING_BUDGET_LEAST : request.thinkingBudget) : 0);
|
|
91
|
+
return Math.min(least, asked);
|
|
92
|
+
}
|
|
93
|
+
const thinks = (request) => typeof request.thinkingBudget === "number" && request.thinkingBudget > 0;
|
|
94
|
+
/** The thinking budget a request limited to `output` keeps: its own, squeezed so the answer keeps its 1,024 tokens. */
|
|
95
|
+
export function thinkingWithin(request, output) {
|
|
96
|
+
if (!thinks(request) || !BUDGET_APIS.has(request.model.api))
|
|
97
|
+
return undefined;
|
|
98
|
+
return Math.max(0, Math.min(request.thinkingBudget, output - ANSWER_TOKENS_LEAST));
|
|
99
|
+
}
|
|
100
|
+
/** The most output tokens from `least` to `asked` whose request costs no more than `left`; undefined when even `least`
|
|
101
|
+
* costs more. A search, so a price with tiers is exact. */
|
|
102
|
+
export function mostOutput(cost, least, asked, left) {
|
|
103
|
+
const fits = (tokens) => cost(tokens) <= left + FIT_TOLERANCE;
|
|
104
|
+
if (!fits(least))
|
|
105
|
+
return undefined;
|
|
106
|
+
if (fits(asked))
|
|
107
|
+
return asked;
|
|
108
|
+
let [low, high] = [least, asked];
|
|
109
|
+
while (high - low > 1) {
|
|
110
|
+
const mid = Math.floor((low + high) / 2);
|
|
111
|
+
if (fits(mid))
|
|
112
|
+
low = mid;
|
|
113
|
+
else
|
|
114
|
+
high = mid;
|
|
115
|
+
}
|
|
116
|
+
return low;
|
|
117
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { CapMark } from "./marks.js";
|
|
2
|
+
/** What the marks say: the cap's spend (null: unknown), the run's reported cost (null once any step's own cost is unknown,
|
|
3
|
+
* as a step a crash cut), the bound of the steps still open, and how many requests were sent (a refused one is none). */
|
|
4
|
+
export type Spend = {
|
|
5
|
+
spentUsd: number | null;
|
|
6
|
+
reportedUsd: number | null;
|
|
7
|
+
boundUsd: number;
|
|
8
|
+
requests: number;
|
|
9
|
+
};
|
|
10
|
+
export declare function spendOf(marks: readonly CapMark[]): Spend;
|
|
11
|
+
/** A run's own priced answers from its marks, as the live cap counts them: each main-model request (never a side call or
|
|
12
|
+
* a paid call) whose end is an answer with a cost above 0, with its model. */
|
|
13
|
+
export declare function ownCostsOf(marks: readonly CapMark[]): {
|
|
14
|
+
model: string;
|
|
15
|
+
usd: number;
|
|
16
|
+
}[];
|
|
17
|
+
/** Whether the run's wrap-up was told (a told mark). */
|
|
18
|
+
export declare const toldIn: (marks: readonly CapMark[]) => boolean;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
export function spendOf(marks) {
|
|
2
|
+
let spent = 0;
|
|
3
|
+
let reported = 0;
|
|
4
|
+
let bound = 0;
|
|
5
|
+
let requests = 0;
|
|
6
|
+
const add = (usd, known) => {
|
|
7
|
+
spent = spent === null || usd === null ? null : spent + usd;
|
|
8
|
+
reported = reported === null || usd === null || !known ? null : reported + usd;
|
|
9
|
+
};
|
|
10
|
+
/** Each id's step under way (its start, no end yet), and the ids whose last step has its end: read in order, so an id
|
|
11
|
+
* used again after its step ended is a step of its own, and an end with no step under way is not counted twice. */
|
|
12
|
+
const open = new Map();
|
|
13
|
+
const ended = new Set();
|
|
14
|
+
/** Ends read before any start of their id (marks that fall out of order): each closes the start that comes after it. */
|
|
15
|
+
const early = new Set();
|
|
16
|
+
const cut = (start) => {
|
|
17
|
+
// A crash cut it: it counts at what it was held at, and no one knows what it cost.
|
|
18
|
+
add(start.heldUsd, false);
|
|
19
|
+
bound += start.boundUsd ?? 0;
|
|
20
|
+
};
|
|
21
|
+
for (const mark of marks) {
|
|
22
|
+
if (mark.kind === "start") {
|
|
23
|
+
if (mark.refused)
|
|
24
|
+
continue;
|
|
25
|
+
if (!mark.tool)
|
|
26
|
+
requests++;
|
|
27
|
+
if (early.delete(mark.id))
|
|
28
|
+
continue;
|
|
29
|
+
const before = open.get(mark.id);
|
|
30
|
+
if (before)
|
|
31
|
+
cut(before);
|
|
32
|
+
open.set(mark.id, mark);
|
|
33
|
+
ended.delete(mark.id);
|
|
34
|
+
}
|
|
35
|
+
else if (mark.kind === "end") {
|
|
36
|
+
if (open.has(mark.id)) {
|
|
37
|
+
open.delete(mark.id);
|
|
38
|
+
ended.add(mark.id);
|
|
39
|
+
add(mark.usd, true);
|
|
40
|
+
}
|
|
41
|
+
else if (!ended.has(mark.id)) {
|
|
42
|
+
// An end with no start yet (out of order, or a step whose start mark is gone) counts its figure, once, and closes
|
|
43
|
+
// the start of its id that comes after it.
|
|
44
|
+
ended.add(mark.id);
|
|
45
|
+
early.add(mark.id);
|
|
46
|
+
add(mark.usd, true);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
for (const start of open.values())
|
|
51
|
+
cut(start);
|
|
52
|
+
return { spentUsd: spent, reportedUsd: reported, boundUsd: bound, requests };
|
|
53
|
+
}
|
|
54
|
+
/** A run's own priced answers from its marks, as the live cap counts them: each main-model request (never a side call or
|
|
55
|
+
* a paid call) whose end is an answer with a cost above 0, with its model. */
|
|
56
|
+
export function ownCostsOf(marks) {
|
|
57
|
+
const starts = new Map();
|
|
58
|
+
const costs = [];
|
|
59
|
+
for (const mark of marks) {
|
|
60
|
+
if (mark.kind === "start")
|
|
61
|
+
starts.set(mark.id, mark);
|
|
62
|
+
else if (mark.kind === "end") {
|
|
63
|
+
const start = starts.get(mark.id);
|
|
64
|
+
if (start?.model && !start.side && !start.tool && mark.rule?.startsWith("answered") && typeof mark.usd === "number" && mark.usd > 0)
|
|
65
|
+
costs.push({ model: start.model, usd: mark.usd });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return costs;
|
|
69
|
+
}
|
|
70
|
+
/** Whether the run's wrap-up was told (a told mark). */
|
|
71
|
+
export const toldIn = (marks) => marks.some((mark) => mark.kind === "told");
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { CapMode, ModelCapRequest, ToolCapRequest } from "./types.js";
|
|
2
|
+
/** What a judgement reads: the cap (read before this check), the run's spend (null: unknown) and its holds (null:
|
|
3
|
+
* unknown). */
|
|
4
|
+
export type JudgeState = {
|
|
5
|
+
capUsd: number;
|
|
6
|
+
spentUsd: number | null;
|
|
7
|
+
heldUsd: number | null;
|
|
8
|
+
mode: CapMode;
|
|
9
|
+
now: number;
|
|
10
|
+
};
|
|
11
|
+
/** A money figure the cap can count: a finite number of 0 or more. Anything else (null, NaN, Infinity, below 0) is
|
|
12
|
+
* unknown: it never reads as $0 and never frees room. */
|
|
13
|
+
export declare const isFigure: (usd: unknown) => usd is number;
|
|
14
|
+
/** A step admitted: what it is held at, the most a cache miss adds, its worst case, the output it may be sent with and its
|
|
15
|
+
* thinking budget, and what it counts at if stopped having streamed that many tokens (within its hold). */
|
|
16
|
+
export type Judged = {
|
|
17
|
+
heldUsd: number;
|
|
18
|
+
boundUsd: number;
|
|
19
|
+
worstUsd: number;
|
|
20
|
+
outputTokensMax?: number;
|
|
21
|
+
thinkingBudget?: number;
|
|
22
|
+
stoppedUsd(streamedTokens: number): number;
|
|
23
|
+
};
|
|
24
|
+
/** A model request priced: its output asked and least, and its cost and worst case at an output. */
|
|
25
|
+
export declare function priced(request: ModelCapRequest, mode: CapMode, now: number): {
|
|
26
|
+
asked: number | undefined;
|
|
27
|
+
cost: (output: number) => number;
|
|
28
|
+
worst: (output: number) => number;
|
|
29
|
+
least: number;
|
|
30
|
+
} | undefined;
|
|
31
|
+
/** The one rule: admits `request` under `state`, or throws CapRefused. */
|
|
32
|
+
declare function judge(request: ModelCapRequest | ToolCapRequest, state: JudgeState): Judged;
|
|
33
|
+
/** The rule's entry, called through this object by every path. */
|
|
34
|
+
export declare const capRule: {
|
|
35
|
+
judge: typeof judge;
|
|
36
|
+
};
|
|
37
|
+
/** What the wrap-up reads: the cap, spend and holds as admission counts them, the run's own priced answers on the
|
|
38
|
+
* request's model, and whether it was told. */
|
|
39
|
+
export type NoteState = {
|
|
40
|
+
capUsd: number | undefined;
|
|
41
|
+
spentUsd: number | null;
|
|
42
|
+
heldUsd: number;
|
|
43
|
+
costs: readonly number[];
|
|
44
|
+
told: boolean;
|
|
45
|
+
mode: CapMode;
|
|
46
|
+
now: number;
|
|
47
|
+
};
|
|
48
|
+
/** The wrap-up for `request`, the run's next main-model request measured before the note is placed: due under three times
|
|
49
|
+
* the typical cost (step 0: its input and a 4,096-token answer) or twice its least, not yet told, never for a side call,
|
|
50
|
+
* and never when the request fits what is left only without the note's bytes. */
|
|
51
|
+
export declare function noteFor(request: ModelCapRequest, state: NoteState): {
|
|
52
|
+
words: string;
|
|
53
|
+
leftUsd: number;
|
|
54
|
+
} | undefined;
|
|
55
|
+
export {};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// The kernel cap's one rule, stateless: given the cap, what the run has spent and what its steps under way hold, judge
|
|
2
|
+
// admits a step (what it is held at, the output it may be sent with) or refuses it in words; noteFor decides the wrap-up.
|
|
3
|
+
// Every path calls these and nothing else decides: createCap (pi, decisions, tools, on its own ledger) and beforeRequestOf
|
|
4
|
+
// (the CLI harnesses, on the runner's booking). capRule.judge is called through the object, once per decision, so a test
|
|
5
|
+
// can see that no path decides without it.
|
|
6
|
+
import { CapRefused } from "./errors.js";
|
|
7
|
+
import { FIT_TOLERANCE, inputBound, mostOutput, outputAsked, outputLeast, pricingOf, requestPrice, STOP_ALLOWANCE_TOKENS, thinkingWithin } from "./price.js";
|
|
8
|
+
import { typicalCost, WRAP_UP_STEP0_ANSWER_TOKENS, wrapUpDue, wrapUpWords } from "./wrap-up.js";
|
|
9
|
+
import { noCeiling, noPrice, noToolPrice, paidRefusal, roomRefusal, unknownHeld, unknownSpend, unmeasured } from "./words.js";
|
|
10
|
+
/** A money figure the cap can count: a finite number of 0 or more. Anything else (null, NaN, Infinity, below 0) is
|
|
11
|
+
* unknown: it never reads as $0 and never frees room. */
|
|
12
|
+
export const isFigure = (usd) => typeof usd === "number" && Number.isFinite(usd) && usd >= 0;
|
|
13
|
+
/** A model request priced: its output asked and least, and its cost and worst case at an output. */
|
|
14
|
+
export function priced(request, mode, now) {
|
|
15
|
+
const bound = inputBound(request);
|
|
16
|
+
const price = request.model.price;
|
|
17
|
+
if (bound === undefined || price === null)
|
|
18
|
+
return undefined;
|
|
19
|
+
const asked = outputAsked(request);
|
|
20
|
+
const { cost, worst } = requestPrice(pricingOf(price), bound, request.previous, now, mode, request.model.id, request.feeUsd ?? 0);
|
|
21
|
+
return { asked, cost, worst, least: asked === undefined ? 0 : outputLeast(request, asked) };
|
|
22
|
+
}
|
|
23
|
+
function judgeModel(request, { capUsd, spentUsd: spent, heldUsd: held, mode, now }) {
|
|
24
|
+
if (inputBound(request) === undefined)
|
|
25
|
+
throw new CapRefused(unmeasured(capUsd), { forGood: true, spentUsd: spent });
|
|
26
|
+
const price = request.model.price;
|
|
27
|
+
if (price === null)
|
|
28
|
+
throw new CapRefused(noPrice(capUsd), { forGood: true, spentUsd: spent });
|
|
29
|
+
if (request.model.outputCeiling === null && price.output > 0)
|
|
30
|
+
throw new CapRefused(noCeiling(capUsd), { forGood: true, spentUsd: spent });
|
|
31
|
+
const p = priced(request, mode, now);
|
|
32
|
+
const output = mostOutput(p.cost, p.least, p.asked ?? 0, capUsd - spent - held);
|
|
33
|
+
if (output === undefined) {
|
|
34
|
+
const { text, figures } = roomRefusal(capUsd, spent, held, p.cost(p.least), p.worst(p.least) - p.cost(p.least));
|
|
35
|
+
throw new CapRefused(text, { forGood: false, spentUsd: spent, figures });
|
|
36
|
+
}
|
|
37
|
+
const heldUsd = p.cost(output);
|
|
38
|
+
const worstUsd = p.worst(output);
|
|
39
|
+
const stoppedPrice = (streamed) => p.cost(Math.min(output, streamed + STOP_ALLOWANCE_TOKENS));
|
|
40
|
+
const thinking = thinkingWithin(request, output);
|
|
41
|
+
return {
|
|
42
|
+
heldUsd,
|
|
43
|
+
boundUsd: Math.max(0, worstUsd - heldUsd),
|
|
44
|
+
worstUsd,
|
|
45
|
+
...(p.asked === undefined ? {} : { outputTokensMax: output }),
|
|
46
|
+
...(thinking === undefined ? {} : { thinkingBudget: thinking }),
|
|
47
|
+
stoppedUsd: (streamed) => Math.min(heldUsd, stoppedPrice(streamed)),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function judgeTool(request, { capUsd, spentUsd: spent, heldUsd: held }) {
|
|
51
|
+
// A hold that is not a finite figure of 0 or more cannot be kept within a cap (a NaN would fail every check open; a
|
|
52
|
+
// negative one would free room): refused for good.
|
|
53
|
+
if (typeof request.holdUsd !== "number" || !Number.isFinite(request.holdUsd) || request.holdUsd < 0)
|
|
54
|
+
throw new CapRefused(noToolPrice(capUsd, request.name), { forGood: true, spentUsd: spent });
|
|
55
|
+
// Written so that a figure that is not a number refuses.
|
|
56
|
+
if (!(spent + held + request.holdUsd <= capUsd + FIT_TOLERANCE)) {
|
|
57
|
+
const { text, figures } = paidRefusal(capUsd, spent, held, request.name, request.holdUsd, request.basis);
|
|
58
|
+
throw new CapRefused(text, { forGood: false, spentUsd: spent, figures });
|
|
59
|
+
}
|
|
60
|
+
return { heldUsd: request.holdUsd, boundUsd: 0, worstUsd: request.holdUsd, stoppedUsd: () => request.holdUsd };
|
|
61
|
+
}
|
|
62
|
+
/** The one rule: admits `request` under `state`, or throws CapRefused. */
|
|
63
|
+
function judge(request, state) {
|
|
64
|
+
// An unknown figure refuses for good: no raise can make it fit, and none is read as $0 (its words never say NaN).
|
|
65
|
+
if (!isFigure(state.spentUsd))
|
|
66
|
+
throw new CapRefused(unknownSpend(state.capUsd), { forGood: true, spentUsd: null });
|
|
67
|
+
if (!isFigure(state.heldUsd))
|
|
68
|
+
throw new CapRefused(unknownHeld(state.capUsd), { forGood: true, spentUsd: state.spentUsd });
|
|
69
|
+
const known = { ...state, spentUsd: state.spentUsd, heldUsd: state.heldUsd };
|
|
70
|
+
return request.kind === "model" ? judgeModel(request, known) : judgeTool(request, known);
|
|
71
|
+
}
|
|
72
|
+
/** The rule's entry, called through this object by every path. */
|
|
73
|
+
export const capRule = { judge };
|
|
74
|
+
/** The wrap-up for `request`, the run's next main-model request measured before the note is placed: due under three times
|
|
75
|
+
* the typical cost (step 0: its input and a 4,096-token answer) or twice its least, not yet told, never for a side call,
|
|
76
|
+
* and never when the request fits what is left only without the note's bytes. */
|
|
77
|
+
export function noteFor(request, state) {
|
|
78
|
+
if (request.side || state.told || state.capUsd === undefined || state.spentUsd === null)
|
|
79
|
+
return undefined;
|
|
80
|
+
const p = priced(request, state.mode, state.now);
|
|
81
|
+
if (!p)
|
|
82
|
+
return undefined;
|
|
83
|
+
const least = p.cost(p.least);
|
|
84
|
+
const typical = typicalCost(state.costs, p.cost(Math.min(p.asked ?? 0, WRAP_UP_STEP0_ANSWER_TOKENS)));
|
|
85
|
+
const due = wrapUpDue(state.capUsd, state.spentUsd, state.heldUsd, typical, least);
|
|
86
|
+
if (!due)
|
|
87
|
+
return undefined;
|
|
88
|
+
const words = wrapUpWords(due.leftUsd, state.costs.length === 0);
|
|
89
|
+
const noted = priced({ ...request, inputTokens: (request.inputTokens ?? 0) + Buffer.byteLength(words, "utf8") }, state.mode, state.now);
|
|
90
|
+
if (noted && noted.cost(noted.least) > due.leftUsd + FIT_TOLERANCE && least <= due.leftUsd + FIT_TOLERANCE)
|
|
91
|
+
return undefined;
|
|
92
|
+
return { words, leftUsd: due.leftUsd };
|
|
93
|
+
}
|