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

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 (45) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +0 -7
  3. package/dist/host/box.d.ts +0 -14
  4. package/dist/host/index.d.ts +4 -4
  5. package/dist/host/index.js +2 -2
  6. package/dist/host/overhead.d.ts +75 -4
  7. package/dist/host/overhead.js +220 -10
  8. package/dist/host/proxy.d.ts +40 -4
  9. package/dist/host/proxy.js +87 -3
  10. package/dist/index.d.ts +0 -2
  11. package/dist/index.js +0 -1
  12. package/dist/kernel/cap/index.d.ts +1 -1
  13. package/dist/kernel/cap/index.js +1 -1
  14. package/dist/kernel/cap/port.d.ts +3 -2
  15. package/dist/kernel/cap/port.js +2 -2
  16. package/dist/kernel/cap/price.js +5 -2
  17. package/dist/kernel/cap/run-cap.d.ts +2 -2
  18. package/dist/kernel/cap/run-cap.js +1 -1
  19. package/dist/kernel/cap/types.d.ts +7 -0
  20. package/dist/kernel/cap/words.d.ts +3 -0
  21. package/dist/kernel/cap/words.js +5 -2
  22. package/dist/kernel/index.d.ts +0 -2
  23. package/dist/kernel/index.js +0 -1
  24. package/dist/kernel/registry/index.d.ts +1 -1
  25. package/dist/kernel/registry/index.js +1 -1
  26. package/dist/kernel/registry/limits.d.ts +0 -1
  27. package/dist/kernel/registry/limits.js +0 -1
  28. package/dist/process/records.d.ts +0 -16
  29. package/dist/process/records.js +0 -41
  30. package/dist/process/settle.d.ts +1 -1
  31. package/dist/process/settle.js +2 -2
  32. package/dist/process/tools.d.ts +9 -0
  33. package/dist/process/tools.js +19 -6
  34. package/dist/process/zod.d.ts +0 -2
  35. package/dist/process/zod.js +0 -4
  36. package/dist/runner.d.ts +8 -0
  37. package/dist/runner.js +3 -3
  38. package/dist/testing.d.ts +17 -5
  39. package/dist/testing.js +72 -21
  40. package/dist/types.d.ts +15 -5
  41. package/package.json +3 -3
  42. package/dist/delegate.d.ts +0 -87
  43. package/dist/delegate.js +0 -143
  44. package/dist/kernel/follow-up.d.ts +0 -67
  45. package/dist/kernel/follow-up.js +0 -146
package/dist/testing.d.ts CHANGED
@@ -20,8 +20,7 @@ export declare function memorySessionStore(): SessionStore & {
20
20
  * this request still streams (after its first call's text, before that call), so two of its requests are in flight.
21
21
  * `sideFirst`: one admitted before this request, then `say` streamed before this request is admitted: text of the
22
22
  * session's (a resumed turn's, say) with no request of this process's own yet, and a side call's the only one open. The
23
- * side call is paid at `usd` with this request (at once, or once its `bookWhen` file exists). `resultWhen`: a call's
24
- * result is told (its tool_end) only once this file exists, as a harness still recording it would. */
23
+ * side call is paid at `usd` with this request (at once, or once its `bookWhen` file exists). */
25
24
  /** `onRefused: "next"`: a request its host refuses (its admission throws) is not the turn's end: the client goes on to its
26
25
  * next action, as a CLI whose request the proxy refused sends another. */
27
26
  export type FauxRequest = {
@@ -47,7 +46,6 @@ export type FauxRequest = {
47
46
  usd: number;
48
47
  say: string;
49
48
  };
50
- resultWhen?: string;
51
49
  };
52
50
  /** One model request of the faux harness, and what its reply does. */
53
51
  export type FauxAction = ({
@@ -108,11 +106,22 @@ export type FauxAction = ({
108
106
  | {
109
107
  cutBooked: true;
110
108
  usd?: number | null;
109
+ }
110
+ /** The model answers with this text through a route that never reaches the session's port (a CLI sending past its
111
+ * model proxy): its text shows, and nothing is admitted or booked. */
112
+ | {
113
+ unbooked: string;
111
114
  };
112
115
  /** `note`: a note its host had for the request (ModelPort.note, the spend cap's wrap-up), as a real adapter's model proxy
113
116
  * would add it to the body: filed with its text, for a test to see. */
117
+ /** `answered`: a request whose reply asks for calls came back (its `until` let go), so its calls are the model's to run.
118
+ * `said`: a call's own text (its `say`) was streamed, so a recovered turn never says it again. `unbooked`: an answer
119
+ * that booked no request (FauxAction `unbooked`), its script place kept. */
114
120
  export declare const FAUX_RECORDS: {
115
121
  readonly request: "faux.request";
122
+ readonly unbooked: "faux.unbooked";
123
+ readonly answered: "faux.answered";
124
+ readonly said: "faux.said";
116
125
  readonly user: "faux.user";
117
126
  readonly turn: "faux.turn";
118
127
  readonly turnEnd: "faux.turn_end";
@@ -121,8 +130,11 @@ export declare const FAUX_RECORDS: {
121
130
  readonly note: "faux.note";
122
131
  };
123
132
  export interface FauxOptions {
124
- /** The session's model replies, in order, by its spec: one action per paid request. */
125
- script: (spec: SessionSpec) => FauxAction[];
133
+ /** The session's model replies, in order, by its spec: one action per paid request. `cwd`: the session's working
134
+ * directory when its host gives one (SessionIO.cwd), which a real CLI builds its absolute paths from. */
135
+ script: (spec: SessionSpec, session: {
136
+ readonly cwd?: string;
137
+ }) => FauxAction[];
126
138
  /** Problems `check` reports for a spec. */
127
139
  refuse?: (spec: SessionSpec) => string[];
128
140
  /** How long `open` takes, ignoring the session's signal, as a slow harness start does (default 0). */
package/dist/testing.js CHANGED
@@ -1,10 +1,13 @@
1
1
  // Test kit: a session store in memory, and a scripted harness with no model and no network. The faux harness keeps its
2
2
  // own records in the store as a real adapter does (the requests it made, each tool call's intent and outcome, its turns),
3
3
  // so a later process resumes from them: a request already made is not made again, and a call a crash cut off is
4
- // answered interrupted, never run again.
4
+ // answered interrupted, never run again. Each call asks the host's gate first, as a real harness's tool bridge does
5
+ // (process/tools.ts askGate): a deny is the call's answer, and a park holds the turn; a recovered turn runs the calls its
6
+ // last request asked for that never started (a parked one), under their own ids, as a real CLI's resume does.
5
7
  import { SessionFenced } from "./errors.js";
6
8
  import { abortedOutcome, SessionHalt } from "./kernel/halt.js";
7
9
  import { startModelProxy } from "./host/proxy.js";
10
+ import { askGate } from "./process/tools.js";
8
11
  import { randomBytes } from "node:crypto";
9
12
  export { SCHEMA_CHECK_CASES } from "./schema-check-cases.js";
10
13
  /** The model proxy's own parts, for tests of a provider policy and of the proxy: the host API (./host) keeps only what a
@@ -38,7 +41,10 @@ export function memorySessionStore() {
38
41
  }
39
42
  /** `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
43
  * 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" };
44
+ /** `answered`: a request whose reply asks for calls came back (its `until` let go), so its calls are the model's to run.
45
+ * `said`: a call's own text (its `say`) was streamed, so a recovered turn never says it again. `unbooked`: an answer
46
+ * that booked no request (FauxAction `unbooked`), its script place kept. */
47
+ export const FAUX_RECORDS = { request: "faux.request", unbooked: "faux.unbooked", answered: "faux.answered", said: "faux.said", user: "faux.user", turn: "faux.turn", turnEnd: "faux.turn_end", call: "faux.call", result: "faux.result", note: "faux.note" };
42
48
  export function fauxAdapter(options) {
43
49
  const stats = { requests: 0, calls: [], opened: [], closed: [] };
44
50
  const adapter = {
@@ -55,16 +61,17 @@ export function fauxAdapter(options) {
55
61
  async open(spec, io) {
56
62
  if (options.openDelayMs)
57
63
  await new Promise((resolve) => setTimeout(resolve, options.openDelayMs));
58
- const script = options.script(spec);
64
+ const script = options.script(spec, io.cwd === undefined ? {} : { cwd: io.cwd });
59
65
  const records = await io.writer.read();
60
66
  // The session's model proxy, when the faux harness is given one: up for the session's life, its key never used here.
61
67
  const proxy = options.proxy ? await startModelProxy({ ...options.proxy.options, hooks: io.models }, randomBytes(32).toString("base64url")) : undefined;
62
68
  io.signal.addEventListener("abort", () => void proxy?.close(), { once: true });
63
69
  const append = (kind, data) => io.writer.append([{ kind, data }]);
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.
70
+ // The script's place: one past its last request's (each faux.request keeps its action's index, as each faux.unbooked
71
+ // does for an answer that booked none), never the count of them, since an action refused with `onRefused: "next"` is
72
+ // skipped with no record.
66
73
  let cursor = records.reduce((next, r) => {
67
- const index = r.kind === FAUX_RECORDS.request ? r.data?.index : undefined;
74
+ const index = r.kind === FAUX_RECORDS.request || r.kind === FAUX_RECORDS.unbooked ? r.data?.index : undefined;
68
75
  return typeof index === "number" && index + 1 > next ? index + 1 : next;
69
76
  }, 0);
70
77
  const turnsStarted = records.filter((r) => r.kind === FAUX_RECORDS.turn).length;
@@ -79,6 +86,23 @@ export function fauxAdapter(options) {
79
86
  await append(FAUX_RECORDS.result, { callId, interrupted: true });
80
87
  }
81
88
  const tools = new Map(spec.tools.map((tool) => [tool.name, tool]));
89
+ /** The calls an action asks for, under their ids: a response's several calls, one call, or a submission. */
90
+ const callsOf = (action, index) => !action ? [] : "calls" in action ? action.calls.map((c, n) => ({ name: c.call, args: c.args ?? {}, callId: `${spec.key}:${index}.${n}`, ...(c.say ? { say: c.say } : {}) }))
91
+ : "call" in action ? [{ name: action.call, args: action.args ?? {}, callId: `${spec.key}:${index}` }]
92
+ : "submit" in action ? [{ name: "submit", args: { value: action.submit }, callId: `${spec.key}:${index}` }] : [];
93
+ // The calls the session's last request asked for that never started (no intent, no answer): the gate parked them, or
94
+ // the process ended before they ran. A recovered turn runs them first, as a real CLI's resume runs the calls left
95
+ // dangling in its transcript; a turn settled or a new one sent leaves them. Only once that request was answered
96
+ // (FAUX_RECORDS.answered): one cut off before its reply came (held at its `until`) asked for nothing yet, so none of
97
+ // its calls runs on the recovery: the turn goes on with the script's next request, as a cut request's always has.
98
+ const begun = new Set(records.filter((r) => r.kind === FAUX_RECORDS.call || r.kind === FAUX_RECORDS.result).map((r) => r.data.callId));
99
+ const answered = new Set(records.filter((r) => r.kind === FAUX_RECORDS.answered).map((r) => r.data.index));
100
+ // Each keeps its own text (`say`) unless it was said already (FAUX_RECORDS.said: the call that parked said its text
101
+ // before its gate).
102
+ const saidAlready = new Set(records.filter((r) => r.kind === FAUX_RECORDS.said).map((r) => r.data.callId));
103
+ let dangling = state === "open_turn" && answered.has(cursor - 1)
104
+ ? callsOf(script[cursor - 1], cursor - 1).filter((call) => !begun.has(call.callId)).map(({ say, ...call }) => ({ ...call, ...(say && !saidAlready.has(call.callId) ? { say } : {}) }))
105
+ : [];
82
106
  /** What the session has been sent, as a model would be prompted with it. */
83
107
  const prompt = records.filter((r) => r.kind === FAUX_RECORDS.user).map((r) => r.data.text);
84
108
  let ending;
@@ -109,10 +133,37 @@ export function fauxAdapter(options) {
109
133
  else
110
134
  signal.addEventListener("abort", () => reject(signal.reason), { once: true });
111
135
  });
136
+ /** One call of the model's: the host's gate first, before anything of it is written (a deny is its answer, in the
137
+ * gate's words, recorded so it is never asked again; a park holds the turn until it is stopped), then its intent,
138
+ * the tool, and its outcome. */
139
+ const runCall = async (name, args, callId, signal) => {
140
+ const tool = tools.get(name);
141
+ const refused = tool && io.gate ? await askGate((call) => io.gate(call), { callId, tool: name, args: (args ?? {}) }, signal) : undefined;
142
+ if (refused)
143
+ return void (await append(FAUX_RECORDS.result, { callId, isError: true, refused: true }));
144
+ await append(FAUX_RECORDS.call, { callId, name });
145
+ io.onEvent({ type: "tool_start", callId, name, args });
146
+ const result = tool ? await tool.call(args, { callId, signal }).catch((error) => ({ text: error.message, isError: true })) : { text: `unknown tool ${name}`, isError: true };
147
+ if (tool)
148
+ stats.calls.push(name);
149
+ await append(FAUX_RECORDS.result, { callId, isError: result.isError === true });
150
+ io.onEvent({ type: "tool_end", callId, name, isError: result.isError === true });
151
+ };
152
+ /** A call's own text, streamed before the call, then noted said (FAUX_RECORDS.said), so a recovered turn says it once. */
153
+ const saying = async (callId, say) => {
154
+ io.onEvent({ type: "text", delta: say });
155
+ await append(FAUX_RECORDS.said, { callId });
156
+ };
112
157
  /** The turn's model loop: one scripted action per paid request, until one ends the turn. */
113
158
  const run = async () => {
114
159
  const signal = AbortSignal.any([io.signal, (turnSignal = new AbortController()).signal]);
115
160
  try {
161
+ // A recovered turn: the calls its last request left dangling run first, then the model goes on.
162
+ for (const { name, args, callId, say } of dangling.splice(0)) {
163
+ if (say)
164
+ await saying(callId, say);
165
+ await runCall(name, args, callId, signal);
166
+ }
116
167
  for (;;) {
117
168
  const action = script[cursor];
118
169
  if (!action)
@@ -123,6 +174,13 @@ export function fauxAdapter(options) {
123
174
  turnSignal.abort(new Error(action.halt));
124
175
  return await hang(signal);
125
176
  }
177
+ if ("unbooked" in action) {
178
+ // Its place kept in a record of its own (no faux.request: no model request was booked), so a session opened
179
+ // again goes on past it, never answers it twice.
180
+ await append(FAUX_RECORDS.unbooked, { index: cursor++ });
181
+ io.onEvent({ type: "text", delta: action.unbooked });
182
+ continue;
183
+ }
126
184
  // Measured as a real adapter's proxy measures its body: the prompt's UTF-8 bytes, with nothing a provider adds.
127
185
  const measured = "inputTokensMax" in action && typeof action.inputTokensMax === "number" ? action.inputTokensMax : Buffer.byteLength(JSON.stringify({ system: spec.system, user: prompt }), "utf8");
128
186
  // On the session's model: the proxy's, when it has one (the host's own requests go there on that model too).
@@ -191,6 +249,9 @@ export function fauxAdapter(options) {
191
249
  // Held in flight, admitted and not answered, until the file it waits for exists (or the turn is stopped).
192
250
  if ("until" in action && typeof action.until === "string")
193
251
  await untilExists(action.until, signal);
252
+ // Its reply is in: the calls it asks for are the model's now, and a recovered turn runs any left unstarted.
253
+ if (callsOf(action, index).length)
254
+ await append(FAUX_RECORDS.answered, { index });
194
255
  const tokens = "tokens" in action && action.tokens ? action.tokens : { input: 10, output: 5 };
195
256
  const usd = action.usd === undefined ? 0.001 : action.usd;
196
257
  const book = () => io.models.afterRequest({ ...tokens, usd }, ticket || undefined, { end: "answered", usd });
@@ -204,27 +265,15 @@ export function fauxAdapter(options) {
204
265
  else if ("end" in action)
205
266
  return await end(action.turn ?? "completed");
206
267
  else {
207
- const asked = "calls" in action ? action.calls.map((c) => ({ name: c.call, args: c.args ?? {}, ...(c.say ? { say: c.say } : {}) }))
208
- : [{ name: "call" in action ? action.call : "submit", args: "call" in action ? action.args ?? {} : { value: action.submit } }];
209
- for (const [n, { name, args, say }] of asked.entries()) {
268
+ for (const [n, { name, args, callId, say }] of callsOf(action, index).entries()) {
210
269
  if (say)
211
- io.onEvent({ type: "text", delta: say });
270
+ await saying(callId, say);
212
271
  // A side call (a title, a summary) admitted and answered while this request still streams: two in flight.
213
272
  if (n === 0 && "sideDuring" in action && action.sideDuring) {
214
273
  const side = await io.models.beforeRequest({ model: "faux-small", side: true, inputTokensMax: 100 });
215
274
  await io.models.afterRequest({ input: 10, output: 5, usd: action.sideDuring.usd }, side || undefined);
216
275
  }
217
- const callId = "calls" in action ? `${spec.key}:${index}.${n}` : `${spec.key}:${index}`;
218
- const tool = tools.get(name);
219
- await append(FAUX_RECORDS.call, { callId, name });
220
- io.onEvent({ type: "tool_start", callId, name, args });
221
- const result = tool ? await tool.call(args, { callId, signal }).catch((error) => ({ text: error.message, isError: true })) : { text: `unknown tool ${name}`, isError: true };
222
- if (tool)
223
- stats.calls.push(name);
224
- if ("resultWhen" in action && typeof action.resultWhen === "string")
225
- await untilExists(action.resultWhen, signal);
226
- await append(FAUX_RECORDS.result, { callId, isError: result.isError === true });
227
- io.onEvent({ type: "tool_end", callId, name, isError: result.isError === true });
276
+ await runCall(name, args, callId, signal);
228
277
  }
229
278
  if (bookAfter)
230
279
  await book();
@@ -252,6 +301,7 @@ export function fauxAdapter(options) {
252
301
  get state() { return state; },
253
302
  async send(text) {
254
303
  state = "idle";
304
+ dangling = [];
255
305
  await append(FAUX_RECORDS.user, { text });
256
306
  prompt.push(text);
257
307
  await append(FAUX_RECORDS.turn, { n: turnsStarted + 1 });
@@ -265,6 +315,7 @@ export function fauxAdapter(options) {
265
315
  throw new Error("faux: there is no turn to settle");
266
316
  await append(FAUX_RECORDS.turnEnd, { status: abortedOutcome(AbortSignal.abort(new SessionHalt("interrupted"))).status });
267
317
  state = "idle";
318
+ dangling = [];
268
319
  },
269
320
  turnEnd: () => ending ? ending.promise : Promise.resolve({ status: "completed" }),
270
321
  async interrupt() { turnSignal?.abort(new SessionHalt("interrupted")); },
package/dist/types.d.ts CHANGED
@@ -145,6 +145,8 @@ export interface ModelRequest {
145
145
  /** The most input tokens the request can be billed for (the model proxy's `inputTokensMaxOf`: the body's UTF-8 bytes
146
146
  * plus what the provider adds), undefined when it was not measured. */
147
147
  inputTokensMax?: number;
148
+ /** Its `inputTokensMax` is its provider's count, not its bytes (ProxyRequest.inputTokensCounted). */
149
+ inputTokensCounted?: true;
148
150
  /** The most output tokens the request asks for, when its body says (the proxy's policy reads it). */
149
151
  outputTokensAsked?: number;
150
152
  /** The least output it may be limited to and still answer: its answer's 1,024 tokens, plus the least thinking its
@@ -184,6 +186,10 @@ export interface ModelRequest {
184
186
  * the proxy minted for this label: ModelProxy.sideKey): a learned workflow's model node, say. The harness's own
185
187
  * requests carry none, and it cannot send one that does: it holds only the session's key. */
186
188
  host?: string;
189
+ /** Which of the session's routes it came by, when the session has more than one (ModelProxyOptions.route: a proxy beside
190
+ * the session's, for a model of another tier): the host prices it by its model and this route, so one model id two
191
+ * routes price apart is held at the price its route books it at. Absent: the session's own route. */
192
+ route?: string;
187
193
  }
188
194
  /** What a paid request cost, once it completed. */
189
195
  export interface ModelUsage {
@@ -283,6 +289,9 @@ export interface GateCall {
283
289
  readonly callId: string;
284
290
  readonly tool: string;
285
291
  readonly args: Record<string, unknown>;
292
+ /** The call runs again after an earlier attempt whose start the log holds (a replay-safe call a crash cut): that
293
+ * attempt may have been sent, so a refusal never says nothing was. */
294
+ readonly replayed?: true;
286
295
  }
287
296
  /** The host's answer before a call's intent: run it, refuse it in these words, or park the run on it. */
288
297
  export type GateAnswer = "allow" | {
@@ -357,9 +366,8 @@ export interface AdapterSession {
357
366
  recover(): Promise<void>;
358
367
  /** Record the open turn as ended, interrupted, and send nothing: the turn is not to be resumed (a person stopped it, and
359
368
  * an interrupt writes no end in the session). Only when `state` is `open_turn`; the session is `idle` after, here and
360
- * when a later process opens it, and the next `send` is a turn of its own. A follow-up closes a cut turn the same way
361
- * (kernel/follow-up.ts, FollowUpTarget.settleOpenTurn), naming its own prompt (`opening`): that one is withdrawn and
362
- * never carried, and the rest is left as it is. */
369
+ * when a later process opens it, and the next `send` is a turn of its own. A host that closes a cut turn of its own
370
+ * prompt names it (`opening`): that one is withdrawn and never carried, and the rest is left as it is. */
363
371
  settleOpenTurn(options?: {
364
372
  opening?: string;
365
373
  }): Promise<void>;
@@ -393,8 +401,10 @@ export interface AdapterSession {
393
401
  /** The session's own model route, for a request the host sends beside the harness's own (a learned workflow's model
394
402
  * node): its model proxy's address with a side key minted for `label` (ModelProxy.sideKey), the model its policy
395
403
  * takes and the API it speaks. Undefined while no proxy is up (no turn has attached one yet). Every model request of
396
- * a session goes through that one proxy: the same policy, origin, credential, price and booking. */
397
- port?(label: string): SessionPort | undefined;
404
+ * a session goes through that one proxy: the same policy, origin, credential, price and booking. `tier`: the run's
405
+ * model of that tier instead (a learned workflow's node of a tier), on a proxy of its own beside the session's, with
406
+ * that model's origin, credential and price and the session's booking; undefined when the session has none for it. */
407
+ port?(label: string, tier?: string): SessionPort | undefined;
398
408
  }
399
409
  /** The API a harness's model proxy speaks: what its provider, its keys and its catalog follow from. */
400
410
  export type Wire = "anthropic-messages" | "openai-responses";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-kernel",
3
- "version": "0.1.0-beta.34",
3
+ "version": "0.1.0-beta.36",
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": ">=24.11.0"
16
+ "node": ">=24.22.3"
17
17
  },
18
18
  "main": "./dist/index.js",
19
19
  "types": "./dist/index.d.ts",
@@ -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.34",
63
+ "@parcha/agentrun-dsl": "0.1.0-beta.36",
64
64
  "ajv": "8.18.0",
65
65
  "typebox": "1.3.27"
66
66
  },
@@ -1,87 +0,0 @@
1
- import { type BeforeRequest } from "./runner.js";
2
- import type { AgentAdapter, HarnessEvent, HostTool, NodeRequest, SessionStore } from "./types.js";
3
- /** The tool's name, as the lead calls it. */
4
- export declare const DELEGATE_TOOL = "delegate";
5
- /** What every delegate answers: its finding, the sources it rests on, and what it could not settle. */
6
- export declare const DELEGATE_RESULT_SCHEMA: Readonly<{
7
- type: "object";
8
- properties: {
9
- answer: {
10
- type: string;
11
- };
12
- citations: {
13
- type: string;
14
- items: {
15
- type: string;
16
- properties: {
17
- url: {
18
- type: string;
19
- };
20
- title: {
21
- type: string;
22
- };
23
- quote: {
24
- type: string;
25
- };
26
- };
27
- required: string[];
28
- additionalProperties: boolean;
29
- };
30
- };
31
- gaps: {
32
- type: string;
33
- items: {
34
- type: string;
35
- };
36
- };
37
- };
38
- required: string[];
39
- additionalProperties: false;
40
- }>;
41
- /** One named sub-agent, as the host defines it. */
42
- export interface DelegateAgent {
43
- /** What the lead is told this agent is for. */
44
- description: string;
45
- /** The child's system prompt, verbatim. */
46
- system: string;
47
- /** The lead's tools this agent gets, by name: a subset of `DelegateOptions.tools`. */
48
- tools: readonly string[];
49
- /** The models-table tier the child runs on (the node's `tier`). */
50
- tier?: NodeRequest["tier"];
51
- /** The share of the lead's remaining time the child may take, in (0, 1] (default 1). */
52
- deadlineShare?: number;
53
- }
54
- /** A child's event: the runner's event, with the delegate call it belongs to. */
55
- export type DelegateEvent = HarnessEvent & {
56
- delegate: {
57
- agent: string;
58
- callId: string;
59
- parentKey: string;
60
- };
61
- };
62
- export interface DelegateOptions {
63
- /** The sub-agents by name (lowercase letters, digits and dashes). */
64
- agents: Readonly<Record<string, DelegateAgent>>;
65
- /** The lead's tools: each agent gets the ones it names, and no others. */
66
- tools: readonly HostTool[];
67
- /** The harness children run on, or one per agent (an agent's own skills, say). */
68
- adapter: AgentAdapter | ((agent: string) => AgentAdapter);
69
- /** The run's store: each child keeps its session there, under its own key. */
70
- store: SessionStore;
71
- /** The lead's session key: a child's is `<parentKey>/delegate:<call id>`. */
72
- parentKey: string;
73
- /** The lead's check before each paid request, so one budget covers the lead and its children. */
74
- beforeRequest?: BeforeRequest;
75
- /** Every child event, with the delegate call it belongs to. */
76
- onEvent?: (event: DelegateEvent) => void;
77
- /** The lead's deadline (epoch ms), if it has one: a child's is this, or its agent's share of the time left. */
78
- deadlineAt?: () => number | undefined;
79
- /** A child's limit when the lead has no deadline (absent: the runner's own default, 120 s; null for none). */
80
- timeoutMs?: number | null;
81
- /** The most paid requests a child makes per attempt (the runner's default when absent). */
82
- maxTurns?: number | null;
83
- }
84
- /** What is wrong with the delegate's definition, or nothing: checked when the tool is made. */
85
- export declare function delegateProblems(options: Pick<DelegateOptions, "agents" | "tools">): string[];
86
- /** The `delegate` host tool: refuses a bad definition when made. */
87
- export declare function delegateTool(options: DelegateOptions): HostTool;
package/dist/delegate.js DELETED
@@ -1,143 +0,0 @@
1
- // A lead hands one task to a named sub-agent, which runs as a child node on the same kernel. Written for AgentRun.
2
- //
3
- // `delegateTool` is an ordinary host tool, `delegate({ agent, task, context? })`, for a lead on any harness. Each call runs
4
- // one child: an `agent` node, through `createHarnessRunner`, with the agent's own system prompt (as the host gave it) and
5
- // its own subset of the lead's tools, answering in a fixed shape (`DELEGATE_RESULT_SCHEMA`). The child is durable under its
6
- // own key, `step:<the lead's key>/delegate:<call id>`, so the call is replay-safe: a delegate that finished answers again
7
- // from its recorded result, and one a crash cut off resumes from its own store (its finished paid requests are never sent
8
- // again). Its paid requests are booked under that key and go through the lead's `beforeRequest`, so one budget covers the
9
- // lead and every child; its deadline is the lead's, or the agent's share of what is left. Children run one at a time, and
10
- // a child has no delegate tool (depth 1).
11
- import { Mutex } from "./process/tools.js";
12
- import { createHarnessRunner, RUNNER_RECORDS, SUBMIT_TOOL } from "./runner.js";
13
- /** The tool's name, as the lead calls it. */
14
- export const DELEGATE_TOOL = "delegate";
15
- /** What every delegate answers: its finding, the sources it rests on, and what it could not settle. */
16
- export const DELEGATE_RESULT_SCHEMA = Object.freeze({
17
- type: "object",
18
- properties: {
19
- answer: { type: "string" },
20
- citations: {
21
- type: "array",
22
- items: { type: "object", properties: { url: { type: "string" }, title: { type: "string" }, quote: { type: "string" } }, required: ["url"], additionalProperties: false },
23
- },
24
- gaps: { type: "array", items: { type: "string" } },
25
- },
26
- required: ["answer", "citations"],
27
- additionalProperties: false,
28
- });
29
- const AGENT_NAME = /^[a-z][a-z0-9-]{0,63}$/;
30
- /** What is wrong with the delegate's definition, or nothing: checked when the tool is made. */
31
- export function delegateProblems(options) {
32
- const problems = [];
33
- const lead = new Set(options.tools.map((t) => t.name));
34
- const names = Object.keys(options.agents);
35
- if (names.length === 0)
36
- problems.push("no agents to delegate to");
37
- if (lead.has(DELEGATE_TOOL))
38
- problems.push(`the lead already has a tool named ${DELEGATE_TOOL}`);
39
- for (const name of names) {
40
- const agent = options.agents[name];
41
- if (!AGENT_NAME.test(name))
42
- problems.push(`the agent name ${JSON.stringify(name.slice(0, 80))} is not lowercase letters, digits and dashes`);
43
- if (typeof agent.system !== "string" || agent.system.length === 0)
44
- problems.push(`the agent ${name} has no system prompt`);
45
- const seen = new Set();
46
- for (const tool of agent.tools) {
47
- if (seen.has(tool))
48
- problems.push(`the agent ${name} names the tool ${tool} twice`);
49
- seen.add(tool);
50
- if (tool === DELEGATE_TOOL)
51
- problems.push(`the agent ${name} may not delegate further (depth 1)`);
52
- else if (tool === SUBMIT_TOOL)
53
- problems.push(`the agent ${name} names ${SUBMIT_TOOL}, which the runner gives every child itself`);
54
- else if (!lead.has(tool))
55
- problems.push(`the agent ${name} names the tool ${tool}, which the lead does not have`);
56
- }
57
- const share = agent.deadlineShare;
58
- if (share !== undefined && !(share > 0 && share <= 1))
59
- problems.push(`the agent ${name}'s deadline share ${share} is not in (0, 1]`);
60
- }
61
- return problems;
62
- }
63
- /** The `delegate` host tool: refuses a bad definition when made. */
64
- export function delegateTool(options) {
65
- const problems = delegateProblems(options);
66
- if (problems.length)
67
- throw new Error(`agentrun-kernel: delegate: ${problems.join("; ")}`);
68
- const byName = new Map(options.tools.map((t) => [t.name, t]));
69
- const names = Object.keys(options.agents);
70
- // One child at a time, whatever the harness's own tool calls do.
71
- const serial = new Mutex();
72
- return {
73
- name: DELEGATE_TOOL,
74
- description: `Hand one task to a sub-agent, which works on it with its own tools and answers with its finding, its sources and its gaps. One at a time. The agents:\n${names.map((n) => `- ${n}: ${options.agents[n].description}`).join("\n")}`,
75
- inputSchema: {
76
- type: "object",
77
- properties: {
78
- agent: { type: "string", enum: names },
79
- task: { type: "string", description: "What the sub-agent is to find out or do, complete in itself." },
80
- context: { type: "string", description: "What it should know from your work so far." },
81
- },
82
- required: ["agent", "task"],
83
- additionalProperties: false,
84
- },
85
- // A child is durable under its own key: run again after a crash, it answers from its record or resumes its session.
86
- replay: "safe",
87
- call: (args, { callId, signal, sessionDir }) => serial.run(async () => {
88
- const { agent: name, task, context } = (args ?? {});
89
- // An own entry only: a name like `constructor` is not an agent.
90
- const agent = typeof name === "string" && Object.hasOwn(options.agents, name) ? options.agents[name] : undefined;
91
- if (!agent)
92
- return { text: `Not delegated: ${JSON.stringify(String(name).slice(0, 80))} is not one of the agents (${names.join(", ")}).`, isError: true };
93
- if (typeof task !== "string" || task.trim() === "")
94
- return { text: "Not delegated: give the task as text.", isError: true };
95
- const tag = { agent: name, callId, parentKey: options.parentKey };
96
- // The child's session: its step's id, so its records are the runner's under `step:<id>`.
97
- const sessionId = `${options.parentKey}/delegate:${callId}`;
98
- const deadlineAt = options.deadlineAt?.();
99
- const left = deadlineAt === undefined ? undefined : deadlineAt - Date.now();
100
- if (left !== undefined && left <= 0) {
101
- // A child that delivered before a crash answers from its record, deadline or not; only new work is refused. Read,
102
- // not opened: opening would fence the session for nothing.
103
- const saved = (await options.store.read(`step:${sessionId}`)).findLast((r) => r.kind === RUNNER_RECORDS.accepted);
104
- if (saved)
105
- return { text: JSON.stringify(saved.data.value) };
106
- return { text: "Not delegated: the lead has no time left.", isError: true };
107
- }
108
- const timeoutMs = left === undefined ? options.timeoutMs : Math.max(1, Math.floor(left * (agent.deadlineShare ?? 1)));
109
- const runNode = createHarnessRunner(typeof options.adapter === "function" ? options.adapter(name) : options.adapter, {
110
- store: options.store,
111
- tools: agent.tools.map((t) => byName.get(t)),
112
- signal,
113
- // The lead's runner's private directories, if it has them: the child's is its own, by its own key.
114
- ...(sessionDir ? { sessionDir } : {}),
115
- ...(timeoutMs === undefined ? {} : { timeoutMs }),
116
- ...(options.maxTurns === undefined ? {} : { maxTurns: options.maxTurns }),
117
- ...(options.beforeRequest ? { beforeRequest: options.beforeRequest } : {}),
118
- ...(options.onEvent ? { onEvent: (event) => options.onEvent({ ...event, delegate: tag }) } : {}),
119
- });
120
- try {
121
- const answer = await runNode({
122
- kind: "agent",
123
- label: `delegate:${name}`,
124
- system: [agent.system],
125
- user: typeof context === "string" && context.trim() ? `${task}\n\nContext from the lead:\n${context}` : task,
126
- schema: DELEGATE_RESULT_SCHEMA,
127
- tools: [...agent.tools],
128
- ...(agent.tier === undefined ? {} : { tier: agent.tier }),
129
- step: { sessionId, attempt: 0, earlierSessionIds: [] },
130
- });
131
- return { text: JSON.stringify(answer) };
132
- }
133
- catch (error) {
134
- // Stopped (the lead paused, the process is draining): not an answer. Rethrown, the lead's harness records the call
135
- // as interrupted and runs the same call id again on resume, which resumes this child. A child that failed on its
136
- // own is an answer the lead reads.
137
- if (signal?.aborted)
138
- throw signal.reason ?? error;
139
- return { text: `The delegate ${name} stopped without an answer: ${String(error?.message ?? error).slice(0, 400)}`, isError: true };
140
- }
141
- }),
142
- };
143
- }
@@ -1,67 +0,0 @@
1
- import type { SessionState as AdapterSessionState, SessionStore, TurnStatus } from "../types.js";
2
- import { foldSession } from "./drive.js";
3
- /** The effect's key in the follow-up's own session. */
4
- export declare const FOLLOW_UP_EFFECT = "follow-up";
5
- /** What a request the reserve refuses says, first. */
6
- export declare const FOLLOW_UP_BUDGET_REACHED = "follow_up_budget_reached";
7
- /** What a request asked for after the follow-up was cancelled says, first. */
8
- export declare const FOLLOW_UP_CANCELLED = "follow_up_cancelled";
9
- /** The follow-up's own session key, beside the session it follows up. */
10
- export declare const followUpKey: (session: string, name: string) => string;
11
- /** The session as a follow-up drives it: an adapter's session, and how a turn a crash cut off is closed unsent. */
12
- export interface FollowUpTarget {
13
- readonly state: AdapterSessionState;
14
- /** Send `text` as a new turn, its submission under `id`. */
15
- send(text: string, options?: {
16
- id?: string;
17
- }): Promise<void>;
18
- turnEnd(): Promise<{
19
- status: TurnStatus;
20
- error?: string;
21
- }>;
22
- /** Record the open turn as ended, interrupted, and send nothing. It withdraws only the submission it is named
23
- * (`opening`), while that is unplaced and the oldest pending. */
24
- settleOpenTurn(options?: {
25
- opening?: string;
26
- }): Promise<void>;
27
- /** Stop the turn in flight. */
28
- interrupt(): Promise<void>;
29
- }
30
- export interface FollowUpOptions {
31
- store: SessionStore;
32
- /** The key of the session it follows up. */
33
- session: string;
34
- /** The follow-up's name: one follow-up per name per session. */
35
- name: string;
36
- prompt: string;
37
- /** The most its paid requests may cost, in dollars, counted from its first request. */
38
- reserveUsd: number;
39
- /** A request's worst case, held for each request in flight and the one asked for. Required: a host with no worst case
40
- * passes 0, and the reserve may then be passed by the one request admitted last. */
41
- worstUsd: number;
42
- }
43
- export type FollowUpResult = {
44
- status: "done";
45
- } | {
46
- status: "interrupted";
47
- } | {
48
- status: "failed";
49
- error: string;
50
- };
51
- export interface FollowUp {
52
- readonly key: string;
53
- /** Ahead of the host's own check on each paid request: undefined outside the follow-up's turn. */
54
- beforeRequest(request: {
55
- spentUsd: number | null;
56
- inFlight: readonly unknown[];
57
- }): undefined | {
58
- refuse: string;
59
- };
60
- /** Sends the follow-up once, or answers from its record. */
61
- run(target: FollowUpTarget, signal: AbortSignal): Promise<FollowUpResult>;
62
- }
63
- export type FollowUpState = "none" | "running" | "done" | "interrupted" | "failed";
64
- /** The follow-up's state in its records, as written: `running` is one a process that died left without an outcome. A
65
- * host reads it before it resumes an open turn: a turn of a `running` or `interrupted` follow-up is settled instead. */
66
- export declare function followUpState(records: Parameters<typeof foldSession>[1]): FollowUpState;
67
- export declare function followUpOnce(options: FollowUpOptions): FollowUp;