@foldrun/core 0.4.0 → 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.
Files changed (170) hide show
  1. package/README.md +7 -4
  2. package/dist/index.d.ts +4 -0
  3. package/dist/index.js +4 -0
  4. package/dist/src/account.d.ts +45 -0
  5. package/dist/src/account.js +130 -0
  6. package/dist/src/api-tools.d.ts +8 -0
  7. package/dist/src/api-tools.js +22 -4
  8. package/dist/src/browser-pod.d.ts +148 -0
  9. package/dist/src/browser-pod.js +333 -0
  10. package/dist/src/catalog.js +2 -1
  11. package/dist/src/clock.d.ts +49 -0
  12. package/dist/src/clock.js +121 -0
  13. package/dist/src/completions.js +17 -8
  14. package/dist/src/confine.d.ts +22 -0
  15. package/dist/src/confine.js +218 -3
  16. package/dist/src/container.d.ts +9 -0
  17. package/dist/src/container.js +115 -5
  18. package/dist/src/context-tools.d.ts +1 -1
  19. package/dist/src/deploy.d.ts +33 -0
  20. package/dist/src/deploy.js +145 -6
  21. package/dist/src/egress.d.ts +7 -0
  22. package/dist/src/egress.js +6 -0
  23. package/dist/src/eol.d.ts +2 -0
  24. package/dist/src/eol.js +7 -0
  25. package/dist/src/evals.d.ts +5 -0
  26. package/dist/src/evals.js +9 -2
  27. package/dist/src/flow-lint.d.ts +8 -0
  28. package/dist/src/flow-lint.js +223 -1
  29. package/dist/src/flow-patterns.d.ts +141 -0
  30. package/dist/src/flow-patterns.js +568 -0
  31. package/dist/src/gitrepo.d.ts +18 -0
  32. package/dist/src/gitrepo.js +49 -0
  33. package/dist/src/host-env.js +5 -0
  34. package/dist/src/kinds.js +1 -1
  35. package/dist/src/language.d.ts +17 -0
  36. package/dist/src/language.js +55 -0
  37. package/dist/src/layout.d.ts +69 -0
  38. package/dist/src/layout.js +200 -0
  39. package/dist/src/library.d.ts +9 -0
  40. package/dist/src/library.js +30 -3
  41. package/dist/src/limits.d.ts +84 -0
  42. package/dist/src/limits.js +287 -0
  43. package/dist/src/locale.d.ts +47 -0
  44. package/dist/src/locale.js +177 -0
  45. package/dist/src/mail.d.ts +88 -0
  46. package/dist/src/mail.js +247 -0
  47. package/dist/src/model-credential.d.ts +14 -0
  48. package/dist/src/model-credential.js +58 -0
  49. package/dist/src/model-probe.d.ts +3 -0
  50. package/dist/src/model-probe.js +1 -0
  51. package/dist/src/notify.d.ts +53 -7
  52. package/dist/src/notify.js +194 -126
  53. package/dist/src/openapi.js +5 -3
  54. package/dist/src/operator.d.ts +201 -0
  55. package/dist/src/operator.js +251 -0
  56. package/dist/src/paths.d.ts +28 -0
  57. package/dist/src/paths.js +55 -0
  58. package/dist/src/platform.d.ts +43 -3
  59. package/dist/src/platform.js +9 -1
  60. package/dist/src/provider-health.js +3 -2
  61. package/dist/src/providers.d.ts +481 -0
  62. package/dist/src/providers.js +1105 -6
  63. package/dist/src/refusal.d.ts +83 -0
  64. package/dist/src/refusal.js +281 -0
  65. package/dist/src/run-container.d.ts +149 -13
  66. package/dist/src/run-container.js +424 -43
  67. package/dist/src/runner.d.ts +177 -9
  68. package/dist/src/runner.js +1146 -154
  69. package/dist/src/runtime.d.ts +52 -0
  70. package/dist/src/runtime.js +493 -58
  71. package/dist/src/script-tools.d.ts +17 -2
  72. package/dist/src/script-tools.js +82 -10
  73. package/dist/src/secret-files.d.ts +6 -5
  74. package/dist/src/secret-files.js +24 -11
  75. package/dist/src/secret-health.d.ts +30 -6
  76. package/dist/src/secret-health.js +42 -20
  77. package/dist/src/secrets.d.ts +19 -0
  78. package/dist/src/secrets.js +155 -86
  79. package/dist/src/starter.d.ts +9 -0
  80. package/dist/src/starter.js +92 -11
  81. package/dist/src/step-exec.d.ts +72 -2
  82. package/dist/src/step-exec.js +431 -37
  83. package/dist/src/step-removal.d.ts +15 -0
  84. package/dist/src/step-removal.js +49 -0
  85. package/dist/src/storage.d.ts +23 -4
  86. package/dist/src/storage.js +125 -23
  87. package/dist/src/store.d.ts +222 -37
  88. package/dist/src/store.js +349 -62
  89. package/dist/src/subagents.d.ts +75 -0
  90. package/dist/src/subagents.js +149 -0
  91. package/dist/src/test-mode.d.ts +17 -2
  92. package/dist/src/test-mode.js +53 -13
  93. package/dist/src/tool-names.d.ts +13 -1
  94. package/dist/src/tool-names.js +38 -11
  95. package/dist/src/tool-programs.d.ts +26 -0
  96. package/dist/src/tool-programs.js +172 -0
  97. package/dist/src/tool-test.js +104 -12
  98. package/dist/src/translator.d.ts +8 -2
  99. package/dist/src/translator.js +69 -23
  100. package/dist/src/trigger-log.d.ts +1 -1
  101. package/dist/src/triggers.d.ts +3 -0
  102. package/dist/src/triggers.js +10 -2
  103. package/dist/src/untrusted-fetch.d.ts +11 -0
  104. package/dist/src/untrusted-fetch.js +77 -0
  105. package/dist/src/web-actions.d.ts +91 -0
  106. package/dist/src/web-actions.js +199 -0
  107. package/dist/src/webhook.d.ts +4 -0
  108. package/dist/src/webhook.js +39 -0
  109. package/index.ts +4 -0
  110. package/package.json +3 -3
  111. package/src/account.ts +149 -0
  112. package/src/api-tools.ts +32 -4
  113. package/src/browser-pod.ts +350 -0
  114. package/src/catalog.ts +2 -1
  115. package/src/clock.ts +149 -0
  116. package/src/completions.ts +17 -8
  117. package/src/confine.ts +218 -3
  118. package/src/container.ts +112 -5
  119. package/src/context-tools.ts +1 -1
  120. package/src/deploy.ts +137 -6
  121. package/src/egress.ts +13 -1
  122. package/src/eol.ts +7 -0
  123. package/src/evals.ts +14 -2
  124. package/src/flow-lint.ts +253 -1
  125. package/src/flow-patterns.ts +597 -0
  126. package/src/gitrepo.ts +48 -0
  127. package/src/host-env.ts +5 -0
  128. package/src/kinds.ts +1 -1
  129. package/src/language.ts +62 -0
  130. package/src/layout.ts +228 -0
  131. package/src/library.ts +37 -3
  132. package/src/limits.ts +290 -0
  133. package/src/locale.ts +217 -0
  134. package/src/mail.ts +318 -0
  135. package/src/model-credential.ts +71 -0
  136. package/src/model-probe.ts +4 -0
  137. package/src/notify.ts +189 -103
  138. package/src/openapi.ts +5 -3
  139. package/src/operator.ts +300 -0
  140. package/src/paths.ts +54 -0
  141. package/src/platform.ts +52 -3
  142. package/src/provider-health.ts +3 -2
  143. package/src/providers.ts +1368 -6
  144. package/src/refusal.ts +320 -0
  145. package/src/run-container.ts +460 -44
  146. package/src/runner.ts +1168 -155
  147. package/src/runtime.ts +487 -55
  148. package/src/script-tools.ts +81 -10
  149. package/src/secret-files.ts +22 -10
  150. package/src/secret-health.ts +64 -19
  151. package/src/secrets.ts +149 -87
  152. package/src/starter.ts +93 -11
  153. package/src/step-exec.ts +447 -38
  154. package/src/step-removal.ts +59 -0
  155. package/src/storage.ts +141 -22
  156. package/src/store.ts +506 -70
  157. package/src/subagents.ts +189 -0
  158. package/src/test-mode.ts +51 -11
  159. package/src/tool-names.ts +40 -11
  160. package/src/tool-programs.ts +179 -0
  161. package/src/tool-test.ts +110 -12
  162. package/src/translator.ts +72 -22
  163. package/src/trigger-log.ts +1 -0
  164. package/src/triggers.ts +10 -2
  165. package/src/untrusted-fetch.ts +88 -0
  166. package/src/web-actions.ts +237 -0
  167. package/src/webhook.ts +41 -0
  168. package/templates/blog-desk/agents/writer/agent.md +1 -1
  169. package/templates/hello/agents/curator/agent.md +4 -4
  170. package/templates/hello/agents/notetaker/agent.md +3 -3
@@ -23,10 +23,11 @@ import path from "node:path";
23
23
  import crypto from "node:crypto";
24
24
  import { spawn, spawnSync } from "node:child_process";
25
25
  import { isPlatformPath } from "./store.js";
26
- import { divertedSummary, isDivertedPath } from "./test-mode.js";
26
+ import { divertedSummary, isDivertedPath, overlayTestWrites } from "./test-mode.js";
27
27
  import { isFileValue, fileContent } from "./secrets.js";
28
28
  import { safeTenantSegment } from "./runtime.js";
29
- import { dataRoot } from "./paths.js";
29
+ import { isOperatorEvent } from "./operator.js";
30
+ import { parseBrowserPod } from "./browser-pod.js";
30
31
  /**
31
32
  * The one place the timing line is worded, so the docker and k8s traces
32
33
  * read the same and a cold-start regression is greppable across both.
@@ -124,6 +125,34 @@ export function hashTree(dir) {
124
125
  walk(dir);
125
126
  return out;
126
127
  }
128
+ /**
129
+ * Every file's mtime under `dir`, relative path to milliseconds — so a copy
130
+ * that cannot carry times can have them put back. `kubectl cp` unpacks with
131
+ * `tar -m`, which stamps every file with the moment it landed; on 2026-09-24
132
+ * gbp-desk's reply-sheet check ("pending-replies.json written in the last
133
+ * hour") passed on a file last written on 2026-09-13, and the poster sent
134
+ * nothing. Every freshness check in every flow was answering "yes".
135
+ */
136
+ export function mtimeManifest(dir) {
137
+ const out = {};
138
+ const walk = (d) => {
139
+ for (const entry of fs.readdirSync(d, { withFileTypes: true })) {
140
+ const abs = path.join(d, entry.name);
141
+ if (entry.isSymbolicLink())
142
+ continue;
143
+ if (entry.isDirectory())
144
+ walk(abs);
145
+ else
146
+ out[path.relative(dir, abs).replaceAll("\\", "/")] = fs.statSync(abs).mtimeMs;
147
+ }
148
+ };
149
+ if (fs.existsSync(dir))
150
+ walk(dir);
151
+ return out;
152
+ }
153
+ /** The in-pod half of mtimeManifest: a node one-liner, run as root before `go`. */
154
+ export const APPLY_MTIMES_JS = `const fs=require("fs"),p=require("path");const m=JSON.parse(fs.readFileSync(process.argv[1],"utf8"));` +
155
+ `for(const [r,t] of Object.entries(m)){try{fs.utimesSync(p.join(process.argv[2],r),t/1000,t/1000)}catch{}}`;
127
156
  const sha = (b) => crypto.createHash("sha256").update(b).digest("hex");
128
157
  /**
129
158
  * Both sides changed a file the step was handed. When each is the handed-in
@@ -255,27 +284,54 @@ export function applyContainerChanges(hostWs, containerWs, baseline, note, diver
255
284
  */
256
285
  export const RUNTIME_CACHE = "/home/agent/.foldrun/runner/.runtimes";
257
286
  /**
258
- * The per-tenant directory backing that mount, or null when there is none.
287
+ * Where the platform's shared runtime layer is mounted, read-only, in a run
288
+ * pod — and read-write, one entry at a time, in the pod that builds an entry
289
+ * for it (foldrun-platform runtime-warm.ts). A fixed path for the same reason
290
+ * as RUNTIME_CACHE: a venv hard-codes its own location. Laid out as
291
+ * <FOLDRUN_DATA>/shared/.runtimes so the builder's prepareRuntime("shared", …)
292
+ * lands exactly here with FOLDRUN_DATA=/opt/foldrun-runtimes.
293
+ */
294
+ export const SHARED_RUNTIMES = "/opt/foldrun-runtimes/shared/.runtimes";
295
+ /** Docker's own volume-name charset: a leading alphanumeric, then
296
+ * alphanumerics plus `_ . -`. The mount source is handed straight to the
297
+ * daemon, so it is validated against this rather than assumed. */
298
+ const DOCKER_VOLUME_NAME = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
299
+ /**
300
+ * The per-tenant runtime cache mount — a Docker NAMED volume and the fixed
301
+ * path it mounts at — or null when there is none.
259
302
  *
260
- * Per-tenant, not shared. A shared cache would store one copy of pandas
261
- * instead of one per account, but it would also be mutable state that one
262
- * tenant's step writes and another tenant's step then *executes* — a poisoned
263
- * venv arriving as a trusted local file, which is precisely the path gVisor,
264
- * the capability drop and the egress policy all exist to close. Disk is the
265
- * cheaper thing to spend. If the duplication ever stops being cheap, the fix
266
- * is a read-only mount filled by a trusted builder, not a writable shared one.
303
+ * A named volume, not a host path. The run's `docker create` is issued to the
304
+ * host daemon over the mounted socket, and that daemon cannot resolve a path
305
+ * under the platform's own FOLDRUN_DATA — which under compose is itself a named
306
+ * volume, or a directory Docker Desktop has not shared — so `-v <hostpath>:…`
307
+ * failed with "mounts denied". A named volume is resolved by the daemon, needs
308
+ * no host sharing, and on first use is seeded from the image's mount point,
309
+ * which the runner image creates owned by the agent user (the DOCKERFILE below,
310
+ * `${RUNTIME_CACHE}`) — so the fresh cache is writable without a host-side chown.
267
311
  *
268
- * Deliberately NOT under `<tenant>/.runtimes`, which is the *host* cache: the
269
- * venvs there carry host absolute paths and would be unusable inside a runner.
270
- * Two roots, so a hit is always a real hit.
312
+ * Per-tenant, not shared. A shared cache would store one copy of pandas instead
313
+ * of one per account, but it would also be mutable state that one tenant's step
314
+ * writes and another tenant's step then *executes* — a poisoned venv arriving
315
+ * as a trusted local file, which is precisely the path gVisor, the capability
316
+ * drop and the egress policy all exist to close. Disk is the cheaper thing to
317
+ * spend. One volume per tenant keeps that boundary; each carries a
318
+ * `foldrun.io/tenant` label so it can be found and pruned (self-hosting/README.md).
319
+ *
320
+ * The venvs inside carry the runner's own absolute paths, distinct from the
321
+ * host's `<tenant>/.runtimes` cache — two roots, so a hit is always a real hit.
271
322
  */
272
- export function runtimeCacheDir(tenant) {
323
+ export function runtimeCacheMount(tenant) {
273
324
  if (process.env.FOLDRUN_RUNTIME_CACHE === "off")
274
325
  return null;
275
326
  const safe = tenant ? safeTenantSegment(tenant) : null;
276
327
  if (!safe)
277
328
  return null;
278
- return path.join(dataRoot(), safe, ".runtimes-sandbox");
329
+ const source = `foldrun-rt-${safe}`;
330
+ // safeTenantSegment already yields Docker's charset and `foldrun-rt-` is a
331
+ // safe leading token — but the source is what the daemon binds, so prove it.
332
+ if (!DOCKER_VOLUME_NAME.test(source))
333
+ return null;
334
+ return { source, target: RUNTIME_CACHE };
279
335
  }
280
336
  // ---------- the runner image ----------
281
337
  const DRIVER = `// The runner container's entrypoint. Reads one step, executes it with the
@@ -333,9 +389,11 @@ try {
333
389
  const { buildScriptTools } = await import("@foldrun/core/script-tools");
334
390
  const { buildConsultTools } = await import("@foldrun/core/agent-tools");
335
391
  const { buildSearchTools, buildHistoryTools, buildDeskTools } = await import("@foldrun/core/context-tools");
392
+ const { httpChannel, buildAskTool, inboxReader } = await import("@foldrun/core/operator");
336
393
  const { startTranslator } = await import("@foldrun/core/translator");
337
394
  const { prepareRuntime } = await import("@foldrun/core/runtime");
338
395
  const { materializeFileSecrets } = await import("@foldrun/core/secret-files");
396
+ const { paidWebActions } = await import("@foldrun/core/browser-pod");
339
397
 
340
398
  const agentDir = "/workspace/" + input.agentRel;
341
399
  // HOME is where a bare relative path lands when anything resolves one
@@ -357,6 +415,10 @@ try {
357
415
  : { interpreters: {}, env: {}, log: [], error: null };
358
416
  for (const line of runtime.log) emit("info", "runtime: " + line);
359
417
  if (runtime.error) emit("error", "runtime: " + runtime.error);
418
+ // The step's own environment gets it too, not only the script tools: an
419
+ // agent that runs "python3 x.py" or a shebang script through Bash should
420
+ // meet the packages its runtime declared, not the image's bare python.
421
+ Object.assign(env, runtime.env);
360
422
 
361
423
  // API and script tools, rebuilt in here from their specs. Secrets were
362
424
  // substituted into API headers before the input crossed the boundary, so
@@ -384,6 +446,11 @@ try {
384
446
  const search = buildSearchTools(input.search ?? []);
385
447
  const history = input.history?.length ? buildHistoryTools(input.history) : { server: null };
386
448
  const desks = input.desks?.length ? buildDeskTools(input.desks) : { server: null };
449
+ // A person in the loop, over the proxy this step's lease already names:
450
+ // ask_person when tools: [ask], and the run's inbox after every tool call.
451
+ const channel = httpChannel(env.FOLDRUN_EGRESS);
452
+ const ask = input.ask ? buildAskTool({ channel, timeoutSec: input.ask.timeoutSec, emit }) : { server: null };
453
+ const inbox = channel ? inboxReader(channel, emit) : undefined;
387
454
 
388
455
  const outcome = await executeStep({
389
456
  agentDir,
@@ -402,8 +469,11 @@ try {
402
469
  ...(search.server ? { foldrun_search: search.server } : {}),
403
470
  ...(history.server ? { foldrun_history: history.server } : {}),
404
471
  ...(desks.server ? { foldrun_desks: desks.server } : {}),
472
+ ...(ask.server ? { foldrun_ask: ask.server } : {}),
405
473
  ...input.mcpServers,
406
474
  },
475
+ ...(inbox ? { inbox } : {}),
476
+ ...(input.subagents?.length ? { subagents: input.subagents } : {}),
407
477
  env,
408
478
  timeoutSec: input.timeoutSec,
409
479
  budgetUsd: input.budgetUsd,
@@ -414,6 +484,12 @@ try {
414
484
  output: input.output,
415
485
  schema: input.schema,
416
486
  maxTurns: input.maxTurns,
487
+ ...(input.limits && Object.keys(input.limits).length ? { limits: input.limits, toolOwners: input.toolOwners ?? {} } : {}),
488
+ // Slim browsing: the platform put this step on the slim image to browse
489
+ // through the account's pod, and named the file the web tool logs its
490
+ // reconnects to. A lost pod stops the step; what it wrote decides what
491
+ // the runner does next (browser-pod.ts).
492
+ ...(env.FOLDRUN_BROWSER_POD_EVENTS ? { browserPod: { events: env.FOLDRUN_BROWSER_POD_EVENTS, methods: api.methods ?? {}, paidWeb: paidWebActions(env), ...(env.FOLDRUN_BROWSER_INIT ? { browseInit: env.FOLDRUN_BROWSER_INIT } : {}) } } : {}),
417
493
  // The container is the boundary; the SDK's own bash sandbox here would
418
494
  // only block declared network use (SSH, curl) for no added safety.
419
495
  sandboxBash: false,
@@ -428,6 +504,7 @@ try {
428
504
  // A consult's spend belongs to the step that asked.
429
505
  const consultCost = consult.drainCost();
430
506
  if (consultCost > 0) outcome.costUsd = (outcome.costUsd ?? 0) + consultCost;
507
+ if (consultCost > 0 && typeof outcome.turnsCostUsd === "number") outcome.turnsCostUsd += consultCost;
431
508
  process.stdout.write(JSON.stringify({ e: "done", ...outcome, res: readActuals() }) + "\\n");
432
509
  process.exit(0);
433
510
  } catch (err) {
@@ -441,35 +518,245 @@ try {
441
518
  process.exit(0);
442
519
  }
443
520
  `;
521
+ // Core itself is installed in a stage of its own (CORE_STAGE) and only the
522
+ // result is copied in: the tarball and the package README — which explains
523
+ // foldrun to a person reading the repo, and which no step reads — stay in
524
+ // that stage and never become a layer of the image. Owner rule, 2026-10-02:
525
+ // foldrun's own docs live in git, not in containers.
526
+ const CORE_STAGE = `FROM base AS core
527
+ WORKDIR /opt/runner
528
+ COPY foldrun-core.tgz ./
529
+ RUN npm init -y >/dev/null && npm install ./foldrun-core.tgz --omit=dev \\
530
+ && npm cache clean --force >/dev/null 2>&1 \\
531
+ && rm -f foldrun-core.tgz node_modules/@foldrun/core/README.md
532
+ `;
444
533
  // docker cp writes root-owned files, so the entrypoint starts as root for
445
534
  // exactly two commands — chown the copied-in trees, drop to the agent user —
446
535
  // and the run flags grant only the three capabilities those two commands
447
536
  // need. By the time any model-directed code executes, the process is uid
448
537
  // 10001 with no capabilities at all.
449
- const DOCKERFILE = `FROM node:22-slim
538
+ const CORE_INSTALL = `WORKDIR /opt/runner
539
+ COPY --from=core --chown=agent:agent /opt/runner/ ./
540
+ COPY --chown=agent:agent driver.mjs entry.sh ./
541
+ RUN mkdir -p /workspace /library /opt/runner/job ${RUNTIME_CACHE} ${SHARED_RUNTIMES} \\
542
+ && chown agent:agent /opt/runner \\
543
+ && chown -R agent:agent /workspace /library /opt/runner/job /home/agent/.foldrun /opt/foldrun-runtimes \\
544
+ && chmod +x /opt/runner/entry.sh
545
+ ENTRYPOINT ["/opt/runner/entry.sh"]
546
+ `;
547
+ /** The uv release copied into the image. Pinned: a floating uv is a floating
548
+ * resolver, and the runtime cache is keyed on the declaration, not on it. */
549
+ export const UV_VERSION = "0.11.25";
550
+ /** How many times a best-effort engine download is tried before the build
551
+ * gives up on it, and the wait before the second and third (15s, then 30s).
552
+ * A GitHub release or Google's apt mirror that blinks for a minute used to
553
+ * cost the engine outright; on x86_64 that now fails the build, so a
554
+ * transient blip would fail a deploy. */
555
+ export const ENGINE_DOWNLOAD_ATTEMPTS = 3;
556
+ /** `retry <engine> <command…>`: one shell function, defined at the top of each
557
+ * RUN that downloads an engine (a RUN is its own shell). Its lines start
558
+ * "runner image:" like every engine line, and go to stderr so a quiet
559
+ * install (>/dev/null) still shows them — the deploy greps them into the
560
+ * step summary (buildFailureSummary). */
561
+ export const RETRY_SH = `retry() { what=$1; shift; n=1; until "$@"; do if [ "$n" -ge ${ENGINE_DOWNLOAD_ATTEMPTS} ]; then echo "runner image: $what - download failed $n times, giving up" >&2; return 1; fi; echo "runner image: $what - download failed (attempt $n of ${ENGINE_DOWNLOAD_ATTEMPTS}), retrying in $((n * 15))s" >&2; sleep $((n * 15)); n=$((n + 1)); done; }`;
562
+ /** The base both targets start from, pinned by digest. The tag alone floats:
563
+ * `node:22-slim` is re-pushed for every Node patch and Debian point release,
564
+ * and will change Debian release when the Node image decides to, so the
565
+ * same runner tag — a hash of this text — could hold different bytes on two
566
+ * rebuilds. With the digest in the text, new base bytes mean a new tag.
567
+ *
568
+ * Debian 13 (trixie), not the 12 that `node:22-slim` still names: its glibc
569
+ * (2.41) runs Lightpanda past 0.3.6, which wants 2.38; Debian 12 has 2.36.
570
+ * Python is 3.13 here (3.11 on 12): runtime.ts checkEntry rebuilds a cached
571
+ * venv whose interpreter moved, once per declaration.
572
+ *
573
+ * Raise it on purpose (foldrun-infra/README.md, "Runner images"): read the
574
+ * current digest of the tag, put it here, build both targets on both arches
575
+ * and make one browse call per engine on the full image:
576
+ * docker buildx imagetools inspect node:22-trixie-slim --format '{{json .Manifest}}' | jq -r .digest
577
+ * The digest names the multi-arch index, so the one pin serves amd64 and
578
+ * arm64 alike. */
579
+ export const NODE_BASE = "node:22-trixie-slim@sha256:b26b04c123d9ff8ab646ceb18b9d75a1173acf64b9a401094b906d27b29338d4";
580
+ // Two images from one file, as build targets.
581
+ //
582
+ // full (the default, the last stage) — everything, browsers included. The
583
+ // per-account browser pod runs it, and so does any step that may
584
+ // browse, because the tool falls back to in-pod Chromium whenever
585
+ // the pod is unavailable or the run is a test.
586
+ // slim — the same base, core and Playwright *client*, no browsers. About
587
+ // a quarter of the size: the browsers were 1.4 GB of a 3.1 GB image
588
+ // that every step pulled and every step started, whether or not it
589
+ // ever opened a page. A step that grants no browsing runs this
590
+ // (run-k8s.ts picks), and its declared packages arrive at run time
591
+ // through the runtime cache — uv is in the base for exactly that.
592
+ //
593
+ // The browsers sit BELOW the core install in `full`, as they always have,
594
+ // so a core change rebuilds one thin layer and not 1.4 GB of Chromium.
595
+ export const DOCKERFILE = `FROM ${NODE_BASE} AS base
450
596
  RUN apt-get update \\
451
597
  && apt-get install -y --no-install-recommends python3 python3-venv ca-certificates bash util-linux tar openssh-client sshpass git curl \\
452
598
  && rm -rf /var/lib/apt/lists/* \\
453
599
  && useradd -m -u 10001 agent
600
+ # uv builds the declared python environments (runtime.ts): a fraction of
601
+ # pip's time, and it can fetch a pinned python the image does not carry.
602
+ COPY --from=ghcr.io/astral-sh/uv:${UV_VERSION} /uv /uvx /usr/local/bin/
603
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/browser NODE_PATH=/usr/local/lib/node_modules
604
+
605
+ ${CORE_STAGE}
606
+ FROM base AS slim
607
+ # Fonts, because a step that draws text without a browser still needs them:
608
+ # the full image gets 51 from Playwright's --with-deps, slim had none, so from
609
+ # 2026-09-29 (when non-browsing steps moved to slim) every resvg/sharp diagram
610
+ # rendered its labels as empty boxes — expert-witness-desk's validator failed
611
+ # four passes on a post image that was "three empty boxes". DejaVu covers
612
+ # Latin, Greek and Cyrillic in a few MB; fontconfig is how renderers find it.
613
+ # DejaVu alone still drew emoji, Chinese, Japanese, Korean, Devanagari and
614
+ # Thai as empty boxes (reproduced 2026-10-01 with resvg-js 2.6 and sharp
615
+ # 0.34), so four more, the smallest set that drew all of them — 8 MB:
616
+ # Symbola emoji and symbols, as outlines. NOT Noto Color Emoji (10 MB):
617
+ # resvg draws nothing from its bitmap glyphs, so a resvg
618
+ # diagram kept its empty boxes.
619
+ # WenQuanYi Micro Hei Chinese, Japanese kana and Korean Hangul, one file.
620
+ # Lohit Devanagari, Loma Hindi and Thai.
621
+ # Here, not in base, so the full image's browser layers stay cached.
622
+ RUN apt-get update \\
623
+ && apt-get install -y --no-install-recommends fonts-dejavu-core fontconfig fonts-symbola fonts-wqy-microhei fonts-lohit-deva fonts-tlwg-loma-otf \\
624
+ && rm -rf /var/lib/apt/lists/* \\
625
+ && fc-cache -f >/dev/null
626
+ # The Playwright client only, the same pinned version as the browser pod's
627
+ # server (the wire protocol is version-locked), so a tool that imports it
628
+ # still loads; there is nothing here for it to launch.
629
+ # npm's download cache is dropped in the same layer: it was 190 MB of every
630
+ # image, read by nothing after the build.
631
+ RUN npm install -g playwright@1.63.0 axe-core@4.13.0 >/dev/null && npm cache clean --force >/dev/null 2>&1
632
+ ${CORE_INSTALL}
633
+ FROM base AS browsers
454
634
  # Real browsers, because directories and portals increasingly render with
455
- # JavaScript and WebFetch sees only the empty shell. Chromium is the one the
635
+ # JavaScript and a plain fetch sees only the empty shell. Chromium is the one the
456
636
  # browser tool drives by default; Firefox and WebKit (Safari's engine) are
457
637
  # there for an agent asked to see a page the way those render it. Installed
458
638
  # to a fixed path the agent user can read (the default cache would be
459
639
  # root's HOME). The browsers' own sandboxes are disabled at launch time — in
460
640
  # this platform the container/gVisor IS the sandbox, and the two fight.
461
- ENV PLAYWRIGHT_BROWSERS_PATH=/opt/browser NODE_PATH=/usr/local/lib/node_modules
462
- RUN npm install -g playwright@1 >/dev/null \\
641
+ # Pinned exactly, not @1: web browse's numbered elements use ariaSnapshot's
642
+ # "ai" mode (1.59+), and the per-account browser pod runs this same image, so
643
+ # a floating version would move both under a working tool on any rebuild.
644
+ # Raise it on purpose, with the gallery tests and one real call.
645
+ # axe-core beside it is web browse's mode=a11y: one file the tool injects
646
+ # into the page; without it the mode falls back to its own shorter checks.
647
+ # Xvfb by name: the browser pod starts it at boot and web browse starts one
648
+ # per call for headless: false. It used to arrive only as one of Playwright's
649
+ # --with-deps packages, so a Playwright bump that dropped it would have
650
+ # broken every windowed browser without a word. No xauth: nothing here runs
651
+ # xvfb-run, and Xvfb started without -auth takes the local client as it is.
652
+ RUN apt-get update \\
653
+ && apt-get install -y --no-install-recommends xvfb \\
654
+ && rm -rf /var/lib/apt/lists/*
655
+ # Google Chrome and Chrome beta come from Google's apt repository, which
656
+ # Playwright adds; each is tried ENGINE_DOWNLOAD_ATTEMPTS times. Only on
657
+ # x86_64: Google ships no Linux Chrome for arm64, so there it is not tried.
658
+ RUN npm install -g playwright@1.63.0 axe-core@4.13.0 >/dev/null \\
463
659
  && playwright install --with-deps chromium firefox webkit >/dev/null \\
464
- && chmod -R a+rX /opt/browser
465
- WORKDIR /opt/runner
466
- COPY foldrun-core.tgz driver.mjs entry.sh ./
467
- RUN npm init -y >/dev/null && npm install ./foldrun-core.tgz --omit=dev \\
468
- && mkdir -p /workspace /library /opt/runner/job ${RUNTIME_CACHE} \\
469
- && chown -R agent:agent /workspace /library /opt/runner /home/agent/.foldrun \\
470
- && chmod +x /opt/runner/entry.sh
471
- ENTRYPOINT ["/opt/runner/entry.sh"]
472
- `;
660
+ && ${RETRY_SH} \\
661
+ && if [ "$(uname -m)" = x86_64 ]; then \\
662
+ retry chrome playwright install --with-deps chrome >/dev/null || echo "runner image: chrome not installed - engine: chrome would fall back to chromium" >&2; \\
663
+ retry chrome-beta playwright install --with-deps chrome-beta >/dev/null || echo "runner image: chrome-beta not installed" >&2; \\
664
+ else echo "runner image: no Google Chrome for $(uname -m) - engine: chrome falls back to chromium"; fi \\
665
+ && chmod -R a+rX /opt/browser \\
666
+ && npm cache clean --force >/dev/null 2>&1
667
+ # Lightpanda (engine: lightpanda): a browser that runs the JavaScript and
668
+ # never draws — a fraction of Chromium's memory for reading and filling
669
+ # pages. Its own program, which web browse starts beside a call and drives
670
+ # over the DevTools protocol; shipped unmodified (AGPL-3.0). Pinned by
671
+ # checksum (GitHub's own asset digests, checked again here). 0.4.1 since the
672
+ # move to Debian 13: 0.3.7 on wants glibc 2.38, and Debian 12's 2.36 held it
673
+ # at 0.3.6. An arch without a build leaves the engine out, and the tool says
674
+ # so when asked for it. Each download (with its checksum) is tried
675
+ # ENGINE_DOWNLOAD_ATTEMPTS times before the engine is left out.
676
+ # Raise it on purpose: the new release's two sha256s, then one
677
+ # engine=lightpanda call on each arch.
678
+ RUN arch=$(uname -m) \\
679
+ && case "$arch" in \\
680
+ x86_64) sum=1d40801e72c0bc61b2cbd3f3562bcfc46de7b79e0568f33f686b64f2e587610a ;; \\
681
+ aarch64) sum=664775c7f5ab69cc3189954c7f9345e25c167cb4dace016173e629f9a5e82c42 ;; \\
682
+ *) sum= ;; \\
683
+ esac \\
684
+ && mkdir -p /opt/browser/lightpanda \\
685
+ && ${RETRY_SH} \\
686
+ && fetch() { curl -fsSL -o /opt/browser/lightpanda/lightpanda "https://github.com/lightpanda-io/browser/releases/download/0.4.1/lightpanda-$arch-linux" \\
687
+ && echo "$sum /opt/browser/lightpanda/lightpanda" | sha256sum -c - >/dev/null; } \\
688
+ && if [ -n "$sum" ] && retry lightpanda fetch; then \\
689
+ chmod a+rx /opt/browser/lightpanda/lightpanda && /opt/browser/lightpanda/lightpanda version; \\
690
+ else rm -f /opt/browser/lightpanda/lightpanda; echo "runner image: lightpanda not installed for $arch - engine: lightpanda says so when asked" >&2; fi
691
+ # Obscura (engine: obscura): a headless browser in Rust around V8 that does
692
+ # draw — screenshots, a raster PDF, a screencast — light like Lightpanda.
693
+ # Apache-2.0. The plain build, not -stealth: this platform does not help a
694
+ # page not see automation. Two binaries, obscura and obscura-worker, which
695
+ # must sit side by side. Pinned by checksum; glibc 2.35 is its floor, so
696
+ # Debian 13 (2.41) runs it. As above, a download is tried
697
+ # ENGINE_DOWNLOAD_ATTEMPTS times, then a failed one leaves the engine out.
698
+ RUN arch=$(uname -m) \\
699
+ && case "$arch" in \\
700
+ x86_64) sum=1534d1e6ddaf3d080ec4091eb41d0a4d8cc042a48b607d3c410fc13b482a9eec ;; \\
701
+ aarch64) sum=5ecf980bca3060236a7a86ec7ed83d943e6598ee87caa46d20325d90bc75f979 ;; \\
702
+ *) sum= ;; \\
703
+ esac \\
704
+ && mkdir -p /opt/browser/obscura \\
705
+ && ${RETRY_SH} \\
706
+ && fetch() { curl -fsSL -o /tmp/obscura.tgz "https://github.com/h4ckf0r0day/obscura/releases/download/v0.2.3/obscura-$arch-linux.tar.gz" \\
707
+ && echo "$sum /tmp/obscura.tgz" | sha256sum -c - >/dev/null; } \\
708
+ && if [ -n "$sum" ] && retry obscura fetch \\
709
+ && tar -xzf /tmp/obscura.tgz -C /opt/browser/obscura obscura obscura-worker; then \\
710
+ chmod a+rx /opt/browser/obscura/obscura /opt/browser/obscura/obscura-worker && /opt/browser/obscura/obscura --version; \\
711
+ else rm -rf /opt/browser/obscura/*; echo "runner image: obscura not installed for $arch - engine: obscura says so when asked" >&2; fi \\
712
+ && rm -f /tmp/obscura.tgz
713
+ # What this image actually has, written down: /opt/browser/engines.json, one
714
+ # entry per engine (its path and version, or null when the install above
715
+ # left it out) plus Xvfb. Chromium's version is its own --version (dotted,
716
+ # so FOLDRUN_RUNNER_ENGINES carries it: a pinned user_agent on engine
717
+ # chromium is compared with it, not with Google Chrome's) then the build.
718
+ # web browse reads it for its "built without" answer, and the deploy reads
719
+ # it to report the engines beside the version.
720
+ # On x86_64 a missing engine FAILS the build: every engine ships for that
721
+ # arch, so a gap there is a failed download, and an image that quietly lacks
722
+ # the Chrome or Lightpanda a desk names would fail those runs instead. A
723
+ # failed build leaves the previous image running and says why. Elsewhere
724
+ # (arm64 has no Google Chrome) the gap is recorded and the image ships.
725
+ RUN node -e ' \\
726
+ const fs = require("fs"), cp = require("child_process"), pw = require("playwright"); \\
727
+ const at = (p) => (p && fs.existsSync(p) ? p : null); \\
728
+ const ver = (bin, args) => { try { return cp.execFileSync(bin, args, { timeout: 30000, stdio: ["ignore", "pipe", "ignore"] }).toString().trim().split("\\n")[0] || null; } catch { return null; } }; \\
729
+ const one = (p, v) => (p ? { path: p, version: v } : null); \\
730
+ const pwBuild = (p) => (p ? (p.match(/(chromium|firefox|webkit)-(\\d+)/) || [])[0] || null : null); \\
731
+ const lp = at("/opt/browser/lightpanda/lightpanda"); \\
732
+ const cr = at(pw.chromium.executablePath()); \\
733
+ const ob = at("/opt/browser/obscura/obscura-worker") && at("/opt/browser/obscura/obscura"); \\
734
+ const engines = { \\
735
+ chromium: one(cr, cr && [ver(cr, ["--version"]), pwBuild(cr)].filter(Boolean).join(" ")), \\
736
+ chrome: one(at("/opt/google/chrome/chrome"), ver("/opt/google/chrome/chrome", ["--version"])), \\
737
+ "chrome-beta": one(at("/opt/google/chrome-beta/chrome"), ver("/opt/google/chrome-beta/chrome", ["--version"])), \\
738
+ firefox: one(at(pw.firefox.executablePath()), pwBuild(pw.firefox.executablePath())), \\
739
+ webkit: one(at(pw.webkit.executablePath()), pwBuild(pw.webkit.executablePath())), \\
740
+ lightpanda: one(lp, lp && ver(lp, ["version"])), \\
741
+ obscura: one(ob, ob && ver(ob, ["--version"])), \\
742
+ }; \\
743
+ const xvfb = ver("sh", ["-c", "command -v Xvfb"]); \\
744
+ const arch = cp.execFileSync("uname", ["-m"]).toString().trim(); \\
745
+ const manifest = { arch, playwright: require("playwright/package.json").version, engines, xvfb }; \\
746
+ fs.writeFileSync("/opt/browser/engines.json", JSON.stringify(manifest, null, 2) + "\\n"); \\
747
+ console.log(JSON.stringify(manifest)); \\
748
+ const missing = ["chromium", "chrome", "firefox", "webkit", "lightpanda", "obscura"].filter((e) => !engines[e]).concat(xvfb ? [] : ["Xvfb"]); \\
749
+ if (missing.length && arch === "x86_64") { \\
750
+ console.error("runner image: MISSING ENGINES on x86_64: " + missing.join(", ")); \\
751
+ console.error("runner image: every engine ships for x86_64, so a missing one is a failed download (the retry lines above say which) - failing the build"); \\
752
+ process.exit(1); \\
753
+ } \\
754
+ if (missing.length) console.error("runner image: built without " + missing.join(", ") + " on " + arch); \\
755
+ ' \\
756
+ && chmod a+r /opt/browser/engines.json
757
+
758
+ FROM browsers AS full
759
+ ${CORE_INSTALL}`;
473
760
  const ENTRY = `#!/bin/sh
474
761
  set -e
475
762
  chown -R agent:agent /workspace /library /opt/runner/job
@@ -499,7 +786,7 @@ function corePackageDir() {
499
786
  }
500
787
  throw new Error("could not locate @foldrun/core's package root");
501
788
  }
502
- export function runnerImageTag() {
789
+ export function runnerImageTag(variant = "full") {
503
790
  // The fingerprint hashes the *built code*, not the version — a version
504
791
  // string that nobody bumped would pin every future run to the runner
505
792
  // image of whatever core happened to build first.
@@ -512,7 +799,7 @@ export function runnerImageTag() {
512
799
  hash.update(String(entry)).update(fs.readFileSync(abs));
513
800
  }
514
801
  }
515
- return `foldrun-runner:${hash.digest("hex").slice(0, 12)}`;
802
+ return `foldrun-runner:${hash.digest("hex").slice(0, 12)}${variant === "slim" ? "-slim" : ""}`;
516
803
  }
517
804
  /**
518
805
  * Build the runner image if this exact (core version, driver, dockerfile)
@@ -527,11 +814,27 @@ export function runnerImageTag() {
527
814
  * (tonistiigi/binfmt); the publisher does that itself, every time, because
528
815
  * the registration does not survive a reboot.
529
816
  */
530
- export function ensureRunnerImage(opts = {}) {
817
+ /**
818
+ * Which image a step runs in: an explicit FOLDRUN_RUNNER_IMAGE when one is
819
+ * set, otherwise the content-hash tag core builds itself. `explicit` is what
820
+ * ensureRunnerImage checks to skip the build — an empty string is *not* an
821
+ * image name (it is `docker build -t ""` → "repository name must have at
822
+ * least one component"), so it falls through to the content-hash tag exactly
823
+ * as an unset value does. Pure, so the resolution is testable without docker.
824
+ */
825
+ export function runnerImageRef(opts = {}) {
826
+ // Each variant has its own override: FOLDRUN_RUNNER_IMAGE names the full
827
+ // image as it always has, FOLDRUN_RUNNER_SLIM_IMAGE the slim one.
828
+ const set = opts.variant === "slim" ? process.env.FOLDRUN_RUNNER_SLIM_IMAGE : process.env.FOLDRUN_RUNNER_IMAGE;
829
+ if (set)
830
+ return { tag: set, explicit: true };
531
831
  const arch = opts.platform ? `-${opts.platform.split("/").pop()}` : "";
532
- const tag = process.env.FOLDRUN_RUNNER_IMAGE ?? runnerImageTag() + arch;
832
+ return { tag: runnerImageTag(opts.variant) + arch, explicit: false };
833
+ }
834
+ export function ensureRunnerImage(opts = {}) {
835
+ const { tag, explicit } = runnerImageRef(opts);
533
836
  const log = [];
534
- if (process.env.FOLDRUN_RUNNER_IMAGE)
837
+ if (explicit)
535
838
  return { tag, log };
536
839
  const have = spawnSync(cli(), ["image", "inspect", tag], { stdio: "ignore" });
537
840
  if (have.status === 0)
@@ -549,10 +852,26 @@ export function ensureRunnerImage(opts = {}) {
549
852
  fs.writeFileSync(path.join(build, "entry.sh"), ENTRY);
550
853
  fs.writeFileSync(path.join(build, "Dockerfile"), DOCKERFILE);
551
854
  log.push(`building runner image ${tag} (first run only)`);
552
- const args = ["build", ...(opts.platform ? ["--platform", opts.platform] : []), "-t", tag, build];
855
+ const args = [
856
+ "build",
857
+ ...(opts.platform ? ["--platform", opts.platform] : []),
858
+ "--target",
859
+ opts.variant ?? "full",
860
+ "-t",
861
+ tag,
862
+ build,
863
+ ];
553
864
  const out = spawnSync(cli(), args, { encoding: "utf8" });
554
865
  if (out.status !== 0) {
555
- throw new Error(`runner image build failed:\n${(out.stderr || out.stdout).slice(-2000)}`);
866
+ const full = `${out.stdout ?? ""}\n${out.stderr ?? ""}`;
867
+ // The whole log beside the summary, for a person on the build machine:
868
+ // the error names the file; the summary is what CI shows.
869
+ const logFile = path.join(os.tmpdir(), "foldrun-runner-build.log");
870
+ try {
871
+ fs.writeFileSync(logFile, full);
872
+ }
873
+ catch { /* the summary still says what failed */ }
874
+ throw new Error(`runner image build failed (full log: ${logFile}):\n${buildFailureSummary(full)}`);
556
875
  }
557
876
  return { tag, log };
558
877
  }
@@ -560,6 +879,39 @@ export function ensureRunnerImage(opts = {}) {
560
879
  fs.rmSync(build, { recursive: true, force: true });
561
880
  }
562
881
  }
882
+ /**
883
+ * What a failed runner build's error says: the lines that name the failure,
884
+ * then the end of the log. Only the last 2000 characters used to survive,
885
+ * and BuildKit ends a failed RUN by echoing the instruction — the engines
886
+ * probe is a long one — so "chrome missing" scrolled out of the very error
887
+ * that existed to say it. Every engine line the DOCKERFILE prints starts
888
+ * "runner image:" (the retries, the giving up, the MISSING ENGINES line);
889
+ * those are kept, from anywhere in the log, with BuildKit's "#12 3.456 "
890
+ * prefix taken off, and so are BuildKit's own ERROR lines (each cut short:
891
+ * they quote the whole instruction). Pure, so it is tested on fixtures.
892
+ */
893
+ export function buildFailureSummary(log, opts = {}) {
894
+ const tail = opts.tail ?? 1500;
895
+ const maxLines = opts.maxLines ?? 40;
896
+ const seen = new Set();
897
+ const key = [];
898
+ for (const raw of log.split("\n")) {
899
+ const line = raw.replace(/^#\d+ \d+(\.\d+)? /, "").trim();
900
+ if (!/^runner image:|^ERROR\b|^error:/i.test(line) && !/did not complete successfully/.test(line))
901
+ continue;
902
+ const cut = line.length > 300 ? line.slice(0, 300) + " …" : line;
903
+ if (seen.has(cut))
904
+ continue;
905
+ seen.add(cut);
906
+ key.push(cut);
907
+ }
908
+ // The ones that say what is missing first: a reader stops at the top.
909
+ key.sort((a, b) => Number(/MISSING ENGINES/.test(b)) - Number(/MISSING ENGINES/.test(a)));
910
+ const head = key.length
911
+ ? key.slice(0, maxLines).map((l) => ` ${l}`).join("\n") + (key.length > maxLines ? `\n … ${key.length - maxLines} more` : "")
912
+ : " (no engine or ERROR line in the log)";
913
+ return `${head}\n--- the last ${tail} characters of the build log ---\n${log.slice(-tail)}`;
914
+ }
563
915
  // ---------- running one step ----------
564
916
  export function parseDriverLine(line) {
565
917
  const trimmed = line.trim();
@@ -575,6 +927,9 @@ export function parseDriverLine(line) {
575
927
  ...(typeof parsed.call === "string" ? { call: parsed.call } : {}),
576
928
  ...(typeof parsed.ms === "number" ? { ms: parsed.ms } : {}),
577
929
  ...(parsed.err === true ? { err: true } : {}),
930
+ ...(isOperatorEvent(parsed.operator) ? { operator: parsed.operator } : {}),
931
+ ...(typeof parsed.subagent === "string" && /^[a-z0-9-]{1,64}$/.test(parsed.subagent) ? { subagent: parsed.subagent } : {}),
932
+ ...(parsed.check === true ? { check: true } : {}),
578
933
  };
579
934
  }
580
935
  if (parsed.e === "done") {
@@ -585,6 +940,8 @@ export function parseDriverLine(line) {
585
940
  conclusion: typeof parsed.conclusion === "string" ? parsed.conclusion : null,
586
941
  ...("data" in parsed ? { data: parsed.data } : {}),
587
942
  costUsd: typeof parsed.costUsd === "number" ? parsed.costUsd : null,
943
+ ...(typeof parsed.turnsCostUsd === "number" ? { turnsCostUsd: parsed.turnsCostUsd } : {}),
944
+ ...(parseBrowserPod(parsed.browserPod) ? { browserPod: parseBrowserPod(parsed.browserPod) } : {}),
588
945
  usage: parsed.usage &&
589
946
  typeof parsed.usage.inputTokens === "number" &&
590
947
  typeof parsed.usage.outputTokens === "number"
@@ -750,8 +1107,19 @@ export async function runStepInContainer(args) {
750
1107
  const wsIn = path.join(staging, "workspace");
751
1108
  fs.cpSync(args.workspaceRoot, wsIn, {
752
1109
  recursive: true,
1110
+ // Times too: a verify that asks "was this written in the last hour?"
1111
+ // is asking about the step, and a copy stamped "now" answers yes for a
1112
+ // file untouched since last week (see mtimeManifest).
1113
+ preserveTimestamps: true,
753
1114
  filter: (src) => !isPlatformPath(path.relative(args.workspaceRoot, src)),
754
1115
  });
1116
+ // A test run: what its earlier steps wrote, over the real files (the
1117
+ // copy is the baseline too, so only this step's own writes come back).
1118
+ if (args.divert) {
1119
+ const laid = overlayTestWrites(wsIn, args.divert.to);
1120
+ if (laid.length)
1121
+ args.emit("info", `test: this step sees ${laid.length} file${laid.length === 1 ? "" : "s"} earlier steps of this run wrote`);
1122
+ }
755
1123
  const libIn = path.join(staging, "library");
756
1124
  if (args.galleryRoot && fs.existsSync(args.galleryRoot))
757
1125
  fs.cpSync(args.galleryRoot, libIn, { recursive: true });
@@ -791,14 +1159,27 @@ export async function runStepInContainer(args) {
791
1159
  // Docker Desktop. The run bridge has inter-container traffic off; the
792
1160
  // host itself stays reachable, which is the one door this needs.
793
1161
  flags.push("--add-host", "host.docker.internal:host-gateway");
794
- // The dependency cache: this tenant's built venvs and npm prefixes,
795
- // mounted where prepareRuntime already looks. Created host-side rather
796
- // than left to the daemon so it belongs to the platform user; the
797
- // entrypoint hands the mount point itself to the agent user.
798
- const cacheDir = runtimeCacheDir(args.tenant);
799
- if (cacheDir) {
800
- fs.mkdirSync(cacheDir, { recursive: true });
801
- flags.push("-v", `${cacheDir}:${RUNTIME_CACHE}`);
1162
+ // The dependency cache: this tenant's built venvs and npm prefixes, in a
1163
+ // per-tenant Docker named volume mounted where prepareRuntime already looks.
1164
+ // Not a host path — the daemon on the far end of the socket cannot resolve
1165
+ // the platform's FOLDRUN_DATA (runtimeCacheMount explains).
1166
+ const cacheMount = runtimeCacheMount(args.tenant);
1167
+ if (cacheMount) {
1168
+ // Create the volume WITH labels first: `docker create -v` auto-creates it
1169
+ // but cannot label it, and an unlabelled volume is unfindable and
1170
+ // unprunable later. Idempotent — a no-op when it already exists. The
1171
+ // segment is the one runtimeCacheMount already validated, so the
1172
+ // assertions below cannot fire when cacheMount is non-null.
1173
+ const seg = safeTenantSegment(args.tenant);
1174
+ const vol = spawnSync(cli(), [
1175
+ "volume", "create",
1176
+ "--label", "foldrun.io/kind=runtime-cache",
1177
+ "--label", `foldrun.io/tenant=${seg}`,
1178
+ cacheMount.source,
1179
+ ], { encoding: "utf8" });
1180
+ if (vol.status !== 0)
1181
+ throw new Error(`docker volume create failed:\n${vol.stderr}`);
1182
+ flags.push("-v", `${cacheMount.source}:${cacheMount.target}`);
802
1183
  }
803
1184
  // The rent clock starts here: staging the workspace is host work, but
804
1185
  // from `create` to `rm` the sandbox is a resource the platform pays for.