@parcha/agentrun-computer 0.1.0-beta.60 → 0.1.0-beta.62
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/README.md +54 -10
- package/dist/browser.d.ts +30 -3
- package/dist/browser.js +126 -6
- package/dist/browserbase.d.ts +4 -1
- package/dist/browserbase.js +45 -31
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/computerd.json +1 -1
- package/dist/conformance/render.d.ts +50 -0
- package/dist/conformance/render.js +55 -0
- package/dist/descriptors/index.d.ts +21 -1
- package/dist/descriptors/index.js +3 -2
- package/dist/descriptors/render.d.ts +20 -0
- package/dist/descriptors/render.js +31 -0
- package/dist/host.d.ts +4 -1
- package/dist/hosted/provider.d.ts +3 -1
- package/dist/hosted/provider.js +30 -7
- package/dist/hosted/rest.d.ts +6 -0
- package/dist/hosted/rest.js +11 -2
- package/dist/hosted/values.d.ts +2 -0
- package/dist/hosted/values.js +4 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -0
- package/dist/kernel.js +28 -16
- package/dist/modal.js +3 -1
- package/dist/orgo-workspaces.d.ts +2 -1
- package/dist/orgo-workspaces.js +5 -2
- package/dist/render.d.ts +34 -0
- package/dist/render.js +509 -0
- package/package.json +5 -1
package/dist/render.js
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
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>) gives the adapter's own two, and create writes
|
|
13
|
+
// every label to a file in the sandbox, root's alone, which get and list read back through runs/sync where a label asked
|
|
14
|
+
// is not the name's, and keep: a computer's labels never change (Render moves no timeout, so there is no extend).
|
|
15
|
+
//
|
|
16
|
+
// Every vendor fact below is from @renderinc/sdk 1.11.0's OpenAPI schema (dist/generated/schema.d.ts, S) or its client
|
|
17
|
+
// (dist/sandboxes/index.js, C), a live probe (11-25: root, HOME=/root, a Render kernel, egress https, and a command
|
|
18
|
+
// started under setsid by runs/sync living on after the call), or the live Core run (11-25, packages/serve/scripts/
|
|
19
|
+
// dial-conformance.mjs: the sandbox's env reaches a runs/sync command, root makes network namespaces in the microVM, the
|
|
20
|
+
// builds API imports the public ghcr.io box image with no credential, and a process escaped with setsid ends with the
|
|
21
|
+
// sandbox's release). One none of these settles says unverified.
|
|
22
|
+
import { boxImageRef, boxRecipeHash } from "./box-image.js";
|
|
23
|
+
import { RENDER } from "./descriptors/render.js";
|
|
24
|
+
import { COMPUTER_LABEL, DEFAULT_CPUS, DEFAULT_MEMORY_MB, show } from "./drift.js";
|
|
25
|
+
import { HostError } from "./host.js";
|
|
26
|
+
import { codeOfError, orThrow, pause, seconds, until } from "./hosted/process.js";
|
|
27
|
+
import { HostedProvider, mayHaveMade, NAME_LABEL, timeoutsOf } from "./hosted/provider.js";
|
|
28
|
+
import { allPages, jsonOf, rest } from "./hosted/rest.js";
|
|
29
|
+
import { dialLaunch } from "./hosted/scripts.js";
|
|
30
|
+
import { dateOf, isWhole } from "./hosted/values.js";
|
|
31
|
+
import { failFor, ok, vendorFail } from "./result.js";
|
|
32
|
+
const API_URL = "https://api.render.com";
|
|
33
|
+
/**
|
|
34
|
+
* S: ownerId, a workspace id (tea-… for a team, usr-… for a person). Held to an id's characters alone, since it goes in
|
|
35
|
+
* every query: whether it names a workspace the key reaches is Render's answer to the first call.
|
|
36
|
+
*/
|
|
37
|
+
const OWNER_ID = /^[A-Za-z0-9_-]{1,64}$/;
|
|
38
|
+
/** S: sandboxId, "sbx-1cd4gcph1rs3idesc73a2b2mg"; held to that form before it reaches a path. */
|
|
39
|
+
const SANDBOX_ID = /^sbx-[a-z0-9]{10,40}$/;
|
|
40
|
+
/** S: sandboxBuildId, sbb-…; a build's name may not start with sbb- (S, sandbox-groups/{id}/builds), so this reads as an id. */
|
|
41
|
+
const BUILD_ID = /^sbb-[a-z0-9]{10,40}$/;
|
|
42
|
+
/** A build's name, 1 to 255 characters (S); held to letters, digits, dots, underscores and hyphens, so an OCI path is not one. */
|
|
43
|
+
const BUILD_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
|
|
44
|
+
/** The name the adapter gives a computer (provider.ts computerName): only a sandbox named so is one of its computers. */
|
|
45
|
+
const COMPUTER_NAME = /^computer-[0-9a-f]{12}$/;
|
|
46
|
+
/** S, sandboxPlan: the sizes a sandbox takes, smallest first. */
|
|
47
|
+
const PLANS = [
|
|
48
|
+
{ plan: "1c-2g", cpus: 1, memoryMb: 2048 },
|
|
49
|
+
{ plan: "2c-4g", cpus: 2, memoryMb: 4096 },
|
|
50
|
+
{ plan: "4c-8g", cpus: 4, memoryMb: 8192 },
|
|
51
|
+
{ plan: "8c-16g", cpus: 8, memoryMb: 16_384 },
|
|
52
|
+
];
|
|
53
|
+
/** S, timeoutSeconds: 0 (none) or 60 to 2592000; the sandbox ends when it elapses. */
|
|
54
|
+
const LEAST_TIMEOUT_S = 60;
|
|
55
|
+
/** 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. */
|
|
56
|
+
const MAX_LIFETIME_MS = 24 * 60 * 60_000;
|
|
57
|
+
/** One page of a listing (S, limitParam: 1 to 100). */
|
|
58
|
+
const PAGE = 100;
|
|
59
|
+
const MAX_PAGES = 100;
|
|
60
|
+
/** 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). */
|
|
61
|
+
const BUILD_MS = 30 * 60_000;
|
|
62
|
+
/** How long a failed create's terminate of the sandbox it made may take: create's own bound may be spent by then. */
|
|
63
|
+
const TERMINATE_MS = 30_000;
|
|
64
|
+
/** S, 429RateLimit: a 429 is sent again after 1, 2 and 4 s. */
|
|
65
|
+
const RETRY = { attempts: 4, baseMs: 1_000 };
|
|
66
|
+
/** A file read's exit when the file is not there. */
|
|
67
|
+
const MISSING = 3;
|
|
68
|
+
/** Where create leaves the computer's labels, root's alone (its directory 0700, umask 077). */
|
|
69
|
+
const LABELS_DIR = "/var/lib/agentrun-computer";
|
|
70
|
+
const LABELS_FILE = `${LABELS_DIR}/labels.json`;
|
|
71
|
+
/** agentrun-dial's launch script (dialLaunch's line), its output and its exit code, root's alone. */
|
|
72
|
+
const DIAL_DIR = "/run/agentrun-dial";
|
|
73
|
+
const DIAL_SCRIPT = `${DIAL_DIR}/launch`;
|
|
74
|
+
const DIAL_LOG = `${DIAL_DIR}/log`;
|
|
75
|
+
const DIAL_EXIT = `${DIAL_DIR}/exit`;
|
|
76
|
+
/** How much of agentrun-dial's log dialLog reads: its end. */
|
|
77
|
+
const LOG_BYTES = 65_536;
|
|
78
|
+
/** A file written whole: base64 through printf, to <path>.new, then moved over <path>. */
|
|
79
|
+
const writeFile = (path, text) => `printf %s '${Buffer.from(text, "utf8").toString("base64")}' | base64 -d > ${path}.new && mv -f ${path}.new ${path}`;
|
|
80
|
+
/** A file read: exits MISSING when it is not there. */
|
|
81
|
+
const readFile = (path, read = "cat") => `[ -f ${path} ] || exit ${MISSING}; ${read} ${path}`;
|
|
82
|
+
/**
|
|
83
|
+
* agentrun-dial's start from its launch script, detached: a session of its own (setsid), no hangup, stdin closed, its
|
|
84
|
+
* output to DIAL_LOG and its exit code to DIAL_EXIT once it ends, so the runs/sync call returns at once.
|
|
85
|
+
*/
|
|
86
|
+
const START = `rm -f ${DIAL_EXIT} && { setsid nohup sh -c 'sh ${DIAL_SCRIPT}; echo $? > ${DIAL_EXIT}' > ${DIAL_LOG} 2>&1 < /dev/null & }`;
|
|
87
|
+
/** create's one run: the labels file, the launch script with the attach URL (the token stays in the env), the start. */
|
|
88
|
+
function launchLine(labels, attach) {
|
|
89
|
+
return ["umask 077", `mkdir -p ${LABELS_DIR} ${DIAL_DIR}`, writeFile(LABELS_FILE, JSON.stringify(labels)), writeFile(DIAL_SCRIPT, dialLaunch({ attach })), START].join(" && ");
|
|
90
|
+
}
|
|
91
|
+
/** The smallest plan holding the size asked; none asked, the adapter's default of 2 CPUs and 4 GiB. */
|
|
92
|
+
function planOf(cpus, memoryMb) {
|
|
93
|
+
const want = cpus === undefined && memoryMb === undefined ? { cpus: DEFAULT_CPUS, memoryMb: DEFAULT_MEMORY_MB } : { cpus: cpus ?? 0, memoryMb: memoryMb ?? 0 };
|
|
94
|
+
return PLANS.find((one) => one.cpus >= want.cpus && one.memoryMb >= want.memoryMb)?.plan;
|
|
95
|
+
}
|
|
96
|
+
/** What a plan gives, as its name says it (Nc-Mg); none for another. */
|
|
97
|
+
function resourcesOf(plan) {
|
|
98
|
+
const sized = /^(\d+)c-(\d+)g$/.exec(plan ?? "");
|
|
99
|
+
return sized ? { resources: { cpus: Number(sized[1]), memoryMb: Number(sized[2]) * 1024 } } : {};
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Render's statuses (S, sandboxStatus) as the adapter's: creating and resuming are starting, suspending and suspended
|
|
103
|
+
* stopped (listed, so a release still ends them), errored gone. terminated is a sandbox that is no more: null, as get and
|
|
104
|
+
* list answer none for it.
|
|
105
|
+
*/
|
|
106
|
+
function stateOf(status) {
|
|
107
|
+
if (status === "running")
|
|
108
|
+
return "running";
|
|
109
|
+
if (status === "creating" || status === "resuming")
|
|
110
|
+
return "starting";
|
|
111
|
+
if (status === "suspending" || status === "suspended")
|
|
112
|
+
return "stopped";
|
|
113
|
+
if (status === "errored")
|
|
114
|
+
return "gone";
|
|
115
|
+
if (status === "terminated")
|
|
116
|
+
return null;
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
/** A sandbox as the adapter reads one, with the labels read for it; undefined for one terminated. */
|
|
120
|
+
function machineOf(found, labels) {
|
|
121
|
+
const state = stateOf(found.status);
|
|
122
|
+
if (state === null)
|
|
123
|
+
return undefined;
|
|
124
|
+
const created = dateOf(found.createdAt);
|
|
125
|
+
const timeout = found.timeoutSeconds;
|
|
126
|
+
const ends = created && isWhole(timeout) && timeout > 0 ? new Date(created.getTime() + timeout * 1000) : undefined;
|
|
127
|
+
const why = state === undefined
|
|
128
|
+
? `Render reads the sandbox's status ${show(found.status)}, which this provider does not know`
|
|
129
|
+
: found.status === "errored"
|
|
130
|
+
? `Render reads the sandbox ${found.id} errored, with no reason given`
|
|
131
|
+
: undefined;
|
|
132
|
+
return {
|
|
133
|
+
id: found.id,
|
|
134
|
+
labels,
|
|
135
|
+
state: state ?? "gone",
|
|
136
|
+
...(created ? { createdAt: created } : {}),
|
|
137
|
+
...(ends ? { endsAt: ends } : {}),
|
|
138
|
+
...(why ? { why } : {}),
|
|
139
|
+
...resourcesOf(found.plan),
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
/** An id held to Render's form before it reaches a path: not_found else. */
|
|
143
|
+
function sandboxId(id) {
|
|
144
|
+
if (!SANDBOX_ID.test(id))
|
|
145
|
+
throw new HostError("not_found", `${JSON.stringify(id)} is not a Render sandbox id`);
|
|
146
|
+
return id;
|
|
147
|
+
}
|
|
148
|
+
/** Render's error body (S, error): { id?, message?, code? }. */
|
|
149
|
+
function explain({ status, bytes, what }) {
|
|
150
|
+
const body = jsonOf(bytes);
|
|
151
|
+
const said = typeof body?.message === "string" && body.message !== "" ? `: ${body.message}` : "";
|
|
152
|
+
return { message: `${what} answered ${status}${said}` };
|
|
153
|
+
}
|
|
154
|
+
/** The last words of a run's output, for a failure: its stderr, else its stdout. */
|
|
155
|
+
const lastWords = ({ stdout, stderr }) => (stderr.trim() || stdout.trim()).slice(-300);
|
|
156
|
+
/** Render Sandboxes as a dial MachineHost (../host.ts): no exec, no upload. */
|
|
157
|
+
class RenderHost {
|
|
158
|
+
descriptor = RENDER;
|
|
159
|
+
facts = {
|
|
160
|
+
// agentrun-dial starts init as its child; nothing is started through exec.
|
|
161
|
+
daemon: "child",
|
|
162
|
+
// The live probe read a kernel of Render's own (uname: 6.18.51-render1+), so each sandbox is a VM of its own.
|
|
163
|
+
isolation: "microvm",
|
|
164
|
+
// Render ends a sandbox at its timeoutSeconds (S), which create sets to the lifetime.
|
|
165
|
+
lifetime: "vendor",
|
|
166
|
+
maxLifetimeMs: MAX_LIFETIME_MS,
|
|
167
|
+
// The box image is built for amd64 alone (release.yml's box job), and the live Core run ran it and its amd64 daemon.
|
|
168
|
+
arch: "amd64",
|
|
169
|
+
// Unverified: the agent that answers runs inside the sandbox listens where S does not say. None declared.
|
|
170
|
+
vendorAgentPorts: [],
|
|
171
|
+
// The sandbox dials the server: Render's runs take no stdin (S: runs/{sync,stream} take { command }), so there is
|
|
172
|
+
// no exec and no upload here. Its descriptor's (connectOf).
|
|
173
|
+
connect: RENDER.connect,
|
|
174
|
+
};
|
|
175
|
+
#api;
|
|
176
|
+
#apiKey;
|
|
177
|
+
#owner;
|
|
178
|
+
#fetch;
|
|
179
|
+
#pollMs;
|
|
180
|
+
/** Each computer's labels once known, by sandbox id: written by create, or read from the labels file once. */
|
|
181
|
+
#labels = new Map();
|
|
182
|
+
/** The box build's name once Render read it succeeded: prepareImage asks no more. */
|
|
183
|
+
#built;
|
|
184
|
+
constructor(options) {
|
|
185
|
+
this.#apiKey = options.apiKey;
|
|
186
|
+
this.#owner = options.ownerId;
|
|
187
|
+
this.#fetch = options.fetch;
|
|
188
|
+
this.#pollMs = options.pollMs;
|
|
189
|
+
this.#api = this.#client(API_URL, () => this.#apiKey);
|
|
190
|
+
}
|
|
191
|
+
/** A REST client whose every call carries `bearer()` as its Bearer token: the API key, or one run's token. */
|
|
192
|
+
#client(base, bearer) {
|
|
193
|
+
return rest({ base, headers: () => ({ Authorization: `Bearer ${bearer()}`, Accept: "application/json" }), vendor: RENDER.id, fetch: this.#fetch, timeoutMs: 30_000, retry: RETRY, explain });
|
|
194
|
+
}
|
|
195
|
+
/** One API call, bounded by ctx: its JSON answer (null for none), or a HostError in Render's words. */
|
|
196
|
+
async #call(method, path, init, ctx) {
|
|
197
|
+
return orThrow(await this.#api.json(method, this.#api.url(path), { ...init, timeoutMs: ctx.timeoutMs }, ctx.signal));
|
|
198
|
+
}
|
|
199
|
+
/** The workspace as a query, which every sandbox call names (C names it on each). */
|
|
200
|
+
#owned(path, query = {}) {
|
|
201
|
+
return `${path}?${new URLSearchParams({ ownerId: this.#owner, ...query })}`;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* One command run in the sandbox: a run token (POST /v1/sandboxes/{id}/runs/sync/token, S: "Send the command to the
|
|
205
|
+
* URL in the response, using the token as the bearer token"), then the command to its URL. `once`: a run that got
|
|
206
|
+
* no answer is never sent again, since it may have run; a read is.
|
|
207
|
+
*/
|
|
208
|
+
async #run(id, command, ctx, once = false) {
|
|
209
|
+
const end = Date.now() + ctx.timeoutMs;
|
|
210
|
+
const minted = (await this.#call("POST", this.#owned(`/v1/sandboxes/${sandboxId(id)}/runs/sync/token`), { retry: true }, ctx));
|
|
211
|
+
const { uri, token } = minted ?? {};
|
|
212
|
+
if (typeof uri !== "string" || !uri.startsWith("https://") || typeof token !== "string" || token === "")
|
|
213
|
+
throw new HostError("vendor", `Render answered no https run URL and token for the sandbox ${id}`);
|
|
214
|
+
const plane = this.#client(new URL(uri).origin, () => token);
|
|
215
|
+
const method = typeof minted?.method === "string" ? minted.method : "POST";
|
|
216
|
+
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));
|
|
217
|
+
if (!isWhole(answer?.exit_code))
|
|
218
|
+
throw new HostError("vendor", `Render's run in ${id} answered no exit code: ${show(answer?.exit_code)}`);
|
|
219
|
+
return { stdout: typeof answer.stdout === "string" ? answer.stdout : "", stderr: typeof answer.stderr === "string" ? answer.stderr : "", exit: answer.exit_code };
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* A sandbox's labels: the ones this host knows, else its name's, else its labels file's, read once through runs/sync
|
|
223
|
+
* 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
|
|
224
|
+
* computer carries none; one not running, or with no file yet, its name's. A read that fails throws, so a listing
|
|
225
|
+
* never answers as though the sandbox were not there.
|
|
226
|
+
*/
|
|
227
|
+
async #labelsOf(found, ctx, need) {
|
|
228
|
+
const name = found.name;
|
|
229
|
+
if (typeof name !== "string" || !COMPUTER_NAME.test(name))
|
|
230
|
+
return {};
|
|
231
|
+
const known = this.#labels.get(found.id);
|
|
232
|
+
if (known !== undefined)
|
|
233
|
+
return known;
|
|
234
|
+
const own = { [COMPUTER_LABEL]: "1", [NAME_LABEL]: name };
|
|
235
|
+
if ((need !== undefined && Object.keys(need).every((key) => key in own)) || found.status !== "running")
|
|
236
|
+
return own;
|
|
237
|
+
const read = await this.#run(found.id, readFile(LABELS_FILE), ctx);
|
|
238
|
+
if (read.exit === MISSING)
|
|
239
|
+
return own;
|
|
240
|
+
if (read.exit !== 0)
|
|
241
|
+
throw new HostError("vendor", `reading the labels file of ${found.id} exited ${read.exit}: ${lastWords(read)}`);
|
|
242
|
+
const parsed = jsonOf(new TextEncoder().encode(read.stdout));
|
|
243
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed) || !Object.values(parsed).every((value) => typeof value === "string")) {
|
|
244
|
+
throw new HostError("vendor", `the labels file of ${found.id} is not a JSON map of strings`);
|
|
245
|
+
}
|
|
246
|
+
const labels = { ...parsed, ...own };
|
|
247
|
+
this.#labels.set(found.id, labels);
|
|
248
|
+
return labels;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Any Render build by its name or id (S: buildName, "the newest successful build with this name in the sandbox
|
|
252
|
+
* group"; buildId), and a size Render's plans hold (S, sandboxPlan). Render's base image ("default", a create that
|
|
253
|
+
* names no build) has no agentrun-dial, so it can't be one.
|
|
254
|
+
*/
|
|
255
|
+
check(spec) {
|
|
256
|
+
const refusals = [];
|
|
257
|
+
const { image, cpus, memoryMb } = spec;
|
|
258
|
+
const most = PLANS[PLANS.length - 1];
|
|
259
|
+
if (typeof image === "string" && !(BUILD_ID.test(image) || (BUILD_NAME.test(image) && image !== "default" && !image.startsWith("sbb-")))) {
|
|
260
|
+
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" });
|
|
261
|
+
}
|
|
262
|
+
if (cpus !== undefined && !(isWhole(cpus) && cpus > 0 && cpus <= most.cpus))
|
|
263
|
+
refusals.push({ field: "cpus", message: `a Render sandbox has at most ${most.cpus} CPUs (plans ${PLANS.map(({ plan }) => plan).join(", ")})` });
|
|
264
|
+
if (memoryMb !== undefined && !(isWhole(memoryMb) && memoryMb > 0 && memoryMb <= most.memoryMb))
|
|
265
|
+
refusals.push({ field: "memoryMb", message: `a Render sandbox has at most ${most.memoryMb} MiB (plans ${PLANS.map(({ plan }) => plan).join(", ")})` });
|
|
266
|
+
return refusals;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* POST /v1/sandboxes (S, sandboxPOST): the workspace, the request's name, the smallest plan holding its size, the
|
|
270
|
+
* lifetime as timeoutSeconds (at least 60), no idle suspension (0), egress allow-all (the sandbox must reach the
|
|
271
|
+
* server; the computer's own programs keep to init's network), the boot env but AGENTRUN_ATTACH_URL as its env, and
|
|
272
|
+
* the build. Only a 429, a refusal that made nothing, is sent again: a create that got no answer may have made a
|
|
273
|
+
* sandbox, which the adapter finds by its name. Then, once the sandbox reads running within ctx.timeoutMs, one
|
|
274
|
+
* runs/sync call writes the labels file and starts agentrun-dial, the URL in its launch script. A sandbox that errors
|
|
275
|
+
* or ends first, a launch that fails, or a bound passed, throws: a create that made a machine to the adapter, which
|
|
276
|
+
* deletes it by its name. A refusal after the sandbox exists (a run token's 429s past every retry, limit; a 401,
|
|
277
|
+
* denied) the adapter reads as a create that made nothing (mayHaveMade), so this terminates the sandbox by its id
|
|
278
|
+
* first and throws the refusal in its own code. req.backstopAt is left: Render's timeout ends the sandbox.
|
|
279
|
+
*/
|
|
280
|
+
async create(req, ctx) {
|
|
281
|
+
const end = Date.now() + ctx.timeoutMs;
|
|
282
|
+
if (req.boot === undefined)
|
|
283
|
+
throw new HostError("invalid", "a Render sandbox dials the server, and the request has no boot env for it");
|
|
284
|
+
const { AGENTRUN_ATTACH_URL: attach, ...env } = req.boot.env;
|
|
285
|
+
if (typeof attach !== "string" || attach === "")
|
|
286
|
+
throw new HostError("invalid", "a Render sandbox dials the server, and the boot env names no AGENTRUN_ATTACH_URL");
|
|
287
|
+
const made = (await this.#call("POST", "/v1/sandboxes", {
|
|
288
|
+
json: {
|
|
289
|
+
ownerId: this.#owner,
|
|
290
|
+
name: req.name,
|
|
291
|
+
plan: planOf(req.cpus, req.memoryMb),
|
|
292
|
+
timeoutSeconds: Math.max(LEAST_TIMEOUT_S, Math.ceil(req.lifetimeMs / 1000)),
|
|
293
|
+
idleTimeoutSeconds: 0,
|
|
294
|
+
networkPolicy: { type: "allow-all" },
|
|
295
|
+
env,
|
|
296
|
+
...(BUILD_ID.test(req.image) ? { buildId: req.image } : { buildName: req.image }),
|
|
297
|
+
},
|
|
298
|
+
retry: (status) => status === 429,
|
|
299
|
+
}, ctx));
|
|
300
|
+
const id = made?.id;
|
|
301
|
+
if (typeof id !== "string" || !SANDBOX_ID.test(id))
|
|
302
|
+
throw new HostError("vendor", `POST /v1/sandboxes answered no sandbox id: ${show(id)}`);
|
|
303
|
+
this.#labels.set(id, { ...req.labels });
|
|
304
|
+
try {
|
|
305
|
+
await this.#untilRunning(made, end, ctx);
|
|
306
|
+
const ran = await this.#run(id, launchLine(req.labels, attach), { ...ctx, timeoutMs: Math.max(1, end - Date.now()) }, true);
|
|
307
|
+
if (ran.exit !== 0)
|
|
308
|
+
throw new HostError("vendor", `starting agentrun-dial in ${id} exited ${ran.exit}: ${lastWords(ran)}`);
|
|
309
|
+
}
|
|
310
|
+
catch (error) {
|
|
311
|
+
if (!(error instanceof HostError) || mayHaveMade(error.code))
|
|
312
|
+
throw error;
|
|
313
|
+
throw await this.#unmade(id, error);
|
|
314
|
+
}
|
|
315
|
+
return { id };
|
|
316
|
+
}
|
|
317
|
+
/** The sandbox a failed create made, terminated by its id: the step's error in its own code, the terminate's outcome added. */
|
|
318
|
+
async #unmade(id, error) {
|
|
319
|
+
let outcome;
|
|
320
|
+
try {
|
|
321
|
+
await this.delete(id, { timeoutMs: TERMINATE_MS });
|
|
322
|
+
outcome = `the sandbox ${id} it made was terminated`;
|
|
323
|
+
}
|
|
324
|
+
catch (failed) {
|
|
325
|
+
outcome =
|
|
326
|
+
failed instanceof HostError && failed.code === "not_found"
|
|
327
|
+
? `the sandbox ${id} it made is gone`
|
|
328
|
+
: `the sandbox ${id} it made could not be terminated (${failed instanceof Error ? failed.message : String(failed)}); Render ends it at its timeout`;
|
|
329
|
+
}
|
|
330
|
+
return new HostError(error.code, `${error.message}; ${outcome}`);
|
|
331
|
+
}
|
|
332
|
+
/** Reads the sandbox until it runs, pollMs apart, by `end`: errored or terminated first throws vendor, the end timeout. */
|
|
333
|
+
async #untilRunning(posted, end, ctx) {
|
|
334
|
+
for (let found = posted; found.status !== "running";) {
|
|
335
|
+
if (found.status === "errored" || found.status === "terminated")
|
|
336
|
+
throw new HostError("vendor", `Render reads the sandbox ${found.id} ${found.status}, so agentrun-dial was not started`);
|
|
337
|
+
if (Date.now() + this.#pollMs >= end)
|
|
338
|
+
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`);
|
|
339
|
+
await pause(this.#pollMs, ctx.signal);
|
|
340
|
+
if (ctx.signal?.aborted)
|
|
341
|
+
throw new HostError("aborted", `the wait for the sandbox ${found.id} to run was aborted`);
|
|
342
|
+
found = (await this.#call("GET", this.#owned(`/v1/sandboxes/${found.id}`), { retry: true }, { ...ctx, timeoutMs: Math.max(1, end - Date.now()) }));
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
/** GET /v1/sandboxes/{id}; 404 is not_found, which the adapter reads as none, and a terminated sandbox is none. */
|
|
346
|
+
async get(id, ctx) {
|
|
347
|
+
const found = (await this.#call("GET", this.#owned(`/v1/sandboxes/${sandboxId(id)}`), { retry: true }, ctx));
|
|
348
|
+
if (typeof found?.status !== "string")
|
|
349
|
+
throw new HostError("vendor", `GET /v1/sandboxes/${id} answered no status`);
|
|
350
|
+
if (found.status === "terminated")
|
|
351
|
+
return undefined;
|
|
352
|
+
return machineOf(found, await this.#labelsOf(found, ctx));
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* GET /v1/sandboxes?ownerId (S, list-sandboxes: terminated ones left out unless asked), by name where the name is
|
|
356
|
+
* asked ("exactly this name"), every page by its last item's cursor while a page is full. Only sandboxes named as
|
|
357
|
+
* computers; a label asked that is not the name's is read from each running one's labels file (#labelsOf), and only
|
|
358
|
+
* those that carry every label asked are answered. A file that can't be read fails the listing in words: a listing
|
|
359
|
+
* that left the sandbox out would read as no such computer.
|
|
360
|
+
*/
|
|
361
|
+
async list(labels, ctx) {
|
|
362
|
+
const name = labels[NAME_LABEL];
|
|
363
|
+
const listed = orThrow(await allPages(async (cursor) => {
|
|
364
|
+
const page = await this.#api.json("GET", this.#api.url(this.#owned("/v1/sandboxes", { limit: String(PAGE), ...(name === undefined ? {} : { name }), ...(cursor === undefined ? {} : { cursor }) })), { retry: true, timeoutMs: ctx.timeoutMs }, ctx.signal);
|
|
365
|
+
if (!page.ok)
|
|
366
|
+
return page;
|
|
367
|
+
if (!Array.isArray(page.value))
|
|
368
|
+
return vendorFail(RENDER.id, "GET /v1/sandboxes answered no list");
|
|
369
|
+
const rows = page.value;
|
|
370
|
+
const items = rows.flatMap((row) => (typeof row?.sandbox?.id === "string" && typeof row.sandbox.status === "string" ? [row.sandbox] : []));
|
|
371
|
+
const last = rows.at(-1)?.cursor;
|
|
372
|
+
return ok({ items, ...(rows.length === PAGE && typeof last === "string" ? { next: last } : {}) });
|
|
373
|
+
}, MAX_PAGES, { vendor: RENDER.id, what: "Render's sandbox listing" }));
|
|
374
|
+
const ours = listed.filter((found) => found.status !== "terminated" && typeof found.name === "string" && COMPUTER_NAME.test(found.name));
|
|
375
|
+
const read = await Promise.all(ours.map(async (found) => {
|
|
376
|
+
const carried = await this.#labelsOf(found, ctx, labels);
|
|
377
|
+
return Object.entries(labels).every(([key, value]) => carried[key] === value) ? machineOf(found, carried) : undefined;
|
|
378
|
+
}));
|
|
379
|
+
return read.flatMap((machine) => machine ?? []);
|
|
380
|
+
}
|
|
381
|
+
/** POST /v1/sandboxes/{id}/terminate (S: 204, also for one already terminated); a 404 is done to the adapter. */
|
|
382
|
+
async delete(id, ctx) {
|
|
383
|
+
await this.#call("POST", this.#owned(`/v1/sandboxes/${sandboxId(id)}/terminate`), { retry: true }, ctx);
|
|
384
|
+
this.#labels.delete(id);
|
|
385
|
+
}
|
|
386
|
+
/** The end of what agentrun-dial wrote, through runs/sync; undefined where it was never started. */
|
|
387
|
+
async dialLog(id, ctx) {
|
|
388
|
+
const read = await this.#run(id, readFile(DIAL_LOG, `tail -c ${LOG_BYTES}`), ctx);
|
|
389
|
+
if (read.exit === MISSING)
|
|
390
|
+
return undefined;
|
|
391
|
+
if (read.exit !== 0)
|
|
392
|
+
throw new HostError("vendor", `reading agentrun-dial's log in ${id} exited ${read.exit}: ${lastWords(read)}`);
|
|
393
|
+
return read.stdout;
|
|
394
|
+
}
|
|
395
|
+
/** agentrun-dial's exit code, which its start writes once it has ended; undefined while it runs, or never started. */
|
|
396
|
+
async dialExit(id, ctx) {
|
|
397
|
+
const read = await this.#run(id, readFile(DIAL_EXIT), ctx);
|
|
398
|
+
if (read.exit === MISSING)
|
|
399
|
+
return undefined;
|
|
400
|
+
if (read.exit !== 0)
|
|
401
|
+
throw new HostError("vendor", `reading agentrun-dial's exit in ${id} exited ${read.exit}: ${lastWords(read)}`);
|
|
402
|
+
const code = read.stdout.trim();
|
|
403
|
+
return /^\d{1,3}$/.test(code) ? Number(code) : undefined;
|
|
404
|
+
}
|
|
405
|
+
/** agentrun-dial started once more from create's launch script (the same attach URL; the token is the sandbox's env still). */
|
|
406
|
+
async redial(id, ctx) {
|
|
407
|
+
const ran = await this.#run(id, `[ -f ${DIAL_SCRIPT} ] || exit ${MISSING}; umask 077 && ${START}`, ctx, true);
|
|
408
|
+
if (ran.exit === MISSING)
|
|
409
|
+
throw new HostError("not_found", `no agentrun-dial was started in the sandbox ${id}, so it is not started again`);
|
|
410
|
+
if (ran.exit !== 0)
|
|
411
|
+
throw new HostError("vendor", `starting agentrun-dial again in ${id} exited ${ran.exit}: ${lastWords(ran)}`);
|
|
412
|
+
}
|
|
413
|
+
/** The workspace's default sandbox group (S, list-sandbox-groups), read a page at a time by cursor until it is found. */
|
|
414
|
+
async #defaultGroup(ctx) {
|
|
415
|
+
const seen = new Set();
|
|
416
|
+
let cursor;
|
|
417
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
418
|
+
const rows = await this.#call("GET", `/v1/sandbox-groups?${new URLSearchParams({ ownerId: this.#owner, limit: String(PAGE), ...(cursor === undefined ? {} : { cursor }) })}`, { retry: true }, ctx);
|
|
419
|
+
if (!Array.isArray(rows))
|
|
420
|
+
throw new HostError("vendor", "GET /v1/sandbox-groups answered no list");
|
|
421
|
+
const listed = rows;
|
|
422
|
+
const group = listed.find((row) => row?.sandboxGroup?.isDefault === true)?.sandboxGroup?.id;
|
|
423
|
+
if (group !== undefined) {
|
|
424
|
+
if (typeof group !== "string" || !/^[a-z0-9-]{1,64}$/.test(group))
|
|
425
|
+
throw new HostError("vendor", `Render answered a default sandbox group whose id is ${show(group)}`);
|
|
426
|
+
return group;
|
|
427
|
+
}
|
|
428
|
+
const next = listed.at(-1)?.cursor;
|
|
429
|
+
if (listed.length < PAGE || typeof next !== "string" || next === "" || seen.has(next))
|
|
430
|
+
break;
|
|
431
|
+
seen.add(next);
|
|
432
|
+
cursor = next;
|
|
433
|
+
}
|
|
434
|
+
throw new HostError("vendor", `Render answered no default sandbox group for the workspace ${this.#owner}`);
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* The box image as a build of the workspace's default sandbox group (the group a create that names none uses, S),
|
|
438
|
+
* named agentrun-box-<recipe hash>, so a new recipe is a new build: a succeeded one of that name is kept (GET
|
|
439
|
+
* …/builds?name&status=succeeded), else POST …/builds { name, sourceImage } imports the box image's public tag (S: "converts
|
|
440
|
+
* a container image into an image that sandboxes can use"), and Render's answer is read until it succeeded or failed.
|
|
441
|
+
* `building` is told before the import. Render pulls the public ghcr.io image with no credential (the live Core run's
|
|
442
|
+
* import took 104 s); a tag the release has not published yet is Render's 400, "source image unavailable".
|
|
443
|
+
*/
|
|
444
|
+
async boxBuild(building, signal) {
|
|
445
|
+
if (this.#built !== undefined)
|
|
446
|
+
return this.#built;
|
|
447
|
+
const name = boxBuildName();
|
|
448
|
+
const ctx = { timeoutMs: 30_000, ...(signal ? { signal } : {}) };
|
|
449
|
+
const group = await this.#defaultGroup(ctx);
|
|
450
|
+
const builds = `/v1/sandbox-groups/${group}/builds`;
|
|
451
|
+
const found = await this.#call("GET", `${builds}?${new URLSearchParams({ name, status: "succeeded", limit: "1" })}`, { retry: true }, ctx);
|
|
452
|
+
if (Array.isArray(found) && found.length > 0)
|
|
453
|
+
return (this.#built = name);
|
|
454
|
+
building();
|
|
455
|
+
let build = (await this.#call("POST", builds, { json: { name, sourceImage: boxImageRef() }, retry: (status) => status === 429 }, ctx));
|
|
456
|
+
const id = build?.id;
|
|
457
|
+
if (typeof id !== "string" || !BUILD_ID.test(id))
|
|
458
|
+
throw new HostError("vendor", `POST ${builds} answered no build id: ${show(id)}`);
|
|
459
|
+
const settled = (one) => {
|
|
460
|
+
if (one?.status === "succeeded")
|
|
461
|
+
return true;
|
|
462
|
+
if (one?.status === "failed")
|
|
463
|
+
throw new HostError("vendor", `Render's build ${id} failed: ${one.failureReason || one.failureCode || "no reason given"}`);
|
|
464
|
+
return undefined;
|
|
465
|
+
};
|
|
466
|
+
if (!settled(build))
|
|
467
|
+
await until(`Render's build ${id}`, { end: Date.now() + BUILD_MS, pollMs: this.#pollMs, signal }, async () => settled((build = (await this.#call("GET", `${builds}/${id}`, { retry: true }, ctx)))));
|
|
468
|
+
return (this.#built = name);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
/** The box image's build name: agentrun-box-<recipe hash>, as the box image's own tag is. */
|
|
472
|
+
const boxBuildName = () => `agentrun-box-${boxRecipeHash()}`;
|
|
473
|
+
const fail = failFor(RENDER.id);
|
|
474
|
+
/** A RenderProvider from its options alone; it reads no environment (serve passes the saved RENDER_API_KEY and RENDER_WORKSPACE_ID). */
|
|
475
|
+
export function create(options) {
|
|
476
|
+
return new RenderProvider(options);
|
|
477
|
+
}
|
|
478
|
+
/** The conformance CLI's module for Render: its settings, and its dialKit that refuses off the public server. */
|
|
479
|
+
export const conformance = () => import("./conformance/render.js");
|
|
480
|
+
/**
|
|
481
|
+
* Computers that are Render Sandboxes, on the shared adapter, each dialing the server that made it: a server with no
|
|
482
|
+
* public https address (AGENTRUN_PUBLIC_URL) refuses a create in words before Render is called. Kind linux.
|
|
483
|
+
*/
|
|
484
|
+
export class RenderProvider extends HostedProvider {
|
|
485
|
+
/**
|
|
486
|
+
* The provider contract's prepareImage (its descriptor declares it): the box image as a build of the workspace's
|
|
487
|
+
* default sandbox group (RenderHost.boxBuild), found or imported. ok with the build's name; onWait is told "build"
|
|
488
|
+
* once, before an import, never when the workspace has one.
|
|
489
|
+
*/
|
|
490
|
+
async prepareImage(context = {}) {
|
|
491
|
+
const name = boxBuildName();
|
|
492
|
+
try {
|
|
493
|
+
return ok(await this.host.boxBuild(() => context.onWait?.("build", name), context.signal));
|
|
494
|
+
}
|
|
495
|
+
catch (error) {
|
|
496
|
+
return fail(codeOfError(this.host, error), `the box image as the Render build ${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
constructor(options) {
|
|
500
|
+
const { apiKey, ownerId, fetch: fetcher = globalThis.fetch, timeouts = {}, ...rest } = options ?? {};
|
|
501
|
+
if (typeof apiKey !== "string" || apiKey === "")
|
|
502
|
+
throw new Error("options.apiKey, a Render API key, is required: the provider reads no environment, so the caller passes it");
|
|
503
|
+
if (typeof ownerId !== "string" || !OWNER_ID.test(ownerId))
|
|
504
|
+
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)}`);
|
|
505
|
+
if (typeof fetcher !== "function")
|
|
506
|
+
throw new Error("options.fetch must be a function, as the global fetch is");
|
|
507
|
+
super(new RenderHost({ apiKey, ownerId, fetch: fetcher, pollMs: timeoutsOf(timeouts).pollMs }), { ...rest, timeouts });
|
|
508
|
+
}
|
|
509
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun-computer",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.62",
|
|
4
4
|
"description": "The open platform's computer protocol: a daemon in every computer, and one provisioner per vendor, starting with Docker.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentrun",
|
|
@@ -57,6 +57,10 @@
|
|
|
57
57
|
"types": "./dist/fly.d.ts",
|
|
58
58
|
"default": "./dist/fly.js"
|
|
59
59
|
},
|
|
60
|
+
"./render": {
|
|
61
|
+
"types": "./dist/render.d.ts",
|
|
62
|
+
"default": "./dist/render.js"
|
|
63
|
+
},
|
|
60
64
|
"./cloudflare": {
|
|
61
65
|
"types": "./dist/cloudflare.d.ts",
|
|
62
66
|
"default": "./dist/cloudflare.js"
|