@parcha/agentrun-computer 0.1.0-beta.41 → 0.1.0-beta.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +2 -0
- package/README.md +254 -14
- package/box/README.md +2 -2
- package/box/build-e2b.mjs +1 -1
- package/dist/box-image.d.ts +1 -3
- package/dist/box-image.js +1 -11
- package/dist/boxd.d.ts +126 -0
- package/dist/boxd.js +418 -0
- package/dist/cloudflare.d.ts +32 -0
- package/dist/cloudflare.js +179 -0
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/computerd.json +2 -2
- package/dist/conformance/boxd.d.ts +77 -0
- package/dist/conformance/boxd.js +113 -0
- package/dist/conformance/cases/isolation.js +1 -17
- package/dist/conformance/cloudflare.d.ts +42 -0
- package/dist/conformance/cloudflare.js +54 -0
- package/dist/conformance/dial-only.d.ts +6 -0
- package/dist/conformance/dial-only.js +9 -0
- package/dist/conformance/e2b.d.ts +12 -3
- package/dist/conformance/e2b.js +21 -4
- package/dist/conformance/fly.d.ts +52 -0
- package/dist/conformance/fly.js +52 -0
- package/dist/conformance/modal.d.ts +15 -2
- package/dist/conformance/modal.js +36 -3
- package/dist/conformance/morph.d.ts +59 -0
- package/dist/conformance/morph.js +95 -0
- package/dist/conformance/phone-harness.js +2 -2
- package/dist/conformance/runner.js +3 -3
- package/dist/conformance/sweep.d.ts +1 -6
- package/dist/conformance/sweep.js +8 -18
- package/dist/descriptors/boxd.d.ts +52 -0
- package/dist/descriptors/boxd.js +29 -0
- package/dist/descriptors/cloudflare.d.ts +21 -0
- package/dist/descriptors/cloudflare.js +29 -0
- package/dist/descriptors/e2b.d.ts +4 -0
- package/dist/descriptors/e2b.js +3 -0
- package/dist/descriptors/fly.d.ts +19 -0
- package/dist/descriptors/fly.js +28 -0
- package/dist/descriptors/index.d.ts +113 -1
- package/dist/descriptors/index.js +7 -2
- package/dist/descriptors/modal.d.ts +3 -0
- package/dist/descriptors/modal.js +7 -2
- package/dist/descriptors/morph.d.ts +15 -0
- package/dist/descriptors/morph.js +21 -0
- package/dist/descriptors/phone-harness.d.ts +1 -0
- package/dist/descriptors/phone-harness.js +2 -0
- package/dist/e2b.d.ts +7 -1
- package/dist/e2b.js +87 -44
- package/dist/fly.d.ts +43 -0
- package/dist/fly.js +245 -0
- package/dist/host.d.ts +8 -28
- package/dist/hosted/process.d.ts +19 -0
- package/dist/hosted/process.js +28 -0
- package/dist/hosted/provider.d.ts +11 -22
- package/dist/hosted/provider.js +30 -201
- package/dist/hosted/scripts.d.ts +2 -8
- package/dist/hosted/scripts.js +2 -22
- package/dist/hosted/ssh-exec.d.ts +2 -1
- package/dist/hosted/ssh-exec.js +58 -2
- package/dist/hosted/values.d.ts +5 -0
- package/dist/hosted/values.js +9 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/modal.d.ts +6 -0
- package/dist/modal.js +20 -10
- package/dist/morph.d.ts +65 -0
- package/dist/morph.js +495 -0
- package/dist/phone-harness.d.ts +15 -5
- package/dist/phone-harness.js +50 -15
- package/dist/screen-watch.js +2 -2
- package/package.json +20 -2
package/dist/boxd.js
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
// The boxd host: boxd machines (KVM microVMs, Ubuntu 24.04) as a MachineHost, through the host's own @boxd-sh/sdk, of
|
|
2
|
+
// which this file names only the slice it calls (every fact from 0.3.1's dist/*.d.ts) and imports nothing at load.
|
|
3
|
+
// boxd's agent runs every command in a machine, so computerd is a child. The daemon, the bridge, the probe, idempotent
|
|
4
|
+
// create, extend and delete-then-wait-gone are the shared adapter's (./hosted/provider.ts). A desktop starts from a
|
|
5
|
+
// snapshot of boxd's own image with a stock app added, which prepareImage() builds once in the key's org.
|
|
6
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
7
|
+
import { BOXD, BOXD_DEFAULT_IMAGE } from "./descriptors/boxd.js";
|
|
8
|
+
import { DEADLINE_LABEL, show } from "./drift.js";
|
|
9
|
+
import { HostError } from "./host.js";
|
|
10
|
+
import { CALL_SLACK_MS, codeOfError, orThrow, race, runChecked, until } from "./hosted/process.js";
|
|
11
|
+
import { HostedProvider, mayHaveMade } from "./hosted/provider.js";
|
|
12
|
+
import { shellLine } from "./hosted/scripts.js";
|
|
13
|
+
import { dateOf } from "./hosted/values.js";
|
|
14
|
+
import { failFor, ok } from "./result.js";
|
|
15
|
+
/** Not a literal, so no type checker or bundler resolves the SDK from this package. */
|
|
16
|
+
const BOXD_PACKAGE = "@boxd-sh/sdk";
|
|
17
|
+
/** A BoxdProvider from its options alone; throws in words when the key is missing, never echoing one. */
|
|
18
|
+
export async function create(options) {
|
|
19
|
+
const { apiKey, Boxd: given, ...rest } = options ?? {};
|
|
20
|
+
if (typeof apiKey !== "string" || apiKey === "")
|
|
21
|
+
throw new Error("options.apiKey, the boxd API key, is required: the provider reads no environment, so the caller passes it");
|
|
22
|
+
const Boxd = given ?? (await import(BOXD_PACKAGE)).Boxd;
|
|
23
|
+
return new BoxdProvider({ ...rest, apiKey, Boxd });
|
|
24
|
+
}
|
|
25
|
+
/** The conformance CLI's module for boxd. */
|
|
26
|
+
export const conformance = () => import("./conformance/boxd.js");
|
|
27
|
+
const DAY_MS = 24 * 60 * 60_000;
|
|
28
|
+
const DEFAULT_BASE_URL = "https://boxd.sh:9443";
|
|
29
|
+
/** The adapter's default requestMs and createMs: the SDK bounds a call by its client's timeout, so each client takes one. */
|
|
30
|
+
const REQUEST_MS = 30_000;
|
|
31
|
+
const CREATE_MS = 120_000;
|
|
32
|
+
const SIZES = { 1: "4G", 2: "8G", 4: "16G", 8: "32G" };
|
|
33
|
+
/** "default", boxd's own image, or a snapshot's name. */
|
|
34
|
+
const IMAGE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
35
|
+
/** 1 to 63 of a-z0-9._/- (Machines.updateLabels); "boxd/" is boxd's own. */
|
|
36
|
+
const LABEL_KEY = /^(?!boxd\/)[a-z0-9._/-]{1,63}$/;
|
|
37
|
+
/** boxd's in-machine agent, which carries the SDK's exec and file calls. */
|
|
38
|
+
const AGENT_PORT = 57073;
|
|
39
|
+
/** The image's own user, which boxd's exec runs as (with passwordless sudo): init refuses to start beside its processes. */
|
|
40
|
+
const IMAGE_UID = 1000;
|
|
41
|
+
/** Standby (suspended) wakes on the next call, and a migration keeps the machine: both run. */
|
|
42
|
+
const STATES = {
|
|
43
|
+
...{ pending: "starting", starting: "starting", running: "running", suspended: "running", migrating: "running" },
|
|
44
|
+
...{ hibernated: "stopped", stopped: "stopped", failed: "gone", destroyed: "gone" },
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* What a desktop needs that boxd's own image lacks: a stock app, Xfce's text editor (mousepad, from Ubuntu's universe),
|
|
48
|
+
* its desktop file checked, run as root on a build machine of boxd's own image. Xvfb is the image's already. The
|
|
49
|
+
* snapshot's name carries this line's hash, so a new line is a new snapshot.
|
|
50
|
+
*/
|
|
51
|
+
const DESKTOP_RECIPE = [
|
|
52
|
+
"set -e",
|
|
53
|
+
"export DEBIAN_FRONTEND=noninteractive",
|
|
54
|
+
"apt-get update -qq",
|
|
55
|
+
"apt-get install -y -qq --no-install-recommends mousepad >/dev/null",
|
|
56
|
+
'test -f /usr/share/applications/org.xfce.mousepad.desktop || { echo "mousepad brought no org.xfce.mousepad.desktop" >&2; exit 1; }',
|
|
57
|
+
"rm -rf /var/lib/apt/lists/*",
|
|
58
|
+
].join("\n");
|
|
59
|
+
/** The desktop snapshot this package's recipe names: agentrun-desktop-<12 hex of the recipe's sha256>. */
|
|
60
|
+
export const boxdDesktopSnapshot = () => `agentrun-desktop-${createHash("sha256").update(DESKTOP_RECIPE).digest("hex").slice(0, 12)}`;
|
|
61
|
+
/** A build, all of it (boot, the recipe, the capture); its machine's delete timer, so a build left by a crash ends. */
|
|
62
|
+
const BUILD_MS = 30 * 60_000;
|
|
63
|
+
const BUILD_TTL_S = 2 * 60 * 60;
|
|
64
|
+
/** The pause between two reads of something boxd is making or deleting. */
|
|
65
|
+
const BUILD_POLL_MS = 2_000;
|
|
66
|
+
/** The most a build machine's cleanup waits for it to read gone. */
|
|
67
|
+
const GONE_MS = 120_000;
|
|
68
|
+
/** The error with words added to its message (one that cannot be written stays as it was): the error is what the caller gets. */
|
|
69
|
+
function withWords(error, words) {
|
|
70
|
+
if (error instanceof Error) {
|
|
71
|
+
try {
|
|
72
|
+
error.message = `${error.message}${words}`;
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
// A read-only message: the error goes on as it is.
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return error;
|
|
79
|
+
}
|
|
80
|
+
/** A machine as the adapter reads one: its labels, its state, and when boxd made it. */
|
|
81
|
+
function machineOf(machine) {
|
|
82
|
+
const state = STATES[machine.status];
|
|
83
|
+
const created = dateOf(machine.createdAt);
|
|
84
|
+
return {
|
|
85
|
+
id: machine.id,
|
|
86
|
+
labels: { ...machine.labels },
|
|
87
|
+
state: state ?? "gone",
|
|
88
|
+
...(created ? { createdAt: created } : {}),
|
|
89
|
+
...(state === "gone" || state === undefined ? { why: `boxd reads its status as ${show(machine.status)}` } : {}),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/** boxd's machines as a MachineHost (../host.ts). */
|
|
93
|
+
class BoxdHost {
|
|
94
|
+
machines;
|
|
95
|
+
creator;
|
|
96
|
+
snapshots;
|
|
97
|
+
options;
|
|
98
|
+
descriptor = BOXD;
|
|
99
|
+
facts = {
|
|
100
|
+
daemon: "child",
|
|
101
|
+
isolation: "microvm",
|
|
102
|
+
// boxd ends a machine only at the delete timer create sets at req.backstopAt, and sets no cap.
|
|
103
|
+
lifetime: "janitor",
|
|
104
|
+
maxLifetimeMs: 30 * DAY_MS,
|
|
105
|
+
arch: "amd64",
|
|
106
|
+
vendorAgentPorts: [AGENT_PORT],
|
|
107
|
+
};
|
|
108
|
+
constructor(machines,
|
|
109
|
+
/** For create alone: bounded by createMs, and never sent twice. */
|
|
110
|
+
creator, snapshots, options) {
|
|
111
|
+
this.machines = machines;
|
|
112
|
+
this.creator = creator;
|
|
113
|
+
this.snapshots = snapshots;
|
|
114
|
+
this.options = options;
|
|
115
|
+
}
|
|
116
|
+
errorCode(error) {
|
|
117
|
+
return codeOf(error);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* An isolated machine (on none of the org's networks) with no standby, which would freeze a quiet computer. Once it is
|
|
121
|
+
* ready: nothing out (the allowlist ["none"]) and no hibernation, since boxd's idle timers watch traffic and a computer
|
|
122
|
+
* may have none. A step after the machine exists that throws an error the adapter reads as a create that may have made
|
|
123
|
+
* one (mayHaveMade: vendor, timeout) is the adapter's to clean up: it sweeps the request's name, finds this machine and
|
|
124
|
+
* deletes it (a timeout's once this call settles). Deleted here first, the sweep would find none and keep listing, and
|
|
125
|
+
* delete a second create's machine of the same request instead. A refusal (limit, denied, ...) the adapter reads as a
|
|
126
|
+
* create that made nothing, so the step deletes the machine by its id (best effort) and throws its own error, the
|
|
127
|
+
* delete's outcome added in words. boxd's delete timer, written in the same call that makes the machine, ends it at
|
|
128
|
+
* req.backstopAt, so it ends even when the server that made it is gone.
|
|
129
|
+
*/
|
|
130
|
+
async create(req, ctx) {
|
|
131
|
+
if (req.egress)
|
|
132
|
+
throw new HostError("invalid", "a boxd computer reaches nothing outside, and this request asks it to");
|
|
133
|
+
const { org, size } = this.options;
|
|
134
|
+
const made = await this.creator.create({
|
|
135
|
+
name: req.name,
|
|
136
|
+
...(org === undefined ? {} : { org }),
|
|
137
|
+
labels: req.labels,
|
|
138
|
+
isolated: true,
|
|
139
|
+
config: { autoSuspendTimeout: 0, ...size },
|
|
140
|
+
...(req.image === BOXD_DEFAULT_IMAGE ? {} : { fromSnapshot: req.image }),
|
|
141
|
+
deleteAfter: Math.ceil((Date.parse(req.backstopAt) - Date.now()) / 1000),
|
|
142
|
+
});
|
|
143
|
+
try {
|
|
144
|
+
await this.machines.waitUntilReady(made.id, { timeout: ctx.timeoutMs });
|
|
145
|
+
await this.machines.setEgressAllow(made.id, ["none"]);
|
|
146
|
+
await this.machines.setAutoHibernateTimeout(made.id, 0);
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
if (mayHaveMade(codeOfError(this, error)))
|
|
150
|
+
throw error;
|
|
151
|
+
throw await this.#unmade(made.id, error);
|
|
152
|
+
}
|
|
153
|
+
return { id: made.id };
|
|
154
|
+
}
|
|
155
|
+
/** The machine a failed create made, deleted by its id; the step's own error comes back, the delete's outcome in its message. */
|
|
156
|
+
async #unmade(id, error) {
|
|
157
|
+
let outcome;
|
|
158
|
+
try {
|
|
159
|
+
await this.delete(id);
|
|
160
|
+
outcome = `the machine ${id} it made was deleted`;
|
|
161
|
+
}
|
|
162
|
+
catch (failed) {
|
|
163
|
+
outcome = `the machine ${id} it made could not be deleted (${failed instanceof Error ? failed.message : String(failed)})`;
|
|
164
|
+
}
|
|
165
|
+
return withWords(error, `; ${outcome}`);
|
|
166
|
+
}
|
|
167
|
+
/** machines.get takes an id alone, so a machine of another org is none of this provider's. Not found is none (adapter). */
|
|
168
|
+
async get(id) {
|
|
169
|
+
const { org } = this.options;
|
|
170
|
+
const machine = await this.machines.get(id);
|
|
171
|
+
return org === undefined || machine.org?.name === org || machine.org?.id === org ? machineOf(machine) : undefined;
|
|
172
|
+
}
|
|
173
|
+
async list(labels) {
|
|
174
|
+
const { org } = this.options;
|
|
175
|
+
const listed = await this.machines.list({ ...(org === undefined ? {} : { org }), labels });
|
|
176
|
+
return [...listed].map(machineOf);
|
|
177
|
+
}
|
|
178
|
+
/** Not found is ok. */
|
|
179
|
+
async delete(id) {
|
|
180
|
+
try {
|
|
181
|
+
await this.machines.delete(id);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
if (codeOf(error) !== "not_found")
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** One streamExec, its line the argv quoted. boxd runs it as the image's user; the adapter's scripts sudo to root. */
|
|
189
|
+
async exec(id, argv) {
|
|
190
|
+
const stream = this.machines.streamExec(id, { command: shellLine(argv) });
|
|
191
|
+
return {
|
|
192
|
+
stdout: stream,
|
|
193
|
+
stderr: stream.stderr,
|
|
194
|
+
write: async (bytes) => stream.write(bytes),
|
|
195
|
+
end: async () => stream.end(),
|
|
196
|
+
wait: () => stream.wait().catch(() => -1),
|
|
197
|
+
// The server kills the process group (TERM, then KILL); close is safe twice (exec.d.ts).
|
|
198
|
+
kill: async () => stream.close(),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
async upload(id, path, bytes) {
|
|
202
|
+
await this.machines.files.upload(id, path, bytes);
|
|
203
|
+
}
|
|
204
|
+
/** The janitor's deadline label; the adapter holds it to the most the machine may live and reads it back. */
|
|
205
|
+
async extend(id, endsAt) {
|
|
206
|
+
await this.machines.updateLabels(id, { set: { [DEADLINE_LABEL]: endsAt.toISOString() } });
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* The desktop snapshot of this name in the org: found ready, or one being made waited for; else built once
|
|
210
|
+
* (`building` told first). A build makes an isolated machine of boxd's own image with no labels (a restore carries a
|
|
211
|
+
* snapshot's labels over to every machine made from it) and boxd's delete timer at BUILD_TTL_S, runs DESKTOP_RECIPE
|
|
212
|
+
* as root through the image user's passwordless sudo, captures the machine under the name, and waits until the
|
|
213
|
+
* capture is ready. A cancelled caller makes no machine, and stops waiting for one to start. The machine is deleted
|
|
214
|
+
* after, pass, fail or cancel, and waited gone, so a sweep after the build finds none of it; one that can't be is said
|
|
215
|
+
* (after the build's own error, when it failed). The snapshot stays: it is the org's image for every desktop. One that
|
|
216
|
+
* failed, or that boxd archived, is refused in words: delete it, then call again. Two first builds that race (two
|
|
217
|
+
* servers, one org) each pay for a build machine, and both captures land under the one name (boxd keeps the latest).
|
|
218
|
+
*/
|
|
219
|
+
async desktopSnapshot(name, building, signal) {
|
|
220
|
+
const end = Date.now() + BUILD_MS;
|
|
221
|
+
const found = await this.#snapshot(name, end, signal);
|
|
222
|
+
if (found !== null)
|
|
223
|
+
return found;
|
|
224
|
+
if (signal?.aborted)
|
|
225
|
+
throw new HostError("aborted", `the build of the boxd snapshot ${name} was aborted before its machine was made`);
|
|
226
|
+
building();
|
|
227
|
+
// Named before the create, so a create whose reply is lost leaves a machine the cleanup still finds.
|
|
228
|
+
const machine = `agentrun-desktop-build-${randomBytes(4).toString("hex")}`;
|
|
229
|
+
const made = new Set();
|
|
230
|
+
let built;
|
|
231
|
+
try {
|
|
232
|
+
built = { name: await this.#build(machine, made, name, end, signal) };
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
built = { error };
|
|
236
|
+
}
|
|
237
|
+
const left = await this.#gone(machine, made);
|
|
238
|
+
if ("error" in built)
|
|
239
|
+
throw left === undefined ? built.error : withWords(built.error, `; ${left}`);
|
|
240
|
+
if (left !== undefined)
|
|
241
|
+
throw new HostError("vendor", `the boxd snapshot ${name} is ready, but ${left}: call again to start from the snapshot`);
|
|
242
|
+
return built.name;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* The build itself, on a machine of this name (its id put in `ids` as create answers it): made, started (a cancel stops
|
|
246
|
+
* the wait), the recipe, the capture read ready.
|
|
247
|
+
*/
|
|
248
|
+
async #build(machine, ids, name, end, signal) {
|
|
249
|
+
const { org } = this.options;
|
|
250
|
+
const made = await this.creator.create({
|
|
251
|
+
name: machine,
|
|
252
|
+
...(org === undefined ? {} : { org }),
|
|
253
|
+
isolated: true,
|
|
254
|
+
config: { autoSuspendTimeout: 0 },
|
|
255
|
+
deleteAfter: BUILD_TTL_S,
|
|
256
|
+
});
|
|
257
|
+
ids.add(made.id);
|
|
258
|
+
const ms = Math.max(1, end - Date.now());
|
|
259
|
+
orThrow(await race(this, this.machines.waitUntilReady(made.id, { timeout: ms }), `the build machine ${made.id}'s start`, ms + CALL_SLACK_MS, signal));
|
|
260
|
+
const what = `the desktop recipe (mousepad) on the build machine ${made.id}`;
|
|
261
|
+
await runChecked(this, made.id, ["sudo", "-n", "sh", "-c", DESKTOP_RECIPE], { ms: Math.max(1, end - Date.now()), signal, what });
|
|
262
|
+
await this.snapshots.create(made.id, name);
|
|
263
|
+
const ready = await this.#snapshot(name, end, signal);
|
|
264
|
+
if (ready === null)
|
|
265
|
+
throw new HostError("vendor", `boxd took the snapshot ${name} of ${made.id}, then read none by that name`);
|
|
266
|
+
return ready;
|
|
267
|
+
}
|
|
268
|
+
/** The snapshot's name once boxd reads it ready (a pending one waited for), null when boxd has none by it; failed or archived throws in words. */
|
|
269
|
+
#snapshot(name, end, signal) {
|
|
270
|
+
const { org } = this.options;
|
|
271
|
+
return until(`the boxd snapshot ${name}`, { end, pollMs: BUILD_POLL_MS, signal }, async () => {
|
|
272
|
+
let read;
|
|
273
|
+
try {
|
|
274
|
+
read = await this.snapshots.get(name, org === undefined ? {} : { org });
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
if (codeOf(error) === "not_found")
|
|
278
|
+
return null;
|
|
279
|
+
throw error;
|
|
280
|
+
}
|
|
281
|
+
if (read.archived)
|
|
282
|
+
throw new HostError("refused", `the boxd snapshot ${name} is archived (storage ${show(read.storage)}), and boxd makes no machine from it until its operator unarchives it: delete it, then call again to build it anew`);
|
|
283
|
+
if (read.status === "ready")
|
|
284
|
+
return name;
|
|
285
|
+
if (read.status === "pending")
|
|
286
|
+
return undefined;
|
|
287
|
+
throw new HostError("vendor", `the boxd snapshot ${name} is ${show(read.status)}, not ready: delete it, then call again to build it anew`);
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* The build's machines, each deleted once and read gone through get, GONE_MS at most: the ids create answered (`made`),
|
|
292
|
+
* which a lagging list can't hide, and every machine of the build's name in the org's list (it has no label to list it
|
|
293
|
+
* by), which finds one whose create reply was lost. Not the caller's to cancel: a cancelled build is cleaned up too.
|
|
294
|
+
* Undefined once none is left, else what is left in words (boxd's delete timer, set at create, ends it).
|
|
295
|
+
*/
|
|
296
|
+
async #gone(machine, made) {
|
|
297
|
+
const { org } = this.options;
|
|
298
|
+
const asked = new Set();
|
|
299
|
+
try {
|
|
300
|
+
await until(`the build machine ${machine}'s delete`, { end: Date.now() + GONE_MS, pollMs: BUILD_POLL_MS }, async () => {
|
|
301
|
+
const listed = await this.machines.list({ ...(org === undefined ? {} : { org }), labels: {} });
|
|
302
|
+
let left = 0;
|
|
303
|
+
for (const id of new Set([...made, ...[...listed].filter((one) => one.name === machine).map((one) => one.id)])) {
|
|
304
|
+
if (!asked.has(id)) {
|
|
305
|
+
asked.add(id);
|
|
306
|
+
await this.delete(id);
|
|
307
|
+
}
|
|
308
|
+
if (!(await this.#readGone(id)))
|
|
309
|
+
left += 1;
|
|
310
|
+
}
|
|
311
|
+
return left === 0 ? true : undefined;
|
|
312
|
+
});
|
|
313
|
+
return undefined;
|
|
314
|
+
}
|
|
315
|
+
catch (error) {
|
|
316
|
+
return `its build machine ${machine} could not be deleted (${error instanceof Error ? error.message : String(error)}), and boxd's delete timer ends it within ${BUILD_TTL_S / 3600} h`;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
/** Whether get reads the machine gone: not found, or in a state that is gone. */
|
|
320
|
+
async #readGone(id) {
|
|
321
|
+
try {
|
|
322
|
+
return STATES[(await this.machines.get(id)).status] === "gone";
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
if (codeOf(error) === "not_found")
|
|
326
|
+
return true;
|
|
327
|
+
throw error;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* An image is "default" or a snapshot's name, and a desktop's is a snapshot; the size is the provider's (vcpu,
|
|
332
|
+
* memory), never the spec's; a label name is one boxd takes.
|
|
333
|
+
*/
|
|
334
|
+
check(spec) {
|
|
335
|
+
const refusals = ["cpus", "memoryMb"]
|
|
336
|
+
.filter((field) => spec[field] !== undefined)
|
|
337
|
+
.map((field) => ({ field, message: `a boxd computer's size is the provider's vcpu and memory options, not the spec's ${field}` }));
|
|
338
|
+
const { image, labels } = spec;
|
|
339
|
+
if (typeof image === "string" && image !== "") {
|
|
340
|
+
if (!IMAGE.test(image))
|
|
341
|
+
refusals.push({ field: "image", message: `an image is "${BOXD_DEFAULT_IMAGE}" (boxd's own Ubuntu 24.04), or the name of a boxd snapshot` });
|
|
342
|
+
else if (image === BOXD_DEFAULT_IMAGE && this.options.kind === "desktop") {
|
|
343
|
+
refusals.push({ field: "image", message: `a boxd desktop starts from a snapshot with a desktop app, and boxd's own image lists none of the stock ones (Xfce's text editor and terminal, xterm): name ${boxdDesktopSnapshot()}, which prepareImage() builds, or a snapshot of your own` });
|
|
344
|
+
}
|
|
345
|
+
else if (image !== BOXD_DEFAULT_IMAGE && this.options.size)
|
|
346
|
+
refusals.push({ field: "image", message: `a machine restored from a snapshot has the snapshot's size, and this provider names one: it takes only "${BOXD_DEFAULT_IMAGE}"` });
|
|
347
|
+
}
|
|
348
|
+
const keys = labels !== null && typeof labels === "object" ? Object.keys(labels).filter((key) => !LABEL_KEY.test(key)) : [];
|
|
349
|
+
if (keys.length > 0)
|
|
350
|
+
refusals.push({ field: "labels", message: `boxd takes label names of 1 to 63 of a-z, 0-9 and ._/-, not starting boxd/: ${keys.map((key) => show(key)).join(", ")}` });
|
|
351
|
+
return refusals;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
/** The SDK names its errors (errors.d.ts); an APIStatusError carries its gRPC code (3 invalid argument, 4 deadline
|
|
355
|
+
* exceeded, 8 resource exhausted, 9 failed precondition, 14 unavailable). */
|
|
356
|
+
function codeOf(error) {
|
|
357
|
+
const { name, grpcCode } = (error ?? {});
|
|
358
|
+
if (name === "AbortError")
|
|
359
|
+
return "aborted";
|
|
360
|
+
if (name === "NotFoundError" || name === "MachineFileNotFoundError")
|
|
361
|
+
return "not_found";
|
|
362
|
+
if (name === "AuthenticationError" || name === "PermissionDeniedError" || name === "RegionNotEnabledError")
|
|
363
|
+
return "denied";
|
|
364
|
+
if (name === "RateLimitError" || grpcCode === 8)
|
|
365
|
+
return "limit";
|
|
366
|
+
// boxd keeps a name to one machine: a create of a name another create took.
|
|
367
|
+
if (name === "ConflictError")
|
|
368
|
+
return "exists";
|
|
369
|
+
if (name === "APIConnectionError" || grpcCode === 4 || grpcCode === 14)
|
|
370
|
+
return "timeout";
|
|
371
|
+
if (grpcCode === 3)
|
|
372
|
+
return "invalid";
|
|
373
|
+
if (grpcCode === 9)
|
|
374
|
+
return "refused";
|
|
375
|
+
return "vendor";
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Computers that are boxd machines, on the shared adapter. A spec's image is "default" or a boxd snapshot's name. A
|
|
379
|
+
* server starts a sandbox from boxd's own image, and a desktop from the snapshot prepareImage() answers.
|
|
380
|
+
*/
|
|
381
|
+
export class BoxdProvider extends HostedProvider {
|
|
382
|
+
/**
|
|
383
|
+
* The provider contract's prepareImage (its descriptor declares it). A sandbox: boxd's own image, with no call. A
|
|
384
|
+
* desktop: the desktop snapshot (boxdDesktopSnapshot) in the key's org, found or built once (BoxdHost.desktopSnapshot),
|
|
385
|
+
* so a new recipe is a new snapshot; onWait is told "build" once, before a build, never when the org has it.
|
|
386
|
+
*/
|
|
387
|
+
async prepareImage(context = {}) {
|
|
388
|
+
if (this.capabilities().kind !== "desktop")
|
|
389
|
+
return ok(BOXD_DEFAULT_IMAGE);
|
|
390
|
+
const name = boxdDesktopSnapshot();
|
|
391
|
+
const host = this.host;
|
|
392
|
+
try {
|
|
393
|
+
return ok(await host.desktopSnapshot(name, () => context.onWait?.("build", name), context.signal));
|
|
394
|
+
}
|
|
395
|
+
catch (error) {
|
|
396
|
+
return failFor(this.id)(codeOfError(host, error), `boxd's desktop snapshot ${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
constructor(options) {
|
|
400
|
+
const { apiKey, Boxd, org, region = "", baseUrl = DEFAULT_BASE_URL, vcpu, memory, maxLifetimeMs = DAY_MS, ...rest } = options;
|
|
401
|
+
if (typeof apiKey !== "string" || apiKey === "")
|
|
402
|
+
throw new Error("a boxd API key is required");
|
|
403
|
+
if (typeof Boxd !== "function")
|
|
404
|
+
throw new Error("options.Boxd must be the @boxd-sh/sdk package's Boxd class");
|
|
405
|
+
if ((vcpu !== undefined || memory !== undefined) && SIZES[vcpu] !== memory)
|
|
406
|
+
throw new Error(`vcpu ${String(vcpu)} with memory ${String(memory)} is not one of boxd's sizes: 1 and 4G, 2 and 8G, 4 and 16G or 8 and 32G`);
|
|
407
|
+
if (Number(rest.daemonUser?.split(":")[0]) === IMAGE_UID)
|
|
408
|
+
throw new Error(`the daemon user ${rest.daemonUser} is the uid of the machine's own user, whose processes init refuses to run beside; choose another, such as 2510:2510`);
|
|
409
|
+
const kind = rest.kind === "desktop" ? "desktop" : "linux";
|
|
410
|
+
if (kind === "desktop" && vcpu !== undefined)
|
|
411
|
+
throw new Error("a boxd desktop starts from a snapshot, which keeps the size it was captured at: name no vcpu or memory for kind desktop");
|
|
412
|
+
const client = { apiKey, baseURL: baseUrl, region };
|
|
413
|
+
const { machines, snapshots } = new Boxd({ ...client, timeout: rest.timeouts?.requestMs ?? REQUEST_MS });
|
|
414
|
+
const creator = new Boxd({ ...client, timeout: rest.timeouts?.createMs ?? CREATE_MS, maxRetries: 0 }).machines;
|
|
415
|
+
const size = vcpu === undefined ? undefined : { vcpu, memory: memory };
|
|
416
|
+
super(new BoxdHost(machines, creator, snapshots, { org, size, kind }), { ...rest, maxLifetimeMs });
|
|
417
|
+
}
|
|
418
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { HostedProvider, type HostedOptions, type HostedTimeouts } from "./hosted/provider.js";
|
|
2
|
+
import type { CallContext } from "./provider.js";
|
|
3
|
+
import { type Result } from "./result.js";
|
|
4
|
+
export interface CloudflareProviderOptions extends Omit<HostedOptions, "kind" | "desktop" | "maxLifetimeMs"> {
|
|
5
|
+
/** The relay Worker's https address, as `wrangler deploy` printed it. */
|
|
6
|
+
relayUrl: string;
|
|
7
|
+
/** The relay's RELAY_TOKEN (`wrangler secret put RELAY_TOKEN`). The caller passes it; this provider reads no environment. */
|
|
8
|
+
relayToken: string;
|
|
9
|
+
/** The fetch every call goes through; default the global one. */
|
|
10
|
+
fetch?: typeof fetch;
|
|
11
|
+
/** The longest lifetime check takes, in ms: at most 24 h, the janitor's cap, which is the default. */
|
|
12
|
+
maxLifetimeMs?: number;
|
|
13
|
+
timeouts?: Partial<HostedTimeouts>;
|
|
14
|
+
}
|
|
15
|
+
/** A CloudflareProvider from its options alone; it reads no environment (serve passes its CLOUDFLARE_RELAY_* keys). */
|
|
16
|
+
export declare function create(options: CloudflareProviderOptions): CloudflareProvider;
|
|
17
|
+
/** The conformance CLI's module for Cloudflare: its settings, and its dialKit that refuses off the public server. */
|
|
18
|
+
export declare const conformance: () => Promise<typeof import("./conformance/cloudflare.js")>;
|
|
19
|
+
/**
|
|
20
|
+
* Computers that are Cloudflare Containers, through the operator's relay, each dialing the server that made it: a server
|
|
21
|
+
* with no public https address (AGENTRUN_PUBLIC_URL) refuses a create in words before the relay is called. Kind linux.
|
|
22
|
+
*/
|
|
23
|
+
export declare class CloudflareProvider extends HostedProvider {
|
|
24
|
+
#private;
|
|
25
|
+
constructor(options: CloudflareProviderOptions);
|
|
26
|
+
/** The provider contract's prepareImage (its descriptor declares it): the box image the relay was deployed FROM. */
|
|
27
|
+
prepareImage({ signal }?: CallContext): Promise<Result<string>>;
|
|
28
|
+
/** Settings' test: the relay's health and version, then one list by the adapter's label, which makes nothing. */
|
|
29
|
+
testConnection(context?: CallContext): Promise<Result<{
|
|
30
|
+
detail: string;
|
|
31
|
+
}>>;
|
|
32
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// The Cloudflare host: a Linux sandbox in a Cloudflare Container, in the operator's account. Only a Durable Object starts
|
|
2
|
+
// a container, so the operator deploys our relay Worker once (relays/cloudflare) and this host calls its routes with the
|
|
3
|
+
// relay's token. A container boots the box image the relay was built FROM with MachineRequest.boot.env and runs
|
|
4
|
+
// agentrun-dial (facts.connect "dial"); nothing reaches into it. No extend: the janitor and init's deadline end it, and
|
|
5
|
+
// the relay's alarm keeps a quiet container up hourly and destroys it at backstopAt. Unverified until the live run: the
|
|
6
|
+
// alarm holding a quiet container past an hour, outbound wss://, and the container ending once agentrun-dial exits.
|
|
7
|
+
import { CLOUDFLARE, CLOUDFLARE_RELAY_VERSION } from "./descriptors/cloudflare.js";
|
|
8
|
+
import { DEFAULT_CPUS, DEFAULT_MEMORY_MB, show } from "./drift.js";
|
|
9
|
+
import { HostError } from "./host.js";
|
|
10
|
+
import { orThrow } from "./hosted/process.js";
|
|
11
|
+
import { HostedProvider } from "./hosted/provider.js";
|
|
12
|
+
import { jsonOf, rest } from "./hosted/rest.js";
|
|
13
|
+
import { dateOf } from "./hosted/values.js";
|
|
14
|
+
import { fail, ok } from "./result.js";
|
|
15
|
+
import { connectionError } from "./test-connection.js";
|
|
16
|
+
const NAME = /^computer-[0-9a-f]{12}$/;
|
|
17
|
+
/** Cloudflare never ends a container on a timer we set (lifetime page): the janitor's cap is ours, a day, as Fly's. */
|
|
18
|
+
const MAX_LIFETIME_MS = 24 * 60 * 60_000;
|
|
19
|
+
/** The named instance types start() takes, smallest first (developers.cloudflare.com/containers/platform-details/limits/). */
|
|
20
|
+
const INSTANCES = [
|
|
21
|
+
{ name: "standard-1", cpus: 0.5, memoryMb: 4096 },
|
|
22
|
+
{ name: "standard-2", cpus: 1, memoryMb: 6144 },
|
|
23
|
+
{ name: "standard-3", cpus: 2, memoryMb: 8192 },
|
|
24
|
+
{ name: "standard-4", cpus: 4, memoryMb: 12288 },
|
|
25
|
+
];
|
|
26
|
+
const LARGEST = INSTANCES[INSTANCES.length - 1];
|
|
27
|
+
/** A create waits for the image's first pull in Cloudflare's registry, then the daemon's fetch and the dial. */
|
|
28
|
+
const CLOUDFLARE_TIMEOUTS = { createMs: 600_000 };
|
|
29
|
+
/** The smallest instance that holds the size: the adapter's default size when the spec gives none. */
|
|
30
|
+
const instanceOf = (cpus = DEFAULT_CPUS, memoryMb = DEFAULT_MEMORY_MB) => INSTANCES.find((one) => one.cpus >= cpus && one.memoryMb >= memoryMb);
|
|
31
|
+
function machineOf(row) {
|
|
32
|
+
const known = row.state === "starting" || row.state === "running" || row.state === "gone";
|
|
33
|
+
const created = dateOf(row.createdAt);
|
|
34
|
+
const why = known ? row.why : `the relay reads the computer's state ${show(row.state)}, which this provider does not know`;
|
|
35
|
+
return {
|
|
36
|
+
id: row.name,
|
|
37
|
+
labels: { ...(row.labels ?? {}) },
|
|
38
|
+
...(typeof row.image === "string" ? { image: row.image } : {}),
|
|
39
|
+
state: known ? row.state : "gone",
|
|
40
|
+
...(created ? { createdAt: created } : {}),
|
|
41
|
+
...(why ? { why } : {}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** A computer's name held to the relay's form before it reaches a path: not_found else. */
|
|
45
|
+
function nameOf(id) {
|
|
46
|
+
if (!NAME.test(id))
|
|
47
|
+
throw new HostError("not_found", `${JSON.stringify(id)} is not a computer of the Cloudflare relay`);
|
|
48
|
+
return id;
|
|
49
|
+
}
|
|
50
|
+
/** Cloudflare's containers, through the relay, as a dial MachineHost (../host.ts): no exec, no upload, no extend. */
|
|
51
|
+
class CloudflareHost {
|
|
52
|
+
descriptor = CLOUDFLARE;
|
|
53
|
+
facts = {
|
|
54
|
+
// agentrun-dial starts init as a child of the container's main process; nothing is started through exec.
|
|
55
|
+
daemon: "child",
|
|
56
|
+
// containers/platform-details/architecture: "Each container instance runs in a Firecracker microVM with its own
|
|
57
|
+
// kernel and network".
|
|
58
|
+
isolation: "microvm",
|
|
59
|
+
lifetime: "janitor",
|
|
60
|
+
maxLifetimeMs: MAX_LIFETIME_MS,
|
|
61
|
+
// The same page: images "should be built for the linux/amd64 architecture", as the box image is.
|
|
62
|
+
arch: "amd64",
|
|
63
|
+
// No page names an agent of Cloudflare's inside the container (unverified).
|
|
64
|
+
vendorAgentPorts: [],
|
|
65
|
+
connect: "dial",
|
|
66
|
+
};
|
|
67
|
+
relayUrl;
|
|
68
|
+
#client;
|
|
69
|
+
constructor(options) {
|
|
70
|
+
this.relayUrl = options.relayUrl;
|
|
71
|
+
this.#client = rest({
|
|
72
|
+
base: options.relayUrl,
|
|
73
|
+
headers: () => ({ Authorization: `Bearer ${options.relayToken}`, Accept: "application/json" }),
|
|
74
|
+
vendor: CLOUDFLARE.id,
|
|
75
|
+
fetch: options.fetch,
|
|
76
|
+
timeoutMs: 30_000,
|
|
77
|
+
retry: { attempts: 4, baseMs: 1_000 },
|
|
78
|
+
// The relay's refusals are { error } in words.
|
|
79
|
+
explain: ({ status, bytes, what }) => {
|
|
80
|
+
const said = jsonOf(bytes)?.error;
|
|
81
|
+
return { message: `${what} answered ${status}${typeof said === "string" && said !== "" ? `: ${said}` : ""}` };
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
/** One call to the relay, bounded by ctx: its JSON answer (null for none), or a HostError in the relay's words. */
|
|
86
|
+
async #call(method, path, init, ctx) {
|
|
87
|
+
return jsonOf(orThrow(await this.#client.call(method, this.#client.url(path), { ...init, timeoutMs: ctx.timeoutMs }, ctx.signal)).bytes);
|
|
88
|
+
}
|
|
89
|
+
/** GET /v1/health: the relay's version and the box image it starts; another version is refused, with how to redeploy. */
|
|
90
|
+
async health(signal) {
|
|
91
|
+
const read = await this.#client.json("GET", this.#client.url("/v1/health"), { retry: true }, signal);
|
|
92
|
+
if (!read.ok)
|
|
93
|
+
return { ok: false, error: connectionError(read.error) };
|
|
94
|
+
const { version, image } = (read.value ?? {});
|
|
95
|
+
if (version !== CLOUDFLARE_RELAY_VERSION) {
|
|
96
|
+
return fail("refused", `the relay at ${this.relayUrl} speaks version ${show(version)}, and this server speaks ${CLOUDFLARE_RELAY_VERSION}: redeploy it from this release's packages/computer/relays/cloudflare (npx wrangler deploy)`);
|
|
97
|
+
}
|
|
98
|
+
if (typeof image !== "string" || image === "")
|
|
99
|
+
return fail("vendor", `the relay at ${this.relayUrl} names no image it starts`);
|
|
100
|
+
return ok({ image });
|
|
101
|
+
}
|
|
102
|
+
/** A size start() has an instance for: standard-4 is Cloudflare's largest. */
|
|
103
|
+
check(spec) {
|
|
104
|
+
const { cpus, memoryMb } = spec;
|
|
105
|
+
const message = `a Cloudflare container has at most ${LARGEST.cpus} vCPUs and ${LARGEST.memoryMb} MiB (${LARGEST.name}, its largest): ask for less`;
|
|
106
|
+
const positive = (value) => typeof value === "number" && value > 0;
|
|
107
|
+
return [
|
|
108
|
+
...(cpus !== undefined && !(positive(cpus) && cpus <= LARGEST.cpus) ? [{ field: "cpus", message }] : []),
|
|
109
|
+
...(memoryMb !== undefined && !(positive(memoryMb) && memoryMb <= LARGEST.memoryMb) ? [{ field: "memoryMb", message }] : []),
|
|
110
|
+
];
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* POST /v1/computers: the relay starts the container of the request's name with the boot env, the instance the size
|
|
114
|
+
* picks, and backstopAt, its alarm's end. The name is the relay's id, so a create of a name it has answers that one.
|
|
115
|
+
*/
|
|
116
|
+
async create(req, ctx) {
|
|
117
|
+
if (req.boot === undefined)
|
|
118
|
+
throw new HostError("invalid", "a Cloudflare container dials the server, and the request has no boot env for it");
|
|
119
|
+
// check() refused a size past the largest, so one instance holds it.
|
|
120
|
+
const instance = instanceOf(req.cpus, req.memoryMb) ?? LARGEST;
|
|
121
|
+
const body = { name: nameOf(req.name), image: req.image, env: req.boot.env, labels: req.labels, instance: instance.name, backstopAt: req.backstopAt };
|
|
122
|
+
// Only a 429, a refusal that made nothing, is sent again: a create that got no answer may have made a container.
|
|
123
|
+
const made = (await this.#call("POST", "/v1/computers", { json: body, named: true, retry: (status) => status === 429 }, ctx));
|
|
124
|
+
if (made?.name !== req.name)
|
|
125
|
+
throw new HostError("vendor", `POST /v1/computers answered another computer: ${show(made?.name)}`);
|
|
126
|
+
return { id: made.name };
|
|
127
|
+
}
|
|
128
|
+
/** GET /v1/computers/{name}; 404 is not_found, which the adapter reads as none. */
|
|
129
|
+
async get(id, ctx) {
|
|
130
|
+
return machineOf((await this.#call("GET", `/v1/computers/${nameOf(id)}`, { retry: true }, ctx)));
|
|
131
|
+
}
|
|
132
|
+
/** GET /v1/computers?{label}={value}: the relay's index, every row with all the labels, in one answer. */
|
|
133
|
+
async list(labels, ctx) {
|
|
134
|
+
const query = new URLSearchParams(Object.entries(labels)).toString();
|
|
135
|
+
const listed = (await this.#call("GET", `/v1/computers${query === "" ? "" : `?${query}`}`, { retry: true }, ctx));
|
|
136
|
+
if (!Array.isArray(listed?.computers))
|
|
137
|
+
throw new HostError("vendor", "GET /v1/computers answered no computers");
|
|
138
|
+
return listed.computers.filter((one) => typeof one?.name === "string").map(machineOf);
|
|
139
|
+
}
|
|
140
|
+
/** DELETE /v1/computers/{name}: the relay destroys the container and drops its row; one already gone is done too. */
|
|
141
|
+
async delete(id, ctx) {
|
|
142
|
+
await this.#call("DELETE", `/v1/computers/${nameOf(id)}`, { retry: true }, ctx);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** A CloudflareProvider from its options alone; it reads no environment (serve passes its CLOUDFLARE_RELAY_* keys). */
|
|
146
|
+
export function create(options) {
|
|
147
|
+
return new CloudflareProvider(options);
|
|
148
|
+
}
|
|
149
|
+
/** The conformance CLI's module for Cloudflare: its settings, and its dialKit that refuses off the public server. */
|
|
150
|
+
export const conformance = () => import("./conformance/cloudflare.js");
|
|
151
|
+
/**
|
|
152
|
+
* Computers that are Cloudflare Containers, through the operator's relay, each dialing the server that made it: a server
|
|
153
|
+
* with no public https address (AGENTRUN_PUBLIC_URL) refuses a create in words before the relay is called. Kind linux.
|
|
154
|
+
*/
|
|
155
|
+
export class CloudflareProvider extends HostedProvider {
|
|
156
|
+
#relay;
|
|
157
|
+
constructor(options) {
|
|
158
|
+
const { relayUrl, relayToken, fetch: fetcher = globalThis.fetch, timeouts = {}, ...rest } = options ?? {};
|
|
159
|
+
if (typeof relayToken !== "string" || relayToken === "")
|
|
160
|
+
throw new Error("options.relayToken, the relay's RELAY_TOKEN, is required: the provider reads no environment, so the caller passes it");
|
|
161
|
+
if (typeof relayUrl !== "string" || !URL.canParse(relayUrl) || new URL(relayUrl).protocol !== "https:")
|
|
162
|
+
throw new Error(`options.relayUrl is the relay Worker's https address, as wrangler deploy printed it, not ${JSON.stringify(relayUrl)}`);
|
|
163
|
+
if (typeof fetcher !== "function")
|
|
164
|
+
throw new Error("options.fetch must be a function, as the global fetch is");
|
|
165
|
+
const host = new CloudflareHost({ relayUrl, relayToken, fetch: fetcher });
|
|
166
|
+
super(host, { ...rest, kind: "linux", timeouts: { ...CLOUDFLARE_TIMEOUTS, ...timeouts } });
|
|
167
|
+
this.#relay = host;
|
|
168
|
+
}
|
|
169
|
+
/** The provider contract's prepareImage (its descriptor declares it): the box image the relay was deployed FROM. */
|
|
170
|
+
async prepareImage({ signal } = {}) {
|
|
171
|
+
const health = await this.#relay.health(signal);
|
|
172
|
+
return health.ok ? ok(health.value.image) : health;
|
|
173
|
+
}
|
|
174
|
+
/** Settings' test: the relay's health and version, then one list by the adapter's label, which makes nothing. */
|
|
175
|
+
async testConnection(context = {}) {
|
|
176
|
+
const health = await this.#relay.health(context.signal);
|
|
177
|
+
return health.ok ? super.testConnection(context) : health;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
Binary file
|
|
Binary file
|
package/dist/computerd.json
CHANGED