@parcha/agentrun-computer 0.1.0-beta.67 → 0.1.0-beta.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +189 -7
  2. package/box/install.sh +22 -6
  3. package/dist/computerd-linux-amd64 +0 -0
  4. package/dist/computerd-linux-arm64 +0 -0
  5. package/dist/computerd.json +1 -1
  6. package/dist/conformance/instabox.d.ts +36 -0
  7. package/dist/conformance/instabox.js +43 -0
  8. package/dist/conformance/sprites.d.ts +32 -0
  9. package/dist/conformance/sprites.js +40 -0
  10. package/dist/conformance/vercel.d.ts +35 -0
  11. package/dist/conformance/vercel.js +43 -0
  12. package/dist/descriptors/e2b.d.ts +13 -0
  13. package/dist/descriptors/e2b.js +18 -3
  14. package/dist/descriptors/index.d.ts +73 -1
  15. package/dist/descriptors/index.js +7 -2
  16. package/dist/descriptors/instabox.d.ts +19 -0
  17. package/dist/descriptors/instabox.js +20 -0
  18. package/dist/descriptors/sprites.d.ts +19 -0
  19. package/dist/descriptors/sprites.js +19 -0
  20. package/dist/descriptors/vercel.d.ts +23 -0
  21. package/dist/descriptors/vercel.js +24 -0
  22. package/dist/docker/egress-main.js +17 -10
  23. package/dist/docker/egress-proxy.d.ts +7 -0
  24. package/dist/docker/egress-proxy.js +12 -0
  25. package/dist/docker/egress.d.ts +3 -1
  26. package/dist/docker/egress.js +11 -4
  27. package/dist/docker/image.d.ts +8 -2
  28. package/dist/docker/image.js +24 -3
  29. package/dist/docker.d.ts +6 -0
  30. package/dist/docker.js +15 -5
  31. package/dist/e2b.d.ts +25 -10
  32. package/dist/e2b.js +36 -16
  33. package/dist/hosted/provider.js +14 -8
  34. package/dist/hosted/rest.js +23 -1
  35. package/dist/hosted/ssh-exec.d.ts +17 -2
  36. package/dist/hosted/ssh-exec.js +17 -6
  37. package/dist/index.d.ts +2 -1
  38. package/dist/index.js +2 -1
  39. package/dist/instabox.d.ts +30 -0
  40. package/dist/instabox.js +424 -0
  41. package/dist/render.js +4 -3
  42. package/dist/sprites.d.ts +37 -0
  43. package/dist/sprites.js +309 -0
  44. package/dist/vercel.d.ts +26 -0
  45. package/dist/vercel.js +262 -0
  46. package/package.json +17 -2
@@ -0,0 +1,309 @@
1
+ // The Fly Sprites host: a Linux sandbox on a sprite, a Firecracker microVM Fly keeps by name, over the Sprites API
2
+ // (https://api.sprites.dev, a Bearer token). Sources: D = docs.sprites.dev (the API reference, its OpenAPI and AsyncAPI
3
+ // files), S = superfly/sprites-js, Fly's own client. A sprite's name is the request's, so the machine's id is its name.
4
+ // Its labels are a list of `name=value` strings (S CreateSpriteRequest), so the adapter packs the map into it. The exec
5
+ // is the exec WebSocket (D exec), its binary frames read and written as they are, never the SDK's text helpers: framedExec's
6
+ // pieces. A sprite has no timer of its own, so the janitor ends it by its deadline label.
7
+ //
8
+ // Unverified until the live run: the arch (amd64); a label string's room (64 bytes, as Fly Machines' metadata); a
9
+ // create of a name the account holds answers 409 (read as exists); delete is done once its 204 answers (the adapter
10
+ // reads it back gone either way); no vendor agent listens on TCP (Fly's in the VM answers on a unix socket); the exec
11
+ // socket stays open through 75 s of silence with no ping of ours (Node's WebSocket sends none); a sprite with an exec
12
+ // running never sleeps; the exec user is root or has passwordless sudo.
13
+ import { SPRITES, SPRITES_IMAGE } from "./descriptors/sprites.js";
14
+ import { HostError } from "./host.js";
15
+ import { framedExec } from "./hosted/framed-exec.js";
16
+ import { orThrow, pause } from "./hosted/process.js";
17
+ import { HostedProvider } from "./hosted/provider.js";
18
+ import { allPages, httpsBase, jsonOf, rest } from "./hosted/rest.js";
19
+ import { dateOf } from "./hosted/values.js";
20
+ import { ok } from "./result.js";
21
+ export async function create(options) {
22
+ return new SpritesProvider(options);
23
+ }
24
+ export const conformance = () => import("./conformance/sprites.js");
25
+ export const DEFAULT_API_URL = "https://api.sprites.dev";
26
+ /** Every computer's name starts with this (MachineRequest.name), so a listing asks for computers alone. */
27
+ const NAME_PREFIX = "computer-";
28
+ const DAY_MS = 24 * 60 * 60_000;
29
+ /** A sprite lives until it is deleted (D lifecycle), so the cap is the janitor's convention. */
30
+ const MAX_LIFETIME_MS = 30 * DAY_MS;
31
+ const CALL_MS = 30_000;
32
+ /** A listing's page, the most D allows. */
33
+ const PAGE = 500;
34
+ /** A stdin frame's bytes, and the socket's backlog a write waits under. */
35
+ const STDIN_BYTES = 64 * 1024;
36
+ const BACKLOG_BYTES = 1024 * 1024;
37
+ /** How long Fly lets a command run on after its socket is gone (D exec, a Go duration): the bridge's reader is gone too. */
38
+ const AFTER_DISCONNECT = "10s";
39
+ /** The exec socket's frames (D exec): the first byte names the stream. */
40
+ const FRAME = { stdin: 0, stdout: 1, stderr: 2, exit: 3, eof: 4 };
41
+ /**
42
+ * The output a command may have waiting, read off its socket and not yet taken: at it the exec ends. The socket has
43
+ * no flow control and Fly keeps no position to read on from, so a reader that stops would otherwise make this process
44
+ * hold all of it. framedExec takes output as fast as its caller reads; the most the adapter or the bench reads in one
45
+ * go is a file through exec (10 MiB, under 14 MiB as base64), so 64 MiB is several times that and still a bound.
46
+ */
47
+ const QUEUE_BYTES = 64 * 1024 * 1024;
48
+ /** Fly's statuses: cold and warm are a sprite asleep, which the next exec wakes. */
49
+ const STATES = { running: "running", warm: "running", cold: "running" };
50
+ /** `name=value` strings as a map; a string with no `=` is none of ours. */
51
+ const labelsOf = (strings = []) => Object.fromEntries(strings.filter((one) => one.includes("=")).map((one) => [one.slice(0, one.indexOf("=")), one.slice(one.indexOf("=") + 1)]));
52
+ function machineOf(sprite) {
53
+ const state = STATES[sprite.status ?? ""];
54
+ const created = dateOf(sprite.created_at);
55
+ return {
56
+ id: sprite.name,
57
+ labels: labelsOf(sprite.labels),
58
+ // One Fly reads in a status this host doesn't know is listed, so the janitor still ends it.
59
+ state: state ?? "stopped",
60
+ ...(state === undefined ? { why: `Fly reads its status as ${sprite.status ?? "none"}` } : {}),
61
+ ...(created ? { createdAt: created } : {}),
62
+ };
63
+ }
64
+ class SpritesHost {
65
+ descriptor = SPRITES;
66
+ facts = { daemon: "child", isolation: "microvm", lifetime: "janitor", maxLifetimeMs: MAX_LIFETIME_MS, arch: "amd64", vendorAgentPorts: [], labels: { packed: { valueBytes: 52 } } };
67
+ #api;
68
+ #token;
69
+ #wsUrl;
70
+ #webSocket;
71
+ constructor(options) {
72
+ this.#token = options.token;
73
+ this.#wsUrl = options.apiUrl.replace(/^https/, "wss");
74
+ this.#webSocket = options.webSocket;
75
+ this.#api = rest({
76
+ base: options.apiUrl,
77
+ headers: () => ({ Authorization: `Bearer ${this.#token}`, Accept: "application/json" }),
78
+ vendor: "sprites",
79
+ ...(options.fetch ? { fetch: options.fetch } : {}),
80
+ timeoutMs: CALL_MS,
81
+ retry: { attempts: 3, baseMs: 500 },
82
+ // The error body is {error: <code>, message} (D errors); a rate or a concurrency cap is a limit whatever its status.
83
+ explain: ({ status, bytes, what }) => {
84
+ const body = jsonOf(bytes);
85
+ const words = [body?.error, body?.message].filter((part) => typeof part === "string" && part !== "").join(": ");
86
+ const limit = body?.error === "sprite_creation_rate_limited" || body?.error === "concurrent_sprite_limit_exceeded";
87
+ return { ...(limit ? { code: "limit" } : {}), message: `${what} answered ${status}${words ? `: ${words}` : ""}` };
88
+ },
89
+ });
90
+ }
91
+ async #call(method, path, query, ctx, init = {}) {
92
+ const search = new URLSearchParams(query).toString();
93
+ const answer = orThrow(await this.#api.call(method, `${this.#api.url(path)}${search ? `?${search}` : ""}`, { timeoutMs: ctx.timeoutMs, ...init }, ctx.signal));
94
+ return { status: answer.status, body: jsonOf(answer.bytes) };
95
+ }
96
+ /** POST /v1/sprites: the request's name and its labels as `name=value` strings. Fly answers at once, the name the id. */
97
+ async create(req, ctx) {
98
+ const labels = Object.entries(req.labels).map(([name, value]) => `${name}=${value}`);
99
+ await this.#call("POST", "/v1/sprites", {}, ctx, { json: { name: req.name, labels }, named: true });
100
+ return { id: req.name };
101
+ }
102
+ /** GET /v1/sprites/{name}; a 404 is none. */
103
+ async get(id, ctx) {
104
+ const read = await this.#call("GET", `/v1/sprites/${encodeURIComponent(id)}`, {}, ctx, { retry: true, accept: (status) => status === 404 || (status >= 200 && status < 300) });
105
+ return read.status === 404 ? undefined : machineOf(read.body);
106
+ }
107
+ /**
108
+ * GET /v1/sprites by the computers' name prefix, every page; then the asked labels, here, since Fly filters by none. One
109
+ * listed with no labels is kept: the adapter reads each by get and keeps those that carry them.
110
+ */
111
+ async list(labels, ctx) {
112
+ const page = async (cursor) => {
113
+ const { body } = await this.#call("GET", "/v1/sprites", { prefix: NAME_PREFIX, max_results: String(PAGE), ...(cursor ? { continuation_token: cursor } : {}) }, ctx, { retry: true });
114
+ const read = body;
115
+ return ok({ items: read.sprites ?? [], ...(read.has_more && read.next_continuation_token ? { next: read.next_continuation_token } : {}) });
116
+ };
117
+ const asked = Object.entries(labels);
118
+ return orThrow(await allPages(page, 100, { vendor: "sprites", what: "GET /v1/sprites" }))
119
+ .filter((sprite) => sprite.name.startsWith(NAME_PREFIX))
120
+ .map(machineOf)
121
+ .filter((machine) => Object.keys(machine.labels).length === 0 || asked.every(([name, value]) => machine.labels[name] === value));
122
+ }
123
+ /** DELETE /v1/sprites/{name}; one Fly no longer has is done. The adapter reads it back gone. */
124
+ async delete(id, ctx) {
125
+ await this.#call("DELETE", `/v1/sprites/${encodeURIComponent(id)}`, {}, ctx, { retry: true, accept: (status) => status === 404 || (status >= 200 && status < 300) });
126
+ }
127
+ exec(id, argv, ctx) {
128
+ return framedExec({
129
+ start: (words, ctx) => this.#open(id, words, ctx),
130
+ events: (exec) => this.#events(exec),
131
+ write: async (exec, text) => {
132
+ const bytes = Buffer.from(text, "utf8");
133
+ for (let at = 0; at < bytes.length; at += STDIN_BYTES) {
134
+ if (exec.socket.readyState !== 1)
135
+ throw new Error("the exec socket is closed");
136
+ exec.socket.send(framed(FRAME.stdin, bytes.subarray(at, at + STDIN_BYTES)));
137
+ while (exec.socket.bufferedAmount > BACKLOG_BYTES && exec.socket.readyState === 1)
138
+ await pause(5);
139
+ }
140
+ },
141
+ end: async (exec) => {
142
+ if (exec.socket.readyState === 1)
143
+ exec.socket.send(framed(FRAME.eof));
144
+ },
145
+ // The session's kill call (D exec kill), SIGKILL, by the id Fly's session_info named; then the socket closes. A kill
146
+ // that comes after the open and before session_info waits for it (at most CALL_MS): closing alone would leave the
147
+ // command to run on for AFTER_DISCONNECT.
148
+ kill: async (exec) => {
149
+ try {
150
+ if (exec.session === undefined)
151
+ await settledWithin(exec.named, CALL_MS);
152
+ if (exec.session !== undefined)
153
+ await this.#call("POST", `/v1/sprites/${encodeURIComponent(id)}/exec/${encodeURIComponent(exec.session)}/kill`, { signal: "SIGKILL" }, { timeoutMs: CALL_MS });
154
+ }
155
+ finally {
156
+ exec.socket.close(1000);
157
+ }
158
+ },
159
+ }, argv, ctx);
160
+ }
161
+ /**
162
+ * Opens the exec socket: argv as its cmd words, argv[0] its path, stdin on, and a short run after a disconnect. Answers
163
+ * once it is open. One that never opens says whether the sprite is there: a refused upgrade's status never reaches a
164
+ * WebSocket client.
165
+ */
166
+ async #open(id, argv, ctx) {
167
+ const url = new URL(`${this.#wsUrl}/v1/sprites/${encodeURIComponent(id)}/exec`);
168
+ for (const word of argv)
169
+ url.searchParams.append("cmd", word);
170
+ url.searchParams.set("path", argv[0] ?? "");
171
+ url.searchParams.set("stdin", "true");
172
+ url.searchParams.set("max_run_after_disconnect", AFTER_DISCONNECT);
173
+ const socket = this.#webSocket(url.href, { headers: { Authorization: `Bearer ${this.#token}` } });
174
+ socket.binaryType = "arraybuffer";
175
+ let named;
176
+ const exec = { socket, queue: [], queued: 0, closed: false, named: new Promise((done) => (named = done)), wake: () => { } };
177
+ const push = (event, bytes = 0) => {
178
+ if (exec.closed)
179
+ return;
180
+ exec.queue.push(event);
181
+ exec.queued += bytes;
182
+ if (exec.queued >= QUEUE_BYTES) {
183
+ // What is waiting goes, and the events end in this error once framedExec next reads them.
184
+ exec.failure ??= new Error(`the command's output not read passed ${QUEUE_BYTES / 1024 / 1024} MiB, so the exec ended: its reader stopped reading`);
185
+ exec.queue.length = 0;
186
+ exec.queued = 0;
187
+ exec.closed = true;
188
+ socket.close(1000);
189
+ }
190
+ exec.wake();
191
+ };
192
+ let opened;
193
+ const open = new Promise((done) => (opened = done));
194
+ socket.addEventListener("open", () => opened());
195
+ socket.addEventListener("message", ({ data }) => {
196
+ if (typeof data === "string") {
197
+ const message = jsonOf(Buffer.from(data));
198
+ if (message?.type === "session_info" && (typeof message.session_id === "string" || typeof message.session_id === "number")) {
199
+ exec.session = String(message.session_id);
200
+ named();
201
+ }
202
+ else if (message?.type === "exit" && typeof message.exit_code === "number")
203
+ push({ exit: message.exit_code });
204
+ return;
205
+ }
206
+ const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : undefined;
207
+ if (bytes === undefined || bytes.length === 0)
208
+ return;
209
+ const payload = Buffer.from(bytes.buffer, bytes.byteOffset + 1, bytes.length - 1);
210
+ if (bytes[0] === FRAME.stdout || bytes[0] === FRAME.stderr)
211
+ push({ stream: bytes[0] === FRAME.stdout ? "stdout" : "stderr", base64: payload.toString("base64") }, payload.length);
212
+ else if (bytes[0] === FRAME.exit)
213
+ push({ exit: payload[0] ?? 0 });
214
+ });
215
+ socket.addEventListener("error", (event) => {
216
+ exec.failure ??= new Error(`the exec socket failed${event.message ? `: ${event.message}` : ""}`);
217
+ opened(exec.failure);
218
+ });
219
+ socket.addEventListener("close", ({ code }) => {
220
+ exec.closed = true;
221
+ opened(new Error(`the exec socket closed before it opened (code ${code ?? "none"})`));
222
+ named();
223
+ exec.wake();
224
+ });
225
+ // The bound's timer and abort listener both go once the start settles: a long-lived signal keeps no listener per exec.
226
+ let timer;
227
+ let onAbort;
228
+ const bound = new Promise((done) => {
229
+ timer = setTimeout(() => done(new HostError("timeout", `the exec socket of ${id} did not open within ${Math.round(ctx.timeoutMs / 1000)} s`)), ctx.timeoutMs);
230
+ onAbort = () => done(new HostError("aborted", `the exec socket of ${id} was aborted`));
231
+ if (ctx.signal?.aborted)
232
+ onAbort();
233
+ else
234
+ ctx.signal?.addEventListener("abort", onAbort, { once: true });
235
+ });
236
+ const failed = await Promise.race([open, bound]).finally(() => {
237
+ clearTimeout(timer);
238
+ if (onAbort)
239
+ ctx.signal?.removeEventListener("abort", onAbort);
240
+ });
241
+ if (failed === undefined)
242
+ return exec;
243
+ socket.close(1000);
244
+ if (failed instanceof HostError)
245
+ throw failed;
246
+ if ((await this.get(id, { timeoutMs: CALL_MS })) === undefined)
247
+ throw new HostError("not_found", `no sprite ${id}`);
248
+ throw new HostError("vendor", `${failed.message} (sprite ${id})`);
249
+ }
250
+ /** The command's events as the socket gives them, until its exit or the socket's close; the socket closes after. */
251
+ async *#events(exec) {
252
+ try {
253
+ for (;;) {
254
+ const event = exec.queue.shift();
255
+ if (event !== undefined) {
256
+ if ("base64" in event)
257
+ exec.queued -= Buffer.byteLength(event.base64, "base64");
258
+ yield event;
259
+ if ("exit" in event)
260
+ return;
261
+ continue;
262
+ }
263
+ if (exec.closed) {
264
+ if (exec.failure)
265
+ throw exec.failure;
266
+ return;
267
+ }
268
+ await new Promise((done) => (exec.wake = done));
269
+ }
270
+ }
271
+ finally {
272
+ if (exec.socket.readyState < 2)
273
+ exec.socket.close(1000);
274
+ }
275
+ }
276
+ /** A sprite has Fly's own size and image: a spec that names another is refused. */
277
+ check(spec) {
278
+ const refusals = ["cpus", "memoryMb"].filter((field) => spec[field] !== undefined).map((field) => ({ field, message: `a sprite's size is Fly's own: leave out ${field}` }));
279
+ if (spec.image !== undefined && spec.image !== SPRITES_IMAGE)
280
+ refusals.push({ field: "image", message: `a sprite starts from Fly's own Ubuntu image alone, "${SPRITES_IMAGE}"` });
281
+ return refusals;
282
+ }
283
+ }
284
+ /** Waits for a promise to settle, or for ms, whichever comes first; the timer goes either way. */
285
+ async function settledWithin(promise, ms) {
286
+ let timer;
287
+ await Promise.race([promise, new Promise((done) => (timer = setTimeout(done, ms)))]).finally(() => clearTimeout(timer));
288
+ }
289
+ /** One exec frame: its stream's byte, then the bytes. */
290
+ function framed(stream, bytes = new Uint8Array()) {
291
+ const frame = new Uint8Array(bytes.length + 1);
292
+ frame[0] = stream;
293
+ frame.set(bytes, 1);
294
+ return frame;
295
+ }
296
+ /** Computers that are sprites, on the shared adapter: a sandbox from Fly's own image ("default"), no desktop. */
297
+ export class SpritesProvider extends HostedProvider {
298
+ constructor(options) {
299
+ const { token, apiUrl = DEFAULT_API_URL, fetch, webSocket, maxLifetimeMs = MAX_LIFETIME_MS, ...rest } = options ?? {};
300
+ if (typeof token !== "string" || token === "")
301
+ throw new Error("options.token, a Sprites API token, is required: the provider reads no environment, so the caller passes it");
302
+ super(new SpritesHost({
303
+ token,
304
+ apiUrl: httpsBase(apiUrl, "the Sprites API URL"),
305
+ ...(fetch ? { fetch } : {}),
306
+ webSocket: webSocket ?? ((url, init) => new WebSocket(url, init)),
307
+ }), { ...rest, maxLifetimeMs });
308
+ }
309
+ }
@@ -0,0 +1,26 @@
1
+ import { HostedProvider, type HostedOptions } from "./hosted/provider.js";
2
+ import { type Result } from "./result.js";
3
+ /** The Vercel provider's options: the token, the team and the project, then the shared adapter's (HostedOptions). */
4
+ export interface VercelProviderOptions extends Omit<HostedOptions, "kind" | "desktop"> {
5
+ /** A Vercel access token of the team. The caller passes it; this provider never reads it from the environment. */
6
+ token: string;
7
+ /** The team the sandboxes bill to (team_...): every call names it. */
8
+ teamId: string;
9
+ /** The project the sandboxes and the box image live in (prj_...). */
10
+ projectId: string;
11
+ /** The fetch every call goes through; default the global one. */
12
+ fetch?: typeof fetch;
13
+ }
14
+ export declare function create(options: VercelProviderOptions): Promise<VercelProvider>;
15
+ export declare const conformance: () => Promise<typeof import("./conformance/vercel.js")>;
16
+ /** The box image as the operator pushes it to the project's registry (PROVIDERS.md, "Your image"): a tag of its recipe. */
17
+ export declare const boxVercelImage: () => string;
18
+ export declare class VercelProvider extends HostedProvider {
19
+ /**
20
+ * The provider contract's prepareImage (its descriptor declares it): the box image as the project's registry holds it,
21
+ * agentrun-box:<recipe hash>, pushed once by the operator (PROVIDERS.md, "Your image"). No call: Vercel resolves the
22
+ * tag at each create, and a project without it refuses the create in words that say how to push it.
23
+ */
24
+ prepareImage(): Promise<Result<string>>;
25
+ constructor(options: VercelProviderOptions);
26
+ }
package/dist/vercel.js ADDED
@@ -0,0 +1,262 @@
1
+ // The Vercel Sandbox host: a Linux sandbox on a Firecracker microVM, over Vercel's REST API (a Bearer token, the team
2
+ // as ?teamId=, the project in each call). Sources: D = vercel.com/docs/sandbox, S = @vercel/sandbox 5.0.0, Vercel's own
3
+ // client, whose calls this host makes. A sandbox's native name is the request's, so the machine's id is its name. Made
4
+ // with persistent false (D persistent-sandboxes), it has the one session create starts, which every command and the
5
+ // timer go through. The exec is a detached command (S runCommand): its NDJSON log stream, stdin by offset, and a kill,
6
+ // as framedExec's pieces. Tags are 5 at most (D tags), so the labels are packed.
7
+ //
8
+ // Unverified until the live run: root makes a network namespace in the microVM; the log stream keeps a character
9
+ // written in two pieces whole and stays open through 75 s of silence; a create whose name the project holds answers
10
+ // 409 (read as exists); a sandbox's end is its session's start plus its timeout; no vendor agent listens on TCP.
11
+ import { boxRecipeHash } from "./box-image.js";
12
+ import { VERCEL } from "./descriptors/vercel.js";
13
+ import { DEFAULT_CPUS } from "./drift.js";
14
+ import { HostError } from "./host.js";
15
+ import { framedExec } from "./hosted/framed-exec.js";
16
+ import { orThrow, pause } from "./hosted/process.js";
17
+ import { HostedProvider } from "./hosted/provider.js";
18
+ import { allPages, jsonOf, ndjson, rest } from "./hosted/rest.js";
19
+ import { dateOf } from "./hosted/values.js";
20
+ import { ok } from "./result.js";
21
+ export async function create(options) {
22
+ return new VercelProvider(options);
23
+ }
24
+ export const conformance = () => import("./conformance/vercel.js");
25
+ const API_URL = "https://api.vercel.com";
26
+ /** Every computer's name starts with this (MachineRequest.name), so a listing asks for the project's computers alone. */
27
+ const NAME_PREFIX = "computer-";
28
+ /** A session's longest life on Pro and Enterprise (D pricing, runtime limits); Hobby's is 45 minutes. */
29
+ const DAY_MS = 24 * 60 * 60_000;
30
+ /** A stdin write's bytes: the SDK's own chunk (S, 512 KiB), its base64 under the API's 1 MB body. */
31
+ const STDIN_BYTES = 512 * 1024;
32
+ const CALL_MS = 30_000;
33
+ /** Reads of a command's output that fail running, after which it is read no more: a control plane down that long is down. */
34
+ const READ_TRIES = 10;
35
+ /** The box image as the operator pushes it to the project's registry (PROVIDERS.md, "Your image"): a tag of its recipe. */
36
+ export const boxVercelImage = () => `agentrun-box:${boxRecipeHash()}`;
37
+ /** A registry reference (D images, "Image references"): [vcr.vercel.com/][team/project/]repository[:tag|@sha256:digest];
38
+ * a team slug has no dot, so another registry's host (ghcr.io/...) is not read as a team. */
39
+ const IMAGE = /^(vcr\.vercel\.com\/)?([a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(:[A-Za-z0-9_][A-Za-z0-9._-]{0,127}|@sha256:[0-9a-f]{64})?$/;
40
+ /** Vercel's statuses (S Session status) as the adapter's: a sandbox made non-persistent never runs again once it stops. */
41
+ const STATES = { pending: "starting", running: "running", stopping: "gone", snapshotting: "gone", stopped: "gone", failed: "gone", aborted: "gone" };
42
+ function machineOf(sandbox, session) {
43
+ const state = STATES[sandbox.status];
44
+ const created = dateOf(sandbox.createdAt);
45
+ const started = session?.startedAt ?? session?.requestedAt;
46
+ return {
47
+ id: sandbox.name,
48
+ labels: { ...(sandbox.tags ?? {}) },
49
+ // One Vercel reads in a status this host doesn't know is listed, so the janitor still ends it.
50
+ state: state ?? "stopped",
51
+ ...(state === undefined ? { why: `Vercel reads its status as ${sandbox.status}` } : state === "gone" && session?.stopReason ? { why: session.stopReason } : {}),
52
+ ...(created ? { createdAt: created } : {}),
53
+ ...(started !== undefined && session ? { endsAt: new Date(started + session.timeout) } : {}),
54
+ };
55
+ }
56
+ class VercelHost {
57
+ descriptor = VERCEL;
58
+ // VCR serves Sandbox a linux/amd64 build alone (D images). Unverified: no page names a listener of Vercel's in the VM
59
+ // (the exec pre-check prints them). 5 tags, a value 256 characters at most (D tags): the packed map's.
60
+ facts = { daemon: "child", isolation: "microvm", lifetime: "vendor", maxLifetimeMs: DAY_MS, arch: "amd64", vendorAgentPorts: [], labels: { count: 5, packed: { valueBytes: 256 } } };
61
+ #api;
62
+ #query;
63
+ /** Each sandbox's session, as create, get and list read it: persistent false, so it never changes. */
64
+ #sessions = new Map();
65
+ constructor(options) {
66
+ const { token, teamId, projectId } = options;
67
+ this.#query = { teamId, projectId };
68
+ this.#api = rest({
69
+ base: API_URL,
70
+ headers: () => ({ Authorization: `Bearer ${token}`, Accept: "application/json" }),
71
+ vendor: "vercel",
72
+ ...(options.fetch ? { fetch: options.fetch } : {}),
73
+ timeoutMs: CALL_MS,
74
+ retry: { attempts: 3, baseMs: 500 },
75
+ // The error body is {error: {code, message}} (S base-client ErrorResponseBody). An image VCR is still preparing
76
+ // answers image_not_ready (D images): a wait, not a refusal.
77
+ explain: ({ status, bytes, what }) => {
78
+ const error = jsonOf(bytes)?.error;
79
+ const words = [error?.code, error?.message].filter((part) => typeof part === "string" && part !== "").join(": ");
80
+ return { ...(error?.code === "image_not_ready" ? { code: "timeout" } : {}), message: `${what} answered ${status}${words ? `: ${words}` : ""}` };
81
+ },
82
+ });
83
+ }
84
+ async #call(method, path, query, ctx, init = {}) {
85
+ const url = `${this.#api.url(path)}?${new URLSearchParams({ teamId: this.#query.teamId, ...query })}`;
86
+ return jsonOf(orThrow(await this.#api.call(method, url, { timeoutMs: ctx.timeoutMs, ...init }, ctx.signal)).bytes);
87
+ }
88
+ #read(sandbox, session) {
89
+ this.#sessions.set(sandbox.name, sandbox.currentSessionId);
90
+ return machineOf(sandbox, session);
91
+ }
92
+ /**
93
+ * POST /v3/sandboxes (S createSandbox): the request's name, the image, the lifetime as the session's timeout,
94
+ * persistent false, the size, the packed labels as tags, and the vendor's deny-all where the machine needs no egress
95
+ * (D firewall: optional hardening under init's fence). Vercel answers once the session runs. A 429 alone is sent again;
96
+ * a create that got no answer may have made the sandbox, which the adapter finds by its name.
97
+ */
98
+ async create(req, ctx) {
99
+ const { projectId } = this.#query;
100
+ const body = { projectId, name: req.name, image: req.image, timeout: req.lifetimeMs, persistent: false, ports: [], resources: { vcpus: req.cpus ?? DEFAULT_CPUS }, tags: req.labels, ...(req.egress ? {} : { networkPolicy: { mode: "deny-all" } }) };
101
+ try {
102
+ const made = await this.#call("POST", "/v3/sandboxes", {}, ctx, { json: body, named: true, retry: (status) => status === 429 });
103
+ this.#read(made.sandbox);
104
+ }
105
+ catch (error) {
106
+ // D images: a reference the project can't reach answers not_found.
107
+ if (!(error instanceof HostError) || error.code !== "not_found")
108
+ throw error;
109
+ throw new HostError("invalid", `${error.message}: is the image ${req.image} in the project's registry? The box image is pushed once with \`vercel vcr build docker . ${boxVercelImage()} --push\` in box/`);
110
+ }
111
+ return { id: req.name };
112
+ }
113
+ /** GET /v2/sandboxes/{name} with resume=false, which never wakes it (S getSandbox); a 404 is none. */
114
+ async get(id, ctx) {
115
+ const read = await this.#call("GET", `/v2/sandboxes/${encodeURIComponent(id)}`, { projectId: this.#query.projectId, resume: "false" }, ctx, { retry: true });
116
+ return this.#read(read.sandbox, read.session);
117
+ }
118
+ /** GET /v2/sandboxes, every page: the project's computers by name prefix, and by the one tag where one is asked (S filters by one). */
119
+ async list(labels, ctx) {
120
+ const tag = Object.entries(labels);
121
+ const query = { project: this.#query.projectId, namePrefix: NAME_PREFIX, ...(tag.length === 1 ? { tags: `${tag[0]?.[0]}:${tag[0]?.[1]}` } : {}) };
122
+ const page = async (cursor) => {
123
+ const read = await this.#call("GET", "/v2/sandboxes", { ...query, ...(cursor ? { cursor } : {}) }, ctx, { retry: true });
124
+ return ok({ items: read.sandboxes, ...(read.pagination?.next ? { next: read.pagination.next } : {}) });
125
+ };
126
+ return orThrow(await allPages(page, 100, { vendor: "vercel", what: "GET /v2/sandboxes" })).map((sandbox) => this.#read(sandbox));
127
+ }
128
+ /** DELETE /v2/sandboxes/{name}, which stops a running one first; one Vercel no longer has is done. */
129
+ async delete(id, ctx) {
130
+ await this.#call("DELETE", `/v2/sandboxes/${encodeURIComponent(id)}`, { projectId: this.#query.projectId }, ctx, { retry: true, accept: (status) => status === 404 || (status >= 200 && status < 300) });
131
+ this.#sessions.delete(id);
132
+ }
133
+ async #session(id, ctx) {
134
+ if (!this.#sessions.has(id))
135
+ await this.get(id, ctx);
136
+ return this.#sessions.get(id);
137
+ }
138
+ exec(id, argv, ctx) {
139
+ const path = (cmd, rest = "") => `/v2/sandboxes/sessions/${cmd.session}/cmd/${cmd.id}${rest}`;
140
+ /** One stdin call (S writeCommandStdin): with its offset, Vercel skips bytes it has, so it is safe to send again. */
141
+ const stdin = async (cmd, json, bytes = 0) => {
142
+ await this.#call("POST", path(cmd, "/stdin"), {}, { timeoutMs: CALL_MS }, { json: { ...json, offset: cmd.offset }, retry: true });
143
+ cmd.offset += bytes;
144
+ };
145
+ return framedExec({
146
+ // As root through sudo, argv as its words (no shell line), stdin attached (S runCommand, detached).
147
+ start: async ([command, ...args], ctx) => {
148
+ const session = await this.#session(id, ctx);
149
+ const started = await this.#call("POST", `/v2/sandboxes/sessions/${session}/cmd`, {}, ctx, { json: { command, args, sudo: true, attachStdin: true } });
150
+ return { session, id: started.command.id, offset: 0, killed: new AbortController() };
151
+ },
152
+ events: (cmd) => this.#events(cmd, path(cmd)),
153
+ write: async (cmd, text) => {
154
+ const bytes = Buffer.from(text, "utf8");
155
+ for (let at = 0; at < bytes.length; at += STDIN_BYTES) {
156
+ const part = bytes.subarray(at, at + STDIN_BYTES);
157
+ await stdin(cmd, { data: part.toString("base64") }, part.length);
158
+ }
159
+ },
160
+ end: (cmd) => stdin(cmd, { close: true }),
161
+ kill: async (cmd) => {
162
+ cmd.killed.abort();
163
+ await this.#call("POST", path(cmd, "/kill"), {}, { timeoutMs: CALL_MS }, { json: { signal: 9 } });
164
+ },
165
+ }, argv, ctx);
166
+ }
167
+ /**
168
+ * A command's output (GET .../logs, NDJSON {stream, data} lines, as text), then its exit code (GET the command:
169
+ * exitCode once it ended). A stream that ends or drops while the command runs is read again: Vercel answers it from
170
+ * the start, so the characters already given each stream are skipped (S getLogsStream). A stream can end before the
171
+ * command's last write, so once the command read finds it exited the logs are read once more before the exit. An
172
+ * `error` line is the command's end in Vercel's words (the sandbox stopped); READ_TRIES failed reads in a row end it too.
173
+ */
174
+ async *#events(cmd, path) {
175
+ const given = { stdout: 0, stderr: 0 };
176
+ const ctx = { timeoutMs: CALL_MS, signal: cmd.killed.signal };
177
+ let exit;
178
+ for (let failed = 0;;) {
179
+ try {
180
+ const skip = { ...given };
181
+ const { body } = orThrow(await this.#api.stream("GET", `${this.#api.url(`${path}/logs`)}?teamId=${encodeURIComponent(this.#query.teamId)}`, { timeoutMs: CALL_MS }, ctx.signal));
182
+ for await (const line of ndjson(body)) {
183
+ if (line.stream === "error")
184
+ throw new HostError("gone", `Vercel ended command ${cmd.id}'s output: ${[line.data.code, line.data.message].filter(Boolean).join(": ")}`);
185
+ const cut = Math.min(skip[line.stream], line.data.length);
186
+ skip[line.stream] -= cut;
187
+ const text = line.data.slice(cut);
188
+ if (text === "")
189
+ continue;
190
+ given[line.stream] += text.length;
191
+ yield { stream: line.stream, text };
192
+ }
193
+ if (exit !== undefined)
194
+ return yield { exit };
195
+ const { command } = await this.#call("GET", path, {}, ctx, { retry: true });
196
+ failed = 0;
197
+ if (typeof command.exitCode === "number") {
198
+ exit = command.exitCode;
199
+ continue;
200
+ }
201
+ }
202
+ catch (error) {
203
+ if (cmd.killed.signal.aborted)
204
+ return;
205
+ if ((error instanceof HostError && error.code === "gone") || ++failed >= READ_TRIES)
206
+ throw error;
207
+ }
208
+ await pause(1_000, cmd.killed.signal);
209
+ }
210
+ }
211
+ /**
212
+ * Moves the session's end by the difference (POST .../extend-timeout, S extendTimeout); never earlier. Past the plan's
213
+ * cap (D pricing: 45 minutes on Hobby, 24 hours on Pro) Vercel refuses, a limit.
214
+ */
215
+ async extend(id, endsAt, ctx) {
216
+ const now = (await this.get(id, ctx))?.endsAt;
217
+ const duration = endsAt.getTime() - (now?.getTime() ?? endsAt.getTime());
218
+ if (duration <= 0)
219
+ return;
220
+ try {
221
+ await this.#call("POST", `/v2/sandboxes/sessions/${await this.#session(id, ctx)}/extend-timeout`, {}, ctx, { json: { duration } });
222
+ }
223
+ catch (error) {
224
+ if (!(error instanceof HostError) || error.code !== "invalid")
225
+ throw error;
226
+ throw new HostError("limit", `Vercel moves a sandbox's end no further: ${error.message}`);
227
+ }
228
+ }
229
+ /** An image is a registry reference; a size is 1 or an even 2 to 8 vCPUs, with 2048 MiB a vCPU and no other memory (S sandbox.ts). */
230
+ check(spec) {
231
+ const refusals = [];
232
+ const { image, cpus, memoryMb } = spec;
233
+ if (typeof image === "string" && !IMAGE.test(image))
234
+ refusals.push({ field: "image", message: `a Vercel image is a Vercel Container Registry reference: ${boxVercelImage()} in the project, or team/project/repository:tag` });
235
+ if (cpus !== undefined && !(cpus === 1 || (typeof cpus === "number" && Number.isInteger(cpus) && cpus >= 2 && cpus <= 8 && cpus % 2 === 0)))
236
+ refusals.push({ field: "cpus", message: "a Vercel sandbox has 1, 2, 4, 6 or 8 vCPUs" });
237
+ const fixed = 2048 * (typeof cpus === "number" ? cpus : DEFAULT_CPUS);
238
+ if (memoryMb !== undefined && memoryMb !== fixed)
239
+ refusals.push({ field: "memoryMb", message: `a Vercel sandbox has 2048 MiB a vCPU, so ${fixed} here: name cpus, not memoryMb` });
240
+ return refusals;
241
+ }
242
+ }
243
+ export class VercelProvider extends HostedProvider {
244
+ /**
245
+ * The provider contract's prepareImage (its descriptor declares it): the box image as the project's registry holds it,
246
+ * agentrun-box:<recipe hash>, pushed once by the operator (PROVIDERS.md, "Your image"). No call: Vercel resolves the
247
+ * tag at each create, and a project without it refuses the create in words that say how to push it.
248
+ */
249
+ async prepareImage() {
250
+ return ok(boxVercelImage());
251
+ }
252
+ constructor(options) {
253
+ const { token, teamId, projectId, fetch, maxLifetimeMs = DAY_MS, ...rest } = options ?? {};
254
+ if (typeof token !== "string" || token === "")
255
+ throw new Error("options.token, a Vercel access token, is required: the provider reads no environment, so the caller passes it");
256
+ for (const [name, value] of [["teamId", teamId], ["projectId", projectId]]) {
257
+ if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value))
258
+ throw new Error(`options.${name} is required: the Vercel ${name === "teamId" ? "team" : "project"} id, such as ${name === "teamId" ? "team_abc123" : "prj_abc123"}`);
259
+ }
260
+ super(new VercelHost({ token, teamId, projectId, ...(fetch ? { fetch } : {}) }), { ...rest, maxLifetimeMs });
261
+ }
262
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-computer",
3
- "version": "0.1.0-beta.67",
3
+ "version": "0.1.0-beta.68",
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",
@@ -10,7 +10,10 @@
10
10
  "daytona",
11
11
  "boxd",
12
12
  "smolcloud",
13
- "groundbox"
13
+ "groundbox",
14
+ "vercel",
15
+ "sprites",
16
+ "instabox"
14
17
  ],
15
18
  "type": "module",
16
19
  "license": "Apache-2.0",
@@ -81,6 +84,18 @@
81
84
  "types": "./dist/groundbox.d.ts",
82
85
  "default": "./dist/groundbox.js"
83
86
  },
87
+ "./vercel": {
88
+ "types": "./dist/vercel.d.ts",
89
+ "default": "./dist/vercel.js"
90
+ },
91
+ "./sprites": {
92
+ "types": "./dist/sprites.d.ts",
93
+ "default": "./dist/sprites.js"
94
+ },
95
+ "./instabox": {
96
+ "types": "./dist/instabox.d.ts",
97
+ "default": "./dist/instabox.js"
98
+ },
84
99
  "./orgo": {
85
100
  "types": "./dist/orgo.d.ts",
86
101
  "default": "./dist/orgo.js"