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

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 (60) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +0 -7
  3. package/dist/host/box.d.ts +0 -14
  4. package/dist/host/index.d.ts +1 -1
  5. package/dist/host/proxy.d.ts +20 -4
  6. package/dist/host/proxy.js +67 -5
  7. package/dist/index.d.ts +1 -3
  8. package/dist/index.js +0 -1
  9. package/dist/kernel/cap/index.d.ts +3 -3
  10. package/dist/kernel/cap/index.js +3 -3
  11. package/dist/kernel/cap/port.js +6 -3
  12. package/dist/kernel/cap/price.d.ts +6 -0
  13. package/dist/kernel/cap/price.js +14 -0
  14. package/dist/kernel/cap/rule.d.ts +8 -0
  15. package/dist/kernel/cap/rule.js +9 -0
  16. package/dist/kernel/cap/types.d.ts +2 -0
  17. package/dist/kernel/cap/words.d.ts +3 -0
  18. package/dist/kernel/cap/words.js +4 -1
  19. package/dist/kernel/index.d.ts +0 -2
  20. package/dist/kernel/index.js +0 -1
  21. package/dist/kernel/registry/computer-surface.generated.d.ts +9 -0
  22. package/dist/kernel/registry/computer-surface.generated.js +611 -0
  23. package/dist/kernel/registry/computer.d.ts +14 -0
  24. package/dist/kernel/registry/computer.js +67 -0
  25. package/dist/kernel/registry/defs.d.ts +1 -4
  26. package/dist/kernel/registry/defs.js +1 -13
  27. package/dist/kernel/registry/handoff.js +4 -4
  28. package/dist/kernel/registry/hands.d.ts +22 -115
  29. package/dist/kernel/registry/hands.js +0 -2
  30. package/dist/kernel/registry/index.d.ts +5 -5
  31. package/dist/kernel/registry/index.js +6 -6
  32. package/dist/kernel/registry/limits.d.ts +0 -1
  33. package/dist/kernel/registry/limits.js +0 -1
  34. package/dist/kernel/registry/registry.d.ts +4 -5
  35. package/dist/kernel/registry/registry.js +27 -29
  36. package/dist/kernel/types.d.ts +2 -1
  37. package/dist/process/records.d.ts +0 -16
  38. package/dist/process/records.js +0 -41
  39. package/dist/process/settle.d.ts +1 -1
  40. package/dist/process/settle.js +2 -2
  41. package/dist/process/tools.d.ts +3 -1
  42. package/dist/process/tools.js +3 -3
  43. package/dist/process/zod.d.ts +0 -2
  44. package/dist/process/zod.js +0 -4
  45. package/dist/run-booking.d.ts +3 -0
  46. package/dist/run-booking.js +7 -0
  47. package/dist/runner.d.ts +21 -2
  48. package/dist/runner.js +27 -10
  49. package/dist/testing.d.ts +9 -4
  50. package/dist/testing.js +22 -16
  51. package/dist/types.d.ts +18 -4
  52. package/package.json +2 -2
  53. package/dist/delegate.d.ts +0 -87
  54. package/dist/delegate.js +0 -143
  55. package/dist/kernel/follow-up.d.ts +0 -67
  56. package/dist/kernel/follow-up.js +0 -146
  57. package/dist/kernel/registry/desktop.d.ts +0 -11
  58. package/dist/kernel/registry/desktop.js +0 -90
  59. package/dist/kernel/registry/phone.d.ts +0 -15
  60. package/dist/kernel/registry/phone.js +0 -135
@@ -75,12 +75,12 @@ export function toolBridge(ctx, tools, options = {}) {
75
75
  replay: tool.replay,
76
76
  input: args,
77
77
  }, (io) => tool.execute(args, hostToolIO(io, ctx, { signal: signal ? AbortSignal.any([signal, io.signal]) : io.signal })));
78
- // A tool answers in text, or in text with images (a screenshot): the images come back as recorded.
79
- const { text: whole, images } = typeof output === 'object' && output !== null ? output : { text: String(output), images: undefined };
78
+ // A tool answers in text, or in text with images (a screenshot) and its value: they come back as recorded.
79
+ const { text: whole, images, structured } = typeof output === 'object' && output !== null ? output : { text: String(output), images: undefined, structured: undefined };
80
80
  const { text, truncated } = boundResult(String(whole));
81
81
  if (fresh && live)
82
82
  ctx.live({ type: 'tool_end', name: tool.name, callId, result: text, ...(truncated ? { truncated } : {}) });
83
- return { text, isError: false, ...(images?.length ? { images } : {}), ...(truncated ? { truncated } : {}) };
83
+ return { text, isError: false, ...(images?.length ? { images } : {}), ...(structured !== undefined ? { structured } : {}), ...(truncated ? { truncated } : {}) };
84
84
  }
85
85
  catch (err) {
86
86
  if (err instanceof EffectFailure) {
@@ -25,8 +25,6 @@ export interface JsonSchemaObject {
25
25
  anyOf?: JsonSchemaObject[];
26
26
  nullable?: boolean;
27
27
  }
28
- /** A zod object for a JSON Schema object (extra properties allowed unless `additionalProperties: false`). */
29
- export declare function zodFromJsonSchema(schema: unknown, z: Z): ZodType;
30
28
  /** The raw shape (`{ key: zodType }`) of a JSON Schema object, for APIs that take a shape. */
31
29
  export declare function zodShapeFromJsonSchema(schema: unknown, z: Z): Record<string, ZodType>;
32
30
  export {};
@@ -13,10 +13,6 @@
13
13
  * `packages/harness-claude-code/src/bridge/json-schema-to-zod.ts`,
14
14
  * Apache-2.0); changed to take `z` as a parameter and to export the shape.
15
15
  */
16
- /** A zod object for a JSON Schema object (extra properties allowed unless `additionalProperties: false`). */
17
- export function zodFromJsonSchema(schema, z) {
18
- return toZodObject(isSchema(schema) ? schema : {}, z);
19
- }
20
16
  /** The raw shape (`{ key: zodType }`) of a JSON Schema object, for APIs that take a shape. */
21
17
  export function zodShapeFromJsonSchema(schema, z) {
22
18
  return toZodShape(isSchema(schema) ? schema : undefined, z);
@@ -4,6 +4,9 @@ import type { SessionRecord } from "./types.js";
4
4
  export interface RunSessions {
5
5
  keys(): readonly string[] | Promise<readonly string[]>;
6
6
  read(key: string): Promise<SessionRecord[]>;
7
+ /** What was spent on the run's behalf outside its sessions, as the host reads it at each admission (what ended at its
8
+ * cost, what is under way at the most it may take); null: unknown. None: nothing is. */
9
+ beside?(): Promise<number | null>;
7
10
  }
8
11
  /** `before`, asked about each request with the run's totals over `sessions` in place of its session's own. */
9
12
  export declare function runBooking(sessions: RunSessions, before: BeforeRequest): BeforeRequest;
@@ -6,6 +6,9 @@
6
6
  // answered (in flight in any session, in this process or a lost one) counts there at what its host held for it;
7
7
  // - `inFlight`: the requests this booking admitted that no record shows yet, each at what it was held at, so two
8
8
  // sessions asking at once never both take room only one of them fits.
9
+ // - what was spent beside its sessions on the run's behalf (`sessions.beside`: a run's learning, graded by runs of its
10
+ // own), read with them at each admission and added to `spentUsd`, so a run and what it pays for elsewhere never pass
11
+ // its cap together. Unknown (null) makes the run's spend unknown.
9
12
  // Admissions run one at a time across the run's sessions. The priced tools' charges and holds are not here: they are the
10
13
  // host's spentUsd and heldUsd hooks (beforeRequestOf), read beside these.
11
14
  import { sessionSpendOf } from "./runner.js";
@@ -29,6 +32,10 @@ export function runBooking(sessions, before) {
29
32
  if (!spend.openHolds.has(turn))
30
33
  recorded.add(idOf(key, turn));
31
34
  }
35
+ if (sessions.beside) {
36
+ const beside = await sessions.beside();
37
+ spentUsd = spentUsd === null || beside === null || !Number.isFinite(beside) ? null : spentUsd + beside;
38
+ }
32
39
  for (const id of [...admitted.keys()])
33
40
  if (recorded.has(id))
34
41
  admitted.delete(id);
package/dist/runner.d.ts CHANGED
@@ -41,6 +41,9 @@ export type BeforeRequest = (request: {
41
41
  /** The most input tokens this request can be billed for (the body's UTF-8 bytes plus what the provider adds, as the
42
42
  * model proxy measured it), undefined when it was not measured: a budget treats that input as unknown, never 0. */
43
43
  inputTokensMax?: number;
44
+ /** Its `inputTokensMax` is its provider's count, not its bytes (ModelRequest.inputTokensCounted): two bounds are compared
45
+ * (the cap's expected pricing) only when both were measured the same way. */
46
+ inputTokensCounted?: true;
44
47
  /** The most output tokens it asks for, and the least it may be limited to and still answer, as the model proxy read
45
48
  * them from its body (ModelRequest). */
46
49
  outputTokensAsked?: number;
@@ -64,6 +67,9 @@ export type BeforeRequest = (request: {
64
67
  };
65
68
  /** A side call (ModelRequest.side): on another model than the session's (a client's), or the host's own (`host`). */
66
69
  side?: true;
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. */
72
+ unanswered?: true;
67
73
  /** It carries the host's note (ModelRequest.noted), and its input measured without it (`inputTokensMaxWithoutNote`):
68
74
  * a host that admits it only without the note says so (Admission.withoutNote). */
69
75
  noted?: true;
@@ -108,6 +114,7 @@ export type InFlight = {
108
114
  inputTokensMax?: number;
109
115
  outputTokensMax?: number;
110
116
  holdUsd?: number;
117
+ boundUsd?: number;
111
118
  host?: string;
112
119
  route?: string;
113
120
  };
@@ -202,6 +209,8 @@ export interface ModelPortOptions {
202
209
  draining?: () => Error | undefined;
203
210
  /** A note the host has for the session's next main-model request, taken by the call (ModelPort.note). */
204
211
  note?: (model: string, request?: NoteRequest) => string | undefined;
212
+ /** A note given back by the request that took it, before its admission (ModelPort.noteReturned). */
213
+ noteReturned?: (note: string) => void;
205
214
  /** The port ends the attempt (the turn limit, the host's refusal, a cost it could not record): the error it throws. */
206
215
  stop?: (reason: "turn_limit" | "refused" | "model_error", message?: string, code?: string) => Error;
207
216
  }
@@ -213,6 +222,14 @@ export interface ModelBooking {
213
222
  turns(): number;
214
223
  /** What they cost; null once one's price is unknown. */
215
224
  spentUsd(): number | null;
225
+ /** What its host holds for the requests still in flight (admitted, not yet answered): `spentUsd` counts answered ones
226
+ * only, so a reader of the run's spend that a request overlapping another must see adds this. Null while one in flight
227
+ * has no hold (never under a cap, which refuses a request it cannot price): unknown, never read as 0. */
228
+ heldUsd(): number | null;
229
+ /** What a cache miss adds to those holds (Admission.boundUsd), the requests still in flight together: the run's tools stop
230
+ * on the holds plus this (the cap counts a request that never answers at both), so a reader that must warn no later
231
+ * adds it too. 0 with none in flight or none with a bound. */
232
+ boundUsd(): number;
216
233
  /** Books, once, each paid request a crash cut off (a `runner.request` with no `runner.turn`): a `runner.turn` marked
217
234
  * `cut` at an unknown price, and a `request_end` saying so. A booked request is answered, so this is idempotent.
218
235
  * Call it before the session sends anything. */
@@ -241,8 +258,10 @@ export declare function sessionSpendOf(records: readonly SessionRecord[]): {
241
258
  }[];
242
259
  cost: SessionCost;
243
260
  };
244
- /** Whether a request answered with no price of its own (bookRequest's rule `answered`, or `answered:<label>`, its usd
245
- * null): booked at its hold for the cap, its cost unknown. */
261
+ /** Whether a request ended with no price of its own (usd null) under a rule that books it at a figure of the host's: an
262
+ * answer with no cost (bookRequest's rule `answered`, or `answered:<label>`: its hold), or one our side stopped
263
+ * (`stopped`: what streamed, an estimate) or lost (`lost`, `lost:<label>`: its hold). Each counts for the cap at that
264
+ * figure, but as a cost it is unknown, never an estimate stored as a known charge (the provider may bill otherwise). */
246
265
  export declare const answeredUnpriced: (data: {
247
266
  usd?: unknown;
248
267
  rule?: unknown;
package/dist/runner.js CHANGED
@@ -88,6 +88,10 @@ export function sessionSpendOf(records) {
88
88
  if (r.kind !== RUNNER_RECORDS.turn)
89
89
  continue;
90
90
  const data = r.data;
91
+ // A request is booked once: a second runner.turn of a turn already answered (two bookings of one session that each
92
+ // read it open, a cut written twice) counts no money and no request again.
93
+ if (typeof data.turn === "number" && answered.has(data.turn))
94
+ continue;
91
95
  const turn = data.turn ?? turns.find((t) => !answered.has(t)) ?? 0;
92
96
  answered.add(turn);
93
97
  // The figure it was booked at (bookRequest), as written. A record from before that has none: a request cut off with
@@ -122,9 +126,11 @@ export function sessionSpendOf(records) {
122
126
  }
123
127
  return { turns, held, bounds, hosts, answered, openHolds, spentUsd, figures, cost: { usd: unpriced > 0 ? null : soFarUsd, soFarUsd, unpriced } };
124
128
  }
125
- /** Whether a request answered with no price of its own (bookRequest's rule `answered`, or `answered:<label>`, its usd
126
- * null): booked at its hold for the cap, its cost unknown. */
127
- export const answeredUnpriced = (data) => data.usd === null && typeof data.rule === "string" && (data.rule === "answered" || data.rule.startsWith("answered:"));
129
+ /** Whether a request ended with no price of its own (usd null) under a rule that books it at a figure of the host's: an
130
+ * answer with no cost (bookRequest's rule `answered`, or `answered:<label>`: its hold), or one our side stopped
131
+ * (`stopped`: what streamed, an estimate) or lost (`lost`, `lost:<label>`: its hold). Each counts for the cap at that
132
+ * figure, but as a cost it is unknown, never an estimate stored as a known charge (the provider may bill otherwise). */
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:"));
128
134
  /** Whether a request was booked lost (bookRequest's rule `lost`, or `lost:<label>`): billed or not, no cost came in. */
129
135
  const bookedLost = (rule) => typeof rule === "string" && (rule === "lost" || rule.startsWith("lost:"));
130
136
  function bookingFor(writer, options) {
@@ -179,7 +185,7 @@ function bookingFor(writer, options) {
179
185
  // A paid request whose cost couldn't be recorded stops the booking itself, whether or not the host gave it a stop.
180
186
  let failed;
181
187
  const end = (reason, message, code) => options.stop ? options.stop(reason, message, code) : new HarnessRunError(reason, turns, 0, { maxTurns: limit, ...(message === undefined ? {} : { message }), ...(code === undefined ? {} : { refusal: code }) });
182
- const admit = async ({ model, inputTokensMax: measured, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, noted, inputTokensMaxWithoutNote, host, route }) => {
188
+ const admit = async ({ model, inputTokensMax: measured, inputTokensCounted, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, unanswered, noted, inputTokensMaxWithoutNote, host, route }) => {
183
189
  let inputTokensMax = measured;
184
190
  const stopped = options.stopped?.(host === undefined ? {} : { host }) ?? failed;
185
191
  if (stopped)
@@ -189,8 +195,8 @@ function bookingFor(writer, options) {
189
195
  throw pausing;
190
196
  if (limit !== null && turns >= limit)
191
197
  throw end("turn_limit");
192
- const verdict = await options.beforeRequest?.({ ...node, model, turn: turns + 1, maxTurns: limit, ...(options.budgetUsd === undefined ? {} : { budgetUsd: options.budgetUsd }), spentUsd, inFlight: open.map((f) => ({ ...f })), inputTokensMax,
193
- ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }), ...(feeUsd === undefined ? {} : { feeUsd }), ...(paid ? { paid } : {}), ...(side ? { side } : {}), ...(noted ? { noted, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
198
+ const verdict = await options.beforeRequest?.({ ...node, model, turn: turns + 1, maxTurns: limit, ...(options.budgetUsd === undefined ? {} : { budgetUsd: options.budgetUsd }), spentUsd, inFlight: open.map((f) => ({ ...f })), inputTokensMax, ...(inputTokensCounted ? { inputTokensCounted } : {}),
199
+ ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }), ...(feeUsd === undefined ? {} : { feeUsd }), ...(paid ? { paid } : {}), ...(side ? { side } : {}), ...(unanswered ? { unanswered } : {}), ...(noted ? { noted, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
194
200
  if (verdict && "refuse" in verdict)
195
201
  throw end("refused", verdict.refuse, typeof verdict.code === "string" ? verdict.code : undefined);
196
202
  const hold = verdict && "holdUsd" in verdict ? heldFigure(verdict.holdUsd) : undefined;
@@ -254,14 +260,15 @@ function bookingFor(writer, options) {
254
260
  if (stoppedLate) {
255
261
  answered.add(turn);
256
262
  await write([{ kind: RUNNER_RECORDS.turn, data: { turn, usd: 0, unsent: true } }]).catch(() => undefined);
257
- emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: 0 }, ...(host === undefined ? {} : { host }), ended: { end: "nothing", label: "never_left" } });
263
+ await emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: 0 }, ...(host === undefined ? {} : { host }), ended: { end: "nothing", label: "never_left" } });
258
264
  throw stoppedLate;
259
265
  }
260
- open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
266
+ open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(bound ? { boundUsd: bound } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
261
267
  return { turn, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(withoutNote ? { noteDropped: true } : {}) };
262
268
  };
263
269
  const models = {
264
270
  ...(options.note ? { note: options.note } : {}),
271
+ ...(options.noteReturned ? { noteReturned: options.noteReturned } : {}),
265
272
  beforeRequest: (request) => {
266
273
  const admitted = admitting.then(() => admit(request));
267
274
  admitting = admitted.catch(() => { });
@@ -325,7 +332,9 @@ function bookingFor(writer, options) {
325
332
  }
326
333
  answered.add(turn);
327
334
  const hosted = hosts.get(turn);
328
- emit({ type: "request_end", turn, usage, ...(hosted === undefined ? {} : { host: hosted }), ...(ended ? { ended } : {}) });
335
+ // Awaited: a host that marks the request's end on its record writes it before the booking counts as settled, so a
336
+ // run's end never lands ahead of the mark that says its request was cut.
337
+ await emit({ type: "request_end", turn, usage, ...(hosted === undefined ? {} : { host: hosted }), ...(ended ? { ended } : {}) });
329
338
  },
330
339
  };
331
340
  // One booking of the cut requests at a time: a call made while one is writing waits for it, never books them again.
@@ -334,7 +343,13 @@ function bookingFor(writer, options) {
334
343
  // A paid request a crash cut off kept its runner.request and has no runner.turn: the provider may have billed it.
335
344
  // Each is booked once, as cut, at an unknown price, and the host is told as for any answered request, so its ledger
336
345
  // shows the possible spend instead of nothing. Booked, it is answered: a later attempt never books it again.
337
- // Only requests an earlier process admitted: one this process has in flight is not cut.
346
+ // Only requests an earlier process admitted: one this process has in flight is not cut. Read again here, just before
347
+ // the cut is written: another booking of this session (an earlier pass of this claim, or one racing it) may have
348
+ // booked it since this one opened, and a request is booked once.
349
+ const bookedSince = sessionSpendOf(await writer.read().catch(() => options.records)).answered;
350
+ for (const t of inherited)
351
+ if (bookedSince.has(t))
352
+ answered.add(t);
338
353
  const left = inherited.filter((t) => !answered.has(t));
339
354
  if (left.length === 0)
340
355
  return;
@@ -385,6 +400,8 @@ function bookingFor(writer, options) {
385
400
  models,
386
401
  turns: () => turns,
387
402
  spentUsd: () => spentUsd,
403
+ heldUsd: () => open.reduce((sum, flight) => (sum === null || flight.holdUsd === undefined ? null : sum + flight.holdUsd), 0),
404
+ boundUsd: () => open.reduce((sum, flight) => sum + (flight.boundUsd ?? 0), 0),
388
405
  bookCut() {
389
406
  cutting ??= bookCut().catch((error) => {
390
407
  cutting = undefined;
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,13 +106,20 @@ 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. */
114
117
  /** `answered`: a request whose reply asks for calls came back (its `until` let go), so its calls are the model's to run.
115
- * `said`: a call's own text (its `say`) was streamed, so a recovered turn never says it again. */
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. */
116
120
  export declare const FAUX_RECORDS: {
117
121
  readonly request: "faux.request";
122
+ readonly unbooked: "faux.unbooked";
118
123
  readonly answered: "faux.answered";
119
124
  readonly said: "faux.said";
120
125
  readonly user: "faux.user";
package/dist/testing.js CHANGED
@@ -42,8 +42,9 @@ export function memorySessionStore() {
42
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
43
43
  * would add it to the body: filed with its text, for a test to see. */
44
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. */
46
- export const FAUX_RECORDS = { request: "faux.request", 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" };
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" };
47
48
  export function fauxAdapter(options) {
48
49
  const stats = { requests: 0, calls: [], opened: [], closed: [] };
49
50
  const adapter = {
@@ -66,10 +67,11 @@ export function fauxAdapter(options) {
66
67
  const proxy = options.proxy ? await startModelProxy({ ...options.proxy.options, hooks: io.models }, randomBytes(32).toString("base64url")) : undefined;
67
68
  io.signal.addEventListener("abort", () => void proxy?.close(), { once: true });
68
69
  const append = (kind, data) => io.writer.append([{ kind, data }]);
69
- // The script's place: one past its last request's (each faux.request keeps its action's index), never the count of
70
- // 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.
71
73
  let cursor = records.reduce((next, r) => {
72
- 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;
73
75
  return typeof index === "number" && index + 1 > next ? index + 1 : next;
74
76
  }, 0);
75
77
  const turnsStarted = records.filter((r) => r.kind === FAUX_RECORDS.turn).length;
@@ -95,12 +97,11 @@ export function fauxAdapter(options) {
95
97
  // its calls runs on the recovery: the turn goes on with the script's next request, as a cut request's always has.
96
98
  const begun = new Set(records.filter((r) => r.kind === FAUX_RECORDS.call || r.kind === FAUX_RECORDS.result).map((r) => r.data.callId));
97
99
  const answered = new Set(records.filter((r) => r.kind === FAUX_RECORDS.answered).map((r) => r.data.index));
98
- // Each keeps its action's resultWhen: its outcome is told only once that file exists, as on its first try; and its own
99
- // text (`say`) unless it was said already (FAUX_RECORDS.said: the call that parked said its text before its gate).
100
- const resultWhenOf = (action) => (action && "resultWhen" in action && typeof action.resultWhen === "string" ? action.resultWhen : undefined);
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).
101
102
  const saidAlready = new Set(records.filter((r) => r.kind === FAUX_RECORDS.said).map((r) => r.data.callId));
102
103
  let dangling = state === "open_turn" && answered.has(cursor - 1)
103
- ? callsOf(script[cursor - 1], cursor - 1).filter((call) => !begun.has(call.callId)).map(({ say, ...call }) => ({ ...call, ...(say && !saidAlready.has(call.callId) ? { say } : {}), resultWhen: resultWhenOf(script[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 } : {}) }))
104
105
  : [];
105
106
  /** What the session has been sent, as a model would be prompted with it. */
106
107
  const prompt = records.filter((r) => r.kind === FAUX_RECORDS.user).map((r) => r.data.text);
@@ -134,8 +135,8 @@ export function fauxAdapter(options) {
134
135
  });
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
136
137
  * gate's words, recorded so it is never asked again; a park holds the turn until it is stopped), then its intent,
137
- * the tool, and its outcome. `resultWhen`: its outcome is told only once that file exists. */
138
- const runCall = async (name, args, callId, signal, resultWhen) => {
138
+ * the tool, and its outcome. */
139
+ const runCall = async (name, args, callId, signal) => {
139
140
  const tool = tools.get(name);
140
141
  const refused = tool && io.gate ? await askGate((call) => io.gate(call), { callId, tool: name, args: (args ?? {}) }, signal) : undefined;
141
142
  if (refused)
@@ -145,8 +146,6 @@ export function fauxAdapter(options) {
145
146
  const result = tool ? await tool.call(args, { callId, signal }).catch((error) => ({ text: error.message, isError: true })) : { text: `unknown tool ${name}`, isError: true };
146
147
  if (tool)
147
148
  stats.calls.push(name);
148
- if (resultWhen)
149
- await untilExists(resultWhen, signal);
150
149
  await append(FAUX_RECORDS.result, { callId, isError: result.isError === true });
151
150
  io.onEvent({ type: "tool_end", callId, name, isError: result.isError === true });
152
151
  };
@@ -160,10 +159,10 @@ export function fauxAdapter(options) {
160
159
  const signal = AbortSignal.any([io.signal, (turnSignal = new AbortController()).signal]);
161
160
  try {
162
161
  // A recovered turn: the calls its last request left dangling run first, then the model goes on.
163
- for (const { name, args, callId, say, resultWhen } of dangling.splice(0)) {
162
+ for (const { name, args, callId, say } of dangling.splice(0)) {
164
163
  if (say)
165
164
  await saying(callId, say);
166
- await runCall(name, args, callId, signal, resultWhen);
165
+ await runCall(name, args, callId, signal);
167
166
  }
168
167
  for (;;) {
169
168
  const action = script[cursor];
@@ -175,6 +174,13 @@ export function fauxAdapter(options) {
175
174
  turnSignal.abort(new Error(action.halt));
176
175
  return await hang(signal);
177
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
+ }
178
184
  // Measured as a real adapter's proxy measures its body: the prompt's UTF-8 bytes, with nothing a provider adds.
179
185
  const measured = "inputTokensMax" in action && typeof action.inputTokensMax === "number" ? action.inputTokensMax : Buffer.byteLength(JSON.stringify({ system: spec.system, user: prompt }), "utf8");
180
186
  // On the session's model: the proxy's, when it has one (the host's own requests go there on that model too).
@@ -267,7 +273,7 @@ export function fauxAdapter(options) {
267
273
  const side = await io.models.beforeRequest({ model: "faux-small", side: true, inputTokensMax: 100 });
268
274
  await io.models.afterRequest({ input: 10, output: 5, usd: action.sideDuring.usd }, side || undefined);
269
275
  }
270
- await runCall(name, args, callId, signal, resultWhenOf(action));
276
+ await runCall(name, args, callId, signal);
271
277
  }
272
278
  if (bookAfter)
273
279
  await book();
package/dist/types.d.ts CHANGED
@@ -60,7 +60,8 @@ export interface HostTool {
60
60
  }): Promise<{
61
61
  text: string;
62
62
  isError?: boolean;
63
- images?: readonly ToolImage[];
63
+ images?: readonly ToolImage[]; /** The answer as a value (a computer tool's), its images' data left out: what a script's nested call reads (Codex's code mode) and an MCP client's structuredContent. */
64
+ structured?: JsonValue;
64
65
  parked?: true;
65
66
  }>;
66
67
  }
@@ -178,6 +179,9 @@ export interface ModelRequest {
178
179
  /** A side call, never its turn's own: on another model than the session's (a client's title, a summary), or the
179
180
  * host's own request beside the harness's (`host`). */
180
181
  side?: true;
182
+ /** 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. */
184
+ unanswered?: true;
181
185
  /** It carries the host's note (ModelPort.note) in its body: the note is delivered once this request is admitted.
182
186
  * `inputTokensMaxWithoutNote`: its input measured as its client sent it, before the note was placed. */
183
187
  noted?: true;
@@ -239,6 +243,9 @@ export interface ModelPort {
239
243
  * session's model proxy adds it to that request's body (ModelProxyHooks.note). `request`: that request as its client
240
244
  * sent it, measured before the note is placed (NoteRequest), so the host can price it as its admission will. */
241
245
  note?(model: string, request?: NoteRequest): string | undefined;
246
+ /** The note `note` gave back: the request that took it left before its admission (its client gone, a refusal or an
247
+ * error before `beforeRequest`), so it was never sent, and the host may give it to the next request at once. */
248
+ noteReturned?(note: string): void;
242
249
  }
243
250
  /** 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
244
251
  * at least, as the model proxy reads them (ModelRequest's figures, without the note). */
@@ -276,6 +283,12 @@ export interface SessionIO {
276
283
  * runs nothing; a park holds the call, writing nothing, until the session's signal is aborted (the run parks on a
277
284
  * person). Absent: every call runs. */
278
285
  gate?(call: GateCall, context?: unknown): Promise<GateAnswer>;
286
+ /** The host's setting now for one of the harness's own tools, by the harness's name for it (Codex's `web_search`), read
287
+ * again at each ask, so a permission set while the session runs reaches its next request. For a tool no call of which
288
+ * reaches the gate before it runs: a provider-hosted search runs inside a model request, so the session offers it only
289
+ * while this says "allow" (a throw reads as "deny"). Absent: the host keeps no per-tool permissions, and what the
290
+ * session was opened with stands. */
291
+ permission?(tool: string): Promise<ToolPermission>;
279
292
  /** A tool the adapter adds of its own (read_skill_file over the session's skills), made the host's: its calls go the
280
293
  * way the host's own tools' do (the run's record of the call and its result, which its Timeline shows, the rule before
281
294
  * a side effect, the host's hooks on the result). An adapter hands every tool it adds through it. Absent: the host
@@ -299,6 +312,8 @@ export type GateAnswer = "allow" | {
299
312
  } | {
300
313
  readonly park: true;
301
314
  };
315
+ /** A tool's setting on the host (SessionIO.permission): it runs, it waits for a person's answer, or it is refused. */
316
+ export type ToolPermission = "allow" | "ask" | "deny";
302
317
  /** 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
303
318
  * only once its outcome is durable in the session's records, so a host never shows a result its store does not have;
304
319
  * `result` is the text recorded, when the adapter reports it. A call stopped before its outcome was recorded gets no
@@ -366,9 +381,8 @@ export interface AdapterSession {
366
381
  recover(): Promise<void>;
367
382
  /** Record the open turn as ended, interrupted, and send nothing: the turn is not to be resumed (a person stopped it, and
368
383
  * an interrupt writes no end in the session). Only when `state` is `open_turn`; the session is `idle` after, here and
369
- * 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
370
- * (kernel/follow-up.ts, FollowUpTarget.settleOpenTurn), naming its own prompt (`opening`): that one is withdrawn and
371
- * never carried, and the rest is left as it is. */
384
+ * 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
385
+ * prompt names it (`opening`): that one is withdrawn and never carried, and the rest is left as it is. */
372
386
  settleOpenTurn(options?: {
373
387
  opening?: string;
374
388
  }): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-kernel",
3
- "version": "0.1.0-beta.35",
3
+ "version": "0.1.0-beta.37",
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.35",
63
+ "@parcha/agentrun-dsl": "0.1.0-beta.37",
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;