@operad-io/harness-process 0.0.0-stage → 0.1.0

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/src/process.ts ADDED
@@ -0,0 +1,568 @@
1
+ /**
2
+ * Runs one harness command in a process group of its own, streams its output
3
+ * line by line, and stops only that group. The harness plugin decides the
4
+ * command and reads the closing Result record; this module never runs in the
5
+ * kernel.
6
+ */
7
+
8
+ import { spawn, type ChildProcess } from "node:child_process";
9
+ import { access, mkdtemp, open, rm } from "node:fs/promises";
10
+ import { constants as fsConstants } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { delimiter, join } from "node:path";
13
+ import { Readable } from "node:stream";
14
+ import { messageLine, type MessageInbox } from "./inbox.ts";
15
+ import {
16
+ ControlReader,
17
+ DRAIN_GRACE_MS,
18
+ createGroupStop,
19
+ endStatus,
20
+ exitFromStatus,
21
+ killProcessGroup,
22
+ lastLines,
23
+ markerEnv,
24
+ reportWorkerStarted,
25
+ trackRoot,
26
+ systemClock,
27
+ type Clock,
28
+ type Ended,
29
+ type Exit,
30
+ type Startup,
31
+ } from "@operad-io/engine/platform";
32
+ import { messageOf } from "@operad-io/engine";
33
+
34
+ export { DRAIN_GRACE_MS, KILL_GRACE_MS, lastLines, systemClock, type Clock } from "@operad-io/engine/platform";
35
+
36
+ /**
37
+ * The sentinel is the process-group leader of one harness run. Its first
38
+ * action ignores SIGTERM; only then does it announce `ready` on the control
39
+ * pipe and start the harness in the same group. When the harness exits the
40
+ * sentinel reports the status and stays alive, so the numeric group id cannot
41
+ * be reused until the stop's last SIGKILL ends the sentinel together with any
42
+ * child that ignored the TERM.
43
+ *
44
+ * The control pipe is the sentinel's stderr. The harness keeps its own stderr
45
+ * in a file the caller names (the first argument), so diagnostics never mix
46
+ * with the JSONL on stdout or the control lines. A reader that does not know a
47
+ * line ignores it.
48
+ *
49
+ * The sentinel watches the process that started it (`$2`), from a helper that
50
+ * runs beside the harness: if the host is killed before it can stop the group,
51
+ * the helper kills the whole group, harness included, instead of leaving both
52
+ * running for a host that is gone. The check cannot wait for the harness to
53
+ * end, because the harness may be the thing that never does.
54
+ *
55
+ * The file replaces a fourth pipe. Bun closes an extra pipe (stdio index 3 and
56
+ * up) of a child process twice, once when its stream ends and once when the
57
+ * child object is collected; by then a SQLite database may own the number, and
58
+ * macOS kills the process (EXC_GUARD). See test/heavy/descriptor-owner.test.ts.
59
+ */
60
+ const SENTINEL = [
61
+ "trap ':' TERM",
62
+ 'parent=$2',
63
+ // The helper's output goes nowhere, so it never holds the control pipe open.
64
+ // The numeric group form is POSIX; dash does not accept `--` before it.
65
+ '( while kill -0 "$parent" 2>/dev/null; do sleep 1; done; kill -KILL -$$ ) >/dev/null 2>&1 &',
66
+ "printf 'ready\\n' >&2",
67
+ 'err=$1',
68
+ "shift 2",
69
+ '"$@" 2>"$err"',
70
+ "status=$?",
71
+ "printf 'end %s\\n' \"$status\" >&2",
72
+ 'while kill -0 "$parent" 2>/dev/null; do sleep 1 2>/dev/null; done',
73
+ ].join("\n");
74
+
75
+ /**
76
+ * What one output line says about a tool call. Each harness names its own
77
+ * events; the caller supplies the classifier.
78
+ */
79
+ export type ToolEvent = "tool-start" | "tool-end";
80
+
81
+ /** How much of the harness's own stderr the fact keeps. */
82
+ const STDERR_LIMIT = 64 * 1024;
83
+
84
+ /**
85
+ * The longest single output line the run holds. A harness that never writes a
86
+ * newline must not be able to grow the buffer until the stall or wall limit
87
+ * fires: past this a line is a malformed stream and the group is stopped.
88
+ */
89
+ export const MAX_LINE_CHARS = 8 * 1024 * 1024;
90
+
91
+ /** Finds an executable on PATH, or returns undefined. */
92
+ export async function findCommand(command: string): Promise<string | undefined> {
93
+ if (command.includes("/")) {
94
+ return (await executable(command)) ? command : undefined;
95
+ }
96
+ const path = process.env.PATH ?? "";
97
+ for (const directory of path.split(delimiter)) {
98
+ if (directory.length === 0) continue;
99
+ const candidate = join(directory, command);
100
+ if (await executable(candidate)) return candidate;
101
+ }
102
+ return undefined;
103
+ }
104
+
105
+ async function executable(path: string): Promise<boolean> {
106
+ try {
107
+ await access(path, fsConstants.X_OK);
108
+ return true;
109
+ } catch {
110
+ return false;
111
+ }
112
+ }
113
+
114
+ export interface AgentRunOptions {
115
+ /** The command name or path, resolved on PATH when it names no directory. */
116
+ readonly command: string;
117
+ readonly args: readonly string[];
118
+ readonly cwd: string;
119
+ /** The prompt written to stdin; the command reads it with `-p -`. */
120
+ readonly stdin?: string | undefined;
121
+ /**
122
+ * Keeps stdin open after the prompt, which then ends with a newline, so
123
+ * `onLine` can answer with `reply`. The child's end of the pipe closes when
124
+ * it exits.
125
+ */
126
+ readonly interactive?: boolean | undefined;
127
+ /**
128
+ * Messages from the host, written to stdin as `message` lines while the
129
+ * command runs. Needs `interactive`; without it nothing is written.
130
+ */
131
+ readonly inbox?: MessageInbox | undefined;
132
+ readonly wallMs: number;
133
+ readonly stallMs: number;
134
+ readonly signal: AbortSignal;
135
+ readonly clock?: Clock | undefined;
136
+ /**
137
+ * Receives each complete stdout line, in order. Reading waits for the answer:
138
+ * a handler that is still busy writes before the next line is taken.
139
+ */
140
+ readonly onLine: (
141
+ line: string,
142
+ reply: (text: string) => void,
143
+ ) => void | Promise<void>;
144
+ /**
145
+ * Classifies one complete stdout line. A line that starts a tool call pauses
146
+ * the stall timer until a line that ends it arrives; the wall limit still
147
+ * runs. Without a classifier no line counts as a tool call.
148
+ */
149
+ readonly toolEvent?: ((line: string) => ToolEvent | undefined) | undefined;
150
+ /** Sends a signal to one process group; a test replaces it to watch signals. */
151
+ readonly killGroup?:
152
+ | ((pgid: number, signal: NodeJS.Signals | 0) => boolean)
153
+ | undefined;
154
+ }
155
+
156
+ export interface AgentRunOutcome {
157
+ readonly exitCode: number | null;
158
+ readonly signal: string | null;
159
+ readonly cancelled: boolean;
160
+ readonly wall: boolean;
161
+ readonly stall: boolean;
162
+ readonly lineTooLong: boolean;
163
+ readonly missing: boolean;
164
+ readonly spawnError: string | undefined;
165
+ readonly stderrTail: readonly string[];
166
+ }
167
+
168
+ /**
169
+ * Splits a stream into complete lines, holding the unterminated tail up to
170
+ * `MAX_LINE_CHARS`. Each line is handed over before the next is read: a busy
171
+ * handler holds the stream, so the pipe cannot fill memory. The tail is dropped
172
+ * and `onOverflow` is called when a line grows past the limit, so no input can
173
+ * exhaust memory.
174
+ */
175
+ class Lines {
176
+ private buffer = "";
177
+ private readonly onLine: (line: string) => void | Promise<void>;
178
+ private readonly onOverflow: () => void;
179
+
180
+ constructor(
181
+ onLine: (line: string) => void | Promise<void>,
182
+ onOverflow: () => void,
183
+ ) {
184
+ this.onLine = onLine;
185
+ this.onOverflow = onOverflow;
186
+ }
187
+
188
+ async push(text: string): Promise<void> {
189
+ if (text.length === 0) return;
190
+ this.buffer += text;
191
+ let newline = this.buffer.indexOf("\n");
192
+ while (newline >= 0) {
193
+ const line = this.buffer.slice(0, newline);
194
+ this.buffer = this.buffer.slice(newline + 1);
195
+ await this.onLine(line);
196
+ newline = this.buffer.indexOf("\n");
197
+ }
198
+ if (this.buffer.length > MAX_LINE_CHARS) {
199
+ this.buffer = "";
200
+ this.onOverflow();
201
+ }
202
+ }
203
+
204
+ async end(): Promise<void> {
205
+ if (this.buffer.length === 0) return;
206
+ const rest = this.buffer;
207
+ this.buffer = "";
208
+ await this.onLine(rest);
209
+ }
210
+ }
211
+
212
+ /** Collects a bounded tail of one stream. */
213
+ class Tail {
214
+ private text = "";
215
+ private readonly onText: ((text: string) => void) | undefined;
216
+
217
+ constructor(onText: ((text: string) => void) | undefined) {
218
+ this.onText = onText;
219
+ }
220
+
221
+ push(text: string): void {
222
+ if (text.length === 0) return;
223
+ this.text = (this.text + text).slice(-STDERR_LIMIT);
224
+ this.onText?.(text);
225
+ }
226
+
227
+ lines(count: number): readonly string[] {
228
+ return lastLines(this.text, count);
229
+ }
230
+ }
231
+
232
+ function consume(
233
+ stream: Readable,
234
+ lines: Lines,
235
+ ): Promise<void> {
236
+ return (async () => {
237
+ const decoder = new TextDecoder();
238
+ try {
239
+ for await (const chunk of stream) {
240
+ const text = decoder.decode(chunk as Uint8Array, { stream: true });
241
+ await lines.push(text);
242
+ }
243
+ const rest = decoder.decode();
244
+ await lines.push(rest);
245
+ } catch {
246
+ // A process that failed to start has no output; its streams may error.
247
+ }
248
+ })();
249
+ }
250
+
251
+ /** The last `STDERR_LIMIT` bytes of a file; empty when it cannot be read. */
252
+ async function readTail(path: string): Promise<string> {
253
+ let handle: Awaited<ReturnType<typeof open>>;
254
+ try {
255
+ handle = await open(path, "r");
256
+ } catch {
257
+ return "";
258
+ }
259
+ try {
260
+ const { size } = await handle.stat();
261
+ const length = Math.min(size, STDERR_LIMIT);
262
+ const buffer = Buffer.alloc(length);
263
+ const { bytesRead } = await handle.read(buffer, 0, length, size - length);
264
+ return new TextDecoder().decode(buffer.subarray(0, bytesRead));
265
+ } catch {
266
+ return "";
267
+ } finally {
268
+ await handle.close();
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Runs one harness command. Cancellation, the wall time and a stalled output
274
+ * stream signal the group with SIGTERM and, after the grace period, SIGKILL.
275
+ * The group is always stopped after the command exits too, so a child it
276
+ * forked cannot outlive it. Only processes this call started are signaled.
277
+ */
278
+ export async function runAgent(
279
+ options: AgentRunOptions,
280
+ ): Promise<AgentRunOutcome> {
281
+ const empty = (overrides: Partial<AgentRunOutcome>): AgentRunOutcome => ({
282
+ exitCode: null,
283
+ signal: null,
284
+ cancelled: false,
285
+ wall: false,
286
+ stall: false,
287
+ lineTooLong: false,
288
+ missing: false,
289
+ spawnError: undefined,
290
+ stderrTail: [],
291
+ ...overrides,
292
+ });
293
+
294
+ if (options.signal.aborted) {
295
+ return empty({ cancelled: true });
296
+ }
297
+
298
+ const executablePath = await findCommand(options.command);
299
+ if (executablePath === undefined) {
300
+ return empty({ missing: true });
301
+ }
302
+
303
+ const clock = options.clock ?? systemClock;
304
+ let resetStallForLine: () => void = () => {};
305
+ let onLineOverflow: () => void = () => {};
306
+ const reply = (text: string): void => {
307
+ const pipe = child.stdin;
308
+ if (options.interactive !== true || pipe === null || pipe.destroyed) return;
309
+ pipe.write(`${text}\n`);
310
+ };
311
+ let toolCalls = 0;
312
+ let onToolActivity: (activity: ToolEvent) => void = () => {};
313
+ const stdoutLines = new Lines(
314
+ (line) => {
315
+ const activity = options.toolEvent?.(line);
316
+ if (activity !== undefined) onToolActivity(activity);
317
+ resetStallForLine();
318
+ return options.onLine(line, reply);
319
+ },
320
+ () => onLineOverflow(),
321
+ );
322
+ const stderrTail = new Tail(undefined);
323
+
324
+ let errorDirectory: string;
325
+ try {
326
+ errorDirectory = await mkdtemp(join(tmpdir(), "operad-harness-"));
327
+ } catch (error) {
328
+ return empty({ spawnError: messageOf(error) });
329
+ }
330
+ const errorPath = join(errorDirectory, "stderr");
331
+
332
+ let child: ChildProcess;
333
+ try {
334
+ child = spawn(
335
+ "sh",
336
+ [
337
+ "-c",
338
+ SENTINEL,
339
+ "operad-harness",
340
+ errorPath,
341
+ String(process.pid),
342
+ executablePath,
343
+ ...options.args,
344
+ ],
345
+ {
346
+ cwd: options.cwd,
347
+ env: { ...process.env, ...markerEnv() },
348
+ detached: true,
349
+ stdio: ["pipe", "pipe", "pipe"],
350
+ },
351
+ );
352
+ } catch (error) {
353
+ await rm(errorDirectory, { recursive: true, force: true });
354
+ return empty({ spawnError: messageOf(error) });
355
+ }
356
+
357
+ trackRoot(child.pid);
358
+ let sentinelExited = false;
359
+ const failed = new Promise<string>((resolve) => {
360
+ child.once("error", (error) => resolve(messageOf(error)));
361
+ });
362
+ const exited = new Promise<Exit>((resolve) => {
363
+ child.once("exit", (code, signal) => {
364
+ sentinelExited = true;
365
+ resolve({ code, signal });
366
+ });
367
+ });
368
+ // A failed spawn emits `error` and never `exit`. Anything that waits for the
369
+ // process to be gone must settle on either, or the step would hang forever.
370
+ const settled = Promise.race<Exit>([
371
+ exited,
372
+ failed.then((): Exit => ({ code: null, signal: null })),
373
+ ]);
374
+
375
+ const stdout = child.stdout;
376
+ const stderr = child.stderr;
377
+ const drained: Promise<void>[] = [];
378
+ if (stdout !== null) {
379
+ drained.push(consume(stdout, stdoutLines));
380
+ }
381
+ const control = stderr === null ? undefined : new ControlReader(stderr);
382
+ const nextControl = (): Promise<string | null> =>
383
+ control === undefined ? Promise.resolve(null) : control.next();
384
+
385
+ // The prompt travels on stdin; the harness reads it with `-p -`.
386
+ const stdin = child.stdin;
387
+ if (stdin !== null) {
388
+ stdin.on("error", () => undefined);
389
+ if (options.interactive === true) {
390
+ stdin.write(`${options.stdin ?? ""}\n`);
391
+ } else if (options.stdin === undefined) stdin.end();
392
+ else stdin.end(options.stdin);
393
+ }
394
+
395
+ // Opens once the sentinel announced that its TERM trap is installed.
396
+ let openGate = (): void => {};
397
+ const readyGate = new Promise<void>((resolve) => {
398
+ openGate = resolve;
399
+ });
400
+
401
+ let readySeen = false;
402
+ const stop = createGroupStop({
403
+ clock,
404
+ killGroup: options.killGroup ?? killProcessGroup,
405
+ pid: () => child.pid,
406
+ sentinelExited: () => sentinelExited,
407
+ readySeen: () => readySeen,
408
+ ready: readyGate,
409
+ });
410
+
411
+ let finished = false;
412
+ let stoppingFor: "cancel" | "wall" | "stall" | "line" | undefined;
413
+ const beginStop = (kind: "cancel" | "wall" | "stall" | "line"): void => {
414
+ if (finished || stoppingFor !== undefined) return;
415
+ stoppingFor = kind;
416
+ void stop();
417
+ };
418
+ onLineOverflow = () => beginStop("line");
419
+
420
+ let wallTimer: unknown;
421
+ if (options.wallMs > 0) {
422
+ wallTimer = clock.setTimeout(() => {
423
+ if (!finished) beginStop("wall");
424
+ }, options.wallMs);
425
+ }
426
+
427
+ let stallTimer: unknown;
428
+ const resetStall = (): void => {
429
+ if (options.stallMs <= 0) return;
430
+ if (stallTimer !== undefined) {
431
+ clock.clearTimeout(stallTimer);
432
+ stallTimer = undefined;
433
+ }
434
+ // A tool call may run as long as it needs: only the wall limit watches it.
435
+ if (toolCalls > 0) return;
436
+ stallTimer = clock.setTimeout(() => {
437
+ if (!finished) beginStop("stall");
438
+ }, options.stallMs);
439
+ };
440
+ onToolActivity = (activity) => {
441
+ if (activity === "tool-start") toolCalls += 1;
442
+ else toolCalls = Math.max(0, toolCalls - 1);
443
+ resetStall();
444
+ };
445
+ resetStall();
446
+ resetStallForLine = resetStall;
447
+
448
+ const onAbort = (): void => beginStop("cancel");
449
+ options.signal.addEventListener("abort", onAbort, { once: true });
450
+
451
+ const clearTimers = (): void => {
452
+ if (wallTimer !== undefined) clock.clearTimeout(wallTimer);
453
+ if (stallTimer !== undefined) clock.clearTimeout(stallTimer);
454
+ };
455
+
456
+ const startup = await Promise.race<Startup>([
457
+ nextControl().then(
458
+ (line): Startup =>
459
+ line === "ready" ? { kind: "ready" } : { kind: "closed" },
460
+ ),
461
+ failed.then((message): Startup => ({ kind: "error", message })),
462
+ exited.then((exit): Startup => ({ kind: "exit", exit })),
463
+ ]);
464
+
465
+ const finish = async (): Promise<{
466
+ readonly tail: readonly string[];
467
+ readonly exit: Exit;
468
+ }> => {
469
+ const drainedOutput = Promise.all(drained).then(() => undefined);
470
+ let drainTimer: unknown;
471
+ const drainLimit = new Promise<void>((resolve) => {
472
+ drainTimer = clock.setTimeout(resolve, DRAIN_GRACE_MS);
473
+ });
474
+ await Promise.race([drainedOutput, drainLimit]);
475
+ if (drainTimer !== undefined) clock.clearTimeout(drainTimer);
476
+ if (stdout !== null) stdout.destroy();
477
+ control?.destroy();
478
+ await drainedOutput;
479
+ await stdoutLines.end();
480
+ const exit = await settled;
481
+ stderrTail.push(await readTail(errorPath));
482
+ await rm(errorDirectory, { recursive: true, force: true });
483
+ return { tail: stderrTail.lines(20), exit };
484
+ };
485
+
486
+ if (startup.kind !== "ready") {
487
+ finished = true;
488
+ clearTimers();
489
+ options.signal.removeEventListener("abort", onAbort);
490
+ await stop();
491
+ await Promise.race([exited, failed]);
492
+ const { tail, exit } = await finish();
493
+ const spawnError =
494
+ stoppingFor !== undefined
495
+ ? undefined
496
+ : startup.kind === "error"
497
+ ? startup.message
498
+ : startup.kind === "closed"
499
+ ? "the harness shell stopped before the command started"
500
+ : undefined;
501
+ return {
502
+ exitCode: exit.code,
503
+ signal: exit.signal,
504
+ cancelled: stoppingFor === "cancel",
505
+ wall: stoppingFor === "wall",
506
+ stall: stoppingFor === "stall",
507
+ lineTooLong: stoppingFor === "line",
508
+ missing: false,
509
+ spawnError,
510
+ stderrTail: tail,
511
+ };
512
+ }
513
+
514
+ readySeen = true;
515
+ openGate();
516
+ reportWorkerStarted();
517
+ const stopListening =
518
+ options.inbox === undefined
519
+ ? undefined
520
+ : options.inbox.listen((text) => {
521
+ if (!finished) reply(messageLine(text));
522
+ });
523
+ if (options.wallMs > 0) options.inbox?.begin?.(options.wallMs);
524
+
525
+ const ended = await Promise.race<Ended>([
526
+ nextControl().then((line): Ended => {
527
+ const status = endStatus(line);
528
+ return status === undefined
529
+ ? { kind: "closed" }
530
+ : { kind: "end", exit: exitFromStatus(status) };
531
+ }),
532
+ exited.then((exit): Ended => ({ kind: "exit", exit })),
533
+ ]);
534
+
535
+ finished = true;
536
+ stopListening?.();
537
+ clearTimers();
538
+ options.signal.removeEventListener("abort", onAbort);
539
+
540
+ let exit: Exit;
541
+ if (ended.kind === "closed") exit = await exited;
542
+ else exit = ended.exit;
543
+
544
+ // Stop the group the command left behind: the sentinel and any forked
545
+ // child. A command that reported its own status has already ended, so there
546
+ // is nothing left to give SIGTERM time for; waiting the grace made every
547
+ // finished run pay 500 ms. A cancellation or limit still takes the TERM path.
548
+ if (ended.kind === "end" && stoppingFor === undefined) {
549
+ const pid = child.pid;
550
+ if (pid !== undefined) (options.killGroup ?? killProcessGroup)(pid, "SIGKILL");
551
+ } else {
552
+ await stop();
553
+ }
554
+ await Promise.race([exited, failed]);
555
+ const { tail } = await finish();
556
+
557
+ return {
558
+ exitCode: exit.code,
559
+ signal: exit.signal,
560
+ cancelled: stoppingFor === "cancel",
561
+ wall: stoppingFor === "wall",
562
+ stall: stoppingFor === "stall",
563
+ lineTooLong: stoppingFor === "line",
564
+ missing: false,
565
+ spawnError: undefined,
566
+ stderrTail: tail,
567
+ };
568
+ }