@notation/factory 0.5.4 → 0.6.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/runner/index.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import { existsSync } from "node:fs";
4
- import { copyFile, mkdir, mkdtemp, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
+ import { copyFile, mkdir, mkdtemp, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
5
5
  import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
6
6
  import { homedir, tmpdir } from "node:os";
7
7
  import { dirname, join, normalize, resolve } from "node:path";
@@ -9,6 +9,8 @@ import { pathToFileURL } from "node:url";
9
9
  import type { CodeHostRunner, RuntimeRunner } from "../contracts/runner.ts";
10
10
  import type { ThreadMessage } from "../router/channel.ts";
11
11
  import type {
12
+ Heartbeat,
13
+ HeartbeatResult,
12
14
  MessagesRequest,
13
15
  MessagesResult,
14
16
  Relay,
@@ -39,12 +41,48 @@ const PROGRESS_INTERVAL_MS = Number(process.env.FACTORY_PROGRESS_INTERVAL_MS ??
39
41
  /** How often the runner edits the run's message to update its clock, while the agent writes no new message. */
40
42
  const CLOCK_INTERVAL_MS = Number(process.env.FACTORY_CLOCK_INTERVAL_MS ?? 60 * 1000);
41
43
 
44
+ /** How often the runner posts a heartbeat to the router for each run it holds. The router marks a run lost after 5 minutes without one. */
45
+ const HEARTBEAT_INTERVAL_MS = Number(process.env.FACTORY_HEARTBEAT_INTERVAL_MS ?? 60 * 1000);
46
+
47
+ /** How long a heartbeat may take before the runner gives up on it and tries again with the next one. */
48
+ const HEARTBEAT_TIMEOUT_MS = 10 * 1000;
49
+
50
+ /** How long the runner waits before it posts a run's `done` heartbeat again, after the router couldn't be reached or failed. */
51
+ const DONE_RETRY_MS = Number(process.env.FACTORY_DONE_RETRY_MS ?? 10 * 1000);
52
+
53
+ /** How many times the runner posts a run's `done` heartbeat, until the router takes it. */
54
+ const DONE_ATTEMPTS = 3;
55
+
42
56
  /** The longest the runner waits, once it's told to stop, for the replies that say its runs were lost. */
43
57
  const STOP_REPLY_TIMEOUT_MS = 5000;
44
58
 
59
+ /** How often the runner saves a run's worktree and session to the state store while the agent runs. */
60
+ const SAVE_INTERVAL_MS = Number(process.env.FACTORY_SAVE_INTERVAL_MS ?? 60 * 1000);
61
+
62
+ /**
63
+ * earlyoom's options. It stops the process with the highest OOM score once
64
+ * less than 10% of memory is available, and logs a memory report every 60
65
+ * seconds. `-s 100,100` has it act on memory alone, so swap can't delay it
66
+ * until the container thrashes. The agents' processes have a higher OOM
67
+ * score than the runner, so earlyoom stops them first. See
68
+ * `AGENT_OOM_SCORE_ADJ`.
69
+ */
70
+ const EARLYOOM_ARGS = ["-r", "60", "-s", "100,100"];
71
+
72
+ /**
73
+ * The OOM score adjustment of the agents' processes and the processes they
74
+ * start. The runner keeps 0, so earlyoom and the kernel stop an agent's
75
+ * processes before the runner. A process without privileges can raise its
76
+ * own score, but not lower it.
77
+ */
78
+ const AGENT_OOM_SCORE_ADJ = 500;
79
+
45
80
  /** The longest a run's agent may take. */
46
81
  const RUN_TIMEOUT_MS = 2 * 60 * 60 * 1000;
47
82
 
83
+ /** How long a stopped command's processes have to exit after SIGTERM, before they get SIGKILL. */
84
+ const STOP_GRACE_MS = 10 * 1000;
85
+
48
86
  /**
49
87
  * The system prompt every agent gets, before its own `systemPrompt`.
50
88
  * `channel` is what the conversation is, such as `GitHub issue`.
@@ -75,6 +113,26 @@ const message = (error: unknown) => (error instanceof Error ? error.message : St
75
113
 
76
114
  const log = (entry: Record<string, unknown>) => console.log(JSON.stringify({ at: new Date().toISOString(), ...entry }));
77
115
 
116
+ /** The most characters of a tool call's argument that the runner logs. */
117
+ const MAX_TOOL_ARGUMENT = 200;
118
+
119
+ /** The fields of a tool's input that the runner logs as its main argument, in the order it looks for them. */
120
+ const MAIN_ARGUMENT_FIELDS = ["command", "file_path", "directory_path", "path", "pattern", "globPattern", "url", "query", "description", "prompt"];
121
+
122
+ /**
123
+ * A tool call's main argument on one line, cut to `MAX_TOOL_ARGUMENT`
124
+ * characters: the first of `MAIN_ARGUMENT_FIELDS` that is a string, or else
125
+ * the whole input as JSON. An input that is a string is its own argument.
126
+ */
127
+ const toolArgument = (input: unknown) => {
128
+ if (input === undefined || input === null) return undefined;
129
+ const fields = typeof input === "object" ? (input as Record<string, unknown>) : {};
130
+ const field = MAIN_ARGUMENT_FIELDS.find((key) => typeof fields[key] === "string");
131
+ const argument = typeof input === "string" ? input : field ? (fields[field] as string) : JSON.stringify(input);
132
+ const line = argument.replace(/\s+/g, " ").trim();
133
+ return line.length > MAX_TOOL_ARGUMENT ? `${line.slice(0, MAX_TOOL_ARGUMENT)}…` : line;
134
+ };
135
+
78
136
  type Result = { code: number | null; stdout: string; stderr: string };
79
137
 
80
138
  const tail = (text: string) => (text.length > MAX_OUTPUT_BYTES ? text.slice(-MAX_OUTPUT_BYTES) : text);
@@ -82,7 +140,10 @@ const tail = (text: string) => (text.length > MAX_OUTPUT_BYTES ? text.slice(-MAX
82
140
  /**
83
141
  * Runs `command`, and resolves with its exit code and output. Rejects only
84
142
  * if it can't start. `input` is written to its stdin. `onLine` gets each
85
- * line of its stdout as it's written.
143
+ * line of its stdout as it's written. Once `signal` aborts, it stops the
144
+ * command, as it does once `timeout` passes. The command runs in its own
145
+ * process group, so stopping it sends SIGTERM to every process it started,
146
+ * such as an agent's `tsc`, and SIGKILL `STOP_GRACE_MS` later.
86
147
  */
87
148
  const exec = (
88
149
  command: string,
@@ -93,16 +154,18 @@ const exec = (
93
154
  timeout,
94
155
  input,
95
156
  onLine,
157
+ signal,
96
158
  }: {
97
159
  cwd?: string;
98
160
  env?: Record<string, string | undefined>;
99
161
  timeout?: number;
100
162
  input?: string;
101
163
  onLine?: (line: string) => void;
164
+ signal?: AbortSignal;
102
165
  } = {},
103
166
  ) =>
104
167
  new Promise<Result>((resolve, reject) => {
105
- const child = spawn(command, args, { cwd, env: env ?? process.env, stdio: ["pipe", "pipe", "pipe"] });
168
+ const child = spawn(command, args, { cwd, env: env ?? process.env, stdio: ["pipe", "pipe", "pipe"], detached: true });
106
169
  // A command that exits without reading all its input closes the pipe, and its exit code says why.
107
170
  child.stdin.on("error", () => {});
108
171
  child.stdin.end(input);
@@ -124,10 +187,25 @@ const exec = (
124
187
  stderr += chunk;
125
188
  if (stderr.length > 2 * MAX_OUTPUT_BYTES) stderr = tail(stderr);
126
189
  });
127
- const timer = timeout ? setTimeout(() => child.kill("SIGTERM"), timeout) : undefined;
190
+ const signalGroup = (name: NodeJS.Signals) => {
191
+ try {
192
+ if (child.pid) process.kill(-child.pid, name);
193
+ } catch {}
194
+ };
195
+ let killer: ReturnType<typeof setTimeout> | undefined;
196
+ // The SIGKILL isn't cancelled when the command exits, since the processes it started may outlive it.
197
+ const stop = () => {
198
+ if (killer) return;
199
+ signalGroup("SIGTERM");
200
+ killer = setTimeout(() => signalGroup("SIGKILL"), STOP_GRACE_MS);
201
+ };
202
+ const timer = timeout ? setTimeout(stop, timeout) : undefined;
203
+ if (signal?.aborted) stop();
204
+ else signal?.addEventListener("abort", stop, { once: true });
128
205
  child.on("error", reject);
129
206
  child.on("close", (code) => {
130
207
  clearTimeout(timer);
208
+ signal?.removeEventListener("abort", stop);
131
209
  if (line && onLine) onLine(line);
132
210
  resolve({ code, stdout: tail(stdout), stderr: tail(stderr) });
133
211
  });
@@ -239,20 +317,27 @@ const worktreeOf = (run: Run): Worktree => {
239
317
  * Saves the worktree to the state store, as a git bundle of one commit on
240
318
  * top of its HEAD. The commit holds every file that git doesn't ignore,
241
319
  * committed or not. The bundle leaves out what `origin` already has.
320
+ * Returns the snapshot's tree and parent, and skips the upload if they are
321
+ * `previous`, which an earlier save returned.
242
322
  */
243
- const saveWorktree = (worktree: Worktree) =>
323
+ const saveWorktree = (worktree: Worktree, previous?: string) =>
244
324
  withTempDir(async (dir) => {
245
325
  const cwd = worktree.path;
246
- // A copy of the worktree's index, so git only reads the files that changed.
326
+ // A copy of the worktree's index, so git only reads the files that
327
+ // changed, and the agent's own index stays as it is.
247
328
  const index = join(dir, "index");
248
329
  await copyFile(resolve(cwd, await git(["rev-parse", "--git-path", "index"], { cwd })), index);
249
330
  await git(["add", "--all"], { cwd, env: { GIT_INDEX_FILE: index } });
250
331
  const tree = await git(["write-tree"], { cwd, env: { GIT_INDEX_FILE: index } });
251
- const commit = await git(["commit-tree", tree, "-p", "HEAD", "-m", "Factory snapshot"], { cwd });
332
+ const head = await git(["rev-parse", "HEAD"], { cwd });
333
+ const snapshot = `${tree} ${head}`;
334
+ if (snapshot === previous) return snapshot;
335
+ const commit = await git(["commit-tree", tree, "-p", head, "-m", "Factory snapshot"], { cwd });
252
336
  await git(["update-ref", worktree.ref, commit], { cwd });
253
337
  const bundle = join(dir, "bundle");
254
338
  await git(["bundle", "create", "--quiet", bundle, worktree.ref, "--not", "--remotes=origin"], { cwd });
255
339
  await putState(worktree.key, await readFile(bundle));
340
+ return snapshot;
256
341
  });
257
342
 
258
343
  /**
@@ -460,11 +545,11 @@ const loadRuntime = (id: string) =>
460
545
  /**
461
546
  * Saves the conversation's session to the state store: its transcript
462
547
  * files, as a tarball of their paths under the runtime's transcripts
463
- * directory, and then the session's id and working directory.
548
+ * directory, and then the session's id, working directory and seen
549
+ * messages. Returns the session and the transcripts' sizes and times, and
550
+ * skips the upload if they are `previous`, which an earlier save returned.
464
551
  */
465
- const saveSession = async (run: Run, transcripts: string) => {
466
- const session = await readSession(run);
467
- if (!session) return;
552
+ const saveSession = async (run: Run, transcripts: string, session: Session, previous?: string) => {
468
553
  const paths: string[] = [];
469
554
  for (const project of await readdir(transcripts).catch(() => [])) {
470
555
  for (const name of [`${session.id}.jsonl`, `${session.id}.settings.json`, session.id]) {
@@ -473,6 +558,9 @@ const saveSession = async (run: Run, transcripts: string) => {
473
558
  if (existsSync(join(transcripts, project, name))) paths.push(`./${join(project, name)}`);
474
559
  }
475
560
  }
561
+ const stats = await Promise.all(paths.map((path) => stat(join(transcripts, path)).catch(() => undefined)));
562
+ const saved = JSON.stringify([session, paths, stats.map((s) => s && [s.size, s.mtimeMs])]);
563
+ if (saved === previous) return saved;
476
564
  if (paths.length > 0) {
477
565
  await withTempDir(async (dir) => {
478
566
  const tarball = join(dir, "session.tar.gz");
@@ -482,6 +570,43 @@ const saveSession = async (run: Run, transcripts: string) => {
482
570
  });
483
571
  }
484
572
  await putState(`${sessionKey(run)}.json`, Buffer.from(JSON.stringify(session)));
573
+ return saved;
574
+ };
575
+
576
+ /**
577
+ * Saves a run's worktree and session to the state store, one save at a
578
+ * time. `session` returns the session to save, or undefined while the runner
579
+ * doesn't know the session's id. `during` starts a save every
580
+ * `SAVE_INTERVAL_MS` while the agent runs, unless one is in progress, and
581
+ * returns a function that stops them. `final` waits for a save in progress,
582
+ * and then saves. Each save skips an upload whose contents haven't changed
583
+ * since the last one.
584
+ */
585
+ const saver = (run: Run, worktree: Worktree, transcripts: string, session: () => Session | undefined) => {
586
+ const last: { worktree?: string; session?: string } = {};
587
+ let inflight: Promise<void> | undefined;
588
+ const save = async () => {
589
+ last.worktree = await saveWorktree(worktree, last.worktree);
590
+ const current = session();
591
+ if (current) last.session = await saveSession(run, transcripts, current, last.session);
592
+ };
593
+ return {
594
+ during() {
595
+ const timer = setInterval(() => {
596
+ if (inflight) return;
597
+ inflight = save()
598
+ .catch((error: unknown) => log({ run: run.id, state: "periodic save failed", error: message(error) }))
599
+ .finally(() => {
600
+ inflight = undefined;
601
+ });
602
+ }, SAVE_INTERVAL_MS);
603
+ return () => clearInterval(timer);
604
+ },
605
+ async final() {
606
+ await inflight;
607
+ await save();
608
+ },
609
+ };
485
610
  };
486
611
 
487
612
  /** Restores the conversation's session from the state store, if this container doesn't have it. */
@@ -569,21 +694,28 @@ const buildPrompt = (run: Run, messages: ThreadMessage[], seen: Seen | undefined
569
694
  * Runs the run's agent in `cwd` with `prompt` on its stdin and the config
570
695
  * directory `configDir`, resuming the session `sessionId` if it's set.
571
696
  * Returns the agent's final message, or `error` if the CLI failed, and the
572
- * session id the CLI reported either way. `onMessage` gets each message the
573
- * agent writes while it runs, if the runtime reads them.
697
+ * session id the CLI reported either way. `progress` gets each message the
698
+ * agent writes while it runs, if the runtime reads them, and `onSession` the
699
+ * session's id. Once `signal` aborts, the runner stops the CLI.
574
700
  */
575
701
  const runAgent = async (
576
702
  adapter: RuntimeRunner,
577
703
  run: Run,
578
704
  { cwd, configDir, prompt, sessionId }: { cwd: string; configDir: string; prompt: string; sessionId?: string },
579
705
  progress: Progress,
706
+ onSession: (id: string) => void,
707
+ signal: AbortSignal,
580
708
  ): Promise<{ text: string; sessionId?: string; error?: string }> => {
581
709
  await mkdir(configDir, { recursive: true });
582
710
  const context = { cwd, prompt, systemPrompt: await systemPrompt(run, cwd), dataDir: DATA, configDir };
583
711
  const args = await adapter.args(run, context);
584
712
  if (sessionId) args.push(...adapter.resume(sessionId));
585
713
 
586
- const result = await exec(adapter.command, args, {
714
+ // The shell raises its own OOM score, which the agent's processes keep, and then becomes the agent's CLI.
715
+ const [command, commandArgs] = existsSync("/proc/self/oom_score_adj")
716
+ ? ["sh", ["-c", `echo ${AGENT_OOM_SCORE_ADJ} > /proc/self/oom_score_adj; exec "$0" "$@"`, adapter.command, ...args]]
717
+ : [adapter.command, args];
718
+ const result = await exec(command, commandArgs, {
587
719
  cwd,
588
720
  env: {
589
721
  ...process.env,
@@ -594,11 +726,18 @@ const runAgent = async (
594
726
  },
595
727
  timeout: RUN_TIMEOUT_MS,
596
728
  input: adapter.input?.(context) ?? prompt,
729
+ signal,
597
730
  onLine: (line) => {
598
731
  const model = adapter.model?.(line);
599
732
  if (model) progress.model(model);
600
733
  const text = adapter.message?.(line);
601
734
  if (text?.trim()) progress.message(text);
735
+ const id = adapter.session?.(line);
736
+ if (id) onSession(id);
737
+ for (const tool of adapter.tools?.(line) ?? []) {
738
+ const argument = toolArgument(tool.input);
739
+ log({ run: run.id, worktree: run.worktree?.branch ?? "scratch", tool: tool.name, ...(argument && { argument }) });
740
+ }
602
741
  },
603
742
  });
604
743
  const output = adapter.parse(result.stdout);
@@ -617,16 +756,33 @@ const assertCommand = async (command: string, name: string) => {
617
756
  }
618
757
  };
619
758
 
620
- /** Posts `text` to the run's conversation, in place of `message` if it's set. Resolves to the message the router names. */
621
- const relay = async (run: Run, text: string, message?: ReplyMessage) => {
622
- const body: Relay = { ticket: run.reply.ticket, signature: run.reply.signature, text, ...(message && { message }) };
759
+ /**
760
+ * Posts `text` to the run's conversation, in place of `message` if it's set.
761
+ * With `done`, it's the run's last reply. Resolves to the message the router
762
+ * names, or to `lost` if the router refused the reply because it marked the
763
+ * run lost.
764
+ */
765
+ const relay = async (run: Run, text: string, message: ReplyMessage | undefined, done: boolean) => {
766
+ const body: Relay = {
767
+ ticket: run.reply.ticket,
768
+ signature: run.reply.signature,
769
+ text,
770
+ ...(message && { message }),
771
+ ...(done && { done }),
772
+ };
623
773
  const response = await fetch(run.reply.url, {
624
774
  method: "POST",
625
775
  headers: { "content-type": "application/json" },
626
776
  body: JSON.stringify(body),
627
777
  });
628
- if (!response.ok) throw new Error(`The router refused the reply with status ${response.status}: ${await response.text()}`);
629
- return ((await response.json().catch(() => ({}))) as Partial<RelayResult>).message;
778
+ const answer = await response.text();
779
+ let result: Partial<RelayResult> & { lost?: boolean } = {};
780
+ try {
781
+ result = JSON.parse(answer);
782
+ } catch {}
783
+ if (response.status === 409 && result.lost) return "lost";
784
+ if (!response.ok) throw new Error(`The router refused the reply with status ${response.status}: ${answer}`);
785
+ return result.message;
630
786
  };
631
787
 
632
788
  /** What the runner reads from the agent's output while it runs. */
@@ -671,10 +827,12 @@ const progressText = (text: string, ms: number, model?: string) => {
671
827
  * "Thinking..." for each part of a thought. While the agent writes no new
672
828
  * message, the shown one is posted again every `CLOCK_INTERVAL_MS`, so its
673
829
  * clock stays current. `finish` posts the final reply
674
- * in their place. The first post replaces the message that the router
675
- * posted while the run waited for the container, if there is one.
830
+ * in their place, as the run's last reply unless `done` is false. The first
831
+ * post replaces the message that the router posted while the run waited for
832
+ * the container, if there is one. A post that the router refuses because it
833
+ * marked the run lost ends the run.
676
834
  */
677
- const replies = (run: Run) => {
835
+ const replies = (run: Run, lost: AbortController) => {
678
836
  let posted: ReplyMessage | undefined = run.reply.message;
679
837
  let pending: string | undefined;
680
838
  let shown: string | undefined;
@@ -685,9 +843,11 @@ const replies = (run: Run) => {
685
843
  let model: string | undefined;
686
844
  // Posts go one at a time, so each one knows the message that the last one posted.
687
845
  let posting: Promise<void> = Promise.resolve();
688
- const post = (text: string) => {
846
+ const post = (text: string, done = false) => {
689
847
  const next = posting.then(async () => {
690
- posted = (await relay(run, text, posted)) ?? posted;
848
+ const result = await relay(run, text, posted, done);
849
+ if (result === "lost") return lose(run, lost);
850
+ posted = result ?? posted;
691
851
  sentAt = Date.now();
692
852
  });
693
853
  posting = next.catch(() => {});
@@ -710,11 +870,17 @@ const replies = (run: Run) => {
710
870
  );
711
871
  ticker = setTimeout(show, CLOCK_INTERVAL_MS);
712
872
  };
873
+ lost.signal.addEventListener("abort", () => {
874
+ clearTimeout(timer);
875
+ clearTimeout(ticker);
876
+ });
713
877
  return {
714
878
  /** Starts the clock, when the run leaves the queue. */
715
879
  start() {
716
880
  startedAt = Date.now();
717
881
  },
882
+ /** The message that the run's next reply replaces. */
883
+ message: () => posted,
718
884
  progress: {
719
885
  message(text: string) {
720
886
  if (text === (pending ?? shown)) return;
@@ -725,20 +891,29 @@ const replies = (run: Run) => {
725
891
  model = name;
726
892
  },
727
893
  } satisfies Progress,
728
- finish(text: string) {
894
+ finish(text: string, done = true) {
729
895
  clearTimeout(timer);
730
896
  clearTimeout(ticker);
731
897
  timer = undefined;
732
898
  ticker = undefined;
733
899
  pending = undefined;
734
- return post(text);
900
+ return post(text, done);
735
901
  },
736
902
  };
737
903
  };
738
904
 
739
- let active = 0;
740
- /** The replies of the runs that are running or queued. */
741
- const held = new Map<string, ReturnType<typeof replies>>();
905
+ /** A run that the runner holds, running or queued, with its replies, and the controller that ends it once the router marks it lost. */
906
+ type Held = { run: Run; reply: ReturnType<typeof replies>; lost: AbortController };
907
+
908
+ /** Ends a run that the router marked lost. See `execute`. */
909
+ const lose = (run: Run, lost: AbortController) => {
910
+ if (lost.signal.aborted) return;
911
+ log({ run: run.id, state: "lost", detail: "The router marked the run lost, so the runner stops it." });
912
+ lost.abort();
913
+ };
914
+
915
+ /** The runs that are running or queued, by id. */
916
+ const held = new Map<string, Held>();
742
917
 
743
918
  /**
744
919
  * Runs one run, and returns the agent's final message, or undefined if the
@@ -758,13 +933,18 @@ const held = new Map<string, ReturnType<typeof replies>>();
758
933
  * tokens.
759
934
  * 5. Runs the agent in the worktree, and has the router mint new tokens
760
935
  * while it runs. Posts the agent's messages as it writes them, each in
761
- * place of the last.
936
+ * place of the last. Saves the worktree and the session to the state
937
+ * store every `SAVE_INTERVAL_MS`. These saves keep the messages that the
938
+ * session had seen before the run, so a run that resumes after this one
939
+ * is lost gets this run's messages again.
762
940
  * 6. Saves the session file, with the messages the agent has now seen, if
763
- * the CLI reported a session, even if it failed.
941
+ * the runner knows the session's id, from the CLI's result or from its
942
+ * output during the run, even if the CLI failed.
764
943
  * 7. Saves the worktree and the session to the state store, whether or not
765
- * the agent succeeded.
944
+ * the agent succeeded. The saves in steps 5 and 7 save the same session
945
+ * that step 6 writes, so the last save never uploads an older session.
766
946
  */
767
- const perform = async (run: Run, notes: string[], progress: Progress) => {
947
+ const perform = async (run: Run, notes: string[], progress: Progress, lost: AbortSignal) => {
768
948
  const worktree = worktreeOf(run);
769
949
  const adapter = await loadRuntime(run.agent.runtime);
770
950
  await assertCommand(adapter.command, adapter.name);
@@ -781,6 +961,10 @@ const perform = async (run: Run, notes: string[], progress: Progress) => {
781
961
  const seen = Object.fromEntries(messages.map((m) => [m.id, bodyHash(m.body)]));
782
962
  const repo = await fetchRepo(run, await loadCodeHost());
783
963
  await checkout(run, repo, worktree, notes);
964
+ let sessionId = session?.id;
965
+ let sessionSeen = session?.seen ?? {};
966
+ const current = () => (sessionId ? { id: sessionId, cwd: worktree.path, seen: sessionSeen } : undefined);
967
+ const saves = saver(run, worktree, transcripts, current);
784
968
  try {
785
969
  await writeFiles([run.files, agentFiles(run)], {
786
970
  worktree: worktree.path,
@@ -799,23 +983,32 @@ const perform = async (run: Run, notes: string[], progress: Progress) => {
799
983
  }),
800
984
  TOKEN_REFRESH_MS,
801
985
  );
986
+ const stopSaving = saves.during();
802
987
  try {
803
988
  const result = await runAgent(
804
989
  adapter,
805
990
  run,
806
991
  { cwd: worktree.path, configDir, prompt, sessionId: session?.id },
807
992
  progress,
993
+ (id) => {
994
+ sessionId = id;
995
+ },
996
+ lost,
808
997
  );
809
- if (result.sessionId) await writeSession(run, { id: result.sessionId, cwd: worktree.path, seen });
998
+ sessionId = result.sessionId ?? sessionId;
999
+ // A lost run's session keeps the messages it had seen before the run, so the restarted run gets them again.
1000
+ if (!lost.aborted) sessionSeen = seen;
1001
+ const ended = current();
1002
+ if (ended) await writeSession(run, ended);
810
1003
  if (result.error) throw new Error(result.error);
811
1004
  return result.text;
812
1005
  } finally {
813
1006
  clearInterval(refreshing);
1007
+ stopSaving();
814
1008
  }
815
1009
  } finally {
816
1010
  try {
817
- await saveWorktree(worktree);
818
- await saveSession(run, transcripts);
1011
+ await saves.final();
819
1012
  } catch (error) {
820
1013
  log({ run: run.id, state: "save failed", error: message(error) });
821
1014
  notes.push(`Factory couldn't save this worktree and session, so they'll be lost when the container sleeps: ${message(error)}`);
@@ -823,28 +1016,40 @@ const perform = async (run: Run, notes: string[], progress: Progress) => {
823
1016
  }
824
1017
  };
825
1018
 
1019
+ /**
1020
+ * The notes of the run that is running, which earlyoom's notes go to. A
1021
+ * container serves one worktree, and runs in a worktree go one at a time,
1022
+ * so at most one run is running.
1023
+ */
1024
+ let runningNotes: string[] | undefined;
1025
+
826
1026
  /** What a skipped run posts in place of the message that the router posted while the run waited for its container. */
827
1027
  const SKIPPED_NOTE = "> An earlier run already read these messages, so this run had nothing new to do.";
828
1028
 
829
1029
  /**
830
1030
  * Runs one run, and posts the agent's final message, or the error, to the
831
1031
  * conversation, with notes on what couldn't be restored or saved. It
832
- * replaces the agent's last message. A skipped run posts nothing, unless
833
- * the router posted a message while the run waited for its container,
834
- * which the run replaces with `SKIPPED_NOTE`.
1032
+ * replaces the agent's last message, and is the run's last reply. A skipped
1033
+ * run posts nothing, and posts its done heartbeat instead, unless the router
1034
+ * posted a message while the run waited for its container, which the run
1035
+ * replaces with `SKIPPED_NOTE`. A run that the router marks lost is over: if
1036
+ * it's queued, it doesn't start, and if it's running, the runner stops its
1037
+ * agent, saves its worktree and session, and posts nothing.
835
1038
  */
836
- const execute = async (run: Run) => {
1039
+ const execute = async (entry: Held) => {
1040
+ const { run, reply, lost } = entry;
1041
+ if (lost.signal.aborted) return log({ run: run.id, state: "skipped", reason: "lost" });
837
1042
  const started = Date.now();
838
- const reply = held.get(run.id) ?? replies(run);
839
1043
  reply.start();
840
1044
  log({ run: run.id, repo: run.repo, trigger: run.trigger, worktree: run.worktree?.branch ?? "scratch", state: "started" });
841
1045
  const notes: string[] = [];
1046
+ runningNotes = notes;
842
1047
  let text: string;
843
1048
  try {
844
- const result = await perform(run, notes, reply.progress);
1049
+ const result = await perform(run, notes, reply.progress, lost.signal);
845
1050
  if (result === undefined) {
846
1051
  log({ run: run.id, state: "skipped", reason: "no new messages" });
847
- if (!run.reply.message) return;
1052
+ if (!run.reply.message) return await heartbeatDone(entry);
848
1053
  text = SKIPPED_NOTE;
849
1054
  } else {
850
1055
  text = result;
@@ -853,7 +1058,10 @@ const execute = async (run: Run) => {
853
1058
  } catch (error) {
854
1059
  log({ run: run.id, state: "failed", error: message(error), ms: Date.now() - started });
855
1060
  text = `The run failed: ${message(error)}`;
1061
+ } finally {
1062
+ runningNotes = undefined;
856
1063
  }
1064
+ if (lost.signal.aborted) return log({ run: run.id, state: "stopped", reason: "lost", ms: Date.now() - started });
857
1065
  try {
858
1066
  const parts = [text || "(The agent finished with no message.)", ...notes.map((note) => `> ${note}`)];
859
1067
  await reply.finish(parts.join("\n\n"));
@@ -862,14 +1070,100 @@ const execute = async (run: Run) => {
862
1070
  }
863
1071
  };
864
1072
 
1073
+ const size = (mib: number) => (mib < 1024 ? `${mib} MiB` : `${(mib / 1024).toFixed(1)} GiB`);
1074
+
1075
+ /**
1076
+ * earlyoom's line when it stops a process. earlyoom 1.7, which Debian 12
1077
+ * has, writes `badness`, and 1.8 writes `oom_score` and the command line.
1078
+ */
1079
+ const EARLYOOM_KILL = /^sending SIG\w+ to process \d+ uid \d+ "(.*?)": (?:badness|oom_score) -?\d+, VmRSS (\d+) MiB/;
1080
+
1081
+ /**
1082
+ * Starts earlyoom, if the image has it, and logs its output. When earlyoom
1083
+ * stops a process while a run is running, the run's reply says so.
1084
+ */
1085
+ const startEarlyoom = () => {
1086
+ const child = spawn("earlyoom", EARLYOOM_ARGS, { stdio: ["ignore", "pipe", "pipe"] });
1087
+ const read = (stream: NodeJS.ReadableStream) => {
1088
+ let rest = "";
1089
+ stream.setEncoding("utf8");
1090
+ stream.on("data", (chunk: string) => {
1091
+ const lines = (rest + chunk).split("\n");
1092
+ rest = lines.pop() ?? "";
1093
+ for (const line of lines) {
1094
+ if (!line.trim()) continue;
1095
+ log({ earlyoom: line });
1096
+ const kill = EARLYOOM_KILL.exec(line);
1097
+ if (!kill) continue;
1098
+ const note = `earlyoom stopped \`${kill[1]}\` (${size(Number(kill[2]))}) because the container was out of memory.`;
1099
+ if (runningNotes && !runningNotes.includes(note)) runningNotes.push(note);
1100
+ }
1101
+ });
1102
+ };
1103
+ read(child.stdout);
1104
+ read(child.stderr);
1105
+ child.on("error", (error: NodeJS.ErrnoException) =>
1106
+ log(
1107
+ error.code === "ENOENT"
1108
+ ? { state: "earlyoom missing", detail: "The image has no earlyoom, so nothing stops a process before the container runs out of memory." }
1109
+ : { state: "earlyoom failed", error: message(error) },
1110
+ ),
1111
+ );
1112
+ child.on("exit", (code, signal) => log({ state: "earlyoom exited", code, signal }));
1113
+ };
1114
+
1115
+ /**
1116
+ * Posts a heartbeat for the run to the router, if the router watches the
1117
+ * run. With `done`, the router stops watching it. Resolves to `lost` if the
1118
+ * router marked the run lost, and to `retry` if the router couldn't be
1119
+ * reached or failed. The outpost Worker's `heartbeat` posts the same body
1120
+ * and reads the answer the same way.
1121
+ */
1122
+ const postHeartbeat = async (run: Run, posted: ReplyMessage | undefined, done: boolean): Promise<"ok" | "lost" | "retry"> => {
1123
+ if (!run.reply.heartbeat) return "ok";
1124
+ const body: Heartbeat = {
1125
+ ticket: run.reply.ticket,
1126
+ signature: run.reply.signature,
1127
+ ...(posted && { message: posted }),
1128
+ ...(done && { done }),
1129
+ };
1130
+ try {
1131
+ const response = await fetch(run.reply.heartbeat, {
1132
+ method: "POST",
1133
+ headers: { "content-type": "application/json" },
1134
+ body: JSON.stringify(body),
1135
+ signal: AbortSignal.timeout(HEARTBEAT_TIMEOUT_MS),
1136
+ });
1137
+ if (!response.ok) {
1138
+ log({ run: run.id, state: "heartbeat refused", status: response.status, error: await response.text() });
1139
+ return response.status < 500 ? "ok" : "retry";
1140
+ }
1141
+ return ((await response.json().catch(() => ({}))) as Partial<HeartbeatResult>).lost ? "lost" : "ok";
1142
+ } catch (error) {
1143
+ log({ run: run.id, state: "heartbeat failed", error: message(error) });
1144
+ return "retry";
1145
+ }
1146
+ };
1147
+
1148
+ /** Posts the run's heartbeat, and ends the run if the router marked it lost. */
1149
+ const heartbeat = async ({ run, reply, lost }: Held) => {
1150
+ if ((await postHeartbeat(run, reply.message(), false)) === "lost") lose(run, lost);
1151
+ };
1152
+
1153
+ /** Posts the run's `done` heartbeat, up to `DONE_ATTEMPTS` times in all, while the router can't be reached or fails. */
1154
+ const heartbeatDone = async ({ run, reply }: Held) => {
1155
+ for (let attempt = 1; (await postHeartbeat(run, reply.message(), true)) === "retry" && attempt < DONE_ATTEMPTS; attempt++) {
1156
+ await new Promise((resolve) => setTimeout(resolve, DONE_RETRY_MS));
1157
+ }
1158
+ };
1159
+
865
1160
  const enqueue = (run: Run) => {
866
- active++;
867
- held.set(run.id, replies(run));
1161
+ const lost = new AbortController();
1162
+ const entry: Held = { run, reply: replies(run, lost), lost };
1163
+ held.set(run.id, entry);
1164
+ void heartbeat(entry);
868
1165
  const key = run.worktree ? `branch:${run.repo}:${run.worktree.branch}` : `scratch:${run.conversation.id}`;
869
- void worktreeLock(key, () => execute(run)).finally(() => {
870
- active--;
871
- held.delete(run.id);
872
- });
1166
+ void worktreeLock(key, () => execute(entry)).finally(() => held.delete(run.id));
873
1167
  };
874
1168
 
875
1169
  const send = (response: ServerResponse, status: number, body: unknown) => {
@@ -905,7 +1199,7 @@ const server = createServer(async (request, response) => {
905
1199
  enqueue(run);
906
1200
  return send(response, 202, { queued: run.id });
907
1201
  }
908
- if (request.method === "GET" && pathname === "/status") return send(response, 200, { active });
1202
+ if (request.method === "GET" && pathname === "/status") return send(response, 200, { active: held.size });
909
1203
  return send(response, 404, { error: "not found" });
910
1204
  } catch (error) {
911
1205
  send(response, 500, { error: message(error) });
@@ -916,10 +1210,12 @@ const server = createServer(async (request, response) => {
916
1210
  // that the process doesn't handle. The provider stops a sleeping container
917
1211
  // with SIGTERM, and also a busy one when it rolls out a new image. The runs
918
1212
  // the runner holds are lost then, so it says so on their conversations.
1213
+ // These replies aren't the runs' last, so the router goes on watching the
1214
+ // runs, and later replaces them with the lost notice and its restart link.
919
1215
  process.on("SIGTERM", async () => {
920
1216
  log({ state: "stopping", runs: held.size });
921
- const lost = [...held.values()].map((reply) =>
922
- reply.finish("The container stopped before this run finished, so the run was lost. Mention the agent again to start it over."),
1217
+ const lost = [...held.values()].map(({ reply }) =>
1218
+ reply.finish("The container stopped before this run finished, so the run was lost. Mention the agent again to start it over.", false),
923
1219
  );
924
1220
  const timeout = new Promise((resolve) => setTimeout(resolve, STOP_REPLY_TIMEOUT_MS));
925
1221
  await Promise.race([Promise.allSettled(lost), timeout]);
@@ -927,4 +1223,8 @@ process.on("SIGTERM", async () => {
927
1223
  });
928
1224
 
929
1225
  await configureGit();
1226
+ startEarlyoom();
1227
+ setInterval(() => {
1228
+ for (const entry of held.values()) void heartbeat(entry);
1229
+ }, HEARTBEAT_INTERVAL_MS);
930
1230
  server.listen(PORT, () => log({ state: "listening", port: PORT }));