English
Docs menu

Agent Sandboxes docs · Reference

Errors of the sandboxes API, and what to do

Updated · 7 min read

What each refusal of the API means and what to do next, by its code and its typed detail: for a program's branches and an agent's next step. Branch on the code and the detail, never on the message, which is a sentence for people and may change.

Reading an error in each SDK

A failed call raises, rejects or returns an error with a code, the API's message and, where it has one, a typed detail. Python raises a subclass of SandboxesError per code (AlreadyExistsError, FailedPreconditionError…) with the detail in detail; TypeScript rejects with a SandboxesError whose detail is a field of its own (error.nameTaken); Go returns a *sandboxes.Error with a field per detail; Rust's Error has code() and details(). Here a name already taken reuses the sandbox that has it, and a stopped sandbox is resumed:

Python
from pethost.sandboxes import AlreadyExistsError, FailedPreconditionError, NameTaken, Stopped

try:
    sandbox = sandboxes.create_sandbox("base", name="api-dev")
except AlreadyExistsError as error:
    if not isinstance(error.detail, NameTaken):
        raise
    sandbox = sandboxes.get_sandbox(error.detail.sandbox_id)  # the sandbox that has the name

try:
    command = sandboxes.run_command(sandbox.sandbox_id, command="make test")
except FailedPreconditionError as error:
    if not isinstance(error.detail, Stopped):
        raise
    sandboxes.resume_sandbox(sandbox.sandbox_id)
    command = sandboxes.run_command(sandbox.sandbox_id, command="make test")
TypeScript
const created = await sandboxes.createSandbox({ template: "base", name: "api-dev" }).catch(async (error) => {
  if (!(error instanceof SandboxesError) || !error.nameTaken) throw error;
  return sandboxes.getSandbox({ sandboxId: error.nameTaken.sandboxId }); // the sandbox that has the name
});

const test = { sandboxId: created.sandboxId, command: "make test" };
const command = await sandboxes.runCommand(test).catch(async (error) => {
  if (!(error instanceof SandboxesError) || !error.stopped) throw error;
  await sandboxes.resumeSandbox({ sandboxId: created.sandboxId });
  return sandboxes.runCommand(test);
});
Go
created, err := client.CreateSandbox(ctx, &sandboxes.CreateSandboxRequest{Template: "base", Name: "api-dev"})
if e, ok := errors.AsType[*sandboxes.Error](err); ok && e.NameTaken != nil {
	created, err = client.GetSandbox(ctx, &sandboxes.GetSandboxRequest{SandboxID: e.NameTaken.SandboxID})
}
if err != nil {
	log.Fatal(err)
}

test := &sandboxes.RunCommandRequest{SandboxID: created.SandboxID, Command: "make test"}
command, err := client.RunCommand(ctx, test)
if e, ok := errors.AsType[*sandboxes.Error](err); ok && e.Stopped != nil {
	if _, err = client.ResumeSandbox(ctx, &sandboxes.ResumeSandboxRequest{SandboxID: created.SandboxID}); err == nil {
		command, err = client.RunCommand(ctx, test)
	}
}
if err != nil {
	log.Fatal(err)
}
fmt.Println(command.State)
Rust
use pethost::sandboxes::ErrorDetail;

let request = CreateSandboxRequest { template: "base".into(), name: "api-dev".into(), ..Default::default() };
let created = match sandboxes.create_sandbox(request).await {
    Ok(sandbox) => sandbox,
    Err(error) => match error.details().iter().find_map(|detail| match detail {
        ErrorDetail::NameTaken(taken) => Some(taken.sandbox_id.clone()),
        _ => None,
    }) {
        Some(sandbox_id) => sandboxes.get_sandbox(GetSandboxRequest { sandbox_id, ..Default::default() }).await?,
        None => return Err(error.into()),
    },
};

let test = RunCommandRequest { sandbox_id: created.sandbox_id.clone(), command: "make test".into(), ..Default::default() };
let command = match sandboxes.run_command(test.clone()).await {
    Err(error) if error.details().iter().any(|detail| matches!(detail, ErrorDetail::Stopped(_))) => {
        let resume = ResumeSandboxRequest { sandbox_id: created.sandbox_id.clone(), ..Default::default() };
        sandboxes.resume_sandbox(resume).await?;
        sandboxes.run_command(test).await?
    }
    other => other?,
};
println!("{:?}", command.state);

Refusals with a typed detail

Code and detailWhat it meansWhat to do
FAILED_PRECONDITION + StoppedA call into a STOPPED sandbox, an SSH login or a port request, and its lifecycle does not say wake_when_stopped.ResumeSandbox, then repeat the call.
UNAVAILABLE + RestoringIts disk is being fetched from object storage for its start; fetched_bytes of total_bytes so far, about 10 s a GiB.Wait, then repeat.
UNAVAILABLE + NoCapacityNo server has room for it now; bound says what the last one lacked, and a fork's fork_count how many copies fit.Try again later, or fork fork_count copies or fewer.
RESOURCE_EXHAUSTED + LimitReachedA limit of the plan, named by limit with its max: vcpus, largest_size, volume_gib, template_versions, template_gib, or secrets.Delete or stop what holds it, or choose a larger plan. Running and paused sandboxes hold vCPUs.
RESOURCE_EXHAUSTED + LimitReached, starts_per_minute, _hour, _dayToo many starts in that sliding window: creates, fork copies and starts of stopped sandboxes. Starts are free and bounded.Repeat at retry_time. Without one, the call asks more than the window allows: split it.
FAILED_PRECONDITION + UsageUnpaidNothing pays for the workspace now: its included usage is used up and its balance is empty. Running and paused sandboxes were stopped.The owner adds to the balance, or starts the plan from the trial, in the console. It lifts within seconds.
FAILED_PRECONDITION + AgentSignInA coding agent cannot reach its model: variable names the variable to bind, sign_in_command the command to run instead.Bind a secret to variable, have a person run sign_in_command in the terminal, or use OpenCode.
FAILED_PRECONDITION + WorkspaceChoiceThe call names no workspace and the token reaches several; workspaces lists them.Send workspace, its id or name, in the call or the client.
ALREADY_EXISTS + NameTakenAnother sandbox of the workspace that is not deleted has the name; sandbox_id is that sandbox.Use that sandbox, or choose another name.

Refusals by their code alone

CodeWhat it meansWhat to do
INVALID_ARGUMENTA field is wrong, and the message names it and says what it takes; or a request_id came again with other fields.Fix the field. Do not retry as is.
NOT_FOUNDNo such sandbox, template, volume or secret, or none the token reaches. From a sandbox's server: the sandbox moved to another.Check the id. The SDKs connect again by themselves when a sandbox moved.
FAILED_PRECONDITIONThe state does not allow the call, as the call says: a new size for a PAUSED sandbox, a secret still bound, a volume still mounted, a template still saving, a desktop that did not start.Do what the message says first, then repeat.
ABORTEDThe sandbox's settings changed since you read them (if_revision).Read it again, and redo your change.
RESOURCE_EXHAUSTEDWithout LimitReached: the sandbox serves 64 calls at once already, or a message was over its bound (1 MiB a request, 17 MiB a WriteFiles).End a call or wait; move a large file through a link.
UNAVAILABLEWithout a detail: no server answers now, or the sandbox is moving to another server.Repeat in a moment.
PERMISSION_DENIEDThe API token is not granted the workspace, or a token approved for Agent Sandboxes' MCP server called another API. From a sandbox's server: a token for another server, after a move.Grant the token the workspace in Settings. The SDKs connect again by themselves after a move.
UNAUTHENTICATEDThe token is missing, mistyped, expired or revoked. From a sandbox's server: a connection token that expired or was revoked (revoke_tokens).Check PETHOST_TOKEN. The SDKs ask for a new connection token by themselves.

A runtime call refused with UNAUTHENTICATED, PERMISSION_DENIED or NOT_FOUND by a sandbox's server did nothing. The SDKs and the CLI ask ConnectSandbox again once and repeat it; a program of your own over HTTP does the same.

Answers that say something failed

Some calls succeed and say in their answer that part of the work failed: the call did what it could, and the answer says where it stopped.

AnswerValuesWhat to do
WriteFilesResponse.failureNOT_FOUND, PERMISSION_DENIED, NOT_A_DIRECTORY, IS_A_DIRECTORY, NO_SPACE, EDIT_NOT_FOUND, EDIT_AMBIGUOUSdone_count changes were made; fix the next one and send the rest.
ControlDesktopResponse.failureOFF_SCREEN, UNKNOWN_KEYdone_count actions were done; the screenshot shows the screen after them.
Command.stateTIMED_OUT, STOPPED, LOSTLOST: the sandbox lost its memory while it ran; run it again.
AgentTurn.stateFAILED, STOPPED, LOSTFAILED: failure_message says why. LOST: prompt again.
Sandbox.state_reasonCRASH, UNPAID, IDLE, MAINTENANCECRASH: state_message says why; only ResumeSandbox starts it.

Over MCP, a WriteFiles or ControlDesktop that stopped short is a tool error, its JSON as the API answers it.

At a port, at a link and over SSH

AnswerWhat it meansWhat to do
401 from a portA private port, and the request had no Pethost-Token, an expired one or another port's.Make the port public, or send a fresh token from CreateLink.
503 “stopped: resume it”The sandbox is stopped and does not wake by a request. SSH says the same words.ResumeSandbox, or turn on wake_when_stopped.
503 while restoringIts disk is coming back from object storage.Wait, then repeat.
403 from the egress proxyInside the sandbox: its egress does not allow the host or port, and the answer says what refused it.Add the host to egress.allow.
421 Misdirected RequestInside the sandbox: a plain HTTP request for another host than its connection was opened to.Nothing: the client opens a new connection for that host.

Retrying safely

A call that makes something takes a request_id: CreateSandbox, ForkSandbox, CreateTemplate, CreateVolume, RunCommand and PromptAgent. Send the same id again after a timeout or a lost answer, and the retry answers what the first call did, for 24 hours. The other calls that change something are idempotent as they are: a pause of a paused sandbox, a delete of a deleted one, answer it as it is. One caveat: a sandbox keeps the ids of its commands and turns on its disk, so one that lost its memory may have lost those of its last seconds, and a retry of such a command runs it again.

Questions

What does “stopped: resume it” mean?

The sandbox is stopped and its lifecycle does not wake it at a call. ResumeSandbox starts it, its files as it left them.

Why is my sandbox refused with LimitReached?

The workspace reached a limit of its plan, which limit names: usually vcpus, held by running and paused sandboxes, or a starts window, with retry_time.

Should I retry UNAVAILABLE?

Yes, after a moment. With NoCapacity, a little later; with Restoring, once the disk is back.

Can I parse the error message?

No: branch on the code and the typed detail. The message is a sentence for people and may change.

Try Pethost Agent Sandboxes

A 7-day trial with $1 of usage and 4 vCPUs, with a card. Then a plan from $20 a month, which includes as much usage.

Start the trial