Backends (runtimes)¶
For anyone who wants a session's agent to run somewhere other than this machine. After this page you will know what each backend needs, how to point a repository at one, and what changes about tabs, archive, and restore when a session is off-box.
A session's backend decides where its workspace and agent run. Every
backend exposes the same session surface — attach, preview, prompt delivery, the
live PTY stream — so the TUI, CLI, and daemon drive a containerised session much
like a local one. Tab admission follows what each kind needs: shell/process tabs
need a local PTY and process; an off-box session serves them too, in the
workspace, when its agent-server advertises a tab API; a VS Code tab on an
off-box session opens the editor running on the
session's host, rooted at the workspace and relayed through the agent-server
(code-server or openvscode-server must be installed there; af detects it and
never installs it). A metadata-only web tab spawns neither and can be added
to an off-box session (docker, ssh, sandbox, hook) when its target is an external
HTTPS URL, or a loopback address (including --port): the daemon's web-tab proxy
reaches the workspace's own 127.0.0.1:<port> through the agent-server's port
relay over the session's existing connection, so the tab shows the dev server
running inside the sandbox, never a daemon-host port. Plain HTTP external URLs
cannot be framed by the HTTPS web UI. Admitted remote web tabs
can be closed, renamed, and reordered like local web tabs.
| Backend | Where the agent runs | Selected with |
|---|---|---|
local (default) |
a git worktree + tmux on the daemon's own machine | nothing (the default), or backend = "local" |
docker |
a container on the daemon's Docker host | backend = "docker" + docker.image |
ssh |
a remote host over SSH | backend = "ssh" + ssh.host |
sandbox |
whatever the operator's own sandbox.ssh command reaches (free-form ssh: jump hosts, ProxyCommand, bastions) |
backend = "sandbox" + global sandbox.ssh |
hook |
wherever your provisioner scripts put it | backend = "hook" (see Hook backend) |
The operator-owned backend settings use [docker], [ssh], and [sandbox] in
global TOML. Their former flat spellings (docker_mount_agent_credentials,
ssh_host_key_verification, sandbox_ssh, and sandbox_binary) remain permanent aliases for
existing TOML and JSON. When both spellings are present, the grouped value wins,
including explicit false and empty-string values.
Select a backend per-repo in .agent-factory/config.json, or per-session on any
surface — each overrides the repo config for that one session:
- CLI —
af sessions create --backend <name>;af sessions backendsfirst if you want to see which values this repo can actually use. - TUI — press
ctrl+rwhile naming the new session and pick from the list. Its rows come from the daemon, so each one says whether this repo can use that backend; picking one it cannot names the config key to fix. Leaving the field alone (or choosing Repo default) keeps the repo's own setting. - Web — the backend select in the new-session modal, same list, same rule.
A host from your global hosts list is picked the same way and
places the session on that host over ssh: af sessions create --host <name> (or
af sessions send-prompt --create --host <name>, or --host on af tasks add), a
host: <name> row in the TUI's ctrl+r list and the web's backend select, and a
Host field in the task forms. Every surface refuses a name that is not in the
list with the same message, and lists an unusable host with the reason.
af agent-server is a backend, not the web UI
The non-local backends work by running an af agent-server in the remote
workspace — a headless, single-workspace process that a daemon dials and
drives. It serves no frontend: opening its port in a browser gets you a
404 telling you so. The web UI is served by the daemon — running af
starts one on demand, then open http://localhost:8443. See
The web client.
Docker backend¶
With backend = "docker", a session runs entirely inside a container:
- The daemon
docker runs a container from your image, publishing an internal port on a random loopback host port. - It clones the repo (from the repo's
originremote) into/workspacein the container. - It copies the
afbinary into the container and starts anaf agent-serverthere — a headless, single-workspace server over the same bearer-token HTTP/WS protocol the daemon speaks (plain HTTP, no TLS). - The daemon drives that in-container agent-server over
http://127.0.0.1:<port>(a container-published loopback port). Attach, preview, prompts, and the live terminal stream all flow over that one authed connection. - On kill, the container is torn down (
docker rm -f) — no leaked containers.
The container is disposable: durability lives in GitHub (the workspace is a
clone of repo@origin), not in the container filesystem — so archive pushes the
branch and reaps the container, and restore re-provisions a fresh container that
clones the branch back (see Archive and restore).
Configuration¶
{
"backend": "docker",
"docker": {
"image": "my-org/af-runtime:latest",
"run_args": ["--memory", "4g", "-e", "MY_VAR=1"]
}
}
| Key | Required | Description |
|---|---|---|
docker.image |
yes | The container image the session runs in (see requirements below). |
docker.run_args |
no | Extra arguments appended verbatim to docker run (mounts, env, resource limits). |
Letting a containerised agent authenticate is not a docker key — it is the
global-only, operator-owned docker.mount_agent_credentials grant. See
Agent credentials in a container.
The Docker runtime does not copy the daemon's whole environment into the
container. Because repository config selects the image and its binaries, af
does not automatically grant that image the built-in agent, GitHub, proxy, or
CA variables used by local sessions. Only names explicitly listed in the
global session_env_passthrough setting cross this boundary. Docker receives
each as -e NAME, so the value does not appear in the docker command line.
On this default boundary the container-native HOME and PATH remain owned
by the image; the credential-mount grant below re-asserts both. An environment
added through docker.run_args still has to be built in or named in
session_env_passthrough before the agent pane may inherit it.
Treat each Docker pass-through name as a trust grant to the configured image,
and prefer an image pinned by digest. For example, a private GitHub Codex
session using environment-backed credentials may explicitly list
GH_TOKEN and OPENAI_API_KEY; that keeps clone, gh, HTTPS push, and Codex
authentication working after the operator has made that trust decision. If you
use stored credentials instead, mount only the relevant config or
credential-helper resources deliberately with docker.run_args, or set the
global docker.mount_agent_credentials grant (below); host paths and native
keyrings are not implicitly mounted into a container.
Agent credentials in a container¶
Most agents authenticate from a file in the daemon user's home (an OAuth token or an API key on disk), not from an environment variable — so the default-deny env boundary above, on its own, leaves a containerised agent unauthenticated.
The operator (not a repo) opts in by setting the global
docker.mount_agent_credentials:
When it is on, a docker session bind-mounts read-only the credential file for that session's own agent — and only that agent. The mapping is:
| The session's agent | Host file(s) mounted read-only → container path under /root |
|---|---|
| claude | ~/.claude/.credentials.json |
| codex | ~/.codex/auth.json |
| gemini | ~/.gemini/{oauth_creds,gemini-credentials,google_accounts}.json (whichever exist) |
| amp | ~/.local/share/amp/secrets.json (amp's stored API key; if you enabled amp's native keyring storage there is no file, so name AMP_API_KEY in session_env_passthrough instead) |
| opencode | ~/.local/share/opencode/auth.json |
| aider | (none — authenticates via API-key env vars; name it in session_env_passthrough) |
| devin | ~/.config/devin/config.json (no effect unless your image also carries the devin CLI) |
Exactly one row applies per session — the one for the session's resolved agent. A codex session is never handed the Claude token, and vice versa (a docker session's agent is fixed for its life). af resolves the file under the daemon user's real home and mounts it only if it exists, so:
- Minimum surface, per agent. It mounts the credential file, not the whole
config directory: an agent writes state and refreshes its token inside that
directory at runtime, so a read-only whole-dir mount would break it, and some of
those dirs reach gigabytes of history (
~/.codex,~/.local/share/opencode).~/.claude.jsonis deliberately not mounted — it is the config/privacy blob (MCP server tokens, every project path and prompt history, account and machine ids), not the credential;~/.claude/.credentials.jsonis what authenticates. - Read-only. The agent authenticates but cannot refresh or rewrite the host credential (a session-lifetime token still works; the disposable container discards its own writes on kill regardless).
-
SELinux-relabeled, on hosts that need it. On a host running SELinux in enforcing mode — the Fedora, RHEL and CentOS default — the mount is
:ro,zinstead of plain:ro. Without the relabel the container still starts and only the read is denied, which surfaces as a session that is silently unauthenticated rather than as an error.zis the shared label rather thanZ: every concurrent session running that agent mounts the same host file, and the private label would relabel it out from under the others. Note that on such a host this does relabel the credential file itself tocontainer_file_t.af reads
/sys/fs/selinux/enforceto decide. Permissive mode is treated as not needing it — SELinux logs the denial there rather than acting on it, so the read succeeds and your file is left untouched. A host switched to enforcing while sessions are running needs those sessions restarted to pick the label up.The rule is: af relabels unless it can prove the relabel is unnecessary.
zis inert wherever SELinux is not enforcing, while skipping it on an enforcing host costs you a silently unauthenticated session — so the two directions are not worth treating alike, and every uncertain case resolves to relabeling. Concretely, af keeps the relabel when:- it cannot read the SELinux mode at all;
- the Docker endpoint is not local (
DOCKER_HOST/DOCKER_CONTEXTpointing off this machine). Docker resolves and labels a bind source on the daemon host, so this host's SELinux mode describes the wrong machine; - no enforce file is visible but the kernel registers
selinuxfs. This is the af-in-a-container case: with the host's Docker socket mounted, af sees a localunix://endpoint, yetselinuxfsis usually not mounted inside a container — so an absent enforce file there means "af cannot see it", not "the machine has no SELinux"./proc/filesystemsis kernel-global rather than namespaced, so it still describes the machine that will label the mount.
One case af cannot see through: a
unix://socket forwarded to a different kernel (socat, or a VM reached through a local path) is indistinguishable from a local daemon. Docker Desktop is the common instance and its VM does not enforce SELinux, so this is theoretical — but if you forward a socket to an enforcing host, set the mount mode yourself viadocker.run_args.The account mount (below) takes the same decision, for the same reasons — af installs both mounts into the same container on the same engine, so they never disagree. One consequence to know about: an account path containing a
:needs Docker's--mountform, which cannot carry a relabel, so af refuses that combination on a host that needs one. MoveAGENT_FACTORY_HOMEto a path without a colon.
A global, operator-owned grant — and a deliberate partial hole
docker.mount_agent_credentials is global-only: a repository selects the
docker image, but only the operator decides whether that image may see
their credentials. This is enforced by source scoping, not a trust gate —
the key simply is not a repo key, so a cloned .agent-factory/config.json
that sets it hits the standard "global setting, cannot be set per-repo" error
(the same model as session_env_passthrough). Were it repo-settable, a cloned
third-party repo could grant itself the operator's credentials by shipping
backend=docker + its own image + this flag — which is exactly what the
default-deny boundary (#2329) exists to prevent.
When on, it re-exposes one credential file to the configured image — the named exception to the boundary, not a relaxation of it: everything else stays blocked, so containment is partial by design. Turn it on only for images you trust with read access to that agent's credential.
No classified environment name carries a non-operator value into the
agent's exec, and no repo-chosen source picks a program on the way to it.
af classifies every environment name that can substitute for, relocate, or
route the mounted credential — API keys and tokens, inline-config names
like OPENCODE_CONFIG_CONTENT, config roots like CODEX_HOME and
OPENCODE_CONFIG_DIR, endpoints and base URLs, proxies and CA bundles,
HOME/XDG_*, SHELL, GitHub token and SSH-agent names, GH_HOST,
DBUS_SESSION_BUS_ADDRESS, gpg's keyring and agent names, git's config
roots and credential-answer programs (GIT_CONFIG_*, GIT_SSH*/
GIT_ASKPASS/SSH_ASKPASS), git's TLS names (GIT_SSL_*,
GIT_PROXY_SSL_*, GIT_HTTP_PROXY_AUTHMETHOD), editor/pager names,
af's own state and tmux
names (AF_*, AGENT_FACTORY_*, TMUX*), and the endpoint names an
agent's own .env loader can restore after the boundary (gemini's
CODE_ASSIST_* and GOOGLE_*_BASE_URL) — plus the program-choice name
PATH and the loader names, derived from the consumers that read them:
every name in glibc's UNSECURE_ENVVARS (the strip list ld.so applies
to set-user-ID programs — LD_PRELOAD, LD_LIBRARY_PATH, LD_AUDIT,
GCONV_PATH, LOCPATH, NLSPATH, GLIBC_TUNABLES, LD_ORIGIN_PATH,
LD_PROFILE, LD_DEBUG_OUTPUT, TMPDIR, TZDIR, the resolver inputs,
and the rest of the source list verbatim) and the environment-import
names of the shells af invokes inside the container (BASH_ENV, ENV,
SHELLOPTS, BASHOPTS, PS4, and every BASH_FUNC_<name>%% bash
would import as a function definition), for every agent in the mount
table above. The C-library half is glibc's own list — the libc af's
dynamically linked binary and the provisioning programs load — so a
musl image's own secure-mode names (e.g. MUSL_LOCPATH, which loads
catalogs rather than code) are outside it. These boundaries enforce
it:
- At
docker run:docker.run_argsentries naming one are refused before the container starts — includingPATH,LD_PRELOAD,LD_LIBRARY_PATH, andLD_AUDIT, which would otherwise let the repo choose the programs af's in-container steps run and the libraries they load (an audit module loaded byLD_AUDITruns in-process in every dynamically linked program at startup, exactly as a preloaded library does). The rest of the derived set is refused on the same terms: a repoGCONV_PATHloads repo gconv modules into those programs, a repoLOCPATH/NLSPATHfeeds them repo locale archives and message catalogs, a repoLD_DEBUG_OUTPUT/LD_PROFILEmakes them write root-owned files, and on an image whose/bin/shis bash a repoBASH_FUNC_cat%%orSHELLOPTSruns or traces repo code in the root (--user 0:0) provisioning shell — the two shell imports that survive root: bash never readsBASH_ENVwhen invoked assh, and it ignores an inheritedPS4at euid 0, so those two reach af's bash-as-bash and non-root invocations instead (an account shell tab, a session-user exec), plusENV, which interactive shells source. Every credential-classified name the operator did not forward is defined and empty in the container environment — so the image's ownENVand a workspace loader that fills only unset names find it already set to nothing. The path-valued trust names keep that defined-empty shape only inside the container environment — the one hopdocker runcan dominate an imageENVat —SSL_CERT_FILEbecause rustls loads the empty value as a PATH and drops every platform root on it alone (OpenSSL only on the empty FILE+DIR pair), andSSL_CERT_DIRdefended beside it for the older rustls that readSome("")the same way (current releases filter empty entries — the measurement and the version floor are below): af's own provisioning execs unset them for their children, and the agent's exec shim re-asserts each to a platform bundle location that exists (#7889). (Measured: gemini's workspace.envsuppliedGEMINI_API_KEYonly when the name was unset; defined-and-empty survived the.env.)HOMEand theXDG_*roots are re-asserted to the mount's real roots,SHELLto/bin/sh,PATHto the image's ownConfig.EnvPATH,GIT_CONFIG_GLOBAL/GIT_CONFIG_SYSTEMto the locations git would consult under the boundary's own roots (an empty pin there is not neutral — it breaksgit config --global), the program-selector names to working defaults —GIT_SSH/GIT_SSH_COMMANDtossh(empty literally names""as the executable and every SSH transport fails),GIT_ASKPASS/SSH_ASKPASS/EDITOR/VISUALto/bin/false(a program that fails every call — git then falls back to the tty prompt as it does for an unset askpass, but no repository-supplied binary ever answers one), andPAGERto/bin/cat— and, for gemini, whose.envloader fills only unset names but treats a defined-empty endpoint as real —CODE_ASSIST_ENDPOINTand the bundled-transport readGOOGLE_CLOUD_UNIVERSE_DOMAIN(which becomes the telemetry dial host) to their first-party defaults, alongside the other??-family reads the artifact measures — so tmux'sdefault-shell -cchain, af's own execs, the agent's bare executable, and the agent's endpoint choice all resolve through first-party values, never a repo-added one. The names an agent's own dotenv loader can fill are pinned for the same reason the endpoint names are: gemini walks up from the workspace applying<dir>/.gemini/.envand<dir>/.envfill-if-unset, so a checked-in file claims any name af leaves unset. af pins each class defined-and-empty where the measured read is falsy-safe, and a class counts as pinned only when every name the agent's read consults is pinned — a chainA || B || defaultleavesAfree for the.envto claim if onlyBis held. The CA-bundle spellings are falsy-safe for their measured readers — node ignoresNODE_EXTRA_CA_CERTSempty, requests falls throughREQUESTS_CA_BUNDLE=''toCURL_CA_BUNDLE, curl falls fromCURL_CA_BUNDLE=''to its compiled CAfile, codex treatsCODEX_CA_CERTIFICATE=''as unset, grpc-js skipsGRPC_DEFAULT_SSL_ROOTS_FILE_PATH=''— so they keep the plain defined-empty pin.SSL_CERT_FILEis the measured path-valued name — rustls-native-certs reads its empty value as a path and loses every platform root on it alone; OpenSSL's empty FILE slot loads zero CAs into the store yetopenssl verifystill resolves a real root through the default hashed DIR, so OpenSSL's loss needs the empty FILE+DIR pair — the state both pins hold until they resolve (#7922).SSL_CERT_DIRis resolved defensively beside it: an empty hashed dir is falsy-safe for current readers — OpenSSL tolerates it and rustls-native-certs ≥ 0.8.4 filters empty entries — but older rustls readSome("")the same path-valued way, so the pair resolves together rather than rely on every build shipping the filtered version (#7889). Both names stay claimed in the container environment but resolve to a real bundle at the exec boundary below. The claimed set is the checked artifact, not this list. The measured reads — everyprocess.envread in@google/gemini-cli@0.42.0, the CLI's own source and the libraries it bundles, which a source-tree measurement of the CLI alone misses — live ininternal/sessionenv/gemini_bundle_env.go, classified per path and pinned by test. Illustrative links: the auth source isCLOUD_SHELL === "true" || GEMINI_CLI_USE_COMPUTE_ADC === "true"(each compare fails on empty, so the default source stands), the grpc-js proxy chain isgrpc_proxy || https_proxy || http_proxywithno_grpc_proxy || no_proxyas the bypass andGRPC_DEFAULT_SSL_ROOTS_FILE_PATHfeeding the transport'screateSecureContext, the metadata endpoint isGCE_METADATA_IP || GCE_METADATA_HOST || HOST_ADDRESS(empty is falsy on either env link and falls back toHOST_ADDRESS, gcp-metadata's compiled constant169.254.169.254— a module constant, not an env read, so there is no third link to pin), the credential file isGOOGLE_APPLICATION_CREDENTIALS || google_application_credentials, the project is the four-linkGCLOUD_PROJECT || GOOGLE_CLOUD_PROJECT || gcloud_project || google_cloud_project, and the git environment-config namesGIT_CONFIG_COUNTandGIT_CONFIG_PARAMETERS(git parses""as count 0 — making every indexedGIT_CONFIG_KEY_*/GIT_CONFIG_VALUE_*pair inert — and as zero-cpairs). git's own TLS names are classified as a group (#7891) — the names git 2.43 actually reads (GIT_SSL_NO_VERIFY,GIT_SSL_CAINFO,GIT_SSL_CAPATH,GIT_SSL_CERT,GIT_SSL_KEY,GIT_SSL_CERT_TYPE,GIT_SSL_KEY_TYPE,GIT_SSL_CERT_PASSWORD_PROTECTED,GIT_SSL_VERSION,GIT_SSL_CIPHER_LIST, theGIT_PROXY_SSL_*twins,GIT_HTTP_PROXY_AUTHMETHOD, andGIT_TEMPLATE_DIR) are never pinned and never resolved:GIT_SSL_NO_VERIFY=itself disables verification (git reads it by getenv, so=0disables too), an envGIT_SSL_CAINFOoutranks a config-file CA the operator forwarded, and a resolved bundle widens a dir-only forward — so the only safe spelling is absent. The provisioning preamble'senv -iwall drops each one an image ordocker.run_argscould set (below), and every filtered hop simply drops them — while a name the operator forwards with a host value reaches git verbatim. The agent's own git in the pane keeps master's pins and config writes (safe.directory, identity) unchanged — the lockdown scopes to af's own git only, and the residual there is #7528: af's credential helper is persisted into the clone's.git/config, so the agent's own git carries af's credential too; closing that is its own issue. Every pinned or re-asserted name is one the agent-server's exec filter admits, so the boundary survives the hop to the agent process itself.
On an account-scoped gemini session the same classified names are
keep-if-set rather than refused: an operator forward through
session_env_passthrough keeps its value, and anything the operator
did not forward is discarded — pinned defined-and-empty at the pane
and dropped at the exec filter — so a workspace .env, an image
ENV, or a remote login environment cannot claim the proxy, trust
roots, credential or project of a credential-bearing request.
docs/usage-limits.md names each discarded value (the project/quota
chain and lowercase twins, the proxy spellings, the trust-root paths,
CLOUDSDK_CONFIG, the metadata endpoints, the executable-credential
gate, the telemetry auth selector) and the remedy for every one is
the same: name it in session_env_passthrough.
- In af's own docker exec steps: every one names /bin/sh by absolute
path, so the container's PATH — whatever it is — cannot hand af a
repo-written sh to intercept the agent-server launch. Commands
inside those scripts (git, cat, chmod) resolve through the
PATH re-asserted above — the image's own binaries. Each script also
re-execs itself under an ALLOWLISTED environment — env -i with only
the names af keeps — because provisioning execs inherit the raw
container env and a per-name denylist can never be complete (#8014
N6: git 2.43 release builds honor GIT_TEST_FSMONITOR as the
core.fsmonitor hook the moment they read the index, and the
OPENSSL_*/SSLKEYLOGFILE/KRB5_*/CURL_HOME names af's git loads
are library-read, outside git's own variable list). What survives
the wall: PATH and HOME verbatim; af's own pins — LC_ALL,
GIT_TERMINAL_PROMPT, the SSH-transport/askpass selector defaults
(GIT_SSH/GIT_SSH_COMMAND → ssh, GIT_ASKPASS/SSH_ASKPASS →
/bin/false, emitted only while the pair carries no operator claim
— a claimed member passes through and the unclaimed siblings are
simply absent, so no image value outranks the claim); every -e
entry af itself emits for the container — the defined-empty NAME=
pins and blanks (the falsy-safe pins, the account loader's blanks,
the GIT_CONFIG_COUNT= neutralizer, the
GIT_CONFIG_KEY_*/GIT_CONFIG_VALUE_* pair blanks a forwarded
count needs — literal NAME= args, so no ambient spelling rides
them in) and the nonempty NAME=value emissions (the loader's
synthesized twins, the re-asserts, the af-git markers — ambient
passes, since a docker -e dominates the image's ENV and every
af-emitted name is refused to docker.run_args or appended after
it last-wins, ambient is af's value); and every name the operator
forwarded through session_env_passthrough with a host value.
Everything else is absent for af's children: the
program/directory/proxy selectors (GIT_EXEC_PATH, GIT_DIR,
GIT_COMMON_DIR, GIT_WORK_TREE, GIT_INDEX_FILE,
GIT_OBJECT_DIRECTORY, GIT_ALTERNATE_OBJECT_DIRECTORIES,
GIT_QUARANTINE_PATH, GIT_PROXY_COMMAND), the file-write sinks
(every path-valued GIT_TRACE*/GIT_TRACE2* name and
GIT_REDIRECT_STDIN/GIT_REDIRECT_STDOUT/GIT_REDIRECT_STDERR —
a repo -e GIT_TRACE_PACKET=/af-account/x would otherwise plant a
file as the owner of the account mount), the whole GIT_TEST_*
class, the git TLS/env names no defined or resolved value is safe
for, the indexed GIT_CONFIG_* machinery, the image's proxy
names, and the library-read family — all dropped unless the
operator forwards them (the SSL_CERT_FILE/SSL_CERT_DIR pair is
the one deliberate exception, documented below). That shift changes what the
image and the repository can hand af's provisioning git, class
by class (#8017 N13):
- Every
docker execstep now runsenv -i, so the image must ship anenvbinary (coreutils or busybox); without one every provisioning step fails before git runs. LC_ALL=Cis pinned, not ambient — an image locale no longer applies to af's git.- On the account path, an image
ENVGH_TOKEN/GITHUB_TOKENorSSH_AUTH_SOCKno longer reaches the provisioning clone — private and agent-socket clones that relied on the image's environment fail until the operator forwards the name throughsession_env_passthrough, and for the socket mounts it at the host value's path (-v "$SSH_AUTH_SOCK:$SSH_AUTH_SOCK"), since nothing rewrites the value the operator set. LD_LIBRARY_PATHandKRB5CCNAMEdrop on both paths —docker.run_args -ecan still carry them into the container, but the wall strips them from af's git — so an image or repo library path or credential cache no longer applies. The remedy is the same: forward the name and mount the library or cache at the host value's path.- On the account path, an image
GIT_SSH_COMMAND(for example-i deploykey) no longer reaches the agent-server's own fetch or archive push — the selector pinssshunless the operator forwardsGIT_SSH_COMMAND/GIT_SSHthroughsession_env_passthroughwith a host value, andafGitScopedEnvironmentkeeps that forwarded value verbatim for every git af itself runs in the container. For a deploy key: forwardGIT_SSH_COMMANDset to e.g.ssh -i /keys/deployand mount the key into the container at that same path withdocker.run_args -v(ssh.identity_fileonly feeds the remote SSH runtime's login key — nothing hands it to git inside a docker container). - An image
ENVproxy (ENV HTTPS_PROXY=…) no longer reaches af's provisioning git — only asession_env_passthroughforward does.
The agent's panes still receive the image's environment
verbatim. The scripts
then point af's OWN git at config files af created and nothing
else: GIT_CONFIG_NOSYSTEM=1, GIT_CONFIG_GLOBAL at a file af
creates fresh in the session home (only safe.directory written into
it), GIT_CONFIG_SYSTEM/XDG_CONFIG_HOME dropped, and git clone
--template= so no image template writes into the clone's
.git/config (the flag stays off once the operator forwards
GIT_TEMPLATE_DIR, and plain-docker and SSH clones keep the
unflagged argv — only the unclaimed credential boundary suppresses
templates); an AF_GIT_CONFIG marker env carries the same roots
to the agent-server's own fetch/push/worktree git, plus an
AF_GIT_FORWARDED marker listing the bare names the operator
forwarded WITH a host value — af's git admits a trust name only
through that set, so a claimed-but-hostless passthrough entry
cannot deliver the image's own GIT_SSL_NO_VERIFY to the
credentialed fetch and push; af-blanked -e NAME= entries are
admitted by their bare name (the empty value is af's, not the
image's), and a GIT_CONFIG_COUNT whose required pairs did not
all arrive usable is neutralized empty after the filter, the same
pin the container boundary installs. The agent-server's own git
runs the same selector rule the preamble installs — a forwarded
selector keeps the operator's value, an unclaimed member is
dropped, and an unclaimed pair takes af's ssh//bin/false
defaults — so the agent-server's own pre-agent fetch origin
never execs an image's GIT_SSH_COMMAND either (#8002 N1), and
GIT_SSH_VARIANT drops unclaimed beside them. The route-name exemptions are
per-slot: forwarding GIT_CONFIG_GLOBAL/GIT_CONFIG_SYSTEM/
GIT_CONFIG_NOSYSTEM/XDG_CONFIG_HOME with a host value exempts
only that slot — the other slots stay af's, and claiming every
slot lifts the CONFIG lockdown while the marker still rides (it is
what scopes the selectors, #8002 N1). Two claim details follow from git's
own resolution: on the account path an XDG-only claim redirects
GIT_CONFIG_GLOBAL at $XDG_CONFIG_HOME/git/config (a
GIT_CONFIG_GLOBAL export replaces the XDG global too, so af's own
file would shadow the claim — the redirect still suppresses the
image's ~/.gitconfig); on the credential-mount path the
XDG_CONFIG_HOME forward can never deliver — af re-asserts it to
the session home after run_args — so the name is dropped from the
claim set and AF_GIT_FORWARDED entirely, and the XDG slot stays
af's unconditionally (a claim there would redirect into the
image-controlled home). The
provisioning safe.directory write targets $GIT_CONFIG_GLOBAL
after the preamble resolves it — af's file, the claimed XDG file,
or the operator's forwarded global — with its directory created
when absent and the write best-effort since a claimed file may be
read-only or unmounted — plus the agent's own resolved global,
which agentGitConfigFile follows through the same claim and whose
write takes the same shape when the global slot is claimed — while
the lockdown stays active, a defined-empty GIT_CONFIG_GLOBAL
leaves the agent's git with no global file to mark, so that half is
skipped with a warning rather than naming a file the agent ignores
(claiming every route slot lifts the lockdown whole, so
agentGitConfigFile is never called and the original --global
write runs against the empty path instead, with no warning).
An operator-FORWARDED trust name is
not a pin and always passes the wall — the clone needs that CA to
reach a private-CA remote — and it wins over whatever the image
set. The SSL_CERT_FILE/SSL_CERT_DIR pair keeps master's
ambient rule, documented here exactly (#8017 N9): before the
re-exec, a member whose sibling is empty or absent is unset; a
name still defined after that guard passes the wall with its
ambient value verbatim. So on the account path an image ENV
SSL_CERT_FILE/SSL_CERT_DIR pair — or a member beside a
forwarded sibling — still reaches af's git, by design: an image
trust root is free power the image already has (it can rewrite
its own CA store), and dropping it would break corporate-CA
images whose bundle exists only inside the image — a remedy
session_env_passthrough cannot provide, since it forwards a
HOST value. On credential-mount af's own -e NAME= blanks leave
each sibling empty, so both are unset there; an unpaired image
member is unset the same way. What never rides in is a defined-
empty LITERAL NAME= arg — af's own blank pins stay excluded
from the emission leg since a defined-empty CA path is a broken
store to openssl rather than an absence. When both names are
unset openssl reads its compiled platform store, so the image's
own CAs keep working — and an operator-forwarded CA must sit at
the host value's path, since nothing rewrites it.
The container sh -c execs af runs WITHOUT this preamble are inert
by content — each is an af-composed probe or bookkeeping script that
spawns no TLS-reading child (#7895): the account and session-user
id probe and mkdir/chown step strings, the skipped-mount
writability probe, and the mountinfo reads in
backend_docker_account*.go; the staged-payload test/wc -c
check and the write-target mountinfo read in
backend_docker_staging.go, plus that file's throwaway
docker run --entrypoint /bin/sh destination probe (a run, not an
exec, on a container af never provisions); and the banner-poll
cat/kill -0 loop in backend_docker_agentserver.go. The one
bypassing exec that is not inert is the detached af agent-server
launch — the child it spawns IS the agent-server, which re-resolves
its pins at its own startup (next bullet).
- At the exec itself: the pins also reach the in-container agent-server,
whose pane launch re-asserts each one immediately
before the agent execs — after tmux's shell hop or a tmux config file
could have re-set one — defined-and-empty for the falsy-safe classes,
or to the first existing platform trust-store path for
SSL_CERT_FILE/SSL_CERT_DIR — except beside a forwarded sibling,
where the pinned slot keeps its defined-empty claim for the reason
above (#7889). The presence-read git names
are dropped there instead — no defined spelling neutralizes them —
unless the operator forwarded one (#7891); the agent-server re-runs
the pin resolve at startup, gated on exactly the names it received
as --session-env-empty — a session carrying no credential pins
emits none and its other env stays byte-identical (#7895) — while
the git-name drop is the spawned-command env filter rather than
that call, so its non-pane children
(hooks, helpers) never inherit an image's trust claim either.
- On tmux: every tmux invocation the agent-server runs carries
-f /dev/null, so the image's /etc/tmux.conf or a ~/.tmux.conf
cannot pick default-shell, run hooks, or write session environment
either. The one residual is an internal fallback that spawns tmux via
systemd-run --scope without -f; it cannot run inside a container —
its marker variable is filtered out and the cgroup namespace is
private — so it is listed, not relied on.
Two name sets are handled differently from the pins:
- Pane-boundary names are refused, blanked at
docker run, and never pinned at the exec shim.AF_SESSION,AF_SESSION_GEN,AF_HOME,AF_INSTANCE_ID,AF_TESTGUARD_RUN,TMUX, andTMUX_PANEare stamped by af and by tmux at the pane boundary — a defined-empty pin would be re-asserted at the exec shim AFTER tmux installed the real values, erasing the session-membership markers the reaper attributes children by and the pane identity in-pane tools read (--self, Claude Code's tmux detection). They are refused todocker.run_argslike every classified name — a repo value would falsify membership — and instead blanked defined-and-empty atdocker run, afterrun_args: the container environment is what everydocker execchild af starts inherits (the agent-server, the provisioning steps), so an imageENV AF_SESSION_GENorTMUXcannot forge a session marker or pane identity outside the pane. The blanking runs on every docker session — account, credential-mount, and plain alike — because an exec child's container environment does not depend on which grant the session carries, so asession_env_passthroughentry naming any of the seven is refused with an explicit error rather than silently overridden by the blank. The in-pane agent still gets the real values — tmux stamps them per pane over the blanked baseline — and a defined-emptyTMUXis safe because tmux itself treats an empty value as unset (measured on tmux 3.4 and 3.2a), so the baseline cannot trip the nested-session presence check. - Selector precedence groups are claimed as groups. Forwarding any
member of
GIT_SSH/GIT_SSH_COMMAND,GIT_ASKPASS/SSH_ASKPASS, orEDITOR/VISUALthroughsession_env_passthrough— when that member is set in the daemon environment — exempts the whole group from the re-assert, and the unforwarded member is reseated to the operator's forwarded value in the sibling's own grammar:GIT_SSHis a program path whileGIT_SSH_COMMANDis a shell command line, so the path is shell-quoted on its way into the command slot, and a command line that cannot be expressed as a path leavesGIT_SSHat af'ssshdefault. A re-asserted sibling would sit ahead in precedence and silently win, while an image-supplied sibling would route around the operator's program — and a forwarded-but-unset member claims nothing, so its sibling keeps the working re-assert. The same shape as the proxy case pairs (HTTP/HTTPS/ALL/NO_PROXY, either case), where the unforwarded twin is set to the forwarded spelling's value because a defined-empty twin would cancel it in clients that read both.
The operator's escape hatch is unchanged: names listed in the global
session_env_passthrough keep their forwarded value and are never blanked
or refused for the operator's own use — except the pane-boundary names
above, refused with the explicit error described there.
Migration. If a working setup legitimately carried one of these names —
a corporate HTTPS_PROXY, a private CA bundle, a private-cloud
OPENAI_BASE_URL — af now overrides it and logs a WARNING once per
session naming each overridden variable (names only, never values),
whether it was pinned empty or re-asserted to a safe value — an image
EDITOR=vim becoming /bin/false is named, not silent. The warning
fires the moment the container exists — before the clone, git, and
agent-server steps that an overridden name could break — so a session
whose provisioning fails on a blanked proxy or CA still logs the
remedy. The image side is read off the image the container actually
runs — resolved after docker run — not the configured tag's pre-run
metadata, which may name a different image than the one that just
pulled; if it cannot be inspected, the warning says so and covers
docker.run_args names only. A repo-set docker.run_args entry for
one is refused outright with the same remedy in the error. The
unconditionally session-shaped names (the mount's HOME, the XDG_*
roots, SHELL, and PATH — which re-asserts the image's own value)
are part of the mount contract itself and not warned.
One caveat on the git config roots: GIT_CONFIG_GLOBAL points git at
<session home>/.gitconfig, which also makes git skip its
$XDG_CONFIG_HOME/git/config fallback — and /etc/gitconfig is where
a prefix=/usr git reads, not necessarily where a prefix=/usr/local
or brew-installed git reads, so an image's own git configuration may
be ignored on this path.
What still trusts the image and the repo. The pins cover the environment boundary only, and only the classified names. The repo chose the image, so the following hops remain trusted:
- The image's own binaries, libraries, CA store, and system files —
the agent's own code and anything it loads can read the mounted file
directly or redirect where its contents are sent. This includes the
image's
Config.EnvPATH(which af re-asserts as the container'sPATH) and any loader names the image configures — everyLD_PRELOAD/LD_LIBRARY_PATH/LD_AUDIT/GCONV_PATH/BASH_ENVthe image sets is refused todocker.run_argsbut left at the image's own value, because an image can already ship any binary or library it wants on those paths. - Workspace configuration, which is file content, not environment —
an
opencode.json, a.claude/or.gemini/settings file (asettings.jsonenvblock included), or a loader that force-loads rather than fill-if-unset can configure where the agent sends what it read; af does not audit them, and not every agent's config surface has been measured. - af-answered folder-trust prompts. af answers the folder/workspace trust prompts Claude, Codex, and Gemini ask before treating a directory's own settings as authoritative — the workspace is told trusted, so anything those settings then do is inside the same image/repo trust this grant already requires.
- Env names the classification does not cover. A name that neither
substitutes, relocates, nor routes the credential is allowed through;
the per-agent reachable surface is pinned by test, but a name an agent
adds upstream is discovered on review, not by construction. For
gemini the completeness claim is a checked artifact rather than this
paragraph:
internal/sessionenv/gemini_bundle_env.gorecords every environment read measured in@google/gemini-cli@0.42.0, the CLI's own source and the library code it bundles (@grpc/grpc-js,google-auth-library,gcp-metadata,googleapis-common,@google-cloud/logging), each classified on both defended paths or waived with a one-line reason — a read that appears or disappears with a CLI version is a reviewed edit there, pinned by test.GIT_CONFIGalone stays unpinned because git reads a defined-empty value as a real config file path andgit configwould break, so it is documented instead — a loader can still claim it. For an operator-forwardedGIT_CONFIG_COUNT, the indexed pairs it activates are refused todocker.run_args(GIT_CONFIG_KEY_*/GIT_CONFIG_VALUE_*are never the repository's to supply) — the operator's own pairs ridesession_env_passthrough; the image'sConfig.Envpairs remain a repo source the environment boundary cannot enumerate, part of the image trust above. GIT_CONFIG_COUNTis whole. Git treats the count as authoritative and fails fatally when theGIT_CONFIG_KEY_n/GIT_CONFIG_VALUE_npairs it names are not present, so a forward that delivers a live count without its pairs breaks everygitinvocation in the session — including af's own provisioninggit config. af therefore checks the count's completeness where the environment is handed to the session — the only place the count's value is known, since it lives in the tmux server's environment at pane spawn or the daemon's environment a bare-eresolves against — and a half-forward is neutralized on every docker session's-eassembly, account or not: af pins the count defined-empty (git reads it as 0, the same shape an unforwarded count takes) and warns naming the missing indices. A defined-but-emptyGIT_CONFIG_KEY_ncounts as missing: git fails it withempty config keyexactly as it fails an absent one, while a defined-emptyGIT_CONFIG_VALUE_nis a legal empty value. The remedy is to also forward the indexed pair names throughsession_env_passthrough.- ssh's user config follows the passwd home, not
$HOME. OpenSSH reads~/.ssh/configfrom the account'sgetpwuidhome directory, so af'sHOMEre-assertion does not move it — the image controls that file, which is already inside the image trust this grant requires, unless the image user's passwd home is the workspace itself, in which case a repo-committed.ssh/configapplies to every ssh the session runs.
Turn the grant on only for images and repositories you trust to that degree; the credential is what they get.
Image requirements (bring-your-own image)¶
There is no af-published image: you bring your own (Sachin-locked
decision). The af binary is copied in for you at session start, so your image
only needs the workspace tooling:
git— to clone the workspace.tmux— the in-container agent-server drives the agent through tmux.shandsleep— the container is kept alive withsleep, and setup runs throughsh.dd— used to stream the live PTY (present in both busybox and coreutils).cat— reads the agent-server's startup banner, and, for an account-scoped session, the container's own/proc/1/mountinfowhen af verifies the account boundary (#3598). On a credential-mount session it is also the re-assertedPAGER(as/bin/cat).false— on a credential-mount session,/bin/falseis the re-asserted value for the askpass and editor selectors (GIT_ASKPASS,SSH_ASKPASS,EDITOR,VISUAL). Bothfalseandcatdegrade gracefully if absent: git reports the program missing rather than silently running anything else.env— on a credential-mount or account-scoped session, the provisioning scripts that run throughexecSh/execSessionShre-exec underenv -i(trustPathUnpinnedScript) so af's provisioning git runs under an af-owned environment (above); an image withoutenvfails those steps (workspace setup, the root-runchmodprep, git clone/fetch/checkout) before git runs. The other provisioningdocker execs — theidprobe, mkdir/chown prep, mount-table reads, write checks, banner poll — bypass the wall and run withoutenv. A plain session (no--account, no credential mount) bypasses the wall too (trustPathUnpinnedScriptreturns the script unchanged when bothcredentialMountsandspec.Account.Dirare empty), soenvis not required there.stat,mkdir,chown,findandid— af probes the container's default user and prepares a writable HOME and/workspacefor that uid, so a BYO image that sets a non-rootUSERdirective (a common hardening practice) provisions the same way a root-default image does. An account-scoped session probes the mounted account's owner; a session with no--accountprobes the image's defaultUSER(id -u/id -g), and af chowns HOME and/workspaceto that uid as root before provisioning as that user.statis account-only (it reads the mounted directory's owner);idruns on every non-account session, andmkdir/chownrun on an account session or when the probe finds a non-root default user — a root-default image on a non-account session skips the chown entirely, so a host directory bind-mounted at/rootor/workspaceis never re-owned and a HOME set viarun_argsstays in effect. Before chowning, af reads the container's own mount table (/proc/self/mountinfo, viacat,cdandpwd -P) and never lets the recursive chown cross into any mount point at or under HOME — however it was created (-v,--mount,--volumes-from,--tmpfs, an imageVOLUME, an agent-credential mount) — so it neither re-owns the operator's host files (a read-write bind) nor EROFS-aborts on a read-only one.findwalks HOME with that prune list when there is at least one such mount; with none it is a plainchown -R -h. Only a directory whose containing mount is the container's own root filesystem is chowned: if HOME or/workspaceis itself a mount, or lives beneath one (a host bind, a volume, a tmpfs, or a symlinked HOME that resolves into one), af never chowns or creates through it — the mount table cannot say what backs a mount, and a docker "volume" can itself be bind-backed through local-driver options, so no mount-kind carve-out is safe. What happens next depends on the session kind: a non-account session warns that it skipped the chown and proceeds, exactly as it always has; an account session probes the mounted directory for writability as the session's own user — atest -w/test -xshell builtin, run after the permitted rootfs chowns so a just-re-owned ancestor is already traversable — warns and proceeds when it is writable, and otherwise refuses provisioning with an error naming the container mount and a remedy fitted to where the mount came from: for a host bind, chown the host directory to that user or drop the bind fromdocker.run_args; for a named or image volume, chown the volume's content or fix ownership in the image; or drop the mount — rather than surfacing later as the clone's bare "Permission denied". If the mount table cannot be read or understood, provisioning fails with an error naming it rather than chowning blind.chownruns with-hin either form so a symlink the image ships under/rootis re-owned itself, not its target outside HOME. On an account session af additionally refusesdocker.run_argsentries forPATHandSHELL, and for every name that makes ld.so, libc, or a shell af invokes inside the container load or run code — the glibcUNSECURE_ENVVARSlist (LD_PRELOAD/LD_LIBRARY_PATH/LD_AUDIT,GCONV_PATH,LOCPATH,NLSPATH,GLIBC_TUNABLES,LD_ORIGIN_PATH,LD_PROFILE,LD_DEBUG_OUTPUT, and the rest of the source list verbatim) plus the shells' environment-import names (BASH_ENV,ENV,SHELLOPTS,BASHOPTS,PS4, and anyBASH_FUNC_<name>%%) — and for the program-entry selectors the agent's own git and tools run, not af's provisioning clone (GIT_SSH/GIT_SSH_COMMAND/GIT_ASKPASS/SSH_ASKPASS— git's transport and askpass programs the agent's own git execs, while af's provisioning git sits behind itsenv -iwall and sees only the pinned default or an operator-forwarded value;EDITOR/VISUAL/PAGER— the editor and pager the agent's own tools and git spawn, which af's provisioning git never opens or pages — so a repo-chosen value runs repository code inside the container as the owner of/af-accountwhen the agent's own git or tools run it) and for the shared-credential names whose own consumers carry an identity for tools af or the agent runs (GH_TOKEN/GITHUB_TOKEN— the token af's own provisioning git reads for its github.com clone helper and its GitHub Enterprise Cloud (.ghe.com) helper;GH_ENTERPRISE_TOKEN/GITHUB_ENTERPRISE_TOKEN— the token af's own provisioning git reads for its GH_HOST-configured Enterprise Server clone helper;SSH_AUTH_SOCK— the ssh-agent socket both the provisioning transport and the agent's ssh authenticate through;SSH_AGENT_PID— the pid half of the pair, agent-side metadata the agent's own ssh tooling reads alongside the socket, never the provisioning transport;GPG_AGENT_INFO— the agent's gpg socket; andAF_DAEMON_TOKEN— the credential af's in-container clients present to the af daemon; only the token names feed the provisioning-git credential claim, so a repo-supplied value is an identity the operator never claimed), both classes the credential-mount guard refuses above — and for the routing/trust class: endpoint selectors, proxies, and TLS trust roots (ANTHROPIC_BASE_URL,HTTPS_PROXY,SSL_CERT_FILE, …) that would route the account's authenticated traffic to a server the repository controls, the same class the credential-mount guard refuses above — and for a=-valued entry naming a name the operator forwards throughsession_env_passthrough, refused on both docker paths so the repo's value cannot last-wins-override the operator's claim (a bare-e NAMEcarries only the daemon environment's own value — exactly what af's own forwarding delivers — so this forwarded-value refusal does not apply to it; the other classified names are still refused bare, but for the two classes just listed a bare entry the operator already forwards is admitted — it only restates the operator's own daemon value, never a repo-chosen program or credential — while one the operator did not forward keeps the classification refusal) — beforedocker run. They would let the repo choose which program af's in-container provisioning commands resolve to (the mount-tablecatandpwd, thechown, the agent's own executable), which library or gconv module every dynamically linked program loads (anLD_AUDITmodule runs in-process in each of those programs at startup, the same way a preloaded library does), or which code a shell af invokes inside the container runs. The root (--user 0:0) provisioning execs aresh -c, and on an image whose/bin/shis bash the imports that survive root areBASH_FUNC_cat%%— the definition replaces thecatthe mount-table read calls — andSHELLOPTS; bash never readsBASH_ENVwhen invoked asshand ignores an inheritedPS4at euid 0, so those reach af's bash-as-bash and non-root invocations instead (an account shell tab, a session-user exec), whileENVreaches interactive shells. The C-library half is glibc's own list — the libc af's binary and the provisioning programs load — so a musl image's secure-mode names (e.g.MUSL_LOCPATH) are outside it — and the refusal names the remedy: set the value in the image'sENV, or have the operator forward it throughsession_env_passthrough. The image's ownConfig.EnvPATHis then re-asserted afterrun_args, andSHELLis pinned to/bin/sh, so docker's last-wins rule keeps every PATH-resolved command on the image's own binaries and the tmuxdefault-shell -cchain on/bin/shunless the operator forwardedPATHorSHELLthemselves. These entries andcatwere already required and simply missing from this list (#3602 review); busybox and coreutils each provide all of them.- The agent CLIs you intend to run (claude, codex, aider, gemini, …).
- A libc/architecture compatible with the daemon's
afbinary. The copied-in binary is the daemon's own executable, and the release artifactsinstall.shfetches are a plaingo build(cgo on) onubuntu-24.04— i.e. dynamically linked against glibc. So your base must be glibc, and its glibc must be ≥ the daemon build's (ubuntu-24.04is glibc 2.39 today):debian:trixie/ubuntu:24.04work,debian:bookworm(2.36) is too old, and a musl base (alpine) will not run the binary at all. If you rebuild the daemon on a newer-glibc distro, rebuild the image on a matching-or-newer base. (Docker keeps this daemon-binary copy on purpose. The sandbox/ssh transports instead streamagent-factory-linux-<arch>-static.tar.gz— a CGO_ENABLED=0 release artifact that execs on ANY libc, alpine included — so only docker's image needs this glibc rule.)
The container's internal agent-server port is 8000; avoid binding it in your
image.
The image this repo ships¶
This repo carries a starting-point image so a docker-backed session works out of the box — build it with:
It is based on node:22-trixie-slim (glibc 2.41; Node 22 for the codex CLI) and
includes claude and codex — the two agents this repo's sessions use. The
Dockerfile carries commented, one-uncomment install lines for the other agents
(gemini, amp, opencode, aider); devin is not installed because af
forwards it no per-agent credentials. Override the tag with
make session-image SESSION_IMAGE=my-org/af-runtime:latest, then set that in the
repo's docker.image. There is no registry step (bring-your-own, built locally).
A minimal hand-rolled example, if you would rather not use the shipped one:
FROM node:22-trixie-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends git tmux ca-certificates \
&& rm -rf /var/lib/apt/lists/*
RUN npm install -g @anthropic-ai/claude-code @openai/codex
# a musl base (alpine) works only if the daemon's af is a static (CGO_ENABLED=0) build
Operations¶
- List managed containers:
docker ps -a --filter label=af.session. Each also carriesaf.home=<AF home>, the daemon (home) that created it. - Automatic orphan reaping: on daemon startup, af removes any leaked session
container this home created (
af.homematches) that no live or mid-provisioning session owns — the cases where a previous daemon died without reaping, a session record was deleted, or a reap raced a create. It is scoped to this AF home and to the currently-targeted Docker engine, so it never touches another home's or another engine's containers, and a container with noaf.homelabel (created by a pre-upgrade af) is left alone. Kill still reaps synchronously; this is only the backstop for the container that outlived its session, and the docker-staging payload dir a provision killed mid-flight left behind. - Reap a leaked container by hand (should never be needed):
docker rm -f <id>
Requirements on the daemon host¶
- The
dockerCLI onPATHand a reachable Docker daemon. - A local Docker engine —
DOCKER_HOST/DOCKER_CONTEXTpointing at this machine.docker runpublishes the in-container agent-server port on the engine host's loopback (-p 127.0.0.1::8000), and the daemon dials its own loopback to reach it, so a remote engine yields an endpoint this daemon can never connect to. af refuses a remote engine at create time (and reports it unavailable at choose time) rather than provisioning a session that fails later with an opaqueconnection refusedto127.0.0.1. - At most one of
DOCKER_HOSTandDOCKER_CONTEXT, unless both point at the same endpoint. When both are set, the docker CLI dialsDOCKER_HOST, but its reference documentsDOCKER_CONTEXTas the override. af cannot tell which one you meant, so it refuses the combination and names both variables in the error — including in the daemon-startup orphan sweep, which skips its destructive pass rather than guess an engine. Endpoint spellings that provably name one engine still pass: letter case, a scheme's default port, and trailing dots or slashes are normalized before af compares them. With only one of them set, af follows the CLI:DOCKER_HOSTwins over the context selected withdocker context use, andDOCKER_CONTEXTwins over it too. - The repo must have an
originremote the container can clone from (GitHub for a real repo; afile://path + arun_argsbind-mount for a self-contained test).
Testing¶
make backend-docker-roundtrip runs the real end-to-end container round-trips on
a host with Docker: it builds a slim git+tmux image, creates a session on the
docker backend, drives the in-container agent-server over http:///ws:// (input →
stream echo → preview/snapshot/liveness), and asserts the container is reaped on
kill. A second case commits real work on the session branch, archives it
(asserting the branch is pushed to origin and the container reaped), then
restores it (asserting a fresh container clones the branch back, the commit
is present, and the session is drivable again). It skips cleanly where Docker is
unavailable.
These builds resolve nothing against a registry and fetch nothing over the
network. The public base is fetched once per test binary, with retry, then the
local-only base the Dockerfiles build FROM is built from it, installing the
packages every round-trip image needs (git, tmux, bash, openssh-server) through
one hardened apk layer under its own infrastructure budget — so a slow
package mirror cannot cancel a per-test docker build inside its 300s (#7896),
and a base that cannot be obtained at all skips, the same way a missing Docker
daemon does. make registry-free-check proves it, by building the real
Dockerfiles inside a second Docker daemon whose egress and forwarding are
dropped — and re-running this bug's own reproduction each time, so it cannot
pass by measuring a network that was quietly reachable (#2521).
Making docker the default backend for a repo¶
To run a repo's sessions in containers by default, set "backend": "docker" in
its .agent-factory/config.json. This is an operator decision, not a default af
ships — the steps below must be done in order, because the flip does not
degrade gracefully on an unprepared box:
- Build the image:
make session-image(or pointdocker.imageat your own — see Image requirements). - Grant credentials (operator, global):
af config set docker.mount_agent_credentials true, so the containerised agent can authenticate (see Agent credentials in a container). This is global-only on purpose and cannot be set from the repo config. - Set the repo default: put
"backend": "docker"and"docker": {"image": …}in the repo's.agent-factory/config.json.
Only after all three does a new session in that repo come up in a container. A flip with no image built, no reachable Docker daemon, or the grant unset does not fall back to local — it fails session creation with a backend error. So make docker the default only once the box is ready.
Existing sessions are unaffected by the flip. A session's backend is recorded
on its own row (InstanceData.BackendType, written from backend.Type()), and
the daemon reconstructs each session from that stored discriminator on
restart/restore — it never re-reads backend from config after create (which is
consulted only when a session is first created). So a running local session comes
back local regardless of the repo's new default; only new creates read it. This is
pinned by TestFromInstanceData_SandboxBackends, so a future change that made
restore re-resolve from config would fail a test rather than silently reinterpret
someone's session.
SSH backend¶
With backend = "ssh", a session runs on a remote host you reach over SSH — the
built-in, opinionated version of what a hook launch_cmd did by hand:
- The daemon runs
ssh(OpenSSH 7.6 or newer must be on the daemon host's PATH; 7.6 is whatssh.host_key_verification = "accept-new"needs, and the other postures need less), with every setting af owns passed explicitly and no configuration file read at all — reusing your keys and verifying the host key againstknown_hosts. - It creates a fresh per-session directory under
~/.af-sessionson the remote (or under the picked host'sworkspace_root, see configuration.md) and clones the repo (from the repo'soriginremote) intoworkspace/there. - It probes the remote's platform (
uname -s/uname -m), picks anafbinary the host can run —sandbox.binaryif set, else the daemon's own binary on a matching platform, else the sha256-verified release artifact for the remote's platform — and installs it under~/.af-bin/(a per-host cache named by the binary's sha256, so installing one build never rewrites another that a running session links to; the next sessions reuse a matching file). An explicitsandbox.binaryis used even on a platform af publishes no build for. The session directory stays first on the agent'sPATH, soafin the pane is the staged one even when the login profile puts an older install ahead of it. It then runsaf versionon the remote and refuses to launch unless the staged binary reports the daemon's own version. Only then does it start anaf agent-serverbound to127.0.0.1:0(a random loopback port — never exposed on the remote's public interface), behind the same bearer-token protocol (plain HTTP).
The bearer token is per-session: the daemon derives it from a 0600
sandbox-runtime-key in its own AF home plus a per-session nonce, and writes
it to af-server-token (0600) in the session directory, where the remote
af agent-server reads it — beside its own binary, never through a flag or
an environment variable, so nothing the agent-server spawns can inherit it.
The session record persists the agent-server's address and version and the
nonce reference (token_ref) — never the token — so the identity a reattach
or a cleanup needs survives a daemon restart. The reference also rides in the
agent-server's own environment as AF_TOKEN_REF so a host-side
/proc/<pid>/environ probe can bind the live process to the record; it is
the one variable that probe may read, and it never reaches agent or shell
panes.
4. It opens an SSH local-forward tunnel to that remote port and drives the
agent-server through it. The tunnel's local end is a unix-domain socket,
not a TCP port: ssh -L <socket>:<remote> binds a path inside a private
tunnels/ directory in af's home (created mode 0700, verified on the opened
directory — and that directory fd is held for the daemon's life, so
everything af creates under it is created relative to the verified object,
never a re-resolved path), where no other local account can place a listener. Every
connection through the socket proves its acceptor is, or descends from,
af's own ssh spawn before a byte is written, so nothing credential-bearing
can reach an endpoint af did not provision — and a forward that cannot be
established fails the session rather than falling back to a TCP port.
Attach, preview, prompts, and the live terminal stream all flow through the
one tunneled, authed connection (the SSH tunnel encrypts it; the bearer
token still applies end to end inside the tunnel — defense in depth).
5. On kill, the remote af agent-server is stopped, the session directory is
removed, and the tunnel + SSH connection are closed — no leaked process, dir,
or tunnel. The remote host itself is left running (it is your machine, not a
disposable sandbox).
Like docker, the workspace is disposable: durability lives in GitHub (the
workspace is a clone of repo@origin) — archive pushes the branch and reaps the
remote session, and restore re-provisions a fresh remote that clones the branch
back (see Archive and restore).
Configuration¶
{
"backend": "ssh",
"ssh": {
"host": "build-box.example.com",
"user": "af",
"port": 22,
"identity_file": "~/.ssh/id_ed25519",
"known_hosts": "~/.ssh/known_hosts"
}
}
| Key | Required | Description |
|---|---|---|
ssh.host |
yes | The remote host (host or host:port) the session runs on. |
ssh.user |
no | The SSH login user (default: the current OS user). |
ssh.port |
no | The SSH port (default: 22). Give the port either here or as host:port in ssh.host, not both with different values — a conflict is rejected with an error naming both, rather than one silently winning. Identical values are fine. |
ssh.identity_file |
no | Path to the private key for auth. Empty ⇒ ssh-agent (SSH_AUTH_SOCK) and the default ~/.ssh keys are tried. ~ is expanded. At session create af refuses a path it cannot hand to ssh — missing, unreadable, not a regular file, or containing % (ssh expands % tokens such as %h/%d when it loads the key, so af would verify one file while ssh reads another) — rather than silently authenticating with agent or default keys as the wrong identity. |
ssh.known_hosts |
no | Path to the known_hosts file the remote's host key is verified against (default: ~/.ssh/known_hosts). ~ is expanded. |
Your
~/.ssh/configdoes not apply, and never has. af runssshwith-F none, so neither~/.ssh/confignor/etc/ssh/ssh_configis read. Only thessh.*settings above,ssh.host_key_verification, and your keys decide how af connects. This is unchanged behaviour — the backend has always ignoredssh_config— and it is deliberate: this backend's contract is that af enforces the host-key posture in code, and aHostblock could otherwise supplyProxyJump,RemoteCommand,SendEnvorForwardAgentbehaviours that no af setting can override.If you need a bastion, a
ProxyJump, aProxyCommand, or any transport af does not model, usebackend = "sandbox"with a free-formsandbox.sshcommand — that backend exists precisely so you can express the connection yourself, and there yourssh_configandknown_hostsare the whole authority. See the sandbox section below.A
ssh.hostwith several addresses stays on one machine. af runs a separatesshfor each step — the setup commands, the port-forward, and the cleanup — so a name answering with more than one address (a round-robin record, several A records, a dual-stack host) could once put the workspace on one machine while the agent-server or the cleanup landed on another. Nothing looked wrong: every step succeeded against a valid host, and the cleanup then removed the wrong machine's directory and reported success while the real one leaked.af now resolves
ssh.hostonce, when the session is created, and every later step dials that one address. The address is recorded with the session, so the cleanup reaches the same machine even after the daemon restarts.This fixes DNS multiplicity, and only DNS multiplicity. Read the next paragraph before assuming it covers you.
A load-balancer VIP is pinned to one machine too. If
ssh.hostreaches a virtual IP in front of several machines — an L4/TCP load balancer, an AWS NLB, a keepalived/IPVS pair, a Kubernetes service — then pinning the address would not have been enough, because the address is not a machine identity: the balancer picks a backend per TCP connection, and af opens one for every provision command, for the tunnel, and for the cleanup.So af asks the machine who it is. On the first connection it reads
SSH_CONNECTION, which tells it the address that backend accepted the connection on, and pins every later step to that. The address is recorded with the session, so the cleanup reaches the same machine even after the daemon restarts.Two cases where af leaves the pin alone, both logged:
- The backend's own address is not reachable from the daemon — a private address in another VPC, or across a NAT boundary. Pinning it would turn a working host into one where every step fails, so af checks first and keeps the address pin instead.
- The balancer preserves the destination address (direct server return), so the backend reports the VIP itself. There is nothing to re-pin to.
In both cases the session behaves as it did before, and a multi-machine target can still split it — point
ssh.hostat one machine if that matters.Your host key configuration is unaffected, which is the part worth knowing:
sshis still given the name as its destination, soknown_hostsis matched and host certificate principals are checked exactly as before. The pin applies only to the TCP connection, through aProxyCommandthat runsafitself — nothing new to install. An earlier attempt pinned the address as ssh's destination and had to restore the name withHostKeyAlias; that rejected host certificates on every non-default port, and was reverted (#3086).One genuine, if small, reduction comes with it:
CheckHostIPis switched off. OpenSSH disables it whenever aProxyCommandis in use, and it defaulted to on for OpenSSH 7.6–8.4 (upstream turned the default off in 8.5). On those clients a pinned session no longer records or cross-checks the host key against the address inknown_hosts, only against the name. Verification against the name — the guarantee that matters, and the one certificates rely on — is unchanged, and af resolving the address itself and reusing that one address for every step covers the driftCheckHostIPwas watching for. It is a trade, not a free win: ssh's IP cross-check for af's single-resolution guarantee.What this changes for an existing
ssh.host, deliberately: a session is tied to the machine it was created on for its whole life. Before, if that machine went away mid-session, the next step would resolve the name again and might reach a different one and appear to keep working — which is the bug, not a feature: the workspace it needed was on the first machine. Now that step fails against the machine holding the workspace, which is the honest answer. Choosing a machine still tries each address the name answers with, so a host with one dead address and one live one is picked correctly at create time.Nothing else about connecting changes: same
known_hostsmatching, same certificate principals, same keys, samessh_config-is-not-read rule, and no new software to install. There is nothing to migrate — existing sessions created before this keep working and are cleaned up by name exactly as they were.If af cannot resolve the name at create time, or cannot run itself as the relay, it says so in the log and connects by name, exactly as it did before — a host af cannot look up still works. The pin is an improvement on connecting by name, so when it cannot be applied af falls back rather than failing the session.
Which resolver picks the address, and when it matters. af resolves the name the same way
sshdoes — through the system resolver (getaddrinfo, which followsnsswitch.confand so uses LDAP,sssdor mDNS too), not with Go's own. In aCGO_ENABLED=0(static) build Go's resolver skips NSS, so wheregetentis available af reachesgetaddrinfothroughgetent ahosts, dials the answers in order and pins the first that answers.getentis not on macOS, and the official Darwin builds are static, so there af cannot reach the system resolver and connects by name (resolving inssheach step) as it did before. A cgo build dials throughgetaddrinfodirectly — unless Go's pure resolver is forced on instead (thenetgobuild tag, orGODEBUG=netdns=go). af still believes it has the system resolver there (it keys that off thecgobuild tag alone), so it does not fall back togetent: a name only NSS can answer fails the probe, and af connects by name as it did before. Either way, once af pins,sshdoes no resolving at all — the connection is made for it — so every step of a session goes to the same place regardless.af and
sshuse the same resolver, so theknown_hostsentry an earliersshrecorded against that name ordinarily matches the machine af pins — but the same resolver does not guarantee the same address, and that is still where this can bite. A name that hands back different machines on different calls — a rotating round-robin — can pin one the entry does not cover; and even with the same answers, af's probe pins whichever address actually answers the dial (it tries them in order, racing IPv6 and IPv4), so a multi-address name whose addresses hold different host keys can pin one the earliersshdid not land on. The session then fails to start naming the host, nothing runs on the wrong machine, verification refuses it before authenticating, and the earlier advice to pointssh.hostat one machine covers it.
accept-newpins only once it knows the host. On the very first connection to a host there is no entry to check against, soaccept-newwould simply record whatever key the pinned machine presented — and if that were the wrong machine, the session would run there silently and the name would stay bound to it. af therefore does not pin that first connection, and pins normally afterwards.insecureverifies nothing, so it is never pinned. Both cases are logged, and both keep the multi-address exposure this section describes.
Host-key verification is strict by default (secure by default — an unverified
host could MITM the connection and capture the bearer token). The operator can
relax it with the global-only ssh.host_key_verification key:
ssh.host_key_verification |
Behavior |
|---|---|
strict (default) |
Verify against a known_hosts file; refuse an unknown or changed key. Existing behavior — no change. |
accept-new |
Trust-on-first-use: record an unknown host's key on first connect and proceed, but still refuse a changed key. This removes the pre-seed step for ephemeral hosts. |
insecure |
No verification. A man-in-the-middle can capture the session bearer token; use only on a trusted network. |
It is global-only (operator-owned), not part of the repo-settable ssh table:
a repo selects ssh.host, but only the operator decides whether to relax
verification — a repo-settable waiver combined with a repo-settable ssh.host
would be a one-commit man-in-the-middle. Set it with
af config set ssh.host_key_verification accept-new.
accept-new records learned keys in an af-owned store under the AF home
($AGENT_FACTORY_HOME/ssh_known_hosts) by default — never your shared
~/.ssh/known_hosts — or in ssh.known_hosts if you set that explicitly.
If you keep the default strict and need to reach a freshly-provisioned host,
either switch that host to accept-new for the first connect, or add its key to
your known_hosts out of band (ssh-keyscan -H host >> ~/.ssh/known_hosts, or
point ssh.known_hosts at a dedicated file), then create the session.
Legacy cleanup records. The ssh.host_key_verification posture is stored alongside a
killed session's cleanup record, but records written before that field existed
carry no posture, so they are cleaned up strictly. If such a record's host is not
in the strict known_hosts file, no retry can ever complete it — af says so once
and stops retrying, naming the host to add, rather than backing off and retrying
forever. Restarting the daemon re-attempts it, so adding the key is enough to let
the cleanup finish. This applies only to those pre-existing records · every
session created since records its posture and is unaffected.
af's ssh invocation never forwards the daemon's environment. The remote
agent-server and pane use credentials already present for the remote login
account, filtered through the same built-in allowlist. Names in the daemon's
global session_env_passthrough list are sent to the remote as names only; if a
matching variable exists in the remote account's environment, the agent may
inherit it. A local token is never copied to the SSH host implicitly.
Requirements on the remote host¶
- An SSH server you can log into with a key, permitting TCP forwarding
(
AllowTcpForwarding yes— the default on most distros; the runtime reaches the remote agent-server through an SSH local-forward tunnel). git,tmux(3.2 or newer),sh, and a platform af ships a binary for (Linux/Darwin on amd64/arm64; the linux release artifact streamed to a host is a separate staticCGO_ENABLED=0build, so the host's libc is not a constraint there). Theafbinary is installed onto the remote for you — the daemon's own build on a same-platform host, the matching release artifact (agent-factory-linux-<arch>-staticon linux) otherwise, always version-checked against the daemon — so there is nothing to pre-install. For an air-gapped or unbuilt-platform host set the globalsandbox.binarykey to a daemon-localafbuild for that host.- The agent CLIs you intend to run (claude, codex, aider, gemini, …).
- The repo must have an
originremote the remote host can clone from (GitHub for a real repo; afile://path for a self-contained test).
Adding and checking a listed host¶
af hosts add <name> [user@]host[:port] saves the host (the same entry
af config set hosts writes) and probes it in one step; af hosts list,
af hosts check [name] and af hosts remove <name> complete the group. You own
connectivity (a tailnet, a VPN, your ssh key): af opens no tunnel and edits no
ssh config, and a host that is unreachable or missing a tool is still saved, with
the fix printed and a non-zero exit so a script notices. These verbs act on this
machine's host list and daemon, so they refuse a remote --daemon-url.
With --json every outcome is exactly one envelope on stdout and nothing on
stderr. A failure is {"data": null, "error": {...}}. When the host was saved
and a later step did not finish, data carries the entry or the probe result
and error.code says which: mutation_committed (saved, but the probe or the
default pick could not run) or host_not_ready (saved and probed, not ready
yet). The exit code is non-zero in both. Concurrent add, remove and
af config set never lose each other's change: the edit is applied by the
writer as one read-modify-write under the exclusive config file lock, so
concurrent writers wait their turn instead of failing or retrying.
A host in the global hosts list is probed for git, tmux (3.2 or newer) and
gh without creating a session on it. af doctor shows one row per listed host
(ready, blocked with the missing tool, unreachable, or unknown), and the daemon repeats
the probe about every ten minutes, so the host pickers show a recent verdict
instead of "not probed yet". An unreachable host or an unreadable reply records
nothing: it can neither mark a host ready nor clear an earlier blocked verdict.
A create always re-checks the host live.
Operations¶
- Find a session's remote files: they live under
~/.af-sessions/<title>.XXXXXXonssh.host(or under the picked host'sworkspace_rootif set). - Reap a leaked session (should never be needed — kill reaps automatically):
ssh <host> 'pkill -f "agent-server --listen"; rm -rf ~/.af-sessions/<dir>'.
Testing¶
CI runs TestSandboxDaemonE2E (.github/workflows/sandbox-e2e.yml, on every master
push and nightly): a real daemon on a default config drives a backend = "sandbox"
session against a containerized sshd host through its own RPCs (create, prompt,
preview, tab, archive, restore, kill, and a task-fired create).
TestSandboxDisruptionsE2E then hits one live session: a daemon restart (same
agent-server process, roster and conversation, no re-provision) and a killed ssh
connection (reconnects with no operator action). A third case archives the
session, restarts the host container and the daemon, restores, and compares a
stdout-only fingerprint (HEAD, a staged file, an unstaged edit, an untracked file
and an ignored one) taken before the archive with one taken after the restore. make backend-sandbox-e2e runs both tests by hand; it is not a routine
local gate.
make backend-ssh-roundtrip runs the real end-to-end SSH round-trips on a host
with Docker: it stands up a throwaway sshd+git+tmux container as the ssh target
(no external host, no dependency on the box's own sshd), creates a session on the
ssh backend pointing at it, drives the remote agent-server over the ssh-tunneled
http:///ws:// (input → stream echo → preview/snapshot/liveness), and asserts the remote
process is reaped + the session dir removed + the tunnel closed on kill. A second
case commits real work, archives it (branch pushed to origin, remote
sandbox reaped), then restores it (a fresh remote clones the branch back, the
commit is present, the session is drivable) — the identical push/pull-branch
flow, over ssh. It skips cleanly where Docker is unavailable.
Sandbox backend¶
backend = "sandbox" reaches the target through your own ssh invocation. The
global sandbox.ssh key holds a free-form command line — whatever already works
in your terminal, including a jump host, a ProxyCommand, a bastion, or any flag
backend = "ssh" does not model — and af runs the same provision, tunnel, and
cleanup steps over it. Your ssh_config, known_hosts, and host-key posture are
the whole authority here; af adds none of its own. It is global-only and
operator-owned, because af executes it on the daemon host (see
Configuration). The remote af binary is staged exactly as
the ssh backend stages it — platform-probed, cached under
~/.af-bin/, sha256- and version-verified — and the same global-only
sandbox.binary override applies.
Connection sharing (
ControlMaster). YourControlMasterandControlPersistsettings apply to the setup and cleanup steps, which reuse a master when one is running. The port-forward never shares a connection: af runs it with-o ControlMaster=no -S none, which outranks any control path in your command orssh_config. A shared forward would live in your master, where af could neither see it fail nor close it when the session ends. So the forward logs in on its own each time af connects it, and it has to authenticate without a prompt (no MFA push or code, no key passphrase outside an agent) even when your other ssh sessions to that host reuse a master. If it cannot, provisioning fails with "the ssh tunnel … never started listening", followed by the last line the tunnel's ssh wrote.Flags af appends to the port-forward. A
sandbox.sshthat wrapssshhas to pass these through to it:-o(ExitOnForwardFailure,ServerAliveInterval,ServerAliveCountMax,ControlMaster,StreamLocalBindUnlink,StreamLocalBindMask),-S,-N,-L, and-Rwhen the session has a callback. A wrapper that rejects one of them fails every port-forward the same way. The setup and cleanup steps add only the remote command. The-Lforward's local end is a unix-domain socket (-L <socket-path>:<host>:<port>), not a TCP port — an OpenSSH client that cannot bind one fails the session with its own error; af has no TCP fallback.Known limitation: af cannot pin a
sandbox.sshtarget to one machine. af runs a separate invocation of your command for each step — the setup commands, the port-forward, and the cleanup. If it reaches a name with several addresses (a round-robin record, a load balancer, a dual-stack host), each invocation resolves independently, so the workspace can end up on one machine while the agent-server or the cleanup lands on another. Nothing looks wrong: every step succeeds against a valid host, and the cleanup then removes the wrong machine's directory and reports success while the real one leaks.
backend = "ssh"no longer has this problem because af composes that command and knows which token is the host.sandbox.sshis your command, and af cannot know which of its words is a hostname — an argument to-o, a jump-host spec, a wrapper's own flag, or the target — so there is nothing it can safely substitute. Guessing would silently rewrite the command you asked for.Two workarounds, both under your control:
- Point the command at a single machine — a literal address, or a name with one address. This is the simplest fix and needs no other change.
- Pin it yourself, the same way af does for
backend = "ssh": keep the name as ssh's destination soknown_hostsand certificate principals still match, and put the address in aProxyCommand— for examplessh -o ProxyCommand='nc 198.51.100.8 22' build-box.example.com. Do not pin by making the address the destination: that forces aHostKeyAlias, and no alias value satisfies both a plain[name]:portentry and a certificate principal.The
sandbox.sshhalf was closed as won't-fix in #3086 (2026-08-11): af cannot know which word of your command is the host, so the two workarounds above are the supported answer.
Operator config on the sandbox¶
The daemon resolves your policy once and writes it to af-policy.json beside the
session (docker: /etc/af-policy.json); the sandbox's af agent-server reads that
file and nothing else. It never reads or creates ~/.agent-factory/config.toml on
the host. The file carries global_agent_skills, worktree_root, branch_prefix,
session_env_passthrough, the program overrides you wrote, and the repo's
post_worktree_commands as the daemon sees them — uncommitted .agent-factory
edits and hooks saved in the TUI included. It never carries sandbox.ssh, hosts,
move_cmd or accounts.
Inspect a sandbox session's work¶
The agent's work lives in the sandbox's workspace, not on the daemon host, so
git status in your own checkout shows nothing. You do not need ssh to the host
to look at it, or to hand the agent something: every client (TUI, web, phone,
af against a remote daemon) opens the same tabs a local session has, and they
run in the workspace.
- Status and diff. Open a shell tab —
af sessions tab-create <title> --kind shell, the TUI's new-tab key, or the web's Terminal button — and rungit statusandgit diff. It is the agent's own workspace, so the branch and uncommitted changes are the agent's. The shell is listed once the sandbox's agent-server serves the tab API; against one that does not, the picker says so instead of creating a tab. - Browse and edit files. Open a VS Code tab —
af sessions tab-create <title> --kind vscode. The editor runs on the host, rooted at the workspace, and the daemon relays it. The host needscode-serveroropenvscode-server; af detects one and does not install it, and a missing one shows the install hint in the tab. See VS Code tabs. - Hand the agent a file. Put the file in the workspace — drag it into the VS
Code explorer, or paste its contents into a shell tab (
cat > notes.md) — then tell the agent where it is withaf sessions send-prompt <title> "read notes.md". The agent sees what is on disk in the workspace; there is no separate upload channel.
An archived sandbox that was archived without pushing keeps its workspace on the host (see Archive and restore): there is no live agent to ask, so read the files from the host, or restore the session to get the tabs back.
Hook backend (bring-your-own-provisioner)¶
backend = "hook" is the escape hatch for infrastructure the built-in docker
and ssh runtimes don't model — Kubernetes, Modal, Daytona, a bastion with
exotic auth, a bespoke orchestrator. Instead of an opinionated built-in, you
provide the provisioning: two shell scripts that stand the workspace up and tear
it down.
Since #1592 Phase 4 PR7 the hook backend follows the same
provision-and-expose contract as docker/ssh. Your launch_cmd clones the
repo on your infra, starts an af agent-server there, and echoes that
server's authed endpoint ({url, token}); the daemon then
drives the session over that ws:// stream — so a hook session matches a local,
docker, or ssh one on attach, type, resize, preview, archive/restore, and kill.
Like the other off-box backends it admits web tabs (external HTTPS, or loopback via the port relay). Shell and process tabs are admitted when the af agent-server your launch_cmd starts advertises tab-api (a current build does): they then run on the session's host, with the daemon keeping a roster row for each; an older agent-server without tab-api keeps the refusal, since those kinds would need a daemon-side worktree. A VS Code tab opens the editor on the session's host.
{
"backend": "hook",
"remote_hooks": {
"launch_cmd": "./.agent-factory/hooks/launch.sh",
"delete_cmd": "./.agent-factory/hooks/delete.sh"
}
}
The mechanics of launch_cmd (its arguments, the JSON endpoint it must echo,
how to start an af agent-server on your infra), delete_cmd, session-name
slugging, and af doctor validation live in the dedicated guide — see
Remote hooks. This is intentionally the built-in ssh
runtime done by hand: if plain SSH-to-a-host covers your case, prefer ssh
(zero scripting); reach for hook only when it doesn't.
Migrating from the old remote_hooks contract¶
PR7 is a breaking, clean-break change. The old hook contract — launch_cmd
returning a session id, plus list_cmd/attach_cmd/terminal_cmd for
enumeration, terminal proxying, and preview capture — has been removed;
launch_cmd now returns an af agent-server endpoint and the only other script
is delete_cmd. A config that still sets a removed key is rejected with an error
pointing at the guide.
The migration is mechanical (your launch_cmd gains an af agent-server start
and echoes its URL). Rather than duplicate it here, follow the copy-pasteable
recipe in
Remote hooks → Migrating from the old contract.
Moving a live session to a sandbox (move script)¶
Status: the building blocks (worktree snapshot, move-script contract, all-or-nothing orchestration) live in the
movepackage. Theaf sessions move <title> --to <host>command is not wired yet. The global-onlymove_cmdsetting exists (a checked-in value is a load error) but nothing reads it yet, so nothing here is user-invokable today; this section is the contract the script will run under.
A move seeds the sandbox workspace from a snapshot of the local worktree — the
branch history plus every uncommitted and untracked file — rather than a fresh
clone. .gitignored files are not carried; the operator's move script copies
them. The script runs on the daemon box, never from repository config.
- stdin: a JSON object with
session_id,title,branch,source_worktree,host,dest_workspaceand (when scoped)account. - env:
AF_SSH— the ssh command without the destination (options only);AF_SSH_DEST— the destination (user@hostor an ssh alias);AF_SSH_FULL— the complete command including the destination. Sorsync -e "$AF_SSH" file "$AF_SSH_DEST:dir/"andsh -c "$AF_SSH \"\$@\"" af-ssh "$AF_SSH_DEST" 'cmd'reach the same machine af does. The variables are shell command lines that may contain quoted options (aProxyCommandwith spaces), so never expand them unquoted: run them throughsh -cwith positional arguments, asexamples/move-script/move.shdoes. The same three values are in the JSON asssh,ssh_destandssh_full. A free-formsandbox.sshcommand already embeds its host and af cannot split it, so thereAF_SSHandAF_SSH_DESTare empty and onlyAF_SSH_FULLis set: runsh -c "$AF_SSH_FULL \"\$@\"" af-ssh-full 'cmd'and, instead ofrsync -e, pipe tar:tar -C src -c . | sh -c "$AF_SSH_FULL \"\$@\"" af-ssh-full 'tar -C dir -x'. - exit:
0continues; anything else aborts. Any failure before the session row switches leaves the local session running exactly as before and reaps the half-built sandbox workspace.
See examples/move-script/move.sh for a documented example.
Session setup hook (setup_commands)¶
A repo's setup_commands run on the daemon's machine, in the session's
source checkout, after provisioning has established the session's transport —
ssh route, agent-server, auth — and before post_worktree_commands and the
agent start (#6667). Local sessions run the same script with a local
destination and no ssh variables.
- env:
AF_SETUP_SESSION_ID,AF_SETUP_SESSION,AF_SETUP_SOURCE(the source checkout — also the working directory),AF_SETUP_MODE(local|remote),AF_SETUP_HOST(the picked host name, when set), andAF_SETUP_DEST— a payload staging dir whose contents af copies into the fresh worktree before hooks run. For a remote session with an ssh route it is a path ON THE HOST, created through the session's own connection; reach it through the route below rather than assuming a filesystem you share. When NOAF_SSHroute is exported — every local session, and an off-box runtime with no ssh transport such asbackend = "docker"— it is a daemon-local path af transports itself, so plaincp/mkdiragainst it is always safe. - ssh route: the same
AF_SSH/AF_SSH_DEST/AF_SSH_FULLcontractmove_cmduses — the session's own connection, for host commands andrsync -ealike. Only an af-composed transport (backend = "ssh") earns theAF_SSH/AF_SSH_DESTsplit; a free-formsandbox.sshcommand setsAF_SSH_FULLalone, and a session with no ssh transport (local, docker, hook) sets none — for docker, af copies the daemon-localAF_SETUP_DESTinto the container once the script finishes. See the move-script contract above for the quoting idioms — the variables are shell command lines, never expand them unquoted. - failure: a failing entry does not block the session. It is recorded on
the session row as
af setup hook failed: <entry>: <status>— on every surface like the callback notice — with the full output retained in a hook log the note names. - confinement: the script is operator-controlled and is NOT confined by
af on the remote host — whatever the new machine needs, it can do. Keep
examples/hooks/session-setup.sh's discipline (writes only intoAF_SETUP_DESTandHOME) unless you mean to change the host.
See examples/hooks/session-setup.sh for a documented example covering
.env* copies, selected uncommitted files, and a host command.
Session-scoped account sync (listed hosts)¶
Status:
--accountanddefault_accountsare admitted on an ssh session placed on a listed host (W7.4). On any other target an explicit--accountis refused at admission with the remedy, and a default account is not applied.
On a host in the global host list ([hosts.<name>]), af copies the session's
selected account into that session's own scope — <session dir>/account on the
host — and points the agent at it with the agent's own variable (CLAUDE_CONFIG_DIR,
CODEX_HOME or GEMINI_CLI_HOME). It never writes the remote user's global agent
config, so the host's own login is neither read nor replaced.
- Only credential files travel (claude
.credentials.json, codexauth.json, gemini's OAuth files) — not history, settings or skills (af's ownagent-factoryskill is the exception: it rides the swap archive for codex and gemini when the session's provisioned policy snapshot grantsglobal_agent_skills— a later live grant or revocation is not what the swap acts on, since a swap does not refresh that snapshot). They are sent over the ssh session's stdin as an archive, so no secret appears in a command line, a script or a log. - Only to a listed host. The licence to send credentials is the host-list
entry, which only the operator writes. A target a repository named (its
[ssh]section) or a free-formsandbox.sshcommand is refused before anything is sent. - The licence is checked at every send, against the entry as it is then. Before
credentials are sent (at create, at restore, and at an account handoff or limit
failover) af compares where the session's connection logs in with what
[hosts.<name>]says now: itshost,portanduser. If the entry was removed or now names another machine, port or user, nothing is sent and the refusal names the edit that restores it. Three spellings compare equal: letter case in the host name, port 22 written out, and auserthat is the login ssh would use anyway. A trailing dot on any name is a different spelling and refuses (box1.example.is notbox1.example), because whether the two name one machine depends on the resolver's settings, which af does not control. Changingidentity_file,host_key_verificationorworkspace_rootdoes not refuse. Reading credentials back and removing them at teardown still works after an entry is removed, so they can always be taken off a host. The comparison is on the entry's text, not on a resolved address: if DNS re-points a name while its entry stays unchanged, af does not detect it, and a running session keeps using the address it was provisioned on. - Refreshes are written back — as a versioned compare-and-swap from a bounded stream. af remembers the version (a content digest) of each credential file it synced into the session. A file the agent did not change is never written back, and a changed one replaces the registry copy only while the registry still holds the version this session synced in: if another session on the same account refreshed it first, or the account was removed, the write is skipped and logged, so a stale snapshot can never overwrite a fresher one. The host is untrusted, so its archive is read under a hard byte limit while it streams — the command is killed when the limit is crossed — and a truncated, oversized or malformed archive is refused whole. The registry is replaced ONLY from a fully validated archive: the host command's exit status is tar's own (a file that shrank while it was read fails the read), the archive must close with tar's end-of-archive marker, hold each allowlisted file exactly once with a size matching its header, and carry no empty or NUL-padded content; any failure keeps the existing credentials. The byte bound is tar's own arithmetic, so a credential at the size cap is accepted. Replacement is atomic, mode 0600, credential files only. Teardown writes back one last time, then removes the scope. A refresh that loses the race stays on the host and is discarded with the session; fan-out to live sessions is not built yet.
handoff --accountand limit failover work on a listed host. The new account is staged beside the live scope while the old agent still runs; the agent-server then stops the agent, moves the old scope aside, moves the new one into place and starts the agent again, so the old agent never writes into the new account's files. The old account is written back (the same compare-and-swap) and removed. The agent keeps its identity environment from launch, so the swap is within the same agent — a cross-agent--towith--accountis refused. The replacement starts a fresh conversation (a transcript lives in the old account's store) and is told so, with the session's task. Every refusal (an unlisted host, an unattributed command, an account of another agent, an older sandbox without the route, or a session already fenced by an earlier indeterminate operation) happens before anything is stopped or staged. When the agent-server advertisesaccount-swap-scoped-stagethe stage lands at a path unique to the swap (account.next.<swap-id>), so an out-of-order stager can never produce the directory a still-queued request's rename will consume; an agent-server that predates the feature still swaps through the sharedaccount.nextspelling, and one whose feature set cannot be read is refused rather than staged at a path its rename may not look at — the swap-id marker check at rename time is defence in depth under either. Before the request crosses to the host, the session row durably records the minted swap id as in flight; the record itself fences every lifecycle gate — a further swap, recovery, reprovision — and is written to disk so an older daemon sees the same row as startup-unknown and leaves it inert rather than silently unfencing it. A daemon that died while the request was queued or its response was in transit therefore reloads a fenced row that knows WHICH swap to ask about, and reconciles that id on reattach before anything binds, provisions, launches, or is admitted. A failure inside the host puts the old scope back, and the stage — the new account's credentials — is removed through the agent-server's serialized discard route where the server offers it, or an ordered remote cleanup where a request can provably no longer be in flight. Stages no live record names — one a dead daemon left before its record landed, or one an older build left — are swept when the session reattaches after a restart, through the same serialized discard, which removes a stage only when its marker names the swap being discarded or it carries no marker (#7799); on an agent-server too old foraccount-swap-discardthey are left for teardown rather than removed unordered. If the swap's own response is lost, af reconciles the session's durable record from the agent-server's terminal status under the swap's minted id: a status naming an earlier swap (or an anonymous pre-identity record) never proves this swap, so the staged scope is discarded on the server — serialized with the swap itself — and the status is re-read once. A committed answer lands the swap with an unconfirmed start; a definite refusal or a rolled-back status leaves the old account live; anything else fences the session as startup-unknown — relaunch, reprovision, recovery, archive, and any further swap are refused until a daemon restart re-runs the same reconcile on the live agent-server, or the row is removed withaf sessions kill, which the fence always admits. Those are the only two exits: no operator verb lifts the fence, pending the owner's decision on whether one should exist (#7797). The fence clears only on a definite verdict — pane liveness alone never clears it — and the fence error names an agent-server too old foraccount-swap-discardso it can be upgraded: upgrading prevents a recurrence but cannot establish the already-lost swap's outcome.- Sessions on one host share its ssh user, so they can read each other's workspaces and synced credentials, exactly as local worktrees share one user today. A Unix user per session is a later hardening, not part of this contract.
Operator-selected agent config. The global-only sandbox_agent_config key
(agent:file entries from a closed set: claude:settings.json, claude:CLAUDE.md,
claude:.claude.json, codex:config.toml, codex:AGENTS.md) lists agent
personalization af places in that same scope — read from the operator's own agent
home on the daemon machine, written beside the synced credentials, one way, and
removed with them. It applies only on a listed host and only to an account-scoped
session; a repository can never set it. A copied codex config.toml is rewritten to
the file credential store so it cannot override the session's account. A declared
file af cannot place — missing, unreadable, not a regular file, unparsable, or
pushing the placement archive over its 64 MiB bound — is skipped rather than
failing the provision, and the
skip is not silent: the session row carries one agent:file: <reason> entry per
skipped file in agent_config_skipped, surfaced on af sessions get, the TUI row,
and the web view until a later provision or account swap places every file.
Not yet built: fanning a refresh out to every live session on the same account (providers that rotate refresh tokens log the others out), write-back on a timer or after a daemon restart.
Archive and restore¶
For the disposable sandbox backends (docker, ssh, and sandbox), a push
archive (docker/hook by default; ssh/sandbox with --push) is push/pull
of the session branch — the durable workspace is the branch on GitHub
(origin), not the sandbox:
- Archive (
af sessions archivefordocker/hook, oraf sessions archive --pushforssh/sandbox) pushes the session branch toorigin, then tears the sandbox down (reaps the container / removes the remote session dir + closes the tunnel). The session record is preserved as an inert Archived row — restorable, but consuming no container or remote process. - Restore (
af sessions restore) re-provisions a fresh sandbox that clones the pushed branch back, restarts theaf agent-server, and relaunches the agent. The session resumes from the pushed branch state.
The ssh/sandbox af sessions archive default instead preserves the
workspace on its host (W8.5): the agent stops and the session directory is kept
where it is — nothing is pushed, committed or reaped — and restore reattaches
that workspace (W8.6), so the branch, worktree, index and ignored files come back
exactly as archived. The agent resumes its conversation only when its provider
store survives the archive: a session run under a synced account has that account
directory removed on archive (the credential teardown the reap would do), so
restore finds no transcript and starts a fresh conversation, while a session
with no synced account keeps its provider store in place and resumes.
The push archive is the same flow for every off-box backend (it is written once
against the runtime seam); the preserve/reattach path is an ssh/sandbox-specific
alternative implementation of the same capabilities. Either way
docker/ssh/sandbox/hook match local on the lifecycle capabilities —
Archive and Recover are both supported. All four are declared off-box in one
place (backendProvisionsOffBox), and all four share a single capability
declaration, so none of them can differ from the others in those capabilities
without that being a deliberate change. Parity is not total: they declare
TabManagement off (and Handoff, which an ssh or sandbox session's agent-server lifts when it advertises agent-swap). The static declaration is the floor: an
off-box session whose agent-server advertises tab-api lifts TabManagement and
serves shell and process tabs off-box too. Without that advertisement an off-box
session carries only its agent tab plus HTTPS web tabs (the one metadata-only kind
admitted off-box; a loopback target is admitted because off-box runtimes relay
loopback through the agent-server) and docs tabs. A Lost sandbox session (one whose
sandbox answered that its agent is gone) is reachable, so recovery relaunches
the agent in place: the sandbox's agent-server stops the agent (if it is still
running) and starts it again in its existing workspace with the provider's resume,
rebuilding the worktree if it was deleted: on the recorded branch when that
branch still exists (its tip is kept), or — when the branch is gone too — by
recreating it from the recorded base commit (falling back to the origin default
branch, then HEAD), which is only attempted when the agent's exact recorded
conversation can be resumed; otherwise the rebuild is refused and the session
stays Lost. A rebuilt worktree runs the repository's post_worktree_commands
again, so installs or builds with side effects repeat on that recovery. When the
worktree still exists, the branch, the tree and any uncommitted work are untouched
and no hooks re-run. Either way nothing is pushed,
reaped, re-cloned or re-provisioned. The same relaunch serves retry-limit on a
dead agent — and reports back whether its respawn resumed the session's own
conversation, which is what the retry's conversation answer relays (a
re-provision, or a sandbox build too old to report, answers not-carried instead). A sandbox built before the relaunch route existed (it advertises the
relaunch feature on /v1/health) falls back to replacing the sandbox: recovery
then pushes its work to origin first (anything unpushed would be destroyed by
the re-clone) — and refuses to replace if that push fails. Unreachability alone
is not death — it does not mark a sandbox Lost, and restore refuses to replace a
sandbox it cannot reach.
Host requirements, credentials and restarts¶
What the sandbox host needs, and what af does to it:
- Tools.
git,tmux(3.2 or newer) and a POSIXshon the non-interactivePATHof the ssh login (af wraps each remote script insh -c '<script>'and sends that as one ssh argument; theshit invokes parses the script, not the login shell). The staticafbinary af copies over also has to run there: see the glibc rule under Docker for the dynamic build. - Git identity is repo-local. After the clone, provisioning writes the
committer identity into the workspace's own
.git/config(git config --local): the operator'suser.name/user.emailas git resolves them on the daemon host. Each field falls back separately to its placeholder ("Agent Factory" foruser.name,af@agent-factory.localforuser.email) only when that field is unset, so configuring just one keeps the configured value and substitutes the placeholder for the other. The host user's global git config is left untouched. - Credentials. The clone uses value-free GitHub credentials: no token value is
written into the clone's config. The per-session agent-server token goes
through stdin into a
0600file in the session directory, never through argv or the environment of a process the agent starts. - Callback credential. For the agent inside the sandbox to call back into
the daemon (
AF_DAEMON_URL/AF_DAEMON_TOKEN), the daemon's dedicated sandbox callback endpoint must be running —network.listen_addrandnetwork.require_tokenare not involved, so a default (loopback, tokenless) daemon already gives sandboxes a working callback. When that is not the case the create is not refused: the session is created without a callback credential and the reason is reported (callback_unavailable_reasonin the backend picker). The credential admits a boundedafsurface —Snapshotreturns the caller's project (the sandbox-safe projection withholds the tmux name and the repository paths), and every other admitted route is bounded by its handler to the caller's own project. - Daemon restart. The agent-server is started with
nohup, so it outlives a daemon restart on the host, and on start the daemon tries to reattach to it in the background (ReattachSandbox): it re-dials the tunnel and rebinds the same agent-server, with no re-provision. What happens next depends on the row: - Reattach succeeds. The row is live again with the same agent-server. Nothing is pushed, replaced or restarted.
- The agent-server crashed but its host is still up (the host answered over a working transport but the agent-server did not, leaving the worktree and tmux server the agent runs in alive). When the row recorded its launch command and the host proves its recorded agent-server PID is gone or has been reused by another program, the daemon reruns that persisted command (the token and callback credential it sources are unchanged, so the restarted process keeps the session's identity), re-dials to the new port, and re-adopts the surviving workspace through the ordinary restore path — the existing worktree is kept, not re-cloned, so uncommitted and unpushed work on the host is preserved either way. When the surviving tmux session reattaches a live agent the agent is not re-run at all. When the tmux session is gone, a row that recorded no exact conversation id respawns the agent in that same workspace (re-running startup on a fresh conversation), while a row that did is refused instead — af will not resume the agent onto a guessed conversation — and stays needing attention. A row that cannot be proven empty — no recorded launch command or PID, the recorded PID still alive, or the host cannot tell — is reported and left alone, so a slow agent-server is never doubled.
- Reattach is not attempted or fails (no persisted runtime identity, the
host does not answer, or the agent-server is not restartable above). The
row stays Lost and holds no agent-server client: it carries the "not
provisioned" sentinel (
ErrRemoteSandboxNotProvisioned), which restore reads as absent (probeAbsentindaemon/restore.goanddaemon/lostrestore_attempt.go), not as a sandbox that answered dead. Absent means replacement is unconditional: the old runtime is torn down and a fresh sandbox is provisioned from the session's branch onorigin. Nothing is pushed first, so work the sandbox never pushed is not preserved on this path; only what already reachedorigincomes back. For a branch af chose at create and never saw pushed, the daemon verifies it atoriginbefore fetching; anoriginit cannot reach refuses the restore and reaps nothing rather than guess the branch. Provisioning needs the host, so a host that is still unreachable fails that attempt and the row stays Lost, but that is the provision failing, not a guard. - A live client sees the agent die (no restart involved, or the row was
reattached first). If the agent-server answers that the agent is gone, the
sandbox is still there. When it advertises
relaunchrecovery relaunches the agent in place (see above); otherwise recovery (and a manual restore) pushes its work tooriginbefore replacing it (probeAnsweredDead), and refuses to replace anything if that push does not land. If it does not answer at all, the probe is unknown and replacement is refused: unreachable is not dead. --force-reapreplaces a sandbox that answered dead, or one that could not be probed, without pushing it; it still requires the session's branch to be known so the replacement never lands on the default branch.
Work that matters should therefore reach origin before a daemon restart can
leave a row un-reattached. For an ssh/sandbox session, the default archive
leaves the workspace on the host and restore reattaches it (W8.5/W8.6), so an
archived session does not depend on a push at all.
What survives, and what doesn't¶
For a push archive (docker/hook by default, or ssh/sandbox with
--push), the sandbox is thrown away, so only what reaches origin survives:
- Committed work on the session branch is pushed, so it is fully preserved.
- Uncommitted work is snapshotted into a WIP commit
(
af: pre-archive snapshot (uncommitted work)) and pushed too, so the working tree is not lost — matching thelocalworktree-move archive's "nothing lost" guarantee as closely as the disposable model allows. If you would rather not carry that WIP commit, commit your work yourself before archiving. - The agent's conversation history lived only in the disposed sandbox and is
not restored — a fresh agent runs on the restored branch. (The
localbackend, which relocates the worktree in place, does resume the conversation, as does anssh/sandboxsession archived by default whose provider store survives the archive — restore reattaches the preserved workspace and resumes from the kept transcript (W8.5/W8.6). A defaultssh/sandboxarchive of a session run under a synced account removes that account directory on archive, so the transcript does not survive and restore starts a fresh conversation; losing the history is otherwise the difference the push/clone flow has and the preserve path does not.)
Requirements¶
A push archive (docker/hook, or ssh/sandbox with --push) needs the
sandbox to push to the repo's origin — the same remote it cloned from. For
a real repo that means the container/remote has git credentials for origin (an
HTTPS token or an SSH deploy key); for a self-contained test a read-write
file:// remote works. If the push fails, the archive fails and the session is
left running (nothing is torn down), so no work is lost. The ssh/sandbox
default archive (W8.5) does not push — the workspace stays on its host — so it
imposes no such requirement.