@parcha/agentrun-kernel 0.1.0-beta.33 → 0.1.0-beta.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/host/index.d.ts +4 -4
  3. package/dist/host/index.js +3 -3
  4. package/dist/host/overhead.d.ts +75 -4
  5. package/dist/host/overhead.js +220 -10
  6. package/dist/host/pinned-binary.d.ts +27 -2
  7. package/dist/host/pinned-binary.js +97 -8
  8. package/dist/host/proxy.d.ts +40 -4
  9. package/dist/host/proxy.js +73 -2
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +2 -2
  12. package/dist/kernel/cap/index.d.ts +2 -2
  13. package/dist/kernel/cap/index.js +2 -2
  14. package/dist/kernel/cap/park.js +4 -2
  15. package/dist/kernel/cap/port.d.ts +3 -2
  16. package/dist/kernel/cap/port.js +7 -2
  17. package/dist/kernel/cap/price.js +5 -2
  18. package/dist/kernel/cap/run-cap.d.ts +21 -5
  19. package/dist/kernel/cap/run-cap.js +42 -4
  20. package/dist/kernel/cap/types.d.ts +7 -0
  21. package/dist/kernel/cap/words.d.ts +9 -0
  22. package/dist/kernel/cap/words.js +16 -1
  23. package/dist/kernel/registry/defs.d.ts +3 -6
  24. package/dist/kernel/registry/defs.js +6 -11
  25. package/dist/kernel/registry/hands.d.ts +3 -22
  26. package/dist/kernel/registry/index.d.ts +1 -3
  27. package/dist/kernel/registry/index.js +3 -3
  28. package/dist/kernel/registry/registry.d.ts +2 -5
  29. package/dist/kernel/registry/registry.js +8 -10
  30. package/dist/process/tools.d.ts +9 -0
  31. package/dist/process/tools.js +19 -6
  32. package/dist/run-booking.js +4 -1
  33. package/dist/runner.d.ts +27 -1
  34. package/dist/runner.js +55 -8
  35. package/dist/testing.d.ts +9 -2
  36. package/dist/testing.js +63 -18
  37. package/dist/types.d.ts +32 -3
  38. package/dist/types.js +2 -0
  39. package/package.json +3 -3
  40. package/dist/kernel/registry/browser.d.ts +0 -11
  41. package/dist/kernel/registry/browser.js +0 -14
@@ -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 {
@@ -82,6 +82,15 @@ export declare class Mutex {
82
82
  }
83
83
  /** The memo key of a tool call. */
84
84
  export declare const toolKey: (callId: string) => string;
85
+ /**
86
+ * The host's gate, asked about a call before anything of it is written: the first step of every harness's tool bridge
87
+ * (this one's, and the faux harness's, run-adapters/testing). Undefined when it allows the call; the refusal for a deny,
88
+ * whose words are the call's answer; a park holds the call until `signal` is aborted (the run parked and this process
89
+ * lets go of it), then rejects, so the harness is never handed a result for it.
90
+ */
91
+ export declare function askGate(gate: (call: GateCall) => Promise<GateAnswer>, call: GateCall, signal: AbortSignal): Promise<{
92
+ deny: string;
93
+ } | undefined>;
85
94
  /**
86
95
  * Build the bridge for one drive. The calls' effects are this drive's: build
87
96
  * a new bridge per `drive(ctx)`.
@@ -24,6 +24,20 @@ function parkedUntilAborted(signal, tool) {
24
24
  signal.addEventListener('abort', parked, { once: true });
25
25
  });
26
26
  }
27
+ /**
28
+ * The host's gate, asked about a call before anything of it is written: the first step of every harness's tool bridge
29
+ * (this one's, and the faux harness's, run-adapters/testing). Undefined when it allows the call; the refusal for a deny,
30
+ * whose words are the call's answer; a park holds the call until `signal` is aborted (the run parked and this process
31
+ * lets go of it), then rejects, so the harness is never handed a result for it.
32
+ */
33
+ export async function askGate(gate, call, signal) {
34
+ const answer = await gate(call);
35
+ if (answer === 'allow')
36
+ return undefined;
37
+ if ('deny' in answer)
38
+ return answer;
39
+ return parkedUntilAborted(signal, call.tool);
40
+ }
27
41
  /**
28
42
  * Build the bridge for one drive. The calls' effects are this drive's: build
29
43
  * a new bridge per `drive(ctx)`.
@@ -45,12 +59,11 @@ export function toolBridge(ctx, tools, options = {}) {
45
59
  const fresh = !ctx.isMemoized(key);
46
60
  // The gate first: before the flush and the intent, so a refused or parked call leaves nothing in the log.
47
61
  if (fresh && options.gate) {
48
- const answer = await options.gate({ callId, tool: tool.name, args: (args ?? {}) });
49
- if (answer !== 'allow') {
50
- if ('deny' in answer)
51
- return { text: answer.deny, isError: true };
52
- await parkedUntilAborted(signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal, tool.name);
53
- }
62
+ // An earlier attempt's start in the log (a replay-safe call a crash cut): it may have been sent, and the gate says so.
63
+ const replayed = ctx.state().effects.has(key);
64
+ const refused = await askGate(options.gate, { callId, tool: tool.name, args: (args ?? {}), ...(replayed ? { replayed: true } : {}) }, signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal);
65
+ if (refused)
66
+ return { text: refused.deny, isError: true };
54
67
  }
55
68
  if (fresh && tool.replay === 'never')
56
69
  await options.beforeNever?.({ name: tool.name, callId, args });
@@ -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;
@@ -64,6 +71,8 @@ export type BeforeRequest = (request: {
64
71
  /** The label of a request the host sent beside the harness's own (ModelRequest.host): a learned workflow's model node,
65
72
  * under the same check as the harness's own. */
66
73
  host?: string;
74
+ /** The route it came by (ModelRequest.route), absent for the session's own: the host prices it by model and route. */
75
+ route?: string;
67
76
  /** This session's paid requests admitted and not yet answered (in this process), oldest first, each with its own
68
77
  * `inputTokensMax`, the output limit it was admitted with (`outputTokensMax`) and what its host held for it
69
78
  * (`holdUsd`): a budget holds each one until it answers, since `spentUsd` counts answered requests only. Requests are
@@ -81,6 +90,11 @@ export type Refusal = {
81
90
  needsUsd: number;
82
91
  leastCapUsd: number;
83
92
  boundUsd?: number;
93
+ step?: {
94
+ name: string;
95
+ holdUsd: number;
96
+ basis: string;
97
+ };
84
98
  };
85
99
  /** The refusal's code, from a host that gives one (a spend cap's: `spend_cap_reached`): carried on the error that ends
86
100
  * the node (HarnessRunError.refusal), so a reader knows the refusal by it, never by its words. */
@@ -95,6 +109,7 @@ export type InFlight = {
95
109
  outputTokensMax?: number;
96
110
  holdUsd?: number;
97
111
  host?: string;
112
+ route?: string;
98
113
  };
99
114
  /** A host's admission: what it holds for the request (`holdUsd`), and the most output tokens, thinking included, it may
100
115
  * be sent with (`outputTokensMax`, what is left of a cap can buy), which its ticket carries to the model proxy. A
@@ -218,9 +233,20 @@ export declare function sessionSpendOf(records: readonly SessionRecord[]): {
218
233
  bounds: Map<number, number>;
219
234
  hosts: Map<number, string>;
220
235
  answered: Set<number>;
236
+ openHolds: Set<number>;
221
237
  spentUsd: number | null;
238
+ figures: {
239
+ turn: number;
240
+ usd: number | null;
241
+ }[];
222
242
  cost: SessionCost;
223
243
  };
244
+ /** Whether a request answered with no price of its own (bookRequest's rule `answered`, or `answered:<label>`, its usd
245
+ * null): booked at its hold for the cap, its cost unknown. */
246
+ export declare const answeredUnpriced: (data: {
247
+ usd?: unknown;
248
+ rule?: unknown;
249
+ }) => boolean;
224
250
  /** A session's cost as a person is shown it: `usd` when every paid request has its own figure, else null with the known
225
251
  * part so far (`soFarUsd`) and how many have none (`unpriced`). */
226
252
  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) {
@@ -159,7 +179,7 @@ function bookingFor(writer, options) {
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
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
- const admit = async ({ model, inputTokensMax: measured, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, noted, inputTokensMaxWithoutNote, host }) => {
182
+ const admit = async ({ model, inputTokensMax: measured, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, noted, inputTokensMaxWithoutNote, host, route }) => {
163
183
  let inputTokensMax = measured;
164
184
  const stopped = options.stopped?.(host === undefined ? {} : { host }) ?? failed;
165
185
  if (stopped)
@@ -170,7 +190,7 @@ function bookingFor(writer, options) {
170
190
  if (limit !== null && turns >= limit)
171
191
  throw end("turn_limit");
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
- ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }), ...(feeUsd === undefined ? {} : { feeUsd }), ...(paid ? { paid } : {}), ...(side ? { side } : {}), ...(noted ? { noted, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}), ...(host === undefined ? {} : { host }) });
193
+ ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }), ...(feeUsd === undefined ? {} : { feeUsd }), ...(paid ? { paid } : {}), ...(side ? { side } : {}), ...(noted ? { noted, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
174
194
  if (verdict && "refuse" in verdict)
175
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;
@@ -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);
@@ -237,7 +257,7 @@ function bookingFor(writer, options) {
237
257
  emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: 0 }, ...(host === undefined ? {} : { host }), ended: { end: "nothing", label: "never_left" } });
238
258
  throw stoppedLate;
239
259
  }
240
- open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(host === undefined ? {} : { host }) });
260
+ open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
241
261
  return { turn, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(withoutNote ? { noteDropped: true } : {}) };
242
262
  };
243
263
  const models = {
@@ -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
package/dist/testing.d.ts CHANGED
@@ -111,8 +111,12 @@ export type FauxAction = ({
111
111
  };
112
112
  /** `note`: a note its host had for the request (ModelPort.note, the spend cap's wrap-up), as a real adapter's model proxy
113
113
  * would add it to the body: filed with its text, for a test to see. */
114
+ /** `answered`: a request whose reply asks for calls came back (its `until` let go), so its calls are the model's to run.
115
+ * `said`: a call's own text (its `say`) was streamed, so a recovered turn never says it again. */
114
116
  export declare const FAUX_RECORDS: {
115
117
  readonly request: "faux.request";
118
+ readonly answered: "faux.answered";
119
+ readonly said: "faux.said";
116
120
  readonly user: "faux.user";
117
121
  readonly turn: "faux.turn";
118
122
  readonly turnEnd: "faux.turn_end";
@@ -121,8 +125,11 @@ export declare const FAUX_RECORDS: {
121
125
  readonly note: "faux.note";
122
126
  };
123
127
  export interface FauxOptions {
124
- /** The session's model replies, in order, by its spec: one action per paid request. */
125
- script: (spec: SessionSpec) => FauxAction[];
128
+ /** The session's model replies, in order, by its spec: one action per paid request. `cwd`: the session's working
129
+ * directory when its host gives one (SessionIO.cwd), which a real CLI builds its absolute paths from. */
130
+ script: (spec: SessionSpec, session: {
131
+ readonly cwd?: string;
132
+ }) => FauxAction[];
126
133
  /** Problems `check` reports for a spec. */
127
134
  refuse?: (spec: SessionSpec) => string[];
128
135
  /** How long `open` takes, ignoring the session's signal, as a slow harness start does (default 0). */
package/dist/testing.js CHANGED
@@ -1,10 +1,13 @@
1
1
  // Test kit: a session store in memory, and a scripted harness with no model and no network. The faux harness keeps its
2
2
  // own records in the store as a real adapter does (the requests it made, each tool call's intent and outcome, its turns),
3
3
  // so a later process resumes from them: a request already made is not made again, and a call a crash cut off is
4
- // answered interrupted, never run again.
4
+ // answered interrupted, never run again. Each call asks the host's gate first, as a real harness's tool bridge does
5
+ // (process/tools.ts askGate): a deny is the call's answer, and a park holds the turn; a recovered turn runs the calls its
6
+ // last request asked for that never started (a parked one), under their own ids, as a real CLI's resume does.
5
7
  import { SessionFenced } from "./errors.js";
6
8
  import { abortedOutcome, SessionHalt } from "./kernel/halt.js";
7
9
  import { startModelProxy } from "./host/proxy.js";
10
+ import { askGate } from "./process/tools.js";
8
11
  import { randomBytes } from "node:crypto";
9
12
  export { SCHEMA_CHECK_CASES } from "./schema-check-cases.js";
10
13
  /** The model proxy's own parts, for tests of a provider policy and of the proxy: the host API (./host) keeps only what a
@@ -38,7 +41,9 @@ export function memorySessionStore() {
38
41
  }
39
42
  /** `note`: a note its host had for the request (ModelPort.note, the spend cap's wrap-up), as a real adapter's model proxy
40
43
  * would add it to the body: filed with its text, for a test to see. */
41
- export const FAUX_RECORDS = { request: "faux.request", user: "faux.user", turn: "faux.turn", turnEnd: "faux.turn_end", call: "faux.call", result: "faux.result", note: "faux.note" };
44
+ /** `answered`: a request whose reply asks for calls came back (its `until` let go), so its calls are the model's to run.
45
+ * `said`: a call's own text (its `say`) was streamed, so a recovered turn never says it again. */
46
+ export const FAUX_RECORDS = { request: "faux.request", answered: "faux.answered", said: "faux.said", user: "faux.user", turn: "faux.turn", turnEnd: "faux.turn_end", call: "faux.call", result: "faux.result", note: "faux.note" };
42
47
  export function fauxAdapter(options) {
43
48
  const stats = { requests: 0, calls: [], opened: [], closed: [] };
44
49
  const adapter = {
@@ -55,7 +60,7 @@ export function fauxAdapter(options) {
55
60
  async open(spec, io) {
56
61
  if (options.openDelayMs)
57
62
  await new Promise((resolve) => setTimeout(resolve, options.openDelayMs));
58
- const script = options.script(spec);
63
+ const script = options.script(spec, io.cwd === undefined ? {} : { cwd: io.cwd });
59
64
  const records = await io.writer.read();
60
65
  // The session's model proxy, when the faux harness is given one: up for the session's life, its key never used here.
61
66
  const proxy = options.proxy ? await startModelProxy({ ...options.proxy.options, hooks: io.models }, randomBytes(32).toString("base64url")) : undefined;
@@ -79,6 +84,24 @@ export function fauxAdapter(options) {
79
84
  await append(FAUX_RECORDS.result, { callId, interrupted: true });
80
85
  }
81
86
  const tools = new Map(spec.tools.map((tool) => [tool.name, tool]));
87
+ /** The calls an action asks for, under their ids: a response's several calls, one call, or a submission. */
88
+ const callsOf = (action, index) => !action ? [] : "calls" in action ? action.calls.map((c, n) => ({ name: c.call, args: c.args ?? {}, callId: `${spec.key}:${index}.${n}`, ...(c.say ? { say: c.say } : {}) }))
89
+ : "call" in action ? [{ name: action.call, args: action.args ?? {}, callId: `${spec.key}:${index}` }]
90
+ : "submit" in action ? [{ name: "submit", args: { value: action.submit }, callId: `${spec.key}:${index}` }] : [];
91
+ // The calls the session's last request asked for that never started (no intent, no answer): the gate parked them, or
92
+ // the process ended before they ran. A recovered turn runs them first, as a real CLI's resume runs the calls left
93
+ // dangling in its transcript; a turn settled or a new one sent leaves them. Only once that request was answered
94
+ // (FAUX_RECORDS.answered): one cut off before its reply came (held at its `until`) asked for nothing yet, so none of
95
+ // its calls runs on the recovery: the turn goes on with the script's next request, as a cut request's always has.
96
+ const begun = new Set(records.filter((r) => r.kind === FAUX_RECORDS.call || r.kind === FAUX_RECORDS.result).map((r) => r.data.callId));
97
+ const answered = new Set(records.filter((r) => r.kind === FAUX_RECORDS.answered).map((r) => r.data.index));
98
+ // Each keeps its action's resultWhen: its outcome is told only once that file exists, as on its first try; and its own
99
+ // text (`say`) unless it was said already (FAUX_RECORDS.said: the call that parked said its text before its gate).
100
+ const resultWhenOf = (action) => (action && "resultWhen" in action && typeof action.resultWhen === "string" ? action.resultWhen : undefined);
101
+ const saidAlready = new Set(records.filter((r) => r.kind === FAUX_RECORDS.said).map((r) => r.data.callId));
102
+ let dangling = state === "open_turn" && answered.has(cursor - 1)
103
+ ? callsOf(script[cursor - 1], cursor - 1).filter((call) => !begun.has(call.callId)).map(({ say, ...call }) => ({ ...call, ...(say && !saidAlready.has(call.callId) ? { say } : {}), resultWhen: resultWhenOf(script[cursor - 1]) }))
104
+ : [];
82
105
  /** What the session has been sent, as a model would be prompted with it. */
83
106
  const prompt = records.filter((r) => r.kind === FAUX_RECORDS.user).map((r) => r.data.text);
84
107
  let ending;
@@ -109,10 +132,39 @@ export function fauxAdapter(options) {
109
132
  else
110
133
  signal.addEventListener("abort", () => reject(signal.reason), { once: true });
111
134
  });
135
+ /** One call of the model's: the host's gate first, before anything of it is written (a deny is its answer, in the
136
+ * gate's words, recorded so it is never asked again; a park holds the turn until it is stopped), then its intent,
137
+ * the tool, and its outcome. `resultWhen`: its outcome is told only once that file exists. */
138
+ const runCall = async (name, args, callId, signal, resultWhen) => {
139
+ const tool = tools.get(name);
140
+ const refused = tool && io.gate ? await askGate((call) => io.gate(call), { callId, tool: name, args: (args ?? {}) }, signal) : undefined;
141
+ if (refused)
142
+ return void (await append(FAUX_RECORDS.result, { callId, isError: true, refused: true }));
143
+ await append(FAUX_RECORDS.call, { callId, name });
144
+ io.onEvent({ type: "tool_start", callId, name, args });
145
+ const result = tool ? await tool.call(args, { callId, signal }).catch((error) => ({ text: error.message, isError: true })) : { text: `unknown tool ${name}`, isError: true };
146
+ if (tool)
147
+ stats.calls.push(name);
148
+ if (resultWhen)
149
+ await untilExists(resultWhen, signal);
150
+ await append(FAUX_RECORDS.result, { callId, isError: result.isError === true });
151
+ io.onEvent({ type: "tool_end", callId, name, isError: result.isError === true });
152
+ };
153
+ /** A call's own text, streamed before the call, then noted said (FAUX_RECORDS.said), so a recovered turn says it once. */
154
+ const saying = async (callId, say) => {
155
+ io.onEvent({ type: "text", delta: say });
156
+ await append(FAUX_RECORDS.said, { callId });
157
+ };
112
158
  /** The turn's model loop: one scripted action per paid request, until one ends the turn. */
113
159
  const run = async () => {
114
160
  const signal = AbortSignal.any([io.signal, (turnSignal = new AbortController()).signal]);
115
161
  try {
162
+ // A recovered turn: the calls its last request left dangling run first, then the model goes on.
163
+ for (const { name, args, callId, say, resultWhen } of dangling.splice(0)) {
164
+ if (say)
165
+ await saying(callId, say);
166
+ await runCall(name, args, callId, signal, resultWhen);
167
+ }
116
168
  for (;;) {
117
169
  const action = script[cursor];
118
170
  if (!action)
@@ -191,6 +243,9 @@ export function fauxAdapter(options) {
191
243
  // Held in flight, admitted and not answered, until the file it waits for exists (or the turn is stopped).
192
244
  if ("until" in action && typeof action.until === "string")
193
245
  await untilExists(action.until, signal);
246
+ // Its reply is in: the calls it asks for are the model's now, and a recovered turn runs any left unstarted.
247
+ if (callsOf(action, index).length)
248
+ await append(FAUX_RECORDS.answered, { index });
194
249
  const tokens = "tokens" in action && action.tokens ? action.tokens : { input: 10, output: 5 };
195
250
  const usd = action.usd === undefined ? 0.001 : action.usd;
196
251
  const book = () => io.models.afterRequest({ ...tokens, usd }, ticket || undefined, { end: "answered", usd });
@@ -204,27 +259,15 @@ export function fauxAdapter(options) {
204
259
  else if ("end" in action)
205
260
  return await end(action.turn ?? "completed");
206
261
  else {
207
- const asked = "calls" in action ? action.calls.map((c) => ({ name: c.call, args: c.args ?? {}, ...(c.say ? { say: c.say } : {}) }))
208
- : [{ name: "call" in action ? action.call : "submit", args: "call" in action ? action.args ?? {} : { value: action.submit } }];
209
- for (const [n, { name, args, say }] of asked.entries()) {
262
+ for (const [n, { name, args, callId, say }] of callsOf(action, index).entries()) {
210
263
  if (say)
211
- io.onEvent({ type: "text", delta: say });
264
+ await saying(callId, say);
212
265
  // A side call (a title, a summary) admitted and answered while this request still streams: two in flight.
213
266
  if (n === 0 && "sideDuring" in action && action.sideDuring) {
214
267
  const side = await io.models.beforeRequest({ model: "faux-small", side: true, inputTokensMax: 100 });
215
268
  await io.models.afterRequest({ input: 10, output: 5, usd: action.sideDuring.usd }, side || undefined);
216
269
  }
217
- const callId = "calls" in action ? `${spec.key}:${index}.${n}` : `${spec.key}:${index}`;
218
- const tool = tools.get(name);
219
- await append(FAUX_RECORDS.call, { callId, name });
220
- io.onEvent({ type: "tool_start", callId, name, args });
221
- const result = tool ? await tool.call(args, { callId, signal }).catch((error) => ({ text: error.message, isError: true })) : { text: `unknown tool ${name}`, isError: true };
222
- if (tool)
223
- stats.calls.push(name);
224
- if ("resultWhen" in action && typeof action.resultWhen === "string")
225
- await untilExists(action.resultWhen, signal);
226
- await append(FAUX_RECORDS.result, { callId, isError: result.isError === true });
227
- io.onEvent({ type: "tool_end", callId, name, isError: result.isError === true });
270
+ await runCall(name, args, callId, signal, resultWhenOf(action));
228
271
  }
229
272
  if (bookAfter)
230
273
  await book();
@@ -252,6 +295,7 @@ export function fauxAdapter(options) {
252
295
  get state() { return state; },
253
296
  async send(text) {
254
297
  state = "idle";
298
+ dangling = [];
255
299
  await append(FAUX_RECORDS.user, { text });
256
300
  prompt.push(text);
257
301
  await append(FAUX_RECORDS.turn, { n: turnsStarted + 1 });
@@ -265,6 +309,7 @@ export function fauxAdapter(options) {
265
309
  throw new Error("faux: there is no turn to settle");
266
310
  await append(FAUX_RECORDS.turnEnd, { status: abortedOutcome(AbortSignal.abort(new SessionHalt("interrupted"))).status });
267
311
  state = "idle";
312
+ dangling = [];
268
313
  },
269
314
  turnEnd: () => ending ? ending.promise : Promise.resolve({ status: "completed" }),
270
315
  async interrupt() { turnSignal?.abort(new SessionHalt("interrupted")); },