@parcha/agentrun-computer 0.1.0-beta.41 → 0.1.0-beta.43

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 (73) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +254 -14
  3. package/box/README.md +2 -2
  4. package/box/build-e2b.mjs +1 -1
  5. package/dist/box-image.d.ts +1 -3
  6. package/dist/box-image.js +1 -11
  7. package/dist/boxd.d.ts +126 -0
  8. package/dist/boxd.js +418 -0
  9. package/dist/cloudflare.d.ts +32 -0
  10. package/dist/cloudflare.js +181 -0
  11. package/dist/computerd-linux-amd64 +0 -0
  12. package/dist/computerd-linux-arm64 +0 -0
  13. package/dist/computerd.json +2 -2
  14. package/dist/conformance/boxd.d.ts +77 -0
  15. package/dist/conformance/boxd.js +113 -0
  16. package/dist/conformance/cases/isolation.js +1 -17
  17. package/dist/conformance/cloudflare.d.ts +42 -0
  18. package/dist/conformance/cloudflare.js +54 -0
  19. package/dist/conformance/dial-only.d.ts +6 -0
  20. package/dist/conformance/dial-only.js +9 -0
  21. package/dist/conformance/e2b.d.ts +12 -3
  22. package/dist/conformance/e2b.js +21 -4
  23. package/dist/conformance/fly.d.ts +52 -0
  24. package/dist/conformance/fly.js +52 -0
  25. package/dist/conformance/modal.d.ts +15 -2
  26. package/dist/conformance/modal.js +36 -3
  27. package/dist/conformance/morph.d.ts +59 -0
  28. package/dist/conformance/morph.js +95 -0
  29. package/dist/conformance/phone-harness.js +2 -2
  30. package/dist/conformance/runner.js +3 -3
  31. package/dist/conformance/sweep.d.ts +1 -6
  32. package/dist/conformance/sweep.js +8 -18
  33. package/dist/descriptors/boxd.d.ts +52 -0
  34. package/dist/descriptors/boxd.js +29 -0
  35. package/dist/descriptors/cloudflare.d.ts +21 -0
  36. package/dist/descriptors/cloudflare.js +29 -0
  37. package/dist/descriptors/e2b.d.ts +4 -0
  38. package/dist/descriptors/e2b.js +3 -0
  39. package/dist/descriptors/fly.d.ts +19 -0
  40. package/dist/descriptors/fly.js +28 -0
  41. package/dist/descriptors/index.d.ts +113 -1
  42. package/dist/descriptors/index.js +7 -2
  43. package/dist/descriptors/modal.d.ts +3 -0
  44. package/dist/descriptors/modal.js +7 -2
  45. package/dist/descriptors/morph.d.ts +15 -0
  46. package/dist/descriptors/morph.js +21 -0
  47. package/dist/descriptors/phone-harness.d.ts +1 -0
  48. package/dist/descriptors/phone-harness.js +2 -0
  49. package/dist/e2b.d.ts +7 -1
  50. package/dist/e2b.js +87 -44
  51. package/dist/fly.d.ts +43 -0
  52. package/dist/fly.js +245 -0
  53. package/dist/host.d.ts +8 -28
  54. package/dist/hosted/process.d.ts +19 -0
  55. package/dist/hosted/process.js +28 -0
  56. package/dist/hosted/provider.d.ts +11 -22
  57. package/dist/hosted/provider.js +30 -201
  58. package/dist/hosted/scripts.d.ts +2 -8
  59. package/dist/hosted/scripts.js +2 -22
  60. package/dist/hosted/ssh-exec.d.ts +2 -1
  61. package/dist/hosted/ssh-exec.js +58 -2
  62. package/dist/hosted/values.d.ts +5 -0
  63. package/dist/hosted/values.js +9 -0
  64. package/dist/index.d.ts +1 -1
  65. package/dist/index.js +2 -2
  66. package/dist/modal.d.ts +6 -0
  67. package/dist/modal.js +20 -10
  68. package/dist/morph.d.ts +65 -0
  69. package/dist/morph.js +495 -0
  70. package/dist/phone-harness.d.ts +15 -5
  71. package/dist/phone-harness.js +50 -15
  72. package/dist/screen-watch.js +2 -2
  73. package/package.json +20 -2
package/dist/morph.js ADDED
@@ -0,0 +1,495 @@
1
+ // The Morph host: Morph Cloud instances, each a VM started from a snapshot (kind linux). The control plane is Morph's
2
+ // REST API over fetch (https://cloud.morph.so/api, a Bearer key; OpenAPI https://cloud.morph.so/api/openapi.json). Every
3
+ // command (the daemon's upload, its install, init's start, the stdio bridge) goes over SSH through the shared SshExec
4
+ // (./hosted/ssh-exec.ts), to Morph's gateway ssh.cloud.morph.so:22 (morph-typescript-sdk src/api.ts:12-13) as the user
5
+ // "<instance id>" with the instance's own key pair, which GET /instance/{id}/ssh/key answers over TLS (OpenAPI
6
+ // InstanceSshKey: "an ephemeral SSH key for establishing connections", api.ts sshKey()). Both SDKs log in as
7
+ // "<instance id>:<API key>" with any key (morph-python-sdk morphcloud/api.py ssh_connect; api.ts:704-711); that is not
8
+ // used, since Morph publishes no host key for its gateway, so a host posing as it would read the account's key out of
9
+ // the username. A public-key login hands an impostor nothing to reuse: its signature is bound to the session. That the
10
+ // gateway takes the instance's key for the user "<instance id>" is **unverified**. Morph's REST exec (POST
11
+ // /instance/{id}/exec) answers once the command ends, with no stdin, so it is not used. The rest of the computer is the
12
+ // shared machine-host adapter's (./hosted/provider.ts).
13
+ //
14
+ // Facts the docs do not settle are marked **unverified**; d7/morph-branch-1 (the lane's live kit) settles most of them.
15
+ import { createHash } from "node:crypto";
16
+ import { readFile } from "node:fs/promises";
17
+ import { isIP, connect as tcp } from "node:net";
18
+ import { boxRecipeHash } from "./box-image.js";
19
+ import { MORPH } from "./descriptors/morph.js";
20
+ import { DEADLINE_LABEL, DEFAULT_CPUS, DEFAULT_MEMORY_MB, show } from "./drift.js";
21
+ import { HostError } from "./host.js";
22
+ import { orThrow, pause, runToExit, uploadThroughExec } from "./hosted/process.js";
23
+ import { HostedProvider, isoOf, MAX_LABEL } from "./hosted/provider.js";
24
+ import { jsonOf, rest } from "./hosted/rest.js";
25
+ import { pemOf, SshExec, SshTunnelError } from "./hosted/ssh-exec.js";
26
+ import { DOMAIN, dateOf, sizeRefusals } from "./hosted/values.js";
27
+ import { failFor, ok } from "./result.js";
28
+ /** Not a literal, so no type checker or bundler resolves ssh2 from this package. */
29
+ const SSH2_PACKAGE = "ssh2";
30
+ /** The SDKs' base (api.ts:11 MORPH_BASE_URL) and SSH gateway (api.ts:12-13). */
31
+ const DEFAULT_API_URL = "https://cloud.morph.so/api";
32
+ const DEFAULT_SSH_HOST = "ssh.cloud.morph.so";
33
+ const DEFAULT_SSH_PORT = 22;
34
+ /** An instance id as it reaches a URL and the SSH username, whose ":" ends it. Morph's form, morphvm_<...>, is unverified. */
35
+ const INSTANCE_ID = /^[A-Za-z0-9_-]{1,128}$/;
36
+ /** A snapshot id, "like snapshot_xxxx" (OpenAPI SnapshotModel.id). */
37
+ const SNAPSHOT_ID = /^snapshot_[A-Za-z0-9_-]{1,120}$/;
38
+ const DAY_MS = 24 * 60 * 60_000;
39
+ /** The image every box snapshot starts from: the default of CreateSnapshotRequest.image_id (OpenAPI). */
40
+ const BASE_IMAGE = "morphvm-minimal";
41
+ /** The box snapshot's size, which is every computer's (a start takes no size): the adapter's default, and 16 GiB of disk. */
42
+ const BOX_SIZE = { vcpus: DEFAULT_CPUS, memory: DEFAULT_MEMORY_MB, disk_size: 16_384 };
43
+ /** The label of a build's own instance and base snapshot, its value the box image's name. */
44
+ const BUILD_LABEL = "agentrun-box-build";
45
+ /** A build (boot, install.sh, snapshot), all of it; and the TTL of its instance, so a build left by a crash ends. */
46
+ const BUILD_MS = 45 * 60_000;
47
+ const BUILD_TTL_S = 2 * 60 * 60;
48
+ /**
49
+ * One REST call of the build that answers at once, and the pause between two reads of something Morph is making. A
50
+ * create that answers only once its snapshot is made has the build's remaining time instead (see boxSnapshot).
51
+ */
52
+ const BUILD_CALL_MS = 60_000;
53
+ const POLL_MS = 1_000;
54
+ /** How far /ttl's read-back end may sit from the call's now plus its seconds, Morph's rounding and the call's transit aside. */
55
+ const TTL_SLACK_MS = 2_000;
56
+ const RECIPE_FILES = ["install.sh", "agentrun-archil"];
57
+ /** An id held to the form above before it reaches a URL or the SSH username: not_found else. */
58
+ function instanceId(id) {
59
+ if (!INSTANCE_ID.test(id))
60
+ throw new HostError("not_found", `${JSON.stringify(id)} is not a Morph instance id`);
61
+ return id;
62
+ }
63
+ /** Morph's error body, FastAPI's: { detail: "<words>" } or { detail: [{ msg }] }, with error_code on snapshot routes (OpenAPI SnapshotWriterError). */
64
+ function detailOf(body) {
65
+ const { detail, error_code: code } = (body ?? {});
66
+ const said = typeof detail === "string" ? detail : Array.isArray(detail) ? detail.map((one) => one?.msg).filter((msg) => typeof msg === "string").join("; ") : "";
67
+ return [typeof code === "string" ? code : "", said].filter(Boolean).join(": ");
68
+ }
69
+ function codeOf(error) {
70
+ if (error instanceof HostError)
71
+ return error.code;
72
+ // ssh2 names the stage that failed (lib/client.js): the gateway refused the login, or the handshake timed out.
73
+ const { level } = (error ?? {});
74
+ if (level === "client-authentication")
75
+ return "denied";
76
+ if (level === "client-timeout")
77
+ return "timeout";
78
+ return "vendor";
79
+ }
80
+ /** Morph's statuses (OpenAPI InstanceStatus) as the adapter's states: saving is a snapshot in progress, error is gone. */
81
+ function stateOf(status) {
82
+ if (status === "ready")
83
+ return "running";
84
+ if (status === "pending" || status === "saving")
85
+ return "starting";
86
+ if (status === "paused")
87
+ return "stopped";
88
+ if (status === "error")
89
+ return "gone";
90
+ return undefined;
91
+ }
92
+ /** An instance as the adapter reads a machine: its state (one this provider does not know is gone, in words), labels, start and TTL's end. */
93
+ function machineOf(instance) {
94
+ const state = stateOf(instance.status);
95
+ const why = state === undefined ? `Morph reads the status ${show(instance.status)}, which this provider does not know` : instance.status === "error" ? "Morph reads the instance in error, with no reason given" : undefined;
96
+ const created = dateOf(instance.created, "s");
97
+ const ends = dateOf(instance.ttl?.ttl_expire_at ?? undefined, "s");
98
+ return {
99
+ id: instance.id,
100
+ labels: { ...(instance.metadata ?? {}) },
101
+ state: state ?? "gone",
102
+ ...(created ? { createdAt: created } : {}),
103
+ ...(ends ? { endsAt: ends } : {}),
104
+ ...(why === undefined ? {} : { why }),
105
+ };
106
+ }
107
+ /** Morph's instances as a MachineHost (../host.ts). */
108
+ class MorphHost {
109
+ descriptor = MORPH;
110
+ facts = {
111
+ daemon: "child",
112
+ // A VM (docs: concepts/mental-model); the hypervisor is not named.
113
+ isolation: "vm",
114
+ // ttl_seconds with ttl_action stop at create, moved by POST /instance/{id}/ttl (docs: documentation/instances/ttl).
115
+ lifetime: "vendor",
116
+ // Morph states no cap: the janitor's, unverified.
117
+ maxLifetimeMs: DAY_MS,
118
+ // Unverified: no arch in the OpenAPI.
119
+ arch: "amd64",
120
+ // The guest's sshd behind the gateway, unverified: the docs name no port inside the VM.
121
+ vendorAgentPorts: [22],
122
+ };
123
+ #client;
124
+ #ssh;
125
+ #sshHost;
126
+ #sshPort;
127
+ /** Each instance's SSH private key (GET /instance/{id}/ssh/key), read before its first exec and kept until delete or a refused login. */
128
+ #keys = new Map();
129
+ constructor(options) {
130
+ const { apiKey } = options;
131
+ this.#sshHost = options.sshHost;
132
+ this.#sshPort = options.sshPort;
133
+ // The user is the instance id alone and the key is the instance's: the account's key never goes over SSH. An
134
+ // instance whose key was let go logs in with none, which the gateway refuses (denied).
135
+ this.#ssh = new SshExec({ ssh2: options.ssh2, loginOf: (id) => ({ username: id, ...(this.#keys.has(id) ? { privateKey: this.#keys.get(id) } : {}), secrets: [apiKey] }), tunnelOf: () => this.#tunnel() });
136
+ this.#client = rest({
137
+ base: options.apiUrl,
138
+ headers: () => ({ Authorization: `Bearer ${apiKey}`, Accept: "application/json" }),
139
+ vendor: "morph",
140
+ fetch: options.fetch,
141
+ timeoutMs: 30_000, // every call gives its own: ctx.timeoutMs
142
+ explain: ({ status, bytes, what }) => {
143
+ const said = detailOf(jsonOf(bytes));
144
+ // 503 is an admission refusal before dispatch (OpenAPI: "Snapshot admission busy", Retry-After: 1).
145
+ return { ...(status === 503 ? { code: "limit" } : {}), message: `${what} answered ${status}${said ? `: ${said}` : ""}` };
146
+ },
147
+ });
148
+ }
149
+ errorCode(error) {
150
+ return codeOf(error);
151
+ }
152
+ /**
153
+ * A TCP connection to the gateway. No host key is pinned: Morph publishes none, and both SDKs take any (paramiko's
154
+ * AutoAddPolicy). The login is a public key, so a host posing as the gateway learns no credential.
155
+ */
156
+ #tunnel() {
157
+ const host = `${this.#sshHost}:${this.#sshPort}`;
158
+ const socket = tcp(this.#sshPort, this.#sshHost);
159
+ // ssh2 reads the socket's errors once it has it; this keeps one before then from being thrown.
160
+ socket.on("error", () => { });
161
+ const opened = new Promise((resolve, reject) => {
162
+ socket.once("connect", resolve);
163
+ socket.once("error", (error) => reject(new SshTunnelError(`the SSH connection to ${host} failed to open: ${error.message}`)));
164
+ });
165
+ opened.catch(() => { });
166
+ return { duplex: socket, opened, host };
167
+ }
168
+ /**
169
+ * argv over SSH through the gateway (hosted/ssh-exec.ts), as the user it lands as: root, unverified. The instance's
170
+ * key is read first when this host has none for it; a refused login lets it go, so the next exec reads it again (a
171
+ * key rotated in the account).
172
+ */
173
+ async exec(id, argv, ctx) {
174
+ instanceId(id);
175
+ if (!this.#keys.has(id))
176
+ this.#keys.set(id, await this.#keyOf(id, ctx));
177
+ try {
178
+ return await this.#ssh.exec(id, argv, ctx);
179
+ }
180
+ catch (error) {
181
+ if (codeOf(error) === "denied")
182
+ this.#keys.delete(id);
183
+ throw error;
184
+ }
185
+ }
186
+ /**
187
+ * GET /instance/{id}/ssh/key (OpenAPI InstanceSshKey): its private key, in a form ssh2 reads. Morph answers PKCS#8
188
+ * (the PEM label "PRIVATE KEY"; d7/morph-live-2's ssh2 refused it), which pemOf converts. The answer's password and
189
+ * token are not kept.
190
+ */
191
+ async #keyOf(id, ctx) {
192
+ const { private_key: given } = (await this.#rest("GET", `/instance/${id}/ssh/key`, undefined, ctx)) ?? {};
193
+ const key = typeof given === "string" ? pemOf(given) : undefined;
194
+ if (key === undefined)
195
+ throw new HostError("vendor", `GET /instance/${id}/ssh/key answered no private key ssh2 can read (PEM: OpenSSH, PKCS#1, SEC1, or PKCS#8 RSA, EC or Ed25519)`);
196
+ return key;
197
+ }
198
+ /** One REST call, bounded by ctx: its JSON answer; a failure throws a HostError in Morph's words. */
199
+ async #rest(method, path, body, ctx) {
200
+ const answer = orThrow(await this.#client.call(method, this.#client.url(path), { ...(body === undefined ? {} : { json: body }), timeoutMs: ctx.timeoutMs }, ctx.signal));
201
+ const parsed = jsonOf(answer.bytes);
202
+ if (parsed === null && method !== "DELETE")
203
+ throw new HostError("vendor", `${method} ${path} answered ${answer.status} with no JSON body`);
204
+ return parsed;
205
+ }
206
+ /** A Morph image is a snapshot id in the key's account; a size is the snapshot's, so cpus and memoryMb are refused. */
207
+ check(given) {
208
+ const refusals = sizeRefusals(given, "a Morph computer", "snapshot");
209
+ if (typeof given.image === "string" && given.image !== "" && !SNAPSHOT_ID.test(given.image)) {
210
+ refusals.push({ field: "image", message: "an image is the id of a Morph snapshot in the key's account, such as snapshot_abc123: the box snapshot prepareImage() builds, or one of your own" });
211
+ }
212
+ return refusals;
213
+ }
214
+ /**
215
+ * POST /instance (OpenAPI StartInstanceRequest): the snapshot, the labels as metadata, which carry the request's name
216
+ * (Morph has no name field and no idempotency key), and the lifetime as a TTL whose action is stop, which releases
217
+ * the instance (docs: documentation/instances/ttl). req.egress is left: Morph has no egress control, so the fence and
218
+ * the egress proxy are ours. The answer comes before the instance is ready; the adapter polls get.
219
+ */
220
+ async create(req, ctx) {
221
+ const made = await this.#rest("POST", "/instance", { snapshot_id: req.image, metadata: req.labels, ttl_seconds: Math.ceil(req.lifetimeMs / 1000), ttl_action: "stop" }, ctx);
222
+ if (typeof made?.id !== "string" || !INSTANCE_ID.test(made.id))
223
+ throw new HostError("vendor", `POST /instance answered no instance id: ${show(made?.id)}`);
224
+ return { id: made.id };
225
+ }
226
+ /** GET /instance/{id}; a 404 is not_found, which the adapter reads as none. What Morph answers for a deleted one is unverified. */
227
+ async get(id, ctx) {
228
+ return machineOf(await this.#rest("GET", `/instance/${instanceId(id)}`, undefined, ctx));
229
+ }
230
+ /**
231
+ * GET /instance, the account's every instance in one answer (OpenAPI InstanceModelCollection, no page fields): the
232
+ * adapter matches the labels. Its metadata[...] filter is not used: whether a dotted key like agentrun.computer
233
+ * survives its deepObject query is unverified, and a filter misread would hide machines.
234
+ */
235
+ async list(labels, ctx) {
236
+ void labels;
237
+ const listed = await this.#rest("GET", "/instance", undefined, ctx);
238
+ if (!Array.isArray(listed?.data))
239
+ throw new HostError("vendor", "GET /instance answered no data list");
240
+ return listed.data.filter((instance) => typeof instance?.id === "string").map(machineOf);
241
+ }
242
+ /** DELETE /instance/{id}, "Stop and delete" (OpenAPI); a 404 is done. Then this host's SSH connections to it end. */
243
+ async delete(id, ctx) {
244
+ try {
245
+ await this.#rest("DELETE", `/instance/${instanceId(id)}`, undefined, { timeoutMs: ctx.timeoutMs });
246
+ }
247
+ finally {
248
+ this.#ssh.closeAll(id);
249
+ this.#keys.delete(id);
250
+ }
251
+ }
252
+ /**
253
+ * The TTL moved to endsAt, rounded up to the second and never past the max-deadline label (POST /instance/{id}/ttl),
254
+ * then the deadline label to endsAt with the rest of the metadata as it was (POST /instance/{id}/metadata, whose
255
+ * merge-or-replace is unverified: the whole map is sent). Whether ttl_seconds counts from now is unverified, so the
256
+ * end /ttl answers is held to now plus the seconds: an end elsewhere throws, and the label is not moved.
257
+ */
258
+ async extend(id, endsAt, ctx) {
259
+ const path = `/instance/${instanceId(id)}`;
260
+ const { metadata } = await this.#rest("GET", path, undefined, ctx);
261
+ const labels = { ...(metadata ?? {}) };
262
+ const most = isoOf(labels[MAX_LABEL]);
263
+ if (most === undefined)
264
+ throw new HostError("refused", `${id}'s label ${MAX_LABEL} reads ${show(labels[MAX_LABEL])}, so the most it may live is unknown; nothing moved`);
265
+ const before = Date.now();
266
+ const seconds = Math.min(Math.ceil((endsAt.getTime() - before) / 1000), Math.floor((most.getTime() - before) / 1000));
267
+ if (seconds < 1)
268
+ throw new HostError("limit", `no whole number of seconds Morph takes moves ${id}'s end to ${endsAt.toISOString()} without passing ${most.toISOString()}; nothing moved`);
269
+ const moved = await this.#rest("POST", `${path}/ttl`, { ttl_seconds: seconds, ttl_action: "stop" }, ctx);
270
+ const at = (moved?.ttl?.ttl_expire_at ?? Number.NaN) * 1000;
271
+ if (!(at >= before + seconds * 1000 - TTL_SLACK_MS && at <= Date.now() + seconds * 1000 + TTL_SLACK_MS)) {
272
+ throw new HostError("vendor", `Morph was asked for a TTL of ${seconds} s on ${id} and reads its end back as ${show(moved?.ttl?.ttl_expire_at)}, not about ${Math.round(before / 1000) + seconds} (Unix s): its TTL does not count from the call, as this provider takes it to`);
273
+ }
274
+ await this.#rest("POST", `${path}/metadata`, { ...labels, [DEADLINE_LABEL]: endsAt.toISOString() }, ctx);
275
+ }
276
+ /** Reads until done answers a value, a pause between reads, until end or signal: a timeout or an abort in words. */
277
+ async #until(what, end, signal, done) {
278
+ for (;;) {
279
+ const value = await done();
280
+ if (value !== undefined)
281
+ return value;
282
+ if (signal?.aborted)
283
+ throw new HostError("aborted", `the wait for ${what} was aborted`);
284
+ if (Date.now() > end)
285
+ throw new HostError("timeout", `${what} was not ready within ${BUILD_MS / 60_000} minutes`);
286
+ await pause(POLL_MS, signal);
287
+ }
288
+ }
289
+ /** Snapshot id once Morph reads it ready; failed or gone throws in words. */
290
+ #snapshotReady(id, end, signal) {
291
+ return this.#until(`the Morph snapshot ${id}`, end, signal, async () => {
292
+ const { status } = await this.#rest("GET", `/snapshot/${id}`, undefined, { timeoutMs: BUILD_CALL_MS, ...(signal ? { signal } : {}) });
293
+ if (status === "ready")
294
+ return id;
295
+ if (status !== "pending")
296
+ throw new HostError("vendor", `the Morph snapshot ${id} is ${show(status)}, not ready`);
297
+ return undefined;
298
+ });
299
+ }
300
+ /**
301
+ * The box snapshot of this name (its digest), oldest first: a ready one, or one being made, waited for. One that
302
+ * failed, with none other, throws in words. undefined when the account has none.
303
+ */
304
+ async #boxOf(name, end, signal) {
305
+ const listed = await this.#rest("GET", `/snapshot?digest=${encodeURIComponent(name)}`, undefined, { timeoutMs: BUILD_CALL_MS, ...(signal ? { signal } : {}) });
306
+ const snapshots = (Array.isArray(listed?.data) ? listed.data : []).filter((one) => one?.digest === name && SNAPSHOT_ID.test(one.id)).sort((a, b) => (a.created ?? 0) - (b.created ?? 0));
307
+ const usable = snapshots.find((one) => one.status === "ready") ?? snapshots.find((one) => one.status === "pending");
308
+ if (usable !== undefined)
309
+ return this.#snapshotReady(usable.id, end, signal);
310
+ const failed = snapshots.find((one) => one.status === "failed");
311
+ if (failed !== undefined)
312
+ throw new HostError("vendor", `the Morph snapshot ${failed.id} of ${name} failed: delete it in the account, then call again`);
313
+ return undefined;
314
+ }
315
+ /**
316
+ * A base snapshot of this name already in the account, by its label (metadata agentrun-box-build=<name>): the oldest
317
+ * ready one, else the oldest pending one (the caller waits for it); every failed one is deleted first. undefined when
318
+ * there is none. The list's metadata[...] filter was proven on GET /instance (d7/morph-branch-3, step 6, hyphenated
319
+ * and dotted keys); on GET /snapshot it is unverified, so the answer is matched by the label again here.
320
+ */
321
+ async #baseOf(name, call) {
322
+ const listed = await this.#rest("GET", `/snapshot?${encodeURIComponent(`metadata[${BUILD_LABEL}]`)}=${encodeURIComponent(name)}`, undefined, call);
323
+ const bases = (Array.isArray(listed?.data) ? listed.data : []).filter((one) => one?.metadata?.[BUILD_LABEL] === name && SNAPSHOT_ID.test(one.id)).sort((a, b) => (a.created ?? 0) - (b.created ?? 0));
324
+ // Another build may have deleted it first: its 404 is done.
325
+ for (const failed of bases.filter((one) => one.status === "failed")) {
326
+ await this.#rest("DELETE", `/snapshot/${failed.id}`, undefined, call).catch((error) => {
327
+ if (codeOf(error) !== "not_found")
328
+ throw error;
329
+ });
330
+ }
331
+ return (bases.find((one) => one.status === "ready") ?? bases.find((one) => one.status === "pending"))?.id;
332
+ }
333
+ /**
334
+ * A new base snapshot (POST /snapshot from morphvm-minimal at BOX_SIZE, labelled), its id. Morph answers only once the
335
+ * snapshot is made: 78 s from the POST to ready at 1 vCPU / 2 GiB / 8 GiB of disk (d7/morph-branch-3), past the 60 s
336
+ * of one call (d7/morph-live-1 timed out there while Morph went on and made it), and no size is known to be faster. So
337
+ * the call has the build's remaining time. An answer that is lost all the same (a timeout, a dropped connection, a 5xx
338
+ * after the send) may still have made it: the account is looked at again by the label, and one found is the base. That
339
+ * look takes no cancel signal, like the create, so a cancelled build still holds the id and its finally deletes it.
340
+ * With none found the create's failure is thrown, and the next build finds the base by its label once Morph lists it.
341
+ */
342
+ async #newBase(name, end) {
343
+ let made;
344
+ try {
345
+ made = await this.#rest("POST", "/snapshot", { image_id: BASE_IMAGE, ...BOX_SIZE, metadata: { [BUILD_LABEL]: name } }, { timeoutMs: Math.max(1, end - Date.now()) });
346
+ }
347
+ catch (error) {
348
+ const found = await this.#baseOf(name, { timeoutMs: BUILD_CALL_MS });
349
+ if (found === undefined)
350
+ throw error;
351
+ return found;
352
+ }
353
+ if (typeof made?.id !== "string" || !SNAPSHOT_ID.test(made.id))
354
+ throw new HostError("vendor", `POST /snapshot answered no snapshot id: ${show(made?.id)}`);
355
+ return made.id;
356
+ }
357
+ /**
358
+ * The box image as a Morph snapshot in the key's account, its digest the name (agentrun-box-<recipe hash>): found, or
359
+ * built once (`building` told first), as PROVIDERS.md's account-built image says. A build makes a base snapshot of
360
+ * morphvm-minimal at BOX_SIZE (POST /snapshot), starts an instance from it (POST /instance), runs box/install.sh as
361
+ * root over SSH, and snapshots the instance with the digest (POST /instance/{id}/snapshot, synchronous by default),
362
+ * with no TTL, so it never expires (OpenAPI SnapshotModel.ttl). The instance is deleted after, and has a TTL of its
363
+ * own besides. The base snapshot is kept once the box snapshot is asked for, with no TTL: whether a snapshot still needs
364
+ * the one its instance started from is unverified. A build that fails before then deletes its base, so repeated
365
+ * failures leave nothing. install.sh needs apt (morphvm-minimal's distro is unverified) and root.
366
+ *
367
+ * The base is labelled (BUILD_LABEL), and a build looks for one by the label before it makes one (#baseOf): a base an
368
+ * earlier build left (a create whose answer was lost) is used, or waited for, and a failed one is deleted. Two servers
369
+ * building the same recipe at once: when both look before either base is listed, each makes one and builds on it, both
370
+ * bases are kept once their box snapshots are asked for, and every caller answers the oldest box snapshot (#boxOf).
371
+ * When the second looks after the first's base is listed, both build on that one base; a build that fails deletes it,
372
+ * so the other's fails too and is called again.
373
+ */
374
+ async boxSnapshot(name, building, signal) {
375
+ const end = Date.now() + BUILD_MS;
376
+ const call = { timeoutMs: BUILD_CALL_MS, ...(signal ? { signal } : {}) };
377
+ const found = await this.#boxOf(name, end, signal);
378
+ if (found !== undefined)
379
+ return found;
380
+ building();
381
+ // The two creates are never signalled, only bounded: a cancel mid-call would lose the id of what Morph made, and the
382
+ // base snapshot has no TTL. A cancel is answered once the id is held, so the finally below deletes what was made.
383
+ const notCancelled = (what) => {
384
+ if (signal?.aborted)
385
+ throw new HostError("aborted", `the box build was aborted after ${what}`);
386
+ };
387
+ const base = (await this.#baseOf(name, call)) ?? (await this.#newBase(name, end));
388
+ // Set once the box snapshot is asked for: from then on it may need the base, which is kept.
389
+ let snapshotted = false;
390
+ let vm;
391
+ try {
392
+ notCancelled(`its base snapshot ${base} was made`);
393
+ await this.#snapshotReady(base, end, signal);
394
+ vm = instanceId((await this.#rest("POST", "/instance", { snapshot_id: base, metadata: { [BUILD_LABEL]: name }, ttl_seconds: BUILD_TTL_S, ttl_action: "stop" }, { timeoutMs: BUILD_CALL_MS })).id);
395
+ notCancelled(`its instance ${vm} was made`);
396
+ await this.#build(vm, name, end, signal, call, () => (snapshotted = true));
397
+ }
398
+ finally {
399
+ // Their own bound, not the caller's signal: a cancelled build still deletes its instance (its TTL backs this),
400
+ // and a build that never asked for the box snapshot deletes its base too, so a failing build leaves nothing.
401
+ if (vm !== undefined)
402
+ await this.delete(vm, { timeoutMs: BUILD_CALL_MS }).catch(() => { });
403
+ if (!snapshotted)
404
+ await this.#rest("DELETE", `/snapshot/${base}`, undefined, { timeoutMs: BUILD_CALL_MS }).catch(() => { });
405
+ }
406
+ // Another server's build of the same recipe may have finished first: every caller answers the oldest.
407
+ const box = await this.#boxOf(name, end, signal);
408
+ if (box === undefined)
409
+ throw new HostError("vendor", `the box snapshot ${name} was made, then not listed by its digest`);
410
+ return box;
411
+ }
412
+ /** The build on its running instance vm: install.sh as root over SSH, then the box snapshot by digest (asking() told first). */
413
+ async #build(vm, name, end, signal, call, asking) {
414
+ await this.#until(`the build instance ${vm}`, end, signal, async () => {
415
+ const { state, why } = machineOf(await this.#rest("GET", `/instance/${vm}`, undefined, call));
416
+ if (state === "gone")
417
+ throw new HostError("vendor", `the build instance ${vm} is gone: ${why ?? "no reason given"}`);
418
+ return state === "running" ? true : undefined;
419
+ });
420
+ const run = async (argv, what) => {
421
+ const ran = orThrow(await runToExit(this, vm, argv, { ms: Math.max(1, end - Date.now()), ...(signal ? { signal } : {}), what }));
422
+ if (ran.exitCode !== 0)
423
+ throw new HostError("vendor", `${what} exited with ${ran.exitCode}: ${`${ran.stderr} ${ran.stdout}`.trim().slice(-300)}`);
424
+ };
425
+ await run(["mkdir", "-p", "/tmp/agentrun-box"], "the build folder's mkdir");
426
+ for (const file of RECIPE_FILES)
427
+ orThrow(await uploadThroughExec(this, vm, `/tmp/agentrun-box/${file}`, await readFile(new URL(`../box/${file}`, import.meta.url)), BUILD_CALL_MS, signal));
428
+ await run(["sh", "-c", "sh /tmp/agentrun-box/install.sh && rm -rf /tmp/agentrun-box"], "box/install.sh");
429
+ asking();
430
+ const made = await this.#rest("POST", `/instance/${vm}/snapshot`, { digest: name, metadata: { "agentrun-box": name } }, { ...call, timeoutMs: Math.max(1, end - Date.now()) });
431
+ await this.#snapshotReady(made.id, end, signal);
432
+ }
433
+ }
434
+ /**
435
+ * A MorphProvider from its options alone; it reads no environment. The key is options.apiKey, nowhere else (serve passes
436
+ * its MORPH_API_KEY, the conformance module what it reads), and ssh2 is the host's package unless given. Throws in words
437
+ * when an option is missing or wrong, never echoing a key.
438
+ */
439
+ export async function create(options) {
440
+ const { ssh2: given, ...rest } = options ?? {};
441
+ // ssh2 is CommonJS: its Client is a named export of the module, and of its default.
442
+ const loaded = given ?? (await import(SSH2_PACKAGE));
443
+ const ssh2 = typeof loaded.Client === "function" ? loaded : loaded.default;
444
+ return new MorphProvider({ ...rest, ssh2: ssh2 });
445
+ }
446
+ /** The conformance CLI's module for Morph: its live switch, the run's cap, its snapshot and the drifted twin. */
447
+ export const conformance = () => import("./conformance/morph.js");
448
+ const fail = failFor(MORPH.id);
449
+ /**
450
+ * Computers that are Morph instances, on the shared adapter. A spec's image is a Morph snapshot id. A server starts
451
+ * every one from the snapshot prepareImage() answers: our box image, built once in the key's own account.
452
+ */
453
+ export class MorphProvider extends HostedProvider {
454
+ /**
455
+ * The provider contract's prepareImage (its descriptor declares it): the box image as a snapshot of the key's
456
+ * account, its digest agentrun-box-<recipe hash>, found or built (MorphHost.boxSnapshot), so a new recipe is a new
457
+ * snapshot. ok with the snapshot's id; onWait is told "build" once, before a build, never when the account has one.
458
+ */
459
+ async prepareImage(context = {}) {
460
+ const name = `agentrun-box-${boxRecipeHash()}`;
461
+ try {
462
+ return ok(await this.host.boxSnapshot(name, () => context.onWait?.("build", name), context.signal));
463
+ }
464
+ catch (error) {
465
+ return fail(codeOf(error), `the box image ${name} as a Morph snapshot: ${error instanceof Error ? error.message : String(error)}`);
466
+ }
467
+ }
468
+ constructor(options) {
469
+ const { apiKey, ssh2, fetch: fetcher = globalThis.fetch, apiUrl = DEFAULT_API_URL, sshHost = DEFAULT_SSH_HOST, sshPort = DEFAULT_SSH_PORT, timeouts = {}, ...rest } = options ?? {};
470
+ if (typeof apiKey !== "string" || apiKey === "")
471
+ throw new Error("options.apiKey, the Morph API key, is required: the provider reads no environment, so the caller passes it");
472
+ if (typeof ssh2?.Client !== "function")
473
+ throw new Error("options.ssh2 must be the ssh2 package (its Client class): the host installs it, as it does for Agent37");
474
+ if (typeof fetcher !== "function")
475
+ throw new Error("options.fetch must be a function, as the global fetch is");
476
+ let api;
477
+ try {
478
+ api = new URL(apiUrl);
479
+ }
480
+ catch {
481
+ throw new Error(`apiUrl must be an https URL such as ${DEFAULT_API_URL}, not ${JSON.stringify(apiUrl)}`);
482
+ }
483
+ if (api.protocol !== "https:" || api.search !== "" || api.hash !== "")
484
+ throw new Error(`apiUrl must be an https URL such as ${DEFAULT_API_URL}, not ${JSON.stringify(apiUrl)}`);
485
+ if (typeof sshHost !== "string" || !(DOMAIN.test(sshHost) || isIP(sshHost) !== 0))
486
+ throw new Error(`sshHost must be a host name such as ${DEFAULT_SSH_HOST}, not ${JSON.stringify(sshHost)}`);
487
+ if (!Number.isSafeInteger(sshPort) || sshPort < 1 || sshPort > 65_535)
488
+ throw new Error(`sshPort must be a TCP port, not ${JSON.stringify(sshPort)}`);
489
+ super(new MorphHost({ apiKey, ssh2, fetch: fetcher, apiUrl: api.href.replace(/\/+$/, ""), sshHost, sshPort }), { ...rest, timeouts });
490
+ }
491
+ }
492
+ /** The account a key reaches, in words, for the sweep's scope: the key's sha256 prefix, never the key. */
493
+ export function accountOf(apiKey, apiUrl = DEFAULT_API_URL) {
494
+ return `the Morph account of the key sha256:${createHash("sha256").update(apiKey, "utf8").digest("hex").slice(0, 12)} at ${apiUrl.replace(/\/+$/, "")}`;
495
+ }
@@ -139,10 +139,19 @@ export interface PhoneProviderOptions {
139
139
  phoned?: string;
140
140
  /**
141
141
  * APK files installed on each phone before phoned starts there (`pm install -r`), as the conformance run installs the
142
- * ui fixture (npm run build:ui-fixture). Default none. A connect that cannot install one fails in words.
142
+ * ui fixture (npm run build:ui-fixture): each one's absolute path on this machine and the sha256 its bytes must have.
143
+ * One not there, or whose bytes are not its pin, refuses create before a phone is rented, and connect. Default env's
144
+ * PHONE_HARNESS_APKS, else none. A connect that cannot install one fails in words.
143
145
  */
144
- apks?: string[];
146
+ apks?: readonly PinnedApk[];
147
+ /** The host's own variables its descriptor declares (hostEnv): PHONE_HARNESS_APKS alone, the server's apks. */
148
+ env?: Readonly<Record<string, string | undefined>>;
145
149
  }
150
+ /** An APK the provider installs: its file's absolute path, and the sha256 of its bytes (64 lowercase hex digits). */
151
+ export type PinnedApk = {
152
+ readonly path: string;
153
+ readonly sha256: string;
154
+ };
146
155
  /** The phone-harness provider from its options alone; throws in words when one is missing or wrong. */
147
156
  export declare function create(options: PhoneProviderOptions): Promise<PhoneHarnessProvider>;
148
157
  /** The conformance CLI's module for the phone harness. */
@@ -170,9 +179,10 @@ export declare class PhoneHarnessProvider implements ComputerProvider {
170
179
  release(ref: ComputerRef, how: ReleaseHow): Promise<Result<void>>;
171
180
  connect(ref: ComputerRef): Promise<Result<ComputerConnection>>;
172
181
  /**
173
- * The live view: the phone client's screen.watch on a connection of the watch's own (daemonWatch), PNG frames from
174
- * screencap. Upright with no rotation of ours: screencap gives the display in its current orientation, and input tap
175
- * and swipe take that same space, so each frame's width and height come from its own screencap, never from wm size.
182
+ * The live view: phoned's screen.watch on a connection of the watch's own (daemonWatch), JPEG frames at most
183
+ * PHONE_FRAME_WIDTH wide unless the caller asks a width, from the phone's screenshot. Upright with no rotation of
184
+ * ours: the screenshot gives the display in its current orientation, and input taps and swipes take that same space,
185
+ * so each frame's width and height come from its own screenshot, never from wm size.
176
186
  */
177
187
  watch(ref: ComputerRef, handlers: ScreenWatchHandlers, options?: WatchOptions): Promise<Result<ScreenWatch>>;
178
188
  /**