Coder relay wire protocol (v2)
Stage 2 S3, core#4634; v2 (the model channel, the baked relay) S5, core#4636
(tracker #4630; ADR-0037 D4/D7; launcher contract
proto/upsquad/sandbox/v1/launcher.proto). This is the contract between the
two halves of a sandboxed coder session:
- the shim — the
cli_paththe agent worker gives its secondClaudeSDKClient(services/agent-worker/src/agent_worker/orchestrator/relay_shim.py). The SDK spawns it exactly as it would spawn the Claude Code CLI. - the relay — one Python 3 stdlib program that runs as the served
sandbox's main process (
internal/workflow/coderdispatch/relay/coder_relay.py, baked into the coder image and run only under the hash the orchestrator embeds; see "Delivery" below). It execs the pinned CLI inside the sandbox.
Only the CLI process and the checkout live in the sandbox. The SDK client, its hooks (every tool call still goes to the Go bridge as PreToolUse), budgets and usage stay in the worker.
Conformance (run it with every extra installed, the claude-sdk extra is the
pinned CLI: cd services/agent-worker && uv run --frozen --all-extras pytest tests/test_coder_relay_conformance.py): services/agent-worker/tests/test_coder_relay_conformance.py
runs the real relay file against the real shim (a fake CLI that echoes what it
received, and the pinned bundled CLI in --version mode). Go side:
internal/workflow/coderdispatch TestRelayCommand_* (delivery bounds).
1. Transport and lifetime
- TCP. The relay listens on
0.0.0.0:$PORT(the launcher setsPORT, default 8080). The orchestrator returnshost:portto the worker ascoder_session.relay_endpoint. - Readiness: a connection whose first bytes are
GETis answeredHTTP/1.0 200 OKwith bodyokand closed. It carries no secret, reveals nothing and does not consume the session's one connection. The orchestrator probes/healthzthroughProbeServedbefore it repliescoder_session. - One session connection. The first connection that completes the handshake (§2) is the session; the relay then CLOSES ITS LISTENER, so any later connection — the correct secret included — is refused at TCP.
- Bad handshakes: a connection that sends a wrong secret, a malformed
handshake, or nothing within 10 s is answered
{"ok":false,"error":"<fixed text>"}(never echoing what it received) and closed. After 5 such connections the relay exits non-zero (the sandbox ends). - The relay exits when the CLI exits (with the CLI's code), when the session connection drops (it kills the CLI: SIGTERM, then SIGKILL after 5 s), and on SIGTERM. A worker crash therefore ends the CLI, not just the lease.
2. Handshake (shim → relay, one line)
{"v":2,"secret":"<64 hex>","argv":["claude", ...],"env":{"NAME":"value", ...}}\n
- Versions roll together. The relay ships in the coder image (pinned by
digest, started by the orchestrator); the shim ships in the agent-worker
image. v2 refuses a
v: 1handshake (pinned bytest_a_bad_handshake_is_refused_with_a_fixed_text, the{"v": 1}case), so a v1 worker against a v2 relay FAILS CLOSED: the coder dispatch is the tool's error result and nothing runs. Roll agent-orchestrator and agent-worker in the same deploy, together with the coder-image pin migration, whenever the protocol version changes. secretiscoder_session.relay_secret(32 bytes, hex). Compared in constant time againstUPSQUAD_RELAY_SECRET, which the relay removes from its own environment at start and never passes to the CLI.argv[0]must be the literalclaude; anything else is refused. The relay execs ITS OWN pinned CLI path (/usr/local/bin/claude) withargv[1:]— never a path the shim names.argvis bounded (≤ 512 entries, ≤ 1 MiB total).--dangerously-skip-permissions,--allow-dangerously-skip-permissionsand--permission-mode bypassPermissionsare refused.envis the keep-list: the shim forwards only the names the worker's segment put inUPSQUAD_CLI_ENV_KEEP, minus every worker-local basic (PATH,HOME,PWD,TMPDIR, TLS bundle paths, proxies,CLAUDE_CONFIG_DIR) and minus the relay's own variables, and minus everyANTHROPIC_*name. The relay accepts only names it allows (DISABLE_AUTOUPDATER,CLAUDE_CODE_*,CLAUDE_AGENT_SDK_VERSION,MAX_THINKING_TOKENS,LANG,LC_ALL,LC_CTYPE,TZ,TRACEPARENT,TRACESTATE) and refuses the handshake on any other name — so no loader variable (LD_*,NODE_OPTIONS, …), no model credential or model URL (ANTHROPIC_AUTH_TOKEN,ANTHROPIC_BASE_URL,ANTHROPIC_API_KEY) and no gateway bearer (UPSQUAD_CODER_GATEWAY_BEARER) can cross. Values ≤ 64 KiB, no NUL. A v1 handshake is refused. Pinned bytest_a_bad_handshake_is_refused_with_a_fixed_text.- The CLI's environment = the sandbox's own environment (PATH, HOME=/tmp, the
offline package-manager settings, the forced-proxy variables) minus
UPSQUAD_RELAY_SECRETandPORT, plus the handshakeenv, withCLAUDE_CONFIG_DIR=/tmp/claudeforced,ANTHROPIC_BASE_URLset to the relay's loopback model listener (§3a),ANTHROPIC_AUTH_TOKENset to the fixed placeholderupsquad-relay-no-credential, and127.0.0.1,localhostappended toNO_PROXY. Its cwd is/work. - No credential crosses the relay. The coder's gateway tools are a worker-hosted SDK MCP server reached over the CLI's control protocol (§3, ordinary stdio bytes); its model calls go over the model channel (§3a).
Reply (relay → shim, one line): {"ok":true}\n, then framing begins.
3. Framing (after {"ok":true})
Every message is type (1 byte) | length (4 bytes, big-endian) | payload,
payload ≤ 1 MiB.
| type | direction | payload |
|---|---|---|
0x00 STDIN | shim → relay | bytes for the CLI's stdin |
0x03 STDIN_EOF | shim → relay | empty: close the CLI's stdin |
0x01 STDOUT | relay → shim | bytes the CLI wrote to stdout |
0x02 STDERR | relay → shim | bytes the CLI wrote to stderr |
0x04 EXIT | relay → shim | 4-byte big-endian signed exit status (negative = killed by that signal); last frame |
0x05 MOPEN | relay → shim | 4-byte stream id: the CLI opened a model connection |
0x06 MDATA | both | 4-byte stream id + bytes of that connection |
0x07 MCLOSE | both | 4-byte stream id: that connection is closed |
An unknown type, an oversize frame or a model frame shorter than its id ends the session (the relay kills the CLI). The shim writes STDOUT/STDERR payloads to its own stdout/stderr and exits with the EXIT status, so the SDK sees an ordinary CLI process. The shim handles everything already received before it treats a closed relay connection as lost: after a failed write it reads the socket to EOF first, so an EXIT the relay sent before it went away still ends the shim with the CLI's code. Every open model stream is charged (its reservation if its usage was not final) before the shim gives up. On the relay side, a model socket closed earlier in the same wakeup is skipped (never read as a CLI pipe), and any unexpected error stops the CLI and still sends an EXIT (status 70).
3a. The model channel (v2)
- The relay listens on
127.0.0.1:<ephemeral>inside the sandbox (never on the network) and gives the CLI that address asANTHROPIC_BASE_URL. Each accepted connection is one stream (≤ 16 at a time); its bytes cross as MDATA frames. - The shim (the worker end) parses each stream's request head (≤ 64 KiB) and
forwards only
POST /v1/messagesandPOST /v1/messages/count_tokensin origin form; anything else is answered locally (400/403) and never leaves the worker. It drops the CLI'sAuthorization/x-api-key, hop-by-hop and forwarding headers, and sendsHost= the Model Gateway,Authorization: Bearer <route>,Accept-Encoding: identity,Connection: close. The route (UPSQUAD_RELAY_MODEL_URL/_TOKEN) is the shim's own input: it is never forwarded. - Metering. The shim reads the usage the gateway returns in each response
(SSE
message_start/message_delta, or a JSONmessage; chunked or not) and appends one line per response toUPSQUAD_RELAY_METERin the worker's scratch directory. The worker sums it (segment.metered_usage) and reports THAT as the coder's usage (cost_source = worker_metered), never the sandbox'sResultMessage. Cost = input rate × (input + 1.25 × cache write + 0.1 × cache read) + output rate × output. A response is priced at the coder model's rates (segment.coder_rates: the worker's price table, else the family's list price) only when the model the GATEWAY reports is of the coder's family (UPSQUAD_RELAY_MODEL_FAMILY); any other model, and every response of a coder whose family is unknown, is priced at the most expensive tier — so a sandbox that asks for a dearer model is never under-priced against its cap. - The cap is hard. The shim buffers each request whole (a
Content-Lengthbody, ≤ 32 MiB; chunked is refused) and reserves its worst case before forwarding it: input rate × 1.25 (a 5-minute cache write, the dearest input the channel admits) × (body bytes + 2000 for the provider's hidden tool/system prompt + 2000 per image block) + output rate ×max_tokens(a Messages request without a positive integermax_tokensis refused), at the rates of the model the request names. Bounded because: acache_controlother than the default (ephemeral, ttl absent or5m) is refused anywhere in the body (a 1-hour write bills 2×; a reported 1-hour write is metered at 2×);documentblocks are refused anywhere, tool results included (a PDF bills ~1.5–3k tokens per page whatever its bytes — an 11.8 KB 100-page PDF bills ~150–300k — and the SDLC coder works on a source checkout, not on documents). This fails CLOSED, it does not degrade: a coder that reads a PDF in its checkout puts adocumentblock in its history, so every later turn of that session gets the same 400 and the session ends (the dispatch fails; nothing is forwarded or billed). The shim serves at most 16 concurrent streams (MAX_STREAMS, the relay's number), refusing the next with a fixed 400 metered zero. The shim does not trust the relay's stream ids: the relay numbers them 1, 2, 3, ... and never reuses one, so aT_MOPENfor any id but the next, or aT_MDATA/T_MCLOSEfor an id never opened, is a protocol violation, and so is every malformed frame (an unknown type, a model frame shorter than its id, one longer thanMAX_FRAME, an EXIT that is not an int32); the shim charges every open stream its reservation and exits 1 (bad frame from the relay). A frame for a stream the shim itself already ended is ignored (it crossed the shim'sT_MCLOSE). A write to the relay that fails does not end the shim at once: it first reads what the relay already sent (anEXITthere still ends it with the CLI's code), then charges every stream still open its reservation and exits 1 (relay connection lost). Request numbers that overflow to infinity (1e400) are refused likeNaN/Infinity. The residual, stated: a hidden prompt beyond 2000 tokens and an image beyond its 2000-token floor; the bound is one admission window of at most 16 streams at those terms (cents at the ceiling rates), settled when each response's real usage is charged (#4690). A shim that is itself killed (the SDK tears the session down) records no line for its in-flight streams: their spend is the gateway ledger's (llm_usage_eventsby run), not the meter's. A request is admitted only while spent + open reservations + its own ≤ the dispatch's clamped budget (UPSQUAD_RELAY_MODEL_BUDGET_USD= min(session, roster entry, envelope remaining)); otherwise the shim answers400itself (not429: the CLI retries those) and records a refusal, and the worker reports the sessionexhausted. A stream that ends before its usage is final (an SSEmessage_stopor a whole JSON message) — the client closed early, the relay died — is charged at least its reservation; a whole non-2xx response bills nothing. A budget that is not a positive finite number forwards nothing. - Egress policy. Only these top-level request keys pass:
model,messages,system,max_tokens,metadata,stream,thinking,tools,tool_choice,context_management,stop_sequences,temperature,top_p,top_k, andoutput_configcarrying only aneffortstring (the pinned CLI's, measured for haiku-4-5, sonnet-4-5, sonnet-4-6, opus-4-5 and opus-4-6, plus sampling). Every tool must be a client tool (aninput_schema, and notypeor exactly"custom"); URL-sourced content anywhere inmessages/systemis refused; only the pinned CLI'santhropic-betavalues (includingeffort-2025-11-24, plus fine-grained tool streaming and prompt caching) pass. A body that repeats a key at any depth is refused (a first-key-wins parser upstream would read another request than the one checked), and what is forwarded is the CHECKED object re-serialised, with its ownContent-Length— never the sandbox's bytes. A refusal is400with a fixed text and meters zero. A CLI bump re-measures this shape (#4690). Header lines are split on CR?LF and a continuation line (leading space or tab) is refused; everyauthorization,x-api-key,proxy-authorization,cookieandx-upsquad-*header is dropped, the shim writes its ownHost,Authorization,Content-Length,Accept-Encoding: identityandConnection: close, and any method but POST is refused. - Proved by
services/agent-worker/tests/test_coder_model_channel.py, including the REAL pinned CLI completing a print-mode turn through relay and shim against a stand-in gateway with no credential but the placeholder.
4. What is in the sandbox, and what is not
As ADR-0037 D7 (amended by S5): PORT, UPSQUAD_RELAY_SECRET (relay only)
and the forced-proxy variables. No credential of ours: not the model
route (the shim holds it, §3a), not a gateway bearer, not the SCM token (the
launcher clones outside the sandbox), not the vault passphrase,
DATABASE_URL, the platform signing key, the launcher caller token or any
long-lived credential.
-
Gateway tools are worker-hosted. The coder's options carry exactly one MCP server,
upsquad_coder_gwoftype: sdk(nohttpserver is ever built for it;build_coder_optionsrefuses one). The CLI sees its tools over the control protocol; each call passes PreToolUse, and the worker executes only a call the bridge allowed, with the allowed input, using a bearer that never leaves it. The bridge denies any other MCP name from a sandboxed agent (ReasonCoderNoMCP). -
The model route is worker-held (§3a). The Model Gateway host is still in the sandbox platform tier (
model-gateway:8091), but nothing in the sandbox can authenticate to it; removing it is a separate change to the egress smoke. -
The worker's listeners bind only its control address when the opt-in coder overlay puts it on
sbx-internal(WORKER_LISTEN_HOST, checked by rule S10 andscripts/coder-overlay-listen-smoke.sh). That protection holds only while a sandbox cannot forge packets or re-address itself: a sandbox must never gainNET_ADMINorNET_RAW— every launched sandbox runs--cap-drop ALLwith no--cap-add(pinned byTestLauncherServer_ServedArgvCarriesEveryCap). -
Since S6 (#4637) the worker is not on
sbx-internalat all. On compose it reaches the relay throughcoder-relay-forwarder(internal/workflow/sandbox/relayforward,cmd/coder-relay-forwarder):- the worker and the forwarder share
coder-relay-ctl, an internal network with a pinned subnet, whose members are exactly those two; - the forwarder listens only on its pinned address there (
10.247.3.2:9481) and is a member ofsbx-internal, but never listens on it; - the shim (
CODER_RELAY_FORWARDER) opens the connection with exactly the 47 bytes{"session":"<32 lower-case hex>"}\nnaming the launcher session in its endpoint. The forwarder compares them bytewise, then dials onlysbx-sess-<id>:8080and splices; anything else is closed before any dial; - the relay protocol above (v2, model channel included: the shim bakes the
forwarder into
relay_shim_src.py's oneFORWARDERline, pinned bytest_through_the_compose_forwarder_the_model_channel_is_unchanged) is unchanged end to end. The forwarder logs the peer, the session id and byte counts, never the payload.
The
NET_ADMIN/NET_RAWrule is not retired: it now protects the dual-homed members (the forwarder, the proxy, the preview router) in the same weak-host way. Proof:scripts/coder-relay-forwarder-smoke.sh(F0–F4) and checker rules S5/S11. Kubernetes uses a NetworkPolicy instead (S6b). - the worker and the forwarder share
Stated residuals (backend-security #4598 comment 7037416142):
- the secret is in the container's
docker inspectConfig.Env (socket holders only) and at/proc/1/environ. The relay sets itself non-dumpable (PR_SET_DUMPABLE=0), which makes its/proc/<pid>/environunreadable to the CLI's uid; even where that fails the secret's only power is this session's single connection, which is already taken; - on compose there is no per-pair network policy: any container on
sbx-internalcan open TCP to the relay port. The secret, the single connection and the constant-time compare are the whole control there (prod-enablement #4647).
5. Delivery
The relay is baked into the coder image (S5): images/code-exec-coder/ coder_relay.py, byte-equal to the embedded one, is copied to
/usr/local/lib/upsquad/coder_relay.py (root-owned, 0444), and the Dockerfile
records its sha256 (CODER_RELAY_SHA256, checked at build time and stamped as
the org.upsquad.coder-relay-sha256 label). The orchestrator starts the
served sandbox with
python3 -I -S -c "<bootstrap>" <sha256 of the embedded relay> /usr/local/lib/upsquad/coder_relay.py
The bootstrap (coderdispatch.relayBootstrap) reads the baked file and
refuses to run it (exit 1, "relay hash mismatch; refusing to run") unless its
sha256 is the one this orchestrator embeds — so an image pinned at another
relay (or an edited, truncated or missing file) fails closed instead of
speaking a protocol the worker does not. A relay change is therefore a
Dockerfile change: a new content tag, a publish (publish-images.yml,
coder_image_only=true) and a new digest pin in a migration
(TestCoderPinTracksTheDockerfile, TestRelayImageCopyIsTheEmbeddedRelay).
The command holds no secret and no token (TestRelayCommand_HoldsNoSecret).