@parcha/agentrun-kernel 0.1.0-beta.32 → 0.1.0-beta.34

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,21 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.34 (2026-11-11)
6
+
7
+ - The server checks a harness's pinned binary (claude-agent's CLI, Codex, OpenCode: its sha256, then the version it reports) without holding its event loop, so requests, timers and store answers go on while a binary of hundreds of MiB is hashed and run. Before, the first check in a process held every request for one to several seconds (GET /v2/capabilities, a server's start, an adapter made for a run). The binary is now hashed off the loop a chunk at a time and run as a child the loop does not wait on. A pass is kept for the adapter's own check, which then reads nothing, and two checks of one binary at once read it once. New: `checkedOnceAsync` and `sha256OfFileAsync` (kernel host), `verifyClaudeAgentCliAsync` (claude-agent), and `verifyCodexAsync` and `verifyCodexBinaryAsync` (Codex). Who breaks: a program that calls the kernel's `checkedOnce` with its own check. A check is now a `BinaryCheck`, a generator that yields each probe (`{ kind: "sha256", path }` or `{ kind: "run", path, args, env, timeoutMs }`) and is given back its answer, so one check runs either way.
8
+ - The kernel registry has no browser kind any more: `CapabilityKind` is `"desktop" | "phone"`, and `browserToolDefs`, `BrowserContract`, `Browser`, `CdpSession`, `Hands.browser`, `HostExecutors.browser` and `createRegistry`'s `browserTools` option are gone. A host whose computer is a browser drives it with its own browser tool (serve's, pi-browser's durable extension), and passes no browser kind, contracts or executors to `createRegistry`.
9
+ - A browser run's money on the runner is counted once and shown. `/v2/usage` shows a runner run's browser time again (its `browser_time` meter read per-run files the runner never writes). A run parked at its cap by a browser call shows the cap's words on its budget card, where its reason was empty. Each browser charge is booked once on the run's ledger, under its real call when it has one, named by its session and time so a reopen never books it twice; a charge owed at the provider (a session's release, a person's carried time) is booked past the cap, as main kept it. The browser's holds (a call's, a session's reserve, a person's time) are money reserved, never spent: a lost claim gives them back, never leaves them counted as spent.
10
+ - A codex, opencode or claude-agent run that reads one of its skills' files (`read_skill_file`) now shows the call and its result on the run's Timeline, as pi's tool calls are shown. On the runner, the adapter's own skill reader ran outside the run's record, so the Timeline had no row for it. The read now goes through the host's tool path (the record, the rule before a side effect, the host's hooks on its result); a new `SessionIO.hostTool` hands an adapter's own tool to the host, and the kernel's `hostedTool(io, tool)` applies it.
11
+ - Upgrading: nothing to change.
12
+ - A run with a spend cap no longer passes it quietly. When an answer costs more than the cap had room for (an answer longer than expected, a native web search), the answer is booked and the run ends failed with error code `spend_cap_reached` and "The run cost $X, $Y over its cap of $Z.", as before the runner; it used to end completed, or pause for a raise at its next request. A cache miss within the bound its request was admitted at still pauses the run at its next request. A paid tool call (a web search or fetch, a paid MCP call) cut off by a runner crash or a takeover is booked as a charge of an unknown amount at the next claim: the run's cost reads unknown, counted at the call's hold for the cap, where it read as free. A model answer with no price (a gateway model the catalog does not list, with no price set) makes the run's cost unknown, never $0. A Claude Code, Codex or workflow run's `/v2/usage` tokens meter is its model requests' booked cost, where it read $0.
13
+
14
+ ## 0.1.0-beta.33 (2026-11-10)
15
+
16
+ - A run parked at its spend cap no longer shows a "Model request failed: 400 {…agentrun_proxy…}" row in its Timeline. The model proxy refused that request before it was sent, and the park's row already says what happened. That refused request also no longer counts as a model request in the run's usage line.
17
+
18
+ The cap's refusal now carries its code through to the proxy as a field: the runner's `Refusal.code`, then `HarnessRunError.refusal`. The proxy writes `code: "spend_cap_reached"` in its refusal body. The Timeline matches on that code and `type: "agentrun_proxy"`, never on the words. Every other model failure, a provider's 400 included, keeps its row.
19
+
5
20
  ## 0.1.0-beta.32 (2026-11-10)
6
21
 
7
22
  - The code copied from the upstream durable harness is now AgentRun's own: the port froze, and the pristine upstream copies, the named patches, the import tables, `scripts/port-durable-harness.mjs` and `npm run verify:port` are gone. `vendor/durable-harness/UPSTREAM.json` still records where each copy came from, and each copy keeps its header and NOTICE its attribution. With it go the kernel's paths that never run:
package/dist/errors.d.ts CHANGED
@@ -35,9 +35,12 @@ export declare class HarnessRunError extends Error {
35
35
  message?: string;
36
36
  maxTurns?: number | null;
37
37
  lastTool?: string;
38
+ refusal?: string;
38
39
  });
39
40
  /** The node's turn limit for this attempt, or null when it had none. */
40
41
  readonly maxTurns?: number | null;
41
42
  /** The name of the last tool the node called, never its arguments. */
42
43
  readonly lastTool?: string;
44
+ /** A `refused` stop's code, when the host that refused gave one (Refusal.code: a spend cap's `spend_cap_reached`). */
45
+ readonly refusal?: string;
43
46
  }
package/dist/errors.js CHANGED
@@ -37,6 +37,8 @@ export class HarnessRunError extends Error {
37
37
  this.maxTurns = detail.maxTurns;
38
38
  if (detail.lastTool !== undefined)
39
39
  this.lastTool = detail.lastTool;
40
+ if (detail.refusal !== undefined)
41
+ this.refusal = detail.refusal;
40
42
  if (reason === "turn_limit" || reason === "no_progress" || reason === "refused")
41
43
  this.final = true;
42
44
  }
@@ -44,4 +46,6 @@ export class HarnessRunError extends Error {
44
46
  maxTurns;
45
47
  /** The name of the last tool the node called, never its arguments. */
46
48
  lastTool;
49
+ /** A `refused` stop's code, when the host that refused gave one (Refusal.code: a spend cap's `spend_cap_reached`). */
50
+ refusal;
47
51
  }
@@ -9,4 +9,4 @@ export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./pa
9
9
  export type { LaunchCommand, ParentWatch } from "./parent-death.js";
10
10
  export { BoxError } from "./box.js";
11
11
  export type { BoxErrorCode, BoxRecord, BoxRecorder, Reaped } from "./box.js";
12
- export { checkedOnce, sha256OfFile } from "./pinned-binary.js";
12
+ export { type BinaryCheck, type BinaryProbe, checkedOnce, checkedOnceAsync, sha256OfFile, sha256OfFileAsync } from "./pinned-binary.js";
@@ -7,4 +7,4 @@ export { processAlive } from "./alive.js";
7
7
  export { serialWriter } from "./serial.js";
8
8
  export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./parent-death.js";
9
9
  export { BoxError } from "./box.js";
10
- export { checkedOnce, sha256OfFile } from "./pinned-binary.js";
10
+ export { checkedOnce, checkedOnceAsync, sha256OfFile, sha256OfFileAsync } from "./pinned-binary.js";
@@ -1,6 +1,31 @@
1
1
  /** The sha256 of the file at `path`, as hex, read a chunk at a time. Throws as `openSync` and `readSync` do. */
2
2
  export declare function sha256OfFile(path: string): string;
3
+ /** sha256OfFile without holding the event loop: each chunk is read off it, and the loop goes on between chunks. Rejects
4
+ * as `open` and `read` do. */
5
+ export declare function sha256OfFileAsync(path: string): Promise<string>;
6
+ /** What a binary's check reads of it: its sha256, or what it prints on stdout when run (`args`, `env` alone, in `cwd`,
7
+ * killed past `timeoutMs`). */
8
+ export type BinaryProbe = {
9
+ readonly kind: "sha256";
10
+ readonly path: string;
11
+ } | {
12
+ readonly kind: "run";
13
+ readonly path: string;
14
+ readonly args: readonly string[];
15
+ readonly env: NodeJS.ProcessEnv;
16
+ readonly cwd?: string;
17
+ readonly timeoutMs: number;
18
+ };
19
+ /** A binary's check, written once as the steps it reads: each step yields a probe and is given back its answer, or has
20
+ * the probe's error thrown in (a file that cannot be read, a binary that cannot be run or does not end in time). It
21
+ * answers its result. */
22
+ export type BinaryCheck<T> = () => Generator<BinaryProbe, T, string>;
3
23
  /** `check`'s result for the binary at `path` against `pins`, run once per identity in this process: a result `ok` calls
4
24
  * passed is kept, and answered again at once while the binary stays the same file, unchanged; any other is never kept.
5
- * A binary that changed while it was checked is not kept, and is checked again next time. */
6
- export declare function checkedOnce<T>(path: string, pins: string, check: () => T, ok: (result: T) => boolean): T;
25
+ * A binary that changed while it was checked is not kept, and is checked again next time. Its reads hold the event
26
+ * loop: a host checks with checkedOnceAsync first, and this answers from what that kept. */
27
+ export declare function checkedOnce<T>(path: string, pins: string, check: BinaryCheck<T>, ok: (result: T) => boolean): T;
28
+ /** checkedOnce without holding the event loop: the sha256 read a chunk at a time off it, the binary run as a child the
29
+ * loop does not wait on. A check of the same binary already running is the one answered; one that passed is kept for
30
+ * checkedOnce too. */
31
+ export declare function checkedOnceAsync<T>(path: string, pins: string, check: BinaryCheck<T>, ok: (result: T) => boolean): Promise<T>;
@@ -1,11 +1,17 @@
1
- // A harness's binary, checked against its pins (codex's, claude-agent's): its sha256 read a chunk at a time, and each
2
- // check that passed kept for the process by what the binary is. A binary is hundreds of MiB; read whole, each check held
3
- // all of it in memory, and a host that checks it again for each model it resolves held it again each time. Here a process
4
- // holds one chunk at most, and checks a binary once per identity: its path, the file it names (device and inode), its
5
- // size and its modification and change times, with the pins it met. Replaced or touched, it is checked again; a check
6
- // that failed is never kept, so the next one runs again.
1
+ // A harness's binary, checked against its pins (codex's, claude-agent's, opencode's): its sha256 read a chunk at a time,
2
+ // and each check that passed kept for the process by what the binary is. A binary is hundreds of MiB; read whole, each
3
+ // check held all of it in memory, and a host that checks it again for each model it resolves held it again each time.
4
+ // Here a process holds one chunk at most, and checks a binary once per identity: its path, the file it names (device and
5
+ // inode), its size and its modification and change times, with the pins it met. Replaced or touched, it is checked
6
+ // again; a check that failed is never kept, so the next one runs again.
7
+ //
8
+ // A check is written once, as the steps it reads of the binary (BinaryCheck: its sha256, what it prints when run), and
9
+ // run either synchronously (checkedOnce: an adapter's own guard as it is made) or without holding the event loop
10
+ // (checkedOnceAsync: a host's, while it goes on answering), each passed check kept for both.
11
+ import { execFile, execFileSync } from "node:child_process";
7
12
  import { createHash } from "node:crypto";
8
13
  import { closeSync, openSync, readSync, statSync } from "node:fs";
14
+ import { open } from "node:fs/promises";
9
15
  /** The bytes read at a time. */
10
16
  const CHUNK = 1 << 20;
11
17
  /** The sha256 of the file at `path`, as hex, read a chunk at a time. Throws as `openSync` and `readSync` do. */
@@ -22,6 +28,64 @@ export function sha256OfFile(path) {
22
28
  }
23
29
  return hash.digest("hex");
24
30
  }
31
+ /** sha256OfFile without holding the event loop: each chunk is read off it, and the loop goes on between chunks. Rejects
32
+ * as `open` and `read` do. */
33
+ export async function sha256OfFileAsync(path) {
34
+ const hash = createHash("sha256");
35
+ const file = await open(path, "r");
36
+ try {
37
+ const chunk = Buffer.allocUnsafe(CHUNK);
38
+ for (;;) {
39
+ const { bytesRead } = await file.read(chunk, 0, CHUNK, null);
40
+ if (bytesRead === 0)
41
+ break;
42
+ hash.update(chunk.subarray(0, bytesRead));
43
+ }
44
+ }
45
+ finally {
46
+ await file.close();
47
+ }
48
+ return hash.digest("hex");
49
+ }
50
+ const runOptions = (probe) => ({ env: probe.env, ...(probe.cwd ? { cwd: probe.cwd } : {}), encoding: "utf8", timeout: probe.timeoutMs });
51
+ /** `check` run with each probe answered synchronously. */
52
+ function checkSync(check) {
53
+ const steps = check();
54
+ for (let step = steps.next();;) {
55
+ if (step.done)
56
+ return step.value;
57
+ let answer;
58
+ try {
59
+ const probe = step.value;
60
+ answer = probe.kind === "sha256" ? sha256OfFile(probe.path) : execFileSync(probe.path, [...probe.args], runOptions(probe));
61
+ }
62
+ catch (error) {
63
+ step = steps.throw(error);
64
+ continue;
65
+ }
66
+ step = steps.next(answer);
67
+ }
68
+ }
69
+ /** One run of a binary, its stdout: rejects as execFileSync throws (a spawn that failed, a nonzero exit, its timeout). */
70
+ const runChild = (probe) => new Promise((resolve, reject) => execFile(probe.path, [...probe.args], runOptions(probe), (error, stdout) => (error ? reject(error) : resolve(stdout))));
71
+ /** `check` run with each probe answered without holding the event loop. */
72
+ async function checkOffLoop(check) {
73
+ const steps = check();
74
+ for (let step = steps.next();;) {
75
+ if (step.done)
76
+ return step.value;
77
+ let answer;
78
+ try {
79
+ const probe = step.value;
80
+ answer = probe.kind === "sha256" ? await sha256OfFileAsync(probe.path) : await runChild(probe);
81
+ }
82
+ catch (error) {
83
+ step = steps.throw(error);
84
+ continue;
85
+ }
86
+ step = steps.next(answer);
87
+ }
88
+ }
25
89
  /** What the file at `path` is, for `pins` (any text that names them): undefined when it cannot be read. */
26
90
  function identityOf(path, pins) {
27
91
  try {
@@ -34,15 +98,40 @@ function identityOf(path, pins) {
34
98
  }
35
99
  /** What each check that passed answered, by the binary's identity. */
36
100
  const passed = new Map();
101
+ /** Each check running without holding the loop, by the binary's identity: a second asks for the same answer. */
102
+ const checking = new Map();
37
103
  /** `check`'s result for the binary at `path` against `pins`, run once per identity in this process: a result `ok` calls
38
104
  * passed is kept, and answered again at once while the binary stays the same file, unchanged; any other is never kept.
39
- * A binary that changed while it was checked is not kept, and is checked again next time. */
105
+ * A binary that changed while it was checked is not kept, and is checked again next time. Its reads hold the event
106
+ * loop: a host checks with checkedOnceAsync first, and this answers from what that kept. */
40
107
  export function checkedOnce(path, pins, check, ok) {
41
108
  const identity = identityOf(path, pins);
42
109
  if (identity !== undefined && passed.has(identity))
43
110
  return passed.get(identity);
44
- const result = check();
111
+ const result = checkSync(check);
45
112
  if (identity !== undefined && ok(result) && identityOf(path, pins) === identity)
46
113
  passed.set(identity, result);
47
114
  return result;
48
115
  }
116
+ /** checkedOnce without holding the event loop: the sha256 read a chunk at a time off it, the binary run as a child the
117
+ * loop does not wait on. A check of the same binary already running is the one answered; one that passed is kept for
118
+ * checkedOnce too. */
119
+ export function checkedOnceAsync(path, pins, check, ok) {
120
+ const identity = identityOf(path, pins);
121
+ if (identity !== undefined && passed.has(identity))
122
+ return Promise.resolve(passed.get(identity));
123
+ const running = identity !== undefined ? checking.get(identity) : undefined;
124
+ if (running)
125
+ return running;
126
+ const result = checkOffLoop(check).then((value) => {
127
+ if (identity !== undefined && ok(value) && identityOf(path, pins) === identity)
128
+ passed.set(identity, value);
129
+ return value;
130
+ });
131
+ if (identity !== undefined) {
132
+ checking.set(identity, result);
133
+ const done = () => void checking.delete(identity);
134
+ result.then(done, done);
135
+ }
136
+ return result;
137
+ }
@@ -19,6 +19,14 @@ import { createServer } from "node:http";
19
19
  import { mcpRoute } from "./mcp-route.js";
20
20
  import { CONTENT_FILTERED } from "../types.js";
21
21
  import { isConnectCode, isGatewayTimeout, rejectionCode } from "../booking.js";
22
+ import { SPEND_CAP_REACHED } from "../kernel/cap/words.js";
23
+ /** 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
+ * error (CapRefused, its `code`), or the runner's stop for the cap's verdict (HarnessRunError, its `refusal`: the
25
+ * verdict's Refusal.code). Never from its words. */
26
+ const capRefusal = (error) => {
27
+ const fields = error;
28
+ return fields?.code === SPEND_CAP_REACHED || fields?.refusal === SPEND_CAP_REACHED;
29
+ };
22
30
  /** The longest a response's text may run with no event boundary before the reasoning count lets it go (a body that is
23
31
  * not a stream of events, read whole as one). */
24
32
  const EVENT_MAX_CHARS = 1 << 22;
@@ -636,7 +644,9 @@ export async function startModelProxy(options, key) {
636
644
  }
637
645
  catch { /* the host's log failed; the request goes on */ }
638
646
  };
639
- const refuse = (res, status, message, req) => {
647
+ /** `code`: the refusal's own code, when it has one (the run's spend cap: `spend_cap_reached`), in the body beside the
648
+ * message, so a reader tells the proxy's refusal by its fields, never by its words. */
649
+ const refuse = (res, status, message, req, code) => {
640
650
  // Every refusal is reported, so a client that calls something the table does not hold is seen, not silently refused.
641
651
  // The client's user-agent names who called: the session's own harness, or another local process that found the port.
642
652
  const agent = req?.headers["user-agent"];
@@ -645,7 +655,7 @@ export async function startModelProxy(options, key) {
645
655
  ...(typeof agent === "string" && agent ? { userAgent: agent.slice(0, 120) } : {}),
646
656
  });
647
657
  res.writeHead(status, { "content-type": "application/json", connection: "close" });
648
- res.end(JSON.stringify({ error: { message, type: "agentrun_proxy" } }));
658
+ res.end(JSON.stringify({ error: { message, type: "agentrun_proxy", ...(code ? { code } : {}) } }));
649
659
  };
650
660
  // The session's MCP door, mounted once here for whichever harness's client calls it (the call id from its fact).
651
661
  const mcpDoor = options.mcp && mcpRoute(options.mcp.session, { callIdMeta: options.mcp.client.callIdMeta, ...(options.mcp.keepaliveMs !== undefined ? { keepaliveMs: options.mcp.keepaliveMs } : {}) });
@@ -861,7 +871,7 @@ export async function startModelProxy(options, key) {
861
871
  }
862
872
  catch (error) {
863
873
  // Not 429: clients retry that, and the runner already refused this request (a turn cap, the host's budget).
864
- return refuse(res, refusedStatus, `refused before it was sent: ${String(error?.message ?? error).slice(0, 300)}`, req);
874
+ return refuse(res, refusedStatus, `refused before it was sent: ${String(error?.message ?? error).slice(0, 300)}`, req, capRefusal(error) ? SPEND_CAP_REACHED : undefined);
865
875
  }
866
876
  /** An admitted request that is not sent after all: refused to its client, and released, booked at nothing, so the
867
877
  * runner's count agrees. */
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { createHarnessRunner, modelPortFor, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
1
+ export { answeredUnpriced, createHarnessRunner, modelPortFor, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
2
2
  export { runBooking, type RunSessions } from "./run-booking.js";
3
3
  export type { Admission, BeforeRequest, Refusal, HarnessRunner, HarnessRunnerOptions, InFlight, ModelBooking, ModelPortEvent, ModelPortOptions, SessionCost } from "./runner.js";
4
4
  export { DELEGATE_RESULT_SCHEMA, DELEGATE_TOOL, delegateProblems, delegateTool } from "./delegate.js";
@@ -8,7 +8,7 @@ export { toolSchemaProblems } from "./schema-check.js";
8
8
  export { READ_SKILL_FILE, readSkillFileTool, SKILL_BYTES, skillProblems } from "./skill-files.js";
9
9
  export type { HostSkill, SkillFileList } from "./skill-files.js";
10
10
  export type { HarnessRunReason } from "./errors.js";
11
- export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS } from "./types.js";
11
+ export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS, hostedTool } from "./types.js";
12
12
  export { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "./booking.js";
13
13
  export type { Booked, Ended, Priced } from "./booking.js";
14
14
  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";
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- export { createHarnessRunner, modelPortFor, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
1
+ export { answeredUnpriced, createHarnessRunner, modelPortFor, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
2
2
  export { runBooking } from "./run-booking.js";
3
3
  export { DELEGATE_RESULT_SCHEMA, DELEGATE_TOOL, delegateProblems, delegateTool } from "./delegate.js";
4
4
  export { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
5
5
  export { toolSchemaProblems } from "./schema-check.js";
6
6
  export { READ_SKILL_FILE, readSkillFileTool, SKILL_BYTES, skillProblems } from "./skill-files.js";
7
- export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS } from "./types.js";
7
+ export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS, hostedTool } from "./types.js";
8
8
  export { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "./booking.js";
@@ -1,9 +1,9 @@
1
1
  export { CapRefused, createCap, DECISION_IMAGE_TOKENS, DECISION_OUTPUT_TOKENS, DecisionPriceUnreadable, END_MARK_WAIT_MS, END_NOT_WRITTEN, MARK_NOT_WRITTEN, openCap } from "./admit.js";
2
2
  export { capRule, noteFor, type Judged, type JudgeState, type NoteState } from "./rule.js";
3
3
  export { beforeRequestOf, type BeforeRequestOptions } from "./port.js";
4
- export { DECISION_SESSION, paidCalls, runCap, TOOL_SESSION, type RunCap, type RunCapOptions, type RunDecisions, type RunTools } from "./run-cap.js";
4
+ export { DECISION_SESSION, overCapOf, paidCalls, runCap, TOOL_SESSION, type RunCap, type RunCapOptions, type RunDecisions, type RunTools } from "./run-cap.js";
5
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";
6
- export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, overCapWords, raiseFigure, raiseTo, suggestedRaise } from "./words.js";
6
+ export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, OVER_CAP_END, overCapEnd, overCapMessage, overCapWords, raiseFigure, raiseTo, 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";
9
9
  export { CapStop, createStepWaits, type StepWaits } from "./steps.js";
@@ -3,9 +3,9 @@
3
3
  export { CapRefused, createCap, DECISION_IMAGE_TOKENS, DECISION_OUTPUT_TOKENS, DecisionPriceUnreadable, END_MARK_WAIT_MS, END_NOT_WRITTEN, MARK_NOT_WRITTEN, openCap } from "./admit.js";
4
4
  export { capRule, noteFor } from "./rule.js";
5
5
  export { beforeRequestOf } from "./port.js";
6
- export { DECISION_SESSION, paidCalls, runCap, TOOL_SESSION } from "./run-cap.js";
6
+ export { DECISION_SESSION, overCapOf, paidCalls, runCap, TOOL_SESSION } from "./run-cap.js";
7
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";
8
- export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, overCapWords, raiseFigure, raiseTo, suggestedRaise } from "./words.js";
8
+ export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, OVER_CAP_END, overCapEnd, overCapMessage, overCapWords, raiseFigure, raiseTo, 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";
11
11
  export { CapStop, createStepWaits } from "./steps.js";
@@ -1,5 +1,5 @@
1
1
  import { CAP_TOLERANCE } from "./price.js";
2
- import { CAP_REFUSAL_CODE, money, suggestedRaise } from "./words.js";
2
+ import { CAP_REFUSAL_CODE, money, SPEND_CAP_REACHED, suggestedRaise } from "./words.js";
3
3
  const micro = (usd) => Math.round(usd * 1e6) / 1e6;
4
4
  /** A bound to a millionth, rounded up (never under what it bounds), as main's overshoot bound is (run-view.ts microUp);
5
5
  * no bound is 0, never -0 (the ceiling of a hair under 0 is -0, which a card would print as "-0"). */
@@ -9,7 +9,9 @@ export function parkOf(refusal, capUsd) {
9
9
  if (refusal.forGood || !refusal.figures)
10
10
  return { outcome: "failed", error: refusal.message };
11
11
  const { spentUsd, needsUsd, leastCapUsd, boundUsd } = refusal.figures;
12
- const words = refusal.message.startsWith(CAP_REFUSAL_CODE) ? refusal.message.slice(CAP_REFUSAL_CODE.length) : refusal.message;
12
+ // Its words without the refusal's code: a model request's ("spend_cap_reached (out of budget): ") or a paid step's
13
+ // ("spend_cap_reached: "), so a pause reads its sentence alone, whichever step was refused.
14
+ const words = [CAP_REFUSAL_CODE, `${SPEND_CAP_REACHED}: `].reduce((said, code) => (said.startsWith(code) ? said.slice(code.length) : said), refusal.message);
13
15
  return {
14
16
  outcome: "parked",
15
17
  pending: { kind: "budget", cap_usd: capUsd, spent_usd: micro(spentUsd), needs_usd: micro(needsUsd), least_cap_usd: leastCapUsd, suggested_cap_usd: suggestedRaise(capUsd, spentUsd, needsUsd), bound_usd: microUp(boundUsd ?? 0) },
@@ -1,7 +1,10 @@
1
1
  import { CapRefused } from "./errors.js";
2
2
  import { inputBound, pricingOf } from "./price.js";
3
3
  import { capRule, isFigure } from "./rule.js";
4
- import { unmeasured } from "./words.js";
4
+ import { SPEND_CAP_REACHED, unmeasured } from "./words.js";
5
+ /** The cap's refusal as the runner takes it: its words, its code, and what the run's end is decided from (parkOf): for
6
+ * good, or for room with its figures. */
7
+ const refusalOf = (error) => ({ refuse: error.message, code: error.code, forGood: error.forGood, ...(error.figures ? { figures: error.figures } : {}) });
5
8
  /** A model the host has no price for: refused under a cap, by the rule. */
6
9
  const unpriced = (id) => ({ id, api: "unknown", price: null, outputCeiling: null });
7
10
  /** The host's beforeRequest for a CLI harness's session: the runner's spend and holds, judged by the one rule. */
@@ -12,6 +15,11 @@ export function beforeRequestOf(options) {
12
15
  const capUsd = options.capUsd();
13
16
  if (capUsd === undefined)
14
17
  return undefined;
18
+ // `owed`: money already owed at the provider: booked and held, never asked of the rule; only for charges incurred
19
+ // outside a call (a browser session's release, the time a person used). It counts in the run's spend and holds like
20
+ // any paid step, so every refusable step after it sees it. Only a figure is money: one that is not goes to the rule.
21
+ if (request.paid?.owed && isFigure(request.feeUsd ?? 0))
22
+ return { holdUsd: request.feeUsd ?? 0 };
15
23
  const model = options.modelOf(request.model) ?? unpriced(request.model);
16
24
  // A request the host sends beside the harness's own (its host label: a learned workflow's node) is another
17
25
  // conversation's prompt: nothing of the session's cache is read for it, so it is priced as a cache miss.
@@ -33,7 +41,7 @@ export function beforeRequestOf(options) {
33
41
  for (const flight of request.inFlight) {
34
42
  const figure = isFigure(flight.holdUsd) ? flight.holdUsd : worstOf(options.modelOf(flight.model), flight.inputTokensMax, flight.outputTokensMax);
35
43
  if (figure === undefined)
36
- return { refuse: unmeasured(capUsd) };
44
+ return { refuse: unmeasured(capUsd), code: SPEND_CAP_REACHED };
37
45
  inFlight += figure;
38
46
  }
39
47
  // The run's spend and holds: the runner's (its model requests) and the host's (its priced tools).
@@ -53,7 +61,7 @@ export function beforeRequestOf(options) {
53
61
  }
54
62
  catch (error) {
55
63
  if (error instanceof CapRefused)
56
- return { refuse: error.message, forGood: error.forGood, ...(error.figures ? { figures: error.figures } : {}) };
64
+ return refusalOf(error);
57
65
  throw error;
58
66
  }
59
67
  }
@@ -65,7 +73,7 @@ export function beforeRequestOf(options) {
65
73
  catch (error) {
66
74
  // Its words, and what the run's end is decided from (parkOf): for good, or for room with its figures.
67
75
  if (error instanceof CapRefused)
68
- return { refuse: error.message, forGood: error.forGood, ...(error.figures ? { figures: error.figures } : {}) };
76
+ return refusalOf(error);
69
77
  throw error;
70
78
  }
71
79
  };
@@ -1,6 +1,6 @@
1
1
  import { type RunSessions } from "../../run-booking.js";
2
2
  import { type BeforeRequest } from "../../runner.js";
3
- import type { SessionWriter } from "../../types.js";
3
+ import type { SessionRecord, SessionWriter } from "../../types.js";
4
4
  import type { Admission, CapMode, CapModel, DecisionCapRequest, Previous, Settled } from "./types.js";
5
5
  /** The session a run's workflow decisions book under. */
6
6
  export declare const DECISION_SESSION = "decisions";
@@ -52,7 +52,10 @@ export interface RunCap {
52
52
  export interface RunTools {
53
53
  /** Admits the paid request `id` at its price (`holdUsd`): its hold, or CapRefused. `call`: the tool call it runs under,
54
54
  * named on its runner.request (none for a step under no call, a person's browser time); `chargedBy`, who charges
55
- * for it, named there as `charged_by`. */
55
+ * for it, named there as `charged_by`; `tool` and `tag`, the tool whose charge it is and its session (ModelRequest.paid);
56
+ * `owed`, money its provider is already owed: held and booked, never refused. `hold`: a hold-only step: money
57
+ * reserved, not spent; given back on a lost claim, never booked as cut. `ref`: the one booking it names: a ref already
58
+ * booked (on the run's records, or on this claim) books nothing again, and the answer says `booked`. */
56
59
  admit(request: {
57
60
  readonly id: string;
58
61
  readonly name: string;
@@ -60,7 +63,14 @@ export interface RunTools {
60
63
  readonly basis: string;
61
64
  readonly call?: string;
62
65
  readonly chargedBy?: string;
63
- }): Promise<Admission>;
66
+ readonly tool?: string;
67
+ readonly tag?: string;
68
+ readonly owed?: true;
69
+ readonly hold?: true;
70
+ readonly ref?: string;
71
+ }): Promise<Admission & {
72
+ readonly booked?: true;
73
+ }>;
64
74
  /** Settles it at what it charged (null: at its hold; 0: nothing was billed). `givenBack`: its hold let go unused,
65
75
  * nothing sent (at 0), its record marked so (ModelUsage.givenBack): never read as a $0 charge or an unpriced one. */
66
76
  settle(id: string, usd: number | null, options?: {
@@ -71,6 +81,12 @@ export interface RunTools {
71
81
  }
72
82
  /** The session a run's paid tool calls book under. */
73
83
  export declare const TOOL_SESSION = "paid-tools";
84
+ /** How a run ends once its booked spend passed its cap (overCapEnd), read from its model session's `records` and what
85
+ * its other sessions spent (`othersUsd`): each request at the figure the cap counts it at (sessionSpendOf's figures: one
86
+ * cut by a crash at its hold plus its bound), and the bound of the requests since the spend last fit, so a cache miss
87
+ * within that bound (a cut request's possible one included) pauses the run instead. Undefined while it fits, by such a
88
+ * miss, or with a spend unknown. */
89
+ export declare function overCapOf(records: readonly SessionRecord[], othersUsd: number, capUsd: number): string | undefined;
74
90
  export declare function runCap(options: RunCapOptions): RunCap;
75
91
  /** A run's paid tool calls booked on `writer` (its TOOL_SESSION) under `before`, the run's one rule (runCap's, or the
76
92
  * adapter loop's runBooking over its spec's check): each held at its price before it is sent (main's paidCall, by the
@@ -6,7 +6,8 @@
6
6
  // spend of both from the journal: a decision held and never answered counts at its hold and its bound, as any request.
7
7
  // Decisions book under their own session (DECISION_SESSION), priced as main holds them (decisionAsk).
8
8
  import { runBooking } from "../../run-booking.js";
9
- import { modelPortFor } from "../../runner.js";
9
+ import { modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "../../runner.js";
10
+ import { overCapEnd } from "./words.js";
10
11
  import { decisionAsk } from "./admit.js";
11
12
  import { CapRefused, DecisionPriceUnreadable } from "./errors.js";
12
13
  import { beforeRequestOf } from "./port.js";
@@ -14,6 +15,23 @@ import { beforeRequestOf } from "./port.js";
14
15
  export const DECISION_SESSION = "decisions";
15
16
  /** The session a run's paid tool calls book under. */
16
17
  export const TOOL_SESSION = "paid-tools";
18
+ /** How a run ends once its booked spend passed its cap (overCapEnd), read from its model session's `records` and what
19
+ * its other sessions spent (`othersUsd`): each request at the figure the cap counts it at (sessionSpendOf's figures: one
20
+ * cut by a crash at its hold plus its bound), and the bound of the requests since the spend last fit, so a cache miss
21
+ * within that bound (a cut request's possible one included) pauses the run instead. Undefined while it fits, by such a
22
+ * miss, or with a spend unknown. */
23
+ export function overCapOf(records, othersUsd, capUsd) {
24
+ const read = sessionSpendOf(records);
25
+ if (read.spentUsd === null)
26
+ return undefined;
27
+ let running = othersUsd;
28
+ let bound = 0;
29
+ for (const { turn, usd } of read.figures) {
30
+ running += usd ?? 0;
31
+ bound = running <= capUsd ? 0 : bound + (read.bounds.get(turn) ?? 0);
32
+ }
33
+ return overCapEnd(othersUsd + read.spentUsd, capUsd, bound);
34
+ }
17
35
  export function runCap(options) {
18
36
  const mode = options.mode ?? "expected";
19
37
  /** Each decision under way's model, as the rule prices it (decisionAsk), by the model key its request books under. */
@@ -62,9 +80,29 @@ export function runCap(options) {
62
80
  * rule's tool judgement), flushed first when `flush` is given, and settled at what it charged. */
63
81
  export async function paidCalls(writer, before, options = {}) {
64
82
  const steps = await stepsOn(writer, before, options.flush, "paid call", () => { });
83
+ // Each `ref` the run's paid steps have booked (on its records, or admitted on this claim): a ref names one booking, so a
84
+ // second admit of it books nothing (`booked`) and opens no step.
85
+ let refs;
86
+ const refsOf = () => (refs ??= writer.read().then((records) => new Set(records.filter((r) => r.kind === RUNNER_RECORDS.request).map((r) => r.data?.ref).filter((ref) => typeof ref === "string"))));
87
+ const book = (request) =>
88
+ // A hold that is no figure (an unpriced browser provider's) goes to the rule as given, which refuses it for good.
89
+ steps.book(request.id, { model: `paid:${request.name}`, inputTokensMax: 0, ...(request.holdUsd !== 0 ? { feeUsd: request.holdUsd } : {}), paid: { name: request.name, basis: request.basis, ...(request.call === undefined ? {} : { call: request.call }), ...(request.chargedBy === undefined ? {} : { charged_by: request.chargedBy }), ...(request.tool === undefined ? {} : { tool: request.tool }), ...(request.tag === undefined ? {} : { tag: request.tag }), ...(request.owed ? { owed: true } : {}), ...(request.hold ? { hold: true } : {}), ...(request.ref === undefined ? {} : { ref: request.ref }) } });
65
90
  return {
66
- // A hold that is no figure (an unpriced browser provider's) goes to the rule as given, which refuses it for good.
67
- admit: (request) => steps.book(request.id, { model: `paid:${request.name}`, inputTokensMax: 0, ...(request.holdUsd !== 0 ? { feeUsd: request.holdUsd } : {}), paid: { name: request.name, basis: request.basis, ...(request.call === undefined ? {} : { call: request.call }), ...(request.chargedBy === undefined ? {} : { charged_by: request.chargedBy }) } }),
91
+ admit: async (request) => {
92
+ if (request.ref === undefined)
93
+ return book(request);
94
+ const booked = await refsOf();
95
+ if (booked.has(request.ref))
96
+ return { id: request.id, heldUsd: 0, boundUsd: 0, worstUsd: 0, stoppedUsd: () => 0, booked: true };
97
+ booked.add(request.ref);
98
+ try {
99
+ return await book(request);
100
+ }
101
+ catch (error) {
102
+ booked.delete(request.ref);
103
+ throw error;
104
+ }
105
+ },
68
106
  settle: (id, usd, options) => steps.settle(id, options?.givenBack ? 0 : usd, options),
69
107
  spentUsd: steps.spentUsd,
70
108
  heldUsd: steps.heldUsd,
@@ -31,6 +31,15 @@ export declare function paidRefusal(cap: number, spent: number, held: number, na
31
31
  * by no more than `boundUsd` (the bound of the requests since the cost last fit), a cache miss did it, and the most it
32
32
  * could have. None at or under the cap, with no cap, or with no known cost. */
33
33
  export declare function overCapWords(spentUsd: number | null, capUsd: number | undefined, boundUsd?: number): string | undefined;
34
+ /** How a run ends whose booked cost `spentUsd` passed `capUsd`: failed, in these words (main's run end), the answer that
35
+ * crossed it booked. None at or under the cap, with no cap, with no known cost, or when it passed by no more than
36
+ * `boundUsd` (a cache miss within the bound it was admitted at: the run pauses at its next request instead). */
37
+ export declare function overCapEnd(spentUsd: number | null, capUsd: number | undefined, boundUsd?: number): string | undefined;
38
+ /** How overCapEnd's words begin, and only theirs: a reader of a run's summary serves one that does as the error
39
+ * spend_cap_reached, its message the words after `spend_cap_reached: ` (overCapMessage). */
40
+ export declare const OVER_CAP_END = "spend_cap_reached: The run cost ";
41
+ /** The message of a run's end in overCapEnd's words: what follows its code; undefined for any other summary. */
42
+ export declare const overCapMessage: (summary: string | null | undefined) => string | undefined;
34
43
  export declare const unmeasured: (cap: number) => string;
35
44
  export declare const noPrice: (cap: number) => string;
36
45
  export declare const noCeiling: (cap: number) => string;
@@ -67,6 +67,21 @@ export function overCapWords(spentUsd, capUsd, boundUsd = 0) {
67
67
  const byMiss = boundUsd > 0 && spentUsd - capUsd <= boundUsd + FIT_TOLERANCE;
68
68
  return byMiss ? `Went ${centsUp(spentUsd - capUsd)} over its cap on a cache miss (at most ${centsUp(boundUsd)}).` : `Spent ${centsMoney(spentUsd)}, ${centsUp(spentUsd - capUsd)} over the run's cap of ${centsMoney(capUsd)}`;
69
69
  }
70
+ /** How a run ends whose booked cost `spentUsd` passed `capUsd`: failed, in these words (main's run end), the answer that
71
+ * crossed it booked. None at or under the cap, with no cap, with no known cost, or when it passed by no more than
72
+ * `boundUsd` (a cache miss within the bound it was admitted at: the run pauses at its next request instead). */
73
+ export function overCapEnd(spentUsd, capUsd, boundUsd = 0) {
74
+ if (capUsd === undefined || typeof spentUsd !== "number" || spentUsd <= capUsd + FIT_TOLERANCE)
75
+ return undefined;
76
+ if (boundUsd > 0 && spentUsd - capUsd <= boundUsd + FIT_TOLERANCE)
77
+ return undefined;
78
+ return `${OVER_CAP_END}${centsMoney(spentUsd)}, ${centsUp(spentUsd - capUsd)} over its cap of ${centsMoney(capUsd)}.`;
79
+ }
80
+ /** How overCapEnd's words begin, and only theirs: a reader of a run's summary serves one that does as the error
81
+ * spend_cap_reached, its message the words after `spend_cap_reached: ` (overCapMessage). */
82
+ export const OVER_CAP_END = `${SPEND_CAP_REACHED}: The run cost `;
83
+ /** The message of a run's end in overCapEnd's words: what follows its code; undefined for any other summary. */
84
+ export const overCapMessage = (summary) => typeof summary === "string" && summary.startsWith(OVER_CAP_END) ? summary.slice(`${SPEND_CAP_REACHED}: `.length) : undefined;
70
85
  export const unmeasured = (cap) => `${SPEND_CAP_REACHED}: Not sent: the size of the next model request's input is unknown, so the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
71
86
  export const noPrice = (cap) => `${SPEND_CAP_REACHED}: Not sent: the next model request's model has no price here, so the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
72
87
  export const noCeiling = (cap) => `${SPEND_CAP_REACHED}: Not sent: the next model request's model has no output ceiling here and its output is priced, so what a request may cost has no bound and the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
@@ -1,4 +1,3 @@
1
- import { type BrowserContract } from "./browser.js";
2
1
  import type { CapabilityKind } from "./hands.js";
3
2
  /** Where the run's shell is: on a computer (bash and the background tools run there), the run's folder's own exec with no
4
3
  * computer (bash only, asked first: a host gives it only where that exec is not its own machine, as serve's Archil
@@ -35,8 +34,6 @@ export declare function hostToolDefs(options: {
35
34
  }): readonly ToolDef[];
36
35
  /** The kinds, in the order their tools follow the host tools. */
37
36
  export declare const CAPABILITY_KINDS: readonly CapabilityKind[];
38
- /** A computer kind's own tools, which a run of that kind sees after its host tools: the desktop's (desktop.ts), the
39
- * phone's (phone.ts), or the browser's, pi-browser's contracts the host passes (browser.ts). */
40
- export declare function capabilityToolDefs(kind: CapabilityKind, options?: {
41
- readonly browserTools?: readonly BrowserContract[];
42
- }): readonly ToolDef[];
37
+ /** A computer kind's own tools, which a run of that kind sees after its host tools: the desktop's (desktop.ts) or the
38
+ * phone's (phone.ts). */
39
+ export declare function capabilityToolDefs(kind: CapabilityKind): readonly ToolDef[];
@@ -2,8 +2,7 @@
2
2
  // edit and bash are pi's (pi 1.5.0's coding tools, MIT), with serve's additions: bash's timeout words and read's image
3
3
  // sentence on a computer. The five background tools are serve's (background.ts). A test holds every one of them, in
4
4
  // order, to serve's own on main. A computer of a kind past files and a shell adds its own tools after them
5
- // (capabilityToolDefs): the desktop's, the phone's, the browser's.
6
- import { browserToolDefs } from "./browser.js";
5
+ // (capabilityToolDefs): the desktop's, the phone's.
7
6
  import { DESKTOP_TOOL_DEFS } from "./desktop.js";
8
7
  import { PHONE_TOOL_DEFS } from "./phone.js";
9
8
  import { BACKGROUND_INPUT_BYTES, BACKGROUND_LIST_MAX, BACKGROUND_LOG_BYTES, BACKGROUND_MAX, BACKGROUND_PAGE_BYTES, BACKGROUND_SIGNALS, BASH_DEFAULT_TIMEOUT_S } from "./limits.js";
@@ -141,13 +140,9 @@ export function hostToolDefs(options) {
141
140
  return defs;
142
141
  }
143
142
  /** The kinds, in the order their tools follow the host tools. */
144
- export const CAPABILITY_KINDS = Object.freeze(["desktop", "phone", "browser"]);
145
- /** A computer kind's own tools, which a run of that kind sees after its host tools: the desktop's (desktop.ts), the
146
- * phone's (phone.ts), or the browser's, pi-browser's contracts the host passes (browser.ts). */
147
- export function capabilityToolDefs(kind, options = {}) {
148
- if (kind === "desktop")
149
- return DESKTOP_TOOL_DEFS;
150
- if (kind === "phone")
151
- return PHONE_TOOL_DEFS;
152
- return browserToolDefs(options.browserTools);
143
+ export const CAPABILITY_KINDS = Object.freeze(["desktop", "phone"]);
144
+ /** A computer kind's own tools, which a run of that kind sees after its host tools: the desktop's (desktop.ts) or the
145
+ * phone's (phone.ts). */
146
+ export function capabilityToolDefs(kind) {
147
+ return kind === "desktop" ? DESKTOP_TOOL_DEFS : PHONE_TOOL_DEFS;
153
148
  }
@@ -61,7 +61,7 @@ export type Processes = {
61
61
  list(): Promise<readonly ProcessInfo[]>;
62
62
  };
63
63
  /** A computer's kind past files and a shell: each adds its own tools to the run's (defs.ts capabilityToolDefs). */
64
- export type CapabilityKind = "desktop" | "phone" | "browser";
64
+ export type CapabilityKind = "desktop" | "phone";
65
65
  /** A kind's tool refused in a run whose computer is not of that kind (or lacks the port): the words name the setting. */
66
66
  export declare const needsKindWords: (tool: string, kind: CapabilityKind) => string;
67
67
  /** A screenshot as a tool's answer: the words, and the PNG in the answer's images. */
@@ -173,20 +173,6 @@ export type Phone = {
173
173
  open(id: string): Promise<void>;
174
174
  };
175
175
  };
176
- /** A connection to a browser's DevTools protocol (pi-browser's CdpLink, in shape). */
177
- export type CdpSession = {
178
- send(method: string, params?: object, sessionId?: string): Promise<unknown>;
179
- on(listener: (event: {
180
- method?: string;
181
- params?: unknown;
182
- sessionId?: string;
183
- }) => void): () => void;
184
- close(): void;
185
- };
186
- /** A browser computer: a connection to its CDP. The browser's tools and take-over are the host's (pi-browser's). */
187
- export type Browser = {
188
- connect(): Promise<CdpSession>;
189
- };
190
176
  /** The agent's hand-over of a desktop or a phone to the person, through the run's hold: ask opens it (what the person is
191
177
  * to do, how both will know it is done, when it expires, ISO time) and resolves with its first answer, or expired. An
192
178
  * abort of `signal` (a stop, a lost claim) rejects it. */
@@ -241,8 +227,6 @@ export type Hands = {
241
227
  readonly input?: Input;
242
228
  /** A phone's screen, touch, typing and apps; absent where the computer is no phone. */
243
229
  readonly phone?: Phone;
244
- /** A browser's CDP; absent where the computer is no browser. */
245
- readonly browser?: Browser;
246
230
  /** A desktop's or a phone's hand-over to the person (the run's hold); absent where there is none. */
247
231
  readonly handoff?: Handoff;
248
232
  };
@@ -273,8 +257,5 @@ export type ToolCall = {
273
257
  export declare function answerOf(call: ToolCall, run: () => Promise<ToolAnswer>): Promise<ToolAnswer>;
274
258
  /** A host tool's run. */
275
259
  export type Executor = (args: unknown, call: ToolCall) => Promise<ToolAnswer>;
276
- /** What the host gives the registry, by tool name: read, write and edit, and bash's own run, which the registry bounds;
277
- * and, for a browser, its tools' runs (pi-browser's, over hands.browser), by tool name. */
278
- export type HostExecutors = Readonly<Partial<Record<"read" | "write" | "edit" | "bash", Executor>>> & {
279
- readonly browser?: Readonly<Record<string, Executor>>;
280
- };
260
+ /** What the host gives the registry, by tool name: read, write and edit, and bash's own run, which the registry bounds. */
261
+ export type HostExecutors = Readonly<Partial<Record<"read" | "write" | "edit" | "bash", Executor>>>;
@@ -1,14 +1,12 @@
1
1
  export { BACKGROUND_EXECUTORS, endBackground, NEEDS_A_COMPUTER, NO_SHELL } from "./background.js";
2
2
  export { boundedBash } from "./bash.js";
3
- export { browserToolDefs } from "./browser.js";
4
- export type { BrowserContract } from "./browser.js";
5
3
  export { bashTimeoutWords, CAPABILITY_KINDS, capabilityToolDefs, hostToolDefs } from "./defs.js";
6
4
  export type { ShellPlace, ToolDef } from "./defs.js";
7
5
  export { DESKTOP_ACTIONS, DESKTOP_EXECUTORS, DESKTOP_KEYS, DESKTOP_MAX_ACTIONS, DESKTOP_TOOL_DEFS } from "./desktop.js";
8
6
  export { defaultPermissionOf, SHELL_FAMILY, SHELL_WATCHERS, shellPermission, shellToolOf } from "./gate.js";
9
7
  export type { Permission } from "./gate.js";
10
8
  export { answerOf, exitCodeOf, needsKindWords } from "./hands.js";
11
- export type { Browser, CapabilityKind, CdpSession, ExecResult, Executor, Hands, HostExecutors, Input, InputAction, Phone, PhoneKey, PhoneNode, PhonePoint, ProcessInfo, Processes, Screen, ScreenPoint, Shot, ToolAnswer, ToolCall, } from "./hands.js";
9
+ export type { CapabilityKind, ExecResult, Executor, Hands, HostExecutors, Input, InputAction, Phone, PhoneKey, PhoneNode, PhonePoint, ProcessInfo, Processes, Screen, ScreenPoint, Shot, ToolAnswer, ToolCall, } from "./hands.js";
12
10
  export { PHONE_EXECUTORS, PHONE_KEYS, PHONE_SWIPE_MAX_MS, PHONE_SWIPE_MS, PHONE_TOOL_DEFS, PHONE_TREE_MAX_CHARS, PHONE_TREE_MAX_NODES } from "./phone.js";
13
11
  export { HANDOFF_DEFAULT_S, HANDOFF_MAX_S, HANDOFF_MIN_S, HANDOFF_TOOL } from "./handoff.js";
14
12
  export type { Handoff } from "./hands.js";
@@ -1,9 +1,9 @@
1
1
  // The kernel's one tool registry: the host tools' definitions, words and limits, the gate's shell family, the run's
2
- // hands, and the executors the kernel owns; a computer kind's own tools (desktop, phone, browser) and the narrow ports
3
- // they run on. Unused on main until the cutover wires serve onto it.
2
+ // hands, and the executors the kernel owns; a computer kind's own tools (desktop, phone) and the narrow ports they run
3
+ // on. A browser computer's tools are the host's browser tool's (serve's tools.ts, pi-browser's durable extension), not
4
+ // the registry's.
4
5
  export { BACKGROUND_EXECUTORS, endBackground, NEEDS_A_COMPUTER, NO_SHELL } from "./background.js";
5
6
  export { boundedBash } from "./bash.js";
6
- export { browserToolDefs } from "./browser.js";
7
7
  export { bashTimeoutWords, CAPABILITY_KINDS, capabilityToolDefs, hostToolDefs } from "./defs.js";
8
8
  export { DESKTOP_ACTIONS, DESKTOP_EXECUTORS, DESKTOP_KEYS, DESKTOP_MAX_ACTIONS, DESKTOP_TOOL_DEFS } from "./desktop.js";
9
9
  export { defaultPermissionOf, SHELL_FAMILY, SHELL_WATCHERS, shellPermission, shellToolOf } from "./gate.js";
@@ -1,4 +1,3 @@
1
- import type { BrowserContract } from "./browser.js";
2
1
  import { type ShellPlace, type ToolDef } from "./defs.js";
3
2
  import { type CapabilityKind, type HostExecutors, type ToolAnswer, type ToolCall } from "./hands.js";
4
3
  export type Registry = {
@@ -7,9 +6,8 @@ export type Registry = {
7
6
  get(name: string): ToolDef | undefined;
8
7
  invoke(name: string, args: unknown, call: ToolCall): Promise<ToolAnswer>;
9
8
  };
10
- /** The registry of a run's host tools, by where its shell is, and its computer's kinds (`kinds`: none, or the desktop,
11
- * the phone or the browser it is), with the host's executors. `browserTools`: pi-browser's BROWSER_TOOLS, as the host
12
- * lists them for this run; needed with the browser kind, and naming them in a refusal without it. `without`: a kind's
9
+ /** The registry of a run's host tools, by where its shell is, and its computer's kinds (`kinds`: none, or the desktop
10
+ * or the phone it is), with the host's executors. `without`: a kind's
13
11
  * tools this run's computer does not offer (its capabilities lack them: an iPhone's tree and keys, say), not listed to
14
12
  * the model; one called anyway runs, and its port's absence answers in words. */
15
13
  export declare function createRegistry(options: {
@@ -17,6 +15,5 @@ export declare function createRegistry(options: {
17
15
  shell: ShellPlace;
18
16
  kinds?: readonly CapabilityKind[];
19
17
  executors: HostExecutors;
20
- browserTools?: readonly BrowserContract[];
21
18
  without?: readonly string[];
22
19
  }): Registry;
@@ -2,9 +2,9 @@
2
2
  // write and edit, and bash's own run, are the host's (pi's tools over the run's hands, until their semantics move
3
3
  // here); the kernel bounds bash and runs the five background tools itself. A computer of a kind past files and a shell
4
4
  // adds its kind's tools after them, in a fixed order: the desktop's and the phone's run on the kernel's own executors
5
- // over the hands' narrow ports; the browser's are the host's contracts and runs (pi-browser's). A registry missing an
6
- // executor for a tool the model sees is refused when it is built, so a run never offers a tool it cannot run. A kind's
7
- // tool the run does not have is refused in words that name the setting.
5
+ // over the hands' narrow ports. A registry missing an executor for a tool the model sees is refused when it is built,
6
+ // so a run never offers a tool it cannot run. A kind's tool the run does not have is refused in words that name the
7
+ // setting.
8
8
  import { BACKGROUND_EXECUTORS, NEEDS_A_COMPUTER, NO_SHELL } from "./background.js";
9
9
  import { boundedBash } from "./bash.js";
10
10
  import { CAPABILITY_KINDS, capabilityToolDefs, hostToolDefs } from "./defs.js";
@@ -12,9 +12,8 @@ import { DESKTOP_EXECUTORS, DESKTOP_TOOL_DEFS } from "./desktop.js";
12
12
  import { answerOf, needsKindWords } from "./hands.js";
13
13
  import { BACKGROUND_TOOLS } from "./limits.js";
14
14
  import { PHONE_EXECUTORS, PHONE_TOOL_DEFS } from "./phone.js";
15
- /** The registry of a run's host tools, by where its shell is, and its computer's kinds (`kinds`: none, or the desktop,
16
- * the phone or the browser it is), with the host's executors. `browserTools`: pi-browser's BROWSER_TOOLS, as the host
17
- * lists them for this run; needed with the browser kind, and naming them in a refusal without it. `without`: a kind's
15
+ /** The registry of a run's host tools, by where its shell is, and its computer's kinds (`kinds`: none, or the desktop
16
+ * or the phone it is), with the host's executors. `without`: a kind's
18
17
  * tools this run's computer does not offer (its capabilities lack them: an iPhone's tree and keys, say), not listed to
19
18
  * the model; one called anyway runs, and its port's absence answers in words. */
20
19
  export function createRegistry(options) {
@@ -32,13 +31,13 @@ export function createRegistry(options) {
32
31
  }
33
32
  const defs = [...own];
34
33
  for (const kind of kinds) {
35
- for (const def of capabilityToolDefs(kind, options.browserTools ? { browserTools: options.browserTools } : {})) {
34
+ for (const def of capabilityToolDefs(kind)) {
36
35
  // A tool two kinds share (the hand-over) is listed once, as the first kind gives it.
37
36
  if (runs.has(def.name))
38
37
  continue;
39
- const run = kind === "desktop" ? DESKTOP_EXECUTORS[def.name] : kind === "phone" ? PHONE_EXECUTORS[def.name] : executors.browser?.[def.name];
38
+ const run = kind === "desktop" ? DESKTOP_EXECUTORS[def.name] : PHONE_EXECUTORS[def.name];
40
39
  if (!run)
41
- throw new Error(`the registry has no executor for ${def.name}, a ${kind} tool the model sees: the host gives the browser's runs`);
40
+ throw new Error(`the registry has no executor for ${def.name}, a ${kind} tool the model sees`);
42
41
  runs.set(def.name, run);
43
42
  if (!options.without?.includes(def.name))
44
43
  defs.push(def);
@@ -48,7 +47,6 @@ export function createRegistry(options) {
48
47
  const kindOf = new Map([
49
48
  ...DESKTOP_TOOL_DEFS.map((def) => [def.name, "desktop"]),
50
49
  ...PHONE_TOOL_DEFS.map((def) => [def.name, "phone"]),
51
- ...(options.browserTools ?? []).map((contract) => [contract.name, "browser"]),
52
50
  ]);
53
51
  const byName = new Map(defs.map((def) => [def.name, def]));
54
52
  return {
@@ -23,8 +23,11 @@ export function runBooking(sessions, before) {
23
23
  for (const key of await sessions.keys()) {
24
24
  const spend = sessionSpendOf(await sessions.read(key));
25
25
  spentUsd = spentUsd === null || spend.spentUsd === null ? null : spentUsd + spend.spentUsd;
26
+ // A hold-only step still open is no spend in its records: this booking keeps counting the one it admitted, in
27
+ // flight at its hold, until it is answered (a lost claim's, admitted by no booking here, counts nothing).
26
28
  for (const turn of spend.turns)
27
- recorded.add(idOf(key, turn));
29
+ if (!spend.openHolds.has(turn))
30
+ recorded.add(idOf(key, turn));
28
31
  }
29
32
  for (const id of [...admitted.keys()])
30
33
  if (recorded.has(id))
package/dist/runner.d.ts CHANGED
@@ -48,12 +48,19 @@ export type BeforeRequest = (request: {
48
48
  /** What it charges beside its tokens (ModelRequest.feeUsd), held with them. */
49
49
  feeUsd?: number;
50
50
  /** A paid tool call, no model request (ModelRequest.paid): held at its fee alone, named so in a refusal. `call`: the
51
- * tool call it was booked under, and `charged_by`, who charges for it, both written on its runner.request. */
51
+ * tool call it was booked under, `charged_by`, who charges for it, and `tool`/`tag`, the tool it is and its session,
52
+ * all written on its runner.request. `owed`: money already owed at its provider, held and booked, never refused.
53
+ * `hold`: a hold-only step, given back on a lost claim; `ref`: the one booking it names (ModelRequest.paid). */
52
54
  paid?: {
53
55
  name: string;
54
56
  basis: string;
55
57
  call?: string;
56
58
  charged_by?: string;
59
+ tool?: string;
60
+ tag?: string;
61
+ owed?: true;
62
+ hold?: true;
63
+ ref?: string;
57
64
  };
58
65
  /** A side call (ModelRequest.side): on another model than the session's (a client's), or the host's own (`host`). */
59
66
  side?: true;
@@ -82,6 +89,9 @@ export type Refusal = {
82
89
  leastCapUsd: number;
83
90
  boundUsd?: number;
84
91
  };
92
+ /** The refusal's code, from a host that gives one (a spend cap's: `spend_cap_reached`): carried on the error that ends
93
+ * the node (HarnessRunError.refusal), so a reader knows the refusal by it, never by its words. */
94
+ code?: string;
85
95
  };
86
96
  /** A request admitted and not yet answered, as a budget holds it: at what its host held for it (`holdUsd`), when it held
87
97
  * one. */
@@ -185,7 +195,7 @@ export interface ModelPortOptions {
185
195
  /** A note the host has for the session's next main-model request, taken by the call (ModelPort.note). */
186
196
  note?: (model: string, request?: NoteRequest) => string | undefined;
187
197
  /** The port ends the attempt (the turn limit, the host's refusal, a cost it could not record): the error it throws. */
188
- stop?: (reason: "turn_limit" | "refused" | "model_error", message?: string) => Error;
198
+ stop?: (reason: "turn_limit" | "refused" | "model_error", message?: string, code?: string) => Error;
189
199
  }
190
200
  /** A session's booking of paid model requests: the adapter's model port, and what it has counted. */
191
201
  export interface ModelBooking {
@@ -215,9 +225,20 @@ export declare function sessionSpendOf(records: readonly SessionRecord[]): {
215
225
  bounds: Map<number, number>;
216
226
  hosts: Map<number, string>;
217
227
  answered: Set<number>;
228
+ openHolds: Set<number>;
218
229
  spentUsd: number | null;
230
+ figures: {
231
+ turn: number;
232
+ usd: number | null;
233
+ }[];
219
234
  cost: SessionCost;
220
235
  };
236
+ /** Whether a request answered with no price of its own (bookRequest's rule `answered`, or `answered:<label>`, its usd
237
+ * null): booked at its hold for the cap, its cost unknown. */
238
+ export declare const answeredUnpriced: (data: {
239
+ usd?: unknown;
240
+ rule?: unknown;
241
+ }) => boolean;
221
242
  /** A session's cost as a person is shown it: `usd` when every paid request has its own figure, else null with the known
222
243
  * part so far (`soFarUsd`) and how many have none (`unpriced`). */
223
244
  export type SessionCost = {
package/dist/runner.js CHANGED
@@ -50,6 +50,11 @@ export async function modelPortFor(writer, options) {
50
50
  export function sessionSpendOf(records) {
51
51
  const requests = records.filter((r) => r.kind === RUNNER_RECORDS.request).map((r) => (r.data ?? {}));
52
52
  const turns = requests.map((data, i) => data.turn ?? i + 1);
53
+ // Hold-only steps (ModelRequest.paid.hold): money reserved, never spent. One still open is no spend here: the process
54
+ // that holds it counts it in flight (runBooking), and a lost claim's is given back (bookCut), never booked as cut.
55
+ const holdOnly = new Set();
56
+ requests.forEach((data, i) => { if (data.hold === true)
57
+ holdOnly.add(turns[i]); });
53
58
  const hosts = new Map();
54
59
  requests.forEach((data, i) => { if (typeof data.host === "string")
55
60
  hosts.set(turns[i], data.host); });
@@ -77,6 +82,8 @@ export function sessionSpendOf(records) {
77
82
  // the cap's, never a cost: a request without its own figure makes the cost unknown, the known part kept beside it.
78
83
  let soFarUsd = 0;
79
84
  let unpriced = 0;
85
+ // Each request's figure for the cap, in the order its spend is summed (`spentUsd` is their sum; null: no figure).
86
+ const figures = [];
80
87
  for (const r of records) {
81
88
  if (r.kind !== RUNNER_RECORDS.turn)
82
89
  continue;
@@ -90,21 +97,34 @@ export function sessionSpendOf(records) {
90
97
  const booked = data.bookedUsd === null ? null : heldFigure(data.bookedUsd);
91
98
  const cut = data.cut === true && booked === undefined;
92
99
  const capped = booked !== undefined && bookedLost(data.rule) ? (worst(turn) ?? booked) : booked;
93
- spentUsd = spent(spentUsd, capped !== undefined ? (capped ?? undefined) : cut ? worst(turn) : data.usd === null ? (heldFigure(data.heldUsd) ?? held.get(turn)) : (data.usd ?? 0));
94
- const own = booked !== undefined ? booked : cut || data.usd === null ? null : data.usd === undefined ? 0 : (heldFigure(data.usd) ?? null);
100
+ const figure = capped !== undefined ? (capped ?? undefined) : cut ? worst(turn) : data.usd === null ? (heldFigure(data.heldUsd) ?? held.get(turn)) : (data.usd ?? 0);
101
+ spentUsd = spent(spentUsd, figure);
102
+ figures.push({ turn, usd: figure ?? null });
103
+ // An answer with no price of its own (usd null) was booked at its hold for the cap: as a cost it is unknown, never
104
+ // the hold (0 with no cap), as main read an unpriced answer.
105
+ const own = answeredUnpriced(data) ? null : booked !== undefined ? booked : cut || data.usd === null ? null : data.usd === undefined ? 0 : (heldFigure(data.usd) ?? null);
95
106
  if (own === null)
96
107
  unpriced++;
97
108
  else
98
109
  soFarUsd += own;
99
110
  }
111
+ const openHolds = new Set();
100
112
  for (const turn of turns) {
101
113
  if (answered.has(turn))
102
114
  continue;
115
+ if (holdOnly.has(turn)) {
116
+ openHolds.add(turn);
117
+ continue;
118
+ }
103
119
  spentUsd = spent(spentUsd, worst(turn));
120
+ figures.push({ turn, usd: worst(turn) ?? null });
104
121
  unpriced++;
105
122
  }
106
- return { turns, held, bounds, hosts, answered, spentUsd, cost: { usd: unpriced > 0 ? null : soFarUsd, soFarUsd, unpriced } };
123
+ return { turns, held, bounds, hosts, answered, openHolds, spentUsd, figures, cost: { usd: unpriced > 0 ? null : soFarUsd, soFarUsd, unpriced } };
107
124
  }
125
+ /** Whether a request answered with no price of its own (bookRequest's rule `answered`, or `answered:<label>`, its usd
126
+ * null): booked at its hold for the cap, its cost unknown. */
127
+ export const answeredUnpriced = (data) => data.usd === null && typeof data.rule === "string" && (data.rule === "answered" || data.rule.startsWith("answered:"));
108
128
  /** Whether a request was booked lost (bookRequest's rule `lost`, or `lost:<label>`): billed or not, no cost came in. */
109
129
  const bookedLost = (rule) => typeof rule === "string" && (rule === "lost" || rule.startsWith("lost:"));
110
130
  function bookingFor(writer, options) {
@@ -158,7 +178,7 @@ function bookingFor(writer, options) {
158
178
  let admitting = Promise.resolve();
159
179
  // A paid request whose cost couldn't be recorded stops the booking itself, whether or not the host gave it a stop.
160
180
  let failed;
161
- const end = (reason, message) => options.stop ? options.stop(reason, message) : new HarnessRunError(reason, turns, 0, { maxTurns: limit, ...(message === undefined ? {} : { message }) });
181
+ const end = (reason, message, code) => options.stop ? options.stop(reason, message, code) : new HarnessRunError(reason, turns, 0, { maxTurns: limit, ...(message === undefined ? {} : { message }), ...(code === undefined ? {} : { refusal: code }) });
162
182
  const admit = async ({ model, inputTokensMax: measured, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, noted, inputTokensMaxWithoutNote, host }) => {
163
183
  let inputTokensMax = measured;
164
184
  const stopped = options.stopped?.(host === undefined ? {} : { host }) ?? failed;
@@ -172,7 +192,7 @@ function bookingFor(writer, options) {
172
192
  const verdict = await options.beforeRequest?.({ ...node, model, turn: turns + 1, maxTurns: limit, ...(options.budgetUsd === undefined ? {} : { budgetUsd: options.budgetUsd }), spentUsd, inFlight: open.map((f) => ({ ...f })), inputTokensMax,
173
193
  ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }), ...(feeUsd === undefined ? {} : { feeUsd }), ...(paid ? { paid } : {}), ...(side ? { side } : {}), ...(noted ? { noted, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}), ...(host === undefined ? {} : { host }) });
174
194
  if (verdict && "refuse" in verdict)
175
- throw end("refused", verdict.refuse);
195
+ throw end("refused", verdict.refuse, typeof verdict.code === "string" ? verdict.code : undefined);
176
196
  const hold = verdict && "holdUsd" in verdict ? heldFigure(verdict.holdUsd) : undefined;
177
197
  // What a cache miss adds to the hold: kept beside it, so a request that never answers counts at both (sessionSpendOf).
178
198
  const bound = hold !== undefined && verdict && "boundUsd" in verdict ? heldFigure(verdict.boundUsd) : undefined;
@@ -194,7 +214,7 @@ function bookingFor(writer, options) {
194
214
  // Durable before the request leaves: admitted, then sent. It counts as a turn once its record is written (admissions
195
215
  // run one at a time), so a write that fails refuses the request and costs no turn.
196
216
  const turn = turns + 1;
197
- await write([{ kind: RUNNER_RECORDS.request, data: { turn, model, ...(hold === undefined ? {} : { heldUsd: hold }), ...(bound ? { boundUsd: bound } : {}), ...(side ? { side } : {}), ...(host === undefined ? {} : { host }), ...(paid?.call === undefined ? {} : { call: paid.call }), ...(paid?.charged_by === undefined ? {} : { charged_by: paid.charged_by }) } }]);
217
+ await write([{ kind: RUNNER_RECORDS.request, data: { turn, model, ...(hold === undefined ? {} : { heldUsd: hold }), ...(bound ? { boundUsd: bound } : {}), ...(side ? { side } : {}), ...(host === undefined ? {} : { host }), ...(paid?.call === undefined ? {} : { call: paid.call }), ...(paid?.charged_by === undefined ? {} : { charged_by: paid.charged_by }), ...(paid?.tool === undefined ? {} : { tool: paid.tool }), ...(paid?.tag === undefined ? {} : { tag: paid.tag }), ...(paid?.owed ? { owed: true } : {}), ...(paid?.hold ? { hold: true } : {}), ...(paid?.ref === undefined ? {} : { ref: paid.ref }) } }]);
198
218
  turns = turn;
199
219
  if (host !== undefined)
200
220
  hosts.set(turn, host);
@@ -315,7 +335,34 @@ function bookingFor(writer, options) {
315
335
  // Each is booked once, as cut, at an unknown price, and the host is told as for any answered request, so its ledger
316
336
  // shows the possible spend instead of nothing. Booked, it is answered: a later attempt never books it again.
317
337
  // Only requests an earlier process admitted: one this process has in flight is not cut.
318
- const numbers = inherited.filter((t) => !answered.has(t));
338
+ const left = inherited.filter((t) => !answered.has(t));
339
+ if (left.length === 0)
340
+ return;
341
+ // A hold-only step an earlier process left open is given back: money reserved, not spent (its holder's charges book
342
+ // the money), never booked as cut. Every other cut step keeps the rule below.
343
+ const givenBack = left.filter((t) => read.openHolds.has(t));
344
+ // An owed step (money already owed at its provider, at the figure it was held at: a browser charge) an earlier process
345
+ // left open is booked at that figure, its known cost, never as an unknown cut: what it owes was settled when it was
346
+ // admitted, and its settle alone was lost.
347
+ const owedTurns = new Set(options.records.filter((r) => r.kind === RUNNER_RECORDS.request).flatMap((r, i) => {
348
+ const data = (r.data ?? {});
349
+ return data.owed === true && data.hold !== true ? [inherited[i]] : [];
350
+ }));
351
+ const owed = left.filter((t) => !read.openHolds.has(t) && owedTurns.has(t) && (held.get(t) ?? 0) > 0);
352
+ const numbers = left.filter((t) => !read.openHolds.has(t) && !owed.includes(t));
353
+ if (givenBack.length) {
354
+ await append(givenBack.map((turn) => ({ kind: RUNNER_RECORDS.turn, data: { turn, usd: 0, givenBack: true } })));
355
+ for (const turn of givenBack)
356
+ answered.add(turn);
357
+ }
358
+ if (owed.length) {
359
+ await append(owed.map((turn) => ({ kind: RUNNER_RECORDS.turn, data: { turn, usd: held.get(turn), bookedUsd: held.get(turn), rule: "owed" } })));
360
+ for (const turn of owed) {
361
+ answered.add(turn);
362
+ const hosted = hosts.get(turn);
363
+ emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: held.get(turn), estimated: true }, ...(hosted === undefined ? {} : { host: hosted }) });
364
+ }
365
+ }
319
366
  if (numbers.length === 0)
320
367
  return;
321
368
  // A cut request whose response had begun carries the ids it gave: the provider saw it, under them. One with none may
@@ -415,7 +462,7 @@ export function createHarnessRunner(adapter, options) {
415
462
  // A stop with no drain (drainMs 0) lets nothing run on, announced or not.
416
463
  const announced = new Set();
417
464
  let immediate = false;
418
- const failure = (reason, message) => new HarnessRunError(reason, turnsSoFar(), submissions, { maxTurns: limit, ...(lastTool === undefined ? {} : { lastTool }), ...(message === undefined ? {} : { message }) });
465
+ const failure = (reason, message, code) => new HarnessRunError(reason, turnsSoFar(), submissions, { maxTurns: limit, ...(lastTool === undefined ? {} : { lastTool }), ...(message === undefined ? {} : { message }), ...(code === undefined ? {} : { refusal: code }) });
419
466
  const controller = new AbortController();
420
467
  let rejectStopped;
421
468
  const interrupted = new Promise((_, reject) => { rejectStopped = reject; });
@@ -447,7 +494,7 @@ export function createHarnessRunner(adapter, options) {
447
494
  onEvent: (event) => emit(event),
448
495
  stopped: () => stopped,
449
496
  draining: () => (draining ? failure("aborted", "harness node pausing: no new paid request") : undefined),
450
- stop: (reason, message) => { stop(failure(reason, message)); return stopped; },
497
+ stop: (reason, message, code) => { stop(failure(reason, message, code)); return stopped; },
451
498
  });
452
499
  const submit = {
453
500
  name: SUBMIT_TOOL,
package/dist/types.d.ts CHANGED
@@ -155,12 +155,23 @@ export interface ModelRequest {
155
155
  /** A paid tool call, no model request (a web search's request, a monid call): held at `feeUsd` alone by the cap's tool
156
156
  * rule, `name` and `basis` in a refusal's words. `call`: the tool call it was booked under, written on its
157
157
  * runner.request so the run view puts its charge under that call. `charged_by`: who charges for it (the tool's
158
- * provider: parallel, monid, an MCP server, a browser vendor), written there too, as main's charge row names it. */
158
+ * provider: parallel, monid, an MCP server, a browser vendor), written there too, as main's charge row names it.
159
+ * `tool` and `tag`: the tool whose charge it is (a browser's, "browser") and its session, written there for the run
160
+ * view to place it as main's charge of that tool. `owed`: money its provider is already owed (a browser session's
161
+ * release, the time a person used): held at `feeUsd` and booked, never asked of the cap's rule, so a run past its cap
162
+ * or of unknown spend still counts it (main keeps it so: keepHold). `hold`: a hold-only step: money reserved, not
163
+ * spent; given back on a lost claim, never booked as cut (its holder's charges book the money, each its own step).
164
+ * `ref`: the one booking it names (a browser charge's session and time): a second admit of the same ref is not booked. */
159
165
  paid?: {
160
166
  name: string;
161
167
  basis: string;
162
168
  call?: string;
163
169
  charged_by?: string;
170
+ tool?: string;
171
+ tag?: string;
172
+ owed?: true;
173
+ hold?: true;
174
+ ref?: string;
164
175
  };
165
176
  /** A side call, never its turn's own: on another model than the session's (a client's title, a summary), or the
166
177
  * host's own request beside the harness's (`host`). */
@@ -259,7 +270,14 @@ export interface SessionIO {
259
270
  * runs nothing; a park holds the call, writing nothing, until the session's signal is aborted (the run parks on a
260
271
  * person). Absent: every call runs. */
261
272
  gate?(call: GateCall, context?: unknown): Promise<GateAnswer>;
273
+ /** A tool the adapter adds of its own (read_skill_file over the session's skills), made the host's: its calls go the
274
+ * way the host's own tools' do (the run's record of the call and its result, which its Timeline shows, the rule before
275
+ * a side effect, the host's hooks on the result). An adapter hands every tool it adds through it. Absent: the host
276
+ * keeps no record of calls, and the tool runs as it is. */
277
+ hostTool?(tool: HostTool): HostTool;
262
278
  }
279
+ /** `tool`, a tool the adapter adds of its own, made the host's (SessionIO.hostTool). */
280
+ export declare const hostedTool: (io: Pick<SessionIO, "hostTool">, tool: HostTool) => HostTool;
263
281
  /** A call as the host's gate is asked about it. */
264
282
  export interface GateCall {
265
283
  readonly callId: string;
package/dist/types.js CHANGED
@@ -15,3 +15,5 @@ export const HOST_RESULT_MAX_CHARS = 120_000;
15
15
  * answer again. A host reads a run's end by it (agentrun-serve's `moderated`).
16
16
  */
17
17
  export const CONTENT_FILTERED = "content_filter: the model provider stopped this answer";
18
+ /** `tool`, a tool the adapter adds of its own, made the host's (SessionIO.hostTool). */
19
+ export const hostedTool = (io, tool) => (io.hostTool ? io.hostTool(tool) : tool);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-kernel",
3
- "version": "0.1.0-beta.32",
3
+ "version": "0.1.0-beta.34",
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",
@@ -60,7 +60,7 @@
60
60
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
61
61
  },
62
62
  "dependencies": {
63
- "@parcha/agentrun-dsl": "0.1.0-beta.32",
63
+ "@parcha/agentrun-dsl": "0.1.0-beta.34",
64
64
  "ajv": "8.18.0",
65
65
  "typebox": "1.3.27"
66
66
  },
@@ -1,11 +0,0 @@
1
- import type { ToolDef } from "./defs.js";
2
- /** A browser tool's contract, as pi-browser's ToolContract gives what the registry reads of it. */
3
- export type BrowserContract = {
4
- readonly name: string;
5
- readonly description: string;
6
- readonly parameters: object;
7
- /** After a crash a `safe` call runs again; an `unsafe` one is reported interrupted. */
8
- readonly replay: "safe" | "unsafe";
9
- };
10
- /** The browser kind's definitions: the host's contracts, as given, held to the setting browser. */
11
- export declare function browserToolDefs(contracts: readonly BrowserContract[] | undefined): readonly ToolDef[];
@@ -1,14 +0,0 @@
1
- /** The browser kind's definitions: the host's contracts, as given, held to the setting browser. */
2
- export function browserToolDefs(contracts) {
3
- if (contracts === undefined)
4
- throw new Error("the browser's definitions are pi-browser's BROWSER_TOOLS, which the host passes as browserTools: the kernel holds no copy");
5
- return contracts.map((contract) => ({
6
- name: contract.name,
7
- source: "host",
8
- gateName: `host:browser/${contract.name}`,
9
- settingsKey: "browser",
10
- description: contract.description,
11
- parameters: contract.parameters,
12
- replaySafe: contract.replay === "safe",
13
- }));
14
- }