@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,424 @@
1
+ // The InstaBox host: a Linux sandbox on an InstaBox machine, a Firecracker microVM, over its REST API
2
+ // (https://api.instabox.sh/v1, the key in X-API-Key). Sources: D = the docs (https://instabox.sh/llms-full.txt), O = the
3
+ // OpenAPI (https://api.instabox.sh/v1/openapi.json). A machine is made (an operation, under an Idempotency-Key), read by
4
+ // id, listed by metadata and deleted (with X-Confirm-Delete) over REST. Every command (the daemon's upload, its install,
5
+ // init's start, the stdio bridge) goes over SSH through the shared SshExec (./hosted/ssh-exec.ts) to InstaBox's gateway,
6
+ // logged in with an SSH token the REST API mints per machine (D ssh-tokens: the token is the username, no key needed).
7
+ // The token rides in the username, so the gateway's host key is pinned to the sha256 the token's answer names
8
+ // (hostKeyFingerprint), and a host posing as the gateway reads no token: the pin is required twice, by the token answer's
9
+ // check and by the SshExec (pinned), so a login with no pin opens no connection. The SSH user is the machine's own, `user` (uid
10
+ // 1000), with passwordless sudo (D templates), which the adapter's scripts take for root. The REST exec takes its stdin
11
+ // once and kills at 10 minutes (D exec), so it is not used; the file API writes as the machine's user, not root (D files),
12
+ // so this host has no upload and the daemon goes through exec. The labels are packed into the machine's metadata, whose
13
+ // keys can't hold every label name (O CreateMachineRequest). A machine's delete timer (deleteAfterSeconds, at most a day)
14
+ // is set at create to the request's backstop, and the janitor ends it at its deadline; its idle pause and its maximum run
15
+ // are switched off, which only a paid plan allows.
16
+ //
17
+ // Unverified until the live run: the gateway takes the token as the username with SSH's none auth; its host key is one
18
+ // ssh2 verifies, whose sha256 is hostKeyFingerprint; a create of a name the workspace holds answers 409 (read as exists);
19
+ // a deleted machine reads 404 or a record in state deleted (both none); sshd's port 22 is the vendor's one TCP listener
20
+ // in the machine; the minimal template is on every paid plan; the metadata's 8 KiB is counted on compact JSON; a silent
21
+ // SSH channel stays open through 75 s.
22
+ import { createHash, randomUUID } from "node:crypto";
23
+ import { isIP, connect as tcp } from "node:net";
24
+ import { INSTABOX } from "./descriptors/instabox.js";
25
+ import { show } from "./drift.js";
26
+ import { proxyFor, tunnelThrough } from "./env-proxy.js";
27
+ import { BACKSTOP_MARGIN_MS, HostError } from "./host.js";
28
+ import { boundOf, orThrow, pause } from "./hosted/process.js";
29
+ import { HostedProvider } from "./hosted/provider.js";
30
+ import { allPages, httpsBase, jsonOf, rest } from "./hosted/rest.js";
31
+ import { HOST_KEY_PIN, SshExec, SshTunnelError } from "./hosted/ssh-exec.js";
32
+ import { DOMAIN, dateOf } from "./hosted/values.js";
33
+ import { ok } from "./result.js";
34
+ import { vendorSdk } from "./vendor-sdk.js";
35
+ export const DEFAULT_API_URL = "https://api.instabox.sh";
36
+ const DAY_MS = 24 * 60 * 60_000;
37
+ /** The delete timer's range (O CreateMachineRequest.deleteAfterSeconds: 60 to 86400). */
38
+ const MAX_DELETE_S = 86_400;
39
+ const MIN_DELETE_S = 60;
40
+ /** The longest a computer lives: its backstop, past it by BACKSTOP_MARGIN_MS, is then within InstaBox's day. */
41
+ const MAX_LIFETIME_MS = DAY_MS - BACKSTOP_MARGIN_MS;
42
+ const CALL_MS = 30_000;
43
+ const PAGE = 100;
44
+ /** How long a token works (O CreateSSHTokenRequest: at most 30 days): a day, the most a machine lives. */
45
+ const TOKEN_TTL_S = 86_400;
46
+ /** The pause between two deletes InstaBox refuses while another operation runs on the machine (409 operation_conflict). */
47
+ const BUSY_MS = 1_000;
48
+ /** A machine id (m_ and base32: O Machine.id) as it reaches a URL. */
49
+ const MACHINE_ID = /^m_[a-z0-9]{1,64}$/;
50
+ /** An SSH token (O SSHToken.token: ibssh_ and base32): the username, nothing a shell or ssh2 reads otherwise. */
51
+ const TOKEN = /^ibssh_[a-z0-9]{1,128}$/;
52
+ /** A template id, a snapshot's name, or a snapshot's id (sn_...): what a create's image names (D create). */
53
+ const IMAGE = /^[a-z0-9][a-z0-9_-]{0,62}$/;
54
+ /** The sizes InstaBox offers, each plan a range of them (D sizes): 2 GiB per vCPU. */
55
+ const SIZES = [2, 4, 8, 16, 32];
56
+ const MIB_PER_CPU = 2048;
57
+ /** InstaBox's codes whose meaning is the adapter's code whatever their status (O Error.code). */
58
+ const CODES = {
59
+ rate_limited: "limit",
60
+ quota_exceeded: "limit",
61
+ concurrency_limit: "limit",
62
+ no_capacity: "limit",
63
+ machine_cooldown: "limit",
64
+ template_limit: "limit",
65
+ spec_not_allowed: "refused",
66
+ template_not_allowed: "refused",
67
+ template_job_only: "refused",
68
+ missing_scope: "denied",
69
+ permission_denied: "denied",
70
+ };
71
+ /** InstaBox's states (O MachineState) as the adapter's; deleted is none (get answers undefined), error is gone. */
72
+ const STATES = {
73
+ creating: "starting",
74
+ starting: "starting",
75
+ resuming: "starting",
76
+ running: "running",
77
+ stopping: "stopped",
78
+ stopped: "stopped",
79
+ suspending: "stopped",
80
+ suspended: "stopped",
81
+ deleting: "gone",
82
+ error: "gone",
83
+ };
84
+ /** A machine as the adapter reads it: a running one not ready yet is starting. */
85
+ function machineOf(one) {
86
+ const known = STATES[one.state ?? ""];
87
+ const state = known === "running" && one.runtime?.ready !== true ? "starting" : known;
88
+ const created = dateOf(one.createdAt);
89
+ const { vcpus, memMiB, persistentDiskGiB } = one.spec ?? {};
90
+ const resources = { ...(vcpus ? { cpus: vcpus } : {}), ...(memMiB ? { memoryMb: memMiB } : {}), ...(persistentDiskGiB ? { diskGb: persistentDiskGiB } : {}) };
91
+ const why = known === undefined
92
+ ? `InstaBox reads its state as ${show(one.state)}, which this provider does not know`
93
+ : one.state === "error"
94
+ ? `InstaBox reads it in error: ${[one.lastError?.code, one.lastError?.message].filter(Boolean).join(": ") || "no reason given"}`
95
+ : undefined;
96
+ return {
97
+ id: one.id,
98
+ labels: { ...(one.metadata ?? {}) },
99
+ // One in a state this provider does not know is listed, so the janitor still ends it.
100
+ state: state ?? "stopped",
101
+ ...(created ? { createdAt: created } : {}),
102
+ ...(Object.keys(resources).length > 0 ? { resources } : {}),
103
+ ...(why === undefined ? {} : { why }),
104
+ };
105
+ }
106
+ /** An id held to InstaBox's form before it reaches a URL: not_found else. */
107
+ function machineId(id) {
108
+ if (!MACHINE_ID.test(id))
109
+ throw new HostError("not_found", `${JSON.stringify(id)} is not an InstaBox machine id`);
110
+ return id;
111
+ }
112
+ /** ssh2 names the stage that failed (lib/client.js): the gateway refused the login, or the handshake timed out. */
113
+ function codeOf(error) {
114
+ if (error instanceof HostError)
115
+ return error.code;
116
+ const { level } = (error ?? {});
117
+ if (level === "client-authentication")
118
+ return "denied";
119
+ if (level === "client-timeout")
120
+ return "timeout";
121
+ return "vendor";
122
+ }
123
+ /** The workspace a key reaches, in words: the key named by its sha256 prefix alone. */
124
+ export function accountOf(apiKey, apiUrl = DEFAULT_API_URL) {
125
+ return `the InstaBox workspace of the key sha256:${createHash("sha256").update(apiKey, "utf8").digest("hex").slice(0, 12)} at ${httpsBase(apiUrl, "the InstaBox API URL")}`;
126
+ }
127
+ class InstaboxHost {
128
+ descriptor = INSTABOX;
129
+ facts = {
130
+ daemon: "child",
131
+ // Firecracker (D templates).
132
+ isolation: "microvm",
133
+ lifetime: "janitor",
134
+ maxLifetimeMs: MAX_LIFETIME_MS,
135
+ arch: "amd64",
136
+ // The guest's sshd, behind the gateway (D: systemd, sshd, sudo); its port, and the guest agent's, unverified.
137
+ vendorAgentPorts: [22],
138
+ // O: 32 keys of 1-64 [A-Za-z0-9_.-], values up to 512 characters, 8 KiB as JSON. Compact JSON adds 6 bytes a label
139
+ // and 1 for the braces past the names and values packLabels counts: 7999 + 6 × 32 + 1 = 8192.
140
+ labels: { count: 32, bytes: 7_999, packed: { valueBytes: 512 } },
141
+ };
142
+ #apiKey;
143
+ #apiUrl;
144
+ #fetch;
145
+ #api;
146
+ #ssh;
147
+ /** Each machine's token mint, in flight or done, kept until delete or a refused login. */
148
+ #logins = new Map();
149
+ /** Each machine's minted login, which SshExec's loginOf reads. */
150
+ #held = new Map();
151
+ constructor(options) {
152
+ this.#apiKey = options.apiKey;
153
+ this.#apiUrl = options.apiUrl;
154
+ this.#fetch = options.fetch;
155
+ this.#api = this.#client();
156
+ // The username is the machine's token alone, the gateway's key pinned: the API key never goes over SSH.
157
+ this.#ssh = new SshExec({
158
+ ssh2: options.ssh2,
159
+ pinned: true,
160
+ loginOf: (id) => {
161
+ const login = this.#held.get(id);
162
+ if (login === undefined)
163
+ throw new HostError("denied", `no SSH token for ${id}`);
164
+ return { username: login.token, hostKey: login.fingerprint, secrets: [login.token, this.#apiKey] };
165
+ },
166
+ tunnelOf: (id) => this.#tunnel(id),
167
+ });
168
+ }
169
+ /** The API's client, with headers of one call's own beside the key (a lifecycle call's Idempotency-Key). */
170
+ #client(headers = {}) {
171
+ return rest({
172
+ base: this.#apiUrl,
173
+ headers: () => ({ "X-API-Key": this.#apiKey, Accept: "application/json", ...headers }),
174
+ vendor: INSTABOX.id,
175
+ ...(this.#fetch ? { fetch: this.#fetch } : {}),
176
+ timeoutMs: CALL_MS,
177
+ retry: { attempts: 3, baseMs: 500 },
178
+ // Every refusal's body is {error: {code, message, hint}} (O Error): a code above is the adapter's whatever its status.
179
+ explain: ({ status, bytes, what }) => {
180
+ const error = jsonOf(bytes)?.error;
181
+ const named = typeof error?.code === "string" ? error.code : undefined;
182
+ const code = named === undefined ? undefined : CODES[named];
183
+ const words = [error?.message, error?.hint].filter((part) => typeof part === "string" && part !== "").join(" ");
184
+ const plan = named === "spec_not_allowed" && status === 403 ? " (a computer switches off InstaBox's idle pause and maximum run, which only a paid plan allows)" : "";
185
+ return { ...(code ? { code } : {}), message: `${what} answered ${status}${named ? ` ${named}` : ""}${words ? `: ${words}` : ""}${plan}` };
186
+ },
187
+ });
188
+ }
189
+ async #call(method, path, ctx, init = {}, api = this.#api) {
190
+ const answer = orThrow(await api.call(method, api.url(path), { timeoutMs: ctx.timeoutMs, ...init }, ctx.signal));
191
+ return { status: answer.status, body: jsonOf(answer.bytes) };
192
+ }
193
+ errorCode(error) {
194
+ return codeOf(error);
195
+ }
196
+ /**
197
+ * POST /v1/machines: the request's name, the image as a template or a snapshot (sn_...), the size when the request
198
+ * names one, the packed labels as metadata, the delete timer at the backstop, no idle pause and no maximum run, no
199
+ * vault and no secrets. Its Idempotency-Key is this one request's, so a create sent again on no answer makes no second
200
+ * machine. InstaBox answers an operation at once, with the machine's id; the adapter polls get while it starts.
201
+ */
202
+ async create(req, ctx) {
203
+ const seconds = Math.ceil((Date.parse(req.backstopAt) - Date.now()) / 1000);
204
+ const cpus = req.cpus ?? (req.memoryMb === undefined ? undefined : req.memoryMb / MIB_PER_CPU);
205
+ const body = {
206
+ name: req.name,
207
+ ...(req.image.startsWith("sn_") ? { snapshotId: req.image } : { templateId: req.image }),
208
+ ...(cpus === undefined ? {} : { vcpus: cpus, memMiB: req.memoryMb ?? cpus * MIB_PER_CPU }),
209
+ metadata: req.labels,
210
+ deleteAfterSeconds: Math.min(MAX_DELETE_S, Math.max(MIN_DELETE_S, seconds)),
211
+ autoSuspendAfterSeconds: 0,
212
+ maxRunMinutes: -1,
213
+ vault: false,
214
+ secrets: [],
215
+ };
216
+ const api = this.#client({ "Idempotency-Key": `agentrun-${req.name}-${req.backstopAt}` });
217
+ const { body: made } = await this.#call("POST", "/v1/machines", ctx, { json: body, retry: true, named: true }, api);
218
+ const id = made?.machineId;
219
+ if (typeof id !== "string" || !MACHINE_ID.test(id))
220
+ throw new HostError("vendor", `POST /v1/machines answered no machine id: ${show(id)}`);
221
+ return { id };
222
+ }
223
+ /** GET /v1/machines/{id}; a 404, or a record of a machine deleted, is none. */
224
+ async get(id, ctx) {
225
+ const read = await this.#call("GET", `/v1/machines/${machineId(id)}`, ctx, { retry: true, accept: (status) => status === 404 || (status >= 200 && status < 300) });
226
+ const one = read.body;
227
+ if (read.status === 404 || one?.state === "deleted")
228
+ return undefined;
229
+ if (typeof one?.id !== "string")
230
+ throw new HostError("vendor", `GET /v1/machines/${id} answered no machine`);
231
+ return machineOf(one);
232
+ }
233
+ /**
234
+ * GET /v1/machines with each asked label as a metadata filter (AND), every page; the labels are matched here too, so a
235
+ * listing that answers more is filtered. A record of a machine deleted is left out.
236
+ */
237
+ async list(labels, ctx) {
238
+ const asked = Object.entries(labels);
239
+ const page = async (cursor) => {
240
+ const query = new URLSearchParams([...asked.map(([name, value]) => ["metadata", `${name}:${value}`]), ["limit", String(PAGE)], ...(cursor ? [["cursor", cursor]] : [])]);
241
+ const { body } = await this.#call("GET", `/v1/machines?${query}`, ctx, { retry: true });
242
+ const read = body;
243
+ return ok({ items: read?.machines ?? [], ...(read?.nextCursor ? { next: read.nextCursor } : {}) });
244
+ };
245
+ return orThrow(await allPages(page, 100, { vendor: INSTABOX.id, what: "GET /v1/machines" }))
246
+ .filter((one) => typeof one?.id === "string" && one.state !== "deleted")
247
+ .map(machineOf)
248
+ .filter((machine) => asked.every(([name, value]) => machine.labels[name] === value));
249
+ }
250
+ /**
251
+ * DELETE /v1/machines/{id}, confirmed by its id, each attempt its own Idempotency-Key; a 404 is done. A machine with
252
+ * an operation running (its create's) refuses the delete with 409 operation_conflict, which is sent again, a pause
253
+ * between, within ctx. Then this host's SSH connections to it end and its login goes: InstaBox ends its tokens with it.
254
+ */
255
+ async delete(id, ctx) {
256
+ const end = Date.now() + ctx.timeoutMs;
257
+ try {
258
+ for (;;) {
259
+ const api = this.#client({ "Idempotency-Key": randomUUID(), "X-Confirm-Delete": machineId(id) });
260
+ const accept = (status) => status === 404 || status === 409 || (status >= 200 && status < 300);
261
+ const { status, body } = await this.#call("DELETE", `/v1/machines/${id}`, { ...ctx, timeoutMs: Math.max(1, end - Date.now()) }, { retry: true, accept }, api);
262
+ if (status !== 409)
263
+ return;
264
+ const code = body?.error?.code;
265
+ if (code !== "operation_conflict")
266
+ throw new HostError("vendor", `DELETE /v1/machines/${id} answered 409 ${show(code)}`);
267
+ if (Date.now() + BUSY_MS >= end)
268
+ throw new HostError("timeout", `InstaBox kept refusing the delete of ${id} within ${Math.round(ctx.timeoutMs / 1000)} s: another operation runs on it`);
269
+ await pause(BUSY_MS, ctx.signal);
270
+ }
271
+ }
272
+ finally {
273
+ this.#ssh.closeAll(id);
274
+ this.#forget(id);
275
+ }
276
+ }
277
+ /**
278
+ * argv over SSH through the gateway (hosted/ssh-exec.ts), as the machine's user with sudo. The machine's token is
279
+ * minted first when this host has none for it. A held token the gateway refuses (revoked, or run out) is let go and
280
+ * another minted, once; a fresh one refused is denied. Execs refused on the same token share the one minted in its place.
281
+ * Each step (the wait on the mint, the SSH start, and again on a refusal) has what is left of ctx's time, and its signal.
282
+ */
283
+ async exec(id, argv, ctx) {
284
+ machineId(id);
285
+ const end = Date.now() + ctx.timeoutMs;
286
+ const left = () => ({ ...ctx, timeoutMs: Math.max(1, end - Date.now()) });
287
+ const held = this.#logins.has(id);
288
+ const login = await this.#login(id, left());
289
+ try {
290
+ return await this.#ssh.exec(id, argv, left());
291
+ }
292
+ catch (error) {
293
+ if (codeOf(error) !== "denied")
294
+ throw error;
295
+ this.#forget(id, login);
296
+ if (!held)
297
+ throw error;
298
+ await this.#login(id, left());
299
+ return this.#ssh.exec(id, argv, left());
300
+ }
301
+ }
302
+ /**
303
+ * The machine's login, minted once for all the execs that ask at once. The mint is no one exec's: it runs within its
304
+ * own CALL_MS and no exec's signal, and each exec waits on it within its own time and signal, so one's cancel or bound
305
+ * ends that exec's wait alone.
306
+ */
307
+ async #login(id, ctx) {
308
+ let minting = this.#logins.get(id);
309
+ if (minting === undefined) {
310
+ const mint = this.#mint(id);
311
+ minting = mint;
312
+ this.#logins.set(id, mint);
313
+ mint.then((login) => this.#logins.get(id) === mint && this.#held.set(id, login), () => this.#logins.get(id) === mint && this.#logins.delete(id));
314
+ }
315
+ const bound = boundOf(ctx.timeoutMs, ctx.signal, `the SSH token mint for ${id}`);
316
+ try {
317
+ return await Promise.race([minting, bound.promise]);
318
+ }
319
+ finally {
320
+ bound.clear();
321
+ }
322
+ }
323
+ /**
324
+ * Lets the machine's login go: every one (delete), or the refused one alone, so a replacement another exec already
325
+ * mints or holds stays.
326
+ */
327
+ #forget(id, refused) {
328
+ if (refused !== undefined && this.#held.get(id) !== refused)
329
+ return;
330
+ this.#logins.delete(id);
331
+ this.#held.delete(id);
332
+ }
333
+ /**
334
+ * POST /v1/machines/{id}/ssh-tokens (D ssh-tokens): a token for a day, and the gateway and host key it names, each
335
+ * held to its form before ssh2 or a socket sees it. Not sent again on no answer: another call is another token.
336
+ */
337
+ async #mint(id) {
338
+ const where = `POST /v1/machines/${id}/ssh-tokens`;
339
+ const { body } = await this.#call("POST", `/v1/machines/${id}/ssh-tokens`, { timeoutMs: CALL_MS }, { json: { name: "agentrun", ttlSeconds: TOKEN_TTL_S }, retry: (status) => status === 429 || status === 503 });
340
+ const { token, host, port, hostKeyFingerprint: fingerprint } = (body ?? {});
341
+ if (typeof token !== "string" || !TOKEN.test(token))
342
+ throw new HostError("vendor", `${where} answered no SSH token of InstaBox's form (ibssh_...)`);
343
+ if (typeof host !== "string" || !(DOMAIN.test(host) || isIP(host) !== 0))
344
+ throw new HostError("vendor", `${where} answered a gateway that is no host name: ${show(host)}`);
345
+ if (typeof port !== "number" || !Number.isSafeInteger(port) || port < 1 || port > 65_535)
346
+ throw new HostError("vendor", `${where} answered a gateway port that is no TCP port: ${show(port)}`);
347
+ if (typeof fingerprint !== "string" || !HOST_KEY_PIN.test(fingerprint))
348
+ throw new HostError("vendor", `${where} answered no host key fingerprint (SHA256:...) to pin the gateway by: ${show(fingerprint)}`);
349
+ return { token, host, port, fingerprint };
350
+ }
351
+ /** A TCP connection to the gateway the machine's token names, through the proxy's CONNECT tunnel when one applies (env-proxy.ts). */
352
+ #tunnel(id) {
353
+ const login = this.#held.get(id);
354
+ if (login === undefined)
355
+ throw new SshTunnelError(`no SSH token for ${id}, so no gateway to connect to`);
356
+ const { host, port } = login;
357
+ const name = isIP(host) === 6 ? `[${host}]` : host;
358
+ const where = `${host}:${port}`;
359
+ const proxy = proxyFor(new URL(`https://${name}:${port}`));
360
+ const through = proxy && tunnelThrough(proxy, name, port);
361
+ const socket = through ? through.socket : tcp(port, host);
362
+ // ssh2 reads the socket's errors once it has it; this keeps one before then from being thrown.
363
+ socket.on("error", () => { });
364
+ const failed = (error) => new SshTunnelError(`the SSH connection to ${where}${proxy ? ` through the proxy ${proxy.host}` : ""} failed to open: ${error.message}`);
365
+ const opened = through
366
+ ? through.opened.catch((error) => Promise.reject(failed(error)))
367
+ : new Promise((resolve, reject) => {
368
+ socket.once("connect", resolve);
369
+ socket.once("error", (error) => reject(failed(error)));
370
+ });
371
+ opened.catch(() => { });
372
+ return { duplex: socket, opened, host: where };
373
+ }
374
+ /**
375
+ * An image is a template id, a snapshot's name or its id (sn_...), by form; a size is one InstaBox offers, 2 to 32
376
+ * vCPUs in powers of two with 2 GiB each: one alone takes the other's match, and a pair that is not one is refused.
377
+ */
378
+ check(spec) {
379
+ const refusals = [];
380
+ if (typeof spec.image === "string" && !IMAGE.test(spec.image))
381
+ refusals.push({ field: "image", message: "an image is an InstaBox template id (minimal, agent-browser, universal), or a snapshot's name or id (sn_...) in the key's workspace" });
382
+ const { cpus, memoryMb } = spec;
383
+ const sizes = SIZES.map((one) => `${one} vCPUs with ${one * MIB_PER_CPU} MB`).join(", ");
384
+ if (cpus !== undefined && !SIZES.includes(cpus))
385
+ refusals.push({ field: "cpus", message: `an InstaBox machine has one of its sizes: ${sizes}` });
386
+ else if (memoryMb !== undefined && cpus !== undefined && memoryMb !== cpus * MIB_PER_CPU)
387
+ refusals.push({ field: "memoryMb", message: `an InstaBox machine has 2048 MB a vCPU, one of its sizes: ${sizes}` });
388
+ else if (memoryMb !== undefined && !SIZES.includes(memoryMb / MIB_PER_CPU))
389
+ refusals.push({ field: "memoryMb", message: `an InstaBox machine has one of its sizes: ${sizes}` });
390
+ return refusals;
391
+ }
392
+ }
393
+ /**
394
+ * An InstaboxProvider from its options alone; it reads no environment. The key is options.apiKey, nowhere else (serve
395
+ * passes its INSTABOX_API_KEY, the conformance module what it reads), and ssh2 is the host's package unless given.
396
+ */
397
+ export async function create(options) {
398
+ const { ssh2: given, ...rest } = options ?? {};
399
+ if (typeof rest.apiKey !== "string" || rest.apiKey === "")
400
+ throw new Error(KEY_REQUIRED);
401
+ // ssh2 is CommonJS: its Client is a named export of the module, and of its default.
402
+ const loaded = given ?? (await vendorSdk(INSTABOX.label, "ssh2"));
403
+ const ssh2 = typeof loaded.Client === "function" ? loaded : loaded.default;
404
+ return new InstaboxProvider({ ...rest, ssh2: ssh2 });
405
+ }
406
+ export const conformance = () => import("./conformance/instabox.js");
407
+ const KEY_REQUIRED = "options.apiKey, the InstaBox API key, is required: the provider reads no environment, so the caller passes it";
408
+ /** The uid of the machine's own user (D templates: uid 1000), whose processes init refuses to run beside. */
409
+ const MACHINE_UID = 1000;
410
+ /** Computers that are InstaBox machines, on the shared adapter: a sandbox from an InstaBox template, no desktop. */
411
+ export class InstaboxProvider extends HostedProvider {
412
+ constructor(options) {
413
+ const { apiKey, ssh2, fetch: fetcher, apiUrl = DEFAULT_API_URL, maxLifetimeMs = MAX_LIFETIME_MS, ...rest } = options ?? {};
414
+ if (typeof apiKey !== "string" || apiKey === "")
415
+ throw new Error(KEY_REQUIRED);
416
+ if (typeof ssh2?.Client !== "function")
417
+ throw new Error("options.ssh2 must be the ssh2 package (its Client class): the host installs it, as it does for Agent37 and Morph");
418
+ if (fetcher !== undefined && typeof fetcher !== "function")
419
+ throw new Error("options.fetch must be a function, as the global fetch is");
420
+ if (Number(rest.daemonUser?.split(":")[0]) === MACHINE_UID)
421
+ throw new Error(`the daemon user ${rest.daemonUser} is the uid of the machine's own user, whose processes init refuses to run beside; choose another, such as 2510:2510`);
422
+ super(new InstaboxHost({ apiKey, ssh2, ...(fetcher ? { fetch: fetcher } : {}), apiUrl: httpsBase(apiUrl, "the InstaBox API URL") }), { ...rest, maxLifetimeMs });
423
+ }
424
+ }
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
+ }