Skip to main content

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_path the agent worker gives its second ClaudeSDKClient (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 sets PORT, default 8080). The orchestrator returns host:port to the worker as coder_session.relay_endpoint.
  • Readiness: a connection whose first bytes are GET is answered HTTP/1.0 200 OK with body ok and closed. It carries no secret, reveals nothing and does not consume the session's one connection. The orchestrator probes /healthz through ProbeServed before it replies coder_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: 1 handshake (pinned by test_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.
  • secret is coder_session.relay_secret (32 bytes, hex). Compared in constant time against UPSQUAD_RELAY_SECRET, which the relay removes from its own environment at start and never passes to the CLI.
  • argv[0] must be the literal claude; anything else is refused. The relay execs ITS OWN pinned CLI path (/usr/local/bin/claude) with argv[1:] — never a path the shim names. argv is bounded (≤ 512 entries, ≤ 1 MiB total). --dangerously-skip-permissions, --allow-dangerously-skip-permissions and --permission-mode bypassPermissions are refused.
  • env is the keep-list: the shim forwards only the names the worker's segment put in UPSQUAD_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 every ANTHROPIC_* 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 by test_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_SECRET and PORT, plus the handshake env, with CLAUDE_CONFIG_DIR=/tmp/claude forced, ANTHROPIC_BASE_URL set to the relay's loopback model listener (§3a), ANTHROPIC_AUTH_TOKEN set to the fixed placeholder upsquad-relay-no-credential, and 127.0.0.1,localhost appended to NO_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.

typedirectionpayload
0x00 STDINshim → relaybytes for the CLI's stdin
0x03 STDIN_EOFshim → relayempty: close the CLI's stdin
0x01 STDOUTrelay → shimbytes the CLI wrote to stdout
0x02 STDERRrelay → shimbytes the CLI wrote to stderr
0x04 EXITrelay → shim4-byte big-endian signed exit status (negative = killed by that signal); last frame
0x05 MOPENrelay → shim4-byte stream id: the CLI opened a model connection
0x06 MDATAboth4-byte stream id + bytes of that connection
0x07 MCLOSEboth4-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 as ANTHROPIC_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/messages and POST /v1/messages/count_tokens in origin form; anything else is answered locally (400/403) and never leaves the worker. It drops the CLI's Authorization/x-api-key, hop-by-hop and forwarding headers, and sends Host = 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 JSON message; chunked or not) and appends one line per response to UPSQUAD_RELAY_METER in 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's ResultMessage. 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-Length body, ≤ 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 integer max_tokens is refused), at the rates of the model the request names. Bounded because: a cache_control other than the default (ephemeral, ttl absent or 5m) is refused anywhere in the body (a 1-hour write bills 2×; a reported 1-hour write is metered at 2×); document blocks 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 a document block 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 a T_MOPEN for any id but the next, or a T_MDATA/T_MCLOSE for 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 than MAX_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's T_MCLOSE). A write to the relay that fails does not end the shim at once: it first reads what the relay already sent (an EXIT there 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 like NaN/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_events by 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 answers 400 itself (not 429: the CLI retries those) and records a refusal, and the worker reports the session exhausted. A stream that ends before its usage is final (an SSE message_stop or 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, and output_config carrying only an effort string (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 (an input_schema, and no type or exactly "custom"); URL-sourced content anywhere in messages/system is refused; only the pinned CLI's anthropic-beta values (including effort-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 own Content-Length — never the sandbox's bytes. A refusal is 400 with 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; every authorization, x-api-key, proxy-authorization, cookie and x-upsquad-* header is dropped, the shim writes its own Host, Authorization, Content-Length, Accept-Encoding: identity and Connection: 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_gw of type: sdk (no http server is ever built for it; build_coder_options refuses 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 and scripts/coder-overlay-listen-smoke.sh). That protection holds only while a sandbox cannot forge packets or re-address itself: a sandbox must never gain NET_ADMIN or NET_RAW — every launched sandbox runs --cap-drop ALL with no --cap-add (pinned by TestLauncherServer_ServedArgvCarriesEveryCap).

  • Since S6 (#4637) the worker is not on sbx-internal at all. On compose it reaches the relay through coder-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 of sbx-internal, but never listens on it;
    • the shim (CODER_RELAY_FORWARDER) opens the connection with exactly the 47 bytes {"session":"<32 lower-case hex>"}\n naming the launcher session in its endpoint. The forwarder compares them bytewise, then dials only sbx-sess-<id>:8080 and 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 one FORWARDER line, pinned by test_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_RAW rule 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).

Stated residuals (backend-security #4598 comment 7037416142):

  • the secret is in the container's docker inspect Config.Env (socket holders only) and at /proc/1/environ. The relay sets itself non-dumpable (PR_SET_DUMPABLE=0), which makes its /proc/<pid>/environ unreadable 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-internal can 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).