> Fetch the index of every Tonbo docs page as Markdown at https://tonbo.dev/llms.txt

# Run GitHub Actions jobs

Last updated 16 November 2026

Run your CI on a development Machine: a warm Machine like the one you and your agent work in. Your jobs run in it with your tools already installed, you can SSH in to debug a failed job where it ran, and it sleeps when idle, so compute is charged only while a job runs. Setup takes about five minutes, with nothing to build and no Docker on your computer.

## Set it up {#setup}

Use it on a private repository, or [require approval for workflows from forks](https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-workflow-runs/approving-workflow-runs-from-public-forks): anyone whose pull request runs here runs code on your Machine. Keep the token where step 2 puts it, a Machine secret, never in the image or in `--env`, which every member can read (see [Security](#security) for the rest).

1. [Create a fine-grained personal access token](https://github.com/settings/personal-access-tokens/new) for one repository, with two repository permissions: Administration (read and write) and Webhooks (read and write). Save it in a file, `github-token.txt`.
2. Create the Machine, with the prebuilt image and the token as a Machine secret:

   **CLI**

   ```shell
   tonbo machine create gha-app --image ghcr.io/tonbo-io/actions-runner:2 --shape m-4 --port 8080:public --sleep-after 3600 --env GITHUB_REPOSITORY=you/app --secret-env GITHUB_TOKEN=./github-token.txt --region ap-southeast-1 --wait
   ```

   **API**

   ```shell
   jq -n --rawfile s0 github-token.txt \
     '{"name":"gha-app","image":"ghcr.io/tonbo-io/actions-runner:2","shape":"m-4","region":"ap-southeast-1","ports":[{"port":8080,"access":"public","default":true}],"sleep_after_seconds":3600,"env":{"GITHUB_REPOSITORY":"you/app"}} + {secrets: {GITHUB_TOKEN: {value: $s0, delivery: "env"}}}' \
     | curl -sS -i https://api.tonbo.dev/v1/machines \
     -H "Authorization: Bearer $TONBO_API_KEY" \
     -H "Idempotency-Key: $(uuidgen)" \
     -H "Content-Type: application/json" \
     -d @-
   until curl -sS https://api.tonbo.dev/v1/machines/gha-app -H "Authorization: Bearer $TONBO_API_KEY" \
     | jq -e '.data.state == "active" or .data.state == "failed"' >/dev/null; do sleep 2; done
   ```

   `jq` reads the token into the body’s `secrets`, and the loop reads the Machine until it is `active`, or `failed` with why. The same fields, flag for flag, as the CLI.
3. Name the label in a workflow and push:

   ```yaml
   jobs:
     test:
       runs-on: [self-hosted, tonbo]
       steps:
         - uses: actions/checkout@v4
         - run: make test
   ```

When the Machine starts, it adds a webhook to the repository that points at itself, at `https://gha-app-<account>.tonbo.sh/`, and every queued job with the `tonbo` label wakes it. Logs, results and artifacts appear in GitHub as they do for any runner, and checks on pull requests work the same; SSH is for looking inside the Machine itself. To look at a job while it runs, or before the Machine sleeps again, open a terminal in it with `tonbo ssh gha-app` (see [Connect with SSH](https://tonbo.dev/docs/machines/ssh.md)); checkouts are under `/cache/work`. To keep a failed job’s state for longer, end the job with a step that waits, and connect while it does:

```yaml
      - if: failure()
        run: sleep 1800
```

## How it works {#how}

The image is the official runner image with a webhook receiver, a few hundred lines with no dependencies, as its command. Nothing polls GitHub.

1. At each start, the receiver makes sure the repository has exactly one webhook for [workflow jobs](https://docs.github.com/en/webhooks/webhook-events-and-payloads#workflow_job) at the Machine’s address, creating or updating it, and never touches other webhooks. The Machine learns its address from its own host name. The webhook’s secret is derived from the token and the Machine’s name, so every start computes the same one without storing anything.
2. Each delivery wakes the Machine. The receiver checks its signature (see [GitHub’s check](https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries)), ignores everything but `queued` jobs of your repository that name its label, and answers at once.
3. It asks GitHub for a [just-in-time runner](https://docs.github.com/en/rest/actions/self-hosted-runners#create-configuration-for-a-just-in-time-runner-for-a-repository) and starts it, at most `MAX_RUNNERS` at a time (one by default). The runner takes one job and exits, and the Machine goes back to sleep.

It records each delivery, so a delivery sent again never starts a second runner. Without a Volume the record lasts until the Machine sleeps; with one, for 3 days. It is the pattern of [Receive webhooks](https://tonbo.dev/docs/machines/webhooks.md).

## For a team {#team}

To run without anyone’s personal token, use a GitHub App. In your organization’s developer settings, create a private GitHub App with no webhook of its own and, for runners of one repository, Administration (read and write) and Webhooks (read and write) on the repository; for an organization’s runners, Self-hosted runners and Webhooks (read and write) on the organization, with `GITHUB_ORG` instead of `GITHUB_REPOSITORY`. Install it, note its App ID and generate a private key, saved as `app.pem`. Then create the Machine with the App instead of the token:

**CLI**

```shell
tonbo machine create gha-app --image ghcr.io/tonbo-io/actions-runner:2 --shape m-4 --port 8080:public --sleep-after 3600 --env GITHUB_APP_ID=123456 --env GITHUB_REPOSITORY=you/app --env REGISTER_WEBHOOK=1 --secret-env GITHUB_APP_PRIVATE_KEY=./app.pem --region ap-southeast-1 --wait
```

**API**

```shell
jq -n --rawfile s0 app.pem \
  '{"name":"gha-app","image":"ghcr.io/tonbo-io/actions-runner:2","shape":"m-4","region":"ap-southeast-1","ports":[{"port":8080,"access":"public","default":true}],"sleep_after_seconds":3600,"env":{"GITHUB_APP_ID":"123456","GITHUB_REPOSITORY":"you/app","REGISTER_WEBHOOK":"1"}} + {secrets: {GITHUB_APP_PRIVATE_KEY: {value: $s0, delivery: "env"}}}' \
  | curl -sS -i https://api.tonbo.dev/v1/machines \
  -H "Authorization: Bearer $TONBO_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d @-
until curl -sS https://api.tonbo.dev/v1/machines/gha-app -H "Authorization: Bearer $TONBO_API_KEY" \
  | jq -e '.data.state == "active" or .data.state == "failed"' >/dev/null; do sleep 2; done
```

`REGISTER_WEBHOOK=1` lets the App add its webhook itself, as the token does. Without it, the App needs only the first permission, and you add the webhook yourself, with a secret written without a trailing newline, because the Machine keeps a secret’s bytes as they are:

```shell
openssl rand -hex 32 | tr -d '\n' > webhook-secret.txt
# add --secret-env GITHUB_WEBHOOK_SECRET=./webhook-secret.txt to the create, then:
gh api repos/you/app/hooks -f name=web -F active=true -f 'events[]=workflow_job' \
  -f config[url]=https://gha-app-<account>.tonbo.sh/ -f config[content_type]=json \
  -f "config[secret]=$(cat webhook-secret.txt)"
```

## Configuration {#configuration}

| Variable | Meaning |
| --- | --- |
| `GITHUB_TOKEN` | A fine-grained personal access token for one repository, with Administration and Webhooks: read and write. A Machine secret. Used when GITHUB_APP_ID is not set. |
| `GITHUB_APP_ID` | A GitHub App’s ID. Set it to use the App instead of a token. |
| `GITHUB_APP_PRIVATE_KEY` | The App’s private key, as a Machine secret. Required with an App. |
| `GITHUB_REPOSITORY or GITHUB_ORG` | Exactly one: owner/name for runners of one repository, or an organization for its runners. Events from anywhere else are ignored. |
| `REGISTER_WEBHOOK` | 1 adds and keeps the webhook at each start, 0 leaves it to you; 1 by default with a token, 0 with an App. |
| `GITHUB_WEBHOOK_SECRET` | The webhook’s secret, as a Machine secret. Derived from the token or the App’s key when not set; required with REGISTER_WEBHOOK=0. |
| `PUBLIC_URL` | The address GitHub delivers to; the Machine’s own HTTPS address by default. |
| `RUNNER_LABEL` | The label a job names to run here; tonbo by default. |
| `RUNNER_GROUP_ID` | The runner group of organization runners; 1, the default group, by default. |
| `MAX_RUNNERS` | How many jobs run at once; 1 by default. |
| `CACHE_DIR` | Where caches, work folders and delivery records live; /cache by default, on a Volume mounted there or on the Machine’s own disk. |
| `DOCKER` | 1 starts Docker with its data in CACHE_DIR. Not verified yet (see Limits). |

Secrets are stored with the Machine before its first boot and never returned (see [the rule](https://tonbo.dev/docs/machines/rules/access.md#env)).

## Limits {#limits}

- Jobs run on Linux on 64-bit Arm, like AWS Graviton: a tool a job downloads as a single binary takes its linux-arm64 (aarch64) build.
- Docker inside a Machine is not verified yet, and most jobs need none: put the tools your jobs use in the image (see [Add your tools](#tools)), and the runner uses them directly, with no container layer in between. Only jobs that use containers themselves need Docker (`container:`, service containers, `docker build`, or actions that run as Docker containers). `DOCKER=1` starts it once the image adds `iptables`.
- GitHub [waits 10 seconds](https://docs.github.com/en/webhooks/using-webhooks/best-practices-for-using-webhooks#respond-within-10-seconds) for an answer and does not send a failed delivery again on its own. A wake takes a few seconds, and close to 10 in some regions, so a delivery that wakes the Machine can now and then fail, and its job waits until another runner takes it. Send failed deliveries again from the webhook’s Recent Deliveries, or with the API (see [Redelivering webhooks](https://docs.github.com/en/webhooks/testing-and-troubleshooting-webhooks/redelivering-webhooks)):

```shell
HOOK=<the webhook's id>
gh api "repos/you/app/hooks/$HOOK/deliveries?per_page=100" \
  --jq '.[] | select(.event == "workflow_job" and .action == "queued"
    and (.status_code < 200 or .status_code >= 300)) | .id' |
  while read -r id; do gh api -X POST "repos/you/app/hooks/$HOOK/deliveries/$id/attempts"; done
```

- While a job runs, the receiver keeps a [hold](https://tonbo.dev/docs/machines/holds.md) on the Machine, so a quiet step, such as a `sleep` or a wait on a service, never lets it sleep under the job, and a job may run past its sleep-after time. Between jobs it holds nothing: the Machine stays awake while a request to it is open, and sleeps once idle (see [Sleep, wake and stop](https://tonbo.dev/docs/machines/sleep.md)), so a long `--sleep-after` costs little.
- Fine-grained tokens expire. A new token, set with `tonbo machine secret set gha-app GITHUB_TOKEN --from ./github-token.txt` or `PUT /v1/machines/gha-app/secrets/GITHUB_TOKEN`, changes the webhook’s secret at the next start, so the delivery that wakes the Machine then fails; send it again.
- A runner takes any queued job with its labels, not only the one that started it. A runner whose job was cancelled first takes the next one, or ends when the Machine sleeps.

## Security {#security}

- Use it for private repositories, or [require approval for workflows from forks](https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-workflow-runs/approving-workflow-runs-from-public-forks): anyone whose pull request runs here runs code on your Machine.
- Keep the token a Machine secret, never in the image or in `--env`, which every member can read. The receiver starts each runner as an unprivileged user without sudo or the receiver’s environment, so a job cannot read the token. Docker gives jobs full control of the Machine, and so removes that protection.
- [Scope the token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to one repository with only the two permissions above, which GitHub requires to start a just-in-time runner and to add the webhook.
- Give each repository a Machine of its own, and a Volume of its own once you add one. A job can write anything into the caches, so shared caches would let one repository’s pull request poison another’s.
- The port is public because GitHub cannot send a key of your account; the signature check keeps everyone else out.

## Add your tools {#tools}

The prebuilt image has the runner, `git` and `build-essential`. Jobs run without sudo, so the tools they need go in the image, where every job finds them installed. Build an image of your own from the prebuilt one for `linux/arm64`, push it to a public registry as on [Run your own image](https://tonbo.dev/docs/machines/images.md), and pass it as `--image`:

**Dockerfile**

```text
FROM ghcr.io/tonbo-io/actions-runner:2
RUN apt-get update && apt-get install -y --no-install-recommends python3 \
  && rm -rf /var/lib/apt/lists/*
```

To change the receiver too, build from its own files: the official runner image at a pinned release, with the receiver as its command, run on the Node.js the runner ships.

Dockerfile of the prebuilt image

**Dockerfile**

```text
# The official GitHub Actions runner image, which has a linux/arm64 variant.
# Pinned to a released tag; bump it when GitHub stops accepting the version.
FROM ghcr.io/actions/actions-runner:2.338.0

USER root
# Jobs run as `runner` without sudo, so a job cannot read the receiver's
# secrets: the tools your jobs need go in the image instead.
RUN apt-get update && apt-get install -y --no-install-recommends git build-essential \
  && rm -rf /var/lib/apt/lists/* && gpasswd -d runner sudo
# Docker (DOCKER=1) is not verified on Machines yet; dockerd's bridge needs iptables:
# RUN apt-get update && apt-get install -y --no-install-recommends iptables && rm -rf /var/lib/apt/lists/*

COPY receiver.mjs /opt/receiver/receiver.mjs
EXPOSE 8080
# The runner ships its own Node.js, so the receiver needs nothing more.
CMD ["/home/runner/externals/node24/bin/node", "/opt/receiver/receiver.mjs"]
```

receiver.mjs

**receiver.mjs**

```js
// Starts a just-in-time GitHub Actions runner for each queued job, in a Tonbo
// Machine that sleeps between jobs. A `workflow_job` webhook delivery wakes the
// Machine; this server checks its signature, keeps only `queued` jobs with this
// runner's labels, claims the delivery id in CACHE_DIR so a redelivery never
// starts a second runner, answers 202, then mints a runner configuration and
// runs `run.sh --jitconfig`: one job per runner, at most MAX_RUNNERS at once.
//
// It reaches GitHub with a fine-grained personal access token (GITHUB_TOKEN) or
// a GitHub App (GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY). With the token, each
// start makes sure one repository webhook points at this Machine, with a secret
// derived from the token and the Machine's name, so a fresh boot needs no state.
// It runs as root; the job runs as `runner`, without sudo or this process's
// environment, so it cannot read the token or the App's private key.
// While a job runs, it holds the Machine awake over the Machine's hold socket,
// so a quiet step (a `sleep`, a wait on a service) never lets the Machine
// sleep under a job; between jobs it holds nothing, and the Machine sleeps
// once idle.
import { execFileSync, spawn } from "node:child_process";
import { createHmac, sign, timingSafeEqual } from "node:crypto";
import fs from "node:fs";
import { createServer, request } from "node:http";
import os from "node:os";
import path from "node:path";

const env = process.env;
const log = (event, detail = {}) => console.error(`gha-receiver ${event}`, JSON.stringify(detail));
const need = (name) => {
  if (env[name]) return env[name];
  log("config_missing", { name });
  process.exit(2);
};

const repo = env.GITHUB_REPOSITORY; // owner/name: runners of one repository
const org = env.GITHUB_ORG; // or: runners of an organization
if (!repo === !org) {
  log("config_invalid", { reason: "set exactly one of GITHUB_REPOSITORY and GITHUB_ORG" });
  process.exit(2);
}
const scope = repo ? `/repos/${repo}` : `/orgs/${org}`;
// A GitHub App when GITHUB_APP_ID is set, otherwise a personal access token.
const appId = env.GITHUB_APP_ID;
const privateKey = appId ? need("GITHUB_APP_PRIVATE_KEY") : undefined;
const pat = appId ? undefined : need("GITHUB_TOKEN").trim();
// With a token the receiver adds its own webhook; with an App, only when asked.
const register = (env.REGISTER_WEBHOOK ?? (appId ? "0" : "1")) === "1";
// The kernel's host name is the first label of the Machine's HTTPS name.
const machine = env.TONBO_MACHINE_NAME;
const onMachine = machine && os.hostname().startsWith(`${machine}-`);
const hookUrl = (env.PUBLIC_URL ?? (onMachine ? `https://${os.hostname()}.tonbo.sh` : ""))
  .replace(/\/*$/, "/")
  .replace(/^\/$/, "");
if (register && !hookUrl) need("PUBLIC_URL");
const secret =
  env.GITHUB_WEBHOOK_SECRET ??
  (register
    ? createHmac("sha256", pat ?? privateKey)
        .update(`tonbo-actions-runner/${machine ?? hookUrl}`)
        .digest("hex")
    : need("GITHUB_WEBHOOK_SECRET"));

const label = (env.RUNNER_LABEL ?? "tonbo").toLowerCase();
const labels = ["self-hosted", "linux", "arm64", label];
const maxRunners = Math.max(1, Number(env.MAX_RUNNERS ?? 1));
const cache = env.CACHE_DIR ?? "/cache"; // a Volume, or the Machine's own disk
const docker = env.DOCKER === "1";
const HOME = "/home/runner"; // where the official image installs the runner
const UID = 1001; // the image's `runner` user
const GID = docker ? 123 : 1001; // its `docker` group reaches dockerd's socket

// Deliveries already claimed (root's), and the job's caches. Without a Volume
// they last until the Machine sleeps, so dedup only holds within one boot.
const deliveries = path.join(cache, "deliveries");
const toolCache = path.join(cache, "toolcache");
for (const dir of [deliveries, toolCache, path.join(cache, "xdg"), path.join(cache, "work")]) {
  fs.mkdirSync(dir, { recursive: true });
  if (dir !== deliveries) fs.chownSync(dir, UID, GID);
}
// GitHub redelivers for 3 days; older claims can go.
for (const name of fs.readdirSync(deliveries)) {
  const file = path.join(deliveries, name);
  if (Date.now() - fs.statSync(file).mtimeMs > 3 * 86_400_000) fs.rmSync(file, { force: true });
}
if (docker) {
  spawn("dockerd", ["--data-root", path.join(cache, "docker")], { stdio: "inherit" });
}

// The job sees these and nothing of the receiver's environment.
const runnerEnv = {
  PATH: env.PATH,
  HOME,
  USER: "runner",
  LANG: "C.UTF-8",
  ImageOS: env.ImageOS ?? "ubuntu24",
  RUNNER_MANUALLY_TRAP_SIG: "1",
  ACTIONS_RUNNER_PRINT_LOG_TO_STDOUT: "1",
  RUNNER_TOOL_CACHE: toolCache,
  AGENT_TOOLSDIRECTORY: toolCache,
  XDG_CACHE_HOME: path.join(cache, "xdg"),
};

const b64 = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
function appJwt() {
  const now = Math.floor(Date.now() / 1000);
  const unsigned = `${b64({ alg: "RS256", typ: "JWT" })}.${b64({ iat: now - 60, exp: now + 540, iss: appId })}`;
  return `${unsigned}.${sign("RSA-SHA256", Buffer.from(unsigned), privateKey).toString("base64url")}`;
}

async function github(method, route, token, body) {
  const response = await fetch(`https://api.github.com${route}`, {
    method,
    headers: {
      accept: "application/vnd.github+json",
      authorization: `Bearer ${token}`,
      "user-agent": "tonbo-github-actions-runner",
      "x-github-api-version": "2022-11-28",
      ...(body ? { "content-type": "application/json" } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
    signal: AbortSignal.timeout(15_000),
  });
  if (!response.ok)
    throw new Error(`${method} ${route}: ${response.status} ${await response.text()}`);
  return response.status === 204 ? null : response.json();
}

let installation = { token: "", until: 0 };
async function token() {
  if (pat) return pat;
  if (Date.now() < installation.until) return installation.token;
  const { id } = await github("GET", `${scope}/installation`, appJwt());
  const answer = await github("POST", `/app/installations/${id}/access_tokens`, appJwt());
  installation = { token: answer.token, until: Date.parse(answer.expires_at) - 5 * 60_000 };
  return installation.token;
}

/** Exactly one webhook for workflow jobs at this Machine's URL; others untouched. */
async function ensureWebhook() {
  const same = (url) => String(url ?? "").replace(/\/*$/, "/") === hookUrl;
  const config = { url: hookUrl, content_type: "json", insecure_ssl: "0", secret };
  const hook = { active: true, events: ["workflow_job"], config };
  for (let attempt = 1; ; attempt++) {
    try {
      const auth = await token();
      const ours = (await github("GET", `${scope}/hooks?per_page=100`, auth)).filter((each) =>
        same(each.config?.url),
      );
      const kept = ours[0]
        ? await github("PATCH", `${scope}/hooks/${ours[0].id}`, auth, hook)
        : await github("POST", `${scope}/hooks`, auth, { name: "web", ...hook });
      for (const extra of ours.slice(1)) await github("DELETE", `${scope}/hooks/${extra.id}`, auth);
      return log("webhook_ready", { url: hookUrl, id: kept.id });
    } catch (error) {
      log("webhook_failed", { attempt, error: error.message });
      if (attempt === 3) return;
      await new Promise((resolve) => setTimeout(resolve, attempt * 10_000));
    }
  }
}

/** A runner install of its own for each slot, its work folder in CACHE_DIR. */
function slotDir(slot) {
  const dir = slot === 0 ? HOME : `/opt/runner-${slot}`;
  if (!fs.existsSync(dir)) execFileSync("cp", ["-al", HOME, dir]);
  const work = path.join(cache, "work", String(slot));
  fs.mkdirSync(work, { recursive: true });
  fs.chownSync(work, UID, GID);
  fs.rmSync(path.join(dir, "_work"), { recursive: true, force: true });
  fs.symlinkSync(work, path.join(dir, "_work"));
  return dir;
}

// The hold: renewed every HOLD_EVERY_MS while a runner's Runner.Worker, which
// runs one job, is alive, and released once none is, so it lapses within
// HOLD_SECONDS of a job's end even if the release is lost. Off a Machine, a
// hold call fails and is only logged.
const HOLD_SOCKET = env.TONBO_HOLD_SOCKET ?? "/run/tonbo-hold.sock";
const HOLD_SECONDS = 300;
const HOLD_EVERY_MS = 15_000;
function holdCall(method) {
  const req = request(
    { socketPath: HOLD_SOCKET, method, path: "/holds/actions-job", host: "tonbo" },
    (res) => {
      res.on("data", () => {}); // drain the body
      if (res.statusCode >= 300) log("hold_refused", { method, status: res.statusCode });
    },
  );
  req.on("error", (error) => log("hold_failed", { method, error: error.message }));
  req.end(method === "PUT" ? JSON.stringify({ seconds: HOLD_SECONDS }) : undefined);
}
function jobRunning() {
  for (const pid of fs.readdirSync("/proc")) {
    if (!/^\d+$/.test(pid)) continue;
    try {
      if (fs.readFileSync(`/proc/${pid}/cmdline`, "utf8").includes("Runner.Worker")) return true;
    } catch {
      // The process ended while we looked.
    }
  }
  return false;
}
let held = false;
setInterval(() => {
  const busy = jobRunning();
  if (busy) holdCall("PUT");
  else if (held) holdCall("DELETE");
  held = busy;
}, HOLD_EVERY_MS).unref();

const pending = [];
const free = Array.from({ length: maxRunners }, (_, slot) => maxRunners - 1 - slot);
const children = new Set();
let stopping = false;

function pump() {
  while (!stopping && pending.length > 0 && free.length > 0) launch(pending.shift(), free.pop());
}

async function launch(job, slot) {
  try {
    const { encoded_jit_config: config } = await github(
      "POST",
      `${scope}/actions/runners/generate-jitconfig`,
      await token(),
      {
        name: `tonbo-${job.id}-${Date.now().toString(36)}`,
        runner_group_id: Number(env.RUNNER_GROUP_ID ?? 1),
        labels,
        work_folder: "_work",
      },
    );
    const dir = slotDir(slot);
    log("runner_start", { job: job.id, slot });
    const child = spawn(path.join(dir, "run.sh"), ["--jitconfig", config], {
      cwd: dir,
      uid: UID,
      gid: GID,
      env: runnerEnv,
      stdio: "inherit",
    });
    children.add(child);
    const code = await new Promise((resolve) => child.on("close", resolve).on("error", resolve));
    children.delete(child);
    log("runner_exit", { job: job.id, slot, code });
  } catch (error) {
    // Release the claim, so a redelivery of this event can try again.
    fs.rmSync(path.join(deliveries, job.delivery), { force: true });
    log("runner_failed", { job: job.id, error: error.message });
  } finally {
    free.push(slot);
    if (stopping && children.size === 0) process.exit(0);
    pump();
  }
}

function wanted(event, payload) {
  if (event !== "workflow_job" || payload?.action !== "queued") return false;
  const owner = repo ? payload.repository?.full_name : payload.organization?.login;
  if (owner?.toLowerCase() !== (repo ?? org).toLowerCase()) return false;
  const jobLabels = (payload.workflow_job?.labels ?? []).map((name) => name.toLowerCase());
  return jobLabels.includes(label) && jobLabels.every((name) => labels.includes(name));
}

const server = createServer(async (req, res) => {
  if (req.method !== "POST") return res.writeHead(req.url === "/healthz" ? 200 : 405).end();
  const chunks = [];
  let size = 0;
  for await (const chunk of req) {
    size += chunk.length;
    if (size > 1 << 20) return res.writeHead(413).end();
    chunks.push(chunk);
  }
  const body = Buffer.concat(chunks);
  const sent = Buffer.from(String(req.headers["x-hub-signature-256"] ?? ""));
  const expected = Buffer.from(`sha256=${createHmac("sha256", secret).update(body).digest("hex")}`);
  if (sent.length !== expected.length || !timingSafeEqual(sent, expected)) {
    return res.writeHead(401).end();
  }
  let payload;
  try {
    payload = JSON.parse(body.toString("utf8"));
  } catch {
    return res.writeHead(400).end();
  }
  if (!wanted(req.headers["x-github-event"], payload)) return res.writeHead(204).end();
  const delivery = String(req.headers["x-github-delivery"] ?? "");
  if (!/^[0-9a-f-]{8,64}$/i.test(delivery)) return res.writeHead(400).end();
  try {
    fs.writeFileSync(path.join(deliveries, delivery), "", { flag: "wx" });
  } catch (error) {
    if (error.code === "EEXIST") return res.writeHead(200).end("already started\n");
    log("claim_failed", { delivery, error: error.message });
    return res.writeHead(500).end();
  }
  res.writeHead(202).end("starting a runner\n");
  log("job_queued", { job: payload.workflow_job.id, delivery });
  pending.push({ id: payload.workflow_job.id, delivery });
  pump();
});
server.listen(Number(env.PORT ?? 8080), "0.0.0.0", () => {
  log("listening");
  if (register) ensureWebhook();
});

// A planned stop: let each runner end its job within the stop grace, then exit.
process.on("SIGTERM", () => {
  stopping = true;
  server.close();
  for (const child of children) child.kill("SIGTERM");
  if (children.size === 0) process.exit(0);
});
```

To keep tool caches and checkouts across sleeps, so the next job starts warm, give the Machine a Volume at `/cache`:

**CLI**

```shell
tonbo volume create gha-cache-app --size 50 --region ap-southeast-1
# then add --volume gha-cache-app:/cache to the create
```

**API**

```shell
VOLUME=$(curl -sS https://api.tonbo.dev/v1/volumes \
  -H "Authorization: Bearer $TONBO_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{"name":"gha-cache-app","region":"ap-southeast-1","size_gib":50}' | jq -r .data.id)
# then add --arg volume "$VOLUME" and + {volumes: [{volume: $volume, path: "/cache"}]} to the create's jq
```

Before you rely on it, check it against [Rules for Machines](https://tonbo.dev/docs/machines/rules.md).
