@parcha/agentrun-kernel 0.1.0-beta.63 → 0.1.0-beta.65

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/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.65 (2026-11-27)
6
+
7
+ - A pi session opened again in a turn now reads the turn back from its conversation before a call the model made runs, not after: a pi-native tool (bash, web_fetch, a subagent) whose read fails is blocked before it does anything, where before it ran and its result was replaced by an error, inviting the model to run it again. <!-- changes/turn-budget-read-before-call.md -->
8
+ - A session that read its own answer never reads the turn back, so a store that cannot read blocks none of its calls.
9
+ - A call pi reruns after a crash (its intent stored, so the read happens after it) keeps what it did when the read fails, held to the window's bound alone, instead of an error.
10
+ - The words a call gets when its turn could not be read are plain: the store's own error is no longer in the model's transcript. A host tool's call pi runs again after a crash, whose read fails before it runs, says an earlier attempt of it may already have taken effect, never that nothing was done.
11
+ - A tool that nests calls (a code-mode script) whose result's length the session's journal could not keep halts its drive, as an effect's failure does, so the harness is never handed that result.
12
+
13
+ ## 0.1.0-beta.64 (2026-11-26)
14
+
15
+ - On a Linux desktop, the check of whether computerd's own user could change an app's desktop file asks the kernel too (`faccessat2` as the effective user, no link followed) for each folder on the way and for the file, beside the mode bits, so an ACL entry or a FUSE file system's own rule that lets the user write is seen. `apps.launch` names a refused desktop file from that one check, by the id asked for, and no longer opens every desktop file again to find it: that open followed links and waited forever on a named pipe called `*.desktop`. A refused file is never read, so the name or program it gives finds no app: asked by that name, `apps.launch` answers `not_found`, and by its id, `denied`. `apps.terminate` ends an app this computerd launched though its desktop file is refused now, as when a file of its id was written ahead of it since; before, it answered `denied` and the app ran on to the computer's end. The computer wire spec says that `apps.launch` answers `denied` for such an app and that `apps.list` leaves it out. A correction to the previous release's note on desktop files: refusing an app whose desktop file computerd's own user could change closes the desktop-file route only, not `write` plus apps as a whole. An app reads its config from the user's home, which `write` reaches, so an agent given both can still reach a shell through an app it opens, and the remedy stays granting no apps on such a desktop. The words every offer of a computer's ops carries (`GUI_REACH`), the serve README and the desktop kind skill say that where `write` is granted, `apps.open` reaches what a shell does with or without a URL or a path, since an app reads its config from the user's home. <!-- changes/apps-launch-refusal-kernel-check.md -->
16
+ - pi's turn budget now outlasts a process that stops in the turn, as Claude's, Codex's, ACP's and OpenCode's do: a pi session opened again takes the turn back from its conversation (its last answer's usage and calls, and each result handed since) before a call claims, so the calls a resume answers split what their answer left instead of each taking its whole bound. A read of the turn that fails runs no call: the call is an error naming why, and the next call reads again. <!-- changes/turn-budget-resume-pi-scripts.md -->
17
+ - A result goes back to the harness only once its length is in the session's journal (`TurnBudget.kept`): a process that stops right after it was handed no longer loses its part of the turn, which a resumed call would claim again. A length the journal could not keep fails the call instead of handing its result.
18
+ - A result settles at the length it was handed: a result of at most 400 characters, whole under any bound, and a refusal's words now hold what they took, so the calls after them split only what is left.
19
+ - A code-mode script's JSON read too large for its bound is handed as a note alone (`[read cut: this result is M characters of JSON, past the N ...]`), since part of a JSON document does not parse: on a 16k-32k window, a script that parses it fails naming the cut instead of on a character in the middle, and the model reads that it should ask for less. A read that is not JSON keeps its start and its note, as before.
20
+ - A failed call's error refused for a window too small to cut it in keeps its first line (as much as fits beside the note in the 400 characters a result always keeps whole), so the model reads what went wrong.
21
+ - A raise that reaches an agentic run's claim while that claim takes a retry of the raise that resumed the run (a raise covering the run's next park, during the retry's commit) waits for the run's next claim too, as one reaching a claim parking the run again does. Before, the claim could take it and park, the run left with nothing to wake it.
22
+ - The run's view shows the cap park a run stands at as its runner reads it: a raise entry clears only the park it names. A raise that names none (checked against the run while it worked) no longer hides a park journaled before it.
23
+ - `@parcha/agentrun-kernel/kernel` exports `savePathOf(given)`, the function `computer_screenshot` resolves its `save_as` with: a path relative to the run's folder, normalized (posix), inside it, ending `.png`, or a thrown refusal in words. A host's tool gate can then hold a `save_as` at the path the screenshot is saved at, not by a reading of its own. AgentRun's serve does this for a folder an MCP tool's file setting files its answers in. Nothing else changes: the screenshot resolves `save_as` as before. <!-- changes/kernel-save-path-of.md -->
24
+
5
25
  ## 0.1.0-beta.63 (2026-11-26)
6
26
 
7
27
  - On a Linux desktop, `apps.list` leaves out, and `apps.launch` and `apps.terminate` refuse as `denied` naming the file and why, an app whose desktop file computerd's own user could change: on the way to it from `/`, every symbolic link followed, the user owns a folder, a link or the file (`~/.local/share/applications` among them), the mode bits let it write the file or a folder holding one of them, or computerd runs as root. The entry is read from the file that walk checked, opened without following a link and refused if another took its place. An app runs what its desktop file says, so before, an agent given `write` and the apps group, with bash denied and exec off, could write a desktop file there and `apps.launch` it, or shadow a system app's id, and run any command. Apps installed under the user's home, as on a paired machine's `~/.local/share/applications`, are no longer listed, and a computerd that runs as root lists none. <!-- changes/apps-launch-writable-desktop-files.md -->
@@ -15,9 +15,13 @@ export declare const unsavedScreenshot: <T extends {
15
15
  readonly description: string;
16
16
  readonly parameters: object;
17
17
  }>(def: T) => T;
18
+ /** `given` as a path in the run's folder a screenshot is saved to (relative, inside it, ending .png), normalized; any
19
+ * other is refused in words. Exported so a host's gate holds a save_as as it is saved, not by a reading of its own. */
20
+ export declare function savePathOf(given: unknown): string;
18
21
  /** What every offer of a computer's ops says of its screen: leaving bash, read or write out does not keep a script from
19
- * a terminal app, a file manager, or an app opened on a URL or a path, a file the agent wrote included. */
20
- export declare const GUI_REACH = "Input ops on a computer with a terminal app or a GUI file manager, and apps.open with a URL or a path, including a file the agent wrote where write is granted, can do what a shell or the file ops do, whatever bash's, read's or write's setting.";
22
+ * a terminal app, a file manager, or an app opened on a URL or a path; and where write is granted, an app opened on
23
+ * neither runs with config the agent can write (an app reads its config from the user's home). */
24
+ export declare const GUI_REACH = "Input ops on a computer with a terminal app or a GUI file manager, and apps.open with a URL or a path, can do what a shell or the file ops do, whatever bash's, read's or write's setting; where write is granted, apps.open can do what a shell does even with no URL or path, since an app reads its config from the user's home.";
21
25
  /** The ops computer_op runs on a computer with `groups`. */
22
26
  export declare function computerOpsFor(groups: readonly string[]): readonly string[];
23
27
  /** The tools a computer with `groups` offers: observe and act with the ui group, or a screen (observe) and input (act)
@@ -50,8 +50,8 @@ const SCREENSHOT_PARAMETERS = (() => {
50
50
  * no save_as, which the run's gate refuses there. */
51
51
  export const unsavedScreenshot = (def) => ({ ...def, description: SCREENSHOT_ALONE, parameters: COMPUTER_TOOL_SCHEMAS.computer_screenshot });
52
52
  /** `given` as a path in the run's folder a screenshot is saved to (relative, inside it, ending .png), normalized; any
53
- * other is refused in words. */
54
- function savePathOf(given) {
53
+ * other is refused in words. Exported so a host's gate holds a save_as as it is saved, not by a reading of its own. */
54
+ export function savePathOf(given) {
55
55
  if (typeof given !== "string" || given === "" || posix.isAbsolute(given) || given.includes("\\"))
56
56
  throw new Error(`save_as is a path relative to the run's folder (shots/home.png): not ${JSON.stringify(given)}`);
57
57
  const path = posix.normalize(given);
@@ -73,8 +73,9 @@ const OP_ARGS = Object.freeze({
73
73
  "files.stat": "{path}",
74
74
  });
75
75
  /** What every offer of a computer's ops says of its screen: leaving bash, read or write out does not keep a script from
76
- * a terminal app, a file manager, or an app opened on a URL or a path, a file the agent wrote included. */
77
- export const GUI_REACH = "Input ops on a computer with a terminal app or a GUI file manager, and apps.open with a URL or a path, including a file the agent wrote where write is granted, can do what a shell or the file ops do, whatever bash's, read's or write's setting.";
76
+ * a terminal app, a file manager, or an app opened on a URL or a path; and where write is granted, an app opened on
77
+ * neither runs with config the agent can write (an app reads its config from the user's home). */
78
+ export const GUI_REACH = "Input ops on a computer with a terminal app or a GUI file manager, and apps.open with a URL or a path, can do what a shell or the file ops do, whatever bash's, read's or write's setting; where write is granted, apps.open can do what a shell does even with no URL or path, since an app reads its config from the user's home.";
78
79
  /** computer_op's words for the ops it offers. */
79
80
  const opWords = (ops) => `One of the computer's ops no other tool runs, as a script's \`computer\` calls it: ${ops.map((op) => (OP_ARGS[op] ? `${op} ${OP_ARGS[op]}` : op)).join(", ")}. An op this computer does not offer is refused. ${GUI_REACH}`;
80
81
  const OP = opWords(Object.keys(COMPUTER_OPS));
@@ -2,7 +2,7 @@ export { BACKGROUND_EXECUTORS, endBackground, NEEDS_A_COMPUTER, NO_SHELL } from
2
2
  export { boundedBash } from "./bash.js";
3
3
  export { bashTimeoutWords, CAPABILITY_KINDS, hostToolDefs } from "./defs.js";
4
4
  export type { ShellPlace, ToolDef } from "./defs.js";
5
- export { COMPUTER_OP_TOOL, COMPUTER_OPS, COMPUTER_TOOLS, computerExecutors, computerOpsFor, computerToolDefs, computerToolsFor, GUI_REACH, STEP_TOOL_OPS, unsavedScreenshot, withoutOps } from "./computer.js";
5
+ export { COMPUTER_OP_TOOL, COMPUTER_OPS, COMPUTER_TOOLS, computerExecutors, computerOpsFor, computerToolDefs, computerToolsFor, GUI_REACH, savePathOf, STEP_TOOL_OPS, unsavedScreenshot, withoutOps } from "./computer.js";
6
6
  export { COMPUTER_TOOL_SCHEMAS, computerDeclarations } from "./computer-surface.generated.js";
7
7
  export { defaultPermissionOf, SHELL_FAMILY, SHELL_WATCHERS, shellPermission, shellToolOf } from "./gate.js";
8
8
  export type { Permission } from "./gate.js";
@@ -5,7 +5,7 @@
5
5
  export { BACKGROUND_EXECUTORS, endBackground, NEEDS_A_COMPUTER, NO_SHELL } from "./background.js";
6
6
  export { boundedBash } from "./bash.js";
7
7
  export { bashTimeoutWords, CAPABILITY_KINDS, hostToolDefs } from "./defs.js";
8
- export { COMPUTER_OP_TOOL, COMPUTER_OPS, COMPUTER_TOOLS, computerExecutors, computerOpsFor, computerToolDefs, computerToolsFor, GUI_REACH, STEP_TOOL_OPS, unsavedScreenshot, withoutOps } from "./computer.js";
8
+ export { COMPUTER_OP_TOOL, COMPUTER_OPS, COMPUTER_TOOLS, computerExecutors, computerOpsFor, computerToolDefs, computerToolsFor, GUI_REACH, savePathOf, STEP_TOOL_OPS, unsavedScreenshot, withoutOps } from "./computer.js";
9
9
  export { COMPUTER_TOOL_SCHEMAS, computerDeclarations } from "./computer-surface.generated.js";
10
10
  export { defaultPermissionOf, SHELL_FAMILY, SHELL_WATCHERS, shellPermission, shellToolOf } from "./gate.js";
11
11
  export { answerOf, exitCodeOf, needsKindWords } from "./hands.js";
@@ -185,8 +185,13 @@ export declare function boundResult(text: string, budget?: ResultBudget): {
185
185
  truncated?: true;
186
186
  };
187
187
  /** `text` held to `max` characters as `boundResult` holds it to its budget's bound, with how it was cut (`ResultBound`)
188
- * when it was. The window's note wherever `max` is under HOST_RESULT_MAX_CHARS. */
189
- export declare function boundTo(text: string, max: number): {
188
+ * when it was. The window's note wherever `max` is under HOST_RESULT_MAX_CHARS. `script`: a code-mode script's read,
189
+ * which computes on what it is handed: a JSON document past the bound is handed as a note alone (scriptCutNote).
190
+ * `error`: a failed call's error, which a refusal never hides whole: its first line stays (errorRefusedNote). */
191
+ export declare function boundTo(text: string, max: number, how?: {
192
+ script?: boolean;
193
+ error?: boolean;
194
+ }): {
190
195
  text: string;
191
196
  truncated?: true;
192
197
  bound?: ResultBound;
@@ -66,16 +66,20 @@ export function toolBridge(ctx, tools, options = {}) {
66
66
  * (not one nested in a tool's), to its claim on the turn. A cut is recorded by its lengths (`boundKey`), once; a call
67
67
  * whose cut is recorded is cut again by that record, so a replay hands the harness what the first run did.
68
68
  */
69
- const deliver = async (callId, whole, nested) => {
69
+ const deliver = async (callId, whole, nested, error) => {
70
70
  const key = boundKey(callId);
71
71
  const recorded = ctx.state().effects.get(key);
72
72
  const known = recorded?.status === 'completed' && isBound(recorded.output) ? recorded.output : undefined;
73
- const claims = known || nested || options.outsideTurn?.(callId) ? undefined : turn;
73
+ // A call a script made (nested in a tool's, or one the harness says is outside the model's turn): what it is handed is
74
+ // the script's to compute on, not the model's to read.
75
+ const script = Boolean(nested || options.outsideTurn?.(callId));
76
+ const claims = known || script ? undefined : turn;
74
77
  if (claims)
75
78
  await claims.ready();
76
79
  const max = known ? known.max : Math.min(resultMaxChars(options.budget), claims ? claims.claim(callId, options.budget?.contextWindow) : HOST_RESULT_MAX_CHARS);
77
- const { text, truncated, bound } = boundTo(whole, max);
80
+ const { text, truncated, bound } = boundTo(whole, max, { script, error: Boolean(error) });
78
81
  claims?.settle(callId, text.length);
82
+ await claims?.kept();
79
83
  if (bound && !known)
80
84
  await ctx.effect(key, { name: 'bound', replay: 'safe', input: null }, async () => bound);
81
85
  return truncated ? { text, truncated } : { text };
@@ -144,7 +148,7 @@ export function toolBridge(ctx, tools, options = {}) {
144
148
  if (err instanceof EffectFailure) {
145
149
  let bounded;
146
150
  try {
147
- bounded = await deliver(callId, failureText(err.error, options.partialChars), nested);
151
+ bounded = await deliver(callId, failureText(err.error, options.partialChars), nested, true);
148
152
  }
149
153
  catch (error) {
150
154
  ctx.halt?.(error);
@@ -175,6 +179,17 @@ export function toolBridge(ctx, tools, options = {}) {
175
179
  }
176
180
  if (live)
177
181
  ctx.live({ type: 'tool_start', name: tool.name, args, callId });
182
+ // Its result as the harness gets it (deliver): one that cannot be handed (its length not kept) halts the drive, as an
183
+ // effect's failure does, so the harness is never handed it.
184
+ const handed = async (whole, error) => {
185
+ try {
186
+ return await deliver(callId, whole, nested, error);
187
+ }
188
+ catch (err) {
189
+ ctx.halt?.(err);
190
+ throw err;
191
+ }
192
+ };
178
193
  let output;
179
194
  try {
180
195
  output = await tool.execute(args, { signal: aborted, progress: () => { }, ctx, stepId: `${toolKey(callId)}#0`, nested: nestedIn(callId, aborted) });
@@ -184,13 +199,13 @@ export function toolBridge(ctx, tools, options = {}) {
184
199
  ctx.halt?.(err);
185
200
  throw err;
186
201
  }
187
- const { text, truncated } = await deliver(callId, err instanceof Error ? err.message : String(err), nested);
202
+ const { text, truncated } = await handed(err instanceof Error ? err.message : String(err), true);
188
203
  if (live)
189
204
  ctx.live({ type: 'tool_end', name: tool.name, callId, isError: true, result: text, ...(truncated ? { truncated } : {}) });
190
205
  return { text, isError: true, ...(truncated ? { truncated } : {}) };
191
206
  }
192
207
  const { text: whole, images, structured } = typeof output === 'object' && output !== null ? output : { text: String(output), images: undefined, structured: undefined };
193
- const { text, truncated } = await deliver(callId, String(whole), nested);
208
+ const { text, truncated } = await handed(String(whole));
194
209
  if (live)
195
210
  ctx.live({ type: 'tool_end', name: tool.name, callId, result: text, ...(truncated ? { truncated } : {}) });
196
211
  return { text, isError: false, ...(images?.length ? { images } : {}), ...(structured !== undefined ? { structured } : {}), ...(truncated ? { truncated } : {}) };
@@ -289,16 +304,53 @@ export function boundResult(text, budget) {
289
304
  const { text: bounded, truncated } = boundTo(text, resultMaxChars(budget));
290
305
  return truncated ? { text: bounded, truncated } : { text: bounded };
291
306
  }
307
+ /** What a failed call's error too large for a window too small to cut it in reads as: its first line (what went wrong),
308
+ * as much of it as fits beside the note in RESULT_ALWAYS_WHOLE_CHARS, then that the rest is not shown. Within that
309
+ * length, so bounding it again (pi bounds a result twice) leaves it as it is. */
310
+ function errorRefusedNote(text, max) {
311
+ const rest = `\n[the rest of this error (${text.length} characters in all) is not shown: this model's context window leaves room for at most ${max} characters of a tool result.]`;
312
+ const line = text.split('\n', 1)[0] ?? '';
313
+ const room = RESULT_ALWAYS_WHOLE_CHARS - rest.length;
314
+ if (line.length <= room)
315
+ return `${line}${rest}`;
316
+ // Cut before a character written as a surrogate pair rather than between its halves, and mark the cut.
317
+ let kept = room - 1;
318
+ if ((line.charCodeAt(kept - 1) & 0xfc00) === 0xd800 && (line.charCodeAt(kept) & 0xfc00) === 0xdc00)
319
+ kept -= 1;
320
+ return `${line.slice(0, kept)}…${rest}`;
321
+ }
322
+ /** What a script's JSON read too large for its bound reads as: none of it, since part of a JSON document does not parse,
323
+ * and a note a script's parse fails on by name (`Unexpected token 'r', "[read cut:"...`), which a script that prints it
324
+ * shows the model. */
325
+ function scriptCutNote(total, max, windowed) {
326
+ return `[read cut: this result is ${total} characters of JSON, past the ${max} characters ${windowed ? "this model's context window leaves a tool result" : 'a tool result may have'}. Part of a JSON document does not parse, so none of it was handed. Ask for less: a narrower query, or a small range where the tool takes an offset.]`;
327
+ }
328
+ /** Whether `text` is a whole JSON object or array (what a script parses). */
329
+ function isJsonDocument(text) {
330
+ if (!/^\s*[[{]/.test(text))
331
+ return false;
332
+ try {
333
+ JSON.parse(text);
334
+ return true;
335
+ }
336
+ catch {
337
+ return false;
338
+ }
339
+ }
292
340
  /** `text` held to `max` characters as `boundResult` holds it to its budget's bound, with how it was cut (`ResultBound`)
293
- * when it was. The window's note wherever `max` is under HOST_RESULT_MAX_CHARS. */
294
- export function boundTo(text, max) {
341
+ * when it was. The window's note wherever `max` is under HOST_RESULT_MAX_CHARS. `script`: a code-mode script's read,
342
+ * which computes on what it is handed: a JSON document past the bound is handed as a note alone (scriptCutNote).
343
+ * `error`: a failed call's error, which a refusal never hides whole: its first line stays (errorRefusedNote). */
344
+ export function boundTo(text, max, how = {}) {
295
345
  if (text.length <= max || text.length <= RESULT_ALWAYS_WHOLE_CHARS)
296
346
  return { text };
347
+ if (how.script && !how.error && isJsonDocument(text))
348
+ return { text: scriptCutNote(text.length, max, max < HOST_RESULT_MAX_CHARS), truncated: true, bound: { kept: 0, whole: text.length, max } };
297
349
  const windowed = max < HOST_RESULT_MAX_CHARS;
298
350
  // The note's own length counted at the bound: what is kept is never longer than that, so neither is its note.
299
351
  let kept = max - cutNote(max, text.length, windowed).length;
300
352
  if (kept < RESULT_LEAST_KEPT_CHARS)
301
- return { text: refusedNote(text.length, max), truncated: true, bound: { kept: 0, whole: text.length, max } };
353
+ return { text: how.error ? errorRefusedNote(text, max) : refusedNote(text.length, max), truncated: true, bound: { kept: 0, whole: text.length, max } };
302
354
  if ((text.charCodeAt(kept - 1) & 0xfc00) === 0xd800 && (text.charCodeAt(kept) & 0xfc00) === 0xdc00)
303
355
  kept -= 1;
304
356
  return { text: `${text.slice(0, kept)}${cutNote(kept, text.length, windowed)}`, truncated: true, bound: { kept, whole: text.length, max } };
@@ -55,8 +55,12 @@ export declare class TurnBudget {
55
55
  begin(): TurnSpan;
56
56
  /** A new turn, from its answer's facts: what was claimed before is forgotten. Input tokens unknown: the turn is unknown. */
57
57
  open(facts: TurnFacts): void;
58
- /** Each answer's facts and each result's length, as they happen, to `sink` (the session's journal: journalTurn), in place of any before. */
59
- journal(sink: (record: TurnRecord) => void): void;
58
+ /** Each answer's facts and each result's length, as they happen, to `sink` (the session's journal: journalTurn), in place of any before.
59
+ * A new sink (a new drive's journal) starts with nothing waited for: a length the last one failed to keep failed its
60
+ * own drive, never the next. When the last one lost a record, the new one is first given the turn again (the answer's
61
+ * facts, then each length handed since, as restore reads them), and a result waits for that too: a call the drive that
62
+ * failed settled, replayed in this one (Codex's), settles nothing new, and its length must still reach the journal. */
63
+ journal(sink: (record: TurnRecord) => void | Promise<void>): void;
60
64
  /** The turn `records` (journal's, in order) leave: the last answer's facts, and each result handed since, held. Only a
61
65
  * budget that has read no answer of its own takes them (a new process resuming its session's turn); else nothing. */
62
66
  restore(records: readonly TurnRecord[]): void;
@@ -69,8 +73,14 @@ export declare class TurnBudget {
69
73
  * gets the same figure. No usable window: HOST_RESULT_MAX_CHARS.
70
74
  */
71
75
  claim(callId: string, contextWindow: number | undefined): number;
72
- /** Call `callId`'s result reached the model at `chars` characters: what it claimed and did not use is left for the rest. */
76
+ /** Call `callId`'s result reached the model at `chars` characters: what it claimed and did not use is left for the rest,
77
+ * and what it took past its claim (a short result is whole under any bound, a refusal's words are what they are) is
78
+ * held, so the calls after it split only what is left. */
73
79
  settle(callId: string, chars: number): void;
80
+ /** Resolves once every result length settled is kept by the sink (journalTurn: committed to the journal), so a result
81
+ * goes back only once a process that stops right after cannot lose its part of the turn. Rejects when one was not:
82
+ * the result must not go back, since a resume would claim its part again. */
83
+ kept(): Promise<void>;
74
84
  }
75
85
  /** The journal stream of a session's turn budget (TurnRecord). */
76
86
  export declare const TURN_STREAM = "kernel.turn";
@@ -85,8 +95,10 @@ export interface TurnJournal {
85
95
  /**
86
96
  * `turn` kept on `journal` (a drive's; the next drive's replaces it): a budget that has read no answer yet (a new process
87
97
  * resuming the session) first takes back the turn the journal holds, so the calls its resume answers split what their
88
- * answer left; then each answer's facts and each result's length go to the journal as they happen. An answer's facts are
89
- * flushed at once: they must outlast a process that stops while its calls run.
98
+ * answer left; then each answer's facts and each result's length go to the journal as they happen, flushed at once: an
99
+ * answer's facts must outlast a process that stops while its calls run, and a result's length one that stops right after
100
+ * it was handed (the bridge waits for it: TurnBudget.kept). A journal that cannot write halts its drive on its own,
101
+ * and a result whose length it could not keep is never handed (kept rejects; the bridge halts and throws).
90
102
  */
91
103
  export declare function journalTurn(turn: TurnBudget | undefined, journal: TurnJournal): void;
92
104
  /** The client tool calls an answer's event-stream line starts (`data: ...`): a Messages `tool_use` block, a Responses
@@ -35,12 +35,17 @@ export class TurnBudget {
35
35
  #facts;
36
36
  /** What this turn's claims hold of what is left, in characters: each claim's bound until its result settles it. */
37
37
  #held = 0;
38
+ /** Each call's claim: its bound, and once its result went back, the length it was handed at. */
38
39
  #claims = new Map();
39
40
  #reading = 0;
40
41
  #waiting = new Set();
41
42
  /** An answer was read into this budget (open, or restore): a journal's records never replace it. */
42
43
  #read = false;
43
44
  #sink;
45
+ /** Every result length handed to the sink, once each is kept (the sinks' promises, together): rejects once one was not. */
46
+ #kept = Promise.resolve();
47
+ /** A record the sink could not keep: the next sink is given the turn again (journal). */
48
+ #lost = false;
44
49
  /** `fixed`: the session's own text every request carries (its system prompt), counted when no answer was read. */
45
50
  constructor(fixed = []) {
46
51
  if (fixed.length)
@@ -84,11 +89,40 @@ export class TurnBudget {
84
89
  this.#held = 0;
85
90
  this.#claims.clear();
86
91
  this.#read = true;
87
- this.#sink?.({ open: this.#facts ? { ...this.#facts } : null });
92
+ // No result waits on an answer's record: one the sink could not keep halts its drive (NativeJournal), and the
93
+ // lengths settled after it, which the bridge waits for, fail with it.
94
+ void Promise.resolve(this.#sink?.(this.#opened())).catch(() => {
95
+ this.#lost = true;
96
+ });
88
97
  }
89
- /** Each answer's facts and each result's length, as they happen, to `sink` (the session's journal: journalTurn), in place of any before. */
98
+ /** The record of the answer this turn opened with. */
99
+ #opened() {
100
+ return { open: this.#facts ? { ...this.#facts } : null };
101
+ }
102
+ /** `result` (a sink's) joined to what kept() waits for. */
103
+ #keep(result) {
104
+ const kept = Promise.all([this.#kept, result]).then(() => { });
105
+ // Seen here, so a length no one waits for never stops the process; kept() still rejects with it.
106
+ kept.catch(() => {
107
+ this.#lost = true;
108
+ });
109
+ this.#kept = kept;
110
+ }
111
+ /** Each answer's facts and each result's length, as they happen, to `sink` (the session's journal: journalTurn), in place of any before.
112
+ * A new sink (a new drive's journal) starts with nothing waited for: a length the last one failed to keep failed its
113
+ * own drive, never the next. When the last one lost a record, the new one is first given the turn again (the answer's
114
+ * facts, then each length handed since, as restore reads them), and a result waits for that too: a call the drive that
115
+ * failed settled, replayed in this one (Codex's), settles nothing new, and its length must still reach the journal. */
90
116
  journal(sink) {
91
117
  this.#sink = sink;
118
+ this.#kept = Promise.resolve();
119
+ if (!this.#lost || !this.#read)
120
+ return;
121
+ this.#lost = false;
122
+ this.#keep(sink(this.#opened()));
123
+ for (const [callId, claimed] of this.#claims)
124
+ if (claimed.settled)
125
+ this.#keep(sink({ settled: { callId, chars: claimed.chars ?? claimed.max } }));
92
126
  }
93
127
  /** The turn `records` (journal's, in order) leave: the last answer's facts, and each result handed since, held. Only a
94
128
  * budget that has read no answer of its own takes them (a new process resuming its session's turn); else nothing. */
@@ -112,7 +146,7 @@ export class TurnBudget {
112
146
  const callId = record.settled?.callId;
113
147
  if (typeof callId !== 'string' || chars === undefined || this.#claims.has(callId))
114
148
  continue;
115
- this.#claims.set(callId, { max: chars, settled: true });
149
+ this.#claims.set(callId, { max: chars, settled: true, chars });
116
150
  this.#held += chars;
117
151
  }
118
152
  this.#read = true;
@@ -161,14 +195,24 @@ export class TurnBudget {
161
195
  this.#held += max;
162
196
  return max;
163
197
  }
164
- /** Call `callId`'s result reached the model at `chars` characters: what it claimed and did not use is left for the rest. */
198
+ /** Call `callId`'s result reached the model at `chars` characters: what it claimed and did not use is left for the rest,
199
+ * and what it took past its claim (a short result is whole under any bound, a refusal's words are what they are) is
200
+ * held, so the calls after it split only what is left. */
165
201
  settle(callId, chars) {
166
202
  const claimed = this.#claims.get(callId);
167
- if (!claimed || claimed.settled)
203
+ const handed = count(chars);
204
+ if (!claimed || claimed.settled || handed === undefined)
168
205
  return;
169
206
  claimed.settled = true;
170
- this.#held += Math.min(chars, claimed.max) - claimed.max;
171
- this.#sink?.({ settled: { callId, chars: Math.min(chars, claimed.max) } });
207
+ claimed.chars = handed;
208
+ this.#held += handed - claimed.max;
209
+ this.#keep(this.#sink?.({ settled: { callId, chars: handed } }));
210
+ }
211
+ /** Resolves once every result length settled is kept by the sink (journalTurn: committed to the journal), so a result
212
+ * goes back only once a process that stops right after cannot lose its part of the turn. Rejects when one was not:
213
+ * the result must not go back, since a resume would claim its part again. */
214
+ async kept() {
215
+ await this.#kept;
172
216
  }
173
217
  }
174
218
  /** The journal stream of a session's turn budget (TurnRecord). */
@@ -176,8 +220,10 @@ export const TURN_STREAM = 'kernel.turn';
176
220
  /**
177
221
  * `turn` kept on `journal` (a drive's; the next drive's replaces it): a budget that has read no answer yet (a new process
178
222
  * resuming the session) first takes back the turn the journal holds, so the calls its resume answers split what their
179
- * answer left; then each answer's facts and each result's length go to the journal as they happen. An answer's facts are
180
- * flushed at once: they must outlast a process that stops while its calls run.
223
+ * answer left; then each answer's facts and each result's length go to the journal as they happen, flushed at once: an
224
+ * answer's facts must outlast a process that stops while its calls run, and a result's length one that stops right after
225
+ * it was handed (the bridge waits for it: TurnBudget.kept). A journal that cannot write halts its drive on its own,
226
+ * and a result whose length it could not keep is never handed (kept rejects; the bridge halts and throws).
181
227
  */
182
228
  export function journalTurn(turn, journal) {
183
229
  if (!turn)
@@ -185,8 +231,7 @@ export function journalTurn(turn, journal) {
185
231
  turn.restore(journal.records(TURN_STREAM).flatMap((r) => (r.data ? [r.data] : [])));
186
232
  turn.journal((record) => {
187
233
  journal.append(TURN_STREAM, record);
188
- if ('open' in record)
189
- void journal.flush().catch(() => { });
234
+ return journal.flush();
190
235
  });
191
236
  }
192
237
  /** The client tool calls an answer's event-stream line starts (`data: ...`): a Messages `tool_use` block, a Responses
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-kernel",
3
- "version": "0.1.0-beta.63",
3
+ "version": "0.1.0-beta.65",
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",
@@ -62,7 +62,7 @@
62
62
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
63
63
  },
64
64
  "dependencies": {
65
- "@parcha/agentrun-dsl": "0.1.0-beta.63",
65
+ "@parcha/agentrun-dsl": "0.1.0-beta.65",
66
66
  "ajv": "8.18.0",
67
67
  "typebox": "1.3.27"
68
68
  },