@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
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.69",
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,11 @@
10
10
  "daytona",
11
11
  "boxd",
12
12
  "smolcloud",
13
- "groundbox"
13
+ "groundbox",
14
+ "vercel",
15
+ "sprites",
16
+ "instabox",
17
+ "northflank"
14
18
  ],
15
19
  "type": "module",
16
20
  "license": "Apache-2.0",
@@ -81,6 +85,22 @@
81
85
  "types": "./dist/groundbox.d.ts",
82
86
  "default": "./dist/groundbox.js"
83
87
  },
88
+ "./vercel": {
89
+ "types": "./dist/vercel.d.ts",
90
+ "default": "./dist/vercel.js"
91
+ },
92
+ "./sprites": {
93
+ "types": "./dist/sprites.d.ts",
94
+ "default": "./dist/sprites.js"
95
+ },
96
+ "./instabox": {
97
+ "types": "./dist/instabox.d.ts",
98
+ "default": "./dist/instabox.js"
99
+ },
100
+ "./northflank": {
101
+ "types": "./dist/northflank.d.ts",
102
+ "default": "./dist/northflank.js"
103
+ },
84
104
  "./orgo": {
85
105
  "types": "./dist/orgo.d.ts",
86
106
  "default": "./dist/orgo.js"