@parcha/agentrun-kernel 0.1.0-beta.37 → 0.1.0-beta.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +53 -0
- package/dist/host/index.d.ts +2 -4
- package/dist/host/index.js +2 -3
- package/dist/host/overhead.d.ts +42 -0
- package/dist/host/overhead.js +84 -10
- package/dist/host/proxy.d.ts +14 -11
- package/dist/host/proxy.js +46 -21
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/kernel/cap/index.d.ts +3 -3
- package/dist/kernel/cap/index.js +2 -2
- package/dist/kernel/cap/port.d.ts +14 -3
- package/dist/kernel/cap/port.js +29 -19
- package/dist/kernel/cap/price.d.ts +31 -12
- package/dist/kernel/cap/price.js +48 -28
- package/dist/kernel/cap/rule.d.ts +3 -1
- package/dist/kernel/cap/rule.js +21 -3
- package/dist/kernel/cap/run-cap.d.ts +9 -2
- package/dist/kernel/cap/run-cap.js +8 -3
- package/dist/kernel/cap/types.d.ts +9 -5
- package/dist/kernel/registry/computer-surface.generated.js +9 -2
- package/dist/kernel/registry/computer.js +12 -4
- package/dist/kernel/registry/hands.d.ts +1 -1
- package/dist/kernel/types.d.ts +8 -1
- package/dist/process/tools.d.ts +2 -0
- package/dist/process/tools.js +59 -5
- package/dist/runner.d.ts +1 -1
- package/dist/runner.js +100 -2
- package/dist/testing.d.ts +6 -2
- package/dist/testing.js +5 -3
- package/dist/tool-deferral.d.ts +12 -0
- package/dist/tool-deferral.js +17 -0
- package/dist/types.d.ts +68 -39
- package/package.json +2 -2
- package/dist/host/mcp-route.d.ts +0 -14
- package/dist/host/mcp-route.js +0 -125
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,59 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.38 (2026-11-14)
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
|
|
9
|
+
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.
|
|
10
|
+
- 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.
|
|
11
|
+
- Kernel: `@parcha/agentrun-kernel/host` exports `NATIVE_SEARCH_USD`. The Claude and Codex proxy policies and the runner's hosted search all read it.
|
|
12
|
+
- `@parcha/agentrun-harness-claude` no longer exports `CLAUDE_WEB_SEARCH_USD`; read `NATIVE_SEARCH_USD` from `@parcha/agentrun-kernel/host`.
|
|
13
|
+
- 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:
|
|
14
|
+
- `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.
|
|
15
|
+
- 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.
|
|
16
|
+
- The desktop-computer skill's Linux section says how to open an app.
|
|
17
|
+
- 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.
|
|
18
|
+
- 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.
|
|
19
|
+
- `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.
|
|
20
|
+
- `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.
|
|
21
|
+
- `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.
|
|
22
|
+
- 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.
|
|
23
|
+
- 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.
|
|
24
|
+
- A refused call inside a script ends the script with the refusal's words.
|
|
25
|
+
- After a crash, a call that was cut off is told as possibly done, and it is not run again.
|
|
26
|
+
- 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.
|
|
27
|
+
- 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.
|
|
28
|
+
- 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.
|
|
29
|
+
- 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.
|
|
30
|
+
- 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.
|
|
31
|
+
- 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.
|
|
32
|
+
- 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.
|
|
33
|
+
- 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.
|
|
34
|
+
- 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.
|
|
35
|
+
- 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.
|
|
36
|
+
- 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.
|
|
37
|
+
- `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.
|
|
38
|
+
- 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.
|
|
39
|
+
- `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.
|
|
40
|
+
- `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`.
|
|
41
|
+
- A provider's label takes its article: "an E2B sandbox", not "a E2B sandbox".
|
|
42
|
+
- 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.
|
|
43
|
+
- Three follow-ups to the tools_search / tools_call / codemode rule, found in a live walk.
|
|
44
|
+
- 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.
|
|
45
|
+
- 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.
|
|
46
|
+
- 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.
|
|
47
|
+
- 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.
|
|
48
|
+
- 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.
|
|
49
|
+
- 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.
|
|
50
|
+
- 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.
|
|
51
|
+
- 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.
|
|
52
|
+
- 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.
|
|
53
|
+
- 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.
|
|
54
|
+
- 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.
|
|
55
|
+
- 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.
|
|
56
|
+
- 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."
|
|
57
|
+
|
|
5
58
|
## 0.1.0-beta.37 (2026-11-13)
|
|
6
59
|
|
|
7
60
|
- 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/dist/host/index.d.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
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";
|
|
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
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";
|
|
6
4
|
export { processAlive } from "./alive.js";
|
|
7
5
|
export { serialWriter } from "./serial.js";
|
|
8
6
|
export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./parent-death.js";
|
package/dist/host/index.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
// What a harness adapter runs beside its harness on the host: the session's model proxy, provider-neutral, with each
|
|
2
2
|
// provider's rules in a `ProviderPolicy`. Written for AgentRun.
|
|
3
|
-
export { ANTHROPIC_IMAGE_TOKENS_MAX, ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS, ASSUMED_TOOL_PROMPT_TOKENS, 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, 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";
|
|
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";
|
package/dist/host/overhead.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { InputCounter } from "./proxy.js";
|
|
1
2
|
/** One image a request carries: the bytes its data takes in the body (its base64, or its data URL; 0 for an image the
|
|
2
3
|
* provider fetches by URL), which are counted at the image's billed size instead, and its pixel size when its data's own
|
|
3
4
|
* header says it (PNG, JPEG, GIF, WebP). */
|
|
@@ -119,6 +120,47 @@ export declare function messagesImagesIn(messages: unknown): ImageInput[];
|
|
|
119
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
|
|
120
121
|
* bytes). An image-shaped object anywhere else is text to the provider: its bytes stay counted as they are. */
|
|
121
122
|
export declare function responsesImagesIn(input: unknown): ImageInput[];
|
|
123
|
+
/**
|
|
124
|
+
* 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
|
|
125
|
+
* own UTF-8 bytes: in `instructions`, and in each `input` item, a message's text, a function call's arguments, a custom
|
|
126
|
+
* tool call's input, a tool's output (a string, or its text parts) and a reasoning summary's text.
|
|
127
|
+
*
|
|
128
|
+
* Why the input bound may count that text at its own bytes: the model reads it as the string itself, never as its JSON
|
|
129
|
+
* spelling in the body. OpenAI's counting recipe encodes each message's decoded value and adds a fixed few tokens a
|
|
130
|
+
* message (num_tokens_from_messages,
|
|
131
|
+
* https://github.com/openai/openai-cookbook/blob/db3144982aa26b87a9bdfb692b4fbedfdf8a14d5/examples/How_to_count_tokens_with_tiktoken.ipynb),
|
|
132
|
+
* and the harmony format OpenAI published for its models puts a message's content, a call's arguments and a tool's
|
|
133
|
+
* output between its special tokens as raw text (`<|message|>{"location":"San Francisco"}<|call|>`,
|
|
134
|
+
* https://github.com/openai/harmony/blob/e0ce87d1c3b9f59dec2e27de4770c769f03ebbd3/docs/format.md#receiving-tool-calls).
|
|
135
|
+
* A byte-level BPE token covers at least one byte of the text it encodes, so that text is at most its UTF-8 bytes in
|
|
136
|
+
* tokens; the escape characters JSON adds around it (`\"`, `\\`, `\n`, `\t`, `\u0000`) are bytes the body spends that no
|
|
137
|
+
* token of it is billed for. Every other byte is counted as sent, as before: the keys, ids and structure of each item
|
|
138
|
+
* still cover the framing the provider puts around it (a role, a recipient, a few special tokens: fewer than the bytes
|
|
139
|
+
* of the keys the item spends); the tool definitions (`tools`, and code mode's `additional_tools` item) are counted
|
|
140
|
+
* whole, since a template renders them into a prompt of its own that may quote their strings again (harmony's
|
|
141
|
+
* TypeScript namespace); and encrypted reasoning is base64, which JSON never escapes, so it keeps its own bytes.
|
|
142
|
+
*/
|
|
143
|
+
export declare function responsesEscapedBytes(body: Record<string, unknown>): number;
|
|
144
|
+
/**
|
|
145
|
+
* The input tokens the provider bills for a Responses `body` beyond its bytes (`providerInputOverhead`, with its
|
|
146
|
+
* sources), less the escapes in the text it carries (`responsesEscapedBytes`, with the argument for it). The Responses
|
|
147
|
+
* API documents no prompt of its own that it adds on these routes, and the framing it puts around each input item and
|
|
148
|
+
* tool definition is a few tokens each, fewer than the bytes of the JSON keys that item already spends in the body. An
|
|
149
|
+
* image is billed by its area, not its bytes: each counts at the most it can be billed as, in place of the bytes its
|
|
150
|
+
* data URL takes in the body. A file input (a PDF, billed by its pages) has no stated bound, so a body with one cannot
|
|
151
|
+
* be measured: this throws, and the request's input is unknown. Codex's and OpenCode's policies both use it.
|
|
152
|
+
*/
|
|
153
|
+
export declare function responsesInputOverhead(body: Record<string, unknown>): number;
|
|
154
|
+
/**
|
|
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.
|
|
162
|
+
*/
|
|
163
|
+
export declare const OPENAI_INPUT_COUNTER: InputCounter;
|
|
122
164
|
/** The image a body's `data` (base64, or a data URL) carries: the bytes it takes, and its size when its header says it.
|
|
123
165
|
* Anything else (an http URL, a file id): no bytes, no size. */
|
|
124
166
|
export declare function imageInputOf(data: unknown): ImageInput;
|
package/dist/host/overhead.js
CHANGED
|
@@ -1,13 +1,3 @@
|
|
|
1
|
-
// The input a provider bills for a request beyond the bytes of its body, by the provider's API: one place for the figures
|
|
2
|
-
// and their sources, used by the model proxy's policies and by a host that bounds a request it sends itself. Written for
|
|
3
|
-
// AgentRun.
|
|
4
|
-
//
|
|
5
|
-
// A request's input can never be more tokens than its body's UTF-8 bytes (`inputTokensMaxOf`), except for what the
|
|
6
|
-
// provider adds or bills by another measure: a prompt it adds itself when tools are present, and images, which it bills by
|
|
7
|
-
// their area after it resizes them, not by their bytes. An image is counted at what the routed model's provider bills it
|
|
8
|
-
// as by its size (Anthropic's, OpenAI's or Google's rule; the most of the three for another provider), in place of the
|
|
9
|
-
// bytes its data takes in the body: a screenshot's base64 is a megabyte, and Claude bills it as some 1,200 tokens. Each
|
|
10
|
-
// figure is the largest the provider documents for any current model, so no model is undercounted.
|
|
11
1
|
/**
|
|
12
2
|
* The tool-use system prompt the Messages API adds to a request with tools, in tokens, by tool_choice. Documented per
|
|
13
3
|
* model under "Pricing" in https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview, and taken at the largest
|
|
@@ -267,6 +257,90 @@ export function responsesImagesIn(input) {
|
|
|
267
257
|
}
|
|
268
258
|
return out;
|
|
269
259
|
}
|
|
260
|
+
/** The items of `type` in `value`, at any depth (a tool's output holds them). */
|
|
261
|
+
function itemsIn(value, type) {
|
|
262
|
+
if (Array.isArray(value))
|
|
263
|
+
return value.reduce((n, item) => n + itemsIn(item, type), 0);
|
|
264
|
+
if (!plain(value))
|
|
265
|
+
return 0;
|
|
266
|
+
return (value.type === type ? 1 : 0) + Object.values(value).reduce((n, item) => n + itemsIn(item, type), 0);
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* 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
|
|
270
|
+
* own UTF-8 bytes: in `instructions`, and in each `input` item, a message's text, a function call's arguments, a custom
|
|
271
|
+
* tool call's input, a tool's output (a string, or its text parts) and a reasoning summary's text.
|
|
272
|
+
*
|
|
273
|
+
* Why the input bound may count that text at its own bytes: the model reads it as the string itself, never as its JSON
|
|
274
|
+
* spelling in the body. OpenAI's counting recipe encodes each message's decoded value and adds a fixed few tokens a
|
|
275
|
+
* message (num_tokens_from_messages,
|
|
276
|
+
* https://github.com/openai/openai-cookbook/blob/db3144982aa26b87a9bdfb692b4fbedfdf8a14d5/examples/How_to_count_tokens_with_tiktoken.ipynb),
|
|
277
|
+
* and the harmony format OpenAI published for its models puts a message's content, a call's arguments and a tool's
|
|
278
|
+
* output between its special tokens as raw text (`<|message|>{"location":"San Francisco"}<|call|>`,
|
|
279
|
+
* https://github.com/openai/harmony/blob/e0ce87d1c3b9f59dec2e27de4770c769f03ebbd3/docs/format.md#receiving-tool-calls).
|
|
280
|
+
* A byte-level BPE token covers at least one byte of the text it encodes, so that text is at most its UTF-8 bytes in
|
|
281
|
+
* tokens; the escape characters JSON adds around it (`\"`, `\\`, `\n`, `\t`, `\u0000`) are bytes the body spends that no
|
|
282
|
+
* token of it is billed for. Every other byte is counted as sent, as before: the keys, ids and structure of each item
|
|
283
|
+
* still cover the framing the provider puts around it (a role, a recipient, a few special tokens: fewer than the bytes
|
|
284
|
+
* of the keys the item spends); the tool definitions (`tools`, and code mode's `additional_tools` item) are counted
|
|
285
|
+
* whole, since a template renders them into a prompt of its own that may quote their strings again (harmony's
|
|
286
|
+
* TypeScript namespace); and encrypted reasoning is base64, which JSON never escapes, so it keeps its own bytes.
|
|
287
|
+
*/
|
|
288
|
+
export function responsesEscapedBytes(body) {
|
|
289
|
+
// What the proxy sends is JSON.stringify's spelling, so the escapes are measured by the same spelling.
|
|
290
|
+
const escaped = (text) => (typeof text === "string" ? Buffer.byteLength(JSON.stringify(text), "utf8") - 2 - Buffer.byteLength(text, "utf8") : 0);
|
|
291
|
+
const textOf = (content) => (typeof content === "string" ? escaped(content) : list(content).reduce((n, part) => n + (plain(part) && (part.type === "input_text" || part.type === "output_text" || part.type === "summary_text" || part.type === "reasoning_text") ? escaped(part.text) : 0), 0));
|
|
292
|
+
let sum = escaped(body.instructions);
|
|
293
|
+
for (const item of list(body.input)) {
|
|
294
|
+
if (!plain(item))
|
|
295
|
+
continue;
|
|
296
|
+
if (item.type === "message" || (item.type === undefined && typeof item.role === "string"))
|
|
297
|
+
sum += textOf(item.content);
|
|
298
|
+
else if (item.type === "function_call")
|
|
299
|
+
sum += escaped(item.arguments);
|
|
300
|
+
else if (item.type === "custom_tool_call")
|
|
301
|
+
sum += escaped(item.input);
|
|
302
|
+
else if (item.type === "function_call_output" || item.type === "custom_tool_call_output")
|
|
303
|
+
sum += textOf(item.output);
|
|
304
|
+
else if (item.type === "reasoning")
|
|
305
|
+
sum += textOf(item.summary) + textOf(item.content);
|
|
306
|
+
}
|
|
307
|
+
return sum;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* The input tokens the provider bills for a Responses `body` beyond its bytes (`providerInputOverhead`, with its
|
|
311
|
+
* sources), less the escapes in the text it carries (`responsesEscapedBytes`, with the argument for it). The Responses
|
|
312
|
+
* API documents no prompt of its own that it adds on these routes, and the framing it puts around each input item and
|
|
313
|
+
* tool definition is a few tokens each, fewer than the bytes of the JSON keys that item already spends in the body. An
|
|
314
|
+
* image is billed by its area, not its bytes: each counts at the most it can be billed as, in place of the bytes its
|
|
315
|
+
* data URL takes in the body. A file input (a PDF, billed by its pages) has no stated bound, so a body with one cannot
|
|
316
|
+
* be measured: this throws, and the request's input is unknown. Codex's and OpenCode's policies both use it.
|
|
317
|
+
*/
|
|
318
|
+
export function responsesInputOverhead(body) {
|
|
319
|
+
if (itemsIn(body.input, "input_file") > 0)
|
|
320
|
+
throw new Error("a file input's billed size has no stated bound");
|
|
321
|
+
return providerInputOverhead("openai-responses", { tools: Array.isArray(body.tools) && body.tools.length > 0, images: responsesImagesIn(body.input), ...(typeof body.model === "string" ? { model: body.model } : {}) }) - responsesEscapedBytes(body);
|
|
322
|
+
}
|
|
323
|
+
/** The fields of a Responses body the input-token count takes (the rest, such as stream, store, include and
|
|
324
|
+
* max_output_tokens, change nothing it counts). */
|
|
325
|
+
const RESPONSES_COUNTED_FIELDS = ["model", "input", "instructions", "tools", "tool_choice", "parallel_tool_calls", "reasoning", "text"];
|
|
326
|
+
/** The request headers the count is sent with: the credential's and the account's, nothing else. */
|
|
327
|
+
const OPENAI_COUNT_HEADERS = new Set(["authorization", "openai-organization", "openai-project"]);
|
|
328
|
+
/**
|
|
329
|
+
* OpenAI's own count of a Responses request's input tokens: POST /v1/responses/input_tokens on api.openai.com only, which
|
|
330
|
+
* "accepts the same input format as the Responses API" and answers `{object: "response.input_tokens", input_tokens}`,
|
|
331
|
+
* "the exact count the model will receive", formatting tokens, tools and images included ("Counting tokens",
|
|
332
|
+
* https://developers.openai.com/api/docs/guides/token-counting; the SDK's `responses.inputTokens.count`,
|
|
333
|
+
* https://github.com/openai/openai-node/blob/543ed94e6451d2eaf43f1a4a16a0fc8c8f42eade/src/resources/responses/input-tokens.ts).
|
|
334
|
+
* The model proxy asks it before each answer request on that origin (never through a gateway), as Anthropic's count is
|
|
335
|
+
* asked (ProviderPolicy.countInput): a count that fails, times out, or answers anything else leaves the byte bound.
|
|
336
|
+
*/
|
|
337
|
+
export const OPENAI_INPUT_COUNTER = Object.freeze({
|
|
338
|
+
origin: "https://api.openai.com",
|
|
339
|
+
path: "/v1/responses/input_tokens",
|
|
340
|
+
body: (body) => Object.fromEntries(RESPONSES_COUNTED_FIELDS.filter((field) => body[field] !== undefined).map((field) => [field, body[field]])),
|
|
341
|
+
headers: (sent) => Object.fromEntries(Object.entries(sent).filter(([name]) => OPENAI_COUNT_HEADERS.has(name.toLowerCase()))),
|
|
342
|
+
tokensOf: (answer) => (plain(answer) && answer.object === "response.input_tokens" && typeof answer.input_tokens === "number" ? answer.input_tokens : undefined),
|
|
343
|
+
});
|
|
270
344
|
/** The image a body's `data` (base64, or a data URL) carries: the bytes it takes, and its size when its header says it.
|
|
271
345
|
* Anything else (an http URL, a file id): no bytes, no size. */
|
|
272
346
|
export function imageInputOf(data) {
|
package/dist/host/proxy.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type IncomingHttpHeaders } from "node:http";
|
|
2
|
-
import { type
|
|
2
|
+
import { type NoteRequest } from "../types.js";
|
|
3
3
|
import { type Ended } from "../booking.js";
|
|
4
4
|
/** A route a policy admits: its method, its exact path, and the request headers forwarded with it. */
|
|
5
5
|
export interface ProxyRoute {
|
|
@@ -20,6 +20,10 @@ export interface ProxyUsage {
|
|
|
20
20
|
cacheRead: number;
|
|
21
21
|
cacheWrite?: number;
|
|
22
22
|
}
|
|
23
|
+
/** What one provider-native web search costs, in USD, beside the tokens: $10 per 1,000 searches (Anthropic's "Web search tool"
|
|
24
|
+
* and OpenAI's "Web search (all models)" list the same price). The one figure every fee reads: the proxy policies of the
|
|
25
|
+
* Claude and Codex harnesses and the runner's hosted search. */
|
|
26
|
+
export declare const NATIVE_SEARCH_USD = 0.01;
|
|
23
27
|
/** What one provider's API may carry through the proxy. */
|
|
24
28
|
export interface ProviderPolicy {
|
|
25
29
|
/** A name for messages. */
|
|
@@ -87,7 +91,7 @@ export interface ProviderPolicy {
|
|
|
87
91
|
/** The output tokens the body `apply` returned asks for at most (its own limit, as `apply` shaped it). Absent or
|
|
88
92
|
* undefined: the body does not say. */
|
|
89
93
|
outputAsked?(body: Record<string, unknown>): number | undefined;
|
|
90
|
-
/** The provider's own count of a request's input tokens (Anthropic's free count_tokens), which the proxy asks before
|
|
94
|
+
/** The provider's own count of a request's input tokens (Anthropic's free count_tokens, OpenAI's input_tokens), which the proxy asks before
|
|
91
95
|
* each of the session's answer requests (`countedInputOf`) when its upstream is exactly `origin`, the provider's own: never
|
|
92
96
|
* through a gateway or any other base, so the key and the request go nowhere the request itself would not. Its count,
|
|
93
97
|
* plus `margin`, is that request's input bound when it is below the byte bound. Absent: never counted. */
|
|
@@ -255,14 +259,6 @@ export interface ModelProxyOptions {
|
|
|
255
259
|
* after the client's, so the client can neither set nor override them, and before the credential's. Checked when the
|
|
256
260
|
* proxy starts (`hostHeaderProblems`). */
|
|
257
261
|
headers?: Readonly<Record<string, string>>;
|
|
258
|
-
/** The session's remote MCP servers, each mounted here at `/mcp/<server>` behind the session's key (mcp-route.ts),
|
|
259
|
-
* for the harness's own MCP client as its adapter declares it (`client`, AdapterCapabilities.mcpClient). One mount for
|
|
260
|
-
* every harness: an adapter hands the session's MCP, never a route of its own. */
|
|
261
|
-
mcp?: {
|
|
262
|
-
session: SessionMcp;
|
|
263
|
-
client: McpClient;
|
|
264
|
-
keepaliveMs?: number;
|
|
265
|
-
};
|
|
266
262
|
/** For tests: the fetch the proxy forwards with. */
|
|
267
263
|
fetch?: typeof fetch;
|
|
268
264
|
/** Told, with CONTENT_FILTERED, once an answer the provider stopped on its content filter has been passed and booked
|
|
@@ -289,7 +285,7 @@ export interface ModelProxy {
|
|
|
289
285
|
* harness. A request under it goes through the same policy, origin, credential, price and hooks as the harness's;
|
|
290
286
|
* its admission names the label (ModelRequest.host), the policy applies it as the host's (`ProxyRequestContext`),
|
|
291
287
|
* it is never the turn's answer request (a content-filter stop on it never halts the turn) and never watched. It opens
|
|
292
|
-
* the model routes only
|
|
288
|
+
* the model routes only. */
|
|
293
289
|
sideKey(label: string): string;
|
|
294
290
|
/** The harness opened its next turn: once the proxy has told it a turn's answer stopped (onCut, onFiltered), it refuses
|
|
295
291
|
* the session's answer requests, unsent and unbooked, until this is called. */
|
|
@@ -301,6 +297,13 @@ export interface ModelProxy {
|
|
|
301
297
|
export interface ProxyRequestContext {
|
|
302
298
|
readonly host?: string;
|
|
303
299
|
}
|
|
300
|
+
/** The last `"<key>": {...}` object in `text`, parsed: how a policy reads a field of an answer's terminal event when the
|
|
301
|
+
* event's line was longer than USAGE_WINDOW, so the proxy kept only its end. JSON may put whitespace on either side of
|
|
302
|
+
* the colon (a Python gateway's `json.dumps` writes `"usage": {`), and the client parses the event whatever its spacing,
|
|
303
|
+
* so this reads it too: a usage the harness counted is never booked at an unknown cost for its spacing. A key's quoted
|
|
304
|
+
* name inside a JSON string is escaped (`\"usage\"`), so it never reads as one. Undefined when there is none, or the
|
|
305
|
+
* last one does not close in `text` or does not parse. */
|
|
306
|
+
export declare function lastObjectOf(text: string, key: string): unknown;
|
|
304
307
|
/** The ids a response's headers give its request, by header name, so a run's books can be joined to the provider's (or
|
|
305
308
|
* a gateway's) request by request; undefined when there are none. Only id-named headers with id-shaped values. */
|
|
306
309
|
export declare function providerIdsOf(headers: Headers): Record<string, string> | undefined;
|
package/dist/host/proxy.js
CHANGED
|
@@ -16,7 +16,6 @@
|
|
|
16
16
|
// Model spend is accounted only there, by the runner: the proxy keeps no ledger of its own.
|
|
17
17
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
18
18
|
import { createServer } from "node:http";
|
|
19
|
-
import { mcpRoute } from "./mcp-route.js";
|
|
20
19
|
import { CONTENT_FILTERED } from "../types.js";
|
|
21
20
|
import { isConnectCode, isGatewayTimeout, rejectionCode } from "../booking.js";
|
|
22
21
|
import { SPEND_CAP_REACHED } from "../kernel/cap/words.js";
|
|
@@ -27,6 +26,10 @@ const capRefusal = (error) => {
|
|
|
27
26
|
const fields = error;
|
|
28
27
|
return fields?.code === SPEND_CAP_REACHED || fields?.refusal === SPEND_CAP_REACHED;
|
|
29
28
|
};
|
|
29
|
+
/** What one provider-native web search costs, in USD, beside the tokens: $10 per 1,000 searches (Anthropic's "Web search tool"
|
|
30
|
+
* and OpenAI's "Web search (all models)" list the same price). The one figure every fee reads: the proxy policies of the
|
|
31
|
+
* Claude and Codex harnesses and the runner's hosted search. */
|
|
32
|
+
export const NATIVE_SEARCH_USD = 0.01;
|
|
30
33
|
/** The longest a response's text may run with no event boundary before the reasoning count lets it go (a body that is
|
|
31
34
|
* not a stream of events, read whole as one). */
|
|
32
35
|
const EVENT_MAX_CHARS = 1 << 22;
|
|
@@ -395,14 +398,44 @@ export function hostHeaderProblems(headers) {
|
|
|
395
398
|
}
|
|
396
399
|
return problems;
|
|
397
400
|
}
|
|
398
|
-
/** A server's endpoint, `/mcp/<server>`, with no query. */
|
|
399
|
-
const MCP_PATH = /^\/mcp\/([a-z][a-z0-9-]{0,31})$/;
|
|
400
|
-
/** Where an MCP client looks for OAuth after a 401: never served here, so it never starts a sign-in against the proxy. */
|
|
401
|
-
const OAUTH_PATH = /^\/(?:\.well-known\/|register(?:$|[/?]))/;
|
|
402
401
|
const UNSAFE_PATH = /[^A-Za-z0-9/_.\-?=&]|\.\.|\/\/|^[^/]|\?.*\?/;
|
|
403
402
|
const MAX_BODY = 32 * 1024 * 1024;
|
|
404
403
|
/** How much of a response's start and end the proxy keeps to read its usage from. */
|
|
405
404
|
const USAGE_WINDOW = 64 * 1024;
|
|
405
|
+
/** The last `"<key>": {...}` object in `text`, parsed: how a policy reads a field of an answer's terminal event when the
|
|
406
|
+
* event's line was longer than USAGE_WINDOW, so the proxy kept only its end. JSON may put whitespace on either side of
|
|
407
|
+
* the colon (a Python gateway's `json.dumps` writes `"usage": {`), and the client parses the event whatever its spacing,
|
|
408
|
+
* so this reads it too: a usage the harness counted is never booked at an unknown cost for its spacing. A key's quoted
|
|
409
|
+
* name inside a JSON string is escaped (`\"usage\"`), so it never reads as one. Undefined when there is none, or the
|
|
410
|
+
* last one does not close in `text` or does not parse. */
|
|
411
|
+
export function lastObjectOf(text, key) {
|
|
412
|
+
const marks = new RegExp(`"${key.replace(/[^A-Za-z0-9_]/g, "")}"\\s*:\\s*\\{`, "g");
|
|
413
|
+
let open = -1;
|
|
414
|
+
for (let found = marks.exec(text); found; found = marks.exec(text))
|
|
415
|
+
open = found.index + found[0].length - 1;
|
|
416
|
+
if (open < 0)
|
|
417
|
+
return undefined;
|
|
418
|
+
let depth = 0;
|
|
419
|
+
for (let i = open; i < text.length; i++) {
|
|
420
|
+
const c = text[i];
|
|
421
|
+
if (c === "\"") {
|
|
422
|
+
for (i++; i < text.length && text[i] !== "\""; i++)
|
|
423
|
+
if (text[i] === "\\")
|
|
424
|
+
i++;
|
|
425
|
+
}
|
|
426
|
+
else if (c === "{")
|
|
427
|
+
depth++;
|
|
428
|
+
else if (c === "}" && --depth === 0) {
|
|
429
|
+
try {
|
|
430
|
+
return JSON.parse(text.slice(open, i + 1));
|
|
431
|
+
}
|
|
432
|
+
catch {
|
|
433
|
+
return undefined;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return undefined;
|
|
438
|
+
}
|
|
406
439
|
/** How long an answer the provider stopped on its content filter is still read after its client left, or the proxy began
|
|
407
440
|
* to close, so the request is booked at the usage its end reports; past it, it is cut off as any other. */
|
|
408
441
|
const FILTERED_DRAIN_MS = 5_000;
|
|
@@ -699,8 +732,6 @@ export async function startModelProxy(options, key) {
|
|
|
699
732
|
res.writeHead(status, { "content-type": "application/json", connection: "close" });
|
|
700
733
|
res.end(JSON.stringify({ error: { message, type: "agentrun_proxy", ...(code ? { code } : {}) } }));
|
|
701
734
|
};
|
|
702
|
-
// The session's MCP door, mounted once here for whichever harness's client calls it (the call id from its fact).
|
|
703
|
-
const mcpDoor = options.mcp && mcpRoute(options.mcp.session, { callIdMeta: options.mcp.client.callIdMeta, ...(options.mcp.keepaliveMs !== undefined ? { keepaliveMs: options.mcp.keepaliveMs } : {}) });
|
|
704
735
|
/** Serves one request. A note it took and did not bring to its admission (it left before `beforeRequest`: its client
|
|
705
736
|
* gone while it was counted, a refusal, an error) is given back to the host then, however it left, so the next request
|
|
706
737
|
* can take it at once. From its admission on the note is the admission's: told, or given back by its refusal. */
|
|
@@ -726,19 +757,6 @@ export async function startModelProxy(options, key) {
|
|
|
726
757
|
// A request refused before its body is read is drained, so its client gets the answer instead of a reset.
|
|
727
758
|
res.once("finish", () => { if (!req.complete)
|
|
728
759
|
req.resume(); });
|
|
729
|
-
const path = req.url ?? "";
|
|
730
|
-
if (options.mcp && OAUTH_PATH.test(path)) {
|
|
731
|
-
res.writeHead(404, { "content-length": "0" });
|
|
732
|
-
return res.end();
|
|
733
|
-
}
|
|
734
|
-
const mcp = mcpDoor ? MCP_PATH.exec(path) : null;
|
|
735
|
-
if (mcp) {
|
|
736
|
-
if (!sameKey(policy.keyOf(req.headers), key))
|
|
737
|
-
return refuse(res, 401, "this session's key is required", req);
|
|
738
|
-
if (closing)
|
|
739
|
-
return refuse(res, 503, "the model proxy is closing", req);
|
|
740
|
-
return mcpDoor(mcp[1], req, res);
|
|
741
|
-
}
|
|
742
760
|
let route;
|
|
743
761
|
let query;
|
|
744
762
|
try {
|
|
@@ -999,7 +1017,8 @@ export async function startModelProxy(options, key) {
|
|
|
999
1017
|
/** An admitted request that is not sent after all: refused to its client, and released, booked at nothing, so the
|
|
1000
1018
|
* runner's count agrees. */
|
|
1001
1019
|
const release = async (status, message) => {
|
|
1002
|
-
|
|
1020
|
+
if (!res.destroyed)
|
|
1021
|
+
refuse(res, status, message, req);
|
|
1003
1022
|
if (!route.free) {
|
|
1004
1023
|
try {
|
|
1005
1024
|
await hooks.afterRequest({ input: 0, output: 0, cacheRead: 0, usd: 0 }, ticket, { end: "nothing", label: "never_left" });
|
|
@@ -1012,6 +1031,12 @@ export async function startModelProxy(options, key) {
|
|
|
1012
1031
|
// Admitted while the proxy was closing, and never sent.
|
|
1013
1032
|
if (closing)
|
|
1014
1033
|
return release(503, "the model proxy is closing");
|
|
1034
|
+
// Admitted after its client left (a stop or a cancel while its hold was made durable): never sent, booked at nothing.
|
|
1035
|
+
// Sent anyway it would be a paid answer for no one, and one never stopped (its client's close came before the proxy
|
|
1036
|
+
// listened for it, below), booked only once the provider ended it: past the run's end, which then read the request as
|
|
1037
|
+
// cut at an unknown cost. Nothing from here to that listener waits, so a client that leaves later is heard there.
|
|
1038
|
+
if (res.destroyed || req.socket.destroyed)
|
|
1039
|
+
return release(499, "the client left before its request was sent");
|
|
1015
1040
|
// Admitted only without the note (its bytes did not fit what is left of the cap): the body as the client sent it.
|
|
1016
1041
|
if (typeof ticket === "object" && ticket !== null && ticket.noteDropped === true) {
|
|
1017
1042
|
if (!plain || plainSent === undefined)
|
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ export { answeredUnpriced, createHarnessRunner, modelPortFor, sessionSpendOf, SU
|
|
|
2
2
|
export { runBooking, type RunSessions } from "./run-booking.js";
|
|
3
3
|
export type { Admission, BeforeRequest, Refusal, HarnessRunner, HarnessRunnerOptions, InFlight, ModelBooking, ModelPortEvent, ModelPortOptions, SessionCost } from "./runner.js";
|
|
4
4
|
export { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
|
|
5
|
+
export { CODEMODE, DEFER_CATALOG_OVER, defersCatalog, isCatalogName, META_TOOLS, TOOLS_CALL, TOOLS_SEARCH } from "./tool-deferral.js";
|
|
5
6
|
export { toolSchemaProblems } from "./schema-check.js";
|
|
6
7
|
export { READ_SKILL_FILE, readSkillFileTool, SKILL_BYTES, skillProblems } from "./skill-files.js";
|
|
7
8
|
export type { HostSkill, SkillFileList } from "./skill-files.js";
|
|
@@ -9,4 +10,4 @@ export type { HarnessRunReason } from "./errors.js";
|
|
|
9
10
|
export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS, hostedTool } from "./types.js";
|
|
10
11
|
export { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "./booking.js";
|
|
11
12
|
export type { Booked, Ended, Priced } from "./booking.js";
|
|
12
|
-
export type {
|
|
13
|
+
export type { AdapterEvent, AdapterSession, AgentAdapter, AdapterFacts, GateAnswer, GateCall, SessionPort, Wire, HarnessEvent, HostTool, McpCallResult, McpTool, NestedCalls, NestedResult, ToolImage, JsonValue, ModelPort, ModelTicket, ModelRequest, ModelUsage, NoteRequest, NodeRequest, SessionIO, SessionRecord, SessionSpec, SessionState, SessionStore, SessionWriter, ToolPermission, TurnStatus, } from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { answeredUnpriced, createHarnessRunner, modelPortFor, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
|
|
2
2
|
export { runBooking } from "./run-booking.js";
|
|
3
3
|
export { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
|
|
4
|
+
export { CODEMODE, DEFER_CATALOG_OVER, defersCatalog, isCatalogName, META_TOOLS, TOOLS_CALL, TOOLS_SEARCH } from "./tool-deferral.js";
|
|
4
5
|
export { toolSchemaProblems } from "./schema-check.js";
|
|
5
6
|
export { READ_SKILL_FILE, readSkillFileTool, SKILL_BYTES, skillProblems } from "./skill-files.js";
|
|
6
7
|
export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS, hostedTool } from "./types.js";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
export { CapRefused, createCap, DECISION_IMAGE_TOKENS, DECISION_OUTPUT_TOKENS, DecisionPriceUnreadable, END_MARK_WAIT_MS, END_NOT_WRITTEN, MARK_NOT_WRITTEN, openCap } from "./admit.js";
|
|
2
2
|
export { capRule, noteFor, requestFigures, type Judged, type JudgeState, type NoteState } from "./rule.js";
|
|
3
|
-
export { beforeRequestOf, type BeforeRequestOptions } from "./port.js";
|
|
3
|
+
export { beforeRequestOf, capRequestOf, type BeforeRequestOptions, type PricedRequest } from "./port.js";
|
|
4
4
|
export { DECISION_SESSION, overCapOf, paidCalls, runCap, TOOL_SESSION, type RunCap, type RunCapOptions, type RunDecisions, type RunTools } from "./run-cap.js";
|
|
5
|
-
export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput,
|
|
5
|
+
export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput, pricingOf, RECENT_REQUESTS_KEPT, recentAfter, ratesFor, requestPrice, warmFrom } from "./price.js";
|
|
6
6
|
export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, OVER_CAP_END, overCapEnd, overCapMessage, overCapWords, paidRefusal, raiseFigure, raiseTo, spentMoney, suggestedRaise } from "./words.js";
|
|
7
7
|
export { checkRaise, followUpOf, parkOf, takeRaises, type BudgetPending, type Park, type RaiseCheck, type RaiseState } from "./park.js";
|
|
8
8
|
export { WRAP_UP_FACTOR, WRAP_UP_LEAST_FACTOR, WRAP_UP_STEP0_ANSWER_TOKENS, typicalCost, wrapUpDue, wrapUpWords } from "./wrap-up.js";
|
|
@@ -11,4 +11,4 @@ export { memoryMarks, type CapMark, type CapMarks, type EndMark, type StartMark,
|
|
|
11
11
|
export { ownCostsOf, spendOf, toldIn, type Spend } from "./recover.js";
|
|
12
12
|
export { StepNotHeld, StepNotSettled } from "./ledger.js";
|
|
13
13
|
export { reasoningBytes, stoppedTokens, streamedBytes } from "./stopped.js";
|
|
14
|
-
export type { Admission, Cap, CapMode, CapModel, CapOptions, CapRequest, DecisionCapRequest, ModelCapRequest, ModelPrice, PriceRates, PriceTier,
|
|
14
|
+
export type { Admission, Cap, CapMode, CapModel, CapOptions, CapRequest, DecisionCapRequest, ModelCapRequest, ModelPrice, PriceRates, PriceTier, RecentRequest, RefusalFigures, Settled, ToolCapRequest } from "./types.js";
|
package/dist/kernel/cap/index.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
// package's index until the cutover: its tests import it from dist/kernel/cap/.
|
|
3
3
|
export { CapRefused, createCap, DECISION_IMAGE_TOKENS, DECISION_OUTPUT_TOKENS, DecisionPriceUnreadable, END_MARK_WAIT_MS, END_NOT_WRITTEN, MARK_NOT_WRITTEN, openCap } from "./admit.js";
|
|
4
4
|
export { capRule, noteFor, requestFigures } from "./rule.js";
|
|
5
|
-
export { beforeRequestOf } from "./port.js";
|
|
5
|
+
export { beforeRequestOf, capRequestOf } from "./port.js";
|
|
6
6
|
export { DECISION_SESSION, overCapOf, paidCalls, runCap, TOOL_SESSION } from "./run-cap.js";
|
|
7
|
-
export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput,
|
|
7
|
+
export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput, pricingOf, RECENT_REQUESTS_KEPT, recentAfter, ratesFor, requestPrice, warmFrom } from "./price.js";
|
|
8
8
|
export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, OVER_CAP_END, overCapEnd, overCapMessage, overCapWords, paidRefusal, raiseFigure, raiseTo, spentMoney, suggestedRaise } from "./words.js";
|
|
9
9
|
export { checkRaise, followUpOf, parkOf, takeRaises } from "./park.js";
|
|
10
10
|
export { WRAP_UP_FACTOR, WRAP_UP_LEAST_FACTOR, WRAP_UP_STEP0_ANSWER_TOKENS, typicalCost, wrapUpDue, wrapUpWords } from "./wrap-up.js";
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import type { BeforeRequest } from "../../runner.js";
|
|
2
|
-
import type { CapMode, CapModel,
|
|
2
|
+
import type { CapMode, CapModel, ModelCapRequest, RecentRequest } from "./types.js";
|
|
3
3
|
export interface BeforeRequestOptions {
|
|
4
4
|
/** The run's cap, read before every request. Undefined: no cap, nothing refused. */
|
|
5
5
|
capUsd(): number | undefined;
|
|
6
6
|
/** A model as the cap prices it, by its id and the route its request came by (ModelRequest.route; absent, the
|
|
7
7
|
* session's own): one id two routes price apart is priced as its route books it. Undefined: a model with no price here. */
|
|
8
8
|
modelOf(id: string, route?: string): CapModel | undefined;
|
|
9
|
-
/** The session's
|
|
10
|
-
|
|
9
|
+
/** The session's recent requests on a model (price.ts recentAfter), by the id the cap prices it under (CapModel.id,
|
|
10
|
+
* which a CLI's request may name otherwise), as their usage reported them: none prices the input uncached. */
|
|
11
|
+
recentOf?(model: string): readonly RecentRequest[];
|
|
11
12
|
/** What the run spent beside the session's model requests, which the runner's booking does not hold: its priced tools'
|
|
12
13
|
* charges (null: unknown). The run's spend is the runner's plus this. A figure that is not finite and 0 or more is
|
|
13
14
|
* unknown too. */
|
|
@@ -15,8 +16,18 @@ export interface BeforeRequestOptions {
|
|
|
15
16
|
/** What the run's priced tools under way hold, beside the session's requests in flight (null: unknown). A figure that is
|
|
16
17
|
* not finite and 0 or more is unknown too: the request is refused, never judged as $0 held. */
|
|
17
18
|
heldUsd?(): number | null;
|
|
19
|
+
/** What the host keeps back beside model request `request` (priced as `asked`) for the steps it may still ask for while
|
|
20
|
+
* it streams (the rule's JudgeState.keepUsd): serve's wrap-up reserve for the session's own requests. Undefined: none. */
|
|
21
|
+
keepBackUsd?(request: Parameters<BeforeRequest>[0], asked: ModelCapRequest): number | undefined;
|
|
18
22
|
mode?: CapMode;
|
|
19
23
|
now?: () => number;
|
|
20
24
|
}
|
|
25
|
+
/** What prices a model request: its model and route, how its input was measured, the output it asks and needs at least,
|
|
26
|
+
* its fee, and whether it is the session's own answer (no side call, no host's request, no unanswered one). */
|
|
27
|
+
export type PricedRequest = Pick<Parameters<BeforeRequest>[0], "model" | "route" | "inputTokensMax" | "inputTokensCounted" | "outputTokensAsked" | "outputTokensLeast" | "feeUsd" | "side" | "host" | "unanswered">;
|
|
28
|
+
/** `request` as the rule prices it: the one place a request's model and the session's recent requests are chosen for it,
|
|
29
|
+
* so its admission, the wrap-up's note and what the run keeps back to answer (requestFigures) price it alike: its input
|
|
30
|
+
* read from the cache a recent request left warm (price.ts warmFrom), else uncached. */
|
|
31
|
+
export declare function capRequestOf(id: string, request: PricedRequest, options: Pick<BeforeRequestOptions, "modelOf" | "recentOf">): ModelCapRequest;
|
|
21
32
|
/** The host's beforeRequest for a CLI harness's session: the runner's spend and holds, judged by the one rule. */
|
|
22
33
|
export declare function beforeRequestOf(options: BeforeRequestOptions): BeforeRequest;
|