@operad-io/harness-process 0.1.0 → 0.2.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
 
@@ -111,6 +124,23 @@ async function executable(path: string): Promise<boolean> {
111
124
  }
112
125
  }
113
126
 
127
+ /** What a caller gives when a reply's worker may stay for the next reply. */
128
+ export interface KeptRunOptions {
129
+ readonly home: string;
130
+ /** The harness name; its kept directory is under this home. */
131
+ readonly name: string;
132
+ /** The one conversation the worker answers, such as `chat:C-0022`. */
133
+ readonly scope: string;
134
+ /** What the worker was started with; a different key never reuses it. */
135
+ readonly key: string;
136
+ /** Test seam: the kept time; defaults to `KEPT_WORKER_MS`. */
137
+ readonly timeoutMs?: number | undefined;
138
+ /** Test seam: how long the first line may take; defaults to `KEPT_FIRST_LINE_MS`. */
139
+ readonly firstLineMs?: number | undefined;
140
+ /** Test seam: the most workers this home keeps; defaults to `MAX_KEPT_WORKERS`. */
141
+ readonly max?: number | undefined;
142
+ }
143
+
114
144
  export interface AgentRunOptions {
115
145
  /** The command name or path, resolved on PATH when it names no directory. */
116
146
  readonly command: string;
@@ -129,6 +159,8 @@ export interface AgentRunOptions {
129
159
  * command runs. Needs `interactive`; without it nothing is written.
130
160
  */
131
161
  readonly inbox?: MessageInbox | undefined;
162
+ /** Set by a chat reply: keep this worker after a done reply and reuse it next time. */
163
+ readonly keep?: KeptRunOptions | undefined;
132
164
  readonly wallMs: number;
133
165
  readonly stallMs: number;
134
166
  readonly signal: AbortSignal;
@@ -141,6 +173,11 @@ export interface AgentRunOptions {
141
173
  line: string,
142
174
  reply: (text: string) => void,
143
175
  ) => void | Promise<void>;
176
+ /**
177
+ * Called once the command has started and before any of its output is read:
178
+ * a harness with no session handshake writes its ready line here.
179
+ */
180
+ readonly onStart?: (() => void) | undefined;
144
181
  /**
145
182
  * Classifies one complete stdout line. A line that starts a tool call pauses
146
183
  * the stall timer until a line that ends it arrives; the wall limit still
@@ -165,6 +202,157 @@ export interface AgentRunOutcome {
165
202
  readonly stderrTail: readonly string[];
166
203
  }
167
204
 
205
+ /** An outcome with nothing wrong, plus what the caller knows. */
206
+ function emptyOutcome(overrides: Partial<AgentRunOutcome>): AgentRunOutcome {
207
+ return {
208
+ exitCode: null,
209
+ signal: null,
210
+ cancelled: false,
211
+ wall: false,
212
+ stall: false,
213
+ lineTooLong: false,
214
+ missing: false,
215
+ spawnError: undefined,
216
+ stderrTail: [],
217
+ ...overrides,
218
+ };
219
+ }
220
+
221
+ /** Why one run is being stopped; `cancel` is the host's signal. */
222
+ export type StopKind = "cancel" | "wall" | "stall" | "line";
223
+
224
+ /** What one run watches: the wall time, a stalled stream, the host's signal and mid-run messages. */
225
+ export interface WatchedRun {
226
+ /** Counts a tool call in a line and restarts the stall timer; call for every line. */
227
+ line(line: string): void;
228
+ /** Starts the wall and stall timers; before the run's program is spoken to. */
229
+ start(): void;
230
+ /** Takes the host's mid-run messages and tells it the run has begun. */
231
+ listenInbox(): void;
232
+ /** Stops the run for this reason, once. */
233
+ interrupt(kind: StopKind): void;
234
+ /** Clears the timers, the inbox listener and the abort listener. */
235
+ end(): void;
236
+ /** The reason the run is being stopped, while it is. */
237
+ readonly stoppingFor: StopKind | undefined;
238
+ }
239
+
240
+ export interface WatchOptions {
241
+ readonly clock: Clock;
242
+ readonly wallMs: number;
243
+ readonly stallMs: number;
244
+ readonly signal: AbortSignal;
245
+ readonly toolEvent?: ((line: string) => ToolEvent | undefined) | undefined;
246
+ /** Begins stopping the program; the watcher has already recorded the reason. */
247
+ readonly beginStop: (kind: StopKind) => void;
248
+ readonly inbox?: MessageInbox | undefined;
249
+ readonly reply: (text: string) => boolean | void;
250
+ }
251
+
252
+ /**
253
+ * One run's wall timer, stall timer, abort listener and inbox listener. A line
254
+ * restarts the stall only while no tool call is open: a tool may run as long as
255
+ * it needs, and only the wall limit watches it.
256
+ */
257
+ export function watchRun(options: WatchOptions): WatchedRun {
258
+ const { clock } = options;
259
+ let finished = false;
260
+ let stoppingFor: StopKind | undefined;
261
+ let toolCalls = 0;
262
+ let wallTimer: unknown;
263
+ let stallTimer: unknown;
264
+ let stopListening: (() => void) | undefined;
265
+
266
+ const interrupt = (kind: StopKind): void => {
267
+ if (finished || stoppingFor !== undefined) return;
268
+ stoppingFor = kind;
269
+ options.beginStop(kind);
270
+ };
271
+ const resetStall = (): void => {
272
+ if (options.stallMs <= 0) return;
273
+ if (stallTimer !== undefined) {
274
+ clock.clearTimeout(stallTimer);
275
+ stallTimer = undefined;
276
+ }
277
+ if (toolCalls > 0) return;
278
+ stallTimer = clock.setTimeout(() => {
279
+ if (!finished) interrupt("stall");
280
+ }, options.stallMs);
281
+ };
282
+ const onAbort = (): void => interrupt("cancel");
283
+ options.signal.addEventListener("abort", onAbort, { once: true });
284
+
285
+ return {
286
+ get stoppingFor() {
287
+ return stoppingFor;
288
+ },
289
+ line(line: string): void {
290
+ const activity = options.toolEvent?.(line);
291
+ if (activity === "tool-start") toolCalls += 1;
292
+ else if (activity === "tool-end") toolCalls = Math.max(0, toolCalls - 1);
293
+ resetStall();
294
+ },
295
+ start(): void {
296
+ if (options.wallMs > 0) {
297
+ wallTimer = clock.setTimeout(() => {
298
+ if (!finished) interrupt("wall");
299
+ }, options.wallMs);
300
+ }
301
+ resetStall();
302
+ },
303
+ listenInbox(): void {
304
+ stopListening =
305
+ options.inbox === undefined
306
+ ? undefined
307
+ : options.inbox.listen((text) => {
308
+ if (finished) return false;
309
+ return options.reply(messageLine(text)) ?? true;
310
+ });
311
+ if (options.wallMs > 0) options.inbox?.begin?.(options.wallMs);
312
+ },
313
+ interrupt,
314
+ end(): void {
315
+ finished = true;
316
+ if (wallTimer !== undefined) clock.clearTimeout(wallTimer);
317
+ if (stallTimer !== undefined) clock.clearTimeout(stallTimer);
318
+ stopListening?.();
319
+ options.signal.removeEventListener("abort", onAbort);
320
+ },
321
+ };
322
+ }
323
+
324
+ /**
325
+ * Ends the workers this home keeps beyond the cap, the one idle longest first.
326
+ * `over` decides whether the count is too high: a reply that just finished
327
+ * trims above the cap, and a reply about to start a worker trims at it.
328
+ */
329
+ export async function trimKept(
330
+ keep: KeptRunOptions,
331
+ clock: Clock,
332
+ over: (count: number, max: number) => boolean,
333
+ ): Promise<void> {
334
+ const max = keep.max ?? MAX_KEPT_WORKERS;
335
+ const kept = [...readKeptWorkersInHome(keep.home)].sort(
336
+ (left, right) => left.lastUsedAt - right.lastUsedAt,
337
+ );
338
+ while (over(kept.length, max) && kept.length > 0) {
339
+ const idle = kept.find((record) => record.busy !== true) ?? kept[0];
340
+ if (idle === undefined) break;
341
+ await stopKeptWorker(idle, { clock });
342
+ kept.splice(kept.indexOf(idle), 1);
343
+ }
344
+ }
345
+
346
+ /** The outcome fields a stop reason sets. */
347
+ function stoppedOutcome(stoppingFor: StopKind | undefined): Partial<AgentRunOutcome> {
348
+ return {
349
+ ...(stoppingFor === "cancel" ? { cancelled: true } : {}),
350
+ ...(stoppingFor === "wall" ? { wall: true } : {}),
351
+ ...(stoppingFor === "stall" ? { stall: true } : {}),
352
+ ...(stoppingFor === "line" ? { lineTooLong: true } : {}),
353
+ };
354
+ }
355
+
168
356
  /**
169
357
  * Splits a stream into complete lines, holding the unterminated tail up to
170
358
  * `MAX_LINE_CHARS`. Each line is handed over before the next is read: a busy
@@ -278,43 +466,28 @@ async function readTail(path: string): Promise<string> {
278
466
  export async function runAgent(
279
467
  options: AgentRunOptions,
280
468
  ): 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
-
469
+ if (options.keep !== undefined) return runKeptAgent(options, options.keep);
294
470
  if (options.signal.aborted) {
295
- return empty({ cancelled: true });
471
+ return emptyOutcome({ cancelled: true });
296
472
  }
297
473
 
298
474
  const executablePath = await findCommand(options.command);
299
475
  if (executablePath === undefined) {
300
- return empty({ missing: true });
476
+ return emptyOutcome({ missing: true });
301
477
  }
302
478
 
303
479
  const clock = options.clock ?? systemClock;
304
- let resetStallForLine: () => void = () => {};
480
+ let watchedLine: (line: string) => void = () => {};
305
481
  let onLineOverflow: () => void = () => {};
306
- const reply = (text: string): void => {
482
+ const reply = (text: string): boolean => {
307
483
  const pipe = child.stdin;
308
- if (options.interactive !== true || pipe === null || pipe.destroyed) return;
484
+ if (options.interactive !== true || pipe === null || pipe.destroyed) return false;
309
485
  pipe.write(`${text}\n`);
486
+ return true;
310
487
  };
311
- let toolCalls = 0;
312
- let onToolActivity: (activity: ToolEvent) => void = () => {};
313
488
  const stdoutLines = new Lines(
314
489
  (line) => {
315
- const activity = options.toolEvent?.(line);
316
- if (activity !== undefined) onToolActivity(activity);
317
- resetStallForLine();
490
+ watchedLine(line);
318
491
  return options.onLine(line, reply);
319
492
  },
320
493
  () => onLineOverflow(),
@@ -325,7 +498,7 @@ export async function runAgent(
325
498
  try {
326
499
  errorDirectory = await mkdtemp(join(tmpdir(), "operad-harness-"));
327
500
  } catch (error) {
328
- return empty({ spawnError: messageOf(error) });
501
+ return emptyOutcome({ spawnError: messageOf(error) });
329
502
  }
330
503
  const errorPath = join(errorDirectory, "stderr");
331
504
 
@@ -351,10 +524,13 @@ export async function runAgent(
351
524
  );
352
525
  } catch (error) {
353
526
  await rm(errorDirectory, { recursive: true, force: true });
354
- return empty({ spawnError: messageOf(error) });
527
+ return emptyOutcome({ spawnError: messageOf(error) });
355
528
  }
356
529
 
357
530
  trackRoot(child.pid);
531
+ // Before the first line is read: a harness with no session handshake is as
532
+ // ready as it will say, so its ready line must not wait for its first output.
533
+ options.onStart?.();
358
534
  let sentinelExited = false;
359
535
  const failed = new Promise<string>((resolve) => {
360
536
  child.once("error", (error) => resolve(messageOf(error)));
@@ -408,50 +584,21 @@ export async function runAgent(
408
584
  ready: readyGate,
409
585
  });
410
586
 
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
- };
587
+ const watch = watchRun({
588
+ clock,
589
+ wallMs: options.wallMs,
590
+ stallMs: options.stallMs,
591
+ signal: options.signal,
592
+ toolEvent: options.toolEvent,
593
+ beginStop: () => {
594
+ void stop();
595
+ },
596
+ inbox: options.inbox,
597
+ reply,
598
+ });
599
+ watchedLine = (line) => watch.line(line);
600
+ onLineOverflow = () => watch.interrupt("line");
601
+ watch.start();
455
602
 
456
603
  const startup = await Promise.race<Startup>([
457
604
  nextControl().then(
@@ -484,9 +631,8 @@ export async function runAgent(
484
631
  };
485
632
 
486
633
  if (startup.kind !== "ready") {
487
- finished = true;
488
- clearTimers();
489
- options.signal.removeEventListener("abort", onAbort);
634
+ const stoppingFor = watch.stoppingFor;
635
+ watch.end();
490
636
  await stop();
491
637
  await Promise.race([exited, failed]);
492
638
  const { tail, exit } = await finish();
@@ -498,29 +644,22 @@ export async function runAgent(
498
644
  : startup.kind === "closed"
499
645
  ? "the harness shell stopped before the command started"
500
646
  : undefined;
501
- return {
647
+ return emptyOutcome({
502
648
  exitCode: exit.code,
503
649
  signal: exit.signal,
504
650
  cancelled: stoppingFor === "cancel",
505
651
  wall: stoppingFor === "wall",
506
652
  stall: stoppingFor === "stall",
507
653
  lineTooLong: stoppingFor === "line",
508
- missing: false,
509
654
  spawnError,
510
655
  stderrTail: tail,
511
- };
656
+ });
512
657
  }
513
658
 
514
659
  readySeen = true;
515
660
  openGate();
516
661
  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);
662
+ watch.listenInbox();
524
663
 
525
664
  const ended = await Promise.race<Ended>([
526
665
  nextControl().then((line): Ended => {
@@ -532,10 +671,8 @@ export async function runAgent(
532
671
  exited.then((exit): Ended => ({ kind: "exit", exit })),
533
672
  ]);
534
673
 
535
- finished = true;
536
- stopListening?.();
537
- clearTimers();
538
- options.signal.removeEventListener("abort", onAbort);
674
+ const stoppingFor = watch.stoppingFor;
675
+ watch.end();
539
676
 
540
677
  let exit: Exit;
541
678
  if (ended.kind === "closed") exit = await exited;
@@ -554,15 +691,392 @@ export async function runAgent(
554
691
  await Promise.race([exited, failed]);
555
692
  const { tail } = await finish();
556
693
 
557
- return {
694
+ return emptyOutcome({
558
695
  exitCode: exit.code,
559
696
  signal: exit.signal,
560
697
  cancelled: stoppingFor === "cancel",
561
698
  wall: stoppingFor === "wall",
562
699
  stall: stoppingFor === "stall",
563
700
  lineTooLong: stoppingFor === "line",
564
- missing: false,
565
- spawnError: undefined,
566
701
  stderrTail: tail,
702
+ });
703
+ }
704
+
705
+ /** The result line of a worker as far as keeping cares: its name, or undefined. */
706
+ function keptResultName(line: string): "done" | "failed" | "cancelled" | undefined {
707
+ let value: unknown;
708
+ try {
709
+ value = JSON.parse(line);
710
+ } catch {
711
+ return undefined;
712
+ }
713
+ if (typeof value !== "object" || value === null) return undefined;
714
+ if (Reflect.get(value, "type") !== "result") return undefined;
715
+ const name: unknown = Reflect.get(value, "result");
716
+ return name === "done" || name === "failed" || name === "cancelled" ? name : undefined;
717
+ }
718
+
719
+ /**
720
+ * Waits a bounded time for a kept worker to record that it is ready for the
721
+ * next reply. A file that exists but cannot be read as a record is not ready:
722
+ * a worker may create the file before it writes the record into it.
723
+ */
724
+ export async function keptRecordAppears(
725
+ meta: string,
726
+ options: {
727
+ readonly now?: (() => number) | undefined;
728
+ readonly wait?: ((directory: string, entry: string, ms: number) => Promise<void>) | undefined;
729
+ } = {},
730
+ ): Promise<void> {
731
+ const now = options.now ?? Date.now;
732
+ const wait = options.wait ?? waitForChange;
733
+ const deadline = now() + 1_000;
734
+ while (readKeptWorker(meta) === undefined && now() < deadline) {
735
+ await wait(dirname(meta), basename(meta), 25);
736
+ }
737
+ }
738
+
739
+ /**
740
+ * Runs one reply through a worker kept from an earlier reply. Undefined means
741
+ * the worker was not reached or did not answer its first line; the caller then
742
+ * starts a new one, and the old worker has been ended.
743
+ */
744
+ async function runKeptSocket(
745
+ record: KeptWorkerRecord,
746
+ options: AgentRunOptions,
747
+ keep: KeptRunOptions,
748
+ clock: Clock,
749
+ ): Promise<AgentRunOutcome | undefined> {
750
+ const firstLineMs = keep.firstLineMs ?? KEPT_FIRST_LINE_MS;
751
+ const socket: Socket = connect(record.socket);
752
+ const connected = await new Promise<boolean>((resolve) => {
753
+ let settled = false;
754
+ const finish = (ok: boolean): void => {
755
+ if (settled) return;
756
+ settled = true;
757
+ clock.clearTimeout(timer);
758
+ resolve(ok);
759
+ };
760
+ const timer = clock.setTimeout(() => finish(false), firstLineMs);
761
+ socket.once("connect", () => finish(true));
762
+ socket.once("error", () => finish(false));
763
+ socket.once("close", () => finish(false));
764
+ });
765
+ if (!connected) {
766
+ socket.destroy();
767
+ await stopKeptWorker(record, { clock });
768
+ return undefined;
769
+ }
770
+
771
+ let firstSeen = false;
772
+ let firstResolve: () => void = () => {};
773
+ const first = new Promise<void>((resolve) => {
774
+ firstResolve = resolve;
775
+ });
776
+ const firstTimer = clock.setTimeout(() => firstResolve(), firstLineMs);
777
+ let resultName: "done" | "failed" | "cancelled" | undefined;
778
+ let resultResolve: () => void = () => {};
779
+ const result = new Promise<void>((resolve) => {
780
+ resultResolve = resolve;
781
+ });
782
+ let closedResolve: () => void = () => {};
783
+ const closed = new Promise<void>((resolve) => {
784
+ closedResolve = resolve;
785
+ });
786
+ const stopWorker = async (): Promise<void> => {
787
+ if (socket.destroyed) {
788
+ await stopKeptWorker(record, { clock });
789
+ return;
790
+ }
791
+ socket.destroy();
792
+ await stopKeptWorker(record, { clock });
793
+ };
794
+ const reply = (text: string): void => {
795
+ if (!socket.destroyed) socket.write(`${text}\n`);
796
+ };
797
+ const watch = watchRun({
798
+ clock,
799
+ wallMs: options.wallMs,
800
+ stallMs: options.stallMs,
801
+ signal: options.signal,
802
+ toolEvent: options.toolEvent,
803
+ beginStop: () => {
804
+ void stopWorker();
805
+ },
806
+ inbox: options.inbox,
807
+ reply,
808
+ });
809
+ const lines = new Lines(
810
+ async (line) => {
811
+ if (!firstSeen) {
812
+ firstSeen = true;
813
+ clock.clearTimeout(firstTimer);
814
+ firstResolve();
815
+ }
816
+ watch.line(line);
817
+ await options.onLine(line, reply);
818
+ const name = keptResultName(line);
819
+ if (name !== undefined && resultName === undefined) {
820
+ resultName = name;
821
+ resultResolve();
822
+ }
823
+ },
824
+ () => watch.interrupt("line"),
825
+ );
826
+ socket.once("close", () => {
827
+ closedResolve();
828
+ if (!firstSeen) firstResolve();
829
+ });
830
+ socket.once("error", () => {
831
+ closedResolve();
832
+ if (!firstSeen) firstResolve();
833
+ });
834
+ const drained = consume(socket, lines);
835
+
836
+ watch.listenInbox();
837
+ socket.write(`${options.stdin ?? ""}\n`);
838
+ options.onStart?.();
839
+ watch.start();
840
+
841
+ const started = await Promise.race<"line" | "closed">([
842
+ first.then(() => (firstSeen ? "line" : "closed")),
843
+ closed.then(() => "closed"),
844
+ ]);
845
+ if (started !== "line" || !firstSeen) {
846
+ watch.end();
847
+ clock.clearTimeout(firstTimer);
848
+ await stopWorker();
849
+ socket.destroy();
850
+ await drained;
851
+ return undefined;
852
+ }
853
+
854
+ await Promise.race([result, closed]);
855
+ if (resultName === undefined && watch.stoppingFor === undefined) {
856
+ // A close often arrives just before the last line has been handed over.
857
+ await drained;
858
+ }
859
+ const stoppingFor = watch.stoppingFor;
860
+ watch.end();
861
+ clock.clearTimeout(firstTimer);
862
+ socket.destroy();
863
+ await drained;
864
+
865
+ if (resultName === "done") {
866
+ return emptyOutcome({ exitCode: 0 });
867
+ }
868
+ await stopKeptWorker(record, { clock });
869
+ if (resultName !== undefined) {
870
+ return emptyOutcome({ exitCode: resultName === "failed" ? 1 : 143, ...stoppedOutcome(stoppingFor) });
871
+ }
872
+ return emptyOutcome(stoppedOutcome(stoppingFor));
873
+ }
874
+
875
+ /** Starts a new worker that will stay after a done reply. */
876
+ async function runKeptFresh(
877
+ options: AgentRunOptions,
878
+ keep: KeptRunOptions,
879
+ clock: Clock,
880
+ ): Promise<AgentRunOutcome> {
881
+ const executablePath = await findCommand(options.command);
882
+ if (executablePath === undefined) return emptyOutcome({ missing: true });
883
+ const slot = newKeptWorkerSlot(keep.home, keep.name);
884
+ const env: NodeJS.ProcessEnv = { ...process.env };
885
+ // A kept worker is not a left-over of the run that started it: no run marker.
886
+ delete env["OPERAD_RUN"];
887
+ delete env["OPERAD_RUN_HOME"];
888
+
889
+ let child: ChildProcess;
890
+ try {
891
+ child = spawn(executablePath, [...options.args, keptWorkerArgument(slot.token)], {
892
+ cwd: options.cwd,
893
+ env,
894
+ detached: true,
895
+ stdio: ["pipe", "pipe", "pipe"],
896
+ });
897
+ } catch (error) {
898
+ return emptyOutcome({ spawnError: messageOf(error) });
899
+ }
900
+ child.unref();
901
+
902
+ const stdout = child.stdout;
903
+ const stderr = child.stderr;
904
+ const stderrTail = new Tail(undefined);
905
+ let resultName: "done" | "failed" | "cancelled" | undefined;
906
+ let resultResolve: () => void = () => {};
907
+ const result = new Promise<void>((resolve) => {
908
+ resultResolve = resolve;
909
+ });
910
+ let exitedResolve: (exit: Exit) => void = () => {};
911
+ const exited = new Promise<Exit>((resolve) => {
912
+ exitedResolve = resolve;
913
+ });
914
+ let spawnResolve: (message: string) => void = () => {};
915
+ const spawnFailed = new Promise<string>((resolve) => {
916
+ spawnResolve = resolve;
917
+ });
918
+
919
+ const stopWorker = async (): Promise<void> => {
920
+ const pid = child.pid;
921
+ if (pid === undefined) return;
922
+ killProcessGroup(pid, "SIGTERM");
923
+ await clock.sleep(KILL_GRACE_MS);
924
+ killProcessGroup(pid, "SIGKILL");
925
+ await stopKeptWorker(
926
+ {
927
+ pid,
928
+ token: slot.token,
929
+ scope: keep.scope,
930
+ key: keep.key,
931
+ socket: slot.socket,
932
+ meta: slot.meta,
933
+ session: null,
934
+ startedAt: 0,
935
+ lastUsedAt: 0,
936
+ },
937
+ { clock },
938
+ );
567
939
  };
940
+ const reply = (text: string): void => {
941
+ if (child.stdin !== null && !child.stdin.destroyed) child.stdin.write(`${text}\n`);
942
+ };
943
+ const watch = watchRun({
944
+ clock,
945
+ wallMs: options.wallMs,
946
+ stallMs: options.stallMs,
947
+ signal: options.signal,
948
+ toolEvent: options.toolEvent,
949
+ beginStop: () => {
950
+ void stopWorker();
951
+ },
952
+ inbox: options.inbox,
953
+ reply,
954
+ });
955
+ let outputDrained: Promise<void> = Promise.resolve();
956
+ if (stdout !== null) {
957
+ const lines = new Lines(
958
+ async (line) => {
959
+ watch.line(line);
960
+ await options.onLine(line, reply);
961
+ const name = keptResultName(line);
962
+ if (name !== undefined && resultName === undefined) {
963
+ resultName = name;
964
+ resultResolve();
965
+ }
966
+ },
967
+ () => watch.interrupt("line"),
968
+ );
969
+ outputDrained = consume(stdout, lines).then(() => lines.end());
970
+ }
971
+ const drainStderr =
972
+ stderr === null
973
+ ? Promise.resolve()
974
+ : (async () => {
975
+ const decoder = new TextDecoder();
976
+ try {
977
+ for await (const chunk of stderr) stderrTail.push(decoder.decode(chunk as Uint8Array, { stream: true }));
978
+ } catch {
979
+ // A process that failed to start has no stderr.
980
+ }
981
+ })();
982
+
983
+ child.once("error", (error) => spawnResolve(messageOf(error)));
984
+ child.once("exit", (code, signal) => exitedResolve({ code, signal }));
985
+ if (child.stdin !== null) child.stdin.on("error", () => undefined);
986
+ watch.listenInbox();
987
+ // The first input tells the worker where its socket and record are, so it can
988
+ // stay after this reply. A reused worker ignores this field.
989
+ let firstInput = options.stdin ?? "";
990
+ try {
991
+ const value: unknown = JSON.parse(firstInput);
992
+ if (isRecord(value)) {
993
+ firstInput = JSON.stringify({
994
+ ...value,
995
+ keep: {
996
+ socket: slot.socket,
997
+ meta: slot.meta,
998
+ token: slot.token,
999
+ scope: keep.scope,
1000
+ key: keep.key,
1001
+ timeoutMs: keep.timeoutMs ?? KEPT_WORKER_MS,
1002
+ },
1003
+ });
1004
+ }
1005
+ } catch {
1006
+ // Not JSON: the worker will report invalid input as it always did.
1007
+ }
1008
+ reply(firstInput);
1009
+ options.onStart?.();
1010
+ watch.start();
1011
+
1012
+ const settled = await Promise.race<"result" | "exit" | "error">([
1013
+ result.then(() => "result" as const),
1014
+ exited.then(() => "exit" as const),
1015
+ spawnFailed.then(() => "error" as const),
1016
+ ]);
1017
+ if (settled === "exit" && resultName === undefined) await outputDrained;
1018
+ const stoppingFor = watch.stoppingFor;
1019
+ watch.end();
1020
+
1021
+ if (settled === "error") {
1022
+ const spawnError = await spawnFailed;
1023
+ await stopWorker();
1024
+ return emptyOutcome({ spawnError });
1025
+ }
1026
+
1027
+ if (settled === "result" && resultName === "done") {
1028
+ // The worker writes its record after the Result; the next message must find it.
1029
+ await keptRecordAppears(slot.meta);
1030
+ // Two replies can finish at once in one home: the cap holds after the
1031
+ // record is there too, not only before a worker is started.
1032
+ await trimKept(keep, clock, (count, max) => count > max);
1033
+ child.stdin?.destroy();
1034
+ child.stdout?.destroy();
1035
+ child.stderr?.destroy();
1036
+ return emptyOutcome({ exitCode: 0 });
1037
+ }
1038
+
1039
+ const exit = settled === "exit" ? await exited : await Promise.race<Exit | undefined>([exited, Promise.resolve(undefined)]);
1040
+ if (resultName !== undefined) {
1041
+ child.stdin?.destroy();
1042
+ child.stdout?.destroy();
1043
+ child.stderr?.destroy();
1044
+ await stopWorker();
1045
+ return emptyOutcome({
1046
+ exitCode: resultName === "failed" ? 1 : 143,
1047
+ ...stoppedOutcome(stoppingFor),
1048
+ });
1049
+ }
1050
+ await stopWorker();
1051
+ await drainStderr;
1052
+ return emptyOutcome({
1053
+ exitCode: exit?.code ?? null,
1054
+ signal: exit?.signal ?? null,
1055
+ ...stoppedOutcome(stoppingFor),
1056
+ stderrTail: stderrTail.lines(20),
1057
+ });
1058
+ }
1059
+
1060
+ /** Chooses, ends and starts kept workers for one reply. */
1061
+ async function runKeptAgent(options: AgentRunOptions, keep: KeptRunOptions): Promise<AgentRunOutcome> {
1062
+ if (options.signal.aborted) return emptyOutcome({ cancelled: true });
1063
+ const clock = options.clock ?? systemClock;
1064
+ const records = readKeptWorkers(keep.home, keep.name);
1065
+ const sameScope = records.filter((record) => record.scope === keep.scope);
1066
+ // A worker started with another model, effort, directory, profile or skills
1067
+ // no longer holds; end it before this reply starts a new one.
1068
+ for (const record of sameScope.filter((record) => record.key !== keep.key)) {
1069
+ await stopKeptWorker(record, { clock });
1070
+ }
1071
+ const candidates = sameScope
1072
+ .filter((record) => record.key === keep.key)
1073
+ .sort((left, right) => right.lastUsedAt - left.lastUsedAt);
1074
+ for (const record of candidates) {
1075
+ const outcome = await runKeptSocket(record, options, keep, clock);
1076
+ if (outcome !== undefined) return outcome;
1077
+ }
1078
+
1079
+ // A new worker is the fourth only after the one idle longest has ended.
1080
+ await trimKept(keep, clock, (count, max) => count >= max);
1081
+ return runKeptFresh(options, keep, clock);
568
1082
  }