@foldrun/core 15.0.0 → 16.0.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 (63) hide show
  1. package/dist/src/a2a-publish.d.ts +7 -0
  2. package/dist/src/a2a-publish.js +15 -1
  3. package/dist/src/a2a-reach.d.ts +156 -0
  4. package/dist/src/a2a-reach.js +446 -0
  5. package/dist/src/browse-egress.d.ts +1 -1
  6. package/dist/src/browse-egress.js +7 -6
  7. package/dist/src/capture.js +2 -1
  8. package/dist/src/env-names.d.ts +12 -0
  9. package/dist/src/env-names.js +49 -0
  10. package/dist/src/failure.d.ts +92 -0
  11. package/dist/src/failure.js +294 -0
  12. package/dist/src/frontmatter-fields.js +1 -1
  13. package/dist/src/install-helper.js +10 -5
  14. package/dist/src/mail.js +2 -1
  15. package/dist/src/network.js +1 -1
  16. package/dist/src/notify.js +12 -7
  17. package/dist/src/ops-log.d.ts +55 -0
  18. package/dist/src/ops-log.js +393 -0
  19. package/dist/src/otel.d.ts +16 -1
  20. package/dist/src/otel.js +121 -5
  21. package/dist/src/run-container.d.ts +55 -3
  22. package/dist/src/run-container.js +109 -17
  23. package/dist/src/run-event.d.ts +179 -0
  24. package/dist/src/run-event.js +473 -0
  25. package/dist/src/runner.js +14 -5
  26. package/dist/src/runtime.d.ts +113 -16
  27. package/dist/src/runtime.js +528 -44
  28. package/dist/src/scan.js +80 -18
  29. package/dist/src/secrets.js +4 -3
  30. package/dist/src/starter.js +1 -1
  31. package/dist/src/step-exec.d.ts +4 -2
  32. package/dist/src/step-exec.js +10 -4
  33. package/dist/src/storage.js +2 -1
  34. package/dist/src/store.d.ts +25 -3
  35. package/dist/src/store.js +40 -10
  36. package/dist/src/triggers.js +6 -5
  37. package/dist/src/webhook.js +3 -2
  38. package/package.json +2 -1
  39. package/src/a2a-publish.ts +19 -1
  40. package/src/a2a-reach.ts +503 -0
  41. package/src/browse-egress.ts +8 -7
  42. package/src/capture.ts +2 -1
  43. package/src/env-names.ts +53 -0
  44. package/src/failure.ts +368 -0
  45. package/src/frontmatter-fields.ts +1 -1
  46. package/src/install-helper.ts +10 -5
  47. package/src/mail.ts +2 -1
  48. package/src/network.ts +1 -1
  49. package/src/notify.ts +12 -9
  50. package/src/ops-log.ts +403 -0
  51. package/src/otel.ts +122 -7
  52. package/src/run-container.ts +112 -21
  53. package/src/run-event.ts +563 -0
  54. package/src/runner.ts +14 -5
  55. package/src/runtime.ts +543 -45
  56. package/src/scan.ts +91 -20
  57. package/src/secrets.ts +4 -5
  58. package/src/starter.ts +1 -1
  59. package/src/step-exec.ts +10 -4
  60. package/src/storage.ts +2 -1
  61. package/src/store.ts +59 -11
  62. package/src/triggers.ts +6 -5
  63. package/src/webhook.ts +3 -2
@@ -131,6 +131,10 @@ export interface StepTiming {
131
131
  * from an executor that marks none, and from a resumed driver (the
132
132
  * first driver's phases are on the record already). */
133
133
  phases?: StartupPhases;
134
+ /** When the phases count from: the epoch ms the executor began the step
135
+ * (FOL-122) — what places them on the clock (StepRecord.startupAt). Set
136
+ * beside `phases` only. */
137
+ origin?: number;
134
138
  }
135
139
  /** The start-up phases and what each marks — startup.ts, where every
136
140
  * surface that shows them reads them from (FOL-74). */
@@ -293,8 +297,52 @@ export declare const RUNTIME_CACHE = "/home/agent/.foldrun/runner/.runtimes";
293
297
  /** Starts the install helper as root, in the background, before the drop to
294
298
  * the agent user: the root half of the `install` tool (install-helper.ts).
295
299
  * The agent reaches it only through the socket; it installs only validated
296
- * Debian package names, and dies with the container. */
300
+ * Debian package names, and dies with the container.
301
+ * @deprecated the start-ups use rootStartSh, which starts the helper in a
302
+ * clean environment with the snapshot key's path (FOL-129). */
297
303
  export declare const INSTALL_HELPER_SH = "FOLDRUN_INSTALL_SOCKET=/opt/runner/job/install.sock; export FOLDRUN_INSTALL_SOCKET\nnode /opt/runner/node_modules/@foldrun/core/dist/src/install-helper.js \"$FOLDRUN_INSTALL_SOCKET\" /home/agent/.foldrun/runner/.runtimes >/dev/null 2>&1 &";
304
+ /**
305
+ * The account's key for sealing its `runtime: system:` snapshots (FOL-129):
306
+ * derived from the install key, so it needs no store and no rotation of its
307
+ * own, and per account, so one account's key seals nothing for another. The
308
+ * worker stages it as the step's SNAPSHOT_KEY_FILE; null (no tenant, or a
309
+ * process without the install key) means the step gets no snapshots.
310
+ */
311
+ export declare function aptSnapshotKey(tenant: string | undefined | null): string | null;
312
+ /**
313
+ * Root's part of a run container's start-up, before the chown and the drop
314
+ * to the agent user (k8s SHIM, docker ENTRY): the snapshot key moved where
315
+ * only root can read it, then — in a subshell whose environment is the root
316
+ * shell's own plus the proxy's variables (ROOT_ENV_FILE), reset to those
317
+ * alone (ROOT_ENV_RESET_SH) — the declared system packages and the install
318
+ * helper. The key never enters an environment: root's commands and the
319
+ * helper get only its path, and the copy in the job folder (which is chowned
320
+ * to the agent next) is gone before the subshell ends, or the start-up stops.
321
+ *
322
+ * The step's own environment (STEP_ENV_FILE) is never read here (FOL-130):
323
+ * its names are the account's to choose, and an LD_PRELOAD or PATH there
324
+ * pointing into the agent-writable cache would run the agent's code as root.
325
+ * ROOT_ENV_FILE is the worker's cut of it to ROOT_ENV_NAMES, sourced before
326
+ * the reset so even a name that should not be there is unset again; the
327
+ * socket and the locale are set after it, so nothing read can move them.
328
+ */
329
+ export declare function rootStartSh(cacheDir?: string): string;
330
+ /**
331
+ * The drop to the agent user, and the only place the step's environment is
332
+ * read (FOL-130): runuser starts with the root shell's own environment — the
333
+ * image's and the pod spec's, which ROOT_SHELL_GUARD_SH has already cleaned —
334
+ * and the agent's shell then sources STEP_ENV_FILE, sets up the egress
335
+ * proxy's CA (which root never needs: apt goes through the proxy unopened),
336
+ * and execs `command`, so its exit status is the step's.
337
+ *
338
+ * What the agent ends with is what it had when root sourced the file before
339
+ * the drop: the step's names over the root shell's, the CA's variables over
340
+ * those, runuser's HOME/USER/LOGNAME over all (kept in positional
341
+ * parameters, which no sourced name can reach), and the install socket at
342
+ * its fixed path. No `set -e`: an egress CA that cannot be written leaves
343
+ * the step without it, as before, rather than stopping it.
344
+ */
345
+ export declare function agentStartSh(command?: string): string;
298
346
  /**
299
347
  * Where the platform's shared runtime layer is mounted, read-only, in a run
300
348
  * pod — and read-write, one entry at a time, in the pod that builds an entry
@@ -371,6 +419,8 @@ export declare const RETRY_SH = "retry() { what=$1; shift; n=1; until \"$@\"; do
371
419
  * RCE, TLS hostname bypasses); the pin before carried 22.23.3. */
372
420
  export declare const NODE_BASE = "node:22-trixie-slim@sha256:8eb619e402eaede1748a3c8173bffab391592812e85136452f781741c7242ddf";
373
421
  export declare const DOCKERFILE = "FROM node:22-trixie-slim@sha256:8eb619e402eaede1748a3c8173bffab391592812e85136452f781741c7242ddf AS base\nRUN apt-get update \\\n && apt-get install -y --no-install-recommends python3 python3-venv ca-certificates bash util-linux tar openssh-client sshpass git curl \\\n && rm -rf /var/lib/apt/lists/* \\\n && useradd -m -u 10001 agent\n# uv builds the declared python environments (runtime.ts): a fraction of\n# pip's time, and it can fetch a pinned python the image does not carry.\nCOPY --from=ghcr.io/astral-sh/uv:0.11.25 /uv /uvx /usr/local/bin/\nENV PLAYWRIGHT_BROWSERS_PATH=/opt/browser NODE_PATH=/usr/local/lib/node_modules\n\nFROM base AS core\nWORKDIR /opt/runner\nCOPY foldrun-core.tgz ./\nRUN npm init -y >/dev/null && npm install ./foldrun-core.tgz --omit=dev \\\n && npm cache clean --force >/dev/null 2>&1 \\\n && rm -f foldrun-core.tgz node_modules/@foldrun/core/README.md\n\nFROM base AS slim\n# Fonts, because a step that draws text without a browser still needs them:\n# the full image gets 51 from Playwright's --with-deps, slim had none, so from\n# 2026-09-29 (when non-browsing steps moved to slim) every resvg/sharp diagram\n# rendered its labels as empty boxes \u2014 expert-witness-desk's validator failed\n# four passes on a post image that was \"three empty boxes\". DejaVu covers\n# Latin, Greek and Cyrillic in a few MB; fontconfig is how renderers find it.\n# DejaVu alone still drew emoji, Chinese, Japanese, Korean, Devanagari and\n# Thai as empty boxes (reproduced 2026-10-01 with resvg-js 2.6 and sharp\n# 0.34), so four more, the smallest set that drew all of them \u2014 8 MB:\n# Symbola emoji and symbols, as outlines. NOT Noto Color Emoji (10 MB):\n# resvg draws nothing from its bitmap glyphs, so a resvg\n# diagram kept its empty boxes.\n# WenQuanYi Micro Hei Chinese, Japanese kana and Korean Hangul, one file.\n# Lohit Devanagari, Loma Hindi and Thai.\n# Here, not in base, so the full image's browser layers stay cached.\nRUN apt-get update \\\n && apt-get install -y --no-install-recommends fonts-dejavu-core fontconfig fonts-symbola fonts-wqy-microhei fonts-lohit-deva fonts-tlwg-loma-otf \\\n && rm -rf /var/lib/apt/lists/* \\\n && fc-cache -f >/dev/null\n# The Playwright client only, the same pinned version as the browser pod's\n# server (the wire protocol is version-locked), so a tool that imports it\n# still loads; there is nothing here for it to launch.\n# npm's download cache is dropped in the same layer: it was 190 MB of every\n# image, read by nothing after the build.\nRUN npm install -g playwright@1.63.0 axe-core@4.13.0 >/dev/null && npm cache clean --force >/dev/null 2>&1\nWORKDIR /opt/runner\nCOPY --from=core --chown=agent:agent /opt/runner/ ./\nCOPY --chown=agent:agent driver.mjs entry.sh ./\nRUN mkdir -p /workspace /library /opt/runner/job /home/agent/.foldrun/runner/.runtimes /opt/foldrun-runtimes/shared/.runtimes \\\n && chown agent:agent /opt/runner \\\n && chown -R agent:agent /workspace /library /opt/runner/job /home/agent/.foldrun /opt/foldrun-runtimes \\\n && chmod +x /opt/runner/entry.sh\nENTRYPOINT [\"/opt/runner/entry.sh\"]\n\nFROM base AS browsers\n# Real browsers, because directories and portals increasingly render with\n# JavaScript and a plain fetch sees only the empty shell. Chromium is the one the\n# browser tool drives by default; Firefox and WebKit (Safari's engine) are\n# there for an agent asked to see a page the way those render it. Installed\n# to a fixed path the agent user can read (the default cache would be\n# root's HOME). The browsers' own sandboxes are disabled at launch time \u2014 in\n# this platform the container/gVisor IS the sandbox, and the two fight.\n# Pinned exactly, not @1: web browse's numbered elements use ariaSnapshot's\n# \"ai\" mode (1.59+), and the per-account browser pod runs this same image, so\n# a floating version would move both under a working tool on any rebuild.\n# Raise it on purpose, with the gallery tests and one real call.\n# axe-core beside it is web browse's mode=a11y: one file the tool injects\n# into the page; without it the mode falls back to its own shorter checks.\n# Xvfb by name: the browser pod starts it at boot and web browse starts one\n# per call for headless: false. It used to arrive only as one of Playwright's\n# --with-deps packages, so a Playwright bump that dropped it would have\n# broken every windowed browser without a word. No xauth: nothing here runs\n# xvfb-run, and Xvfb started without -auth takes the local client as it is.\nRUN apt-get update \\\n && apt-get install -y --no-install-recommends xvfb \\\n && rm -rf /var/lib/apt/lists/*\n# Google Chrome and Chrome beta come from Google's apt repository, which\n# Playwright adds; each is tried ENGINE_DOWNLOAD_ATTEMPTS times. Only on\n# x86_64: Google ships no Linux Chrome for arm64, so there it is not tried.\nRUN npm install -g playwright@1.63.0 axe-core@4.13.0 >/dev/null \\\n && playwright install --with-deps chromium firefox webkit >/dev/null \\\n && retry() { what=$1; shift; n=1; until \"$@\"; do if [ \"$n\" -ge 3 ]; then echo \"runner image: $what - download failed $n times, giving up\" >&2; return 1; fi; echo \"runner image: $what - download failed (attempt $n of 3), retrying in $((n * 15))s\" >&2; sleep $((n * 15)); n=$((n + 1)); done; } \\\n && if [ \"$(uname -m)\" = x86_64 ]; then \\\n retry chrome playwright install --with-deps chrome >/dev/null || echo \"runner image: chrome not installed - engine: chrome would fall back to chromium\" >&2; \\\n retry chrome-beta playwright install --with-deps chrome-beta >/dev/null || echo \"runner image: chrome-beta not installed\" >&2; \\\n else echo \"runner image: no Google Chrome for $(uname -m) - engine: chrome falls back to chromium\"; fi \\\n && chmod -R a+rX /opt/browser \\\n && npm cache clean --force >/dev/null 2>&1\n# Lightpanda (engine: lightpanda): a browser that runs the JavaScript and\n# never draws \u2014 a fraction of Chromium's memory for reading and filling\n# pages. Its own program, which web browse starts beside a call and drives\n# over the DevTools protocol; shipped unmodified (AGPL-3.0). Pinned by\n# checksum (GitHub's own asset digests, checked again here). 0.4.1 since the\n# move to Debian 13: 0.3.7 on wants glibc 2.38, and Debian 12's 2.36 held it\n# at 0.3.6. An arch without a build leaves the engine out, and the tool says\n# so when asked for it. Each download (with its checksum) is tried\n# ENGINE_DOWNLOAD_ATTEMPTS times before the engine is left out.\n# Raise it on purpose: the new release's two sha256s, then one\n# engine=lightpanda call on each arch.\nRUN arch=$(uname -m) \\\n && case \"$arch\" in \\\n x86_64) sum=1d40801e72c0bc61b2cbd3f3562bcfc46de7b79e0568f33f686b64f2e587610a ;; \\\n aarch64) sum=664775c7f5ab69cc3189954c7f9345e25c167cb4dace016173e629f9a5e82c42 ;; \\\n *) sum= ;; \\\n esac \\\n && mkdir -p /opt/browser/lightpanda \\\n && retry() { what=$1; shift; n=1; until \"$@\"; do if [ \"$n\" -ge 3 ]; then echo \"runner image: $what - download failed $n times, giving up\" >&2; return 1; fi; echo \"runner image: $what - download failed (attempt $n of 3), retrying in $((n * 15))s\" >&2; sleep $((n * 15)); n=$((n + 1)); done; } \\\n && fetch() { curl -fsSL -o /opt/browser/lightpanda/lightpanda \"https://github.com/lightpanda-io/browser/releases/download/0.4.1/lightpanda-$arch-linux\" \\\n && echo \"$sum /opt/browser/lightpanda/lightpanda\" | sha256sum -c - >/dev/null; } \\\n && if [ -n \"$sum\" ] && retry lightpanda fetch; then \\\n chmod a+rx /opt/browser/lightpanda/lightpanda && /opt/browser/lightpanda/lightpanda version; \\\n else rm -f /opt/browser/lightpanda/lightpanda; echo \"runner image: lightpanda not installed for $arch - engine: lightpanda says so when asked\" >&2; fi\n# Obscura (engine: obscura): a headless browser in Rust around V8 that does\n# draw \u2014 screenshots, a raster PDF, a screencast \u2014 light like Lightpanda.\n# Apache-2.0. The plain build, not -stealth: this platform does not help a\n# page not see automation. Two binaries, obscura and obscura-worker, which\n# must sit side by side. Pinned by checksum; glibc 2.35 is its floor, so\n# Debian 13 (2.41) runs it. As above, a download is tried\n# ENGINE_DOWNLOAD_ATTEMPTS times, then a failed one leaves the engine out.\nRUN arch=$(uname -m) \\\n && case \"$arch\" in \\\n x86_64) sum=1534d1e6ddaf3d080ec4091eb41d0a4d8cc042a48b607d3c410fc13b482a9eec ;; \\\n aarch64) sum=5ecf980bca3060236a7a86ec7ed83d943e6598ee87caa46d20325d90bc75f979 ;; \\\n *) sum= ;; \\\n esac \\\n && mkdir -p /opt/browser/obscura \\\n && retry() { what=$1; shift; n=1; until \"$@\"; do if [ \"$n\" -ge 3 ]; then echo \"runner image: $what - download failed $n times, giving up\" >&2; return 1; fi; echo \"runner image: $what - download failed (attempt $n of 3), retrying in $((n * 15))s\" >&2; sleep $((n * 15)); n=$((n + 1)); done; } \\\n && fetch() { curl -fsSL -o /tmp/obscura.tgz \"https://github.com/h4ckf0r0day/obscura/releases/download/v0.2.3/obscura-$arch-linux.tar.gz\" \\\n && echo \"$sum /tmp/obscura.tgz\" | sha256sum -c - >/dev/null; } \\\n && if [ -n \"$sum\" ] && retry obscura fetch \\\n && tar -xzf /tmp/obscura.tgz -C /opt/browser/obscura obscura obscura-worker; then \\\n chmod a+rx /opt/browser/obscura/obscura /opt/browser/obscura/obscura-worker && /opt/browser/obscura/obscura --version; \\\n else rm -rf /opt/browser/obscura/*; echo \"runner image: obscura not installed for $arch - engine: obscura says so when asked\" >&2; fi \\\n && rm -f /tmp/obscura.tgz\n# What this image actually has, written down: /opt/browser/engines.json, one\n# entry per engine (its path and version, or null when the install above\n# left it out) plus Xvfb. Chromium's version is its own --version (dotted,\n# so FOLDRUN_RUNNER_ENGINES carries it: a pinned user_agent on engine\n# chromium is compared with it, not with Google Chrome's) then the build.\n# web browse reads it for its \"built without\" answer, and the deploy reads\n# it to report the engines beside the version.\n# On x86_64 a missing engine FAILS the build: every engine ships for that\n# arch, so a gap there is a failed download, and an image that quietly lacks\n# the Chrome or Lightpanda a desk names would fail those runs instead. A\n# failed build leaves the previous image running and says why. Elsewhere\n# (arm64 has no Google Chrome) the gap is recorded and the image ships.\nRUN node -e ' \\\n const fs = require(\"fs\"), cp = require(\"child_process\"), pw = require(\"playwright\"); \\\n const at = (p) => (p && fs.existsSync(p) ? p : null); \\\n 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; } }; \\\n const one = (p, v) => (p ? { path: p, version: v } : null); \\\n const pwBuild = (p) => (p ? (p.match(/(chromium|firefox|webkit)-(\\d+)/) || [])[0] || null : null); \\\n const lp = at(\"/opt/browser/lightpanda/lightpanda\"); \\\n const cr = at(pw.chromium.executablePath()); \\\n const ob = at(\"/opt/browser/obscura/obscura-worker\") && at(\"/opt/browser/obscura/obscura\"); \\\n const engines = { \\\n chromium: one(cr, cr && [ver(cr, [\"--version\"]), pwBuild(cr)].filter(Boolean).join(\" \")), \\\n chrome: one(at(\"/opt/google/chrome/chrome\"), ver(\"/opt/google/chrome/chrome\", [\"--version\"])), \\\n \"chrome-beta\": one(at(\"/opt/google/chrome-beta/chrome\"), ver(\"/opt/google/chrome-beta/chrome\", [\"--version\"])), \\\n firefox: one(at(pw.firefox.executablePath()), pwBuild(pw.firefox.executablePath())), \\\n webkit: one(at(pw.webkit.executablePath()), pwBuild(pw.webkit.executablePath())), \\\n lightpanda: one(lp, lp && ver(lp, [\"version\"])), \\\n obscura: one(ob, ob && ver(ob, [\"--version\"])), \\\n }; \\\n const xvfb = ver(\"sh\", [\"-c\", \"command -v Xvfb\"]); \\\n const arch = cp.execFileSync(\"uname\", [\"-m\"]).toString().trim(); \\\n const manifest = { arch, playwright: require(\"playwright/package.json\").version, engines, xvfb }; \\\n fs.writeFileSync(\"/opt/browser/engines.json\", JSON.stringify(manifest, null, 2) + \"\\n\"); \\\n console.log(JSON.stringify(manifest)); \\\n const missing = [\"chromium\", \"chrome\", \"firefox\", \"webkit\", \"lightpanda\", \"obscura\"].filter((e) => !engines[e]).concat(xvfb ? [] : [\"Xvfb\"]); \\\n if (missing.length && arch === \"x86_64\") { \\\n console.error(\"runner image: MISSING ENGINES on x86_64: \" + missing.join(\", \")); \\\n 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\"); \\\n process.exit(1); \\\n } \\\n if (missing.length) console.error(\"runner image: built without \" + missing.join(\", \") + \" on \" + arch); \\\n ' \\\n && chmod a+r /opt/browser/engines.json\n\nFROM browsers AS full\nWORKDIR /opt/runner\nCOPY --from=core --chown=agent:agent /opt/runner/ ./\nCOPY --chown=agent:agent driver.mjs entry.sh ./\nRUN mkdir -p /workspace /library /opt/runner/job /home/agent/.foldrun/runner/.runtimes /opt/foldrun-runtimes/shared/.runtimes \\\n && chown agent:agent /opt/runner \\\n && chown -R agent:agent /workspace /library /opt/runner/job /home/agent/.foldrun /opt/foldrun-runtimes \\\n && chmod +x /opt/runner/entry.sh\nENTRYPOINT [\"/opt/runner/entry.sh\"]\n";
422
+ /** The docker run container's entrypoint (entry.sh), exported for its tests. */
423
+ export declare const ENTRY: string;
374
424
  /** Which build target of the runner image (see DOCKERFILE). */
375
425
  export type RunnerVariant = "full" | "slim";
376
426
  export declare function runnerImageTag(variant?: RunnerVariant): string;
@@ -547,8 +597,10 @@ export interface WriteDivert {
547
597
  /**
548
598
  * What crosses into the container as its environment, and how.
549
599
  *
550
- * A docker --env-file is one `KEY=value` per line and cannot carry a
551
- * newline. @file secrets are multi-line by nature (a PEM key, a cert), so
600
+ * It crosses as a file the agent's shell sources after the drop (env.sh,
601
+ * FOL-130); until then it was a docker --env-file, one `KEY=value` per
602
+ * line, which cannot carry a newline — and what a step sees stays the shape
603
+ * that file set. @file secrets are multi-line by nature (a PEM key, a cert), so
552
604
  * they are staged as files NOW, into the copied-in workspace, and the env
553
605
  * carries the container path — the one place a path is stable across the
554
606
  * boundary. A plain secret whose value happens to hold a newline gets the
@@ -27,8 +27,8 @@ import { spawn, spawnSync } from "node:child_process";
27
27
  import { CAPTURE_CAP, isPlatformPath } from "./store.js";
28
28
  import { divertedSummary, isDivertedPath, overlayTestWrites } from "./test-mode.js";
29
29
  import { refusedBack, refusedLine, keptLine } from "./copy-back.js";
30
- import { isFileValue, fileContent } from "./secrets.js";
31
- import { safeTenantSegment, systemInstallSh, SYSTEM_FROM_INPUT_SH, INSTALL_SOCKET } from "./runtime.js";
30
+ import { isFileValue, fileContent, installKeyMaterial } from "./secrets.js";
31
+ import { safeTenantSegment, systemInstallSh, SYSTEM_FROM_INPUT_SH, INSTALL_SOCKET, ROOT_ENV_RESET_SH, ROOT_SHELL_GUARD_SH, ROOT_ENV_FILE, STEP_ENV_FILE, stepEnvShell, rootEnvShell, SNAPSHOT_KEY_FILE } from "./runtime.js";
32
32
  import { egressCaSh } from "./network.js";
33
33
  import { anyMemoryMi, quantityMi } from "./resources.js";
34
34
  import { STARTUP_PHASES } from "./startup.js";
@@ -430,9 +430,86 @@ export const RUNTIME_CACHE = "/home/agent/.foldrun/runner/.runtimes";
430
430
  /** Starts the install helper as root, in the background, before the drop to
431
431
  * the agent user: the root half of the `install` tool (install-helper.ts).
432
432
  * The agent reaches it only through the socket; it installs only validated
433
- * Debian package names, and dies with the container. */
433
+ * Debian package names, and dies with the container.
434
+ * @deprecated the start-ups use rootStartSh, which starts the helper in a
435
+ * clean environment with the snapshot key's path (FOL-129). */
434
436
  export const INSTALL_HELPER_SH = `FOLDRUN_INSTALL_SOCKET=${INSTALL_SOCKET}; export FOLDRUN_INSTALL_SOCKET
435
437
  node /opt/runner/node_modules/@foldrun/core/dist/src/install-helper.js "$FOLDRUN_INSTALL_SOCKET" ${RUNTIME_CACHE} >/dev/null 2>&1 &`;
438
+ /**
439
+ * The account's key for sealing its `runtime: system:` snapshots (FOL-129):
440
+ * derived from the install key, so it needs no store and no rotation of its
441
+ * own, and per account, so one account's key seals nothing for another. The
442
+ * worker stages it as the step's SNAPSHOT_KEY_FILE; null (no tenant, or a
443
+ * process without the install key) means the step gets no snapshots.
444
+ */
445
+ export function aptSnapshotKey(tenant) {
446
+ if (!tenant)
447
+ return null;
448
+ try {
449
+ return crypto.createHmac("sha256", installKeyMaterial()).update(`foldrun apt snapshot v1\0${tenant}`).digest("hex");
450
+ }
451
+ catch {
452
+ return null;
453
+ }
454
+ }
455
+ /**
456
+ * Root's part of a run container's start-up, before the chown and the drop
457
+ * to the agent user (k8s SHIM, docker ENTRY): the snapshot key moved where
458
+ * only root can read it, then — in a subshell whose environment is the root
459
+ * shell's own plus the proxy's variables (ROOT_ENV_FILE), reset to those
460
+ * alone (ROOT_ENV_RESET_SH) — the declared system packages and the install
461
+ * helper. The key never enters an environment: root's commands and the
462
+ * helper get only its path, and the copy in the job folder (which is chowned
463
+ * to the agent next) is gone before the subshell ends, or the start-up stops.
464
+ *
465
+ * The step's own environment (STEP_ENV_FILE) is never read here (FOL-130):
466
+ * its names are the account's to choose, and an LD_PRELOAD or PATH there
467
+ * pointing into the agent-writable cache would run the agent's code as root.
468
+ * ROOT_ENV_FILE is the worker's cut of it to ROOT_ENV_NAMES, sourced before
469
+ * the reset so even a name that should not be there is unset again; the
470
+ * socket and the locale are set after it, so nothing read can move them.
471
+ */
472
+ export function rootStartSh(cacheDir = RUNTIME_CACHE) {
473
+ return `FOLDRUN_INSTALL_SOCKET=${INSTALL_SOCKET}; export FOLDRUN_INSTALL_SOCKET
474
+ (
475
+ if [ -f ${ROOT_ENV_FILE} ] && [ ! -L ${ROOT_ENV_FILE} ]; then . ${ROOT_ENV_FILE}; fi
476
+ ${ROOT_ENV_RESET_SH}
477
+ FOLDRUN_INSTALL_SOCKET=${INSTALL_SOCKET} LANG=C.UTF-8 LC_ALL=C.UTF-8; export FOLDRUN_INSTALL_SOCKET LANG LC_ALL
478
+ unset FOLDRUN_SNAP_KEY_FILE; FOLDRUN_SNAP_KEY_FILE=""
479
+ if [ -e ${SNAPSHOT_KEY_FILE} ] || [ -L ${SNAPSHOT_KEY_FILE} ]; then
480
+ _fk=$(mktemp -d /tmp/.foldrun-key.XXXXXX 2>/dev/null) && [ ! -L ${SNAPSHOT_KEY_FILE} ] && cat ${SNAPSHOT_KEY_FILE} > "$_fk/key" 2>/dev/null && FOLDRUN_SNAP_KEY_FILE=$_fk/key
481
+ rm -f ${SNAPSHOT_KEY_FILE}
482
+ fi
483
+ ${SYSTEM_FROM_INPUT_SH}
484
+ ${systemInstallSh(cacheDir)}
485
+ FOLDRUN_SNAP_KEY_FILE="$FOLDRUN_SNAP_KEY_FILE" node /opt/runner/node_modules/@foldrun/core/dist/src/install-helper.js "$FOLDRUN_INSTALL_SOCKET" ${cacheDir} >/dev/null 2>&1 &
486
+ )
487
+ if [ -e ${SNAPSHOT_KEY_FILE} ] || [ -L ${SNAPSHOT_KEY_FILE} ]; then echo "the snapshot key could not be removed from the job folder — not starting the step" >&2; exit 1; fi`;
488
+ }
489
+ /**
490
+ * The drop to the agent user, and the only place the step's environment is
491
+ * read (FOL-130): runuser starts with the root shell's own environment — the
492
+ * image's and the pod spec's, which ROOT_SHELL_GUARD_SH has already cleaned —
493
+ * and the agent's shell then sources STEP_ENV_FILE, sets up the egress
494
+ * proxy's CA (which root never needs: apt goes through the proxy unopened),
495
+ * and execs `command`, so its exit status is the step's.
496
+ *
497
+ * What the agent ends with is what it had when root sourced the file before
498
+ * the drop: the step's names over the root shell's, the CA's variables over
499
+ * those, runuser's HOME/USER/LOGNAME over all (kept in positional
500
+ * parameters, which no sourced name can reach), and the install socket at
501
+ * its fixed path. No `set -e`: an egress CA that cannot be written leaves
502
+ * the step without it, as before, rather than stopping it.
503
+ */
504
+ export function agentStartSh(command = "node /opt/runner/driver.mjs") {
505
+ const inner = `set -- "$HOME" "$USER" "$LOGNAME"
506
+ set -a; if [ -f ${STEP_ENV_FILE} ]; then . ${STEP_ENV_FILE}; fi; set +a
507
+ HOME=$1 USER=$2 LOGNAME=$3; export HOME USER LOGNAME; shift 3
508
+ FOLDRUN_INSTALL_SOCKET=${INSTALL_SOCKET}; export FOLDRUN_INSTALL_SOCKET
509
+ ${egressCaSh("/opt/runner/job")}
510
+ exec ${command}`;
511
+ return `runuser -u agent -- /bin/sh -c '${inner.replaceAll("'", `'\\''`)}'`;
512
+ }
436
513
  /**
437
514
  * Where the platform's shared runtime layer is mounted, read-only, in a run
438
515
  * pod — and read-write, one entry at a time, in the pod that builds an entry
@@ -1028,19 +1105,19 @@ ${CORE_INSTALL}`;
1028
1105
  // runtime: system: — apt as root, before the drop (runtime.ts systemInstallSh).
1029
1106
  // set -e is off around it: a failed install is reported by the driver, which
1030
1107
  // reads the status file and fails the step with apt's own words.
1031
- const ENTRY = `#!/bin/sh
1108
+ /** The docker run container's entrypoint (entry.sh), exported for its tests. */
1109
+ export const ENTRY = `#!/bin/sh
1032
1110
  set +e
1033
- ${egressCaSh("/opt/runner/job")}
1034
- ${SYSTEM_FROM_INPUT_SH}
1035
- ${systemInstallSh(RUNTIME_CACHE)}
1036
- ${INSTALL_HELPER_SH}
1037
- set -e
1038
- chown -R agent:agent /workspace /library /opt/runner/job
1111
+ ${ROOT_SHELL_GUARD_SH}
1039
1112
  # The runtime cache, when one is mounted. NOT recursive: a warm cache is tens
1040
1113
  # of thousands of files and its contents are already agent-owned from the step
1041
- # that built them — only the mount point itself arrives owned by root.
1114
+ # that built them — only the mount point itself arrives owned by root. Before
1115
+ # the system install: root works in the cache as the agent user (FOL-129).
1042
1116
  chown agent:agent ${RUNTIME_CACHE} 2>/dev/null || true
1043
- exec runuser -u agent -- node /opt/runner/driver.mjs
1117
+ ${rootStartSh(RUNTIME_CACHE)}
1118
+ set -e
1119
+ chown -R agent:agent /workspace /library /opt/runner/job
1120
+ exec ${agentStartSh()}
1044
1121
  `;
1045
1122
  function corePackageDir() {
1046
1123
  // This file *is* part of @foldrun/core, so its own package.json is a walk
@@ -1382,8 +1459,10 @@ export function heldCores(cpus, isolation, available) {
1382
1459
  /**
1383
1460
  * What crosses into the container as its environment, and how.
1384
1461
  *
1385
- * A docker --env-file is one `KEY=value` per line and cannot carry a
1386
- * newline. @file secrets are multi-line by nature (a PEM key, a cert), so
1462
+ * It crosses as a file the agent's shell sources after the drop (env.sh,
1463
+ * FOL-130); until then it was a docker --env-file, one `KEY=value` per
1464
+ * line, which cannot carry a newline — and what a step sees stays the shape
1465
+ * that file set. @file secrets are multi-line by nature (a PEM key, a cert), so
1387
1466
  * they are staged as files NOW, into the copied-in workspace, and the env
1388
1467
  * carries the container path — the one place a path is stable across the
1389
1468
  * boundary. A plain secret whose value happens to hold a newline gets the
@@ -1573,9 +1652,18 @@ export async function runStepInContainer(args) {
1573
1652
  const jobIn = path.join(staging, "job");
1574
1653
  fs.mkdirSync(jobIn);
1575
1654
  fs.writeFileSync(path.join(jobIn, "input.json"), JSON.stringify(args.input, null, 2));
1655
+ // The account's snapshot key, for root's start-up alone (rootStartSh
1656
+ // moves it out of the agent's reach before the drop) — FOL-129.
1657
+ const snapKey = aptSnapshotKey(args.tenant);
1658
+ if (snapKey)
1659
+ fs.writeFileSync(path.join(jobIn, "snapshot.key"), snapKey, { mode: 0o600 });
1576
1660
  const containerEnv = stageContainerEnv(args.env, wsIn, args.input.agentRel, args.emit);
1577
- const envFile = path.join(staging, "env");
1578
- fs.writeFileSync(envFile, Object.entries(containerEnv).map(([k, v]) => `${k}=${v}`).join("\n"), { mode: 0o600 });
1661
+ // Files in the job folder, not the container's environment (FOL-130): a
1662
+ // docker --env-file is PID 1's environment, so a secret named LD_PRELOAD
1663
+ // reached the root shell before its first line. The agent's shell sources
1664
+ // env.sh after the drop; root's start-up reads only the proxy's lines.
1665
+ fs.writeFileSync(path.join(jobIn, "env.sh"), stepEnvShell(containerEnv), { mode: 0o600 });
1666
+ fs.writeFileSync(path.join(jobIn, "root-env.sh"), rootEnvShell(containerEnv), { mode: 0o600 });
1579
1667
  const lim = args.limits ?? resolveResources(args.size);
1580
1668
  const cpus = dockerCpus(lim.cpus);
1581
1669
  const flags = [
@@ -1592,7 +1680,6 @@ export async function runStepInContainer(args) {
1592
1680
  // the whole machine from the steps beside it.
1593
1681
  "--memory", dockerMemory(lim.memory),
1594
1682
  ...(cpus ? ["--cpus", cpus] : []),
1595
- "--env-file", envFile,
1596
1683
  ];
1597
1684
  // gVisor (or kata) where the host has it: one env var, because the flag
1598
1685
  // is the same docker invocation everywhere else.
@@ -1645,6 +1732,10 @@ export async function runStepInContainer(args) {
1645
1732
  cp(`${wsIn}/.`, `${containerId}:/workspace`);
1646
1733
  cp(`${libIn}/.`, `${containerId}:/library`);
1647
1734
  cp(`${jobIn}/input.json`, `${containerId}:/opt/runner/job/input.json`);
1735
+ cp(`${jobIn}/env.sh`, `${containerId}:${STEP_ENV_FILE}`);
1736
+ cp(`${jobIn}/root-env.sh`, `${containerId}:${ROOT_ENV_FILE}`);
1737
+ if (snapKey)
1738
+ cp(`${jobIn}/snapshot.key`, `${containerId}:${SNAPSHOT_KEY_FILE}`);
1648
1739
  phases.files = Date.now() - t0;
1649
1740
  // Start attached and read the driver's JSONL. The step timeout gets a
1650
1741
  // backstop out here — a wedged container is killed, not waited on.
@@ -1735,6 +1826,7 @@ export async function runStepInContainer(args) {
1735
1826
  firstOutputMs: firstOutputAt === null ? null : firstOutputAt - t0 - sandboxMs,
1736
1827
  totalMs: Date.now() - t0,
1737
1828
  phases,
1829
+ origin: t0,
1738
1830
  };
1739
1831
  args.emit("info", timingLine(timing));
1740
1832
  return { ...outcome, timing, applied, ...(refused.length ? { refused } : {}) };
@@ -0,0 +1,179 @@
1
+ import { type RunRecord, type StepRecord } from "./store.ts";
2
+ import { type ErrorClass, type OpsFields } from "./ops-log.ts";
3
+ import { type FailureExplained, type FailureKind, type LimitScope } from "./failure.ts";
4
+ /** The funnel's marks, in order. */
5
+ export declare const FUNNEL: readonly ["submitted", "queued", "eligible", "claimed", "scheduled", "podReady", "sandboxUp", "firstOutput", "finished"];
6
+ export type FunnelMark = (typeof FUNNEL)[number];
7
+ /** Whether a finished run counts toward the success-rate SLI: `good`
8
+ * (completed), `bad` (failed, and the failure is ours, a provider's or the
9
+ * cluster's), or `excluded` (the customer's own code, settings or decision
10
+ * — sloOutcome). Null while the run is not finished. */
11
+ export type SloOutcome = "good" | "bad" | "excluded";
12
+ /** Why a failed run is excluded from the success rate, or why it is bad. */
13
+ export declare const SLO_REASONS: readonly ["completed", "cancelled", "customer_code", "customer_check", "customer_budget", "customer_security", "customer_network", "customer_credential", "customer_limit", "platform", "model", "capacity", "deadline", "unexplained"];
14
+ export type SloReason = (typeof SLO_REASONS)[number];
15
+ /** The SLO rule's version, on every row: a row says which rule judged it,
16
+ * so a change to the rule never silently rewrites history's meaning. */
17
+ export declare const SLO_RULES_VERSION = 1;
18
+ export interface RunWideEvent {
19
+ runId: string;
20
+ tenant: string;
21
+ workspace: string;
22
+ /** The flow's name, or the agent's for a direct agent run. */
23
+ flow: string;
24
+ kind: "flow" | "agent";
25
+ test: boolean;
26
+ status: RunRecord["status"];
27
+ errorClass: ErrorClass | null;
28
+ failureKind: FailureKind | null;
29
+ failureScope: LimitScope | null;
30
+ slo: SloOutcome | null;
31
+ sloReason: SloReason | null;
32
+ rulesVersion: number;
33
+ /** The funnel step's runner image, model (its first model call's, else
34
+ * the step's own setting) and size class. */
35
+ image: "full" | "slim" | null;
36
+ model: string | null;
37
+ size: string | null;
38
+ /** ISO instants; null where the run did not reach the mark, or the
39
+ * record does not say. */
40
+ at: Record<FunnelMark, string | null>;
41
+ /** The earliest model output of any step this run executed — with
42
+ * parallel steps, possibly not the funnel step's. */
43
+ earliestOutput: string | null;
44
+ /** The funnel step's index; its start-up marks, in seconds from `startupAt`
45
+ * (STARTUP_PHASES); and whether that origin is the executor's own
46
+ * (`exact`) or the attempt's start (`estimated`). */
47
+ funnelStep: number | null;
48
+ startup: Record<string, number> | null;
49
+ startupAt: string | null;
50
+ origin: "exact" | "estimated" | null;
51
+ /** Steps in the record (rescues and sub-agents included), how many ran in
52
+ * a sandbox, and attempts across the steps this run executed. */
53
+ steps: number;
54
+ sandboxedSteps: number;
55
+ attempts: number;
56
+ /** Summed over every attempt of every step this run executed. */
57
+ costUsd: number;
58
+ computeSecs: number;
59
+ /** The funnel step's sandbox start-up (step.startupSecs). */
60
+ startupSecs: number | null;
61
+ /** The largest any one step's sandbox held, and the most any one used —
62
+ * not the run's capacity (parallel steps add up), and the limit and the
63
+ * use may be two different steps'. Each step's last attempt. Disk used
64
+ * is not measured in the sandbox today: null, never estimated. CPU busy
65
+ * and throttled seconds are summed. */
66
+ cpuLimit: number | null;
67
+ cpuBusySecs: number | null;
68
+ cpuThrottledSecs: number | null;
69
+ memLimitGiB: number | null;
70
+ memPeakBytes: number | null;
71
+ diskLimitGiB: number | null;
72
+ diskUsedBytes: number | null;
73
+ }
74
+ /** What the queue knows that the record does not (the platform's row). */
75
+ export interface QueueFacts {
76
+ queuedAt?: string | null;
77
+ eligibleAt?: string | null;
78
+ claimedAt?: string | null;
79
+ }
80
+ /**
81
+ * Why a failed run failed, for the wide event. runFailure (store.ts, the
82
+ * customer's view) reads the first failed step, an optional one included,
83
+ * and a stop only when no step failed; the funnel wants the run's own
84
+ * terminal cause: a stop first, then the step that failed the run.
85
+ */
86
+ export declare function terminalFailure(run: RunRecord): (FailureExplained & {
87
+ text: string;
88
+ step: StepRecord | null;
89
+ }) | null;
90
+ /**
91
+ * Does this run count against the platform's success rate, and why?
92
+ *
93
+ * Excluded — the customer's own code, settings or decision:
94
+ * cancelled a person or a caller stopped it
95
+ * customer_code their script, tool or hook failed
96
+ * customer_check their verify:, output: json or schema: did not hold
97
+ * customer_budget their budget: ran out
98
+ * customer_security a platform security control stopped what their agent did
99
+ * customer_network the error IS the proxy refusing a site off their
100
+ * network: list (a refusal merely on the trail of a
101
+ * step that failed for another reason does not count)
102
+ * customer_credential their own model key was refused (supply `own`)
103
+ * customer_limit a limit whose scope is theirs (CUSTOMER_SCOPES)
104
+ * Bad — everything else: platform (ours, or a node short of memory or disk
105
+ * evicting it), model (a provider failing, the platform's key refused),
106
+ * capacity (the install's or the node's limit), deadline (a time limit with
107
+ * no scope of theirs), unexplained.
108
+ */
109
+ export declare function sloOutcome(run: RunRecord, failure?: (FailureExplained & {
110
+ text: string;
111
+ step: StepRecord | null;
112
+ }) | null): {
113
+ slo: SloOutcome;
114
+ reason: SloReason;
115
+ } | null;
116
+ /** The run's wide event. Pure: the record, and what the queue adds. */
117
+ export declare function runWideEvent(tenant: string, workspace: string, run: RunRecord, queue?: QueueFacts): RunWideEvent;
118
+ /** Seconds between two marks of an event, or null when either is missing
119
+ * (or the later reads earlier: two clocks). */
120
+ export declare function funnelSecs(ev: Pick<RunWideEvent, "at">, from: FunnelMark, to: FunnelMark): number | null;
121
+ /** The ops-log fields an ops span may carry — the collector's allowlist
122
+ * (foldrun-infra alloy-config.yaml) is held to this list by its test. */
123
+ export declare const OPS_SPAN_FIELDS: readonly ["runId", "tenant", "workspace", "flow", "agent", "kind", "outcome", "errorClass", "verdict", "reason", "image", "size", "model", "usd", "step", "attempt", "phase", "ms"];
124
+ /** Every name an ops span may have. */
125
+ export declare const OPS_SPAN_NAMES: readonly ["run", "submit", "queue.wait", "drive", "pod.start", "sandbox.start", "first_output", ...("startup.applied" | "startup.driver" | "startup.files" | "startup.go" | "startup.imports" | "startup.ready" | "startup.room" | "startup.services" | "startup.shim" | "startup.system" | "startup.tools")[]];
126
+ export declare const OPS_SERVICES: readonly ["foldrun-web", "foldrun-worker", "foldrun-runner"];
127
+ type Attr = {
128
+ key: string;
129
+ value: {
130
+ stringValue: string;
131
+ } | {
132
+ intValue: string;
133
+ } | {
134
+ doubleValue: number;
135
+ } | {
136
+ boolValue: boolean;
137
+ };
138
+ };
139
+ /** An ops span's fields as OTLP attributes, `foldrun.<field>`: only
140
+ * OPS_SPAN_FIELDS, only values opsLine lets through. */
141
+ export declare function opsAttributes(fields: OpsFields): Attr[];
142
+ /** The trace id of a run's ops trace — under a key of its own, never the
143
+ * account's trace id (otel.ts). */
144
+ export declare function opsTraceId(tenant: string, workspace: string, runId: string): string;
145
+ /**
146
+ * The run's ops trace as an OTLP/HTTP JSON body, or null when the run has
147
+ * no start and end to draw between.
148
+ */
149
+ export declare function opsTrace(ev: RunWideEvent): {
150
+ resourceSpans: {
151
+ resource: {
152
+ attributes: {
153
+ key: string;
154
+ value: {
155
+ stringValue: string;
156
+ };
157
+ }[];
158
+ };
159
+ scopeSpans: {
160
+ scope: {
161
+ name: string;
162
+ };
163
+ spans: {
164
+ traceId: string;
165
+ spanId: string;
166
+ parentSpanId?: string | undefined;
167
+ name: "drive" | "first_output" | "pod.start" | "queue.wait" | "run" | "sandbox.start" | "startup.applied" | "startup.driver" | "startup.files" | "startup.go" | "startup.imports" | "startup.ready" | "startup.room" | "startup.services" | "startup.shim" | "startup.system" | "startup.tools" | "submit";
168
+ kind: number;
169
+ startTimeUnixNano: string;
170
+ endTimeUnixNano: string;
171
+ attributes: Attr[];
172
+ status: {
173
+ code: number;
174
+ };
175
+ }[];
176
+ }[];
177
+ }[];
178
+ } | null;
179
+ export {};