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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/dist/host/index.d.ts +2 -4
  3. package/dist/host/index.js +2 -3
  4. package/dist/host/overhead.d.ts +42 -0
  5. package/dist/host/overhead.js +84 -10
  6. package/dist/host/proxy.d.ts +34 -15
  7. package/dist/host/proxy.js +99 -25
  8. package/dist/index.d.ts +2 -1
  9. package/dist/index.js +1 -0
  10. package/dist/kernel/cap/index.d.ts +4 -4
  11. package/dist/kernel/cap/index.js +3 -3
  12. package/dist/kernel/cap/port.d.ts +14 -3
  13. package/dist/kernel/cap/port.js +29 -16
  14. package/dist/kernel/cap/price.d.ts +31 -6
  15. package/dist/kernel/cap/price.js +49 -15
  16. package/dist/kernel/cap/rule.d.ts +11 -1
  17. package/dist/kernel/cap/rule.js +30 -3
  18. package/dist/kernel/cap/run-cap.d.ts +9 -2
  19. package/dist/kernel/cap/run-cap.js +8 -3
  20. package/dist/kernel/cap/types.d.ts +11 -5
  21. package/dist/kernel/registry/computer-surface.generated.d.ts +9 -0
  22. package/dist/kernel/registry/computer-surface.generated.js +618 -0
  23. package/dist/kernel/registry/computer.d.ts +14 -0
  24. package/dist/kernel/registry/computer.js +75 -0
  25. package/dist/kernel/registry/defs.d.ts +1 -4
  26. package/dist/kernel/registry/defs.js +1 -13
  27. package/dist/kernel/registry/handoff.js +4 -4
  28. package/dist/kernel/registry/hands.d.ts +22 -115
  29. package/dist/kernel/registry/hands.js +0 -2
  30. package/dist/kernel/registry/index.d.ts +4 -4
  31. package/dist/kernel/registry/index.js +5 -5
  32. package/dist/kernel/registry/registry.d.ts +4 -5
  33. package/dist/kernel/registry/registry.js +27 -29
  34. package/dist/kernel/types.d.ts +10 -2
  35. package/dist/process/tools.d.ts +5 -1
  36. package/dist/process/tools.js +62 -8
  37. package/dist/run-booking.d.ts +3 -0
  38. package/dist/run-booking.js +7 -0
  39. package/dist/runner.d.ts +21 -2
  40. package/dist/runner.js +126 -11
  41. package/dist/testing.d.ts +6 -2
  42. package/dist/testing.js +5 -3
  43. package/dist/tool-deferral.d.ts +12 -0
  44. package/dist/tool-deferral.js +17 -0
  45. package/dist/types.d.ts +83 -39
  46. package/package.json +2 -2
  47. package/dist/host/mcp-route.d.ts +0 -14
  48. package/dist/host/mcp-route.js +0 -125
  49. package/dist/kernel/registry/desktop.d.ts +0 -11
  50. package/dist/kernel/registry/desktop.js +0 -90
  51. package/dist/kernel/registry/phone.d.ts +0 -15
  52. package/dist/kernel/registry/phone.js +0 -135
@@ -51,36 +51,56 @@ export function toolBridge(ctx, tools, options = {}) {
51
51
  const mutex = new Mutex();
52
52
  const serial = options.serial ?? true;
53
53
  const live = options.live ?? true;
54
+ // Each tool's run by name, outside the mutex: a nested call runs inside the call that made it, which holds the mutex.
55
+ const runs = new Map();
56
+ /** The session's tools as calls nested in `outer` (NestedCalls): each through its own run, gate first, keyed
57
+ * `tool:<outer>/<key>`, so a rerun of `outer` gets a recorded one's answer and never runs it twice. */
58
+ const nestedIn = (outer, signal) => ({
59
+ async call(name, args, key) {
60
+ const run = runs.get(name);
61
+ if (!run)
62
+ return { text: `unknown tool: ${name}`, isError: true, refused: true, fresh: true };
63
+ const callId = `${outer}/${key}`;
64
+ const fresh = !ctx.isMemoized(toolKey(callId));
65
+ const { interrupted, ...result } = await run(args, callId, signal, true);
66
+ return { ...result, ...(interrupted ? { interrupted: true } : {}), fresh };
67
+ },
68
+ // A value the call's first run fixed, as a replay-safe effect of its own: its rerun reads the first one.
69
+ memo: (key, value) => ctx.effect(`nested:${outer}/${key}`, { name: 'nested.memo', replay: 'safe', input: null }, async () => value),
70
+ });
54
71
  const bridged = tools.map((tool) => {
55
- const run = async (args, callId, signal) => {
72
+ const run = async (args, callId, signal, nested) => {
56
73
  if (!callId)
57
74
  throw new TypeError(`agentrun-kernel: a call to ${tool.name} has no call id; derive a stable one`);
58
75
  const key = toolKey(callId);
76
+ // A tool that only nests calls writes nothing of its own: it runs, each nested call recorded as itself.
77
+ if (tool.nests)
78
+ return runNesting(args, callId, signal, nested);
59
79
  const fresh = !ctx.isMemoized(key);
60
80
  // The gate first: before the flush and the intent, so a refused or parked call leaves nothing in the log.
61
81
  if (fresh && options.gate) {
62
82
  // 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
83
  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);
84
+ const refused = await askGate(options.gate, { callId, tool: tool.name, args: (args ?? {}), ...(replayed ? { replayed: true } : {}), ...(nested ? { nested } : {}) }, signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal);
65
85
  if (refused)
66
- return { text: refused.deny, isError: true };
86
+ return { text: refused.deny, isError: true, refused: true };
67
87
  }
68
88
  if (fresh && tool.replay === 'never')
69
89
  await options.beforeNever?.({ name: tool.name, callId, args });
70
90
  if (fresh && live)
71
- ctx.live({ type: 'tool_start', name: tool.name, args, callId });
91
+ ctx.live({ type: 'tool_start', name: tool.name, args, callId, ...(nested ? { parent: callId.slice(0, callId.lastIndexOf('/')) } : {}) });
72
92
  try {
73
93
  const output = await ctx.effect(key, {
74
94
  name: `tool.${tool.name}`,
75
95
  replay: tool.replay,
76
96
  input: args,
77
97
  }, (io) => tool.execute(args, hostToolIO(io, ctx, { signal: signal ? AbortSignal.any([signal, io.signal]) : io.signal })));
78
- // A tool answers in text, or in text with images (a screenshot): the images come back as recorded.
79
- const { text: whole, images } = typeof output === 'object' && output !== null ? output : { text: String(output), images: undefined };
98
+ // A tool answers in text, or in text with images (a screenshot) and its value: they come back as recorded.
99
+ const { text: whole, images, structured } = typeof output === 'object' && output !== null ? output : { text: String(output), images: undefined, structured: undefined };
80
100
  const { text, truncated } = boundResult(String(whole));
81
101
  if (fresh && live)
82
102
  ctx.live({ type: 'tool_end', name: tool.name, callId, result: text, ...(truncated ? { truncated } : {}) });
83
- return { text, isError: false, ...(images?.length ? { images } : {}), ...(truncated ? { truncated } : {}) };
103
+ return { text, isError: false, ...(images?.length ? { images } : {}), ...(structured !== undefined ? { structured } : {}), ...(truncated ? { truncated } : {}) };
84
104
  }
85
105
  catch (err) {
86
106
  if (err instanceof EffectFailure) {
@@ -93,6 +113,39 @@ export function toolBridge(ctx, tools, options = {}) {
93
113
  throw err;
94
114
  }
95
115
  };
116
+ /** A tool that `nests`: asked at the gate as itself, then run with the session's tools as its nested calls, no effect
117
+ * of its own written. Its error result is its answer; a throw while the drive or the call is aborted (a nested call
118
+ * parked, the session let go) halts the drive, as an effect's does, so the harness is never handed a result. */
119
+ const runNesting = async (args, callId, signal, nested) => {
120
+ const aborted = signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal;
121
+ if (options.gate) {
122
+ const refused = await askGate(options.gate, { callId, tool: tool.name, args: (args ?? {}), ...(nested ? { nested } : {}) }, aborted);
123
+ if (refused)
124
+ return { text: refused.deny, isError: true, refused: true };
125
+ }
126
+ if (live)
127
+ ctx.live({ type: 'tool_start', name: tool.name, args, callId });
128
+ let output;
129
+ try {
130
+ output = await tool.execute(args, { signal: aborted, progress: () => { }, ctx, stepId: `${toolKey(callId)}#0`, nested: nestedIn(callId, aborted) });
131
+ }
132
+ catch (err) {
133
+ if (aborted.aborted) {
134
+ ctx.halt?.(err);
135
+ throw err;
136
+ }
137
+ const { text, truncated } = boundResult(err instanceof Error ? err.message : String(err));
138
+ if (live)
139
+ ctx.live({ type: 'tool_end', name: tool.name, callId, isError: true, result: text, ...(truncated ? { truncated } : {}) });
140
+ return { text, isError: true, ...(truncated ? { truncated } : {}) };
141
+ }
142
+ const { text: whole, images, structured } = typeof output === 'object' && output !== null ? output : { text: String(output), images: undefined, structured: undefined };
143
+ const { text, truncated } = boundResult(String(whole));
144
+ if (live)
145
+ ctx.live({ type: 'tool_end', name: tool.name, callId, result: text, ...(truncated ? { truncated } : {}) });
146
+ return { text, isError: false, ...(images?.length ? { images } : {}), ...(structured !== undefined ? { structured } : {}), ...(truncated ? { truncated } : {}) };
147
+ };
148
+ runs.set(tool.name, run);
96
149
  return {
97
150
  name: tool.name,
98
151
  description: tool.description,
@@ -103,7 +156,8 @@ export function toolBridge(ctx, tools, options = {}) {
103
156
  });
104
157
  const byName = new Map(bridged.map((t) => [t.name, t]));
105
158
  return {
106
- tools: bridged,
159
+ // What is listed to the model: a deferred tool is run by name (a nested call, `get`, `call`) and never listed.
160
+ tools: bridged.filter((_, index) => !tools[index].deferred),
107
161
  get: (name) => byName.get(name),
108
162
  call: async (name, args, callId, signal) => {
109
163
  const tool = byName.get(name);
@@ -4,6 +4,9 @@ import type { SessionRecord } from "./types.js";
4
4
  export interface RunSessions {
5
5
  keys(): readonly string[] | Promise<readonly string[]>;
6
6
  read(key: string): Promise<SessionRecord[]>;
7
+ /** What was spent on the run's behalf outside its sessions, as the host reads it at each admission (what ended at its
8
+ * cost, what is under way at the most it may take); null: unknown. None: nothing is. */
9
+ beside?(): Promise<number | null>;
7
10
  }
8
11
  /** `before`, asked about each request with the run's totals over `sessions` in place of its session's own. */
9
12
  export declare function runBooking(sessions: RunSessions, before: BeforeRequest): BeforeRequest;
@@ -6,6 +6,9 @@
6
6
  // answered (in flight in any session, in this process or a lost one) counts there at what its host held for it;
7
7
  // - `inFlight`: the requests this booking admitted that no record shows yet, each at what it was held at, so two
8
8
  // sessions asking at once never both take room only one of them fits.
9
+ // - what was spent beside its sessions on the run's behalf (`sessions.beside`: a run's learning, graded by runs of its
10
+ // own), read with them at each admission and added to `spentUsd`, so a run and what it pays for elsewhere never pass
11
+ // its cap together. Unknown (null) makes the run's spend unknown.
9
12
  // Admissions run one at a time across the run's sessions. The priced tools' charges and holds are not here: they are the
10
13
  // host's spentUsd and heldUsd hooks (beforeRequestOf), read beside these.
11
14
  import { sessionSpendOf } from "./runner.js";
@@ -29,6 +32,10 @@ export function runBooking(sessions, before) {
29
32
  if (!spend.openHolds.has(turn))
30
33
  recorded.add(idOf(key, turn));
31
34
  }
35
+ if (sessions.beside) {
36
+ const beside = await sessions.beside();
37
+ spentUsd = spentUsd === null || beside === null || !Number.isFinite(beside) ? null : spentUsd + beside;
38
+ }
32
39
  for (const id of [...admitted.keys()])
33
40
  if (recorded.has(id))
34
41
  admitted.delete(id);
package/dist/runner.d.ts CHANGED
@@ -41,6 +41,9 @@ export type BeforeRequest = (request: {
41
41
  /** The most input tokens this request can be billed for (the body's UTF-8 bytes plus what the provider adds, as the
42
42
  * model proxy measured it), undefined when it was not measured: a budget treats that input as unknown, never 0. */
43
43
  inputTokensMax?: number;
44
+ /** Its `inputTokensMax` is its provider's count, not its bytes (ModelRequest.inputTokensCounted): two bounds are compared
45
+ * (the cap's expected pricing) only when both were measured the same way. */
46
+ inputTokensCounted?: true;
44
47
  /** The most output tokens it asks for, and the least it may be limited to and still answer, as the model proxy read
45
48
  * them from its body (ModelRequest). */
46
49
  outputTokensAsked?: number;
@@ -64,6 +67,9 @@ export type BeforeRequest = (request: {
64
67
  };
65
68
  /** A side call (ModelRequest.side): on another model than the session's (a client's), or the host's own (`host`). */
66
69
  side?: true;
70
+ /** A request on the session's model that is no answer of the turn (ModelRequest.unanswered: a title, a summary, a
71
+ * child's): still the run's own to book, but never one of the session's recent requests, read or kept. */
72
+ unanswered?: true;
67
73
  /** It carries the host's note (ModelRequest.noted), and its input measured without it (`inputTokensMaxWithoutNote`):
68
74
  * a host that admits it only without the note says so (Admission.withoutNote). */
69
75
  noted?: true;
@@ -108,6 +114,7 @@ export type InFlight = {
108
114
  inputTokensMax?: number;
109
115
  outputTokensMax?: number;
110
116
  holdUsd?: number;
117
+ boundUsd?: number;
111
118
  host?: string;
112
119
  route?: string;
113
120
  };
@@ -202,6 +209,8 @@ export interface ModelPortOptions {
202
209
  draining?: () => Error | undefined;
203
210
  /** A note the host has for the session's next main-model request, taken by the call (ModelPort.note). */
204
211
  note?: (model: string, request?: NoteRequest) => string | undefined;
212
+ /** A note given back by the request that took it, before its admission (ModelPort.noteReturned). */
213
+ noteReturned?: (note: string) => void;
205
214
  /** The port ends the attempt (the turn limit, the host's refusal, a cost it could not record): the error it throws. */
206
215
  stop?: (reason: "turn_limit" | "refused" | "model_error", message?: string, code?: string) => Error;
207
216
  }
@@ -213,6 +222,14 @@ export interface ModelBooking {
213
222
  turns(): number;
214
223
  /** What they cost; null once one's price is unknown. */
215
224
  spentUsd(): number | null;
225
+ /** What its host holds for the requests still in flight (admitted, not yet answered): `spentUsd` counts answered ones
226
+ * only, so a reader of the run's spend that a request overlapping another must see adds this. Null while one in flight
227
+ * has no hold (never under a cap, which refuses a request it cannot price): unknown, never read as 0. */
228
+ heldUsd(): number | null;
229
+ /** What a cache miss adds to those holds (Admission.boundUsd), the requests still in flight together: the run's tools stop
230
+ * on the holds plus this (the cap counts a request that never answers at both), so a reader that must warn no later
231
+ * adds it too. 0 with none in flight or none with a bound. */
232
+ boundUsd(): number;
216
233
  /** Books, once, each paid request a crash cut off (a `runner.request` with no `runner.turn`): a `runner.turn` marked
217
234
  * `cut` at an unknown price, and a `request_end` saying so. A booked request is answered, so this is idempotent.
218
235
  * Call it before the session sends anything. */
@@ -241,8 +258,10 @@ export declare function sessionSpendOf(records: readonly SessionRecord[]): {
241
258
  }[];
242
259
  cost: SessionCost;
243
260
  };
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. */
261
+ /** Whether a request ended with no price of its own (usd null) under a rule that books it at a figure of the host's: an
262
+ * answer with no cost (bookRequest's rule `answered`, or `answered:<label>`: its hold), or one our side stopped
263
+ * (`stopped`: what streamed, an estimate) or lost (`lost`, `lost:<label>`: its hold). Each counts for the cap at that
264
+ * figure, but as a cost it is unknown, never an estimate stored as a known charge (the provider may bill otherwise). */
246
265
  export declare const answeredUnpriced: (data: {
247
266
  usd?: unknown;
248
267
  rule?: unknown;
package/dist/runner.js CHANGED
@@ -88,6 +88,10 @@ export function sessionSpendOf(records) {
88
88
  if (r.kind !== RUNNER_RECORDS.turn)
89
89
  continue;
90
90
  const data = r.data;
91
+ // A request is booked once: a second runner.turn of a turn already answered (two bookings of one session that each
92
+ // read it open, a cut written twice) counts no money and no request again.
93
+ if (typeof data.turn === "number" && answered.has(data.turn))
94
+ continue;
91
95
  const turn = data.turn ?? turns.find((t) => !answered.has(t)) ?? 0;
92
96
  answered.add(turn);
93
97
  // The figure it was booked at (bookRequest), as written. A record from before that has none: a request cut off with
@@ -122,11 +126,44 @@ export function sessionSpendOf(records) {
122
126
  }
123
127
  return { turns, held, bounds, hosts, answered, openHolds, spentUsd, figures, cost: { usd: unpriced > 0 ? null : soFarUsd, soFarUsd, unpriced } };
124
128
  }
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:"));
129
+ /** Whether a request ended with no price of its own (usd null) under a rule that books it at a figure of the host's: an
130
+ * answer with no cost (bookRequest's rule `answered`, or `answered:<label>`: its hold), or one our side stopped
131
+ * (`stopped`: what streamed, an estimate) or lost (`lost`, `lost:<label>`: its hold). Each counts for the cap at that
132
+ * figure, but as a cost it is unknown, never an estimate stored as a known charge (the provider may bill otherwise). */
133
+ export const answeredUnpriced = (data) => data.usd === null && typeof data.rule === "string" && (data.rule === "answered" || data.rule.startsWith("answered:") || data.rule === "stopped" || data.rule === "lost" || data.rule.startsWith("lost:"));
128
134
  /** Whether a request was booked lost (bookRequest's rule `lost`, or `lost:<label>`): billed or not, no cost came in. */
129
135
  const bookedLost = (rule) => typeof rule === "string" && (rule === "lost" || rule.startsWith("lost:"));
136
+ /** The bookings of each session scope (SessionWriter.scope) in this process, across its claims: each request a booking
137
+ * admitted and has not seen answer (`flying`, settled once its afterRequest has written or failed to), and each answered
138
+ * request whose runner.turn the store refused (`refused`: a claim lost as the request answered). The scope's next
139
+ * booking waits for the first and writes the second at its bookCut: a request that answered is booked at what it
140
+ * reported, once, never cut at an unknown cost because the claim that sent it could no longer write. */
141
+ const handoffs = new Map();
142
+ /** How long a bookCut waits for an earlier booking's request still in flight in this process (its claim lost, its loop
143
+ * stopping, which ends its requests): past it, the request is booked cut as one a dead process left. */
144
+ const HANDOFF_WAIT_MS = 10_000;
145
+ /** The most scopes kept: past it, the oldest with nothing in flight is dropped (a run resumed in another process, or not
146
+ * at all, never takes what it left here; its next booking anywhere books those requests cut, as before). */
147
+ const HANDOFF_SCOPES_MAX = 1024;
148
+ const handoffOf = (scope) => {
149
+ let at = handoffs.get(scope);
150
+ if (!at) {
151
+ at = { flying: new Map(), refused: new Map() };
152
+ handoffs.set(scope, at);
153
+ if (handoffs.size > HANDOFF_SCOPES_MAX)
154
+ for (const [key, old] of handoffs)
155
+ if (old.flying.size === 0 && key !== scope) {
156
+ handoffs.delete(key);
157
+ break;
158
+ }
159
+ }
160
+ return at;
161
+ };
162
+ const handoffDone = (scope) => {
163
+ const at = handoffs.get(scope);
164
+ if (at && at.flying.size === 0 && at.refused.size === 0)
165
+ handoffs.delete(scope);
166
+ };
130
167
  function bookingFor(writer, options) {
131
168
  const node = { key: options.key, label: options.label ?? options.key, ...(options.executionPath === undefined ? {} : { executionPath: options.executionPath }) };
132
169
  const limit = options.maxTurns ?? null;
@@ -157,6 +194,24 @@ function bookingFor(writer, options) {
157
194
  }
158
195
  // This process's requests in flight, oldest first: the turn each was admitted as, and its model.
159
196
  const open = [];
197
+ // Each of them as the session's scope knows it in flight (handoffs), settled once its afterRequest has written or not.
198
+ const scope = writer.scope;
199
+ const settles = new Map();
200
+ const fly = (turn) => {
201
+ if (scope === undefined)
202
+ return;
203
+ let settle;
204
+ const flying = handoffOf(scope).flying;
205
+ const done = new Promise((resolve) => (settle = resolve));
206
+ flying.set(turn, done);
207
+ settles.set(turn, () => {
208
+ settles.delete(turn);
209
+ if (flying.get(turn) === done)
210
+ flying.delete(turn);
211
+ settle();
212
+ handoffDone(scope);
213
+ });
214
+ };
160
215
  // Response ids whose own write was refused, marked `late`: the booking's next write of its own (the next runner.request,
161
216
  // or a runner.turn) carries them first, so a request this process cuts by dying after that still keeps its ids. One a
162
217
  // runner.turn writes with the ids is dropped, never written twice. A process that dies before writing for its booking
@@ -179,7 +234,7 @@ function bookingFor(writer, options) {
179
234
  // A paid request whose cost couldn't be recorded stops the booking itself, whether or not the host gave it a stop.
180
235
  let failed;
181
236
  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 }) });
182
- const admit = async ({ model, inputTokensMax: measured, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, noted, inputTokensMaxWithoutNote, host, route }) => {
237
+ const admit = async ({ model, inputTokensMax: measured, inputTokensCounted, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, unanswered, noted, inputTokensMaxWithoutNote, host, route }) => {
183
238
  let inputTokensMax = measured;
184
239
  const stopped = options.stopped?.(host === undefined ? {} : { host }) ?? failed;
185
240
  if (stopped)
@@ -189,8 +244,8 @@ function bookingFor(writer, options) {
189
244
  throw pausing;
190
245
  if (limit !== null && turns >= limit)
191
246
  throw end("turn_limit");
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,
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 }) });
247
+ 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, ...(inputTokensCounted ? { inputTokensCounted } : {}),
248
+ ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }), ...(feeUsd === undefined ? {} : { feeUsd }), ...(paid ? { paid } : {}), ...(side ? { side } : {}), ...(unanswered ? { unanswered } : {}), ...(noted ? { noted, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
194
249
  if (verdict && "refuse" in verdict)
195
250
  throw end("refused", verdict.refuse, typeof verdict.code === "string" ? verdict.code : undefined);
196
251
  const hold = verdict && "holdUsd" in verdict ? heldFigure(verdict.holdUsd) : undefined;
@@ -254,14 +309,16 @@ function bookingFor(writer, options) {
254
309
  if (stoppedLate) {
255
310
  answered.add(turn);
256
311
  await write([{ kind: RUNNER_RECORDS.turn, data: { turn, usd: 0, unsent: true } }]).catch(() => undefined);
257
- emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: 0 }, ...(host === undefined ? {} : { host }), ended: { end: "nothing", label: "never_left" } });
312
+ await emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: 0 }, ...(host === undefined ? {} : { host }), ended: { end: "nothing", label: "never_left" } });
258
313
  throw stoppedLate;
259
314
  }
260
- open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
315
+ open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(bound ? { boundUsd: bound } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
316
+ fly(turn);
261
317
  return { turn, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(withoutNote ? { noteDropped: true } : {}) };
262
318
  };
263
319
  const models = {
264
320
  ...(options.note ? { note: options.note } : {}),
321
+ ...(options.noteReturned ? { noteReturned: options.noteReturned } : {}),
265
322
  beforeRequest: (request) => {
266
323
  const admitted = admitting.then(() => admit(request));
267
324
  admitting = admitted.catch(() => { });
@@ -306,13 +363,21 @@ function bookingFor(writer, options) {
306
363
  // sessionSpendOf reads it on the next claim.
307
364
  const capped = booking && bookedLost(booking.rule) && hold !== undefined ? hold + (bounds.get(turn) ?? 0) : figure;
308
365
  spentUsd = spent(spentUsd, capped ?? undefined);
366
+ const settle = settles.get(turn);
367
+ const data = { turn, usd: usage.usd, ...tokensOf(usage), ...(usage.givenBack ? { givenBack: true } : {}), ...(usage.estimated ? { estimated: true } : {}), ...(usage.tableUsd === undefined ? {} : { tableUsd: usage.tableUsd }), ...(usage.providerIds ? { providerIds: usage.providerIds } : {}), ...(stopped === undefined ? {} : { heldUsd: Math.min(hold, stopped), stopped: true }), ...(booking ? { bookedUsd: booking.usd, rule: booking.rule } : {}), ...(note ? { note } : {}) };
309
368
  try {
310
369
  // A runner.turn with the ids holds what a carried response record of this turn would: that one is dropped. A
311
370
  // stopped one keeps the figure it counts at (`heldUsd`), so a later process counts it the same.
312
371
  const covers = (r) => usage.providerIds !== undefined && r.data.turn === turn;
313
- await write([{ kind: RUNNER_RECORDS.turn, data: { turn, usd: usage.usd, ...tokensOf(usage), ...(usage.givenBack ? { givenBack: true } : {}), ...(usage.estimated ? { estimated: true } : {}), ...(usage.tableUsd === undefined ? {} : { tableUsd: usage.tableUsd }), ...(usage.providerIds ? { providerIds: usage.providerIds } : {}), ...(stopped === undefined ? {} : { heldUsd: Math.min(hold, stopped), stopped: true }), ...(booking ? { bookedUsd: booking.usd, rule: booking.rule } : {}), ...(note ? { note } : {}) } }], covers);
372
+ await write([{ kind: RUNNER_RECORDS.turn, data }], covers);
373
+ settle?.();
314
374
  }
315
375
  catch (error) {
376
+ // Refused (its claim lost as it answered, say): the booking is handed to the session's next booking in this
377
+ // process, which writes it at its bookCut, never cutting a request that answered (handoffs).
378
+ if (scope !== undefined)
379
+ handoffOf(scope).refused.set(turn, { data, usage, ...(ended ? { ended } : {}) });
380
+ settle?.();
316
381
  // A paid request whose cost can't be kept: the attempt stops, saying so, rather than spend on uncounted. Asked
317
382
  // with the request's own host label, as its admission was: a stop that holds only the harness's own requests (a
318
383
  // parked turn's) never hides the failure from the host's. A turn parked on a call (TurnParked) is no stop of the
@@ -325,7 +390,9 @@ function bookingFor(writer, options) {
325
390
  }
326
391
  answered.add(turn);
327
392
  const hosted = hosts.get(turn);
328
- emit({ type: "request_end", turn, usage, ...(hosted === undefined ? {} : { host: hosted }), ...(ended ? { ended } : {}) });
393
+ // Awaited: a host that marks the request's end on its record writes it before the booking counts as settled, so a
394
+ // run's end never lands ahead of the mark that says its request was cut.
395
+ await emit({ type: "request_end", turn, usage, ...(hosted === undefined ? {} : { host: hosted }), ...(ended ? { ended } : {}) });
329
396
  },
330
397
  };
331
398
  // One booking of the cut requests at a time: a call made while one is writing waits for it, never books them again.
@@ -334,7 +401,53 @@ function bookingFor(writer, options) {
334
401
  // A paid request a crash cut off kept its runner.request and has no runner.turn: the provider may have billed it.
335
402
  // Each is booked once, as cut, at an unknown price, and the host is told as for any answered request, so its ledger
336
403
  // shows the possible spend instead of nothing. Booked, it is answered: a later attempt never books it again.
337
- // Only requests an earlier process admitted: one this process has in flight is not cut.
404
+ // Only requests an earlier process admitted: one this process has in flight is not cut. Read again here, just before
405
+ // the cut is written: another booking of this session (an earlier pass of this claim, or one racing it) may have
406
+ // booked it since this one opened, and a request is booked once.
407
+ // An earlier booking of this session in this process (a claim lost, then taken again here) may still have one of them
408
+ // in flight: its end is waited for, bounded, so a request that answers meanwhile is booked by what it reported.
409
+ const before = scope === undefined ? undefined : handoffs.get(scope);
410
+ const flying = before ? inherited.filter((t) => !answered.has(t)).flatMap((t) => before.flying.get(t) ?? []) : [];
411
+ if (flying.length) {
412
+ let timer;
413
+ await Promise.race([Promise.all(flying), new Promise((resolve) => (timer = setTimeout(resolve, HANDOFF_WAIT_MS)))]);
414
+ clearTimeout(timer);
415
+ }
416
+ const now = await writer.read().catch(() => options.records);
417
+ const bookedSince = sessionSpendOf(now).answered;
418
+ for (const t of inherited)
419
+ if (bookedSince.has(t))
420
+ answered.add(t);
421
+ // A request an earlier booking in this process saw answer, whose runner.turn its store refused: written now as that
422
+ // booking would have written it, and told as it would have told it, at what it reported. One the session booked since
423
+ // is dropped: a request is booked once.
424
+ const handed = scope === undefined ? undefined : handoffs.get(scope);
425
+ if (scope !== undefined && handed) {
426
+ for (const t of inherited)
427
+ if (answered.has(t))
428
+ handed.refused.delete(t);
429
+ const taken = inherited.flatMap((turn) => {
430
+ const one = handed.refused.get(turn);
431
+ return one ? [{ turn, ...one }] : [];
432
+ });
433
+ if (taken.length) {
434
+ const records = taken.map((one) => ({ kind: RUNNER_RECORDS.turn, data: one.data }));
435
+ await append(records);
436
+ for (const one of taken) {
437
+ handed.refused.delete(one.turn);
438
+ answered.add(one.turn);
439
+ }
440
+ // Its spend read the request at its hold and bound (or unknown); booked, it reads at what it was booked at. Only
441
+ // before this booking's own requests: the spend is the session's records then.
442
+ if (turns === inherited.length && open.length === 0)
443
+ spentUsd = sessionSpendOf([...now, ...records]).spentUsd;
444
+ for (const one of taken) {
445
+ const hosted = hosts.get(one.turn);
446
+ await emit({ type: "request_end", turn: one.turn, usage: one.usage, ...(hosted === undefined ? {} : { host: hosted }), ...(one.ended ? { ended: one.ended } : {}) });
447
+ }
448
+ }
449
+ handoffDone(scope);
450
+ }
338
451
  const left = inherited.filter((t) => !answered.has(t));
339
452
  if (left.length === 0)
340
453
  return;
@@ -385,6 +498,8 @@ function bookingFor(writer, options) {
385
498
  models,
386
499
  turns: () => turns,
387
500
  spentUsd: () => spentUsd,
501
+ heldUsd: () => open.reduce((sum, flight) => (sum === null || flight.holdUsd === undefined ? null : sum + flight.holdUsd), 0),
502
+ boundUsd: () => open.reduce((sum, flight) => sum + (flight.boundUsd ?? 0), 0),
388
503
  bookCut() {
389
504
  cutting ??= bookCut().catch((error) => {
390
505
  cutting = undefined;
package/dist/testing.d.ts CHANGED
@@ -5,8 +5,12 @@ export { SCHEMA_CHECK_CASES, type SchemaCheckCase } from "./schema-check-cases.j
5
5
  * harness runs. */
6
6
  export { inputTokensMaxOf, matchRoute, parseStrict, reportedCostOf } from "./host/proxy.js";
7
7
  /** A session store in memory: what one run's store holds, across the processes a test plays. Each `open` of a key
8
- * counts one more holder at once, and a writer appends only while its count is the newest. */
9
- export declare function memorySessionStore(): SessionStore & {
8
+ * counts one more holder at once, and a writer appends only while its count is the newest. `scope`: the run's identity
9
+ * in this process, for a test that plays a claim lost and taken again in one process (SessionWriter.scope); without it,
10
+ * each open plays a process of its own, which hands nothing on. */
11
+ export declare function memorySessionStore(options?: {
12
+ scope?: string;
13
+ }): SessionStore & {
10
14
  keys(): string[];
11
15
  };
12
16
  /** What a scripted request reports beside its cost, as a real adapter's proxy reads a response, and how it is measured:
package/dist/testing.js CHANGED
@@ -14,8 +14,10 @@ export { SCHEMA_CHECK_CASES } from "./schema-check-cases.js";
14
14
  * harness runs. */
15
15
  export { inputTokensMaxOf, matchRoute, parseStrict, reportedCostOf } from "./host/proxy.js";
16
16
  /** A session store in memory: what one run's store holds, across the processes a test plays. Each `open` of a key
17
- * counts one more holder at once, and a writer appends only while its count is the newest. */
18
- export function memorySessionStore() {
17
+ * counts one more holder at once, and a writer appends only while its count is the newest. `scope`: the run's identity
18
+ * in this process, for a test that plays a claim lost and taken again in one process (SessionWriter.scope); without it,
19
+ * each open plays a process of its own, which hands nothing on. */
20
+ export function memorySessionStore(options = {}) {
19
21
  const sessions = new Map();
20
22
  const holders = new Map();
21
23
  const read = async (key) => structuredClone(sessions.get(key) ?? []);
@@ -26,6 +28,7 @@ export function memorySessionStore() {
26
28
  holders.set(key, holder);
27
29
  return {
28
30
  key,
31
+ ...(options.scope === undefined ? {} : { scope: `${options.scope}\n${key}` }),
29
32
  read: () => read(key),
30
33
  async append(records) {
31
34
  if (holders.get(key) !== holder)
@@ -53,7 +56,6 @@ export function fauxAdapter(options) {
53
56
  get calls() { return stats.calls; },
54
57
  get opened() { return stats.opened; },
55
58
  get closed() { return stats.closed; },
56
- capabilities: () => ({}),
57
59
  check: (spec) => [
58
60
  ...(spec.context === "fork" ? ["the faux harness cannot fork a session"] : []),
59
61
  ...(options.refuse?.(spec) ?? []),
@@ -0,0 +1,12 @@
1
+ export declare const TOOLS_SEARCH = "tools_search";
2
+ export declare const TOOLS_CALL = "tools_call";
3
+ export declare const CODEMODE = "codemode";
4
+ /** The three, by name: none of them can be called through another, and none is searched for. */
5
+ export declare const META_TOOLS: ReadonlySet<string>;
6
+ /** A run with more catalog tools than this is deferred them. */
7
+ export declare const DEFER_CATALOG_OVER = 20;
8
+ /** Whether a tool is a catalog tool, by the name a harness gives it: an MCP tool (`mcp__<server>__<tool>`) or a monid
9
+ * endpoint (`monid__<provider>__<endpoint>`). */
10
+ export declare const isCatalogName: (name: string) => boolean;
11
+ /** Whether a run whose host tools are `names` has its catalog tools deferred: more than DEFER_CATALOG_OVER of them. */
12
+ export declare const defersCatalog: (names: readonly string[]) => boolean;
@@ -0,0 +1,17 @@
1
+ // One discovery system. A run lists every tool to the model in full until its catalog tools (an MCP server's, a monid
2
+ // one) pass DEFER_CATALOG_OVER: then they are deferred, not listed, and the model finds them with tools_search and runs
3
+ // them with tools_call. Claude Code defers MCP tools itself (its ToolSearch), on under the same test, so it is offered
4
+ // neither of ours. Built-ins and a harness's own tools are always listed. A run under the threshold has no search or call:
5
+ // they would find tools the model already has, at about 640 tokens on every request.
6
+ export const TOOLS_SEARCH = "tools_search";
7
+ export const TOOLS_CALL = "tools_call";
8
+ export const CODEMODE = "codemode";
9
+ /** The three, by name: none of them can be called through another, and none is searched for. */
10
+ export const META_TOOLS = new Set([TOOLS_SEARCH, TOOLS_CALL, CODEMODE]);
11
+ /** A run with more catalog tools than this is deferred them. */
12
+ export const DEFER_CATALOG_OVER = 20;
13
+ /** Whether a tool is a catalog tool, by the name a harness gives it: an MCP tool (`mcp__<server>__<tool>`) or a monid
14
+ * endpoint (`monid__<provider>__<endpoint>`). */
15
+ export const isCatalogName = (name) => name.startsWith("mcp__") || name.startsWith("monid_");
16
+ /** Whether a run whose host tools are `names` has its catalog tools deferred: more than DEFER_CATALOG_OVER of them. */
17
+ export const defersCatalog = (names) => names.filter(isCatalogName).length > DEFER_CATALOG_OVER;