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

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 (38) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/host/proxy.d.ts +20 -4
  3. package/dist/host/proxy.js +53 -4
  4. package/dist/index.d.ts +1 -1
  5. package/dist/kernel/cap/index.d.ts +2 -2
  6. package/dist/kernel/cap/index.js +2 -2
  7. package/dist/kernel/cap/port.js +6 -3
  8. package/dist/kernel/cap/price.d.ts +6 -0
  9. package/dist/kernel/cap/price.js +14 -0
  10. package/dist/kernel/cap/rule.d.ts +8 -0
  11. package/dist/kernel/cap/rule.js +9 -0
  12. package/dist/kernel/cap/types.d.ts +2 -0
  13. package/dist/kernel/registry/computer-surface.generated.d.ts +9 -0
  14. package/dist/kernel/registry/computer-surface.generated.js +611 -0
  15. package/dist/kernel/registry/computer.d.ts +14 -0
  16. package/dist/kernel/registry/computer.js +67 -0
  17. package/dist/kernel/registry/defs.d.ts +1 -4
  18. package/dist/kernel/registry/defs.js +1 -13
  19. package/dist/kernel/registry/handoff.js +4 -4
  20. package/dist/kernel/registry/hands.d.ts +22 -115
  21. package/dist/kernel/registry/hands.js +0 -2
  22. package/dist/kernel/registry/index.d.ts +4 -4
  23. package/dist/kernel/registry/index.js +5 -5
  24. package/dist/kernel/registry/registry.d.ts +4 -5
  25. package/dist/kernel/registry/registry.js +27 -29
  26. package/dist/kernel/types.d.ts +2 -1
  27. package/dist/process/tools.d.ts +3 -1
  28. package/dist/process/tools.js +3 -3
  29. package/dist/run-booking.d.ts +3 -0
  30. package/dist/run-booking.js +7 -0
  31. package/dist/runner.d.ts +21 -2
  32. package/dist/runner.js +27 -10
  33. package/dist/types.d.ts +16 -1
  34. package/package.json +2 -2
  35. package/dist/kernel/registry/desktop.d.ts +0 -11
  36. package/dist/kernel/registry/desktop.js +0 -90
  37. package/dist/kernel/registry/phone.d.ts +0 -15
  38. package/dist/kernel/registry/phone.js +0 -135
package/CHANGELOG.md CHANGED
@@ -2,6 +2,44 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.37 (2026-11-13)
6
+
7
+ - 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)`.
8
+ - `computer_script` runs JavaScript in an isolate in serve whose only binding is `computer` (no network, no keys, no timers); its types are `spec/computer/computer.d.ts`, generated with the tools' schemas by `scripts/generate-computer-surface.mjs` (`--check` in CI). A model reads them compactly (no comments, one line a declaration); `computer_act`'s schema types its steps with no words, and its description declares them as TypeScript.
9
+ - A script's `computer.shell` and `computer.files` are held to the run's tool settings as the `bash`, `write` and `read` tools are (a deny or a read-only bash policy refuses inside the script; a setting that asks refuses, since a script can't wait for a person), and a refused step throws in the script, so the steps after it never run. Without the ui group a scroll goes as wheel clicks (about 120 pixels each), which every driver takes.
10
+ - pi offers its code mode (`codemode`) beside its tools with a desktop or a phone, `computer` bound in its scripts; the call is held to the computer kind's setting.
11
+ - In Codex's code mode a script's call of a computer tool answers the tool's value as JSON, its images' data in it; any other tool answers its words and a line saying its images were not sent (in code mode an image reaches a script only as text). A call a script repeats after a restart, of a computer tool that completed, gets that same JSON again.
12
+ - agentrun-serve's `computerMcp` serves a run's computer tools to an MCP client, each answer with `structuredContent`.
13
+ - The desktop-computer and phone-computer skills teach the route: observe, act by ref, check, and one script for steps already known.
14
+ - A run near its cap is told to wrap up again, on the runner, for every harness (part of #2080).
15
+ - Once what is left of the cap is about one typical request, the run's next model request tells the model, inside that request, to finish now ("This run's budget is about $X, …"). The note goes to the model only and never into the run's transcript.
16
+ - It is worked out from everything the run has spent and holds, including requests still in flight. A Claude Code or Codex run whose requests overlap is told on time, not late or never.
17
+ - It is told once per cap. A raised cap is told again when the run comes near the new cap.
18
+ - It composes with the cap's wrap-up as one story: the note tells the model what is left, and once what is left no longer covers what the run keeps back to answer (one typical step and the least answer), its tools stop. The note also comes due on that same rule, so the model is told no later than its first refused call.
19
+ - Kernel: `requestFigures(request, mode, now)` in the cap gives a main-model request's least, step-0 typical and worst cost, which the run's reserve is priced from.
20
+ - The Timeline shows the note as AgentRun's own row ("AgentRun: This run's budget is about $X, …"), written only once a request carrying it has been admitted.
21
+ - Kernel: `ModelPort` and the model proxy's hooks gain `noteReturned?(note)`. The proxy calls it when a request that took the host's note leaves before its admission (its client gone, a refusal, an error), so the host can give the note to the next request at once.
22
+ - Kernel, a change for anyone reading or implementing `ModelBooking`: it gains `heldUsd(): number | null`, the holds of the session's requests still in flight. It returns null (unknown, never 0) while one of them has no hold, and a reader must treat null as unknown. `spentUsd()` still counts answered requests only, so the run's total is `spentUsd()` plus `heldUsd()`. It also gains `boundUsd(): number`, what a cache miss adds to those holds (0 with none): the run's tools stop on the holds plus this, so the note counts both.
23
+ - A web_search setting of deny or ask now applies to a Claude Code or Codex run's own web search at its next search, including a run that started while it was allow. Before, the setting was read only when the run started, so a run that started with native search kept searching after the setting changed.
24
+ - Claude Code: each WebSearch asks the run's gate before it runs, as a host tool's call does. A deny refuses it in the gate's words. An ask parks the run on the person with nothing searched; once they allow it, the model's next search with the same query runs once, with no second card.
25
+ - Codex: its search runs inside the provider's model request, so its proxy reads web_search's setting before each request and offers the provider its search only while the setting is allow. A failed read offers no search.
26
+ - `SessionIO.permission(tool)` (agentrun-kernel) is the host's setting for a harness's own tool at the time of the read. The runner reads it from the store each time. `ProviderPolicy.apply` may return a promise.
27
+ - A runner run whose plane resolves web_search to native now gets the harness's own search (#2458). The runner had built the run's environment without its plane, so Claude Code and Codex runs on a runner never had it on.
28
+ - A web_search that resolves to the model provider's own search works again on the runner for pi (#2458). It used to answer "web_search has no model to search on" every time:
29
+ - A pi run's own web_search on an Anthropic or OpenAI model. That is what `auto` picks for pi, and `native` too. Each search now goes through the run's model proxy with the provider's search tool, and its searches are booked at the provider's price on top of its tokens.
30
+ - A learned workflow's call node whose web_search resolves native, on any harness.
31
+
32
+ Each run's search uses that run's own model route, never one shared by the whole process. Hand-written workflow agents were not affected: their web_search never resolves native. Both harness packages now export their `withWebSearches` price wrapper, and the Codex one its `webSearchUsd`. A claude-agent or codex run's own search is not switched on by this change.
33
+
34
+ A capped run holds a hosted search's fees with its tokens before the request is sent, at the most searches the request allows, so the fees can't pass the cap. The kernel's model proxy takes a policy's `feeMaxUsd(body)` and holds it as the request's `feeUsd`; a fee it can't bound leaves the request unmeasured. The proxy also hands `usageOf` the sent body as a second argument, so a pi request on OpenAI's Responses that offered no search reads 0 searches from its body, even when its answer names a search call.
35
+ - A capped run on the runner is priced the way the cap's `expected` mode says: each model request from the previous request of its session. The cache that request read or wrote counts at the cache-read price, and only its other input plus what the body grew by since counts at full price. Before, the runner gave the cap no previous request, so every step was held as a whole cache miss, and a run needed a cap several times what it spent (a 5-step Sonnet run that spends $0.04 needed $0.11). `strict` mode is unchanged: every token uncached. A side call (a title, a summary) is priced as a cache miss, as a host's own request already was.
36
+ - A pi run's cost counts every request it made. A learned workflow's model node, or a request on another model than the run's, is booked beside pi's own answers as a side call, and the run's view, its Timeline usage row and its stored cost now add it, where they read pi's answers alone (three requests booked at $0.000014 each read $0.000028). A request a lost runner left unanswered is booked cut once, however many of the next claim's bookings read it open: its hold and bound count once toward the cap, and its cost is unknown once, where a second booking could count it twice. A pi run's stored cost is now its booking's, as a CLI run's is: a run cancelled or stopped while its model's answer streamed reads its cost unknown (the cut request may be billed for what it streamed), never the $0 its cut answer carried.
37
+ - A capped run's cap counts what its learning spent on its behalf, so the run and its grades never pass the cap together.
38
+ - Before, a follow-up on a run that learned was held only to the run's own spend: an earlier round's grade, which runs as a learning run of its own, was not counted, and the run could end up past its cap by that grade.
39
+ - Every gate of the run now reads its own spend plus what its learning runs took: a grade that ended at its cost, and one still under way at its own cap, the most it may take. That covers the model and paid-tool gate on pi and on the CLI harnesses (claude-agent, codex, opencode), the end of a run whose spend passed its cap, the wrap-up note and the tools' wrap-up, the check before a later round looks back, and the cap each later grade runs under.
40
+ - A follow-up that doesn't fit parks the run for a raise, as at any spend limit. Its budget card counts the grades in what the run has spent. An uncapped run is unchanged.
41
+ - Kernel: `RunSessions.beside()`, when given, is added to the run's spend at each admission (`runBooking`).
42
+
5
43
  ## 0.1.0-beta.36 (2026-11-13)
6
44
 
7
45
  - The kernel and the Claude Agent test kit drop exports nothing in AgentRun used. From `@parcha/agentrun-kernel`: the `delegate` tool (`delegateTool`, `DELEGATE_TOOL`, `DELEGATE_RESULT_SCHEMA`, `delegateProblems` and the `DelegateAgent`, `DelegateEvent` and `DelegateOptions` types). From `./kernel`: the follow-up turn (`followUpOnce`, `followUpState`, `followUpKey`, `FOLLOW_UP_EFFECT`, `FOLLOW_UP_BUDGET_REACHED`, `FOLLOW_UP_CANCELLED` and their types) and `BASH_MAX_TIMEOUT_S`. From `./process`: `lastTurnEnd`, `summarizeBatch`, `batchTranscript` and `zodFromJsonSchema`. From `@parcha/agentrun-harness-claude/testing`: `lastUserText`. An embedder that imported one of them keeps its own copy: each was a small helper, or a feature the server never wired (a follow-up turn, a delegate tool). `zodShapeFromJsonSchema` stays.
@@ -34,11 +34,14 @@ export interface ProviderPolicy {
34
34
  header?(name: string, value: string): string | undefined;
35
35
  /** The body the provider gets for a request on `route`: throw a `ProxyRefusal` to refuse it. `context.host`: the
36
36
  * request is the host's own, beside the harness's (ModelProxy.sideKey), whose tools are its own client-side ones, not
37
- * the session's. */
38
- apply(body: unknown, route: ProxyRoute, context?: ProxyRequestContext): Record<string, unknown>;
37
+ * the session's. A policy that reads something of the host's first (a tool's permission now) answers with a promise,
38
+ * which may reject the same way. */
39
+ apply(body: unknown, route: ProxyRoute, context?: ProxyRequestContext): Record<string, unknown> | Promise<Record<string, unknown>>;
39
40
  /** The usage a completed response reports, if it reports one: from its whole text, or, for a long one, its first and
40
- * last 64 KiB (a provider may report input tokens as a stream starts and output tokens as it ends). */
41
- usageOf(text: string): ProxyUsage | undefined;
41
+ * last 64 KiB (a provider may report input tokens as a stream starts and output tokens as it ends). `body`: the body
42
+ * its request was sent with (`apply`'s), so what the request offered (a hosted tool it did not offer never ran) is
43
+ * read from the request, never guessed from the answer's words. */
44
+ usageOf(text: string, body?: Record<string, unknown>): ProxyUsage | undefined;
42
45
  /** Whether the provider stopped a completed answer on its content filter (a refusal), read from its text as `usageOf`
43
46
  * reads it, never by matching its words, and from `lineStarts`, the start of each of its last whole lines (16 KiB of
44
47
  * each, for a line longer than the text kept). Absent: the policy cannot tell, and no answer is read as stopped. */
@@ -76,6 +79,11 @@ export interface ProviderPolicy {
76
79
  * below 0 is no bound (unmeasured). Undefined: the body has no input bound the policy can state (a hosted tool that
77
80
  * reads pages into the input), so `inputTokensMax` is undefined, never 0 or the body's bytes alone. Absent: none. */
78
81
  serverInputOverhead?(body: Record<string, unknown>): number | undefined;
82
+ /** What the body `apply` returned may charge beside its tokens at most, in USD: a hosted tool's per-use fees, at the
83
+ * most uses the body allows it. Held with its tokens (ProxyRequest.feeUsd), so a cap reserves the fees before the
84
+ * request leaves, not only once its answer reports them. A figure that is not finite (the body allows its tool any
85
+ * number of uses), or a throw: the request's worst case is unknown, as an unmeasured input's is. Absent: none. */
86
+ feeMaxUsd?(body: Record<string, unknown>): number;
79
87
  /** The output tokens the body `apply` returned asks for at most (its own limit, as `apply` shaped it). Absent or
80
88
  * undefined: the body does not say. */
81
89
  outputAsked?(body: Record<string, unknown>): number | undefined;
@@ -177,9 +185,15 @@ export interface ProxyRequest {
177
185
  outputTokensAsked?: number;
178
186
  /** The least output it may be limited to and still answer (the policy's `outputLeast`). */
179
187
  outputTokensLeast?: number;
188
+ /** What it may charge beside its tokens at most (the policy's `feeMaxUsd`), in USD: held with them. */
189
+ feeUsd?: number;
180
190
  /** A side call, never its turn's own: on another model than the session's (a client's small-model call: a title, a
181
191
  * summary), or the host's own request beside the harness's (`host`). */
182
192
  side?: true;
193
+ /** On the session's model but no answer of the turn (the policy's `answers` reads it so: a title, a summary, a child's
194
+ * request). Still the turn's to book, but a conversation of its own: the cap never prices the session's next request
195
+ * from it, nor it from the session's. */
196
+ unanswered?: true;
183
197
  /** It carries the host's note (`ModelProxyHooks.note`), placed in its body: the host's to record once it is admitted. */
184
198
  noted?: true;
185
199
  /** The label of the side key it came under (ModelProxy.sideKey): the host's own request, beside the harness's. */
@@ -203,6 +217,8 @@ export interface ModelProxyHooks {
203
217
  * proxy asks only for a paid request on the session's model whose policy can place one (`addNote`), with that request
204
218
  * as its client sent it (NoteRequest: its input bound and output asks, measured before the note is placed). */
205
219
  note?(model: string, request?: NoteRequest): string | undefined;
220
+ /** The note `note` gave back (ModelPort.noteReturned): the request that took it left before `beforeRequest`. */
221
+ noteReturned?(note: string): void;
206
222
  }
207
223
  export interface ModelProxyOptions {
208
224
  policy: ProviderPolicy;
@@ -701,7 +701,28 @@ export async function startModelProxy(options, key) {
701
701
  };
702
702
  // The session's MCP door, mounted once here for whichever harness's client calls it (the call id from its fact).
703
703
  const mcpDoor = options.mcp && mcpRoute(options.mcp.session, { callIdMeta: options.mcp.client.callIdMeta, ...(options.mcp.keepaliveMs !== undefined ? { keepaliveMs: options.mcp.keepaliveMs } : {}) });
704
+ /** Serves one request. A note it took and did not bring to its admission (it left before `beforeRequest`: its client
705
+ * gone while it was counted, a refusal, an error) is given back to the host then, however it left, so the next request
706
+ * can take it at once. From its admission on the note is the admission's: told, or given back by its refusal. */
704
707
  const serve = async (req, res) => {
708
+ const taken = {};
709
+ try {
710
+ await serveRequest(req, res, taken);
711
+ }
712
+ finally {
713
+ if (taken.note !== undefined) {
714
+ const note = taken.note;
715
+ taken.note = undefined;
716
+ try {
717
+ hooks.noteReturned?.(note);
718
+ }
719
+ catch (error) {
720
+ say(`model proxy (${policy.id}): the host's note could not be given back`, { error: String(error?.message ?? error).slice(0, 200) });
721
+ }
722
+ }
723
+ }
724
+ };
725
+ const serveRequest = async (req, res, taken) => {
705
726
  // A request refused before its body is read is drained, so its client gets the answer instead of a reset.
706
727
  res.once("finish", () => { if (!req.complete)
707
728
  req.resume(); });
@@ -752,7 +773,7 @@ export async function startModelProxy(options, key) {
752
773
  let body;
753
774
  const headers = { "content-type": "application/json" };
754
775
  try {
755
- body = policy.apply(parseStrict(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))), route, host === undefined ? {} : { host });
776
+ body = await policy.apply(parseStrict(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))), route, host === undefined ? {} : { host });
756
777
  // The listed headers, as the policy keeps them (or refuses them), before the runner is asked.
757
778
  for (const name of route.headers ?? []) {
758
779
  const value = req.headers[name.toLowerCase()];
@@ -800,6 +821,10 @@ export async function startModelProxy(options, key) {
800
821
  request = {};
801
822
  }
802
823
  const note = hooks.note(asked, request);
824
+ // Taken: given back (serve) unless this request brings it to its admission, below. One the policy fails to place
825
+ // goes back too: this request goes without it.
826
+ if (note)
827
+ taken.note = note;
803
828
  if (note) {
804
829
  try {
805
830
  const without = body;
@@ -809,6 +834,11 @@ export async function startModelProxy(options, key) {
809
834
  }
810
835
  catch (error) {
811
836
  say(`model proxy (${policy.id}): the host's note could not be placed; the request goes without it`, { error: String(error?.message ?? error).slice(0, 200) });
837
+ taken.note = undefined;
838
+ try {
839
+ hooks.noteReturned?.(note);
840
+ }
841
+ catch { /* the host's to say */ }
812
842
  }
813
843
  }
814
844
  }
@@ -853,6 +883,19 @@ export async function startModelProxy(options, key) {
853
883
  say(`model proxy (${policy.id}): the policy could not read the body's output; its worst case is unmeasured`, { error: String(error?.message ?? error).slice(0, 200) });
854
884
  inputTokensMax = undefined;
855
885
  }
886
+ // What it may charge beside its tokens (a hosted tool's per-use fees), held with them. One the policy cannot bound
887
+ // leaves its worst case unknown, as an unmeasured input does.
888
+ let feeUsd = 0;
889
+ try {
890
+ const fee = policy.feeMaxUsd ? policy.feeMaxUsd(body) : 0;
891
+ if (figure(fee) === undefined)
892
+ throw new Error(`no bound on its fees (${String(fee)})`);
893
+ feeUsd = fee;
894
+ }
895
+ catch (error) {
896
+ say(`model proxy (${policy.id}): the request's fees have no bound; its worst case is unmeasured`, { error: String(error?.message ?? error).slice(0, 200) });
897
+ inputTokensMax = undefined;
898
+ }
856
899
  // The provider's credential and its headers come before the runner is asked: a request that could not be sent is
857
900
  // refused without being admitted, so it is never booked and spends no turn.
858
901
  let credential = "";
@@ -930,14 +973,20 @@ export async function startModelProxy(options, key) {
930
973
  }
931
974
  // This request's own admission, handed back to its booking (requests may be in flight together).
932
975
  let ticket;
976
+ // The note, if this request carries it, is its admission's from here: told once admitted, given back by a refusal.
977
+ if (noted)
978
+ taken.note = undefined;
933
979
  try {
934
980
  if (!route.free)
935
981
  ticket = await hooks.beforeRequest({
936
- // A side call: on another model than the session's, or the host's own (it counts toward no typical request).
937
- model: asked, inputTokensMax, ...(asked !== model || host !== undefined ? { side: true } : {}),
982
+ // A side call: on another model than the session's, or the host's own (it counts toward no typical request). One on
983
+ // the session's model that is no answer of the turn (a title, a summary, a child's: `answering`, the policy's
984
+ // answers) is `unanswered`: booked as any request, but a conversation of its own to the cap's expected pricing.
985
+ model: asked, inputTokensMax, ...(asked !== model || host !== undefined ? { side: true } : {}), ...(!answering && host === undefined ? { unanswered: true } : {}),
938
986
  ...(noted ? { noted: true, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}),
939
987
  ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }),
940
988
  ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }),
989
+ ...(feeUsd > 0 ? { feeUsd } : {}),
941
990
  ...(host === undefined ? {} : { host }),
942
991
  ...(inputTokensCounted ? { inputTokensCounted: true } : {}),
943
992
  ...(options.route === undefined ? {} : { route: options.route }),
@@ -1301,7 +1350,7 @@ export async function startModelProxy(options, key) {
1301
1350
  else {
1302
1351
  let unread = false;
1303
1352
  try {
1304
- usage = policy.usageOf(length <= USAGE_WINDOW ? tail : `${head}\n${lastOf(tail)}`);
1353
+ usage = policy.usageOf(length <= USAGE_WINDOW ? tail : `${head}\n${lastOf(tail)}`, body);
1305
1354
  }
1306
1355
  catch (error) {
1307
1356
  say(`model proxy (${policy.id}): the usage could not be read; the request is booked at an unknown cost`, { error: String(error?.message ?? error).slice(0, 200) });
package/dist/index.d.ts CHANGED
@@ -9,4 +9,4 @@ export type { HarnessRunReason } from "./errors.js";
9
9
  export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS, hostedTool } from "./types.js";
10
10
  export { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "./booking.js";
11
11
  export type { Booked, Ended, Priced } from "./booking.js";
12
- export type { AdapterCapabilities, AdapterEvent, AdapterSession, AgentAdapter, AdapterFacts, GateAnswer, GateCall, SessionPort, Wire, HarnessEvent, HostTool, McpCallResult, McpClient, McpTool, ToolImage, JsonValue, ModelPort, ModelTicket, ModelRequest, ModelUsage, NoteRequest, NodeRequest, SessionIO, SessionMcp, SessionRecord, SessionSpec, SessionState, SessionStore, SessionWriter, TurnStatus, } from "./types.js";
12
+ export type { AdapterCapabilities, AdapterEvent, AdapterSession, AgentAdapter, AdapterFacts, GateAnswer, GateCall, SessionPort, Wire, HarnessEvent, HostTool, McpCallResult, McpClient, McpTool, ToolImage, JsonValue, ModelPort, ModelTicket, ModelRequest, ModelUsage, NoteRequest, NodeRequest, SessionIO, SessionMcp, SessionRecord, SessionSpec, SessionState, SessionStore, SessionWriter, ToolPermission, TurnStatus, } 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
- export { capRule, noteFor, type Judged, type JudgeState, type NoteState } from "./rule.js";
2
+ export { capRule, noteFor, requestFigures, type Judged, type JudgeState, type NoteState } from "./rule.js";
3
3
  export { beforeRequestOf, type BeforeRequestOptions } 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, pricingOf, ratesFor, requestPrice } from "./price.js";
5
+ export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput, previousAfter, pricingOf, ratesFor, requestPrice } 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";
@@ -1,10 +1,10 @@
1
1
  // The kernel cap (kernel tangle 2: the cap lives in the kernel, the same for every harness). Not exported from the
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
- export { capRule, noteFor } from "./rule.js";
4
+ export { capRule, noteFor, requestFigures } from "./rule.js";
5
5
  export { beforeRequestOf } 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, pricingOf, ratesFor, requestPrice } from "./price.js";
7
+ export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput, previousAfter, pricingOf, ratesFor, requestPrice } 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";
@@ -21,9 +21,12 @@ export function beforeRequestOf(options) {
21
21
  if (request.paid?.owed && isFigure(request.feeUsd ?? 0))
22
22
  return { holdUsd: request.feeUsd ?? 0 };
23
23
  const model = options.modelOf(request.model, request.route) ?? unpriced(request.model);
24
- // A request the host sends beside the harness's own (its host label: a learned workflow's node) is another
25
- // conversation's prompt: nothing of the session's cache is read for it, so it is priced as a cache miss.
26
- const previous = request.host === undefined ? options.previousOf?.(request.model) : undefined;
24
+ // A request the host sends beside the harness's own (its host label: a learned workflow's node), a side call, or one
25
+ // that is no answer of the turn (a title, a summary, a child's) is another conversation's prompt: nothing of the
26
+ // session's cache is read for it, so it is priced as a cache miss.
27
+ // Its bound must be measured as the next request's is (a provider's count, or bytes): their difference is no growth.
28
+ const before = request.host === undefined && !request.side && !request.unanswered ? options.previousOf?.(request.model) : undefined;
29
+ const previous = before && (before.counted === true) === (request.inputTokensCounted === true) ? before : undefined;
27
30
  const asked = {
28
31
  kind: "model",
29
32
  id: `turn-${request.turn}`,
@@ -31,6 +31,12 @@ export declare function pricingOf(price: ModelPrice): Pricing;
31
31
  * after the cache plus what the body grew by at full price. Undefined (all of it uncached) with no previous request, one
32
32
  * on another model, one that ended CACHE_WARM_MS or more ago, or a clock that reads before its end. */
33
33
  export declare function expectedInput(bound: number, previous: Previous | undefined, now: number, model: string): InputParts | undefined;
34
+ /** The session's previous request once `ended` has answered: `ended` itself when it continues the conversation (the first
35
+ * request, another model's, one measured another way, or one at least as big as the previous), none when it is smaller.
36
+ * A smaller body is a compaction or another conversation's (a child's, which the proxy cannot tell from the root's):
37
+ * history resets, so it never sticks on a request the conversation has left and never prices the next from another's
38
+ * cache. The next request is priced uncached (one miss window), then warm from its own predecessor. */
39
+ export declare function previousAfter(previous: Previous | undefined, ended: Previous): Previous | undefined;
34
40
  /** A request priced under `mode`: `cost(output)`, what it is held at (its expected input, never more than uncached), and
35
41
  * `worst(output)`, its input uncached; each with its hosted tools' most fee. */
36
42
  export declare function requestPrice(pricing: Pricing, bound: number, previous: Previous | undefined, now: number, mode: CapMode, model: string, feeUsd?: number): {
@@ -53,8 +53,22 @@ export function expectedInput(bound, previous, now, model) {
53
53
  const gap = now - previous.endedAt;
54
54
  if (!(gap >= 0 && gap < CACHE_WARM_MS))
55
55
  return undefined;
56
+ // A conversation only grows between its own requests: a smaller body is not one (a compaction, or another conversation's),
57
+ // so none of the previous request's cache is known to be read by it. Priced uncached, never under what it can cost.
58
+ if (bound < previous.boundTokens)
59
+ return undefined;
56
60
  return { cached: previous.cachedTokens, fresh: previous.inputTokens + Math.max(0, bound - previous.boundTokens) };
57
61
  }
62
+ /** The session's previous request once `ended` has answered: `ended` itself when it continues the conversation (the first
63
+ * request, another model's, one measured another way, or one at least as big as the previous), none when it is smaller.
64
+ * A smaller body is a compaction or another conversation's (a child's, which the proxy cannot tell from the root's):
65
+ * history resets, so it never sticks on a request the conversation has left and never prices the next from another's
66
+ * cache. The next request is priced uncached (one miss window), then warm from its own predecessor. */
67
+ export function previousAfter(previous, ended) {
68
+ if (previous && previous.model === ended.model && previous.counted === ended.counted && ended.boundTokens < previous.boundTokens)
69
+ return undefined;
70
+ return ended;
71
+ }
58
72
  /** A request priced under `mode`: `cost(output)`, what it is held at (its expected input, never more than uncached), and
59
73
  * `worst(output)`, its input uncached; each with its hosted tools' most fee. */
60
74
  export function requestPrice(pricing, bound, previous, now, mode, model, feeUsd = 0) {
@@ -34,6 +34,14 @@ declare function judge(request: ModelCapRequest | ToolCapRequest, state: JudgeSt
34
34
  export declare const capRule: {
35
35
  judge: typeof judge;
36
36
  };
37
+ /** A main-model request's figures as the cap prices it, for what a run keeps back to answer: its least (an answer at the
38
+ * fewest output tokens the cap admits it at), its step-0 typical cost (its input and a WRAP_UP_STEP0_ANSWER_TOKENS answer,
39
+ * the wrap-up's own) and its worst (its full asked output, its bound included). Undefined when it cannot be priced. */
40
+ export declare function requestFigures(request: ModelCapRequest, mode: CapMode, now: number): {
41
+ leastUsd: number;
42
+ step0Usd: number;
43
+ worstUsd: number;
44
+ } | undefined;
37
45
  /** What the wrap-up reads: the cap, spend and holds as admission counts them, the run's own priced answers on the
38
46
  * request's model, and whether it was told. */
39
47
  export type NoteState = {
@@ -71,6 +71,15 @@ function judge(request, state) {
71
71
  }
72
72
  /** The rule's entry, called through this object by every path. */
73
73
  export const capRule = { judge };
74
+ /** A main-model request's figures as the cap prices it, for what a run keeps back to answer: its least (an answer at the
75
+ * fewest output tokens the cap admits it at), its step-0 typical cost (its input and a WRAP_UP_STEP0_ANSWER_TOKENS answer,
76
+ * the wrap-up's own) and its worst (its full asked output, its bound included). Undefined when it cannot be priced. */
77
+ export function requestFigures(request, mode, now) {
78
+ const p = priced(request, mode, now);
79
+ if (!p)
80
+ return undefined;
81
+ return { leastUsd: p.cost(p.least), step0Usd: p.cost(Math.min(p.asked ?? 0, WRAP_UP_STEP0_ANSWER_TOKENS)), worstUsd: p.worst(p.asked ?? p.least) };
82
+ }
74
83
  /** The wrap-up for `request`, the run's next main-model request measured before the note is placed: due under three times
75
84
  * the typical cost (step 0: its input and a 4,096-token answer) or twice its least, not yet told, never for a side call,
76
85
  * and never when the request fits what is left only without the note's bytes. */
@@ -34,6 +34,8 @@ export interface Previous {
34
34
  readonly cachedTokens: number;
35
35
  readonly inputTokens: number;
36
36
  readonly boundTokens: number;
37
+ /** Its bound was its provider's count, not its bytes: used only for a next request bounded the same way. */
38
+ readonly counted?: boolean;
37
39
  readonly endedAt: number;
38
40
  }
39
41
  /** A model request about to be sent, from any harness (pi in process, a CLI's through the model proxy). */
@@ -0,0 +1,9 @@
1
+ /** Each per-step tool's parameters, as JSON Schema. */
2
+ export declare const COMPUTER_TOOL_SCHEMAS: {
3
+ readonly [tool in "computer_observe" | "computer_act" | "computer_screenshot" | "computer_script"]: object;
4
+ };
5
+ /** computer_act's steps as TypeScript, for its description: its schema types them, with no words. */
6
+ export declare const ACT_STEPS = "type UiStep = { press: UiRef; } | { set: UiRef; value: string; } | { perform: UiRef; action: string; } | { click: UiRef | Point; button?: \"left\" | \"right\"; count?: 1 | 2 | 3; } | { type: string; into?: UiRef; } | { key: string; } | { nav: \"back\" | \"home\" | \"app_switch\"; } | { scroll: UiRef | Point; dx?: number; dy?: number; } | { drag: Point[]; ms?: number; }; type UiRef = string; type Point = [ x: number, y: number ];";
7
+ /** The declarations a script on a computer with these groups reads: the types its members reach, Computer with only
8
+ * the members its groups offer, and `declare const computer`, one line each. */
9
+ export declare function computerDeclarations(groups: readonly string[]): string;