@parcha/agentrun-computer 0.1.0-beta.61 → 0.1.0-beta.63

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/dist/render.js ADDED
@@ -0,0 +1,719 @@
1
+ // The Render host: a Linux sandbox on a Render Sandbox in the operator's Render workspace, over Render's REST API
2
+ // (https://api.render.com/v1, a Bearer API key). Render runs a command in a sandbox through a run token's URL
3
+ // (runs/sync, answered once the command ends; runs/stream, its output as events), with no stdin, which can't carry the
4
+ // stdio bridge, so this host has none: its sandboxes dial the server (facts.connect "dial"). The sandbox boots the box
5
+ // image, imported once into the workspace as a sandbox build (prepareImage), with MachineRequest.boot.env as its env but
6
+ // AGENTRUN_ATTACH_URL. Render's API names no command a sandbox runs at its start (sandboxPOST has none, and nothing of
7
+ // the image's CMD), so create waits for the sandbox to run and starts agentrun-dial itself, in one runs/sync call that
8
+ // detaches it (setsid): it fetches the server's computerd, checks its sha256, starts init and dials the attach route with
9
+ // the machine's own token, which stays in the sandbox's env. The rest of the computer is the shared machine-host
10
+ // adapter's (./hosted/provider.ts).
11
+ //
12
+ // Render's sandboxes carry no labels: a sandbox's name (computer-<12 hex>-r<run hash>-e<epoch>) gives the adapter's own
13
+ // two and says whose run and epoch it may be, and create writes every label to a file in the sandbox, root's alone, which
14
+ // get and list read back through runs/sync where a label asked is not the name's, and keep for the whole process: a
15
+ // computer's labels never change (Render moves no timeout, so there is no extend). That read needs a healthy guest, so
16
+ // one that fails, or has no answer within the call's own bound, gives get the name's two: enough for release to find and
17
+ // terminate a wedged sandbox, never a reason it is left to bill to its timeout. A listing by a label beyond the name's
18
+ // fails closed on it instead, naming the sandbox: it can't tell whether that one is a match. A listing by run reads only
19
+ // the sandboxes whose name has the run's hash (and the epoch asked), so only the run's own can fail it.
20
+ //
21
+ // Every vendor fact below is from @renderinc/sdk 1.11.0's OpenAPI schema (dist/generated/schema.d.ts, S) or its client
22
+ // (dist/sandboxes/index.js, C), a live probe (11-25: root, HOME=/root, a Render kernel, egress https, and a command
23
+ // started under setsid by runs/sync living on after the call), or the live Core run (11-25, packages/serve/scripts/
24
+ // dial-conformance.mjs: the sandbox's env reaches a runs/sync command, root makes network namespaces in the microVM, the
25
+ // builds API imports the public ghcr.io box image with no credential, and a process escaped with setsid ends with the
26
+ // sandbox's release). One none of these settles says unverified.
27
+ import { createHash } from "node:crypto";
28
+ import { boxImageRef, boxRecipeHash } from "./box-image.js";
29
+ import { RENDER } from "./descriptors/render.js";
30
+ import { COMPUTER_LABEL, DEFAULT_CPUS, DEFAULT_MEMORY_MB, show } from "./drift.js";
31
+ import { HostError } from "./host.js";
32
+ import { codeOfError, orThrow, pause, seconds, until, untilAborted } from "./hosted/process.js";
33
+ import { HostedProvider, mayHaveMade, NAME_LABEL, timeoutsOf } from "./hosted/provider.js";
34
+ import { allPages, jsonOf, rest } from "./hosted/rest.js";
35
+ import { dialLaunch } from "./hosted/scripts.js";
36
+ import { dateOf, isWhole } from "./hosted/values.js";
37
+ import { EPOCH_LABEL, RUN_LABEL, runHash } from "./labels.js";
38
+ import { failFor, ok, vendorFail } from "./result.js";
39
+ /**
40
+ * The box build's find-or-import under way in this process, by workspace, key and box image (owner id, the key's
41
+ * keyTag, build name, image tag): every provider of the workspace and key joins it, one of another key (a wrong one's
42
+ * 401) never, and it is dropped once it settles. Render's own POST answers a build of the same name and digest already
43
+ * pending, running or succeeded (S, create-sandbox-build), so this saves the calls, not a second build.
44
+ */
45
+ const FLIGHTS = new Map();
46
+ /** A key as a map key: the first 16 hex digits of its sha256, never the key. */
47
+ const keyTag = (apiKey) => createHash("sha256").update(apiKey, "utf8").digest("hex").slice(0, 16);
48
+ /** Kept, by workspace (owner id). */
49
+ const KEPT = new Map();
50
+ function keptOf(owner) {
51
+ let kept = KEPT.get(owner);
52
+ if (kept === undefined)
53
+ KEPT.set(owner, (kept = { labels: new Map(), ending: new Set() }));
54
+ return kept;
55
+ }
56
+ const API_URL = "https://api.render.com";
57
+ /**
58
+ * S: ownerId, a workspace id (tea-… for a team, usr-… for a person). Held to an id's characters alone, since it goes in
59
+ * every query: whether it names a workspace the key reaches is Render's answer to the first call.
60
+ */
61
+ const OWNER_ID = /^[A-Za-z0-9_-]{1,64}$/;
62
+ /** S: sandboxBuildId, sbb-…; a build's name may not start with sbb- (S, sandbox-groups/{id}/builds), so this reads as an id. */
63
+ const BUILD_ID = /^sbb-[a-z0-9]{10,40}$/;
64
+ /** A build's name, 1 to 255 characters (S); held to letters, digits, dots, underscores and hyphens, so an OCI path is not one. */
65
+ const BUILD_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
66
+ /**
67
+ * A computer's sandbox name: the adapter's name for it (computer-<12 hex>, computerNameFor), then -r<its run's hash>
68
+ * and -e<its epoch> where its labels carry them, as Orgo's names do (orgo-names.ts): at most 57 characters of Render's 64
69
+ * (S, sandboxPOST name). Only a sandbox named so is one of its computers.
70
+ */
71
+ const SANDBOX_NAME = /^(computer-[0-9a-f]{12})(?:-r([a-z2-7]{16}))?(?:-e(0|[1-9][0-9]{0,15}))?$/;
72
+ /** A computer's sandbox name for create's request: its name, then its run label's hash and its epoch label where they are one. */
73
+ function sandboxName({ name, labels }) {
74
+ const run = labels[RUN_LABEL];
75
+ const epoch = labels[EPOCH_LABEL];
76
+ return `${name}${typeof run === "string" && run !== "" ? `-r${runHash(run)}` : ""}${typeof epoch === "string" && /^(?:0|[1-9][0-9]{0,15})$/.test(epoch) ? `-e${epoch}` : ""}`;
77
+ }
78
+ /** What a sandbox's name says: the adapter's name, the run's hash and the epoch; undefined for a sandbox not named as a computer. */
79
+ function nameParts(name) {
80
+ const match = typeof name === "string" ? SANDBOX_NAME.exec(name) : null;
81
+ if (match === null)
82
+ return undefined;
83
+ return { computer: match[1], ...(match[2] ? { run: match[2] } : {}), ...(match[3] !== undefined ? { epoch: match[3] } : {}) };
84
+ }
85
+ /**
86
+ * Whether a sandbox so named can carry these labels: one of a name, a run or an epoch other than those asked can't, so
87
+ * a listing never reads its guest, and a guest that can't answer refuses no listing it could not be in. A run's own
88
+ * sandboxes always have its hash, so a hash another run shares (16 base32 letters, 80 bits) only adds a sandbox to be
89
+ * read, whose file then says its run, or which fails the listing closed: it never leaves one of the run's out.
90
+ */
91
+ function mayCarry(parts, labels) {
92
+ const name = labels[NAME_LABEL];
93
+ const run = labels[RUN_LABEL];
94
+ const epoch = labels[EPOCH_LABEL];
95
+ return (name === undefined || parts.computer === name) && (run === undefined || parts.run === runHash(run)) && (epoch === undefined || parts.epoch === epoch);
96
+ }
97
+ /** S, sandboxPlan: the sizes a sandbox takes, smallest first. */
98
+ const PLANS = [
99
+ { plan: "1c-2g", cpus: 1, memoryMb: 2048 },
100
+ { plan: "2c-4g", cpus: 2, memoryMb: 4096 },
101
+ { plan: "4c-8g", cpus: 4, memoryMb: 8192 },
102
+ { plan: "8c-16g", cpus: 8, memoryMb: 16_384 },
103
+ ];
104
+ /** S, timeoutSeconds: 0 (none) or 60 to 2592000; the sandbox ends when it elapses. */
105
+ const LEAST_TIMEOUT_S = 60;
106
+ /** Render ends a sandbox at its timeout, up to 30 days (S); a computer's cap here is a day, as Fly's and Agent37's. */
107
+ const MAX_LIFETIME_MS = 24 * 60 * 60_000;
108
+ /** One page of a listing (S, limitParam: 1 to 100). */
109
+ const PAGE = 100;
110
+ const MAX_PAGES = 100;
111
+ /** How many labels files a listing reads at once: each is a run token and a runs/sync call, and a workspace's runs are rate limited (S, 429RateLimit). */
112
+ const LABEL_READS = 4;
113
+ /** S, sandboxBuildStatus: a build of these has, or will have, the box image; failed is imported again. */
114
+ const BUILD_LIVE = ["succeeded", "pending", "running"];
115
+ /** How long the box image's import may take (C's own wait for an image is 10 minutes; the box image is about 400 MB). */
116
+ const BUILD_MS = 30 * 60_000;
117
+ /** How long a failed create's terminate of the sandbox it made may take: create's own bound may be spent by then. */
118
+ const TERMINATE_MS = 30_000;
119
+ /** S, 429RateLimit: a 429 is sent again after 1, 2 and 4 s. */
120
+ const RETRY = { attempts: 4, baseMs: 1_000 };
121
+ /** A file read's exit when the file is not there. */
122
+ const MISSING = 3;
123
+ /** Where create leaves the computer's labels, root's alone (its directory 0700, umask 077). */
124
+ const LABELS_DIR = "/var/lib/agentrun-computer";
125
+ const LABELS_FILE = `${LABELS_DIR}/labels.json`;
126
+ /** agentrun-dial's launch script (dialLaunch's line), its output and its exit code, root's alone. */
127
+ const DIAL_DIR = "/run/agentrun-dial";
128
+ const DIAL_SCRIPT = `${DIAL_DIR}/launch`;
129
+ const DIAL_LOG = `${DIAL_DIR}/log`;
130
+ const DIAL_EXIT = `${DIAL_DIR}/exit`;
131
+ /** How much of agentrun-dial's log dialLog reads: its end. */
132
+ const LOG_BYTES = 65_536;
133
+ /** A file written whole: base64 through printf, to <path>.new, then moved over <path>. */
134
+ const writeFile = (path, text) => `printf %s '${Buffer.from(text, "utf8").toString("base64")}' | base64 -d > ${path}.new && mv -f ${path}.new ${path}`;
135
+ /** A file read: exits MISSING when it is not there. */
136
+ const readFile = (path, read = "cat") => `[ -f ${path} ] || exit ${MISSING}; ${read} ${path}`;
137
+ /**
138
+ * agentrun-dial's start from its launch script, detached: a session of its own (setsid), no hangup, stdin closed, its
139
+ * output to DIAL_LOG and its exit code to DIAL_EXIT once it ends, so the runs/sync call returns at once.
140
+ */
141
+ const START = `rm -f ${DIAL_EXIT} && { setsid nohup sh -c 'sh ${DIAL_SCRIPT}; echo $? > ${DIAL_EXIT}' > ${DIAL_LOG} 2>&1 < /dev/null & }`;
142
+ /** create's one run: the labels file, the launch script with the attach URL (the token stays in the env), the start. */
143
+ function launchLine(labels, attach) {
144
+ return ["umask 077", `mkdir -p ${LABELS_DIR} ${DIAL_DIR}`, writeFile(LABELS_FILE, JSON.stringify(labels)), writeFile(DIAL_SCRIPT, dialLaunch({ attach })), START].join(" && ");
145
+ }
146
+ /** The smallest plan holding the size asked; none asked, the adapter's default of 2 CPUs and 4 GiB. */
147
+ function planOf(cpus, memoryMb) {
148
+ const want = cpus === undefined && memoryMb === undefined ? { cpus: DEFAULT_CPUS, memoryMb: DEFAULT_MEMORY_MB } : { cpus: cpus ?? 0, memoryMb: memoryMb ?? 0 };
149
+ return PLANS.find((one) => one.cpus >= want.cpus && one.memoryMb >= want.memoryMb)?.plan;
150
+ }
151
+ /** What a plan gives, as its name says it (Nc-Mg); none for another. */
152
+ function resourcesOf(plan) {
153
+ const sized = /^(\d+)c-(\d+)g$/.exec(plan ?? "");
154
+ return sized ? { resources: { cpus: Number(sized[1]), memoryMb: Number(sized[2]) * 1024 } } : {};
155
+ }
156
+ /**
157
+ * Render's statuses (S, sandboxStatus) as the adapter's: creating and resuming are starting, suspending and suspended
158
+ * stopped (listed, so a release still ends them), errored gone. terminated is a sandbox that is no more: null, as get and
159
+ * list answer none for it.
160
+ */
161
+ function stateOf(status) {
162
+ if (status === "running")
163
+ return "running";
164
+ if (status === "creating" || status === "resuming")
165
+ return "starting";
166
+ if (status === "suspending" || status === "suspended")
167
+ return "stopped";
168
+ if (status === "errored")
169
+ return "gone";
170
+ if (status === "terminated")
171
+ return null;
172
+ return undefined;
173
+ }
174
+ /** A sandbox as the adapter reads one, with the labels read for it; undefined for one terminated. */
175
+ function machineOf(found, labels) {
176
+ const state = stateOf(found.status);
177
+ if (state === null)
178
+ return undefined;
179
+ const created = dateOf(found.createdAt);
180
+ const timeout = found.timeoutSeconds;
181
+ const ends = created && isWhole(timeout) && timeout > 0 ? new Date(created.getTime() + timeout * 1000) : undefined;
182
+ const why = state === undefined
183
+ ? `Render reads the sandbox's status ${show(found.status)}, which this provider does not know`
184
+ : found.status === "errored"
185
+ ? `Render reads the sandbox ${found.id} errored, with no reason given`
186
+ : undefined;
187
+ return {
188
+ id: found.id,
189
+ labels,
190
+ state: state ?? "gone",
191
+ ...(created ? { createdAt: created } : {}),
192
+ ...(ends ? { endsAt: ends } : {}),
193
+ ...(why ? { why } : {}),
194
+ ...resourcesOf(found.plan),
195
+ };
196
+ }
197
+ /** Whether an id Render answered can be one path segment: any string but none, `.` and `..` (which a URL resolves away). */
198
+ const segmentable = (id) => typeof id === "string" && id !== "" && id !== "." && id !== "..";
199
+ /**
200
+ * A sandbox id as one path segment, encoded: Render's ids read sbx-… (S, sandboxId), but one of another form is still
201
+ * read and terminated by it, never left running because this host did not know the form. One that can't be a segment
202
+ * is no sandbox: not_found.
203
+ */
204
+ function sandboxPath(id) {
205
+ if (!segmentable(id))
206
+ throw new HostError("not_found", `${JSON.stringify(id)} is not a Render sandbox id`);
207
+ return encodeURIComponent(id);
208
+ }
209
+ /** Each of items through `each`, at most `most` at once, the answers in the items' order. */
210
+ async function eachAtMost(items, most, each) {
211
+ const answers = new Array(items.length);
212
+ let next = 0;
213
+ const worker = async () => {
214
+ while (next < items.length) {
215
+ const at = next++;
216
+ answers[at] = await each(items[at]);
217
+ }
218
+ };
219
+ await Promise.all(Array.from({ length: Math.min(most, items.length) }, worker));
220
+ return answers;
221
+ }
222
+ /** Render's error body (S, error): { id?, message?, code? }. */
223
+ function explain({ status, bytes, what }) {
224
+ const body = jsonOf(bytes);
225
+ const said = typeof body?.message === "string" && body.message !== "" ? `: ${body.message}` : "";
226
+ return { message: `${what} answered ${status}${said}` };
227
+ }
228
+ /** The last words of a run's output, for a failure: its stderr, else its stdout. */
229
+ const lastWords = ({ stdout, stderr }) => (stderr.trim() || stdout.trim()).slice(-300);
230
+ /** Render Sandboxes as a dial MachineHost (../host.ts): no exec, no upload. */
231
+ class RenderHost {
232
+ descriptor = RENDER;
233
+ facts = {
234
+ // agentrun-dial starts init as its child; nothing is started through exec.
235
+ daemon: "child",
236
+ // The live probe read a kernel of Render's own (uname: 6.18.51-render1+), so each sandbox is a VM of its own.
237
+ isolation: "microvm",
238
+ // Render ends a sandbox at its timeoutSeconds (S), which create sets to the lifetime.
239
+ lifetime: "vendor",
240
+ maxLifetimeMs: MAX_LIFETIME_MS,
241
+ // The box image is built for amd64 alone (release.yml's box job), and the live Core run ran it and its amd64 daemon.
242
+ arch: "amd64",
243
+ // Unverified: the agent that answers runs inside the sandbox listens where S does not say. None declared.
244
+ vendorAgentPorts: [],
245
+ // The sandbox dials the server: Render's runs take no stdin (S: runs/{sync,stream} take { command }), so there is
246
+ // no exec and no upload here. Its descriptor's (connectOf).
247
+ connect: RENDER.connect,
248
+ };
249
+ #api;
250
+ #apiKey;
251
+ #owner;
252
+ #fetch;
253
+ #pollMs;
254
+ /** What this process keeps of the workspace's sandboxes (KEPT): every provider of the workspace shares it. */
255
+ #labels;
256
+ #ending;
257
+ /** The box build's name once Render read it succeeded: prepareImage asks no more. */
258
+ #built;
259
+ constructor(options) {
260
+ this.#apiKey = options.apiKey;
261
+ this.#owner = options.ownerId;
262
+ this.#fetch = options.fetch;
263
+ this.#pollMs = options.pollMs;
264
+ this.#api = this.#client(API_URL, () => this.#apiKey);
265
+ ({ labels: this.#labels, ending: this.#ending } = keptOf(this.#owner));
266
+ }
267
+ /** A REST client whose every call carries `bearer()` as its Bearer token: the API key, or one run's token. */
268
+ #client(base, bearer) {
269
+ return rest({ base, headers: () => ({ Authorization: `Bearer ${bearer()}`, Accept: "application/json" }), vendor: RENDER.id, fetch: this.#fetch, timeoutMs: 30_000, retry: RETRY, explain });
270
+ }
271
+ /** One API call, bounded by ctx: its JSON answer (null for none), or a HostError in Render's words. */
272
+ async #call(method, path, init, ctx) {
273
+ return orThrow(await this.#api.json(method, this.#api.url(path), { ...init, timeoutMs: ctx.timeoutMs }, ctx.signal));
274
+ }
275
+ /** The workspace as a query, which every sandbox call names (C names it on each). */
276
+ #owned(path, query = {}) {
277
+ return `${path}?${new URLSearchParams({ ownerId: this.#owner, ...query })}`;
278
+ }
279
+ /**
280
+ * One command run in the sandbox: a run token (POST /v1/sandboxes/{id}/runs/sync/token, S: "Send the command to the
281
+ * URL in the response, using the token as the bearer token"), then the command to its URL. `once`: a run that got
282
+ * no answer is never sent again, since it may have run; a read is.
283
+ */
284
+ async #run(id, command, ctx, once = false) {
285
+ const end = Date.now() + ctx.timeoutMs;
286
+ const minted = (await this.#call("POST", this.#owned(`/v1/sandboxes/${sandboxPath(id)}/runs/sync/token`), { retry: true }, ctx));
287
+ const { uri, token } = minted ?? {};
288
+ if (typeof uri !== "string" || !uri.startsWith("https://") || typeof token !== "string" || token === "")
289
+ throw new HostError("vendor", `Render answered no https run URL and token for the sandbox ${id}`);
290
+ const plane = this.#client(new URL(uri).origin, () => token);
291
+ const method = typeof minted?.method === "string" ? minted.method : "POST";
292
+ const answer = orThrow(await plane.json(method, uri, { json: { command }, timeoutMs: Math.max(1, end - Date.now()), retry: once ? (status) => status === 429 : true }, ctx.signal));
293
+ if (!isWhole(answer?.exit_code))
294
+ throw new HostError("vendor", `Render's run in ${id} answered no exit code: ${show(answer?.exit_code)}`);
295
+ return { stdout: typeof answer.stdout === "string" ? answer.stdout : "", stderr: typeof answer.stderr === "string" ? answer.stderr : "", exit: answer.exit_code };
296
+ }
297
+ /**
298
+ * A sandbox's labels: the ones this process knows, else its name's, else its labels file's, read once through runs/sync
299
+ * and kept. `need`: a listing's labels; when the name's hold every one asked, no file is read. A sandbox not named as a
300
+ * computer carries none; one not running, one terminated from this process, or one with no file yet, its name's. The
301
+ * read is held to `end` (epoch ms, the call's own bound): one that fails or has no answer by then gives the name's,
302
+ * kept for nothing, so the next read tries again, with `unread`, why: get answers the name's (release needs no more),
303
+ * and a listing fails closed on it. Only the caller's own abort throws.
304
+ */
305
+ async #labelsOf(found, ctx, end, need) {
306
+ const parts = nameParts(found.name);
307
+ if (parts === undefined)
308
+ return { labels: {} };
309
+ const known = this.#labels.get(found.id);
310
+ if (known !== undefined)
311
+ return { labels: known };
312
+ const own = { [COMPUTER_LABEL]: "1", [NAME_LABEL]: parts.computer };
313
+ if ((need !== undefined && Object.keys(need).every((key) => key in own)) || found.status !== "running" || this.#ending.has(found.id))
314
+ return { labels: own };
315
+ const late = { labels: own, unread: `no answer within ${seconds(ctx.timeoutMs)}` };
316
+ const left = end - Date.now();
317
+ if (left <= 0)
318
+ return late;
319
+ const bound = AbortSignal.timeout(left);
320
+ let file;
321
+ try {
322
+ file = await this.#labelsFile(found.id, { timeoutMs: left, signal: ctx.signal ? AbortSignal.any([ctx.signal, bound]) : bound });
323
+ }
324
+ catch (error) {
325
+ if (ctx.signal?.aborted)
326
+ throw error;
327
+ return bound.aborted ? late : { labels: own, unread: error instanceof Error ? error.message : String(error) };
328
+ }
329
+ if (file === undefined)
330
+ return { labels: own };
331
+ const labels = { ...file, ...own };
332
+ this.#labels.set(found.id, labels);
333
+ return { labels };
334
+ }
335
+ /** The labels file read through runs/sync: undefined when it is not there yet; a read that fails throws in words. */
336
+ async #labelsFile(id, ctx) {
337
+ const read = await this.#run(id, readFile(LABELS_FILE), ctx);
338
+ if (read.exit === MISSING)
339
+ return undefined;
340
+ if (read.exit !== 0)
341
+ throw new HostError("vendor", `reading the labels file of ${id} exited ${read.exit}: ${lastWords(read)}`);
342
+ const parsed = jsonOf(new TextEncoder().encode(read.stdout));
343
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed) || !Object.values(parsed).every((value) => typeof value === "string")) {
344
+ throw new HostError("vendor", `the labels file of ${id} is not a JSON map of strings`);
345
+ }
346
+ return parsed;
347
+ }
348
+ /** A sandbox Render reads gone: its labels and its terminate are let go. */
349
+ #forget(id) {
350
+ this.#labels.delete(id);
351
+ this.#ending.delete(id);
352
+ }
353
+ /**
354
+ * Any Render build by its name or id (S: buildName, "the newest successful build with this name in the sandbox
355
+ * group"; buildId), and a size Render's plans hold (S, sandboxPlan). Render's base image ("default", a create that
356
+ * names no build) has no agentrun-dial, so it can't be one.
357
+ */
358
+ check(spec) {
359
+ const refusals = [];
360
+ const { image, cpus, memoryMb } = spec;
361
+ const most = PLANS[PLANS.length - 1];
362
+ if (typeof image === "string" && !(BUILD_ID.test(image) || (BUILD_NAME.test(image) && image !== "default" && !image.startsWith("sbb-")))) {
363
+ refusals.push({ field: "image", message: "an image is the name or id of a Render sandbox build that holds agentrun-dial: the box image's, which prepareImage() imports (agentrun-box-<tag>), or one of your own FROM it; Render's base image (default) has none" });
364
+ }
365
+ if (cpus !== undefined && !(isWhole(cpus) && cpus > 0 && cpus <= most.cpus))
366
+ refusals.push({ field: "cpus", message: `a Render sandbox has at most ${most.cpus} CPUs (plans ${PLANS.map(({ plan }) => plan).join(", ")})` });
367
+ if (memoryMb !== undefined && !(isWhole(memoryMb) && memoryMb > 0 && memoryMb <= most.memoryMb))
368
+ refusals.push({ field: "memoryMb", message: `a Render sandbox has at most ${most.memoryMb} MiB (plans ${PLANS.map(({ plan }) => plan).join(", ")})` });
369
+ return refusals;
370
+ }
371
+ /**
372
+ * POST /v1/sandboxes (S, sandboxPOST): the workspace, the request's name with its run's hash and epoch (sandboxName),
373
+ * the smallest plan holding its size, the lifetime as timeoutSeconds (at least 60), no idle suspension (0), egress
374
+ * allow-all (the sandbox must reach the server; the computer's own programs keep to init's network), the boot env but
375
+ * AGENTRUN_ATTACH_URL as its env, and the build. Only a 429, a refusal that made nothing, is sent again: a create that
376
+ * got no answer may have made a sandbox, which the adapter finds by its name. Then, once the sandbox reads running
377
+ * within ctx.timeoutMs, one runs/sync call writes the labels file and starts agentrun-dial, the URL in its launch
378
+ * script. A sandbox that errors or ends first, a launch that fails, or a bound passed, throws: a create that made a
379
+ * machine to the adapter, which deletes it by its name. A refusal after the sandbox exists (a run token's 429s past
380
+ * every retry, limit; a 401, denied) the adapter reads as a create that made nothing (mayHaveMade), so this terminates
381
+ * the sandbox by its id first and throws the refusal in its own code. req.backstopAt is left: Render's timeout ends the
382
+ * sandbox.
383
+ */
384
+ async create(req, ctx) {
385
+ const end = Date.now() + ctx.timeoutMs;
386
+ if (req.boot === undefined)
387
+ throw new HostError("invalid", "a Render sandbox dials the server, and the request has no boot env for it");
388
+ const { AGENTRUN_ATTACH_URL: attach, ...env } = req.boot.env;
389
+ if (typeof attach !== "string" || attach === "")
390
+ throw new HostError("invalid", "a Render sandbox dials the server, and the boot env names no AGENTRUN_ATTACH_URL");
391
+ const made = (await this.#call("POST", "/v1/sandboxes", {
392
+ json: {
393
+ ownerId: this.#owner,
394
+ name: sandboxName(req),
395
+ plan: planOf(req.cpus, req.memoryMb),
396
+ timeoutSeconds: Math.max(LEAST_TIMEOUT_S, Math.ceil(req.lifetimeMs / 1000)),
397
+ idleTimeoutSeconds: 0,
398
+ networkPolicy: { type: "allow-all" },
399
+ env,
400
+ ...(BUILD_ID.test(req.image) ? { buildId: req.image } : { buildName: req.image }),
401
+ },
402
+ retry: (status) => status === 429,
403
+ }, ctx));
404
+ const id = made?.id;
405
+ if (!segmentable(id))
406
+ throw new HostError("vendor", `POST /v1/sandboxes answered no sandbox id: ${show(id)}`);
407
+ this.#labels.set(id, { ...req.labels });
408
+ try {
409
+ await this.#untilRunning(made, end, ctx);
410
+ const ran = await this.#run(id, launchLine(req.labels, attach), { ...ctx, timeoutMs: Math.max(1, end - Date.now()) }, true);
411
+ if (ran.exit !== 0)
412
+ throw new HostError("vendor", `starting agentrun-dial in ${id} exited ${ran.exit}: ${lastWords(ran)}`);
413
+ }
414
+ catch (error) {
415
+ if (!(error instanceof HostError) || mayHaveMade(error.code))
416
+ throw error;
417
+ throw await this.#unmade(id, error);
418
+ }
419
+ return { id };
420
+ }
421
+ /** The sandbox a failed create made, terminated by its id: the step's error in its own code, the terminate's outcome added. */
422
+ async #unmade(id, error) {
423
+ let outcome;
424
+ try {
425
+ await this.delete(id, { timeoutMs: TERMINATE_MS });
426
+ outcome = `the sandbox ${id} it made was terminated`;
427
+ }
428
+ catch (failed) {
429
+ outcome =
430
+ failed instanceof HostError && failed.code === "not_found"
431
+ ? `the sandbox ${id} it made is gone`
432
+ : `the sandbox ${id} it made could not be terminated (${failed instanceof Error ? failed.message : String(failed)}); Render ends it at its timeout`;
433
+ }
434
+ return new HostError(error.code, `${error.message}; ${outcome}`);
435
+ }
436
+ /** Reads the sandbox until it runs, pollMs apart, by `end`: errored or terminated first throws vendor, the end timeout. */
437
+ async #untilRunning(posted, end, ctx) {
438
+ for (let found = posted; found.status !== "running";) {
439
+ if (found.status === "errored" || found.status === "terminated")
440
+ throw new HostError("vendor", `Render reads the sandbox ${found.id} ${found.status}, so agentrun-dial was not started`);
441
+ if (Date.now() + this.#pollMs >= end)
442
+ throw new HostError("timeout", `the sandbox ${found.id} did not read running within ${seconds(ctx.timeoutMs)} (it reads ${found.status}), so agentrun-dial was not started`);
443
+ await pause(this.#pollMs, ctx.signal);
444
+ if (ctx.signal?.aborted)
445
+ throw new HostError("aborted", `the wait for the sandbox ${found.id} to run was aborted`);
446
+ found = (await this.#call("GET", this.#owned(`/v1/sandboxes/${sandboxPath(found.id)}`), { retry: true }, { ...ctx, timeoutMs: Math.max(1, end - Date.now()) }));
447
+ }
448
+ }
449
+ /**
450
+ * GET /v1/sandboxes/{id}; 404 is not_found, which the adapter reads as none, and a terminated sandbox is none: either
451
+ * lets go of what this process kept of it. Its labels are read within this call's own bound (#labelsOf), and a read that
452
+ * fails gives the name's two: enough for the adapter to know its computer and release it.
453
+ */
454
+ async get(id, ctx) {
455
+ const end = Date.now() + ctx.timeoutMs;
456
+ let found;
457
+ try {
458
+ found = (await this.#call("GET", this.#owned(`/v1/sandboxes/${sandboxPath(id)}`), { retry: true }, ctx));
459
+ }
460
+ catch (error) {
461
+ if (error instanceof HostError && error.code === "not_found")
462
+ this.#forget(id);
463
+ throw error;
464
+ }
465
+ if (typeof found?.status !== "string")
466
+ throw new HostError("vendor", `GET /v1/sandboxes/${id} answered no status`);
467
+ if (found.status === "terminated") {
468
+ this.#forget(id);
469
+ return undefined;
470
+ }
471
+ return machineOf(found, (await this.#labelsOf(found, ctx, end)).labels);
472
+ }
473
+ /**
474
+ * GET /v1/sandboxes?ownerId (S, list-sandboxes: terminated ones left out unless asked), every page by its last item's
475
+ * cursor while a page is full: Render filters by an exact name alone, and a sandbox's name carries its run and epoch
476
+ * beside the adapter's, so the name asked is matched here. Only sandboxes named as computers whose name may carry the
477
+ * labels asked (mayCarry: the adapter's name, the run's hash and the epoch); a label asked that is not the name's is
478
+ * read from each running one's labels file (#labelsOf), LABEL_READS at once, all within this call's own bound, and only
479
+ * those that carry every label asked are answered. A file that can't be read by then fails the listing closed, once
480
+ * every read has ended, naming each such sandbox and why: the listing can't tell whether it carries the labels asked,
481
+ * and leaving it out would let a run's listing miss a newer epoch's fence or call a partial cleanup whole (janitor.ts
482
+ * releaseOlder). So only a sandbox that may be the run's can fail a listing by run: another run's is never read. A
483
+ * listing by the name alone reads no file, and a sandbox terminated from this process is never read, so neither fails
484
+ * so. What this process kept of a sandbox the listing no longer shows is let go: Render ended it, at its timeout or by
485
+ * another's hand.
486
+ */
487
+ async list(labels, ctx) {
488
+ const end = Date.now() + ctx.timeoutMs;
489
+ // Only what was kept before the listing began is let go: a sandbox made while it ran may not be on its pages.
490
+ const kept = [...new Set([...this.#labels.keys(), ...this.#ending])];
491
+ const listed = orThrow(await allPages(async (cursor) => {
492
+ const page = await this.#api.json("GET", this.#api.url(this.#owned("/v1/sandboxes", { limit: String(PAGE), ...(cursor === undefined ? {} : { cursor }) })), { retry: true, timeoutMs: ctx.timeoutMs }, ctx.signal);
493
+ if (!page.ok)
494
+ return page;
495
+ if (!Array.isArray(page.value))
496
+ return vendorFail(RENDER.id, "GET /v1/sandboxes answered no list");
497
+ const rows = page.value;
498
+ const items = rows.flatMap((row) => (typeof row?.sandbox?.id === "string" && typeof row.sandbox.status === "string" ? [row.sandbox] : []));
499
+ const last = rows.at(-1)?.cursor;
500
+ return ok({ items, ...(rows.length === PAGE && typeof last === "string" ? { next: last } : {}) });
501
+ }, MAX_PAGES, { vendor: RENDER.id, what: "Render's sandbox listing" }));
502
+ const live = listed.filter((found) => found.status !== "terminated");
503
+ const shown = new Set(live.map(({ id }) => id));
504
+ for (const id of kept)
505
+ if (!shown.has(id))
506
+ this.#forget(id);
507
+ const ours = live.filter((found) => {
508
+ const parts = nameParts(found.name);
509
+ return parts !== undefined && mayCarry(parts, labels);
510
+ });
511
+ const read = await eachAtMost(ours, LABEL_READS, async (found) => ({ found, ...(await this.#labelsOf(found, ctx, end, labels)) }));
512
+ const unread = read.flatMap(({ found, unread: why }) => (why === undefined ? [] : [`${found.id}: ${why}`]));
513
+ if (unread.length > 0) {
514
+ const asked = Object.entries(labels).filter(([key]) => key !== COMPUTER_LABEL && key !== NAME_LABEL);
515
+ const carry = unread.length === 1 ? "it carries" : "they carry";
516
+ throw new HostError("vendor", `could not read the labels of ${unread.join("; ")}; the listing can't tell whether ${carry} ${asked.map(([key, value]) => `${key}=${value}`).join(", ")}`);
517
+ }
518
+ return read.flatMap(({ found, labels: carried }) => (Object.entries(labels).every(([key, value]) => carried[key] === value) ? (machineOf(found, carried) ?? []) : []));
519
+ }
520
+ /**
521
+ * POST /v1/sandboxes/{id}/terminate (S: 204, also for one already terminated); a 404 is done to the adapter. What this
522
+ * process kept of it stays until get reads it gone: Render may read it running a while yet, and its labels still
523
+ * answer. It is marked ending for every provider of the workspace, so none reads its guest meanwhile.
524
+ */
525
+ async delete(id, ctx) {
526
+ try {
527
+ await this.#call("POST", this.#owned(`/v1/sandboxes/${sandboxPath(id)}/terminate`), { retry: true }, ctx);
528
+ }
529
+ catch (error) {
530
+ if (error instanceof HostError && error.code === "not_found")
531
+ this.#forget(id);
532
+ throw error;
533
+ }
534
+ this.#ending.add(id);
535
+ }
536
+ /** The end of what agentrun-dial wrote, through runs/sync; undefined where it was never started. */
537
+ async dialLog(id, ctx) {
538
+ const read = await this.#run(id, readFile(DIAL_LOG, `tail -c ${LOG_BYTES}`), ctx);
539
+ if (read.exit === MISSING)
540
+ return undefined;
541
+ if (read.exit !== 0)
542
+ throw new HostError("vendor", `reading agentrun-dial's log in ${id} exited ${read.exit}: ${lastWords(read)}`);
543
+ return read.stdout;
544
+ }
545
+ /** agentrun-dial's exit code, which its start writes once it has ended; undefined while it runs, or never started. */
546
+ async dialExit(id, ctx) {
547
+ const read = await this.#run(id, readFile(DIAL_EXIT), ctx);
548
+ if (read.exit === MISSING)
549
+ return undefined;
550
+ if (read.exit !== 0)
551
+ throw new HostError("vendor", `reading agentrun-dial's exit in ${id} exited ${read.exit}: ${lastWords(read)}`);
552
+ const code = read.stdout.trim();
553
+ return /^\d{1,3}$/.test(code) ? Number(code) : undefined;
554
+ }
555
+ /** agentrun-dial started once more from create's launch script (the same attach URL; the token is the sandbox's env still). */
556
+ async redial(id, ctx) {
557
+ const ran = await this.#run(id, `[ -f ${DIAL_SCRIPT} ] || exit ${MISSING}; umask 077 && ${START}`, ctx, true);
558
+ if (ran.exit === MISSING)
559
+ throw new HostError("not_found", `no agentrun-dial was started in the sandbox ${id}, so it is not started again`);
560
+ if (ran.exit !== 0)
561
+ throw new HostError("vendor", `starting agentrun-dial again in ${id} exited ${ran.exit}: ${lastWords(ran)}`);
562
+ }
563
+ /** The workspace's default sandbox group (S, list-sandbox-groups), read a page at a time by cursor until it is found. */
564
+ async #defaultGroup(ctx) {
565
+ const seen = new Set();
566
+ let cursor;
567
+ for (let page = 0; page < MAX_PAGES; page++) {
568
+ const rows = await this.#call("GET", `/v1/sandbox-groups?${new URLSearchParams({ ownerId: this.#owner, limit: String(PAGE), ...(cursor === undefined ? {} : { cursor }) })}`, { retry: true }, ctx);
569
+ if (!Array.isArray(rows))
570
+ throw new HostError("vendor", "GET /v1/sandbox-groups answered no list");
571
+ const listed = rows;
572
+ const group = listed.find((row) => row?.sandboxGroup?.isDefault === true)?.sandboxGroup?.id;
573
+ if (group !== undefined) {
574
+ if (typeof group !== "string" || !/^[a-z0-9-]{1,64}$/.test(group))
575
+ throw new HostError("vendor", `Render answered a default sandbox group whose id is ${show(group)}`);
576
+ return group;
577
+ }
578
+ const next = listed.at(-1)?.cursor;
579
+ if (listed.length < PAGE || typeof next !== "string" || next === "" || seen.has(next))
580
+ break;
581
+ seen.add(next);
582
+ cursor = next;
583
+ }
584
+ throw new HostError("vendor", `Render answered no default sandbox group for the workspace ${this.#owner}`);
585
+ }
586
+ /**
587
+ * The box image as a build of the workspace's default sandbox group (the group a create that names none uses, S),
588
+ * named agentrun-box-<recipe hash>, so a new recipe is a new build. Concurrent callers in this process share one
589
+ * find-or-import per workspace, key and box image (FLIGHTS), whichever provider they call through (serve makes one per
590
+ * claim), forgotten once it settles. `building` is told once, before the wait on an import, its own or one under way
591
+ * when it joined; a caller's signal ends its own wait alone: the import's wait goes on, within BUILD_MS, for the next
592
+ * caller.
593
+ */
594
+ async boxBuild(building, signal) {
595
+ if (this.#built !== undefined)
596
+ return this.#built;
597
+ if (signal?.aborted)
598
+ throw new HostError("aborted", "the wait for the box build was aborted before it began");
599
+ const key = JSON.stringify([this.#owner, keyTag(this.#apiKey), boxBuildName(), boxImageRef()]);
600
+ let flight = FLIGHTS.get(key);
601
+ if (flight === undefined) {
602
+ const started = this.#fly();
603
+ FLIGHTS.set(key, (flight = started));
604
+ void started.answer.then(() => {
605
+ if (FLIGHTS.get(key) === started)
606
+ FLIGHTS.delete(key);
607
+ });
608
+ }
609
+ const tell = () => {
610
+ try {
611
+ building();
612
+ }
613
+ catch {
614
+ // The caller's listener is its own: a throw changes nothing here.
615
+ }
616
+ };
617
+ if (flight.importing)
618
+ tell();
619
+ else
620
+ flight.toTell.add(tell);
621
+ try {
622
+ const settled = await untilAborted(flight.answer, [signal]);
623
+ if (settled === undefined)
624
+ throw new HostError("aborted", "the wait for the box build was aborted; its import goes on for the next caller");
625
+ if ("error" in settled)
626
+ throw settled.error;
627
+ return (this.#built = settled.name);
628
+ }
629
+ finally {
630
+ flight.toTell.delete(tell);
631
+ }
632
+ }
633
+ /** A find-or-import through this host's API key: it never rejects (its error is its answer). */
634
+ #fly() {
635
+ const flight = { answer: Promise.resolve({ error: undefined }), importing: false, toTell: new Set() };
636
+ const importing = () => {
637
+ flight.importing = true;
638
+ for (const tell of flight.toTell)
639
+ tell();
640
+ };
641
+ flight.answer = this.#findOrImport(importing).then((name) => ({ name }), (error) => ({ error }));
642
+ return flight;
643
+ }
644
+ /**
645
+ * The box build found or imported, held to no caller: a build of its name that succeeded is the answer; one pending
646
+ * or running (an import another call or process started, or a POST whose answer was lost) is waited for (GET
647
+ * …/builds?name&status=succeeded&status=pending&status=running, newest first; an array is one key per status, as C's
648
+ * openapi-fetch sends it). Else POST …/builds { name, sourceImage } imports the box image's public tag (S: "converts a
649
+ * container image into an image that sandboxes can use"), and Render's answer is read until it succeeded or failed.
650
+ * `importing` is told before either wait. Render pulls the public ghcr.io image with no credential (the live Core
651
+ * run's import took 104 s); a tag the release has not published yet is Render's 400, "source image unavailable".
652
+ */
653
+ async #findOrImport(importing) {
654
+ const name = boxBuildName();
655
+ const ctx = { timeoutMs: 30_000 };
656
+ const group = await this.#defaultGroup(ctx);
657
+ const builds = `/v1/sandbox-groups/${group}/builds`;
658
+ const query = new URLSearchParams([["name", name], ...BUILD_LIVE.map((status) => ["status", status]), ["limit", String(PAGE)]]);
659
+ const listed = await this.#call("GET", `${builds}?${query}`, { retry: true }, ctx);
660
+ const found = (Array.isArray(listed) ? listed : []).flatMap((row) => (row?.build ? [row.build] : []));
661
+ if (found.some(({ status }) => status === "succeeded"))
662
+ return name;
663
+ importing();
664
+ let build = found.find(({ id, status }) => (status === "pending" || status === "running") && typeof id === "string" && BUILD_ID.test(id));
665
+ build ??= (await this.#call("POST", builds, { json: { name, sourceImage: boxImageRef() }, retry: (status) => status === 429 }, ctx));
666
+ const id = build?.id;
667
+ if (typeof id !== "string" || !BUILD_ID.test(id))
668
+ throw new HostError("vendor", `POST ${builds} answered no build id: ${show(id)}`);
669
+ const settled = (one) => {
670
+ if (one?.status === "succeeded")
671
+ return true;
672
+ if (one?.status === "failed")
673
+ throw new HostError("vendor", `Render's build ${id} failed: ${one.failureReason || one.failureCode || "no reason given"}`);
674
+ return undefined;
675
+ };
676
+ if (!settled(build))
677
+ await until(`Render's build ${id}`, { end: Date.now() + BUILD_MS, pollMs: this.#pollMs }, async () => settled((build = (await this.#call("GET", `${builds}/${id}`, { retry: true }, ctx)))));
678
+ return name;
679
+ }
680
+ }
681
+ /** The box image's build name: agentrun-box-<recipe hash>, as the box image's own tag is. */
682
+ const boxBuildName = () => `agentrun-box-${boxRecipeHash()}`;
683
+ const fail = failFor(RENDER.id);
684
+ /** A RenderProvider from its options alone; it reads no environment (serve passes the saved RENDER_API_KEY and RENDER_WORKSPACE_ID). */
685
+ export function create(options) {
686
+ return new RenderProvider(options);
687
+ }
688
+ /** The conformance CLI's module for Render: its settings, and its dialKit that refuses off the public server. */
689
+ export const conformance = () => import("./conformance/render.js");
690
+ /**
691
+ * Computers that are Render Sandboxes, on the shared adapter, each dialing the server that made it: a server with no
692
+ * public https address (AGENTRUN_PUBLIC_URL) refuses a create in words before Render is called. Kind linux.
693
+ */
694
+ export class RenderProvider extends HostedProvider {
695
+ /**
696
+ * The provider contract's prepareImage (its descriptor declares it): the box image as a build of the workspace's
697
+ * default sandbox group (RenderHost.boxBuild), found or imported. ok with the build's name; onWait is told "build"
698
+ * once, before an import, never when the workspace has one.
699
+ */
700
+ async prepareImage(context = {}) {
701
+ const name = boxBuildName();
702
+ try {
703
+ return ok(await this.host.boxBuild(() => context.onWait?.("build", name), context.signal));
704
+ }
705
+ catch (error) {
706
+ return fail(codeOfError(this.host, error), `the box image as the Render build ${name}: ${error instanceof Error ? error.message : String(error)}`);
707
+ }
708
+ }
709
+ constructor(options) {
710
+ const { apiKey, ownerId, fetch: fetcher = globalThis.fetch, timeouts = {}, ...rest } = options ?? {};
711
+ if (typeof apiKey !== "string" || apiKey === "")
712
+ throw new Error("options.apiKey, a Render API key, is required: the provider reads no environment, so the caller passes it");
713
+ if (typeof ownerId !== "string" || !OWNER_ID.test(ownerId))
714
+ throw new Error(`options.ownerId is the Render workspace its sandboxes live in (tea-… for a team, usr-… for a person), not ${JSON.stringify(ownerId)}`);
715
+ if (typeof fetcher !== "function")
716
+ throw new Error("options.fetch must be a function, as the global fetch is");
717
+ super(new RenderHost({ apiKey, ownerId, fetch: fetcher, pollMs: timeoutsOf(timeouts).pollMs }), { ...rest, timeouts });
718
+ }
719
+ }