@catamorphic/work-server 0.1.0-alpha.42 → 0.1.0-alpha.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +4 -1
  2. package/dist/agents.d.ts.map +1 -1
  3. package/dist/{chunk-kcck20aw.js → chunk-ynxz0am9.js} +80 -9
  4. package/dist/chunk-ynxz0am9.js.map +11 -0
  5. package/dist/cluster.d.ts +19 -1
  6. package/dist/cluster.d.ts.map +1 -1
  7. package/dist/execution-config.d.ts +2 -1
  8. package/dist/execution-config.d.ts.map +1 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +962 -268
  12. package/dist/index.js.map +21 -19
  13. package/dist/machines/contract.d.ts +138 -14
  14. package/dist/machines/contract.d.ts.map +1 -1
  15. package/dist/machines/sequencer.d.ts +33 -6
  16. package/dist/machines/sequencer.d.ts.map +1 -1
  17. package/dist/machines/simulation.d.ts +64 -0
  18. package/dist/machines/simulation.d.ts.map +1 -1
  19. package/dist/machines/work-machines.d.ts +40 -2
  20. package/dist/machines/work-machines.d.ts.map +1 -1
  21. package/dist/server.d.ts +11 -1
  22. package/dist/server.d.ts.map +1 -1
  23. package/dist/testing.d.ts +1 -1
  24. package/dist/testing.d.ts.map +1 -1
  25. package/dist/testing.js +208 -17
  26. package/dist/testing.js.map +4 -4
  27. package/dist/workers/cache-archive-routes.d.ts +24 -0
  28. package/dist/workers/cache-archive-routes.d.ts.map +1 -0
  29. package/dist/workers/disk-care.d.ts +36 -1
  30. package/dist/workers/disk-care.d.ts.map +1 -1
  31. package/dist/workers/harness-sign-ins.d.ts +32 -1
  32. package/dist/workers/harness-sign-ins.d.ts.map +1 -1
  33. package/dist/workers/machine-store.d.ts +37 -0
  34. package/dist/workers/machine-store.d.ts.map +1 -1
  35. package/dist/workers/member-machine-routes.d.ts +3 -0
  36. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  37. package/dist/workers/member-machines.d.ts +52 -5
  38. package/dist/workers/member-machines.d.ts.map +1 -1
  39. package/dist/workers/placement.d.ts +10 -0
  40. package/dist/workers/placement.d.ts.map +1 -1
  41. package/dist/workers/sign-in-store.d.ts +67 -0
  42. package/dist/workers/sign-in-store.d.ts.map +1 -0
  43. package/dist/workers/sign-ins.d.ts +4 -6
  44. package/dist/workers/sign-ins.d.ts.map +1 -1
  45. package/dist/workers/worker-protocol.d.ts +9 -1
  46. package/dist/workers/worker-protocol.d.ts.map +1 -1
  47. package/dist/workers/worker-registry.d.ts +20 -6
  48. package/dist/workers/worker-registry.d.ts.map +1 -1
  49. package/dist/workers/worker-runtime.d.ts.map +1 -1
  50. package/package.json +18 -19
  51. package/src/agents.ts +5 -0
  52. package/src/cluster.ts +62 -7
  53. package/src/execution-config.ts +2 -1
  54. package/src/index.ts +7 -0
  55. package/src/machines/contract-kit.ts +1 -1
  56. package/src/machines/contract.ts +191 -19
  57. package/src/machines/sequencer.ts +106 -11
  58. package/src/machines/simulation.ts +370 -20
  59. package/src/machines/work-machines.ts +71 -3
  60. package/src/server.ts +120 -29
  61. package/src/testing.ts +1 -0
  62. package/src/workers/cache-archive-routes.ts +125 -0
  63. package/src/workers/disk-care.ts +157 -6
  64. package/src/workers/harness-sign-ins.ts +207 -22
  65. package/src/workers/machine-store.ts +341 -58
  66. package/src/workers/member-machine-routes.ts +58 -3
  67. package/src/workers/member-machines.ts +168 -14
  68. package/src/workers/placement.ts +7 -0
  69. package/src/workers/sign-in-store.ts +241 -0
  70. package/src/workers/sign-ins.ts +9 -33
  71. package/src/workers/worker-protocol.ts +9 -1
  72. package/src/workers/worker-registry.ts +47 -6
  73. package/src/workers/worker-runtime.ts +9 -3
  74. package/dist/chunk-kcck20aw.js.map +0 -11
@@ -1,3 +1,5 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
1
3
  import {
2
4
  type DiskFloorDefault,
3
5
  describeDisk,
@@ -6,6 +8,7 @@ import {
6
8
  measureDisk,
7
9
  type SandboxProvider,
8
10
  } from "@catamorphic/sandbox";
11
+ import { z } from "zod";
9
12
 
10
13
  /** How often a machine measures its disk (ADR 0336). */
11
14
  export const DISK_MEASURE_INTERVAL_MS = 30_000;
@@ -13,6 +16,129 @@ export const DISK_MEASURE_INTERVAL_MS = 30_000;
13
16
  export const DISK_CLEAN_INTERVAL_MS = 60 * 60_000;
14
17
  /** How soon it cleans again while it is under its floor. */
15
18
  export const DISK_LOW_CLEAN_INTERVAL_MS = 10 * 60_000;
19
+ /**
20
+ * A machine that noted nothing for this long was not running: stopped
21
+ * (ADR 0350), asleep or down. Its notes are 30 seconds apart.
22
+ */
23
+ export const DISK_AWAY_AFTER_MS = 5 * 60_000;
24
+ /** The file in a machine's data folder where it notes that it runs. */
25
+ export const RUNNING_TIME_FILE = "running-time.json";
26
+
27
+ /** A stretch a machine was not running, in milliseconds since the epoch. */
28
+ export interface AwayStretch {
29
+ from: number;
30
+ to: number;
31
+ }
32
+
33
+ /**
34
+ * How far back from `now` a machine must look to cover `ranMs` of the time
35
+ * it ran: `ranMs`, and every stretch it was not running that falls inside.
36
+ * A stretch that ended more than `ranMs` of running time ago adds nothing,
37
+ * and one a clock that went back left ahead of `now` counts up to `now`.
38
+ */
39
+ export function reachOfRunningTime(args: {
40
+ ranMs: number;
41
+ now: number;
42
+ away: readonly AwayStretch[];
43
+ }): number {
44
+ let left = args.ranMs;
45
+ let cursor = args.now;
46
+ for (const stretch of [...args.away].sort((a, b) => b.to - a.to)) {
47
+ const to = Math.min(stretch.to, cursor);
48
+ if (stretch.from >= to) continue;
49
+ const ran = cursor - to;
50
+ if (ran >= left) break;
51
+ left -= ran;
52
+ cursor = stretch.from;
53
+ }
54
+ return args.now - (cursor - left);
55
+ }
56
+
57
+ /** What a machine keeps of when it ran: its last note, and each stretch away. */
58
+ const RunningNotes = z.object({
59
+ seenAt: z.number(),
60
+ away: z.array(z.tuple([z.number(), z.number()])),
61
+ });
62
+
63
+ /**
64
+ * When a machine was not running, kept in one small JSON file on the disk a
65
+ * stop retains (ADR 0350). The machine notes that it runs every time it
66
+ * looks at its disk; a note more than `awayAfterMs` after the one before
67
+ * closes a stretch it was away. A machine that crashed left its last note,
68
+ * so the time after it counts as away too. A machine without a file, or
69
+ * whose clock went back, has no stretch to add: it starts from this note.
70
+ */
71
+ class RunningTime {
72
+ private seenAt: number | undefined;
73
+ private away: AwayStretch[] = [];
74
+ private failed = false;
75
+
76
+ constructor(
77
+ private readonly args: {
78
+ file: string;
79
+ /** Stretches older than this much running time are forgotten. */
80
+ keepMs: number;
81
+ awayAfterMs: number;
82
+ now: () => number;
83
+ log?: (line: string) => void;
84
+ },
85
+ ) {
86
+ const notes = RunningNotes.safeParse(read(args.file)).data;
87
+ if (!notes) return;
88
+ this.seenAt = notes.seenAt;
89
+ this.away = notes.away.map(([from, to]) => ({ from, to }));
90
+ }
91
+
92
+ /**
93
+ * The machine runs now. Answers how far back `keepMs` of its running
94
+ * time reaches.
95
+ */
96
+ note(): number {
97
+ const now = this.args.now();
98
+ if (this.seenAt !== undefined && now - this.seenAt > this.args.awayAfterMs)
99
+ this.away.push({ from: this.seenAt, to: now });
100
+ this.seenAt = now;
101
+ const reach = reachOfRunningTime({
102
+ ranMs: this.args.keepMs,
103
+ now,
104
+ away: this.away,
105
+ });
106
+ this.away = this.away.filter(
107
+ (stretch) => stretch.to > now - reach && stretch.from < now,
108
+ );
109
+ try {
110
+ fs.mkdirSync(path.dirname(this.args.file), { recursive: true });
111
+ const temporary = `${this.args.file}.${process.pid}.tmp`;
112
+ fs.writeFileSync(
113
+ temporary,
114
+ JSON.stringify({
115
+ seenAt: this.seenAt,
116
+ away: this.away.map((stretch) => [stretch.from, stretch.to]),
117
+ }),
118
+ { mode: 0o600 },
119
+ );
120
+ fs.renameSync(temporary, this.args.file);
121
+ this.failed = false;
122
+ } catch (error) {
123
+ // Said once. The next start counts from the last note that was kept.
124
+ if (!this.failed)
125
+ this.args.log?.(
126
+ `Could not note that this machine is running: ${error instanceof Error ? error.message : String(error)}`,
127
+ );
128
+ this.failed = true;
129
+ }
130
+ return reach;
131
+ }
132
+ }
133
+
134
+ /** A JSON file's content, or undefined for one that is absent or unreadable. */
135
+ function read(file: string): unknown {
136
+ try {
137
+ return JSON.parse(fs.readFileSync(file, "utf8"));
138
+ } catch {
139
+ return undefined;
140
+ }
141
+ }
16
142
 
17
143
  export interface DiskCare {
18
144
  /** The latest measurement, if any filesystem could be measured. */
@@ -29,7 +155,9 @@ export interface DiskCare {
29
155
  * with the least room above its floor for the machine to report, and
30
156
  * removes what its provider left that nothing used for `graceMs`: once at
31
157
  * start, then hourly, and at once (at most every 10 minutes) while under
32
- * its floor.
158
+ * its floor. With `runningFile`, `graceMs` is time the machine ran: a
159
+ * stretch it was stopped (ADR 0350), asleep or down does not count against
160
+ * what it keeps, so a machine resumed after days still has its images.
33
161
  */
34
162
  export function startDiskCare(args: {
35
163
  provider: Pick<SandboxProvider, "disk">;
@@ -41,14 +169,34 @@ export function startDiskCare(args: {
41
169
  defaultFloor?: DiskFloorDefault;
42
170
  /** `WORK_IMAGE_RETENTION_HOURS`, in milliseconds. */
43
171
  graceMs: number;
172
+ /**
173
+ * Where the machine notes that it runs, on the disk a stop retains.
174
+ * Absent, or with a provider that removes nothing, all time counts as
175
+ * running.
176
+ */
177
+ runningFile?: string;
178
+ /** {@link DISK_AWAY_AFTER_MS} when absent. */
179
+ awayAfterMs?: number;
44
180
  measureEveryMs?: number;
45
181
  cleanEveryMs?: number;
46
182
  lowCleanEveryMs?: number;
47
183
  log?: (line: string) => void;
48
184
  /** For tests: measure as {@link measureDisk} does. */
49
185
  measureDisk?: typeof measureDisk;
186
+ /** The clock, for tests. */
187
+ now?: () => number;
50
188
  }): DiskCare {
51
189
  const measure = args.measureDisk ?? measureDisk;
190
+ const running =
191
+ args.runningFile && args.provider.disk?.clean
192
+ ? new RunningTime({
193
+ file: args.runningFile,
194
+ keepMs: args.graceMs,
195
+ awayAfterMs: args.awayAfterMs ?? DISK_AWAY_AFTER_MS,
196
+ now: args.now ?? Date.now,
197
+ ...(args.log ? { log: args.log } : {}),
198
+ })
199
+ : undefined;
52
200
  let latest: MachineDisk | undefined;
53
201
  let wasLow = false;
54
202
  let stopped = false;
@@ -58,7 +206,9 @@ export function startDiskCare(args: {
58
206
  const run = args.provider.disk?.clean;
59
207
  if (!run || cleaning || stopped) return;
60
208
  lastClean = Date.now();
61
- cleaning = run({ graceMs: args.graceMs })
209
+ // Noted as it is read: a machine that slept through its last note
210
+ // counts that stretch before it removes anything.
211
+ cleaning = run({ graceMs: running?.note() ?? args.graceMs })
62
212
  .then((lines) => {
63
213
  for (const line of lines) args.log?.(line);
64
214
  })
@@ -104,11 +254,12 @@ export function startDiskCare(args: {
104
254
  });
105
255
  return measuring;
106
256
  };
257
+ running?.note();
107
258
  void measureNow();
108
- const timer = setInterval(
109
- () => void measureNow(),
110
- args.measureEveryMs ?? DISK_MEASURE_INTERVAL_MS,
111
- );
259
+ const timer = setInterval(() => {
260
+ running?.note();
261
+ void measureNow();
262
+ }, args.measureEveryMs ?? DISK_MEASURE_INTERVAL_MS);
112
263
  timer.unref();
113
264
  return {
114
265
  latest: () => latest,
@@ -1,11 +1,18 @@
1
- import { type ChildProcess, spawn } from "node:child_process";
1
+ import { spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import fs from "node:fs";
4
- import type { Readable } from "node:stream";
4
+ import path from "node:path";
5
+ import type { Readable, Writable } from "node:stream";
5
6
  import {
7
+ SANDBOX_CAPABILITIES,
8
+ type SandboxEgress,
9
+ type SandboxImage,
10
+ type SandboxProvider,
6
11
  SIGN_IN_SPECS,
7
12
  type SignInHarness,
8
13
  type SignInSpec,
14
+ signInHomePath,
15
+ spawnInSandbox,
9
16
  } from "@catamorphic/sandbox";
10
17
  import { z } from "zod";
11
18
  import {
@@ -24,7 +31,12 @@ import {
24
31
  * A member signs in to Claude Code or Codex on one of their machines from
25
32
  * the Work app (ADRs 0213, 0342): this machine runs the harness's own
26
33
  * unmodified login into a home of its own for them, the app shows the link
27
- * it printed, and the member finishes in their own browser. Codex prints a
34
+ * it printed, and the member finishes in their own browser. On a machine
35
+ * whose sandboxes run images, the login runs in a sign-in sandbox of the
36
+ * image a turn in the member's Environment runs, with that home mounted
37
+ * where turns mount it, so the CLI that signs in is the one that runs
38
+ * (ADR 0363). The sandbox is nobody's workspace: no checkout, no secrets,
39
+ * nothing but the home, and it goes when the login ends. Codex prints a
28
40
  * one-time code the member enters there (`codex login --device-auth`);
29
41
  * Claude Code's page gives the member a code, which they paste into the
30
42
  * app and this machine writes to the login as its one line of input
@@ -36,9 +48,23 @@ import {
36
48
  * nowhere else. No answer, message, log or error here carries it.
37
49
  */
38
50
 
51
+ /**
52
+ * What a turn in the Environment a sign-in is for runs (ADR 0363): its
53
+ * image (absent: the machine's own) and its network.
54
+ */
55
+ export interface SignInSandbox {
56
+ image?: SandboxImage;
57
+ egress?: SandboxEgress;
58
+ }
59
+
39
60
  /** What a member does with a harness's sign-in on a machine. */
40
61
  export type HarnessSignInRequest =
41
- | { action: "begin"; harness: SignInHarness; member: string }
62
+ | {
63
+ action: "begin";
64
+ harness: SignInHarness;
65
+ member: string;
66
+ sandbox?: SignInSandbox;
67
+ }
42
68
  | {
43
69
  action: "status";
44
70
  harness: SignInHarness;
@@ -98,11 +124,35 @@ const DEFAULT_CODE_MINUTES = 15;
98
124
  const EXIT_DRAIN_MS = 500;
99
125
  /** Finished attempts are remembered this long for a late status read. */
100
126
  const FINISHED_TTL_MS = 60 * 60_000;
127
+ /**
128
+ * Beside a pending home whose login runs in a sandbox: the sandbox's id, so
129
+ * a machine that restarted removes a sandbox its earlier process left.
130
+ */
131
+ const SANDBOX_NOTE = ".sandbox";
132
+
133
+ /**
134
+ * A login running, on this machine or in its sign-in sandbox: a Node child
135
+ * process, or a process in a sandbox read as one.
136
+ */
137
+ interface LoginProcess {
138
+ readonly stdin: Writable | null;
139
+ readonly stdout: Readable | null;
140
+ readonly stderr: Readable | null;
141
+ readonly exitCode: number | null;
142
+ kill(signal?: NodeJS.Signals): boolean;
143
+ once(
144
+ event: "exit",
145
+ listener: (code: number | null, signal: NodeJS.Signals | null) => void,
146
+ ): unknown;
147
+ once(event: "error", listener: (error: Error) => void): unknown;
148
+ }
101
149
 
102
150
  interface Attempt {
103
151
  harness: SignInHarness;
104
152
  member: string;
105
- child: ChildProcess;
153
+ child: LoginProcess;
154
+ /** Ends the login's sign-in sandbox, if it has one; safe to call again. */
155
+ release: () => Promise<void>;
106
156
  staging: string;
107
157
  expiresAt: number;
108
158
  state: HarnessSignInState;
@@ -247,9 +297,133 @@ export class HarnessSignIns {
247
297
  * placement now rather than at its next scan.
248
298
  */
249
299
  onChange?: () => void;
300
+ /**
301
+ * The machine's sandboxes (ADR 0363). Where they run images, every
302
+ * login runs in a sandbox of one: the Environment's, or the
303
+ * machine's own. Otherwise, and without it, a login runs on this
304
+ * machine with the CLI on its `PATH`.
305
+ */
306
+ provider?: SandboxProvider;
250
307
  },
251
308
  ) {}
252
309
 
310
+ private recovered?: Promise<void>;
311
+
312
+ /**
313
+ * Remove the sign-in sandboxes, and their pending homes, that an earlier
314
+ * process of this machine left: it forgot their logins when it stopped.
315
+ */
316
+ recover(): Promise<void> {
317
+ this.recovered ??= (async () => {
318
+ const pending = path.join(this.options.signInRoot, ".pending");
319
+ let names: string[];
320
+ try {
321
+ names = fs.readdirSync(pending);
322
+ } catch {
323
+ return;
324
+ }
325
+ for (const name of names) {
326
+ if (!name.endsWith(SANDBOX_NOTE)) continue;
327
+ const note = path.join(pending, name);
328
+ const id = fs.readFileSync(note, "utf8").trim();
329
+ if (id)
330
+ await this.options.provider
331
+ ?.destroySandbox(id)
332
+ .catch(() => undefined);
333
+ fs.rmSync(note.slice(0, -SANDBOX_NOTE.length), {
334
+ recursive: true,
335
+ force: true,
336
+ });
337
+ fs.rmSync(note, { force: true });
338
+ }
339
+ })();
340
+ return this.recovered;
341
+ }
342
+
343
+ /** The machine's sandboxes, where a login runs in an image of theirs. */
344
+ private imageSandboxes(): SandboxProvider | undefined {
345
+ const provider = this.options.provider;
346
+ return provider?.processes &&
347
+ provider.capabilities?.includes(SANDBOX_CAPABILITIES.images)
348
+ ? provider
349
+ : undefined;
350
+ }
351
+
352
+ /**
353
+ * Start a harness's own login into `staging`: in a sign-in sandbox of
354
+ * the Environment's image on a machine whose sandboxes run images, else
355
+ * on this machine.
356
+ */
357
+ private async startLogin(input: {
358
+ harness: SignInHarness;
359
+ staging: string;
360
+ sandbox?: SignInSandbox;
361
+ }): Promise<{ child: LoginProcess; release: () => Promise<void> }> {
362
+ const spec = SIGN_IN_SPECS[input.harness];
363
+ const provider = this.imageSandboxes();
364
+ if (!provider?.processes) {
365
+ const login = signInCommand({
366
+ harness: input.harness,
367
+ home: input.staging,
368
+ });
369
+ const child = spawn(login.command, login.args, {
370
+ env: signInEnvironment({
371
+ harness: input.harness,
372
+ base: this.options.env ?? process.env,
373
+ login: { ...login.env, NO_COLOR: "1" },
374
+ }),
375
+ // A login that waits for a pasted code reads it from a plain pipe.
376
+ stdio: [spec.expects ? "pipe" : "ignore", "pipe", "pipe"],
377
+ });
378
+ return { child, release: async () => {} };
379
+ }
380
+ const processes = provider.processes;
381
+ let handle: { providerId: string };
382
+ try {
383
+ handle = await provider.createSandbox({
384
+ ...(input.sandbox?.image ? { image: input.sandbox.image } : {}),
385
+ ...(input.sandbox?.egress ? { egress: input.sandbox.egress } : {}),
386
+ signInLogin: {
387
+ harness: input.harness,
388
+ pending: path.basename(input.staging),
389
+ },
390
+ labels: { purpose: "sign-in" },
391
+ });
392
+ } catch (error) {
393
+ throw new HarnessSignInRefusedError(
394
+ `Could not make a sandbox to sign in to ${spec.name} in: ${
395
+ error instanceof Error ? error.message : String(error)
396
+ }`,
397
+ );
398
+ }
399
+ const note = `${input.staging}${SANDBOX_NOTE}`;
400
+ fs.writeFileSync(note, handle.providerId, { mode: 0o600 });
401
+ let released: Promise<void> | undefined;
402
+ const release = () => {
403
+ released ??= provider.destroySandbox(handle.providerId).then(
404
+ () => fs.rmSync(note, { force: true }),
405
+ () => undefined,
406
+ );
407
+ return released;
408
+ };
409
+ const home = signInHomePath({
410
+ workspaceRoot: provider.workspaceRoot,
411
+ harness: input.harness,
412
+ });
413
+ const child = spawnInSandbox({
414
+ processes,
415
+ sandboxId: handle.providerId,
416
+ command: spec.command,
417
+ args: [...spec.login, ...spec.defaultArgs],
418
+ cwd: provider.workspaceRoot,
419
+ env: { [spec.homeVariable]: home, NO_COLOR: "1" },
420
+ name: `${spec.name} sign-in`,
421
+ });
422
+ // A login that prints nothing a person reads needs no input.
423
+ if (!spec.expects) child.stdin.end();
424
+ return { child, release };
425
+ }
426
+
253
427
  /** One request from the control plane (or this server's own routes). */
254
428
  async handle(
255
429
  request: HarnessSignInRequest,
@@ -298,8 +472,10 @@ export class HarnessSignIns {
298
472
  async begin(input: {
299
473
  harness: SignInHarness;
300
474
  member: string;
475
+ sandbox?: SignInSandbox;
301
476
  }): Promise<HarnessSignInStarted> {
302
477
  this.prune();
478
+ await this.recover();
303
479
  const { harness, member } = input;
304
480
  const spec = SIGN_IN_SPECS[harness];
305
481
  try {
@@ -321,20 +497,18 @@ export class HarnessSignIns {
321
497
  harness,
322
498
  member,
323
499
  });
324
- const login = signInCommand({
325
- harness,
326
- home: staging,
327
- env: this.options.env,
328
- });
329
- const child = spawn(login.command, login.args, {
330
- env: signInEnvironment({
500
+ let started: { child: LoginProcess; release: () => Promise<void> };
501
+ try {
502
+ started = await this.startLogin({
331
503
  harness,
332
- base: this.options.env ?? process.env,
333
- login: { ...login.env, NO_COLOR: "1" },
334
- }),
335
- // A login that waits for a pasted code reads it from a plain pipe.
336
- stdio: [spec.expects ? "pipe" : "ignore", "pipe", "pipe"],
337
- });
504
+ staging,
505
+ ...(input.sandbox ? { sandbox: input.sandbox } : {}),
506
+ });
507
+ } catch (error) {
508
+ fs.rmSync(staging, { recursive: true, force: true });
509
+ throw error;
510
+ }
511
+ const { child, release } = started;
338
512
  // A login that ended takes no more input; writing then is no failure.
339
513
  child.stdin?.on("error", () => undefined);
340
514
  const id = randomUUID();
@@ -346,7 +520,9 @@ export class HarnessSignIns {
346
520
  settled = true;
347
521
  clearTimeout(timer);
348
522
  child.kill("SIGTERM");
349
- fs.rmSync(staging, { recursive: true, force: true });
523
+ void release().then(() =>
524
+ fs.rmSync(staging, { recursive: true, force: true }),
525
+ );
350
526
  reject(new HarnessSignInRefusedError(message));
351
527
  };
352
528
  const timer = setTimeout(
@@ -376,6 +552,7 @@ export class HarnessSignIns {
376
552
  harness,
377
553
  member,
378
554
  child,
555
+ release,
379
556
  staging,
380
557
  expiresAt,
381
558
  state: "waiting",
@@ -409,7 +586,7 @@ export class HarnessSignIns {
409
586
  `Could not run ${spec.name} on this machine: ${error.message}. Install it there first`,
410
587
  ),
411
588
  );
412
- const ended = (code: number | null) => {
589
+ const ended = async (code: number | null) => {
413
590
  if (!settled) {
414
591
  fail(
415
592
  lastWords(output) ??
@@ -419,6 +596,9 @@ export class HarnessSignIns {
419
596
  }
420
597
  const attempt = this.attempts.get(id);
421
598
  if (attempt?.state !== "waiting") return;
599
+ // The sandbox goes before its home takes the member's place.
600
+ await release();
601
+ if (this.attempts.get(id)?.state !== "waiting") return;
422
602
  if (code === 0 && signedIn({ harness, home: staging })) {
423
603
  try {
424
604
  // Someone else may have signed in here meanwhile.
@@ -459,6 +639,8 @@ export class HarnessSignIns {
459
639
  Promise.all([drained(child.stdout), drained(child.stderr)]),
460
640
  new Promise((resolve) => setTimeout(resolve, EXIT_DRAIN_MS)),
461
641
  ]).then(() => ended(code));
642
+ // The process ended: its sandbox goes, whatever happens next.
643
+ void release();
462
644
  });
463
645
  });
464
646
  }
@@ -563,8 +745,11 @@ export class HarnessSignIns {
563
745
  attempt.output = "";
564
746
  clearTimeout(attempt.deadline);
565
747
  if (attempt.child.exitCode === null) attempt.child.kill("SIGTERM");
566
- if (state !== "signed-in")
567
- fs.rmSync(attempt.staging, { recursive: true, force: true });
748
+ if (state === "signed-in") return;
749
+ const { staging } = attempt;
750
+ void attempt
751
+ .release()
752
+ .then(() => fs.rmSync(staging, { recursive: true, force: true }));
568
753
  }
569
754
 
570
755
  private prune(): void {