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

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 (102) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +5 -0
  3. package/dist/errors.d.ts +7 -0
  4. package/dist/errors.js +10 -0
  5. package/dist/host/box.d.ts +0 -58
  6. package/dist/host/box.js +7 -0
  7. package/dist/host/index.d.ts +4 -10
  8. package/dist/host/index.js +2 -5
  9. package/dist/host/mcp-route.d.ts +3 -0
  10. package/dist/host/mcp-route.js +6 -2
  11. package/dist/host/proxy.d.ts +96 -5
  12. package/dist/host/proxy.js +518 -43
  13. package/dist/host/serial.js +2 -1
  14. package/dist/index.d.ts +5 -4
  15. package/dist/index.js +3 -2
  16. package/dist/kernel/cap/admit.d.ts +35 -0
  17. package/dist/kernel/cap/admit.js +186 -0
  18. package/dist/kernel/cap/errors.d.ts +20 -0
  19. package/dist/kernel/cap/errors.js +25 -0
  20. package/dist/kernel/cap/index.d.ts +14 -0
  21. package/dist/kernel/cap/index.js +15 -0
  22. package/dist/kernel/cap/ledger.d.ts +37 -0
  23. package/dist/kernel/cap/ledger.js +83 -0
  24. package/dist/kernel/cap/marks.d.ts +50 -0
  25. package/dist/kernel/cap/marks.js +28 -0
  26. package/dist/kernel/cap/park.d.ts +80 -0
  27. package/dist/kernel/cap/park.js +57 -0
  28. package/dist/kernel/cap/port.d.ts +21 -0
  29. package/dist/kernel/cap/port.js +95 -0
  30. package/dist/kernel/cap/price.d.ts +54 -0
  31. package/dist/kernel/cap/price.js +117 -0
  32. package/dist/kernel/cap/recover.d.ts +18 -0
  33. package/dist/kernel/cap/recover.js +71 -0
  34. package/dist/kernel/cap/rule.d.ts +55 -0
  35. package/dist/kernel/cap/rule.js +93 -0
  36. package/dist/kernel/cap/run-cap.d.ts +80 -0
  37. package/dist/kernel/cap/run-cap.js +132 -0
  38. package/dist/kernel/cap/steps.d.ts +36 -0
  39. package/dist/kernel/cap/steps.js +64 -0
  40. package/dist/kernel/cap/stopped.d.ts +17 -0
  41. package/dist/kernel/cap/stopped.js +34 -0
  42. package/dist/kernel/cap/types.d.ts +151 -0
  43. package/dist/kernel/cap/types.js +1 -0
  44. package/dist/kernel/cap/words.d.ts +39 -0
  45. package/dist/kernel/cap/words.js +75 -0
  46. package/dist/kernel/cap/wrap-up.d.ts +17 -0
  47. package/dist/kernel/cap/wrap-up.js +37 -0
  48. package/dist/kernel/drive.d.ts +0 -1
  49. package/dist/kernel/drive.js +9 -2
  50. package/dist/kernel/index.d.ts +1 -0
  51. package/dist/kernel/index.js +1 -0
  52. package/dist/kernel/registry/background.d.ts +12 -0
  53. package/dist/kernel/registry/background.js +342 -0
  54. package/dist/kernel/registry/bash.d.ts +3 -0
  55. package/dist/kernel/registry/bash.js +23 -0
  56. package/dist/kernel/registry/browser.d.ts +11 -0
  57. package/dist/kernel/registry/browser.js +14 -0
  58. package/dist/kernel/registry/defs.d.ts +42 -0
  59. package/dist/kernel/registry/defs.js +153 -0
  60. package/dist/kernel/registry/desktop.d.ts +11 -0
  61. package/dist/kernel/registry/desktop.js +90 -0
  62. package/dist/kernel/registry/gate.d.ts +20 -0
  63. package/dist/kernel/registry/gate.js +32 -0
  64. package/dist/kernel/registry/handoff.d.ts +11 -0
  65. package/dist/kernel/registry/handoff.js +51 -0
  66. package/dist/kernel/registry/hands.d.ts +280 -0
  67. package/dist/kernel/registry/hands.js +28 -0
  68. package/dist/kernel/registry/index.d.ts +17 -0
  69. package/dist/kernel/registry/index.js +14 -0
  70. package/dist/kernel/registry/limits.d.ts +27 -0
  71. package/dist/kernel/registry/limits.js +29 -0
  72. package/dist/kernel/registry/phone.d.ts +15 -0
  73. package/dist/kernel/registry/phone.js +135 -0
  74. package/dist/kernel/registry/registry.d.ts +22 -0
  75. package/dist/kernel/registry/registry.js +75 -0
  76. package/dist/kernel/types.d.ts +0 -7
  77. package/dist/process/builtins.js +1 -1
  78. package/dist/process/index.d.ts +1 -0
  79. package/dist/process/index.js +1 -0
  80. package/dist/process/journal.js +1 -1
  81. package/dist/process/recovery.js +1 -1
  82. package/dist/process/resume.d.ts +20 -0
  83. package/dist/process/resume.js +16 -0
  84. package/dist/process/tail.js +1 -1
  85. package/dist/process/tools.d.ts +8 -1
  86. package/dist/process/tools.js +20 -3
  87. package/dist/process/zod.js +1 -1
  88. package/dist/run-booking.d.ts +9 -0
  89. package/dist/run-booking.js +50 -0
  90. package/dist/runner.d.ts +91 -17
  91. package/dist/runner.js +132 -41
  92. package/dist/testing.d.ts +79 -12
  93. package/dist/testing.js +106 -13
  94. package/dist/types.d.ts +204 -10
  95. package/package.json +8 -4
  96. package/vendor/durable-harness/UPSTREAM.json +0 -9
  97. package/dist/host/box-slot.d.ts +0 -26
  98. package/dist/host/box-slot.js +0 -112
  99. package/dist/host/egress-proxy.d.ts +0 -45
  100. package/dist/host/egress-proxy.js +0 -416
  101. package/dist/host/egress-table.d.ts +0 -24
  102. package/dist/host/egress-table.js +0 -165
@@ -0,0 +1,75 @@
1
+ // The kernel's one registry of host tools: the model-visible definitions (defs.ts), each with its executor. read,
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
+ // here); the kernel bounds bash and runs the five background tools itself. A computer of a kind past files and a shell
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.
8
+ import { BACKGROUND_EXECUTORS, NEEDS_A_COMPUTER, NO_SHELL } from "./background.js";
9
+ import { boundedBash } from "./bash.js";
10
+ import { CAPABILITY_KINDS, capabilityToolDefs, hostToolDefs } from "./defs.js";
11
+ import { DESKTOP_EXECUTORS, DESKTOP_TOOL_DEFS } from "./desktop.js";
12
+ import { answerOf, needsKindWords } from "./hands.js";
13
+ import { BACKGROUND_TOOLS } from "./limits.js";
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
18
+ * tools this run's computer does not offer (its capabilities lack them: an iPhone's tree and keys, say), not listed to
19
+ * the model; one called anyway runs, and its port's absence answers in words. */
20
+ export function createRegistry(options) {
21
+ const { shell, executors } = options;
22
+ const kinds = CAPABILITY_KINDS.filter((kind) => options.kinds?.includes(kind));
23
+ const own = hostToolDefs({ maxExecS: options.maxExecS, shell });
24
+ const runs = new Map();
25
+ for (const def of own) {
26
+ const run = def.name === "bash"
27
+ ? executors.bash && boundedBash(executors.bash, shell === "computer")
28
+ : BACKGROUND_EXECUTORS[def.name] ?? executors[def.name];
29
+ if (!run)
30
+ throw new Error(`the registry has no executor for ${def.name}, a tool the model sees: the host gives read, write, edit and bash's own run`);
31
+ runs.set(def.name, run);
32
+ }
33
+ const defs = [...own];
34
+ for (const kind of kinds) {
35
+ for (const def of capabilityToolDefs(kind, options.browserTools ? { browserTools: options.browserTools } : {})) {
36
+ // A tool two kinds share (the hand-over) is listed once, as the first kind gives it.
37
+ if (runs.has(def.name))
38
+ continue;
39
+ const run = kind === "desktop" ? DESKTOP_EXECUTORS[def.name] : kind === "phone" ? PHONE_EXECUTORS[def.name] : executors.browser?.[def.name];
40
+ 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`);
42
+ runs.set(def.name, run);
43
+ if (!options.without?.includes(def.name))
44
+ defs.push(def);
45
+ }
46
+ }
47
+ // Every kind's tool by name, the run's or not, for the refusal of one it does not have.
48
+ const kindOf = new Map([
49
+ ...DESKTOP_TOOL_DEFS.map((def) => [def.name, "desktop"]),
50
+ ...PHONE_TOOL_DEFS.map((def) => [def.name, "phone"]),
51
+ ...(options.browserTools ?? []).map((contract) => [contract.name, "browser"]),
52
+ ]);
53
+ const byName = new Map(defs.map((def) => [def.name, def]));
54
+ return {
55
+ list: () => defs,
56
+ get: (name) => byName.get(name) ?? defs.find((def) => def.gateName === name),
57
+ invoke(name, args, call) {
58
+ const run = runs.get(name);
59
+ if (run)
60
+ return run(args, call);
61
+ return answerOf(call, async () => {
62
+ if (shell !== "computer" && BACKGROUND_TOOLS.includes(name)) {
63
+ throw new Error(NEEDS_A_COMPUTER);
64
+ }
65
+ // No shell at all: bash is not listed, and a call of it anyway says how to get one.
66
+ if (shell === "none" && name === "bash")
67
+ throw new Error(NO_SHELL);
68
+ const kind = kindOf.get(name);
69
+ if (kind)
70
+ throw new Error(needsKindWords(name, kind));
71
+ throw new Error(`there is no host tool ${name} in this run`);
72
+ });
73
+ },
74
+ };
75
+ }
@@ -60,9 +60,6 @@ export interface EffectOptions {
60
60
  replay: ReplayPolicy;
61
61
  input: unknown;
62
62
  placed?: string[];
63
- /** Where the effect must run and what it needs; recorded with the intent, not acted on by this kernel. */
64
- requires?: string;
65
- needs?: string[];
66
63
  }
67
64
  export interface EffectIO {
68
65
  signal: AbortSignal;
@@ -80,7 +77,6 @@ export interface KernelWorld {
80
77
  export interface DriveContext {
81
78
  readonly runId: string;
82
79
  readonly world: KernelWorld;
83
- readonly config: unknown;
84
80
  state(): SessionState;
85
81
  effect<T>(key: string, options: EffectOptions, fn: (io: EffectIO) => Promise<T>): Promise<T>;
86
82
  isMemoized(key: string): boolean;
@@ -108,9 +104,6 @@ export interface HostTool<Input = any> {
108
104
  description: string;
109
105
  inputSchema: object;
110
106
  replay: ReplayPolicy;
111
- /** Where the tool must run, and what it needs: passed to the effect's intent. */
112
- requires?: string;
113
- needs?: string[];
114
107
  /** Its answer: the text, or the text with the images it shows. Recorded as the call's outcome, so a call answered
115
108
  * from the record answers with the same images. */
116
109
  execute(input: Input, io: HostToolIO): Promise<string | ToolOutput>;
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-process/src/builtins.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, imports rewritten for AgentRun; patches: 001-begin-reservation, 002-message-prefix, 003-comments-name-this-host
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  import { EffectFailure, EffectInterrupted, Fatal, hostToolIO } from '../kernel/index.js';
5
5
  import { clip, failureText, toolKey } from './tools.js';
6
6
  /**
@@ -7,3 +7,4 @@ export * from "./inbox.js";
7
7
  export * from "./tail.js";
8
8
  export * from "./zod.js";
9
9
  export * from "./settle.js";
10
+ export * from "./resume.js";
@@ -9,3 +9,4 @@ export * from "./inbox.js";
9
9
  export * from "./tail.js";
10
10
  export * from "./zod.js";
11
11
  export * from "./settle.js";
12
+ export * from "./resume.js";
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-process/src/journal.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, imports rewritten for AgentRun; patches: 002-message-prefix, 004-comments-name-the-session-writer
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { BLOB_PIECE_CHARS, blobStreamName, Fatal, readBlobs, Restart, sha256Hex, writeBlob } from '../kernel/index.js';
6
6
  import { JOURNAL, journalBatches, journalKey, journalRecords, TRANSCRIPT, } from './records.js';
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-process/src/recovery.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, imports rewritten for AgentRun; patches: 003-comments-name-this-host, 009-recovery-system-note, 010-recovery-note-statuses-only
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  import { pendingSubmissions } from '../kernel/index.js';
5
5
  import { openTurn } from './records.js';
6
6
  export { openTurn };
@@ -0,0 +1,20 @@
1
+ import type { DriveContext } from '../kernel/index.js';
2
+ import { type ToolBridge } from './tools.js';
3
+ /** A tool use the CLI's transcript left with no result: its id, the host tool it calls and its input. */
4
+ export interface DanglingCall {
5
+ callId: string;
6
+ tool: string;
7
+ args: unknown;
8
+ }
9
+ /** A call's result, as it is settled into the CLI's transcript: its text, and whether it is an error. */
10
+ export interface CallOutcome {
11
+ text: string;
12
+ isError: boolean;
13
+ }
14
+ /** The dangling calls that never reached their intent: no effect of theirs in the drive's records. */
15
+ export declare function unstartedCalls(ctx: DriveContext, dangling: readonly DanglingCall[]): DanglingCall[];
16
+ /**
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
+ */
20
+ export declare function resumeUnstartedCalls(ctx: DriveContext, bridge: ToolBridge, dangling: readonly DanglingCall[], settle: (call: DanglingCall, outcome: CallOutcome) => Promise<void>): Promise<void>;
@@ -0,0 +1,16 @@
1
+ import { toolKey } from './tools.js';
2
+ /** The dangling calls that never reached their intent: no effect of theirs in the drive's records. */
3
+ export function unstartedCalls(ctx, dangling) {
4
+ const effects = ctx.state().effects;
5
+ return dangling.filter((call) => !effects.has(toolKey(call.callId)));
6
+ }
7
+ /**
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.
10
+ */
11
+ export async function resumeUnstartedCalls(ctx, bridge, dangling, settle) {
12
+ for (const call of unstartedCalls(ctx, dangling)) {
13
+ const result = await bridge.call(call.tool, call.args, call.callId);
14
+ await settle(call, { text: result.text, isError: result.isError });
15
+ }
16
+ }
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-process/src/tail.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, patches: 002-message-prefix
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
5
5
  /**
6
6
  * A line-complete tail of an append-only file (a JSONL transcript, a
@@ -1,5 +1,5 @@
1
1
  import { type DriveContext, type EffectError, type HostTool, type ReplayPolicy } from '../kernel/index.js';
2
- import { type ToolImage } from '../types.js';
2
+ import { type GateAnswer, type GateCall, 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).
@@ -45,6 +45,13 @@ export interface BridgedTool {
45
45
  call(args: unknown, callId: string, signal?: AbortSignal): Promise<ToolResult>;
46
46
  }
47
47
  export interface ToolBridgeOptions {
48
+ /**
49
+ * The host's gate (SessionIO.gate), asked about a call the log has not finished before anything of it: before
50
+ * `beforeNever` and before its intent. "allow" runs it; a deny is the call's error result in the host's words,
51
+ * nothing written and nothing run; a park holds the call, nothing written, until the drive's (or the harness's)
52
+ * signal is aborted, and then rejects.
53
+ */
54
+ gate?: (call: GateCall) => Promise<GateAnswer>;
48
55
  /**
49
56
  * Runs before a `replay: 'never'` call that the log has not finished:
50
57
  * the place for `journal.flush()`, so the harness's record of the call is
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-process/src/tools.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, imports rewritten for AgentRun; patches: 002-message-prefix, 003-comments-name-this-host, 008-tool-images, 011-result-bound
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  import { EffectFailure, hostToolIO } from '../kernel/index.js';
5
5
  import { HOST_RESULT_MAX_CHARS } from '../types.js';
6
6
  /** A promise-chain mutex. */
@@ -14,6 +14,16 @@ export class Mutex {
14
14
  }
15
15
  /** The memo key of a tool call. */
16
16
  export const toolKey = (callId) => `tool:${callId}`;
17
+ /** A call the gate parked: held, never answered here, until `signal` is aborted (the run parked and this process lets
18
+ * go of it); then it rejects, so the harness is never handed a result for it. */
19
+ function parkedUntilAborted(signal, tool) {
20
+ return new Promise((_, reject) => {
21
+ const parked = () => reject(new Error(`${tool} was parked: the run waits for a person's answer`));
22
+ if (signal.aborted)
23
+ return parked();
24
+ signal.addEventListener('abort', parked, { once: true });
25
+ });
26
+ }
17
27
  /**
18
28
  * Build the bridge for one drive. The calls' effects are this drive's: build
19
29
  * a new bridge per `drive(ctx)`.
@@ -33,6 +43,15 @@ export function toolBridge(ctx, tools, options = {}) {
33
43
  throw new TypeError(`agentrun-kernel: a call to ${tool.name} has no call id; derive a stable one`);
34
44
  const key = toolKey(callId);
35
45
  const fresh = !ctx.isMemoized(key);
46
+ // The gate first: before the flush and the intent, so a refused or parked call leaves nothing in the log.
47
+ 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
+ }
54
+ }
36
55
  if (fresh && tool.replay === 'never')
37
56
  await options.beforeNever?.({ name: tool.name, callId, args });
38
57
  if (fresh && live)
@@ -42,8 +61,6 @@ export function toolBridge(ctx, tools, options = {}) {
42
61
  name: `tool.${tool.name}`,
43
62
  replay: tool.replay,
44
63
  input: args,
45
- ...(tool.requires ? { requires: tool.requires } : {}),
46
- ...(tool.needs?.length ? { needs: tool.needs } : {}),
47
64
  }, (io) => tool.execute(args, hostToolIO(io, ctx, { signal: signal ? AbortSignal.any([signal, io.signal]) : io.signal })));
48
65
  // A tool answers in text, or in text with images (a screenshot): the images come back as recorded.
49
66
  const { text: whole, images } = typeof output === 'object' && output !== null ? output : { text: String(output), images: undefined };
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-process/src/zod.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, patches: 005-comments-name-the-agent-sdk
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  /**
5
5
  * JSON Schema to zod, for harness SDKs whose tool APIs take zod (the Claude
6
6
  * Agent SDK's in-process MCP tools, OpenCode's plugin tools). `HostTool`s carry
@@ -0,0 +1,9 @@
1
+ import { type BeforeRequest } from "./runner.js";
2
+ import type { SessionRecord } from "./types.js";
3
+ /** The run's sessions: every key it has, and each one's records. */
4
+ export interface RunSessions {
5
+ keys(): readonly string[] | Promise<readonly string[]>;
6
+ read(key: string): Promise<SessionRecord[]>;
7
+ }
8
+ /** `before`, asked about each request with the run's totals over `sessions` in place of its session's own. */
9
+ export declare function runBooking(sessions: RunSessions, before: BeforeRequest): BeforeRequest;
@@ -0,0 +1,50 @@
1
+ // The run's one booking. A run's model requests are booked per session (modelPortFor: each CLI session key, and pi's own
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
+ // holds, never on its own alone. runBooking wraps the host's beforeRequest (the cap's beforeRequestOf) so that each
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.
9
+ // Admissions run one at a time across the run's sessions. The priced tools' charges and holds are not here: they are the
10
+ // host's spentUsd and heldUsd hooks (beforeRequestOf), read beside these.
11
+ import { sessionSpendOf } from "./runner.js";
12
+ const idOf = (key, turn) => `${key}\u0000${turn}`;
13
+ /** `before`, asked about each request with the run's totals over `sessions` in place of its session's own. */
14
+ export function runBooking(sessions, before) {
15
+ /** Admitted here and not yet recorded, by session and turn. One whose record never lands (its write refused, its
16
+ * process gone) stays held: the run's spend is never under-counted. */
17
+ const admitted = new Map();
18
+ let queue = Promise.resolve();
19
+ return (request) => {
20
+ const asked = queue.then(async () => {
21
+ let spentUsd = 0;
22
+ const recorded = new Set();
23
+ for (const key of await sessions.keys()) {
24
+ const spend = sessionSpendOf(await sessions.read(key));
25
+ spentUsd = spentUsd === null || spend.spentUsd === null ? null : spentUsd + spend.spentUsd;
26
+ for (const turn of spend.turns)
27
+ recorded.add(idOf(key, turn));
28
+ }
29
+ for (const id of [...admitted.keys()])
30
+ if (recorded.has(id))
31
+ admitted.delete(id);
32
+ const verdict = await before({ ...request, spentUsd, inFlight: [...admitted.values()] });
33
+ if (!(verdict && "refuse" in verdict)) {
34
+ const holdUsd = verdict && "holdUsd" in verdict ? verdict.holdUsd : undefined;
35
+ const outputTokensMax = verdict && "outputTokensMax" in verdict ? verdict.outputTokensMax : request.outputTokensAsked;
36
+ admitted.set(idOf(request.key, request.turn), {
37
+ turn: request.turn,
38
+ model: request.model,
39
+ ...(request.inputTokensMax === undefined ? {} : { inputTokensMax: request.inputTokensMax }),
40
+ ...(outputTokensMax === undefined ? {} : { outputTokensMax }),
41
+ ...(typeof holdUsd === "number" ? { holdUsd } : {}),
42
+ ...(request.host === undefined ? {} : { host: request.host }),
43
+ });
44
+ }
45
+ return verdict;
46
+ });
47
+ queue = asked.catch(() => undefined);
48
+ return asked;
49
+ };
50
+ }
package/dist/runner.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { AgentAdapter, HarnessEvent, HostTool, ModelPort, ModelUsage, NodeRequest, SessionRecord, SessionStore, SessionWriter } from "./types.js";
1
+ import { type Ended } from "./booking.js";
2
+ import type { AgentAdapter, HarnessEvent, HostTool, JsonValue, ModelPort, ModelUsage, NodeRequest, NoteRequest, SessionRecord, SessionStore, SessionWriter } from "./types.js";
2
3
  /** Exactly the interpreter's `runNode`, plus `stop`: a pause of every node it is running. With `drainMs`, each node
3
4
  * starts no new turn, call or paid request, its calls in flight run on until their outcomes are recorded (for at most
4
5
  * `drainMs`, on an adapter that can drain), and then it stops, failing `aborted`; its session resumes from its records
@@ -21,7 +22,7 @@ export declare const RUNNER_RECORDS: {
21
22
  readonly accepted: "runner.accepted";
22
23
  };
23
24
  /** What the host is asked before each paid request. A `refuse` ends the node, final. A `holdUsd` (a finite amount, 0
24
- * or more) is what the host holds for the request, its cap's worst case: written on the request's record before it
25
+ * or more) is what the host holds for the request, what its cap admitted it at: written on the request's record before it
25
26
  * leaves, it is what the request counts at in the spend the host is shown when the request's own cost never comes in
26
27
  * (a response cut short, booked at an unknown cost, or a request a crash cut off, read by a later process). Without
27
28
  * one, such a request leaves the spend unknown. The cost booked for the request is unknown either way. */
@@ -44,31 +45,71 @@ export type BeforeRequest = (request: {
44
45
  * them from its body (ModelRequest). */
45
46
  outputTokensAsked?: number;
46
47
  outputTokensLeast?: number;
48
+ /** What it charges beside its tokens (ModelRequest.feeUsd), held with them. */
49
+ feeUsd?: number;
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. */
52
+ paid?: {
53
+ name: string;
54
+ basis: string;
55
+ call?: string;
56
+ charged_by?: string;
57
+ };
58
+ /** A side call (ModelRequest.side): on another model than the session's (a client's), or the host's own (`host`). */
59
+ side?: true;
60
+ /** It carries the host's note (ModelRequest.noted), and its input measured without it (`inputTokensMaxWithoutNote`):
61
+ * a host that admits it only without the note says so (Admission.withoutNote). */
62
+ noted?: true;
63
+ inputTokensMaxWithoutNote?: number;
64
+ /** The label of a request the host sent beside the harness's own (ModelRequest.host): a learned workflow's model node,
65
+ * under the same check as the harness's own. */
66
+ host?: string;
47
67
  /** This session's paid requests admitted and not yet answered (in this process), oldest first, each with its own
48
- * `inputTokensMax` and the output limit it was admitted with (`outputTokensMax`): a budget holds each one's
49
- * worst case until it answers, since `spentUsd` counts answered requests only. Requests are admitted one at a time,
50
- * so each check sees every request admitted before it. */
68
+ * `inputTokensMax`, the output limit it was admitted with (`outputTokensMax`) and what its host held for it
69
+ * (`holdUsd`): a budget holds each one until it answers, since `spentUsd` counts answered requests only. Requests are
70
+ * admitted one at a time, so each check sees every request admitted before it. */
51
71
  inFlight: readonly InFlight[];
52
- }) => void | {
72
+ }) => void | Refusal | Admission | Promise<void | Refusal | Admission>;
73
+ /** A host's refusal of a request: its words, and, from a spend cap, whether no raise could send it (`forGood`) and, for
74
+ * one a raise could, its figures (what the cap counted as taken, what the request needs at the least, the least cap that
75
+ * sends it): what the run's end is decided from (the kernel cap's parkOf). */
76
+ export type Refusal = {
53
77
  refuse: string;
54
- } | Admission | Promise<void | {
55
- refuse: string;
56
- } | Admission>;
57
- /** A request admitted and not yet answered, as a budget holds it. */
78
+ forGood?: boolean;
79
+ figures?: {
80
+ spentUsd: number;
81
+ needsUsd: number;
82
+ leastCapUsd: number;
83
+ boundUsd?: number;
84
+ };
85
+ };
86
+ /** A request admitted and not yet answered, as a budget holds it: at what its host held for it (`holdUsd`), when it held
87
+ * one. */
58
88
  export type InFlight = {
59
89
  turn: number;
60
90
  model: string;
61
91
  inputTokensMax?: number;
62
92
  outputTokensMax?: number;
93
+ holdUsd?: number;
94
+ host?: string;
63
95
  };
64
96
  /** A host's admission: what it holds for the request (`holdUsd`), and the most output tokens, thinking included, it may
65
97
  * be sent with (`outputTokensMax`, what is left of a cap can buy), which its ticket carries to the model proxy. A
66
98
  * request its client stops part way (`ModelUsage.stoppedAfterBytes`), its cost unknown, counts at `stoppedUsd` of what
67
- * streamed, in tokens (one a byte), never more than `holdUsd`; without it, at `holdUsd`. */
99
+ * streamed, in tokens (one a byte), never more than `holdUsd`; without it, at `holdUsd`. `withoutNote`: a request that
100
+ * carries its host's note is admitted only as it was without it (the note's bytes did not fit): it goes without it.
101
+ * `note`: the host's record of the note this request carries, written on the request's `runner.turn` record once it
102
+ * ends, beside how it was booked, so a later process reads whether the note reached an answer. `boundUsd`: the most a
103
+ * cache miss adds to `holdUsd`, written beside it, so a request that never answers counts for the cap at both. */
68
104
  export type Admission = {
69
105
  holdUsd?: number;
106
+ boundUsd?: number;
70
107
  outputTokensMax?: number;
71
108
  stoppedUsd?: (streamedTokens: number) => number;
109
+ withoutNote?: true;
110
+ note?: {
111
+ [key: string]: JsonValue;
112
+ };
72
113
  };
73
114
  export interface HarnessRunnerOptions {
74
115
  /** The run's store, through whoever owns it. */
@@ -88,8 +129,8 @@ export interface HarnessRunnerOptions {
88
129
  signal?: AbortSignal;
89
130
  /** The host's check before each paid request: its budget, `max_cost_usd`. */
90
131
  beforeRequest?: BeforeRequest;
91
- /** Every event, with the node it belongs to. */
92
- onEvent?: (event: HarnessEvent) => void;
132
+ /** Every event, with the node it belongs to. A `request_start` handler's promise is awaited before the request leaves. */
133
+ onEvent?: (event: HarnessEvent) => void | Promise<void>;
93
134
  /** The private directory of a session, when the adapter needs one. */
94
135
  sessionDir?: (key: string) => string;
95
136
  }
@@ -97,15 +138,19 @@ export interface HarnessRunnerOptions {
97
138
  * turn limit counts paid requests only, so without this bound a harness whose turns never reach its model (a cached or
98
139
  * refused answer, a misconfigured model) would be sent turns forever, on microtasks no timer can interrupt. */
99
140
  export declare const NO_PROGRESS_TURNS = 3;
100
- /** What a paid request tells a host, beside its session's key and label. */
141
+ /** What a paid request tells a host, beside its session's key and label. A `request_end` carries how its path saw the
142
+ * request end (`ended`, booking.ts), when the path said. */
101
143
  export type ModelPortEvent = {
102
144
  type: "request_start";
103
145
  turn: number;
104
146
  model: string;
147
+ host?: string;
105
148
  } | {
106
149
  type: "request_end";
107
150
  turn: number;
108
151
  usage: ModelUsage;
152
+ host?: string;
153
+ ended?: Ended;
109
154
  };
110
155
  export interface ModelPortOptions {
111
156
  /** The session's key: what `beforeRequest` and every event carry. */
@@ -117,20 +162,28 @@ export interface ModelPortOptions {
117
162
  budgetUsd?: number;
118
163
  /** Asked before every paid request; a `refuse` ends the attempt. */
119
164
  beforeRequest?: BeforeRequest;
165
+ /** Every event. For `request_start` its promise is awaited before the request leaves, and a rejection refuses it: a
166
+ * host's start mark, made durable there, is never behind a request that was sent. */
120
167
  onEvent?: (event: ModelPortEvent & {
121
168
  key: string;
122
169
  label: string;
123
170
  executionPath?: string;
124
- }) => void;
171
+ }) => void | Promise<void>;
125
172
  /** The session's records, as already read (default: read from the writer). */
126
173
  records?: readonly SessionRecord[];
127
174
  /** How a record is written (default: the writer's append, which a newer open fences). */
128
175
  append?: (records: SessionRecord[]) => Promise<void>;
129
- /** The attempt has stopped: the error a new paid request is refused with. */
130
- stopped?: () => Error | undefined;
176
+ /** The attempt has stopped: the error a new paid request is refused with. Told the request's host label, for a host
177
+ * that admits its own requests (ModelRequest.host) while the harness's own are held. A `TurnParked` refuses new
178
+ * requests but is no stop of the booking: a paid request whose cost can't be recorded meanwhile still stops it. */
179
+ stopped?: (request: {
180
+ host?: string;
181
+ }) => Error | undefined;
131
182
  /** A pause is draining the attempt: the error a new paid request is refused with, while the attempt itself goes on. A
132
183
  * request is refused if the pause began before its record is written, even while the host's check of it was running. */
133
184
  draining?: () => Error | undefined;
185
+ /** A note the host has for the session's next main-model request, taken by the call (ModelPort.note). */
186
+ note?: (model: string, request?: NoteRequest) => string | undefined;
134
187
  /** The port ends the attempt (the turn limit, the host's refusal, a cost it could not record): the error it throws. */
135
188
  stop?: (reason: "turn_limit" | "refused" | "model_error", message?: string) => Error;
136
189
  }
@@ -151,4 +204,25 @@ export interface ModelBooking {
151
204
  * records (`runner.request` before a request leaves, `runner.turn` with its cost when it answers), the same turn limit
152
205
  * and `beforeRequest`, the same events. `createHarnessRunner` is built on it. */
153
206
  export declare function modelPortFor(writer: SessionWriter, options: ModelPortOptions): Promise<ModelBooking>;
207
+ /** What a session's runner records say: the turn of each paid request that left, in order (`turns`), what its host held
208
+ * for each (`held`), the label of each the host sent beside the harness's own (`hosts`), which were answered, and the
209
+ * session's spend (null: unknown). A turn is a paid request that left: counted from the records written before each one
210
+ * left, so a request a crash cut off (or one still in flight, read from another process or session) counts at the
211
+ * figure its host held for it, and leaves the spend unknown when there is none. */
212
+ export declare function sessionSpendOf(records: readonly SessionRecord[]): {
213
+ turns: number[];
214
+ held: Map<number, number>;
215
+ bounds: Map<number, number>;
216
+ hosts: Map<number, string>;
217
+ answered: Set<number>;
218
+ spentUsd: number | null;
219
+ cost: SessionCost;
220
+ };
221
+ /** A session's cost as a person is shown it: `usd` when every paid request has its own figure, else null with the known
222
+ * part so far (`soFarUsd`) and how many have none (`unpriced`). */
223
+ export type SessionCost = {
224
+ usd: number | null;
225
+ soFarUsd: number;
226
+ unpriced: number;
227
+ };
154
228
  export declare function createHarnessRunner(adapter: AgentAdapter, options: HarnessRunnerOptions): HarnessRunner;