@parcha/agentrun-computer 0.1.0-beta.36 → 0.1.0-beta.38

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.
Files changed (155) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +547 -478
  3. package/box/Dockerfile +18 -1
  4. package/box/README.md +13 -0
  5. package/box/build-agent37.mjs +158 -0
  6. package/box/build-daytona.py +2 -2
  7. package/box/build-e2b.mjs +41 -18
  8. package/box/recipe.mjs +43 -0
  9. package/dist/agent37-ssh.d.ts +89 -0
  10. package/dist/agent37-ssh.js +445 -0
  11. package/dist/agent37.d.ts +104 -0
  12. package/dist/agent37.js +402 -0
  13. package/dist/attach.d.ts +146 -0
  14. package/dist/attach.js +469 -0
  15. package/dist/browserbase.d.ts +2 -10
  16. package/dist/browserbase.js +3 -6
  17. package/dist/client.d.ts +45 -4
  18. package/dist/client.js +92 -4
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/computerd.json +4 -0
  22. package/dist/conformance/agent37.d.ts +96 -0
  23. package/dist/conformance/agent37.js +154 -0
  24. package/dist/conformance/cases/apps.d.ts +11 -0
  25. package/dist/conformance/cases/apps.js +173 -73
  26. package/dist/conformance/cases/health.js +14 -0
  27. package/dist/conformance/cases/index.js +2 -0
  28. package/dist/conformance/cases/isolation.d.ts +7 -5
  29. package/dist/conformance/cases/isolation.js +44 -14
  30. package/dist/conformance/cases/mount.js +1 -1
  31. package/dist/conformance/cases/provider.js +27 -1
  32. package/dist/conformance/cases/screen.d.ts +3 -0
  33. package/dist/conformance/cases/screen.js +18 -0
  34. package/dist/conformance/cases/settings.d.ts +29 -23
  35. package/dist/conformance/cases/settings.js +76 -58
  36. package/dist/conformance/cases/touch.js +19 -17
  37. package/dist/conformance/cases/ui.d.ts +2 -0
  38. package/dist/conformance/cases/ui.js +475 -0
  39. package/dist/conformance/cli.d.ts +9 -0
  40. package/dist/conformance/cli.js +94 -9
  41. package/dist/conformance/daytona.d.ts +9 -20
  42. package/dist/conformance/daytona.js +12 -21
  43. package/dist/conformance/e2b.d.ts +6 -0
  44. package/dist/conformance/e2b.js +9 -2
  45. package/dist/conformance/exec-stream.d.ts +45 -0
  46. package/dist/conformance/exec-stream.js +486 -0
  47. package/dist/conformance/fixture.d.ts +1 -1
  48. package/dist/conformance/fixture.js +25 -1
  49. package/dist/conformance/modal.d.ts +17 -13
  50. package/dist/conformance/modal.js +18 -9
  51. package/dist/conformance/orgo.d.ts +3 -3
  52. package/dist/conformance/orgo.js +6 -8
  53. package/dist/conformance/phone-harness.d.ts +6 -2
  54. package/dist/conformance/phone-harness.js +21 -4
  55. package/dist/conformance/report.js +1 -1
  56. package/dist/conformance/runner.js +23 -4
  57. package/dist/conformance/sweep.d.ts +50 -0
  58. package/dist/conformance/sweep.js +187 -0
  59. package/dist/conformance/types.d.ts +13 -5
  60. package/dist/conformance/ui-fixture.d.ts +56 -0
  61. package/dist/conformance/ui-fixture.js +43 -0
  62. package/dist/create-requests.d.ts +51 -0
  63. package/dist/create-requests.js +121 -0
  64. package/dist/daytona.d.ts +20 -133
  65. package/dist/daytona.js +405 -1449
  66. package/dist/descriptor.d.ts +11 -1
  67. package/dist/descriptor.js +9 -0
  68. package/dist/descriptors/agent37.d.ts +41 -0
  69. package/dist/descriptors/agent37.js +28 -0
  70. package/dist/descriptors/daytona.d.ts +6 -5
  71. package/dist/descriptors/daytona.js +9 -5
  72. package/dist/descriptors/index.d.ts +42 -7
  73. package/dist/descriptors/index.js +4 -2
  74. package/dist/descriptors/orgo.d.ts +2 -1
  75. package/dist/descriptors/orgo.js +3 -2
  76. package/dist/descriptors/phone-harness.d.ts +1 -1
  77. package/dist/descriptors/phone-harness.js +2 -2
  78. package/dist/descriptors/shared.d.ts +1 -1
  79. package/dist/descriptors/shared.js +2 -2
  80. package/dist/desktop.d.ts +18 -4
  81. package/dist/desktop.js +89 -9
  82. package/dist/docker.d.ts +7 -10
  83. package/dist/docker.js +272 -34
  84. package/dist/drift.js +4 -4
  85. package/dist/e2b.d.ts +16 -290
  86. package/dist/e2b.js +230 -1393
  87. package/dist/fake-ui-driver.d.ts +97 -0
  88. package/dist/fake-ui-driver.js +717 -0
  89. package/dist/host.d.ts +201 -0
  90. package/dist/host.js +8 -0
  91. package/dist/hosted/process.d.ts +81 -0
  92. package/dist/hosted/process.js +259 -0
  93. package/dist/hosted/provider.d.ts +160 -0
  94. package/dist/hosted/provider.js +1415 -0
  95. package/dist/hosted/rest.d.ts +66 -0
  96. package/dist/hosted/rest.js +121 -0
  97. package/dist/hosted/scripts.d.ts +82 -0
  98. package/dist/{child.js → hosted/scripts.js} +118 -12
  99. package/dist/hosted/values.d.ts +5 -0
  100. package/dist/hosted/values.js +8 -0
  101. package/dist/index.d.ts +7 -3
  102. package/dist/index.js +7 -4
  103. package/dist/kernel.d.ts +2 -10
  104. package/dist/kernel.js +3 -6
  105. package/dist/kinds.d.ts +11 -2
  106. package/dist/kinds.js +20 -4
  107. package/dist/local-chrome.d.ts +2 -10
  108. package/dist/local-chrome.js +3 -6
  109. package/dist/modal.d.ts +22 -257
  110. package/dist/modal.js +183 -1280
  111. package/dist/mount-archil.d.ts +8 -4
  112. package/dist/mount-archil.js +22 -11
  113. package/dist/mount.d.ts +10 -4
  114. package/dist/mount.js +8 -4
  115. package/dist/orgo-channel.d.ts +3 -2
  116. package/dist/orgo-channel.js +5 -2
  117. package/dist/orgo-desktop.d.ts +9 -4
  118. package/dist/orgo-desktop.js +33 -13
  119. package/dist/orgo-workspaces.d.ts +47 -0
  120. package/dist/orgo-workspaces.js +94 -0
  121. package/dist/orgo.d.ts +10 -13
  122. package/dist/orgo.js +32 -21
  123. package/dist/phone-harness.d.ts +31 -28
  124. package/dist/phone-harness.js +510 -702
  125. package/dist/png.d.ts +4 -0
  126. package/dist/png.js +27 -0
  127. package/dist/protocol.d.ts +339 -33
  128. package/dist/protocol.js +97 -3
  129. package/dist/provider.d.ts +36 -8
  130. package/dist/provider.js +16 -0
  131. package/dist/providers.d.ts +11 -12
  132. package/dist/result.d.ts +1 -1
  133. package/dist/screen-watch.js +34 -6
  134. package/dist/surface/api.d.ts +260 -0
  135. package/dist/surface/api.js +1 -0
  136. package/dist/surface/core.d.ts +55 -0
  137. package/dist/surface/core.js +475 -0
  138. package/dist/surface/index.d.ts +5 -0
  139. package/dist/surface/index.js +3 -0
  140. package/dist/surface/outline.d.ts +10 -0
  141. package/dist/surface/outline.js +51 -0
  142. package/dist/surface/script.d.ts +10 -0
  143. package/dist/surface/script.js +94 -0
  144. package/dist/ui-engine.d.ts +114 -0
  145. package/dist/ui-engine.js +814 -0
  146. package/package.json +18 -3
  147. package/dist/child.d.ts +0 -42
  148. package/dist/conformance/daytona-sweep.d.ts +0 -18
  149. package/dist/conformance/daytona-sweep.js +0 -126
  150. package/dist/conformance/e2b-diagnose.d.ts +0 -16
  151. package/dist/conformance/e2b-diagnose.js +0 -61
  152. package/dist/conformance/e2b-sweep.d.ts +0 -18
  153. package/dist/conformance/e2b-sweep.js +0 -132
  154. package/dist/conformance/modal-sweep.d.ts +0 -22
  155. package/dist/conformance/modal-sweep.js +0 -213
@@ -1,8 +1,8 @@
1
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.
2
+ // its HTTPS API, and driven over adb. connect() pushes phoned (daemon-android/, the phone's driver: one dex jar) to the
3
+ // phone when it lacks it, starts it as the shell user through app_process, and speaks the protocol to it over adb's
4
+ // exec: service: phoned answers the phone groups (exec, screen, input.touch, input.keys, apps, ui) on the phone itself.
5
+ // A cloud iPhone (driven by the API's control URL) is a later change: platform "ios" is refused for now.
6
6
  //
7
7
  // The library reads no environment: the API key and every setting are options (serve passes PHONE_HARNESS_API_KEY as
8
8
  // apiKey). The vendor keeps no labels on a session, so the provider keeps its own in a ledger (an option: serve's store,
@@ -11,12 +11,14 @@
11
11
  import { execFile } from "node:child_process";
12
12
  import { createHash, randomBytes } from "node:crypto";
13
13
  import { readFileSync } from "node:fs";
14
+ import { readFile } from "node:fs/promises";
14
15
  import { createConnection } from "node:net";
15
- import { promisify } from "node:util";
16
- import { crc32, deflate } from "node:zlib";
17
- import { checkActions } from "./actions.js";
16
+ import { basename } from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+ import { DaemonClient } from "./client.js";
19
+ import { CreateRequests, endedWords, labelsDiffer, otherSpecWords } from "./create-requests.js";
18
20
  import { PHONE_GROUPS, PHONE_HARNESS } from "./descriptors/phone-harness.js";
19
- import { MAX_CHUNK_BYTES, MAX_UI_NODES, PROTOCOL_VERSION, } from "./protocol.js";
21
+ import { PROTOCOL_VERSION } from "./protocol.js";
20
22
  import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
21
23
  import { failFor, ok, vendorFail } from "./result.js";
22
24
  import { daemonWatch, redactWords } from "./screen-watch.js";
@@ -25,10 +27,6 @@ import { listTested } from "./test-connection.js";
25
27
  const fail = failFor("phone-harness");
26
28
  /** The phone harness's API. */
27
29
  export const PHONE_HARNESS_URL = "https://api.phone-harness.com";
28
- /** A phone mounts no folder. */
29
- export const MOUNT = PHONE_HARNESS.mounts;
30
- /** The one configuration it offers, as its capabilities() declare it: its descriptor's. */
31
- export const CAPABILITIES = PHONE_HARNESS.capabilities;
32
30
  /** The longest lifetime by default: a rented phone bills by the minute. */
33
31
  export const DEFAULT_MAX_LIFETIME_MS = 30 * 60_000;
34
32
  /** How long create waits for a phone to be ready by default: the service's own CLI waits 240 s. */
@@ -39,14 +37,51 @@ const DEFAULT_REQUEST_MS = 30_000;
39
37
  const ADB_TIMEOUT_MS = 30_000;
40
38
  /** The user every shell command on an Android runs as: shell, 2000. */
41
39
  const SHELL_USER = "2000:2000";
40
+ /** phoned's jar in this package, built by npm run build:phoned beside the compiled modules. */
41
+ const DEFAULT_PHONED_PATH = fileURLToPath(new URL("./phoned.jar", import.meta.url));
42
+ /** Where phoned's jars and logs go on a phone: the shell user's own directory. */
43
+ const PHONE_TMP = "/data/local/tmp";
44
+ /** How long a jar push may take: about 70 KB, over a link to a cloud phone. */
45
+ const PUSH_TIMEOUT_MS = 120_000;
46
+ /** How long phoned may take to start and answer hello: app_process starts a runtime first. */
47
+ const HELLO_TIMEOUT_MS = 30_000;
48
+ /**
49
+ * How long a phoned whose connection closed has to exit before the next phoned on its phone kills it: once its stdin
50
+ * ends it gives its running requests 3 s, lets go of the phone's accessibility and exits.
51
+ */
52
+ const PHONED_EXIT_S = 10;
53
+ /** How long a killed phoned has to be gone. */
54
+ const PHONED_KILL_S = 2;
55
+ /**
56
+ * A shell command for the phone that waits until the process is gone (a zombie counts: it holds nothing; so does
57
+ * another process that took its pid), up to PHONED_EXIT_S; then kills it and waits PHONED_KILL_S more. Its last line is
58
+ * exited, killed or running. /proc/<pid>/stat less its "<pid> (<name>) " gives the state as $1 and the start time as ${20}.
59
+ */
60
+ function untilGone({ pid, start }) {
61
+ const wait = (seconds) => `n=0; while alive && [ $n -lt ${seconds * 10} ]; do sleep 0.1; n=$((n+1)); done`;
62
+ return `p=${pid}; t=${start}; alive() { s=$(cat /proc/$p/stat 2>/dev/null) || return 1; s=\${s##*") "}; set -- $s; [ "$1" != Z ] && [ "\${20}" = "$t" ]; }; ${wait(PHONED_EXIT_S)}; alive || { echo exited; exit 0; }; kill -9 $p 2>/dev/null; ${wait(PHONED_KILL_S)}; alive && echo running || echo killed`;
63
+ }
42
64
  const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
43
65
  /** The ledger's id for a create not answered yet. */
44
66
  const pendingId = (requestKey) => `pending-${requestKey}`;
67
+ /** The Idempotency-Key of a request: every create of one request id sends the same key, so the service can tell them one. */
68
+ const requestKeyOf = (requestId) => createHash("sha256").update(requestId, "utf8").digest("hex");
69
+ /**
70
+ * How a spec differs from a phone of its request, as the ledger reads it back: its labels and its image, every field of
71
+ * a spec check() lets a phone ask for but its network (always open) and its lifetime (each create counts its own).
72
+ */
73
+ function phoneDiffer(spec, labels, image, seen) {
74
+ const differ = labelsDiffer(spec.labels ?? {}, labels, seen);
75
+ if (spec.image !== image)
76
+ differ.push(`image: asked ${spec.image}, ${seen} ${image}`);
77
+ return differ;
78
+ }
45
79
  /** A ledger in this process's memory: the default, and enough for one process that makes and ends its phones. */
46
80
  export function memoryLedger() {
47
81
  const entries = new Map();
48
82
  return {
49
83
  put: (entry) => void entries.set(entry.id, structuredClone(entry)),
84
+ claim: (entry) => !entries.has(entry.id) && (entries.set(entry.id, structuredClone(entry)), true),
50
85
  get: (id) => structuredClone(entries.get(id)),
51
86
  list: () => [...entries.values()].map((entry) => structuredClone(entry)),
52
87
  remove: (id) => void entries.delete(id),
@@ -67,6 +102,7 @@ function guardedLedger(ledger) {
67
102
  };
68
103
  return {
69
104
  put: guard("written", (entry) => ledger.put(entry)),
105
+ claim: guard("written", (entry) => ledger.claim(entry)),
70
106
  get: guard("read", (id) => ledger.get(id)),
71
107
  list: guard("read", () => ledger.list()),
72
108
  remove: guard("written", (id) => ledger.remove(id)),
@@ -119,15 +155,22 @@ export function adbCli(path = "adb", { port = ADB_SERVER_PORT, env } = {}) {
119
155
  child.stdin?.end(input ?? "");
120
156
  });
121
157
  let started;
122
- const server = async (service, { timeoutMs, transport }) => {
123
- const what = serviceWords(service);
158
+ /** The adb server, started once: a failed start is tried again by the next request. */
159
+ const serverUp = async (timeoutMs) => {
124
160
  started ??= run(["start-server"], { timeoutMs });
125
161
  const start = await started;
126
162
  if (!start.ok || start.value.exitCode !== 0) {
127
163
  started = undefined;
128
164
  return start.ok ? vendorFail("phone-harness", `adb start-server failed: ${start.value.stderr.trim().split("\n")[0] || `exit code ${start.value.exitCode}`}`) : start;
129
165
  }
130
- const frame = (request) => `${Buffer.byteLength(request).toString(16).padStart(4, "0")}${request}`;
166
+ return ok(undefined);
167
+ };
168
+ const frame = (request) => `${Buffer.byteLength(request).toString(16).padStart(4, "0")}${request}`;
169
+ const server = async (service, { timeoutMs, transport }) => {
170
+ const what = serviceWords(service);
171
+ const up = await serverUp(timeoutMs);
172
+ if (!up.ok)
173
+ return up;
131
174
  return new Promise((resolve) => {
132
175
  let buffer = Buffer.alloc(0);
133
176
  let settled = false;
@@ -166,7 +209,69 @@ export function adbCli(path = "adb", { port = ADB_SERVER_PORT, env } = {}) {
166
209
  });
167
210
  });
168
211
  };
169
- return { run, server };
212
+ const open = async (service, { timeoutMs, transport }) => {
213
+ const what = serviceWords(service);
214
+ const up = await serverUp(timeoutMs);
215
+ if (!up.ok)
216
+ return up;
217
+ return new Promise((resolve) => {
218
+ let buffer = Buffer.alloc(0);
219
+ let settled = false;
220
+ // First host:transport-id, whose OKAY binds the socket to the phone; then the service, whose OKAY hands the
221
+ // socket over to it.
222
+ let asking = `host:transport-id:${transport}`;
223
+ const socket = createConnection({ host: "127.0.0.1", port });
224
+ /** The adb server's refusal: its answer is never OKAY here, so it is always a failure. */
225
+ const refused = (raw, of) => {
226
+ const answer = adbAnswer(raw, of);
227
+ return answer.ok ? vendorFail("phone-harness", `the adb server answered ${of} without OKAY`) : answer;
228
+ };
229
+ const done = (result) => {
230
+ if (settled)
231
+ return;
232
+ settled = true;
233
+ clearTimeout(timer);
234
+ socket.off("data", onData);
235
+ socket.off("error", onError);
236
+ socket.off("close", onClose);
237
+ if (!result.ok)
238
+ socket.destroy();
239
+ resolve(result);
240
+ };
241
+ const onData = (chunk) => {
242
+ buffer = Buffer.concat([buffer, chunk]);
243
+ while (!settled && buffer.length >= 4) {
244
+ const status = buffer.subarray(0, 4).toString("latin1");
245
+ // FAIL is followed by its hex length and words: wait for them, or for the close that ends them.
246
+ if (status !== "OKAY") {
247
+ const length = buffer.length >= 8 ? Number.parseInt(buffer.subarray(4, 8).toString("latin1"), 16) : Number.NaN;
248
+ if (status === "FAIL" && !(buffer.length >= 8 + length))
249
+ return;
250
+ return done(refused(buffer, asking === service ? what : asking));
251
+ }
252
+ buffer = buffer.subarray(4);
253
+ if (asking !== service) {
254
+ asking = service;
255
+ socket.write(frame(service));
256
+ continue;
257
+ }
258
+ // The service's stream from here on: what came after its OKAY is the first of it.
259
+ socket.pause();
260
+ if (buffer.length > 0)
261
+ socket.unshift(buffer);
262
+ return done(ok(socket));
263
+ }
264
+ };
265
+ const onError = (error) => done(vendorFail("phone-harness", `the adb server on 127.0.0.1:${port} could not be reached for ${what}: ${error.message}`));
266
+ const onClose = () => done(buffer.length >= 4 ? refused(buffer, asking === service ? what : asking) : vendorFail("phone-harness", `the adb server closed ${asking === service ? what : asking} before it answered`));
267
+ const timer = setTimeout(() => done(fail("timeout", `the adb server did not answer ${what} within ${timeoutMs / 1000} s`)), timeoutMs);
268
+ socket.on("connect", () => socket.write(frame(asking)));
269
+ socket.on("data", onData);
270
+ socket.on("error", onError);
271
+ socket.on("close", onClose);
272
+ });
273
+ };
274
+ return { run, server, open };
170
275
  }
171
276
  /** A service as error words name it: its kind and first word, never the rest (a shell command's code, an endpoint). */
172
277
  export function serviceWords(service) {
@@ -211,6 +316,12 @@ export class PhoneHarnessProvider {
211
316
  #fetch;
212
317
  #adb;
213
318
  #ledger;
319
+ /** Each create in flight, and the names of the phones this provider ended (create-requests.ts). Past this process, the
320
+ * ledger's released entry is what holds, until the service has ended the phone. */
321
+ #requests = new CreateRequests();
322
+ /** The Idempotency-Keys whose pending entry a create here claimed, kept until it is removed: a pending entry of one is
323
+ * this provider's own (no create of it is in flight, CreateRequests shares those), so a retry here sends the POST. */
324
+ #claimed = new Set();
214
325
  #maxLifetimeMs;
215
326
  #readyMs;
216
327
  #pollMs;
@@ -223,6 +334,21 @@ export class PhoneHarnessProvider {
223
334
  #holders = new Map();
224
335
  /** Each endpoint's host:disconnect still on its way: a connect to that endpoint waits for it before its own. */
225
336
  #leaving = new Map();
337
+ /**
338
+ * Each endpoint's phoned, started by its first connection and shared by all of them, as its adb transport is: a phone
339
+ * has one accessibility connection to give. The last holder's release ends it before the disconnect.
340
+ */
341
+ #daemons = new Map();
342
+ /**
343
+ * Each endpoint's last phoned, by its process on the phone, until it is seen gone: the next phoned there starts only
344
+ * once it is (#lastGone), since it holds the phone's one accessibility connection until it exits, after its
345
+ * connection closed.
346
+ */
347
+ #lastPhoned = new Map();
348
+ #phonedPath;
349
+ #apks;
350
+ /** Each file the provider puts on its phones (phoned's jar, the APKs), read once: its bytes' sha256 names it there. */
351
+ #files = new Map();
226
352
  constructor(options) {
227
353
  const { apiKey, platform = "android" } = options ?? {};
228
354
  if (typeof apiKey !== "string" || apiKey === "")
@@ -235,9 +361,14 @@ export class PhoneHarnessProvider {
235
361
  this.#baseUrl = (options.baseUrl ?? PHONE_HARNESS_URL).replace(/\/+$/, "");
236
362
  this.#fetch = options.fetch ?? globalThis.fetch;
237
363
  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()");
364
+ if (adb !== undefined && typeof adb !== "string" && !(typeof adb?.run === "function" && typeof adb?.server === "function" && typeof adb?.open === "function")) {
365
+ throw new Error("options.adb is the adb CLI's path, or a transport with run(), server() and open()");
240
366
  }
367
+ this.#phonedPath = options.phoned ?? DEFAULT_PHONED_PATH;
368
+ const apks = options.apks ?? [];
369
+ if (!Array.isArray(apks) || !apks.every((path) => typeof path === "string" && path !== ""))
370
+ throw new Error(`options.apks ${show(options.apks)} is not a list of APK paths`);
371
+ this.#apks = [...apks];
241
372
  this.#adb = adb === undefined || typeof adb === "string" ? adbCli(adb ?? "adb") : adb;
242
373
  this.#ledger = guardedLedger(options.ledger ?? memoryLedger());
243
374
  this.#maxLifetimeMs = options.maxLifetimeMs ?? DEFAULT_MAX_LIFETIME_MS;
@@ -378,12 +509,102 @@ export class PhoneHarnessProvider {
378
509
  await this.#ledger.remove(id);
379
510
  return ok(undefined);
380
511
  }
512
+ /**
513
+ * Forgets a phone the service ended: its request is spent first, so a retry of it is refused exists (endedWords),
514
+ * never a second POST /sessions, and then its entry goes.
515
+ */
516
+ async #forget(entry) {
517
+ this.#requests.end(entry.name);
518
+ await this.#ledger.remove(entry.id);
519
+ }
381
520
  #deadlineOf(session, fallback) {
382
521
  return new Date(typeof session.expires_at === "number" && Number.isFinite(session.expires_at) ? session.expires_at * 1000 : fallback).toISOString();
383
522
  }
384
523
  // --- the provider ----------------------------------------------------------------------------------------------
385
- create(spec, context = {}) {
386
- return ledgerSafe(() => this.#create(spec, context));
524
+ /**
525
+ * Makes a phone, once per request (provider.md, Idempotent create): context.requestId names it (computerNameFor) and
526
+ * gives the POST's Idempotency-Key. A request whose phone the ledger holds answers that phone once it is ready; one
527
+ * released is refused exists; a create of a request in flight here waits for the first (CreateRequests).
528
+ */
529
+ create(spec, context) {
530
+ const refusals = this.check(spec);
531
+ return ledgerSafe(() => this.#requests.create(spec, context, {
532
+ refuse: fail,
533
+ ...(refusals.length > 0 ? { refused: refusals.map(({ field, message }) => `${field}: ${message}`).join("; ") } : {}),
534
+ make: (name) => this.#create(spec, name, requestKeyOf(context.requestId), context.signal),
535
+ }));
536
+ }
537
+ /**
538
+ * The phone the ledger holds for a request, or undefined when it holds none: one whose create's answer was lost is
539
+ * asked for by its key first, and recorded when the service made it. One released, or ended, is refused exists; one
540
+ * of another spec is refused exists; one still starting is waited for, within readyMs.
541
+ */
542
+ async #held(spec, name, requestKey, signal) {
543
+ const entries = await this.#ledger.list();
544
+ let entry = entries.find((one) => one.name === name && one.request === undefined);
545
+ const pending = entries.find((one) => one.id === pendingId(requestKey));
546
+ if (entry === undefined && pending !== undefined) {
547
+ const recovered = await this.#api("GET", `/sessions/requests/${requestKey}`);
548
+ if (!recovered.ok)
549
+ return recovered.error.code === "not_found" ? undefined : recovered;
550
+ const session = sessionOf(recovered.value.json, `GET /sessions/requests/${requestKey}`);
551
+ if (!session.ok)
552
+ return session;
553
+ // Claimed, never put over an entry another create recorded while the service answered: that one, and its release
554
+ // marker, stand. One already forgotten was released and is gone.
555
+ const found = { id: session.value.id, name, labels: { ...pending.labels }, image: pending.image, deadline: this.#deadlineOf(session.value, Date.parse(pending.deadline)) };
556
+ entry = (await this.#ledger.claim(found)) ? found : await this.#ledger.get(found.id);
557
+ await this.#ledger.remove(pending.id);
558
+ if (entry === undefined)
559
+ return fail("exists", endedWords(name));
560
+ }
561
+ if (entry === undefined)
562
+ return undefined;
563
+ if (entry.released !== undefined || this.#now() >= Date.parse(entry.deadline))
564
+ return fail("exists", endedWords(name));
565
+ const differ = phoneDiffer(spec, entry.labels, entry.image, "read back");
566
+ if (differ.length > 0)
567
+ return fail("exists", otherSpecWords(name, "was made", differ));
568
+ // The same wait a fresh create makes, within readyMs; a phone that ended, or reached its deadline as it started, is
569
+ // spent. One not ready in time is left to the create that made it, which ends it.
570
+ const ready = await this.#ready(entry.id, this.#now(), signal);
571
+ if (!ready.ok)
572
+ return ready.error.code === "gone" ? fail("exists", endedWords(name)) : ready;
573
+ if (this.#now() >= Date.parse(this.#deadlineOf(ready.value, Date.parse(entry.deadline))))
574
+ return fail("exists", endedWords(name));
575
+ return ok({ id: entry.id, name });
576
+ }
577
+ /**
578
+ * Waits until the phone id is ready, within readyMs counted from `from`, each read bounded by what readyMs has left so
579
+ * a stalled one cannot hold the wait past it: the ready session, or why not. gone: the service ended the phone, or it
580
+ * did not start; timeout: readyMs passed; aborted: the signal fired.
581
+ */
582
+ async #ready(id, from, signal) {
583
+ for (;;) {
584
+ if (signal?.aborted)
585
+ return fail("aborted", `create was aborted while the phone ${id} started`);
586
+ const left = this.#readyMs - (this.#now() - from);
587
+ const bound = Math.max(1, Math.min(this.#requestMs, left));
588
+ const read = await this.#session(id, signal, bound);
589
+ if (!read.ok && read.error.code === "timeout") {
590
+ // A read cut off by its own bound (requestMs) while readyMs has time left is one slow answer, not the deadline:
591
+ // ask again. Only a read bounded by what readyMs had left, or the check below, ends the wait.
592
+ if (bound < left && this.#now() - from < this.#readyMs) {
593
+ await this.#sleep(this.#pollMs);
594
+ continue;
595
+ }
596
+ return fail("timeout", `the phone ${id} was not ready within ${this.#readyMs / 1000} s: ${read.error.message}`);
597
+ }
598
+ if (!read.ok)
599
+ return fail(read.error.code, `the phone ${id} did not start: ${read.error.message}`);
600
+ if (read.value.state === "ready")
601
+ return read;
602
+ if (read.value.state !== "provisioning")
603
+ return fail("gone", `the phone ${id} did not start: ${this.#clean(read.value.error ?? read.value.state)}`);
604
+ if (this.#now() - from >= this.#readyMs)
605
+ return fail("timeout", `the phone ${id} was not ready within ${this.#readyMs / 1000} s`);
606
+ await this.#sleep(this.#pollMs);
607
+ }
387
608
  }
388
609
  attach(ref, context = {}) {
389
610
  return ledgerSafe(() => this.#attach(ref, context));
@@ -408,18 +629,40 @@ export class PhoneHarnessProvider {
408
629
  watch(ref, handlers, options) {
409
630
  return daemonWatch(this, ref, handlers, options);
410
631
  }
411
- async #create(spec, { signal } = {}) {
412
- const refusals = this.check(spec);
413
- if (refusals.length > 0)
414
- return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
632
+ async #create(spec, name, requestKey, signal) {
415
633
  if (signal?.aborted)
416
634
  return fail("aborted", "create was aborted before the phone harness was asked");
417
- const from = this.#now();
418
- const requestKey = randomBytes(16).toString("hex");
635
+ const looked = this.#now();
419
636
  const body = { platform: "android", kind: "emulator", timeout_seconds: Math.ceil(runLifetimeMs(spec) / 1000) };
420
- // The key goes into the ledger before the POST: whatever answers are lost, list() can find the phone by it.
637
+ // The key goes into the ledger before the POST: whatever answers are lost, list() can find the phone by it. It is
638
+ // claimed, never put over another's: a create of the request in another provider on the same ledger (another
639
+ // process) holds the request's spec there, and one of another spec is refused before it can POST the same key.
640
+ // One of the same spec waits for that create's phone (#held finds it by the key, and never ends it): only the
641
+ // create that holds the claim owns the phone, to end it if it gives up. A claim older than any create's POST and
642
+ // its recovery (readyMs and twice requestMs from this look) is one whose create ended unrecorded: this one sends.
421
643
  const pending = pendingId(requestKey);
422
- await this.#ledger.put({ id: pending, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline: new Date(from + runLifetimeMs(spec)).toISOString(), request: requestKey });
644
+ const stale = looked + this.#readyMs + 2 * this.#requestMs;
645
+ for (;;) {
646
+ const held = await this.#held(spec, name, requestKey, signal);
647
+ if (held !== undefined)
648
+ return held;
649
+ if (await this.#ledger.claim({ id: pending, name, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline: new Date(this.#now() + runLifetimeMs(spec)).toISOString(), request: requestKey }))
650
+ break;
651
+ const other = await this.#ledger.get(pending);
652
+ // Gone since: that create has ended, with a phone or none; look again.
653
+ if (other === undefined)
654
+ continue;
655
+ const differ = phoneDiffer(spec, other.labels, other.image, "in flight");
656
+ if (differ.length > 0)
657
+ return fail("exists", otherSpecWords(name, "is being made", differ));
658
+ if (this.#claimed.has(requestKey) || this.#now() >= stale)
659
+ break;
660
+ if (signal?.aborted)
661
+ return fail("aborted", `create was aborted while another create of this request made ${name}`);
662
+ await this.#sleep(this.#pollMs);
663
+ }
664
+ this.#claimed.add(requestKey);
665
+ const from = this.#now();
423
666
  const posted = await this.#api("POST", "/sessions", { body, headers: { "Idempotency-Key": requestKey }, ...(signal ? { signal } : {}) });
424
667
  const cancelled = !posted.ok && posted.error.code === "aborted";
425
668
  let first = posted.ok ? sessionOf(posted.value.json, "POST /sessions") : undefined;
@@ -441,6 +684,7 @@ export class PhoneHarnessProvider {
441
684
  else if (!posted.ok) {
442
685
  // The phone harness refused the request: nothing was made, and the key is forgotten.
443
686
  await this.#ledger.remove(pending);
687
+ this.#claimed.delete(requestKey);
444
688
  return posted;
445
689
  }
446
690
  if (first === undefined || !first.ok)
@@ -460,54 +704,43 @@ export class PhoneHarnessProvider {
460
704
  }
461
705
  };
462
706
  const named = await record(async () => {
463
- await this.#ledger.put({ id, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline: this.#deadlineOf(first.value, from + runLifetimeMs(spec)) });
707
+ await this.#ledger.put({ id, name, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline: this.#deadlineOf(first.value, from + runLifetimeMs(spec)) });
464
708
  await this.#ledger.remove(pending);
709
+ this.#claimed.delete(requestKey);
465
710
  });
466
711
  if (!named.ok)
467
712
  return named;
468
713
  const ended = async (code, words) => {
714
+ // A phone create gave up on: its request is spent, as one released.
715
+ this.#requests.end(name);
469
716
  const gone = await this.#end(id);
470
717
  return fail(code, `${words}; ${gone.ok ? "it was ended" : `it could not be ended (${gone.error.message})`}`);
471
718
  };
472
719
  if (cancelled)
473
720
  return ended("aborted", `create was aborted during POST /sessions, after the service made the phone ${id}`);
474
- let session = first.value;
475
- for (;;) {
476
- if (signal?.aborted)
477
- return ended("aborted", `create was aborted while the phone ${id} started`);
478
- // A read takes no longer than readyMs has left, so a stalled one cannot hold create past it.
479
- const left = this.#readyMs - (this.#now() - from);
480
- const bound = Math.max(1, Math.min(this.#requestMs, left));
481
- const read = await this.#session(id, signal, bound);
482
- if (!read.ok && read.error.code === "timeout") {
483
- // A read cut off by its own bound (requestMs) while readyMs has time left is one slow answer, not the deadline:
484
- // ask again. Only a read bounded by what readyMs had left, or the deadline check below, ends the phone.
485
- if (bound < left && this.#now() - from < this.#readyMs) {
486
- await this.#sleep(this.#pollMs);
487
- continue;
488
- }
489
- return ended("timeout", `the phone ${id} was not ready within ${this.#readyMs / 1000} s: ${read.error.message}`);
490
- }
491
- if (!read.ok)
492
- return ended(read.error.code === "gone" ? "vendor" : read.error.code, `the phone ${id} did not start: ${read.error.message}`);
493
- session = read.value;
494
- if (session.state === "ready")
495
- break;
496
- if (session.state !== "provisioning")
497
- return ended("vendor", `the phone ${id} did not start: ${this.#clean(session.error ?? session.state)}`);
498
- if (this.#now() - from >= this.#readyMs)
499
- return ended("timeout", `the phone ${id} was not ready within ${this.#readyMs / 1000} s`);
500
- await this.#sleep(this.#pollMs);
501
- }
721
+ const ready = await this.#ready(id, from, signal);
722
+ if (!ready.ok)
723
+ return ended(ready.error.code === "gone" ? "vendor" : ready.error.code, ready.error.message);
724
+ const session = ready.value;
502
725
  const deadline = this.#deadlineOf(session, from + runLifetimeMs(spec));
503
- const kept = await record(() => this.#ledger.put({ id, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline }));
726
+ // The entry as kept now: a create of the same request on another provider may have answered this phone while it
727
+ // started (#held), and its caller released it. That release stands: never written over, and the phone not answered.
728
+ let released = false;
729
+ const kept = await record(async () => {
730
+ const now = await this.#ledger.get(id);
731
+ released = now === undefined || now.released !== undefined;
732
+ if (!released)
733
+ await this.#ledger.put({ ...now, id, name, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline });
734
+ });
504
735
  if (!kept.ok)
505
736
  return kept;
737
+ if (released)
738
+ return fail("exists", endedWords(name));
506
739
  const took = this.#now() - from;
507
740
  if (this.#now() >= Date.parse(deadline)) {
508
741
  return ended("timeout", `the phone ${id}'s lifetime of ${runLifetimeMs(spec) / 1000} s ended before it was ready (it took ${Math.round(took / 100) / 10} s)`);
509
742
  }
510
- return ok({ id, name: id });
743
+ return ok({ id, name });
511
744
  }
512
745
  async #attach(ref, { signal } = {}) {
513
746
  let entry;
@@ -532,13 +765,13 @@ export class PhoneHarnessProvider {
532
765
  const session = await this.#session(id, signal);
533
766
  if (!session.ok) {
534
767
  if (session.error.code === "gone")
535
- await this.#ledger.remove(id);
768
+ await this.#forget(entry);
536
769
  return session;
537
770
  }
538
771
  if (session.value.state !== "ready" && session.value.state !== "provisioning")
539
772
  return fail("gone", `${id} is ${session.value.state}`);
540
773
  const deadline = new Date(this.#deadlineOf(session.value, Date.parse(entry.deadline)));
541
- return ok({ id, name: id, spec: { image: entry.image, user: SHELL_USER, network: "open", deadline, kind: "android" } });
774
+ return ok({ id, name: entry.name, spec: { image: entry.image, user: SHELL_USER, network: "open", deadline, kind: "android" } });
542
775
  }
543
776
  /**
544
777
  * Settings' test: one GET /sessions, the account's sessions joined to the ledger, and a GET of any phone of the
@@ -580,7 +813,7 @@ export class PhoneHarnessProvider {
580
813
  await this.#ledger.remove(listed.id);
581
814
  continue;
582
815
  }
583
- entry = { id: made.id, labels: { ...entry.labels }, image: entry.image, deadline: this.#deadlineOf(made, Date.parse(entry.deadline)) };
816
+ entry = { id: made.id, name: entry.name, labels: { ...entry.labels }, image: entry.image, deadline: this.#deadlineOf(made, Date.parse(entry.deadline)) };
584
817
  await this.#ledger.put(entry);
585
818
  await this.#ledger.remove(listed.id);
586
819
  }
@@ -588,11 +821,11 @@ export class PhoneHarnessProvider {
588
821
  // Released, and being ended: never listed. Forgotten once the listing leaves it out and its own GET is a 404,
589
822
  // or once its deadline has passed.
590
823
  if (this.#now() > Date.parse(entry.deadline))
591
- await this.#ledger.remove(entry.id);
824
+ await this.#forget(entry);
592
825
  else if (!live.has(entry.id)) {
593
826
  const read = await this.#session(entry.id, signal);
594
827
  if (!read.ok && read.error.code === "gone")
595
- await this.#ledger.remove(entry.id);
828
+ await this.#forget(entry);
596
829
  }
597
830
  continue;
598
831
  }
@@ -601,7 +834,7 @@ export class PhoneHarnessProvider {
601
834
  // Not in the listing: its own GET says whether the service ended it (404), and only then is it forgotten.
602
835
  const read = await this.#session(entry.id, signal);
603
836
  if (!read.ok && read.error.code === "gone") {
604
- await this.#ledger.remove(entry.id);
837
+ await this.#forget(entry);
605
838
  continue;
606
839
  }
607
840
  if (!read.ok)
@@ -611,7 +844,7 @@ export class PhoneHarnessProvider {
611
844
  if (!carries(entry.labels, labels) || out.some((info) => info.ref.id === entry.id))
612
845
  continue;
613
846
  out.push({
614
- ref: { id: entry.id, name: entry.id },
847
+ ref: { id: entry.id, name: entry.name },
615
848
  labels: { ...entry.labels },
616
849
  deadline: new Date(this.#deadlineOf(session, Date.parse(entry.deadline))),
617
850
  state: session.state === "ready" || session.state === "provisioning" ? "running" : "stopped",
@@ -636,6 +869,9 @@ export class PhoneHarnessProvider {
636
869
  if (how !== "delete")
637
870
  return fail("unsupported", `a cloud phone is kept for no agent (the phone harness declares no persistence), so release ${JSON.stringify(how)} is refused and the phone is left as it is: release it with delete`);
638
871
  const entry = await this.#ledger.get(ref.id);
872
+ // A released phone's request is spent: the same request id again is refused, never made a second time.
873
+ if (entry !== undefined)
874
+ this.#requests.end(entry.name);
639
875
  if (entry?.released !== undefined) {
640
876
  // Released already, and the service may still be ending it: ok. Its own GET says whether it is gone, and then it is
641
877
  // forgotten; a phone the service still holds running is sent its DELETE again.
@@ -726,7 +962,15 @@ export class PhoneHarnessProvider {
726
962
  if (left > 0)
727
963
  return void this.#holders.set(endpoint, left);
728
964
  this.#holders.delete(endpoint);
729
- const leaving = server(`host:disconnect:${endpoint}`)
965
+ // The phone's phoned goes with its last holder, in the same critical section: a connect after this starts its own.
966
+ const daemon = this.#daemons.get(endpoint);
967
+ this.#daemons.delete(endpoint);
968
+ const leaving = (async () => {
969
+ const started = await daemon;
970
+ if (started?.ok)
971
+ await started.value.end();
972
+ })()
973
+ .then(() => server(`host:disconnect:${endpoint}`))
730
974
  .catch(() => undefined)
731
975
  .finally(() => {
732
976
  if (this.#leaving.get(endpoint) === leaving)
@@ -777,663 +1021,227 @@ export class PhoneHarnessProvider {
777
1021
  return letGo(vendorFail("phone-harness", /\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}`));
778
1022
  }
779
1023
  }
780
- const client = new AdbClient(id, adb, release, this.#sleep, this.#now);
781
- const opened = await client.open(this.#daemonVersion);
782
- if (!opened.ok) {
783
- await client.closed();
784
- return opened;
1024
+ let started = this.#daemons.get(endpoint);
1025
+ if (started === undefined) {
1026
+ const starting = this.#startPhoned(endpoint, id, adb, onPhone, () => {
1027
+ // phoned ended on its own (the phone killed it, or it failed): the next connect starts another, once this start
1028
+ // is done, so its pid is kept before that start waits on it.
1029
+ void starting.then(() => {
1030
+ if (this.#daemons.get(endpoint) === starting)
1031
+ this.#daemons.delete(endpoint);
1032
+ });
1033
+ });
1034
+ started = starting;
1035
+ this.#daemons.set(endpoint, starting);
785
1036
  }
786
- const hello = opened.value;
787
- if (hello.version !== this.version) {
788
- await client.closed();
789
- return fail("refused", `hello: the daemon reports version ${hello.version}, expected ${this.version}`);
1037
+ const daemon = await started;
1038
+ if (!daemon.ok) {
1039
+ if (this.#daemons.get(endpoint) === started)
1040
+ this.#daemons.delete(endpoint);
1041
+ return letGo(daemon);
790
1042
  }
1043
+ const { hello } = daemon.value;
1044
+ if (hello.version !== this.#daemonVersion)
1045
+ return letGo(fail("refused", `hello: the daemon reports version ${hello.version}, expected ${this.#daemonVersion}`));
1046
+ if (hello.protocol !== PROTOCOL_VERSION)
1047
+ return letGo(fail("refused", `hello: phoned speaks protocol ${hello.protocol}, and this provider ${PROTOCOL_VERSION}`));
1048
+ const client = new PhoneClient(daemon.value.client, release);
791
1049
  return ok({ client, hello, close: () => client.closed() });
792
1050
  }
793
- }
794
- /** Whether labels carries every one of wanted. */
795
- const carries = (labels, wanted) => Object.entries(wanted ?? {}).every(([key, value]) => labels[key] === value);
796
- function sessionOf(json, where) {
797
- const s = json;
798
- if (typeof s !== "object" || s === null || typeof s.id !== "string" || typeof s.state !== "string")
799
- return vendorFail("phone-harness", `${where} answered ${show(json).slice(0, 200)}, not a session`);
800
- return ok(s);
801
- }
802
- // --- the client: the protocol over adb ---------------------------------------------------------------------------
803
- /** Android's keycode for each key name in KEYS. */
804
- const KEYCODES = {
805
- enter: "ENTER",
806
- tab: "TAB",
807
- space: "SPACE",
808
- backspace: "DEL",
809
- delete: "FORWARD_DEL",
810
- escape: "ESCAPE",
811
- insert: "INSERT",
812
- up: "DPAD_UP",
813
- down: "DPAD_DOWN",
814
- left: "DPAD_LEFT",
815
- right: "DPAD_RIGHT",
816
- home: "MOVE_HOME",
817
- end: "MOVE_END",
818
- pageup: "PAGE_UP",
819
- pagedown: "PAGE_DOWN",
820
- shift: "SHIFT_LEFT",
821
- ctrl: "CTRL_LEFT",
822
- alt: "ALT_LEFT",
823
- super: "META_LEFT",
824
- capslock: "CAPS_LOCK",
825
- ...Object.fromEntries(Array.from({ length: 12 }, (_, i) => [`f${i + 1}`, `F${i + 1}`])),
826
- };
827
- const BUTTON_KEYS = { back: "BACK", home: "HOME", app_switch: "APP_SWITCH" };
828
- const refuse = (code, message) => fail(code, message);
829
- /** The in-process client of one cloud Android: each protocol method is one or more adb commands. */
830
- class AdbClient {
831
- transport;
832
- adb;
833
- disconnect;
834
- sleep;
835
- now;
836
- #closed = false;
837
- #hello;
838
- #size = [0, 0];
839
- #scale = 1;
840
- /** The shot held for screen.read, until read to its end or the next shot. */
841
- #held;
842
- /** The newest watch frame's rest, held apart from the shot's (as computerd's is), so neither evicts the other. */
843
- #watchHeld;
844
- /**
845
- * screen.watch's state: the newest frame's seq, what it was read from (a digest of the pixels), the frame, and when
846
- * the screen was last read (read, by now()).
847
- */
848
- #watch = {
849
- seq: 0,
850
- digest: "",
851
- read: Number.NEGATIVE_INFINITY,
852
- };
853
- /** One screen.watch at a time on this connection. */
854
- #watching = Promise.resolve();
855
- /** One input.actions batch at a time on this connection: a second waits for the first, whole. */
856
- #inputs = Promise.resolve();
857
- /** Fires on close: every adb run and wait in flight ends with it, so a close never waits for the phone. */
858
- #closing = new AbortController();
859
- /** The disconnect close started, which the connection's close waits for. */
860
- #gone = Promise.resolve();
861
- constructor(
862
- /** The adb server's transport id of the phone: no secret, so it may be in an argv. */
863
- transport, adb,
864
- /** Lets the adb server drop the phone's transport, by its endpoint over the server's socket. */
865
- disconnect, sleep, now) {
866
- this.transport = transport;
867
- this.adb = adb;
868
- this.disconnect = disconnect;
869
- this.sleep = sleep;
870
- this.now = now;
871
- }
872
- /** What the phone is: its ABI, its Android release, its screen's size and density; then the hello it answers. */
873
- async open(version) {
874
- const abi = await this.#shell("getprop ro.product.cpu.abi");
875
- if (!abi.ok)
876
- return abi;
877
- const release = await this.#shell("getprop ro.build.version.release");
878
- if (!release.ok)
879
- return release;
880
- const size = await this.#shell("wm size");
881
- if (!size.ok)
882
- return size;
883
- const density = await this.#shell("wm density");
884
- if (!density.ok)
885
- return density;
886
- const sizes = [...size.value.matchAll(/(\d+)x(\d+)/g)];
887
- const last = sizes.at(-1);
888
- if (!last)
889
- return vendorFail("phone-harness", `the phone (adb transport ${this.transport}) did not say its screen's size: ${size.value.trim().slice(0, 100)}`);
890
- this.#size = [Number(last[1]), Number(last[2])];
891
- const dpi = [...density.value.matchAll(/(\d+)/g)].at(-1);
892
- this.#scale = dpi ? Number(dpi[1]) / 160 : 1;
893
- const reported = abi.value.trim();
894
- // An empty answer says no release: the hello then carries none.
895
- const osVersion = release.value.trim();
896
- this.#hello = { protocol: PROTOCOL_VERSION, version, os: "android", ...(osVersion ? { osVersion } : {}), kind: "android", arch: ARCH[reported] ?? reported, groups: [...PHONE_GROUPS] };
897
- return ok(this.#hello);
898
- }
899
- close() {
900
- if (this.#closed)
901
- return;
902
- this.#closed = true;
903
- this.#held = undefined;
904
- this.#watchHeld = undefined;
905
- this.#closing.abort();
906
- this.#gone = this.disconnect().catch(() => undefined);
907
- }
908
- /** Closes, and waits until the adb server has let the phone's transport go. */
909
- async closed() {
910
- this.close();
911
- await this.#gone;
912
- }
913
- /** The caller's signal and the connection's close, as one signal. */
914
- #either(signal) {
915
- return signal ? AbortSignal.any([signal, this.#closing.signal]) : this.#closing.signal;
916
- }
917
- /** One shell command on the phone: its stdout, or the failure in words (adb's, redacted: it names the endpoint). */
918
- async #shell(command, signal, timeoutMs) {
919
- const ran = await this.adb(["shell", command], { signal: this.#either(signal), ...(timeoutMs === undefined ? {} : { timeoutMs }) });
920
- if (!ran.ok)
921
- return ran;
922
- if (ran.value.exitCode !== 0) {
923
- const why = (ran.value.stderr.trim() || ran.value.stdout.toString("utf8").trim()).split("\n")[0] || `exit code ${ran.value.exitCode}`;
924
- return vendorFail("phone-harness", `${command.split(" ").slice(0, 2).join(" ")} on the phone failed: ${redactWords(why)}`);
925
- }
926
- return ok(ran.value.stdout.toString("utf8"));
927
- }
928
- async #execOut(command, signal) {
929
- const ran = await this.adb(["exec-out", command], { timeoutMs: 60_000, signal: this.#either(signal) });
930
- if (!ran.ok)
931
- return ran;
932
- if (ran.value.exitCode !== 0)
933
- return vendorFail("phone-harness", `${command.split(" ")[0]} on the phone failed: ${redactWords(ran.value.stderr.trim().split("\n")[0] || `exit code ${ran.value.exitCode}`)}`);
934
- return ok(ran.value.stdout);
935
- }
936
- async call(method, params, options = {}) {
937
- if (this.#closed)
938
- return fail("gone", "the connection to the phone is closed");
939
- if (options.signal?.aborted)
940
- return fail("aborted", `${method} was aborted`);
941
- return (await this.#answer(method, (params ?? {}), options.signal));
942
- }
943
- async #answer(method, params, signal) {
944
- switch (method) {
945
- case "hello":
946
- return ok(this.#hello);
947
- case "ping":
948
- return ok({});
949
- case "screen.shot":
950
- return this.#shot(params.region);
951
- case "screen.read":
952
- return this.#read(params.id, params.offset);
953
- case "screen.watch": {
954
- const turn = this.#watching.then(() => this.#screenWatch(params, this.#either(signal)));
955
- this.#watching = turn.catch(() => undefined);
956
- return turn;
957
- }
958
- case "input.actions":
959
- return this.#inTurn(params.actions, this.#either(signal));
960
- case "apps.list":
961
- return this.#appsList();
962
- case "apps.launch":
963
- return this.#launch(params.id);
964
- case "apps.terminate":
965
- return this.#terminate(params.id);
966
- case "apps.ui_tree":
967
- return this.#tree();
968
- }
969
- const group = method.split(".")[0];
970
- if (["exec", "files", "process", "tar"].includes(group))
971
- return refuse("unsupported", `${method}: a phone has no shell in the computer protocol, so it offers no exec, files or processes`);
972
- if (method === "apps.install")
973
- return refuse("unsupported", "apps.install: this phone takes no files to install from");
974
- if (method === "deadline.extend")
975
- return refuse("unsupported", "deadline.extend: a cloud phone's session ends when the phone harness says; it has no extend");
976
- return refuse("unsupported", `${method} is not a method this phone answers`);
977
- }
978
- // --- screen --------------------------------------------------------------------------------------------------
979
- async #shot(region) {
980
- const raw = await this.#execOut("screencap");
981
- if (!raw.ok)
982
- return raw;
983
- const frame = decodeScreencap(raw.value);
984
- if (!frame.ok)
985
- return frame;
986
- const { width, height, rgba } = frame.value;
987
- this.#size = [width, height];
988
- let rect = [0, 0, width, height];
989
- if (region !== undefined) {
990
- const r = region;
991
- 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)) {
992
- return refuse("invalid", `region ${show(region)} is not [x, y, w, h] inside the ${width}x${height} screen`);
993
- }
994
- rect = r;
1051
+ /** A file the provider puts on its phones, and its sha256, read once; not_found in the words missing gives. */
1052
+ #fileAt(path, missing) {
1053
+ let read = this.#files.get(path);
1054
+ if (read === undefined) {
1055
+ read = readFile(path).then((bytes) => ok({ path, sha256: createHash("sha256").update(bytes).digest("hex") }), (error) => {
1056
+ this.#files.delete(path);
1057
+ return fail("not_found", missing(error.code ?? error.message));
1058
+ });
1059
+ this.#files.set(path, read);
995
1060
  }
996
- const bytes = await encodePng(rgba, width, rect);
997
- // close() may have run while the frame was deflating: hold nothing for a closed connection.
998
- if (this.#closed)
999
- return fail("gone", "the connection to the phone is closed");
1000
- const id = randomBytes(6).toString("hex");
1001
- this.#held = { id, bytes };
1002
- const data = bytes.subarray(0, MAX_CHUNK_BYTES);
1003
- return ok({ id, size: bytes.length, data: data.toString("base64"), eof: data.length === bytes.length, width: rect[2], height: rect[3], scale: this.#scale });
1061
+ return read;
1004
1062
  }
1005
1063
  /**
1006
- * screen.watch: the live view's frames, as computerd answers them but as PNG (format png), read with screencap once
1007
- * each WATCH_POLL_MS (about 1 a second) at most, across calls too: an animated screen acked at once is read no faster
1008
- * 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
1009
- * newest waits for a change until waitMs passes. maxWidth scales the frame (nearest pixel); width and height stay the
1010
- * screen's, the input space. quality is checked and has no effect on a PNG. The signal (the caller's cancel and the
1011
- * connection's close) ends a screencap and a wait in flight.
1064
+ * Puts file on the phone at remote, a name that holds its sha256, only when the phone lacks it there: pushed beside
1065
+ * that name and then moved to it, so a file of that name is always whole. what names it in the errors.
1012
1066
  */
1013
- async #screenWatch(params, signal) {
1014
- const { after, waitMs = 2_000, maxWidth = 1_280, quality = 60 } = params;
1015
- const whole = (v, lo, hi) => Number.isSafeInteger(v) && v >= lo && v <= hi;
1016
- if (!whole(after, 0, Number.MAX_SAFE_INTEGER))
1017
- return refuse("invalid", "screen.watch takes after: the seq of the last frame the caller has, 0 for none");
1018
- if (!whole(waitMs, 0, 10_000))
1019
- return refuse("invalid", `waitMs ${show(waitMs)} is outside 0 to 10000`);
1020
- if (!whole(maxWidth, 1, 16_384))
1021
- return refuse("invalid", `maxWidth ${show(maxWidth)} is outside 1 to 16384`);
1022
- if (!whole(quality, 1, 100))
1023
- return refuse("invalid", `quality ${show(quality)} is outside 1 to 100`);
1024
- const watch = this.#watch;
1025
- if (after > watch.seq)
1026
- return refuse("invalid", `after ${after} is past the newest frame, ${watch.seq}`);
1027
- if (after < watch.seq && watch.frame)
1028
- return ok(this.#frameAnswer());
1029
- const aborted = () => refuse("aborted", "screen.watch was aborted");
1030
- const deadline = this.now() + waitMs;
1031
- for (;;) {
1032
- const wait = watch.read + WATCH_POLL_MS - this.now();
1033
- if (wait > 0)
1034
- await this.#pause(wait, signal);
1035
- if (signal.aborted || this.#closed)
1036
- return aborted();
1037
- watch.read = this.now();
1038
- const raw = await this.#execOut("screencap", signal);
1039
- if (signal.aborted || this.#closed)
1040
- return aborted();
1041
- if (!raw.ok)
1042
- return raw;
1043
- const read = decodeScreencap(raw.value);
1044
- if (!read.ok)
1045
- return read;
1046
- const { width, height, rgba } = read.value;
1047
- this.#size = [width, height];
1048
- // The size is in the digest: a phone turned to landscape may give the same pixels, the other way round.
1049
- const digest = createHash("sha256").update(`${width}x${height}|`).update(rgba).digest("hex");
1050
- if (watch.seq === 0 || digest !== watch.digest) {
1051
- const frameWidth = Math.min(width, maxWidth);
1052
- const frameHeight = Math.max(1, Math.floor((height * frameWidth) / width));
1053
- const pixels = frameWidth === width ? rgba : scaleRgba(rgba, width, height, frameWidth, frameHeight);
1054
- // Encoded before the frame is published: a watch that reads the seq while this one encodes never gets an older
1055
- // frame under the newer seq.
1056
- const bytes = await encodePng(pixels, frameWidth, [0, 0, frameWidth, frameHeight]);
1057
- if (signal.aborted || this.#closed)
1058
- return aborted();
1059
- watch.seq += 1;
1060
- watch.digest = digest;
1061
- watch.frame = { bytes, frameWidth, frameHeight, width, height };
1062
- return ok(this.#frameAnswer());
1063
- }
1064
- const left = deadline - this.now();
1065
- if (left < WATCH_POLL_MS) {
1066
- // Not another read before the wait is over: answer no change when it is.
1067
- if (left > 0)
1068
- await this.#pause(left, signal);
1069
- if (signal.aborted || this.#closed)
1070
- return aborted();
1071
- return ok({ seq: watch.seq, changed: false, width, height });
1072
- }
1073
- }
1074
- }
1075
- /** The newest frame as screen.watch answers it: its first chunk, the rest held for screen.read. */
1076
- #frameAnswer() {
1077
- const { seq, frame } = this.#watch;
1078
- const { bytes, frameWidth, frameHeight, width, height } = frame;
1079
- const data = bytes.subarray(0, MAX_CHUNK_BYTES);
1080
- const eof = data.length === bytes.length;
1081
- const id = randomBytes(6).toString("hex");
1082
- if (!eof)
1083
- this.#watchHeld = { id, bytes };
1084
- return { seq, changed: true, ...(eof ? {} : { id }), size: bytes.length, data: data.toString("base64"), eof, format: "png", frameWidth, frameHeight, width, height };
1085
- }
1086
- /** The rest of the shot or the watch frame held by id, from offset: each is dropped once read to its end. */
1087
- #read(id, offset) {
1088
- const frame = this.#watchHeld !== undefined && this.#watchHeld.id === id;
1089
- const held = frame ? this.#watchHeld : this.#held;
1090
- if (held === undefined || held.id !== id)
1091
- return refuse("not_found", `no shot ${show(id)} is held: take one with screen.shot`);
1092
- if (!(Number.isSafeInteger(offset) && offset >= 0 && offset <= held.bytes.length))
1093
- return refuse("invalid", `offset ${show(offset)} is not inside the shot's ${held.bytes.length} bytes`);
1094
- const data = held.bytes.subarray(offset, offset + MAX_CHUNK_BYTES);
1095
- const eof = offset + data.length >= held.bytes.length;
1096
- if (eof && frame)
1097
- this.#watchHeld = undefined;
1098
- else if (eof)
1099
- this.#held = undefined;
1100
- return ok({ data: data.toString("base64"), eof });
1067
+ async #place(transport, adb, onPhone, file, remote, what) {
1068
+ const have = await onPhone(`shell:sha256sum ${remote} 2>/dev/null`, transport);
1069
+ if (!have.ok)
1070
+ return have;
1071
+ if (have.value.startsWith(file.sha256))
1072
+ return ok(undefined);
1073
+ const pushed = await adb(["push", file.path, `${remote}.part`], { timeoutMs: PUSH_TIMEOUT_MS });
1074
+ if (!pushed.ok)
1075
+ return pushed;
1076
+ if (pushed.value.exitCode !== 0)
1077
+ return vendorFail("phone-harness", `adb push of ${what} to the phone failed: ${redactWords(pushed.value.stderr.trim().split("\n")[0] || `exit code ${pushed.value.exitCode}`)}`);
1078
+ // Checked before it takes its name: a file under that name is always whole.
1079
+ const landed = await onPhone(`shell:sha256sum ${remote}.part`, transport);
1080
+ if (!landed.ok)
1081
+ return landed;
1082
+ if (!landed.value.startsWith(file.sha256))
1083
+ return vendorFail("phone-harness", `${what} reached the phone changed: its sha256 there is not the file's (${redactWords(landed.value.trim().split("\n")[0] ?? "")})`);
1084
+ const moved = await onPhone(`shell:mv ${remote}.part ${remote} && echo moved`, transport);
1085
+ if (!moved.ok)
1086
+ return moved;
1087
+ if (moved.value.trim() !== "moved")
1088
+ return vendorFail("phone-harness", `${what} could not be put in place on the phone: ${redactWords(moved.value.trim().split("\n")[0] ?? "")}`);
1089
+ return ok(undefined);
1101
1090
  }
1102
- // --- input ---------------------------------------------------------------------------------------------------
1103
- /** The shell commands of one action, or why the phone cannot do it. Its adb call gets busyMs on top of its bound. */
1104
- #commands(action) {
1105
- const point = ([x, y]) => `${Math.round(x)} ${Math.round(y)}`;
1106
- switch (action.type) {
1107
- case "tap":
1108
- return { commands: Array.from({ length: action.count ?? 1 }, () => `input tap ${point(action.at)}`) };
1109
- case "long_press":
1110
- return { commands: [`input swipe ${point(action.at)} ${point(action.at)} ${action.ms ?? 800}`], busyMs: action.ms ?? 800 };
1111
- case "swipe": {
1112
- const path = action.path;
1113
- if (path.length === 2)
1114
- return { commands: [`input swipe ${point(path[0])} ${point(path[1])} ${action.ms ?? 300}`], busyMs: action.ms ?? 300 };
1115
- const last = path[path.length - 1];
1116
- // input motionevent has no duration, so ms goes between the moves as toybox sleeps. Each segment takes its
1117
- // share by length, evenly when the path has none. Each motionevent takes time of its own, so the swipe
1118
- // lasts ms at least.
1119
- const lengths = path.slice(1).map((p, i) => Math.hypot(p[0] - path[i][0], p[1] - path[i][1]));
1120
- const total = lengths.reduce((sum, one) => sum + one, 0);
1121
- const steps = [`input motionevent DOWN ${point(path[0])}`];
1122
- let gone = 0;
1123
- let walked = 0;
1124
- for (const [i, p] of path.slice(1).entries()) {
1125
- walked += total > 0 ? lengths[i] : 1;
1126
- const by = action.ms === undefined ? 0 : Math.round((action.ms * walked) / (total > 0 ? total : lengths.length));
1127
- if (by > gone)
1128
- steps.push(`sleep ${(by - gone) / 1000}`);
1129
- gone = by;
1130
- steps.push(`input motionevent MOVE ${point(p)}`);
1131
- }
1132
- steps.push(`input motionevent UP ${point(last)}`);
1133
- return { commands: [steps.join(";")], busyMs: gone };
1134
- }
1135
- case "button":
1136
- return { commands: [`input keyevent KEYCODE_${BUTTON_KEYS[action.name]}`] };
1137
- case "type": {
1138
- if (/[^\x20-\x7e\n]/.test(action.text))
1139
- return { kind: "unsupported", message: "type: adb's input text takes printable ASCII and line breaks only" };
1140
- const commands = [];
1141
- for (const [i, line] of action.text.split("\n").entries()) {
1142
- if (i > 0)
1143
- commands.push("input keyevent KEYCODE_ENTER");
1144
- // input text reads a % followed by s as a space, and nothing else. A space is sent as %s; a literal %s
1145
- // is split across two calls, so its % ends one and its s starts the next and the two never meet.
1146
- const pieces = line.split("%s");
1147
- for (const [j, piece] of pieces.entries()) {
1148
- const part = `${j > 0 ? "s" : ""}${piece}${j < pieces.length - 1 ? "%" : ""}`;
1149
- if (part !== "")
1150
- commands.push(`input text ${quote(part.replaceAll(" ", "%s"))}`);
1151
- }
1152
- }
1153
- return { commands };
1154
- }
1155
- case "key": {
1156
- if (action.keys.length !== 1)
1157
- 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` };
1158
- const key = action.keys[0];
1159
- const press = KEYCODES[key] ? `input keyevent KEYCODE_${KEYCODES[key]}` : /^[a-z0-9]$/.test(key) ? `input keyevent KEYCODE_${key.toUpperCase()}` : `input text ${quote(key)}`;
1160
- return { commands: Array.from({ length: action.repeat ?? 1 }, () => press) };
1091
+ /**
1092
+ * The apks option's APKs, each put on the phone like phoned's jar and installed there with `pm install -r`, once per
1093
+ * phone: a marker beside it on the phone (<apk>.installed) says that phone installed those bytes, so a later connect,
1094
+ * which starts phoned afresh, installs nothing again.
1095
+ */
1096
+ async #install(transport, adb, onPhone) {
1097
+ for (const path of this.#apks) {
1098
+ const what = `the APK ${basename(path)}`;
1099
+ const apk = await this.#fileAt(path, (why) => `${what}, which the provider's apks option names, is not at ${path} (${why})`);
1100
+ if (!apk.ok)
1101
+ return apk;
1102
+ const remote = `${PHONE_TMP}/apk-${apk.value.sha256.slice(0, 16)}.apk`;
1103
+ const done = await onPhone(`shell:test -e ${remote}.installed && echo installed`, transport);
1104
+ if (!done.ok)
1105
+ return done;
1106
+ if (done.value.trim() === "installed")
1107
+ continue;
1108
+ const placed = await this.#place(transport, adb, onPhone, apk.value, remote, what);
1109
+ if (!placed.ok)
1110
+ return placed;
1111
+ const installed = await onPhone(`shell:pm install -r ${remote} 2>&1`, transport);
1112
+ if (!installed.ok)
1113
+ return installed;
1114
+ // pm says Success on a line of its own, else Failure [INSTALL_FAILED_…: why].
1115
+ if (!/^Success$/m.test(installed.value)) {
1116
+ const said = installed.value.split("\n").find((line) => /Failure|Error|Exception/.test(line)) ?? installed.value.trim().split("\n")[0] ?? "";
1117
+ return vendorFail("phone-harness", `${what} did not install on the phone: ${redactWords(said.trim()) || "pm install answered nothing"}`);
1161
1118
  }
1162
- case "wait":
1163
- return { commands: [], waitMs: action.ms };
1164
- case "pinch":
1165
- return { kind: "unsupported", message: "pinch: a cloud Android takes one finger through adb, so a pinch is not offered" };
1166
- case "hold":
1167
- return { kind: "unsupported", message: "hold: adb's input keyevent cannot keep a key down" };
1168
- default:
1169
- return { kind: "unsupported", message: `${action.type} is not an action this phone takes` };
1119
+ const marked = await onPhone(`shell:touch ${remote}.installed && echo marked`, transport);
1120
+ if (!marked.ok)
1121
+ return marked;
1122
+ if (marked.value.trim() !== "marked")
1123
+ return vendorFail("phone-harness", `${what} installed, and its marker could not be written on the phone: ${redactWords(marked.value.trim().split("\n")[0] ?? "")}`);
1170
1124
  }
1125
+ return ok(undefined);
1171
1126
  }
1172
- /** A wait of ms, which ends early when signal fires. */
1173
- async #pause(ms, signal) {
1174
- if (signal === undefined)
1175
- return this.sleep(ms);
1176
- if (signal.aborted)
1177
- return;
1178
- let stop = () => { };
1179
- // The listener is on before the sleep starts, so a cancel during it is never missed.
1180
- const stopped = new Promise((resolve) => {
1181
- stop = resolve;
1182
- signal.addEventListener("abort", stop, { once: true });
1183
- });
1184
- try {
1185
- await Promise.race([this.sleep(ms), stopped]);
1127
+ /**
1128
+ * Starts phoned on the phone and says hello, after installing the apks option's APKs. The jar goes to the phone under
1129
+ * its sha256 (#place). phoned runs as the shell user through app_process (scrcpy's way in), on adb's exec: service,
1130
+ * whose socket carries its stdin and stdout raw; its stderr goes to a log beside the jar. It starts once the
1131
+ * endpoint's last phoned is gone (#lastGone), and its pid is kept for the next start's wait.
1132
+ */
1133
+ async #startPhoned(endpoint, transport, adb, onPhone, ended) {
1134
+ const installed = await this.#install(transport, adb, onPhone);
1135
+ if (!installed.ok)
1136
+ return installed;
1137
+ const jar = await this.#fileAt(this.#phonedPath, (why) => `phoned, the phone's driver, is not at ${this.#phonedPath} (${why}): build it with npm run build:phoned, or give the provider's phoned option`);
1138
+ if (!jar.ok)
1139
+ return jar;
1140
+ const remote = `${PHONE_TMP}/phoned-${jar.value.sha256.slice(0, 16)}.jar`;
1141
+ const placed = await this.#place(transport, adb, onPhone, jar.value, remote, "phoned");
1142
+ if (!placed.ok)
1143
+ return placed;
1144
+ const gone = await this.#lastGone(endpoint, transport, onPhone);
1145
+ if (!gone.ok)
1146
+ return gone;
1147
+ // sh writes its pid and start time, which app_process keeps as it takes sh's place by exec, to a file of this start's
1148
+ // own (the 22nd field of /proc/<pid>/stat is ${20} once its "<pid> (<name>) " is cut), read back after hello.
1149
+ const base = remote.slice(0, -".jar".length);
1150
+ const pidFile = `${base}-${randomBytes(4).toString("hex")}.pid`;
1151
+ const stream = await this.#adb.open(`exec:s=$(cat /proc/$$/stat); s=\${s##*") "}; set -- $s; echo $$ \${20} >${pidFile}; CLASSPATH=${remote} exec app_process / ai.agentrun.phoned.android.Main 2>${base}.log`, { timeoutMs: ADB_TIMEOUT_MS, transport });
1152
+ if (!stream.ok)
1153
+ return stream;
1154
+ const socket = stream.value;
1155
+ socket.once("close", ended);
1156
+ const client = new DaemonClient({ readable: socket, writable: socket });
1157
+ socket.resume();
1158
+ const end = async () => {
1159
+ if (socket.destroyed)
1160
+ return;
1161
+ const closed = new Promise((resolve) => socket.once("close", () => resolve()));
1162
+ client.close();
1163
+ await closed;
1164
+ };
1165
+ const hello = await client.call("hello", { client: `@parcha/agentrun-computer ${VERSION}` }, { signal: this.#timeout(HELLO_TIMEOUT_MS) });
1166
+ // Read whether or not it said hello: one that did not may still run, and the next phoned here waits for it as well.
1167
+ const read = await onPhone(`shell:cat ${pidFile} && rm -f ${pidFile}`, transport);
1168
+ const said = read.ok ? read.value.trim() : "";
1169
+ const fields = /^([1-9][0-9]*) ([0-9]+)$/.exec(said);
1170
+ if (fields)
1171
+ this.#lastPhoned.set(endpoint, { pid: Number(fields[1]), start: fields[2] });
1172
+ if (!hello.ok) {
1173
+ await end();
1174
+ return vendorFail("phone-harness", `phoned did not say hello on the phone (${hello.error.code}: ${redactWords(hello.error.message)}); its log on the phone is ${base}.log`);
1186
1175
  }
1187
- finally {
1188
- signal.removeEventListener("abort", stop);
1176
+ if (!fields) {
1177
+ await end();
1178
+ const why = read.ok ? `it read ${show(redactWords(said.split("\n")[0] ?? ""))}` : redactWords(read.error.message);
1179
+ return vendorFail("phone-harness", `phoned said hello, and its process id could not be read back from the phone (${why}): without it the next phoned could start before this one lets go of the phone's accessibility`);
1189
1180
  }
1181
+ return ok({ client, hello: hello.value, end });
1190
1182
  }
1191
1183
  /**
1192
- * A batch in its turn: batches run one at a time, since two at once would interleave their adb commands on the phone.
1193
- * A cancel while the batch waits answers at once, aborted with none of it run, and its turn then passes with nothing
1194
- * done; a cancel once it runs stops it at the action it is on (#actions).
1184
+ * Waits until the endpoint's last phoned is gone from the phone, and kills it when it outstays PHONED_EXIT_S. A phone
1185
+ * has one accessibility connection to give, and phoned holds it until it exits: a phoned started before then finds it
1186
+ * taken ("already registered" at its first ui call), so none starts while the last one runs.
1195
1187
  */
1196
- #inTurn(actions, signal) {
1197
- 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" } });
1198
- let started = false;
1199
- const turn = this.#inputs.then(() => {
1200
- started = true;
1201
- return signal.aborted ? waitedOut() : this.#actions(actions, signal);
1202
- });
1203
- this.#inputs = turn.catch(() => undefined);
1204
- return new Promise((resolve, reject) => {
1205
- const stop = () => {
1206
- if (!started)
1207
- resolve(waitedOut());
1208
- };
1209
- signal.addEventListener("abort", stop, { once: true });
1210
- if (signal.aborted)
1211
- stop();
1212
- turn.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
1213
- });
1214
- }
1215
- async #actions(actions, signal) {
1216
- const refused = checkActions(actions, PHONE_GROUPS);
1217
- if (refused !== undefined)
1218
- return ok({ done: 0, failed: refused });
1219
- const list = actions;
1220
- const plans = [];
1221
- for (const [index, action] of list.entries()) {
1222
- const plan = this.#commands(action);
1223
- if ("kind" in plan)
1224
- return ok({ done: 0, failed: { index, kind: plan.kind, message: `action ${index}: ${plan.message}` } });
1225
- for (const at of pointsOf(action)) {
1226
- if (at[0] < 0 || at[1] < 0 || at[0] >= this.#size[0] || at[1] >= this.#size[1]) {
1227
- return ok({ done: 0, failed: { index, kind: "invalid", message: `action ${index}: ${show(at)} is off the ${this.#size[0]}x${this.#size[1]} screen` } });
1228
- }
1229
- }
1230
- plans.push(plan);
1188
+ async #lastGone(endpoint, transport, onPhone) {
1189
+ const last = this.#lastPhoned.get(endpoint);
1190
+ if (last === undefined)
1191
+ return ok(undefined);
1192
+ const { pid } = last;
1193
+ const waited = await onPhone(`shell:${untilGone(last)}`, transport);
1194
+ if (!waited.ok)
1195
+ return waited;
1196
+ const said = waited.value.trim().split("\n").at(-1) ?? "";
1197
+ if (said === "running") {
1198
+ return vendorFail("phone-harness", `the phoned of this phone's last connection (pid ${pid}) did not exit within ${PHONED_EXIT_S} s, nor ${PHONED_KILL_S} s after a kill, and it holds the phone's accessibility: no phoned starts beside it; release this phone and create another`);
1231
1199
  }
1232
- // A cancel stops the batch at the action it is on: before its wait, after it, and before each command.
1233
- const cancelled = (index) => ok({ done: index, failed: { index, kind: "aborted", message: `action ${index}: the batch was aborted; actions ${index} on did not run` } });
1234
- for (const [index, plan] of plans.entries()) {
1235
- if (signal?.aborted)
1236
- return cancelled(index);
1237
- if (plan.waitMs !== undefined) {
1238
- await this.#pause(plan.waitMs, signal);
1239
- // A wait the cancel cut short is not done.
1240
- if (signal?.aborted)
1241
- return cancelled(index);
1242
- }
1243
- for (const command of plan.commands) {
1244
- if (signal?.aborted)
1245
- return cancelled(index);
1246
- const ran = await this.#shell(command, signal, ADB_TIMEOUT_MS + (plan.busyMs ?? 0));
1247
- if (!ran.ok) {
1248
- const kind = ran.error.code === "timeout" || ran.error.code === "aborted" || ran.error.code === "not_found" ? ran.error.code : "invalid";
1249
- return ok({ done: index, failed: { index, kind, message: `action ${index}: ${ran.error.message}` } });
1250
- }
1251
- }
1252
- }
1253
- return ok({ done: plans.length });
1254
- }
1255
- // --- apps ----------------------------------------------------------------------------------------------------
1256
- async #foreground() {
1257
- const out = await this.#shell("dumpsys activity activities");
1258
- if (!out.ok)
1259
- return out;
1260
- const found = /topResumedActivity=ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)\//.exec(out.value) ?? /mResumedActivity: ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)\//.exec(out.value);
1261
- return ok(found ? found[1] : null);
1262
- }
1263
- async #appsList() {
1264
- const out = await this.#shell("pm list packages");
1265
- if (!out.ok)
1266
- return out;
1267
- const apps = out.value
1268
- .split("\n")
1269
- .filter((line) => line.startsWith("package:"))
1270
- .map((line) => ({ id: line.slice("package:".length).trim() }))
1271
- .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
1272
- const foreground = await this.#foreground();
1273
- if (!foreground.ok)
1274
- return foreground;
1275
- return ok({ apps, foreground: foreground.value });
1276
- }
1277
- async #launch(id) {
1278
- if (typeof id !== "string" || !APP_ID.test(id))
1279
- return refuse("invalid", `id ${show(id)} is not an Android package id`);
1280
- const resolved = await this.#shell(`cmd package resolve-activity --brief -c android.intent.category.LAUNCHER ${id}`);
1281
- if (!resolved.ok)
1282
- return resolved;
1283
- const component = resolved.value
1284
- .split("\n")
1285
- .map((line) => line.trim())
1286
- .reverse()
1287
- .find((line) => COMPONENT.test(line));
1288
- if (component === undefined)
1289
- return refuse("not_found", `${id} has no activity to launch: is it installed?`);
1290
- // The app named comes to the front, not whatever its task last held: on Android 15 Settings' task keeps search (another
1291
- // package) on top, and a plain start resumes it there. A cleared task starts the app itself (phone probe 2).
1292
- const started = await this.#shell(`am start -W --activity-clear-task -n ${component}`);
1293
- if (!started.ok)
1294
- return started;
1295
- if (/Error:|Exception/.test(started.value))
1296
- return vendorFail("phone-harness", `am start of ${component}: ${redactWords(started.value.trim().split("\n").at(-1) ?? "")}`);
1297
- return ok({});
1200
+ if (said !== "exited" && said !== "killed")
1201
+ return vendorFail("phone-harness", `the wait for the last phoned on the phone (pid ${pid}) to exit answered ${show(redactWords(said))}`);
1202
+ this.#lastPhoned.delete(endpoint);
1203
+ return ok(undefined);
1298
1204
  }
1299
- async #terminate(id) {
1300
- if (typeof id !== "string" || !APP_ID.test(id))
1301
- return refuse("invalid", `id ${show(id)} is not an Android package id`);
1302
- const stopped = await this.#shell(`am force-stop ${id}`);
1303
- return stopped.ok ? ok({}) : stopped;
1205
+ }
1206
+ /**
1207
+ * One connection's client of the phone's shared phoned: calls go to phoned, and close lets this connection's hold of
1208
+ * the phone go. A call still running when its connection closes is cancelled (phoned gets $/cancelRequest); a later
1209
+ * one fails with gone.
1210
+ */
1211
+ class PhoneClient {
1212
+ daemon;
1213
+ release;
1214
+ #closing = new AbortController();
1215
+ #gone = Promise.resolve();
1216
+ constructor(daemon,
1217
+ /** Lets this connection's hold of the phone go: the last one ends phoned and drops the adb transport. */
1218
+ release) {
1219
+ this.daemon = daemon;
1220
+ this.release = release;
1304
1221
  }
1305
- async #tree() {
1306
- const raw = await this.#execOut("uiautomator dump /dev/tty");
1307
- if (!raw.ok)
1308
- return raw;
1309
- const text = raw.value.toString("utf8");
1310
- const start = text.indexOf("<?xml");
1311
- if (start < 0)
1312
- return refuse("unsupported", `uiautomator gave no tree for this screen: ${redactWords(text.trim().split("\n")[0] || "nothing")}`);
1313
- return parseUiTree(text.slice(start, text.lastIndexOf(">") + 1), this.#size);
1222
+ call(method, params, options = {}) {
1223
+ if (this.#closing.signal.aborted)
1224
+ return Promise.resolve(fail("gone", "the connection to the phone is closed"));
1225
+ const signal = options.signal ? AbortSignal.any([options.signal, this.#closing.signal]) : this.#closing.signal;
1226
+ return this.daemon.call(method, params, { signal });
1314
1227
  }
1315
- }
1316
- /** Every point an action touches, to check against the screen. */
1317
- function pointsOf(action) {
1318
- if (action.type === "tap" || action.type === "long_press")
1319
- return [action.at];
1320
- if (action.type === "swipe")
1321
- return action.path;
1322
- return [];
1323
- }
1324
- /** The frame `adb exec-out screencap` gives: a header (width, height, format, and a color space on newer Androids), then the pixels. */
1325
- export function decodeScreencap(raw) {
1326
- if (raw.length < 12)
1327
- return vendorFail("phone-harness", `screencap gave ${raw.length} bytes, not a frame`);
1328
- const width = raw.readUInt32LE(0);
1329
- const height = raw.readUInt32LE(4);
1330
- const format = raw.readUInt32LE(8);
1331
- const pixels = width * height * 4;
1332
- const header = raw.length - pixels;
1333
- if (!(width > 0 && height > 0 && (header === 12 || header === 16)))
1334
- return vendorFail("phone-harness", `screencap gave ${raw.length} bytes for a ${width}x${height} frame`);
1335
- const rgba = Buffer.from(raw.subarray(header));
1336
- // 1 is RGBA_8888, 2 RGBX_8888 (alpha unset), 5 BGRA_8888.
1337
- if (format === 2)
1338
- for (let i = 3; i < rgba.length; i += 4)
1339
- rgba[i] = 255;
1340
- else if (format === 5)
1341
- for (let i = 0; i < rgba.length; i += 4)
1342
- [rgba[i], rgba[i + 2]] = [rgba[i + 2], rgba[i]];
1343
- else if (format !== 1)
1344
- return fail("unsupported", `screencap gave pixel format ${format}, which this provider does not read`);
1345
- return ok({ width, height, rgba });
1346
- }
1347
- /** How often a waiting screen.watch reads a phone's screen: about once a second (the user-approved decision, 2026-11-09). */
1348
- const WATCH_POLL_MS = 1_000;
1349
- /** A width x height RGBA frame scaled to toWidth x toHeight by the nearest pixel. */
1350
- function scaleRgba(rgba, width, height, toWidth, toHeight) {
1351
- const out = Buffer.alloc(toWidth * toHeight * 4);
1352
- for (let y = 0; y < toHeight; y++) {
1353
- const sy = Math.floor((y * height) / toHeight);
1354
- for (let x = 0; x < toWidth; x++) {
1355
- const sx = Math.floor((x * width) / toWidth);
1356
- rgba.copy(out, (y * toWidth + x) * 4, (sy * width + sx) * 4, (sy * width + sx) * 4 + 4);
1357
- }
1228
+ close() {
1229
+ if (this.#closing.signal.aborted)
1230
+ return;
1231
+ this.#closing.abort();
1232
+ this.#gone = this.release().catch(() => undefined);
1358
1233
  }
1359
- return out;
1360
- }
1361
- /** zlib's deflate on its thread pool: a screen's deflate never holds this process's event loop. */
1362
- const deflateAsync = promisify(deflate);
1363
- /** An 8-bit RGBA PNG, non-interlaced, of rect of a width-wide RGBA frame. The rows are deflated off the event loop: a
1364
- * 1080x2400 screen took about 170 ms, every request of the server this harness runs in waiting on it. */
1365
- export async function encodePng(rgba, width, [x, y, w, h]) {
1366
- const rows = Buffer.alloc((w * 4 + 1) * h);
1367
- for (let row = 0; row < h; row++) {
1368
- const from = ((y + row) * width + x) * 4;
1369
- rgba.copy(rows, row * (w * 4 + 1) + 1, from, from + w * 4);
1234
+ /** Closes, and waits until the phone's hold is let go (phoned ended and the transport dropped, when it was the last). */
1235
+ async closed() {
1236
+ this.close();
1237
+ await this.#gone;
1370
1238
  }
1371
- const chunk = (type, data) => {
1372
- const length = Buffer.alloc(4);
1373
- length.writeUInt32BE(data.length);
1374
- const typed = Buffer.concat([Buffer.from(type, "latin1"), data]);
1375
- const crc = Buffer.alloc(4);
1376
- crc.writeUInt32BE(crc32(typed) >>> 0);
1377
- return Buffer.concat([length, typed, crc]);
1378
- };
1379
- const ihdr = Buffer.alloc(13);
1380
- ihdr.writeUInt32BE(w, 0);
1381
- ihdr.writeUInt32BE(h, 4);
1382
- ihdr.set([8, 6, 0, 0, 0], 8);
1383
- return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", await deflateAsync(rows)), chunk("IEND", Buffer.alloc(0))]);
1384
1239
  }
1385
- const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
1386
- 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()]);
1387
- /** uiautomator's dump as the protocol's tree: one root (the window's, or one over several), at most MAX_UI_NODES nodes. */
1388
- export function parseUiTree(xml, [width, height]) {
1389
- const top = [];
1390
- const stack = [];
1391
- let nodes = 0;
1392
- let truncated = false;
1393
- let dropped = 0;
1394
- for (const tag of xml.matchAll(/<(\/?)node\b([^>]*?)(\/?)>/g)) {
1395
- const [, closing, body, selfClosing] = tag;
1396
- if (closing) {
1397
- if (dropped > 0)
1398
- dropped--;
1399
- else
1400
- stack.pop();
1401
- continue;
1402
- }
1403
- if (dropped > 0 || nodes >= MAX_UI_NODES) {
1404
- truncated = true;
1405
- if (!selfClosing)
1406
- dropped++;
1407
- continue;
1408
- }
1409
- const attrs = {};
1410
- for (const [, key, value] of body.matchAll(/([\w:-]+)="([^"]*)"/g))
1411
- attrs[key] = unescape(value);
1412
- const box = /^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$/.exec(attrs.bounds ?? "");
1413
- const [x1, y1, x2, y2] = box ? box.slice(1).map(Number) : [0, 0, 0, 0];
1414
- const bool = (key) => attrs[key] === "true";
1415
- const node = {
1416
- role: attrs.class || "node",
1417
- ...(attrs["resource-id"] ? { id: attrs["resource-id"] } : {}),
1418
- ...(attrs.text ? { text: attrs.text } : {}),
1419
- ...(attrs["content-desc"] ? { label: attrs["content-desc"] } : {}),
1420
- bounds: [x1, y1, Math.max(0, x2 - x1), Math.max(0, y2 - y1)],
1421
- enabled: bool("enabled"),
1422
- clickable: bool("clickable"),
1423
- focused: bool("focused"),
1424
- selected: bool("selected"),
1425
- checked: bool("checked"),
1426
- scrollable: bool("scrollable"),
1427
- children: [],
1428
- };
1429
- nodes++;
1430
- (stack.at(-1)?.children ?? top).push(node);
1431
- if (!selfClosing)
1432
- stack.push(node);
1433
- }
1434
- if (top.length === 0)
1435
- return vendorFail("phone-harness", "uiautomator's dump held no node");
1436
- if (top.length === 1)
1437
- return ok({ root: top[0], nodes, truncated });
1438
- return ok({ root: { role: "hierarchy", bounds: [0, 0, width, height], enabled: true, children: top }, nodes: nodes + 1, truncated });
1240
+ /** Whether labels carries every one of wanted. */
1241
+ const carries = (labels, wanted) => Object.entries(wanted ?? {}).every(([key, value]) => labels[key] === value);
1242
+ function sessionOf(json, where) {
1243
+ const s = json;
1244
+ if (typeof s !== "object" || s === null || typeof s.id !== "string" || typeof s.state !== "string")
1245
+ return vendorFail("phone-harness", `${where} answered ${show(json).slice(0, 200)}, not a session`);
1246
+ return ok(s);
1439
1247
  }