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

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 (70) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/NOTICE +2 -0
  3. package/dist/booking.d.ts +25 -6
  4. package/dist/booking.js +15 -4
  5. package/dist/host/index.d.ts +4 -5
  6. package/dist/host/index.js +3 -3
  7. package/dist/host/o200k.d.ts +11 -0
  8. package/dist/host/o200k.js +185 -0
  9. package/dist/host/overhead.d.ts +105 -3
  10. package/dist/host/overhead.js +276 -20
  11. package/dist/host/proxy.d.ts +97 -16
  12. package/dist/host/proxy.js +420 -108
  13. package/dist/index.d.ts +6 -5
  14. package/dist/index.js +4 -3
  15. package/dist/kernel/cap/admit.d.ts +5 -8
  16. package/dist/kernel/cap/admit.js +13 -19
  17. package/dist/kernel/cap/free.d.ts +43 -0
  18. package/dist/kernel/cap/free.js +71 -0
  19. package/dist/kernel/cap/index.d.ts +7 -6
  20. package/dist/kernel/cap/index.js +6 -5
  21. package/dist/kernel/cap/marks.d.ts +2 -3
  22. package/dist/kernel/cap/park.d.ts +3 -4
  23. package/dist/kernel/cap/park.js +4 -5
  24. package/dist/kernel/cap/port.d.ts +11 -5
  25. package/dist/kernel/cap/port.js +26 -24
  26. package/dist/kernel/cap/price.d.ts +10 -30
  27. package/dist/kernel/cap/price.js +15 -48
  28. package/dist/kernel/cap/recover.d.ts +1 -2
  29. package/dist/kernel/cap/recover.js +2 -4
  30. package/dist/kernel/cap/rule.d.ts +11 -17
  31. package/dist/kernel/cap/rule.js +37 -19
  32. package/dist/kernel/cap/run-cap.d.ts +25 -10
  33. package/dist/kernel/cap/run-cap.js +78 -35
  34. package/dist/kernel/cap/types.d.ts +11 -27
  35. package/dist/kernel/cap/words.d.ts +13 -8
  36. package/dist/kernel/cap/words.js +23 -14
  37. package/dist/kernel/cap/wrap-up.d.ts +4 -0
  38. package/dist/kernel/cap/wrap-up.js +5 -1
  39. package/dist/kernel/registry/computer-surface.generated.d.ts +1 -1
  40. package/dist/kernel/registry/computer-surface.generated.js +18 -27
  41. package/dist/kernel/registry/computer.d.ts +14 -7
  42. package/dist/kernel/registry/computer.js +64 -16
  43. package/dist/kernel/registry/gate.d.ts +2 -2
  44. package/dist/kernel/registry/gate.js +4 -7
  45. package/dist/kernel/registry/hands.d.ts +4 -5
  46. package/dist/kernel/registry/index.d.ts +1 -1
  47. package/dist/kernel/registry/index.js +1 -1
  48. package/dist/kernel/registry/registry.js +6 -9
  49. package/dist/kernel/types.d.ts +8 -1
  50. package/dist/process/recovery.d.ts +4 -1
  51. package/dist/process/recovery.js +15 -3
  52. package/dist/process/resume.d.ts +5 -2
  53. package/dist/process/resume.js +15 -3
  54. package/dist/process/tools.d.ts +28 -1
  55. package/dist/process/tools.js +102 -5
  56. package/dist/run-booking.d.ts +21 -2
  57. package/dist/run-booking.js +215 -18
  58. package/dist/runner.d.ts +82 -21
  59. package/dist/runner.js +271 -56
  60. package/dist/testing.d.ts +10 -4
  61. package/dist/testing.js +7 -5
  62. package/dist/tool-deferral.d.ts +12 -0
  63. package/dist/tool-deferral.js +17 -0
  64. package/dist/types.d.ts +133 -48
  65. package/dist/types.js +8 -0
  66. package/package.json +5 -3
  67. package/vendor/o200k/LICENSE +61 -0
  68. package/vendor/o200k/o200k_base.tiktoken +199998 -0
  69. package/dist/host/mcp-route.d.ts +0 -14
  70. package/dist/host/mcp-route.js +0 -125
@@ -1,4 +1,4 @@
1
- import type { JsonValue, SessionWriter, ToolImage } from "../types.js";
1
+ import type { JsonValue, NestedCalls, SessionWriter, ToolImage } from "../types.js";
2
2
  export type ReplayPolicy = "safe" | "never";
3
3
  export type SubmissionKind = "prompt" | "steer" | "followUp" | "withdraw";
4
4
  /** One input a person sent the session, as the host recorded it. */
@@ -104,6 +104,11 @@ export interface HostTool<Input = any> {
104
104
  description: string;
105
105
  inputSchema: object;
106
106
  replay: ReplayPolicy;
107
+ /** It only calls the session's other tools, each a call of its own (HostToolIO `nested`): the bridge writes no effect
108
+ * of its own for it, so a crash leaves it to run again, its nested calls answered from their records. */
109
+ nests?: true;
110
+ /** Callable by name (a nested call) but never listed to the model (the bridge leaves it out of `tools`). */
111
+ deferred?: true;
107
112
  /** Its answer: the text, or the text with the images it shows. Recorded as the call's outcome, so a call answered
108
113
  * from the record answers with the same images. */
109
114
  execute(input: Input, io: HostToolIO): Promise<string | ToolOutput>;
@@ -119,5 +124,7 @@ export interface HostToolIO {
119
124
  progress(chunk: unknown): void;
120
125
  ctx: DriveContext;
121
126
  stepId?: string;
127
+ /** For a tool that `nests`: the session's other tools by their names on the bridge, each call one of its own. */
128
+ nested?: NestedCalls;
122
129
  }
123
130
  export type { JsonValue };
@@ -53,9 +53,12 @@ export declare function recoveryNote(state: SessionState, options?: RecoveryOpti
53
53
  * The note as a harness carries it outside the user's turn (a system prompt, a developer item): from the harness, about the
54
54
  * turn before, in the harness's own words only. It names each call and says how it ended, and never quotes what a tool was
55
55
  * given or answered with (that is data the agent read, not something the harness may speak for), a prompt, or a pending message.
56
+ * `shown`: the calls whose result or error the conversation already carries, in the recovered output of the script that made
57
+ * them (Codex's code mode): for a completed or failed one the note says it is there, never that it is not shown. With none
58
+ * (every other harness), each call's output is not shown here, as it says.
56
59
  * `undefined` when no turn is open.
57
60
  */
58
- export declare function recoverySystemNote(state: SessionState): string | undefined;
61
+ export declare function recoverySystemNote(state: SessionState, shown?: ReadonlySet<string>): string | undefined;
59
62
  /** The user's turn that resumes a cut-off turn: only the user's words (the prompts the session never got, then the messages sent since), or a bare nudge. */
60
63
  export declare function recoveryUserTurn(lost: string[], pending: string[]): string;
61
64
  /**
@@ -42,13 +42,17 @@ export function recoveryNote(state, options = {}) {
42
42
  * The note as a harness carries it outside the user's turn (a system prompt, a developer item): from the harness, about the
43
43
  * turn before, in the harness's own words only. It names each call and says how it ended, and never quotes what a tool was
44
44
  * given or answered with (that is data the agent read, not something the harness may speak for), a prompt, or a pending message.
45
+ * `shown`: the calls whose result or error the conversation already carries, in the recovered output of the script that made
46
+ * them (Codex's code mode): for a completed or failed one the note says it is there, never that it is not shown. With none
47
+ * (every other harness), each call's output is not shown here, as it says.
45
48
  * `undefined` when no turn is open.
46
49
  */
47
- export function recoverySystemNote(state) {
50
+ export function recoverySystemNote(state, shown = new Set()) {
48
51
  const turn = openTurn(state);
49
52
  if (!turn)
50
53
  return undefined;
51
54
  const calls = turn.calls.map((e) => recoveryCall(e, 0));
55
+ const carried = (c) => shown.has(c.callId) && (c.status === 'completed' || c.status === 'failed');
52
56
  const lines = [
53
57
  'The harness, not the user, adds this about the turn before this one:',
54
58
  '[Recovery] Your previous turn was interrupted: the process running it stopped, and this session was resumed from its durable log.',
@@ -59,12 +63,20 @@ export function recoverySystemNote(state) {
59
63
  else {
60
64
  lines.push('What the log records about the tool calls since that turn began (none was run again):');
61
65
  for (const c of calls)
62
- lines.push(`- ${c.name}, call ${c.callId}: ${ended(c)}`);
63
- lines.push('', 'The output of those calls is not shown here. Check the actual state before relying on it.');
66
+ lines.push(`- ${c.name}, call ${c.callId}: ${carried(c) ? endedShown(c) : ended(c)}`);
67
+ const unshown = calls.filter((c) => !carried(c)).length;
68
+ if (unshown === calls.length)
69
+ lines.push('', 'The output of those calls is not shown here. Check the actual state before relying on it.');
70
+ else if (unshown > 0)
71
+ lines.push('', 'The output of the other calls is not shown here. Check the actual state before relying on it.');
64
72
  }
65
73
  lines.push('', 'Check the actual state before repeating anything that may have taken effect, then carry on with the task.');
66
74
  return lines.join('\n');
67
75
  }
76
+ /** How a call whose outcome the conversation carries ended (`shown`, recoverySystemNote): where that outcome is. */
77
+ function endedShown(c) {
78
+ return c.status === 'failed' ? 'failed. Its error is in the output of the script that made the call, above.' : 'completed. Its result is in the output of the script that made the call, above.';
79
+ }
68
80
  function ended(c) {
69
81
  switch (c.status) {
70
82
  case 'completed':
@@ -13,8 +13,11 @@ export interface CallOutcome {
13
13
  }
14
14
  /** The dangling calls that never reached their intent: no effect of theirs in the drive's records. */
15
15
  export declare function unstartedCalls(ctx: DriveContext, dangling: readonly DanglingCall[]): DanglingCall[];
16
+ /** The dangling calls whose end the drive's records hold: completed, or failed of their own accord (not cut off). */
17
+ export declare function endedCalls(ctx: DriveContext, dangling: readonly DanglingCall[]): DanglingCall[];
16
18
  /**
17
- * Each dangling call that never reached its intent through `bridge` (gate, intent, call, result), then `settle`d into
18
- * the CLI's transcript, one call after another in the transcript's order. Calls with an intent are left as they are.
19
+ * Each dangling call that never reached its intent through `bridge` (gate, intent, call, result), and each one whose end
20
+ * the records hold read back through it (its memo: nothing runs, nothing is asked), then `settle`d into the CLI's
21
+ * transcript, one call after another in the transcript's order. A call cut off is left as it is.
19
22
  */
20
23
  export declare function resumeUnstartedCalls(ctx: DriveContext, bridge: ToolBridge, dangling: readonly DanglingCall[], settle: (call: DanglingCall, outcome: CallOutcome) => Promise<void>): Promise<void>;
@@ -4,12 +4,24 @@ export function unstartedCalls(ctx, dangling) {
4
4
  const effects = ctx.state().effects;
5
5
  return dangling.filter((call) => !effects.has(toolKey(call.callId)));
6
6
  }
7
+ /** The dangling calls whose end the drive's records hold: completed, or failed of their own accord (not cut off). */
8
+ export function endedCalls(ctx, dangling) {
9
+ const effects = ctx.state().effects;
10
+ return dangling.filter((call) => {
11
+ const effect = effects.get(toolKey(call.callId));
12
+ return effect?.status === 'completed' || (effect?.status === 'failed' && effect.error?.interrupted !== true);
13
+ });
14
+ }
7
15
  /**
8
- * Each dangling call that never reached its intent through `bridge` (gate, intent, call, result), then `settle`d into
9
- * the CLI's transcript, one call after another in the transcript's order. Calls with an intent are left as they are.
16
+ * Each dangling call that never reached its intent through `bridge` (gate, intent, call, result), and each one whose end
17
+ * the records hold read back through it (its memo: nothing runs, nothing is asked), then `settle`d into the CLI's
18
+ * transcript, one call after another in the transcript's order. A call cut off is left as it is.
10
19
  */
11
20
  export async function resumeUnstartedCalls(ctx, bridge, dangling, settle) {
12
- for (const call of unstartedCalls(ctx, dangling)) {
21
+ const taken = new Set([...unstartedCalls(ctx, dangling), ...endedCalls(ctx, dangling)]);
22
+ for (const call of dangling) {
23
+ if (!taken.has(call))
24
+ continue;
13
25
  const result = await bridge.call(call.tool, call.args, call.callId);
14
26
  await settle(call, { text: result.text, isError: result.isError });
15
27
  }
@@ -1,5 +1,5 @@
1
1
  import { type DriveContext, type EffectError, type HostTool, type ReplayPolicy } from '../kernel/index.js';
2
- import { type GateAnswer, type GateCall, type JsonValue, type ToolImage } from '../types.js';
2
+ import { type GateAnswer, type GateCall, type HostTool as AdapterTool, type JsonValue, type ToolImage } from '../types.js';
3
3
  /**
4
4
  * The tool bridge: `HostTool`s as a harness-neutral list a port maps onto its
5
5
  * harness's own tool mechanism (Codex's dynamic tools).
@@ -30,6 +30,8 @@ export interface ToolResult {
30
30
  structured?: JsonValue;
31
31
  /** The text was cut at HOST_RESULT_MAX_CHARS (`boundResult`); it says so in its last line. */
32
32
  truncated?: true;
33
+ /** The gate refused the call: the text is its words, and nothing of the call was written or run. */
34
+ refused?: true;
33
35
  }
34
36
  /** One tool, harness-neutral. */
35
37
  export interface BridgedTool {
@@ -121,3 +123,28 @@ export declare function boundResult(text: string): {
121
123
  };
122
124
  /** At most `max` characters, with a marker when cut. */
123
125
  export declare function clip(text: string, max: number): string;
126
+ /** What a harness adds to the one conversion of a host tool into the bridge's (`bridgeTool`): each is absent where it has none. */
127
+ export interface BridgeHooks {
128
+ /** The name the harness gives the tool (Codex's `mcp_` form for an MCP tool); with `nestedName` its inverse for a nested call. */
129
+ name?: string;
130
+ description?: string;
131
+ /** A tool that nests calls names them by the host's names; the bridge holds them by the harness's: this maps one to the other. */
132
+ nestedName?(name: string): string;
133
+ /** Run once the call's intent is in the records, before the tool runs: the harness's live `tool_start`, its pause check. A throw is the call's error. */
134
+ start?(call: {
135
+ callId: string;
136
+ attempt: number;
137
+ args: unknown;
138
+ }): void;
139
+ /** The problem with a result's images for this harness's model, or undefined: the call's error, by the tool's name and the image. */
140
+ imageProblems?(images: readonly ToolImage[]): string | undefined;
141
+ /** The tool parked the call for a person's approval: recorded so, before its answer. */
142
+ parked?(ctx: DriveContext, callId: string): Promise<unknown>;
143
+ }
144
+ /** A host tool (`call(args, context)`) as the bridge's tool (`execute(input, io)`), once for every harness: the same name,
145
+ * schema, replay policy, `nests` and `deferred`; the call runs as a kernel effect, whose intent is durable in the session's
146
+ * records before `execute` is entered, so a crash inside a `never` tool is always reported, never repeated. The effect's
147
+ * step is `tool:<the harness's call id>#<attempt>`, so the host sees the harness's call id and the attempt (above 0 when
148
+ * a crash cut an earlier one and the kernel runs the call again). A result that is an error is the call's failure; its
149
+ * value and images are recorded with the outcome (a script's nested call is answered them). */
150
+ export declare function bridgeTool(tool: AdapterTool, hooks?: BridgeHooks): HostTool;
@@ -51,24 +51,53 @@ 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, own) {
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, own ? AbortSignal.any([signal, own]) : 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. A value given
69
+ // as a function is called only while none is recorded, and outside the effect, so a throw of its (a cap's refusal, a
70
+ // stop) is never recorded as the memo's outcome: the next run calls it again.
71
+ async memo(key, value) {
72
+ const memoKey = `nested:${outer}/${key}`;
73
+ const options = { name: 'nested.memo', replay: 'safe', input: null };
74
+ if (typeof value !== 'function' || ctx.isMemoized(memoKey))
75
+ return ctx.effect(memoKey, options, async () => value);
76
+ const fixed = await value();
77
+ return ctx.effect(memoKey, options, async () => fixed);
78
+ },
79
+ });
54
80
  const bridged = tools.map((tool) => {
55
- const run = async (args, callId, signal) => {
81
+ const run = async (args, callId, signal, nested) => {
56
82
  if (!callId)
57
83
  throw new TypeError(`agentrun-kernel: a call to ${tool.name} has no call id; derive a stable one`);
58
84
  const key = toolKey(callId);
85
+ // A tool that only nests calls writes nothing of its own: it runs, each nested call recorded as itself.
86
+ if (tool.nests)
87
+ return runNesting(args, callId, signal, nested);
59
88
  const fresh = !ctx.isMemoized(key);
60
89
  // The gate first: before the flush and the intent, so a refused or parked call leaves nothing in the log.
61
90
  if (fresh && options.gate) {
62
91
  // 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
92
  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);
93
+ 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
94
  if (refused)
66
- return { text: refused.deny, isError: true };
95
+ return { text: refused.deny, isError: true, refused: true };
67
96
  }
68
97
  if (fresh && tool.replay === 'never')
69
98
  await options.beforeNever?.({ name: tool.name, callId, args });
70
99
  if (fresh && live)
71
- ctx.live({ type: 'tool_start', name: tool.name, args, callId });
100
+ ctx.live({ type: 'tool_start', name: tool.name, args, callId, ...(nested ? { parent: callId.slice(0, callId.lastIndexOf('/')) } : {}) });
72
101
  try {
73
102
  const output = await ctx.effect(key, {
74
103
  name: `tool.${tool.name}`,
@@ -93,6 +122,39 @@ export function toolBridge(ctx, tools, options = {}) {
93
122
  throw err;
94
123
  }
95
124
  };
125
+ /** A tool that `nests`: asked at the gate as itself, then run with the session's tools as its nested calls, no effect
126
+ * of its own written. Its error result is its answer; a throw while the drive or the call is aborted (a nested call
127
+ * parked, the session let go) halts the drive, as an effect's does, so the harness is never handed a result. */
128
+ const runNesting = async (args, callId, signal, nested) => {
129
+ const aborted = signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal;
130
+ if (options.gate) {
131
+ const refused = await askGate(options.gate, { callId, tool: tool.name, args: (args ?? {}), ...(nested ? { nested } : {}) }, aborted);
132
+ if (refused)
133
+ return { text: refused.deny, isError: true, refused: true };
134
+ }
135
+ if (live)
136
+ ctx.live({ type: 'tool_start', name: tool.name, args, callId });
137
+ let output;
138
+ try {
139
+ output = await tool.execute(args, { signal: aborted, progress: () => { }, ctx, stepId: `${toolKey(callId)}#0`, nested: nestedIn(callId, aborted) });
140
+ }
141
+ catch (err) {
142
+ if (aborted.aborted) {
143
+ ctx.halt?.(err);
144
+ throw err;
145
+ }
146
+ const { text, truncated } = boundResult(err instanceof Error ? err.message : String(err));
147
+ if (live)
148
+ ctx.live({ type: 'tool_end', name: tool.name, callId, isError: true, result: text, ...(truncated ? { truncated } : {}) });
149
+ return { text, isError: true, ...(truncated ? { truncated } : {}) };
150
+ }
151
+ const { text: whole, images, structured } = typeof output === 'object' && output !== null ? output : { text: String(output), images: undefined, structured: undefined };
152
+ const { text, truncated } = boundResult(String(whole));
153
+ if (live)
154
+ ctx.live({ type: 'tool_end', name: tool.name, callId, result: text, ...(truncated ? { truncated } : {}) });
155
+ return { text, isError: false, ...(images?.length ? { images } : {}), ...(structured !== undefined ? { structured } : {}), ...(truncated ? { truncated } : {}) };
156
+ };
157
+ runs.set(tool.name, run);
96
158
  return {
97
159
  name: tool.name,
98
160
  description: tool.description,
@@ -103,7 +165,8 @@ export function toolBridge(ctx, tools, options = {}) {
103
165
  });
104
166
  const byName = new Map(bridged.map((t) => [t.name, t]));
105
167
  return {
106
- tools: bridged,
168
+ // What is listed to the model: a deferred tool is run by name (a nested call, `get`, `call`) and never listed.
169
+ tools: bridged.filter((_, index) => !tools[index].deferred),
107
170
  get: (name) => byName.get(name),
108
171
  call: async (name, args, callId, signal) => {
109
172
  const tool = byName.get(name);
@@ -148,3 +211,37 @@ export function boundResult(text) {
148
211
  export function clip(text, max) {
149
212
  return text.length <= max ? text : `${text.slice(0, max)}… [${text.length - max} more characters]`;
150
213
  }
214
+ /** A host tool (`call(args, context)`) as the bridge's tool (`execute(input, io)`), once for every harness: the same name,
215
+ * schema, replay policy, `nests` and `deferred`; the call runs as a kernel effect, whose intent is durable in the session's
216
+ * records before `execute` is entered, so a crash inside a `never` tool is always reported, never repeated. The effect's
217
+ * step is `tool:<the harness's call id>#<attempt>`, so the host sees the harness's call id and the attempt (above 0 when
218
+ * a crash cut an earlier one and the kernel runs the call again). A result that is an error is the call's failure; its
219
+ * value and images are recorded with the outcome (a script's nested call is answered them). */
220
+ export function bridgeTool(tool, hooks = {}) {
221
+ return {
222
+ name: hooks.name ?? tool.name,
223
+ description: hooks.description ?? tool.description,
224
+ inputSchema: tool.inputSchema,
225
+ replay: tool.replay,
226
+ ...(tool.nests ? { nests: true } : {}),
227
+ ...(tool.deferred ? { deferred: true } : {}),
228
+ async execute(input, io) {
229
+ const callId = (io.stepId ?? '').replace(/^tool:/, '').replace(/#\d+$/, '');
230
+ const attempt = Number(/#(\d+)$/.exec(io.stepId ?? '')?.[1] ?? 0);
231
+ hooks.start?.({ callId, attempt, args: input });
232
+ const nested = io.nested && hooks.nestedName ? { call: (name, args, key, signal) => io.nested.call(hooks.nestedName(name), args, key, signal), memo: io.nested.memo } : io.nested;
233
+ const result = await tool.call(input, { callId, signal: io.signal, attempt, ...(nested ? { nested } : {}) });
234
+ if (result.parked && hooks.parked)
235
+ await hooks.parked(io.ctx, callId);
236
+ if (result.isError)
237
+ throw new Error(result.text);
238
+ const structured = result.structured !== undefined ? { structured: result.structured } : {};
239
+ if (!result.images?.length)
240
+ return result.structured === undefined ? result.text : { text: result.text, ...structured };
241
+ const wrong = hooks.imageProblems?.(result.images);
242
+ if (wrong)
243
+ throw new Error(wrong);
244
+ return { text: result.text, images: result.images.map((image) => ({ mimeType: image.mimeType, data: image.data })), ...structured };
245
+ },
246
+ };
247
+ }
@@ -8,5 +8,24 @@ export interface RunSessions {
8
8
  * cost, what is under way at the most it may take); null: unknown. None: nothing is. */
9
9
  beside?(): Promise<number | null>;
10
10
  }
11
- /** `before`, asked about each request with the run's totals over `sessions` in place of its session's own. */
12
- export declare function runBooking(sessions: RunSessions, before: BeforeRequest): BeforeRequest;
11
+ export interface RunBookingOptions {
12
+ /** Whether the run has parked (a step refused for room it could not wait for, a paid call's refusal): a request waiting
13
+ * for room leaves the line refused in its own words, so nothing more is sent until a raise. */
14
+ parked?(): boolean;
15
+ /** How long a waiter waits with none of the steps it waits on settling before it is refused (default WAIT_STALL_MS). */
16
+ stallMs?: number;
17
+ /** The run's stop (a stop, a cancel, a lost claim): every waiter leaves the line at it, admitted for nothing. */
18
+ stopped?: AbortSignal;
19
+ }
20
+ /** How soon a waiter reads the run's records again, first and at the slowest (it doubles between them). */
21
+ export declare const WAIT_POLL_FIRST_MS = 50;
22
+ export declare const WAIT_POLL_MOST_MS = 1000;
23
+ /** How long a request waits for room with none of the steps it waits on settling: past it, it is refused for room and the
24
+ * run parks (a step that never settles, which nothing here expects, never hangs the run). */
25
+ export declare const WAIT_STALL_MS: number;
26
+ /** How long an admission may go unrecorded before no one waits on it: its record is written just after its admission,
27
+ * so one missing this long never will be (its write refused, its booking stopped). It is still held, never freed. */
28
+ export declare const RECORD_WAIT_MS = 30000;
29
+ /** `before`, asked about each request with the run's totals over `sessions` in place of its session's own; a refusal that
30
+ * waits is asked again once the room may be there (above). */
31
+ export declare function runBooking(sessions: RunSessions, before: BeforeRequest, options?: RunBookingOptions): BeforeRequest;
@@ -2,59 +2,256 @@
2
2
  // once it is an adapter), but a cap is the run's: a session is judged on what every session of the run has spent and
3
3
  // holds, never on its own alone. runBooking wraps the host's beforeRequest (the cap's beforeRequestOf) so that each
4
4
  // request it is asked about carries the run's totals:
5
- // - `spentUsd`: every session's spend from its runner records (sessionSpendOf), summed; a request recorded and not yet
6
- // answered (in flight in any session, in this process or a lost one) counts there at what its host held for it;
7
- // - `inFlight`: the requests this booking admitted that no record shows yet, each at what it was held at, so two
8
- // sessions asking at once never both take room only one of them fits.
5
+ // - `spentUsd`: every session's spend from its runner records (sessionSpendOf), summed: what was booked, and a request
6
+ // recorded and never answered that no booking here admitted (a lost claim's, cut) at what its host held for it. A
7
+ // request this booking admitted and still in flight is no spend: it is held (below), never read as spent;
8
+ // - `inFlight`: the requests this booking admitted that no record shows answered yet, each at what it was held at, so two
9
+ // sessions asking at once never both take room only one of them fits. A hold-only step is marked `stays` (no request
10
+ // waits on it), and so is one admitted RECORD_WAIT_MS ago that no record shows at all (its write refused: a phantom);
9
11
  // - what was spent beside its sessions on the run's behalf (`sessions.beside`: a run's learning, graded by runs of its
10
12
  // own), read with them at each admission and added to `spentUsd`, so a run and what it pays for elsewhere never pass
11
13
  // its cap together. Unknown (null) makes the run's spend unknown.
14
+ // - `freeRequestsMade`: the run's requests on free models so far (each runner.request marked `freeRequest`, and each
15
+ // admitted here not yet recorded), which the cap's ceiling on such requests reads (runCap, free.ts).
12
16
  // Admissions run one at a time across the run's sessions. The priced tools' charges and holds are not here: they are the
13
17
  // host's spentUsd and heldUsd hooks (beforeRequestOf), read beside these.
18
+ //
19
+ // Waiting for room. A refusal that `waits` (the cap's: the request fits beside the run's spend, only not beside the holds
20
+ // of steps in flight that settle on their own) is not handed on: the request waits in the run's line, first come first
21
+ // served, and is asked again once a step it waited on has settled (each settle books the step at what it cost, at most its
22
+ // hold, so the room comes back). Every step joins the line as it comes, before its first ask, and only the line's first
23
+ // asks, so a small one never takes the room an earlier one waits for, even when the two came together. Model requests,
24
+ // decisions and paid tool calls (a web fetch's, a search's) wait alike, but for one thing:
25
+ // - A paid call never waits on the request that asked for it. pi runs a tool once its request has answered, but a CLI
26
+ // may not: Claude Code books a request's cost after its calls, and Codex starts a call with its response still open,
27
+ // so that request settles only once the call returns. A paid call names the model session whose tool call it runs in
28
+ // (ModelRequest.paid.under); that session's requests in flight are its parents, which no record links to the call
29
+ // (the call's id is in the response, never on the request's records), so each of them counts as one. For the call,
30
+ // they are `stays`: held beside it, never waited on. It fits beside them or is refused now (a raise sends it), never
31
+ // admitted past the cap. It still waits on every other step, which settles without it (another session's requests
32
+ // included: pi's children, each booked before its own calls run).
33
+ // - A paid call whose own session has a request in flight goes ahead of the line's steps that are not such calls (after
34
+ // any that are, in the order they came): a step waiting for room may wait on that request, which cannot settle until
35
+ // the call is done, so behind it the call would wait on its own request too.
36
+ // - The hold ledger is the run's records (every session's runner.request and runner.turn), which every process of the run
37
+ // writes: a waiter reads them again on a short timer, from WAIT_POLL_FIRST_MS doubling to WAIT_POLL_MOST_MS, so a step
38
+ // that settles in this process or any other wakes it the same way. No process signals another.
39
+ // - No deadlock: a waiter holds nothing while it waits (nothing is admitted, recorded or held for it), and it waits only on
40
+ // steps that end by themselves (a request streaming, a decision, a paid call), never on a hold-only step, on a lost
41
+ // claim's request, or, for a paid call, on its own session's requests. A waiter whose steps stop settling for WAIT_STALL_MS is refused after all, in the words it waited
42
+ // under: the run parks for a raise, as before waiting existed.
43
+ // - A waiter leaves the line, admitted for nothing and holding nothing, when its client goes (its signal: a stop, a
44
+ // cancel, a lost claim), when the run stops (`stopped`, for a paid call or a decision too), when its booking stops (`halted`: thrown, as a stop that came during the check), or when the
45
+ // run parks meanwhile (`parked`: refused in its own words, so nothing more is sent until a raise).
46
+ // - Nothing is admitted once its signal is aborted: a step that comes, or reaches its turn, after its client went or the
47
+ // run stopped is refused with the signal's reason, before any read, so no call starts or is charged after a stop.
14
48
  import { sessionSpendOf } from "./runner.js";
49
+ import { freeRequestsIn } from "./kernel/cap/free.js";
50
+ /** How soon a waiter reads the run's records again, first and at the slowest (it doubles between them). */
51
+ export const WAIT_POLL_FIRST_MS = 50;
52
+ export const WAIT_POLL_MOST_MS = 1_000;
53
+ /** How long a request waits for room with none of the steps it waits on settling: past it, it is refused for room and the
54
+ * run parks (a step that never settles, which nothing here expects, never hangs the run). */
55
+ export const WAIT_STALL_MS = 10 * 60_000;
56
+ /** How long an admission may go unrecorded before no one waits on it: its record is written just after its admission,
57
+ * so one missing this long never will be (its write refused, its booking stopped). It is still held, never freed. */
58
+ export const RECORD_WAIT_MS = 30_000;
15
59
  const idOf = (key, turn) => `${key}\u0000${turn}`;
16
- /** `before`, asked about each request with the run's totals over `sessions` in place of its session's own. */
17
- export function runBooking(sessions, before) {
18
- /** Admitted here and not yet recorded, by session and turn. One whose record never lands (its write refused, its
19
- * process gone) stays held: the run's spend is never under-counted. */
60
+ /** The error a waiter leaves with when its client goes. */
61
+ const gone = (signal) => (signal.reason instanceof Error ? signal.reason : new Error("the request's client went while it waited for room under the run's cap"));
62
+ /** `before`, asked about each request with the run's totals over `sessions` in place of its session's own; a refusal that
63
+ * waits is asked again once the room may be there (above). */
64
+ export function runBooking(sessions, before, options = {}) {
65
+ /** Admitted here and not yet answered, by session and turn, with when. One whose record never lands (its write refused,
66
+ * its process gone) stays held: the run's spend is never under-counted. */
20
67
  const admitted = new Map();
21
68
  let queue = Promise.resolve();
22
- return (request) => {
69
+ /** The requests waiting for room, in the order they came: only the first asks. */
70
+ const line = [];
71
+ const stallMs = options.stallMs ?? WAIT_STALL_MS;
72
+ /** One admission, in turn with every other: `before`'s verdict on `request` over the run's totals now, and the steps in
73
+ * flight it was judged beside that settle on their own (what a refusal that waits waits on). */
74
+ const ask = (request, signal) => {
23
75
  const asked = queue.then(async () => {
76
+ // A step whose client went, or whose run stopped, while it waited its turn here is never admitted: nothing is held,
77
+ // recorded or charged for it, and the next one asks.
78
+ if (signal?.aborted)
79
+ throw gone(signal);
24
80
  let spentUsd = 0;
81
+ // The run's requests on free models so far, each counted once: every one whose runner.request says so, answered, in
82
+ // flight or cut, in any session and any process, and below, each admitted here not yet recorded.
83
+ let freeRequestsMade = 0;
25
84
  const recorded = new Set();
85
+ const answered = new Set();
26
86
  for (const key of await sessions.keys()) {
27
- const spend = sessionSpendOf(await sessions.read(key));
28
- spentUsd = spentUsd === null || spend.spentUsd === null ? null : spentUsd + spend.spentUsd;
29
- // A hold-only step still open is no spend in its records: this booking keeps counting the one it admitted, in
30
- // flight at its hold, until it is answered (a lost claim's, admitted by no booking here, counts nothing).
87
+ const records = await sessions.read(key);
88
+ const spend = sessionSpendOf(records);
89
+ freeRequestsMade += freeRequestsIn(records);
31
90
  for (const turn of spend.turns)
32
- if (!spend.openHolds.has(turn))
33
- recorded.add(idOf(key, turn));
91
+ recorded.add(idOf(key, turn));
92
+ for (const turn of spend.answered)
93
+ answered.add(idOf(key, turn));
94
+ // Each request's figure (sessionSpendOf's), but one this booking admitted and has not seen answered: that one is
95
+ // held, in flight below, never spent. A hold-only step still open is no figure there: held below too.
96
+ let own = 0;
97
+ for (const { turn, usd } of spend.figures) {
98
+ if (!spend.answered.has(turn) && admitted.has(idOf(key, turn)))
99
+ continue;
100
+ own = own === null || usd === null ? null : own + usd;
101
+ }
102
+ spentUsd = spentUsd === null || own === null ? null : spentUsd + own;
34
103
  }
35
104
  if (sessions.beside) {
36
105
  const beside = await sessions.beside();
37
106
  spentUsd = spentUsd === null || beside === null || !Number.isFinite(beside) ? null : spentUsd + beside;
38
107
  }
39
108
  for (const id of [...admitted.keys()])
40
- if (recorded.has(id))
109
+ if (answered.has(id))
41
110
  admitted.delete(id);
42
- const verdict = await before({ ...request, spentUsd, inFlight: [...admitted.values()] });
111
+ const now = Date.now();
112
+ const settling = new Set();
113
+ const inFlight = [];
114
+ const under = request.paid?.under;
115
+ for (const [id, { at, key, ...flight }] of admitted) {
116
+ if (flight.freeRequest && !recorded.has(id))
117
+ freeRequestsMade += 1;
118
+ // One that may never settle by itself (a hold-only step, an admission whose record never landed) stays: held, and
119
+ // never waited on. So does, for a paid call, a request of the session it runs in: it may be the one that asked
120
+ // for the call, which settles only once the call is done.
121
+ const stays = flight.stays === true || (!recorded.has(id) && now - at > RECORD_WAIT_MS) || (under !== undefined && key === under);
122
+ if (!stays)
123
+ settling.add(id);
124
+ inFlight.push(stays ? { ...flight, stays: true } : flight);
125
+ }
126
+ const verdict = await before({ ...request, spentUsd, inFlight, freeRequestsMade });
43
127
  if (!(verdict && "refuse" in verdict)) {
44
128
  const holdUsd = verdict && "holdUsd" in verdict ? verdict.holdUsd : undefined;
129
+ const freeRequest = !!verdict && "freeRequest" in verdict && verdict.freeRequest === true;
45
130
  const outputTokensMax = verdict && "outputTokensMax" in verdict ? verdict.outputTokensMax : request.outputTokensAsked;
46
131
  admitted.set(idOf(request.key, request.turn), {
132
+ at: Date.now(),
133
+ key: request.key,
47
134
  turn: request.turn,
48
135
  model: request.model,
49
136
  ...(request.inputTokensMax === undefined ? {} : { inputTokensMax: request.inputTokensMax }),
50
137
  ...(outputTokensMax === undefined ? {} : { outputTokensMax }),
51
138
  ...(typeof holdUsd === "number" ? { holdUsd } : {}),
52
139
  ...(request.host === undefined ? {} : { host: request.host }),
140
+ ...(request.route === undefined ? {} : { route: request.route }),
141
+ ...(freeRequest ? { freeRequest: true } : {}),
142
+ // A hold-only step, or money already owed (a browser session's reserve or release, settled when its session
143
+ // ends, not when a call answers): never waited on.
144
+ ...(request.paid?.hold || request.paid?.owed ? { stays: true } : {}),
53
145
  });
54
146
  }
55
- return verdict;
147
+ return { verdict, settling };
56
148
  });
57
149
  queue = asked.catch(() => undefined);
58
150
  return asked;
59
151
  };
152
+ /** Waits `ms`, or less: until the line's first leaves (`place.wake`) or the request's client goes. */
153
+ const nap = (place, ms, signal) => new Promise((resolve) => {
154
+ const done = () => {
155
+ clearTimeout(timer);
156
+ signal?.removeEventListener("abort", done);
157
+ if (place.wake === done)
158
+ place.wake = undefined;
159
+ resolve();
160
+ };
161
+ const timer = setTimeout(done, ms);
162
+ place.wake = done;
163
+ signal?.addEventListener("abort", done, { once: true });
164
+ });
165
+ /** Leaves the line; the next one asks at once (the room the first waited for may fit it too). */
166
+ const leave = (place) => {
167
+ const at = line.indexOf(place);
168
+ if (at < 0)
169
+ return;
170
+ line.splice(at, 1);
171
+ if (at === 0)
172
+ line[0]?.wake?.();
173
+ };
174
+ /** Why a waiter leaves now, if it does: its client went, the run stopped or its booking did (thrown), or the run parked
175
+ * (refused). */
176
+ const leaving = (request, signal) => {
177
+ if (signal?.aborted)
178
+ throw gone(signal);
179
+ const halted = request.halted?.();
180
+ if (halted)
181
+ throw halted;
182
+ return options.parked?.() ? "parked" : undefined;
183
+ };
184
+ /** Whether `request` is a paid call whose own session (paid.under) has a request in flight: one admitted here that the
185
+ * session's records do not show answered. */
186
+ const underOpen = async (request) => {
187
+ const under = request.paid?.under;
188
+ if (under === undefined)
189
+ return false;
190
+ const turns = [...admitted.values()].filter((flight) => flight.key === under).map((flight) => flight.turn);
191
+ if (turns.length === 0)
192
+ return false;
193
+ const answered = sessionSpendOf(await sessions.read(under)).answered;
194
+ return turns.some((turn) => !answered.has(turn));
195
+ };
196
+ /** A refusal as handed on: one that waits is the plain refusal it is to anyone not waiting. */
197
+ const plain = (verdict) => {
198
+ if (!(verdict && "refuse" in verdict && verdict.waits))
199
+ return verdict;
200
+ const { waits: _waits, ...refusal } = verdict;
201
+ return refusal;
202
+ };
203
+ return async (request) => {
204
+ // What ends its wait: its own client's going (a model request's), or the run's stop (any step's: a paid call's or a
205
+ // decision's has no client of its own here).
206
+ const signal = request.signal && options.stopped ? AbortSignal.any([request.signal, options.stopped]) : (request.signal ?? options.stopped);
207
+ // Every step joins the line as it comes, before its first ask, and asks only once it is first: steps that come together
208
+ // are asked in the order they came, so one behind a step that must wait never goes ahead of it. The first leaving
209
+ // (admitted, refused or gone) wakes the next at once. A paid call whose own session has a request in flight goes ahead
210
+ // of every step that is not one: a step ahead may wait on that request, which settles only once the call is done.
211
+ const place = request.paid?.under !== undefined && (await underOpen(request)) ? { under: true } : {};
212
+ const ahead = place.under ? line.findIndex((other) => !other.under) : -1;
213
+ if (ahead < 0)
214
+ line.push(place);
215
+ else
216
+ line.splice(ahead, 0, place);
217
+ try {
218
+ let pause = WAIT_POLL_FIRST_MS;
219
+ while (line[0] !== place) {
220
+ // Not first yet: it has no verdict of its own to be refused in, so a park reaches it as its first ask does.
221
+ await nap(place, pause, signal);
222
+ if (signal?.aborted)
223
+ throw gone(signal);
224
+ const halted = request.halted?.();
225
+ if (halted)
226
+ throw halted;
227
+ pause = Math.min(2 * pause, WAIT_POLL_MOST_MS);
228
+ }
229
+ pause = WAIT_POLL_FIRST_MS;
230
+ let quietSince = Date.now();
231
+ let waitedOn;
232
+ for (;;) {
233
+ const { verdict, settling } = await ask(request, signal);
234
+ if (!(verdict && "refuse" in verdict && verdict.waits))
235
+ return verdict;
236
+ // A step it waited on has settled since it last asked: the wait goes on, from the first pause again.
237
+ if (waitedOn && [...waitedOn].some((id) => !settling.has(id))) {
238
+ quietSince = Date.now();
239
+ pause = WAIT_POLL_FIRST_MS;
240
+ }
241
+ waitedOn = settling;
242
+ if (Date.now() - quietSince >= stallMs)
243
+ return plain(verdict);
244
+ // It waits first in line: only the first asks again.
245
+ do {
246
+ await nap(place, pause, signal);
247
+ if (leaving(request, signal) === "parked")
248
+ return plain(verdict);
249
+ pause = Math.min(2 * pause, WAIT_POLL_MOST_MS);
250
+ } while (line[0] !== place);
251
+ }
252
+ }
253
+ finally {
254
+ leave(place);
255
+ }
256
+ };
60
257
  }