@parcha/agentrun-kernel 0.1.0-beta.31 → 0.1.0-beta.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +5 -0
  3. package/dist/errors.d.ts +7 -0
  4. package/dist/errors.js +10 -0
  5. package/dist/host/box.d.ts +0 -58
  6. package/dist/host/box.js +7 -0
  7. package/dist/host/index.d.ts +4 -10
  8. package/dist/host/index.js +2 -5
  9. package/dist/host/mcp-route.d.ts +3 -0
  10. package/dist/host/mcp-route.js +6 -2
  11. package/dist/host/proxy.d.ts +96 -5
  12. package/dist/host/proxy.js +518 -43
  13. package/dist/host/serial.js +2 -1
  14. package/dist/index.d.ts +5 -4
  15. package/dist/index.js +3 -2
  16. package/dist/kernel/cap/admit.d.ts +35 -0
  17. package/dist/kernel/cap/admit.js +186 -0
  18. package/dist/kernel/cap/errors.d.ts +20 -0
  19. package/dist/kernel/cap/errors.js +25 -0
  20. package/dist/kernel/cap/index.d.ts +14 -0
  21. package/dist/kernel/cap/index.js +15 -0
  22. package/dist/kernel/cap/ledger.d.ts +37 -0
  23. package/dist/kernel/cap/ledger.js +83 -0
  24. package/dist/kernel/cap/marks.d.ts +50 -0
  25. package/dist/kernel/cap/marks.js +28 -0
  26. package/dist/kernel/cap/park.d.ts +80 -0
  27. package/dist/kernel/cap/park.js +57 -0
  28. package/dist/kernel/cap/port.d.ts +21 -0
  29. package/dist/kernel/cap/port.js +95 -0
  30. package/dist/kernel/cap/price.d.ts +54 -0
  31. package/dist/kernel/cap/price.js +117 -0
  32. package/dist/kernel/cap/recover.d.ts +18 -0
  33. package/dist/kernel/cap/recover.js +71 -0
  34. package/dist/kernel/cap/rule.d.ts +55 -0
  35. package/dist/kernel/cap/rule.js +93 -0
  36. package/dist/kernel/cap/run-cap.d.ts +80 -0
  37. package/dist/kernel/cap/run-cap.js +132 -0
  38. package/dist/kernel/cap/steps.d.ts +36 -0
  39. package/dist/kernel/cap/steps.js +64 -0
  40. package/dist/kernel/cap/stopped.d.ts +17 -0
  41. package/dist/kernel/cap/stopped.js +34 -0
  42. package/dist/kernel/cap/types.d.ts +151 -0
  43. package/dist/kernel/cap/types.js +1 -0
  44. package/dist/kernel/cap/words.d.ts +39 -0
  45. package/dist/kernel/cap/words.js +75 -0
  46. package/dist/kernel/cap/wrap-up.d.ts +17 -0
  47. package/dist/kernel/cap/wrap-up.js +37 -0
  48. package/dist/kernel/drive.d.ts +0 -1
  49. package/dist/kernel/drive.js +9 -2
  50. package/dist/kernel/index.d.ts +1 -0
  51. package/dist/kernel/index.js +1 -0
  52. package/dist/kernel/registry/background.d.ts +12 -0
  53. package/dist/kernel/registry/background.js +342 -0
  54. package/dist/kernel/registry/bash.d.ts +3 -0
  55. package/dist/kernel/registry/bash.js +23 -0
  56. package/dist/kernel/registry/browser.d.ts +11 -0
  57. package/dist/kernel/registry/browser.js +14 -0
  58. package/dist/kernel/registry/defs.d.ts +42 -0
  59. package/dist/kernel/registry/defs.js +153 -0
  60. package/dist/kernel/registry/desktop.d.ts +11 -0
  61. package/dist/kernel/registry/desktop.js +90 -0
  62. package/dist/kernel/registry/gate.d.ts +20 -0
  63. package/dist/kernel/registry/gate.js +32 -0
  64. package/dist/kernel/registry/handoff.d.ts +11 -0
  65. package/dist/kernel/registry/handoff.js +51 -0
  66. package/dist/kernel/registry/hands.d.ts +280 -0
  67. package/dist/kernel/registry/hands.js +28 -0
  68. package/dist/kernel/registry/index.d.ts +17 -0
  69. package/dist/kernel/registry/index.js +14 -0
  70. package/dist/kernel/registry/limits.d.ts +27 -0
  71. package/dist/kernel/registry/limits.js +29 -0
  72. package/dist/kernel/registry/phone.d.ts +15 -0
  73. package/dist/kernel/registry/phone.js +135 -0
  74. package/dist/kernel/registry/registry.d.ts +22 -0
  75. package/dist/kernel/registry/registry.js +75 -0
  76. package/dist/kernel/types.d.ts +0 -7
  77. package/dist/process/builtins.js +1 -1
  78. package/dist/process/index.d.ts +1 -0
  79. package/dist/process/index.js +1 -0
  80. package/dist/process/journal.js +1 -1
  81. package/dist/process/recovery.js +1 -1
  82. package/dist/process/resume.d.ts +20 -0
  83. package/dist/process/resume.js +16 -0
  84. package/dist/process/tail.js +1 -1
  85. package/dist/process/tools.d.ts +8 -1
  86. package/dist/process/tools.js +20 -3
  87. package/dist/process/zod.js +1 -1
  88. package/dist/run-booking.d.ts +9 -0
  89. package/dist/run-booking.js +50 -0
  90. package/dist/runner.d.ts +91 -17
  91. package/dist/runner.js +132 -41
  92. package/dist/testing.d.ts +79 -12
  93. package/dist/testing.js +106 -13
  94. package/dist/types.d.ts +204 -10
  95. package/package.json +8 -4
  96. package/vendor/durable-harness/UPSTREAM.json +0 -9
  97. package/dist/host/box-slot.d.ts +0 -26
  98. package/dist/host/box-slot.js +0 -112
  99. package/dist/host/egress-proxy.d.ts +0 -45
  100. package/dist/host/egress-proxy.js +0 -416
  101. package/dist/host/egress-table.d.ts +0 -24
  102. package/dist/host/egress-table.js +0 -165
@@ -0,0 +1,17 @@
1
+ /** Due when what is left is under this many times a priced request's typical cost. */
2
+ export declare const WRAP_UP_FACTOR = 3;
3
+ /** Or under this many times the next request's least admission: room for about one more request. */
4
+ export declare const WRAP_UP_LEAST_FACTOR = 2;
5
+ /** While nothing is priced (step 0), a request's typical cost is its input and this many output tokens, never its whole
6
+ * allowance, which no turn uses (the lead's ruling (d), 2026-11-07). */
7
+ export declare const WRAP_UP_STEP0_ANSWER_TOKENS = 4096;
8
+ /** A priced request's typical cost: the median of `costs` after the first (which writes the cache), the one with one,
9
+ * `nextExpected` with none. A cost not known, or $0, is no priced request. */
10
+ export declare function typicalCost(costs: readonly unknown[], nextExpected: number): number;
11
+ /** Whether a run is due its wrap-up: what is left (the cap less spent and held, as admission counts it) under
12
+ * WRAP_UP_FACTOR times `typical`, or under WRAP_UP_LEAST_FACTOR times the next request's least. */
13
+ export declare function wrapUpDue(cap: number, spent: number, held: number, typical: number, leastUsd?: number): {
14
+ leftUsd: number;
15
+ } | undefined;
16
+ /** The note's words, what is left to the cent; before any priced request, the budget and a short answer. */
17
+ export declare const wrapUpWords: (leftUsd: number, nonePriced?: boolean) => string;
@@ -0,0 +1,37 @@
1
+ // The wrap-up's rule and words: near its cap, a run's next main-model request carries one note telling the model to
2
+ // finish, or, before anything is priced, the budget. The cap decides (admit.ts note); a harness only places the words.
3
+ import { centsMoney } from "./words.js";
4
+ /** Due when what is left is under this many times a priced request's typical cost. */
5
+ export const WRAP_UP_FACTOR = 3;
6
+ /** Or under this many times the next request's least admission: room for about one more request. */
7
+ export const WRAP_UP_LEAST_FACTOR = 2;
8
+ /** While nothing is priced (step 0), a request's typical cost is its input and this many output tokens, never its whole
9
+ * allowance, which no turn uses (the lead's ruling (d), 2026-11-07). */
10
+ export const WRAP_UP_STEP0_ANSWER_TOKENS = 4_096;
11
+ /** A priced request's typical cost: the median of `costs` after the first (which writes the cache), the one with one,
12
+ * `nextExpected` with none. A cost not known, or $0, is no priced request. */
13
+ export function typicalCost(costs, nextExpected) {
14
+ const priced = costs.filter((usd) => typeof usd === "number" && Number.isFinite(usd) && usd > 0);
15
+ if (priced.length === 0)
16
+ return nextExpected;
17
+ if (priced.length === 1)
18
+ return priced[0];
19
+ const warm = priced.slice(1).sort((a, b) => a - b);
20
+ const mid = Math.floor(warm.length / 2);
21
+ return warm.length % 2 ? warm[mid] : (warm[mid - 1] + warm[mid]) / 2;
22
+ }
23
+ /** Whether a run is due its wrap-up: what is left (the cap less spent and held, as admission counts it) under
24
+ * WRAP_UP_FACTOR times `typical`, or under WRAP_UP_LEAST_FACTOR times the next request's least. */
25
+ export function wrapUpDue(cap, spent, held, typical, leastUsd) {
26
+ const leftUsd = cap - spent - held;
27
+ if (!Number.isFinite(leftUsd))
28
+ return undefined;
29
+ const byTypical = Number.isFinite(typical) && leftUsd < WRAP_UP_FACTOR * typical;
30
+ const byLeast = leastUsd !== undefined && Number.isFinite(leastUsd) && leftUsd < WRAP_UP_LEAST_FACTOR * leastUsd;
31
+ return byTypical || byLeast ? { leftUsd } : undefined;
32
+ }
33
+ /** The note's words, what is left to the cent; before any priced request, the budget and a short answer. */
34
+ export const wrapUpWords = (leftUsd, nonePriced = false) => {
35
+ const left = centsMoney(Math.max(0, leftUsd));
36
+ return nonePriced ? `This run's budget is about ${left}, enough for little work: answer as soon as you can.` : `About ${left} left of this run's budget: finish now with your answer.`;
37
+ };
@@ -24,7 +24,6 @@ export interface OpenDriveOptions {
24
24
  /** The session's writer (`SessionStore.open`): the drive writes only through it, and its key is the session's. */
25
25
  writer: SessionWriter;
26
26
  signal: AbortSignal;
27
- config?: unknown;
28
27
  attempt?: number;
29
28
  deadline?: number;
30
29
  live?: (event: unknown) => void;
@@ -158,8 +158,7 @@ export async function openDrive(options) {
158
158
  const drive = {
159
159
  runId: key,
160
160
  // The copied code's own writes (a journal's blobs) go through the same queue as the drive's.
161
- world: { store: { key: writer.key, read: () => writer.read(), append: (written) => append([...written]) } },
162
- config: options.config,
161
+ world: { store: { key: writer.key, read: () => writer.read(), append: (written) => append([...written]), sync: () => queue.then(() => writer.sync()) } },
163
162
  attempt: options.attempt ?? 0,
164
163
  ...(options.deadline === undefined ? {} : { deadline: options.deadline }),
165
164
  signal,
@@ -198,6 +197,10 @@ export async function openDrive(options) {
198
197
  throw new EffectFailure(known.error ?? { message: "failed" });
199
198
  if (known?.status === "running" || inflight.has(k))
200
199
  throw new Fatal(`agentrun-kernel: effect ${k} is already running in this drive`);
200
+ // A writer with no sync cannot make the start of an effect that may not run twice durable: refused before its
201
+ // start is written, so no intent is left without an outcome.
202
+ if (effectOptions.replay !== "safe" && typeof writer.sync !== "function")
203
+ throw new Fatal(`agentrun-kernel: effect ${k} may not run twice, and the session's writer has no sync to make its start durable`);
201
204
  if (signal.aborted)
202
205
  throw signal.reason;
203
206
  const placing = effectOptions.placed ?? [];
@@ -214,6 +217,10 @@ export async function openDrive(options) {
214
217
  // is not what the log placed, so it must rebuild instead of running.
215
218
  if (placing.length && state.effects.get(k)?.placed.length !== placing.length)
216
219
  throw new Restart(`agentrun-kernel: effect ${k} placed a withdrawn submission; the drive must be rebuilt`);
220
+ // An effect that may not run twice runs only once its start is durable: after a lost box the next drive finds
221
+ // the start with no end and reports it interrupted, rather than finding nothing and running it again.
222
+ if (effectOptions.replay !== "safe")
223
+ await writer.sync();
217
224
  const partial = [];
218
225
  let output;
219
226
  try {
@@ -6,3 +6,4 @@ export { foldSession, hostToolIO, INTERRUPTED_TEXT, KERNEL_RECORDS, openDrive, p
6
6
  export type { Drive, OpenDriveOptions } from "./drive.js";
7
7
  export { FOLLOW_UP_BUDGET_REACHED, FOLLOW_UP_CANCELLED, FOLLOW_UP_EFFECT, followUpKey, followUpOnce, followUpState } from "./follow-up.js";
8
8
  export type { FollowUp, FollowUpOptions, FollowUpResult, FollowUpState, FollowUpTarget } from "./follow-up.js";
9
+ export * from "./registry/index.js";
@@ -3,3 +3,4 @@ export { abortedOutcome, SessionHalt } from "./halt.js";
3
3
  export { BLOB_PIECE_CHARS, BLOB_RECORD, blobStreamName, readBlobs, sha256Hex, writeBlob } from "./blobs.js";
4
4
  export { foldSession, hostToolIO, INTERRUPTED_TEXT, KERNEL_RECORDS, openDrive, pendingSubmissions } from "./drive.js";
5
5
  export { FOLLOW_UP_BUDGET_REACHED, FOLLOW_UP_CANCELLED, FOLLOW_UP_EFFECT, followUpKey, followUpOnce, followUpState } from "./follow-up.js";
6
+ export * from "./registry/index.js";
@@ -0,0 +1,12 @@
1
+ import { type Executor, type Hands } from "./hands.js";
2
+ /** Every background tool's refusal with no computer (Mode 1 or Mode 2), naming the agent's computer setting and its v2
3
+ * view, place. */
4
+ export declare const NEEDS_A_COMPUTER = "Background programs need a computer: run this agent with a sandbox computer (Settings \u2192 Computers; place sandbox in the v2 API).";
5
+ /** bash's refusal on a run with no shell (ShellPlace "none": no computer mounts the run's folder, and it is a folder of
6
+ * the server's own machine), naming the setting that gives one. A command never runs on the server itself. */
7
+ export declare const NO_SHELL = "bash is not available in this run: it has no computer to run commands in, and commands never run on the server itself. Run this agent with a sandbox computer (Settings \u2192 Computers; place sandbox in the v2 API).";
8
+ /** The background tools' executors, by name. */
9
+ export declare const BACKGROUND_EXECUTORS: Readonly<Record<string, Executor>>;
10
+ /** The run's end: TERM to every background process still running, KILL to each one still running 3 s later. How many it
11
+ * ended; with no computer's processes, none. Call it before the computer is released. */
12
+ export declare function endBackground(hands: Hands): Promise<number>;
@@ -0,0 +1,342 @@
1
+ // The background tools on the computer's processes (hands.processes; the computer module's reference behaviour):
2
+ // `bash_background` starts a command in a fresh shell and answers at once with its id; `bash_output` reads its output
3
+ // in pages, from a byte offset, from the computer's own log; `bash_input` writes its stdin; `bash_signal` sends its
4
+ // process group TERM, INT or KILL (INT on a terminal is Ctrl-C to its foreground job); `bash_list` lists them. No call
5
+ // runs a script of its own on the computer, and none reads a file by path.
6
+ //
7
+ // A process's id is the run's own: the first number with no entry of its name in work/background/ and no background
8
+ // process of this computer's. Its shell's argv carries it after the shell's $0, which marks the process as a background
9
+ // one: every call reaches only those, never one bash or anything else started on the computer. The computer writes the
10
+ // first 16 MiB of its stdout and stderr to work/background/<id>/output.log, a file it makes itself and never through a
11
+ // link, runs the process until it and every process left in its group have ended, and keeps what left the group
12
+ // running. The run's end ends every one still running (endBackground: TERM, then KILL 3 s later). With no computer the
13
+ // five tools are refused in words: a process left on the owner's machine is what that refusal prevents.
14
+ import { answerOf } from "./hands.js";
15
+ import { BACKGROUND_DIR, BACKGROUND_INPUT_BYTES, BACKGROUND_LIST_MAX, BACKGROUND_LOG_BYTES, BACKGROUND_MAX, BACKGROUND_PAGE_BYTES, BACKGROUND_SIGNALS } from "./limits.js";
16
+ /** Every background tool's refusal with no computer (Mode 1 or Mode 2), naming the agent's computer setting and its v2
17
+ * view, place. */
18
+ export const NEEDS_A_COMPUTER = "Background programs need a computer: run this agent with a sandbox computer (Settings → Computers; place sandbox in the v2 API).";
19
+ /** bash's refusal on a run with no shell (ShellPlace "none": no computer mounts the run's folder, and it is a folder of
20
+ * the server's own machine), naming the setting that gives one. A command never runs on the server itself. */
21
+ export const NO_SHELL = "bash is not available in this run: it has no computer to run commands in, and commands never run on the server itself. Run this agent with a sandbox computer (Settings → Computers; place sandbox in the v2 API).";
22
+ /** The terminal a `tty: true` process runs on. */
23
+ const TTY_SIZE = Object.freeze({ cols: 80, rows: 24 });
24
+ /** How long `bash_signal` waits for the process to end before it answers. */
25
+ const SIGNAL_WAIT_MS = 2_000;
26
+ /** How long the run's end waits after TERM before KILL, and after KILL. */
27
+ const END_GRACE_MS = 3_000;
28
+ /** The shell's script: stderr into stdout (one stream, in order), then the command. $1 is the id, $2 the command. */
29
+ const SCRIPT = 'exec 2>&1; eval "$2"';
30
+ /** $0 of a background process's shell: what tells one from any other process on the computer. */
31
+ const MARKER = "agentrun-background";
32
+ /** Each signal's number, for an exit code past 128, and back. */
33
+ const SIGNAL_NAMES = { 1: "HUP", 2: "INT", 3: "QUIT", 6: "ABRT", 9: "KILL", 13: "PIPE", 14: "ALRM", 15: "TERM" };
34
+ const SIGNAL_NUMBERS = Object.fromEntries(Object.entries(SIGNAL_NAMES).map(([n, name]) => [name, Number(n)]));
35
+ const MIB = BACKGROUND_LOG_BYTES / (1024 * 1024);
36
+ const n = (value) => value.toLocaleString("en-US");
37
+ const codeOf = (error) => error?.code;
38
+ const wordsOf = (error) => (error instanceof Error ? error.message : String(error));
39
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
40
+ /** A process's state as the computer reports its end; an exit code past 128 is said as the signal it stands for. */
41
+ function stateOf(info) {
42
+ if (info.running)
43
+ return { state: "running" };
44
+ const signal = info.signal ?? (info.exitCode !== null && info.exitCode > 128 ? SIGNAL_NAMES[info.exitCode - 128] : undefined);
45
+ const code = info.exitCode ?? (signal !== undefined && SIGNAL_NUMBERS[signal] !== undefined ? 128 + SIGNAL_NUMBERS[signal] : null);
46
+ return { state: "exited", exit_code: code, ...(signal ? { signal } : {}) };
47
+ }
48
+ /** A state in words: `is running`, `exited with code 0`, `ended by signal TERM (exit code 143)`. */
49
+ function stateWords(state) {
50
+ if (state.state === "running")
51
+ return "is running";
52
+ if (state.signal)
53
+ return `ended by signal ${state.signal}${state.exit_code !== null ? ` (exit code ${state.exit_code})` : ""}`;
54
+ return `exited with code ${state.exit_code}`;
55
+ }
56
+ const noSuch = (id) => new Error(`there is no background process ${id} in this run: bash_list shows them`);
57
+ /** A refusal of the computer's that no word of a call's explains. */
58
+ const unanswered = (error) => new Error(`the run's box did not answer: ${wordsOf(error)}`);
59
+ const linkDir = () => new Error(`work/${BACKGROUND_DIR} is a link, so no background process starts: remove it, and its logs go in a directory of their own again`);
60
+ /** A process's id as a call gives it: digits only, so no call names a path. */
61
+ function idOf(value) {
62
+ const id = typeof value === "number" && Number.isSafeInteger(value) ? String(value) : typeof value === "string" ? value.trim() : "";
63
+ if (!/^[1-9][0-9]{0,8}$/.test(id))
64
+ throw new Error(`${JSON.stringify(value)} is no background process id: an id is the number bash_background answered, such as "1" (bash_list shows them)`);
65
+ return id;
66
+ }
67
+ const intArg = (value, name, min, max, fallback) => {
68
+ if (value === undefined || value === null)
69
+ return fallback;
70
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max)
71
+ throw new Error(`${name} is a whole number from ${n(min)} to ${n(max)}`);
72
+ return value;
73
+ };
74
+ /** The trust rule: a background process's shell has the marker as $0 (argv[3]) and a numeric id as $1 (argv[4]). */
75
+ const isBackground = (info) => info.argv[3] === MARKER && /^[1-9][0-9]*$/.test(info.argv[4] ?? "");
76
+ const idIn = (info) => info.argv[4];
77
+ const commandOf = (info) => info.argv[5] ?? "";
78
+ const logOf = (id) => `${BACKGROUND_DIR}/${id}/output.log`;
79
+ /** Every background process of the computer, in start order. */
80
+ async function backgrounds(processes) {
81
+ try {
82
+ return (await processes.list()).filter(isBackground);
83
+ }
84
+ catch (error) {
85
+ throw unanswered(error);
86
+ }
87
+ }
88
+ /** Background process `id`, the newest by that id. */
89
+ async function find(processes, id) {
90
+ const info = (await backgrounds(processes)).findLast((one) => idIn(one) === id);
91
+ if (!info)
92
+ throw noSuch(id);
93
+ return info;
94
+ }
95
+ /** The bytes the log of `info` holds so far, and whether output past them was dropped; undefined when it cannot be read. */
96
+ async function logSize(processes, info) {
97
+ try {
98
+ const read = await processes.read(info.handle, { offset: 0, maxBytes: 1 });
99
+ return { size: read.size, capped: read.capped };
100
+ }
101
+ catch {
102
+ return undefined;
103
+ }
104
+ }
105
+ /** `handle`'s state once it has ended, or after `ms`, whichever is first. */
106
+ async function settled(processes, handle, ms) {
107
+ const end = Date.now() + ms;
108
+ for (;;) {
109
+ const info = (await processes.list()).find((one) => one.handle === handle);
110
+ if (!info || !info.running || Date.now() >= end)
111
+ return info;
112
+ await sleep(50);
113
+ }
114
+ }
115
+ /** The end of `bytes` that ends inside a UTF-8 character, left for the next page: how many bytes to keep (none, when the
116
+ * page holds only part of one character). */
117
+ function wholeChars(bytes) {
118
+ for (let back = 1; back <= Math.min(3, bytes.length); back++) {
119
+ const byte = bytes[bytes.length - back];
120
+ if ((byte & 0xc0) === 0x80)
121
+ continue;
122
+ const length = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1;
123
+ return length > back ? bytes.length - back : bytes.length;
124
+ }
125
+ return bytes.length;
126
+ }
127
+ /** The last start in flight on each computer's processes: a start waits for it, so the cap's count, the id it picks and
128
+ * the start are one step, and nine starts at once start eight. */
129
+ const starting = new WeakMap();
130
+ function inTurn(processes, step) {
131
+ const turn = (starting.get(processes) ?? Promise.resolve()).then(step, step);
132
+ starting.set(processes, turn.catch(() => undefined));
133
+ return turn;
134
+ }
135
+ /** The numbers taken in the run's work/background/ (any entry named by digits), or a link refusal when the folder is a
136
+ * link. */
137
+ async function takenIn(hands) {
138
+ const taken = new Set();
139
+ const stat = await hands.stat(BACKGROUND_DIR).catch((error) => Promise.reject(unanswered(error)));
140
+ if (stat === undefined)
141
+ return taken;
142
+ if (stat.kind === "link")
143
+ throw linkDir();
144
+ if (stat.kind !== "dir")
145
+ return taken;
146
+ for (const entry of await hands.list(BACKGROUND_DIR).catch((error) => Promise.reject(unanswered(error)))) {
147
+ if (/^[1-9][0-9]*$/.test(entry.name))
148
+ taken.add(entry.name);
149
+ }
150
+ return taken;
151
+ }
152
+ /** The shell `argv` starts, bash first, sh where the computer has no bash. */
153
+ async function startShell(processes, args, spec) {
154
+ try {
155
+ return await processes.start({ ...spec, argv: ["bash", "-c", SCRIPT, MARKER, ...args] });
156
+ }
157
+ catch (error) {
158
+ if (codeOf(error) !== "not_found")
159
+ throw error;
160
+ return processes.start({ ...spec, argv: ["sh", "-c", SCRIPT, MARKER, ...args] });
161
+ }
162
+ }
163
+ const bashBackground = async (processes, args, hands, signal) => {
164
+ const given = args;
165
+ const command = typeof given.command === "string" ? given.command : "";
166
+ const tty = given.tty === true;
167
+ if (!command.trim())
168
+ throw new Error("command is the shell command to start");
169
+ const { id, pid } = await inTurn(processes, async () => {
170
+ // A call cancelled while it waited its turn starts nothing.
171
+ signal?.throwIfAborted();
172
+ const listed = await backgrounds(processes);
173
+ const running = listed.filter((info) => info.running).length;
174
+ if (running >= BACKGROUND_MAX)
175
+ throw new Error(`${running} background processes already run in this run's box, the most at once (${BACKGROUND_MAX}): end one with bash_signal (bash_list shows them), or wait for one to exit, then start this again.`);
176
+ const taken = await takenIn(hands);
177
+ for (const info of listed)
178
+ taken.add(idIn(info));
179
+ let next = 1;
180
+ signal?.throwIfAborted();
181
+ while (taken.has(String(next)))
182
+ next++;
183
+ try {
184
+ const shell = await startShell(processes, [String(next), command], { cwd: ".", log: logOf(String(next)), waitGroup: true, orphans: "keep", ...(tty ? { pty: { ...TTY_SIZE } } : { stdin: true }) });
185
+ return { id: String(next), pid: shell.pid };
186
+ }
187
+ catch (error) {
188
+ if (codeOf(error) === "denied" && / is a link/.test(wordsOf(error)))
189
+ throw linkDir();
190
+ throw new Error(`the run's box did not start the process: ${wordsOf(error)}`);
191
+ }
192
+ });
193
+ const log = logOf(id);
194
+ return { text: `Started background process ${id} (process group ${pid})${tty ? " on a terminal" : ""}. Its output goes to ${log} in work/: read it with bash_output {"id": "${id}"}, write its stdin with bash_input, end it with bash_signal.`, details: { id, log, pid, ...(tty ? { tty } : {}) } };
195
+ };
196
+ const bashOutput = async (processes, args) => {
197
+ const given = args;
198
+ const id = idOf(given.id);
199
+ const at = intArg(given.offset, "offset", 0, BACKGROUND_LOG_BYTES, 0);
200
+ const max = intArg(given.max_bytes, "max_bytes", 1, BACKGROUND_PAGE_BYTES, BACKGROUND_PAGE_BYTES);
201
+ const info = await find(processes, id);
202
+ const state = stateOf(info);
203
+ let size;
204
+ let capped;
205
+ let page = new Uint8Array();
206
+ try {
207
+ const read = await processes.read(info.handle, { offset: at, maxBytes: max });
208
+ ({ size, capped } = read);
209
+ page = read.data;
210
+ }
211
+ catch (error) {
212
+ // The computer refuses a read past the log's end: its size says how far the log goes.
213
+ const whole = codeOf(error) === "invalid" ? await logSize(processes, info) : undefined;
214
+ if (!whole || whole.size >= at)
215
+ throw unanswered(error);
216
+ ({ size, capped } = whole);
217
+ }
218
+ // A character the page would split is left for the next one, unless the process has ended and nothing follows.
219
+ const keep = state.state === "running" || at + page.length < size ? wholeChars(page) : page.length;
220
+ // A page too small for the one character it starts with reads nothing, and says what to ask instead.
221
+ if (keep === 0 && page.length > 0)
222
+ throw new Error(`the character at byte ${at} of background process ${id}'s output is longer than max_bytes ${max}: ask again with max_bytes 4 or more`);
223
+ const bytes = page.subarray(0, keep);
224
+ const next = at + bytes.length;
225
+ const more = next < size;
226
+ const where = at >= size && bytes.length === 0
227
+ ? `No output past byte ${n(at)} (the log has ${n(size)} bytes)${state.state === "running" ? "; call again later with the same offset for what comes next" : ""}.`
228
+ : `Output bytes ${n(at)} to ${n(next)} of ${n(size)}${more ? `; call again with offset ${next} for the next part` : state.state === "running" ? `, all of it so far; call again with offset ${next} for what comes next` : ", the end"}.`;
229
+ const cap = capped ? ` Its log reached the ${MIB} MiB cap, so later output was dropped.` : "";
230
+ const text = new TextDecoder().decode(bytes);
231
+ return { text: `Background process ${id} ${stateWords(state)}. ${where}${cap}${text ? `\n\n${text}` : ""}`, details: { id, ...state, offset: at, next_offset: next, size, ...(capped ? { capped } : {}) } };
232
+ };
233
+ /** Each terminal process's state of its line: whether input written so far ends in a partial line. */
234
+ const unterminated = new WeakMap();
235
+ function partialLines(processes) {
236
+ let lines = unterminated.get(processes);
237
+ if (!lines)
238
+ unterminated.set(processes, (lines = new Map()));
239
+ return lines;
240
+ }
241
+ const bashInput = async (processes, args) => {
242
+ const given = args;
243
+ const id = idOf(given.id);
244
+ const text = typeof given.text === "string" ? given.text : "";
245
+ const bytes = Buffer.byteLength(text);
246
+ if (bytes > BACKGROUND_INPUT_BYTES)
247
+ throw new Error(`text is at most ${BACKGROUND_INPUT_BYTES / 1024} KiB a call; send it in parts`);
248
+ const close = given.close === true;
249
+ if (!text && !close)
250
+ throw new Error("text is what to write: give some, or close: true to close stdin");
251
+ const info = await find(processes, id);
252
+ if (!info.running)
253
+ throw new Error(`background process ${id} ${stateWords(stateOf(info))}, so it takes no input`);
254
+ // Ctrl-D at a line's start is the end of input; after a partial line (this call's text, or an earlier call's left
255
+ // unterminated), the first one sends the line on and the second ends the input.
256
+ const lines = partialLines(processes);
257
+ const partial = text !== "" ? !text.endsWith("\n") : lines.get(info.handle) === true;
258
+ const eof = close && info.pty ? (partial ? "\x04\x04" : "\x04") : "";
259
+ const data = new Uint8Array(Buffer.from(text + eof));
260
+ try {
261
+ await processes.write(info.handle, { ...(data.length > 0 ? { data } : {}), ...(close && !info.pty ? { close: true } : {}) });
262
+ }
263
+ catch (error) {
264
+ if (/stdin is closed/.test(wordsOf(error)))
265
+ throw new Error(`background process ${id}'s stdin is closed: an earlier bash_input closed it`);
266
+ throw new Error(`process ${id} did not take its input: ${wordsOf(error)} (a process that does not read its stdin fills its pipe at 64 KiB)`);
267
+ }
268
+ if (info.pty)
269
+ lines.set(info.handle, !close && partial);
270
+ return { text: `Wrote ${n(bytes)} bytes to background process ${id}'s stdin${close ? ", then closed it" : ""}. Read what it answers with bash_output.`, details: { id, bytes, ...(close ? { closed: true } : {}) } };
271
+ };
272
+ const bashSignal = async (processes, args) => {
273
+ const given = args;
274
+ const id = idOf(given.id);
275
+ const signal = typeof given.signal === "string" ? given.signal.trim().toUpperCase().replace(/^SIG/, "") : "";
276
+ if (!BACKGROUND_SIGNALS.includes(signal))
277
+ throw new Error(`signal is one of ${BACKGROUND_SIGNALS.join(", ")}`);
278
+ const info = await find(processes, id);
279
+ if (!info.running)
280
+ throw new Error(`background process ${id} ${stateWords(stateOf(info))}, so no signal was sent`);
281
+ let note;
282
+ try {
283
+ ({ note } = await processes.signal(info.handle, signal));
284
+ }
285
+ catch (error) {
286
+ throw new Error(`${signal} was not sent to background process ${id}: ${wordsOf(error)}`);
287
+ }
288
+ const after = await settled(processes, info.handle, SIGNAL_WAIT_MS).catch((error) => Promise.reject(unanswered(error)));
289
+ const state = after ? stateOf(after) : { state: "running" };
290
+ return { text: `Sent ${signal} to background process ${id}${note ? ` (${note})` : ""}: it ${stateWords(state)}.${state.state === "running" ? " Send KILL to end it at once." : ""}`, details: { id, signal, ...state } };
291
+ };
292
+ const bashList = async (processes) => {
293
+ const all = [...(await backgrounds(processes))].sort((a, b) => Number(idIn(b)) - Number(idIn(a)));
294
+ const shown = [...all.filter((info) => info.running), ...all.filter((info) => !info.running)].slice(0, BACKGROUND_LIST_MAX);
295
+ if (shown.length === 0)
296
+ return { text: "No background processes in this run's box: bash_background starts one.", details: { processes: [] } };
297
+ const sizes = await Promise.all(shown.map((info) => logSize(processes, info)));
298
+ const listed = shown.map((info, i) => ({
299
+ id: idIn(info),
300
+ ...stateOf(info),
301
+ size: sizes[i]?.size ?? 0,
302
+ started: new Date(info.startedAt).toISOString().replace(/\.\d{3}Z$/, "Z"),
303
+ ...(info.pty ? { tty: true } : {}),
304
+ command: commandOf(info),
305
+ }));
306
+ const running = all.filter((info) => info.running).length;
307
+ const lines = listed.map((p) => `${p.id}: ${stateWords(p)}; ${n(p.size)} bytes of output; started ${p.started}; ${JSON.stringify(p.command.replace(/\s+/g, " ").slice(0, 120))}${p.tty ? " (tty)" : ""}`);
308
+ const left = all.length - shown.length;
309
+ return { text: `${running} of at most ${BACKGROUND_MAX} running.\n${lines.join("\n")}${left > 0 ? `\n(and ${left} older ones that ended)` : ""}`, details: { running, processes: listed } };
310
+ };
311
+ /** A background tool's run: refused in words where the run has no computer's processes. */
312
+ const onProcesses = (name, run) => (args, call) => answerOf(call, async () => {
313
+ call.signal?.throwIfAborted();
314
+ const processes = call.hands.processes;
315
+ if (!processes)
316
+ throw new Error(NEEDS_A_COMPUTER);
317
+ return run(processes, args, call.hands, call.signal);
318
+ });
319
+ /** The background tools' executors, by name. */
320
+ export const BACKGROUND_EXECUTORS = {
321
+ bash_background: onProcesses("bash_background", bashBackground),
322
+ bash_output: onProcesses("bash_output", bashOutput),
323
+ bash_input: onProcesses("bash_input", bashInput),
324
+ bash_signal: onProcesses("bash_signal", bashSignal),
325
+ bash_list: onProcesses("bash_list", (processes) => bashList(processes)),
326
+ };
327
+ /** The run's end: TERM to every background process still running, KILL to each one still running 3 s later. How many it
328
+ * ended; with no computer's processes, none. Call it before the computer is released. */
329
+ export async function endBackground(hands) {
330
+ const processes = hands.processes;
331
+ if (!processes)
332
+ return 0;
333
+ const running = (await backgrounds(processes)).filter((info) => info.running);
334
+ for (const info of running)
335
+ await processes.signal(info.handle, "TERM").catch(() => undefined);
336
+ const after = await Promise.all(running.map((info) => settled(processes, info.handle, END_GRACE_MS).catch(() => undefined)));
337
+ const left = running.filter((_, i) => after[i] === undefined || after[i].running);
338
+ for (const info of left)
339
+ await processes.signal(info.handle, "KILL").catch(() => undefined);
340
+ await Promise.all(left.map((info) => settled(processes, info.handle, END_GRACE_MS).catch(() => undefined)));
341
+ return running.length;
342
+ }
@@ -0,0 +1,3 @@
1
+ import { type Executor } from "./hands.js";
2
+ /** `run`, bounded to its call's hands' `maxExecS`. */
3
+ export declare function boundedBash(run: Executor, background: boolean): Executor;
@@ -0,0 +1,23 @@
1
+ // bash bounded to the run's hands (moved from serve's coding-tools.ts boundedBash): a call with no timeout runs at the
2
+ // default, one asking for more than the hands' ceiling runs at the ceiling and says so: in a diagnostic when it ends,
3
+ // and after its error when it times out. The run itself is the host's (pi's bash over the run's hands); it answers a
4
+ // timeout as its error, so what the command printed before it is kept.
5
+ import { answerOf } from "./hands.js";
6
+ import { BASH_DEFAULT_TIMEOUT_S } from "./limits.js";
7
+ const capWords = (asked, max, background) => `bash runs a command for at most ${max} s: this one ran with ${max} s, not the ${asked} s asked.${background ? " For longer work use bash_background." : ""}`;
8
+ /** `run`, bounded to its call's hands' `maxExecS`. */
9
+ export function boundedBash(run, background) {
10
+ return (args, call) => answerOf(call, async () => {
11
+ const max = call.hands.maxExecS;
12
+ const asked = args?.timeout;
13
+ const capped = typeof asked === "number" && asked > max;
14
+ const timeout = typeof asked === "number" ? Math.min(asked, max) : Math.min(BASH_DEFAULT_TIMEOUT_S, max);
15
+ const answer = await run({ ...args, timeout }, call);
16
+ if (!capped)
17
+ return answer;
18
+ const words = capWords(asked, max, background);
19
+ if (answer.error !== undefined && /timed out/i.test(answer.error))
20
+ return { ...answer, error: `${answer.error}. ${words}` };
21
+ return { ...answer, diagnostics: [...(answer.diagnostics ?? []), { severity: "warn", code: "timeout_capped", message: words }] };
22
+ });
23
+ }
@@ -0,0 +1,11 @@
1
+ import type { ToolDef } from "./defs.js";
2
+ /** A browser tool's contract, as pi-browser's ToolContract gives what the registry reads of it. */
3
+ export type BrowserContract = {
4
+ readonly name: string;
5
+ readonly description: string;
6
+ readonly parameters: object;
7
+ /** After a crash a `safe` call runs again; an `unsafe` one is reported interrupted. */
8
+ readonly replay: "safe" | "unsafe";
9
+ };
10
+ /** The browser kind's definitions: the host's contracts, as given, held to the setting browser. */
11
+ export declare function browserToolDefs(contracts: readonly BrowserContract[] | undefined): readonly ToolDef[];
@@ -0,0 +1,14 @@
1
+ /** The browser kind's definitions: the host's contracts, as given, held to the setting browser. */
2
+ export function browserToolDefs(contracts) {
3
+ if (contracts === undefined)
4
+ throw new Error("the browser's definitions are pi-browser's BROWSER_TOOLS, which the host passes as browserTools: the kernel holds no copy");
5
+ return contracts.map((contract) => ({
6
+ name: contract.name,
7
+ source: "host",
8
+ gateName: `host:browser/${contract.name}`,
9
+ settingsKey: "browser",
10
+ description: contract.description,
11
+ parameters: contract.parameters,
12
+ replaySafe: contract.replay === "safe",
13
+ }));
14
+ }
@@ -0,0 +1,42 @@
1
+ import { type BrowserContract } from "./browser.js";
2
+ import type { CapabilityKind } from "./hands.js";
3
+ /** Where the run's shell is: on a computer (bash and the background tools run there), the run's folder's own exec with no
4
+ * computer (bash only, asked first: a host gives it only where that exec is not its own machine, as serve's Archil
5
+ * serverless exec), or nowhere (no shell tool at all, and a bash call is refused in words). */
6
+ export type ShellPlace = "computer" | "local" | "none";
7
+ /** A tool the model sees. */
8
+ export type ToolDef = {
9
+ readonly name: string;
10
+ readonly source: "host";
11
+ /** Its name in the kernel's grammar, `source:toolkit/action`. */
12
+ readonly gateName: string;
13
+ /** The settings key the tool gate reads for it: bash's for the whole shell family. */
14
+ readonly settingsKey: string;
15
+ readonly description: string;
16
+ readonly parameters: object;
17
+ /** A call the kernel may run again after a crash (it changes nothing). */
18
+ readonly replaySafe: boolean;
19
+ /** A shell tool: held to bash's setting; a watcher runs unasked under ask. */
20
+ readonly shell?: {
21
+ readonly family: "bash";
22
+ readonly watcher: boolean;
23
+ };
24
+ };
25
+ /** bash's timeout, said: the default and this run's ceiling, and, where background processes run, where longer work goes. */
26
+ export declare function bashTimeoutWords(maxExecS: number, background: boolean): {
27
+ sentence: string;
28
+ parameter: string;
29
+ };
30
+ /** The model-visible host tools of a run, in the order the model sees them: read, write and edit always; bash where
31
+ * the run has a shell, its words bounded by `maxExecS`; and the five background tools on a computer. */
32
+ export declare function hostToolDefs(options: {
33
+ maxExecS: number;
34
+ shell: ShellPlace;
35
+ }): readonly ToolDef[];
36
+ /** The kinds, in the order their tools follow the host tools. */
37
+ export declare const CAPABILITY_KINDS: readonly CapabilityKind[];
38
+ /** A computer kind's own tools, which a run of that kind sees after its host tools: the desktop's (desktop.ts), the
39
+ * phone's (phone.ts), or the browser's, pi-browser's contracts the host passes (browser.ts). */
40
+ export declare function capabilityToolDefs(kind: CapabilityKind, options?: {
41
+ readonly browserTools?: readonly BrowserContract[];
42
+ }): readonly ToolDef[];