@usine/executor 0.6.1-next.575.g3f7aea9.1.1 → 0.6.1-next.577.gce404bf.1.1

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 (42) hide show
  1. package/README.md +5 -5
  2. package/dist/supervisor/confine.d.ts +9 -0
  3. package/dist/supervisor/confine.d.ts.map +1 -0
  4. package/dist/supervisor/confine.js +41 -0
  5. package/dist/supervisor/confine.js.map +1 -0
  6. package/dist/supervisor/container.d.ts +20 -21
  7. package/dist/supervisor/container.d.ts.map +1 -1
  8. package/dist/supervisor/container.js +263 -204
  9. package/dist/supervisor/container.js.map +1 -1
  10. package/dist/supervisor/detect.d.ts +15 -0
  11. package/dist/supervisor/detect.d.ts.map +1 -0
  12. package/dist/supervisor/detect.js +69 -0
  13. package/dist/supervisor/detect.js.map +1 -0
  14. package/dist/supervisor/homes/file.d.ts +10 -0
  15. package/dist/supervisor/homes/file.d.ts.map +1 -0
  16. package/dist/supervisor/homes/file.js +44 -0
  17. package/dist/supervisor/homes/file.js.map +1 -0
  18. package/dist/supervisor/homes/homes.d.ts +25 -0
  19. package/dist/supervisor/homes/homes.d.ts.map +1 -0
  20. package/dist/supervisor/homes/homes.js +13 -0
  21. package/dist/supervisor/homes/homes.js.map +1 -0
  22. package/dist/supervisor/homes/memory.d.ts +5 -0
  23. package/dist/supervisor/homes/memory.d.ts.map +1 -0
  24. package/dist/supervisor/homes/memory.js +19 -0
  25. package/dist/supervisor/homes/memory.js.map +1 -0
  26. package/dist/supervisor/names.d.ts +6 -0
  27. package/dist/supervisor/names.d.ts.map +1 -1
  28. package/dist/supervisor/names.js +4 -0
  29. package/dist/supervisor/names.js.map +1 -1
  30. package/dist/supervisor/privileges.d.ts +6 -0
  31. package/dist/supervisor/privileges.d.ts.map +1 -0
  32. package/dist/supervisor/privileges.js +10 -0
  33. package/dist/supervisor/privileges.js.map +1 -0
  34. package/dist/supervisor/storage.d.ts +44 -7
  35. package/dist/supervisor/storage.d.ts.map +1 -1
  36. package/dist/supervisor/storage.js +152 -116
  37. package/dist/supervisor/storage.js.map +1 -1
  38. package/dist/supervisor/supervisor.d.ts +4 -1
  39. package/dist/supervisor/supervisor.d.ts.map +1 -1
  40. package/dist/supervisor/supervisor.js +4 -1
  41. package/dist/supervisor/supervisor.js.map +1 -1
  42. package/package.json +6 -6
@@ -4,16 +4,20 @@ import { ExecShell } from "@usine/agents/child-host";
4
4
  import { catalog } from "@usine/agents/harness";
5
5
  import { WorkingDirectory } from "@usine/agents/runtime";
6
6
  import { SupervisorSandbox, SupervisorSeat, SupervisorUnavailable, } from "@usine/agents/supervisor";
7
- import { directoryName } from "./names.js";
8
- import { bindMount } from "../bind-mount.js";
7
+ import { conversationKey } from "./names.js";
8
+ import { confinedDirectory } from "./confine.js";
9
+ import { bindMount, mountField } from "../bind-mount.js";
9
10
  import { prepareImage } from "./image.js";
10
- import { checkConversationStorage, mountConversation } from "./storage.js";
11
+ import { ConversationHomes } from "./homes/homes.js";
12
+ import { archiveHome, checkWorkspaceSize, memoryShortfall, removeFuseStorage, restoreHome, } from "./storage.js";
11
13
  import { SupervisorLimits, WorkerName } from "@usine/core/worker";
12
- import { Cause, Effect, Fiber, FileSystem, Layer, Option, Random, Result, Schedule, Schema, Stream, } from "effect";
14
+ import { Effect, FileSystem, Layer, Option, Random, Result, Schedule, Schema, Stream, SubscriptionRef, } from "effect";
13
15
  import { ChildProcess, ChildProcessSpawner } from "effect/process";
14
16
  import { collectCommand } from "../child-command.js";
15
17
  import { runtimeOptions } from "../remote/runtime.js";
16
18
  import { modelRelayServer, relayModelRequest } from "./model-relay.js";
19
+ import { noNewPrivileges, ROOTLESS_PODMAN_REFUSAL } from "./privileges.js";
20
+ import { detectSandboxRuntime } from "./detect.js";
17
21
  /** The port inside the sandbox on which the model relay listens, on the loopback address. */
18
22
  export const MODEL_RELAY_PORT = 8787;
19
23
  /** The directory inside the sandbox that holds the model relay's socket. */
@@ -54,72 +58,22 @@ require("node:net")
54
58
  .on("connect", () => process.exit(0))
55
59
  .on("error", () => process.exit(1));
56
60
  `;
57
- /** How long the runtime has to answer at startup, so that a hung daemon doesn't hold the orchestrator. */
58
- const DETECTION_TIMEOUT = "15 seconds";
59
61
  /** How long a new sandbox's model relay has to accept connections. */
60
62
  const RELAY_START_TIMEOUT = "30 seconds";
63
+ /** How long a turn waits for the startup check before it asks the member to retry. */
64
+ const READY_TIMEOUT = "30 seconds";
65
+ /** How long the copy of a conversation's home out of its sandbox may take. */
66
+ const SAVE_TIMEOUT = "2 minutes";
67
+ /** How long the startup check's container may take, from its start to its removal. */
68
+ const CHECK_TIMEOUT = "2 minutes";
61
69
  /** The label whose value is the sandbox root of the orchestrator that started the container. */
62
70
  const ROOT_LABEL = "usine.supervisor.root";
63
71
  /** The label whose value is the conversation that the container runs a turn of. */
64
72
  const CONVERSATION_LABEL = "usine.supervisor.conversation";
65
- /** The output format of `<runtime> info` that says whether the runtime runs without root. */
66
- const rootlessFormat = {
67
- podman: "{{.Host.Security.Rootless}}",
68
- docker: "{{json .SecurityOptions}}",
69
- };
70
- /**
71
- * Finds the container runtime for supervisor sandboxes: `preferred`, or Podman and then Docker.
72
- * Returns why there is none when no candidate is installed or can run containers.
73
- */
74
- export const detectSandboxRuntime = Effect.fn("SupervisorSandbox.detectRuntime")(function* (preferred) {
75
- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
76
- const candidates = Option.match(preferred, {
77
- onNone: () => ["podman", "docker"],
78
- onSome: (runtime) => [runtime],
79
- });
80
- const problems = [];
81
- for (const runtime of candidates) {
82
- const info = yield* collectCommand(spawner, "preflight", runtime, ["info", "--format", rootlessFormat[runtime]], { forceKillAfter: "2 seconds" }, 65536).pipe(Effect.timeout(DETECTION_TIMEOUT), Effect.result);
83
- if (Result.isFailure(info)) {
84
- if (Cause.isTimeoutError(info.failure)) {
85
- problems.push(`${runtime} didn't answer within ${DETECTION_TIMEOUT}`);
86
- yield* Effect.logInfo("Skipped a container runtime that didn't answer", {
87
- runtime,
88
- timeout: DETECTION_TIMEOUT,
89
- });
90
- continue;
91
- }
92
- yield* Effect.logInfo("Skipped a container runtime that isn't installed", {
93
- runtime,
94
- message: info.failure.message,
95
- });
96
- continue;
97
- }
98
- if (info.success.exitCode !== 0) {
99
- const reason = info.success.stderr.trim().split("\n")[0] ?? "";
100
- problems.push(`${runtime} is installed but can't run containers${reason === "" ? "" : `: ${reason}`}`);
101
- yield* Effect.logInfo("Skipped a container runtime that can't run containers", {
102
- runtime,
103
- exitCode: info.success.exitCode,
104
- reason,
105
- });
106
- continue;
107
- }
108
- const output = info.success.stdout.trim();
109
- const rootless = runtime === "podman" ? output === "true" : output.includes("rootless");
110
- yield* Effect.logInfo("Found the container runtime for supervisor sandboxes", {
111
- runtime,
112
- rootless,
113
- });
114
- return Result.succeed({ runtime, rootless });
115
- }
116
- const names = candidates.map((runtime) => (runtime === "podman" ? "Podman" : "Docker"));
117
- return Result.fail(SupervisorUnavailable.make({
118
- message: problems.length > 0
119
- ? `Supervisor sessions run in a container, and ${problems.join("; ")}`
120
- : `Supervisor sessions run in a container, and ${names.join(" or ")} isn't installed on the orchestrator host`,
121
- }));
122
- });
73
+ /** The value of the conversation label on the startup check's container. */
74
+ const CHECK_CONVERSATION = "usine-startup-check";
75
+ /** The startup check container's main process, which waits until the check removes it. */
76
+ const IDLE_SCRIPT = "setInterval(() => {}, 60_000);";
123
77
  /** The user that the container's processes run as, so that files they write belong to this host user. */
124
78
  const userOptions = ({ runtime, rootless }) => {
125
79
  const owner = `${process.getuid?.() ?? 0}:${process.getgid?.() ?? 0}`;
@@ -128,10 +82,14 @@ const userOptions = ({ runtime, rootless }) => {
128
82
  // Root in a rootless Docker container is the host user.
129
83
  return rootless ? ["--user", "0:0", "--env", "IS_SANDBOX=1"] : ["--user", owner];
130
84
  };
131
- /** The arguments of `<runtime> run` that start one turn's sandbox in the background. */
132
- export const sandboxRunArguments = (options) => {
133
- const { paths } = options;
134
- const limits = options.limits ?? SupervisorLimits.make({});
85
+ const conversationPaths = (root) => ({
86
+ root,
87
+ home: `${root}/home`,
88
+ workspace: `${root}/workspace`,
89
+ });
90
+ /** The arguments of `<runtime> run` that start a sandbox with `main` as its Node.js arguments. */
91
+ const containerArguments = (options) => {
92
+ const { paths, limits } = options;
135
93
  return [
136
94
  "run",
137
95
  "--detach",
@@ -172,25 +130,37 @@ export const sandboxRunArguments = (options) => {
172
130
  "--workdir",
173
131
  paths.workspace,
174
132
  "--mount",
175
- bindMount(paths.root, paths.root, "writable"),
133
+ [
134
+ "type=tmpfs",
135
+ mountField("destination", paths.root),
136
+ `tmpfs-size=${limits.conversationSizeMib * 1024 ** 2}`,
137
+ "tmpfs-mode=1777",
138
+ ].join(","),
176
139
  "--mount",
177
140
  bindMount(paths.workspace, paths.workspace, "readonly"),
178
- ...options.sources.flatMap(({ repository, directory }) => [
179
- "--mount",
180
- bindMount(directory, `${paths.workspace}/${repository}`, "readonly"),
181
- ]),
182
- "--mount",
183
- bindMount(options.relayDirectory, RELAY_DIRECTORY, "readonly"),
141
+ ...options.mounts.flatMap((mount) => ["--mount", mount]),
184
142
  "--entrypoint",
185
143
  "node",
186
144
  options.image,
145
+ ...options.main,
146
+ ];
147
+ };
148
+ /** The arguments of `<runtime> run` that start one turn's sandbox in the background. */
149
+ export const sandboxRunArguments = (options) => containerArguments({
150
+ ...options,
151
+ limits: options.limits ?? SupervisorLimits.make({}),
152
+ mounts: [
153
+ ...options.sources.map(({ repository, directory }) => bindMount(directory, `${options.paths.workspace}/${repository}`, "readonly")),
154
+ bindMount(options.relayDirectory, RELAY_DIRECTORY, "readonly"),
155
+ ],
156
+ main: [
187
157
  "-e",
188
158
  RELAY_SCRIPT,
189
159
  String(MODEL_RELAY_PORT),
190
160
  `${RELAY_DIRECTORY}/model.sock`,
191
161
  String(RELAY_CHECK_INTERVAL_MILLIS),
192
- ];
193
- };
162
+ ],
163
+ });
194
164
  /** Runs each command line with this host's shell, which enters the sandbox with `<runtime> exec`. */
195
165
  const localTransport = (spawner) => ({
196
166
  run: (line, stdin) => spawner
@@ -211,77 +181,38 @@ const credentialRoute = (route, protocol) => route.credential(protocol).pipe(Eff
211
181
  onSome: (kind) => kind === "subscription" ? "gateway-subscription" : "gateway-api-key",
212
182
  })));
213
183
  const unavailableBecause = (action) => (error) => SupervisorUnavailable.make({ message: `Can't ${action}: ${error.message}` });
184
+ const unavailableWhile = (readiness) => {
185
+ switch (readiness._tag) {
186
+ case "Preparing":
187
+ return Option.some(SupervisorUnavailable.make({
188
+ message: `The supervisor isn't ready yet: usine is ${readiness.step}. Retry the turn later.`,
189
+ }));
190
+ case "Ready":
191
+ return Option.none();
192
+ case "Refused":
193
+ return Option.some(readiness.reason);
194
+ }
195
+ };
214
196
  /**
215
197
  * Opens the sandboxes of supervisor turns on `runtime`, with the harness's model requests sent
216
- * through `openRoute`.
198
+ * through `openRoute`. Startup removes the containers and FUSE images that earlier processes left,
199
+ * then prepares the image and checks a container in the background; turns wait for that check.
217
200
  */
218
201
  const makeContainerSandbox = Effect.fn("SupervisorSandbox.make")(function* (options, runtime, openRoute) {
219
202
  const fs = yield* FileSystem.FileSystem;
220
203
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
204
+ const homes = yield* ConversationHomes;
221
205
  const transport = localTransport(spawner);
222
206
  const limits = options.limits ?? SupervisorLimits.make({});
223
207
  const runtimeCommand = (args) => collectCommand(spawner, "prepare", runtime.runtime, args, { forceKillAfter: "2 seconds" }, 65536).pipe(Effect.timeout("30 seconds"));
224
- /** Whether `path` exists as a directory, without following a symbolic link at `path`. */
225
- const realDirectory = Effect.fn("SupervisorSandbox.realDirectory")(function* (path) {
226
- const info = yield* fs.lstat(path).pipe(Effect.asSome, Effect.catchIf((error) => error.reason._tag === "NotFound", () => Effect.succeedNone));
227
- if (Option.isSome(info) && info.value.type === "Directory")
228
- return;
229
- if (Option.isSome(info)) {
230
- yield* Effect.logWarning("Replaced a file in a supervisor conversation with a directory", {
231
- path,
232
- type: info.value.type,
233
- });
234
- yield* fs.remove(path);
235
- }
236
- yield* fs.makeDirectory(path);
237
- });
238
- /**
239
- * Makes each directory from `root` down to `path` a real directory, replacing a symbolic link or
240
- * other file in its place. A sandbox can write under `root`, so nothing there is followed.
241
- */
242
- const confinedDirectory = Effect.fn("SupervisorSandbox.confinedDirectory")(function* (root, path) {
243
- let current = root;
244
- for (const segment of path.slice(root.length + 1).split("/")) {
245
- current = `${current}/${segment}`;
246
- yield* realDirectory(current);
247
- }
248
- });
249
- /**
250
- * Writes `contents` to `path` under `root` without following a symbolic link: to a new file
251
- * beside it, which then replaces whatever `path` is.
252
- */
253
- const writeConfinedFile = Effect.fn("SupervisorSandbox.writeConfinedFile")(function* (root, path, contents) {
254
- const directory = path.slice(0, path.lastIndexOf("/"));
255
- yield* confinedDirectory(root, directory);
256
- const existing = yield* fs.lstat(path).pipe(Effect.asSome, Effect.catchIf((error) => error.reason._tag === "NotFound", () => Effect.succeedNone));
257
- if (Option.isSome(existing) && existing.value.type !== "File") {
258
- // A turn's shell left a directory, link, or other entry where the settings file belongs.
259
- yield* Effect.logWarning("Replaced an entry in a supervisor conversation with a settings file", {
260
- path,
261
- type: existing.value.type,
262
- });
263
- if (existing.value.type === "Directory")
264
- yield* fs.remove(path, { recursive: true });
265
- }
266
- const suffix = (yield* Random.nextIntBetween(0, 0xffffffff)).toString(16);
267
- const staged = `${path}.usine-${suffix}`;
268
- // `wx` creates the file and fails on any existing entry, including a symbolic link.
269
- yield* fs.writeFileString(staged, contents, { flag: "wx" });
270
- yield* fs.rename(staged, path);
271
- });
272
- /** Writes the harness's gateway settings, pointed at the relay, into the conversation's home. */
273
- const writeWiring = Effect.fn("SupervisorSandbox.writeWiring")(function* (harness, paths) {
274
- const credential = Option.flatMap(catalog.get(harness), ({ worker }) => worker.credential);
275
- if (Option.isNone(credential))
276
- return Option.none();
277
- const { protocol, gatewayPath, gateway } = credential.value;
208
+ /** The harness's gateway settings, pointed at the relay, for the conversation's home. */
209
+ const wiringOf = (harness, paths) => Option.map(Option.flatMap(catalog.get(harness), ({ worker }) => worker.credential), ({ protocol, gatewayPath, gateway }) => {
278
210
  const rendered = gateway.render(`http://127.0.0.1:${MODEL_RELAY_PORT}/${gatewayPath}`, `${paths.home}/.${harness}`);
279
- for (const [path, contents] of rendered.files)
280
- yield* writeConfinedFile(paths.root, path, contents);
281
- return Option.some({
211
+ return {
282
212
  protocol,
213
+ files: rendered.files,
283
214
  environment: { ...rendered.environment, [rendered.tokenVariable]: SANDBOX_TOKEN },
284
- });
215
+ };
285
216
  });
286
217
  const serveRelay = Effect.fn("SupervisorSandbox.serveRelay")(function* (socket, route, model) {
287
218
  // A model response streams for as long as the turn's longest answer.
@@ -312,6 +243,29 @@ const makeContainerSandbox = Effect.fn("SupervisorSandbox.make")(function* (opti
312
243
  })), Effect.retry({ schedule: Schedule.spaced("200 millis") }), Effect.timeout(RELAY_START_TIMEOUT), Effect.mapError(() => SupervisorUnavailable.make({
313
244
  message: `The supervisor sandbox's model relay didn't start within ${RELAY_START_TIMEOUT}`,
314
245
  })));
246
+ /** Fails unless the runtime applied the configured CPU, memory, swap and PID limits to `name`. */
247
+ const verifyLimits = Effect.fn("SupervisorSandbox.verifyLimits")(function* (name) {
248
+ const enforced = yield* runtimeCommand([
249
+ "exec",
250
+ name,
251
+ "sh",
252
+ "-ec",
253
+ CONTAINER_LIMITS_SCRIPT,
254
+ "sh",
255
+ String(limits.cpus),
256
+ String(limits.memoryMib * 1024 ** 2),
257
+ String(limits.pids),
258
+ ]).pipe(Effect.mapError(unavailableBecause("verify supervisor resource limits")));
259
+ if (enforced.exitCode === 0)
260
+ return;
261
+ yield* Effect.logWarning("The supervisor runtime did not enforce resource limits", {
262
+ container: name,
263
+ runtime: runtime.runtime,
264
+ });
265
+ return yield* SupervisorUnavailable.make({
266
+ message: "The runtime did not enforce supervisor CPU, memory, zero-swap and PID limits; check cgroup v2 delegation",
267
+ });
268
+ });
315
269
  const listContainers = (conversation) => runtimeCommand([
316
270
  "ps",
317
271
  "--all",
@@ -343,11 +297,76 @@ const makeContainerSandbox = Effect.fn("SupervisorSandbox.make")(function* (opti
343
297
  message: "Supervisor containers from an earlier process remain; refusing new turns",
344
298
  });
345
299
  }
346
- yield* checkConversationStorage(options.root);
347
- const imageReady = yield* prepareImage(spawner, runtime.runtime, options.image, Option.fromUndefinedOr(options.imagePullTimeout)).pipe(Effect.tapError((error) => Effect.logWarning("Supervisor image preparation failed; retrying in one minute", {
348
- image: options.image,
300
+ yield* removeFuseStorage(options.root).pipe(Effect.catch((error) => Effect.logWarning("Could not look for supervisor storage from an earlier version", {
301
+ root: options.root,
349
302
  message: error.message,
350
- })), Effect.retry({ schedule: Schedule.spaced("1 minute") }), Effect.forkScoped);
303
+ })));
304
+ /**
305
+ * Starts a container with a turn's limits and in-memory home, and copies a home into it and back
306
+ * out, so that a host problem fails this check and not a member's turn.
307
+ */
308
+ const checkContainer = Effect.fn("SupervisorSandbox.checkContainer")(function* () {
309
+ const paths = conversationPaths(`${options.root}/startup-check`);
310
+ yield* confinedDirectory(fs, options.root, paths.workspace);
311
+ const suffix = (yield* Random.nextIntBetween(0, 0xffffffff)).toString(16);
312
+ const container = { runtime: runtime.runtime, name: `usine-supervisor-check-${suffix}` };
313
+ yield* Effect.addFinalizer(() => cleanup(CHECK_CONVERSATION).pipe(Effect.asVoid));
314
+ yield* startContainer(container.name, containerArguments({
315
+ name: container.name,
316
+ root: options.root,
317
+ conversation: CHECK_CONVERSATION,
318
+ runtime,
319
+ image: options.image,
320
+ paths,
321
+ limits,
322
+ mounts: [],
323
+ main: ["-e", IDLE_SCRIPT],
324
+ }));
325
+ yield* verifyLimits(container.name);
326
+ yield* restoreHome(spawner, container, paths.root, Option.none(), [
327
+ [`${paths.home}/check`, "usine startup check\n"],
328
+ ]);
329
+ const archived = yield* Stream.runCollect(archiveHome(spawner, container, paths.root, limits.conversationSizeMib));
330
+ yield* restoreHome(spawner, container, paths.root, Option.some(Stream.fromIterable(archived)), []);
331
+ }, Effect.scoped, Effect.timeoutOrElse({
332
+ duration: CHECK_TIMEOUT,
333
+ orElse: () => Effect.fail(SupervisorUnavailable.make({
334
+ message: `the check didn't finish within ${CHECK_TIMEOUT}`,
335
+ })),
336
+ }), Effect.catch((error) => Effect.gen(function* () {
337
+ const rootlessPodman = runtime.runtime === "podman" && runtime.rootless;
338
+ return yield* SupervisorUnavailable.make({
339
+ message: rootlessPodman && (yield* noNewPrivileges)
340
+ ? `Supervisor sessions run in a container, and ${ROOTLESS_PODMAN_REFUSAL}. The startup check failed: ${error.message}`
341
+ : `The supervisor's startup check failed: ${error.message}`,
342
+ });
343
+ })));
344
+ const readiness = yield* SubscriptionRef.make({
345
+ _tag: "Preparing",
346
+ step: "preparing the supervisor image",
347
+ });
348
+ yield* Effect.gen(function* () {
349
+ yield* prepareImage(spawner, runtime.runtime, options.image, Option.fromUndefinedOr(options.imagePullTimeout)).pipe(Effect.tapError((error) => Effect.logWarning("Supervisor image preparation failed; retrying in one minute", {
350
+ image: options.image,
351
+ message: error.message,
352
+ }).pipe(Effect.andThen(SubscriptionRef.set(readiness, {
353
+ _tag: "Preparing",
354
+ step: `preparing the supervisor image, which failed and is retried every minute (${error.message})`,
355
+ })))), Effect.retry({ schedule: Schedule.spaced("1 minute") }));
356
+ yield* SubscriptionRef.set(readiness, {
357
+ _tag: "Preparing",
358
+ step: "checking a test container",
359
+ });
360
+ const checked = yield* checkContainer().pipe(Effect.result);
361
+ if (Result.isFailure(checked)) {
362
+ yield* Effect.logWarning("The supervisor's startup check failed; fix the cause and restart usine", { runtime: runtime.runtime, message: checked.failure.message });
363
+ return yield* SubscriptionRef.set(readiness, { _tag: "Refused", reason: checked.failure });
364
+ }
365
+ yield* Effect.logInfo("The supervisor's startup check passed", { runtime: runtime.runtime });
366
+ yield* SubscriptionRef.set(readiness, { _tag: "Ready" });
367
+ }).pipe(Effect.forkScoped);
368
+ const unavailable = SubscriptionRef.get(readiness).pipe(Effect.map(unavailableWhile));
369
+ const checked = SubscriptionRef.changes(readiness).pipe(Stream.filter((state) => state._tag !== "Preparing"), Stream.runHead, Effect.andThen(unavailable));
351
370
  const running = new Map();
352
371
  const holdConversation = (conversation, directory) => Effect.acquireRelease(Effect.gen(function* () {
353
372
  if (running.get(directory) === "active") {
@@ -376,22 +395,60 @@ const makeContainerSandbox = Effect.fn("SupervisorSandbox.make")(function* (opti
376
395
  directory,
377
396
  });
378
397
  })));
379
- return Effect.fn("SupervisorSandbox.open")(function* (request) {
398
+ /** The turns whose sandboxes run, by container name. */
399
+ const turns = new Map();
400
+ /**
401
+ * Saves the home of `turn` from its sandbox, then checks the files that the orchestrator's own
402
+ * harness process wrote for the conversation.
403
+ */
404
+ const saveTurn = Effect.fn("SupervisorSandbox.save")(function* (turn) {
405
+ yield* Effect.annotateCurrentSpan({
406
+ conversation: turn.conversation,
407
+ container: turn.container.name,
408
+ });
409
+ turn.saveTried = true;
410
+ yield* homes
411
+ .save(turn.key, archiveHome(spawner, turn.container, turn.paths.root, limits.conversationSizeMib))
412
+ .pipe(Effect.mapError((error) => error._tag === "HomeStoreError"
413
+ ? SupervisorUnavailable.make({
414
+ message: `Can't save the conversation's home: ${error.message}`,
415
+ })
416
+ : error), Effect.timeoutOrElse({
417
+ duration: SAVE_TIMEOUT,
418
+ orElse: () => Effect.fail(SupervisorUnavailable.make({
419
+ message: `Can't save the conversation's home: the copy didn't finish within ${SAVE_TIMEOUT}`,
420
+ })),
421
+ }));
422
+ yield* checkWorkspaceSize(fs, turn.paths.workspace, limits);
423
+ yield* Effect.logInfo("Saved a supervisor conversation", {
424
+ conversation: turn.conversation,
425
+ container: turn.container.name,
426
+ });
427
+ });
428
+ const save = (seat) => Option.match(Option.fromUndefinedOr(turns.get(seat.host.container.name)), {
429
+ onNone: () => Effect.fail(SupervisorUnavailable.make({
430
+ message: "Can't save the conversation: its turn's sandbox is closed",
431
+ })),
432
+ onSome: saveTurn,
433
+ });
434
+ const open = Effect.fn("SupervisorSandbox.open")(function* (request) {
380
435
  yield* Effect.annotateCurrentSpan({
381
436
  conversation: request.conversation,
382
437
  harness: request.harness,
383
438
  sources: request.sources.length,
384
439
  });
385
- yield* Fiber.join(imageReady).pipe(Effect.timeout("30 seconds"), Effect.mapError(() => SupervisorUnavailable.make({
386
- message: "The supervisor image is still being prepared; retry the turn later",
387
- })), Effect.tapError((error) => Effect.logWarning(error.message, {
388
- conversation: request.conversation,
389
- image: options.image,
390
- })));
391
- const segment = directoryName(request.conversation);
392
- const root = `${options.root}/conversations/${segment}`;
440
+ const notReady = yield* checked.pipe(Effect.timeoutOrElse({ duration: READY_TIMEOUT, orElse: () => unavailable }));
441
+ if (Option.isSome(notReady)) {
442
+ yield* Effect.logWarning("Supervisor turn refused: the sandbox isn't ready", {
443
+ conversation: request.conversation,
444
+ reason: notReady.value.message,
445
+ });
446
+ return yield* notReady.value;
447
+ }
448
+ const key = conversationKey(request.conversation);
449
+ const paths = conversationPaths(`${options.root}/conversations/${key}`);
393
450
  // No sandbox of the conversation writes to its directory while this turn prepares it.
394
- yield* holdConversation(request.conversation, root);
451
+ yield* holdConversation(request.conversation, paths.root);
395
452
  if ((yield* listContainers(request.conversation)).length !== 0) {
396
453
  yield* Effect.logWarning("A supervisor container remains; refusing a new turn", {
397
454
  conversation: request.conversation,
@@ -400,19 +457,15 @@ const makeContainerSandbox = Effect.fn("SupervisorSandbox.make")(function* (opti
400
457
  message: "A supervisor container remains for this conversation; refusing a new turn",
401
458
  });
402
459
  }
403
- yield* mountConversation(fs, spawner, options.root, segment, limits);
404
- const paths = { root, home: `${root}/home`, workspace: `${root}/workspace` };
405
460
  // The workspace, and the mount points of the sources in it, exist before they're mounted, even
406
461
  // for a turn without sources: Podman refuses a missing mount source, and Docker creates it as
407
- // its daemon's user.
408
- yield* fs
409
- .makeDirectory(root, { recursive: true })
410
- .pipe(Effect.andThen(Effect.forEach([
411
- paths.home,
462
+ // its daemon's user. A runtime follows links in a mount source, so none is followed here.
463
+ yield* Effect.forEach([
412
464
  paths.workspace,
413
465
  ...request.sources.map(({ repository }) => `${paths.workspace}/${repository}`),
414
- ], (directory) => confinedDirectory(root, directory), { discard: true })), Effect.mapError(unavailableBecause("create the conversation's directories")));
415
- const wiring = yield* writeWiring(request.harness, paths).pipe(Effect.mapError(unavailableBecause("write the harness's model settings")));
466
+ ], (directory) => confinedDirectory(fs, options.root, directory), { discard: true });
467
+ const written = yield* checkWorkspaceSize(fs, paths.workspace, limits);
468
+ const wiring = wiringOf(request.harness, paths);
416
469
  const route = yield* openRoute.pipe(Effect.mapError(unavailableBecause("open the instance's model route")));
417
470
  const credential = yield* Option.match(wiring, {
418
471
  onNone: () => Effect.succeed("gateway"),
@@ -424,10 +477,13 @@ const makeContainerSandbox = Effect.fn("SupervisorSandbox.make")(function* (opti
424
477
  .pipe(Effect.mapError(unavailableBecause("create the model relay's directory")));
425
478
  yield* serveRelay(`${relayDirectory}/model.sock`, route, request.model).pipe(Effect.mapError(unavailableBecause("serve the model relay")));
426
479
  const suffix = (yield* Random.nextIntBetween(0, 0xffffffff)).toString(16);
427
- const name = `usine-supervisor-${segment.slice(0, 40)}-${suffix}`;
480
+ const container = {
481
+ runtime: runtime.runtime,
482
+ name: `usine-supervisor-${key.slice(0, 40)}-${suffix}`,
483
+ };
428
484
  yield* Effect.addFinalizer(() => cleanup(request.conversation).pipe(Effect.asVoid));
429
- yield* startContainer(name, sandboxRunArguments({
430
- name,
485
+ yield* startContainer(container.name, sandboxRunArguments({
486
+ name: container.name,
431
487
  root: options.root,
432
488
  conversation: request.conversation,
433
489
  runtime,
@@ -437,34 +493,32 @@ const makeContainerSandbox = Effect.fn("SupervisorSandbox.make")(function* (opti
437
493
  relayDirectory,
438
494
  limits,
439
495
  }));
440
- yield* awaitRelay(name);
441
- const enforced = yield* runtimeCommand([
442
- "exec",
443
- name,
444
- "sh",
445
- "-ec",
446
- CONTAINER_LIMITS_SCRIPT,
447
- "sh",
448
- String(limits.cpus),
449
- String(limits.memoryMib * 1024 ** 2),
450
- String(limits.pids),
451
- ]).pipe(Effect.mapError(unavailableBecause("verify supervisor resource limits")));
452
- if (enforced.exitCode !== 0) {
453
- yield* Effect.logWarning("The supervisor runtime did not enforce resource limits", {
496
+ yield* awaitRelay(container.name);
497
+ yield* verifyLimits(container.name);
498
+ const saved = yield* homes
499
+ .load(key)
500
+ .pipe(Effect.mapError(unavailableBecause("read the conversation's saved home")));
501
+ yield* restoreHome(spawner, container, paths.root, saved, Option.match(wiring, { onNone: () => [], onSome: ({ files }) => files }));
502
+ const turn = {
503
+ conversation: request.conversation,
504
+ key,
505
+ container,
506
+ paths,
507
+ saveTried: false,
508
+ };
509
+ turns.set(container.name, turn);
510
+ // Runs before the container's removal, which the finalizers added earlier do.
511
+ yield* Effect.addFinalizer(() => Effect.gen(function* () {
512
+ turns.delete(container.name);
513
+ if (turn.saveTried)
514
+ return;
515
+ yield* saveTurn(turn).pipe(Effect.catch((error) => Effect.logWarning("Could not save a supervisor conversation at the end of its turn", {
454
516
  conversation: request.conversation,
455
- container: name,
456
- runtime: runtime.runtime,
457
- });
458
- return yield* SupervisorUnavailable.make({
459
- message: "The runtime did not enforce supervisor CPU, memory, zero-swap and PID limits; check cgroup v2 delegation",
460
- });
461
- }
517
+ message: error.message,
518
+ })));
519
+ }));
462
520
  return SupervisorSeat.make({
463
- host: yield* Schema.decodeEffect(SupervisorSeat.fields.host)(ExecShell.make({
464
- transport,
465
- destination: name,
466
- container: { runtime: runtime.runtime, name },
467
- })).pipe(Effect.mapError(unavailableBecause("construct the supervisor seat"))),
521
+ host: yield* Schema.decodeEffect(SupervisorSeat.fields.host)(ExecShell.make({ transport, destination: container.name, container })).pipe(Effect.mapError(unavailableBecause("construct the supervisor seat"))),
468
522
  worker: WorkerName.make("supervisor"),
469
523
  protocolFrameMib: limits.protocolFrameMib,
470
524
  cwd: WorkingDirectory.make(paths.workspace),
@@ -473,35 +527,46 @@ const makeContainerSandbox = Effect.fn("SupervisorSandbox.make")(function* (opti
473
527
  onSome: ({ environment }) => environment,
474
528
  }),
475
529
  credential,
530
+ restored: Option.isSome(saved) || written > 0,
476
531
  });
477
532
  });
533
+ return { unavailable, checked, open, save };
534
+ });
535
+ /** A sandbox on which every turn fails with `reason`. */
536
+ const refusing = (reason) => ({
537
+ unavailable: Effect.succeedSome(reason),
538
+ checked: Effect.succeedSome(reason),
539
+ open: () => Effect.fail(reason),
540
+ save: () => Effect.fail(reason),
478
541
  });
479
542
  /**
480
543
  * The supervisor sandbox as one container per turn, on Podman or Docker on the orchestrator host.
481
544
  * The container has no network: a relay inside it forwards the harness's model requests over a
482
545
  * socket to the orchestrator, which sends them through the instance's model route with the
483
546
  * instance's credential. Each repository's source is mounted read-only under the working
484
- * directory, and only the conversation's own directory is writable; no instance file is mounted.
485
- * The conversation's directory, with the harness's saved sessions, stays after the turn. Without
486
- * a container runtime or a model route, every turn fails with the reason.
547
+ * directory. The harness's home is an in-memory filesystem of `conversation_size_mib`, which each
548
+ * turn restores from `ConversationHomes` and saves back when it ends; no instance file is
549
+ * mounted. Without a container runtime, a model route, or limits that leave the harness memory,
550
+ * every turn fails with the reason.
487
551
  */
488
552
  export const containerSandboxLayer = (options) => Layer.effect(SupervisorSandbox, Effect.gen(function* () {
553
+ const limits = options.limits ?? SupervisorLimits.make({});
489
554
  const detected = yield* detectSandboxRuntime(options.runtime);
490
555
  const available = Result.flatMap(detected, (runtime) => Option.match(options.route, {
491
556
  onNone: () => Result.fail(SupervisorUnavailable.make({
492
557
  message: "Supervisor sessions reach the model through the instance's gateway, and no worker gateway is configured",
493
558
  })),
494
- onSome: (route) => Result.succeed({ runtime, route }),
559
+ onSome: (route) => Option.match(memoryShortfall(limits), {
560
+ onNone: () => Result.succeed({ runtime, route }),
561
+ onSome: (message) => Result.fail(SupervisorUnavailable.make({ message })),
562
+ }),
495
563
  }));
496
564
  if (Result.isFailure(available)) {
497
565
  const reason = available.failure;
498
566
  yield* Effect.logInfo("Supervisor sessions are unavailable on this orchestrator", {
499
567
  reason: reason.message,
500
568
  });
501
- return {
502
- unavailable: Option.some(reason),
503
- open: () => Effect.fail(reason),
504
- };
569
+ return refusing(reason);
505
570
  }
506
571
  const { runtime, route } = available.success;
507
572
  const prepared = yield* makeContainerSandbox(options, runtime, route).pipe(Effect.result);
@@ -509,14 +574,8 @@ export const containerSandboxLayer = (options) => Layer.effect(SupervisorSandbox
509
574
  yield* Effect.logWarning("Supervisor sandbox preparation failed", {
510
575
  message: prepared.failure.message,
511
576
  });
512
- return {
513
- unavailable: Option.some(prepared.failure),
514
- open: () => Effect.fail(prepared.failure),
515
- };
577
+ return refusing(prepared.failure);
516
578
  }
517
- return {
518
- unavailable: Option.none(),
519
- open: prepared.success,
520
- };
579
+ return prepared.success;
521
580
  }));
522
581
  //# sourceMappingURL=container.js.map