Skip to content
中文

Cloud phones

A cloud phone is an Android 14 phone running in the cloud, with a 720×1280 screen, operated by an agent or your program. It uses the same sandbox API as a Linux sandbox: create it with templateID: "android" and size: "android-2c4g". A phone has no terminal and no file API; you operate it through one endpoint, POST /sandbox/v1/sandboxes/{id}/act, one action per call.

Create it and wait until it is ready

终端窗口
curl https://api.deepraxis.com/sandbox/v1/sandboxes \
-H "Authorization: Bearer $PRAXIS_API_KEY" \
-H "content-type: application/json" \
-d '{"templateID": "android", "size": "android-2c4g", "ephemeral": true, "timeout": 600}'

A phone is ephemeral only (ephemeral: true) and ends at timeout (seconds); see two sandbox lifecycles. The response carries platform: "android", state and readyAt.

A phone has three states, shown in state on the create response and on GET /sandbox/v1/sandboxes/{id}:

stateMeaningCan you operate it?
startingThe machine is still being builtNo
bootingThe machine runs but the program on the phone has not connected; readyAt is nullNo
runningThe program has connected; readyAt is the epoch-millisecond instant it didYes

The create call usually takes tens of seconds to return, with booting, and state becomes running about a minute and a half after the create was sent. These are indicative figures, not guarantees.

Do not hold one request open waiting for the phone; poll. After the create returns, GET /sandbox/v1/sandboxes/{id} every 2 seconds until state is running. The create request also accepts waitForReady: true, which keeps the whole create open for at most 55 s (creating the machine alone takes tens of seconds, so it often answers before the phone is ready); running out of time is not an error, it answers the state reached and you still poll.

An action sent before running answers 503 DEVICE_NOT_READY; see errors and retries.

See the screen, tap, look again

The loop has three steps: snapshot to read the screen, act on a ref it returned, snapshot again.

  1. snapshot returns the UI tree; every operable node carries a [ref=eN].
  2. tap, long_press, scroll and type name a node with ref.
  3. A ref is valid only for the latest snapshot. A new snapshot replaces all refs; an old ref answers INVALID_PARAMS. After a tap changes the screen, take a new snapshot before using a ref again.

An example snapshot result (after opening the Settings app):

{
"type": "snapshot",
"snapshot": "- scrollable [ref=e1]\n - text \"设置\"\n - clickable [ref=e2]\n - text \"搜索设置\"\n - scrollable [ref=e3]\n - clickable [ref=e4]\n - text \"网络和互联网\"\n - text \"移动网络、WLAN、热点\"\n …",
"refs": 19,
"truncated": false,
"package": "com.android.settings"
}

snapshot is indented text, one line per operable node with [ref=eN], and the node’s text as child lines. refs is how many nodes have a ref and package is the foreground app. A tree over 200000 characters is cut and truncated is true; the refs already given stay valid. The value of a password field is shown as •••.

All actions

The request body is the action itself; type is required. An extra field answers INVALID_PARAMS.

typeBodyNotes
snapshot{"type":"snapshot"}Read the UI tree and mint refs
screenshot{"type":"screenshot"}Capture the screen; see screenshots
tap{"type":"tap","ref":"e5"} or {"type":"tap","x":360,"y":640}Tap a node’s center or a point; give ref or x and y, never both
long_press{"type":"long_press","ref":"e5","durationMs":1500}Press and hold; same ref or x, y rule; durationMs defaults to 1000
swipe{"type":"swipe","from":{"x":360,"y":900},"to":{"x":360,"y":300},"durationMs":300}Finger from from to to; durationMs optional
scroll{"type":"scroll","direction":"down","ref":"e3"}Scroll half a screen at the screen center, or at the ref node; direction is up, down, left or right, and the direction is where the view moves: down shows what is below, right what is to the right; ref is optional
type{"type":"type","text":"hello","ref":"e2"}Type text; with ref it taps that node first, without it types into the focused field; ASCII only
key{"type":"key","key":"back"}Press a key: back, home, recents, enter, delete, power, volume_up, volume_down
open_app{"type":"open_app","package":"com.android.settings","activity":"…"}Open an app; activity optional, omitted opens the launcher activity
close_app{"type":"close_app","package":"com.android.settings"}Force-stop an app
open_url{"type":"open_url","url":"https://example.com"}Open an http or https URL in the phone’s browser
wait{"type":"wait","ms":500}Wait ms milliseconds, then answer; lets the screen settle

Value ranges:

FieldRange
refe plus a positive integer, at most 32 characters, such as e5
x, yInteger, 0 to 10000
durationMs, msInteger, 1 to 10000 milliseconds
textAt most 10000 characters, printable ASCII only
packageJava package name, at least two segments, at most 255 characters
activityAt most 256 characters
urlAt most 2048 characters, http or https

Except snapshot, screenshot and wait, a successful action answers {"type":"ok","ms":58}, where ms is the action’s duration as the phone measured it. wait answers {"type":"wait","ms":500}.

Screenshots

screenshot returns a JPEG inline in the response:

{
"type": "screenshot",
"mediaType": "image/jpeg",
"data": "/9j/4AAQSkZJRgABAQAA…",
"width": 720,
"height": 1280,
"bytes": 31745
}

data is base64 and bytes is the decoded size. To look at one from code mode, build a data URL:

const image = await praxis.sandbox.sandboxes.act({
path: { sandboxID },
body: { type: "screenshot" },
});
const src = "data:" + image.mediaType + ";base64," + image.data;

In your own program, save it as a file with writeFile("screen.jpg", Buffer.from(image.data, "base64")).

Run commands

A phone has no terminal, but it runs shell commands. A command runs as root through sh -c and stderr is merged into stdout, so stderr is always an empty string; read stdout:

终端窗口
curl https://api.deepraxis.com/sandbox/v1/sandboxes/$SANDBOX_ID/commands \
-H "Authorization: Bearer $PRAXIS_API_KEY" \
-H "content-type: application/json" \
-d '{"cmd": "getprop ro.build.version.release; wm size"}'
{ "stdout": "14\nPhysical size: 720x1280\n", "stderr": "", "exitCode": 0 }

The body may carry cwd, envs and timeoutMs (1 to 3600000 milliseconds). A nonzero exit code still answers 200; read exitCode. Background commands are not available on a phone.

Errors and retries

StatusCodeCauseWhat to do
503DEVICE_NOT_READYThe phone is not drivable yet; the body’s state is starting or booting, with retryable: true and Retry-After: 2Wait Retry-After seconds and send the same request, or poll state
503SERVICE_UNAVAILABLEThe phone is connected but answered nothing this time (the action timed out, or the connection went away mid-action), with retryable: true and Retry-After: 2Wait the same way and retry; before retrying, take a snapshot to see whether the previous action took effect
400INVALID_PARAMSThe action is invalid: unknown type, missing field, field out of range, ref and coordinates both given or neither, a ref not in the latest snapshot, non-ASCII textFix the request as the message says; for a stale ref, take a new snapshot
501CAPABILITY_UNSUPPORTEDAn action sent to a Linux sandbox, or the file or terminal API used on a phoneA Linux sandbox has no screen: create one with templateID: "android"; on a phone use commands instead
404INSTANCE_NOT_FOUNDThe sandbox does not exist, was deleted, or belongs to another organizationCreate a new one

Both 503s are retryable; the full example below shows how. An action changes the phone, so after SERVICE_UNAVAILABLE do not blindly resend tap or type: take a snapshot and look.

Timings

These are measurements against a phone in Shanghai, taken on the server side. They are indicative, not guarantees.

ActionRound trip through the phone channelThe phone’s own measurement
tap, key, type450–500 mstap 54 ms, key 4–10 ms, type 23 ms
screenshot, open_appabout 1.1 s
snapshotabout 0.9–1.3 s

The Server-Timing response header gives the call’s three segments: dispatch (before the action left for the phone), phone (from leaving to the phone’s answer) and device (the phone’s own measurement, 0 for an action that does not time itself), for example dispatch;dur=3, phone;dur=118, device;dur=42.

Limits

  • A phone runs one action at a time. Send the next only after the previous call returns.
  • Non-ASCII text (Chinese, emoji) cannot be typed yet; it answers INVALID_PARAMS.
  • A phone has no file API and no terminal; read and write files with commands.
  • A phone is billed per 4-hour block. Ten minutes of use is billed as one block and deleting early does not refund the current block, so use one phone per task and delete it as soon as the task ends.
  • A phone ends at its timeout; reaching it afterwards answers SANDBOX_EXPIRED (410).

Many actions on one connection

The same path, GET /sandbox/v1/sandboxes/{id}/act, with the standard WebSocket upgrade headers is the caller’s action socket: one handshake instead of one HTTP request per action. The server first sends {"type":"ready","instanceId":"…"}; then you send {"id":"…","action":{…}} (action has the same shape as a request body in the table above, id is at most 64 characters) and receive, in submission order, {"id":"…","result":{…}} or {"id":"…","error":{"code":"…","message":"…","retryable":true}}. At most 8 actions may be in flight on one connection (the next answers RATE_LIMITED), and 10 malformed frames in a row close it with 1008. Authentication is your own API Key. Before the handshake, a phone that is not ready answers 503 DEVICE_NOT_READY as well.

Full example

This TypeScript creates a phone, polls until it is ready, opens Settings, reads the screen, taps the first node that has a ref, takes a screenshot, and finally deletes the phone. call retries a 503 after Retry-After. It needs Bun or Node 18 or later; set PRAXIS_API_KEY to your API Key.

import { writeFile } from "node:fs/promises";
const API = "https://api.deepraxis.com/sandbox/v1";
const headers = {
Authorization: `Bearer ${process.env.PRAXIS_API_KEY}`,
"Content-Type": "application/json",
};
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
// One call: JSON in, JSON out. A 503 means the phone is not ready yet, or answered nothing
// this time: wait Retry-After seconds and send the same request again, up to 10 times.
async function call(method: string, path: string, body?: unknown) {
for (let attempt = 0; attempt < 10; attempt++) {
const res = await fetch(`${API}${path}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
});
if (res.status === 503) {
await sleep(Number(res.headers.get("Retry-After") ?? "2") * 1000);
continue;
}
if (res.status === 204) return null;
const json = await res.json();
if (!res.ok) throw new Error(`${method} ${path} -> ${res.status} ${JSON.stringify(json)}`);
return json;
}
throw new Error(`${method} ${path} -> still 503 after 10 attempts`);
}
// 1. Create the phone. The call returns in about 45-50 s with state "booting".
const phone = await call("POST", "/sandboxes", {
templateID: "android",
size: "android-2c4g",
ephemeral: true,
timeout: 600,
});
const id: string = phone.sandboxID;
try {
// 2. Poll until the phone program has connected: state "running".
for (let i = 0; i < 60; i++) {
const detail = await call("GET", `/sandboxes/${id}`);
if (detail.state === "running") break;
await sleep(2000);
}
// 3. Open Settings, then read the screen. The snapshot mints the refs.
await call("POST", `/sandboxes/${id}/act`, { type: "open_app", package: "com.android.settings" });
await call("POST", `/sandboxes/${id}/act`, { type: "wait", ms: 1500 });
const view = await call("POST", `/sandboxes/${id}/act`, { type: "snapshot" });
console.log(view.snapshot);
// 4. Tap the first node that has a ref, exactly as the latest snapshot named it.
const ref = /\[ref=(e\d+)\]/.exec(view.snapshot)?.[1];
if (ref) await call("POST", `/sandboxes/${id}/act`, { type: "tap", ref });
// 5. Look at the result: a JPEG, base64 inline.
const image = await call("POST", `/sandboxes/${id}/act`, { type: "screenshot" });
await writeFile("screen.jpg", Buffer.from(image.data, "base64"));
console.log(image.mediaType, image.width, image.height, image.bytes);
} finally {
// 6. Release the phone, even when a step above failed.
await call("DELETE", `/sandboxes/${id}`);
}

Expected output: first the Settings UI tree, and a last line like image/jpeg 720 1280 31745; the current directory gains a screen.jpg.

In code mode, the methods of praxis.sandbox.sandboxes do the same. create, retrieve, act and delete all take { path, body }, and the sandbox id in path is called sandboxID:

const { sandboxes } = praxis.sandbox;
const phone = await sandboxes.create({
body: { templateID: "android", size: "android-2c4g", ephemeral: true, timeout: 600 },
});
const sandboxID = phone.sandboxID;
try {
// Poll until running; wait 2 s between retrieves
let state = phone.state;
while (state !== "running") {
await new Promise((resolve) => setTimeout(resolve, 2000));
state = (await sandboxes.retrieve({ path: { sandboxID } })).state;
}
await sandboxes.act({ path: { sandboxID }, body: { type: "open_app", package: "com.android.settings" } });
await sandboxes.act({ path: { sandboxID }, body: { type: "wait", ms: 1500 } });
const view = await sandboxes.act({ path: { sandboxID }, body: { type: "snapshot" } });
const ref = /\[ref=(e\d+)\]/.exec(view.snapshot)?.[1];
if (ref) await sandboxes.act({ path: { sandboxID }, body: { type: "tap", ref } });
const image = await sandboxes.act({ path: { sandboxID }, body: { type: "screenshot" } });
console.log("data:" + image.mediaType + ";base64," + image.data);
} finally {
await sandboxes.delete({ path: { sandboxID } });
}

Give an agent its own phone

So far your program opened the phone itself. A general agent can also have its own phone, and the platform powers it on and off and keeps it for the agent:

  1. Turn it on: switch on 手机 (Phone) in the agent’s settings, or call POST /agent/v1/agents/{agent_id} with "phone": {}. Omitted fields take their defaults: model android-2c4g, name Phone. Having phone in the configuration means it is on; "phone": null turns it off. A service agent cannot have a phone; sending one answers 400.
  2. How the agent uses it: its sessions gain a phone tool with the same actions plus power_on, power_off and status. The tool has no action to change the model or reset the phone; power_off is how the agent lets it go, and only a person changes the model, in settings.
  3. How it starts: the model calls power_on. That call returns at once; the phone is usually ready in 60–90 s (longer when it restores last time’s apps). Do other work while it starts — any other action waits up to 15 s and otherwise tells you it is still starting. A session that never touches the phone costs nothing.
  4. One power-on is one fixed 4-hour session: counted from power_on, it powers off on its own at the end and nothing extends it. To keep working, call power_on again — that is a new session, and it restores last time’s apps and logins.
  5. App state is kept: about 15 minutes before a phone powers off, the platform packs third-party apps’ data directories and installs into File. On the next phone it reinstalls them and puts the data back before the agent’s first action. The system accounts and /sdcard are not kept. Apps that bind a login to the hardware (WeChat, banking apps) may need one fresh sign-in on the new device, done by a person in the screen tab. List apps not to keep in phone.archive.exclude.
  6. Changing the model or turning it off ("phone": null) archives the old phone first, then releases it.

Watch and take over

  • GET /agent/v1/agents/{agent_id}/phone answers the phone’s state (none, starting, booting, restoring, running, archiving, releasing), its sandbox_id, lease_ends_at (when the current block ends) and archived_at (the last archive). none means no phone is running now.
  • With the sandbox_id, drive it through this page’s act, or open it in the Console under Sandbox → Instances, where the 屏幕 (Screen) tab shows it live and lets a person tap and type, for example to sign in or enter a code.
  • POST /agent/v1/agents/{agent_id}/phone/release releases it now: archive first, then shut down. The configuration stays, and the next use boots a new phone and restores the archive. Repeating the call is safe.
  • These two operations are for people and their programs; the agent’s tool cannot call them.

Next steps