@parcha/agentrun-computer 0.0.0-stage → 0.1.0-beta.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +2411 -2
- package/box/Dockerfile +69 -0
- package/box/agentrun-archil +168 -0
- package/box/build-daytona.py +26 -0
- package/box/build-e2b.mjs +32 -0
- package/box/build-modal.py +17 -0
- package/dist/actions.d.ts +18 -0
- package/dist/actions.js +139 -0
- package/dist/browser.d.ts +151 -0
- package/dist/browser.js +305 -0
- package/dist/browserbase.d.ts +139 -0
- package/dist/browserbase.js +408 -0
- package/dist/child.d.ts +40 -0
- package/dist/child.js +127 -0
- package/dist/client.d.ts +22 -0
- package/dist/client.js +136 -0
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/conformance/archil.d.ts +68 -0
- package/dist/conformance/archil.js +152 -0
- package/dist/conformance/browserbase.d.ts +35 -0
- package/dist/conformance/browserbase.js +45 -0
- package/dist/conformance/cases/apps.d.ts +2 -0
- package/dist/conformance/cases/apps.js +155 -0
- package/dist/conformance/cases/browser.d.ts +4 -0
- package/dist/conformance/cases/browser.js +105 -0
- package/dist/conformance/cases/drift.d.ts +2 -0
- package/dist/conformance/cases/drift.js +64 -0
- package/dist/conformance/cases/exec.d.ts +2 -0
- package/dist/conformance/cases/exec.js +125 -0
- package/dist/conformance/cases/files.d.ts +2 -0
- package/dist/conformance/cases/files.js +294 -0
- package/dist/conformance/cases/health.d.ts +2 -0
- package/dist/conformance/cases/health.js +71 -0
- package/dist/conformance/cases/index.d.ts +9 -0
- package/dist/conformance/cases/index.js +37 -0
- package/dist/conformance/cases/input.d.ts +12 -0
- package/dist/conformance/cases/input.js +109 -0
- package/dist/conformance/cases/isolation.d.ts +21 -0
- package/dist/conformance/cases/isolation.js +98 -0
- package/dist/conformance/cases/lifetime.d.ts +2 -0
- package/dist/conformance/cases/lifetime.js +64 -0
- package/dist/conformance/cases/mount.d.ts +2 -0
- package/dist/conformance/cases/mount.js +252 -0
- package/dist/conformance/cases/process.d.ts +2 -0
- package/dist/conformance/cases/process.js +240 -0
- package/dist/conformance/cases/provider.d.ts +2 -0
- package/dist/conformance/cases/provider.js +302 -0
- package/dist/conformance/cases/screen.d.ts +9 -0
- package/dist/conformance/cases/screen.js +230 -0
- package/dist/conformance/cases/settings.d.ts +57 -0
- package/dist/conformance/cases/settings.js +142 -0
- package/dist/conformance/cases/touch.d.ts +2 -0
- package/dist/conformance/cases/touch.js +117 -0
- package/dist/conformance/cases/util.d.ts +7 -0
- package/dist/conformance/cases/util.js +8 -0
- package/dist/conformance/cdp.d.ts +13 -0
- package/dist/conformance/cdp.js +88 -0
- package/dist/conformance/cli.d.ts +29 -0
- package/dist/conformance/cli.js +231 -0
- package/dist/conformance/daytona-sweep.d.ts +18 -0
- package/dist/conformance/daytona-sweep.js +126 -0
- package/dist/conformance/daytona.d.ts +83 -0
- package/dist/conformance/daytona.js +107 -0
- package/dist/conformance/docker.d.ts +38 -0
- package/dist/conformance/docker.js +70 -0
- package/dist/conformance/drift-daemon.d.ts +8 -0
- package/dist/conformance/drift-daemon.js +41 -0
- package/dist/conformance/e2b-diagnose.d.ts +16 -0
- package/dist/conformance/e2b-diagnose.js +61 -0
- package/dist/conformance/e2b-sweep.d.ts +18 -0
- package/dist/conformance/e2b-sweep.js +132 -0
- package/dist/conformance/e2b.d.ts +74 -0
- package/dist/conformance/e2b.js +111 -0
- package/dist/conformance/fixture.d.ts +65 -0
- package/dist/conformance/fixture.js +98 -0
- package/dist/conformance/index.d.ts +8 -0
- package/dist/conformance/index.js +8 -0
- package/dist/conformance/kernel.d.ts +31 -0
- package/dist/conformance/kernel.js +40 -0
- package/dist/conformance/kind.d.ts +23 -0
- package/dist/conformance/kind.js +58 -0
- package/dist/conformance/modal-sweep.d.ts +22 -0
- package/dist/conformance/modal-sweep.js +213 -0
- package/dist/conformance/modal.d.ts +69 -0
- package/dist/conformance/modal.js +76 -0
- package/dist/conformance/orgo.d.ts +41 -0
- package/dist/conformance/orgo.js +69 -0
- package/dist/conformance/phone-harness.d.ts +61 -0
- package/dist/conformance/phone-harness.js +241 -0
- package/dist/conformance/png.d.ts +16 -0
- package/dist/conformance/png.js +132 -0
- package/dist/conformance/report.d.ts +2 -0
- package/dist/conformance/report.js +86 -0
- package/dist/conformance/runner.d.ts +11 -0
- package/dist/conformance/runner.js +585 -0
- package/dist/conformance/tar.d.ts +13 -0
- package/dist/conformance/tar.js +105 -0
- package/dist/conformance/types.d.ts +257 -0
- package/dist/conformance/types.js +24 -0
- package/dist/daemon-copy.d.ts +40 -0
- package/dist/daemon-copy.js +259 -0
- package/dist/daytona.d.ts +180 -0
- package/dist/daytona.js +1498 -0
- package/dist/desktop.d.ts +24 -0
- package/dist/desktop.js +68 -0
- package/dist/docker/egress-main.d.ts +1 -0
- package/dist/docker/egress-main.js +68 -0
- package/dist/docker/egress-proxy.d.ts +53 -0
- package/dist/docker/egress-proxy.js +450 -0
- package/dist/docker/egress-table.d.ts +39 -0
- package/dist/docker/egress-table.js +197 -0
- package/dist/docker/egress.d.ts +109 -0
- package/dist/docker/egress.js +318 -0
- package/dist/docker/image.d.ts +49 -0
- package/dist/docker/image.js +302 -0
- package/dist/docker/stage.d.ts +21 -0
- package/dist/docker/stage.js +290 -0
- package/dist/docker/volume.d.ts +24 -0
- package/dist/docker/volume.js +67 -0
- package/dist/docker.d.ts +156 -0
- package/dist/docker.js +1277 -0
- package/dist/drift.d.ts +200 -0
- package/dist/drift.js +416 -0
- package/dist/e2b.d.ts +337 -0
- package/dist/e2b.js +1516 -0
- package/dist/entry.d.ts +2 -0
- package/dist/entry.js +24 -0
- package/dist/files.d.ts +50 -0
- package/dist/files.js +208 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +26 -0
- package/dist/isolation.d.ts +29 -0
- package/dist/isolation.js +71 -0
- package/dist/janitor.d.ts +50 -0
- package/dist/janitor.js +135 -0
- package/dist/kernel.d.ts +113 -0
- package/dist/kernel.js +358 -0
- package/dist/kinds.d.ts +79 -0
- package/dist/kinds.js +133 -0
- package/dist/labels.d.ts +23 -0
- package/dist/labels.js +50 -0
- package/dist/modal.d.ts +302 -0
- package/dist/modal.js +1374 -0
- package/dist/mount-archil.d.ts +164 -0
- package/dist/mount-archil.js +471 -0
- package/dist/mount.d.ts +57 -0
- package/dist/mount.js +104 -0
- package/dist/orgo-channel.d.ts +96 -0
- package/dist/orgo-channel.js +391 -0
- package/dist/orgo.d.ts +139 -0
- package/dist/orgo.js +1006 -0
- package/dist/phone-harness.d.ts +185 -0
- package/dist/phone-harness.js +1420 -0
- package/dist/processes.d.ts +24 -0
- package/dist/processes.js +40 -0
- package/dist/protocol.d.ts +729 -0
- package/dist/protocol.js +54 -0
- package/dist/provider.d.ts +245 -0
- package/dist/provider.js +37 -0
- package/dist/providers.d.ts +68 -0
- package/dist/providers.js +25 -0
- package/dist/result.d.ts +15 -0
- package/dist/result.js +2 -0
- package/dist/screen-watch.d.ts +150 -0
- package/dist/screen-watch.js +490 -0
- package/dist/test-connection.d.ts +17 -0
- package/dist/test-connection.js +26 -0
- package/dist/wait.d.ts +23 -0
- package/dist/wait.js +65 -0
- package/package.json +62 -4
|
@@ -0,0 +1,1420 @@
|
|
|
1
|
+
// The phone kind on the phone harness's cloud phones (phone-harness.com): a cloud Android rented by the minute through
|
|
2
|
+
// its HTTPS API, and driven over adb. No computerd runs on a phone: connect() gives a client in this process that
|
|
3
|
+
// answers the protocol's phone groups (screen, input.touch, input.keys, apps, apps.ui_tree) with adb commands, and
|
|
4
|
+
// refuses the rest in words. A cloud iPhone (driven by the API's control URL) is a later change: platform "ios" is
|
|
5
|
+
// refused for now.
|
|
6
|
+
//
|
|
7
|
+
// The library reads no environment: the API key and every setting are options (serve passes PHONE_HARNESS_API_KEY as
|
|
8
|
+
// apiKey). The vendor keeps no labels on a session, so the provider keeps its own in a ledger (an option: serve's store,
|
|
9
|
+
// in memory by default): list, attach, release and the janitor see only the sessions the ledger names, never another
|
|
10
|
+
// session on the same account.
|
|
11
|
+
import { execFile } from "node:child_process";
|
|
12
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
13
|
+
import { readFileSync } from "node:fs";
|
|
14
|
+
import { createConnection } from "node:net";
|
|
15
|
+
import { crc32, deflateSync } from "node:zlib";
|
|
16
|
+
import { checkActions } from "./actions.js";
|
|
17
|
+
import { MAX_CHUNK_BYTES, MAX_UI_NODES, } from "./protocol.js";
|
|
18
|
+
import { checkLifetime, } from "./provider.js";
|
|
19
|
+
import { fail, ok } from "./result.js";
|
|
20
|
+
import { daemonWatch, redactWords } from "./screen-watch.js";
|
|
21
|
+
import { listTested } from "./test-connection.js";
|
|
22
|
+
/** The phone harness's API. */
|
|
23
|
+
export const PHONE_HARNESS_URL = "https://api.phone-harness.com";
|
|
24
|
+
/** What a cloud Android offers through this provider, as its capabilities and hello declare them. */
|
|
25
|
+
export const PHONE_GROUPS = ["screen", "input.touch", "input.keys", "apps", "apps.ui_tree"];
|
|
26
|
+
/** A phone mounts no folder. */
|
|
27
|
+
export const MOUNT = [];
|
|
28
|
+
/** The one configuration it offers, as its capabilities() declare it: the kind registry's entry holds the same. */
|
|
29
|
+
export const CAPABILITIES = [{ kind: "android", groups: [...PHONE_GROUPS] }];
|
|
30
|
+
/** The image a phone is read back by: a cloud Android has none to choose, so a setting that names none takes this. */
|
|
31
|
+
export const PHONE_IMAGE = "android";
|
|
32
|
+
/** The longest lifetime by default: a rented phone bills by the minute. */
|
|
33
|
+
export const DEFAULT_MAX_LIFETIME_MS = 30 * 60_000;
|
|
34
|
+
/** How long create waits for a phone to be ready by default: the service's own CLI waits 240 s. */
|
|
35
|
+
export const DEFAULT_READY_MS = 240_000;
|
|
36
|
+
/** How long one API request may take by default: a stalled request is cut off, and create's own calls stay bounded. */
|
|
37
|
+
const DEFAULT_REQUEST_MS = 30_000;
|
|
38
|
+
/** How long one adb call may take. */
|
|
39
|
+
const ADB_TIMEOUT_MS = 30_000;
|
|
40
|
+
/** The user every shell command on an Android runs as: shell, 2000. */
|
|
41
|
+
const SHELL_USER = "2000:2000";
|
|
42
|
+
const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
43
|
+
/** The ledger's id for a create not answered yet. */
|
|
44
|
+
const pendingId = (requestKey) => `pending-${requestKey}`;
|
|
45
|
+
/** A ledger in this process's memory: the default, and enough for one process that makes and ends its phones. */
|
|
46
|
+
export function memoryLedger() {
|
|
47
|
+
const entries = new Map();
|
|
48
|
+
return {
|
|
49
|
+
put: (entry) => void entries.set(entry.id, structuredClone(entry)),
|
|
50
|
+
get: (id) => structuredClone(entries.get(id)),
|
|
51
|
+
list: () => [...entries.values()].map((entry) => structuredClone(entry)),
|
|
52
|
+
remove: (id) => void entries.delete(id),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** A ledger call that threw: the store could not be read or written. */
|
|
56
|
+
class LedgerFailure extends Error {
|
|
57
|
+
}
|
|
58
|
+
/** The ledger with every throw, sync or async, made a LedgerFailure in words. */
|
|
59
|
+
function guardedLedger(ledger) {
|
|
60
|
+
const guard = (how, call) => async (...args) => {
|
|
61
|
+
try {
|
|
62
|
+
return await call(...args);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
throw new LedgerFailure(`the phone ledger could not be ${how}: ${error instanceof Error ? error.message : String(error)}`);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
return {
|
|
69
|
+
put: guard("written", (entry) => ledger.put(entry)),
|
|
70
|
+
get: guard("read", (id) => ledger.get(id)),
|
|
71
|
+
list: guard("read", () => ledger.list()),
|
|
72
|
+
remove: guard("written", (id) => ledger.remove(id)),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/** fn's result, or a ledger that failed as a result in words: a provider's calls answer, never throw. */
|
|
76
|
+
async function ledgerSafe(fn) {
|
|
77
|
+
try {
|
|
78
|
+
return await fn();
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
if (error instanceof LedgerFailure)
|
|
82
|
+
return fail("phone", error.message);
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** The adb server's port when none is given: adb's own default. */
|
|
87
|
+
export const ADB_SERVER_PORT = 5037;
|
|
88
|
+
/** The environment variables adb reads to find its server or its device: every one is dropped from a spawned adb's. */
|
|
89
|
+
const ADB_ENV = /^(ADB_|ANDROID_ADB_|ANDROID_SERIAL$)/;
|
|
90
|
+
/**
|
|
91
|
+
* The adb CLI (Android platform-tools) at path, by execFile, never a shell, and the adb server it starts, on the
|
|
92
|
+
* loopback at port (adb's own default), spoken to by its socket protocol.
|
|
93
|
+
*
|
|
94
|
+
* env is the environment a spawned adb starts from, with every adb variable dropped from it (ADB_SERVER_SOCKET,
|
|
95
|
+
* ANDROID_ADB_SERVER_SOCKET, ANDROID_ADB_SERVER_ADDRESS, ANDROID_SERIAL, ...), so nothing in it points the CLI at
|
|
96
|
+
* another server than its socket requests reach. The library reads no environment of its own: a caller passes it (the
|
|
97
|
+
* conformance module passes process.env). Without env, a spawned adb inherits the process's environment as it is.
|
|
98
|
+
*/
|
|
99
|
+
export function adbCli(path = "adb", { port = ADB_SERVER_PORT, env } = {}) {
|
|
100
|
+
// Every spawned adb names the server the socket requests go to: without -P it would take its own default, 5037 or
|
|
101
|
+
// ANDROID_ADB_SERVER_PORT, and start or ask another server.
|
|
102
|
+
const spawnEnv = env === undefined ? undefined : Object.fromEntries(Object.entries(env).filter(([name, value]) => value !== undefined && !ADB_ENV.test(name)));
|
|
103
|
+
const run = (args, { timeoutMs, signal, input }) => new Promise((resolve) => {
|
|
104
|
+
const child = execFile(path, ["-P", String(port), ...args], { encoding: "buffer", ...(spawnEnv ? { env: spawnEnv } : {}), timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 64 * 1024 * 1024, ...(signal ? { signal } : {}) }, (error, stdout, stderr) => {
|
|
105
|
+
const code = error?.code;
|
|
106
|
+
if (code === "ENOENT") {
|
|
107
|
+
return resolve(fail("not_found", `the phone provider needs adb (Android platform-tools) on this machine: ${path} is not there; install platform-tools or give the provider's adb option`));
|
|
108
|
+
}
|
|
109
|
+
if (error && error.killed)
|
|
110
|
+
return resolve(fail("timeout", `adb did not finish within ${timeoutMs / 1000} s, so it was killed`));
|
|
111
|
+
if (error && signal?.aborted)
|
|
112
|
+
return resolve(fail("aborted", "adb was aborted"));
|
|
113
|
+
if (error && typeof error.code !== "number")
|
|
114
|
+
return resolve(fail("phone", `adb could not run: ${error.message.split("\n")[0]}`));
|
|
115
|
+
resolve(ok({ exitCode: typeof code === "number" ? code : error ? 1 : 0, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr).toString("utf8") }));
|
|
116
|
+
});
|
|
117
|
+
// stdin always ends, so no adb waits on it; it carries the input when there is one.
|
|
118
|
+
child.stdin?.on("error", () => undefined);
|
|
119
|
+
child.stdin?.end(input ?? "");
|
|
120
|
+
});
|
|
121
|
+
let started;
|
|
122
|
+
const server = async (service, { timeoutMs, transport }) => {
|
|
123
|
+
const what = serviceWords(service);
|
|
124
|
+
started ??= run(["start-server"], { timeoutMs });
|
|
125
|
+
const start = await started;
|
|
126
|
+
if (!start.ok || start.value.exitCode !== 0) {
|
|
127
|
+
started = undefined;
|
|
128
|
+
return start.ok ? fail("phone", `adb start-server failed: ${start.value.stderr.trim().split("\n")[0] || `exit code ${start.value.exitCode}`}`) : start;
|
|
129
|
+
}
|
|
130
|
+
const frame = (request) => `${Buffer.byteLength(request).toString(16).padStart(4, "0")}${request}`;
|
|
131
|
+
return new Promise((resolve) => {
|
|
132
|
+
let buffer = Buffer.alloc(0);
|
|
133
|
+
let settled = false;
|
|
134
|
+
// With a transport: first host:transport-id, whose OKAY binds the socket to the phone; then the service.
|
|
135
|
+
let bound = transport === undefined;
|
|
136
|
+
const done = (result) => {
|
|
137
|
+
if (settled)
|
|
138
|
+
return;
|
|
139
|
+
settled = true;
|
|
140
|
+
clearTimeout(timer);
|
|
141
|
+
socket.destroy();
|
|
142
|
+
resolve(result);
|
|
143
|
+
};
|
|
144
|
+
const socket = createConnection({ host: "127.0.0.1", port });
|
|
145
|
+
const timer = setTimeout(() => done(fail("timeout", `the adb server did not answer ${what} within ${timeoutMs / 1000} s`)), timeoutMs);
|
|
146
|
+
socket.on("connect", () => socket.write(frame(bound ? service : `host:transport-id:${transport}`)));
|
|
147
|
+
socket.on("data", (chunk) => {
|
|
148
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
149
|
+
if (bound || buffer.length < 4)
|
|
150
|
+
return;
|
|
151
|
+
const status = buffer.subarray(0, 4).toString("latin1");
|
|
152
|
+
if (status !== "OKAY")
|
|
153
|
+
return done(adbAnswer(buffer, `host:transport-id:${transport}`));
|
|
154
|
+
buffer = buffer.subarray(4);
|
|
155
|
+
bound = true;
|
|
156
|
+
socket.write(frame(service));
|
|
157
|
+
});
|
|
158
|
+
socket.on("error", (error) => done(fail("phone", `the adb server on 127.0.0.1:${port} could not be reached for ${what}: ${error.message}`)));
|
|
159
|
+
socket.on("close", () => {
|
|
160
|
+
if (!bound)
|
|
161
|
+
return done(fail("phone", `the adb server closed host:transport-id:${transport} before it answered`));
|
|
162
|
+
// A phone's service answers OKAY and then its output, with no length: the output is what follows.
|
|
163
|
+
if (transport !== undefined && buffer.subarray(0, 4).toString("latin1") === "OKAY")
|
|
164
|
+
return done(ok(buffer.subarray(4).toString("utf8")));
|
|
165
|
+
done(adbAnswer(buffer, what));
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
};
|
|
169
|
+
return { run, server };
|
|
170
|
+
}
|
|
171
|
+
/** A service as error words name it: its kind and first word, never the rest (a shell command's code, an endpoint). */
|
|
172
|
+
export function serviceWords(service) {
|
|
173
|
+
const [kind, rest = ""] = service.split(/:(.*)/s);
|
|
174
|
+
return `${kind}:${rest.split(/[\s:]/)[0]}`;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* The adb server's answer: OKAY, or FAIL and its words, each optionally followed by a length-prefixed message. FAIL's
|
|
178
|
+
* words may name the phone's endpoint: they are redacted.
|
|
179
|
+
*/
|
|
180
|
+
export function adbAnswer(raw, what) {
|
|
181
|
+
const status = raw.subarray(0, 4).toString("latin1");
|
|
182
|
+
const rest = raw.subarray(4);
|
|
183
|
+
const length = rest.length >= 4 ? Number.parseInt(rest.subarray(0, 4).toString("latin1"), 16) : Number.NaN;
|
|
184
|
+
const message = Number.isSafeInteger(length) && length >= 0 && rest.length >= 4 + length ? rest.subarray(4, 4 + length).toString("utf8") : rest.toString("utf8");
|
|
185
|
+
if (status === "OKAY")
|
|
186
|
+
return ok(message);
|
|
187
|
+
if (status === "FAIL")
|
|
188
|
+
return fail("phone", `the adb server refused ${what}: ${redactWords(message.trim())}`);
|
|
189
|
+
return fail("phone", `the adb server answered ${what} with ${JSON.stringify(raw.subarray(0, 40).toString("latin1"))}, not OKAY or FAIL`);
|
|
190
|
+
}
|
|
191
|
+
/** The phone-harness provider from its options alone; throws in words when one is missing or wrong. */
|
|
192
|
+
export async function create(options) {
|
|
193
|
+
return new PhoneHarnessProvider(options);
|
|
194
|
+
}
|
|
195
|
+
/** The conformance CLI's module for the phone harness. */
|
|
196
|
+
export const conformance = () => import("./conformance/phone-harness.js");
|
|
197
|
+
const show = (value) => JSON.stringify(value) ?? String(value);
|
|
198
|
+
/** One argument for the phone's sh: single-quoted. */
|
|
199
|
+
const quote = (text) => `'${text.replaceAll("'", "'\\''")}'`;
|
|
200
|
+
/** An Android package id: dotted Java names. */
|
|
201
|
+
const APP_ID = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$/;
|
|
202
|
+
/** An activity component: package/class. */
|
|
203
|
+
const COMPONENT = /^[A-Za-z][A-Za-z0-9_.]*\/[A-Za-z0-9_.$]+$/;
|
|
204
|
+
/** Go's names for the ABIs a phone reports. */
|
|
205
|
+
const ARCH = { "arm64-v8a": "arm64", x86_64: "amd64", x86: "386", "armeabi-v7a": "arm" };
|
|
206
|
+
export class PhoneHarnessProvider {
|
|
207
|
+
id = "phone-harness";
|
|
208
|
+
version = VERSION;
|
|
209
|
+
#apiKey;
|
|
210
|
+
#baseUrl;
|
|
211
|
+
#fetch;
|
|
212
|
+
#adb;
|
|
213
|
+
#ledger;
|
|
214
|
+
#maxLifetimeMs;
|
|
215
|
+
#readyMs;
|
|
216
|
+
#pollMs;
|
|
217
|
+
#now;
|
|
218
|
+
#sleep;
|
|
219
|
+
#requestMs;
|
|
220
|
+
#timeout;
|
|
221
|
+
#daemonVersion;
|
|
222
|
+
/** How many open connections hold each endpoint's adb transport: the last to let go disconnects it. */
|
|
223
|
+
#holders = new Map();
|
|
224
|
+
/** Each endpoint's host:disconnect still on its way: a connect to that endpoint waits for it before its own. */
|
|
225
|
+
#leaving = new Map();
|
|
226
|
+
constructor(options) {
|
|
227
|
+
const { apiKey, platform = "android" } = options ?? {};
|
|
228
|
+
if (typeof apiKey !== "string" || apiKey === "")
|
|
229
|
+
throw new Error("the phone-harness provider needs options.apiKey: serve passes PHONE_HARNESS_API_KEY");
|
|
230
|
+
if (platform === "ios")
|
|
231
|
+
throw new Error('platform "ios" is not offered yet: the phone-harness provider rents a cloud Android; an iPhone is a later change');
|
|
232
|
+
if (platform !== "android")
|
|
233
|
+
throw new Error(`platform ${show(platform)} is not one of android, ios`);
|
|
234
|
+
this.#apiKey = apiKey;
|
|
235
|
+
this.#baseUrl = (options.baseUrl ?? PHONE_HARNESS_URL).replace(/\/+$/, "");
|
|
236
|
+
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
237
|
+
const adb = options.adb;
|
|
238
|
+
if (adb !== undefined && typeof adb !== "string" && !(typeof adb?.run === "function" && typeof adb?.server === "function")) {
|
|
239
|
+
throw new Error("options.adb is the adb CLI's path, or a transport with run() and server()");
|
|
240
|
+
}
|
|
241
|
+
this.#adb = adb === undefined || typeof adb === "string" ? adbCli(adb ?? "adb") : adb;
|
|
242
|
+
this.#ledger = guardedLedger(options.ledger ?? memoryLedger());
|
|
243
|
+
this.#maxLifetimeMs = options.maxLifetimeMs ?? DEFAULT_MAX_LIFETIME_MS;
|
|
244
|
+
if (!(Number.isSafeInteger(this.#maxLifetimeMs) && this.#maxLifetimeMs > 0))
|
|
245
|
+
throw new Error(`maxLifetimeMs ${show(options.maxLifetimeMs)} is not a whole number of milliseconds above 0`);
|
|
246
|
+
this.#readyMs = options.readyMs ?? DEFAULT_READY_MS;
|
|
247
|
+
this.#pollMs = options.pollMs ?? 2000;
|
|
248
|
+
this.#now = options.now ?? (() => Date.now());
|
|
249
|
+
this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
250
|
+
this.#requestMs = options.requestMs ?? DEFAULT_REQUEST_MS;
|
|
251
|
+
if (!(Number.isSafeInteger(this.#requestMs) && this.#requestMs > 0))
|
|
252
|
+
throw new Error(`requestMs ${show(options.requestMs)} is not a whole number of milliseconds above 0`);
|
|
253
|
+
this.#timeout = options.timeout ?? ((ms) => AbortSignal.timeout(ms));
|
|
254
|
+
this.#daemonVersion = options.daemonVersion ?? VERSION;
|
|
255
|
+
}
|
|
256
|
+
capabilities() {
|
|
257
|
+
return {
|
|
258
|
+
kind: "android",
|
|
259
|
+
os: "android",
|
|
260
|
+
daemon: "none",
|
|
261
|
+
lifetime: "vendor",
|
|
262
|
+
network: ["open"],
|
|
263
|
+
isolation: "vm",
|
|
264
|
+
groups: [...PHONE_GROUPS],
|
|
265
|
+
maxLifetimeMs: this.#maxLifetimeMs,
|
|
266
|
+
release: ["delete"],
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
check(spec) {
|
|
270
|
+
const refusals = checkLifetime(spec?.lifetimeMs, this.capabilities());
|
|
271
|
+
if (typeof spec?.image !== "string" || spec.image === "")
|
|
272
|
+
refusals.push({ field: "image", message: "image is required: a name the phone is read back by (a cloud Android has no image to choose)" });
|
|
273
|
+
if (spec?.network !== "open")
|
|
274
|
+
refusals.push({ field: "network", message: `network ${show(spec?.network)}: a cloud phone's network is open, and it cannot be closed or narrowed` });
|
|
275
|
+
if (spec?.user !== undefined)
|
|
276
|
+
refusals.push({ field: "user", message: "user: a cloud phone has no user to choose; every command runs as the phone's shell user" });
|
|
277
|
+
for (const field of ["cpus", "memoryMb", "pids", "workdir"]) {
|
|
278
|
+
if (spec?.[field] !== undefined)
|
|
279
|
+
refusals.push({ field, message: `${field}: a cloud phone's size and folders are the vendor's, and cannot be asked for` });
|
|
280
|
+
}
|
|
281
|
+
if (spec?.mount !== undefined)
|
|
282
|
+
refusals.push({ field: "mount", message: "mount: a cloud phone mounts no folder" });
|
|
283
|
+
return refusals;
|
|
284
|
+
}
|
|
285
|
+
// --- the API ---------------------------------------------------------------------------------------------------
|
|
286
|
+
/** Words without the key, whatever the vendor echoed. */
|
|
287
|
+
#clean(text) {
|
|
288
|
+
return text.replaceAll(this.#apiKey, "[the key]");
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* One request, bounded by ms (default requestMs) and by the caller's signal. A failure is `uncertain` when the
|
|
292
|
+
* service may have acted on the request all the same: no answer (lost, or cut off by its bound), or a 5xx other than
|
|
293
|
+
* phones_busy, the service's own word that nothing was made.
|
|
294
|
+
*/
|
|
295
|
+
async #api(method, path, { body, headers = {}, signal, ms = this.#requestMs } = {}) {
|
|
296
|
+
const bound = this.#timeout(Math.max(1, Math.ceil(ms)));
|
|
297
|
+
const either = signal ? AbortSignal.any([signal, bound]) : bound;
|
|
298
|
+
const cut = (error) => {
|
|
299
|
+
if (signal?.aborted)
|
|
300
|
+
return fail("aborted", `${method} ${path} was aborted`);
|
|
301
|
+
if (bound.aborted)
|
|
302
|
+
return { ...fail("timeout", `${method} ${path}: the phone harness did not answer within ${Math.round(ms / 100) / 10} s`), uncertain: true };
|
|
303
|
+
return { ...fail("unreachable", `${method} ${path}: the phone harness could not be reached: ${this.#clean(error?.message ?? String(error))}`), uncertain: true };
|
|
304
|
+
};
|
|
305
|
+
let response;
|
|
306
|
+
try {
|
|
307
|
+
response = await this.#fetch(`${this.#baseUrl}${path}`, {
|
|
308
|
+
method,
|
|
309
|
+
headers: { Authorization: `Bearer ${this.#apiKey}`, Accept: "application/json", ...(body === undefined ? {} : { "Content-Type": "application/json" }), ...headers },
|
|
310
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
311
|
+
signal: either,
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
return cut(error);
|
|
316
|
+
}
|
|
317
|
+
let text;
|
|
318
|
+
try {
|
|
319
|
+
text = await response.text();
|
|
320
|
+
}
|
|
321
|
+
catch (error) {
|
|
322
|
+
// The answer's body stalled or broke: as a lost answer when it was cut off, else no words.
|
|
323
|
+
if (signal?.aborted || bound.aborted)
|
|
324
|
+
return cut(error);
|
|
325
|
+
text = "";
|
|
326
|
+
}
|
|
327
|
+
let json;
|
|
328
|
+
try {
|
|
329
|
+
json = text === "" ? undefined : JSON.parse(text);
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
json = undefined;
|
|
333
|
+
}
|
|
334
|
+
if (response.ok)
|
|
335
|
+
return ok({ status: response.status, json });
|
|
336
|
+
const answer = (typeof json === "object" && json !== null ? json : {});
|
|
337
|
+
const said = this.#clean(answer.error ?? (text.slice(0, 200) || response.statusText || "no words"));
|
|
338
|
+
const where = `${method} ${path}`;
|
|
339
|
+
if (response.status === 401)
|
|
340
|
+
return fail("denied", `${where}: the phone harness refused the API key (401): ${said}`);
|
|
341
|
+
if (response.status === 403)
|
|
342
|
+
return fail("denied", `${where}: ${said} (403)`);
|
|
343
|
+
if (answer.code === "phones_busy") {
|
|
344
|
+
const retry = answer.retry_after_seconds ?? Number(response.headers.get("retry-after"));
|
|
345
|
+
return fail("limit", `${where}: ${said}${Number.isFinite(retry) && retry > 0 ? `; try again in ${retry} s` : ""} (phones_busy)`);
|
|
346
|
+
}
|
|
347
|
+
if (answer.code === "session_limit")
|
|
348
|
+
return fail("limit", `${where}: ${said} (session_limit)`);
|
|
349
|
+
if (response.status === 404)
|
|
350
|
+
return fail("not_found", `${where}: ${said} (404)`);
|
|
351
|
+
const failed = fail("phone", `${where}: ${said} (${response.status}${answer.code ? `, ${answer.code}` : ""})`);
|
|
352
|
+
// A 5xx is no refusal: a gateway may answer it for a request the service went on to act on.
|
|
353
|
+
return response.status >= 500 ? { ...failed, uncertain: true } : failed;
|
|
354
|
+
}
|
|
355
|
+
async #session(id, signal, ms) {
|
|
356
|
+
const got = await this.#api("GET", `/sessions/${encodeURIComponent(id)}`, { ...(signal ? { signal } : {}), ...(ms === undefined ? {} : { ms }) });
|
|
357
|
+
if (!got.ok)
|
|
358
|
+
return got.error.code === "not_found" ? fail("gone", `${id} has ended`) : got;
|
|
359
|
+
return sessionOf(got.value.json, `GET /sessions/${id}`);
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* DELETE of the phone. The service ends a session asynchronously, so the ledger forgets it only once its own GET is
|
|
363
|
+
* a 404. Until then its entry stays, marked released, and a second release of it answers ok.
|
|
364
|
+
*/
|
|
365
|
+
async #end(id) {
|
|
366
|
+
const ended = await this.#api("DELETE", `/sessions/${encodeURIComponent(id)}`);
|
|
367
|
+
if (!ended.ok && ended.error.code !== "not_found")
|
|
368
|
+
return ended;
|
|
369
|
+
if (ended.ok) {
|
|
370
|
+
const read = await this.#session(id);
|
|
371
|
+
const entry = await this.#ledger.get(id);
|
|
372
|
+
if (!(!read.ok && read.error.code === "gone") && entry !== undefined) {
|
|
373
|
+
await this.#ledger.put({ ...entry, released: entry.released ?? new Date(this.#now()).toISOString() });
|
|
374
|
+
return ok(undefined);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
await this.#ledger.remove(id);
|
|
378
|
+
return ok(undefined);
|
|
379
|
+
}
|
|
380
|
+
#deadlineOf(session, fallback) {
|
|
381
|
+
return new Date(typeof session.expires_at === "number" && Number.isFinite(session.expires_at) ? session.expires_at * 1000 : fallback).toISOString();
|
|
382
|
+
}
|
|
383
|
+
// --- the provider ----------------------------------------------------------------------------------------------
|
|
384
|
+
create(spec, context = {}) {
|
|
385
|
+
return ledgerSafe(() => this.#create(spec, context));
|
|
386
|
+
}
|
|
387
|
+
attach(ref, context = {}) {
|
|
388
|
+
return ledgerSafe(() => this.#attach(ref, context));
|
|
389
|
+
}
|
|
390
|
+
list(labels, context = {}) {
|
|
391
|
+
return ledgerSafe(() => this.#list(labels, context));
|
|
392
|
+
}
|
|
393
|
+
network(ref, policy) {
|
|
394
|
+
return ledgerSafe(() => this.#network(ref, policy));
|
|
395
|
+
}
|
|
396
|
+
release(ref, how) {
|
|
397
|
+
return ledgerSafe(() => this.#release(ref, how));
|
|
398
|
+
}
|
|
399
|
+
connect(ref) {
|
|
400
|
+
return ledgerSafe(() => this.#connect(ref));
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* The live view: the phone client's screen.watch on a connection of the watch's own (daemonWatch), PNG frames from
|
|
404
|
+
* screencap. Upright with no rotation of ours: screencap gives the display in its current orientation, and input tap
|
|
405
|
+
* and swipe take that same space, so each frame's width and height come from its own screencap, never from wm size.
|
|
406
|
+
*/
|
|
407
|
+
watch(ref, handlers, options) {
|
|
408
|
+
return daemonWatch(this, ref, handlers, options);
|
|
409
|
+
}
|
|
410
|
+
async #create(spec, { signal } = {}) {
|
|
411
|
+
const refusals = this.check(spec);
|
|
412
|
+
if (refusals.length > 0)
|
|
413
|
+
return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
|
|
414
|
+
if (signal?.aborted)
|
|
415
|
+
return fail("aborted", "create was aborted before the phone harness was asked");
|
|
416
|
+
const from = this.#now();
|
|
417
|
+
const requestKey = randomBytes(16).toString("hex");
|
|
418
|
+
const body = { platform: "android", kind: "emulator", timeout_seconds: Math.ceil(spec.lifetimeMs / 1000) };
|
|
419
|
+
// The key goes into the ledger before the POST: whatever answers are lost, list() can find the phone by it.
|
|
420
|
+
const pending = pendingId(requestKey);
|
|
421
|
+
await this.#ledger.put({ id: pending, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline: new Date(from + spec.lifetimeMs).toISOString(), request: requestKey });
|
|
422
|
+
const posted = await this.#api("POST", "/sessions", { body, headers: { "Idempotency-Key": requestKey }, ...(signal ? { signal } : {}) });
|
|
423
|
+
const cancelled = !posted.ok && posted.error.code === "aborted";
|
|
424
|
+
let first = posted.ok ? sessionOf(posted.value.json, "POST /sessions") : undefined;
|
|
425
|
+
// Only a refusal (a 4xx, or phones_busy) says nothing was made. No answer, a cancel, a 5xx, or a 2xx with no
|
|
426
|
+
// session in it leaves the request uncertain: the service may have made the phone.
|
|
427
|
+
const uncertain = posted.ok ? !first?.ok : posted.uncertain === true || cancelled;
|
|
428
|
+
if (uncertain) {
|
|
429
|
+
// Ask by its key, never POST again, before the key is forgotten. The ask is create's own, not under the
|
|
430
|
+
// caller's signal, which may have fired; a phone it finds is recorded, and ended below if create was cancelled.
|
|
431
|
+
const why = !posted.ok ? posted.error.message : `POST /sessions answered ${posted.value.status} with no session (${first?.ok === false ? first.error.message : "no words"})`;
|
|
432
|
+
const kept = "the ledger keeps the request's key, so list() finds the phone if it was made";
|
|
433
|
+
const recovered = await this.#api("GET", `/sessions/requests/${requestKey}`);
|
|
434
|
+
if (!recovered.ok)
|
|
435
|
+
return fail(cancelled ? "aborted" : "phone", `${why}; and the service has no session for the request: ${recovered.error.message}; ${kept}`);
|
|
436
|
+
first = sessionOf(recovered.value.json, `GET /sessions/requests/${requestKey}`);
|
|
437
|
+
if (!first.ok)
|
|
438
|
+
return fail(cancelled ? "aborted" : "phone", `${why}; and its recovery answered no session: ${first.error.message}; ${kept}`);
|
|
439
|
+
}
|
|
440
|
+
else if (!posted.ok) {
|
|
441
|
+
// The phone harness refused the request: nothing was made, and the key is forgotten.
|
|
442
|
+
await this.#ledger.remove(pending);
|
|
443
|
+
return posted;
|
|
444
|
+
}
|
|
445
|
+
if (first === undefined || !first.ok)
|
|
446
|
+
return fail("phone", "POST /sessions answered no session");
|
|
447
|
+
const id = first.value.id;
|
|
448
|
+
/** A ledger write about the phone, or the phone ended in words: a phone its ledger cannot record would bill unseen. */
|
|
449
|
+
const record = async (write) => {
|
|
450
|
+
try {
|
|
451
|
+
await write();
|
|
452
|
+
return ok(undefined);
|
|
453
|
+
}
|
|
454
|
+
catch (error) {
|
|
455
|
+
// Ended at once, by the API alone: the ledger has just failed.
|
|
456
|
+
const ended = await this.#api("DELETE", `/sessions/${encodeURIComponent(id)}`);
|
|
457
|
+
const after = ended.ok || ended.error.code === "not_found" ? "the phone was ended" : `the phone ${id} could not be ended (${ended.error.message})`;
|
|
458
|
+
return fail("phone", `${error instanceof Error ? error.message : String(error)}; ${after}`);
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
const named = await record(async () => {
|
|
462
|
+
await this.#ledger.put({ id, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline: this.#deadlineOf(first.value, from + spec.lifetimeMs) });
|
|
463
|
+
await this.#ledger.remove(pending);
|
|
464
|
+
});
|
|
465
|
+
if (!named.ok)
|
|
466
|
+
return named;
|
|
467
|
+
const ended = async (code, words) => {
|
|
468
|
+
const gone = await this.#end(id);
|
|
469
|
+
return fail(code, `${words}; ${gone.ok ? "it was ended" : `it could not be ended (${gone.error.message})`}`);
|
|
470
|
+
};
|
|
471
|
+
if (cancelled)
|
|
472
|
+
return ended("aborted", `create was aborted during POST /sessions, after the service made the phone ${id}`);
|
|
473
|
+
let session = first.value;
|
|
474
|
+
for (;;) {
|
|
475
|
+
if (signal?.aborted)
|
|
476
|
+
return ended("aborted", `create was aborted while the phone ${id} started`);
|
|
477
|
+
// A read takes no longer than readyMs has left, so a stalled one cannot hold create past it.
|
|
478
|
+
const left = this.#readyMs - (this.#now() - from);
|
|
479
|
+
const bound = Math.max(1, Math.min(this.#requestMs, left));
|
|
480
|
+
const read = await this.#session(id, signal, bound);
|
|
481
|
+
if (!read.ok && read.error.code === "timeout") {
|
|
482
|
+
// A read cut off by its own bound (requestMs) while readyMs has time left is one slow answer, not the deadline:
|
|
483
|
+
// ask again. Only a read bounded by what readyMs had left, or the deadline check below, ends the phone.
|
|
484
|
+
if (bound < left && this.#now() - from < this.#readyMs) {
|
|
485
|
+
await this.#sleep(this.#pollMs);
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
return ended("timeout", `the phone ${id} was not ready within ${this.#readyMs / 1000} s: ${read.error.message}`);
|
|
489
|
+
}
|
|
490
|
+
if (!read.ok)
|
|
491
|
+
return ended(read.error.code === "gone" ? "phone" : read.error.code, `the phone ${id} did not start: ${read.error.message}`);
|
|
492
|
+
session = read.value;
|
|
493
|
+
if (session.state === "ready")
|
|
494
|
+
break;
|
|
495
|
+
if (session.state !== "provisioning")
|
|
496
|
+
return ended("phone", `the phone ${id} did not start: ${this.#clean(session.error ?? session.state)}`);
|
|
497
|
+
if (this.#now() - from >= this.#readyMs)
|
|
498
|
+
return ended("timeout", `the phone ${id} was not ready within ${this.#readyMs / 1000} s`);
|
|
499
|
+
await this.#sleep(this.#pollMs);
|
|
500
|
+
}
|
|
501
|
+
const deadline = this.#deadlineOf(session, from + spec.lifetimeMs);
|
|
502
|
+
const kept = await record(() => this.#ledger.put({ id, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline }));
|
|
503
|
+
if (!kept.ok)
|
|
504
|
+
return kept;
|
|
505
|
+
const took = this.#now() - from;
|
|
506
|
+
if (this.#now() >= Date.parse(deadline)) {
|
|
507
|
+
return ended("timeout", `the phone ${id}'s lifetime of ${spec.lifetimeMs / 1000} s ended before it was ready (it took ${Math.round(took / 100) / 10} s)`);
|
|
508
|
+
}
|
|
509
|
+
return ok({ id, name: id });
|
|
510
|
+
}
|
|
511
|
+
async #attach(ref, { signal } = {}) {
|
|
512
|
+
let entry;
|
|
513
|
+
if ("id" in ref) {
|
|
514
|
+
entry = await this.#ledger.get(ref.id);
|
|
515
|
+
if (entry === undefined)
|
|
516
|
+
return fail("not_found", `${ref.id} is not a phone this provider made`);
|
|
517
|
+
if (entry.released !== undefined)
|
|
518
|
+
return fail("not_found", `${ref.id} was released, and the service is ending it`);
|
|
519
|
+
}
|
|
520
|
+
else {
|
|
521
|
+
// A pending entry is a create not answered yet, not a phone: list() adopts it once its phone is seen. A released
|
|
522
|
+
// one is ending.
|
|
523
|
+
const found = (await this.#ledger.list()).filter((one) => one.request === undefined && one.released === undefined && carries(one.labels, ref.labels));
|
|
524
|
+
if (found.length === 0)
|
|
525
|
+
return fail("not_found", `no phone of this provider carries the labels ${show(ref.labels)}`);
|
|
526
|
+
if (found.length > 1)
|
|
527
|
+
return fail("invalid", `${found.length} phones of this provider (${found.map((one) => one.id).join(", ")}) carry the labels ${show(ref.labels)}: attach takes one`);
|
|
528
|
+
entry = found[0];
|
|
529
|
+
}
|
|
530
|
+
const id = entry.id;
|
|
531
|
+
const session = await this.#session(id, signal);
|
|
532
|
+
if (!session.ok) {
|
|
533
|
+
if (session.error.code === "gone")
|
|
534
|
+
await this.#ledger.remove(id);
|
|
535
|
+
return session;
|
|
536
|
+
}
|
|
537
|
+
if (session.value.state !== "ready" && session.value.state !== "provisioning")
|
|
538
|
+
return fail("gone", `${id} is ${session.value.state}`);
|
|
539
|
+
const deadline = new Date(this.#deadlineOf(session.value, Date.parse(entry.deadline)));
|
|
540
|
+
return ok({ id, name: id, spec: { image: entry.image, user: SHELL_USER, network: "open", deadline, kind: "android" } });
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Settings' test: one GET /sessions, the account's sessions joined to the ledger, and a GET of any phone of the
|
|
544
|
+
* ledger the listing leaves out. It rents nothing.
|
|
545
|
+
*/
|
|
546
|
+
async testConnection(context = {}) {
|
|
547
|
+
return listTested("Phone harness", await this.list({}, context));
|
|
548
|
+
}
|
|
549
|
+
async #list(labels, { signal } = {}) {
|
|
550
|
+
// The ledger is read before the account's sessions: a phone whose entry is read was made before the GET, so it is
|
|
551
|
+
// in its answer unless it is gone. An entry a create writes later is not seen by this list, and so not forgotten.
|
|
552
|
+
const entries = await this.#ledger.list();
|
|
553
|
+
const got = await this.#api("GET", "/sessions", signal ? { signal } : {});
|
|
554
|
+
if (!got.ok)
|
|
555
|
+
return got;
|
|
556
|
+
if (!Array.isArray(got.value.json))
|
|
557
|
+
return fail("phone", `GET /sessions answered ${show(got.value.json).slice(0, 200)}, not a list`);
|
|
558
|
+
const live = new Map();
|
|
559
|
+
for (const one of got.value.json) {
|
|
560
|
+
const session = sessionOf(one, "GET /sessions");
|
|
561
|
+
if (session.ok)
|
|
562
|
+
live.set(session.value.id, session.value);
|
|
563
|
+
}
|
|
564
|
+
const out = [];
|
|
565
|
+
for (const listed of entries) {
|
|
566
|
+
let entry = listed;
|
|
567
|
+
if (entry.request !== undefined) {
|
|
568
|
+
// A create not answered yet: its phone is the account's session whose request_key is exactly its key.
|
|
569
|
+
const made = [...live.values()].find((session) => session.request_key === entry.request);
|
|
570
|
+
if (made === undefined) {
|
|
571
|
+
// Still being made, or never made: after its deadline nothing of it can be alive, and it is forgotten.
|
|
572
|
+
if (this.#now() > Date.parse(entry.deadline))
|
|
573
|
+
await this.#ledger.remove(entry.id);
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
if (entries.some((one) => one.id === made.id)) {
|
|
577
|
+
// create has put the session's own entry and not yet removed its key: that entry is the phone, listed
|
|
578
|
+
// in its turn (and kept as it is, released or not), and the key is only dropped.
|
|
579
|
+
await this.#ledger.remove(listed.id);
|
|
580
|
+
continue;
|
|
581
|
+
}
|
|
582
|
+
entry = { id: made.id, labels: { ...entry.labels }, image: entry.image, deadline: this.#deadlineOf(made, Date.parse(entry.deadline)) };
|
|
583
|
+
await this.#ledger.put(entry);
|
|
584
|
+
await this.#ledger.remove(listed.id);
|
|
585
|
+
}
|
|
586
|
+
if (entry.released !== undefined) {
|
|
587
|
+
// Released, and being ended: never listed. Forgotten once the listing leaves it out and its own GET is a 404,
|
|
588
|
+
// or once its deadline has passed.
|
|
589
|
+
if (this.#now() > Date.parse(entry.deadline))
|
|
590
|
+
await this.#ledger.remove(entry.id);
|
|
591
|
+
else if (!live.has(entry.id)) {
|
|
592
|
+
const read = await this.#session(entry.id, signal);
|
|
593
|
+
if (!read.ok && read.error.code === "gone")
|
|
594
|
+
await this.#ledger.remove(entry.id);
|
|
595
|
+
}
|
|
596
|
+
continue;
|
|
597
|
+
}
|
|
598
|
+
let session = live.get(entry.id);
|
|
599
|
+
if (session === undefined) {
|
|
600
|
+
// Not in the listing: its own GET says whether the service ended it (404), and only then is it forgotten.
|
|
601
|
+
const read = await this.#session(entry.id, signal);
|
|
602
|
+
if (!read.ok && read.error.code === "gone") {
|
|
603
|
+
await this.#ledger.remove(entry.id);
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
if (!read.ok)
|
|
607
|
+
return read;
|
|
608
|
+
session = read.value;
|
|
609
|
+
}
|
|
610
|
+
if (!carries(entry.labels, labels) || out.some((info) => info.ref.id === entry.id))
|
|
611
|
+
continue;
|
|
612
|
+
out.push({
|
|
613
|
+
ref: { id: entry.id, name: entry.id },
|
|
614
|
+
labels: { ...entry.labels },
|
|
615
|
+
deadline: new Date(this.#deadlineOf(session, Date.parse(entry.deadline))),
|
|
616
|
+
state: session.state === "ready" || session.state === "provisioning" ? "running" : "stopped",
|
|
617
|
+
network: "open",
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
return ok(out);
|
|
621
|
+
}
|
|
622
|
+
async #network(ref, policy) {
|
|
623
|
+
const entry = await this.#ledger.get(ref.id);
|
|
624
|
+
if (entry === undefined)
|
|
625
|
+
return fail("not_found", `${ref.id} is not a phone this provider made`);
|
|
626
|
+
if (entry.released !== undefined)
|
|
627
|
+
return fail("not_found", `${ref.id} was released, and the service is ending it`);
|
|
628
|
+
if (policy === undefined || policy === "open")
|
|
629
|
+
return ok("open");
|
|
630
|
+
return fail("refused", `network ${show(policy)}: a cloud phone's network is open, and it cannot be closed or narrowed`);
|
|
631
|
+
}
|
|
632
|
+
async #release(ref, how) {
|
|
633
|
+
if (how === "stop")
|
|
634
|
+
return fail("unsupported", "a cloud phone has no stop: release it with delete, which ends the session");
|
|
635
|
+
const entry = await this.#ledger.get(ref.id);
|
|
636
|
+
if (entry?.released !== undefined) {
|
|
637
|
+
// Released already, and the service may still be ending it: ok. Its own GET says whether it is gone, and then it is
|
|
638
|
+
// forgotten; a phone the service still holds running is sent its DELETE again.
|
|
639
|
+
const read = await this.#session(ref.id);
|
|
640
|
+
if (!read.ok && read.error.code === "gone") {
|
|
641
|
+
await this.#ledger.remove(ref.id);
|
|
642
|
+
return ok(undefined);
|
|
643
|
+
}
|
|
644
|
+
if (!read.ok)
|
|
645
|
+
return read;
|
|
646
|
+
return read.value.state === "ready" || read.value.state === "provisioning" ? this.#end(ref.id) : ok(undefined);
|
|
647
|
+
}
|
|
648
|
+
if (entry === undefined) {
|
|
649
|
+
// Not this provider's to end. Its own GET tells a phone already gone (ok, as release is idempotent) from another
|
|
650
|
+
// session on the account, which is refused and never sent a DELETE.
|
|
651
|
+
const read = await this.#session(ref.id);
|
|
652
|
+
if (!read.ok)
|
|
653
|
+
return read.error.code === "gone" ? ok(undefined) : read;
|
|
654
|
+
return fail("not_found", `${ref.id} is not a phone this provider made: it is not ended`);
|
|
655
|
+
}
|
|
656
|
+
return this.#end(ref.id);
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* The adb server's transport id of the phone at endpoint, from host:devices-l, once it is a device: a connected
|
|
660
|
+
* phone may show as offline for a moment first.
|
|
661
|
+
*/
|
|
662
|
+
async #transportOf(endpoint) {
|
|
663
|
+
let last = "not listed";
|
|
664
|
+
for (let tries = 0; tries < 10; tries++) {
|
|
665
|
+
if (tries > 0)
|
|
666
|
+
await this.#sleep(500);
|
|
667
|
+
const listed = await this.#adb.server("host:devices-l", { timeoutMs: ADB_TIMEOUT_MS });
|
|
668
|
+
if (!listed.ok)
|
|
669
|
+
return listed;
|
|
670
|
+
const line = listed.value.split("\n").find((one) => one.trim().split(/\s+/)[0] === endpoint);
|
|
671
|
+
const state = line?.trim().split(/\s+/)[1];
|
|
672
|
+
const id = /\btransport_id:(\d+)\b/.exec(line ?? "")?.[1];
|
|
673
|
+
if (state === "device" && id !== undefined)
|
|
674
|
+
return ok(id);
|
|
675
|
+
last = state ?? "not listed";
|
|
676
|
+
}
|
|
677
|
+
return fail("phone", `adb connected to the phone, and the adb server still lists it as ${last}, not a device`);
|
|
678
|
+
}
|
|
679
|
+
async #connect(ref) {
|
|
680
|
+
const entry = await this.#ledger.get(ref.id);
|
|
681
|
+
if (entry === undefined)
|
|
682
|
+
return fail("not_found", `${ref.id} is not a phone this provider made`);
|
|
683
|
+
if (entry.released !== undefined)
|
|
684
|
+
return fail("not_found", `${ref.id} was released, and the service is ending it`);
|
|
685
|
+
const session = await this.#session(ref.id);
|
|
686
|
+
if (!session.ok)
|
|
687
|
+
return session;
|
|
688
|
+
if (session.value.state !== "ready")
|
|
689
|
+
return fail("gone", `${ref.id} is ${session.value.state}, not ready`);
|
|
690
|
+
let link = session.value.adb;
|
|
691
|
+
if (!(link?.host && link.port && link.code)) {
|
|
692
|
+
const asked = await this.#api("POST", `/sessions/${encodeURIComponent(ref.id)}/adb`);
|
|
693
|
+
if (!asked.ok)
|
|
694
|
+
return asked;
|
|
695
|
+
link = asked.value.json;
|
|
696
|
+
}
|
|
697
|
+
const { host, port, code } = link ?? {};
|
|
698
|
+
// The vendor's shapes (OpenAPI SessionAdb): a DNS name, a port, and a code ph_ and base32 letters. Anything outside
|
|
699
|
+
// these characters is refused rather than passed to adb.
|
|
700
|
+
if (typeof host !== "string" || !/^[A-Za-z0-9.:-]+$/.test(host) || !Number.isSafeInteger(port) || typeof code !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(code)) {
|
|
701
|
+
return fail("phone", `the phone harness gave ${ref.id} no adb link this provider can use (a host, a port and an unlock code)`);
|
|
702
|
+
}
|
|
703
|
+
// The endpoint and the code never reach an argv: the endpoint goes to the adb server over its socket, the unlock as
|
|
704
|
+
// a shell service on a socket the server bound to the phone, and every spawned adb names the phone by its transport id.
|
|
705
|
+
const endpoint = `${host}:${port}`;
|
|
706
|
+
const server = (service) => this.#adb.server(service, { timeoutMs: ADB_TIMEOUT_MS });
|
|
707
|
+
const onPhone = (service, id) => this.#adb.server(service, { timeoutMs: ADB_TIMEOUT_MS, transport: id });
|
|
708
|
+
// The adb server keeps one transport per endpoint, and a second connect reuses it ("already connected"): every
|
|
709
|
+
// connection to the phone holds it, and only the last to let go disconnects it (live run 4). The count and the
|
|
710
|
+
// disconnect are one critical section:
|
|
711
|
+
// - a disconnect still on its way is waited for first, so this connect never reuses a transport it is dropping;
|
|
712
|
+
// - the hold is taken before host:connect, with no await in between, so a last release meanwhile sees this holder
|
|
713
|
+
// and keeps the transport.
|
|
714
|
+
while (this.#leaving.has(endpoint))
|
|
715
|
+
await this.#leaving.get(endpoint);
|
|
716
|
+
this.#holders.set(endpoint, (this.#holders.get(endpoint) ?? 0) + 1);
|
|
717
|
+
let held = true;
|
|
718
|
+
const release = async () => {
|
|
719
|
+
if (!held)
|
|
720
|
+
return;
|
|
721
|
+
held = false;
|
|
722
|
+
const left = (this.#holders.get(endpoint) ?? 1) - 1;
|
|
723
|
+
if (left > 0)
|
|
724
|
+
return void this.#holders.set(endpoint, left);
|
|
725
|
+
this.#holders.delete(endpoint);
|
|
726
|
+
const leaving = server(`host:disconnect:${endpoint}`)
|
|
727
|
+
.catch(() => undefined)
|
|
728
|
+
.finally(() => {
|
|
729
|
+
if (this.#leaving.get(endpoint) === leaving)
|
|
730
|
+
this.#leaving.delete(endpoint);
|
|
731
|
+
});
|
|
732
|
+
this.#leaving.set(endpoint, leaving);
|
|
733
|
+
await leaving;
|
|
734
|
+
};
|
|
735
|
+
const letGo = async (failed) => {
|
|
736
|
+
await release();
|
|
737
|
+
return failed;
|
|
738
|
+
};
|
|
739
|
+
// A failed connect lets its hold go: it drops the transport only when no other connection holds it.
|
|
740
|
+
const connected = await server(`host:connect:${endpoint}`);
|
|
741
|
+
if (!connected.ok)
|
|
742
|
+
return letGo(connected);
|
|
743
|
+
const said = connected.value.trim();
|
|
744
|
+
// adb's answer names the endpoint, so none of it is passed on: the error is the provider's own words.
|
|
745
|
+
if (!said.includes("connected") || /cannot|failed|unable/i.test(said)) {
|
|
746
|
+
return letGo(fail("phone", `adb could not reach the phone of ${ref.id}: the adb server could not connect to its adb endpoint`));
|
|
747
|
+
}
|
|
748
|
+
const transport = await this.#transportOf(endpoint);
|
|
749
|
+
if (!transport.ok)
|
|
750
|
+
return letGo(transport);
|
|
751
|
+
const id = transport.value;
|
|
752
|
+
const adb = (args, { timeoutMs = ADB_TIMEOUT_MS, signal } = {}) => this.#adb.run(["-t", id, ...args], { timeoutMs, ...(signal ? { signal } : {}) });
|
|
753
|
+
// Ask first: the vendor's lock is per TCP connection, so a transport another connection unlocked answers at once,
|
|
754
|
+
// and an `unlock` on it would reach the phone's own sh ("unlock: inaccessible or not found", live run 4).
|
|
755
|
+
const asked = await onPhone("shell:echo ph-ok", id);
|
|
756
|
+
if (!asked.ok)
|
|
757
|
+
return letGo(asked);
|
|
758
|
+
if (!asked.value.includes("ph-ok")) {
|
|
759
|
+
if (!/^locked\b/.test(asked.value.trim()))
|
|
760
|
+
return letGo(fail("phone", `the phone of ${ref.id} answered neither ph-ok nor locked`));
|
|
761
|
+
// The vendor's unlock is the shell command `unlock <code>`, once per connection (docs, guides/connect-adb): the
|
|
762
|
+
// shell service's own string, sent over the adb server's socket bound to the phone, so no argv holds the code.
|
|
763
|
+
// Probe 1 (2026-11-08) showed it live: "unlocked", and getprop answered after it.
|
|
764
|
+
const unlocked = await onPhone(`shell:unlock ${code}`, id);
|
|
765
|
+
if (!unlocked.ok)
|
|
766
|
+
return letGo(unlocked);
|
|
767
|
+
// Another connect may have unlocked the transport meanwhile: the probe below is the judge, the answer only words.
|
|
768
|
+
const probe = await adb(["shell", "echo ph-ok"]);
|
|
769
|
+
if (!probe.ok)
|
|
770
|
+
return letGo(probe);
|
|
771
|
+
if (!probe.value.stdout.toString("utf8").includes("ph-ok")) {
|
|
772
|
+
// The vendor's answer ("wrong code") may echo the code, more than once, or an endpoint: all are taken out.
|
|
773
|
+
const words = redactWords(unlocked.value.trim().split("\n")[0].replaceAll(code, "[code]"));
|
|
774
|
+
return letGo(fail("phone", /\bunlocked\b/.test(unlocked.value) ? `the phone of ${ref.id} stayed locked after its unlock code` : `the phone of ${ref.id} refused its unlock code: ${words}`));
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
const client = new AdbClient(id, adb, release, this.#sleep, this.#now);
|
|
778
|
+
const opened = await client.open(this.#daemonVersion);
|
|
779
|
+
if (!opened.ok) {
|
|
780
|
+
await client.closed();
|
|
781
|
+
return opened;
|
|
782
|
+
}
|
|
783
|
+
const hello = opened.value;
|
|
784
|
+
if (hello.version !== this.version) {
|
|
785
|
+
await client.closed();
|
|
786
|
+
return fail("refused", `hello: the daemon reports version ${hello.version}, expected ${this.version}`);
|
|
787
|
+
}
|
|
788
|
+
return ok({ client, hello, close: () => client.closed() });
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
/** Whether labels carries every one of wanted. */
|
|
792
|
+
const carries = (labels, wanted) => Object.entries(wanted ?? {}).every(([key, value]) => labels[key] === value);
|
|
793
|
+
function sessionOf(json, where) {
|
|
794
|
+
const s = json;
|
|
795
|
+
if (typeof s !== "object" || s === null || typeof s.id !== "string" || typeof s.state !== "string")
|
|
796
|
+
return fail("phone", `${where} answered ${show(json).slice(0, 200)}, not a session`);
|
|
797
|
+
return ok(s);
|
|
798
|
+
}
|
|
799
|
+
// --- the client: the protocol over adb ---------------------------------------------------------------------------
|
|
800
|
+
/** Android's keycode for each key name in KEYS. */
|
|
801
|
+
const KEYCODES = {
|
|
802
|
+
enter: "ENTER",
|
|
803
|
+
tab: "TAB",
|
|
804
|
+
space: "SPACE",
|
|
805
|
+
backspace: "DEL",
|
|
806
|
+
delete: "FORWARD_DEL",
|
|
807
|
+
escape: "ESCAPE",
|
|
808
|
+
insert: "INSERT",
|
|
809
|
+
up: "DPAD_UP",
|
|
810
|
+
down: "DPAD_DOWN",
|
|
811
|
+
left: "DPAD_LEFT",
|
|
812
|
+
right: "DPAD_RIGHT",
|
|
813
|
+
home: "MOVE_HOME",
|
|
814
|
+
end: "MOVE_END",
|
|
815
|
+
pageup: "PAGE_UP",
|
|
816
|
+
pagedown: "PAGE_DOWN",
|
|
817
|
+
shift: "SHIFT_LEFT",
|
|
818
|
+
ctrl: "CTRL_LEFT",
|
|
819
|
+
alt: "ALT_LEFT",
|
|
820
|
+
super: "META_LEFT",
|
|
821
|
+
capslock: "CAPS_LOCK",
|
|
822
|
+
...Object.fromEntries(Array.from({ length: 12 }, (_, i) => [`f${i + 1}`, `F${i + 1}`])),
|
|
823
|
+
};
|
|
824
|
+
const BUTTON_KEYS = { back: "BACK", home: "HOME", app_switch: "APP_SWITCH" };
|
|
825
|
+
const refuse = (code, message) => fail(code, message);
|
|
826
|
+
/** The in-process client of one cloud Android: each protocol method is one or more adb commands. */
|
|
827
|
+
class AdbClient {
|
|
828
|
+
transport;
|
|
829
|
+
adb;
|
|
830
|
+
disconnect;
|
|
831
|
+
sleep;
|
|
832
|
+
now;
|
|
833
|
+
#closed = false;
|
|
834
|
+
#hello;
|
|
835
|
+
#size = [0, 0];
|
|
836
|
+
#scale = 1;
|
|
837
|
+
/** The shot held for screen.read, until read to its end or the next shot. */
|
|
838
|
+
#held;
|
|
839
|
+
/** The newest watch frame's rest, held apart from the shot's (as computerd's is), so neither evicts the other. */
|
|
840
|
+
#watchHeld;
|
|
841
|
+
/**
|
|
842
|
+
* screen.watch's state: the newest frame's seq, what it was read from (a digest of the pixels), the frame, and when
|
|
843
|
+
* the screen was last read (read, by now()).
|
|
844
|
+
*/
|
|
845
|
+
#watch = {
|
|
846
|
+
seq: 0,
|
|
847
|
+
digest: "",
|
|
848
|
+
read: Number.NEGATIVE_INFINITY,
|
|
849
|
+
};
|
|
850
|
+
/** One screen.watch at a time on this connection. */
|
|
851
|
+
#watching = Promise.resolve();
|
|
852
|
+
/** One input.actions batch at a time on this connection: a second waits for the first, whole. */
|
|
853
|
+
#inputs = Promise.resolve();
|
|
854
|
+
/** Fires on close: every adb run and wait in flight ends with it, so a close never waits for the phone. */
|
|
855
|
+
#closing = new AbortController();
|
|
856
|
+
/** The disconnect close started, which the connection's close waits for. */
|
|
857
|
+
#gone = Promise.resolve();
|
|
858
|
+
constructor(
|
|
859
|
+
/** The adb server's transport id of the phone: no secret, so it may be in an argv. */
|
|
860
|
+
transport, adb,
|
|
861
|
+
/** Lets the adb server drop the phone's transport, by its endpoint over the server's socket. */
|
|
862
|
+
disconnect, sleep, now) {
|
|
863
|
+
this.transport = transport;
|
|
864
|
+
this.adb = adb;
|
|
865
|
+
this.disconnect = disconnect;
|
|
866
|
+
this.sleep = sleep;
|
|
867
|
+
this.now = now;
|
|
868
|
+
}
|
|
869
|
+
/** What the phone is: its ABI, its screen's size and density; then the hello it answers. */
|
|
870
|
+
async open(version) {
|
|
871
|
+
const abi = await this.#shell("getprop ro.product.cpu.abi");
|
|
872
|
+
if (!abi.ok)
|
|
873
|
+
return abi;
|
|
874
|
+
const size = await this.#shell("wm size");
|
|
875
|
+
if (!size.ok)
|
|
876
|
+
return size;
|
|
877
|
+
const density = await this.#shell("wm density");
|
|
878
|
+
if (!density.ok)
|
|
879
|
+
return density;
|
|
880
|
+
const sizes = [...size.value.matchAll(/(\d+)x(\d+)/g)];
|
|
881
|
+
const last = sizes.at(-1);
|
|
882
|
+
if (!last)
|
|
883
|
+
return fail("phone", `the phone (adb transport ${this.transport}) did not say its screen's size: ${size.value.trim().slice(0, 100)}`);
|
|
884
|
+
this.#size = [Number(last[1]), Number(last[2])];
|
|
885
|
+
const dpi = [...density.value.matchAll(/(\d+)/g)].at(-1);
|
|
886
|
+
this.#scale = dpi ? Number(dpi[1]) / 160 : 1;
|
|
887
|
+
const reported = abi.value.trim();
|
|
888
|
+
this.#hello = { version, os: "android", kind: "android", arch: ARCH[reported] ?? reported, groups: [...PHONE_GROUPS] };
|
|
889
|
+
return ok(this.#hello);
|
|
890
|
+
}
|
|
891
|
+
close() {
|
|
892
|
+
if (this.#closed)
|
|
893
|
+
return;
|
|
894
|
+
this.#closed = true;
|
|
895
|
+
this.#held = undefined;
|
|
896
|
+
this.#watchHeld = undefined;
|
|
897
|
+
this.#closing.abort();
|
|
898
|
+
this.#gone = this.disconnect().catch(() => undefined);
|
|
899
|
+
}
|
|
900
|
+
/** Closes, and waits until the adb server has let the phone's transport go. */
|
|
901
|
+
async closed() {
|
|
902
|
+
this.close();
|
|
903
|
+
await this.#gone;
|
|
904
|
+
}
|
|
905
|
+
/** The caller's signal and the connection's close, as one signal. */
|
|
906
|
+
#either(signal) {
|
|
907
|
+
return signal ? AbortSignal.any([signal, this.#closing.signal]) : this.#closing.signal;
|
|
908
|
+
}
|
|
909
|
+
/** One shell command on the phone: its stdout, or the failure in words (adb's, redacted: it names the endpoint). */
|
|
910
|
+
async #shell(command, signal, timeoutMs) {
|
|
911
|
+
const ran = await this.adb(["shell", command], { signal: this.#either(signal), ...(timeoutMs === undefined ? {} : { timeoutMs }) });
|
|
912
|
+
if (!ran.ok)
|
|
913
|
+
return ran;
|
|
914
|
+
if (ran.value.exitCode !== 0) {
|
|
915
|
+
const why = (ran.value.stderr.trim() || ran.value.stdout.toString("utf8").trim()).split("\n")[0] || `exit code ${ran.value.exitCode}`;
|
|
916
|
+
return fail("phone", `${command.split(" ").slice(0, 2).join(" ")} on the phone failed: ${redactWords(why)}`);
|
|
917
|
+
}
|
|
918
|
+
return ok(ran.value.stdout.toString("utf8"));
|
|
919
|
+
}
|
|
920
|
+
async #execOut(command, signal) {
|
|
921
|
+
const ran = await this.adb(["exec-out", command], { timeoutMs: 60_000, signal: this.#either(signal) });
|
|
922
|
+
if (!ran.ok)
|
|
923
|
+
return ran;
|
|
924
|
+
if (ran.value.exitCode !== 0)
|
|
925
|
+
return fail("phone", `${command.split(" ")[0]} on the phone failed: ${redactWords(ran.value.stderr.trim().split("\n")[0] || `exit code ${ran.value.exitCode}`)}`);
|
|
926
|
+
return ok(ran.value.stdout);
|
|
927
|
+
}
|
|
928
|
+
async call(method, params, options = {}) {
|
|
929
|
+
if (this.#closed)
|
|
930
|
+
return fail("gone", "the connection to the phone is closed");
|
|
931
|
+
if (options.signal?.aborted)
|
|
932
|
+
return fail("aborted", `${method} was aborted`);
|
|
933
|
+
return (await this.#answer(method, (params ?? {}), options.signal));
|
|
934
|
+
}
|
|
935
|
+
async #answer(method, params, signal) {
|
|
936
|
+
switch (method) {
|
|
937
|
+
case "hello":
|
|
938
|
+
return ok(this.#hello);
|
|
939
|
+
case "ping":
|
|
940
|
+
return ok({});
|
|
941
|
+
case "screen.shot":
|
|
942
|
+
return this.#shot(params.region);
|
|
943
|
+
case "screen.read":
|
|
944
|
+
return this.#read(params.id, params.offset);
|
|
945
|
+
case "screen.watch": {
|
|
946
|
+
const turn = this.#watching.then(() => this.#screenWatch(params, this.#either(signal)));
|
|
947
|
+
this.#watching = turn.catch(() => undefined);
|
|
948
|
+
return turn;
|
|
949
|
+
}
|
|
950
|
+
case "input.actions":
|
|
951
|
+
return this.#inTurn(params.actions, this.#either(signal));
|
|
952
|
+
case "apps.list":
|
|
953
|
+
return this.#appsList();
|
|
954
|
+
case "apps.launch":
|
|
955
|
+
return this.#launch(params.id);
|
|
956
|
+
case "apps.terminate":
|
|
957
|
+
return this.#terminate(params.id);
|
|
958
|
+
case "apps.ui_tree":
|
|
959
|
+
return this.#tree();
|
|
960
|
+
}
|
|
961
|
+
const group = method.split(".")[0];
|
|
962
|
+
if (["exec", "files", "process", "tar"].includes(group))
|
|
963
|
+
return refuse("unsupported", `${method}: a phone has no shell in the computer protocol, so it offers no exec, files or processes`);
|
|
964
|
+
if (method === "apps.install")
|
|
965
|
+
return refuse("unsupported", "apps.install: this phone takes no files to install from");
|
|
966
|
+
if (method === "deadline.extend")
|
|
967
|
+
return refuse("unsupported", "deadline.extend: a cloud phone's session ends when the phone harness says; it has no extend");
|
|
968
|
+
return refuse("unsupported", `${method} is not a method this phone answers`);
|
|
969
|
+
}
|
|
970
|
+
// --- screen --------------------------------------------------------------------------------------------------
|
|
971
|
+
async #shot(region) {
|
|
972
|
+
const raw = await this.#execOut("screencap");
|
|
973
|
+
if (!raw.ok)
|
|
974
|
+
return raw;
|
|
975
|
+
const frame = decodeScreencap(raw.value);
|
|
976
|
+
if (!frame.ok)
|
|
977
|
+
return frame;
|
|
978
|
+
const { width, height, rgba } = frame.value;
|
|
979
|
+
this.#size = [width, height];
|
|
980
|
+
let rect = [0, 0, width, height];
|
|
981
|
+
if (region !== undefined) {
|
|
982
|
+
const r = region;
|
|
983
|
+
if (!(Array.isArray(r) && r.length === 4 && r.every((v) => Number.isSafeInteger(v)) && r[0] >= 0 && r[1] >= 0 && r[2] > 0 && r[3] > 0 && r[0] + r[2] <= width && r[1] + r[3] <= height)) {
|
|
984
|
+
return refuse("invalid", `region ${show(region)} is not [x, y, w, h] inside the ${width}x${height} screen`);
|
|
985
|
+
}
|
|
986
|
+
rect = r;
|
|
987
|
+
}
|
|
988
|
+
const bytes = encodePng(rgba, width, rect);
|
|
989
|
+
const id = randomBytes(6).toString("hex");
|
|
990
|
+
this.#held = { id, bytes };
|
|
991
|
+
const data = bytes.subarray(0, MAX_CHUNK_BYTES);
|
|
992
|
+
return ok({ id, size: bytes.length, data: data.toString("base64"), eof: data.length === bytes.length, width: rect[2], height: rect[3], scale: this.#scale });
|
|
993
|
+
}
|
|
994
|
+
/**
|
|
995
|
+
* screen.watch: the live view's frames, as computerd answers them but as PNG (format png), read with screencap once
|
|
996
|
+
* each WATCH_POLL_MS (about 1 a second) at most, across calls too: an animated screen acked at once is read no faster
|
|
997
|
+
* than an idle one is polled. after is the caller's ack; an older one gets the newest frame at once, and one at the
|
|
998
|
+
* newest waits for a change until waitMs passes. maxWidth scales the frame (nearest pixel); width and height stay the
|
|
999
|
+
* screen's, the input space. quality is checked and has no effect on a PNG. The signal (the caller's cancel and the
|
|
1000
|
+
* connection's close) ends a screencap and a wait in flight.
|
|
1001
|
+
*/
|
|
1002
|
+
async #screenWatch(params, signal) {
|
|
1003
|
+
const { after, waitMs = 2_000, maxWidth = 1_280, quality = 60 } = params;
|
|
1004
|
+
const whole = (v, lo, hi) => Number.isSafeInteger(v) && v >= lo && v <= hi;
|
|
1005
|
+
if (!whole(after, 0, Number.MAX_SAFE_INTEGER))
|
|
1006
|
+
return refuse("invalid", "screen.watch takes after: the seq of the last frame the caller has, 0 for none");
|
|
1007
|
+
if (!whole(waitMs, 0, 10_000))
|
|
1008
|
+
return refuse("invalid", `waitMs ${show(waitMs)} is outside 0 to 10000`);
|
|
1009
|
+
if (!whole(maxWidth, 1, 16_384))
|
|
1010
|
+
return refuse("invalid", `maxWidth ${show(maxWidth)} is outside 1 to 16384`);
|
|
1011
|
+
if (!whole(quality, 1, 100))
|
|
1012
|
+
return refuse("invalid", `quality ${show(quality)} is outside 1 to 100`);
|
|
1013
|
+
const watch = this.#watch;
|
|
1014
|
+
if (after > watch.seq)
|
|
1015
|
+
return refuse("invalid", `after ${after} is past the newest frame, ${watch.seq}`);
|
|
1016
|
+
if (after < watch.seq && watch.frame)
|
|
1017
|
+
return ok(this.#frameAnswer());
|
|
1018
|
+
const aborted = () => refuse("aborted", "screen.watch was aborted");
|
|
1019
|
+
const deadline = this.now() + waitMs;
|
|
1020
|
+
for (;;) {
|
|
1021
|
+
const wait = watch.read + WATCH_POLL_MS - this.now();
|
|
1022
|
+
if (wait > 0)
|
|
1023
|
+
await this.#pause(wait, signal);
|
|
1024
|
+
if (signal.aborted || this.#closed)
|
|
1025
|
+
return aborted();
|
|
1026
|
+
watch.read = this.now();
|
|
1027
|
+
const raw = await this.#execOut("screencap", signal);
|
|
1028
|
+
if (signal.aborted || this.#closed)
|
|
1029
|
+
return aborted();
|
|
1030
|
+
if (!raw.ok)
|
|
1031
|
+
return raw;
|
|
1032
|
+
const read = decodeScreencap(raw.value);
|
|
1033
|
+
if (!read.ok)
|
|
1034
|
+
return read;
|
|
1035
|
+
const { width, height, rgba } = read.value;
|
|
1036
|
+
this.#size = [width, height];
|
|
1037
|
+
// The size is in the digest: a phone turned to landscape may give the same pixels, the other way round.
|
|
1038
|
+
const digest = createHash("sha256").update(`${width}x${height}|`).update(rgba).digest("hex");
|
|
1039
|
+
if (watch.seq === 0 || digest !== watch.digest) {
|
|
1040
|
+
const frameWidth = Math.min(width, maxWidth);
|
|
1041
|
+
const frameHeight = Math.max(1, Math.floor((height * frameWidth) / width));
|
|
1042
|
+
const pixels = frameWidth === width ? rgba : scaleRgba(rgba, width, height, frameWidth, frameHeight);
|
|
1043
|
+
watch.seq += 1;
|
|
1044
|
+
watch.digest = digest;
|
|
1045
|
+
watch.frame = { bytes: encodePng(pixels, frameWidth, [0, 0, frameWidth, frameHeight]), frameWidth, frameHeight, width, height };
|
|
1046
|
+
return ok(this.#frameAnswer());
|
|
1047
|
+
}
|
|
1048
|
+
const left = deadline - this.now();
|
|
1049
|
+
if (left < WATCH_POLL_MS) {
|
|
1050
|
+
// Not another read before the wait is over: answer no change when it is.
|
|
1051
|
+
if (left > 0)
|
|
1052
|
+
await this.#pause(left, signal);
|
|
1053
|
+
if (signal.aborted || this.#closed)
|
|
1054
|
+
return aborted();
|
|
1055
|
+
return ok({ seq: watch.seq, changed: false, width, height });
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
/** The newest frame as screen.watch answers it: its first chunk, the rest held for screen.read. */
|
|
1060
|
+
#frameAnswer() {
|
|
1061
|
+
const { seq, frame } = this.#watch;
|
|
1062
|
+
const { bytes, frameWidth, frameHeight, width, height } = frame;
|
|
1063
|
+
const data = bytes.subarray(0, MAX_CHUNK_BYTES);
|
|
1064
|
+
const eof = data.length === bytes.length;
|
|
1065
|
+
const id = randomBytes(6).toString("hex");
|
|
1066
|
+
if (!eof)
|
|
1067
|
+
this.#watchHeld = { id, bytes };
|
|
1068
|
+
return { seq, changed: true, ...(eof ? {} : { id }), size: bytes.length, data: data.toString("base64"), eof, format: "png", frameWidth, frameHeight, width, height };
|
|
1069
|
+
}
|
|
1070
|
+
/** The rest of the shot or the watch frame held by id, from offset: each is dropped once read to its end. */
|
|
1071
|
+
#read(id, offset) {
|
|
1072
|
+
const frame = this.#watchHeld !== undefined && this.#watchHeld.id === id;
|
|
1073
|
+
const held = frame ? this.#watchHeld : this.#held;
|
|
1074
|
+
if (held === undefined || held.id !== id)
|
|
1075
|
+
return refuse("not_found", `no shot ${show(id)} is held: take one with screen.shot`);
|
|
1076
|
+
if (!(Number.isSafeInteger(offset) && offset >= 0 && offset <= held.bytes.length))
|
|
1077
|
+
return refuse("invalid", `offset ${show(offset)} is not inside the shot's ${held.bytes.length} bytes`);
|
|
1078
|
+
const data = held.bytes.subarray(offset, offset + MAX_CHUNK_BYTES);
|
|
1079
|
+
const eof = offset + data.length >= held.bytes.length;
|
|
1080
|
+
if (eof && frame)
|
|
1081
|
+
this.#watchHeld = undefined;
|
|
1082
|
+
else if (eof)
|
|
1083
|
+
this.#held = undefined;
|
|
1084
|
+
return ok({ data: data.toString("base64"), eof });
|
|
1085
|
+
}
|
|
1086
|
+
// --- input ---------------------------------------------------------------------------------------------------
|
|
1087
|
+
/** The shell commands of one action, or why the phone cannot do it. Its adb call gets busyMs on top of its bound. */
|
|
1088
|
+
#commands(action) {
|
|
1089
|
+
const point = ([x, y]) => `${Math.round(x)} ${Math.round(y)}`;
|
|
1090
|
+
switch (action.type) {
|
|
1091
|
+
case "tap":
|
|
1092
|
+
return { commands: Array.from({ length: action.count ?? 1 }, () => `input tap ${point(action.at)}`) };
|
|
1093
|
+
case "long_press":
|
|
1094
|
+
return { commands: [`input swipe ${point(action.at)} ${point(action.at)} ${action.ms ?? 800}`], busyMs: action.ms ?? 800 };
|
|
1095
|
+
case "swipe": {
|
|
1096
|
+
const path = action.path;
|
|
1097
|
+
if (path.length === 2)
|
|
1098
|
+
return { commands: [`input swipe ${point(path[0])} ${point(path[1])} ${action.ms ?? 300}`], busyMs: action.ms ?? 300 };
|
|
1099
|
+
const last = path[path.length - 1];
|
|
1100
|
+
// input motionevent has no duration, so ms goes between the moves as toybox sleeps. Each segment takes its
|
|
1101
|
+
// share by length, evenly when the path has none. Each motionevent takes time of its own, so the swipe
|
|
1102
|
+
// lasts ms at least.
|
|
1103
|
+
const lengths = path.slice(1).map((p, i) => Math.hypot(p[0] - path[i][0], p[1] - path[i][1]));
|
|
1104
|
+
const total = lengths.reduce((sum, one) => sum + one, 0);
|
|
1105
|
+
const steps = [`input motionevent DOWN ${point(path[0])}`];
|
|
1106
|
+
let gone = 0;
|
|
1107
|
+
let walked = 0;
|
|
1108
|
+
for (const [i, p] of path.slice(1).entries()) {
|
|
1109
|
+
walked += total > 0 ? lengths[i] : 1;
|
|
1110
|
+
const by = action.ms === undefined ? 0 : Math.round((action.ms * walked) / (total > 0 ? total : lengths.length));
|
|
1111
|
+
if (by > gone)
|
|
1112
|
+
steps.push(`sleep ${(by - gone) / 1000}`);
|
|
1113
|
+
gone = by;
|
|
1114
|
+
steps.push(`input motionevent MOVE ${point(p)}`);
|
|
1115
|
+
}
|
|
1116
|
+
steps.push(`input motionevent UP ${point(last)}`);
|
|
1117
|
+
return { commands: [steps.join(";")], busyMs: gone };
|
|
1118
|
+
}
|
|
1119
|
+
case "button":
|
|
1120
|
+
return { commands: [`input keyevent KEYCODE_${BUTTON_KEYS[action.name]}`] };
|
|
1121
|
+
case "type": {
|
|
1122
|
+
if (/[^\x20-\x7e\n]/.test(action.text))
|
|
1123
|
+
return { kind: "unsupported", message: "type: adb's input text takes printable ASCII and line breaks only" };
|
|
1124
|
+
const commands = [];
|
|
1125
|
+
for (const [i, line] of action.text.split("\n").entries()) {
|
|
1126
|
+
if (i > 0)
|
|
1127
|
+
commands.push("input keyevent KEYCODE_ENTER");
|
|
1128
|
+
// input text reads a % followed by s as a space, and nothing else. A space is sent as %s; a literal %s
|
|
1129
|
+
// is split across two calls, so its % ends one and its s starts the next and the two never meet.
|
|
1130
|
+
const pieces = line.split("%s");
|
|
1131
|
+
for (const [j, piece] of pieces.entries()) {
|
|
1132
|
+
const part = `${j > 0 ? "s" : ""}${piece}${j < pieces.length - 1 ? "%" : ""}`;
|
|
1133
|
+
if (part !== "")
|
|
1134
|
+
commands.push(`input text ${quote(part.replaceAll(" ", "%s"))}`);
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
return { commands };
|
|
1138
|
+
}
|
|
1139
|
+
case "key": {
|
|
1140
|
+
if (action.keys.length !== 1)
|
|
1141
|
+
return { kind: "unsupported", message: `key ${show(action.keys)}: a combo of keys is not something adb's input keyevent can press; send one key at a time` };
|
|
1142
|
+
const key = action.keys[0];
|
|
1143
|
+
const press = KEYCODES[key] ? `input keyevent KEYCODE_${KEYCODES[key]}` : /^[a-z0-9]$/.test(key) ? `input keyevent KEYCODE_${key.toUpperCase()}` : `input text ${quote(key)}`;
|
|
1144
|
+
return { commands: Array.from({ length: action.repeat ?? 1 }, () => press) };
|
|
1145
|
+
}
|
|
1146
|
+
case "wait":
|
|
1147
|
+
return { commands: [], waitMs: action.ms };
|
|
1148
|
+
case "pinch":
|
|
1149
|
+
return { kind: "unsupported", message: "pinch: a cloud Android takes one finger through adb, so a pinch is not offered" };
|
|
1150
|
+
case "hold":
|
|
1151
|
+
return { kind: "unsupported", message: "hold: adb's input keyevent cannot keep a key down" };
|
|
1152
|
+
default:
|
|
1153
|
+
return { kind: "unsupported", message: `${action.type} is not an action this phone takes` };
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
/** A wait of ms, which ends early when signal fires. */
|
|
1157
|
+
async #pause(ms, signal) {
|
|
1158
|
+
if (signal === undefined)
|
|
1159
|
+
return this.sleep(ms);
|
|
1160
|
+
if (signal.aborted)
|
|
1161
|
+
return;
|
|
1162
|
+
let stop = () => { };
|
|
1163
|
+
// The listener is on before the sleep starts, so a cancel during it is never missed.
|
|
1164
|
+
const stopped = new Promise((resolve) => {
|
|
1165
|
+
stop = resolve;
|
|
1166
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
1167
|
+
});
|
|
1168
|
+
try {
|
|
1169
|
+
await Promise.race([this.sleep(ms), stopped]);
|
|
1170
|
+
}
|
|
1171
|
+
finally {
|
|
1172
|
+
signal.removeEventListener("abort", stop);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* A batch in its turn: batches run one at a time, since two at once would interleave their adb commands on the phone.
|
|
1177
|
+
* A cancel while the batch waits answers at once, aborted with none of it run, and its turn then passes with nothing
|
|
1178
|
+
* done; a cancel once it runs stops it at the action it is on (#actions).
|
|
1179
|
+
*/
|
|
1180
|
+
#inTurn(actions, signal) {
|
|
1181
|
+
const waitedOut = () => ok({ done: 0, failed: { index: 0, kind: "aborted", message: "action 0: the batch was aborted while it waited for the batch before it; none of it ran" } });
|
|
1182
|
+
let started = false;
|
|
1183
|
+
const turn = this.#inputs.then(() => {
|
|
1184
|
+
started = true;
|
|
1185
|
+
return signal.aborted ? waitedOut() : this.#actions(actions, signal);
|
|
1186
|
+
});
|
|
1187
|
+
this.#inputs = turn.catch(() => undefined);
|
|
1188
|
+
return new Promise((resolve, reject) => {
|
|
1189
|
+
const stop = () => {
|
|
1190
|
+
if (!started)
|
|
1191
|
+
resolve(waitedOut());
|
|
1192
|
+
};
|
|
1193
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
1194
|
+
if (signal.aborted)
|
|
1195
|
+
stop();
|
|
1196
|
+
turn.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
|
|
1197
|
+
});
|
|
1198
|
+
}
|
|
1199
|
+
async #actions(actions, signal) {
|
|
1200
|
+
const refused = checkActions(actions, PHONE_GROUPS);
|
|
1201
|
+
if (refused !== undefined)
|
|
1202
|
+
return ok({ done: 0, failed: refused });
|
|
1203
|
+
const list = actions;
|
|
1204
|
+
const plans = [];
|
|
1205
|
+
for (const [index, action] of list.entries()) {
|
|
1206
|
+
const plan = this.#commands(action);
|
|
1207
|
+
if ("kind" in plan)
|
|
1208
|
+
return ok({ done: 0, failed: { index, kind: plan.kind, message: `action ${index}: ${plan.message}` } });
|
|
1209
|
+
for (const at of pointsOf(action)) {
|
|
1210
|
+
if (at[0] < 0 || at[1] < 0 || at[0] >= this.#size[0] || at[1] >= this.#size[1]) {
|
|
1211
|
+
return ok({ done: 0, failed: { index, kind: "invalid", message: `action ${index}: ${show(at)} is off the ${this.#size[0]}x${this.#size[1]} screen` } });
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
plans.push(plan);
|
|
1215
|
+
}
|
|
1216
|
+
// A cancel stops the batch at the action it is on: before its wait, after it, and before each command.
|
|
1217
|
+
const cancelled = (index) => ok({ done: index, failed: { index, kind: "aborted", message: `action ${index}: the batch was aborted; actions ${index} on did not run` } });
|
|
1218
|
+
for (const [index, plan] of plans.entries()) {
|
|
1219
|
+
if (signal?.aborted)
|
|
1220
|
+
return cancelled(index);
|
|
1221
|
+
if (plan.waitMs !== undefined) {
|
|
1222
|
+
await this.#pause(plan.waitMs, signal);
|
|
1223
|
+
// A wait the cancel cut short is not done.
|
|
1224
|
+
if (signal?.aborted)
|
|
1225
|
+
return cancelled(index);
|
|
1226
|
+
}
|
|
1227
|
+
for (const command of plan.commands) {
|
|
1228
|
+
if (signal?.aborted)
|
|
1229
|
+
return cancelled(index);
|
|
1230
|
+
const ran = await this.#shell(command, signal, ADB_TIMEOUT_MS + (plan.busyMs ?? 0));
|
|
1231
|
+
if (!ran.ok) {
|
|
1232
|
+
const kind = ran.error.code === "timeout" || ran.error.code === "aborted" || ran.error.code === "not_found" ? ran.error.code : "invalid";
|
|
1233
|
+
return ok({ done: index, failed: { index, kind, message: `action ${index}: ${ran.error.message}` } });
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
return ok({ done: plans.length });
|
|
1238
|
+
}
|
|
1239
|
+
// --- apps ----------------------------------------------------------------------------------------------------
|
|
1240
|
+
async #foreground() {
|
|
1241
|
+
const out = await this.#shell("dumpsys activity activities");
|
|
1242
|
+
if (!out.ok)
|
|
1243
|
+
return out;
|
|
1244
|
+
const found = /topResumedActivity=ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)\//.exec(out.value) ?? /mResumedActivity: ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)\//.exec(out.value);
|
|
1245
|
+
return ok(found ? found[1] : null);
|
|
1246
|
+
}
|
|
1247
|
+
async #appsList() {
|
|
1248
|
+
const out = await this.#shell("pm list packages");
|
|
1249
|
+
if (!out.ok)
|
|
1250
|
+
return out;
|
|
1251
|
+
const apps = out.value
|
|
1252
|
+
.split("\n")
|
|
1253
|
+
.filter((line) => line.startsWith("package:"))
|
|
1254
|
+
.map((line) => ({ id: line.slice("package:".length).trim() }))
|
|
1255
|
+
.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
1256
|
+
const foreground = await this.#foreground();
|
|
1257
|
+
if (!foreground.ok)
|
|
1258
|
+
return foreground;
|
|
1259
|
+
return ok({ apps, foreground: foreground.value });
|
|
1260
|
+
}
|
|
1261
|
+
async #launch(id) {
|
|
1262
|
+
if (typeof id !== "string" || !APP_ID.test(id))
|
|
1263
|
+
return refuse("invalid", `id ${show(id)} is not an Android package id`);
|
|
1264
|
+
const resolved = await this.#shell(`cmd package resolve-activity --brief -c android.intent.category.LAUNCHER ${id}`);
|
|
1265
|
+
if (!resolved.ok)
|
|
1266
|
+
return resolved;
|
|
1267
|
+
const component = resolved.value
|
|
1268
|
+
.split("\n")
|
|
1269
|
+
.map((line) => line.trim())
|
|
1270
|
+
.reverse()
|
|
1271
|
+
.find((line) => COMPONENT.test(line));
|
|
1272
|
+
if (component === undefined)
|
|
1273
|
+
return refuse("not_found", `${id} has no activity to launch: is it installed?`);
|
|
1274
|
+
// The app named comes to the front, not whatever its task last held: on Android 15 Settings' task keeps search (another
|
|
1275
|
+
// package) on top, and a plain start resumes it there. A cleared task starts the app itself (phone probe 2).
|
|
1276
|
+
const started = await this.#shell(`am start -W --activity-clear-task -n ${component}`);
|
|
1277
|
+
if (!started.ok)
|
|
1278
|
+
return started;
|
|
1279
|
+
if (/Error:|Exception/.test(started.value))
|
|
1280
|
+
return refuse("phone", `am start of ${component}: ${redactWords(started.value.trim().split("\n").at(-1) ?? "")}`);
|
|
1281
|
+
return ok({});
|
|
1282
|
+
}
|
|
1283
|
+
async #terminate(id) {
|
|
1284
|
+
if (typeof id !== "string" || !APP_ID.test(id))
|
|
1285
|
+
return refuse("invalid", `id ${show(id)} is not an Android package id`);
|
|
1286
|
+
const stopped = await this.#shell(`am force-stop ${id}`);
|
|
1287
|
+
return stopped.ok ? ok({}) : stopped;
|
|
1288
|
+
}
|
|
1289
|
+
async #tree() {
|
|
1290
|
+
const raw = await this.#execOut("uiautomator dump /dev/tty");
|
|
1291
|
+
if (!raw.ok)
|
|
1292
|
+
return raw;
|
|
1293
|
+
const text = raw.value.toString("utf8");
|
|
1294
|
+
const start = text.indexOf("<?xml");
|
|
1295
|
+
if (start < 0)
|
|
1296
|
+
return refuse("unsupported", `uiautomator gave no tree for this screen: ${redactWords(text.trim().split("\n")[0] || "nothing")}`);
|
|
1297
|
+
return parseUiTree(text.slice(start, text.lastIndexOf(">") + 1), this.#size);
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
/** Every point an action touches, to check against the screen. */
|
|
1301
|
+
function pointsOf(action) {
|
|
1302
|
+
if (action.type === "tap" || action.type === "long_press")
|
|
1303
|
+
return [action.at];
|
|
1304
|
+
if (action.type === "swipe")
|
|
1305
|
+
return action.path;
|
|
1306
|
+
return [];
|
|
1307
|
+
}
|
|
1308
|
+
/** The frame `adb exec-out screencap` gives: a header (width, height, format, and a color space on newer Androids), then the pixels. */
|
|
1309
|
+
export function decodeScreencap(raw) {
|
|
1310
|
+
if (raw.length < 12)
|
|
1311
|
+
return fail("phone", `screencap gave ${raw.length} bytes, not a frame`);
|
|
1312
|
+
const width = raw.readUInt32LE(0);
|
|
1313
|
+
const height = raw.readUInt32LE(4);
|
|
1314
|
+
const format = raw.readUInt32LE(8);
|
|
1315
|
+
const pixels = width * height * 4;
|
|
1316
|
+
const header = raw.length - pixels;
|
|
1317
|
+
if (!(width > 0 && height > 0 && (header === 12 || header === 16)))
|
|
1318
|
+
return fail("phone", `screencap gave ${raw.length} bytes for a ${width}x${height} frame`);
|
|
1319
|
+
const rgba = Buffer.from(raw.subarray(header));
|
|
1320
|
+
// 1 is RGBA_8888, 2 RGBX_8888 (alpha unset), 5 BGRA_8888.
|
|
1321
|
+
if (format === 2)
|
|
1322
|
+
for (let i = 3; i < rgba.length; i += 4)
|
|
1323
|
+
rgba[i] = 255;
|
|
1324
|
+
else if (format === 5)
|
|
1325
|
+
for (let i = 0; i < rgba.length; i += 4)
|
|
1326
|
+
[rgba[i], rgba[i + 2]] = [rgba[i + 2], rgba[i]];
|
|
1327
|
+
else if (format !== 1)
|
|
1328
|
+
return fail("unsupported", `screencap gave pixel format ${format}, which this provider does not read`);
|
|
1329
|
+
return ok({ width, height, rgba });
|
|
1330
|
+
}
|
|
1331
|
+
/** How often a waiting screen.watch reads a phone's screen: about once a second (the user-approved decision, 2026-11-09). */
|
|
1332
|
+
const WATCH_POLL_MS = 1_000;
|
|
1333
|
+
/** A width x height RGBA frame scaled to toWidth x toHeight by the nearest pixel. */
|
|
1334
|
+
function scaleRgba(rgba, width, height, toWidth, toHeight) {
|
|
1335
|
+
const out = Buffer.alloc(toWidth * toHeight * 4);
|
|
1336
|
+
for (let y = 0; y < toHeight; y++) {
|
|
1337
|
+
const sy = Math.floor((y * height) / toHeight);
|
|
1338
|
+
for (let x = 0; x < toWidth; x++) {
|
|
1339
|
+
const sx = Math.floor((x * width) / toWidth);
|
|
1340
|
+
rgba.copy(out, (y * toWidth + x) * 4, (sy * width + sx) * 4, (sy * width + sx) * 4 + 4);
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
return out;
|
|
1344
|
+
}
|
|
1345
|
+
/** An 8-bit RGBA PNG, non-interlaced, of rect of a width-wide RGBA frame. */
|
|
1346
|
+
export function encodePng(rgba, width, [x, y, w, h]) {
|
|
1347
|
+
const rows = Buffer.alloc((w * 4 + 1) * h);
|
|
1348
|
+
for (let row = 0; row < h; row++) {
|
|
1349
|
+
const from = ((y + row) * width + x) * 4;
|
|
1350
|
+
rgba.copy(rows, row * (w * 4 + 1) + 1, from, from + w * 4);
|
|
1351
|
+
}
|
|
1352
|
+
const chunk = (type, data) => {
|
|
1353
|
+
const length = Buffer.alloc(4);
|
|
1354
|
+
length.writeUInt32BE(data.length);
|
|
1355
|
+
const typed = Buffer.concat([Buffer.from(type, "latin1"), data]);
|
|
1356
|
+
const crc = Buffer.alloc(4);
|
|
1357
|
+
crc.writeUInt32BE(crc32(typed) >>> 0);
|
|
1358
|
+
return Buffer.concat([length, typed, crc]);
|
|
1359
|
+
};
|
|
1360
|
+
const ihdr = Buffer.alloc(13);
|
|
1361
|
+
ihdr.writeUInt32BE(w, 0);
|
|
1362
|
+
ihdr.writeUInt32BE(h, 4);
|
|
1363
|
+
ihdr.set([8, 6, 0, 0, 0], 8);
|
|
1364
|
+
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(rows)), chunk("IEND", Buffer.alloc(0))]);
|
|
1365
|
+
}
|
|
1366
|
+
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
1367
|
+
const unescape = (text) => text.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (_, name) => name[0] === "#" ? String.fromCodePoint(name[1] === "x" || name[1] === "X" ? Number.parseInt(name.slice(2), 16) : Number(name.slice(1))) : ENTITIES[name.toLowerCase()]);
|
|
1368
|
+
/** uiautomator's dump as the protocol's tree: one root (the window's, or one over several), at most MAX_UI_NODES nodes. */
|
|
1369
|
+
export function parseUiTree(xml, [width, height]) {
|
|
1370
|
+
const top = [];
|
|
1371
|
+
const stack = [];
|
|
1372
|
+
let nodes = 0;
|
|
1373
|
+
let truncated = false;
|
|
1374
|
+
let dropped = 0;
|
|
1375
|
+
for (const tag of xml.matchAll(/<(\/?)node\b([^>]*?)(\/?)>/g)) {
|
|
1376
|
+
const [, closing, body, selfClosing] = tag;
|
|
1377
|
+
if (closing) {
|
|
1378
|
+
if (dropped > 0)
|
|
1379
|
+
dropped--;
|
|
1380
|
+
else
|
|
1381
|
+
stack.pop();
|
|
1382
|
+
continue;
|
|
1383
|
+
}
|
|
1384
|
+
if (dropped > 0 || nodes >= MAX_UI_NODES) {
|
|
1385
|
+
truncated = true;
|
|
1386
|
+
if (!selfClosing)
|
|
1387
|
+
dropped++;
|
|
1388
|
+
continue;
|
|
1389
|
+
}
|
|
1390
|
+
const attrs = {};
|
|
1391
|
+
for (const [, key, value] of body.matchAll(/([\w:-]+)="([^"]*)"/g))
|
|
1392
|
+
attrs[key] = unescape(value);
|
|
1393
|
+
const box = /^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$/.exec(attrs.bounds ?? "");
|
|
1394
|
+
const [x1, y1, x2, y2] = box ? box.slice(1).map(Number) : [0, 0, 0, 0];
|
|
1395
|
+
const bool = (key) => attrs[key] === "true";
|
|
1396
|
+
const node = {
|
|
1397
|
+
role: attrs.class || "node",
|
|
1398
|
+
...(attrs["resource-id"] ? { id: attrs["resource-id"] } : {}),
|
|
1399
|
+
...(attrs.text ? { text: attrs.text } : {}),
|
|
1400
|
+
...(attrs["content-desc"] ? { label: attrs["content-desc"] } : {}),
|
|
1401
|
+
bounds: [x1, y1, Math.max(0, x2 - x1), Math.max(0, y2 - y1)],
|
|
1402
|
+
enabled: bool("enabled"),
|
|
1403
|
+
clickable: bool("clickable"),
|
|
1404
|
+
focused: bool("focused"),
|
|
1405
|
+
selected: bool("selected"),
|
|
1406
|
+
checked: bool("checked"),
|
|
1407
|
+
scrollable: bool("scrollable"),
|
|
1408
|
+
children: [],
|
|
1409
|
+
};
|
|
1410
|
+
nodes++;
|
|
1411
|
+
(stack.at(-1)?.children ?? top).push(node);
|
|
1412
|
+
if (!selfClosing)
|
|
1413
|
+
stack.push(node);
|
|
1414
|
+
}
|
|
1415
|
+
if (top.length === 0)
|
|
1416
|
+
return fail("phone", "uiautomator's dump held no node");
|
|
1417
|
+
if (top.length === 1)
|
|
1418
|
+
return ok({ root: top[0], nodes, truncated });
|
|
1419
|
+
return ok({ root: { role: "hierarchy", bounds: [0, 0, width, height], enabled: true, children: top }, nodes: nodes + 1, truncated });
|
|
1420
|
+
}
|