@parcha/agentrun-kernel 0.1.0-beta.62 → 0.1.0-beta.64

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 CHANGED
@@ -2,6 +2,34 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.64 (2026-11-26)
6
+
7
+ - On a Linux desktop, the check of whether computerd's own user could change an app's desktop file asks the kernel too (`faccessat2` as the effective user, no link followed) for each folder on the way and for the file, beside the mode bits, so an ACL entry or a FUSE file system's own rule that lets the user write is seen. `apps.launch` names a refused desktop file from that one check, by the id asked for, and no longer opens every desktop file again to find it: that open followed links and waited forever on a named pipe called `*.desktop`. A refused file is never read, so the name or program it gives finds no app: asked by that name, `apps.launch` answers `not_found`, and by its id, `denied`. `apps.terminate` ends an app this computerd launched though its desktop file is refused now, as when a file of its id was written ahead of it since; before, it answered `denied` and the app ran on to the computer's end. The computer wire spec says that `apps.launch` answers `denied` for such an app and that `apps.list` leaves it out. A correction to the previous release's note on desktop files: refusing an app whose desktop file computerd's own user could change closes the desktop-file route only, not `write` plus apps as a whole. An app reads its config from the user's home, which `write` reaches, so an agent given both can still reach a shell through an app it opens, and the remedy stays granting no apps on such a desktop. The words every offer of a computer's ops carries (`GUI_REACH`), the serve README and the desktop kind skill say that where `write` is granted, `apps.open` reaches what a shell does with or without a URL or a path, since an app reads its config from the user's home. <!-- changes/apps-launch-refusal-kernel-check.md -->
8
+ - pi's turn budget now outlasts a process that stops in the turn, as Claude's, Codex's, ACP's and OpenCode's do: a pi session opened again takes the turn back from its conversation (its last answer's usage and calls, and each result handed since) before a call claims, so the calls a resume answers split what their answer left instead of each taking its whole bound. A read of the turn that fails runs no call: the call is an error naming why, and the next call reads again. <!-- changes/turn-budget-resume-pi-scripts.md -->
9
+ - A result goes back to the harness only once its length is in the session's journal (`TurnBudget.kept`): a process that stops right after it was handed no longer loses its part of the turn, which a resumed call would claim again. A length the journal could not keep fails the call instead of handing its result.
10
+ - A result settles at the length it was handed: a result of at most 400 characters, whole under any bound, and a refusal's words now hold what they took, so the calls after them split only what is left.
11
+ - A code-mode script's JSON read too large for its bound is handed as a note alone (`[read cut: this result is M characters of JSON, past the N ...]`), since part of a JSON document does not parse: on a 16k-32k window, a script that parses it fails naming the cut instead of on a character in the middle, and the model reads that it should ask for less. A read that is not JSON keeps its start and its note, as before.
12
+ - A failed call's error refused for a window too small to cut it in keeps its first line (as much as fits beside the note in the 400 characters a result always keeps whole), so the model reads what went wrong.
13
+ - A raise that reaches an agentic run's claim while that claim takes a retry of the raise that resumed the run (a raise covering the run's next park, during the retry's commit) waits for the run's next claim too, as one reaching a claim parking the run again does. Before, the claim could take it and park, the run left with nothing to wake it.
14
+ - The run's view shows the cap park a run stands at as its runner reads it: a raise entry clears only the park it names. A raise that names none (checked against the run while it worked) no longer hides a park journaled before it.
15
+ - `@parcha/agentrun-kernel/kernel` exports `savePathOf(given)`, the function `computer_screenshot` resolves its `save_as` with: a path relative to the run's folder, normalized (posix), inside it, ending `.png`, or a thrown refusal in words. A host's tool gate can then hold a `save_as` at the path the screenshot is saved at, not by a reading of its own. AgentRun's serve does this for a folder an MCP tool's file setting files its answers in. Nothing else changes: the screenshot resolves `save_as` as before. <!-- changes/kernel-save-path-of.md -->
16
+
17
+ ## 0.1.0-beta.63 (2026-11-26)
18
+
19
+ - On a Linux desktop, `apps.list` leaves out, and `apps.launch` and `apps.terminate` refuse as `denied` naming the file and why, an app whose desktop file computerd's own user could change: on the way to it from `/`, every symbolic link followed, the user owns a folder, a link or the file (`~/.local/share/applications` among them), the mode bits let it write the file or a folder holding one of them, or computerd runs as root. The entry is read from the file that walk checked, opened without following a link and refused if another took its place. An app runs what its desktop file says, so before, an agent given `write` and the apps group, with bash denied and exec off, could write a desktop file there and `apps.launch` it, or shadow a system app's id, and run any command. Apps installed under the user's home, as on a paired machine's `~/.local/share/applications`, are no longer listed, and a computerd that runs as root lists none. <!-- changes/apps-launch-writable-desktop-files.md -->
20
+
21
+ The surface's `apps.open` (a script's `computer.apps.open`) refuses a `url` that starts with `-`, after leading whitespace too, as `invalid` before the call leaves it, in computerd's words, so a paired Linux machine on an older computerd doesn't hand it to the app as a flag. The computer README and `AppsLaunchParams.url`'s comment say what a `url` is on Linux. The words every offer of a computer's ops carries (`GUI_REACH`) and the desktop kind skill say that `apps.open` with a path reaches what a shell does for a file the agent wrote too, where `write` is granted.
22
+ - On a Linux desktop, `apps.launch` (a script's `computer.apps.open`) refuses a `url` that is neither an absolute URL with a scheme (`https://…`, `file:///…`) nor an absolute path, and starts nothing. Before, computerd put the `url` into the app's argv as it was: one starting with `-`, after leading whitespace too, reached the app as a flag (Chromium's `--renderer-cmd-prefix` runs a command, on a computer whose exec is off), and a relative path reached it as a file. A `url` starting with `-` is refused `invalid` in words of its own: `starts with "-": the app would take it as a flag, not a url`. The macOS and Android daemons already took only a URL with a scheme, handed to the OS rather than to an argv. <!-- changes/apps-open-url-guard.md -->
23
+
24
+ The words every offer of a computer's ops carries (`GUI_REACH`) now say that `apps.open` with a URL or a path, not only a `file://` URL, reaches what the shell and the file ops do. serve's README and the desktop kind skill no longer say that every op the gate refuses whatever its arguments is left out of `computer_op`'s list: only the ops held to a tool (the file ops, `shell.run`, `processes.start`) are; apps and raw input stay.
25
+ - A tool result is held to the model's context window, not only to the fixed 120,000-character bound: a model with a small window (an Ollama model at 65,536 tokens, a 16k one) is never handed a result that fills its context. <!-- changes/tool-result-window-bound.md -->
26
+ - `boundResult(text, budget?)` takes the model's window (`{ contextWindow, baseInputTokens? }`): a result may take at most a quarter of what the window leaves (`RESULT_WINDOW_SHARE`), at three characters a token (`RESULT_CHARS_PER_TOKEN`), and never more than `HOST_RESULT_MAX_CHARS`. Past that it is cut with a note saying it was cut to fit the window and how to read on; a window too small for any cut refuses the result in words, and a result of at most 400 characters (`RESULT_ALWAYS_WHOLE_CHARS`) always stands whole, so bounding a bound changes nothing. With no window the bound is exactly as before. `resultMaxChars(budget)` gives the bound, and `boundTo(text, max)` cuts to a given bound, saying how (`ResultBound`: the characters kept, the whole length, the bound).
27
+ - `SessionSpec.contextWindow` carries the session model's window, and each harness adapter (Claude, Codex, ACP, OpenCode) takes a `contextWindow` option for when the host passes none; Codex and OpenCode are told that window in place of their 272,000 guess. A Codex script cut off by a crash is answered within the same bound (`recoveryMaxChars`), not `EXEC_RECOVERY_MAX_CHARS`.
28
+ - agentrun-serve puts the run's model window from its catalog on every session, and pi now holds every tool result to it too: a host tool's and a pi-native one's (web_fetch, web_search, the browser's), which before reached the model up to pi's own output limits. What a host tool streams while it runs is held to the bound too (`boundedProgress`), since pi writes a call cut off past its restart limit from that text, without its hooks.
29
+ - A turn's results together fit what the window has left (`TurnBudget`, `ResultBudget.turn`): from what the context already holds (the last request's input tokens and its answer's output, else the session's system prompt and tool schemas counted with o200k), less the room kept for the model's answer (`answerReserve`: a quarter of the window, at most `ANSWER_RESERVE_MAX_TOKENS`, 16,384 tokens), each call the model made takes the smaller of its own bound and what is left over the calls still unanswered, so parallel calls split it, and below the least a cut keeps a result is refused in words. The kernel owns the rule; the session's model proxy reports each answer's facts (`ModelProxyOptions.turn`, its calls counted from the stream by `toolCallsIn`) for Claude, Codex, OpenCode and Goose, and pi and Claude Code on a person's login report them from their own hooks (pi's afterResponse, the login's stream booking). `windowBudget(window, system?)` builds the budget with its turn. A call whose result goes to the harness's own tool rather than the model (`ToolBridgeOptions.outsideTurn`: Codex's code-mode script calls) takes the per-result bound alone, outside the turn's split.
30
+ - The bridge records each cut it hands a harness (`bound:<callId>`, `boundKey`), and a replay of the call is cut by that record. Codex compares a nested call's two records on those lengths, never on the note's words; `boundOf` is gone. A session written before the record still agrees where Codex got the host's bound's cut, as before.
31
+ - On Claude, Codex, ACP and OpenCode, a turn's budget outlasts a process that stops in the turn (a park, a crash): each answer's facts and each result's length as it was handed go to the session's journal as they happen (`journalTurn`, `TURN_STREAM`), and a budget that has read no answer yet takes them back before any call claims (`TurnBudget.restore`). The calls a resume answers split what their answer left, and a result handed before the stop keeps its part. Codex's recovered script outputs claim their room in the turn too and are held to that claim (`ResultBudget.maxChars`). pi's turn budget is not journaled yet: a pi session opened again starts a fresh one, and each result there keeps its per-result bound.
32
+
5
33
  ## 0.1.0-beta.62 (2026-11-26)
6
34
 
7
35
  **Breaking:**
@@ -2,6 +2,7 @@ import { type IncomingHttpHeaders } from "node:http";
2
2
  import { type CapCut, type NoteRequest } from "../types.js";
3
3
  import { type Ended } from "../booking.js";
4
4
  import type { BilledRequest } from "./overhead.js";
5
+ import { type TurnBudget } from "../process/turn-budget.js";
5
6
  /** A route a policy admits: its method, its exact path, and the request headers forwarded with it. */
6
7
  export interface ProxyRoute {
7
8
  readonly method: string;
@@ -285,6 +286,11 @@ export interface ModelProxyHooks {
285
286
  export interface ModelProxyOptions {
286
287
  policy: ProviderPolicy;
287
288
  hooks: ModelProxyHooks;
289
+ /** The session's turn budget (the harness's ResultBudget.turn): each answer of the turn's (ProviderPolicy.answers, the
290
+ * harness's own, never the host's) opens it with its facts, the input tokens its request held (the provider's usage,
291
+ * cached input included, else the request's input bound), its output, and the client tool calls it made, read from its
292
+ * stream. A tool call waits while an answer is read (TurnBudget.ready), so its result is never bound on the turn before. */
293
+ turn?: TurnBudget;
288
294
  /** The session's model, as the runner names it to `beforeRequest`. The policy fixes the body's model. */
289
295
  model: string;
290
296
  /** This proxy's route among the session's, told to `beforeRequest` with each request (ModelRequest.route) so the host
@@ -20,6 +20,7 @@ import { CONTENT_FILTERED } from "../types.js";
20
20
  import { isConnectCode, isGatewayTimeout, rejectionCode } from "../booking.js";
21
21
  import { SPEND_CAP_REACHED } from "../kernel/cap/words.js";
22
22
  import { onOpenRouter, openRouterAttribution } from "./openrouter-attribution.js";
23
+ import { toolCallsIn, toolCallsInBody } from "../process/turn-budget.js";
23
24
  /** Whether a request's admission refused it for the run's spend cap, read from the error's fields alone: the cap's own
24
25
  * error (CapRefused, its `code`), or the runner's stop for the cap's verdict (HarnessRunError, its `refusal`: the
25
26
  * verdict's Refusal.code). Never from its words. */
@@ -1387,7 +1388,11 @@ export async function startModelProxy(options, key) {
1387
1388
  let filteredTold = false;
1388
1389
  /** Called once the request is booked, when its answer was read on after its stop (the proxy's close waits for it). */
1389
1390
  let drained;
1391
+ /** The turn this answer opens (ModelProxyOptions.turn), while it is read; and the client tool calls its stream started. */
1392
+ let turnSpan;
1393
+ let toolCalls = 0;
1390
1394
  const settled = () => {
1395
+ turnSpan?.end();
1391
1396
  if (!drained)
1392
1397
  return;
1393
1398
  draining.delete(controller);
@@ -1493,6 +1498,9 @@ export async function startModelProxy(options, key) {
1493
1498
  };
1494
1499
  try {
1495
1500
  // From here a paid request may be paid, so every way out below books it exactly once.
1501
+ // The turn's answer is read from here: a tool call the client makes on it waits for its facts.
1502
+ if (answering && host === undefined && !route.free && options.turn)
1503
+ turnSpan = options.turn.begin();
1496
1504
  let upstream = await forward(`${origin}${route.path}${query ? `?${query}` : ""}`, { method: route.method, headers, body: sent, signal: controller.signal });
1497
1505
  // The provider answered (and a paid request was paid): a host callback that throws must not lose the answer or
1498
1506
  // its booking.
@@ -1634,6 +1642,8 @@ export async function startModelProxy(options, key) {
1634
1642
  lineLength += part.length;
1635
1643
  line = lineLength <= USAGE_WINDOW ? line + part : "";
1636
1644
  if (at < lines.length - 1) {
1645
+ if (turnSpan && upstream.ok && lineLength <= USAGE_WINDOW)
1646
+ toolCalls += toolCallsIn(line);
1637
1647
  starts.push(lineStart);
1638
1648
  if (starts.length > LINE_STARTS)
1639
1649
  starts.shift();
@@ -1793,6 +1803,13 @@ export async function startModelProxy(options, key) {
1793
1803
  // An answer of the client's own that reached it whole and reported its usage: what its whole input billed, kept
1794
1804
  // with the body it was sent with, for the session's next request on its model (policy.inputAfter).
1795
1805
  const billedInput = usage.input + usage.cacheRead + (usage.cacheWrite ?? 0);
1806
+ // The turn's facts, from an answer that reached its client whole: its input as billed (else the request's bound, the
1807
+ // provider's or the local count), its output, and its calls (a whole JSON body's read from it whole).
1808
+ if (turnSpan && answered?.ok && failed === undefined && translated === undefined && refusedIn === undefined) {
1809
+ const calls = wholeBody ? (length <= USAGE_WINDOW ? toolCallsInBody(tail) : undefined) : toolCalls;
1810
+ const read = !unread && Number.isSafeInteger(billedInput) && billedInput > 0;
1811
+ turnSpan.open({ ...(read ? { inputTokens: billedInput, outputTokens: usage.output } : inputTokensMax === undefined ? {} : { inputTokens: inputTokensMax }), ...(calls === undefined ? {} : { calls }) });
1812
+ }
1796
1813
  if (answered?.ok && !stoppedByClient && !unread && failed === undefined && translated === undefined && refusedIn === undefined && host === undefined && Number.isSafeInteger(billedInput) && billedInput > 0)
1797
1814
  billed.set(asked, { body, inputTokens: billedInput });
1798
1815
  // The reasoning an answer of the session's model reported: the most one answer reasoned is what a later request's
@@ -15,9 +15,13 @@ export declare const unsavedScreenshot: <T extends {
15
15
  readonly description: string;
16
16
  readonly parameters: object;
17
17
  }>(def: T) => T;
18
+ /** `given` as a path in the run's folder a screenshot is saved to (relative, inside it, ending .png), normalized; any
19
+ * other is refused in words. Exported so a host's gate holds a save_as as it is saved, not by a reading of its own. */
20
+ export declare function savePathOf(given: unknown): string;
18
21
  /** What every offer of a computer's ops says of its screen: leaving bash, read or write out does not keep a script from
19
- * a terminal app, a file manager, or an app opened on a file:// URL. */
20
- export declare const GUI_REACH = "Input ops on a computer with a terminal app or a GUI file manager, and apps.open with a file:// URL, can do what a shell or the file ops do, whatever bash's, read's or write's setting.";
22
+ * a terminal app, a file manager, or an app opened on a URL or a path; and where write is granted, an app opened on
23
+ * neither runs with config the agent can write (an app reads its config from the user's home). */
24
+ export declare const GUI_REACH = "Input ops on a computer with a terminal app or a GUI file manager, and apps.open with a URL or a path, can do what a shell or the file ops do, whatever bash's, read's or write's setting; where write is granted, apps.open can do what a shell does even with no URL or path, since an app reads its config from the user's home.";
21
25
  /** The ops computer_op runs on a computer with `groups`. */
22
26
  export declare function computerOpsFor(groups: readonly string[]): readonly string[];
23
27
  /** The tools a computer with `groups` offers: observe and act with the ui group, or a screen (observe) and input (act)
@@ -50,8 +50,8 @@ const SCREENSHOT_PARAMETERS = (() => {
50
50
  * no save_as, which the run's gate refuses there. */
51
51
  export const unsavedScreenshot = (def) => ({ ...def, description: SCREENSHOT_ALONE, parameters: COMPUTER_TOOL_SCHEMAS.computer_screenshot });
52
52
  /** `given` as a path in the run's folder a screenshot is saved to (relative, inside it, ending .png), normalized; any
53
- * other is refused in words. */
54
- function savePathOf(given) {
53
+ * other is refused in words. Exported so a host's gate holds a save_as as it is saved, not by a reading of its own. */
54
+ export function savePathOf(given) {
55
55
  if (typeof given !== "string" || given === "" || posix.isAbsolute(given) || given.includes("\\"))
56
56
  throw new Error(`save_as is a path relative to the run's folder (shots/home.png): not ${JSON.stringify(given)}`);
57
57
  const path = posix.normalize(given);
@@ -73,8 +73,9 @@ const OP_ARGS = Object.freeze({
73
73
  "files.stat": "{path}",
74
74
  });
75
75
  /** What every offer of a computer's ops says of its screen: leaving bash, read or write out does not keep a script from
76
- * a terminal app, a file manager, or an app opened on a file:// URL. */
77
- export const GUI_REACH = "Input ops on a computer with a terminal app or a GUI file manager, and apps.open with a file:// URL, can do what a shell or the file ops do, whatever bash's, read's or write's setting.";
76
+ * a terminal app, a file manager, or an app opened on a URL or a path; and where write is granted, an app opened on
77
+ * neither runs with config the agent can write (an app reads its config from the user's home). */
78
+ export const GUI_REACH = "Input ops on a computer with a terminal app or a GUI file manager, and apps.open with a URL or a path, can do what a shell or the file ops do, whatever bash's, read's or write's setting; where write is granted, apps.open can do what a shell does even with no URL or path, since an app reads its config from the user's home.";
78
79
  /** computer_op's words for the ops it offers. */
79
80
  const opWords = (ops) => `One of the computer's ops no other tool runs, as a script's \`computer\` calls it: ${ops.map((op) => (OP_ARGS[op] ? `${op} ${OP_ARGS[op]}` : op)).join(", ")}. An op this computer does not offer is refused. ${GUI_REACH}`;
80
81
  const OP = opWords(Object.keys(COMPUTER_OPS));
@@ -2,7 +2,7 @@ export { BACKGROUND_EXECUTORS, endBackground, NEEDS_A_COMPUTER, NO_SHELL } from
2
2
  export { boundedBash } from "./bash.js";
3
3
  export { bashTimeoutWords, CAPABILITY_KINDS, hostToolDefs } from "./defs.js";
4
4
  export type { ShellPlace, ToolDef } from "./defs.js";
5
- export { COMPUTER_OP_TOOL, COMPUTER_OPS, COMPUTER_TOOLS, computerExecutors, computerOpsFor, computerToolDefs, computerToolsFor, GUI_REACH, STEP_TOOL_OPS, unsavedScreenshot, withoutOps } from "./computer.js";
5
+ export { COMPUTER_OP_TOOL, COMPUTER_OPS, COMPUTER_TOOLS, computerExecutors, computerOpsFor, computerToolDefs, computerToolsFor, GUI_REACH, savePathOf, STEP_TOOL_OPS, unsavedScreenshot, withoutOps } from "./computer.js";
6
6
  export { COMPUTER_TOOL_SCHEMAS, computerDeclarations } from "./computer-surface.generated.js";
7
7
  export { defaultPermissionOf, SHELL_FAMILY, SHELL_WATCHERS, shellPermission, shellToolOf } from "./gate.js";
8
8
  export type { Permission } from "./gate.js";
@@ -5,7 +5,7 @@
5
5
  export { BACKGROUND_EXECUTORS, endBackground, NEEDS_A_COMPUTER, NO_SHELL } from "./background.js";
6
6
  export { boundedBash } from "./bash.js";
7
7
  export { bashTimeoutWords, CAPABILITY_KINDS, hostToolDefs } from "./defs.js";
8
- export { COMPUTER_OP_TOOL, COMPUTER_OPS, COMPUTER_TOOLS, computerExecutors, computerOpsFor, computerToolDefs, computerToolsFor, GUI_REACH, STEP_TOOL_OPS, unsavedScreenshot, withoutOps } from "./computer.js";
8
+ export { COMPUTER_OP_TOOL, COMPUTER_OPS, COMPUTER_TOOLS, computerExecutors, computerOpsFor, computerToolDefs, computerToolsFor, GUI_REACH, savePathOf, STEP_TOOL_OPS, unsavedScreenshot, withoutOps } from "./computer.js";
9
9
  export { COMPUTER_TOOL_SCHEMAS, computerDeclarations } from "./computer-surface.generated.js";
10
10
  export { defaultPermissionOf, SHELL_FAMILY, SHELL_WATCHERS, shellPermission, shellToolOf } from "./gate.js";
11
11
  export { answerOf, exitCodeOf, needsKindWords } from "./hands.js";
@@ -8,3 +8,4 @@ export * from "./tail.js";
8
8
  export * from "./zod.js";
9
9
  export * from "./settle.js";
10
10
  export * from "./resume.js";
11
+ export * from "./turn-budget.js";
@@ -10,3 +10,4 @@ export * from "./tail.js";
10
10
  export * from "./zod.js";
11
11
  export * from "./settle.js";
12
12
  export * from "./resume.js";
13
+ export * from "./turn-budget.js";
@@ -1,5 +1,6 @@
1
1
  import { type DriveContext, type EffectError, type HostTool, type ReplayPolicy } from '../kernel/index.js';
2
2
  import { type GateAnswer, type GateCall, type HostTool as AdapterTool, type JsonValue, type ToolImage } from '../types.js';
3
+ import { TurnBudget } from './turn-budget.js';
3
4
  /**
4
5
  * The tool bridge: `HostTool`s as a harness-neutral list a port maps onto its
5
6
  * harness's own tool mechanism (Codex's dynamic tools).
@@ -13,9 +14,12 @@ import { type GateAnswer, type GateCall, type HostTool as AdapterTool, type Json
13
14
  * tools turned off, these are its only tools, so every side effect it can
14
15
  * cause has an intent in the log before it runs.
15
16
  *
16
- * Every result a harness gets passes here, so here it is held to the host's
17
- * bound: a text past HOST_RESULT_MAX_CHARS keeps its start and says where it
18
- * was cut (`boundResult`), the call's record keeping it whole.
17
+ * Every result a harness gets passes here, so here it is held to the bound:
18
+ * HOST_RESULT_MAX_CHARS, or less where the harness passes its model's context
19
+ * window (`ToolBridgeOptions.budget`, `resultMaxChars`), and, with the budget's turn
20
+ * (`ResultBudget.turn`), to the call's share of what the window has left this turn.
21
+ * A longer text keeps its start and says where it was cut (`boundResult`), the
22
+ * call's record keeping it whole; the cut is recorded by its lengths (`boundKey`).
19
23
  */
20
24
  /** What a call returns to the harness. */
21
25
  export interface ToolResult {
@@ -28,7 +32,7 @@ export interface ToolResult {
28
32
  images?: readonly ToolImage[];
29
33
  /** The answer as a value, where the tool gives one (recorded with its outcome): what a script's nested call reads. */
30
34
  structured?: JsonValue;
31
- /** The text was cut at HOST_RESULT_MAX_CHARS (`boundResult`); it says so in its last line. */
35
+ /** The text was cut at its bound, or refused for a window too small for any cut (`boundResult`); it says so. */
32
36
  truncated?: true;
33
37
  /** The gate refused the call: the text is its words, and nothing of the call was written or run. */
34
38
  refused?: true;
@@ -72,6 +76,12 @@ export interface ToolBridgeOptions {
72
76
  live?: boolean;
73
77
  /** How much of a partial output an interrupted result quotes. Default 2000 characters. */
74
78
  partialChars?: number;
79
+ /** What the harness's model can take of one result (its context window): every result is held to `resultMaxChars` of
80
+ * it, and, with its turn, a call the model made to its share of what the turn has left. Absent: HOST_RESULT_MAX_CHARS alone. */
81
+ budget?: ResultBudget;
82
+ /** A call whose result goes to something of the harness's own, not to the model (a code-mode script's call, which the
83
+ * script reads): held to the per-result bound alone, never a claim on the turn, whose split is the model's calls'. */
84
+ outsideTurn?: (callId: string) => boolean;
75
85
  }
76
86
  export interface ToolBridge {
77
87
  tools: BridgedTool[];
@@ -86,6 +96,15 @@ export declare class Mutex {
86
96
  }
87
97
  /** The memo key of a tool call. */
88
98
  export declare const toolKey: (callId: string) => string;
99
+ /** The key of the record of a call's cut (`ResultBound`): written when the bridge hands a call's result cut or refused. */
100
+ export declare const boundKey: (callId: string) => string;
101
+ /** How a call's result was cut, as recorded (`boundKey`): the characters of it kept (0 for a refusal), its whole length,
102
+ * and the bound it was held to, from which the same cut is made again. */
103
+ export interface ResultBound {
104
+ kept: number;
105
+ whole: number;
106
+ max: number;
107
+ }
89
108
  /**
90
109
  * The host's gate, asked about a call before anything of it is written: the first step of every harness's tool bridge
91
110
  * (this one's, and the faux harness's, run-adapters/testing). Undefined when it allows the call; the refusal for a deny,
@@ -111,15 +130,71 @@ export declare function toolBridge(ctx: DriveContext, tools: HostTool[], options
111
130
  * effect") plus the last progress it reported.
112
131
  */
113
132
  export declare function failureText(error: EffectError, partialChars?: number): string;
133
+ /** What a harness's model can take of one tool result: its context window, and what every request of the session already
134
+ * spends of it. Either may be absent; with no usable window the host's fixed bound (HOST_RESULT_MAX_CHARS) alone holds. */
135
+ export interface ResultBudget {
136
+ /** The model's context window, in tokens. Not a positive finite number (absent, 0, NaN, Infinity): unknown. */
137
+ contextWindow?: number;
138
+ /** Tokens of the window each request spends before any tool result (its system prompt, its tool list), when the
139
+ * harness knows them. Default 0: the share below leaves room for them. */
140
+ baseInputTokens?: number;
141
+ /** The session's turn budget (turn-budget.ts): what the window has left this turn, which a bridge's calls share. */
142
+ turn?: TurnBudget;
143
+ /** The most one result may take, where it is known for that result alone (its claim on `turn`, for a result a harness
144
+ * builds from its log, not through the bridge): the bound never passes it. */
145
+ maxChars?: number;
146
+ }
147
+ /** The most of a model's context window one tool result may take: a quarter, so a turn has room for its prompt, a few
148
+ * results and the answer. Conservative on purpose: a result past it is cut, never handed to a model it would fill. */
149
+ export declare const RESULT_WINDOW_SHARE = 0.25;
150
+ /** Characters per token when a window becomes characters: 3, under the 4 English prose averages, so code, JSON and
151
+ * non-Latin text (fewer characters a token) still fit. */
152
+ export declare const RESULT_CHARS_PER_TOKEN = 3;
153
+ /** The least of a result a cut keeps: below it (a window too small for its note and this much text) the result is refused
154
+ * in words instead, never passed through. */
155
+ export declare const RESULT_LEAST_KEPT_CHARS = 200;
156
+ /** A result at most this long is never cut or refused, however small the window: a refusal's words (under 300 characters)
157
+ * would cost the window about as much. It also makes the bound idempotent: a cut or a refusal, bound again under the same
158
+ * budget, is unchanged (pi bounds a host tool's answer, then again in its afterTool hook). */
159
+ export declare const RESULT_ALWAYS_WHOLE_CHARS = 400;
160
+ /**
161
+ * The most characters one tool result reaches a model with, for `budget`: HOST_RESULT_MAX_CHARS, or less, a
162
+ * RESULT_WINDOW_SHARE of the window left after the base input at RESULT_CHARS_PER_TOKEN, when that is smaller. No usable
163
+ * window: HOST_RESULT_MAX_CHARS. A base input at or past the window: 0 (every result past its refusal's words is refused).
164
+ */
165
+ export declare function resultMaxChars(budget?: ResultBudget): number;
166
+ /** A harness's `resultBudget` option for a model of `contextWindow`, with the session's turn budget (its fixed text,
167
+ * `system`, counted while no answer is read), or none when no window is known (the host's bound alone): what each
168
+ * adapter spreads into its harness's options, the session's window or its own. Its `turn` is what the adapter hands
169
+ * the session's model proxy (ModelProxyOptions.turn), which reads each answer's facts into it. */
170
+ export declare const windowBudget: (contextWindow: number | undefined, system?: readonly string[]) => {
171
+ resultBudget?: ResultBudget;
172
+ };
114
173
  /**
115
- * `text` within HOST_RESULT_MAX_CHARS characters, as a harness gets a call's
116
- * result: a longer one keeps its start, cut before a character written as a
117
- * surrogate pair rather than between its halves, and ends with a line saying
118
- * so, `[cut at N of M characters]`, counted in the bound. `truncated` when cut.
174
+ * `text` within `resultMaxChars(budget)` characters, as a harness gets a call's result. Within it: whole. Past it: its
175
+ * start, cut before a character written as a surrogate pair rather than between its halves, then a line saying so,
176
+ * counted in the bound: `[cut at N of M characters]` at the host's bound (no budget, or a window too large to bind: as it
177
+ * always read), or the window's note (kept N of M, cut to fit this model's context window; ask for less, or read on where
178
+ * the tool takes an offset). Where the bound leaves less than RESULT_LEAST_KEPT_CHARS beside its note, the result is
179
+ * refused in a short line of words instead (which may itself pass a bound that small; it carries none of the result).
180
+ * A text of at most RESULT_ALWAYS_WHOLE_CHARS is whole under any budget, so bounding a bound changes nothing. The
181
+ * original oversized text is never returned. `truncated` when cut or refused.
119
182
  */
120
- export declare function boundResult(text: string): {
183
+ export declare function boundResult(text: string, budget?: ResultBudget): {
184
+ text: string;
185
+ truncated?: true;
186
+ };
187
+ /** `text` held to `max` characters as `boundResult` holds it to its budget's bound, with how it was cut (`ResultBound`)
188
+ * when it was. The window's note wherever `max` is under HOST_RESULT_MAX_CHARS. `script`: a code-mode script's read,
189
+ * which computes on what it is handed: a JSON document past the bound is handed as a note alone (scriptCutNote).
190
+ * `error`: a failed call's error, which a refusal never hides whole: its first line stays (errorRefusedNote). */
191
+ export declare function boundTo(text: string, max: number, how?: {
192
+ script?: boolean;
193
+ error?: boolean;
194
+ }): {
121
195
  text: string;
122
196
  truncated?: true;
197
+ bound?: ResultBound;
123
198
  };
124
199
  /** At most `max` characters, with a marker when cut. */
125
200
  export declare function clip(text: string, max: number): string;
@@ -3,6 +3,7 @@
3
3
  // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  import { EffectFailure, hostToolIO } from '../kernel/index.js';
5
5
  import { HOST_RESULT_MAX_CHARS } from '../types.js';
6
+ import { TurnBudget } from './turn-budget.js';
6
7
  /** A promise-chain mutex. */
7
8
  export class Mutex {
8
9
  tail = Promise.resolve();
@@ -14,6 +15,12 @@ export class Mutex {
14
15
  }
15
16
  /** The memo key of a tool call. */
16
17
  export const toolKey = (callId) => `tool:${callId}`;
18
+ /** The key of the record of a call's cut (`ResultBound`): written when the bridge hands a call's result cut or refused. */
19
+ export const boundKey = (callId) => `bound:${callId}`;
20
+ const isBound = (value) => {
21
+ const v = value;
22
+ return typeof v === 'object' && v !== null && [v.kept, v.whole, v.max].every((n) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0);
23
+ };
17
24
  /** A call the gate parked: held, never answered here, until `signal` is aborted (the run parked and this process lets
18
25
  * go of it); then it rejects, so the harness is never handed a result for it. */
19
26
  function parkedUntilAborted(signal, tool) {
@@ -51,6 +58,32 @@ export function toolBridge(ctx, tools, options = {}) {
51
58
  const mutex = new Mutex();
52
59
  const serial = options.serial ?? true;
53
60
  const live = options.live ?? true;
61
+ const turn = options.budget?.turn;
62
+ // What every request carries of the bridge's tools (their schemas), for a turn whose answer the host never reads.
63
+ turn?.fixed('tools', JSON.stringify(tools.filter((t) => !t.deferred).map((t) => ({ name: t.name, description: t.description, input_schema: t.inputSchema }))));
64
+ /**
65
+ * `whole` as call `callId`'s result reaches the harness: held to the budget's bound, and, for a call the model made
66
+ * (not one nested in a tool's), to its claim on the turn. A cut is recorded by its lengths (`boundKey`), once; a call
67
+ * whose cut is recorded is cut again by that record, so a replay hands the harness what the first run did.
68
+ */
69
+ const deliver = async (callId, whole, nested, error) => {
70
+ const key = boundKey(callId);
71
+ const recorded = ctx.state().effects.get(key);
72
+ const known = recorded?.status === 'completed' && isBound(recorded.output) ? recorded.output : undefined;
73
+ // A call a script made (nested in a tool's, or one the harness says is outside the model's turn): what it is handed is
74
+ // the script's to compute on, not the model's to read.
75
+ const script = Boolean(nested || options.outsideTurn?.(callId));
76
+ const claims = known || script ? undefined : turn;
77
+ if (claims)
78
+ await claims.ready();
79
+ const max = known ? known.max : Math.min(resultMaxChars(options.budget), claims ? claims.claim(callId, options.budget?.contextWindow) : HOST_RESULT_MAX_CHARS);
80
+ const { text, truncated, bound } = boundTo(whole, max, { script, error: Boolean(error) });
81
+ claims?.settle(callId, text.length);
82
+ await claims?.kept();
83
+ if (bound && !known)
84
+ await ctx.effect(key, { name: 'bound', replay: 'safe', input: null }, async () => bound);
85
+ return truncated ? { text, truncated } : { text };
86
+ };
54
87
  // Each tool's run by name, outside the mutex: a nested call runs inside the call that made it, which holds the mutex.
55
88
  const runs = new Map();
56
89
  /** The session's tools as calls nested in `outer` (NestedCalls): each through its own run, gate first, keyed
@@ -106,14 +139,22 @@ export function toolBridge(ctx, tools, options = {}) {
106
139
  }, (io) => tool.execute(args, hostToolIO(io, ctx, { signal: signal ? AbortSignal.any([signal, io.signal]) : io.signal })));
107
140
  // A tool answers in text, or in text with images (a screenshot) and its value: they come back as recorded.
108
141
  const { text: whole, images, structured } = typeof output === 'object' && output !== null ? output : { text: String(output), images: undefined, structured: undefined };
109
- const { text, truncated } = boundResult(String(whole));
142
+ const { text, truncated } = await deliver(callId, String(whole), nested);
110
143
  if (fresh && live)
111
144
  ctx.live({ type: 'tool_end', name: tool.name, callId, result: text, ...(truncated ? { truncated } : {}) });
112
145
  return { text, isError: false, ...(images?.length ? { images } : {}), ...(structured !== undefined ? { structured } : {}), ...(truncated ? { truncated } : {}) };
113
146
  }
114
147
  catch (err) {
115
148
  if (err instanceof EffectFailure) {
116
- const { text, truncated } = boundResult(failureText(err.error, options.partialChars));
149
+ let bounded;
150
+ try {
151
+ bounded = await deliver(callId, failureText(err.error, options.partialChars), nested, true);
152
+ }
153
+ catch (error) {
154
+ ctx.halt?.(error);
155
+ throw error;
156
+ }
157
+ const { text, truncated } = bounded;
117
158
  if (fresh && live)
118
159
  ctx.live({ type: 'tool_end', name: tool.name, callId, isError: true, result: text, ...(truncated ? { truncated } : {}) });
119
160
  return { text, isError: true, ...(err.error.interrupted ? { interrupted: true } : {}), ...(truncated ? { truncated } : {}) };
@@ -147,13 +188,13 @@ export function toolBridge(ctx, tools, options = {}) {
147
188
  ctx.halt?.(err);
148
189
  throw err;
149
190
  }
150
- const { text, truncated } = boundResult(err instanceof Error ? err.message : String(err));
191
+ const { text, truncated } = await deliver(callId, err instanceof Error ? err.message : String(err), nested, true);
151
192
  if (live)
152
193
  ctx.live({ type: 'tool_end', name: tool.name, callId, isError: true, result: text, ...(truncated ? { truncated } : {}) });
153
194
  return { text, isError: true, ...(truncated ? { truncated } : {}) };
154
195
  }
155
196
  const { text: whole, images, structured } = typeof output === 'object' && output !== null ? output : { text: String(output), images: undefined, structured: undefined };
156
- const { text, truncated } = boundResult(String(whole));
197
+ const { text, truncated } = await deliver(callId, String(whole), nested);
157
198
  if (live)
158
199
  ctx.live({ type: 'tool_end', name: tool.name, callId, result: text, ...(truncated ? { truncated } : {}) });
159
200
  return { text, isError: false, ...(images?.length ? { images } : {}), ...(structured !== undefined ? { structured } : {}), ...(truncated ? { truncated } : {}) };
@@ -195,21 +236,113 @@ export function failureText(error, partialChars = 2000) {
195
236
  const text = typeof last === 'string' ? last : JSON.stringify(last);
196
237
  return `${message}\nPartial output before the interruption:\n${clip(text, partialChars)}`;
197
238
  }
239
+ /** The most of a model's context window one tool result may take: a quarter, so a turn has room for its prompt, a few
240
+ * results and the answer. Conservative on purpose: a result past it is cut, never handed to a model it would fill. */
241
+ export const RESULT_WINDOW_SHARE = 0.25;
242
+ /** Characters per token when a window becomes characters: 3, under the 4 English prose averages, so code, JSON and
243
+ * non-Latin text (fewer characters a token) still fit. */
244
+ export const RESULT_CHARS_PER_TOKEN = 3;
245
+ /** The least of a result a cut keeps: below it (a window too small for its note and this much text) the result is refused
246
+ * in words instead, never passed through. */
247
+ export const RESULT_LEAST_KEPT_CHARS = 200;
248
+ /** A result at most this long is never cut or refused, however small the window: a refusal's words (under 300 characters)
249
+ * would cost the window about as much. It also makes the bound idempotent: a cut or a refusal, bound again under the same
250
+ * budget, is unchanged (pi bounds a host tool's answer, then again in its afterTool hook). */
251
+ export const RESULT_ALWAYS_WHOLE_CHARS = 400;
198
252
  /**
199
- * `text` within HOST_RESULT_MAX_CHARS characters, as a harness gets a call's
200
- * result: a longer one keeps its start, cut before a character written as a
201
- * surrogate pair rather than between its halves, and ends with a line saying
202
- * so, `[cut at N of M characters]`, counted in the bound. `truncated` when cut.
253
+ * The most characters one tool result reaches a model with, for `budget`: HOST_RESULT_MAX_CHARS, or less, a
254
+ * RESULT_WINDOW_SHARE of the window left after the base input at RESULT_CHARS_PER_TOKEN, when that is smaller. No usable
255
+ * window: HOST_RESULT_MAX_CHARS. A base input at or past the window: 0 (every result past its refusal's words is refused).
203
256
  */
204
- export function boundResult(text) {
205
- if (text.length <= HOST_RESULT_MAX_CHARS)
257
+ export function resultMaxChars(budget) {
258
+ const window = budget?.contextWindow;
259
+ if (typeof window !== 'number' || !Number.isFinite(window) || window <= 0)
260
+ return HOST_RESULT_MAX_CHARS;
261
+ const base = budget?.baseInputTokens;
262
+ const room = Math.max(0, window - (typeof base === 'number' && Number.isFinite(base) && base > 0 ? base : 0));
263
+ const own = budget?.maxChars;
264
+ const max = Math.min(HOST_RESULT_MAX_CHARS, Math.floor(room * RESULT_WINDOW_SHARE * RESULT_CHARS_PER_TOKEN));
265
+ return typeof own === 'number' && Number.isFinite(own) && own >= 0 ? Math.min(max, Math.floor(own)) : max;
266
+ }
267
+ /** A harness's `resultBudget` option for a model of `contextWindow`, with the session's turn budget (its fixed text,
268
+ * `system`, counted while no answer is read), or none when no window is known (the host's bound alone): what each
269
+ * adapter spreads into its harness's options, the session's window or its own. Its `turn` is what the adapter hands
270
+ * the session's model proxy (ModelProxyOptions.turn), which reads each answer's facts into it. */
271
+ export const windowBudget = (contextWindow, system = []) => (contextWindow ? { resultBudget: { contextWindow, turn: new TurnBudget(system) } } : {});
272
+ /** The line a cut result ends with: the host's bound's, as it always read, or the window's, which says why and how to go on. */
273
+ function cutNote(kept, total, windowed) {
274
+ return windowed
275
+ ? `\n[kept ${kept} of ${total} characters: the result was cut to fit this model's context window. Ask for less, or read on from character ${kept} where the tool takes an offset.]`
276
+ : `\n[cut at ${kept} of ${total} characters]`;
277
+ }
278
+ /** What a result too large for a window too small to cut it in reads as: none of it. */
279
+ function refusedNote(total, max) {
280
+ return `[not shown: this result is ${total} characters, and this model's context window leaves room for at most ${max} characters of a tool result. Ask for much less: a narrower query, or a small range where the tool takes an offset.]`;
281
+ }
282
+ /**
283
+ * `text` within `resultMaxChars(budget)` characters, as a harness gets a call's result. Within it: whole. Past it: its
284
+ * start, cut before a character written as a surrogate pair rather than between its halves, then a line saying so,
285
+ * counted in the bound: `[cut at N of M characters]` at the host's bound (no budget, or a window too large to bind: as it
286
+ * always read), or the window's note (kept N of M, cut to fit this model's context window; ask for less, or read on where
287
+ * the tool takes an offset). Where the bound leaves less than RESULT_LEAST_KEPT_CHARS beside its note, the result is
288
+ * refused in a short line of words instead (which may itself pass a bound that small; it carries none of the result).
289
+ * A text of at most RESULT_ALWAYS_WHOLE_CHARS is whole under any budget, so bounding a bound changes nothing. The
290
+ * original oversized text is never returned. `truncated` when cut or refused.
291
+ */
292
+ export function boundResult(text, budget) {
293
+ const { text: bounded, truncated } = boundTo(text, resultMaxChars(budget));
294
+ return truncated ? { text: bounded, truncated } : { text: bounded };
295
+ }
296
+ /** What a failed call's error too large for a window too small to cut it in reads as: its first line (what went wrong),
297
+ * as much of it as fits beside the note in RESULT_ALWAYS_WHOLE_CHARS, then that the rest is not shown. Within that
298
+ * length, so bounding it again (pi bounds a result twice) leaves it as it is. */
299
+ function errorRefusedNote(text, max) {
300
+ const rest = `\n[the rest of this error (${text.length} characters in all) is not shown: this model's context window leaves room for at most ${max} characters of a tool result.]`;
301
+ const line = text.split('\n', 1)[0] ?? '';
302
+ const room = RESULT_ALWAYS_WHOLE_CHARS - rest.length;
303
+ if (line.length <= room)
304
+ return `${line}${rest}`;
305
+ // Cut before a character written as a surrogate pair rather than between its halves, and mark the cut.
306
+ let kept = room - 1;
307
+ if ((line.charCodeAt(kept - 1) & 0xfc00) === 0xd800 && (line.charCodeAt(kept) & 0xfc00) === 0xdc00)
308
+ kept -= 1;
309
+ return `${line.slice(0, kept)}…${rest}`;
310
+ }
311
+ /** What a script's JSON read too large for its bound reads as: none of it, since part of a JSON document does not parse,
312
+ * and a note a script's parse fails on by name (`Unexpected token 'r', "[read cut:"...`), which a script that prints it
313
+ * shows the model. */
314
+ function scriptCutNote(total, max, windowed) {
315
+ return `[read cut: this result is ${total} characters of JSON, past the ${max} characters ${windowed ? "this model's context window leaves a tool result" : 'a tool result may have'}. Part of a JSON document does not parse, so none of it was handed. Ask for less: a narrower query, or a small range where the tool takes an offset.]`;
316
+ }
317
+ /** Whether `text` is a whole JSON object or array (what a script parses). */
318
+ function isJsonDocument(text) {
319
+ if (!/^\s*[[{]/.test(text))
320
+ return false;
321
+ try {
322
+ JSON.parse(text);
323
+ return true;
324
+ }
325
+ catch {
326
+ return false;
327
+ }
328
+ }
329
+ /** `text` held to `max` characters as `boundResult` holds it to its budget's bound, with how it was cut (`ResultBound`)
330
+ * when it was. The window's note wherever `max` is under HOST_RESULT_MAX_CHARS. `script`: a code-mode script's read,
331
+ * which computes on what it is handed: a JSON document past the bound is handed as a note alone (scriptCutNote).
332
+ * `error`: a failed call's error, which a refusal never hides whole: its first line stays (errorRefusedNote). */
333
+ export function boundTo(text, max, how = {}) {
334
+ if (text.length <= max || text.length <= RESULT_ALWAYS_WHOLE_CHARS)
206
335
  return { text };
207
- const note = (kept) => `\n[cut at ${kept} of ${text.length} characters]`;
336
+ if (how.script && !how.error && isJsonDocument(text))
337
+ return { text: scriptCutNote(text.length, max, max < HOST_RESULT_MAX_CHARS), truncated: true, bound: { kept: 0, whole: text.length, max } };
338
+ const windowed = max < HOST_RESULT_MAX_CHARS;
208
339
  // The note's own length counted at the bound: what is kept is never longer than that, so neither is its note.
209
- let kept = HOST_RESULT_MAX_CHARS - note(HOST_RESULT_MAX_CHARS).length;
340
+ let kept = max - cutNote(max, text.length, windowed).length;
341
+ if (kept < RESULT_LEAST_KEPT_CHARS)
342
+ return { text: how.error ? errorRefusedNote(text, max) : refusedNote(text.length, max), truncated: true, bound: { kept: 0, whole: text.length, max } };
210
343
  if ((text.charCodeAt(kept - 1) & 0xfc00) === 0xd800 && (text.charCodeAt(kept) & 0xfc00) === 0xdc00)
211
344
  kept -= 1;
212
- return { text: `${text.slice(0, kept)}${note(kept)}`, truncated: true };
345
+ return { text: `${text.slice(0, kept)}${cutNote(kept, text.length, windowed)}`, truncated: true, bound: { kept, whole: text.length, max } };
213
346
  }
214
347
  /** At most `max` characters, with a marker when cut. */
215
348
  export function clip(text, max) {
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The turn budget: what a model's context window has left for one turn's tool results, together. Each result alone is
3
+ * held to its share of the window (tools.ts resultMaxChars); this holds a turn's results, all of them, to what the
4
+ * context has not spent. The kernel owns the rule; a harness only reports two facts of each answer (`open`): the input
5
+ * tokens its request held and its output, and how many tool calls it made. The session's model proxy reports them for
6
+ * every harness it serves (ModelProxyOptions.turn); pi, and Claude Code on a person's login (no proxy), report them
7
+ * from their own hooks.
8
+ *
9
+ * What is left for a turn: the window, less what the request held, the answer, and the room kept for the model's next
10
+ * answer (answerReserve), at RESULT_CHARS_PER_TOKEN. Each call claims the smaller of its own bound and what is
11
+ * left over the calls still unanswered, so parallel calls split it evenly, and a result shorter than its claim gives
12
+ * the rest back. With no answer read (a harness whose model traffic the host does not see), the session's fixed text
13
+ * (its system prompt and tool schemas, `fixed`), counted with o200k, is what the context holds, and each result is held
14
+ * to its share of the rest.
15
+ */
16
+ /** The share of the window a turn keeps for the model's answer after its results: the results never take it. */
17
+ export declare const ANSWER_RESERVE_SHARE = 0.25;
18
+ /** The most tokens a turn keeps for the model's answer, whatever the window. */
19
+ export declare const ANSWER_RESERVE_MAX_TOKENS = 16384;
20
+ /** The tokens a turn on a window of `contextWindow` keeps for the model's answer after its results. */
21
+ export declare const answerReserve: (contextWindow: number) => number;
22
+ /** The two facts of an answer: the input tokens its request held (the provider's count, its cached input included, or the
23
+ * host's local count), the output it said, and the client tool calls it made. Each may be unknown. */
24
+ export interface TurnFacts {
25
+ inputTokens?: number;
26
+ outputTokens?: number;
27
+ calls?: number;
28
+ }
29
+ /** An answer being read: `open` with its facts once read, `end` however it ended (both once; `end` after `open` is nothing). */
30
+ export interface TurnSpan {
31
+ open(facts: TurnFacts): void;
32
+ end(): void;
33
+ }
34
+ /** What a turn budget journals as it happens (journalTurn): an answer's facts as it opened the turn (`open`, null when its
35
+ * input was unknown), and a result's length as it was handed (`settled`). */
36
+ export type TurnRecord = {
37
+ open: {
38
+ inputTokens: number;
39
+ outputTokens: number;
40
+ calls?: number;
41
+ } | null;
42
+ } | {
43
+ settled: {
44
+ callId: string;
45
+ chars: number;
46
+ };
47
+ };
48
+ export declare class TurnBudget {
49
+ #private;
50
+ /** `fixed`: the session's own text every request carries (its system prompt), counted when no answer was read. */
51
+ constructor(fixed?: readonly string[]);
52
+ /** Text every request of the session carries, by name (a bridge's tool schemas, 'tools'): replaces the text of that name. */
53
+ fixed(name: string, text: string): void;
54
+ /** An answer of the turn's is being read: a call waits for it (`ready`) before it claims. */
55
+ begin(): TurnSpan;
56
+ /** A new turn, from its answer's facts: what was claimed before is forgotten. Input tokens unknown: the turn is unknown. */
57
+ open(facts: TurnFacts): void;
58
+ /** Each answer's facts and each result's length, as they happen, to `sink` (the session's journal: journalTurn), in place of any before.
59
+ * A new sink (a new drive's journal) starts with nothing waited for: a length the last one failed to keep failed its
60
+ * own drive, never the next. When the last one lost a record, the new one is first given the turn again (the answer's
61
+ * facts, then each length handed since, as restore reads them), and a result waits for that too: a call the drive that
62
+ * failed settled, replayed in this one (Codex's), settles nothing new, and its length must still reach the journal. */
63
+ journal(sink: (record: TurnRecord) => void | Promise<void>): void;
64
+ /** The turn `records` (journal's, in order) leave: the last answer's facts, and each result handed since, held. Only a
65
+ * budget that has read no answer of its own takes them (a new process resuming its session's turn); else nothing. */
66
+ restore(records: readonly TurnRecord[]): void;
67
+ /** Resolves once no answer is being read (or READY_WAIT_MS passed), and, with none read yet, once the fixed text is counted. */
68
+ ready(waitMs?: number): Promise<void>;
69
+ /**
70
+ * The most characters call `callId`'s result may reach the model with, on a window of `contextWindow` tokens: its share
71
+ * of the window left after what the context holds, and, in a turn whose answer was read, at most what is left of the
72
+ * turn over the calls still unanswered, which this call then holds until `settle`. A call claimed again in the same turn
73
+ * gets the same figure. No usable window: HOST_RESULT_MAX_CHARS.
74
+ */
75
+ claim(callId: string, contextWindow: number | undefined): number;
76
+ /** Call `callId`'s result reached the model at `chars` characters: what it claimed and did not use is left for the rest,
77
+ * and what it took past its claim (a short result is whole under any bound, a refusal's words are what they are) is
78
+ * held, so the calls after it split only what is left. */
79
+ settle(callId: string, chars: number): void;
80
+ /** Resolves once every result length settled is kept by the sink (journalTurn: committed to the journal), so a result
81
+ * goes back only once a process that stops right after cannot lose its part of the turn. Rejects when one was not:
82
+ * the result must not go back, since a resume would claim its part again. */
83
+ kept(): Promise<void>;
84
+ }
85
+ /** The journal stream of a session's turn budget (TurnRecord). */
86
+ export declare const TURN_STREAM = "kernel.turn";
87
+ /** A drive's journal, as journalTurn writes and reads it (NativeJournal). */
88
+ export interface TurnJournal {
89
+ append(stream: string, data: unknown): unknown;
90
+ flush(): Promise<void>;
91
+ records<T = unknown>(stream?: string): readonly {
92
+ data: T | undefined;
93
+ }[];
94
+ }
95
+ /**
96
+ * `turn` kept on `journal` (a drive's; the next drive's replaces it): a budget that has read no answer yet (a new process
97
+ * resuming the session) first takes back the turn the journal holds, so the calls its resume answers split what their
98
+ * answer left; then each answer's facts and each result's length go to the journal as they happen, flushed at once: an
99
+ * answer's facts must outlast a process that stops while its calls run, and a result's length one that stops right after
100
+ * it was handed (the bridge waits for it: TurnBudget.kept). A journal that cannot write halts its drive on its own,
101
+ * and a result whose length it could not keep is never handed (kept rejects; the bridge halts and throws).
102
+ */
103
+ export declare function journalTurn(turn: TurnBudget | undefined, journal: TurnJournal): void;
104
+ /** The client tool calls an answer's event-stream line starts (`data: ...`): a Messages `tool_use` block, a Responses
105
+ * function or custom tool call item, or a Chat Completions tool call's first piece (the one with its id). A provider's
106
+ * own tool (a server tool use) is not the client's call. Any other line, or one that does not parse: 0. */
107
+ export declare function toolCallsIn(line: string): number;
108
+ /** The client tool calls a whole JSON answer (no event stream) made, in the same three formats; undefined when it does not parse. */
109
+ export declare function toolCallsInBody(text: string): number | undefined;
@@ -0,0 +1,273 @@
1
+ // Written for AgentRun.
2
+ import { o200kTokens } from '../host/o200k.js';
3
+ import { HOST_RESULT_MAX_CHARS } from '../types.js';
4
+ import { RESULT_CHARS_PER_TOKEN, resultMaxChars } from './tools.js';
5
+ /**
6
+ * The turn budget: what a model's context window has left for one turn's tool results, together. Each result alone is
7
+ * held to its share of the window (tools.ts resultMaxChars); this holds a turn's results, all of them, to what the
8
+ * context has not spent. The kernel owns the rule; a harness only reports two facts of each answer (`open`): the input
9
+ * tokens its request held and its output, and how many tool calls it made. The session's model proxy reports them for
10
+ * every harness it serves (ModelProxyOptions.turn); pi, and Claude Code on a person's login (no proxy), report them
11
+ * from their own hooks.
12
+ *
13
+ * What is left for a turn: the window, less what the request held, the answer, and the room kept for the model's next
14
+ * answer (answerReserve), at RESULT_CHARS_PER_TOKEN. Each call claims the smaller of its own bound and what is
15
+ * left over the calls still unanswered, so parallel calls split it evenly, and a result shorter than its claim gives
16
+ * the rest back. With no answer read (a harness whose model traffic the host does not see), the session's fixed text
17
+ * (its system prompt and tool schemas, `fixed`), counted with o200k, is what the context holds, and each result is held
18
+ * to its share of the rest.
19
+ */
20
+ /** The share of the window a turn keeps for the model's answer after its results: the results never take it. */
21
+ export const ANSWER_RESERVE_SHARE = 0.25;
22
+ /** The most tokens a turn keeps for the model's answer, whatever the window. */
23
+ export const ANSWER_RESERVE_MAX_TOKENS = 16_384;
24
+ /** The tokens a turn on a window of `contextWindow` keeps for the model's answer after its results. */
25
+ export const answerReserve = (contextWindow) => Math.min(Math.floor(contextWindow * ANSWER_RESERVE_SHARE), ANSWER_RESERVE_MAX_TOKENS);
26
+ /** The most a call waits for an answer still being read (`ready`) before it is bound on what is known: the proxy reads an
27
+ * answer's usage the moment it ends, so this is only reached if that reading never ends. */
28
+ const READY_WAIT_MS = 10_000;
29
+ const count = (n) => (typeof n === 'number' && Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined);
30
+ const usableWindow = (window) => typeof window === 'number' && Number.isFinite(window) && window > 0;
31
+ export class TurnBudget {
32
+ #fixed = new Map();
33
+ #fixedTokens;
34
+ #counting;
35
+ #facts;
36
+ /** What this turn's claims hold of what is left, in characters: each claim's bound until its result settles it. */
37
+ #held = 0;
38
+ /** Each call's claim: its bound, and once its result went back, the length it was handed at. */
39
+ #claims = new Map();
40
+ #reading = 0;
41
+ #waiting = new Set();
42
+ /** An answer was read into this budget (open, or restore): a journal's records never replace it. */
43
+ #read = false;
44
+ #sink;
45
+ /** Every result length handed to the sink, once each is kept (the sinks' promises, together): rejects once one was not. */
46
+ #kept = Promise.resolve();
47
+ /** A record the sink could not keep: the next sink is given the turn again (journal). */
48
+ #lost = false;
49
+ /** `fixed`: the session's own text every request carries (its system prompt), counted when no answer was read. */
50
+ constructor(fixed = []) {
51
+ if (fixed.length)
52
+ this.#fixed.set('system', fixed.join('\n\n'));
53
+ }
54
+ /** Text every request of the session carries, by name (a bridge's tool schemas, 'tools'): replaces the text of that name. */
55
+ fixed(name, text) {
56
+ if (this.#fixed.get(name) === text)
57
+ return;
58
+ this.#fixed.set(name, text);
59
+ this.#fixedTokens = undefined;
60
+ this.#counting = undefined;
61
+ }
62
+ /** An answer of the turn's is being read: a call waits for it (`ready`) before it claims. */
63
+ begin() {
64
+ this.#reading += 1;
65
+ let done = false;
66
+ const end = () => {
67
+ if (done)
68
+ return;
69
+ done = true;
70
+ this.#reading -= 1;
71
+ if (this.#reading === 0)
72
+ for (const wake of [...this.#waiting])
73
+ wake();
74
+ };
75
+ return {
76
+ open: (facts) => {
77
+ if (!done)
78
+ this.open(facts);
79
+ end();
80
+ },
81
+ end,
82
+ };
83
+ }
84
+ /** A new turn, from its answer's facts: what was claimed before is forgotten. Input tokens unknown: the turn is unknown. */
85
+ open(facts) {
86
+ const inputTokens = count(facts.inputTokens);
87
+ const calls = count(facts.calls);
88
+ this.#facts = inputTokens === undefined ? undefined : { inputTokens, outputTokens: count(facts.outputTokens) ?? 0, ...(calls ? { calls } : {}) };
89
+ this.#held = 0;
90
+ this.#claims.clear();
91
+ this.#read = true;
92
+ // No result waits on an answer's record: one the sink could not keep halts its drive (NativeJournal), and the
93
+ // lengths settled after it, which the bridge waits for, fail with it.
94
+ void Promise.resolve(this.#sink?.(this.#opened())).catch(() => {
95
+ this.#lost = true;
96
+ });
97
+ }
98
+ /** The record of the answer this turn opened with. */
99
+ #opened() {
100
+ return { open: this.#facts ? { ...this.#facts } : null };
101
+ }
102
+ /** `result` (a sink's) joined to what kept() waits for. */
103
+ #keep(result) {
104
+ const kept = Promise.all([this.#kept, result]).then(() => { });
105
+ // Seen here, so a length no one waits for never stops the process; kept() still rejects with it.
106
+ kept.catch(() => {
107
+ this.#lost = true;
108
+ });
109
+ this.#kept = kept;
110
+ }
111
+ /** Each answer's facts and each result's length, as they happen, to `sink` (the session's journal: journalTurn), in place of any before.
112
+ * A new sink (a new drive's journal) starts with nothing waited for: a length the last one failed to keep failed its
113
+ * own drive, never the next. When the last one lost a record, the new one is first given the turn again (the answer's
114
+ * facts, then each length handed since, as restore reads them), and a result waits for that too: a call the drive that
115
+ * failed settled, replayed in this one (Codex's), settles nothing new, and its length must still reach the journal. */
116
+ journal(sink) {
117
+ this.#sink = sink;
118
+ this.#kept = Promise.resolve();
119
+ if (!this.#lost || !this.#read)
120
+ return;
121
+ this.#lost = false;
122
+ this.#keep(sink(this.#opened()));
123
+ for (const [callId, claimed] of this.#claims)
124
+ if (claimed.settled)
125
+ this.#keep(sink({ settled: { callId, chars: claimed.chars ?? claimed.max } }));
126
+ }
127
+ /** The turn `records` (journal's, in order) leave: the last answer's facts, and each result handed since, held. Only a
128
+ * budget that has read no answer of its own takes them (a new process resuming its session's turn); else nothing. */
129
+ restore(records) {
130
+ if (this.#read)
131
+ return;
132
+ let last = -1;
133
+ records.forEach((record, i) => void (record && 'open' in record && (last = i)));
134
+ if (last < 0)
135
+ return;
136
+ const opened = records[last].open;
137
+ const inputTokens = count(opened?.inputTokens);
138
+ const calls = count(opened?.calls);
139
+ this.#facts = inputTokens === undefined ? undefined : { inputTokens, outputTokens: count(opened?.outputTokens) ?? 0, ...(calls ? { calls } : {}) };
140
+ this.#held = 0;
141
+ this.#claims.clear();
142
+ for (const record of records.slice(last + 1)) {
143
+ if (!record || !('settled' in record))
144
+ continue;
145
+ const chars = count(record.settled?.chars);
146
+ const callId = record.settled?.callId;
147
+ if (typeof callId !== 'string' || chars === undefined || this.#claims.has(callId))
148
+ continue;
149
+ this.#claims.set(callId, { max: chars, settled: true, chars });
150
+ this.#held += chars;
151
+ }
152
+ this.#read = true;
153
+ }
154
+ /** Resolves once no answer is being read (or READY_WAIT_MS passed), and, with none read yet, once the fixed text is counted. */
155
+ async ready(waitMs = READY_WAIT_MS) {
156
+ if (this.#reading > 0) {
157
+ await new Promise((resolve) => {
158
+ const wake = () => {
159
+ clearTimeout(timer);
160
+ this.#waiting.delete(wake);
161
+ resolve();
162
+ };
163
+ const timer = setTimeout(wake, waitMs);
164
+ timer.unref?.();
165
+ this.#waiting.add(wake);
166
+ });
167
+ }
168
+ if (this.#facts || this.#fixedTokens !== undefined || this.#fixed.size === 0)
169
+ return;
170
+ this.#counting ??= o200kTokens([...this.#fixed.values()].join('\n\n')).then((tokens) => void (this.#fixedTokens = tokens), () => void (this.#fixedTokens = 0));
171
+ await this.#counting;
172
+ }
173
+ /**
174
+ * The most characters call `callId`'s result may reach the model with, on a window of `contextWindow` tokens: its share
175
+ * of the window left after what the context holds, and, in a turn whose answer was read, at most what is left of the
176
+ * turn over the calls still unanswered, which this call then holds until `settle`. A call claimed again in the same turn
177
+ * gets the same figure. No usable window: HOST_RESULT_MAX_CHARS.
178
+ */
179
+ claim(callId, contextWindow) {
180
+ if (!usableWindow(contextWindow))
181
+ return HOST_RESULT_MAX_CHARS;
182
+ const claimed = this.#claims.get(callId);
183
+ if (claimed)
184
+ return claimed.max;
185
+ const facts = this.#facts;
186
+ const held = facts ? facts.inputTokens : (this.#fixedTokens ?? 0);
187
+ const share = resultMaxChars({ contextWindow, baseInputTokens: held });
188
+ if (!facts)
189
+ return share;
190
+ const room = contextWindow - facts.inputTokens - facts.outputTokens - answerReserve(contextWindow);
191
+ const left = Math.max(0, room * RESULT_CHARS_PER_TOKEN - this.#held);
192
+ const unanswered = Math.max(1, (facts.calls ?? 0) - this.#claims.size);
193
+ const max = Math.min(share, Math.floor(left / unanswered));
194
+ this.#claims.set(callId, { max, settled: false });
195
+ this.#held += max;
196
+ return max;
197
+ }
198
+ /** Call `callId`'s result reached the model at `chars` characters: what it claimed and did not use is left for the rest,
199
+ * and what it took past its claim (a short result is whole under any bound, a refusal's words are what they are) is
200
+ * held, so the calls after it split only what is left. */
201
+ settle(callId, chars) {
202
+ const claimed = this.#claims.get(callId);
203
+ const handed = count(chars);
204
+ if (!claimed || claimed.settled || handed === undefined)
205
+ return;
206
+ claimed.settled = true;
207
+ claimed.chars = handed;
208
+ this.#held += handed - claimed.max;
209
+ this.#keep(this.#sink?.({ settled: { callId, chars: handed } }));
210
+ }
211
+ /** Resolves once every result length settled is kept by the sink (journalTurn: committed to the journal), so a result
212
+ * goes back only once a process that stops right after cannot lose its part of the turn. Rejects when one was not:
213
+ * the result must not go back, since a resume would claim its part again. */
214
+ async kept() {
215
+ await this.#kept;
216
+ }
217
+ }
218
+ /** The journal stream of a session's turn budget (TurnRecord). */
219
+ export const TURN_STREAM = 'kernel.turn';
220
+ /**
221
+ * `turn` kept on `journal` (a drive's; the next drive's replaces it): a budget that has read no answer yet (a new process
222
+ * resuming the session) first takes back the turn the journal holds, so the calls its resume answers split what their
223
+ * answer left; then each answer's facts and each result's length go to the journal as they happen, flushed at once: an
224
+ * answer's facts must outlast a process that stops while its calls run, and a result's length one that stops right after
225
+ * it was handed (the bridge waits for it: TurnBudget.kept). A journal that cannot write halts its drive on its own,
226
+ * and a result whose length it could not keep is never handed (kept rejects; the bridge halts and throws).
227
+ */
228
+ export function journalTurn(turn, journal) {
229
+ if (!turn)
230
+ return;
231
+ turn.restore(journal.records(TURN_STREAM).flatMap((r) => (r.data ? [r.data] : [])));
232
+ turn.journal((record) => {
233
+ journal.append(TURN_STREAM, record);
234
+ return journal.flush();
235
+ });
236
+ }
237
+ /** The client tool calls an answer's event-stream line starts (`data: ...`): a Messages `tool_use` block, a Responses
238
+ * function or custom tool call item, or a Chat Completions tool call's first piece (the one with its id). A provider's
239
+ * own tool (a server tool use) is not the client's call. Any other line, or one that does not parse: 0. */
240
+ export function toolCallsIn(line) {
241
+ if (!line.startsWith('data:') || !/tool_use|output_item\.added|tool_calls/.test(line))
242
+ return 0;
243
+ let event;
244
+ try {
245
+ event = JSON.parse(line.slice(5));
246
+ }
247
+ catch {
248
+ return 0;
249
+ }
250
+ if (event?.type === 'content_block_start')
251
+ return event.content_block?.type === 'tool_use' ? 1 : 0;
252
+ if (event?.type === 'response.output_item.added')
253
+ return CALL_ITEMS.has(event.item?.type) ? 1 : 0;
254
+ const calls = event?.choices?.[0]?.delta?.tool_calls;
255
+ return Array.isArray(calls) ? calls.filter((call) => typeof call?.id === 'string' && call.id !== '').length : 0;
256
+ }
257
+ /** The client tool calls a whole JSON answer (no event stream) made, in the same three formats; undefined when it does not parse. */
258
+ export function toolCallsInBody(text) {
259
+ let body;
260
+ try {
261
+ body = JSON.parse(text);
262
+ }
263
+ catch {
264
+ return undefined;
265
+ }
266
+ if (Array.isArray(body?.content))
267
+ return body.content.filter((block) => block?.type === 'tool_use').length;
268
+ if (Array.isArray(body?.output))
269
+ return body.output.filter((item) => CALL_ITEMS.has(item?.type)).length;
270
+ const calls = body?.choices?.[0]?.message?.tool_calls;
271
+ return Array.isArray(calls) ? calls.length : undefined;
272
+ }
273
+ const CALL_ITEMS = new Set(['function_call', 'custom_tool_call']);
package/dist/types.d.ts CHANGED
@@ -23,7 +23,8 @@ export interface ToolImage {
23
23
  * The most characters a host tool's result reaches a harness with: its text as the model reads it (`text.length`). The
24
24
  * kernel's tool bridge, which every host tool's result passes on its way to a harness, cuts every result past it: its
25
25
  * start, cut where a character ends, then a line saying where it was cut (`[cut at N of M characters]`), the call's end
26
- * flagged `truncated`; the call's record keeps it whole. Each harness tells its CLI to pass a result this long to the
26
+ * flagged `truncated`; the call's record keeps it whole. A model whose context window the harness knows gets less, its
27
+ * window's share (process/tools.ts resultMaxChars, boundResult): this is the ceiling, never raised by a large window. Each harness tells its CLI to pass a result this long to the
27
28
  * model whole: the Claude Agent CLI otherwise saves one past 50,000 characters to a file and tells the model to read it
28
29
  * (which a confined session cannot), and Codex cuts the middle of one past its truncation policy. The Claude Agent CLI
29
30
  * takes at most 500,000 here.
@@ -178,6 +179,10 @@ export interface SessionSpec {
178
179
  tier?: NodeRequest["tier"];
179
180
  effort?: NodeRequest["effort"];
180
181
  thinking?: NodeRequest["thinking"];
182
+ /** The session model's context window in tokens, when the host knows it (its catalog's). Each harness holds every tool
183
+ * result to its share of it (process/tools.ts resultMaxChars), under HOST_RESULT_MAX_CHARS; a harness that tells its
184
+ * CLI a window tells it this one. Absent: the harness's own (its adapter's option), else the host's bound alone. */
185
+ contextWindow?: number;
181
186
  }
182
187
  /** A paid model request, as the session is about to send it. */
183
188
  export interface ModelRequest {
package/dist/types.js CHANGED
@@ -2,7 +2,8 @@
2
2
  * The most characters a host tool's result reaches a harness with: its text as the model reads it (`text.length`). The
3
3
  * kernel's tool bridge, which every host tool's result passes on its way to a harness, cuts every result past it: its
4
4
  * start, cut where a character ends, then a line saying where it was cut (`[cut at N of M characters]`), the call's end
5
- * flagged `truncated`; the call's record keeps it whole. Each harness tells its CLI to pass a result this long to the
5
+ * flagged `truncated`; the call's record keeps it whole. A model whose context window the harness knows gets less, its
6
+ * window's share (process/tools.ts resultMaxChars, boundResult): this is the ceiling, never raised by a large window. Each harness tells its CLI to pass a result this long to the
6
7
  * model whole: the Claude Agent CLI otherwise saves one past 50,000 characters to a file and tells the model to read it
7
8
  * (which a confined session cannot), and Codex cuts the middle of one past its truncation policy. The Claude Agent CLI
8
9
  * takes at most 500,000 here.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-kernel",
3
- "version": "0.1.0-beta.62",
3
+ "version": "0.1.0-beta.64",
4
4
  "description": "Agent harnesses other than Pi, starting with Codex, behind one seam: a DSL node's runNode and an AgentRun run on a harness adapter, durable in AgentRun's own store.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -62,7 +62,7 @@
62
62
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
63
63
  },
64
64
  "dependencies": {
65
- "@parcha/agentrun-dsl": "0.1.0-beta.62",
65
+ "@parcha/agentrun-dsl": "0.1.0-beta.64",
66
66
  "ajv": "8.18.0",
67
67
  "typebox": "1.3.27"
68
68
  },