@parcha/agentrun-computer 0.1.0-beta.68 → 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 (50) hide show
  1. package/README.md +55 -3
  2. package/box/README.md +8 -0
  3. package/box/install.sh +40 -2
  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/northflank.d.ts +44 -0
  11. package/dist/conformance/northflank.js +50 -0
  12. package/dist/descriptor.d.ts +6 -0
  13. package/dist/descriptor.js +2 -0
  14. package/dist/descriptors/agent37.d.ts +1 -0
  15. package/dist/descriptors/agent37.js +2 -0
  16. package/dist/descriptors/daytona.d.ts +1 -0
  17. package/dist/descriptors/daytona.js +2 -0
  18. package/dist/descriptors/e2b.d.ts +1 -0
  19. package/dist/descriptors/e2b.js +2 -0
  20. package/dist/descriptors/fly.d.ts +1 -0
  21. package/dist/descriptors/fly.js +2 -0
  22. package/dist/descriptors/groundbox.d.ts +1 -0
  23. package/dist/descriptors/groundbox.js +2 -0
  24. package/dist/descriptors/index.d.ts +34 -1
  25. package/dist/descriptors/index.js +3 -2
  26. package/dist/descriptors/instabox.d.ts +1 -0
  27. package/dist/descriptors/instabox.js +2 -0
  28. package/dist/descriptors/modal.d.ts +1 -0
  29. package/dist/descriptors/modal.js +2 -0
  30. package/dist/descriptors/northflank.d.ts +24 -0
  31. package/dist/descriptors/northflank.js +30 -0
  32. package/dist/descriptors/orgo.d.ts +1 -0
  33. package/dist/descriptors/orgo.js +2 -0
  34. package/dist/descriptors/render.d.ts +1 -0
  35. package/dist/descriptors/render.js +2 -0
  36. package/dist/groundbox.js +15 -2
  37. package/dist/hosted/download.d.ts +16 -0
  38. package/dist/hosted/download.js +108 -2
  39. package/dist/hosted/provider.js +11 -4
  40. package/dist/hosted/scripts.d.ts +2 -0
  41. package/dist/hosted/scripts.js +29 -0
  42. package/dist/northflank.d.ts +44 -0
  43. package/dist/northflank.js +448 -0
  44. package/dist/orgo-desktop.js +2 -2
  45. package/dist/orgo-names.d.ts +15 -1
  46. package/dist/orgo-names.js +13 -0
  47. package/dist/orgo.d.ts +10 -0
  48. package/dist/orgo.js +64 -4
  49. package/dist/providers.d.ts +10 -4
  50. package/package.json +7 -2
@@ -0,0 +1,448 @@
1
+ // The Northflank host: a Linux sandbox on a Northflank service, a Kata microVM on Northflank Cloud, in the customer's own
2
+ // project, over Northflank's REST API (https://api.northflank.com/v1, a Bearer token). Sources: D = the docs
3
+ // (https://northflank.com/docs/v1/: sandboxes/quickstart, sandboxes/configure-and-manage-sandboxes, api/use-the-api), S =
4
+ // @northflank/js-client 0.13.0, Northflank's own client, whose calls this host makes without it. A sandbox is a service
5
+ // (D quickstart): its name is the request's and its id (computer-<12 hex>), its image the box image or the spec's, its
6
+ // command `sleep infinity`. The labels are packed into the workload's annotations, whose keys must be Kubernetes names.
7
+ // The exec is S's command-exec WebSocket (ExecCommandStandard): JSON messages, the token in the first, stdin, stdout
8
+ // and stderr as latin1 strings (encoding latin1: one code point a byte), the exit in a completion message. It has no
9
+ // kill, so a command runs under the shared pid wrapper (framedExec). The janitor deletes at the deadline label; create
10
+ // sets the service's expiryTime at the request's backstop, past which Northflank pauses it (no compute billed) and
11
+ // schedules its deletion, so a computer whose server is gone stops costing.
12
+ //
13
+ // Unverified until the live run: latin1 carries every byte both ways; the exec socket stays open through 75 s of silence
14
+ // with no ping of ours; Northflank sends its init answer on the socket; output may trail the completion message, and the
15
+ // socket closes after the last of it; exec as user root is root; a create whose name the project holds answers 409
16
+ // (read as exists); a service's id is its name; the annotations come back on get as the object given; the quickstart's
17
+ // scale call after a create is needed or harmless; a deleted service answers 404; amd64; no vendor agent on TCP in the
18
+ // guest (Kata's is on vsock); root makes a network namespace in the guest.
19
+ import { BACKSTOP_MARGIN_MS, HostError } from "./host.js";
20
+ import { boxImageRef } from "./box-image.js";
21
+ import { NORTHFLANK } from "./descriptors/northflank.js";
22
+ import { DEFAULT_CPUS, DEFAULT_MEMORY_MB, show } from "./drift.js";
23
+ import { framedExec } from "./hosted/framed-exec.js";
24
+ import { orThrow, pause } from "./hosted/process.js";
25
+ import { HostedProvider } from "./hosted/provider.js";
26
+ import { allPages, httpsBase, jsonOf, rest } from "./hosted/rest.js";
27
+ import { PACKED_NAME, dateOf } from "./hosted/values.js";
28
+ import { ok } from "./result.js";
29
+ export async function create(options) {
30
+ return new NorthflankProvider(options);
31
+ }
32
+ export const conformance = () => import("./conformance/northflank.js");
33
+ export const DEFAULT_API_URL = "https://api.northflank.com";
34
+ /** Every computer's name starts with this (MachineRequest.name), so a listing keeps the project's computers alone. */
35
+ const NAME_PREFIX = "computer-";
36
+ /** createOptions.expiryTime's range, in seconds (S CreateServiceDeploymentData: 300 to 604800). */
37
+ const MIN_EXPIRY_S = 300;
38
+ const MAX_EXPIRY_S = 604_800;
39
+ /** The longest a computer lives: its backstop, past it by BACKSTOP_MARGIN_MS, is then within the expiry's 7 days. */
40
+ const MAX_LIFETIME_MS = MAX_EXPIRY_S * 1000 - BACKSTOP_MARGIN_MS;
41
+ const CALL_MS = 30_000;
42
+ /** A listing's page, the most S allows. */
43
+ const PAGE = 100;
44
+ /** The gets a listing makes at once, for the labels its answer lacks. */
45
+ const LIST_READS = 8;
46
+ /** How long a listing's read of a computer answers the next get of it, once: the adapter reads each one listed again. */
47
+ const LISTED_READ_MS = 2_000;
48
+ /** A stdin message's bytes, and the socket's backlog a write waits under. */
49
+ const STDIN_BYTES = 64 * 1024;
50
+ const BACKLOG_BYTES = 1024 * 1024;
51
+ /** How long output may trail the completion message with none coming before the exit is read: S's drain, 30 s. */
52
+ const DRAIN_MS = 30_000;
53
+ /** The output a command may have waiting, unread: at it the exec ends (the socket has no flow control). */
54
+ const QUEUE_BYTES = 64 * 1024 * 1024;
55
+ /**
56
+ * The plans a size maps to (https://northflank.com/pricing: vCPUs and MB a plan). A spec names cpus, memoryMb or both; one
57
+ * alone takes its plan's other.
58
+ */
59
+ const PLANS = [
60
+ { id: "nf-compute-100-2", cpus: 1, memoryMb: 2048 },
61
+ { id: "nf-compute-200", cpus: 2, memoryMb: 4096 },
62
+ { id: "nf-compute-400", cpus: 4, memoryMb: 8192 },
63
+ { id: "nf-compute-800-16", cpus: 8, memoryMb: 16_384 },
64
+ ];
65
+ /** An image path: a registry reference, its host optional (Docker Hub then), a tag or a digest. */
66
+ const IMAGE = /^[a-z0-9][a-z0-9._:/-]*[a-z0-9](:[A-Za-z0-9_][A-Za-z0-9._-]{0,127}|@sha256:[0-9a-f]{64})?$/;
67
+ /** A project, team or service id as it reaches a path: Northflank's slugs. */
68
+ const SLUG = /^[a-z0-9][a-z0-9-]{0,62}$/;
69
+ /**
70
+ * The image's boot is a pull, and Northflank's delete is not done at its answer; status is read every 2 s, not 1, since
71
+ * a token has 1000 requests an hour (D use-the-api).
72
+ */
73
+ const NORTHFLANK_TIMEOUTS = { createMs: 600_000, goneMs: 180_000, pollMs: 2_000 };
74
+ /**
75
+ * Northflank's deployment statuses (S) as the adapter's; a service that expired is paused, so stopped. A FAILED one is
76
+ * stopped too, not gone: the service is still there, and only a listed computer reaches the janitor's delete.
77
+ */
78
+ const STATES = { PENDING: "starting", IN_PROGRESS: "starting", COMPLETED: "running", FAILED: "stopped" };
79
+ /** The annotations as a map of strings: S types them "string or object". */
80
+ function annotationsOf(value) {
81
+ const map = typeof value === "string" ? jsonOf(Buffer.from(value)) : value;
82
+ if (typeof map !== "object" || map === null || Array.isArray(map))
83
+ return {};
84
+ return Object.fromEntries(Object.entries(map).filter((entry) => typeof entry[1] === "string"));
85
+ }
86
+ function machineOf(service) {
87
+ const status = service.status?.deployment?.status;
88
+ const known = status === undefined ? "starting" : STATES[status];
89
+ const created = dateOf(service.createdAt);
90
+ const plan = PLANS.find((one) => one.id === service.billing?.deploymentPlan);
91
+ const why = service.expiredAt ? `Northflank paused it at its expiry, ${service.expiredAt}` : status === "FAILED" ? "Northflank reads its deployment FAILED" : known === undefined ? `Northflank reads its deployment ${show(status)}, which this provider does not know` : undefined;
92
+ return {
93
+ id: service.id,
94
+ labels: annotationsOf(service.deployment?.metadata?.annotations),
95
+ // One expired (paused), or in a status this provider does not know, is listed, so the janitor still ends it.
96
+ state: service.expiredAt ? "stopped" : (known ?? "stopped"),
97
+ ...(created ? { createdAt: created } : {}),
98
+ ...(plan ? { resources: { cpus: plan.cpus, memoryMb: plan.memoryMb } } : {}),
99
+ ...(why === undefined ? {} : { why }),
100
+ };
101
+ }
102
+ /** The plan of a size, the adapter's default where the request names none; undefined for one no plan has. */
103
+ function planOf(cpus, memoryMb) {
104
+ const want = cpus === undefined && memoryMb === undefined ? { cpus: DEFAULT_CPUS, memoryMb: DEFAULT_MEMORY_MB } : { cpus, memoryMb };
105
+ return PLANS.find((one) => (want.cpus === undefined || one.cpus === want.cpus) && (want.memoryMb === undefined || one.memoryMb === want.memoryMb))?.id;
106
+ }
107
+ /** An id held to Northflank's form before it reaches a path: not_found else. */
108
+ function serviceId(id) {
109
+ if (!SLUG.test(id))
110
+ throw new HostError("not_found", `${JSON.stringify(id)} is not a Northflank service id`);
111
+ return id;
112
+ }
113
+ class NorthflankHost {
114
+ descriptor = NORTHFLANK;
115
+ facts = {
116
+ daemon: "child",
117
+ // A CPU sandbox on Northflank Cloud is a Kata microVM (D sandboxes-on-northflank-cloud).
118
+ isolation: "microvm",
119
+ lifetime: "janitor",
120
+ maxLifetimeMs: MAX_LIFETIME_MS,
121
+ arch: "amd64",
122
+ // Kata's agent talks over vsock, not TCP (unverified until the live run).
123
+ vendorAgentPorts: [],
124
+ // Kubernetes annotations: keys are qualified names, so the labels are packed; 256 KiB of keys and values in all.
125
+ labels: { bytes: 262_144, packed: {} },
126
+ };
127
+ #api;
128
+ #token;
129
+ /** /projects/{projectId}, after /teams/{teamId} for an organisation token. */
130
+ #scope;
131
+ #wsUrl;
132
+ #webSocket;
133
+ /**
134
+ * The last listings' reads, by id, each answering the next get of its computer once within LISTED_READ_MS: the
135
+ * adapter's list reads every computer the host's listing names (foundBy), which here would read each a second time,
136
+ * against a token's 1000 requests an hour. A create or a delete during a listing leaves its reads out.
137
+ */
138
+ #read = new Map();
139
+ #writes = 0;
140
+ constructor(options) {
141
+ this.#token = options.token;
142
+ this.#scope = `${options.teamId === undefined ? "" : `/teams/${options.teamId}`}/projects/${options.projectId}`;
143
+ this.#wsUrl = options.apiUrl.replace(/^https/, "wss");
144
+ this.#webSocket = options.webSocket;
145
+ this.#api = rest({
146
+ base: `${options.apiUrl}/v1`,
147
+ headers: () => ({ Authorization: `Bearer ${this.#token}`, Accept: "application/json" }),
148
+ vendor: NORTHFLANK.id,
149
+ ...(options.fetch ? { fetch: options.fetch } : {}),
150
+ timeoutMs: CALL_MS,
151
+ retry: { attempts: 3, baseMs: 1_000 },
152
+ // A refusal's body is {error: {status, message, id, details}} (S ApiCallError); the status is the code.
153
+ explain: ({ status, bytes, what }) => {
154
+ const error = jsonOf(bytes)?.error;
155
+ const words = typeof error?.message === "string" && error.message !== "" ? `: ${error.message}` : "";
156
+ return { message: `${what} answered ${status}${words}${typeof error?.id === "string" ? ` (Northflank error ${error.id})` : ""}` };
157
+ },
158
+ });
159
+ }
160
+ async #call(method, path, ctx, init = {}) {
161
+ const answer = orThrow(await this.#api.call(method, this.#api.url(`${this.#scope}${path}`), { timeoutMs: ctx.timeoutMs, ...init }, ctx.signal));
162
+ return { status: answer.status, body: jsonOf(answer.bytes) };
163
+ }
164
+ /**
165
+ * POST .../services/deployment (D quickstart): the request's name, the plan of its size, the image with `sleep
166
+ * infinity` as its entrypoint and command, one instance, the packed labels as the workload's annotations, and the
167
+ * expiry at the backstop; then the quickstart's scale to one instance. The name is the id.
168
+ */
169
+ async create(req, ctx) {
170
+ const plan = planOf(req.cpus, req.memoryMb);
171
+ if (plan === undefined)
172
+ throw new HostError("invalid", `no Northflank plan has ${req.cpus ?? "any"} vCPUs and ${req.memoryMb ?? "any"} MB`);
173
+ const seconds = Math.ceil((Date.parse(req.backstopAt) - Date.now()) / 1000);
174
+ const body = {
175
+ name: req.name,
176
+ billing: { deploymentPlan: plan },
177
+ deployment: {
178
+ instances: 1,
179
+ external: { imagePath: req.image },
180
+ docker: { configType: "customEntrypointCustomCommand", customEntrypoint: "/bin/sh", customCommand: "-c 'exec sleep infinity'" },
181
+ metadata: { annotations: req.labels },
182
+ },
183
+ createOptions: { expiryTime: Math.min(MAX_EXPIRY_S, Math.max(MIN_EXPIRY_S, seconds)) },
184
+ };
185
+ this.#wrote();
186
+ const { body: made } = await this.#call("POST", "/services/deployment", ctx, { json: body, named: true, retry: (status) => status === 429 });
187
+ const id = made?.data?.id;
188
+ const service = typeof id === "string" && SLUG.test(id) ? id : req.name;
189
+ try {
190
+ await this.#call("POST", `/services/${service}/scale`, ctx, { json: { instances: 1 }, retry: true });
191
+ }
192
+ catch (error) {
193
+ // The service is made and billed: deleted here, its own bound and no caller's signal, before create answers.
194
+ // Where that fails too it may be there, so the code is the vendor's, which the adapter sweeps the name on.
195
+ try {
196
+ await this.delete(service, { timeoutMs: CALL_MS });
197
+ }
198
+ catch (left) {
199
+ throw new HostError("vendor", `${error.message}; the service ${service} it made may be left, its delete failed (${left.message})`);
200
+ }
201
+ throw error;
202
+ }
203
+ return { id: service };
204
+ }
205
+ /** A create or a delete: the listings' reads answer no get after it. */
206
+ #wrote() {
207
+ this.#writes += 1;
208
+ this.#read.clear();
209
+ }
210
+ /** GET .../services/{id}; a 404 is none. A listing's read of it within LISTED_READ_MS answers once instead. */
211
+ async get(id, ctx) {
212
+ const listed = this.#read.get(id);
213
+ this.#read.delete(id);
214
+ if (listed !== undefined && Date.now() - listed.at < LISTED_READ_MS)
215
+ return listed.machine;
216
+ return this.#get(id, ctx);
217
+ }
218
+ async #get(id, ctx) {
219
+ const read = await this.#call("GET", `/services/${serviceId(id)}`, ctx, { retry: true, accept: (status) => status === 404 || (status >= 200 && status < 300) });
220
+ if (read.status === 404)
221
+ return undefined;
222
+ const service = read.body?.data;
223
+ if (typeof service?.id !== "string")
224
+ throw new HostError("vendor", `GET .../services/${id} answered no service`);
225
+ return machineOf(service);
226
+ }
227
+ /**
228
+ * GET .../services, every page: the project's computers by name prefix, and the one whose id is the packed name when
229
+ * one is asked. A listing carries no annotations, so each computer it names is read by get for its labels, LIST_READS
230
+ * at a time; one gone between the two is left out, and the reads answer the adapter's own read of each that follows
231
+ * (#read). The adapter filters by the labels it asked.
232
+ */
233
+ async list(labels, ctx) {
234
+ const name = labels[PACKED_NAME];
235
+ const page = async (cursor) => {
236
+ const query = new URLSearchParams({ per_page: String(PAGE), ...(cursor ? { cursor } : {}) });
237
+ const { body } = await this.#call("GET", `/services?${query}`, ctx, { retry: true });
238
+ const read = body;
239
+ return ok({ items: read?.data?.services ?? [], ...(read?.pagination?.hasNextPage && read.pagination.cursor ? { next: read.pagination.cursor } : {}) });
240
+ };
241
+ const ids = orThrow(await allPages(page, 100, { vendor: NORTHFLANK.id, what: "GET .../services" }))
242
+ .filter((service) => typeof service?.id === "string" && SLUG.test(service.id) && service.id.startsWith(NAME_PREFIX) && (name === undefined || service.id === name || service.name === name))
243
+ .map((service) => service.id);
244
+ const writes = this.#writes;
245
+ const machines = [];
246
+ for (let at = 0; at < ids.length; at += LIST_READS) {
247
+ const reads = await Promise.all(ids.slice(at, at + LIST_READS).map((id) => this.#get(id, ctx)));
248
+ for (const machine of reads)
249
+ if (machine !== undefined)
250
+ machines.push(machine);
251
+ }
252
+ if (this.#writes === writes)
253
+ for (const machine of machines)
254
+ this.#read.set(machine.id, { machine, at: Date.now() });
255
+ return machines;
256
+ }
257
+ /** DELETE .../services/{id}, which ends its billing (D configure-and-manage-sandboxes); one Northflank no longer has is done. */
258
+ async delete(id, ctx) {
259
+ this.#wrote();
260
+ try {
261
+ await this.#call("DELETE", `/services/${serviceId(id)}`, ctx, { retry: true, accept: (status) => status === 404 || (status >= 200 && status < 300) });
262
+ }
263
+ finally {
264
+ this.#wrote();
265
+ }
266
+ }
267
+ exec(id, argv, ctx) {
268
+ return framedExec({
269
+ start: (words, ctx) => this.#open(serviceId(id), words, ctx),
270
+ events: (exec) => this.#events(exec),
271
+ write: async (exec, text) => {
272
+ const bytes = Buffer.from(text, "utf8");
273
+ for (let at = 0; at < bytes.length; at += STDIN_BYTES) {
274
+ if (exec.socket.readyState !== 1)
275
+ throw new Error("the exec socket is closed");
276
+ exec.socket.send(JSON.stringify({ type: "payload", data: bytes.subarray(at, at + STDIN_BYTES).toString("latin1") }));
277
+ while (exec.socket.bufferedAmount > BACKLOG_BYTES && exec.socket.readyState === 1)
278
+ await pause(5);
279
+ }
280
+ },
281
+ end: async (exec) => {
282
+ if (exec.socket.readyState === 1)
283
+ exec.socket.send(JSON.stringify({ type: "stdInEnd" }));
284
+ },
285
+ // No kill: Northflank has none (S closes the socket alone), so framedExec runs argv under the pid wrapper.
286
+ }, argv, ctx);
287
+ }
288
+ /**
289
+ * Opens the command-exec socket and sends its init: the token, argv as the command with no shell, as root, latin1, no
290
+ * tty. Answers once it is open. One that never opens says whether the service is there: a refused upgrade's status
291
+ * never reaches a WebSocket client.
292
+ */
293
+ async #open(id, argv, ctx) {
294
+ const socket = this.#webSocket(`${this.#wsUrl}/v1/command-exec${this.#scope}/services/${id}`);
295
+ const exec = { socket, queue: [], queued: 0, closed: false, wake: () => { } };
296
+ const close = () => {
297
+ if (socket.readyState < 2)
298
+ socket.close(1000);
299
+ };
300
+ const push = (event, bytes) => {
301
+ if (exec.closed)
302
+ return;
303
+ exec.queue.push(event);
304
+ exec.queued += bytes;
305
+ if (exec.queued >= QUEUE_BYTES) {
306
+ exec.failure ??= new Error(`the command's output not read passed ${QUEUE_BYTES / 1024 / 1024} MiB, so the exec ended: its reader stopped reading`);
307
+ exec.queue.length = 0;
308
+ exec.closed = true;
309
+ close();
310
+ }
311
+ exec.wake();
312
+ };
313
+ // After the completion, output may still come: the exit is read once the socket closes, or DRAIN_MS after the last.
314
+ const draining = () => {
315
+ if (exec.exit === undefined)
316
+ return;
317
+ clearTimeout(exec.drain);
318
+ exec.drain = setTimeout(close, DRAIN_MS);
319
+ };
320
+ let opened;
321
+ const open = new Promise((done) => (opened = done));
322
+ socket.addEventListener("open", () => {
323
+ const context = { command: [...argv], shell: "none", user: "root", group: "root", encoding: "latin1", tty: false };
324
+ socket.send(JSON.stringify({ type: "init", data: { auth: { type: "apiToken", apiToken: this.#token }, context } }));
325
+ opened();
326
+ });
327
+ socket.addEventListener("message", ({ data }) => {
328
+ const message = typeof data === "string" ? jsonOf(Buffer.from(data)) : null;
329
+ const body = message?.data;
330
+ if ((message?.type === "stdOut" || message?.type === "stdErr") && typeof body === "string") {
331
+ const bytes = Buffer.from(body, "latin1");
332
+ push({ stream: message.type === "stdOut" ? "stdout" : "stderr", base64: bytes.toString("base64") }, bytes.length);
333
+ draining();
334
+ }
335
+ else if (message?.type === "completion" && typeof body === "object" && typeof body?.exitCode === "number") {
336
+ exec.exit = body.exitCode;
337
+ draining();
338
+ }
339
+ else if (message?.type === "init" && typeof body === "object" && body?.auth !== "successful") {
340
+ exec.failure ??= new HostError("denied", `Northflank refused the command on ${id}: ${typeof body?.message === "string" ? body.message : "no reason given"}`);
341
+ close();
342
+ }
343
+ else if (message?.type === "error") {
344
+ exec.failure ??= new HostError("vendor", `Northflank ended the command on ${id}: ${typeof body === "object" && typeof body?.message === "string" ? body.message : "no reason given"}`);
345
+ close();
346
+ }
347
+ });
348
+ socket.addEventListener("error", (event) => {
349
+ exec.failure ??= new Error(`the exec socket failed${event.message ? `: ${event.message}` : ""}`);
350
+ opened(exec.failure);
351
+ });
352
+ socket.addEventListener("close", ({ code }) => {
353
+ exec.closed = true;
354
+ clearTimeout(exec.drain);
355
+ opened(new Error(`the exec socket closed before it opened (code ${code ?? "none"})`));
356
+ exec.wake();
357
+ });
358
+ let timer;
359
+ let onAbort;
360
+ const bound = new Promise((done) => {
361
+ timer = setTimeout(() => done(new HostError("timeout", `the exec socket of ${id} did not open within ${Math.round(ctx.timeoutMs / 1000)} s`)), ctx.timeoutMs);
362
+ onAbort = () => done(new HostError("aborted", `the exec socket of ${id} was aborted`));
363
+ if (ctx.signal?.aborted)
364
+ onAbort();
365
+ else
366
+ ctx.signal?.addEventListener("abort", onAbort, { once: true });
367
+ });
368
+ const failed = await Promise.race([open, bound]).finally(() => {
369
+ clearTimeout(timer);
370
+ if (onAbort)
371
+ ctx.signal?.removeEventListener("abort", onAbort);
372
+ });
373
+ if (failed === undefined)
374
+ return exec;
375
+ close();
376
+ if (failed instanceof HostError)
377
+ throw failed;
378
+ if ((await this.get(id, { timeoutMs: CALL_MS })) === undefined)
379
+ throw new HostError("not_found", `no Northflank service ${id}`);
380
+ throw new HostError("vendor", `${failed.message} (service ${id})`);
381
+ }
382
+ /** The command's events as the socket gives them, then its exit once the socket closed; the socket closes after. */
383
+ async *#events(exec) {
384
+ try {
385
+ for (;;) {
386
+ const event = exec.queue.shift();
387
+ if (event !== undefined) {
388
+ if ("base64" in event)
389
+ exec.queued -= Buffer.byteLength(event.base64, "base64");
390
+ yield event;
391
+ continue;
392
+ }
393
+ if (exec.closed) {
394
+ if (exec.failure)
395
+ throw exec.failure;
396
+ if (exec.exit !== undefined)
397
+ yield { exit: exec.exit };
398
+ return;
399
+ }
400
+ await new Promise((done) => (exec.wake = done));
401
+ }
402
+ }
403
+ finally {
404
+ clearTimeout(exec.drain);
405
+ if (exec.socket.readyState < 2)
406
+ exec.socket.close(1000);
407
+ }
408
+ }
409
+ /** An image is a registry reference; a size is one of the plans', one field taking the other's match. */
410
+ check(spec) {
411
+ const refusals = [];
412
+ const { image, cpus, memoryMb } = spec;
413
+ if (typeof image === "string" && !IMAGE.test(image))
414
+ refusals.push({ field: "image", message: `a Northflank image is a registry reference, such as ${boxImageRef()}` });
415
+ if ((cpus !== undefined || memoryMb !== undefined) && planOf(cpus, memoryMb) === undefined) {
416
+ const sizes = PLANS.map((one) => `${one.cpus} vCPUs with ${one.memoryMb} MB`).join(", ");
417
+ refusals.push({ field: cpus === undefined ? "memoryMb" : "cpus", message: `a Northflank computer has one of its plans' sizes: ${sizes}` });
418
+ }
419
+ return refusals;
420
+ }
421
+ }
422
+ /**
423
+ * Computers that are Northflank services in the customer's project, on the shared adapter: a sandbox from the box image
424
+ * (or the spec's), no desktop.
425
+ */
426
+ export class NorthflankProvider extends HostedProvider {
427
+ /** The provider contract's prepareImage (its descriptor declares it): the box image's public tag. No call: Northflank pulls it at each create. */
428
+ async prepareImage() {
429
+ return ok(boxImageRef());
430
+ }
431
+ constructor(options) {
432
+ const { token, projectId, teamId, apiUrl = DEFAULT_API_URL, fetch, webSocket, maxLifetimeMs = MAX_LIFETIME_MS, timeouts = {}, ...rest } = options ?? {};
433
+ if (typeof token !== "string" || token === "")
434
+ throw new Error("options.token, a Northflank API token, is required: the provider reads no environment, so the caller passes it");
435
+ if (typeof projectId !== "string" || !SLUG.test(projectId))
436
+ throw new Error(`options.projectId is required: the id of your Northflank project the computers live in (lowercase letters, digits and hyphens), not ${show(projectId)}`);
437
+ if (teamId !== undefined && (typeof teamId !== "string" || !SLUG.test(teamId)))
438
+ throw new Error(`options.teamId, for an organisation token, is the team's id (lowercase letters, digits and hyphens), not ${show(teamId)}`);
439
+ super(new NorthflankHost({
440
+ token,
441
+ projectId,
442
+ ...(teamId === undefined ? {} : { teamId }),
443
+ apiUrl: httpsBase(apiUrl, "the Northflank API URL"),
444
+ ...(fetch ? { fetch } : {}),
445
+ webSocket: webSocket ?? ((url) => new WebSocket(url)),
446
+ }), { ...rest, maxLifetimeMs, timeouts: { ...NORTHFLANK_TIMEOUTS, ...timeouts } });
447
+ }
448
+ }
@@ -38,7 +38,7 @@ import { EPOCH_LABEL, OWNER_LABEL, OWNER_SERVER_LABEL, ownerLabels, RUN_HASH_LAB
38
38
  import { checkMount } from "./mount.js";
39
39
  import { ORGO_API_URL, orgoRest } from "./orgo-channel.js";
40
40
  import { workspaceChoices, workspaceHolder } from "./orgo-workspaces.js";
41
- import { COMPUTER_ID, claimProblem, andSettled, inTurn, filterProblem, labelProblem, labelsOf, NAME_MAX, NO_DEADLINE, nameParts, orgoMemoryLedger, orgoName, ownedListing, ownerHashOfLabels, ownerReadBack, refProblem, sameComputer, settleEntry, show, renewEntry, takeEntry, withDeadline, } from "./orgo-names.js";
41
+ import { COMPUTER_ID, claimProblem, andSettled, inTurn, filterProblem, labelProblem, labelsOf, NAME_MAX, NO_DEADLINE, nameParts, orgoMemoryLedger, orgoName, ownedListing, ownerHashOfLabels, ownerReadBack, refProblem, sameComputer, settleEntry, show, renewEntry, takeEntry, orgoSize, withDeadline, } from "./orgo-names.js";
42
42
  import { encodePng } from "./png.js";
43
43
  import { MAX_CHUNK_BYTES, MAX_LIST_ENTRIES, MAX_OUTPUT_BYTES, PROTOCOL_VERSION, } from "./protocol.js";
44
44
  import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
@@ -505,7 +505,7 @@ export class OrgoDesktopProvider {
505
505
  if (signal?.aborted)
506
506
  return this.#abandon(ref, { code: "aborted", message: "create was aborted" });
507
507
  if (prepared.ok)
508
- return ok(ref);
508
+ return ok({ ...ref, ...orgoSize(made.value, { ...(cpu === undefined ? {} : { cpus: cpu }), memoryMb: ram * 1024 }) });
509
509
  return this.#abandon(ref, prepared.error);
510
510
  }
511
511
  /** Running, answering a command, its labels file written, then its screen and the hello a connection answers. */
@@ -1,4 +1,4 @@
1
- import type { ComputerClaim, ComputerOwner, ComputerRef } from "./provider.js";
1
+ import type { ComputerClaim, ComputerOwner, ComputerRef, ComputerResources } from "./provider.js";
2
2
  import { type Result } from "./result.js";
3
3
  /** The longest name Orgo holds. */
4
4
  export declare const NAME_MAX = 80;
@@ -141,12 +141,26 @@ export interface OrgoComputer {
141
141
  id: string;
142
142
  name: string;
143
143
  status: string;
144
+ /** The size it runs at, as Orgo's create and its reads answer it: RAM in GB and vCPUs. Orgo bills by it. */
145
+ ram?: unknown;
146
+ cpu?: unknown;
144
147
  os?: string;
145
148
  workspace_id?: string;
146
149
  project_id?: string;
147
150
  ends_at?: string | null;
148
151
  created_at?: string;
149
152
  }
153
+ /**
154
+ * The size a computer runs at, as its create reports it (CreatedComputer.resources): what Orgo's answer says (ram in GB,
155
+ * cpu in vCPUs), each figure it leaves out the one the create sent (`sent`, as the labels file keeps it), which Orgo runs
156
+ * or refuses with a 400, never another. None where neither says one.
157
+ */
158
+ export declare function orgoSize(answer: Pick<OrgoComputer, "ram" | "cpu"> | undefined, sent: {
159
+ cpus?: number;
160
+ memoryMb?: number;
161
+ }): {
162
+ resources?: ComputerResources;
163
+ };
150
164
  export declare const show: (value: unknown) => string;
151
165
  /**
152
166
  * The name of a computer with these labels: computer-<hex>, then -r<the run label's hash> and -e<the epoch label> when
@@ -206,6 +206,19 @@ export function orgoMemoryLedger() {
206
206
  }
207
207
  /** An Orgo computer's id. */
208
208
  export const COMPUTER_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
209
+ const positive = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined);
210
+ /**
211
+ * The size a computer runs at, as its create reports it (CreatedComputer.resources): what Orgo's answer says (ram in GB,
212
+ * cpu in vCPUs), each figure it leaves out the one the create sent (`sent`, as the labels file keeps it), which Orgo runs
213
+ * or refuses with a 400, never another. None where neither says one.
214
+ */
215
+ export function orgoSize(answer, sent) {
216
+ const ramGb = positive(answer?.ram);
217
+ const cpus = positive(answer?.cpu) ?? sent.cpus;
218
+ const memoryMb = ramGb === undefined ? sent.memoryMb : ramGb * 1024;
219
+ const resources = { ...(cpus === undefined ? {} : { cpus }), ...(memoryMb === undefined ? {} : { memoryMb }) };
220
+ return Object.keys(resources).length > 0 ? { resources } : {};
221
+ }
209
222
  export const show = (value) => (value === undefined ? "nothing" : JSON.stringify(value));
210
223
  /**
211
224
  * The name of a computer with these labels: computer-<hex>, then -r<the run label's hash> and -e<the epoch label> when
package/dist/orgo.d.ts CHANGED
@@ -75,6 +75,16 @@ export declare const LABELS_FILE = "/opt/agentrun/labels.json";
75
75
  * nothing of its own loses a socket.
76
76
  */
77
77
  export declare const LOCKDOWN_SCRIPT: string;
78
+ /**
79
+ * Ends Orgo's PRIMARY autocutsel, so a selection no longer takes the clipboard. Orgo's desktop runs two as root, one per
80
+ * selection (`autocutsel -fork -selection CLIPBOARD` and `... PRIMARY`), both through CUT_BUFFER0: selecting text (Ctrl+L
81
+ * in a file manager selects its location) sets PRIMARY, the PRIMARY one copies that text into the cut buffer, and the
82
+ * CLIPBOARD one then takes CLIPBOARD with it as plain text, so a cut or copy of files is gone before its paste. The
83
+ * CLIPBOARD one is kept: the clipboard still reaches Orgo's VNC viewer. Only a process whose whole command line is the
84
+ * PRIMARY one's is ended (pgrep -x -f, which never matches this script or itself): SIGTERM, then up to 5 s for it to be
85
+ * gone (a zombie counts as gone). Prints `ended <pids>`, or `none`; exits 1 when one outlives its SIGTERM or pgrep fails.
86
+ */
87
+ export declare const PRIMARY_SYNC_SCRIPT: string;
78
88
  /**
79
89
  * Orgo desktops: see the module's header. A spec's image is "linux" (Orgo's base desktop) or an Orgo template
80
90
  * (namespace/name@version); cpus and memoryMb are Orgo's sizes; the network is none.
package/dist/orgo.js CHANGED
@@ -27,7 +27,7 @@ import { checkMount } from "./mount.js";
27
27
  import { ORGO_API_URL, orgoRest, orgoTerminalChannel, START_LOG } from "./orgo-channel.js";
28
28
  import { OrgoDesktopProvider } from "./orgo-desktop.js";
29
29
  import { workspaceChoices, workspaceHolder } from "./orgo-workspaces.js";
30
- import { COMPUTER_ID, filterProblem, labelProblem, labelsOf, NAME_MAX, NO_DEADLINE, nameParts, orgoMemoryLedger, orgoName, claimProblem, andSettled, inTurn, ownedListing, ownerHashOfLabels, ownerReadBack, refProblem, sameComputer, settleEntry, show, renewEntry, takeEntry, withDeadline, } from "./orgo-names.js";
30
+ import { COMPUTER_ID, filterProblem, labelProblem, labelsOf, NAME_MAX, NO_DEADLINE, nameParts, orgoMemoryLedger, orgoName, orgoSize, claimProblem, andSettled, inTurn, ownedListing, ownerHashOfLabels, ownerReadBack, refProblem, sameComputer, settleEntry, show, renewEntry, takeEntry, withDeadline, } from "./orgo-names.js";
31
31
  import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
32
32
  import { failFor, ok, vendorFail } from "./result.js";
33
33
  import { daemonWatch } from "./screen-watch.js";
@@ -161,6 +161,33 @@ export const LOCKDOWN_SCRIPT = [
161
161
  "EOF",
162
162
  "exit $failed",
163
163
  ].join("\n");
164
+ /**
165
+ * Ends Orgo's PRIMARY autocutsel, so a selection no longer takes the clipboard. Orgo's desktop runs two as root, one per
166
+ * selection (`autocutsel -fork -selection CLIPBOARD` and `... PRIMARY`), both through CUT_BUFFER0: selecting text (Ctrl+L
167
+ * in a file manager selects its location) sets PRIMARY, the PRIMARY one copies that text into the cut buffer, and the
168
+ * CLIPBOARD one then takes CLIPBOARD with it as plain text, so a cut or copy of files is gone before its paste. The
169
+ * CLIPBOARD one is kept: the clipboard still reaches Orgo's VNC viewer. Only a process whose whole command line is the
170
+ * PRIMARY one's is ended (pgrep -x -f, which never matches this script or itself): SIGTERM, then up to 5 s for it to be
171
+ * gone (a zombie counts as gone). Prints `ended <pids>`, or `none`; exits 1 when one outlives its SIGTERM or pgrep fails.
172
+ */
173
+ export const PRIMARY_SYNC_SCRIPT = [
174
+ "# agentrun-computer: orgo-primary-sync",
175
+ 'pids=$(pgrep -x -f "autocutsel -fork -selection PRIMARY")',
176
+ 'case $? in 0) ;; 1) echo none; exit 0 ;; *) echo "pgrep failed"; exit 1 ;; esac',
177
+ // The state is the field after the last ")": the command's name before it, in parentheses, may hold spaces.
178
+ "alive() { [ -e \"/proc/$1\" ] && [ \"$(sed -n 's/.*) \\([A-Z]\\).*/\\1/p' \"/proc/$1/stat\" 2>/dev/null)\" != Z ]; }",
179
+ "kill -TERM $pids 2>/dev/null",
180
+ "i=0",
181
+ "while [ $i -lt 50 ]; do",
182
+ "\tleft=",
183
+ '\tfor p in $pids; do alive "$p" && left="$left $p"; done',
184
+ '\t[ -n "$left" ] || { echo "ended" $pids; exit 0; }',
185
+ "\tsleep 0.1",
186
+ "\ti=$((i + 1))",
187
+ "done",
188
+ 'echo "autocutsel$left outlived SIGTERM"',
189
+ "exit 1",
190
+ ].join("\n");
164
191
  const seconds = (ms) => `${ms / 1000} s`;
165
192
  const pause = (ms, signal) => new Promise((done) => {
166
193
  const timer = setTimeout(finish, ms);
@@ -396,7 +423,7 @@ export class OrgoProvider {
396
423
  const last = await this.#converge(spec, request, labels, made.value, signal);
397
424
  if (last !== undefined)
398
425
  return last;
399
- return ok(prepared.value.length > 0 ? { ...ref, notes: prepared.value } : ref);
426
+ return ok({ ...ref, ...(prepared.value.length > 0 ? { notes: prepared.value } : {}), ...orgoSize(made.value, { cpus: cpu, memoryMb: ram * 1024 }) });
400
427
  }
401
428
  /**
402
429
  * The one computer a request keeps. Two creates of one request in two processes can both find no computer for it
@@ -472,8 +499,15 @@ export class OrgoProvider {
472
499
  if (differ.length > 0)
473
500
  return fail("exists", otherSpecWords(record.name, "was made", differ));
474
501
  const inside = await this.#inside(ref, signal);
475
- if (inside.ok)
476
- return ok(inside.value.length > 0 ? { ...ref, notes: inside.value } : ref);
502
+ if (inside.ok) {
503
+ // The workspace's listing carries no size: Orgo's read of the computer says the one it runs at.
504
+ const read = await this.#get(record.id, signal);
505
+ // A read that fails says no size: the size asked is never taken for the one it runs at.
506
+ if (!read.ok)
507
+ return read;
508
+ const size = orgoSize(read.value, { ...(file.value.cpus === undefined ? {} : { cpus: file.value.cpus }), ...(file.value.memoryMb === undefined ? {} : { memoryMb: file.value.memoryMb }) });
509
+ return ok({ ...ref, ...(inside.value.length > 0 ? { notes: inside.value } : {}), ...size });
510
+ }
477
511
  if (inside.error.code === "aborted")
478
512
  return inside;
479
513
  // Its daemon is not up yet: the create that made it is still preparing it.
@@ -538,6 +572,11 @@ export class OrgoProvider {
538
572
  const locked = await this.#lockDown(ref, socket, signal);
539
573
  if (!locked.ok)
540
574
  return locked;
575
+ // Orgo's PRIMARY autocutsel ended, before any tool runs, so a text selection never replaces a cut; one left running
576
+ // is a warning in the notes, and the create goes on.
577
+ const primary = await this.#endPrimarySync(ref, signal);
578
+ if (!primary.ok)
579
+ return primary;
541
580
  const started = await this.#channel.start(ref.id, ["sh", "-c", commands.init], { how: this.#start, timeoutMs: execMs, ...(signal ? { signal } : {}) });
542
581
  if (!started.ok)
543
582
  return fail(started.error.code, `starting the daemon in ${ref.name} failed: ${started.error.message}`);
@@ -555,6 +594,7 @@ export class OrgoProvider {
555
594
  ...inside.value,
556
595
  `Orgo's own network listens on ${ports.value.join(", ") || "no TCP port"} (TCP, as root reads it); the tools' probe was refused at each and at ${ORGO_AGENT_PORTS.join(", ")}, on both loopbacks`,
557
596
  `Orgo's desktop sockets made root's alone: ${locked.value.join(", ") || "none"} (the display's own, ${socket}, left to the tools)`,
597
+ primary.value,
558
598
  ]);
559
599
  }
560
600
  finally {
@@ -570,6 +610,26 @@ export class OrgoProvider {
570
610
  return fail("refused", `making Orgo's desktop sockets root's alone in ${ref.name} failed (exit ${ran.value.exitCode}): ${ran.value.output.trim().slice(0, 200)}`);
571
611
  return ok(ran.value.output.split("\n").flatMap((line) => (line.startsWith("locked ") ? [line.slice("locked ".length).trim()] : [])));
572
612
  }
613
+ /**
614
+ * Orgo's PRIMARY autocutsel ended (PRIMARY_SYNC_SCRIPT), and the create's note on it. One left running costs a cut its
615
+ * paste, not the desktop: one that outlives its SIGTERM, a pgrep that fails, or a channel that can't run the script is a
616
+ * warning in the note, and the create goes on. An abort alone fails it.
617
+ */
618
+ async #endPrimarySync(ref, signal) {
619
+ const stillRunning = (pid) => `Orgo's PRIMARY autocutsel is still running (${pid}): selecting text after a cut replaces the clipboard, so linux.files.move may paste text`;
620
+ const ran = await this.#channel.run(ref.id, ["sh", "-c", PRIMARY_SYNC_SCRIPT], { timeoutMs: this.#timeouts.execMs, ...(signal ? { signal } : {}) });
621
+ if (!ran.ok)
622
+ return ran.error.code === "aborted" ? ran : ok(stillRunning(`pid could not be read: ${ran.error.message}`));
623
+ const { exitCode, output } = ran.value;
624
+ if (exitCode !== 0) {
625
+ const left = /^autocutsel (.+) outlived SIGTERM$/m.exec(output)?.[1].trim().split(/\s+/);
626
+ return ok(stillRunning(left ? `pid ${left.join(", ")}` : `pid could not be read: ${output.trim().slice(0, 200) || `exit ${exitCode}`}`));
627
+ }
628
+ const ended = /^ended (.+)$/m.exec(output)?.[1].trim().split(/\s+/) ?? [];
629
+ return ok(ended.length > 0
630
+ ? `Orgo's PRIMARY autocutsel ended (pid ${ended.join(", ")}), so a text selection no longer replaces the clipboard; its CLIPBOARD one runs on for the VNC viewer`
631
+ : "no PRIMARY autocutsel ran in Orgo's desktop");
632
+ }
573
633
  /** The TCP ports root listens on in Orgo's own network, sorted, read through the channel. */
574
634
  async #rootPorts(ref, signal) {
575
635
  const read = await this.#channel.run(ref.id, ["sh", "-c", PORTS_SCRIPT], { timeoutMs: this.#timeouts.execMs, ...(signal ? { signal } : {}) });