Run Autohand Code on Cloudflare Containers
Use Cloudflare Containers when you need Worker-routed HTTP control plus a container image that can run a Linux process.
Advanced · 45 min
Provider docs used
This tutorial follows provider documentation for current container image, Wrangler, and routing configuration. Cloudflare facts on this page were checked against these pages on 15 October 2026. Keep them open while you work, because Cloudflare defaults can change.
Cloudflare Containers getting started
developers.cloudflare.com: configure containers from Wrangler with an image, Durable Object binding, and an exports entry.
Container class API
developers.cloudflare.com: defaultPort, sleepAfter, envVars, and startAndWaitForPorts.
Environment variables and secrets
developers.cloudflare.com: pass Worker secrets into the container explicitly and keep them out of the image.
When to use this
Use Cloudflare Containers when a Worker trigger is not enough and you want Cloudflare to run the containerized runner. Containers suit short, stateless, or resumable jobs: container disk is ephemeral, and a container that goes to sleep starts again from the image with a fresh disk. Start with a VPS or Docker host if you need persistent workspaces, large dependency caches, private VPC access, or simple shell debugging.
You need:
- A Cloudflare account on the Workers Paid plan. Container usage is billed only on Workers Paid.
- Docker running locally, because
wrangler deploybuilds and pushes the image from your Dockerfile. - An Autohand API key from Autohand Console.
- A read-only deploy key for the repository you want reviewed.
Step 1: Create the runner container
The container exposes a small HTTP API. The API receives an allowlisted task and starts Autohand Code inside the container. Cloudflare requires images that run on linux/amd64.
FROM node:22-bookworm
RUN apt-get update \
&& apt-get install -y --no-install-recommends git openssh-client ca-certificates build-essential \
&& rm -rf /var/lib/apt/lists/*
RUN npm install -g autohand-cli
WORKDIR /runner
COPY server.mjs /runner/server.mjs
EXPOSE 8787
CMD ["node", "/runner/server.mjs"]
Step 2: Add a minimal runner API
The runner checks the task against an allowlist, refuses a second job while one is running, clones or updates the repository itself, and pipes the recent commits to the agent. Doing the git work in your own code means the agent never needs the deploy key or a shell command, so --restricted has nothing to approve.
// server.mjs
import { createServer } from "node:http";
import { spawn } from "node:child_process";
import { closeSync, existsSync, openSync, writeFileSync } from "node:fs";
const prompts = {
review: "Review the git log and diff on stdin and summarize action items. Do not edit files."
};
const KEY_PATH = "/runner/deploy_key";
const REPO_DIR = "/runner/repo";
const CHANGES_PATH = "/runner/changes.txt";
let running = false;
function run(cmd, args, { env, stdin = "ignore", capture = false }) {
return new Promise((resolve, reject) => {
const child = spawn(cmd, args, { env, stdio: [stdin, capture ? "pipe" : "inherit", "inherit"] });
let output = "";
if (capture) child.stdout.on("data", chunk => { output += chunk; });
child.on("error", reject);
child.on("close", code => (code === 0 ? resolve(output) : reject(new Error(`${cmd} exited with ${code}`))));
});
}
async function runJob(task, repoUrl) {
writeFileSync(KEY_PATH, `${process.env.GIT_DEPLOY_KEY}\n`, { mode: 0o600 });
const gitEnv = {
...process.env,
GIT_SSH_COMMAND: `ssh -i ${KEY_PATH} -o StrictHostKeyChecking=accept-new`
};
if (existsSync(REPO_DIR)) {
await run("git", ["-C", REPO_DIR, "pull", "--ff-only"], { env: gitEnv });
} else {
await run("git", ["clone", repoUrl, REPO_DIR], { env: gitEnv });
}
const changes = await run("git", ["-C", REPO_DIR, "log", "-p", "--since=24.hours", "--max-count=50"], { env: gitEnv, capture: true });
if (!changes.trim()) {
console.log("no commits in the last 24 hours");
return;
}
// The CLI reads piped input from a file or FIFO, not a socket,
// so hand it the log as a file descriptor.
writeFileSync(CHANGES_PATH, changes);
const changesFd = openSync(CHANGES_PATH, "r");
// The agent does not need the deploy key.
const { GIT_DEPLOY_KEY, ...agentEnv } = process.env;
try {
await run("autohand", [
"--bare",
"-p", prompts[task],
"--restricted",
"--max-requests", "40",
"--max-duration", "1500",
"--output-format", "stream-json",
"--path", REPO_DIR
], { env: agentEnv, stdin: changesFd });
} finally {
closeSync(changesFd);
}
}
createServer((req, res) => {
if (req.method === "GET" && req.url === "/status") {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ running }));
return;
}
if (req.method !== "POST") {
res.writeHead(405);
res.end("method not allowed\n");
return;
}
const task = req.headers["x-task"];
const repoUrl = req.headers["x-repo-url"];
if (!Object.hasOwn(prompts, task) || !repoUrl) {
res.writeHead(400);
res.end("unknown task\n");
return;
}
if (running) {
res.writeHead(409);
res.end("a job is already running\n");
return;
}
running = true;
runJob(task, repoUrl)
.catch(err => console.error(err))
.finally(() => { running = false; });
res.writeHead(202);
res.end("queued\n");
}).listen(8787, "0.0.0.0");
The CLI writes stream-json events to stdout, so they land in the container logs. The busy check matters because one container serves one repository, and two overlapping jobs would fight over the same clone and spend credits twice.
--restricted denies any operation that would need approval. --max-requests stops the run after that many model requests, sub-agents included, and --max-duration stops it after that many seconds of wall time. The values above are starting points: tune them for your repository, and keep --max-duration below the sleepAfter window you set in Step 4. --bare also skips hooks, LSP, auto-memory, and automatic AGENTS.md loading, so put any project instructions the review needs in the prompt.
Step 3: Configure Wrangler
Cloudflare Containers use Worker configuration plus a Durable Object class. The image can point at a local Dockerfile or a qualified image reference.
name = "autohand-container-runner"
main = "src/index.js"
compatibility_date = "2026-10-15"
[observability]
enabled = true
[[containers]]
class_name = "AutohandCodeContainer"
image = "./Dockerfile"
instance_type = "standard-1"
max_instances = 5
[[durable_objects.bindings]]
name = "AUTOHAND_CONTAINER"
class_name = "AutohandCodeContainer"
[exports.AutohandCodeContainer]
type = "durable-object"
storage = "sqlite"
As of Cloudflare’s Wrangler configuration docs on 15 October 2026:
instance_typedefaults tolite(1/16 vCPU, 256 MiB memory, 2 GB disk). That is likely too small for Node, git, and a repository clone, so set it on purpose.standard-1gives 1/2 vCPU, 4 GiB memory, and 8 GB disk.max_instancescaps concurrently running container instances and defaults to 20 if you leave it out. Stopped containers do not count toward it.- The
exportsblock is the recommended way to declare the Durable Object class. Older projects use a[[migrations]]block withnew_sqlite_classes, which Cloudflare now calls legacy. A Worker cannot use both.
Step 4: Route requests to containers
Install the helper with npm i @cloudflare/containers. The Worker checks a bearer token, maps a repository name to a URL from its own allowlist, and forwards the request to that repository’s container. The container class passes the secrets the runner needs on every start.
// src/index.js
import { Container, getContainer } from "@cloudflare/containers";
const REPOS = {
"web-app": "git@github.com:your-org/web-app.git"
};
export class AutohandCodeContainer extends Container {
defaultPort = 8787;
sleepAfter = "30m";
constructor(ctx, env) {
super(ctx, env);
// Worker secrets do not reach the container unless you pass them.
this.envVars = {
AUTOHAND_PROVIDER: "autohandai",
AUTOHAND_API_KEY: env.AUTOHAND_API_KEY,
AUTOHAND_AI_API_KEY: env.AUTOHAND_API_KEY,
GIT_DEPLOY_KEY: env.GIT_DEPLOY_KEY
};
}
}
async function authorized(request, token) {
if (!token) return false; // never accept "Bearer undefined"
const encoder = new TextEncoder();
const [given, expected] = await Promise.all([
crypto.subtle.digest("SHA-256", encoder.encode(request.headers.get("authorization") ?? "")),
crypto.subtle.digest("SHA-256", encoder.encode(`Bearer ${token}`))
]);
return crypto.subtle.timingSafeEqual(given, expected);
}
export default {
async fetch(request, env) {
if (!(await authorized(request, env.TRIGGER_TOKEN))) {
return new Response("unauthorized", { status: 401 });
}
const { pathname } = new URL(request.url);
const isStatus = request.method === "GET" && pathname === "/status";
if (request.method !== "POST" && !isStatus) {
return new Response("method not allowed", { status: 405 });
}
const repo = request.headers.get("x-repo");
if (!Object.hasOwn(REPOS, repo)) {
return new Response("unknown repo", { status: 400 });
}
const headers = new Headers(request.headers);
headers.delete("authorization");
headers.set("x-repo-url", REPOS[repo]);
const container = getContainer(env.AUTOHAND_CONTAINER, repo);
return container.fetch(new Request(request, { headers }));
}
};
- Secrets: Worker secrets are not copied into the container automatically. The class sets
envVars, which Cloudflare passes to the container on every start. You can also pass per-start values withcontainer.startAndWaitForPorts({ startOptions: { envVars } }), but those apply only when that call starts the container, so a container already started by another request would run without them. - Token: The
!tokenguard stops the Worker from accepting the literal headerBearer undefinedif you forget to set the secret. Hashing both values beforetimingSafeEqualgives equal-length inputs and avoids leaking the token through timing. - Repository allowlist: Each name passed to
getContaineris its own container instance. The allowlist stops callers from inventing names to start new containers, and the repository URL comes from the Worker, not the caller.
Step 5: Add secrets and deploy
Use Worker secrets for tokens. Keep them out of the Dockerfile and out of build variables, because those end up in the image.
wrangler secret put AUTOHAND_API_KEY
wrangler secret put TRIGGER_TOKEN
wrangler secret put GIT_DEPLOY_KEY < ~/.ssh/autohand_deploy_key
wrangler deploy
Each wrangler secret put prompts for a value or reads it from standard input, as in the deploy key line. Changing a secret deploys a new Worker version, but a container that is already running keeps the values it started with until it stops. On the first deploy, the Worker can go live a few minutes before the container is ready, so expect early requests to fail while Cloudflare provisions it.
Trigger a run:
curl -X POST "https://autohand-container-runner.<your-subdomain>.workers.dev" \
-H "authorization: Bearer $TRIGGER_TOKEN" \
-H "x-repo: web-app" \
-H "x-task: review"
You should get queued. A second request while the job runs returns 409, and a request without the token returns 401. With observability enabled, the container output, including the agent’s stream-json events, appears in the Containers section of the Cloudflare dashboard.
Operations checklist
- Long jobs can be stopped by
sleepAfter. The timer (default10m, set to30mhere) is reset by incoming requests. The Worker returns202straight away, and Cloudflare’s docs do not say that a process running inside the container counts as activity, so a job that outlives the window with no requests can be stopped partway. Keep--max-durationunder the window, or have your caller pollGET /statusthrough the Worker with the sameauthorizationandx-repoheaders; each poll resets the timer. - When Cloudflare stops a container it sends
SIGTERM, waits up to 15 minutes, then sendsSIGKILL. HandleSIGTERMinserver.mjsif you need to log an interrupted job. - Design jobs to be resumable, because a container that sleeps starts again with a fresh disk and must clone the repository again.
- Keep repository clones and dependency caches small unless you intentionally add durable storage elsewhere.
- Use allowlisted tasks instead of arbitrary prompts from public requests.
- Use
max_instancesto cap how many containers run at once, and the runner’s busy check to cap jobs per container. Neither caps total spend;--max-requestsand--max-durationbound each run. - Containers have internet access by default (
enableInternetistrue). Review Cloudflare’s outbound traffic controls if the runner should reach only your git host and Autohand. - Start with the plain Worker trigger tutorial if you already have a VPS or Docker runner.