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

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 (83) hide show
  1. package/README.md +243 -9
  2. package/box/README.md +8 -0
  3. package/box/install.sh +60 -6
  4. package/dist/boxd.js +43 -8
  5. package/dist/computerd-linux-amd64 +0 -0
  6. package/dist/computerd-linux-arm64 +0 -0
  7. package/dist/computerd.json +1 -1
  8. package/dist/conformance/cli.d.ts +6 -0
  9. package/dist/conformance/cli.js +14 -3
  10. package/dist/conformance/instabox.d.ts +36 -0
  11. package/dist/conformance/instabox.js +43 -0
  12. package/dist/conformance/northflank.d.ts +44 -0
  13. package/dist/conformance/northflank.js +50 -0
  14. package/dist/conformance/sprites.d.ts +32 -0
  15. package/dist/conformance/sprites.js +40 -0
  16. package/dist/conformance/vercel.d.ts +35 -0
  17. package/dist/conformance/vercel.js +43 -0
  18. package/dist/descriptor.d.ts +6 -0
  19. package/dist/descriptor.js +2 -0
  20. package/dist/descriptors/agent37.d.ts +1 -0
  21. package/dist/descriptors/agent37.js +2 -0
  22. package/dist/descriptors/daytona.d.ts +1 -0
  23. package/dist/descriptors/daytona.js +2 -0
  24. package/dist/descriptors/e2b.d.ts +14 -0
  25. package/dist/descriptors/e2b.js +20 -3
  26. package/dist/descriptors/fly.d.ts +1 -0
  27. package/dist/descriptors/fly.js +2 -0
  28. package/dist/descriptors/groundbox.d.ts +1 -0
  29. package/dist/descriptors/groundbox.js +2 -0
  30. package/dist/descriptors/index.d.ts +106 -1
  31. package/dist/descriptors/index.js +8 -2
  32. package/dist/descriptors/instabox.d.ts +20 -0
  33. package/dist/descriptors/instabox.js +22 -0
  34. package/dist/descriptors/modal.d.ts +1 -0
  35. package/dist/descriptors/modal.js +2 -0
  36. package/dist/descriptors/northflank.d.ts +24 -0
  37. package/dist/descriptors/northflank.js +30 -0
  38. package/dist/descriptors/orgo.d.ts +1 -0
  39. package/dist/descriptors/orgo.js +2 -0
  40. package/dist/descriptors/render.d.ts +1 -0
  41. package/dist/descriptors/render.js +2 -0
  42. package/dist/descriptors/sprites.d.ts +19 -0
  43. package/dist/descriptors/sprites.js +19 -0
  44. package/dist/descriptors/vercel.d.ts +23 -0
  45. package/dist/descriptors/vercel.js +24 -0
  46. package/dist/docker/egress-main.js +17 -10
  47. package/dist/docker/egress-proxy.d.ts +7 -0
  48. package/dist/docker/egress-proxy.js +12 -0
  49. package/dist/docker/egress.d.ts +3 -1
  50. package/dist/docker/egress.js +11 -4
  51. package/dist/docker/image.d.ts +8 -2
  52. package/dist/docker/image.js +24 -3
  53. package/dist/docker.d.ts +6 -0
  54. package/dist/docker.js +15 -5
  55. package/dist/e2b.d.ts +25 -10
  56. package/dist/e2b.js +36 -16
  57. package/dist/groundbox.js +15 -2
  58. package/dist/hosted/download.d.ts +16 -0
  59. package/dist/hosted/download.js +108 -2
  60. package/dist/hosted/provider.js +25 -12
  61. package/dist/hosted/rest.js +23 -1
  62. package/dist/hosted/scripts.d.ts +2 -0
  63. package/dist/hosted/scripts.js +29 -0
  64. package/dist/hosted/ssh-exec.d.ts +17 -2
  65. package/dist/hosted/ssh-exec.js +17 -6
  66. package/dist/index.d.ts +2 -1
  67. package/dist/index.js +2 -1
  68. package/dist/instabox.d.ts +30 -0
  69. package/dist/instabox.js +424 -0
  70. package/dist/northflank.d.ts +44 -0
  71. package/dist/northflank.js +448 -0
  72. package/dist/orgo-desktop.js +2 -2
  73. package/dist/orgo-names.d.ts +15 -1
  74. package/dist/orgo-names.js +13 -0
  75. package/dist/orgo.d.ts +10 -0
  76. package/dist/orgo.js +64 -4
  77. package/dist/providers.d.ts +10 -4
  78. package/dist/render.js +4 -3
  79. package/dist/sprites.d.ts +37 -0
  80. package/dist/sprites.js +309 -0
  81. package/dist/vercel.d.ts +26 -0
  82. package/dist/vercel.js +262 -0
  83. package/package.json +22 -2
@@ -1,4 +1,4 @@
1
- import type { DialKit, RunFolder } from "./conformance/types.js";
1
+ import type { Clock, DialKit, RunFolder } from "./conformance/types.js";
2
2
  import type { ProviderDescriptor } from "./descriptor.js";
3
3
  import { DESCRIPTORS } from "./descriptors/index.js";
4
4
  import type { MachineHost } from "./host.js";
@@ -9,9 +9,9 @@ export type ProviderEnv = Readonly<Record<string, string | undefined>>;
9
9
  /**
10
10
  * What a conformance module exports, the CLI's contract for a module given by path too: createProvider(), and optionally
11
11
  * createDriftedProvider() for the drift case, conformanceImage() for a run that names no image, conformanceNotes for
12
- * the report, mountFor() for the mount cases, dialKit() for a dial host, and settingsFromEnv(env), the provider's options it reads from the
13
- * environment by its COMPUTER_<ID>_* names, with ENV, those names by role. The CLI passes each function its options,
14
- * which a module may ignore.
12
+ * the report, conformanceClock for a host that keeps its own time, mountFor() for the mount cases, dialKit() for a dial
13
+ * host, and settingsFromEnv(env), the provider's options it reads from the environment by its COMPUTER_<ID>_* names,
14
+ * with ENV, those names by role. The CLI passes each function its options, which a module may ignore.
15
15
  */
16
16
  export interface ConformanceModule {
17
17
  createProvider(options?: object): ComputerProvider | Promise<ComputerProvider>;
@@ -23,6 +23,12 @@ export interface ConformanceModule {
23
23
  signal?: AbortSignal;
24
24
  }): string | Promise<string>;
25
25
  conformanceNotes?: string[];
26
+ /**
27
+ * The clock the run reads and waits on, where the provider's timers run on one other than the wall clock (a fake
28
+ * host's): the deadline case then waits on it rather than in real time. It reads no earlier than the clock the
29
+ * provider stamps a computer's deadline with. Without it, the wall clock: a vendor's provider exports none.
30
+ */
31
+ conformanceClock?: Clock;
26
32
  /** For a host whose machines dial (facts.connect "dial"): the server they dial, for provider.dial-token. */
27
33
  dialKit?(options?: object): DialKit | Promise<DialKit>;
28
34
  /**
package/dist/render.js CHANGED
@@ -514,9 +514,10 @@ class RenderHost {
514
514
  /**
515
515
  * GET /v1/sandboxes?ownerId (S, list-sandboxes: terminated ones left out unless asked), every page by its last item's
516
516
  * cursor while a page is full. Render filters by an exact name alone, and a sandbox's name carries its run and epoch
517
- * beside the adapter's: a listing that asks all three (wholeName, as a create's sweeps for the sandbox it made do) asks
518
- * Render for that name, and the name's labels hold all three, so no file is read; any other is matched here, over
519
- * every page (MAX_PAGES at most, then it fails). Only sandboxes named as computers whose name may carry the
517
+ * beside the adapter's: a listing that asks all three (wholeName, as a create's sweeps for the sandbox it made and its
518
+ * first look after its POST do) asks Render for that name, and the name's labels hold all three, so no file is read;
519
+ * any other is matched here, over every page (MAX_PAGES at most, then it fails): a create's first check and the
520
+ * convergence that settles it, so a create reads the workspace's pages twice. Only sandboxes named as computers whose name may carry the
520
521
  * labels asked (mayCarry: the adapter's name, the run's hash and the epoch); a label asked that is not the name's is
521
522
  * read from each running one's labels file (#labelsOf), LABEL_READS at once, all within this call's own bound, and only
522
523
  * those that carry every label asked are answered. A file that can't be read by then fails the listing closed, once
@@ -0,0 +1,37 @@
1
+ import { HostedProvider, type HostedOptions } from "./hosted/provider.js";
2
+ /** The parts of a WebSocket the host uses: Node's global WebSocket, or a stand-in in tests. */
3
+ export interface SpritesSocket {
4
+ binaryType: string;
5
+ /** 0 connecting, 1 open, 2 closing, 3 closed. */
6
+ readonly readyState: number;
7
+ /** Bytes sent and not yet on the wire: a write waits while it is high. */
8
+ readonly bufferedAmount: number;
9
+ send(data: Uint8Array): void;
10
+ close(code?: number): void;
11
+ addEventListener(type: "open" | "message" | "close" | "error", listener: (event: {
12
+ data?: unknown;
13
+ code?: number;
14
+ message?: string;
15
+ }) => void): void;
16
+ }
17
+ export type SpritesSocketFactory = (url: string, init: {
18
+ headers: Record<string, string>;
19
+ }) => SpritesSocket;
20
+ /** The Sprites provider's options: the token, then the shared adapter's (HostedOptions). */
21
+ export interface SpritesProviderOptions extends Omit<HostedOptions, "kind" | "desktop"> {
22
+ /** A Sprites API token. The caller passes it; this provider never reads it from the environment. */
23
+ token: string;
24
+ /** The API's root; default https://api.sprites.dev. */
25
+ apiUrl?: string;
26
+ /** The fetch every REST call goes through; default the global one. */
27
+ fetch?: typeof fetch;
28
+ /** For tests: every exec socket opens through it. Default Node's global WebSocket. */
29
+ webSocket?: SpritesSocketFactory;
30
+ }
31
+ export declare function create(options: SpritesProviderOptions): Promise<SpritesProvider>;
32
+ export declare const conformance: () => Promise<typeof import("./conformance/sprites.js")>;
33
+ export declare const DEFAULT_API_URL = "https://api.sprites.dev";
34
+ /** Computers that are sprites, on the shared adapter: a sandbox from Fly's own image ("default"), no desktop. */
35
+ export declare class SpritesProvider extends HostedProvider {
36
+ constructor(options: SpritesProviderOptions);
37
+ }
@@ -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
+ }