@parcha/agentrun-kernel 0.1.0-beta.38 → 0.1.0-beta.40

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 (67) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/NOTICE +2 -0
  3. package/dist/booking.d.ts +25 -6
  4. package/dist/booking.js +15 -4
  5. package/dist/host/index.d.ts +4 -3
  6. package/dist/host/index.js +3 -2
  7. package/dist/host/o200k.d.ts +11 -0
  8. package/dist/host/o200k.js +185 -0
  9. package/dist/host/overhead.d.ts +72 -12
  10. package/dist/host/overhead.js +220 -38
  11. package/dist/host/proxy.d.ts +85 -7
  12. package/dist/host/proxy.js +374 -87
  13. package/dist/index.d.ts +6 -6
  14. package/dist/index.js +4 -4
  15. package/dist/kernel/cap/admit.d.ts +5 -8
  16. package/dist/kernel/cap/admit.js +13 -19
  17. package/dist/kernel/cap/free.d.ts +43 -0
  18. package/dist/kernel/cap/free.js +71 -0
  19. package/dist/kernel/cap/index.d.ts +6 -5
  20. package/dist/kernel/cap/index.js +5 -4
  21. package/dist/kernel/cap/marks.d.ts +2 -3
  22. package/dist/kernel/cap/park.d.ts +3 -4
  23. package/dist/kernel/cap/park.js +4 -5
  24. package/dist/kernel/cap/port.d.ts +8 -13
  25. package/dist/kernel/cap/port.js +10 -18
  26. package/dist/kernel/cap/price.d.ts +10 -49
  27. package/dist/kernel/cap/price.js +15 -68
  28. package/dist/kernel/cap/recover.d.ts +1 -2
  29. package/dist/kernel/cap/recover.js +2 -4
  30. package/dist/kernel/cap/rule.d.ts +8 -16
  31. package/dist/kernel/cap/rule.js +35 -35
  32. package/dist/kernel/cap/run-cap.d.ts +21 -13
  33. package/dist/kernel/cap/run-cap.js +74 -36
  34. package/dist/kernel/cap/types.d.ts +11 -31
  35. package/dist/kernel/cap/words.d.ts +13 -8
  36. package/dist/kernel/cap/words.js +23 -14
  37. package/dist/kernel/cap/wrap-up.d.ts +4 -0
  38. package/dist/kernel/cap/wrap-up.js +5 -1
  39. package/dist/kernel/registry/computer-surface.generated.d.ts +1 -1
  40. package/dist/kernel/registry/computer-surface.generated.js +9 -25
  41. package/dist/kernel/registry/computer.d.ts +14 -7
  42. package/dist/kernel/registry/computer.js +52 -12
  43. package/dist/kernel/registry/gate.d.ts +2 -2
  44. package/dist/kernel/registry/gate.js +4 -7
  45. package/dist/kernel/registry/hands.d.ts +3 -4
  46. package/dist/kernel/registry/index.d.ts +1 -1
  47. package/dist/kernel/registry/index.js +1 -1
  48. package/dist/kernel/registry/registry.js +6 -9
  49. package/dist/process/recovery.d.ts +4 -1
  50. package/dist/process/recovery.js +15 -3
  51. package/dist/process/resume.d.ts +5 -2
  52. package/dist/process/resume.js +15 -3
  53. package/dist/process/tools.d.ts +26 -1
  54. package/dist/process/tools.js +47 -4
  55. package/dist/run-booking.d.ts +21 -2
  56. package/dist/run-booking.js +215 -18
  57. package/dist/runner.d.ts +82 -21
  58. package/dist/runner.js +176 -59
  59. package/dist/testing.d.ts +4 -2
  60. package/dist/testing.js +2 -2
  61. package/dist/tool-deferral.d.ts +3 -3
  62. package/dist/tool-deferral.js +4 -4
  63. package/dist/types.d.ts +70 -14
  64. package/dist/types.js +8 -0
  65. package/package.json +5 -3
  66. package/vendor/o200k/LICENSE +61 -0
  67. package/vendor/o200k/o200k_base.tiktoken +199998 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,89 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.39 (2026-11-16)
6
+
7
+ - Near its cap, a run's parallel steps wait for each other instead of parking: a model request, a decision or a paid tool call (a web fetch, a search, a monid call, codemode's among them) that does not fit only because steps still running hold the room it needs waits for them to settle, and is sent once its room is back. It is refused only when what the run has spent and its own least need do not fit with nothing else running. The cap is never passed: every step is admitted by the same rule over the holds as they are then. Eight subagents started at once under a $0.50 cap, or a burst of 25 fetches and searches under a $4 cap that cost about $0.50, now finish where they parked at `spend_cap_reached`.
8
+ - Waiters go first come, first served across the run's sessions, and only the first in line asks, so a small step never takes the room an earlier one waits for. A waiter holds nothing. It leaves the line unsent when its run is stopped, cancelled or loses its claim, and is refused in its own words when the run parks meanwhile. A step it waits on that does not settle within 10 minutes refuses it, and the run parks for a raise as before. The line reads the run's records again on a short timer (50 ms doubling to 1 s), so steps in other processes of the run wake it the same way.
9
+ - Breaking: the budget pause's `spent_usd` is what the run spent, never what its running steps hold. The new `held_usd` says what they held when the step was refused (mostly 0), and `suggested_cap_usd` is `spent_usd` + `held_usd` + 10 × `needs_usd`. A client that read `spent_usd` as everything the cap had taken adds `held_usd`. The generated TypeScript and Python clients gain the field.
10
+ - The refusal words keep spent and held apart: "Not sent: this run has spent $0.45 of its $0.50 cap and is holding $0.03 for steps still running; the next step, web_fetch, could cost up to $0.10 (a fetch), more than the cap leaves even once the steps still running settle. Raise the cap to at least $0.55 to continue." The console's budget pause says what is held beside what is spent.
11
+ - A paid tool call never waits on the model request that asked for it. Claude Code books a request's cost after its calls and Codex starts a call with its response still open, so that request settles only once the call returns. A paid call made in a CLI's tool call is judged beside its session's requests still running: it is sent when it fits beside them, waits only for other steps to settle, and is refused at once when it cannot fit beside them, never left to stall for 10 minutes. It also goes ahead of steps in line that may be waiting on that request.
12
+ - A running run's cost in the runs list is what it has spent: a step still running counts once it is answered, never at its hold.
13
+ - Kernel: `aloneRefusal`, `runBooking`, `RunBookingOptions`, `RECORD_WAIT_MS`, `WAIT_STALL_MS`, `WAIT_POLL_FIRST_MS` and `WAIT_POLL_MOST_MS` are exported; `RunCapOptions` gains `parked`, `waitStallMs` and `stopped`; `Refusal` gains `waits` and `figures.heldUsd`; `InFlight` gains `stays`; `ModelRequest` and `ProxyRequest` gain `signal`; `ModelRequest.paid` and `RunTools.admit` gain `under`, the model session whose tool call a paid call runs in; `BudgetPending` gains `held_usd`.
14
+ - A run's cap is never passed: every model request is held at its worst case, its whole input priced uncached (at the cache-write rate when that is dearer), so a cache miss can no longer take a run past its `max_cost_usd`. The `expected` cap mode, which priced the input from the previous request's cache and let a miss go over by a bound, is gone, and with it the `cap_mode` setting.
15
+ - Breaking, for API clients: remove `cap_mode` from what you send. A run start (`POST /agents/{agent_id}/runs`, `POST /runs`) that still sends it is refused `422` with `{"field": "cap_mode", "reason": "not_allowed"}`, and an agent definition (create or update) that still sends it is refused `422` with `definition.cap_mode` `not_allowed`. The generated clients and the CLI no longer have it (`--cap-mode` is gone). Every run now behaves as `strict` did. A stored agent revision or run launch that still holds a cap mode is read as if it had none. An inline agent's version (`POST /runs` with `external`) that first ran with a cap mode keeps it in its stored body, so running that version again with the field dropped is `409 external_body_conflict`: publish a new version and run that.
16
+ - Breaking: `cost.overshoot_bound_usd` and the budget pause's `overshoot_bound_usd` are gone from the run's view. The generated TypeScript and Python clients and the CLI (`--cap-mode`) lose them too.
17
+ - A request is not parked for want of room to answer: its output is clamped to what the cap has left after its input at the worst case, and it is refused only when that input plus the least answer (1,024 tokens) does not fit. The in-flight hold and the CLI harness's reserve for its answer are counted at the worst case too.
18
+ - A Codex or OpenCode request on an OpenAI model (gpt-4o and later, the o-series, gpt-oss) is held at a local count of its input in place of its bytes, on every route: o200k_base over the body as sent, plus a tenth, 16 tokens an item and 256 a request, with encrypted reasoning at its bytes and each image at its billed size, and never above its bytes. A capped run through a gateway that parked on its bytes (a $0.50 lead list asked for $0.52) now goes on. Any other model keeps its byte bound.
19
+ - The kernel ships OpenAI's o200k_base vocabulary file unchanged (3.6 MB, MIT, `vendor/o200k/`, checked by the sha256 tiktoken pins) and counts with it itself: no tokenizer package is a dependency. Its ranks are loaded on the first count.
20
+ - A run whose requests read the cache spends less than it is held at, so it pauses earlier than under `expected`: raise the cap by the cached share of its input if a run that used to finish now pauses.
21
+ - A capped run on a ChatGPT plan model (`chatgpt/…`) is admitted. Its model requests are billed to the plan: each is held at $0, its output is never limited on dollars, and it adds $0 to the cap's spend and to the wrap-up's reserve. A paid tool beside them still counts and stops the run at the cap. A model with no price that is no plan's model is still refused under a cap.
22
+ - On a ChatGPT plan, a 429 that says the plan's usage limit is reached (`usage_limit_exceeded` or `subscription_sharing_usage_limit_exceeded`) ends the run with "Your ChatGPT plan's limit is reached. Manage usage in your ChatGPT settings, then run it again.": no retry, no switch to a key, no raise-the-cap pause.
23
+ - Kernel: `CapModel.plan`, `PLAN_LIMIT_WORDS`, `PLAN_LIMIT_CODE`, `ProviderPolicy.finalError` and `ModelProxyOptions.onFinal` are new, and so are `ProviderPolicy.countInputLocally`, `responsesLocalInputTokens`, `localInputOf`, `o200kTokens`, `o200kModel` and `LOCAL_COUNT_MARGIN`.
24
+ - Kernel: `CapMode`, `RecentRequest`, `CapOptions.mode`, `Admission.boundUsd`, `RefusalFigures.boundUsd`, `DECISION_OUTPUT_TOKENS` and `ModelRequest.inputTokensCounted` are gone. A decision is held at its model's most completion tokens.
25
+ - A Codex or OpenCode request straight to OpenAI is no longer counted by OpenAI before it is sent: it is held at the kernel's local o200k_base count with its margin, as a request through a gateway already is, so it never waits up to 3 seconds on `POST /v1/responses/input_tokens` first. A capped run on such a route may pause a little sooner than it did on OpenAI's exact count; the cap is still never passed.
26
+ - Breaking, for a host of the kernel: `OPENAI_INPUT_COUNTER` is gone. A `ProviderPolicy` that named it as `countInput` drops it and sets `countInputLocally: responsesLocalInputTokens`. Anthropic's count (`countInput` on the claude-agent policy) is unchanged.
27
+ - `computer_script` is gone: a desktop or phone run scripts its computer through the host's `codemode`, whose script has the computer as `computer` (its types in codemode's description), and each of its calls is a nested call, held to the run's gate and recorded on the timeline. A shell command is held to the agent's `bash` setting, a started process to `bash_background`, a file written to `write`, and a file read to `read`. An agent definition that named `computer_script` uses `codemode` instead. Codex, whose code mode takes no binding, and an MCP client of the claim's computer server (which serves the step tools and `computer_op`, never `codemode`) call the step tools and `computer_op` (`{op, args}`, an op named as `computer`'s method is, `shell.run` or `apps.open`) for what a `computer_script` script's `computer` ran. An earlier run's `computer_script` rows still read as they did.
28
+ - The kernel's `isCatalogName` is now `isCatalogWire`, and it matches a monid endpoint's wire name by `monid__` (the name every harness calls it by), no longer by the old single `monid_`. A host that imported `isCatalogName` from `@parcha/agentrun-kernel` imports `isCatalogWire` instead.
29
+ - An agent's monid pin is kept on its revision beside its MCP pin (`revisions.monid_pin`; Postgres migration `0012_revision_monid_pin.sql`, and a server open adds the column to a SQLite store), no longer inside the revision's body. An edit that leaves an agent's monid grants as they were reads nothing of monid's listing and keeps the pin; a grant it adds is read alone. Nothing reads a pin from an older revision's body (no compatibility path): a revision saved before this, with monid grants and no `monid_pin`, fails closed. Its runs are offered no monid endpoint, so no call runs unheld, until the agent is saved again.
30
+ - One check holds MCP and monid grants at the save and before each run. Its words for a tool the harness would drop or retype are "The tool <catalog name> cannot be offered on <harness>: <why>." for both sources. A workflow's monid grant is refused in the MCP grant's words: "<grant>: a workflow's nodes don't bind monid endpoints here yet; grant it to an agentic agent."
31
+ - A name that is no tool here is refused as "<name> is not a tool here: grant one of <the server's tools>, an MCP server's tool as mcp:<server>/<tool>, or a monid endpoint as monid:<provider>/<endpoint>."
32
+ - The monid key check reads `GET /v1/endpoints?limit=1`, the listing a save pins from, which monid does not charge for.
33
+ - A subagent given a grant gets each of the run's catalog tools that grant gives by the gate's keys, for MCP and monid alike.
34
+ - A learned workflow asks once per call, and its card says what it will do. The `learned_workflow` call's approval card lists each MCP action set to ask that the workflow can call, with the shape of its arguments (`{"tool":"mcp:linear/create_issue","args":{"title":"{title}"}}`; a `{name}` is filled in while the workflow runs). One allow lets those actions run with no second ask.
35
+ - Each MCP node now runs as a call nested in the workflow's call, asked at the gate as its own tool. An action the card did not name (set to ask after the card was shown, or past the card's 2 KB preview) parks the run on a card of its own instead of failing the workflow. An approval passes by tool, so a tool with any action past the preview is left off the card entirely, and each of its actions asks on its own. Each check of a polled MCP node, and each attempt of a retried one, is a call of its own, and a node's call is cut when the node is (a sibling's failure, its deadline). Only the card approved for that same call counts: an earlier call's card, of the same workflow or another, never passes it. A deny of any of the workflow's MCP actions still refuses the whole call before any node runs.
36
+ - A draft is no longer refused at learn time because its ask-set MCP actions would not all fit on one card: the ones past the card ask as they run.
37
+ - A `learned_workflow` call that a park or a crash cut runs again from its start, where a crash used to end it interrupted and hand it back to the model. Its model, decision and call nodes answer what they answered the first time, read from the record without asking the model or the decision provider again, so each is asked and booked on the run's ledger once; an MCP call that already ran answers from its record, so nothing is sent twice. A workflow served first still hands the job back when a crash cuts it, and an ask its card did not name refuses that node.
38
+ - A run's guard rows count the last trace each `learned_workflow` call wrote, so a call run again is counted once.
39
+ - `NestedCalls.memo` (`@parcha/agentrun-kernel`) also takes a function, called only while nothing is recorded for its key: a rerun reads the recorded value and never calls it, and a throw of the function records nothing. `NestedCalls.call` takes an optional fourth `signal`, which the nested call runs on beside the calling one's.
40
+ - Breaking: removed from `@parcha/agentrun-serve`'s modules: `host-calls.js` (`HostCalls`, `withHostCalls`, `hostCalls`), `learnedAskFits`, `LEARNED_ASK_CARD_BYTES` and `learnedMcpTools` (use `learnedMcpCalls`, which returns each action with its arguments), `DraftAsk` and `draftProblems`' `ask` parameter, `learnedDraftTools`' `asked` field, `RunPermissions.decide`, `SpecGate.askedFor` (the gate answers `{ ask: card }` instead) and `LearnedWorkflowRun.decide`. `LearnedWorkflowRun.mcpTools` is now a map from catalog name to the session's tool name, and `nestedOf` hands a call its nested calls.
41
+ - A server with no model key can run codex and pi on a person's ChatGPT plan. The owner signs in under `/settings/chatgpt` (OpenAI's Sign in with ChatGPT through pi-ai's own flow, finished by the loopback callback or by pasting the address the sign-in tab ended on), and models named `chatgpt/<id>` go to OpenAI's Responses API on the plan's token, billed to the plan with no price here.
42
+ - `GET /settings/chatgpt`, `POST /settings/chatgpt/sign-in`, `POST /settings/chatgpt/sign-in/finish` and `DELETE /settings/chatgpt` (owner session only). A bad or stale pasted address is a 400 in words. Sign-out revokes the session at OpenAI, then removes it.
43
+ - The sign-in is sealed in one row and read per request by the server and every runner, in their own processes or containers. A token renews once across all of them, 5 minutes before it ends: one holder takes a lease on the row (a compare-and-set on its sealed bytes, `SealedKeys.replaceIf`), and the others adopt the pair it writes back, so a refresh token is never used twice. A renewal sent with no answer read holds the lease to its end, since its refresh token may be spent; a fault OpenAI answers gives it back. A sign-out during a renewal stays. A refused renewal marks the sign-in expired, and runs on it fail at once in words. A 401 from OpenAI, in a pi turn or a workflow's model node, renews the token on the next request when the row still holds it.
44
+ - Capabilities say per harness whether it runs on the plan: pi and codex do, Claude Agent and OpenCode still need a key. Models list `source: "chatgpt"`.
45
+ - On the plan, the Codex policy sends no `max_output_tokens` and none of the keys the plan does not take, refuses a system-role message in words, and names its originator. Its turns are booked with `billing: "plan"` and no cost.
46
+ - Kernel: a model proxy's credential may throw `CredentialUnavailable` to refuse a request in the host's words (`code: "credential_unavailable"`), and `credentialRefused` tells the host the credential a provider answered 401 to.
47
+ - A run on a free model now stops at 60 requests on free models. A free model's catalog price is all zeros (an OpenRouter `:free` model and the like), so no spend cap could stop one stuck in a loop: a run on a free model made 520 web searches before it ended, burning its provider's shared daily quota. The request after the 60th is not sent, and the run ends `failed`, as one its cap ends, with error `spend_cap_reached`: "Not sent: this run reached its 60-request limit for free models." The limit holds capped or not, on every harness, and no raise lifts it. A server that needs more sets `AGENTRUN_FREE_MODEL_REQUESTS` (a whole number above 0; anything else refuses the start). ChatGPT-plan requests don't count.
48
+ - What counts: each request on a free model the run makes, its subagents' and side calls' included, and one a crash cut. A paid request, a paid tool call and a workflow's decision never count.
49
+ - A free request a crash cut, booked by the next process, is now a known $0 marked `free`, as a free request that ends in its own process already is; it was booked as unknown.
50
+ - Capabilities report the limit as `limits.free_model_requests` (marked `freerequests/1`), and the console says "free model: up to 60 requests" beside the spend cap of an agent on a free model.
51
+ - Kernel: `runCap` takes `freeRequests`, and `kernel/cap` exports `freeModel` and `freeRequest` (one rule for what the cap books at $0 and what the limit counts), `planCapModel`, `freeModelRequestsOf` and `freeCeilingEnd`. A runner's `runner.request` record says `freeRequest: true` for a request the limit counts.
52
+ - A run on a free model is now told when its free-model request limit is near. The request that has 3 requests left (itself included; the limit is 60, or `AGENTRUN_FREE_MODEL_REQUESTS`) carries one note, "AgentRun server note: 3 free-model requests left in this run, this one included: finish now with your answer.", labelled and placed the way the spend cap's wrap-up note is, once per run and shown as the server's row in the timeline. Before, the request past the limit was refused with no warning. A paid model's or a ChatGPT plan's requests never count or carry it. When the dollar cap's note is due on the same request, that one goes first.
53
+ - A capped Claude Agent run on a Claude model reached through a gateway (Sonnet 5.5 through OpenRouter) no longer stops at its second step with most of its cap left. The provider's count is asked for only at Anthropic, and no local tokenizer counts Claude, so each request was bounded by its bytes: about four times its tokens. An inbox agent's second request read as about 32,000 tokens, so at a $0.10 cap the step after one that cost $0.01-0.02 "needs at least $0.10" and the run paused, where a real step costs about $0.03. The model proxy now keeps each model's last request whose answer reported its whole input, and bounds a later request that carries it unchanged by that billed input plus the bytes of the messages it adds, when that is lower. That request must match the earlier one in everything that bills input apart from the added messages (system, tools, thinking, effort, model); a moved cache marker (a `cache_control` key on a tool, a system or message content block, or a block of a tool result's content) does not count as a change, and a `cache_control` key anywhere else is compared as text. The wrap-up note is asked for on that bound. A first request, a request that changes its tools or prompt, one that adds a document, or one that offers the hosted search keeps its byte bound, and a step that does not fit is still refused.
54
+
55
+ pi on a Claude model takes the same bound, through the same policy. Through a gateway, the smallest cap that takes a pi desktop run on Sonnet through its four screenshots to its answer goes from $0.12 to $0.09, the same as straight to Anthropic: the run needs $0.082, where it needed $0.110 on its bytes. Its first request keeps its byte bound ($0.052).
56
+ - A capped run on a model whose tokenizer is o200k_base, reached over Messages without Anthropic's count (pi on GPT-6.1 Sol through OpenRouter, sent through serve's translation), bounds each request's input by a local count with its stated margin, as a Responses request to a gateway already does. Before, its bytes were the bound: after a few long pages the body passed 272,000 bytes, every rate was priced at Sol's long-context tier, and a $1.50 run stopped at $0.10-0.27 because the cap refused to send a step it could pay for. A Claude model, a body with a document, or one that offers the hosted search keeps the provider count or the byte bound.
57
+ When a run's cap is below what its model needs for one more step and an answer, the wrap-up's words now say so with both amounts, and the effort the model's request asked for when it named one ("This run's cap of $0.25 is below what gpt-6.1-sol at medium effort needs for one more step and an answer, about $0.32."), so a run that stopped its tools at its first call shows the cap was the cause. The rule that decides when a run wraps up has not changed.
58
+ Saving an agent with a cap below that figure (POST /agents, an edit of its definition, or a package install with a per-run budget) now saves with a warning on `definition.max_cost_usd` ("This agent's cap of $0.25 is below what gpt-6.1-sol at medium effort needs for one more step and an answer, about $0.32: a run will wrap up at its first tool call."). It is never refused. The figure is priced on the first request the agent's harness sends: the harness's own input before the agent's prompt (Codex about 12,200 tokens, from billing; Claude Agent, OpenCode and pi measured on their pinned builds, each stated beside its pin), the agent's prompt where the model's tokenizer is o200k_base, and the least output at the agent's effort, its thinking included: a pi agent on a Claude model that thinks with a budget is priced with Claude's 1,024-token thinking minimum, as its first request asks for it.
59
+ - Two fixes to how a Codex code-mode `exec` reads after a park or a crash, and one to pi's wording. A Codex exec's end row now sorts after the rows of the calls its script made: a crash leaves the exec open on the run's record, and Codex's recovered answer to it ends it after the resume. An exec whose call parked on a person's approval and then ran reads ok, with the stopped-and-resumed text, as a codemode script that parked reads on pi and claude-agent, never failed. An exec cut off mid-call still reads failed, after its cut call's row. The same holds for an exec that yielded and was finished by the model's pending `wait` on its cell: it reads ok when its parked call was allowed and ran, and failed when that call was refused or the wait was told the script was cut off. A recovered exec's outcome is saved in the session's log before Codex is answered, so a second crash before its end is recorded still ends it as that outcome says. An exec that no answer of Codex's ends (its run stopped while its call waited for approval, or a crash whose next drive never resumed Codex's thread) is closed with the run, "interrupted", after its calls' rows, never left open or shown failed ahead of them. A computer_op refused before it ran is named on the timeline by its op ("Refused: files.write"), never by "computer_op" or by its arguments, on every harness. On pi, a script's call a crash cut off now reads "interrupted: the process running it stopped before it reported an outcome; it may or may not have taken effect", the words claude-agent, opencode and Codex already give it. On Codex, a computer_op answer stays text, because Codex 0.164.0's code mode hands a script one string and never throws on a tool's reply. The desktop and phone kind skills now say how to read it: an op that ran answers JSON to parse, and a refused op answers the gate's words, which open with `Permission denied:` or `The user denied this`, or give the tool's name then `is read-only for this agent, so this call was refused:` or `can't be called:`.
60
+ - On Codex in code mode, a tool call that finished in the same script as a call waiting for approval now keeps its whole result when the run goes on. Before, the script was cut when the run paused, and on the resume the model got each finished call's result cut to its first 2,000 characters, with a note saying the output of those calls was not shown. So it ran a long read again.
61
+ - A finished call's result, or a failed call's error, comes back as the script got it live: up to the same 120,000-character bound every tool result has, with the usual line saying where it was cut past that.
62
+ - The recovered script output as a whole stays within that bound plus 2,000 characters for the words around the results. Past it, every result in it is cut to the same share, each keeping its start and its last line (a long MCP answer's last line says where the whole answer was filed) and saying where it was cut. Every call's outcome is still told, unless the script made so many calls that their lines alone pass the bound: then the output is cut with the same note, and the recovery note says only the calls still in it are shown above.
63
+ - The recovery note says a finished or failed call's outcome is in the output of the script that made it, instead of "not shown here". A call whose outcome is not in that output (one cut mid-way) keeps the old words.
64
+ - `recoverySystemNote` takes the calls whose outcome is already shown as an optional second argument. Without it the note reads as before, so Claude Code, OpenCode and pi are unchanged.
65
+ - Three fixes to codemode's computer calls. A script call a person allowed carries its computer calls on its own result row only, not on its approval and "ran once you allowed it" rows too, so summing a run's rows counts each computer call once. A script rerun after a crash tells a recorded call whose answer has no value (a file write) by its answer's words, as it was answered live, not as `completed: null`. On Codex, a code-mode `exec` has its own rows, and each host tool call its script makes sits under it (`parent_tool_use_id`, the exec's call id), as a codemode script's calls do on pi, claude-agent and opencode; a host lends this through the new optional `SessionIO.ownCalls`. A Codex script that failed reads failed on its exec's row, never `exec: ok`.
66
+ - A run whose every model request went to a free model (one whose known price is $0 for every token, such as an OpenRouter `:free` model) now costs a known $0 and says why: its usage row reads "Cost: $0 · free model over N model requests", its `cost` and the usage row carry `free: true` (`x-agentrun-serve: "freemodel/1"`), and the console shows "$0 · free model". A request on such a model that failed once it left, was retried or was cut is booked at $0, where it used to make the run's cost unknown ("not priced"). The booking decides it from the model's known price, so a model with no known price still reads unknown and a paid model is unchanged. OpenRouter's routers (`openrouter/auto` and its kin), which its catalog lists at $0 but which bill the routed model, are never free.
67
+ - OpenRouter runs book what OpenRouter charged; routers need no cap or a read-back cost; a provider's error inside a stream is booked by what it reported.
68
+ - A request on an OpenRouter model is booked at the cost OpenRouter states in the answer's usage (with your own provider key, its fee plus the provider's charge). The price table's figure is kept beside it (`tableUsd`). A cap still holds each request at list price before it leaves. A stated cost that is missing, not a number, or above that hold is not used: the table's figure is booked instead.
69
+ - OpenRouter's routers (`openrouter/auto`, `openrouter/free` and the others) have no price here, because the model they pick is not known in advance. A run with a spend cap is refused before it starts. A run without one is booked at the cost OpenRouter reports, else unknown, never $0.
70
+ - A provider's error inside a successful (200) stream (Anthropic's `overloaded_error`, `api_error` or `rate_limit_error`, OpenRouter's mid-stream errors, a Responses `response.failed`) is booked by one rule. If the stream reported tokens before the error, they are booked at list price, or at the cost OpenRouter stated, and the run's cost stays known: before, such a request was booked at the cap's hold and made the run's cost unknown. If it reported no tokens, it is booked as refused at $0, and the run's record keeps the provider's message (`refusal`, or `providerError` beside a booked figure). That holds only while the model generated nothing: once the stream shows the model began its output (a content block, a Responses output item, hidden reasoning included, or a text-tools model's reply the runner had not sent yet), an error with no usage is booked at an unknown cost, never $0.
71
+ - Kernel: `startModelProxy` books a cost stated in the answer's usage when its origin is OpenRouter's or serve's translation route's (`statesUsageCost`, `ROUTE_ORIGIN`), on every harness: claude-agent, codex and opencode runs on OpenRouter book what OpenRouter charged too. `Ended` gains `tableUsd` on an answer, `{ end: "answered", label: "error", reason }` and `{ end: "nothing", label: "refused", reason }`. `bookRequest` books the table's figure (rule `answered:over_hold`) when a reported figure is above the hold. The claude-agent policy's usage reads a stream that ends in an `error` event as whole. Routers and in-stream errors are handled on those harnesses too.
72
+ - On Claude Code, a tool call that ran beside a call waiting for approval keeps its result. Before, when one answer from the model made two MCP calls, a read that runs on its own and a write that asks, and the run paused on the write, the read's result was lost once the run went on. The model was told the read was interrupted, so it ran the read again.
73
+ - The read had finished and its result was in the run's journal, but Claude Code had not written it to its own transcript before the pause let it go. On the resume, every call left without a result in that transcript whose end the journal holds now gets that recorded result before the CLI starts again. Nothing runs twice and nothing is asked again.
74
+ - A call the pause or a crash cut off before it ended is answered as interrupted, as before. A call the pause held before it started still runs once it is approved.
75
+ - The same rule covers every CLI harness that resumes from its own transcript (Codex, OpenCode). Codex already kept the result in its own transcript.
76
+ - A sandbox run resumed after a server stop, and any run resumed after a park, is now told its computer is new. Before, only a desktop or a phone was told after a server stop, and a parked run's resume never was. The ready line says "It's a new <kind>: the one before is gone, with what was on it." The model's note names no cause, and it reads by kind: a desktop or phone is told to look at the screen again, and a sandbox to check its files. The note and the cap's wrap-up note now start with "AgentRun server note:". The timeline row still reads "AgentRun: …" with the label only once. The run's journal now records each computer a claim makes, and a later claim reads that record. A run that made its computer before this upgrade has no record, so if it resumes after the upgrade on a new computer, it isn't told.
77
+ - An ended run's cost is one figure, read from its booking, and no run reads as ended without it. `GET /runs/{id}`, the runs list and the stored `cost_usd` of an ended run now read the same sum of its booked requests, paid tool calls and decisions (each request counted once), where the view used to read pi's own price for an answer whose booking had not landed yet. A run's end waits for every booking whose write has begun (bounded at 30 s, with a warning when it gives up) before it writes the end, so the final request's booking is never left behind. The end's cost is read apart from its metrics, so metrics that time out no longer drop the cost.
78
+ A model request cut with no answer and no usage (its runner lost mid-request) under a cap is booked at what the cap held for it, the most it can have cost (`runner.turn` `rule: "cut"`, `atMost: true`), so the run's cost stays known instead of turning unknown. A cost that counts one says so: the run's `cost` and the timeline's usage row carry `upper_bound: true`, the usage row reads "Cost: at most $0.97 over 2 model requests", and the console shows "at most $0.97". A cut with no hold (no cap) or a paid tool call that was cut stays unknown, as before: a paid call's `runner.request` now says `paid: true`, so a later process that books it cut never reads its fee as a bound. A hold is never counted as spend: when another charge leaves the total unknown, `so_far_usd` sums the exact charges only and each request booked at its hold counts in `unpriced`, and `upper_bound` is set only on a known figure. The usage row of a CLI or workflow run, and a pi run's with side requests, now carries `upper_bound` and "at most" the same way. The run row stores the bound beside its cost: a new `cost_upper_bound` column (SQLite: added when the server opens a store, and a runner refuses a store until then; Postgres: migration 0014), which `GET /runs/{id}` and the runs list read as `cost.upper_bound`, so the view, the list and the column always agree on the figure, the bound and an unknown. A stored bound is never read as spend: `GET /usage` counts a run whose stored cost is a bound as a run of unknown cost (in `unpriced_runs`, with only its exact charges in `total_usd` and its lines, by every grouping and meter), and the runner's `run_ended` log line says `cost_usd=unknown` with `cost_usd_at_most` beside it. An end whose cost read fails reads it again (three tries within its 30 s bound) before it stores the cost unknown, and `GET /runs/{id}` of an ended run reads the stored cost, so it never shows a figure the list and the column do not. Learning's figures say no "at most", so they read a bounded run's cost as unknown: a look-back's `look_back_usd` and `job_cost_usd`, a learning batch row's `cost_usd` and `total_usd` (a batch stops `cost_unknown` on one, as before), the cost series, the money rule's all-in cost, and an agent's learning impact (`median_cost_usd`, `cost_runs`).
79
+ A cost marked `upper_bound` (the run's `cost` and the timeline's usage row) now also carries `so_far_usd`, what it is known to have spent with no hold in it, and `unpriced`, how many requests it counts at their hold, so every reader that adds more charges to it keeps the hold apart: a workflow's usage row joined with its decisions, its `GET /runs/{id}` cost while it runs, and its graph's `totals.cost_usd` (which says no "at most", so a sum with a hold in it reads null there). A charged $0.01 beside a $0.25 hold and a decision of unknown cost reads "$0.01 known, 2 not priced", no longer "$0.26 known". The over-cap row says "Spent" of the known spend only; a bound past the cap reads "At most $0.26 spent, at most $0.06 over the run's cap". Breaking: `so_far_usd` and `unpriced` are no longer absent whenever `usd` is known; a client that took their presence to mean an unknown cost checks `usd === null` instead.
80
+ A request billed to a ChatGPT plan costs the run $0 however it ended: one cut by a crash or stopped is booked `rule: "cut"` (or its stop's rule) at $0 with `billing: "plan"`, never unknown, so a plan run's cost no longer blanks when a request is cut. Its `runner.request` says `plan: true`. The stored `cost_usd` and the runs list of a plan run now read the known figure the view already showed.
81
+ A workflow run's stored `cost_usd` is read from its booking by the same rule (`GET /runs/{id}` of an ended workflow run reads it too), no longer from its cap's figures. Breaking: a workflow request stopped while it streamed now leaves the cost unknown, as on an agent run, where it used to store the cap's estimate; a decision cut by a crash counts at its hold as an upper bound.
82
+ - A server note (the replaced computer's, the spend cap's wrap-up, the free-model limit's wrap-up) now counts as told only once a request carrying it is answered. Before, it counted as told when the request was admitted, so a request that then failed (an upstream 429, an error status, a lost or cut stream, a runner stopped before the answer) took the note with it, and the harness's retry or the resumed run went out without it: the model never saw it. On a route serve translates (OpenRouter's), a provider's error status counts as a failure too: the model proxy now ends a stream that closes on an error event in words with `label: "error"` and the words as its reason (the session record's `providerError`), booked as before. The failed request gives the note back, the retry carries it, and the timeline row is written once, when the note is answered. One request at a time still carries it.
83
+ - A tool row on a run's timeline carries the call's catalog name (`mcp:notes5/write_note`, `monid:faux/person/enrich`), not the wire name the harness called it by (`mcp__notes5__write_note`). Runs recorded before this show the same names now: the rename is made when the timeline is read.
84
+ - Each harness's facts state their own map from the model's name for a host tool to the host's (`AdapterFacts.hostName`, replacing OpenCode's `toolAlias`), and the tool gate and the meta tools read it instead of stripping prefixes.
85
+ - One conversion turns a host tool into the tool bridge's (`bridgeTool`, from `@parcha/agentrun-kernel/process`); the Claude Agent, Codex and OpenCode adapters each add only what is theirs.
86
+ - A capped run's wrap-up note now comes due on the same input count its request is admitted by. The model proxy counts a request (the provider's count, or the local count for a model whose tokenizer is o200k_base) before it asks for the note, so the note's least, its step-0 figure and the reserve it is checked against are priced on that count, never on the body's bytes. Before, the note was priced on the bytes while admission read the count: a $2 code review on pi with GPT-6.1 Sol through OpenRouter, whose script call was cut at the output ceiling, sent an answer request past 272,000 bytes that was told to "finish now" with $1.56 left (its least read as about $1.45 at the long-context rate, $0.25 on its count), and it answered with no review; a $1 run was told its budget was "enough for little work" on its first request. The noted request is bounded by that count plus the note's own bytes, and a client that goes while its request is counted no longer takes the note.
87
+
5
88
  ## 0.1.0-beta.38 (2026-11-14)
6
89
 
7
90
  - A run's MCP tools are host tools on every harness: each call passes the run's one tool gate before anything is sent, and the runner calls the server with the credential, books the call and records it, as it does any host tool. opencode now runs MCP tools (`features.mcp_client.harnesses` lists it, and an opencode agent granted `mcp:<server>/<tool>` saves and runs). claude-agent offers a granted tool as `mcp__hands__mcp__<server>__<tool>` and codex as `mcp_<server>__<tool>` (Codex refuses a dynamic tool named `mcp__*`); the Timeline, tool settings and approvals still name it `mcp:<server>/<tool>`. A call set to ask on claude-agent, codex or opencode holds the CLI's call while the run waits (no "waits for a person's approval" result row while it is parked); on the person's allow the resumed session gets the call's own result, no `[tool approval]` message. A codex run no longer fails at its start when a granted server can't be reached: the server's error shows at the first call, as on pi. On a code-mode Codex model, a script's tool call held for a person's approval runs once on their allow, under its own call id, and the script's cut-off `exec` reads its result (or, when the `exec` had yielded, the model's `wait` on its cell); before, the resume told the model the call may have run, and the call the model made again asked again, so the allow never reached a call.
package/NOTICE CHANGED
@@ -4,3 +4,5 @@ Copyright 2026 Parcha Labs, Inc.
4
4
  This product includes software from vercel-labs/durable-harness (https://github.com/vercel-labs/durable-harness), Copyright 2026 Vercel Inc., licensed under the Apache License 2.0.
5
5
 
6
6
  The copied files are listed in vendor/durable-harness/UPSTREAM.json. Two kernel files written for AgentRun, src/kernel/types.ts and src/kernel/errors.ts, keep one declaration each identical to that project's harness-world package (EffectRecord's fields and the EffectFailure class), so the copied files compile against them; UPSTREAM.json records them as "interfaces matched".
7
+
8
+ This product includes OpenAI's o200k_base vocabulary from openai/tiktoken (https://github.com/openai/tiktoken), Copyright (c) 2022 OpenAI, Shantanu Jain, and the o200k_base split pattern as spelled for JavaScript by niieani/gpt-tokenizer (https://github.com/niieani/gpt-tokenizer), Copyright (c) 2023-2024 Bazyli Brzoska, both licensed under the MIT License. The vocabulary ships unchanged as vendor/o200k/o200k_base.tiktoken; vendor/o200k/LICENSE records where each came from and holds both licenses.
package/dist/booking.d.ts CHANGED
@@ -4,24 +4,41 @@
4
4
  * under-count: a request counts at what it can have cost, never less.
5
5
  *
6
6
  * A path says how its request ended (`Ended`), and `bookRequest` gives its figure:
7
- * - `answered`: a whole answer, at the cost its usage (or its gateway) says, else the hold;
8
- * - `nothing`: the provider answered a status before any event (not a gateway's timeout), or the request provably never
9
- * left (`isConnectCode`): 0;
7
+ * - `answered`: a whole answer, at the cost its usage (or its gateway) says, else the hold. A figure the provider reported
8
+ * above the hold (the request's worst case at list) is not believed: the table's figure beside it, else the hold. A
9
+ * 200 stream the provider ended in its error event after it reported tokens is one too (`error`): those tokens at list;
10
+ * - `nothing`: the provider answered a status before any event (not a gateway's timeout), the request provably never
11
+ * left (`isConnectCode`), or the provider refused it inside its answer (its error event in a 200 stream, an overload or
12
+ * a rate limit, before it reported any token): 0;
10
13
  * - `lost`: anything that can have been billed and says no cost (a transport error once it left, a cut answer, a
11
14
  * gateway's 504 or 524, an answer after an attempt that was lost, which can have been billed twice, a crash): the hold;
12
15
  * - `stopped`: our abort, its client gone part way: what streamed (its content, and the part of a hidden reasoning
13
16
  * budget that did not stream), priced by the path (`stoppedPrice`), never past the hold.
14
- * With no hold (no cap), a figure no one knows is `null`, as it always was.
17
+ * With no hold (no cap), a figure no one knows is `null`, as it always was. A request on a free model (`free`: its known
18
+ * price is $0 for every token) is 0 however it ended: whatever it was billed for costs nothing.
15
19
  */
16
20
  /** How a request ended, as its path saw it. `label` names the case for the record (`rule`); it changes no figure but
17
- * `answered`'s `filtered` (a content-filter end: its reported usage, else the hold, as any answer). */
21
+ * `answered`'s `filtered` (a content-filter end: its reported usage, else the hold, as any answer). An answer's
22
+ * `tableUsd`: beside a figure the provider reported (`usd`), the price table's for the same usage. A refusal's or an
23
+ * error's `reason`: the provider's own words, the credential cut. */
18
24
  export type Ended = {
19
25
  end: "answered";
20
26
  usd: number | null;
21
27
  label?: "filtered";
28
+ tableUsd?: number | null;
29
+ } | {
30
+ end: "answered";
31
+ usd: number | null;
32
+ label: "error";
33
+ reason?: string;
34
+ tableUsd?: number | null;
22
35
  } | {
23
36
  end: "nothing";
24
37
  label: "status" | "never_left";
38
+ } | {
39
+ end: "nothing";
40
+ label: "refused";
41
+ reason?: string;
25
42
  } | {
26
43
  end: "lost";
27
44
  label: "error_before" | "error_after" | "gateway_timeout" | "retried" | "cut";
@@ -31,10 +48,12 @@ export type Ended = {
31
48
  streamedTokens: number;
32
49
  };
33
50
  /** What a path prices a request with: what its cap held for it, and what it counts at when stopped having streamed
34
- * `tokens` (its input, those tokens and the stop's allowance, at most its output limit, at its price). */
51
+ * `tokens` (its input, those tokens and the stop's allowance, at most its output limit, at its price). `free`: its model's
52
+ * known price is $0 for every token, with no fee beside (runner.ts Admitted.free). */
35
53
  export type Priced = {
36
54
  hold?: number;
37
55
  stoppedPrice?: (streamedTokens: number) => number;
56
+ free?: boolean;
38
57
  };
39
58
  /** A booked request: its figure (null when no one knows it and nothing was held), and the rule that gave it. */
40
59
  export type Booked = {
package/dist/booking.js CHANGED
@@ -4,24 +4,35 @@
4
4
  * under-count: a request counts at what it can have cost, never less.
5
5
  *
6
6
  * A path says how its request ended (`Ended`), and `bookRequest` gives its figure:
7
- * - `answered`: a whole answer, at the cost its usage (or its gateway) says, else the hold;
8
- * - `nothing`: the provider answered a status before any event (not a gateway's timeout), or the request provably never
9
- * left (`isConnectCode`): 0;
7
+ * - `answered`: a whole answer, at the cost its usage (or its gateway) says, else the hold. A figure the provider reported
8
+ * above the hold (the request's worst case at list) is not believed: the table's figure beside it, else the hold. A
9
+ * 200 stream the provider ended in its error event after it reported tokens is one too (`error`): those tokens at list;
10
+ * - `nothing`: the provider answered a status before any event (not a gateway's timeout), the request provably never
11
+ * left (`isConnectCode`), or the provider refused it inside its answer (its error event in a 200 stream, an overload or
12
+ * a rate limit, before it reported any token): 0;
10
13
  * - `lost`: anything that can have been billed and says no cost (a transport error once it left, a cut answer, a
11
14
  * gateway's 504 or 524, an answer after an attempt that was lost, which can have been billed twice, a crash): the hold;
12
15
  * - `stopped`: our abort, its client gone part way: what streamed (its content, and the part of a hidden reasoning
13
16
  * budget that did not stream), priced by the path (`stoppedPrice`), never past the hold.
14
- * With no hold (no cap), a figure no one knows is `null`, as it always was.
17
+ * With no hold (no cap), a figure no one knows is `null`, as it always was. A request on a free model (`free`: its known
18
+ * price is $0 for every token) is 0 however it ended: whatever it was billed for costs nothing.
15
19
  */
16
20
  const figure = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
17
21
  /** The one booking of a request: `ended` priced by `priced`. */
18
22
  export function bookRequest(ended, priced) {
19
23
  const hold = figure(priced.hold);
20
24
  const rule = "label" in ended && ended.label ? `${ended.end}:${ended.label}` : ended.end;
25
+ // Nothing it was billed for costs anything: a known $0, never the hold and never unknown. The rule still says how it ended.
26
+ if (priced.free === true)
27
+ return { usd: 0, rule };
21
28
  switch (ended.end) {
22
29
  case "answered": {
23
30
  // A content filter's end is an answer: its usage when it reported one, else the hold.
24
31
  const usd = figure(ended.usd);
32
+ // A provider's figure above what the cap held for the request (its worst case at list) is not what it can have
33
+ // cost: the table's figure for the same usage stands, else the hold. A table's own figure (no `tableUsd`) is not judged.
34
+ if (usd !== undefined && hold !== undefined && usd > hold && ended.tableUsd !== undefined)
35
+ return { usd: figure(ended.tableUsd) ?? hold, rule: `${rule}:over_hold` };
25
36
  return { usd: usd ?? hold ?? null, rule };
26
37
  }
27
38
  case "nothing":
@@ -1,6 +1,7 @@
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, OPENAI_INPUT_COUNTER, openaiPatchMultiplier, providerInputOverhead, responsesEscapedBytes, responsesImagesIn, responsesInputOverhead, type ImageInput, type InputShape } from "./overhead.js";
2
- export { COUNT_TIMEOUT_MS, countedInputOf, hostHeaderProblems, lastObjectOf, NATIVE_SEARCH_USD, ProxyRefusal, sameKey, startModelProxy } from "./proxy.js";
3
- export type { InputCounter, 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, LOCAL_COUNT_MARGIN, messagesImagesIn, messagesInputAfter, messagesLocalInputTokens, OPENAI_IMAGE_TOKENS_MAX, openaiImageTokens, openaiPatchMultiplier, providerInputOverhead, responsesEscapedBytes, responsesImagesIn, responsesInputOverhead, responsesLocalInputTokens, type BilledRequest, type ImageInput, type InputShape } from "./overhead.js";
2
+ export { O200K_SHA256, O200K_VOCABULARY, o200kModel, o200kTokens } from "./o200k.js";
3
+ export { COUNT_TIMEOUT_MS, countedInputOf, CredentialUnavailable, localInputOf, hostHeaderProblems, lastObjectOf, NATIVE_SEARCH_USD, ProxyRefusal, ROUTE_ORIGIN, sameKey, startModelProxy, statesUsageCost, streamErrorOf, usageCostOf } from "./proxy.js";
4
+ export type { InputCounter, ModelProxy, ModelProxyHooks, ModelProxyOptions, ModelUsageReport, ProviderPolicy, ProxyRequest, ProxyRequestContext, ProxyRoute, ProxyUsage, StreamError } from "./proxy.js";
4
5
  export { processAlive } from "./alive.js";
5
6
  export { serialWriter } from "./serial.js";
6
7
  export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./parent-death.js";
@@ -1,7 +1,8 @@
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, anthropicImageTokens, GEMINI_HIGH_RESOLUTION_TOKENS, geminiImageTokens, imageInputOf, imageProviderOf, imageSizeOf, imageTokens, INPUT_OVERHEAD_APIS, messagesImagesIn, OPENAI_IMAGE_TOKENS_MAX, openaiImageTokens, OPENAI_INPUT_COUNTER, openaiPatchMultiplier, providerInputOverhead, responsesEscapedBytes, responsesImagesIn, responsesInputOverhead } from "./overhead.js";
4
- export { COUNT_TIMEOUT_MS, countedInputOf, hostHeaderProblems, lastObjectOf, NATIVE_SEARCH_USD, 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, LOCAL_COUNT_MARGIN, messagesImagesIn, messagesInputAfter, messagesLocalInputTokens, OPENAI_IMAGE_TOKENS_MAX, openaiImageTokens, openaiPatchMultiplier, providerInputOverhead, responsesEscapedBytes, responsesImagesIn, responsesInputOverhead, responsesLocalInputTokens } from "./overhead.js";
4
+ export { O200K_SHA256, O200K_VOCABULARY, o200kModel, o200kTokens } from "./o200k.js";
5
+ export { COUNT_TIMEOUT_MS, countedInputOf, CredentialUnavailable, localInputOf, hostHeaderProblems, lastObjectOf, NATIVE_SEARCH_USD, ProxyRefusal, ROUTE_ORIGIN, sameKey, startModelProxy, statesUsageCost, streamErrorOf, usageCostOf } from "./proxy.js";
5
6
  export { processAlive } from "./alive.js";
6
7
  export { serialWriter } from "./serial.js";
7
8
  export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./parent-death.js";
@@ -0,0 +1,11 @@
1
+ /** OpenAI's o200k_base vocabulary, as tiktoken loads it: each token's bytes in base64 and its rank, a line each. */
2
+ export declare const O200K_VOCABULARY: URL;
3
+ /** The vocabulary file's sha256, as tiktoken pins it (`expected_hash`). */
4
+ export declare const O200K_SHA256 = "446a9538cb6c348e3516120d7c08b09f57c36495e2acfffe59a5bf8b0cfb1a2d";
5
+ /** Whether `model` (a body's `model`) is one o200k_base counts (`O200K_MODEL`). */
6
+ export declare function o200kModel(model: unknown): boolean;
7
+ /** The split on the engine's own classes. */
8
+ export declare const O200K_SPLIT: RegExp;
9
+ /** The o200k_base tokens of `text`, every special token's spelling counted as the plain text it is (the provider encodes
10
+ * a request's text so: `<|endoftext|>` in a message is text, never a special token). */
11
+ export declare function o200kTokens(text: string): Promise<number>;
@@ -0,0 +1,185 @@
1
+ // o200k_base, the tokenizer OpenAI publishes for its models from gpt-4o on, for counting only. Written for AgentRun, from
2
+ // two MIT-licensed sources whose notices are in vendor/o200k/LICENSE:
3
+ // - the vocabulary is OpenAI's own file, byte for byte (vendor/o200k/o200k_base.tiktoken, `O200K_SHA256`), the one
4
+ // tiktoken loads and pins by that hash (o200k_base in
5
+ // https://github.com/openai/tiktoken/blob/79dc2c0533685b893616c78160b5d9e40876e724/tiktoken_ext/openai_public.py),
6
+ // Copyright (c) 2022 OpenAI, Shantanu Jain;
7
+ // - the split is tiktoken's o200k_base pattern as gpt-tokenizer spells it for JavaScript's regular expressions
8
+ // (O200K_TOKEN_SPLIT_REGEX's native form in
9
+ // https://github.com/niieani/gpt-tokenizer/blob/785c2695acbda31ae31ef8ab6343bcd7f1dde72f/src/encodingParams/constants.ts),
10
+ // Copyright (c) 2023-2024 Bazyli Brzoska: `(?i:'s|...)` as a character class per letter, `ſ` among them, and `\s` as
11
+ // Unicode's White_Space, which tiktoken's regex reads and JavaScript's `\s` does not (U+0085, U+FEFF).
12
+ // Each piece the split finds is one token when the vocabulary holds its bytes, else its bytes are merged by tiktoken's
13
+ // byte-pair rule: the adjacent pair of lowest rank first, the leftmost on a tie, until no pair is in the vocabulary
14
+ // (taken off a min-heap, as gpt-tokenizer does, so a long piece is never rescanned after each merge). The count is the
15
+ // pieces' tokens. It counts what gpt-tokenizer 4.1.2's o200k_base `countTokens` counted with no special token allowed,
16
+ // which this replaces: that package is 31 MB of encodings, chat formats and price tables, and only this was used.
17
+ // tiktoken's letter and number classes are Unicode 16's. Node 24 knows Unicode 17, which made letters and numbers of some
18
+ // characters that were neither: on a text that holds one, the split takes them out of the engine's classes again, as
19
+ // gpt-tokenizer does (its UNICODE_17_TO_16 ranges), so the count is Unicode 16's; any other text takes the plain classes,
20
+ // which are faster. An engine of another Unicode takes its own classes: a character it classes otherwise moves a split
21
+ // around it, by a token or so, which the local count's margin covers.
22
+ import { readFile } from "node:fs/promises";
23
+ /** OpenAI's o200k_base vocabulary, as tiktoken loads it: each token's bytes in base64 and its rank, a line each. */
24
+ export const O200K_VOCABULARY = new URL("../../vendor/o200k/o200k_base.tiktoken", import.meta.url);
25
+ /** The vocabulary file's sha256, as tiktoken pins it (`expected_hash`). */
26
+ export const O200K_SHA256 = "446a9538cb6c348e3516120d7c08b09f57c36495e2acfffe59a5bf8b0cfb1a2d";
27
+ /** Model ids, as a session or a gateway names them (`openai/gpt-6.1-sol`), whose tokenizer is o200k_base: gpt-4o, gpt-4.1,
28
+ * gpt-4.5, gpt-5 and later, chatgpt-4o, the o-series, codex- and gpt-oss models. gpt-3.5 and gpt-4 (cl100k_base) are
29
+ * not, nor any other vendor's model: o200k_base can undercount them. */
30
+ const O200K_MODEL = /^(?:openai\/)?(?:gpt-(?:4o|4\.1|4\.5|[5-9]|[1-9]\d)|chatgpt-4o|o[1-9](?:-|$)|codex-|gpt-oss-)/i;
31
+ /** Whether `model` (a body's `model`) is one o200k_base counts (`O200K_MODEL`). */
32
+ export function o200kModel(model) {
33
+ return typeof model === "string" && O200K_MODEL.test(model);
34
+ }
35
+ const CONTRACTION = String.raw `(?:'(?:[sSſ]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE]))?`;
36
+ /** tiktoken's o200k_base split, in JavaScript's spelling, over the classes given (each the inside of a character class). */
37
+ const splitOf = (letter, number, upper, lower, flags) => new RegExp([
38
+ String.raw `[^\r\n${letter}${number}]?[${upper}]*[${lower}]+${CONTRACTION}`,
39
+ String.raw `[^\r\n${letter}${number}]?[${upper}]+[${lower}]*${CONTRACTION}`,
40
+ String.raw `[${number}]{1,3}`,
41
+ String.raw ` ?[^\p{White_Space}${letter}${number}]+[\r\n\/]*`,
42
+ String.raw `\p{White_Space}*[\r\n]+`,
43
+ String.raw `\p{White_Space}+(?!\P{White_Space})`,
44
+ String.raw `\p{White_Space}+`,
45
+ ].join("|"), flags);
46
+ const NATIVE = { letter: String.raw `\p{L}`, number: String.raw `\p{N}`, upper: String.raw `\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}`, lower: String.raw `\p{Ll}\p{Lm}\p{Lo}\p{M}` };
47
+ /** The split on the engine's own classes. */
48
+ export const O200K_SPLIT = splitOf(NATIVE.letter, NATIVE.number, NATIVE.upper, NATIVE.lower, "gu");
49
+ /** What Unicode 17 added to each class that Unicode 16 did not have in it (gpt-tokenizer's UNICODE_17_TO_16_*_EXCLUDE
50
+ * ranges; nothing left them), and the UTF-16 units that start any of those characters. */
51
+ const ADDED_IN_17 = {
52
+ letter: String.raw `࢏౜೜꟎-꟏꟒꟔꟱\u{10940}-\u{10959}\u{10EC5}-\u{10EC7}\u{11DB0}-\u{11DDB}\u{16EA0}-\u{16EB8}\u{16EBB}-\u{16ED3}\u{16FF2}-\u{16FF3}\u{187F8}-\u{187FF}\u{18D09}-\u{18D1E}\u{18D80}-\u{18DF2}\u{1E6C0}-\u{1E6DE}\u{1E6E0}-\u{1E6E2}\u{1E6E4}-\u{1E6E5}\u{1E6E7}-\u{1E6ED}\u{1E6F0}-\u{1E6F4}\u{1E6FE}-\u{1E6FF}\u{2B73A}-\u{2B73F}\u{2CEA2}-\u{2CEAD}\u{323B0}-\u{33479}`,
53
+ number: String.raw `\u{11DE0}-\u{11DE9}\u{16FF4}-\u{16FF6}`,
54
+ upper: String.raw `ʕ࢏౜೜᫏-᫝᫠-᫫꟎꟒꟔꟱\u{10940}-\u{10959}\u{10EC5}-\u{10EC7}\u{10EFA}-\u{10EFB}\u{11B60}-\u{11B67}\u{11DB0}-\u{11DDB}\u{16EA0}-\u{16EB8}\u{16FF2}-\u{16FF3}\u{187F8}-\u{187FF}\u{18D09}-\u{18D1E}\u{18D80}-\u{18DF2}\u{1E6C0}-\u{1E6DE}\u{1E6E0}-\u{1E6F5}\u{1E6FE}-\u{1E6FF}\u{2B73A}-\u{2B73F}\u{2CEA2}-\u{2CEAD}\u{323B0}-\u{33479}`,
55
+ lower: String.raw `࢏౜೜᫏-᫝᫠-᫫꟏꟱\u{10940}-\u{10959}\u{10EC5}-\u{10EC7}\u{10EFA}-\u{10EFB}\u{11B60}-\u{11B67}\u{11DB0}-\u{11DDB}\u{16EBB}-\u{16ED3}\u{16FF2}-\u{16FF3}\u{187F8}-\u{187FF}\u{18D09}-\u{18D1E}\u{18D80}-\u{18DF2}\u{1E6C0}-\u{1E6DE}\u{1E6E0}-\u{1E6F5}\u{1E6FE}-\u{1E6FF}\u{2B73A}-\u{2B73F}\u{2CEA2}-\u{2CEAD}\u{323B0}-\u{33479}`,
56
+ units: String.raw `ʕ࢏౜೜᫏-᫝᫠-᫫꟎-꟏꟒꟔꟱\uD802-\uD803\uD806-\uD807\uD81B\uD821\uD823\uD839\uD86D\uD873\uD888-\uD88D`,
57
+ };
58
+ /** On a Unicode 17 engine: the split on Unicode 16's classes, and the test for a text that needs it (one holding a unit
59
+ * that may start a character Unicode 17 added to a class; a false alarm only costs the slower pattern). */
60
+ const UNICODE_16 = process.versions.unicode === "17.0" ? {
61
+ split: splitOf(...["letter", "number", "upper", "lower"].map((k) => `[[${NATIVE[k]}]--[${ADDED_IN_17[k]}]]`), "gv"),
62
+ needed: new RegExp(`[${ADDED_IN_17.units}]`),
63
+ } : undefined;
64
+ let loaded;
65
+ /** The vocabulary, read the first time a text is counted (a session that never counts never reads it). */
66
+ const ranks = () => (loaded ??= readFile(O200K_VOCABULARY, "latin1").then((text) => {
67
+ const out = new Map();
68
+ for (const line of text.split("\n")) {
69
+ const space = line.indexOf(" ");
70
+ if (space > 0)
71
+ out.set(Buffer.from(line.slice(0, space), "base64").toString("latin1"), Number(line.slice(space + 1)));
72
+ }
73
+ return out;
74
+ }));
75
+ /** The tokens of each piece counted, by its text: bounded, and emptied when full. */
76
+ const counted = new Map();
77
+ const COUNTED_MAX = 100_000;
78
+ /** The o200k_base tokens of `text`, every special token's spelling counted as the plain text it is (the provider encodes
79
+ * a request's text so: `<|endoftext|>` in a message is text, never a special token). */
80
+ export async function o200kTokens(text) {
81
+ const vocabulary = await ranks();
82
+ let tokens = 0;
83
+ const split = UNICODE_16 && UNICODE_16.needed.test(text) ? UNICODE_16.split : O200K_SPLIT;
84
+ for (const [piece] of text.matchAll(split)) {
85
+ let n = counted.get(piece);
86
+ if (n === undefined) {
87
+ n = pieceTokens(vocabulary, Buffer.from(piece, "utf8").toString("latin1"));
88
+ if (counted.size >= COUNTED_MAX)
89
+ counted.clear();
90
+ counted.set(piece, n);
91
+ }
92
+ tokens += n;
93
+ }
94
+ return tokens;
95
+ }
96
+ /** The tokens one piece's bytes (`bytes`, a char a byte) merge to: one when the vocabulary holds them, else the parts
97
+ * the byte-pair rule leaves. Every single byte is a token of o200k_base. */
98
+ function pieceTokens(vocabulary, bytes) {
99
+ const length = bytes.length;
100
+ if (length === 0)
101
+ return 0;
102
+ if (length === 1 || vocabulary.has(bytes))
103
+ return 1;
104
+ // The parts are a linked list over byte offsets: a live part at `i` spans [i, next[i]). `rank[i]` is the rank of the part
105
+ // at `i` merged with the one after it (Infinity when that is no token).
106
+ const next = new Int32Array(length + 1);
107
+ const previous = new Int32Array(length + 1);
108
+ const rank = new Float64Array(length + 1);
109
+ const live = new Uint8Array(length + 1);
110
+ const pairRank = (i) => {
111
+ const middle = next[i];
112
+ return middle >= length ? Infinity : (vocabulary.get(bytes.slice(i, next[middle])) ?? Infinity);
113
+ };
114
+ // A min-heap of [rank, offset] pairs, packed flat, ordered by rank and then offset: the leftmost of the lowest first.
115
+ const heap = [];
116
+ const lower = (a, b) => heap[a] < heap[b] || (heap[a] === heap[b] && heap[a + 1] < heap[b + 1]);
117
+ const swap = (a, b) => {
118
+ const r = heap[a], at = heap[a + 1];
119
+ heap[a] = heap[b];
120
+ heap[a + 1] = heap[b + 1];
121
+ heap[b] = r;
122
+ heap[b + 1] = at;
123
+ };
124
+ const push = (r, at) => {
125
+ heap.push(r, at);
126
+ for (let i = heap.length - 2; i > 0;) {
127
+ const parent = (((i >> 1) - 1) >> 1) << 1;
128
+ if (!lower(i, parent))
129
+ break;
130
+ swap(i, parent);
131
+ i = parent;
132
+ }
133
+ };
134
+ const pop = () => {
135
+ const last = heap.length - 2;
136
+ swap(0, last);
137
+ const top = [heap[last], heap[last + 1]];
138
+ heap.length = last;
139
+ for (let i = 0;;) {
140
+ const left = i * 2 + 2, right = left + 2;
141
+ let least = i;
142
+ if (left < heap.length && lower(left, least))
143
+ least = left;
144
+ if (right < heap.length && lower(right, least))
145
+ least = right;
146
+ if (least === i)
147
+ break;
148
+ swap(i, least);
149
+ i = least;
150
+ }
151
+ return top;
152
+ };
153
+ for (let i = 0; i <= length; i++) {
154
+ next[i] = i + 1;
155
+ previous[i] = i - 1;
156
+ live[i] = 1;
157
+ }
158
+ for (let i = 0; i < length - 1; i++) {
159
+ rank[i] = pairRank(i);
160
+ if (rank[i] !== Infinity)
161
+ push(rank[i], i);
162
+ }
163
+ let parts = length;
164
+ while (heap.length > 0) {
165
+ const [r, at] = pop();
166
+ // An entry an earlier merge made stale: its part is gone, or its pair is another now.
167
+ if (!live[at] || rank[at] !== r)
168
+ continue;
169
+ const merged = next[at];
170
+ live[merged] = 0;
171
+ next[at] = next[merged];
172
+ previous[next[merged]] = at;
173
+ parts--;
174
+ rank[at] = pairRank(at);
175
+ if (rank[at] !== Infinity)
176
+ push(rank[at], at);
177
+ const before = previous[at];
178
+ if (before >= 0) {
179
+ rank[before] = pairRank(before);
180
+ if (rank[before] !== Infinity)
181
+ push(rank[before], before);
182
+ }
183
+ }
184
+ return parts;
185
+ }
@@ -1,4 +1,3 @@
1
- import type { InputCounter } from "./proxy.js";
2
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
3
2
  * provider fetches by URL), which are counted at the image's billed size instead, and its pixel size when its data's own
4
3
  * header says it (PNG, JPEG, GIF, WebP). */
@@ -116,9 +115,9 @@ export declare function imageSizeOf(data: string): {
116
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
117
116
  * anywhere else (a tool call's arguments) is text to the provider: its bytes stay counted as they are. */
118
117
  export declare function messagesImagesIn(messages: unknown): ImageInput[];
119
- /** A Responses body's images, only where the API reads one as an image: an `input_image` item, a part of an item's
120
- * 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
121
- * bytes). An image-shaped object anywhere else is text to the provider: its bytes stay counted as they are. */
118
+ /** A Responses body's images, only where the API reads one as an image (`responsesImageParts`), in every turn. Each is a
119
+ * data URL's, or a URL's or file id's (no bytes). An image-shaped object anywhere else is text to the provider: its
120
+ * bytes stay counted as they are. */
122
121
  export declare function responsesImagesIn(input: unknown): ImageInput[];
123
122
  /**
124
123
  * The bytes JSON's escapes add to the text a Responses body carries for the model to read as it is, beyond that text's
@@ -152,15 +151,76 @@ export declare function responsesEscapedBytes(body: Record<string, unknown>): nu
152
151
  */
153
152
  export declare function responsesInputOverhead(body: Record<string, unknown>): number;
154
153
  /**
155
- * OpenAI's own count of a Responses request's input tokens: POST /v1/responses/input_tokens on api.openai.com only, which
156
- * "accepts the same input format as the Responses API" and answers `{object: "response.input_tokens", input_tokens}`,
157
- * "the exact count the model will receive", formatting tokens, tools and images included ("Counting tokens",
158
- * https://developers.openai.com/api/docs/guides/token-counting; the SDK's `responses.inputTokens.count`,
159
- * https://github.com/openai/openai-node/blob/543ed94e6451d2eaf43f1a4a16a0fc8c8f42eade/src/resources/responses/input-tokens.ts).
160
- * The model proxy asks it before each answer request on that origin (never through a gateway), as Anthropic's count is
161
- * asked (ProviderPolicy.countInput): a count that fails, times out, or answers anything else leaves the byte bound.
154
+ * The margin a local count adds, and why each part:
155
+ * - `share`, 10% of the counted tokens: the count is o200k_base's, the vocabulary tiktoken names for gpt-4o, gpt-4.1,
156
+ * gpt-4.5, gpt-5, the o-series and gpt-oss (MODEL_PREFIX_TO_ENCODING,
157
+ * https://github.com/openai/tiktoken/blob/79dc2c0533685b893616c78160b5d9e40876e724/tiktoken/model.py#L7-L37). A later
158
+ * model that bills by a revised vocabulary may split some text finer; a tenth more covers a revision of that order.
159
+ * - `perItem`, 16 tokens for each input item (and each part of a tool's result), each tool and the instructions: the framing the provider renders around
160
+ * each (harmony's `<|start|>assistant<|channel|>commentary to=functions.read <|constrain|>json<|message|>`, some 12
161
+ * tokens, https://github.com/openai/harmony/blob/e0ce87d1c3b9f59dec2e27de4770c769f03ebbd3/docs/format.md), beside
162
+ * the cookbook's 3 a message (num_tokens_from_messages,
163
+ * https://github.com/openai/openai-cookbook/blob/db3144982aa26b87a9bdfb692b4fbedfdf8a14d5/examples/How_to_count_tokens_with_tiktoken.ipynb).
164
+ * - `perRequest`, 256 tokens: the system message the provider writes itself (harmony's identity, dates, reasoning level
165
+ * and channels, some 60 tokens), the tools' namespace header and the reply's priming.
166
+ * The count is of the body as sent, its JSON keys, ids, quotes and escapes included, which the provider bills none of as
167
+ * text: that slack is on top of the margin. What the tokenizer cannot see is counted as the byte bound counts it: an
168
+ * encrypted reasoning or compaction item's `encrypted_content` at its bytes (its plaintext is billed, and a byte bounds a
169
+ * token), and each image at the most its provider bills it as (`imageTokens`), never at its base64.
162
170
  */
163
- export declare const OPENAI_INPUT_COUNTER: InputCounter;
171
+ export declare const LOCAL_COUNT_MARGIN: Readonly<{
172
+ share: 0.1;
173
+ perItem: 16;
174
+ perRequest: 256;
175
+ }>;
176
+ /**
177
+ * The local count of a Responses `body`'s input tokens, margin included (`LOCAL_COUNT_MARGIN`): its JSON as sent, counted
178
+ * with o200k_base, with each `encrypted_content` at its bytes and each image at what it is billed as in place of their
179
+ * text. Undefined (the body keeps its byte bound) for a model whose tokenizer is not o200k_base (`o200kModel`), for a body
180
+ * with a file input (billed by its pages, with no stated bound), and for a body that is not an object.
181
+ */
182
+ export declare function responsesLocalInputTokens(body: Record<string, unknown>): Promise<number | undefined>;
183
+ /**
184
+ * The local count of a Messages `body`'s input tokens, margin included (`LOCAL_COUNT_MARGIN`), by the same rule as a
185
+ * Responses body's (`responsesLocalInputTokens`), for a Messages request to a model whose tokenizer is o200k_base: one
186
+ * serve's translation sends on to a provider of another API (pi's session on `openai/gpt-6.1-sol` through OpenRouter,
187
+ * whose chat completions carry the same text). Its JSON as sent, counted with o200k_base, with a thinking block's
188
+ * `signature` and a redacted one's `data` at their bytes and each image at what it is billed as on the routed model, in
189
+ * place of their text. An item is each message's block and each block inside a tool_result (one for a message with
190
+ * none), each tool and each system block: the provider frames each turn, call, result and part of a result it renders.
191
+ * Undefined (the body keeps its byte bound) for a model whose tokenizer is not o200k_base (every Claude model: Anthropic
192
+ * counts those itself, or the byte bound holds), for a body with a document (billed by its pages, with no stated bound),
193
+ * and for a body that is not an object.
194
+ */
195
+ export declare function messagesLocalInputTokens(body: Record<string, unknown>): Promise<number | undefined>;
196
+ /** An earlier request of a session and the input tokens its provider billed for it (input, cache reads and cache writes
197
+ * together), as its answer reported them. */
198
+ export interface BilledRequest {
199
+ readonly body: Record<string, unknown>;
200
+ readonly inputTokens: number;
201
+ }
202
+ /**
203
+ * The most input tokens a Messages `body` can be billed for, from an earlier request of its session that the provider
204
+ * billed (`earlier`): that request's billed input, plus the bytes of the messages `body` carries after the ones the two
205
+ * share, each image among them at the most it is billed as in place of its data's bytes. Undefined (no figure: the body
206
+ * keeps its other bounds) when the two differ in anything but their messages and the fields that bill no input
207
+ * (`max_tokens`, `stream`, `metadata`), when the earlier request's figure is not a count, or when the messages it adds
208
+ * hold a document (billed by its pages, with no stated bound).
209
+ *
210
+ * Why it never undercounts: the provider renders a request as its system prompt and tools, then each message in turn,
211
+ * each between its own role markers, and bills each message's tokens whatever follows it. So the two requests' system
212
+ * prompt, tools (the tool-use prompt with them) and shared messages bill alike, and the earlier request was billed for all
213
+ * of them, and for any message of its own the later one dropped, which only adds to the figure. What the later request
214
+ * adds is bounded as the byte bound bounds any body (`inputTokensMaxOf`): a byte-level BPE token covers at least one
215
+ * byte, and the JSON keys each message spends cover its role markers. Two bodies are compared as the model reads them:
216
+ * a cache marker, where the API reads one (`readOf`), bills nothing, and a message's string content is the one text block the API reads it as (the Claude
217
+ * CLI sends its environment message as a block in one request and a string in the next). A thinking block the API leaves
218
+ * out of a later request's context (an earlier turn's) only makes the later request cheaper.
219
+ *
220
+ * It needs no tokenizer, so it bounds a Claude model through a gateway (OpenRouter), which counts nothing and whose
221
+ * tokenizer is not o200k_base: the CLI's second request, read at its bytes, is four times what it bills.
222
+ */
223
+ export declare function messagesInputAfter(earlier: BilledRequest, body: Record<string, unknown>): number | undefined;
164
224
  /** The image a body's `data` (base64, or a data URL) carries: the bytes it takes, and its size when its header says it.
165
225
  * Anything else (an http URL, a file id): no bytes, no size. */
166
226
  export declare function imageInputOf(data: unknown): ImageInput;