The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
/*
* What a runner host runs at boot, written once for both clouds.
*
* The script is the same shape everywhere, because what it does is the same
* everywhere: install what a box needs, fetch the runner binary, refuse to
* install it unless the checksum matches, and hand it to systemd. Five things
* genuinely differ, and they are the five hooks below — where the host learns
* its own address, how a private registry credential is fetched, what mounts a
* volume, which disk box state is kept on, and what has to be done in the guest
* to reach `/dev/kvm`.
*
* The last one is the reason this file is not simply AWS's script with a couple
* of substitutions. On AWS nested virtualization is an instance attribute and
* the guest needs nothing; on GCP it also needs the guest's KVM device to be
* readable by the account the runner runs as, which is what
* `scripts/deploy/gcp/setup-kvm.sh` has been doing by hand. A shared renderer
* with an explicit hook is what stops that from being a step someone remembers.
*
* One secret is written into this script, deliberately: the registration token.
*
* That is a decision and not an oversight, so it is recorded here rather than
* left for someone to "fix". Everything else a host reads — a private registry
* credential, anything the store marks as an address — still reaches the unit
* through the fetch the `startWrapper` hook renders, and must keep doing so.
*
* The cost is real and known: this script *is* the instance metadata, so the
* token is readable by anything running on the host, and what runs on a runner
* is untrusted code by design. It is readable off the API too, by any caller
* holding no more than `compute.instances.get` — no login required. Anyone
* holding it can speak to the control plane as that runner.
*
* It was accepted to keep the token out of a secret store: the value has to be
* the same one the API seeded the row from, and routing it through a per-cloud
* store adds a resource, a grant and a fetch to the one path that must work on
* a host nobody can log into. If that trade is ever revisited, the machinery is
* already here — deliver the token as an address in `RunnerRequest.secrets` and
* the wrapper fetches it like any other secret.
*/
import { registrySetup, runnerInstallLock, recordRunnerDigest, recordInstalledRunnerVersion } from './runner-registry.ts'
import { fetchVerifiedRunner, type RunnerArtifact } from './runner-binary.ts'
import { kernelDeployment } from './runner-kernel.ts'
import { renderRunnerEnvironment } from './runner-environment.ts'
/**
* Where the unit environment lives on a host.
*
* Named because two things write it: the boot script here, and the OS policy
* in `runner-upgrade.ts` that converges it afterwards. A host created before its
* stage changed domain has no other way to be told — it only ever has the boot
* script it was created with: `metadataStartupScript` is in `ignoreChanges`.
*/
export const RUNNER_ENV_FILE = '/etc/boxlite/runner.env'
/** Where a host keeps box state: the runner's home, and the mount its unit will not start without. */
export const RUNNER_HOME = '/var/lib/boxlite'
/**
* The control-plane address as the unit spells it.
*
* One rule in one place: the boot script writes it and the policy that keeps it
* current compares against it. A second derivation is a host that reads as
* non-compliant forever because the two disagree by a trailing slash.
*/
export const runnerApiUrl = (apiUrl: string): string => `${apiUrl.replace(/\/$/, '')}/api`
/** What one cloud contributes to the boot script. */
export type BootPlatform = {
/** Shell that sets `HOST_IP` to the address the control plane reaches. */
hostAddress: string
/**
* Shell that installs whatever mounts a volume. Different products, same job:
* Mountpoint for Amazon S3 on one cloud, gcsfuse on the other.
*/
installVolumeMount: string
/**
* Shell that makes `/dev/kvm` usable. Empty where the platform already has.
* See the note above: this is the hook that exists for GCP's sake.
*/
prepareKvm: string
/**
* Shell that puts `RUNNER_HOME` on a disk of its own, or empty where box state
* stays on the root disk. Runs before the unit is enabled, and must be safe to
* run at every boot.
*/
prepareHome: string
/**
* Shell that configures host Transparent Huge Pages before the runner starts,
* or omitted where the platform does not converge host THP.
*/
prepareThp?: string
/**
* A start wrapper for cloud credentials and host enrollment when required.
*
* A wrapper rather than a one-time fetch so a `systemctl restart` picks up a
* rotated credential, and fail-closed so a host that cannot read one refuses
* to start rather than running without a secret it was given.
*/
startWrapper: { script: string; path: string } | null
/** `Environment=` lines the unit needs and only this cloud can name. */
unitEnvironment: Record<string, string>
}
export type BootInput = {
/** Where the host registers itself. The `/api` prefix is added here. */
apiUrl: string
/** Where it ships telemetry. */
otlpUrl: string
/** Release candidate or per-commit artifact verified before extracting. */
binary: RunnerArtifact & { identity: string }
/** The region an `s3://` address is read from. Null for a public one. */
region?: string | null
/** The port the runner multiplexes everything onto. */
port: number
/** Values the unit carries beyond what this file decides. */
environment: Record<string, string>
platform: BootPlatform
reservedEnvironment?: readonly string[]
}
/**
* The boot script, base64-encoded the way both clouds want it.
*
* `set -euo pipefail` and the log redirect are first and are not decoration: a
* half-finished bootstrap must not leave a host that looks up and has silently
* skipped the checksum verification.
*/
export const renderRunnerBoot = (input: BootInput): string => {
const { platform } = input
const { BOXLITE_RUNNER_ENV, ...environment } = input.environment
const customEnvironment = renderRunnerEnvironment(BOXLITE_RUNNER_ENV, [
...Object.keys(environment),
...Object.keys(platform.unitEnvironment),
...(input.reservedEnvironment ?? []),
])
const region = input.region ?? null
const execStart = platform.startWrapper ? platform.startWrapper.path : '/usr/local/bin/boxlite-runner'
const unitEnvironment = {
BOXLITE_API_URL: runnerApiUrl(input.apiUrl),
API_VERSION: '2',
API_PORT: String(input.port),
BOXLITE_HOME_DIR: RUNNER_HOME,
OTEL_LOGGING_ENABLED: 'true',
OTEL_TRACING_ENABLED: 'true',
OTEL_EXPORTER_OTLP_ENDPOINT: input.otlpUrl,
...environment,
...platform.unitEnvironment,
}
if (!/^[0-9]+\.[0-9]+\.[0-9]+(?:\+[a-f0-9]{40})?$/.test(input.binary.identity)) {
throw new Error('Invalid Runner boot identity')
}
const script = `#!/bin/bash
exec > /var/log/runner-setup.log 2>&1
# Fail fast and loud: a half-finished bootstrap must not leave a runner that
# looks up but silently skipped the binary download or its checksum check.
set -euo pipefail
# A package manager still holding the lock from the image's own first boot.
while fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1; do sleep 5; done
apt-get update
# nfs-common is the NFSv4.1 client filestore volumes mount with "mount -t nfs";
# the Ubuntu cloud image does not carry it by default, so the boot has to install it.
apt-get install -y curl ca-certificates iproute2 nfs-common
${platform.installVolumeMount}
${platform.prepareKvm}
# A box is a microVM, so a host without /dev/kvm can accept work and fail every
# single request. Refuse to finish the bootstrap instead — an instance that
# never registers is a visible failure; one that registers and cannot start a
# box is a silent one.
[ -e /dev/kvm ] || { echo "FATAL: /dev/kvm is absent; this host cannot run boxes" >&2; exit 1; }
${runnerInstallLock}
${input.binary.release ? registrySetup(input.binary.release) : ''}
${fetchVerifiedRunner(input.binary, 'boot', region)}
tar -xzf /tmp/boxlite-runner.tar.gz -C /usr/local/bin/
rm -f /tmp/boxlite-runner.tar.gz /tmp/boxlite-runner.sha256
chmod +x /usr/local/bin/boxlite-runner
${input.binary.release ? recordRunnerDigest : `installed_identity='${input.binary.identity}'\n${recordInstalledRunnerVersion}`}
${kernelDeployment().install}
${platform.prepareThp ?? ''}
${platform.hostAddress}
${platform.startWrapper?.script ?? ''}
# The unit's settings live in a file rather than in Environment= lines.
#
# One of them — the host's own address — is not known until this script runs,
# and appending it to the unit would land it after [Install], where systemd
# reads it as part of that section and the runner never sees it. A file is also
# what makes a rotated value a rewrite and a restart rather than a redeploy.
mkdir -p -m 750 /etc/boxlite
cat > ${RUNNER_ENV_FILE} << 'RUNNERENV'
${Object.entries(unitEnvironment)
.map(([key, value]) => `${key}=${value}`)
.join('\n')}${customEnvironment.block ? '\n' + customEnvironment.block : ''}
RUNNERENV
printf 'RUNNER_DOMAIN=%s\\n' "$HOST_IP" >> ${RUNNER_ENV_FILE}
chmod 640 ${RUNNER_ENV_FILE}
cat > /etc/systemd/system/boxlite-runner.service << 'UNIT'
[Unit]
Description=BoxLite Runner
After=network.target
# Never on the disk beneath a mount that failed. Where the home is on the root
# filesystem, this names only that mount, which is always there.
RequiresMountsFor=${RUNNER_HOME}
[Service]
Type=simple
ExecStart=${execStart}
EnvironmentFile=${RUNNER_ENV_FILE}
Restart=always
RestartSec=5
# The runner budgets 30s internally to stop its VMs; 60s leaves headroom for
# in-flight handlers and the deferred close.
TimeoutStopSec=60
[Install]
WantedBy=multi-user.target
UNIT
${platform.prepareHome}
mkdir -p ${RUNNER_HOME}
systemctl daemon-reload
systemctl enable boxlite-runner
systemctl start boxlite-runner
echo "Runner setup complete"
`
return Buffer.from(script).toString('base64')
}