Sandboxes
Long-lived interactive sessions — exec, persistent terminals, suspend and resume, preview URLs.
A sandbox is a pet: one pod, kept around, with a terminal and usually a durable workspace attached. It's what an AI agent session or a cloud dev environment runs on. Where a job is "run this and tell me what happened", a sandbox is "keep this alive and let me poke at it".
Creating one
const sandbox = await cp.sandboxes.create({
environment,
workspace: workspaceId, // omit for ephemeral scratch
cache: { policy: "write-back", writebackSec: 10 },
egress: egress.none(),
resources: { cpu: "2", memory: "4Gi" },
idleSuspend: "15m", // omit for never
maxLifetime: "24h", // hard kill switch
label: "agent session — #general",
});Bursting past the request
resources is a request the scheduler reserves, and by default also the limit. A sandbox can ask for more headroom than it reserves:
cpu_limit_millislets it use more CPU thancpu_milliswhile the node has room. Unset, or belowcpu_millis, means the limit is the request. A session that compiles in bursts wants a small request, so several fit on a node, and a large limit.memory_limit_mbdoes the same for memory, with one difference: going over a memory limit is not throttled, the pod is killed. The limits on a node can add up to more than it has, so a node that really runs out kills something first. Size the gap with that in mind.
Only sandboxes honour these two today; jobs and apps ignore them.
Node shares and memory mounts
Besides workspaces and volumes, a mount's volume can be one of two more kinds:
workspaces: [
{ mountPath: "/workspace", readOnly: true, volume: { nodeShare: "mirror" } },
{ mountPath: "/run/secrets", volume: { memory: true, sizeMb: 16 } },
]node_sharenames a read-only directory the cluster admin declared on every node (cp-cluster-prereqscsi.nodeShares) and something the cluster runs keeps current — a git mirror, a warm dependency cache. Every pod on the node mounts the same copy, with nothing copied in. The mount is the share's current generation as it stood when the pod started, so it never changes under a running workload. It must beread_only, has no size, and the pod is placed only on a node whose copy is ready. Which namespaces may mount a share is the cluster admin's; a share the cluster does not report (capabilities.node_shares) isFailedPrecondition.memoryis a tmpfs ofsize_mb(1–1024), created and destroyed with the pod and charged to its memory limit — for material that must never reach disk, such as a credential the workload fetches for itself. It is never the primary mount, so inputs, outputs and the working directory stay where they were.
Apps support neither yet.
Running a command
A sandbox runs its environment's command as its workload — the entrypoint of the image, unless you say otherwise:
const sandbox = await cp.sandboxes.create({
environment,
argv: ["npm", "run", "dev"], // omit to use the environment or image's own
restart: "on_failure", // "never" (default) | "on_failure" | "always"
});The command is resolved once, at create, and persisted — so a resume runs the same thing rather than picking up whatever the image tag points at now. The order is:
argvon the request- the environment's
default_argv - the image's own
ENTRYPOINT/CMD
Pass execOnly: true for a sandbox that runs nothing and exists only to be exec'd into. That is not the same as omitting argv: omitting means "resolve one", execOnly means "there is none".
This changed. Sandboxes previously ran a keepalive process instead of the image's entrypoint — not as a fallback, but as a silent replacement, because setting a container's command overrides ENTRYPOINT outright. A sandbox built on an image that starts a dev server started nothing at all. Now it starts the server. If you were relying on the old behaviour, set execOnly: true.
A crashing command cannot kill the sandbox. The workload runs as a child of a supervisor that holds PID 1, so when it exits — cleanly or not — the pod stays up, the workspace keeps syncing, and you can still exec in to find out why.
Two policies, two questions
restart governs the command; onExit governs the sandbox. They are separate because they answer separate questions, and because "retry my server, but if it's beyond saving stop paying for the sandbox" has no expression otherwise.
await cp.sandboxes.create({
environment,
restart: "on_failure", // the command: rerun it if it failed
onExit: "suspend", // the sandbox: once we're done rerunning, suspend
});restart — what happens to the command:
never (default) | It runs once. However it ends, that's the end of it |
on_failure | A non-zero exit or a signal starts it again, with backoff, until a crash-loop ceiling. A clean exit is treated as done |
always | Started again however it ends, a clean exit included — so it never finally stops |
on_failure and always differ only on a clean exit. For a server that never exits successfully they behave identically.
onExit — what happens to the sandbox, once the command is not going to run again:
suspend_on_success (default) | Suspends after a clean exit; stays up after a failure |
keep | Stays up either way, ready to exec into |
suspend | Suspends either way — the sandbox existed to run one thing |
The default is asymmetric on purpose: a crashed run is the one you most need to look at, and a suspended sandbox cannot be looked at — its pod is gone, so there is no filesystem to inspect and no shell to open.
restart is evaluated first. onExit applies only once the command is not being restarted, so under restart: "always" it never applies at all. A run that exits within a few seconds of starting is never auto-suspended either, so a fast-exiting entrypoint does not make every resume look like it did nothing.
The run log
sandbox.logs() is what the workload printed — one continuous record across the sandbox's whole life, not just its current pod:
for await (const chunk of sandbox.logs({ follow: true })) {
if (chunk.body.case === "marker") {
console.log(`--- ${chunk.body.value.kind} ---`); // RUN_EXITED, SUSPENDED, CRASHED…
} else {
process.stdout.write(chunk.body.value);
}
}It cannot come from the pod: a suspend deletes the pod, so pod logs would lose everything at the first suspend. The control plane collects and retains it instead.
Boundaries arrive as typed markers interleaved with the output in the same cursor order, rather than as text banners you would have to pattern-match:
| Marker | When |
|---|---|
RUN_STARTED | A run began — carries its argv and image digest |
RUN_EXITED | It ended — carries the exit code, or the signal that killed it |
SUSPENDED / RESUMED | Explicitly, or by the idle timer |
CRASHED | The pod died — OOM, eviction, a lost node |
TERMINATED | An ending a resume cannot help with |
run on each chunk counts from 1 inside its pod and resets when that pod is replaced. It is a display grouping, not a unique execution identity. Pass the last offset you saw as fromOffset to resume without re-reading.
Guarded agents reporting agent.execution_log_identity revision 1 also include
execution_generation, pod_uid and run_id on RUN_STARTED and RUN_EXITED.
To establish readiness from output, read chunks in cursor order across all
runs, wait for a start marker matching the current sandbox generation, pod UID
and GetSandboxProcess.run_id, then inspect that run's output. A subsequent
start or exit ends that observation window. Recheck the live process identity
before acting on a match. Empty identity fields identify older or unguarded
agents and cannot establish readiness for a replacement execution.
Retention is bounded — 16 MiB and 30 days per sandbox — but markers are exempt from pruning, so a log whose output has aged out still shows where its runs, crashes and suspends were. Without that exemption a pruned log would read as one uninterrupted run.
GetSandboxLogs is the same record as one bounded, unary read: the latest chunks by default (limit up to 2000 chunks, limit_bytes up to 1 MiB), or the chunks after from_offset, optionally for one run. next_offset continues a forward read and more says later chunks exist.
This is not a console session. A console session is a terminal you drive; the run log is what the sandbox's own command emitted, whether or not anyone was attached.
States are CREATING → RUNNING → SUSPENDED → RUNNING … and finally TERMINATED. WatchSandbox streams transitions with a human-readable detail ("idle-suspended", "oom", "exposed :8080").
GetSandbox reads back the whole envelope — resources, TTLs, cache policy, workload env, the base runtime_egress and every active grant — so a console can answer "why was that host refused?" without inspecting the pod.
Moving a managed game server
The Games service uses SandboxService.MoveSandbox to move one persistent
server between nodes in the same managed cluster. It keeps the team's namespace
and sibling servers in place. Cross-cluster moves are not supported by this RPC.
ListSandboxMoveTargets accepts the namespace and sandbox ID. CP derives the
owning cluster and enrolled hosts, then checks each candidate's Kubernetes
readiness and actual agent/CSI capabilities. Results include display names,
the current host and an unavailable reason for ineligible hosts. A host that
can't hold the server's whole pod (every container, init container and sidecar,
against its allocatable resources minus what is already requested) is
INSUFFICIENT_CAPACITY, with unavailable_detail naming what the pod requests
and what the host has free. Eligibility is an observation; MoveSandbox checks
the destination, its capacity included, again at admission.
Both RPCs require the verified Games service identity and namespace write access.
Submit the exact sandbox revision, execution generation, destination node, idempotency key and normalized stop action. The readiness policy must match the policy stored when the sandbox was created. CP derives every writable persistent volume and moves them together. The initial contract accepts at most 16 volumes; unsupported mounts fail validation.
Special files in a world
Moves, volume backups and restores copy the world file by file.
- Symbolic links. These are copied as links, with their target text kept exactly: relative, absolute, pointing outside the volume, or dangling. The copy never follows them.
- Sockets and FIFOs. These hold no data, so they are skipped. The completed
operation lists each skipped path in
warnings, with codeSPECIAL_FILE_SKIPPEDand anentry_typeofsocketorfifo.warning_countis the full number; at most 100 are listed. - Device nodes. A device node refuses the operation with
UNSUPPORTED_ENTRY_TYPEand its path. - Hard links. Each name is copied as its own file.
Links are not given their original modification time. Symbolic links, sockets
and FIFOs are carried only when the nodes involved run CSI and operator
release37 or later. On an older node, a world containing them is refused with
UNSUPPORTED_ENTRY_TYPE, as before.
For a running server, CP withdraws its routes, confirms source stop and detach, copies and checksums the files, commits target storage authority, starts the next execution generation, verifies its readiness and then republishes routes. Players disconnect during this operation. A server that was stopped remains stopped after the move. The hostname and allocated public ports remain assigned; IP continuity is not part of the contract.
Keep the returned operation ID and exact request for retries. SUCCEEDED means
the move completed; NEEDS_ACTION retains the operation's resource locks and
recovery evidence. A lost response is not permission to submit a different move
or restart the old source. Recovery observes completed effects before retrying,
and cannot roll back to old source data after the target has become a writer.
A parked move
A parked operation's failure says why it parked (for example
TARGET_UNSCHEDULABLE when the destination can't schedule the pod, which parks
within a few seconds rather than waiting out the start timeout), and its
recovery_actions say what can be done:
| Action | Call | When |
|---|---|---|
RETRY | MoveSandbox with the original key and request | Always. It resumes the move's current leg, including one re-targeted below. |
RETARGET | RetargetSandboxMove | Parked before the world was promoted (with the source stopped), or after the destination was released but the server couldn't start there. |
ABANDON | AbandonSandboxMove | Parked before the world was promoted. |
ABANDON_WORLD_LOST | AbandonSandboxMove with accept_world_lost | Promoted but not yet released, and only when no copy of the world exists. |
RetargetSandboxMove continues the same operation to another eligible host.
The world's current location becomes the source, so a move whose destination
couldn't start the server can go back to the host it came from. A workload
start the destination never granted is stopped first; one that did start is
stopped with the stop action you send. Every copy is kept until the new
destination has the world. Repeating the call with the move's current
destination resumes it.
Name the new destination in target_node_id by its node id (for example
cl-83110ab496bb0072, as ListSandboxMoveTargets lists it) or by the host's
name (for example install16); CP resolves a name to the node id and records
the id. A target that names no admitted host is refused with
FAILED_PRECONDITION and changes nothing.
If a step fails because another service did, the parked failure has code
DEPENDENCY_FAILED and its message names the service and what CP asked of it
(for example Burrow could not revoke the managed network credential …; Burrow answered: …). Each step of a re-target checks what is already done
before acting, so a retry after any partial failure picks up where it stopped.
AbandonSandboxMove ends a move parked before promotion: CP confirms the
source copy still exists, releases the move's locks and leaves the server
stopped on its source, ready to start. The operation ends CANCELLED with
phase abandoned. A move whose world can be found on no host ends FAILED
with phase world_lost only when accept_world_lost is set; the server is
left stopped, to restore from a backup or delete. CP refuses to abandon a move
whose world exists on a host: retry it or re-target it instead.
CancelOperation on a move is honoured while it can still be undone: a
running move abandons itself at its next step, and a parked one at its next
resume. Once the world is promoted, cancellation is refused.
Aborting a stuck operation
A backup, restore, stop or create whose worker died can hold its sandbox or
volume locked until its lease runs out, which for some operations is a day.
OperationService.AbortOperation is the way out, for a caller with the
operator role on the namespace. It ends the operation FAILED with failure
code ABORTED_BY_OPERATOR and your reason, and releases its locks. Nothing
is deleted.
- Send the
expected_revisionyou inspected; a moved-on operation is refused. - A worker lease that is still live refuses the call unless you set
break_live_lease, saying its worker is gone. - A step whose effect was never confirmed is only given up when you name its
ordinal in
accept_unresolved_steps. The first refusal lists them. - A copying backup is marked failed and its reservation released. A restore can be aborted only while its volume is still on the backing it started from; after that, retry it. A create whose resource exists is refused: retry the original request.
- Moves are refused here: use
AbandonSandboxMove, which checks where the world is first.
Repeating the call after the abort returns the aborted operation.
Exec
Exec is bidi: the first message is the spec, then stdin frames; the server streams stdout, stderr, and a terminal exit.
const out = await sandbox.exec(["python", "main.py"], {
cwd: "/workspace",
timeout: "2m",
idleTimeout: "30s", // cut it loose on silence, not on the clock
});
console.log(out.stdout, out.stderr, out.exitCode, out.terminationName);timeout is a backstop against a runaway process; idleTimeout is the one that catches a stuck one. A command still producing output is left alone however long it runs — an npm install legitimately takes a while — while one that has gone quiet is released, and whatever it printed first is returned rather than thrown away (out.idleTimedOut).
sandbox.shell("…") wraps a command in bash -lc, and sandbox.script("python3", code) feeds a multi-line script on stdin so quoting never arises.
argv only — never a shell string, unless you ask for a shell explicitly. The exit is status-derived, so an OOM reads as OOM_KILLED rather than a mysterious 137.
Exec ties the process to the stream that started it. Hang up and the process dies. When that's wrong — and for a browser terminal or an agent working across turns it usually is — use a console session instead.
Console sessions
A console session is a terminal owned by a daemon inside the sandbox's own container, so it outlives every client that attaches. The load-bearing idea is the cursor, not the stream: output is a byte-addressed ring with absolute offsets, so "resume after a dropped WebSocket" and "poll between agent turns" are the same request — everything after offset N.
const dev = await sandbox.processes.start("dev", "npm run dev", {
cwd: "/workspace",
cols: 120, rows: 32,
idleTtl: "1h",
});
if (dev.exitCode !== undefined) console.error(dev.startupOutput); // it died on startupStarting the same name again reattaches rather than duplicating, so it is safe to repeat on every page load (dev.reattached). A freshly-started process is observed for a few seconds before being returned — the state captured the instant a session is created is always "started", so a process that dies at once on a wrong cwd or a missing command would otherwise report success.
Read it back later with dev.tail({ bytes: 4000 }), or sandbox.processes.get("dev") from a different turn entirely.
Two ways to drive it:
| Shape | Calls | For |
|---|---|---|
| Streaming | AttachConsole (bidi: spec, then stdin/resize; server streams output) | Interactive terminals — set replay: true for a fresh terminal that has nothing on screen, or from_offset to resume exactly |
| Unary | WriteConsole / ReadConsole / ResizeConsole | Agents between turns, CLIs, anything that can't hold a stream. ReadConsole.wait_ms turns a read into a long poll |
WriteConsole returns the ring tail_offset after the write, so a caller can read from there and see only that command's output. A reader that fell behind the retained window is told (truncated: true) rather than silently handed a gap.
Sessions are capped at 8 per sandbox by default — each shell and its children draw on the pod's pids limit, and an uncapped console exhausts the pid cgroup in a way that looks like a broken image. CloseConsoleSession escalates SIGTERM to SIGKILL, because an interactive shell ignores SIGTERM and a close that doesn't escalate silently does nothing.
A session's state is RUNNING, EXITED, or LOST — the last meaning the pod that hosted it is gone (suspended, rescheduled, evicted). The captured scrollback is still readable; the process isn't coming back. Sessions do not survive a suspend: there is no checkpoint and no process migration.
Suspend, resume, delete
await sandbox.suspend(); // retain volumes, delete the pod
await sandbox.resume(); // reschedule with the retained volumes
await sandbox.delete({ deleteWorkspace: false });sandbox.keepAlive() resets the idle clock without running anything, and returns when the sandbox would next be suspended. sandbox.heartbeat() runs that on a timer paced from the server's own answer, rather than a guessed interval.
Suspend deletes the pod and retains its volumes. Persistent volumes are node-local, so resume respects their placement. File writes already reach the mounted filesystem; there is no workspace sync or flush RPC.
The workspace outlives the sandbox unless you ask otherwise: delete_workspace is opt-in, so results are still readable after the session is gone.
A suspend records its boundary in the run log before the pod is deleted, so an auto-suspend never erases the record of why it happened.
Preview URLs
ExposePort publishes a port the sandbox is serving on, at an isolated origin:
const exposed = await sandbox.expose(8080, { auth: "signed-url" });
// exposed.url → https://8080-<sandbox-id>.preview.containers.xnr.appsandbox.exposeAll([8080, 5173]) returns port → URL for a set, skipping any already exposed.
| Auth mode | Who can reach it |
|---|---|
AUTH_SIGNED_URL | Anyone with the token; the click-through URL carries ?__cpt=…, which the proxy moves into a host-scoped cookie on first hit |
AUTH_FORWARD_AUTH | Anyone who can sign in to Xeonr Auth |
AUTH_PUBLIC | Anyone |
The preview domain is a separate origin from the console, with host-scoped cookies only, so hostile content served by a sandbox can never reach a console session. Exposing a port never reopens egress — the sandbox's policy still applies to outbound traffic.
A hit on a suspended sandbox resumes it, which is what makes scale-to-zero dev environments work.
One sharp edge: the agent owns ports 80, 443 and 53 inside the pod to capture traffic from clients that don't speak HTTP_PROXY. A sandbox that must serve on 80 or 443 gets capture disabled automatically — but only from the next pod start, since ports are only known from ExposePort. Exposing 80 or 443 on a live sandbox logs a warning and needs a suspend + resume before the workload can bind it. Such a sandbox keeps egress through the explicit proxy listener; it only loses the transparent path.
Live egress changes
GrantEgress opens an additive window on a running sandbox — the thing NetworkPolicy can never do per-pod-per-moment — and RevokeEgress removes one grant by id. Both take effect within seconds, with no pod restart. See Egress.