@foldrun/core 15.1.0 → 17.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 (52) 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/egress.d.ts +9 -0
  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/network.js +1 -1
  15. package/dist/src/ops-log.js +4 -0
  16. package/dist/src/otel.d.ts +16 -1
  17. package/dist/src/otel.js +121 -5
  18. package/dist/src/platform.d.ts +8 -0
  19. package/dist/src/run-container.d.ts +88 -4
  20. package/dist/src/run-container.js +215 -26
  21. package/dist/src/run-event.d.ts +179 -0
  22. package/dist/src/run-event.js +473 -0
  23. package/dist/src/runner.js +35 -1
  24. package/dist/src/runtime.d.ts +116 -16
  25. package/dist/src/runtime.js +531 -44
  26. package/dist/src/scan.js +80 -18
  27. package/dist/src/search-egress.d.ts +58 -0
  28. package/dist/src/search-egress.js +88 -0
  29. package/dist/src/starter.js +4 -1
  30. package/dist/src/store.d.ts +34 -3
  31. package/dist/src/store.js +46 -10
  32. package/package.json +2 -1
  33. package/src/a2a-publish.ts +19 -1
  34. package/src/a2a-reach.ts +503 -0
  35. package/src/browse-egress.ts +8 -7
  36. package/src/egress.ts +7 -0
  37. package/src/env-names.ts +53 -0
  38. package/src/failure.ts +368 -0
  39. package/src/frontmatter-fields.ts +1 -1
  40. package/src/install-helper.ts +10 -5
  41. package/src/network.ts +1 -1
  42. package/src/ops-log.ts +4 -0
  43. package/src/otel.ts +122 -7
  44. package/src/platform.ts +8 -0
  45. package/src/run-container.ts +228 -29
  46. package/src/run-event.ts +563 -0
  47. package/src/runner.ts +32 -1
  48. package/src/runtime.ts +546 -45
  49. package/src/scan.ts +91 -20
  50. package/src/search-egress.ts +116 -0
  51. package/src/starter.ts +4 -1
  52. package/src/store.ts +75 -12
@@ -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
@@ -845,7 +922,7 @@ export const RETRY_SH = `retry() { what=$1; shift; n=1; until "$@"; do if [ "$n"
845
922
  * 23 Oct 2026: Node 22.23.4 (the 21 Oct security release: Brotli decoder
846
923
  * RCE, TLS hostname bypasses); the pin before carried 22.23.3. */
847
924
  export const NODE_BASE = "node:22-trixie-slim@sha256:8eb619e402eaede1748a3c8173bffab391592812e85136452f781741c7242ddf";
848
- // Two images from one file, as build targets.
925
+ // Two images from one file, as build targets, in two parts.
849
926
  //
850
927
  // full (the default, the last stage) — everything, browsers included. The
851
928
  // per-account browser pod runs it, and so does any step that may
@@ -858,10 +935,42 @@ export const NODE_BASE = "node:22-trixie-slim@sha256:8eb619e402eaede1748a3c8173b
858
935
  // (run-k8s.ts picks), and its declared packages arrive at run time
859
936
  // through the runtime cache — uv is in the base for exactly that.
860
937
  //
938
+ // The parts (FOL-50, 5 Nov 2026):
939
+ //
940
+ // the OS RUNNER_OS_DOCKERFILE: Debian, every apt package, uv, the
941
+ // Playwright client and, for full, the browsers (Google's Chrome
942
+ // included). Targets `slim-os` and `browsers`. Everything that
943
+ // writes /var/lib/dpkg/status is here and nowhere else.
944
+ // the app core and the driver on top (CORE_STAGE, CORE_INSTALL): files
945
+ // only, no apt.
946
+ //
947
+ // Built together (runnerDockerfile() — a laptop, a self-hoster, images.yml)
948
+ // it is one image as before. The hosted platform builds the OS part on its
949
+ // own as the runner BASE image, pins it by digest (foldrun-infra
950
+ // images/runner-base.env, refreshed weekly and at once for a fixable critical
951
+ // vulnerability) and builds the app part FROM it (FOLDRUN_RUNNER_BASE_SLIM /
952
+ // _FULL). A release that changes only foldrun's code then keeps the base's
953
+ // bytes, so the dpkg status a `runtime: system:` snapshot was built on is
954
+ // still there after the deploy (runtime.ts systemInstallSh) — rebuilding the
955
+ // OS on every core change moved Chrome, the apt index and every package's
956
+ // status line, and each release cost each package set a full apt install.
957
+ //
861
958
  // The browsers sit BELOW the core install in `full`, as they always have,
862
959
  // so a core change rebuilds one thin layer and not 1.4 GB of Chromium.
863
- export const DOCKERFILE = `FROM ${NODE_BASE} AS base
960
+ /** Stands for the OS definition's id inside its own text: the id is the
961
+ * sha256 of the text with this in place, then substituted in. */
962
+ const OS_ID_SLOT = "@@FOLDRUN_RUNNER_OS@@";
963
+ /** The end of each OS target: which definition built it, as a label and as
964
+ * a file the app part checks (OS_GUARD). Not under /var/lib/dpkg. */
965
+ const OS_MARK = `LABEL io.foldrun.runner-os=${OS_ID_SLOT}
966
+ RUN echo ${OS_ID_SLOT} > /etc/foldrun-runner-os`;
967
+ const OS_TEMPLATE = `FROM ${NODE_BASE} AS base
968
+ # upgrade: node's image lags Debian security (the platform images learnt it
969
+ # on 6 Oct 2026, perl-base), and the hosted runner's base is rebuilt weekly
970
+ # precisely so those fixes arrive; without it a refresh changed nothing the
971
+ # node image already carried.
864
972
  RUN apt-get update \\
973
+ && DEBIAN_FRONTEND=noninteractive apt-get upgrade -y --no-install-recommends \\
865
974
  && apt-get install -y --no-install-recommends python3 python3-venv ca-certificates bash util-linux tar openssh-client sshpass git curl \\
866
975
  && rm -rf /var/lib/apt/lists/* \\
867
976
  && useradd -m -u 10001 agent
@@ -870,8 +979,7 @@ RUN apt-get update \\
870
979
  COPY --from=ghcr.io/astral-sh/uv:${UV_VERSION} /uv /uvx /usr/local/bin/
871
980
  ENV PLAYWRIGHT_BROWSERS_PATH=/opt/browser NODE_PATH=/usr/local/lib/node_modules
872
981
 
873
- ${CORE_STAGE}
874
- FROM base AS slim
982
+ FROM base AS slim-os
875
983
  # Fonts, because a step that draws text without a browser still needs them:
876
984
  # the full image gets 51 from Playwright's --with-deps, slim had none, so from
877
985
  # 2026-09-29 (when non-browsing steps moved to slim) every resvg/sharp diagram
@@ -897,7 +1005,8 @@ RUN apt-get update \\
897
1005
  # npm's download cache is dropped in the same layer: it was 190 MB of every
898
1006
  # image, read by nothing after the build.
899
1007
  RUN npm install -g playwright@1.63.0 axe-core@4.13.0 >/dev/null && npm cache clean --force >/dev/null 2>&1
900
- ${CORE_INSTALL}
1008
+ ${OS_MARK}
1009
+
901
1010
  FROM base AS browsers
902
1011
  # Real browsers, because directories and portals increasingly render with
903
1012
  # JavaScript and a plain fetch sees only the empty shell. Chromium is the one the
@@ -1022,25 +1131,81 @@ RUN node -e ' \\
1022
1131
  if (missing.length) console.error("runner image: built without " + missing.join(", ") + " on " + arch); \\
1023
1132
  ' \\
1024
1133
  && chmod a+r /opt/browser/engines.json
1025
-
1134
+ ${OS_MARK}
1135
+ `;
1136
+ /** Which definition of the OS part this core holds: 16 hex of the sha256 of
1137
+ * its text. A base image carries it (label io.foldrun.runner-os and
1138
+ * /etc/foldrun-runner-os); a base from another definition is refused. */
1139
+ export const RUNNER_OS_ID = crypto.createHash("sha256").update(OS_TEMPLATE).digest("hex").slice(0, 16);
1140
+ /** The runner's OS part on its own — what the base image is built from
1141
+ * (targets RUNNER_OS_TARGETS). No build context: it copies nothing local. */
1142
+ export const RUNNER_OS_DOCKERFILE = OS_TEMPLATE.split(OS_ID_SLOT).join(RUNNER_OS_ID);
1143
+ /** The OS part's build target for each runner variant. */
1144
+ export const RUNNER_OS_TARGETS = { slim: "slim-os", full: "browsers" };
1145
+ /** The app part's first word in both variants: the OS under it is the one
1146
+ * this core's text describes. A base built from an older definition (a
1147
+ * Playwright bump, a new apt package) would otherwise ship a runner whose
1148
+ * browsers or packages are not the ones its core expects. */
1149
+ const OS_GUARD = `RUN test "$(cat /etc/foldrun-runner-os 2>/dev/null)" = "${RUNNER_OS_ID}" \\
1150
+ || { echo "runner image: its base was built from another definition (wants ${RUNNER_OS_ID}, has $(cat /etc/foldrun-runner-os 2>/dev/null || echo none)) - build the base again: bash foldrun-infra/dev/ci/runner-base.sh refresh" >&2; exit 1; }`;
1151
+ const BASE_REF = /^[a-z0-9][a-z0-9._/:-]*@sha256:[0-9a-f]{64}$/;
1152
+ /**
1153
+ * The runner base from FOLDRUN_RUNNER_BASE_SLIM and FOLDRUN_RUNNER_BASE_FULL:
1154
+ * both or neither (empty counts as unset, as FOLDRUN_RUNNER_IMAGE does), each
1155
+ * an image by digest — a tag would let the same runner tag hold another
1156
+ * base's bytes. Anything else throws: a half-set base is a broken deploy,
1157
+ * not a reason to quietly build the OS again.
1158
+ */
1159
+ export function runnerBase(env = process.env) {
1160
+ const slim = env.FOLDRUN_RUNNER_BASE_SLIM ?? "";
1161
+ const full = env.FOLDRUN_RUNNER_BASE_FULL ?? "";
1162
+ if (!slim && !full)
1163
+ return null;
1164
+ if (!slim || !full) {
1165
+ throw new Error("FOLDRUN_RUNNER_BASE_SLIM and FOLDRUN_RUNNER_BASE_FULL go together: set both (the base's two images, by digest) or neither");
1166
+ }
1167
+ for (const [k, v] of [["FOLDRUN_RUNNER_BASE_SLIM", slim], ["FOLDRUN_RUNNER_BASE_FULL", full]]) {
1168
+ if (!BASE_REF.test(v))
1169
+ throw new Error(`${k} must name an image by digest (name@sha256:<64 hex>), not ${JSON.stringify(v.slice(0, 120))}`);
1170
+ }
1171
+ return { slim, full };
1172
+ }
1173
+ /**
1174
+ * The runner's Dockerfile: with no base, the OS part and the app part in one
1175
+ * file (a self-contained build); with one, the app part FROM the base's two
1176
+ * images. The app part's text is the same either way.
1177
+ */
1178
+ export function runnerDockerfile(base = null) {
1179
+ const os = base
1180
+ ? `FROM ${base.slim} AS slim-os\nFROM ${base.full} AS browsers\nFROM slim-os AS base\n`
1181
+ : RUNNER_OS_DOCKERFILE;
1182
+ return `${os}
1183
+ ${CORE_STAGE}
1184
+ FROM slim-os AS slim
1185
+ ${OS_GUARD}
1186
+ ${CORE_INSTALL}
1026
1187
  FROM browsers AS full
1188
+ ${OS_GUARD}
1027
1189
  ${CORE_INSTALL}`;
1190
+ }
1191
+ /** The self-contained runner Dockerfile (no base): runnerDockerfile(). */
1192
+ export const DOCKERFILE = runnerDockerfile();
1028
1193
  // runtime: system: — apt as root, before the drop (runtime.ts systemInstallSh).
1029
1194
  // set -e is off around it: a failed install is reported by the driver, which
1030
1195
  // reads the status file and fails the step with apt's own words.
1031
- const ENTRY = `#!/bin/sh
1196
+ /** The docker run container's entrypoint (entry.sh), exported for its tests. */
1197
+ export const ENTRY = `#!/bin/sh
1032
1198
  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
1199
+ ${ROOT_SHELL_GUARD_SH}
1039
1200
  # The runtime cache, when one is mounted. NOT recursive: a warm cache is tens
1040
1201
  # 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.
1202
+ # that built them — only the mount point itself arrives owned by root. Before
1203
+ # the system install: root works in the cache as the agent user (FOL-129).
1042
1204
  chown agent:agent ${RUNTIME_CACHE} 2>/dev/null || true
1043
- exec runuser -u agent -- node /opt/runner/driver.mjs
1205
+ ${rootStartSh(RUNTIME_CACHE)}
1206
+ set -e
1207
+ chown -R agent:agent /workspace /library /opt/runner/job
1208
+ exec ${agentStartSh()}
1044
1209
  `;
1045
1210
  function corePackageDir() {
1046
1211
  // This file *is* part of @foldrun/core, so its own package.json is a walk
@@ -1066,7 +1231,9 @@ export function runnerImageTag(variant = "full") {
1066
1231
  // The fingerprint hashes the *built code*, not the version — a version
1067
1232
  // string that nobody bumped would pin every future run to the runner
1068
1233
  // image of whatever core happened to build first.
1069
- const hash = crypto.createHash("sha256").update(DRIVER + "\n" + DOCKERFILE + "\n" + ENTRY);
1234
+ // The Dockerfile as it will be built — with the base's digests in it when
1235
+ // one is set, so a new base is a new tag.
1236
+ const hash = crypto.createHash("sha256").update(DRIVER + "\n" + runnerDockerfile(runnerBase()) + "\n" + ENTRY);
1070
1237
  const dist = path.join(corePackageDir(), "dist");
1071
1238
  if (fs.existsSync(dist)) {
1072
1239
  for (const entry of fs.readdirSync(dist, { recursive: true }).sort()) {
@@ -1112,6 +1279,12 @@ export function ensureRunnerImage(opts = {}) {
1112
1279
  const log = [];
1113
1280
  if (explicit)
1114
1281
  return { tag, log };
1282
+ const base = runnerBase();
1283
+ // A base is one platform's images (the hosted base is linux/amd64): a
1284
+ // cross-build on it would pull the wrong arch or none.
1285
+ if (base && opts.platform) {
1286
+ throw new Error(`a runner base names one platform's images: unset FOLDRUN_RUNNER_BASE_SLIM and FOLDRUN_RUNNER_BASE_FULL to build for ${opts.platform}`);
1287
+ }
1115
1288
  const have = spawnSync(cli(), ["image", "inspect", tag], { stdio: "ignore" });
1116
1289
  if (have.status === 0)
1117
1290
  return { tag, log };
@@ -1126,8 +1299,9 @@ export function ensureRunnerImage(opts = {}) {
1126
1299
  fs.renameSync(path.join(build, tarball), path.join(build, "foldrun-core.tgz"));
1127
1300
  fs.writeFileSync(path.join(build, "driver.mjs"), DRIVER);
1128
1301
  fs.writeFileSync(path.join(build, "entry.sh"), ENTRY);
1129
- fs.writeFileSync(path.join(build, "Dockerfile"), DOCKERFILE);
1130
- log.push(`building runner image ${tag} (first run only)`);
1302
+ // The same text the tag hashed (runnerImageTag), base and all.
1303
+ fs.writeFileSync(path.join(build, "Dockerfile"), runnerDockerfile(base));
1304
+ log.push(`building runner image ${tag} (first run only)${base ? ` on base ${base.full.split("@")[1].slice(7, 19)}` : ""}`);
1131
1305
  const args = [
1132
1306
  "build",
1133
1307
  ...(opts.platform ? ["--platform", opts.platform] : []),
@@ -1382,8 +1556,10 @@ export function heldCores(cpus, isolation, available) {
1382
1556
  /**
1383
1557
  * What crosses into the container as its environment, and how.
1384
1558
  *
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
1559
+ * It crosses as a file the agent's shell sources after the drop (env.sh,
1560
+ * FOL-130); until then it was a docker --env-file, one `KEY=value` per
1561
+ * line, which cannot carry a newline — and what a step sees stays the shape
1562
+ * that file set. @file secrets are multi-line by nature (a PEM key, a cert), so
1387
1563
  * they are staged as files NOW, into the copied-in workspace, and the env
1388
1564
  * carries the container path — the one place a path is stable across the
1389
1565
  * boundary. A plain secret whose value happens to hold a newline gets the
@@ -1573,9 +1749,18 @@ export async function runStepInContainer(args) {
1573
1749
  const jobIn = path.join(staging, "job");
1574
1750
  fs.mkdirSync(jobIn);
1575
1751
  fs.writeFileSync(path.join(jobIn, "input.json"), JSON.stringify(args.input, null, 2));
1752
+ // The account's snapshot key, for root's start-up alone (rootStartSh
1753
+ // moves it out of the agent's reach before the drop) — FOL-129.
1754
+ const snapKey = aptSnapshotKey(args.tenant);
1755
+ if (snapKey)
1756
+ fs.writeFileSync(path.join(jobIn, "snapshot.key"), snapKey, { mode: 0o600 });
1576
1757
  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 });
1758
+ // Files in the job folder, not the container's environment (FOL-130): a
1759
+ // docker --env-file is PID 1's environment, so a secret named LD_PRELOAD
1760
+ // reached the root shell before its first line. The agent's shell sources
1761
+ // env.sh after the drop; root's start-up reads only the proxy's lines.
1762
+ fs.writeFileSync(path.join(jobIn, "env.sh"), stepEnvShell(containerEnv), { mode: 0o600 });
1763
+ fs.writeFileSync(path.join(jobIn, "root-env.sh"), rootEnvShell(containerEnv), { mode: 0o600 });
1579
1764
  const lim = args.limits ?? resolveResources(args.size);
1580
1765
  const cpus = dockerCpus(lim.cpus);
1581
1766
  const flags = [
@@ -1592,7 +1777,6 @@ export async function runStepInContainer(args) {
1592
1777
  // the whole machine from the steps beside it.
1593
1778
  "--memory", dockerMemory(lim.memory),
1594
1779
  ...(cpus ? ["--cpus", cpus] : []),
1595
- "--env-file", envFile,
1596
1780
  ];
1597
1781
  // gVisor (or kata) where the host has it: one env var, because the flag
1598
1782
  // is the same docker invocation everywhere else.
@@ -1645,6 +1829,10 @@ export async function runStepInContainer(args) {
1645
1829
  cp(`${wsIn}/.`, `${containerId}:/workspace`);
1646
1830
  cp(`${libIn}/.`, `${containerId}:/library`);
1647
1831
  cp(`${jobIn}/input.json`, `${containerId}:/opt/runner/job/input.json`);
1832
+ cp(`${jobIn}/env.sh`, `${containerId}:${STEP_ENV_FILE}`);
1833
+ cp(`${jobIn}/root-env.sh`, `${containerId}:${ROOT_ENV_FILE}`);
1834
+ if (snapKey)
1835
+ cp(`${jobIn}/snapshot.key`, `${containerId}:${SNAPSHOT_KEY_FILE}`);
1648
1836
  phases.files = Date.now() - t0;
1649
1837
  // Start attached and read the driver's JSONL. The step timeout gets a
1650
1838
  // backstop out here — a wedged container is killed, not waited on.
@@ -1735,6 +1923,7 @@ export async function runStepInContainer(args) {
1735
1923
  firstOutputMs: firstOutputAt === null ? null : firstOutputAt - t0 - sandboxMs,
1736
1924
  totalMs: Date.now() - t0,
1737
1925
  phases,
1926
+ origin: t0,
1738
1927
  };
1739
1928
  args.emit("info", timingLine(timing));
1740
1929
  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 {};