@parcha/agentrun-kernel 0.1.0-beta.33 → 0.1.0-beta.35

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.
Files changed (41) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/host/index.d.ts +4 -4
  3. package/dist/host/index.js +3 -3
  4. package/dist/host/overhead.d.ts +75 -4
  5. package/dist/host/overhead.js +220 -10
  6. package/dist/host/pinned-binary.d.ts +27 -2
  7. package/dist/host/pinned-binary.js +97 -8
  8. package/dist/host/proxy.d.ts +40 -4
  9. package/dist/host/proxy.js +73 -2
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +2 -2
  12. package/dist/kernel/cap/index.d.ts +2 -2
  13. package/dist/kernel/cap/index.js +2 -2
  14. package/dist/kernel/cap/park.js +4 -2
  15. package/dist/kernel/cap/port.d.ts +3 -2
  16. package/dist/kernel/cap/port.js +7 -2
  17. package/dist/kernel/cap/price.js +5 -2
  18. package/dist/kernel/cap/run-cap.d.ts +21 -5
  19. package/dist/kernel/cap/run-cap.js +42 -4
  20. package/dist/kernel/cap/types.d.ts +7 -0
  21. package/dist/kernel/cap/words.d.ts +9 -0
  22. package/dist/kernel/cap/words.js +16 -1
  23. package/dist/kernel/registry/defs.d.ts +3 -6
  24. package/dist/kernel/registry/defs.js +6 -11
  25. package/dist/kernel/registry/hands.d.ts +3 -22
  26. package/dist/kernel/registry/index.d.ts +1 -3
  27. package/dist/kernel/registry/index.js +3 -3
  28. package/dist/kernel/registry/registry.d.ts +2 -5
  29. package/dist/kernel/registry/registry.js +8 -10
  30. package/dist/process/tools.d.ts +9 -0
  31. package/dist/process/tools.js +19 -6
  32. package/dist/run-booking.js +4 -1
  33. package/dist/runner.d.ts +27 -1
  34. package/dist/runner.js +55 -8
  35. package/dist/testing.d.ts +9 -2
  36. package/dist/testing.js +63 -18
  37. package/dist/types.d.ts +32 -3
  38. package/dist/types.js +2 -0
  39. package/package.json +3 -3
  40. package/dist/kernel/registry/browser.d.ts +0 -11
  41. package/dist/kernel/registry/browser.js +0 -14
package/CHANGELOG.md CHANGED
@@ -2,6 +2,48 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.35 (2026-11-11)
6
+
7
+ - 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.
8
+ 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.
9
+ 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.
10
+ - 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.
11
+
12
+ 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).
13
+ - 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:
14
+ - 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".
15
+ - 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.
16
+ - Runs on the runner behave as before the cutover in four places a person could hit:
17
+ - 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.
18
+ - 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.
19
+ - 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.
20
+ - 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.
21
+ - 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.
22
+ - 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.
23
+ - 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.
24
+
25
+ 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):
26
+ - Anthropic: its 28-pixel patches or its area at 750 pixels a token, whichever is more, at most 4,784.
27
+ - 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.
28
+ - Google: 258 per 768-pixel tile, at least 1,120.
29
+ - Any other provider: the most of the three.
30
+ 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.
31
+
32
+ `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.
33
+ - 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:
34
+ - 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.
35
+ - 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.
36
+ - 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.
37
+
38
+ ## 0.1.0-beta.34 (2026-11-11)
39
+
40
+ - 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.
41
+ - The kernel registry has no browser kind any more: `CapabilityKind` is `"desktop" | "phone"`, and `browserToolDefs`, `BrowserContract`, `Browser`, `CdpSession`, `Hands.browser`, `HostExecutors.browser` and `createRegistry`'s `browserTools` option are gone. A host whose computer is a browser drives it with its own browser tool (serve's, pi-browser's durable extension), and passes no browser kind, contracts or executors to `createRegistry`.
42
+ - A browser run's money on the runner is counted once and shown. `/v2/usage` shows a runner run's browser time again (its `browser_time` meter read per-run files the runner never writes). A run parked at its cap by a browser call shows the cap's words on its budget card, where its reason was empty. Each browser charge is booked once on the run's ledger, under its real call when it has one, named by its session and time so a reopen never books it twice; a charge owed at the provider (a session's release, a person's carried time) is booked past the cap, as main kept it. The browser's holds (a call's, a session's reserve, a person's time) are money reserved, never spent: a lost claim gives them back, never leaves them counted as spent.
43
+ - A codex, opencode or claude-agent run that reads one of its skills' files (`read_skill_file`) now shows the call and its result on the run's Timeline, as pi's tool calls are shown. On the runner, the adapter's own skill reader ran outside the run's record, so the Timeline had no row for it. The read now goes through the host's tool path (the record, the rule before a side effect, the host's hooks on its result); a new `SessionIO.hostTool` hands an adapter's own tool to the host, and the kernel's `hostedTool(io, tool)` applies it.
44
+ - Upgrading: nothing to change.
45
+ - A run with a spend cap no longer passes it quietly. When an answer costs more than the cap had room for (an answer longer than expected, a native web search), the answer is booked and the run ends failed with error code `spend_cap_reached` and "The run cost $X, $Y over its cap of $Z.", as before the runner; it used to end completed, or pause for a raise at its next request. A cache miss within the bound its request was admitted at still pauses the run at its next request. A paid tool call (a web search or fetch, a paid MCP call) cut off by a runner crash or a takeover is booked as a charge of an unknown amount at the next claim: the run's cost reads unknown, counted at the call's hold for the cap, where it read as free. A model answer with no price (a gateway model the catalog does not list, with no price set) makes the run's cost unknown, never $0. A Claude Code, Codex or workflow run's `/v2/usage` tokens meter is its model requests' booked cost, where it read $0.
46
+
5
47
  ## 0.1.0-beta.33 (2026-11-10)
6
48
 
7
49
  - A run parked at its spend cap no longer shows a "Model request failed: 400 {…agentrun_proxy…}" row in its Timeline. The model proxy refused that request before it was sent, and the park's row already says what happened. That refused request also no longer counts as a model request in the run's usage line.
@@ -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";
@@ -9,4 +9,4 @@ export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./pa
9
9
  export type { LaunchCommand, ParentWatch } from "./parent-death.js";
10
10
  export { BoxError } from "./box.js";
11
11
  export type { BoxErrorCode, BoxRecord, BoxRecorder, Reaped } from "./box.js";
12
- export { checkedOnce, sha256OfFile } from "./pinned-binary.js";
12
+ export { type BinaryCheck, type BinaryProbe, checkedOnce, checkedOnceAsync, sha256OfFile, sha256OfFileAsync } from "./pinned-binary.js";
@@ -1,10 +1,10 @@
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";
8
8
  export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./parent-death.js";
9
9
  export { BoxError } from "./box.js";
10
- export { checkedOnce, sha256OfFile } from "./pinned-binary.js";
10
+ export { checkedOnce, checkedOnceAsync, sha256OfFile, sha256OfFileAsync } from "./pinned-binary.js";
@@ -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: number;
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", ...). A documented API gets its documented figures; any other gets the
51
- * general figure (`INPUT_OVERHEAD_APIS`). Never undefined: an input that cannot be measured is the body's, not the API's.
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;
@@ -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. Each figure is the largest the provider documents for any current
8
- // model, so no model is undercounted.
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", ...). A documented API gets its documented figures; any other gets the
63
- * general figure (`INPUT_OVERHEAD_APIS`). Never undefined: an input that cannot be measured is the body's, not the API's.
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 (!Number.isSafeInteger(shape.images) || shape.images < 0)
67
- throw new Error(`not an image count: ${String(shape.images).slice(0, 40)}`);
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) + shape.images * ANTHROPIC_IMAGE_TOKENS_MAX;
95
+ return anthropicToolPrompt(shape) + imagesNet;
70
96
  if (api === CHAT_COMPLETIONS)
71
- return (shape.tools ? ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS.anyOrTool : 0) + shape.images * OPENAI_IMAGE_TOKENS_MAX;
97
+ return (shape.tools ? ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS.anyOrTool : 0) + imagesNet;
72
98
  if (INPUT_OVERHEAD_APIS.includes(api))
73
- return shape.images * OPENAI_IMAGE_TOKENS_MAX;
74
- return (shape.tools ? ASSUMED_TOOL_PROMPT_TOKENS : 0) + shape.images * OPENAI_IMAGE_TOKENS_MAX;
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
  }
@@ -1,6 +1,31 @@
1
1
  /** The sha256 of the file at `path`, as hex, read a chunk at a time. Throws as `openSync` and `readSync` do. */
2
2
  export declare function sha256OfFile(path: string): string;
3
+ /** sha256OfFile without holding the event loop: each chunk is read off it, and the loop goes on between chunks. Rejects
4
+ * as `open` and `read` do. */
5
+ export declare function sha256OfFileAsync(path: string): Promise<string>;
6
+ /** What a binary's check reads of it: its sha256, or what it prints on stdout when run (`args`, `env` alone, in `cwd`,
7
+ * killed past `timeoutMs`). */
8
+ export type BinaryProbe = {
9
+ readonly kind: "sha256";
10
+ readonly path: string;
11
+ } | {
12
+ readonly kind: "run";
13
+ readonly path: string;
14
+ readonly args: readonly string[];
15
+ readonly env: NodeJS.ProcessEnv;
16
+ readonly cwd?: string;
17
+ readonly timeoutMs: number;
18
+ };
19
+ /** A binary's check, written once as the steps it reads: each step yields a probe and is given back its answer, or has
20
+ * the probe's error thrown in (a file that cannot be read, a binary that cannot be run or does not end in time). It
21
+ * answers its result. */
22
+ export type BinaryCheck<T> = () => Generator<BinaryProbe, T, string>;
3
23
  /** `check`'s result for the binary at `path` against `pins`, run once per identity in this process: a result `ok` calls
4
24
  * passed is kept, and answered again at once while the binary stays the same file, unchanged; any other is never kept.
5
- * A binary that changed while it was checked is not kept, and is checked again next time. */
6
- export declare function checkedOnce<T>(path: string, pins: string, check: () => T, ok: (result: T) => boolean): T;
25
+ * A binary that changed while it was checked is not kept, and is checked again next time. Its reads hold the event
26
+ * loop: a host checks with checkedOnceAsync first, and this answers from what that kept. */
27
+ export declare function checkedOnce<T>(path: string, pins: string, check: BinaryCheck<T>, ok: (result: T) => boolean): T;
28
+ /** checkedOnce without holding the event loop: the sha256 read a chunk at a time off it, the binary run as a child the
29
+ * loop does not wait on. A check of the same binary already running is the one answered; one that passed is kept for
30
+ * checkedOnce too. */
31
+ export declare function checkedOnceAsync<T>(path: string, pins: string, check: BinaryCheck<T>, ok: (result: T) => boolean): Promise<T>;
@@ -1,11 +1,17 @@
1
- // A harness's binary, checked against its pins (codex's, claude-agent's): its sha256 read a chunk at a time, and each
2
- // check that passed kept for the process by what the binary is. A binary is hundreds of MiB; read whole, each check held
3
- // all of it in memory, and a host that checks it again for each model it resolves held it again each time. Here a process
4
- // holds one chunk at most, and checks a binary once per identity: its path, the file it names (device and inode), its
5
- // size and its modification and change times, with the pins it met. Replaced or touched, it is checked again; a check
6
- // that failed is never kept, so the next one runs again.
1
+ // A harness's binary, checked against its pins (codex's, claude-agent's, opencode's): its sha256 read a chunk at a time,
2
+ // and each check that passed kept for the process by what the binary is. A binary is hundreds of MiB; read whole, each
3
+ // check held all of it in memory, and a host that checks it again for each model it resolves held it again each time.
4
+ // Here a process holds one chunk at most, and checks a binary once per identity: its path, the file it names (device and
5
+ // inode), its size and its modification and change times, with the pins it met. Replaced or touched, it is checked
6
+ // again; a check that failed is never kept, so the next one runs again.
7
+ //
8
+ // A check is written once, as the steps it reads of the binary (BinaryCheck: its sha256, what it prints when run), and
9
+ // run either synchronously (checkedOnce: an adapter's own guard as it is made) or without holding the event loop
10
+ // (checkedOnceAsync: a host's, while it goes on answering), each passed check kept for both.
11
+ import { execFile, execFileSync } from "node:child_process";
7
12
  import { createHash } from "node:crypto";
8
13
  import { closeSync, openSync, readSync, statSync } from "node:fs";
14
+ import { open } from "node:fs/promises";
9
15
  /** The bytes read at a time. */
10
16
  const CHUNK = 1 << 20;
11
17
  /** The sha256 of the file at `path`, as hex, read a chunk at a time. Throws as `openSync` and `readSync` do. */
@@ -22,6 +28,64 @@ export function sha256OfFile(path) {
22
28
  }
23
29
  return hash.digest("hex");
24
30
  }
31
+ /** sha256OfFile without holding the event loop: each chunk is read off it, and the loop goes on between chunks. Rejects
32
+ * as `open` and `read` do. */
33
+ export async function sha256OfFileAsync(path) {
34
+ const hash = createHash("sha256");
35
+ const file = await open(path, "r");
36
+ try {
37
+ const chunk = Buffer.allocUnsafe(CHUNK);
38
+ for (;;) {
39
+ const { bytesRead } = await file.read(chunk, 0, CHUNK, null);
40
+ if (bytesRead === 0)
41
+ break;
42
+ hash.update(chunk.subarray(0, bytesRead));
43
+ }
44
+ }
45
+ finally {
46
+ await file.close();
47
+ }
48
+ return hash.digest("hex");
49
+ }
50
+ const runOptions = (probe) => ({ env: probe.env, ...(probe.cwd ? { cwd: probe.cwd } : {}), encoding: "utf8", timeout: probe.timeoutMs });
51
+ /** `check` run with each probe answered synchronously. */
52
+ function checkSync(check) {
53
+ const steps = check();
54
+ for (let step = steps.next();;) {
55
+ if (step.done)
56
+ return step.value;
57
+ let answer;
58
+ try {
59
+ const probe = step.value;
60
+ answer = probe.kind === "sha256" ? sha256OfFile(probe.path) : execFileSync(probe.path, [...probe.args], runOptions(probe));
61
+ }
62
+ catch (error) {
63
+ step = steps.throw(error);
64
+ continue;
65
+ }
66
+ step = steps.next(answer);
67
+ }
68
+ }
69
+ /** One run of a binary, its stdout: rejects as execFileSync throws (a spawn that failed, a nonzero exit, its timeout). */
70
+ const runChild = (probe) => new Promise((resolve, reject) => execFile(probe.path, [...probe.args], runOptions(probe), (error, stdout) => (error ? reject(error) : resolve(stdout))));
71
+ /** `check` run with each probe answered without holding the event loop. */
72
+ async function checkOffLoop(check) {
73
+ const steps = check();
74
+ for (let step = steps.next();;) {
75
+ if (step.done)
76
+ return step.value;
77
+ let answer;
78
+ try {
79
+ const probe = step.value;
80
+ answer = probe.kind === "sha256" ? await sha256OfFileAsync(probe.path) : await runChild(probe);
81
+ }
82
+ catch (error) {
83
+ step = steps.throw(error);
84
+ continue;
85
+ }
86
+ step = steps.next(answer);
87
+ }
88
+ }
25
89
  /** What the file at `path` is, for `pins` (any text that names them): undefined when it cannot be read. */
26
90
  function identityOf(path, pins) {
27
91
  try {
@@ -34,15 +98,40 @@ function identityOf(path, pins) {
34
98
  }
35
99
  /** What each check that passed answered, by the binary's identity. */
36
100
  const passed = new Map();
101
+ /** Each check running without holding the loop, by the binary's identity: a second asks for the same answer. */
102
+ const checking = new Map();
37
103
  /** `check`'s result for the binary at `path` against `pins`, run once per identity in this process: a result `ok` calls
38
104
  * passed is kept, and answered again at once while the binary stays the same file, unchanged; any other is never kept.
39
- * A binary that changed while it was checked is not kept, and is checked again next time. */
105
+ * A binary that changed while it was checked is not kept, and is checked again next time. Its reads hold the event
106
+ * loop: a host checks with checkedOnceAsync first, and this answers from what that kept. */
40
107
  export function checkedOnce(path, pins, check, ok) {
41
108
  const identity = identityOf(path, pins);
42
109
  if (identity !== undefined && passed.has(identity))
43
110
  return passed.get(identity);
44
- const result = check();
111
+ const result = checkSync(check);
45
112
  if (identity !== undefined && ok(result) && identityOf(path, pins) === identity)
46
113
  passed.set(identity, result);
47
114
  return result;
48
115
  }
116
+ /** checkedOnce without holding the event loop: the sha256 read a chunk at a time off it, the binary run as a child the
117
+ * loop does not wait on. A check of the same binary already running is the one answered; one that passed is kept for
118
+ * checkedOnce too. */
119
+ export function checkedOnceAsync(path, pins, check, ok) {
120
+ const identity = identityOf(path, pins);
121
+ if (identity !== undefined && passed.has(identity))
122
+ return Promise.resolve(passed.get(identity));
123
+ const running = identity !== undefined ? checking.get(identity) : undefined;
124
+ if (running)
125
+ return running;
126
+ const result = checkOffLoop(check).then((value) => {
127
+ if (identity !== undefined && ok(value) && identityOf(path, pins) === identity)
128
+ passed.set(identity, value);
129
+ return value;
130
+ });
131
+ if (identity !== undefined) {
132
+ checking.set(identity, result);
133
+ const done = () => void checking.delete(identity);
134
+ result.then(done, done);
135
+ }
136
+ return result;
137
+ }