@parcha/agentrun-kernel 0.1.0-beta.30 → 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 +68 -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 +5 -9
  8. package/dist/host/index.js +2 -4
  9. package/dist/host/mcp-route.d.ts +14 -0
  10. package/dist/host/mcp-route.js +125 -0
  11. package/dist/host/proxy.d.ts +96 -2
  12. package/dist/host/proxy.js +533 -41
  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 +235 -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
package/dist/testing.js CHANGED
@@ -4,7 +4,12 @@
4
4
  // answered interrupted, never run again.
5
5
  import { SessionFenced } from "./errors.js";
6
6
  import { abortedOutcome, SessionHalt } from "./kernel/halt.js";
7
+ import { startModelProxy } from "./host/proxy.js";
8
+ import { randomBytes } from "node:crypto";
7
9
  export { SCHEMA_CHECK_CASES } from "./schema-check-cases.js";
10
+ /** The model proxy's own parts, for tests of a provider policy and of the proxy: the host API (./host) keeps only what a
11
+ * harness runs. */
12
+ export { inputTokensMaxOf, matchRoute, parseStrict, reportedCostOf } from "./host/proxy.js";
8
13
  /** A session store in memory: what one run's store holds, across the processes a test plays. Each `open` of a key
9
14
  * counts one more holder at once, and a writer appends only while its count is the newest. */
10
15
  export function memorySessionStore() {
@@ -24,24 +29,27 @@ export function memorySessionStore() {
24
29
  throw new SessionFenced(key);
25
30
  sessions.set(key, [...(sessions.get(key) ?? []), ...structuredClone(records)]);
26
31
  },
32
+ // Memory has no box to lose: every append is as durable as it gets.
33
+ sync: async () => { },
27
34
  };
28
35
  },
29
36
  keys: () => [...sessions.keys()],
30
37
  };
31
38
  }
32
- export const FAUX_RECORDS = { request: "faux.request", user: "faux.user", turn: "faux.turn", turnEnd: "faux.turn_end", call: "faux.call", result: "faux.result" };
39
+ /** `note`: a note its host had for the request (ModelPort.note, the spend cap's wrap-up), as a real adapter's model proxy
40
+ * would add it to the body: filed with its text, for a test to see. */
41
+ export const FAUX_RECORDS = { request: "faux.request", user: "faux.user", turn: "faux.turn", turnEnd: "faux.turn_end", call: "faux.call", result: "faux.result", note: "faux.note" };
33
42
  export function fauxAdapter(options) {
34
43
  const stats = { requests: 0, calls: [], opened: [], closed: [] };
35
44
  const adapter = {
36
45
  id: "faux",
37
- version: "0.0.0",
38
46
  get requests() { return stats.requests; },
39
47
  get calls() { return stats.calls; },
40
48
  get opened() { return stats.opened; },
41
49
  get closed() { return stats.closed; },
42
- capabilities: () => ({ fork: options.fork ?? false }),
50
+ capabilities: () => ({}),
43
51
  check: (spec) => [
44
- ...(spec.context === "fork" && !options.fork ? ["the faux harness cannot fork a session"] : []),
52
+ ...(spec.context === "fork" ? ["the faux harness cannot fork a session"] : []),
45
53
  ...(options.refuse?.(spec) ?? []),
46
54
  ],
47
55
  async open(spec, io) {
@@ -49,8 +57,16 @@ export function fauxAdapter(options) {
49
57
  await new Promise((resolve) => setTimeout(resolve, options.openDelayMs));
50
58
  const script = options.script(spec);
51
59
  const records = await io.writer.read();
60
+ // The session's model proxy, when the faux harness is given one: up for the session's life, its key never used here.
61
+ const proxy = options.proxy ? await startModelProxy({ ...options.proxy.options, hooks: io.models }, randomBytes(32).toString("base64url")) : undefined;
62
+ io.signal.addEventListener("abort", () => void proxy?.close(), { once: true });
52
63
  const append = (kind, data) => io.writer.append([{ kind, data }]);
53
- let cursor = records.filter((r) => r.kind === FAUX_RECORDS.request).length;
64
+ // The script's place: one past its last request's (each faux.request keeps its action's index), never the count of
65
+ // them, since an action refused with `onRefused: "next"` is skipped with no record.
66
+ let cursor = records.reduce((next, r) => {
67
+ const index = r.kind === FAUX_RECORDS.request ? r.data?.index : undefined;
68
+ return typeof index === "number" && index + 1 > next ? index + 1 : next;
69
+ }, 0);
54
70
  const turnsStarted = records.filter((r) => r.kind === FAUX_RECORDS.turn).length;
55
71
  const turnsEnded = records.filter((r) => r.kind === FAUX_RECORDS.turnEnd).length;
56
72
  let state = turnsStarted === 0 ? "new" : turnsStarted > turnsEnded ? "open_turn" : "idle";
@@ -79,6 +95,14 @@ export function fauxAdapter(options) {
79
95
  io.onEvent({ type: "turn_end", status });
80
96
  ending?.resolve({ status, ...(error === undefined ? {} : { error }) });
81
97
  };
98
+ const untilExists = async (file, signal) => {
99
+ const { existsSync } = await import("node:fs");
100
+ while (!existsSync(file)) {
101
+ if (signal.aborted)
102
+ throw signal.reason;
103
+ await new Promise((resolve) => setTimeout(resolve, 20));
104
+ }
105
+ };
82
106
  const hang = (signal) => new Promise((_, reject) => {
83
107
  if (signal.aborted)
84
108
  reject(signal.reason);
@@ -100,7 +124,41 @@ export function fauxAdapter(options) {
100
124
  return await hang(signal);
101
125
  }
102
126
  // Measured as a real adapter's proxy measures its body: the prompt's UTF-8 bytes, with nothing a provider adds.
103
- const ticket = await io.models.beforeRequest({ model: "faux", inputTokensMax: Buffer.byteLength(JSON.stringify({ system: spec.system, user: prompt }), "utf8") });
127
+ const measured = "inputTokensMax" in action && typeof action.inputTokensMax === "number" ? action.inputTokensMax : Buffer.byteLength(JSON.stringify({ system: spec.system, user: prompt }), "utf8");
128
+ // On the session's model: the proxy's, when it has one (the host's own requests go there on that model too).
129
+ const own = options.proxy?.options.model ?? "faux";
130
+ // A note its host has for this request, taken before it is measured, as the model proxy takes it: its bytes count
131
+ // in what the request is admitted at, and it is filed as sent once the request is admitted carrying it.
132
+ const note = io.models.note?.(own, { inputTokensMax: measured, ...("outputTokensAsked" in action && typeof action.outputTokensAsked === "number" ? { outputTokensAsked: action.outputTokensAsked } : {}), ...("outputTokensLeast" in action && typeof action.outputTokensLeast === "number" ? { outputTokensLeast: action.outputTokensLeast } : {}) });
133
+ if ("sideAfterNote" in action && action.sideAfterNote) {
134
+ const side = await io.models.beforeRequest({ model: "faux-small", side: true, inputTokensMax: 100 });
135
+ await io.models.afterRequest({ input: 10, output: 5, usd: action.sideAfterNote.usd }, side || undefined);
136
+ }
137
+ if ("sideFirst" in action && action.sideFirst) {
138
+ const { usd, say } = action.sideFirst;
139
+ const side = await io.models.beforeRequest({ model: "faux-small", side: true, inputTokensMax: 100 });
140
+ const paySide = () => io.models.afterRequest({ input: 10, output: 5, usd }, side || undefined);
141
+ if ("bookWhen" in action && typeof action.bookWhen === "string")
142
+ void untilExists(action.bookWhen, signal).then(paySide).catch(() => undefined);
143
+ else
144
+ await paySide();
145
+ io.onEvent({ type: "text", delta: say });
146
+ }
147
+ // The output it asks for at most (a CLI's max_tokens), as a real adapter's proxy reads it from the body.
148
+ const asked = { ...("outputTokensAsked" in action && typeof action.outputTokensAsked === "number" ? { outputTokensAsked: action.outputTokensAsked } : {}), ...("outputTokensLeast" in action && typeof action.outputTokensLeast === "number" ? { outputTokensLeast: action.outputTokensLeast } : {}) };
149
+ const admit = () => io.models.beforeRequest({ model: own, inputTokensMax: note ? measured + Buffer.byteLength(note, "utf8") : measured, ...asked, ...(note ? { noted: true, inputTokensMaxWithoutNote: measured } : {}) });
150
+ let ticket;
151
+ try {
152
+ ticket = await admit();
153
+ }
154
+ catch (error) {
155
+ if (!("onRefused" in action && action.onRefused === "next"))
156
+ throw error;
157
+ cursor += 1;
158
+ continue;
159
+ }
160
+ if (note && !ticket?.noteDropped)
161
+ await append(FAUX_RECORDS.note, { text: note });
104
162
  if ("cut" in action) {
105
163
  stats.requests += 1;
106
164
  return await hang(signal);
@@ -112,7 +170,7 @@ export function fauxAdapter(options) {
112
170
  return await hang(signal);
113
171
  }
114
172
  finally {
115
- await io.models.afterRequest({ input: 10, output: 5, usd: action.usd === undefined ? 0.001 : action.usd });
173
+ await io.models.afterRequest({ input: 10, output: 5, usd: action.usd === undefined ? 0.001 : action.usd }, ticket || undefined, { end: "lost", label: "cut" });
116
174
  }
117
175
  }
118
176
  stats.requests += 1;
@@ -121,20 +179,41 @@ export function fauxAdapter(options) {
121
179
  // write it into the body: filed, for a test to see.
122
180
  const limit = ticket ? ticket.outputTokensMax : undefined;
123
181
  await append(FAUX_RECORDS.request, { index, ...(limit === undefined ? {} : { outputTokensMax: limit }) });
124
- if ("fail" in action)
182
+ if ("fail" in action) {
183
+ await io.models.afterRequest({ input: 0, output: 0, cacheRead: 0, usd: 0 }, ticket || undefined, { end: "nothing", label: "status" });
125
184
  return await end("failed", action.fail);
126
- const book = () => io.models.afterRequest({ input: 10, output: 5, usd: action.usd === undefined ? 0.001 : action.usd });
185
+ }
186
+ if ("unanswered" in action) {
187
+ const how = action.unanswered;
188
+ await io.models.afterRequest({ input: 0, output: 0, cacheRead: 0, usd: how === "status" ? 0 : null }, ticket || undefined, how === "status" ? { end: "nothing", label: "status" } : how === "stopped" ? { end: "stopped", streamedTokens: 10 } : { end: "lost", label: "error_after", began: true });
189
+ continue;
190
+ }
191
+ // Held in flight, admitted and not answered, until the file it waits for exists (or the turn is stopped).
192
+ if ("until" in action && typeof action.until === "string")
193
+ await untilExists(action.until, signal);
194
+ const tokens = "tokens" in action && action.tokens ? action.tokens : { input: 10, output: 5 };
195
+ const usd = action.usd === undefined ? 0.001 : action.usd;
196
+ const book = () => io.models.afterRequest({ ...tokens, usd }, ticket || undefined, { end: "answered", usd });
127
197
  const bookAfter = "calls" in action && action.bookAfter === true;
128
- if (!bookAfter)
198
+ if ("bookWhen" in action && typeof action.bookWhen === "string")
199
+ void untilExists(action.bookWhen, signal).then(book).catch(() => undefined);
200
+ else if (!bookAfter)
129
201
  await book();
130
202
  if ("say" in action)
131
203
  io.onEvent({ type: "text", delta: action.say });
132
204
  else if ("end" in action)
133
205
  return await end(action.turn ?? "completed");
134
206
  else {
135
- const asked = "calls" in action ? action.calls.map((c) => ({ name: c.call, args: c.args ?? {} }))
207
+ const asked = "calls" in action ? action.calls.map((c) => ({ name: c.call, args: c.args ?? {}, ...(c.say ? { say: c.say } : {}) }))
136
208
  : [{ name: "call" in action ? action.call : "submit", args: "call" in action ? action.args ?? {} : { value: action.submit } }];
137
- for (const [n, { name, args }] of asked.entries()) {
209
+ for (const [n, { name, args, say }] of asked.entries()) {
210
+ if (say)
211
+ io.onEvent({ type: "text", delta: say });
212
+ // A side call (a title, a summary) admitted and answered while this request still streams: two in flight.
213
+ if (n === 0 && "sideDuring" in action && action.sideDuring) {
214
+ const side = await io.models.beforeRequest({ model: "faux-small", side: true, inputTokensMax: 100 });
215
+ await io.models.afterRequest({ input: 10, output: 5, usd: action.sideDuring.usd }, side || undefined);
216
+ }
138
217
  const callId = "calls" in action ? `${spec.key}:${index}.${n}` : `${spec.key}:${index}`;
139
218
  const tool = tools.get(name);
140
219
  await append(FAUX_RECORDS.call, { callId, name });
@@ -142,6 +221,8 @@ export function fauxAdapter(options) {
142
221
  const result = tool ? await tool.call(args, { callId, signal }).catch((error) => ({ text: error.message, isError: true })) : { text: `unknown tool ${name}`, isError: true };
143
222
  if (tool)
144
223
  stats.calls.push(name);
224
+ if ("resultWhen" in action && typeof action.resultWhen === "string")
225
+ await untilExists(action.resultWhen, signal);
145
226
  await append(FAUX_RECORDS.result, { callId, isError: result.isError === true });
146
227
  io.onEvent({ type: "tool_end", callId, name, isError: result.isError === true });
147
228
  }
@@ -187,7 +268,19 @@ export function fauxAdapter(options) {
187
268
  },
188
269
  turnEnd: () => ending ? ending.promise : Promise.resolve({ status: "completed" }),
189
270
  async interrupt() { turnSignal?.abort(new SessionHalt("interrupted")); },
190
- async close() { turnSignal?.abort(new SessionHalt("closed")); stats.closed.push(spec.key); },
271
+ async close() {
272
+ turnSignal?.abort(new SessionHalt("closed"));
273
+ // A slow harness stop: told closed only once it has taken its time.
274
+ if (options.closeDelayMs)
275
+ await new Promise((resolve) => setTimeout(resolve, options.closeDelayMs));
276
+ await proxy?.close();
277
+ // A harness whose stop fails: the close rejects, saying so, and is never told closed.
278
+ if (options.closeError)
279
+ throw new Error(options.closeError);
280
+ stats.closed.push(spec.key);
281
+ options.onClose?.(spec.key);
282
+ },
283
+ port: (label) => (proxy && options.proxy ? { url: proxy.url, key: proxy.sideKey(label), model: options.proxy.options.model, api: options.proxy.api } : undefined),
191
284
  };
192
285
  return session;
193
286
  },
package/dist/types.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ProviderPolicy } from "./host/proxy.js";
1
2
  import type { WorkflowDeps } from "@parcha/agentrun-dsl";
2
3
  import type { Ended } from "./booking.js";
3
4
  export type JsonValue = null | boolean | number | string | JsonValue[] | {
@@ -43,19 +44,58 @@ export interface HostTool {
43
44
  /** `safe`: may run again after a crash. `never`: at most once; a call a crash cut off is reported, never repeated. */
44
45
  replay: "safe" | "never";
45
46
  /** The tool's answer: its text (cut at HOST_RESULT_MAX_CHARS on its way to the harness), and any images it shows (a
46
- * screenshot), which a harness that can show them sends the model with the text. `sessionDir` is the runner's own,
47
+ * screenshot), which a harness that can show them sends the model with the text; `parked`: the host parked the call
48
+ * for a person's approval, so it did not run, and the text says it waits. `sessionDir` is the runner's own,
47
49
  * when it has one: a tool that runs a node of its own (the delegate) gives its child a private directory the same
48
- * way, by the child's key. */
50
+ * way, by the child's key. `model`: the calling session's model as its harness resolves it (pi's: a pi-ai Model, whose
51
+ * input and input limits a file read sizes an image by); `output`: where the call's output goes while it runs (the
52
+ * session's live view of the running tool). Each is absent where a harness has none to give. */
49
53
  call(args: unknown, context: {
50
54
  callId: string;
51
55
  signal: AbortSignal;
52
- sessionDir?: (key: string) => string;
56
+ sessionDir?: (key: string) => string; /** The kernel's attempt at this call: 0 the first time; above 0 when a crash cut an earlier attempt of a replay-safe tool and this one runs it again, so the earlier one may have been sent. */
57
+ attempt?: number;
58
+ model?: unknown;
59
+ output?(chunk: string): void;
53
60
  }): Promise<{
54
61
  text: string;
55
62
  isError?: boolean;
56
63
  images?: readonly ToolImage[];
64
+ parked?: true;
57
65
  }>;
58
66
  }
67
+ /** A tool of a remote MCP server, as the server listed it when its owner saved it (the run's pinned copy). */
68
+ export interface McpTool {
69
+ name: string;
70
+ title?: string;
71
+ description?: string;
72
+ inputSchema: Record<string, unknown>;
73
+ annotations?: Record<string, unknown>;
74
+ }
75
+ /** What an MCP tool call answers the model: its text, and whether the tool said it failed. */
76
+ export interface McpCallResult {
77
+ content: {
78
+ type: "text";
79
+ text: string;
80
+ }[];
81
+ isError?: boolean;
82
+ /** The host parked the call for a person's approval: it did not run, and the text says it waits. The harness's own
83
+ * client never sees this flag (the door sends `content` and `isError`). */
84
+ parked?: true;
85
+ }
86
+ /** A session's remote MCP servers: each one's granted tools, and the call that reaches them through the host, which holds
87
+ * their credentials. A harness with its own MCP client points it at the session's model proxy (`/mcp/<server>`). */
88
+ export interface SessionMcp {
89
+ servers: readonly {
90
+ name: string;
91
+ tools: readonly McpTool[];
92
+ }[];
93
+ /** Never throws: a failure is an `isError` result the model reads. `callId` is the harness's id for the call. */
94
+ call(server: string, tool: string, args: Record<string, unknown>, context: {
95
+ signal: AbortSignal;
96
+ callId?: string;
97
+ }): Promise<McpCallResult>;
98
+ }
59
99
  /** One durable record of a session, in the order it was appended. */
60
100
  export interface SessionRecord {
61
101
  kind: string;
@@ -78,6 +118,10 @@ export interface SessionWriter {
78
118
  /** Resolves once the records are durable, in order. Rejects with `SessionFenced`, writing none of them, once a newer
79
119
  * `open` of the key has resolved. */
80
120
  append(records: readonly SessionRecord[]): Promise<void>;
121
+ /** Make every record appended so far survive a lost box, not only a dead process: the kernel calls it after an
122
+ * effect's start and before the effect runs. A writer whose appends are durable already resolves at once. A wrapper
123
+ * passes it on (serialWriter): a writer without one is refused at the first effect that needs it. */
124
+ sync(): Promise<void>;
81
125
  }
82
126
  /** What one session is. */
83
127
  export interface SessionSpec {
@@ -88,6 +132,8 @@ export interface SessionSpec {
88
132
  system: string[];
89
133
  /** Exactly these tools; the harness's own stay off. */
90
134
  tools: HostTool[];
135
+ /** The remote MCP servers it may call, for a harness that has its own MCP client. */
136
+ mcp?: SessionMcp;
91
137
  context: "fresh" | "fork";
92
138
  tier?: NodeRequest["tier"];
93
139
  effort?: NodeRequest["effort"];
@@ -104,6 +150,29 @@ export interface ModelRequest {
104
150
  /** The least output it may be limited to and still answer: its answer's 1,024 tokens, plus the least thinking its
105
151
  * provider takes when it thinks (the proxy's policy says). Absent: 1,024. */
106
152
  outputTokensLeast?: number;
153
+ /** What it charges beside its tokens (a decision's per-request and per-image prices), in USD: held with them. */
154
+ feeUsd?: number;
155
+ /** A paid tool call, no model request (a web search's request, a monid call): held at `feeUsd` alone by the cap's tool
156
+ * rule, `name` and `basis` in a refusal's words. `call`: the tool call it was booked under, written on its
157
+ * runner.request so the run view puts its charge under that call. `charged_by`: who charges for it (the tool's
158
+ * provider: parallel, monid, an MCP server, a browser vendor), written there too, as main's charge row names it. */
159
+ paid?: {
160
+ name: string;
161
+ basis: string;
162
+ call?: string;
163
+ charged_by?: string;
164
+ };
165
+ /** A side call, never its turn's own: on another model than the session's (a client's title, a summary), or the
166
+ * host's own request beside the harness's (`host`). */
167
+ side?: true;
168
+ /** It carries the host's note (ModelPort.note) in its body: the note is delivered once this request is admitted.
169
+ * `inputTokensMaxWithoutNote`: its input measured as its client sent it, before the note was placed. */
170
+ noted?: true;
171
+ inputTokensMaxWithoutNote?: number;
172
+ /** A request the host sent beside the harness's own, on the session's own route (its model proxy, under a side key
173
+ * the proxy minted for this label: ModelProxy.sideKey): a learned workflow's model node, say. The harness's own
174
+ * requests carry none, and it cannot send one that does: it holds only the session's key. */
175
+ host?: string;
107
176
  }
108
177
  /** What a paid request cost, once it completed. */
109
178
  export interface ModelUsage {
@@ -119,6 +188,10 @@ export interface ModelUsage {
119
188
  /** A request a crash cut off: it left, and no answer came back to this run. Its tokens are unknown (0 here) and its
120
189
  * price is null; the provider may have billed it. */
121
190
  cut?: boolean;
191
+ /** A paid step's hold given back unused (a workflow call node's, its effect never sent the paid request it held for):
192
+ * nothing was sent and nothing charged, at usd 0. Its record says so, so no reader takes it for a $0 charge or an
193
+ * unpriced one. */
194
+ givenBack?: true;
122
195
  /** The ids the provider's response gave the request, by header name (the provider's `request-id`, a gateway's call
123
196
  * id such as LiteLLM's `x-litellm-call-id`): what joins this booking to the provider's own log. A cut request has
124
197
  * them only if its response had begun. */
@@ -145,13 +218,27 @@ export interface ModelPort {
145
218
  afterRequest(usage: ModelUsage, ticket?: ModelTicket, ended?: Ended): Promise<void>;
146
219
  /** Records the ids a paid request's response gave it, as its headers arrive and before its answer is read. */
147
220
  responded?(ids: Record<string, string>, ticket?: ModelTicket): Promise<void>;
221
+ /** A note its host has for the session's next main-model request (the spend cap's wrap-up), taken by this call; the
222
+ * session's model proxy adds it to that request's body (ModelProxyHooks.note). `request`: that request as its client
223
+ * sent it, measured before the note is placed (NoteRequest), so the host can price it as its admission will. */
224
+ note?(model: string, request?: NoteRequest): string | undefined;
148
225
  }
226
+ /** A request about to take its host's note, as its client sent it: its input bound and the output it asks for and needs
227
+ * at least, as the model proxy reads them (ModelRequest's figures, without the note). */
228
+ export type NoteRequest = {
229
+ inputTokensMax?: number;
230
+ outputTokensAsked?: number;
231
+ outputTokensLeast?: number;
232
+ };
149
233
  /** A paid request's admission: the turn it was admitted as, which its answer is booked under. */
150
234
  export interface ModelTicket {
151
235
  turn: number;
152
236
  /** The most output tokens, thinking included, the request may be sent with: what is left of its host's spend cap can
153
237
  * buy. The session's model proxy writes it into the body; absent, the request goes as asked. */
154
238
  outputTokensMax?: number;
239
+ /** Admitted only without its host's note (ModelRequest.noted): its bytes did not fit what is left of the cap. The
240
+ * request goes as its client sent it, and the note waits for another request. */
241
+ noteDropped?: true;
155
242
  }
156
243
  /** What the host lends a session. */
157
244
  export interface SessionIO {
@@ -167,7 +254,24 @@ export interface SessionIO {
167
254
  * a harness works in an empty directory of its own. */
168
255
  cwd?: string;
169
256
  onEvent(event: AdapterEvent): void;
257
+ /** The host's gate, asked about a call of a host tool before anything of it is written (before its intent, and before
258
+ * the flush a call that runs at most once takes): "allow" runs it; a deny answers the model with the host's words and
259
+ * runs nothing; a park holds the call, writing nothing, until the session's signal is aborted (the run parks on a
260
+ * person). Absent: every call runs. */
261
+ gate?(call: GateCall, context?: unknown): Promise<GateAnswer>;
262
+ }
263
+ /** A call as the host's gate is asked about it. */
264
+ export interface GateCall {
265
+ readonly callId: string;
266
+ readonly tool: string;
267
+ readonly args: Record<string, unknown>;
170
268
  }
269
+ /** The host's answer before a call's intent: run it, refuse it in these words, or park the run on it. */
270
+ export type GateAnswer = "allow" | {
271
+ readonly deny: string;
272
+ } | {
273
+ readonly park: true;
274
+ };
171
275
  /** An event of a session, as the adapter reports it. The runner adds the node it belongs to. A call's `tool_end` is sent
172
276
  * only once its outcome is durable in the session's records, so a host never shows a result its store does not have;
173
277
  * `result` is the text recorded, when the adapter reports it. A call stopped before its outcome was recorded gets no
@@ -175,6 +279,11 @@ export interface SessionIO {
175
279
  export type AdapterEvent = {
176
280
  type: "text";
177
281
  delta: string;
282
+ }
283
+ /** The model's message ended inside the turn, and another may follow in it (a CLI that resumes a cut answer itself):
284
+ * what it said so far is one message. */
285
+ | {
286
+ type: "text_end";
178
287
  } | {
179
288
  type: "tool_start";
180
289
  callId: string;
@@ -188,9 +297,14 @@ export type AdapterEvent = {
188
297
  isError: boolean;
189
298
  result?: string;
190
299
  truncated?: true;
191
- } | {
300
+ }
301
+ /** `stopReason: "length"` only when the turn's final answer was cut at the model's output limit (unfinished), with that
302
+ * answer's output tokens when the adapter knows them: a host reads the answer as cut, never as the run's end. */
303
+ | {
192
304
  type: "turn_end";
193
305
  status: TurnStatus;
306
+ stopReason?: "length";
307
+ outputTokens?: number;
194
308
  };
195
309
  /** An event as a host receives it: the adapter's, the runner's own, and the node each belongs to. */
196
310
  export type HarnessEvent = (AdapterEvent | {
@@ -201,6 +315,7 @@ export type HarnessEvent = (AdapterEvent | {
201
315
  type: "request_end";
202
316
  turn: number;
203
317
  usage: ModelUsage;
318
+ ended?: Ended;
204
319
  }) & {
205
320
  key: string;
206
321
  label: string;
@@ -211,8 +326,15 @@ export type TurnStatus = "completed" | "interrupted" | "failed";
211
326
  export type SessionState = "new" | "open_turn" | "idle";
212
327
  export interface AdapterSession {
213
328
  readonly state: SessionState;
214
- /** Place the input, then send it: a new turn. */
215
- send(text: string): Promise<void>;
329
+ /** Place the input, then send it: a new turn. `id`: the input's own request id (a follow-up's, such as a raised run's
330
+ * turn), so placing it again is the same input, never the run's first one. `origin`: who wrote it when the person did
331
+ * not (a trigger's first input, its launch's): an adapter that keeps the run's record writes it with the input. */
332
+ send(text: string, options?: {
333
+ id?: string;
334
+ origin?: {
335
+ readonly [key: string]: unknown;
336
+ };
337
+ }): Promise<void>;
216
338
  /** Resume the turn a crash cut off, from the session's records. Only when `state` is `open_turn`. */
217
339
  recover(): Promise<void>;
218
340
  /** Record the open turn as ended, interrupted, and send nothing: the turn is not to be resumed (a person stopped it, and
@@ -239,15 +361,118 @@ export interface AdapterSession {
239
361
  }): Promise<void>;
240
362
  /** Stop the harness's processes and let go of the session. */
241
363
  close(): Promise<void>;
364
+ /** A person's message placed in the turn in flight, at its next boundary, for a harness that takes one mid-turn (pi).
365
+ * `id`: the request id the placement carries (the host's command), so the host can tell the commit that placed it.
366
+ * `mode`: "steer" (the default) steers the turn in flight; "followUp" waits for the turn's end and runs as a turn of
367
+ * its own (a message that answers nothing, such as a trigger's). `origin`: who wrote it when the person did not (a
368
+ * trigger's message), kept on the message the harness records, as the Timeline shows it. Absent when the harness takes
369
+ * no message mid-turn: the host refuses the steer in words. */
370
+ steer?(text: string, id?: string, mode?: "steer" | "followUp", options?: {
371
+ readonly origin?: {
372
+ readonly [key: string]: unknown;
373
+ };
374
+ }): Promise<void>;
375
+ /** The session's own model route, for a request the host sends beside the harness's own (a learned workflow's model
376
+ * node): its model proxy's address with a side key minted for `label` (ModelProxy.sideKey), the model its policy
377
+ * takes and the API it speaks. Undefined while no proxy is up (no turn has attached one yet). Every model request of
378
+ * a session goes through that one proxy: the same policy, origin, credential, price and booking. */
379
+ port?(label: string): SessionPort | undefined;
380
+ }
381
+ /** The API a harness's model proxy speaks: what its provider, its keys and its catalog follow from. */
382
+ export type Wire = "anthropic-messages" | "openai-responses";
383
+ /** What a harness is, as its adapter states it: the host reads these and never branches on a harness's name. They
384
+ * describe the harness; none renames or reshapes what its model sees, and none turns its own built-ins, sandbox or
385
+ * session machine on. */
386
+ export interface AdapterFacts {
387
+ /** The harness's id ("claude-agent", "codex", "opencode"). */
388
+ readonly id: string;
389
+ /** Its name in a sentence ("Claude", "Codex", "OpenCode"). */
390
+ readonly label: string;
391
+ /** The API its model proxy speaks. */
392
+ readonly wire: Wire;
393
+ /** Whether it takes a message mid-turn (else a message waits for the turn's end). */
394
+ readonly steer: boolean;
395
+ /** False when a tool call that started is never run again by a restart, replay-safe or not: the harness's own process
396
+ * holds the turn, and only its model calls again (a CLI). Absent: a restart reruns a replay-safe call, by the
397
+ * kernel's rule. */
398
+ readonly rerunsStarted?: false;
399
+ /** How many times the harness resumes an answer its model's output limit cut, itself, inside one turn (a CLI's own
400
+ * recovery): above 0, a turn never ends on such a cut until those run out; 0, a cut ends its turn, as pi's does.
401
+ * Absent: not declared. */
402
+ readonly recoversCutAnswers?: number;
403
+ /** What one run of it holds in memory, in MiB: the host admits runs by it. */
404
+ readonly runMib: number;
405
+ /** Whether it binds a session's remote MCP servers (its own MCP client, at the session's gateway). */
406
+ readonly mcp: boolean;
407
+ /** The thinking levels it takes, lowest first: a run's level above its highest runs at that highest. */
408
+ readonly thinking: readonly ("low" | "medium" | "high" | "xhigh" | "max")[];
409
+ /** Its own web search, when the provider runs it: `native`, the provider's search through the session's proxy (its
410
+ * input read at an allowance); `live`, the harness's own live search, booked per call. None: it has no search of
411
+ * its own. */
412
+ readonly webSearch?: "native" | "live";
413
+ /** Its model is its own, chosen on its own wire's settings, never the host's default for the other harnesses. */
414
+ readonly ownModel: boolean;
415
+ /** The model as the harness names it (Anthropic's id has no dot). */
416
+ normalizeModel(model: {
417
+ provider: string;
418
+ modelId: string;
419
+ }): {
420
+ provider: string;
421
+ modelId: string;
422
+ };
423
+ /** How it is installed and pinned: the line that installs it into a project, the package it pins, and the codes its
424
+ * own setup errors carry when installing (`install`) or the pinned build (`pins`) is the fix. */
425
+ readonly install: {
426
+ npmLine: string;
427
+ spec: string;
428
+ codes: {
429
+ install: string;
430
+ pins: string;
431
+ };
432
+ };
433
+ /** The problems its own MCP client has with a tool's input schema (`tool` as it names it, `mcp__<server>__<tool>`):
434
+ * shapes it drops or retypes, measured on its pinned build, so a grant of that tool would offer the model another
435
+ * tool than the one granted. None: its client takes any schema the kernel's check does. */
436
+ schemaProblems?(tool: string, schema: Record<string, unknown>): string[];
437
+ /** A name its client calls a session's MCP tool by beside `mcp__<server>__<tool>` (OpenCode's `<server>_<tool>`). */
438
+ readonly toolAlias?: RegExp;
439
+ /** Its CLI's own tools, by the name a call reaches the host by, each with the host's table tool it is (Claude's
440
+ * `Bash` is `bash`): a host holds such a call to that tool's setting. None: its CLI calls only the host's tools. */
441
+ readonly nativeTools?: Readonly<Record<string, string>>;
442
+ /** The policy its model proxy applies, for a host that serves the same route itself (a test's faux harness). */
443
+ policy(options: {
444
+ model: string;
445
+ tools: readonly string[];
446
+ auth?: "bearer" | "x-api-key";
447
+ webSearch?: true | "live";
448
+ webSearchAllowance?: number;
449
+ maxOutputTokens?: number;
450
+ }): ProviderPolicy;
451
+ }
452
+ /** A session's model proxy, as the host reaches it for its own requests beside the harness's (AdapterSession.port). */
453
+ export interface SessionPort {
454
+ /** The proxy's origin, on the loopback interface with a port of its own (ModelProxy.url). */
455
+ url: string;
456
+ /** The side key the request presents, as a bearer token. */
457
+ key: string;
458
+ /** The model the session's policy takes (its own id, as the harness sends it). */
459
+ model: string;
460
+ /** The API the proxy serves: Anthropic's Messages (claude-agent) or OpenAI's Responses (codex, opencode). */
461
+ api: "anthropic-messages" | "openai-responses";
242
462
  }
243
463
  export interface AdapterCapabilities {
244
- /** Whether the adapter can start a session from another's transcript. */
245
- fork: boolean;
464
+ /** Its harness's own MCP client, when it has one: it calls `spec.mcp`'s servers at the session proxy's `/mcp/<server>`,
465
+ * which the kernel's model proxy mounts from the session's MCP and this fact (ModelProxyOptions.mcp). */
466
+ mcpClient?: McpClient;
467
+ }
468
+ /** A harness's own MCP client, as its adapter declares it: the `_meta` key of a `tools/call` that carries the harness's
469
+ * own id for the call (Claude Code's `claudecode/toolUseId`, Codex's `callId`), the id its timeline and gate know the
470
+ * call by. The route reads that key and no other. */
471
+ export interface McpClient {
472
+ callIdMeta: string;
246
473
  }
247
474
  export interface AgentAdapter {
248
475
  readonly id: string;
249
- /** The harness version the adapter is pinned to. */
250
- readonly version: string;
251
476
  capabilities(): AdapterCapabilities;
252
477
  /** Problems with a session before anything is spent; an empty list opens it. */
253
478
  check(spec: SessionSpec): string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-kernel",
3
- "version": "0.1.0-beta.30",
3
+ "version": "0.1.0-beta.32",
4
4
  "description": "Agent harnesses other than Pi, starting with Codex, behind one seam: a DSL node's runNode and an AgentRun run on a harness adapter, durable in AgentRun's own store.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -13,7 +13,7 @@
13
13
  "license": "Apache-2.0",
14
14
  "author": "Parcha Labs, Inc.",
15
15
  "engines": {
16
- "node": ">=22.19.0"
16
+ "node": ">=24.11.0"
17
17
  },
18
18
  "main": "./dist/index.js",
19
19
  "types": "./dist/index.d.ts",
@@ -30,6 +30,10 @@
30
30
  "types": "./dist/kernel/index.d.ts",
31
31
  "default": "./dist/kernel/index.js"
32
32
  },
33
+ "./kernel/cap": {
34
+ "types": "./dist/kernel/cap/index.d.ts",
35
+ "default": "./dist/kernel/cap/index.js"
36
+ },
33
37
  "./process": {
34
38
  "types": "./dist/process/index.d.ts",
35
39
  "default": "./dist/process/index.js"
@@ -56,9 +60,9 @@
56
60
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
57
61
  },
58
62
  "dependencies": {
59
- "@parcha/agentrun-dsl": "0.1.0-beta.30",
63
+ "@parcha/agentrun-dsl": "0.1.0-beta.32",
60
64
  "ajv": "8.18.0",
61
- "typebox": "1.3.7"
65
+ "typebox": "1.3.27"
62
66
  },
63
67
  "repository": {
64
68
  "type": "git",
@@ -40,15 +40,6 @@
40
40
  "blob": "0c9f118023f7e7122621c84c4766b478fe8a73ca",
41
41
  "sha256": "8814035a33a55916306f2e91f9fb582389556da858a94085449f0a66aba4846d"
42
42
  },
43
- "src/kernel/types.ts": {
44
- "upstream": "packages/harness-world/src/types.ts",
45
- "blob": "d12a050e7395a6a4d5319acf88ba3d728b783443",
46
- "sha256": "775a12d0c7737dad58ac8b5e8a9695c559762a8196b7cd78b48fa284803a9a3f",
47
- "kind": "interfaces matched",
48
- "declarations": [
49
- "EffectRecord"
50
- ]
51
- },
52
43
  "src/kernel/errors.ts": {
53
44
  "upstream": "packages/harness-world/src/errors.ts",
54
45
  "blob": "f778e8b800281227c9b005865a02e1026cc1fefd",
@@ -1,26 +0,0 @@
1
- import { type BoxedChild, type BoxRecord, type BoxRecorder, type Reaped } from "./box.js";
2
- /** `empty`: a reap counted the last box empty, or there was none. `full`: a reap found it not empty, or could not count. */
3
- export type BoxSlotState = "empty" | "live" | "reaping" | "full";
4
- /** What the slot needs of a started box: when it is let go, and when it exited. Its exit status is never read. */
5
- export type SlotChild = Pick<BoxedChild, "ready" | "exited">;
6
- export interface BoxStart<P> {
7
- /** The box's process, as its start returned it. */
8
- process: P;
9
- /** Settles once the box's process exited (or never got going) and the reap that follows gave its verdict: resolves
10
- * only when the box holds nothing, else rejects with BoxError box_not_empty. */
11
- reaped: Promise<void>;
12
- }
13
- export interface BoxSlot<P extends SlotChild> {
14
- readonly state: BoxSlotState;
15
- /** Starts the session's next box, synchronously end to end. Refused (BoxError box_busy) unless the slot is empty.
16
- * `start` gets the recorder wrapped so the slot keeps the latest record, and calls `ahead` itself before it spawns
17
- * anything. A start that throws after `ahead` has its box reaped (the slot shows it), and the error goes up. */
18
- start(start: (recorder: BoxRecorder) => P, recorder: BoxRecorder): BoxStart<P>;
19
- /** At open: the record the session's last box left, reaped before anything starts. The slot is empty only if that
20
- * reap counts it empty. */
21
- adopt(previous: BoxRecord): Promise<void>;
22
- }
23
- /** One session's box slot, reaping with `reap`. */
24
- export declare function boxSlot<P extends SlotChild>(options: {
25
- reap: (record: BoxRecord) => Promise<Reaped>;
26
- }): BoxSlot<P>;