@operad-io/harness-process 0.1.1 → 0.3.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 CHANGED
@@ -8,8 +8,9 @@
8
8
  import { spawn, type ChildProcess } from "node:child_process";
9
9
  import { access, mkdtemp, open, rm } from "node:fs/promises";
10
10
  import { constants as fsConstants } from "node:fs";
11
+ import { connect, type Socket } from "node:net";
11
12
  import { tmpdir } from "node:os";
12
- import { delimiter, join } from "node:path";
13
+ import { basename, delimiter, dirname, join } from "node:path";
13
14
  import { Readable } from "node:stream";
14
15
  import { messageLine, type MessageInbox } from "./inbox.ts";
15
16
  import {
@@ -18,9 +19,21 @@ import {
18
19
  createGroupStop,
19
20
  endStatus,
20
21
  exitFromStatus,
22
+ KILL_GRACE_MS,
23
+ KEPT_FIRST_LINE_MS,
24
+ KEPT_WORKER_MS,
25
+ MAX_KEPT_WORKERS,
21
26
  killProcessGroup,
22
27
  lastLines,
23
28
  markerEnv,
29
+ newKeptWorkerSlot,
30
+ readKeptWorker,
31
+ readKeptWorkers,
32
+ readKeptWorkersInHome,
33
+ stopKeptWorker,
34
+ keptWorkerArgument,
35
+ waitForChange,
36
+ type KeptWorkerRecord,
24
37
  reportWorkerStarted,
25
38
  trackRoot,
26
39
  systemClock,
@@ -29,7 +42,7 @@ import {
29
42
  type Exit,
30
43
  type Startup,
31
44
  } from "@operad-io/engine/platform";
32
- import { messageOf } from "@operad-io/engine";
45
+ import { isRecord, messageOf } from "@operad-io/engine";
33
46
 
34
47
  export { DRAIN_GRACE_MS, KILL_GRACE_MS, lastLines, systemClock, type Clock } from "@operad-io/engine/platform";
35
48
 
@@ -88,6 +101,24 @@ const STDERR_LIMIT = 64 * 1024;
88
101
  */
89
102
  export const MAX_LINE_CHARS = 8 * 1024 * 1024;
90
103
 
104
+ /**
105
+ * The most one over-long line may run to while it is skipped. A line past
106
+ * `MAX_LINE_CHARS` is dropped, not held, and the run goes on with the next
107
+ * line (a harness that carries an image on one line must not fail the step); a
108
+ * line that never ends is a malformed stream and past this the group is stopped.
109
+ */
110
+ export const MAX_SKIPPED_LINE_CHARS = 256 * 1024 * 1024;
111
+
112
+ // The log line that stands for a stdout line dropped for its length, so a
113
+ // reader of the log sees that output was left out and how much.
114
+ export function skippedLineRecord(chars: number): string {
115
+ return JSON.stringify({
116
+ type: "line_skipped",
117
+ chars,
118
+ message: `a line of ${chars} characters was dropped unread (the limit is ${MAX_LINE_CHARS})`,
119
+ });
120
+ }
121
+
91
122
  /** Finds an executable on PATH, or returns undefined. */
92
123
  export async function findCommand(command: string): Promise<string | undefined> {
93
124
  if (command.includes("/")) {
@@ -111,6 +142,23 @@ async function executable(path: string): Promise<boolean> {
111
142
  }
112
143
  }
113
144
 
145
+ /** What a caller gives when a reply's worker may stay for the next reply. */
146
+ export interface KeptRunOptions {
147
+ readonly home: string;
148
+ /** The harness name; its kept directory is under this home. */
149
+ readonly name: string;
150
+ /** The one conversation the worker answers, such as `chat:C-0022`. */
151
+ readonly scope: string;
152
+ /** What the worker was started with; a different key never reuses it. */
153
+ readonly key: string;
154
+ /** Test seam: the kept time; defaults to `KEPT_WORKER_MS`. */
155
+ readonly timeoutMs?: number | undefined;
156
+ /** Test seam: how long the first line may take; defaults to `KEPT_FIRST_LINE_MS`. */
157
+ readonly firstLineMs?: number | undefined;
158
+ /** Test seam: the most workers this home keeps; defaults to `MAX_KEPT_WORKERS`. */
159
+ readonly max?: number | undefined;
160
+ }
161
+
114
162
  export interface AgentRunOptions {
115
163
  /** The command name or path, resolved on PATH when it names no directory. */
116
164
  readonly command: string;
@@ -129,6 +177,8 @@ export interface AgentRunOptions {
129
177
  * command runs. Needs `interactive`; without it nothing is written.
130
178
  */
131
179
  readonly inbox?: MessageInbox | undefined;
180
+ /** Set by a chat reply: keep this worker after a done reply and reuse it next time. */
181
+ readonly keep?: KeptRunOptions | undefined;
132
182
  readonly wallMs: number;
133
183
  readonly stallMs: number;
134
184
  readonly signal: AbortSignal;
@@ -141,6 +191,16 @@ export interface AgentRunOptions {
141
191
  line: string,
142
192
  reply: (text: string) => void,
143
193
  ) => void | Promise<void>;
194
+ /**
195
+ * Called with the length of a stdout line past `MAX_LINE_CHARS`, which was
196
+ * dropped unread. The run goes on with the next line.
197
+ */
198
+ readonly onSkipped?: ((chars: number) => void) | undefined;
199
+ /**
200
+ * Called once the command has started and before any of its output is read:
201
+ * a harness with no session handshake writes its ready line here.
202
+ */
203
+ readonly onStart?: (() => void) | undefined;
144
204
  /**
145
205
  * Classifies one complete stdout line. A line that starts a tool call pauses
146
206
  * the stall timer until a line that ends it arrives; the wall limit still
@@ -165,47 +225,229 @@ export interface AgentRunOutcome {
165
225
  readonly stderrTail: readonly string[];
166
226
  }
167
227
 
228
+ /** An outcome with nothing wrong, plus what the caller knows. */
229
+ function emptyOutcome(overrides: Partial<AgentRunOutcome>): AgentRunOutcome {
230
+ return {
231
+ exitCode: null,
232
+ signal: null,
233
+ cancelled: false,
234
+ wall: false,
235
+ stall: false,
236
+ lineTooLong: false,
237
+ missing: false,
238
+ spawnError: undefined,
239
+ stderrTail: [],
240
+ ...overrides,
241
+ };
242
+ }
243
+
244
+ /** Why one run is being stopped; `cancel` is the host's signal. */
245
+ export type StopKind = "cancel" | "wall" | "stall" | "line";
246
+
247
+ /** What one run watches: the wall time, a stalled stream, the host's signal and mid-run messages. */
248
+ export interface WatchedRun {
249
+ /** Counts a tool call in a line and restarts the stall timer; call for every line. */
250
+ line(line: string): void;
251
+ /** Starts the wall and stall timers; before the run's program is spoken to. */
252
+ start(): void;
253
+ /** Takes the host's mid-run messages and tells it the run has begun. */
254
+ listenInbox(): void;
255
+ /** Stops the run for this reason, once. */
256
+ interrupt(kind: StopKind): void;
257
+ /** Clears the timers, the inbox listener and the abort listener. */
258
+ end(): void;
259
+ /** The reason the run is being stopped, while it is. */
260
+ readonly stoppingFor: StopKind | undefined;
261
+ }
262
+
263
+ export interface WatchOptions {
264
+ readonly clock: Clock;
265
+ readonly wallMs: number;
266
+ readonly stallMs: number;
267
+ readonly signal: AbortSignal;
268
+ readonly toolEvent?: ((line: string) => ToolEvent | undefined) | undefined;
269
+ /** Begins stopping the program; the watcher has already recorded the reason. */
270
+ readonly beginStop: (kind: StopKind) => void;
271
+ readonly inbox?: MessageInbox | undefined;
272
+ readonly reply: (text: string) => boolean | void;
273
+ }
274
+
275
+ /**
276
+ * One run's wall timer, stall timer, abort listener and inbox listener. A line
277
+ * restarts the stall only while no tool call is open: a tool may run as long as
278
+ * it needs, and only the wall limit watches it.
279
+ */
280
+ export function watchRun(options: WatchOptions): WatchedRun {
281
+ const { clock } = options;
282
+ let finished = false;
283
+ let stoppingFor: StopKind | undefined;
284
+ let toolCalls = 0;
285
+ let wallTimer: unknown;
286
+ let stallTimer: unknown;
287
+ let stopListening: (() => void) | undefined;
288
+
289
+ const interrupt = (kind: StopKind): void => {
290
+ if (finished || stoppingFor !== undefined) return;
291
+ stoppingFor = kind;
292
+ options.beginStop(kind);
293
+ };
294
+ const resetStall = (): void => {
295
+ if (options.stallMs <= 0) return;
296
+ if (stallTimer !== undefined) {
297
+ clock.clearTimeout(stallTimer);
298
+ stallTimer = undefined;
299
+ }
300
+ if (toolCalls > 0) return;
301
+ stallTimer = clock.setTimeout(() => {
302
+ if (!finished) interrupt("stall");
303
+ }, options.stallMs);
304
+ };
305
+ const onAbort = (): void => interrupt("cancel");
306
+ options.signal.addEventListener("abort", onAbort, { once: true });
307
+
308
+ return {
309
+ get stoppingFor() {
310
+ return stoppingFor;
311
+ },
312
+ line(line: string): void {
313
+ const activity = options.toolEvent?.(line);
314
+ if (activity === "tool-start") toolCalls += 1;
315
+ else if (activity === "tool-end") toolCalls = Math.max(0, toolCalls - 1);
316
+ resetStall();
317
+ },
318
+ start(): void {
319
+ if (options.wallMs > 0) {
320
+ wallTimer = clock.setTimeout(() => {
321
+ if (!finished) interrupt("wall");
322
+ }, options.wallMs);
323
+ }
324
+ resetStall();
325
+ },
326
+ listenInbox(): void {
327
+ stopListening =
328
+ options.inbox === undefined
329
+ ? undefined
330
+ : options.inbox.listen((text) => {
331
+ if (finished) return false;
332
+ return options.reply(messageLine(text)) ?? true;
333
+ });
334
+ if (options.wallMs > 0) options.inbox?.begin?.(options.wallMs);
335
+ },
336
+ interrupt,
337
+ end(): void {
338
+ finished = true;
339
+ if (wallTimer !== undefined) clock.clearTimeout(wallTimer);
340
+ if (stallTimer !== undefined) clock.clearTimeout(stallTimer);
341
+ stopListening?.();
342
+ options.signal.removeEventListener("abort", onAbort);
343
+ },
344
+ };
345
+ }
346
+
347
+ /**
348
+ * Ends the workers this home keeps beyond the cap, the one idle longest first.
349
+ * `over` decides whether the count is too high: a reply that just finished
350
+ * trims above the cap, and a reply about to start a worker trims at it.
351
+ */
352
+ export async function trimKept(
353
+ keep: KeptRunOptions,
354
+ clock: Clock,
355
+ over: (count: number, max: number) => boolean,
356
+ ): Promise<void> {
357
+ const max = keep.max ?? MAX_KEPT_WORKERS;
358
+ const kept = [...readKeptWorkersInHome(keep.home)].sort(
359
+ (left, right) => left.lastUsedAt - right.lastUsedAt,
360
+ );
361
+ while (over(kept.length, max) && kept.length > 0) {
362
+ const idle = kept.find((record) => record.busy !== true) ?? kept[0];
363
+ if (idle === undefined) break;
364
+ await stopKeptWorker(idle, { clock });
365
+ kept.splice(kept.indexOf(idle), 1);
366
+ }
367
+ }
368
+
369
+ /** The outcome fields a stop reason sets. */
370
+ function stoppedOutcome(stoppingFor: StopKind | undefined): Partial<AgentRunOutcome> {
371
+ return {
372
+ ...(stoppingFor === "cancel" ? { cancelled: true } : {}),
373
+ ...(stoppingFor === "wall" ? { wall: true } : {}),
374
+ ...(stoppingFor === "stall" ? { stall: true } : {}),
375
+ ...(stoppingFor === "line" ? { lineTooLong: true } : {}),
376
+ };
377
+ }
378
+
168
379
  /**
169
380
  * Splits a stream into complete lines, holding the unterminated tail up to
170
381
  * `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.
382
+ * handler holds the stream, so the pipe cannot fill memory. A line that grows
383
+ * past the limit is dropped as it arrives and `onSkipped` gets its length once
384
+ * it ends; the next line is read as usual. A line that passes
385
+ * `MAX_SKIPPED_LINE_CHARS` without ending calls `onOverflow`.
174
386
  */
175
387
  class Lines {
176
388
  private buffer = "";
389
+ /** The length of the over-long line being dropped; undefined when none is. */
390
+ private skipped: number | undefined = undefined;
177
391
  private readonly onLine: (line: string) => void | Promise<void>;
392
+ private readonly onSkipped: (chars: number) => void;
178
393
  private readonly onOverflow: () => void;
179
394
 
180
395
  constructor(
181
396
  onLine: (line: string) => void | Promise<void>,
397
+ onSkipped: (chars: number) => void,
182
398
  onOverflow: () => void,
183
399
  ) {
184
400
  this.onLine = onLine;
401
+ this.onSkipped = onSkipped;
185
402
  this.onOverflow = onOverflow;
186
403
  }
187
404
 
188
405
  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();
406
+ let rest = text;
407
+ while (rest.length > 0) {
408
+ if (this.skipped !== undefined) {
409
+ const end = rest.indexOf("\n");
410
+ if (end < 0) {
411
+ this.skipped += rest.length;
412
+ if (this.skipped > MAX_SKIPPED_LINE_CHARS) {
413
+ this.skipped = undefined;
414
+ this.onOverflow();
415
+ }
416
+ return;
417
+ }
418
+ this.onSkipped(this.skipped + end);
419
+ this.skipped = undefined;
420
+ rest = rest.slice(end + 1);
421
+ continue;
422
+ }
423
+ this.buffer += rest;
424
+ rest = "";
425
+ let newline = this.buffer.indexOf("\n");
426
+ while (newline >= 0) {
427
+ const line = this.buffer.slice(0, newline);
428
+ this.buffer = this.buffer.slice(newline + 1);
429
+ if (line.length > MAX_LINE_CHARS) this.onSkipped(line.length);
430
+ else await this.onLine(line);
431
+ newline = this.buffer.indexOf("\n");
432
+ }
433
+ if (this.buffer.length > MAX_LINE_CHARS) {
434
+ this.skipped = this.buffer.length;
435
+ this.buffer = "";
436
+ }
201
437
  }
202
438
  }
203
439
 
204
440
  async end(): Promise<void> {
441
+ if (this.skipped !== undefined) {
442
+ const chars = this.skipped;
443
+ this.skipped = undefined;
444
+ this.onSkipped(chars);
445
+ }
205
446
  if (this.buffer.length === 0) return;
206
447
  const rest = this.buffer;
207
448
  this.buffer = "";
208
- await this.onLine(rest);
449
+ if (rest.length > MAX_LINE_CHARS) this.onSkipped(rest.length);
450
+ else await this.onLine(rest);
209
451
  }
210
452
  }
211
453
 
@@ -278,45 +520,32 @@ async function readTail(path: string): Promise<string> {
278
520
  export async function runAgent(
279
521
  options: AgentRunOptions,
280
522
  ): 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
-
523
+ if (options.keep !== undefined) return runKeptAgent(options, options.keep);
294
524
  if (options.signal.aborted) {
295
- return empty({ cancelled: true });
525
+ return emptyOutcome({ cancelled: true });
296
526
  }
297
527
 
298
528
  const executablePath = await findCommand(options.command);
299
529
  if (executablePath === undefined) {
300
- return empty({ missing: true });
530
+ return emptyOutcome({ missing: true });
301
531
  }
302
532
 
303
533
  const clock = options.clock ?? systemClock;
304
- let resetStallForLine: () => void = () => {};
534
+ let watchedLine: (line: string) => void = () => {};
305
535
  let onLineOverflow: () => void = () => {};
306
- const reply = (text: string): void => {
536
+ let skippedLine: (chars: number) => void = () => {};
537
+ const reply = (text: string): boolean => {
307
538
  const pipe = child.stdin;
308
- if (options.interactive !== true || pipe === null || pipe.destroyed) return;
539
+ if (options.interactive !== true || pipe === null || pipe.destroyed) return false;
309
540
  pipe.write(`${text}\n`);
541
+ return true;
310
542
  };
311
- let toolCalls = 0;
312
- let onToolActivity: (activity: ToolEvent) => void = () => {};
313
543
  const stdoutLines = new Lines(
314
544
  (line) => {
315
- const activity = options.toolEvent?.(line);
316
- if (activity !== undefined) onToolActivity(activity);
317
- resetStallForLine();
545
+ watchedLine(line);
318
546
  return options.onLine(line, reply);
319
547
  },
548
+ (chars) => skippedLine(chars),
320
549
  () => onLineOverflow(),
321
550
  );
322
551
  const stderrTail = new Tail(undefined);
@@ -325,7 +554,7 @@ export async function runAgent(
325
554
  try {
326
555
  errorDirectory = await mkdtemp(join(tmpdir(), "operad-harness-"));
327
556
  } catch (error) {
328
- return empty({ spawnError: messageOf(error) });
557
+ return emptyOutcome({ spawnError: messageOf(error) });
329
558
  }
330
559
  const errorPath = join(errorDirectory, "stderr");
331
560
 
@@ -351,10 +580,13 @@ export async function runAgent(
351
580
  );
352
581
  } catch (error) {
353
582
  await rm(errorDirectory, { recursive: true, force: true });
354
- return empty({ spawnError: messageOf(error) });
583
+ return emptyOutcome({ spawnError: messageOf(error) });
355
584
  }
356
585
 
357
586
  trackRoot(child.pid);
587
+ // Before the first line is read: a harness with no session handshake is as
588
+ // ready as it will say, so its ready line must not wait for its first output.
589
+ options.onStart?.();
358
590
  let sentinelExited = false;
359
591
  const failed = new Promise<string>((resolve) => {
360
592
  child.once("error", (error) => resolve(messageOf(error)));
@@ -408,50 +640,26 @@ export async function runAgent(
408
640
  ready: readyGate,
409
641
  });
410
642
 
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);
643
+ const watch = watchRun({
644
+ clock,
645
+ wallMs: options.wallMs,
646
+ stallMs: options.stallMs,
647
+ signal: options.signal,
648
+ toolEvent: options.toolEvent,
649
+ beginStop: () => {
650
+ void stop();
651
+ },
652
+ inbox: options.inbox,
653
+ reply,
654
+ });
655
+ watchedLine = (line) => watch.line(line);
656
+ onLineOverflow = () => watch.interrupt("line");
657
+ skippedLine = (chars) => {
658
+ // A dropped line is still output: the stall timer restarts.
659
+ watch.line("");
660
+ options.onSkipped?.(chars);
454
661
  };
662
+ watch.start();
455
663
 
456
664
  const startup = await Promise.race<Startup>([
457
665
  nextControl().then(
@@ -484,9 +692,8 @@ export async function runAgent(
484
692
  };
485
693
 
486
694
  if (startup.kind !== "ready") {
487
- finished = true;
488
- clearTimers();
489
- options.signal.removeEventListener("abort", onAbort);
695
+ const stoppingFor = watch.stoppingFor;
696
+ watch.end();
490
697
  await stop();
491
698
  await Promise.race([exited, failed]);
492
699
  const { tail, exit } = await finish();
@@ -498,29 +705,22 @@ export async function runAgent(
498
705
  : startup.kind === "closed"
499
706
  ? "the harness shell stopped before the command started"
500
707
  : undefined;
501
- return {
708
+ return emptyOutcome({
502
709
  exitCode: exit.code,
503
710
  signal: exit.signal,
504
711
  cancelled: stoppingFor === "cancel",
505
712
  wall: stoppingFor === "wall",
506
713
  stall: stoppingFor === "stall",
507
714
  lineTooLong: stoppingFor === "line",
508
- missing: false,
509
715
  spawnError,
510
716
  stderrTail: tail,
511
- };
717
+ });
512
718
  }
513
719
 
514
720
  readySeen = true;
515
721
  openGate();
516
722
  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);
723
+ watch.listenInbox();
524
724
 
525
725
  const ended = await Promise.race<Ended>([
526
726
  nextControl().then((line): Ended => {
@@ -532,10 +732,8 @@ export async function runAgent(
532
732
  exited.then((exit): Ended => ({ kind: "exit", exit })),
533
733
  ]);
534
734
 
535
- finished = true;
536
- stopListening?.();
537
- clearTimers();
538
- options.signal.removeEventListener("abort", onAbort);
735
+ const stoppingFor = watch.stoppingFor;
736
+ watch.end();
539
737
 
540
738
  let exit: Exit;
541
739
  if (ended.kind === "closed") exit = await exited;
@@ -554,15 +752,400 @@ export async function runAgent(
554
752
  await Promise.race([exited, failed]);
555
753
  const { tail } = await finish();
556
754
 
557
- return {
755
+ return emptyOutcome({
558
756
  exitCode: exit.code,
559
757
  signal: exit.signal,
560
758
  cancelled: stoppingFor === "cancel",
561
759
  wall: stoppingFor === "wall",
562
760
  stall: stoppingFor === "stall",
563
761
  lineTooLong: stoppingFor === "line",
564
- missing: false,
565
- spawnError: undefined,
566
762
  stderrTail: tail,
763
+ });
764
+ }
765
+
766
+ /** The result line of a worker as far as keeping cares: its name, or undefined. */
767
+ function keptResultName(line: string): "done" | "failed" | "cancelled" | undefined {
768
+ let value: unknown;
769
+ try {
770
+ value = JSON.parse(line);
771
+ } catch {
772
+ return undefined;
773
+ }
774
+ if (typeof value !== "object" || value === null) return undefined;
775
+ if (Reflect.get(value, "type") !== "result") return undefined;
776
+ const name: unknown = Reflect.get(value, "result");
777
+ return name === "done" || name === "failed" || name === "cancelled" ? name : undefined;
778
+ }
779
+
780
+ /**
781
+ * Waits a bounded time for a kept worker to record that it is ready for the
782
+ * next reply. A file that exists but cannot be read as a record is not ready:
783
+ * a worker may create the file before it writes the record into it.
784
+ */
785
+ export async function keptRecordAppears(
786
+ meta: string,
787
+ options: {
788
+ readonly now?: (() => number) | undefined;
789
+ readonly wait?: ((directory: string, entry: string, ms: number) => Promise<void>) | undefined;
790
+ } = {},
791
+ ): Promise<void> {
792
+ const now = options.now ?? Date.now;
793
+ const wait = options.wait ?? waitForChange;
794
+ const deadline = now() + 1_000;
795
+ while (readKeptWorker(meta) === undefined && now() < deadline) {
796
+ await wait(dirname(meta), basename(meta), 25);
797
+ }
798
+ }
799
+
800
+ /**
801
+ * Runs one reply through a worker kept from an earlier reply. Undefined means
802
+ * the worker was not reached or did not answer its first line; the caller then
803
+ * starts a new one, and the old worker has been ended.
804
+ */
805
+ async function runKeptSocket(
806
+ record: KeptWorkerRecord,
807
+ options: AgentRunOptions,
808
+ keep: KeptRunOptions,
809
+ clock: Clock,
810
+ ): Promise<AgentRunOutcome | undefined> {
811
+ const firstLineMs = keep.firstLineMs ?? KEPT_FIRST_LINE_MS;
812
+ const socket: Socket = connect(record.socket);
813
+ const connected = await new Promise<boolean>((resolve) => {
814
+ let settled = false;
815
+ const finish = (ok: boolean): void => {
816
+ if (settled) return;
817
+ settled = true;
818
+ clock.clearTimeout(timer);
819
+ resolve(ok);
820
+ };
821
+ const timer = clock.setTimeout(() => finish(false), firstLineMs);
822
+ socket.once("connect", () => finish(true));
823
+ socket.once("error", () => finish(false));
824
+ socket.once("close", () => finish(false));
825
+ });
826
+ if (!connected) {
827
+ socket.destroy();
828
+ await stopKeptWorker(record, { clock });
829
+ return undefined;
830
+ }
831
+
832
+ let firstSeen = false;
833
+ let firstResolve: () => void = () => {};
834
+ const first = new Promise<void>((resolve) => {
835
+ firstResolve = resolve;
836
+ });
837
+ const firstTimer = clock.setTimeout(() => firstResolve(), firstLineMs);
838
+ let resultName: "done" | "failed" | "cancelled" | undefined;
839
+ let resultResolve: () => void = () => {};
840
+ const result = new Promise<void>((resolve) => {
841
+ resultResolve = resolve;
842
+ });
843
+ let closedResolve: () => void = () => {};
844
+ const closed = new Promise<void>((resolve) => {
845
+ closedResolve = resolve;
846
+ });
847
+ const stopWorker = async (): Promise<void> => {
848
+ if (socket.destroyed) {
849
+ await stopKeptWorker(record, { clock });
850
+ return;
851
+ }
852
+ socket.destroy();
853
+ await stopKeptWorker(record, { clock });
854
+ };
855
+ const reply = (text: string): void => {
856
+ if (!socket.destroyed) socket.write(`${text}\n`);
567
857
  };
858
+ const watch = watchRun({
859
+ clock,
860
+ wallMs: options.wallMs,
861
+ stallMs: options.stallMs,
862
+ signal: options.signal,
863
+ toolEvent: options.toolEvent,
864
+ beginStop: () => {
865
+ void stopWorker();
866
+ },
867
+ inbox: options.inbox,
868
+ reply,
869
+ });
870
+ const lines = new Lines(
871
+ async (line) => {
872
+ if (!firstSeen) {
873
+ firstSeen = true;
874
+ clock.clearTimeout(firstTimer);
875
+ firstResolve();
876
+ }
877
+ watch.line(line);
878
+ await options.onLine(line, reply);
879
+ const name = keptResultName(line);
880
+ if (name !== undefined && resultName === undefined) {
881
+ resultName = name;
882
+ resultResolve();
883
+ }
884
+ },
885
+ (chars) => {
886
+ watch.line("");
887
+ options.onSkipped?.(chars);
888
+ },
889
+ () => watch.interrupt("line"),
890
+ );
891
+ socket.once("close", () => {
892
+ closedResolve();
893
+ if (!firstSeen) firstResolve();
894
+ });
895
+ socket.once("error", () => {
896
+ closedResolve();
897
+ if (!firstSeen) firstResolve();
898
+ });
899
+ const drained = consume(socket, lines);
900
+
901
+ watch.listenInbox();
902
+ socket.write(`${options.stdin ?? ""}\n`);
903
+ options.onStart?.();
904
+ watch.start();
905
+
906
+ const started = await Promise.race<"line" | "closed">([
907
+ first.then(() => (firstSeen ? "line" : "closed")),
908
+ closed.then(() => "closed"),
909
+ ]);
910
+ if (started !== "line" || !firstSeen) {
911
+ watch.end();
912
+ clock.clearTimeout(firstTimer);
913
+ await stopWorker();
914
+ socket.destroy();
915
+ await drained;
916
+ return undefined;
917
+ }
918
+
919
+ await Promise.race([result, closed]);
920
+ if (resultName === undefined && watch.stoppingFor === undefined) {
921
+ // A close often arrives just before the last line has been handed over.
922
+ await drained;
923
+ }
924
+ const stoppingFor = watch.stoppingFor;
925
+ watch.end();
926
+ clock.clearTimeout(firstTimer);
927
+ socket.destroy();
928
+ await drained;
929
+
930
+ if (resultName === "done") {
931
+ return emptyOutcome({ exitCode: 0 });
932
+ }
933
+ await stopKeptWorker(record, { clock });
934
+ if (resultName !== undefined) {
935
+ return emptyOutcome({ exitCode: resultName === "failed" ? 1 : 143, ...stoppedOutcome(stoppingFor) });
936
+ }
937
+ return emptyOutcome(stoppedOutcome(stoppingFor));
938
+ }
939
+
940
+ /** Starts a new worker that will stay after a done reply. */
941
+ async function runKeptFresh(
942
+ options: AgentRunOptions,
943
+ keep: KeptRunOptions,
944
+ clock: Clock,
945
+ ): Promise<AgentRunOutcome> {
946
+ const executablePath = await findCommand(options.command);
947
+ if (executablePath === undefined) return emptyOutcome({ missing: true });
948
+ const slot = newKeptWorkerSlot(keep.home, keep.name);
949
+ const env: NodeJS.ProcessEnv = { ...process.env };
950
+ // A kept worker is not a left-over of the run that started it: no run marker.
951
+ delete env["OPERAD_RUN"];
952
+ delete env["OPERAD_RUN_HOME"];
953
+
954
+ let child: ChildProcess;
955
+ try {
956
+ child = spawn(executablePath, [...options.args, keptWorkerArgument(slot.token)], {
957
+ cwd: options.cwd,
958
+ env,
959
+ detached: true,
960
+ stdio: ["pipe", "pipe", "pipe"],
961
+ });
962
+ } catch (error) {
963
+ return emptyOutcome({ spawnError: messageOf(error) });
964
+ }
965
+ child.unref();
966
+
967
+ const stdout = child.stdout;
968
+ const stderr = child.stderr;
969
+ const stderrTail = new Tail(undefined);
970
+ let resultName: "done" | "failed" | "cancelled" | undefined;
971
+ let resultResolve: () => void = () => {};
972
+ const result = new Promise<void>((resolve) => {
973
+ resultResolve = resolve;
974
+ });
975
+ let exitedResolve: (exit: Exit) => void = () => {};
976
+ const exited = new Promise<Exit>((resolve) => {
977
+ exitedResolve = resolve;
978
+ });
979
+ let spawnResolve: (message: string) => void = () => {};
980
+ const spawnFailed = new Promise<string>((resolve) => {
981
+ spawnResolve = resolve;
982
+ });
983
+
984
+ const stopWorker = async (): Promise<void> => {
985
+ const pid = child.pid;
986
+ if (pid === undefined) return;
987
+ killProcessGroup(pid, "SIGTERM");
988
+ await clock.sleep(KILL_GRACE_MS);
989
+ killProcessGroup(pid, "SIGKILL");
990
+ await stopKeptWorker(
991
+ {
992
+ pid,
993
+ token: slot.token,
994
+ scope: keep.scope,
995
+ key: keep.key,
996
+ socket: slot.socket,
997
+ meta: slot.meta,
998
+ session: null,
999
+ startedAt: 0,
1000
+ lastUsedAt: 0,
1001
+ },
1002
+ { clock },
1003
+ );
1004
+ };
1005
+ const reply = (text: string): void => {
1006
+ if (child.stdin !== null && !child.stdin.destroyed) child.stdin.write(`${text}\n`);
1007
+ };
1008
+ const watch = watchRun({
1009
+ clock,
1010
+ wallMs: options.wallMs,
1011
+ stallMs: options.stallMs,
1012
+ signal: options.signal,
1013
+ toolEvent: options.toolEvent,
1014
+ beginStop: () => {
1015
+ void stopWorker();
1016
+ },
1017
+ inbox: options.inbox,
1018
+ reply,
1019
+ });
1020
+ let outputDrained: Promise<void> = Promise.resolve();
1021
+ if (stdout !== null) {
1022
+ const lines = new Lines(
1023
+ async (line) => {
1024
+ watch.line(line);
1025
+ await options.onLine(line, reply);
1026
+ const name = keptResultName(line);
1027
+ if (name !== undefined && resultName === undefined) {
1028
+ resultName = name;
1029
+ resultResolve();
1030
+ }
1031
+ },
1032
+ (chars) => {
1033
+ watch.line("");
1034
+ options.onSkipped?.(chars);
1035
+ },
1036
+ () => watch.interrupt("line"),
1037
+ );
1038
+ outputDrained = consume(stdout, lines).then(() => lines.end());
1039
+ }
1040
+ const drainStderr =
1041
+ stderr === null
1042
+ ? Promise.resolve()
1043
+ : (async () => {
1044
+ const decoder = new TextDecoder();
1045
+ try {
1046
+ for await (const chunk of stderr) stderrTail.push(decoder.decode(chunk as Uint8Array, { stream: true }));
1047
+ } catch {
1048
+ // A process that failed to start has no stderr.
1049
+ }
1050
+ })();
1051
+
1052
+ child.once("error", (error) => spawnResolve(messageOf(error)));
1053
+ child.once("exit", (code, signal) => exitedResolve({ code, signal }));
1054
+ if (child.stdin !== null) child.stdin.on("error", () => undefined);
1055
+ watch.listenInbox();
1056
+ // The first input tells the worker where its socket and record are, so it can
1057
+ // stay after this reply. A reused worker ignores this field.
1058
+ let firstInput = options.stdin ?? "";
1059
+ try {
1060
+ const value: unknown = JSON.parse(firstInput);
1061
+ if (isRecord(value)) {
1062
+ firstInput = JSON.stringify({
1063
+ ...value,
1064
+ keep: {
1065
+ socket: slot.socket,
1066
+ meta: slot.meta,
1067
+ token: slot.token,
1068
+ scope: keep.scope,
1069
+ key: keep.key,
1070
+ timeoutMs: keep.timeoutMs ?? KEPT_WORKER_MS,
1071
+ },
1072
+ });
1073
+ }
1074
+ } catch {
1075
+ // Not JSON: the worker will report invalid input as it always did.
1076
+ }
1077
+ reply(firstInput);
1078
+ options.onStart?.();
1079
+ watch.start();
1080
+
1081
+ const settled = await Promise.race<"result" | "exit" | "error">([
1082
+ result.then(() => "result" as const),
1083
+ exited.then(() => "exit" as const),
1084
+ spawnFailed.then(() => "error" as const),
1085
+ ]);
1086
+ if (settled === "exit" && resultName === undefined) await outputDrained;
1087
+ const stoppingFor = watch.stoppingFor;
1088
+ watch.end();
1089
+
1090
+ if (settled === "error") {
1091
+ const spawnError = await spawnFailed;
1092
+ await stopWorker();
1093
+ return emptyOutcome({ spawnError });
1094
+ }
1095
+
1096
+ if (settled === "result" && resultName === "done") {
1097
+ // The worker writes its record after the Result; the next message must find it.
1098
+ await keptRecordAppears(slot.meta);
1099
+ // Two replies can finish at once in one home: the cap holds after the
1100
+ // record is there too, not only before a worker is started.
1101
+ await trimKept(keep, clock, (count, max) => count > max);
1102
+ child.stdin?.destroy();
1103
+ child.stdout?.destroy();
1104
+ child.stderr?.destroy();
1105
+ return emptyOutcome({ exitCode: 0 });
1106
+ }
1107
+
1108
+ const exit = settled === "exit" ? await exited : await Promise.race<Exit | undefined>([exited, Promise.resolve(undefined)]);
1109
+ if (resultName !== undefined) {
1110
+ child.stdin?.destroy();
1111
+ child.stdout?.destroy();
1112
+ child.stderr?.destroy();
1113
+ await stopWorker();
1114
+ return emptyOutcome({
1115
+ exitCode: resultName === "failed" ? 1 : 143,
1116
+ ...stoppedOutcome(stoppingFor),
1117
+ });
1118
+ }
1119
+ await stopWorker();
1120
+ await drainStderr;
1121
+ return emptyOutcome({
1122
+ exitCode: exit?.code ?? null,
1123
+ signal: exit?.signal ?? null,
1124
+ ...stoppedOutcome(stoppingFor),
1125
+ stderrTail: stderrTail.lines(20),
1126
+ });
1127
+ }
1128
+
1129
+ /** Chooses, ends and starts kept workers for one reply. */
1130
+ async function runKeptAgent(options: AgentRunOptions, keep: KeptRunOptions): Promise<AgentRunOutcome> {
1131
+ if (options.signal.aborted) return emptyOutcome({ cancelled: true });
1132
+ const clock = options.clock ?? systemClock;
1133
+ const records = readKeptWorkers(keep.home, keep.name);
1134
+ const sameScope = records.filter((record) => record.scope === keep.scope);
1135
+ // A worker started with another model, effort, directory, profile or skills
1136
+ // no longer holds; end it before this reply starts a new one.
1137
+ for (const record of sameScope.filter((record) => record.key !== keep.key)) {
1138
+ await stopKeptWorker(record, { clock });
1139
+ }
1140
+ const candidates = sameScope
1141
+ .filter((record) => record.key === keep.key)
1142
+ .sort((left, right) => right.lastUsedAt - left.lastUsedAt);
1143
+ for (const record of candidates) {
1144
+ const outcome = await runKeptSocket(record, options, keep, clock);
1145
+ if (outcome !== undefined) return outcome;
1146
+ }
1147
+
1148
+ // A new worker is the fourth only after the one idle longest has ended.
1149
+ await trimKept(keep, clock, (count, max) => count >= max);
1150
+ return runKeptFresh(options, keep, clock);
568
1151
  }