@parcha/agentrun-kernel 0.1.0-beta.34 → 0.1.0-beta.36
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 +40 -0
- package/README.md +0 -7
- package/dist/host/box.d.ts +0 -14
- package/dist/host/index.d.ts +4 -4
- package/dist/host/index.js +2 -2
- package/dist/host/overhead.d.ts +75 -4
- package/dist/host/overhead.js +220 -10
- package/dist/host/proxy.d.ts +40 -4
- package/dist/host/proxy.js +87 -3
- package/dist/index.d.ts +0 -2
- package/dist/index.js +0 -1
- package/dist/kernel/cap/index.d.ts +1 -1
- package/dist/kernel/cap/index.js +1 -1
- package/dist/kernel/cap/port.d.ts +3 -2
- package/dist/kernel/cap/port.js +2 -2
- package/dist/kernel/cap/price.js +5 -2
- package/dist/kernel/cap/run-cap.d.ts +2 -2
- package/dist/kernel/cap/run-cap.js +1 -1
- package/dist/kernel/cap/types.d.ts +7 -0
- package/dist/kernel/cap/words.d.ts +3 -0
- package/dist/kernel/cap/words.js +5 -2
- package/dist/kernel/index.d.ts +0 -2
- package/dist/kernel/index.js +0 -1
- package/dist/kernel/registry/index.d.ts +1 -1
- package/dist/kernel/registry/index.js +1 -1
- package/dist/kernel/registry/limits.d.ts +0 -1
- package/dist/kernel/registry/limits.js +0 -1
- package/dist/process/records.d.ts +0 -16
- package/dist/process/records.js +0 -41
- package/dist/process/settle.d.ts +1 -1
- package/dist/process/settle.js +2 -2
- package/dist/process/tools.d.ts +9 -0
- package/dist/process/tools.js +19 -6
- package/dist/process/zod.d.ts +0 -2
- package/dist/process/zod.js +0 -4
- package/dist/runner.d.ts +8 -0
- package/dist/runner.js +3 -3
- package/dist/testing.d.ts +17 -5
- package/dist/testing.js +72 -21
- package/dist/types.d.ts +15 -5
- package/package.json +3 -3
- package/dist/delegate.d.ts +0 -87
- package/dist/delegate.js +0 -143
- package/dist/kernel/follow-up.d.ts +0 -67
- package/dist/kernel/follow-up.js +0 -146
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,46 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.36 (2026-11-13)
|
|
6
|
+
|
|
7
|
+
- The kernel and the Claude Agent test kit drop exports nothing in AgentRun used. From `@parcha/agentrun-kernel`: the `delegate` tool (`delegateTool`, `DELEGATE_TOOL`, `DELEGATE_RESULT_SCHEMA`, `delegateProblems` and the `DelegateAgent`, `DelegateEvent` and `DelegateOptions` types). From `./kernel`: the follow-up turn (`followUpOnce`, `followUpState`, `followUpKey`, `FOLLOW_UP_EFFECT`, `FOLLOW_UP_BUDGET_REACHED`, `FOLLOW_UP_CANCELLED` and their types) and `BASH_MAX_TIMEOUT_S`. From `./process`: `lastTurnEnd`, `summarizeBatch`, `batchTranscript` and `zodFromJsonSchema`. From `@parcha/agentrun-harness-claude/testing`: `lastUserText`. An embedder that imported one of them keeps its own copy: each was a small helper, or a feature the server never wired (a follow-up turn, a delegate tool). `zodShapeFromJsonSchema` stays.
|
|
8
|
+
- `@parcha/agentrun-kernel/host` no longer exports the types `BoxRecorder` and `Reaped`; nothing in the repo used them. A host that imported either declares its own shape.
|
|
9
|
+
- A run's spend-cap pause no longer says it spent "$0" when it spent less than a cent. The words round what was spent to the cent, so a run that had spent $0.003 read "this run has spent $0 of its $0.105 cap", as if nothing had been spent. A spend above $0 that rounds to $0 now reads "less than a cent" ("this run has spent less than a cent of its $0.105 cap"). A spend of exactly $0, and any spend of a cent or more, reads as before. The exact amount stays in the pause's `spent_usd`.
|
|
10
|
+
- A model request a provider refuses for a while (a 429 at capacity, an overload, a 5xx) no longer ends the run after pi's default three retries of about 17 seconds. The adapter loop gives pi 8 retries, 2s doubling to at most 30s apart (about two and a half minutes), and pi-ai retries a request refused before any output twice more inside each attempt, after the wait the provider asked for: the session's model proxy now passes an error answer's `retry-after`, `retry-after-ms` and `x-should-retry` on to the client. Each retry is a new request the run's cap judges and books: a refused one books nothing, and one that finds no room under the cap parks the run in the cap's words, never retried past it.
|
|
11
|
+
|
|
12
|
+
## 0.1.0-beta.35 (2026-11-11)
|
|
13
|
+
|
|
14
|
+
- On the runner, a learned workflow node that names a tier (`fast`, `strong`) now runs on the host's model of that tier (`AGENT_MODEL_FAST`, `AGENT_MODEL_STRONG`) instead of the run's own model. Its requests take the run's one route and stay under the run's cap, and each is booked at its own model's price. A tier the host names no model of still runs on the run's own model. A tier whose model can't be reached fails the workflow call and names why; it never runs on another model. This holds on every harness: pi, Claude Agent, Codex and OpenCode. On a CLI harness the tier's requests go through a proxy of their own beside the CLI session's, never through the CLI. A tier's model key saved in Settings → Model keys is opened for that tier's requests alone. It never goes into a tool's environment. A tier whose model has the same id as the run's model is still held and booked at the tier's own price. `AdapterSession.port` and the run ledger's `models` take an optional `tier`. The kernel's `ModelRequest`, `ModelProxyOptions` and in-flight records carry an optional `route`, and the cap's `modelOf(id, route)` prices a request by model and route.
|
|
15
|
+
Who breaks: a host that already sets `AGENT_MODEL_FAST` or `AGENT_MODEL_STRONG` changes with no action. Its learned workflows' nodes of that tier now run on that model and at its price, and when that model can't be reached the learned_workflow call fails where it used to run on the run's own model.
|
|
16
|
+
Upgrading: a host whose `AGENT_MODEL_FAST` or `AGENT_MODEL_STRONG` names a model it can't reach should unset it or make the model reachable; learned tier nodes now run on it.
|
|
17
|
+
- A capped run straight to Anthropic is no longer paused by a cap it could work under. Before each answer request on a route to `https://api.anthropic.com` (pi and claude-agent), the model proxy asks Anthropic's free token count (`POST /v1/messages/count_tokens`). It sends only the credential and version headers, and never goes through a gateway or any other base. The request's input bound is then that count plus the tool-use prompt, where before it was the body's bytes (about two to three times the tokens billed). A count that fails, says nothing or takes over 3 seconds leaves the byte bound, and the request goes on. Through OpenRouter or any other gateway the bound stays the bytes, so the cap still never passes.
|
|
18
|
+
|
|
19
|
+
The serve README's spend-cap section now states the smallest cap that works, by cap mode, measured on a pi desktop run on Sonnet. In `strict` mode (and in `expected`, the default, until the runner prices a step from the previous request's cache, #2504) it is $0.05 for the first request and $0.11 for a five-step run through a gateway, and $0.03 and $0.09 straight to Anthropic. The console's cap fields say it in a line, with a link. A cap below these still pauses with `Not sent: ... the next step needs at least $X`. A policy may count a request through `ProviderPolicy.countInput` (`InputCounter`, `countedInputOf` in the kernel host).
|
|
20
|
+
- A Claude Code or Codex call that needs approval shows on the run's timeline while it waits, and the test harness for those CLIs asks the tool gate before each call, as the real ones do:
|
|
21
|
+
- serve: a CLI call the tool gate asks about goes on the run's record as it parks, its start marked parked, the way an MCP call parked at its door already did. Before, the timeline showed the approval card with no call row above it until the call ran. An allowed call then runs under that one start; a stop withdraws it and its row reads "Not run: the run was stopped while it waited".
|
|
22
|
+
- kernel: `askGate(gate, call, signal)` (`process/tools.ts`) is the gate step every tool bridge takes first: undefined for an allow, the refusal for a deny, and a park holds the call until the signal aborts. The faux harness in `@parcha/agentrun-kernel/testing` now asks it before each call: a deny is the call's answer, recorded so it is never asked again, and a park holds the turn. A recovered turn first runs the calls its last request left with no intent and no result (a parked one), under their own ids, as a real CLI's resume does. A test that scripts a faux CLI call to a tool set to ask (a `monid.` or MCP catalog tool by default) now sees the run park on it.
|
|
23
|
+
- Runs on the runner behave as before the cutover in four places a person could hit:
|
|
24
|
+
- A run keeps the files it was started with. The server holds each of a run's `file_ids` for it at the start, so a file deleted between the start and the runner's claim is still copied into the run's `inputs/`. The hold goes once the copy is made, or when the run ends without one.
|
|
25
|
+
- A copy of a run's files that fails ends the run failed with "The run's files could not be copied into its workspace: <why>", instead of the bare error.
|
|
26
|
+
- A message sent while a turn works is answered before the run ends. The runner hands a turn's end every message it has not handed on yet, rather than at its next poll half a second later, so the run's end no longer refuses one the API took. On pi, a message placed as the turn answered was answered after the run's end was written: the run read completed, then wrote another answer.
|
|
27
|
+
- A claude-agent run's rows name a file it wrote or read by its name in the workspace (`Wrote hello.md`, `Saved hello.md`), not by the absolute path the Claude CLI sends, which named a folder on the runner's machine. The call's input preview keeps the path as sent.
|
|
28
|
+
- The test kit's faux adapter tells its script the session's working directory (`script(spec, { cwd })`), as a real CLI builds its absolute paths from it.
|
|
29
|
+
- A tool call the runner runs again after a crash meets the run's gate again. Before, a replay-safe call (web_search, web_fetch) that pi reran after a crash skipped the gate: a deny set since its first attempt didn't stop it, and a tool set to ask since ran it with no one's approval. Now a deny or a pin refuses the rerun in words saying the earlier attempt may have taken effect ("whether it took effect is not known"), never "nothing was sent", and a tool set to ask parks the run on it, the owner's answer then acting on it. A stop that lands while the rerun is asked wins over a permission that comes after it: the call never starts. Codex and Claude Code reruns say the same.
|
|
30
|
+
- A capped run that reads screenshots is no longer refused at its cap after the first one. A model request's input bound counted an image's base64 as one token per byte, and then the image's billed maximum on top. A 1280x720 screenshot (about a megabyte of base64) read as some 1.3 million input tokens, so a Sonnet step under a $1.50 cap "needed at least $4.83" when Claude bills it a few cents.
|
|
31
|
+
|
|
32
|
+
Each image, in every turn, now counts at what the routed model's provider can bill it as, in place of its data's bytes, whatever API carries it. The size comes from the image's own header (PNG, JPEG, GIF or WebP):
|
|
33
|
+
- Anthropic: its 28-pixel patches or its area at 750 pixels a token, whichever is more, at most 4,784.
|
|
34
|
+
- OpenAI: its 512-pixel tiles after resizing (85 + 170 each; 85 at detail low), or for a patch-billed mini or nano model its 32-pixel patches at that model's multiplier when more, at most 73,800.
|
|
35
|
+
- Google: 258 per 768-pixel tile, at least 1,120.
|
|
36
|
+
- Any other provider: the most of the three.
|
|
37
|
+
An image whose size can't be read counts at its provider's per-image maximum, never at its bytes. An image-shaped object outside where the API reads images (a tool call's arguments) is counted at its bytes, as text.
|
|
38
|
+
|
|
39
|
+
`InputShape.images` (the kernel host's `providerInputOverhead`) is now a list of images, each with the bytes its data takes and its size when known; `InputShape.model` names the routed model; the figure can be below 0, and so can a policy's `serverInputOverhead`, never past the body's bytes. Upgrading: pass `images: [{ bytes, width?, height? }]`, built with `imageInputOf`, `messagesImagesIn` or `responsesImagesIn`, and the model, in place of a count.
|
|
40
|
+
- A paid call the cap refused for room pauses the run with the run's spend as it is when the pause lands, and never refuses a person's answer to a question the same turn ended on:
|
|
41
|
+
- The budget card (and its words) count what calls beside the refused one charged before the model's next request, not the spend at the refusal. A call that would now fit (one beside it settled for less than it held) pauses nothing.
|
|
42
|
+
- A turn that ends on a question to the person (ask_person) with no next model request drops the refused call's pending pause, so the person's answer reaches the model and is never refused in that call's words, on this claim or the next.
|
|
43
|
+
- The kernel cap's refusal for a paid call names the call (`figures.step`: its name, hold and basis), and `paidRefusal` is exported, so a host can say a refusal again with the run's spend later.
|
|
44
|
+
|
|
5
45
|
## 0.1.0-beta.34 (2026-11-11)
|
|
6
46
|
|
|
7
47
|
- The server checks a harness's pinned binary (claude-agent's CLI, Codex, OpenCode: its sha256, then the version it reports) without holding its event loop, so requests, timers and store answers go on while a binary of hundreds of MiB is hashed and run. Before, the first check in a process held every request for one to several seconds (GET /v2/capabilities, a server's start, an adapter made for a run). The binary is now hashed off the loop a chunk at a time and run as a child the loop does not wait on. A pass is kept for the adapter's own check, which then reads nothing, and two checks of one binary at once read it once. New: `checkedOnceAsync` and `sha256OfFileAsync` (kernel host), `verifyClaudeAgentCliAsync` (claude-agent), and `verifyCodexAsync` and `verifyCodexBinaryAsync` (Codex). Who breaks: a program that calls the kernel's `checkedOnce` with its own check. A check is now a `BinaryCheck`, a generator that yields each probe (`{ kind: "sha256", path }` or `{ kind: "run", path, args, env, timeoutMs }`) and is given back its answer, so one check runs either way.
|
package/README.md
CHANGED
|
@@ -38,13 +38,6 @@ harness adapter the way they run on Pi, durable in AgentRun's own store.
|
|
|
38
38
|
- `./kernel` is the durable kernel an adapter runs on (`openDrive` over the session's writer): an effect's intent, then
|
|
39
39
|
at most one outcome; after a crash a `safe` effect runs again and a `never` one is reported interrupted, never run
|
|
40
40
|
again. So a tool that costs money per call (a paid search) is `never`: `safe` means free to run again. A drive whose writer was fenced gets a `Restart` at its next write, so it never runs a new effect.
|
|
41
|
-
`followUpOnce` sends one more turn into a session that has answered, with a prompt the host names, at most once: it
|
|
42
|
-
is a `never` effect on its own key (`followUpKey(session, name)`), so a crash inside it leaves it interrupted, and the
|
|
43
|
-
turn a crash cut off is settled (`settleOpenTurn`), never resumed. Its prompt's submission has an id of its own
|
|
44
|
-
(`follow-up:<key>`), and the settle is named only that one, so it never withdraws a person's message. Its
|
|
45
|
-
`beforeRequest` goes ahead of the host's and holds the follow-up's paid requests to `reserveUsd`, counted from its
|
|
46
|
-
first request; an unknown spend is refused.
|
|
47
|
-
`followUpState(records)` tells a host, before it resumes an open turn, whether that turn is a follow-up's.
|
|
48
41
|
`./process` is the shared layer for harnesses that run as a child process: the native journal, the transcript, the
|
|
49
42
|
recovery note, the tool bridge, the built-ins' hook-pair calls, the inbox (and `waitForSubmissions`, for a harness that
|
|
50
43
|
waits for input while a turn runs), `zodShapeFromJsonSchema`, for harness SDKs whose tool APIs take zod, and
|
package/dist/host/box.d.ts
CHANGED
|
@@ -13,20 +13,6 @@ export interface BoxRecord {
|
|
|
13
13
|
startTime: string;
|
|
14
14
|
};
|
|
15
15
|
}
|
|
16
|
-
/** Where a box's record goes. `ahead` is synchronous (the file and its directory are synced before it returns) and runs
|
|
17
|
-
* before the spawn; `started` runs while bwrap waits, and no process of the harness runs until it resolves. */
|
|
18
|
-
export interface BoxRecorder {
|
|
19
|
-
ahead(record: BoxRecord): void;
|
|
20
|
-
started(record: BoxRecord): Promise<void>;
|
|
21
|
-
}
|
|
22
|
-
/** What a reap found, by the kernel's own count: the processes left in the recorded pid namespace, or the cgroup's.
|
|
23
|
-
* `none`: the record names neither a pid nor a cgroup, so there was nothing to count (a crash before the pid was
|
|
24
|
-
* known; --die-with-parent ends such a box with its parent). */
|
|
25
|
-
export interface Reaped {
|
|
26
|
-
empty: boolean;
|
|
27
|
-
left: number;
|
|
28
|
-
by: "pidns" | "cgroup" | "none";
|
|
29
|
-
}
|
|
30
16
|
export type BoxErrorCode = "bwrap_missing" | "bwrap_setuid" | "bwrap_userns_denied" | "box_probe_failed" | "box_refused" | "box_record_failed" | "box_start_failed"
|
|
31
17
|
/** A start while the session's last box is live, being reaped, or was not confirmed empty. */
|
|
32
18
|
| "box_busy"
|
package/dist/host/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { ANTHROPIC_IMAGE_TOKENS_MAX, ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS, ASSUMED_TOOL_PROMPT_TOKENS, INPUT_OVERHEAD_APIS, OPENAI_IMAGE_TOKENS_MAX, providerInputOverhead, type InputShape } from "./overhead.js";
|
|
2
|
-
export { hostHeaderProblems, ProxyRefusal, sameKey, startModelProxy } from "./proxy.js";
|
|
3
|
-
export type { ModelProxy, ModelProxyHooks, ModelProxyOptions, ModelUsageReport, ProviderPolicy, ProxyRequest, ProxyRequestContext, ProxyRoute, ProxyUsage } from "./proxy.js";
|
|
1
|
+
export { ANTHROPIC_IMAGE_TOKENS_MAX, ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS, ASSUMED_TOOL_PROMPT_TOKENS, anthropicImageTokens, GEMINI_HIGH_RESOLUTION_TOKENS, geminiImageTokens, imageInputOf, imageProviderOf, imageSizeOf, imageTokens, INPUT_OVERHEAD_APIS, messagesImagesIn, OPENAI_IMAGE_TOKENS_MAX, openaiImageTokens, openaiPatchMultiplier, providerInputOverhead, responsesImagesIn, type ImageInput, type InputShape } from "./overhead.js";
|
|
2
|
+
export { COUNT_TIMEOUT_MS, countedInputOf, hostHeaderProblems, ProxyRefusal, sameKey, startModelProxy } from "./proxy.js";
|
|
3
|
+
export type { InputCounter, ModelProxy, ModelProxyHooks, ModelProxyOptions, ModelUsageReport, ProviderPolicy, ProxyRequest, ProxyRequestContext, ProxyRoute, ProxyUsage } from "./proxy.js";
|
|
4
4
|
export { mcpRoute } from "./mcp-route.js";
|
|
5
5
|
export type { McpHandler, McpRouteOptions } from "./mcp-route.js";
|
|
6
6
|
export { processAlive } from "./alive.js";
|
|
@@ -8,5 +8,5 @@ export { serialWriter } from "./serial.js";
|
|
|
8
8
|
export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./parent-death.js";
|
|
9
9
|
export type { LaunchCommand, ParentWatch } from "./parent-death.js";
|
|
10
10
|
export { BoxError } from "./box.js";
|
|
11
|
-
export type { BoxErrorCode, BoxRecord
|
|
11
|
+
export type { BoxErrorCode, BoxRecord } from "./box.js";
|
|
12
12
|
export { type BinaryCheck, type BinaryProbe, checkedOnce, checkedOnceAsync, sha256OfFile, sha256OfFileAsync } from "./pinned-binary.js";
|
package/dist/host/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// What a harness adapter runs beside its harness on the host: the session's model proxy, provider-neutral, with each
|
|
2
2
|
// provider's rules in a `ProviderPolicy`. Written for AgentRun.
|
|
3
|
-
export { ANTHROPIC_IMAGE_TOKENS_MAX, ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS, ASSUMED_TOOL_PROMPT_TOKENS, INPUT_OVERHEAD_APIS, OPENAI_IMAGE_TOKENS_MAX, providerInputOverhead } from "./overhead.js";
|
|
4
|
-
export { hostHeaderProblems, ProxyRefusal, sameKey, startModelProxy } from "./proxy.js";
|
|
3
|
+
export { ANTHROPIC_IMAGE_TOKENS_MAX, ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS, ASSUMED_TOOL_PROMPT_TOKENS, anthropicImageTokens, GEMINI_HIGH_RESOLUTION_TOKENS, geminiImageTokens, imageInputOf, imageProviderOf, imageSizeOf, imageTokens, INPUT_OVERHEAD_APIS, messagesImagesIn, OPENAI_IMAGE_TOKENS_MAX, openaiImageTokens, openaiPatchMultiplier, providerInputOverhead, responsesImagesIn } from "./overhead.js";
|
|
4
|
+
export { COUNT_TIMEOUT_MS, countedInputOf, hostHeaderProblems, ProxyRefusal, sameKey, startModelProxy } from "./proxy.js";
|
|
5
5
|
export { mcpRoute } from "./mcp-route.js";
|
|
6
6
|
export { processAlive } from "./alive.js";
|
|
7
7
|
export { serialWriter } from "./serial.js";
|
package/dist/host/overhead.d.ts
CHANGED
|
@@ -1,11 +1,24 @@
|
|
|
1
|
+
/** One image a request carries: the bytes its data takes in the body (its base64, or its data URL; 0 for an image the
|
|
2
|
+
* provider fetches by URL), which are counted at the image's billed size instead, and its pixel size when its data's own
|
|
3
|
+
* header says it (PNG, JPEG, GIF, WebP). */
|
|
4
|
+
export interface ImageInput {
|
|
5
|
+
readonly bytes: number;
|
|
6
|
+
readonly width?: number;
|
|
7
|
+
readonly height?: number;
|
|
8
|
+
/** The detail it asks for, where the API takes one (OpenAI's `low`, `high` or `auto`). */
|
|
9
|
+
readonly detail?: string;
|
|
10
|
+
}
|
|
1
11
|
/** What of a request decides what its provider adds: whether it offers tools, how it asks for them, and its images. */
|
|
2
12
|
export interface InputShape {
|
|
3
13
|
/** The request offers at least one tool. */
|
|
4
14
|
tools: boolean;
|
|
5
15
|
/** Its tool_choice, as Anthropic names them; absent for the provider's default. */
|
|
6
16
|
toolChoice?: "auto" | "none" | "any" | "tool";
|
|
7
|
-
/** Its image inputs, at any depth (a tool's result included). */
|
|
8
|
-
images:
|
|
17
|
+
/** Its image inputs, at any depth (earlier turns' and a tool's result included). */
|
|
18
|
+
images: readonly ImageInput[];
|
|
19
|
+
/** The model it is routed to, as the session names it (`anthropic/claude-sonnet-5.5` through a gateway): its provider's
|
|
20
|
+
* rule bills its images (`imageTokens`). Absent or unknown: the most any known rule bills each one as. */
|
|
21
|
+
model?: string;
|
|
9
22
|
}
|
|
10
23
|
/**
|
|
11
24
|
* The tool-use system prompt the Messages API adds to a request with tools, in tokens, by tool_choice. Documented per
|
|
@@ -45,9 +58,67 @@ export declare const ASSUMED_TOOL_PROMPT_TOKENS = 2048;
|
|
|
45
58
|
* image.
|
|
46
59
|
*/
|
|
47
60
|
export declare const INPUT_OVERHEAD_APIS: readonly string[];
|
|
61
|
+
/**
|
|
62
|
+
* The most tokens Claude bills an image of `width` x `height` pixels as: its count of 28 px patches (the
|
|
63
|
+
* high-resolution tier) or its area at 750 pixels a token (the standard tier), whichever is more, at most
|
|
64
|
+
* `ANTHROPIC_IMAGE_TOKENS_MAX`. Claude only ever shrinks an image before it counts it ("Resolution and token cost",
|
|
65
|
+
* https://platform.claude.com/docs/en/build-with-claude/vision), so the image as sent is the most it can be billed as.
|
|
66
|
+
*/
|
|
67
|
+
export declare function anthropicImageTokens(width: number, height: number): number;
|
|
48
68
|
/**
|
|
49
69
|
* The input tokens a provider bills for a request of `shape` beyond its body's bytes, on the API `api` (pi's names:
|
|
50
|
-
* "anthropic-messages", "openai-responses", ...)
|
|
51
|
-
*
|
|
70
|
+
* "anthropic-messages", "openai-responses", ...): its tool prompt, and each image at what it can be billed as in place of
|
|
71
|
+
* the bytes its data takes in the body (so the figure is below 0 for a request whose images' data is larger than they
|
|
72
|
+
* are billed as; the body's bytes and this together are its bound). A documented API gets its documented figures; any
|
|
73
|
+
* other gets the general figure (`INPUT_OVERHEAD_APIS`). Never undefined: an input that cannot be measured is the
|
|
74
|
+
* body's, not the API's.
|
|
52
75
|
*/
|
|
53
76
|
export declare function providerInputOverhead(api: string, shape: InputShape): number;
|
|
77
|
+
/** The provider whose image rule a model id is billed by, by the id as the session names it (a gateway's
|
|
78
|
+
* `vendor/model`, or the vendor's own): undefined for one the rules do not know. */
|
|
79
|
+
export declare function imageProviderOf(model: string | undefined): "anthropic" | "openai" | "google" | undefined;
|
|
80
|
+
/**
|
|
81
|
+
* The most tokens OpenAI bills an image of `width` x `height` as, by its "Calculating costs" rules
|
|
82
|
+
* (https://developers.openai.com/api/docs/guides/images-vision):
|
|
83
|
+
* - the tile rule, for every model: at detail "low", 85 tokens; otherwise (high, or auto, which may choose high) the
|
|
84
|
+
* image fit within 2048 x 2048, then its shorter side brought to 768 (up as well as down, the dearer reading for a
|
|
85
|
+
* small image), each 512 px tile 170 tokens beside a base of 85. A gpt-4o-mini model bills 2,833 and 5,667 a tile;
|
|
86
|
+
* - the patch rule, for the models it lists as billed by 32 px patches (`openaiPatchMultiplier`): its patches at the
|
|
87
|
+
* model's multiplier, when that is more.
|
|
88
|
+
* At most `OPENAI_IMAGE_TOKENS_MAX`. With no model named, every rule at its dearest: gpt-4o-mini's tiles and the patches
|
|
89
|
+
* at the largest multiplier, 2.46.
|
|
90
|
+
*/
|
|
91
|
+
export declare function openaiImageTokens(width: number, height: number, model?: string, detail?: string): number;
|
|
92
|
+
/** The multiplier OpenAI bills a patch-billed model's 32 px patches at: 2.46 for a nano model, 1.72 for o4-mini (and
|
|
93
|
+
* codex-mini, built on it), 1.62 for another mini model (gpt-4o-mini excepted: it bills tiles); 0 for a tile-billed
|
|
94
|
+
* model; 2.46, the largest, for a model not named. */
|
|
95
|
+
export declare function openaiPatchMultiplier(model: string | undefined): number;
|
|
96
|
+
/** What Gemini bills a picture as at the most ("Media resolution" and "Image understanding" in its API docs): 258 tokens
|
|
97
|
+
* an image at most 384 px on each side, else 258 for each 768 px tile; and a picture at Gemini 3's high media resolution
|
|
98
|
+
* 1,120 tokens. The more of the two. */
|
|
99
|
+
export declare const GEMINI_HIGH_RESOLUTION_TOKENS = 1120;
|
|
100
|
+
export declare function geminiImageTokens(width: number, height: number): number;
|
|
101
|
+
/**
|
|
102
|
+
* The most tokens `image` is billed as by the routed `model`'s provider: Anthropic's, OpenAI's or Google's rule by its
|
|
103
|
+
* size; for a model of another provider, or of none known, the most any of the three rules bills it as. An image whose
|
|
104
|
+
* size cannot be read counts at the largest per-image maximum documented, `OPENAI_IMAGE_TOKENS_MAX` (Anthropic's own,
|
|
105
|
+
* `ANTHROPIC_IMAGE_TOKENS_MAX`, on a Claude model), never at its bytes.
|
|
106
|
+
*/
|
|
107
|
+
export declare function imageTokens(model: string | undefined, image: ImageInput): number;
|
|
108
|
+
/** The pixel size an image's base64 `data` says in its own header (PNG, JPEG, GIF or WebP), or undefined: another format,
|
|
109
|
+
* or a header that cannot be read. Only its start is decoded (a JPEG's frame header within its first 256 KiB). */
|
|
110
|
+
export declare function imageSizeOf(data: string): {
|
|
111
|
+
width: number;
|
|
112
|
+
height: number;
|
|
113
|
+
} | undefined;
|
|
114
|
+
/** A Messages body's images, only where the API reads one as an image: a block of a message's content, or of a
|
|
115
|
+
* tool_result's content, in every turn. Each is a base64 source's data, or a URL's (no bytes). An image-shaped object
|
|
116
|
+
* anywhere else (a tool call's arguments) is text to the provider: its bytes stay counted as they are. */
|
|
117
|
+
export declare function messagesImagesIn(messages: unknown): ImageInput[];
|
|
118
|
+
/** A Responses body's images, only where the API reads one as an image: an `input_image` item, a part of an item's
|
|
119
|
+
* content, or a part of a function call's output, in every turn. Each is a data URL's, or a URL's or file id's (no
|
|
120
|
+
* bytes). An image-shaped object anywhere else is text to the provider: its bytes stay counted as they are. */
|
|
121
|
+
export declare function responsesImagesIn(input: unknown): ImageInput[];
|
|
122
|
+
/** The image a body's `data` (base64, or a data URL) carries: the bytes it takes, and its size when its header says it.
|
|
123
|
+
* Anything else (an http URL, a file id): no bytes, no size. */
|
|
124
|
+
export declare function imageInputOf(data: unknown): ImageInput;
|
package/dist/host/overhead.js
CHANGED
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
//
|
|
5
5
|
// A request's input can never be more tokens than its body's UTF-8 bytes (`inputTokensMaxOf`), except for what the
|
|
6
6
|
// provider adds or bills by another measure: a prompt it adds itself when tools are present, and images, which it bills by
|
|
7
|
-
// their area after it resizes them, not by their bytes.
|
|
8
|
-
//
|
|
7
|
+
// their area after it resizes them, not by their bytes. An image is counted at what the routed model's provider bills it
|
|
8
|
+
// as by its size (Anthropic's, OpenAI's or Google's rule; the most of the three for another provider), in place of the
|
|
9
|
+
// bytes its data takes in the body: a screenshot's base64 is a megabyte, and Claude bills it as some 1,200 tokens. Each
|
|
10
|
+
// figure is the largest the provider documents for any current model, so no model is undercounted.
|
|
9
11
|
/**
|
|
10
12
|
* The tool-use system prompt the Messages API adds to a request with tools, in tokens, by tool_choice. Documented per
|
|
11
13
|
* model under "Pricing" in https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview, and taken at the largest
|
|
@@ -57,19 +59,227 @@ export const ASSUMED_TOOL_PROMPT_TOKENS = 2_048;
|
|
|
57
59
|
export const INPUT_OVERHEAD_APIS = Object.freeze(["anthropic-messages", "openai-responses", "azure-openai-responses", "openai-codex-responses", CHAT_COMPLETIONS]);
|
|
58
60
|
/** The tool-use prompt Anthropic adds for a request of `shape`: none without tools. */
|
|
59
61
|
const anthropicToolPrompt = (shape) => (!shape.tools ? 0 : shape.toolChoice === "any" || shape.toolChoice === "tool" ? ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS.anyOrTool : ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS.autoOrNone);
|
|
62
|
+
/**
|
|
63
|
+
* The most tokens Claude bills an image of `width` x `height` pixels as: its count of 28 px patches (the
|
|
64
|
+
* high-resolution tier) or its area at 750 pixels a token (the standard tier), whichever is more, at most
|
|
65
|
+
* `ANTHROPIC_IMAGE_TOKENS_MAX`. Claude only ever shrinks an image before it counts it ("Resolution and token cost",
|
|
66
|
+
* https://platform.claude.com/docs/en/build-with-claude/vision), so the image as sent is the most it can be billed as.
|
|
67
|
+
*/
|
|
68
|
+
export function anthropicImageTokens(width, height) {
|
|
69
|
+
return Math.min(ANTHROPIC_IMAGE_TOKENS_MAX, Math.max(Math.ceil(width / 28) * Math.ceil(height / 28), Math.ceil((width * height) / 750)));
|
|
70
|
+
}
|
|
71
|
+
/** Whether `image` is a figure the bounds can read: whole bytes, and a size of whole positive pixels or none. */
|
|
72
|
+
function checkedImage(image) {
|
|
73
|
+
const pixels = (n) => n === undefined || (Number.isSafeInteger(n) && n > 0);
|
|
74
|
+
if (!image || !Number.isSafeInteger(image.bytes) || image.bytes < 0 || !pixels(image.width) || !pixels(image.height) || (image.width === undefined) !== (image.height === undefined)) {
|
|
75
|
+
throw new Error(`not an image's bytes and size: ${JSON.stringify(image).slice(0, 80)}`);
|
|
76
|
+
}
|
|
77
|
+
return image;
|
|
78
|
+
}
|
|
60
79
|
/**
|
|
61
80
|
* The input tokens a provider bills for a request of `shape` beyond its body's bytes, on the API `api` (pi's names:
|
|
62
|
-
* "anthropic-messages", "openai-responses", ...)
|
|
63
|
-
*
|
|
81
|
+
* "anthropic-messages", "openai-responses", ...): its tool prompt, and each image at what it can be billed as in place of
|
|
82
|
+
* the bytes its data takes in the body (so the figure is below 0 for a request whose images' data is larger than they
|
|
83
|
+
* are billed as; the body's bytes and this together are its bound). A documented API gets its documented figures; any
|
|
84
|
+
* other gets the general figure (`INPUT_OVERHEAD_APIS`). Never undefined: an input that cannot be measured is the
|
|
85
|
+
* body's, not the API's.
|
|
64
86
|
*/
|
|
65
87
|
export function providerInputOverhead(api, shape) {
|
|
66
|
-
if (!
|
|
67
|
-
throw new Error(`not
|
|
88
|
+
if (!Array.isArray(shape.images))
|
|
89
|
+
throw new Error(`not a list of images: ${String(shape.images).slice(0, 40)}`);
|
|
90
|
+
const images = shape.images.map(checkedImage);
|
|
91
|
+
// Each image at what the routed model's provider bills it as (imageTokens), whatever API carries it: a gateway speaks
|
|
92
|
+
// one API for every provider it routes to.
|
|
93
|
+
const imagesNet = images.reduce((sum, image) => sum + imageTokens(shape.model, image) - image.bytes, 0);
|
|
68
94
|
if (api === "anthropic-messages")
|
|
69
|
-
return anthropicToolPrompt(shape) +
|
|
95
|
+
return anthropicToolPrompt(shape) + imagesNet;
|
|
70
96
|
if (api === CHAT_COMPLETIONS)
|
|
71
|
-
return (shape.tools ? ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS.anyOrTool : 0) +
|
|
97
|
+
return (shape.tools ? ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS.anyOrTool : 0) + imagesNet;
|
|
72
98
|
if (INPUT_OVERHEAD_APIS.includes(api))
|
|
73
|
-
return
|
|
74
|
-
return (shape.tools ? ASSUMED_TOOL_PROMPT_TOKENS : 0) +
|
|
99
|
+
return imagesNet;
|
|
100
|
+
return (shape.tools ? ASSUMED_TOOL_PROMPT_TOKENS : 0) + imagesNet;
|
|
101
|
+
}
|
|
102
|
+
/** The provider whose image rule a model id is billed by, by the id as the session names it (a gateway's
|
|
103
|
+
* `vendor/model`, or the vendor's own): undefined for one the rules do not know. */
|
|
104
|
+
export function imageProviderOf(model) {
|
|
105
|
+
if (!model)
|
|
106
|
+
return undefined;
|
|
107
|
+
if (/^anthropic\/|(^|\/)claude/i.test(model))
|
|
108
|
+
return "anthropic";
|
|
109
|
+
if (/^openai\/|(^|\/)(gpt|chatgpt|codex|o\d)/i.test(model))
|
|
110
|
+
return "openai";
|
|
111
|
+
if (/^google\/|(^|\/)gemini/i.test(model))
|
|
112
|
+
return "google";
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The most tokens OpenAI bills an image of `width` x `height` as, by its "Calculating costs" rules
|
|
117
|
+
* (https://developers.openai.com/api/docs/guides/images-vision):
|
|
118
|
+
* - the tile rule, for every model: at detail "low", 85 tokens; otherwise (high, or auto, which may choose high) the
|
|
119
|
+
* image fit within 2048 x 2048, then its shorter side brought to 768 (up as well as down, the dearer reading for a
|
|
120
|
+
* small image), each 512 px tile 170 tokens beside a base of 85. A gpt-4o-mini model bills 2,833 and 5,667 a tile;
|
|
121
|
+
* - the patch rule, for the models it lists as billed by 32 px patches (`openaiPatchMultiplier`): its patches at the
|
|
122
|
+
* model's multiplier, when that is more.
|
|
123
|
+
* At most `OPENAI_IMAGE_TOKENS_MAX`. With no model named, every rule at its dearest: gpt-4o-mini's tiles and the patches
|
|
124
|
+
* at the largest multiplier, 2.46.
|
|
125
|
+
*/
|
|
126
|
+
export function openaiImageTokens(width, height, model, detail) {
|
|
127
|
+
// gpt-4o-mini's tile rates are the dearest: a model not named (a gateway's alias may be one) is held to them.
|
|
128
|
+
const mini = model === undefined || /4o-mini/i.test(model);
|
|
129
|
+
let tiled;
|
|
130
|
+
if (detail === "low")
|
|
131
|
+
tiled = mini ? 2_833 : 85;
|
|
132
|
+
else {
|
|
133
|
+
const fit = Math.min(1, 2048 / Math.max(width, height));
|
|
134
|
+
const short = 768 / Math.min(width * fit, height * fit);
|
|
135
|
+
const tiles = Math.ceil((width * fit * short) / 512) * Math.ceil((height * fit * short) / 512);
|
|
136
|
+
tiled = mini ? 2_833 + 5_667 * tiles : 85 + 170 * tiles;
|
|
137
|
+
}
|
|
138
|
+
const multiplier = openaiPatchMultiplier(model);
|
|
139
|
+
const patched = multiplier > 0 ? Math.ceil(Math.ceil(width / 32) * Math.ceil(height / 32) * multiplier) : 0;
|
|
140
|
+
return Math.min(OPENAI_IMAGE_TOKENS_MAX, Math.max(tiled, patched));
|
|
141
|
+
}
|
|
142
|
+
/** The multiplier OpenAI bills a patch-billed model's 32 px patches at: 2.46 for a nano model, 1.72 for o4-mini (and
|
|
143
|
+
* codex-mini, built on it), 1.62 for another mini model (gpt-4o-mini excepted: it bills tiles); 0 for a tile-billed
|
|
144
|
+
* model; 2.46, the largest, for a model not named. */
|
|
145
|
+
export function openaiPatchMultiplier(model) {
|
|
146
|
+
if (model === undefined)
|
|
147
|
+
return 2.46;
|
|
148
|
+
if (/nano/i.test(model))
|
|
149
|
+
return 2.46;
|
|
150
|
+
if (/o4-mini|codex-mini/i.test(model))
|
|
151
|
+
return 1.72;
|
|
152
|
+
if (/mini/i.test(model) && !/4o-mini/i.test(model))
|
|
153
|
+
return 1.62;
|
|
154
|
+
return 0;
|
|
155
|
+
}
|
|
156
|
+
/** What Gemini bills a picture as at the most ("Media resolution" and "Image understanding" in its API docs): 258 tokens
|
|
157
|
+
* an image at most 384 px on each side, else 258 for each 768 px tile; and a picture at Gemini 3's high media resolution
|
|
158
|
+
* 1,120 tokens. The more of the two. */
|
|
159
|
+
export const GEMINI_HIGH_RESOLUTION_TOKENS = 1_120;
|
|
160
|
+
export function geminiImageTokens(width, height) {
|
|
161
|
+
const tiled = width <= 384 && height <= 384 ? 258 : 258 * Math.ceil(width / 768) * Math.ceil(height / 768);
|
|
162
|
+
return Math.max(tiled, GEMINI_HIGH_RESOLUTION_TOKENS);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The most tokens `image` is billed as by the routed `model`'s provider: Anthropic's, OpenAI's or Google's rule by its
|
|
166
|
+
* size; for a model of another provider, or of none known, the most any of the three rules bills it as. An image whose
|
|
167
|
+
* size cannot be read counts at the largest per-image maximum documented, `OPENAI_IMAGE_TOKENS_MAX` (Anthropic's own,
|
|
168
|
+
* `ANTHROPIC_IMAGE_TOKENS_MAX`, on a Claude model), never at its bytes.
|
|
169
|
+
*/
|
|
170
|
+
export function imageTokens(model, image) {
|
|
171
|
+
const provider = imageProviderOf(model);
|
|
172
|
+
if (image.width === undefined || image.height === undefined)
|
|
173
|
+
return provider === "anthropic" ? ANTHROPIC_IMAGE_TOKENS_MAX : OPENAI_IMAGE_TOKENS_MAX;
|
|
174
|
+
const { width, height } = image;
|
|
175
|
+
if (provider === "anthropic")
|
|
176
|
+
return anthropicImageTokens(width, height);
|
|
177
|
+
if (provider === "openai")
|
|
178
|
+
return openaiImageTokens(width, height, model, image.detail);
|
|
179
|
+
if (provider === "google")
|
|
180
|
+
return geminiImageTokens(width, height);
|
|
181
|
+
// Of no provider known: every OpenAI rule (no model named), beside Anthropic's and Google's.
|
|
182
|
+
return Math.max(anthropicImageTokens(width, height), openaiImageTokens(width, height), geminiImageTokens(width, height));
|
|
183
|
+
}
|
|
184
|
+
/** The pixel size an image's base64 `data` says in its own header (PNG, JPEG, GIF or WebP), or undefined: another format,
|
|
185
|
+
* or a header that cannot be read. Only its start is decoded (a JPEG's frame header within its first 256 KiB). */
|
|
186
|
+
export function imageSizeOf(data) {
|
|
187
|
+
const head = Buffer.from(data.slice(0, 349_528), "base64");
|
|
188
|
+
const sized = (width, height) => (width > 0 && height > 0 ? { width, height } : undefined);
|
|
189
|
+
if (head.length >= 24 && head.readUInt32BE(0) === 0x89504e47 && head.toString("latin1", 12, 16) === "IHDR")
|
|
190
|
+
return sized(head.readUInt32BE(16), head.readUInt32BE(20));
|
|
191
|
+
if (head.length >= 10 && head.toString("latin1", 0, 4) === "GIF8")
|
|
192
|
+
return sized(head.readUInt16LE(6), head.readUInt16LE(8));
|
|
193
|
+
if (head.length >= 30 && head.toString("latin1", 0, 4) === "RIFF" && head.toString("latin1", 8, 12) === "WEBP") {
|
|
194
|
+
const kind = head.toString("latin1", 12, 16);
|
|
195
|
+
if (kind === "VP8X")
|
|
196
|
+
return sized(1 + head.readUIntLE(24, 3), 1 + head.readUIntLE(27, 3));
|
|
197
|
+
if (kind === "VP8L") {
|
|
198
|
+
const bits = head.readUInt32LE(21);
|
|
199
|
+
return sized(1 + (bits & 0x3fff), 1 + ((bits >>> 14) & 0x3fff));
|
|
200
|
+
}
|
|
201
|
+
if (kind === "VP8 ")
|
|
202
|
+
return sized(head.readUInt16LE(26) & 0x3fff, head.readUInt16LE(28) & 0x3fff);
|
|
203
|
+
return undefined;
|
|
204
|
+
}
|
|
205
|
+
if (head.length >= 4 && head[0] === 0xff && head[1] === 0xd8) {
|
|
206
|
+
// Walk the segments to a start-of-frame marker (SOF0-SOF15, but not DHT, JPG or DAC), which holds the height then width.
|
|
207
|
+
for (let at = 2; at + 9 <= head.length;) {
|
|
208
|
+
if (head[at] !== 0xff)
|
|
209
|
+
return undefined;
|
|
210
|
+
const marker = head[at + 1];
|
|
211
|
+
if (marker === 0xff) {
|
|
212
|
+
at += 1;
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
|
|
216
|
+
at += 2;
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc)
|
|
220
|
+
return sized(head.readUInt16BE(at + 7), head.readUInt16BE(at + 5));
|
|
221
|
+
at += 2 + head.readUInt16BE(at + 2);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return undefined;
|
|
225
|
+
}
|
|
226
|
+
const plain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
227
|
+
const list = (value) => (Array.isArray(value) ? value : []);
|
|
228
|
+
/** A Messages body's images, only where the API reads one as an image: a block of a message's content, or of a
|
|
229
|
+
* tool_result's content, in every turn. Each is a base64 source's data, or a URL's (no bytes). An image-shaped object
|
|
230
|
+
* anywhere else (a tool call's arguments) is text to the provider: its bytes stay counted as they are. */
|
|
231
|
+
export function messagesImagesIn(messages) {
|
|
232
|
+
const out = [];
|
|
233
|
+
const image = (block) => {
|
|
234
|
+
if (plain(block) && block.type === "image")
|
|
235
|
+
out.push(plain(block.source) && block.source.type === "base64" ? imageInputOf(block.source.data) : { bytes: 0 });
|
|
236
|
+
};
|
|
237
|
+
for (const message of list(messages)) {
|
|
238
|
+
if (!plain(message))
|
|
239
|
+
continue;
|
|
240
|
+
for (const block of list(message.content)) {
|
|
241
|
+
image(block);
|
|
242
|
+
if (plain(block) && block.type === "tool_result")
|
|
243
|
+
for (const inner of list(block.content))
|
|
244
|
+
image(inner);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return out;
|
|
248
|
+
}
|
|
249
|
+
/** A Responses body's images, only where the API reads one as an image: an `input_image` item, a part of an item's
|
|
250
|
+
* content, or a part of a function call's output, in every turn. Each is a data URL's, or a URL's or file id's (no
|
|
251
|
+
* bytes). An image-shaped object anywhere else is text to the provider: its bytes stay counted as they are. */
|
|
252
|
+
export function responsesImagesIn(input) {
|
|
253
|
+
const out = [];
|
|
254
|
+
const image = (part) => {
|
|
255
|
+
if (plain(part) && part.type === "input_image")
|
|
256
|
+
out.push({ ...imageInputOf(part.image_url), ...(typeof part.detail === "string" ? { detail: part.detail } : {}) });
|
|
257
|
+
};
|
|
258
|
+
for (const item of list(input)) {
|
|
259
|
+
if (!plain(item))
|
|
260
|
+
continue;
|
|
261
|
+
image(item);
|
|
262
|
+
for (const part of list(item.content))
|
|
263
|
+
image(part);
|
|
264
|
+
if (item.type === "function_call_output")
|
|
265
|
+
for (const part of list(item.output))
|
|
266
|
+
image(part);
|
|
267
|
+
}
|
|
268
|
+
return out;
|
|
269
|
+
}
|
|
270
|
+
/** The image a body's `data` (base64, or a data URL) carries: the bytes it takes, and its size when its header says it.
|
|
271
|
+
* Anything else (an http URL, a file id): no bytes, no size. */
|
|
272
|
+
export function imageInputOf(data) {
|
|
273
|
+
if (typeof data !== "string")
|
|
274
|
+
return { bytes: 0 };
|
|
275
|
+
const base64 = /^data:[^,]*;base64,/i.exec(data);
|
|
276
|
+
if (data.startsWith("data:") && !base64)
|
|
277
|
+
return { bytes: 0 };
|
|
278
|
+
const payload = base64 ? data.slice(base64[0].length) : data;
|
|
279
|
+
// A URL the provider fetches is billed by the image it finds, and only its own bytes are in the body.
|
|
280
|
+
if (!base64 && /^[a-z][a-z0-9+.-]*:\/\//i.test(data))
|
|
281
|
+
return { bytes: 0 };
|
|
282
|
+
const size = imageSizeOf(payload);
|
|
283
|
+
// Its whole string, once JSON writes it: base64 and a data URL's prefix need no escaping.
|
|
284
|
+
return { bytes: Buffer.byteLength(JSON.stringify(data), "utf8") - 2, ...(size ?? {}) };
|
|
75
285
|
}
|
package/dist/host/proxy.d.ts
CHANGED
|
@@ -70,14 +70,20 @@ export interface ProviderPolicy {
|
|
|
70
70
|
* smaller one for a client's background calls). The runner is asked about, and the price taken for, that model.
|
|
71
71
|
* Absent, or undefined for a body: the session's model. */
|
|
72
72
|
modelOf?(body: Record<string, unknown>): string | undefined;
|
|
73
|
-
/** The input tokens the provider bills for the body `apply` returned
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
73
|
+
/** The input tokens the provider bills for the body `apply` returned beyond its bytes: a prompt it adds itself, such as
|
|
74
|
+
* a tool-use system prompt, and each image at what it is billed as in place of the bytes its data takes in the body
|
|
75
|
+
* (`providerInputOverhead`), which can make it less than 0. Added to the body's bytes for `inputTokensMax`; the sum
|
|
76
|
+
* below 0 is no bound (unmeasured). Undefined: the body has no input bound the policy can state (a hosted tool that
|
|
77
|
+
* reads pages into the input), so `inputTokensMax` is undefined, never 0 or the body's bytes alone. Absent: none. */
|
|
77
78
|
serverInputOverhead?(body: Record<string, unknown>): number | undefined;
|
|
78
79
|
/** The output tokens the body `apply` returned asks for at most (its own limit, as `apply` shaped it). Absent or
|
|
79
80
|
* undefined: the body does not say. */
|
|
80
81
|
outputAsked?(body: Record<string, unknown>): number | undefined;
|
|
82
|
+
/** The provider's own count of a request's input tokens (Anthropic's free count_tokens), which the proxy asks before
|
|
83
|
+
* each of the session's answer requests (`countedInputOf`) when its upstream is exactly `origin`, the provider's own: never
|
|
84
|
+
* through a gateway or any other base, so the key and the request go nowhere the request itself would not. Its count,
|
|
85
|
+
* plus `margin`, is that request's input bound when it is below the byte bound. Absent: never counted. */
|
|
86
|
+
countInput?: InputCounter;
|
|
81
87
|
/** The least output the body may be limited to and still answer: 1,024 tokens for the answer, plus the least thinking
|
|
82
88
|
* its provider takes when it thinks. Absent: 1,024. */
|
|
83
89
|
outputLeast?(body: Record<string, unknown>): number;
|
|
@@ -178,6 +184,9 @@ export interface ProxyRequest {
|
|
|
178
184
|
noted?: true;
|
|
179
185
|
/** The label of the side key it came under (ModelProxy.sideKey): the host's own request, beside the harness's. */
|
|
180
186
|
host?: string;
|
|
187
|
+
/** Its `inputTokensMax` is its provider's count (ProviderPolicy.countInput), not its bytes: a host that compares one
|
|
188
|
+
* request's bound with another's (how far a conversation grew) pairs a counted bound only with a counted one. */
|
|
189
|
+
inputTokensCounted?: true;
|
|
181
190
|
}
|
|
182
191
|
export interface ModelProxyHooks {
|
|
183
192
|
/** Before a paid request leaves; a throw refuses it. What it returns (a ticket) is handed back to this request's
|
|
@@ -200,6 +209,10 @@ export interface ModelProxyOptions {
|
|
|
200
209
|
hooks: ModelProxyHooks;
|
|
201
210
|
/** The session's model, as the runner names it to `beforeRequest`. The policy fixes the body's model. */
|
|
202
211
|
model: string;
|
|
212
|
+
/** This proxy's route among the session's, told to `beforeRequest` with each request (ModelRequest.route) so the host
|
|
213
|
+
* prices it at this proxy's price: a proxy beside the session's for another tier's model names its tier. Absent: the
|
|
214
|
+
* session's own. */
|
|
215
|
+
route?: string;
|
|
203
216
|
/** The provider's base: its origin and, for a gateway that serves the API under a path, that path
|
|
204
217
|
* (`https://api.example.com`, `https://gateway.example/api`). A route's path is appended to it. A base with userinfo, a
|
|
205
218
|
* query or a fragment is refused, so the key goes only where the base reads. */
|
|
@@ -293,6 +306,29 @@ export declare function matchRoute(routes: readonly ProxyRoute[], method: string
|
|
|
293
306
|
export declare function parseStrict(text: string): unknown;
|
|
294
307
|
/** Whether `given` is `key`, in time that does not depend on where they differ. */
|
|
295
308
|
export declare const sameKey: (given: string, key: string) => boolean;
|
|
309
|
+
/** A provider's endpoint that counts a request's input tokens (ProviderPolicy.countInput). */
|
|
310
|
+
export interface InputCounter {
|
|
311
|
+
/** The provider's own base (`https://api.anthropic.com`): counted only when the session's upstream is exactly it. */
|
|
312
|
+
readonly origin: string;
|
|
313
|
+
/** The counting endpoint's path under it (`/v1/messages/count_tokens`). */
|
|
314
|
+
readonly path: string;
|
|
315
|
+
/** The body to count, from the request's (the fields the endpoint takes). */
|
|
316
|
+
body(body: Record<string, unknown>): Record<string, unknown>;
|
|
317
|
+
/** The headers to send it, from the request's as the proxy sends them (its credential and version headers among them). */
|
|
318
|
+
headers(sent: Record<string, string>): Record<string, string>;
|
|
319
|
+
/** The input tokens its answer says, or undefined when it says none. */
|
|
320
|
+
tokensOf(answer: unknown): number | undefined;
|
|
321
|
+
/** What the provider bills beside the count, which the count may leave out (a tool-use system prompt): added to it. */
|
|
322
|
+
margin?(body: Record<string, unknown>): number;
|
|
323
|
+
}
|
|
324
|
+
/** How long a count may take before the request goes on its byte bound: a count never holds a request up for long. */
|
|
325
|
+
export declare const COUNT_TIMEOUT_MS = 3000;
|
|
326
|
+
/**
|
|
327
|
+
* The exact input tokens of a request with body `body`, by its provider's own count (`policy.countInput`), plus its
|
|
328
|
+
* margin; undefined (the request keeps its byte bound) when the policy has no counter, the upstream `origin` is not
|
|
329
|
+
* the counter's own, or the count fails, times out or says no count. Never throws: a count is only ever a tighter bound.
|
|
330
|
+
*/
|
|
331
|
+
export declare function countedInputOf(policy: ProviderPolicy, origin: string, body: Record<string, unknown>, headers: Record<string, string>, fetch: typeof globalThis.fetch, say?: (message: string, detail?: Record<string, unknown>) => void, timeoutMs?: number, signal?: AbortSignal): Promise<number | undefined>;
|
|
296
332
|
/** Start a session's model proxy on the loopback interface, admitting `key`. */
|
|
297
333
|
/**
|
|
298
334
|
* The most input tokens a request with body `sent` (the body `apply` returned, as it is sent) can be billed for: its UTF-8
|