@parcha/agentrun-kernel 0.1.0-beta.37 → 0.1.0-beta.39

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 (70) hide show
  1. package/CHANGELOG.md +136 -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 -5
  6. package/dist/host/index.js +3 -3
  7. package/dist/host/o200k.d.ts +11 -0
  8. package/dist/host/o200k.js +185 -0
  9. package/dist/host/overhead.d.ts +105 -3
  10. package/dist/host/overhead.js +276 -20
  11. package/dist/host/proxy.d.ts +97 -16
  12. package/dist/host/proxy.js +420 -108
  13. package/dist/index.d.ts +6 -5
  14. package/dist/index.js +4 -3
  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 +7 -6
  20. package/dist/kernel/cap/index.js +6 -5
  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 +11 -5
  25. package/dist/kernel/cap/port.js +26 -24
  26. package/dist/kernel/cap/price.d.ts +10 -30
  27. package/dist/kernel/cap/price.js +15 -48
  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 +11 -17
  31. package/dist/kernel/cap/rule.js +37 -19
  32. package/dist/kernel/cap/run-cap.d.ts +25 -10
  33. package/dist/kernel/cap/run-cap.js +78 -35
  34. package/dist/kernel/cap/types.d.ts +11 -27
  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 +18 -27
  41. package/dist/kernel/registry/computer.d.ts +14 -7
  42. package/dist/kernel/registry/computer.js +64 -16
  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 +4 -5
  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/kernel/types.d.ts +8 -1
  50. package/dist/process/recovery.d.ts +4 -1
  51. package/dist/process/recovery.js +15 -3
  52. package/dist/process/resume.d.ts +5 -2
  53. package/dist/process/resume.js +15 -3
  54. package/dist/process/tools.d.ts +28 -1
  55. package/dist/process/tools.js +102 -5
  56. package/dist/run-booking.d.ts +21 -2
  57. package/dist/run-booking.js +215 -18
  58. package/dist/runner.d.ts +82 -21
  59. package/dist/runner.js +271 -56
  60. package/dist/testing.d.ts +10 -4
  61. package/dist/testing.js +7 -5
  62. package/dist/tool-deferral.d.ts +12 -0
  63. package/dist/tool-deferral.js +17 -0
  64. package/dist/types.d.ts +133 -48
  65. package/dist/types.js +8 -0
  66. package/package.json +5 -3
  67. package/vendor/o200k/LICENSE +61 -0
  68. package/vendor/o200k/o200k_base.tiktoken +199998 -0
  69. package/dist/host/mcp-route.d.ts +0 -14
  70. package/dist/host/mcp-route.js +0 -125
package/CHANGELOG.md CHANGED
@@ -2,6 +2,142 @@
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
+
88
+ ## 0.1.0-beta.38 (2026-11-14)
89
+
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.
91
+
92
+ Who breaks: a run parked on an MCP call at the MCP door before this version does not resume its call: cancel it and start it again. A Codex thread started before this version loses its MCP tools when it resumes (Codex resumes a thread with the dynamic tools it started with): start a new run. Code built on the kernel's MCP door breaks too. Removed: `SessionSpec.mcp`, `SessionMcp`, `McpClient`, `AdapterCapabilities` and `AgentAdapter.capabilities()`, `AdapterFacts.mcp`, `ModelProxyOptions.mcp`, `mcpRoute`, `McpHandler` and `McpRouteOptions` (`@parcha/agentrun-kernel/host`), and `McpCallResult.parked`. Hand a session its MCP tools as host tools in `SessionSpec.tools` instead.
93
+ - A provider-native web search's fee is one constant, `NATIVE_SEARCH_USD` ($0.01, $10 per 1,000), instead of three copies. The price does not change.
94
+ - Kernel: `@parcha/agentrun-kernel/host` exports `NATIVE_SEARCH_USD`. The Claude and Codex proxy policies and the runner's hosted search all read it.
95
+ - `@parcha/agentrun-harness-claude` no longer exports `CLAUDE_WEB_SEARCH_USD`; read `NATIVE_SEARCH_USD` from `@parcha/agentrun-kernel/host`.
96
+ - An agent can open an app on a Linux desktop. Before, every app an agent started there closed right away, so a person watching the Screen tab on E2B or Agent37 saw a black desktop for the whole run. `computer.shell.run` passes no `DISPLAY`, and its command's guard ends everything the command started, `setsid` and `&` included. Two changes fix this:
97
+ - `computer.processes.start(command, { cwd, env })` (on a computer with the processes group) starts a program that keeps running after the call. That program, and any app a launcher forks, runs until it exits or the computer ends. It answers `{ pid }`. In a run it is held to bash's setting, as `bash_background` is, so a read-only bash policy refuses it.
98
+ - On a desktop whose hello names a display, the surface adds `DISPLAY` to the env of `shell.run` and `processes.start`, under the call's own variables. An app opens where the screen is, and a tool such as `xdotool` finds it.
99
+ - The desktop-computer skill's Linux section says how to open an app.
100
+ - One discovery system. A run lists every tool until its catalog tools (MCP and monid) pass 20; then they are deferred, found with `tools_search` and run with `tools_call`. Under 20 there is no search or call, and Claude Code's own tool search follows the same threshold and gets neither of ours. `codemode`, `tools_search` and `tools_call` each have a tool-settings key (allow by default); a tool set to deny is not offered at all.
101
+ - Every harness (pi, Claude Code, OpenCode and Codex) now offers three host tools over the run's own tools: `tools_search`, `tools_call` and `codemode`. Codex gets the first two and keeps its own code mode. With MCP servers on a Claude Code run, the CLI's own tool search is on.
102
+ - `tools_search {query, limit?}` ranks the run's tools by what they do (BM25 over each tool's description and argument words) and answers each match's name, description and input schema. It lists only tools the run may call: never one set to deny, and never the three tools themselves.
103
+ - `tools_call {name, args}` calls one of the run's tools by name. The call is asked about, recorded and booked as that tool's own call, under `<callId>/call`. An ask parks the run, and once approved the call runs once. A deny refuses it in the gate's words. A call of an unknown name, of `tools_call` itself, of `tools_search` or of `codemode` is refused in words, and nothing runs.
104
+ - `codemode {script}` runs a JavaScript script in a QuickJS sandbox. Its `await tools.<name>(args)` calls are each the run's own call, gated, recorded and booked under `<callId>/s<n>`. The sandbox has the tools and nothing else of the run: no environment, keys, files, network or timers.
105
+ - A call inside a script that needs approval follows Codex's rule. The run parks. Once a person answers, the script runs again: recorded calls answer from their records, the parked call runs once (or is refused), its outcome is the script's answer, and the rest of the script does not run.
106
+ - A call made through `tools_call` or a script answers what a direct call answers: its text and images to the model, and in a script its value (a tool's structured result, else its text). On pi the harness's own tools (an extension's, the browser's) are found and called the same way as the host's.
107
+ - A refused call inside a script ends the script with the refusal's words.
108
+ - After a crash, a call that was cut off is told as possibly done, and it is not run again.
109
+ - A paid call made through `tools_call` or a script books exactly as a direct call does: held before it is sent, under the cap, and settled once. The cap's wrap-up still refuses the model's own next call.
110
+ - The three tools' definitions ride on every model request: about 2,000 bytes, 639 tokens on Sonnet. So the smallest caps the README measures rise. A pi desktop run on Sonnet through a gateway now needs $0.07 for its first request and $0.13 for five steps in `strict` mode, or $0.07 in `expected` mode (it was $0.06, $0.12 and $0.06). Straight to Anthropic, it needs $0.04 for its first request, and five steps still need $0.09 in `strict` mode and $0.06 in `expected` mode.
111
+ - Claude Code: with an MCP server's tools on the run, the CLI runs with `ENABLE_TOOL_SEARCH=true` and its ToolSearch. The run's MCP tools reach the model through `hands` only once ToolSearch finds them, and every other tool of the session loads as before. The session's proxy admits the tool search's beta (`advanced-tool-use-2025-11-20`), ToolSearch and its placeholder. It also admits a `tool_reference` block, inside a tool result only, that names one of the session's own tools. Without MCP tools, all of these stay refused.
112
+ - A server started by `agentrun-serve` (and so by `npx agentrun`) can start a worker thread from a file. The launcher no longer passes Node `--input-type`, which a worker inherits and Node refuses. Before this, a `codemode` script there failed with "--input-type can only be used with string input via --eval, --print, or STDIN", and so did pi's code mode on a desktop or a phone.
113
+ - A capped run no longer prices a request as if nothing were cached after an approval, a deny, a raise or a smaller request of its own, and a Codex or Claude Code run no longer has a tool call refused with "Budget nearly spent" while the request that asked for it is still streaming and the cap has room for both.
114
+ - The recent requests: the cap keeps the session's answered requests of the last 4 minutes and prices each request from the one on its model with the biggest body no bigger than its own. A smaller request between two of the conversation's own (Codex sends one while a tool runs; a summary, a child's) no longer resets the history, so the conversation's next request stays warm. Before, a $0.50 Codex run's next request after one was priced all fresh, held all that was left, and was told "About $0.43 left of this run's budget: finish now" on a $0.08 job.
115
+ - Resume: the recent requests are kept with the run, so the first request after a new claim is priced from them, warm when they ended under 4 minutes ago and uncached after that, the same rule as inside one claim, on every harness. Before, a $0.15 Codex run paused after a deny with "needs at least $0.22": its next request was priced all fresh.
116
+ - In flight: a CLI harness's request is now sent with the most output whose worst case still leaves the run's wrap-up reserve (one typical step and one least answer) free, so a call it makes mid-response finds room. A $0.50 Codex request that held $0.36 and a $0.12 bound at its whole 32,000-token ask is now sent with fewer tokens, and its call passes. When the request's least and the reserve do not both fit, it is admitted as before, with the most what is left buys, and a call it makes is refused for the reserve as before. pi starts a tool only once its response is complete, so its requests are sized as before.
117
+ - The cap's guarantees are unchanged: no request is held past what is left, a warm price that guesses wrong costs at most the request's bound beyond its hold (as any cache miss under `expected`), every hold settles to what the request cost, and turns sum to the run's cost.
118
+ - Kernel cap (private, not in the package's index): `ModelCapRequest.previous` is `recent` (a list of `RecentRequest`, was `Previous`), `previousOf` on `beforeRequestOf` and `runCap` is `recentOf`, and `previousAfter` is `recentAfter`, with `warmFrom` picking the request a price reads. `JudgeState.keepUsd`, and `keepBackUsd` on `beforeRequestOf` and `runCap`, tell the rule what the host keeps back beside a request.
119
+ - A desktop with no ui group (E2B's, Agent37's) can be driven by the tools alone, and its first screen no longer reads as broken.
120
+ - `computer_observe` and `computer_act` with `app` open that app, or bring it in front, before the screenshot or the input (apps.launch, as a script's `computer.apps.open` does). A screenshot with no app in front lists the app ids to name. Before, a tools-only agent had no way to open an app there. Such an observe counts as an app opening. While the person holds the desktop it waits, then is not done. After a crash it is not run again.
121
+ - The desktop's background is one slate colour (xsetroot, run before xfwm4), not black. Agent37's desktop recipe (`box/build-agent37.mjs`) adds x11-xserver-utils for it; rebuild `agentrun-box` once.
122
+ - `computer_act` offers no `expect` on a desktop with no ui group, which can't check one: its schema there has none, so a model is no longer offered a wait that is then refused.
123
+ - `GET /v2/runs/{run_id}/computer` on an ended run says `session: "closed"` for its desktop or phone, and for a browser step the run ended under, not `opening`.
124
+ - A provider's label takes its article: "an E2B sandbox", not "a E2B sandbox".
125
+ - A capped Codex, OpenCode or pi (on OpenAI's Responses) run's next-step estimate is closer to its real input, so it pauses for a raise later and less often: the input bound counts the text the model reads (a tool's output, a message, a call's arguments) at its own bytes instead of its JSON-escaped ones, some 4 to 6% less on a code-mode body full of fetched pages, which keeps more requests under the 272k-token long-context tier where every rate doubles. On a route straight to OpenAI the input is counted exactly by OpenAI's `POST /v1/responses/input_tokens`, asked with only the credential and account headers and never through a gateway; a count that fails or takes over 3 seconds leaves the byte bound. The cap still never spends past itself: tool definitions and encrypted reasoning keep every byte.
126
+ - Three follow-ups to the tools_search / tools_call / codemode rule, found in a live walk.
127
+ - Claude Code now follows the same switch as every other harness. With `tools_search` or `tools_call` set to deny, its own tool search is off and every tool is listed; before, it deferred a run's catalog tools behind its own ToolSearch whatever the setting said. The server makes the one decision (`SessionSpec.deferCatalog`) and Claude Code's adapter obeys it.
128
+ - Settings → Tools lists `tools_search`, `tools_call` and `codemode`, each allow or deny, allow by default. They are in `capabilities.tools` with `meta: true` (no grant: the agent editor does not offer them) and a one-line blurb.
129
+ - codemode's description names real functions of the run (`tools.<name>`, the first three) and says to leave off the prefix a harness shows in the model's own tool list (`hands_`, `mcp__hands__`). On OpenCode a script wrote `tools.hands_mcp__hn__…` five times in five runs and failed.
130
+ - A capped run on a CLI harness (Codex, Claude Code) prices its next request from the cache its previous request left warm, at admission, for the wrap-up note and for the room it keeps back to answer, so it is no longer told to finish, or refused a tool call, while what is left still buys many of its steps.
131
+ - Before, a CLI's request names its model as its provider does (`openai/gpt-6.1-sol`, `claude-sonnet-5-5`) while the cap prices it under the run's model id (`gpt-6.1-sol`, `anthropic/claude-sonnet-5.5`). The session's previous request was filed under the first and looked up under the second, so every request was priced as if nothing were cached. The note and the reserve never read the previous request at all, on any harness.
132
+ - Example: a Codex run under $0.50 was told to finish with $0.45 left, because its next request was priced at $0.23 all fresh; read from the cache, it needed about $0.05.
133
+ - Admission's rule is unchanged: a request whose least does not fit what is left is refused. A request with no previous one in hand (a run's first, or one after a compaction) is priced uncached, as before. A CLI request on a warm cache is now held at its warm price, as pi's already was.
134
+ - Kernel: `capRequestOf` builds a request as the cap prices it (its model, and the session's previous request when it continues the conversation, looked up by the priced model's id). `RunCap.asked(request)` returns it with the run's own pricing. `beforeRequestOf` uses the same function.
135
+ - A long answer through an OpenAI Responses gateway that writes its JSON with spaces is priced, a request that answered while its runner's claim was lost is booked at its cost when the run resumes, and a run whose spend is unknown never reads as a full cap to its learning.
136
+ - Before, the model proxy read a long answer's usage (its terminal event longer than the 64 KiB it keeps) only when the gateway wrote `"usage":{` with no space. A Python gateway (LiteLLM's `json.dumps`) writes `"usage": {`, so such a request was booked at an unknown cost though the harness counted its tokens: the run's cost read unknown with nothing unmetered. pi on the gateway, Codex and OpenCode read the usage the same way and are all fixed. Kernel: `lastObjectOf(text, key)` reads the last `"<key>": {...}` object of a cut answer, whatever its spacing.
137
+ - Before, a runner that lost a run's claim (its lease lapsed while the box stalled) and took the run again in the same process booked a request that had answered meanwhile as cut, at an unknown cost: the lost claim's write of its cost was refused, so the resumed run read the request unanswered. The run's cost read unknown though the request reported its usage on a priced model. Kernel: `SessionWriter.scope` names a session across claims in one process (serve's `journalSessions` sets the run's id beside the key); a booking whose cost write is refused hands it to the next booking of the same scope, whose `bookCut` waits (at most 10 s) for one still in flight and writes it as it would have been written. A request with no price stays unpriced and counts for the cap at its hold. A process that died hands nothing on: its requests are booked cut, as before. A workflow run's model booking now takes them too: its claim books an earlier claim's requests before the workflow resumes, where before it never did, so a workflow's request that answered under a lost claim stayed counted at its hold.
138
+ - Before, a run cancelled or stopped while its model request was being admitted could still send that request: the proxy forwarded it after its client had left, nothing stopped it, and it was booked only once the provider ended it, after the run had ended, so the run read the request as cut at an unknown cost. The proxy now books such a request at nothing (never left) and never sends it, so a run cancelled before any request reached the model costs $0. A request that reached the model and was cut keeps the cut rule: unpriced, counted for the cap at its hold.
139
+ - Before, a capped run whose shown cost was unknown gave its learning grade a cap of $0 ("Not graded: no room under the cap.") and its look-back a reached cap. The grade's cap and the look-back now read the run's spend as its own cap gates read it: an answer with no price counts at the figure the cap held for it, never $0 and never the whole cap. Only when that figure is unknown too, the grade is not queued and says why: "Not graded: this run's spend is unknown, so its budget can't cover the grade."
140
+
5
141
  ## 0.1.0-beta.37 (2026-11-13)
6
142
 
7
143
  - Every harness sees a desktop or a phone through one surface: the tools `computer_observe`, `computer_act`, `computer_screenshot` and `computer_script`, the same answers from a script, an MCP client or a tool call. Breaking: the `desktop_*` and `phone_*` tools are gone, replaced by the `computer_*` tools (a desktop's and a phone's alike, held to the `desktop` or `phone` setting), and the script API's `apps.open(id)` returns nothing; bind the app with `computer.app(id)`.
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,8 +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, 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
- export { mcpRoute } from "./mcp-route.js";
5
- export type { McpHandler, McpRouteOptions } from "./mcp-route.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";
6
5
  export { processAlive } from "./alive.js";
7
6
  export { serialWriter } from "./serial.js";
8
7
  export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./parent-death.js";
@@ -1,8 +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, openaiPatchMultiplier, providerInputOverhead, responsesImagesIn } from "./overhead.js";
4
- export { COUNT_TIMEOUT_MS, countedInputOf, hostHeaderProblems, ProxyRefusal, sameKey, startModelProxy } from "./proxy.js";
5
- export { mcpRoute } from "./mcp-route.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";
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";
@@ -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
+ }