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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runner.d.ts CHANGED
@@ -68,7 +68,7 @@ export type BeforeRequest = (request: {
68
68
  /** A side call (ModelRequest.side): on another model than the session's (a client's), or the host's own (`host`). */
69
69
  side?: true;
70
70
  /** A request on the session's model that is no answer of the turn (ModelRequest.unanswered: a title, a summary, a
71
- * child's): still the run's own to book, but never the session's previous request, read or replaced. */
71
+ * child's): still the run's own to book, but never one of the session's recent requests, read or kept. */
72
72
  unanswered?: true;
73
73
  /** It carries the host's note (ModelRequest.noted), and its input measured without it (`inputTokensMaxWithoutNote`):
74
74
  * a host that admits it only without the note says so (Admission.withoutNote). */
package/dist/runner.js CHANGED
@@ -133,6 +133,37 @@ export function sessionSpendOf(records) {
133
133
  export const answeredUnpriced = (data) => data.usd === null && typeof data.rule === "string" && (data.rule === "answered" || data.rule.startsWith("answered:") || data.rule === "stopped" || data.rule === "lost" || data.rule.startsWith("lost:"));
134
134
  /** Whether a request was booked lost (bookRequest's rule `lost`, or `lost:<label>`): billed or not, no cost came in. */
135
135
  const bookedLost = (rule) => typeof rule === "string" && (rule === "lost" || rule.startsWith("lost:"));
136
+ /** The bookings of each session scope (SessionWriter.scope) in this process, across its claims: each request a booking
137
+ * admitted and has not seen answer (`flying`, settled once its afterRequest has written or failed to), and each answered
138
+ * request whose runner.turn the store refused (`refused`: a claim lost as the request answered). The scope's next
139
+ * booking waits for the first and writes the second at its bookCut: a request that answered is booked at what it
140
+ * reported, once, never cut at an unknown cost because the claim that sent it could no longer write. */
141
+ const handoffs = new Map();
142
+ /** How long a bookCut waits for an earlier booking's request still in flight in this process (its claim lost, its loop
143
+ * stopping, which ends its requests): past it, the request is booked cut as one a dead process left. */
144
+ const HANDOFF_WAIT_MS = 10_000;
145
+ /** The most scopes kept: past it, the oldest with nothing in flight is dropped (a run resumed in another process, or not
146
+ * at all, never takes what it left here; its next booking anywhere books those requests cut, as before). */
147
+ const HANDOFF_SCOPES_MAX = 1024;
148
+ const handoffOf = (scope) => {
149
+ let at = handoffs.get(scope);
150
+ if (!at) {
151
+ at = { flying: new Map(), refused: new Map() };
152
+ handoffs.set(scope, at);
153
+ if (handoffs.size > HANDOFF_SCOPES_MAX)
154
+ for (const [key, old] of handoffs)
155
+ if (old.flying.size === 0 && key !== scope) {
156
+ handoffs.delete(key);
157
+ break;
158
+ }
159
+ }
160
+ return at;
161
+ };
162
+ const handoffDone = (scope) => {
163
+ const at = handoffs.get(scope);
164
+ if (at && at.flying.size === 0 && at.refused.size === 0)
165
+ handoffs.delete(scope);
166
+ };
136
167
  function bookingFor(writer, options) {
137
168
  const node = { key: options.key, label: options.label ?? options.key, ...(options.executionPath === undefined ? {} : { executionPath: options.executionPath }) };
138
169
  const limit = options.maxTurns ?? null;
@@ -163,6 +194,24 @@ function bookingFor(writer, options) {
163
194
  }
164
195
  // This process's requests in flight, oldest first: the turn each was admitted as, and its model.
165
196
  const open = [];
197
+ // Each of them as the session's scope knows it in flight (handoffs), settled once its afterRequest has written or not.
198
+ const scope = writer.scope;
199
+ const settles = new Map();
200
+ const fly = (turn) => {
201
+ if (scope === undefined)
202
+ return;
203
+ let settle;
204
+ const flying = handoffOf(scope).flying;
205
+ const done = new Promise((resolve) => (settle = resolve));
206
+ flying.set(turn, done);
207
+ settles.set(turn, () => {
208
+ settles.delete(turn);
209
+ if (flying.get(turn) === done)
210
+ flying.delete(turn);
211
+ settle();
212
+ handoffDone(scope);
213
+ });
214
+ };
166
215
  // Response ids whose own write was refused, marked `late`: the booking's next write of its own (the next runner.request,
167
216
  // or a runner.turn) carries them first, so a request this process cuts by dying after that still keeps its ids. One a
168
217
  // runner.turn writes with the ids is dropped, never written twice. A process that dies before writing for its booking
@@ -264,6 +313,7 @@ function bookingFor(writer, options) {
264
313
  throw stoppedLate;
265
314
  }
266
315
  open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(bound ? { boundUsd: bound } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
316
+ fly(turn);
267
317
  return { turn, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(withoutNote ? { noteDropped: true } : {}) };
268
318
  };
269
319
  const models = {
@@ -313,13 +363,21 @@ function bookingFor(writer, options) {
313
363
  // sessionSpendOf reads it on the next claim.
314
364
  const capped = booking && bookedLost(booking.rule) && hold !== undefined ? hold + (bounds.get(turn) ?? 0) : figure;
315
365
  spentUsd = spent(spentUsd, capped ?? undefined);
366
+ const settle = settles.get(turn);
367
+ const data = { turn, usd: usage.usd, ...tokensOf(usage), ...(usage.givenBack ? { givenBack: true } : {}), ...(usage.estimated ? { estimated: true } : {}), ...(usage.tableUsd === undefined ? {} : { tableUsd: usage.tableUsd }), ...(usage.providerIds ? { providerIds: usage.providerIds } : {}), ...(stopped === undefined ? {} : { heldUsd: Math.min(hold, stopped), stopped: true }), ...(booking ? { bookedUsd: booking.usd, rule: booking.rule } : {}), ...(note ? { note } : {}) };
316
368
  try {
317
369
  // A runner.turn with the ids holds what a carried response record of this turn would: that one is dropped. A
318
370
  // stopped one keeps the figure it counts at (`heldUsd`), so a later process counts it the same.
319
371
  const covers = (r) => usage.providerIds !== undefined && r.data.turn === turn;
320
- await write([{ kind: RUNNER_RECORDS.turn, data: { turn, usd: usage.usd, ...tokensOf(usage), ...(usage.givenBack ? { givenBack: true } : {}), ...(usage.estimated ? { estimated: true } : {}), ...(usage.tableUsd === undefined ? {} : { tableUsd: usage.tableUsd }), ...(usage.providerIds ? { providerIds: usage.providerIds } : {}), ...(stopped === undefined ? {} : { heldUsd: Math.min(hold, stopped), stopped: true }), ...(booking ? { bookedUsd: booking.usd, rule: booking.rule } : {}), ...(note ? { note } : {}) } }], covers);
372
+ await write([{ kind: RUNNER_RECORDS.turn, data }], covers);
373
+ settle?.();
321
374
  }
322
375
  catch (error) {
376
+ // Refused (its claim lost as it answered, say): the booking is handed to the session's next booking in this
377
+ // process, which writes it at its bookCut, never cutting a request that answered (handoffs).
378
+ if (scope !== undefined)
379
+ handoffOf(scope).refused.set(turn, { data, usage, ...(ended ? { ended } : {}) });
380
+ settle?.();
323
381
  // A paid request whose cost can't be kept: the attempt stops, saying so, rather than spend on uncounted. Asked
324
382
  // with the request's own host label, as its admission was: a stop that holds only the harness's own requests (a
325
383
  // parked turn's) never hides the failure from the host's. A turn parked on a call (TurnParked) is no stop of the
@@ -346,10 +404,50 @@ function bookingFor(writer, options) {
346
404
  // Only requests an earlier process admitted: one this process has in flight is not cut. Read again here, just before
347
405
  // the cut is written: another booking of this session (an earlier pass of this claim, or one racing it) may have
348
406
  // booked it since this one opened, and a request is booked once.
349
- const bookedSince = sessionSpendOf(await writer.read().catch(() => options.records)).answered;
407
+ // An earlier booking of this session in this process (a claim lost, then taken again here) may still have one of them
408
+ // in flight: its end is waited for, bounded, so a request that answers meanwhile is booked by what it reported.
409
+ const before = scope === undefined ? undefined : handoffs.get(scope);
410
+ const flying = before ? inherited.filter((t) => !answered.has(t)).flatMap((t) => before.flying.get(t) ?? []) : [];
411
+ if (flying.length) {
412
+ let timer;
413
+ await Promise.race([Promise.all(flying), new Promise((resolve) => (timer = setTimeout(resolve, HANDOFF_WAIT_MS)))]);
414
+ clearTimeout(timer);
415
+ }
416
+ const now = await writer.read().catch(() => options.records);
417
+ const bookedSince = sessionSpendOf(now).answered;
350
418
  for (const t of inherited)
351
419
  if (bookedSince.has(t))
352
420
  answered.add(t);
421
+ // A request an earlier booking in this process saw answer, whose runner.turn its store refused: written now as that
422
+ // booking would have written it, and told as it would have told it, at what it reported. One the session booked since
423
+ // is dropped: a request is booked once.
424
+ const handed = scope === undefined ? undefined : handoffs.get(scope);
425
+ if (scope !== undefined && handed) {
426
+ for (const t of inherited)
427
+ if (answered.has(t))
428
+ handed.refused.delete(t);
429
+ const taken = inherited.flatMap((turn) => {
430
+ const one = handed.refused.get(turn);
431
+ return one ? [{ turn, ...one }] : [];
432
+ });
433
+ if (taken.length) {
434
+ const records = taken.map((one) => ({ kind: RUNNER_RECORDS.turn, data: one.data }));
435
+ await append(records);
436
+ for (const one of taken) {
437
+ handed.refused.delete(one.turn);
438
+ answered.add(one.turn);
439
+ }
440
+ // Its spend read the request at its hold and bound (or unknown); booked, it reads at what it was booked at. Only
441
+ // before this booking's own requests: the spend is the session's records then.
442
+ if (turns === inherited.length && open.length === 0)
443
+ spentUsd = sessionSpendOf([...now, ...records]).spentUsd;
444
+ for (const one of taken) {
445
+ const hosted = hosts.get(one.turn);
446
+ await emit({ type: "request_end", turn: one.turn, usage: one.usage, ...(hosted === undefined ? {} : { host: hosted }), ...(one.ended ? { ended: one.ended } : {}) });
447
+ }
448
+ }
449
+ handoffDone(scope);
450
+ }
353
451
  const left = inherited.filter((t) => !answered.has(t));
354
452
  if (left.length === 0)
355
453
  return;
package/dist/testing.d.ts CHANGED
@@ -5,8 +5,12 @@ export { SCHEMA_CHECK_CASES, type SchemaCheckCase } from "./schema-check-cases.j
5
5
  * harness runs. */
6
6
  export { inputTokensMaxOf, matchRoute, parseStrict, reportedCostOf } from "./host/proxy.js";
7
7
  /** A session store in memory: what one run's store holds, across the processes a test plays. Each `open` of a key
8
- * counts one more holder at once, and a writer appends only while its count is the newest. */
9
- export declare function memorySessionStore(): SessionStore & {
8
+ * counts one more holder at once, and a writer appends only while its count is the newest. `scope`: the run's identity
9
+ * in this process, for a test that plays a claim lost and taken again in one process (SessionWriter.scope); without it,
10
+ * each open plays a process of its own, which hands nothing on. */
11
+ export declare function memorySessionStore(options?: {
12
+ scope?: string;
13
+ }): SessionStore & {
10
14
  keys(): string[];
11
15
  };
12
16
  /** What a scripted request reports beside its cost, as a real adapter's proxy reads a response, and how it is measured:
package/dist/testing.js CHANGED
@@ -14,8 +14,10 @@ export { SCHEMA_CHECK_CASES } from "./schema-check-cases.js";
14
14
  * harness runs. */
15
15
  export { inputTokensMaxOf, matchRoute, parseStrict, reportedCostOf } from "./host/proxy.js";
16
16
  /** A session store in memory: what one run's store holds, across the processes a test plays. Each `open` of a key
17
- * counts one more holder at once, and a writer appends only while its count is the newest. */
18
- export function memorySessionStore() {
17
+ * counts one more holder at once, and a writer appends only while its count is the newest. `scope`: the run's identity
18
+ * in this process, for a test that plays a claim lost and taken again in one process (SessionWriter.scope); without it,
19
+ * each open plays a process of its own, which hands nothing on. */
20
+ export function memorySessionStore(options = {}) {
19
21
  const sessions = new Map();
20
22
  const holders = new Map();
21
23
  const read = async (key) => structuredClone(sessions.get(key) ?? []);
@@ -26,6 +28,7 @@ export function memorySessionStore() {
26
28
  holders.set(key, holder);
27
29
  return {
28
30
  key,
31
+ ...(options.scope === undefined ? {} : { scope: `${options.scope}\n${key}` }),
29
32
  read: () => read(key),
30
33
  async append(records) {
31
34
  if (holders.get(key) !== holder)
@@ -53,7 +56,6 @@ export function fauxAdapter(options) {
53
56
  get calls() { return stats.calls; },
54
57
  get opened() { return stats.opened; },
55
58
  get closed() { return stats.closed; },
56
- capabilities: () => ({}),
57
59
  check: (spec) => [
58
60
  ...(spec.context === "fork" ? ["the faux harness cannot fork a session"] : []),
59
61
  ...(options.refuse?.(spec) ?? []),
@@ -0,0 +1,12 @@
1
+ export declare const TOOLS_SEARCH = "tools_search";
2
+ export declare const TOOLS_CALL = "tools_call";
3
+ export declare const CODEMODE = "codemode";
4
+ /** The three, by name: none of them can be called through another, and none is searched for. */
5
+ export declare const META_TOOLS: ReadonlySet<string>;
6
+ /** A run with more catalog tools than this is deferred them. */
7
+ export declare const DEFER_CATALOG_OVER = 20;
8
+ /** Whether a tool is a catalog tool, by the name a harness gives it: an MCP tool (`mcp__<server>__<tool>`) or a monid
9
+ * endpoint (`monid__<provider>__<endpoint>`). */
10
+ export declare const isCatalogName: (name: string) => boolean;
11
+ /** Whether a run whose host tools are `names` has its catalog tools deferred: more than DEFER_CATALOG_OVER of them. */
12
+ export declare const defersCatalog: (names: readonly string[]) => boolean;
@@ -0,0 +1,17 @@
1
+ // One discovery system. A run lists every tool to the model in full until its catalog tools (an MCP server's, a monid
2
+ // one) pass DEFER_CATALOG_OVER: then they are deferred, not listed, and the model finds them with tools_search and runs
3
+ // them with tools_call. Claude Code defers MCP tools itself (its ToolSearch), on under the same test, so it is offered
4
+ // neither of ours. Built-ins and a harness's own tools are always listed. A run under the threshold has no search or call:
5
+ // they would find tools the model already has, at about 640 tokens on every request.
6
+ export const TOOLS_SEARCH = "tools_search";
7
+ export const TOOLS_CALL = "tools_call";
8
+ export const CODEMODE = "codemode";
9
+ /** The three, by name: none of them can be called through another, and none is searched for. */
10
+ export const META_TOOLS = new Set([TOOLS_SEARCH, TOOLS_CALL, CODEMODE]);
11
+ /** A run with more catalog tools than this is deferred them. */
12
+ export const DEFER_CATALOG_OVER = 20;
13
+ /** Whether a tool is a catalog tool, by the name a harness gives it: an MCP tool (`mcp__<server>__<tool>`) or a monid
14
+ * endpoint (`monid__<provider>__<endpoint>`). */
15
+ export const isCatalogName = (name) => name.startsWith("mcp__") || name.startsWith("monid_");
16
+ /** Whether a run whose host tools are `names` has its catalog tools deferred: more than DEFER_CATALOG_OVER of them. */
17
+ export const defersCatalog = (names) => names.filter(isCatalogName).length > DEFER_CATALOG_OVER;
package/dist/types.d.ts CHANGED
@@ -56,7 +56,8 @@ export interface HostTool {
56
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
57
  attempt?: number;
58
58
  model?: unknown;
59
- output?(chunk: string): void;
59
+ output?(chunk: string): void; /** The session's other tools, called as calls of their own nested in this one (NestedCalls): given to a tool that `nests`, where the harness has a way to. */
60
+ nested?: NestedCalls;
60
61
  }): Promise<{
61
62
  text: string;
62
63
  isError?: boolean;
@@ -64,6 +65,40 @@ export interface HostTool {
64
65
  structured?: JsonValue;
65
66
  parked?: true;
66
67
  }>;
68
+ /** The tool only calls the session's other tools (tools_call, codemode), each as a call of its own nested in this one
69
+ * (`context.nested`): each nested call passes the gate as itself and is recorded under its own id, so this call writes
70
+ * no intent or outcome of its own. A harness runs it again after a crash, its recorded nested calls answered from their
71
+ * records, never run twice. */
72
+ nests?: true;
73
+ /** Registered and callable (by the gate, and by a nested call: tools_call, a script), but not listed to the model: a
74
+ * catalog tool of a run whose catalog is deferred (tool-deferral.ts), which the model finds with tools_search. */
75
+ deferred?: true;
76
+ }
77
+ /**
78
+ * A tool's calls of the session's other tools, each a call of its own nested in the calling one: asked about at the gate
79
+ * as itself (GateCall `nested`), its intent and outcome recorded under `<callId>/<key>` before and after it runs, as a
80
+ * call the model made is. A call the record finished answers from the record, never runs again.
81
+ */
82
+ export interface NestedCalls {
83
+ /** Call tool `name` (a session tool, by its host name) with `args`, under `key`: stable for the same call in a rerun
84
+ * of the calling one. A deny answers `refused` with the gate's words; a park holds until the session lets go, then
85
+ * rejects. */
86
+ call(name: string, args: Record<string, unknown>, key: string): Promise<NestedResult>;
87
+ /** `value` the first time `key` is asked in this call, and that first value again in every rerun of the call. */
88
+ memo<T extends JsonValue>(key: string, value: T): Promise<T>;
89
+ }
90
+ /** A nested call's answer. */
91
+ export interface NestedResult {
92
+ text: string;
93
+ isError?: boolean;
94
+ images?: readonly ToolImage[];
95
+ structured?: JsonValue;
96
+ /** The gate refused it: `text` is the gate's words, and nothing of it ran. */
97
+ refused?: true;
98
+ /** Its intent was recorded and its outcome lost (a crash cut it): it may or may not have taken effect. */
99
+ interrupted?: true;
100
+ /** It was asked and run (or refused) now, in this attempt of the calling call; false when its answer came from the record. */
101
+ fresh: boolean;
67
102
  }
68
103
  /** A tool of a remote MCP server, as the server listed it when its owner saved it (the run's pinned copy). */
69
104
  export interface McpTool {
@@ -73,29 +108,13 @@ export interface McpTool {
73
108
  inputSchema: Record<string, unknown>;
74
109
  annotations?: Record<string, unknown>;
75
110
  }
76
- /** What an MCP tool call answers the model: its text, and whether the tool said it failed. */
111
+ /** What an MCP tool call answers: its text, and whether the tool said it failed. */
77
112
  export interface McpCallResult {
78
113
  content: {
79
114
  type: "text";
80
115
  text: string;
81
116
  }[];
82
117
  isError?: boolean;
83
- /** The host parked the call for a person's approval: it did not run, and the text says it waits. The harness's own
84
- * client never sees this flag (the door sends `content` and `isError`). */
85
- parked?: true;
86
- }
87
- /** A session's remote MCP servers: each one's granted tools, and the call that reaches them through the host, which holds
88
- * their credentials. A harness with its own MCP client points it at the session's model proxy (`/mcp/<server>`). */
89
- export interface SessionMcp {
90
- servers: readonly {
91
- name: string;
92
- tools: readonly McpTool[];
93
- }[];
94
- /** Never throws: a failure is an `isError` result the model reads. `callId` is the harness's id for the call. */
95
- call(server: string, tool: string, args: Record<string, unknown>, context: {
96
- signal: AbortSignal;
97
- callId?: string;
98
- }): Promise<McpCallResult>;
99
118
  }
100
119
  /** One durable record of a session, in the order it was appended. */
101
120
  export interface SessionRecord {
@@ -115,6 +134,12 @@ export interface SessionStore {
115
134
  /** The one holder that may write a session. */
116
135
  export interface SessionWriter {
117
136
  readonly key: string;
137
+ /** The session's identity across the claims of one holder (a runner's name and a run's id beside the key), for a store
138
+ * whose claims a holder can lose and take again. A booking of the session whose cost write is refused (its claim lost
139
+ * as its request answered) hands that booking to the next booking of the same scope in this process, which writes it
140
+ * before it books any request cut (ModelBooking.bookCut). Absent: nothing is handed on, and such a request is booked
141
+ * cut. Never shared by two holders: another runner, as one that died, takes nothing of it. */
142
+ readonly scope?: string;
118
143
  read(): Promise<SessionRecord[]>;
119
144
  /** Resolves once the records are durable, in order. Rejects with `SessionFenced`, writing none of them, once a newer
120
145
  * `open` of the key has resolved. */
@@ -131,11 +156,13 @@ export interface SessionSpec {
131
156
  label: string;
132
157
  executionPath?: string;
133
158
  system: string[];
134
- /** Exactly these tools; the harness's own stay off. */
159
+ /** Exactly these tools (a run's remote MCP tools among them, as host tools); the harness's own stay off. */
135
160
  tools: HostTool[];
136
- /** The remote MCP servers it may call, for a harness that has its own MCP client. */
137
- mcp?: SessionMcp;
138
161
  context: "fresh" | "fork";
162
+ /** The host's one verdict on whether the run's catalog tools are deferred (tool-deferral.ts defersCatalog, and both
163
+ * tools_search and tools_call allowed). A harness with a tool search of its own (`ownToolSearch`) turns it on exactly
164
+ * when this is true; absent, it decides by the names alone. */
165
+ deferCatalog?: boolean;
139
166
  tier?: NodeRequest["tier"];
140
167
  effort?: NodeRequest["effort"];
141
168
  thinking?: NodeRequest["thinking"];
@@ -180,7 +207,7 @@ export interface ModelRequest {
180
207
  * host's own request beside the harness's (`host`). */
181
208
  side?: true;
182
209
  /** On the session's model but no answer of the turn (a title, a summary, a child's request): booked as any request, but
183
- * never the session's previous request for the cap's expected pricing, read or replaced. */
210
+ * never one of the session's recent requests for the cap's expected pricing, read or kept. */
184
211
  unanswered?: true;
185
212
  /** It carries the host's note (ModelPort.note) in its body: the note is delivered once this request is admitted.
186
213
  * `inputTokensMaxWithoutNote`: its input measured as its client sent it, before the note was placed. */
@@ -305,6 +332,9 @@ export interface GateCall {
305
332
  /** The call runs again after an earlier attempt whose start the log holds (a replay-safe call a crash cut): that
306
333
  * attempt may have been sent, so a refusal never says nothing was. */
307
334
  readonly replayed?: true;
335
+ /** A call a running tool made (NestedCalls: a script's, tools_call's), part of a call already let through: the cap's
336
+ * wrap-up never refuses one, so a call in flight is never cut short, as pi's nested call is not. */
337
+ readonly nested?: true;
308
338
  }
309
339
  /** The host's answer before a call's intent: run it, refuse it in these words, or park the run on it. */
310
340
  export type GateAnswer = "allow" | {
@@ -445,8 +475,6 @@ export interface AdapterFacts {
445
475
  readonly recoversCutAnswers?: number;
446
476
  /** What one run of it holds in memory, in MiB: the host admits runs by it. */
447
477
  readonly runMib: number;
448
- /** Whether it binds a session's remote MCP servers (its own MCP client, at the session's gateway). */
449
- readonly mcp: boolean;
450
478
  /** The thinking levels it takes, lowest first: a run's level above its highest runs at that highest. */
451
479
  readonly thinking: readonly ("low" | "medium" | "high" | "xhigh" | "max")[];
452
480
  /** Its own web search, when the provider runs it: `native`, the provider's search through the session's proxy (its
@@ -455,6 +483,12 @@ export interface AdapterFacts {
455
483
  readonly webSearch?: "native" | "live";
456
484
  /** Its model is its own, chosen on its own wire's settings, never the host's default for the other harnesses. */
457
485
  readonly ownModel: boolean;
486
+ /** It runs the model's scripts itself (Codex's code mode, its nested calls the host's tools): the host offers no
487
+ * `codemode` of its own beside it. Absent: the host's codemode is offered. */
488
+ readonly ownCodemode?: true;
489
+ /** It defers a run's MCP tools behind a tool search of its own (Claude Code's ToolSearch), so the host offers no
490
+ * `tools_search` or `tools_call` beside it. Absent: the host's are offered when a run's catalog tools are deferred. */
491
+ readonly ownToolSearch?: true;
458
492
  /** The model as the harness names it (Anthropic's id has no dot). */
459
493
  normalizeModel(model: {
460
494
  provider: string;
@@ -473,9 +507,9 @@ export interface AdapterFacts {
473
507
  pins: string;
474
508
  };
475
509
  };
476
- /** The problems its own MCP client has with a tool's input schema (`tool` as it names it, `mcp__<server>__<tool>`):
477
- * shapes it drops or retypes, measured on its pinned build, so a grant of that tool would offer the model another
478
- * tool than the one granted. None: its client takes any schema the kernel's check does. */
510
+ /** The problems it has with a host tool's input schema (`tool` by its name, a run's MCP tool's `mcp__<server>__<tool>`):
511
+ * shapes it drops or retypes, measured on its pinned build, so a grant of an MCP tool would offer the model another
512
+ * tool than the one granted. None: it takes any schema the kernel's check does. */
479
513
  schemaProblems?(tool: string, schema: Record<string, unknown>): string[];
480
514
  /** A name its client calls a session's MCP tool by beside `mcp__<server>__<tool>` (OpenCode's `<server>_<tool>`). */
481
515
  readonly toolAlias?: RegExp;
@@ -503,20 +537,15 @@ export interface SessionPort {
503
537
  /** The API the proxy serves: Anthropic's Messages (claude-agent) or OpenAI's Responses (codex, opencode). */
504
538
  api: "anthropic-messages" | "openai-responses";
505
539
  }
506
- export interface AdapterCapabilities {
507
- /** Its harness's own MCP client, when it has one: it calls `spec.mcp`'s servers at the session proxy's `/mcp/<server>`,
508
- * which the kernel's model proxy mounts from the session's MCP and this fact (ModelProxyOptions.mcp). */
509
- mcpClient?: McpClient;
510
- }
511
- /** A harness's own MCP client, as its adapter declares it: the `_meta` key of a `tools/call` that carries the harness's
512
- * own id for the call (Claude Code's `claudecode/toolUseId`, Codex's `callId`), the id its timeline and gate know the
513
- * call by. The route reads that key and no other. */
514
- export interface McpClient {
515
- callIdMeta: string;
516
- }
517
540
  export interface AgentAdapter {
518
541
  readonly id: string;
519
- capabilities(): AdapterCapabilities;
542
+ /** Tools the harness runs itself beside the session's host tools (pi's subagent tool, its browser's): offered to the
543
+ * model as the host tools are, so the host's tools_search lists them and a nested call reaches one by its name. */
544
+ readonly ownTools?: readonly {
545
+ readonly name: string;
546
+ readonly description: string;
547
+ readonly inputSchema: Record<string, unknown>;
548
+ }[];
520
549
  /** Problems with a session before anything is spent; an empty list opens it. */
521
550
  check(spec: SessionSpec): string[];
522
551
  /** Opens the session, restoring it from `io.writer` when its key has records. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-kernel",
3
- "version": "0.1.0-beta.37",
3
+ "version": "0.1.0-beta.38",
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",
@@ -60,7 +60,7 @@
60
60
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
61
61
  },
62
62
  "dependencies": {
63
- "@parcha/agentrun-dsl": "0.1.0-beta.37",
63
+ "@parcha/agentrun-dsl": "0.1.0-beta.38",
64
64
  "ajv": "8.18.0",
65
65
  "typebox": "1.3.27"
66
66
  },
@@ -1,14 +0,0 @@
1
- import type { IncomingMessage, ServerResponse } from "node:http";
2
- import type { SessionMcp } from "../types.js";
3
- /** The protocol revisions answered, newest first: a client asking for another gets the newest. */
4
- export declare const MCP_ROUTE_VERSIONS: readonly string[];
5
- export interface McpRouteOptions {
6
- /** How often a call in flight sends a keepalive. Default 15 s. */
7
- keepaliveMs?: number;
8
- /** The `_meta` key of a `tools/call` that carries the harness's own id for the call (McpClient.callIdMeta); none, the
9
- * call has no id. */
10
- callIdMeta?: string;
11
- }
12
- /** The handler a model proxy mounts at `/mcp/<server>` (ModelProxyOptions.mcp). */
13
- export type McpHandler = (server: string, req: IncomingMessage, res: ServerResponse) => Promise<void>;
14
- export declare function mcpRoute(mcp: SessionMcp, options?: McpRouteOptions): McpHandler;
@@ -1,125 +0,0 @@
1
- import { parseStrict } from "./proxy.js";
2
- /** The protocol revisions answered, newest first: a client asking for another gets the newest. */
3
- export const MCP_ROUTE_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"];
4
- const MAX_BODY = 4 * 1024 * 1024;
5
- const KEEPALIVE_MS = 15_000;
6
- const isPlain = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7
- const isId = (v) => typeof v === "string" || (typeof v === "number" && Number.isSafeInteger(v));
8
- export function mcpRoute(mcp, options = {}) {
9
- const keepaliveMs = options.keepaliveMs ?? KEEPALIVE_MS;
10
- const servers = new Map(mcp.servers.map((server) => [server.name, server]));
11
- /** Calls in flight, by server and JSON-RPC id. */
12
- const running = new Map();
13
- const keyOf = (server, id) => `${server}\0${typeof id}:${id}`;
14
- const json = (res, status, body) => {
15
- res.writeHead(status, body === undefined ? { "content-length": "0" } : { "content-type": "application/json" });
16
- res.end(body === undefined ? undefined : JSON.stringify(body));
17
- };
18
- const failure = (id, code, message) => ({ jsonrpc: "2.0", id, error: { code, message } });
19
- return async (server, req, res) => {
20
- const served = servers.get(server);
21
- if (!served)
22
- return json(res, 404, failure(null, -32601, `this session has no MCP server ${server}`));
23
- if (req.method !== "POST") {
24
- res.writeHead(405, { allow: "POST", "content-length": "0" });
25
- return void res.end();
26
- }
27
- const chunks = [];
28
- let size = 0;
29
- for await (const chunk of req) {
30
- size += chunk.length;
31
- if (size > MAX_BODY)
32
- return json(res, 413, failure(null, -32600, "the request is too large"));
33
- chunks.push(chunk);
34
- }
35
- let message;
36
- try {
37
- const parsed = parseStrict(Buffer.concat(chunks).toString("utf8"));
38
- if (!isPlain(parsed))
39
- return json(res, 400, failure(null, -32600, "one JSON-RPC message per request; no batches"));
40
- message = parsed;
41
- }
42
- catch {
43
- return json(res, 400, failure(null, -32700, "the body is not JSON"));
44
- }
45
- const params = isPlain(message.params) ? message.params : {};
46
- // A notification, or the client's answer to a request: nothing to say back.
47
- if (typeof message.method !== "string" || message.id === undefined) {
48
- if (message.method === "notifications/cancelled" && isId(params.requestId))
49
- running.get(keyOf(server, params.requestId))?.abort();
50
- return json(res, 202);
51
- }
52
- if (!isId(message.id))
53
- return json(res, 400, failure(null, -32600, "the request's id must be a string or an integer"));
54
- const id = message.id;
55
- const answer = (result) => json(res, 200, { jsonrpc: "2.0", id, result });
56
- switch (message.method) {
57
- case "initialize": {
58
- const asked = params.protocolVersion;
59
- const protocolVersion = typeof asked === "string" && MCP_ROUTE_VERSIONS.includes(asked) ? asked : MCP_ROUTE_VERSIONS[0];
60
- return answer({ protocolVersion, capabilities: { tools: {} }, serverInfo: { name: `agentrun-${server}`, version: "1.0.0" } });
61
- }
62
- case "ping":
63
- return answer({});
64
- case "tools/list":
65
- return answer({ tools: served.tools.map((tool) => ({ name: tool.name, ...(tool.title ? { title: tool.title } : {}), description: tool.description ?? "", inputSchema: tool.inputSchema, ...(tool.annotations ? { annotations: tool.annotations } : {}) })) });
66
- case "tools/call":
67
- return call(server, id, params, req, res);
68
- default:
69
- return json(res, 200, failure(id, -32601, `${String(message.method).slice(0, 64)} is not a method this server answers`));
70
- }
71
- };
72
- async function call(server, id, params, req, res) {
73
- const meta = isPlain(params._meta) ? params._meta : {};
74
- const progressToken = isId(meta.progressToken) ? meta.progressToken : undefined;
75
- // The harness's own id for the call, under the key its adapter declared (McpClient.callIdMeta), and no other.
76
- const own = options.callIdMeta !== undefined && Object.hasOwn(meta, options.callIdMeta) ? meta[options.callIdMeta] : undefined;
77
- const callId = typeof own === "string" ? own : undefined;
78
- const stream = String(req.headers.accept ?? "").includes("text/event-stream");
79
- const controller = new AbortController();
80
- const key = keyOf(server, id);
81
- running.set(key, controller);
82
- // A client gone before the answer: its call is aborted, upstream too.
83
- res.once("close", () => { if (!res.writableFinished)
84
- controller.abort(); });
85
- const send = (body) => res.write(`event: message\ndata: ${JSON.stringify(body)}\n\n`);
86
- let timer;
87
- if (stream) {
88
- res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
89
- res.flushHeaders();
90
- let beat = 0;
91
- timer = setInterval(() => {
92
- beat += 1;
93
- if (progressToken === undefined)
94
- res.write(": keepalive\n\n");
95
- else
96
- send({ jsonrpc: "2.0", method: "notifications/progress", params: { progressToken, progress: beat } });
97
- }, keepaliveMs);
98
- }
99
- let result;
100
- try {
101
- const name = params.name;
102
- const args = isPlain(params.arguments) ? params.arguments : {};
103
- const granted = typeof name === "string" && servers.get(server).tools.some((tool) => tool.name === name);
104
- result = granted
105
- // The door calls the session's MCP (serve's gateway.call); its target is the tool plane's one invoke() (fix 2).
106
- ? await mcp.call(server, name, args, { signal: controller.signal, ...(callId ? { callId } : {}) })
107
- : { content: [{ type: "text", text: `${String(name).slice(0, 64)} is not a tool of the MCP server ${server} in this session.` }], isError: true };
108
- }
109
- catch (error) {
110
- result = { content: [{ type: "text", text: `The MCP server ${server}'s call failed: ${String(error?.message ?? error).slice(0, 300)}` }], isError: true };
111
- }
112
- finally {
113
- clearInterval(timer);
114
- running.delete(key);
115
- }
116
- if (res.destroyed)
117
- return;
118
- // What the client reads of the answer: its content, and whether it failed (never the host's `parked`).
119
- const body = { jsonrpc: "2.0", id, result: { content: result.content, ...(result.isError ? { isError: true } : {}) } };
120
- if (!stream)
121
- return json(res, 200, body);
122
- send(body);
123
- res.end();
124
- }
125
- }