@parcha/agentrun-computer 0.1.0-beta.39 → 0.1.0-beta.41

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 (57) hide show
  1. package/README.md +56 -21
  2. package/box/Dockerfile +11 -58
  3. package/box/README.md +15 -2
  4. package/box/build-daytona.py +4 -2
  5. package/box/build-e2b.mjs +1 -1
  6. package/box/install.sh +148 -0
  7. package/box/recipe.mjs +12 -10
  8. package/dist/agent37.js +2 -1
  9. package/dist/attach.d.ts +46 -1
  10. package/dist/attach.js +48 -4
  11. package/dist/box-image.d.ts +2 -0
  12. package/dist/box-image.js +10 -0
  13. package/dist/computerd-linux-amd64 +0 -0
  14. package/dist/computerd-linux-arm64 +0 -0
  15. package/dist/computerd.json +2 -2
  16. package/dist/conformance/cases/isolation.js +17 -1
  17. package/dist/conformance/cases/lifetime.js +30 -0
  18. package/dist/conformance/cases/provider.js +63 -1
  19. package/dist/conformance/cli.js +27 -5
  20. package/dist/conformance/daytona.d.ts +25 -0
  21. package/dist/conformance/daytona.js +26 -1
  22. package/dist/conformance/exec-stream.d.ts +37 -7
  23. package/dist/conformance/exec-stream.js +349 -89
  24. package/dist/conformance/report.js +3 -0
  25. package/dist/conformance/runner.js +134 -12
  26. package/dist/conformance/sweep.d.ts +7 -2
  27. package/dist/conformance/sweep.js +17 -7
  28. package/dist/conformance/types.d.ts +42 -0
  29. package/dist/daytona.d.ts +8 -1
  30. package/dist/daytona.js +126 -101
  31. package/dist/descriptor.d.ts +22 -1
  32. package/dist/descriptor.js +18 -0
  33. package/dist/descriptors/daytona.d.ts +12 -3
  34. package/dist/descriptors/daytona.js +15 -7
  35. package/dist/descriptors/index.d.ts +8 -1
  36. package/dist/e2b.js +1 -1
  37. package/dist/host.d.ts +91 -26
  38. package/dist/host.js +5 -0
  39. package/dist/hosted/framed-exec.d.ts +38 -0
  40. package/dist/hosted/framed-exec.js +119 -0
  41. package/dist/hosted/process.d.ts +13 -5
  42. package/dist/hosted/process.js +39 -14
  43. package/dist/hosted/provider.d.ts +48 -6
  44. package/dist/hosted/provider.js +435 -64
  45. package/dist/hosted/rest.d.ts +29 -0
  46. package/dist/hosted/rest.js +91 -6
  47. package/dist/hosted/scripts.d.ts +58 -0
  48. package/dist/hosted/scripts.js +138 -1
  49. package/dist/hosted/ssh-exec.d.ts +7 -6
  50. package/dist/hosted/ssh-exec.js +35 -52
  51. package/dist/hosted/values.d.ts +1 -1
  52. package/dist/index.d.ts +2 -2
  53. package/dist/index.js +2 -2
  54. package/dist/kinds.d.ts +2 -0
  55. package/dist/modal.js +21 -8
  56. package/dist/providers.d.ts +4 -2
  57. package/package.json +1 -1
package/dist/host.d.ts CHANGED
@@ -23,12 +23,18 @@ export interface MachineHost {
23
23
  * carries req.name where the vendor can find it again by listing: the vendor's native name, or a label. A native name
24
24
  * the vendor already has throws exists (a REST host's named call: hosted/rest.ts), and the adapter adopts the machine
25
25
  * the name lists, as a retry does. An answer that never comes is not a machine the adapter forgets: it lists by
26
- * req.labels and deletes what it finds.
26
+ * req.labels and deletes what it finds. A host with facts.labels "machine" keeps neither: req.name is its native
27
+ * name where it has one (Machine.name), and the adapter writes req.labels into the machine itself.
27
28
  */
28
29
  create(req: MachineRequest, ctx: HostCall): Promise<{
29
30
  id: string;
30
31
  }>;
31
- /** One machine as the vendor reads it now; undefined once the vendor no longer has it (not found is that, or a HostError not_found). */
32
+ /**
33
+ * One machine as the vendor reads it now; undefined once the vendor no longer has it (not found is that, or a
34
+ * HostError not_found), and for a record the vendor keeps of a machine that is deleted and will not come back
35
+ * (Hyperbrowser's closed, Blaxel's TERMINATED), which list leaves out too. gone is one still being destroyed: it holds
36
+ * the wait after a delete, so a host that reads a kept record gone waits out goneMs on every delete.
37
+ */
32
38
  get(id: string, ctx: HostCall): Promise<Machine | undefined>;
33
39
  /**
34
40
  * The machines of the account the vendor's listing shows for these labels, every page, within ctx.timeoutMs in all.
@@ -37,7 +43,10 @@ export interface MachineHost {
37
43
  * timer moved: E2B's). It may answer more machines than carry all the labels (a vendor that filters by some, or
38
44
  * none): the adapter keeps those whose get does. A listing may lag a create: two creates of one request on two
39
45
  * provider instances can then both make a machine, and the adapter deletes every one but the oldest (createdAt), so
40
- * a vendor may see a second create deleted.
46
+ * a vendor may see a second create deleted. With facts.labels "machine" it lists by req.name where the vendor lists by
47
+ * name, else every machine: the adapter keeps those of the name and of our image (Machine.image), then reads each
48
+ * one's labels from inside it; one whose read fails or does not end is left out of that listing, in words, except
49
+ * from a listing by a request's name, which that read fails.
41
50
  */
42
51
  list(labels: Record<string, string>, ctx: HostCall): Promise<Machine[]>;
43
52
  /**
@@ -51,21 +60,31 @@ export interface MachineHost {
51
60
  *
52
61
  * exec is the whole protocol: the adapter installs and starts its daemon through it, then talks to the daemon over
53
62
  * one exec'd process's stdin and stdout for the computer's whole life (the stdio bridge, spec/computer/stdio.md). So:
54
- * - Two-way and live. Each write() reaches the process's stdin as it is written, and stdout and stderr bytes come
55
- * back as the process writes them, while it runs. Not request and response, never held until the process exits.
56
- * - Byte-exact. Every byte value 0-255, both ways: no UTF-8 decode or encode, no newline translation, no terminal,
57
- * nothing added or dropped. A client that hands output over as text breaks this (E2B's commands.run does).
63
+ * - Two-way and live. Each write() reaches the process's stdin as it is written, and stdout and stderr come back as
64
+ * the process writes them, while it runs. Not request and response, never held until the process exits.
65
+ * - Text intact. UTF-8 text both ways, every code point as it was: long lines, \r and \r\n kept (no terminal, no
66
+ * newline translation), nothing added or dropped. Everything the adapter sends or reads is text (the bridge's JSON
67
+ * lines, its upload in base64), and each write() holds whole characters. An exec that carries bytes carries this. A
68
+ * vendor whose input call ends what it is given with a newline (Daytona's) holds a write's last partial line until
69
+ * its newline or end(), so the process reads its stdin as written: the bridge's lines end in one, and what is
70
+ * read by length is followed by end().
58
71
  * - No timeout. The process runs until it exits or kill() ends it: a vendor's command timeout, and any idle timeout
59
72
  * on the stream, are off.
60
- * - stdout and stderr stay apart. wait() answers the process's own exit code. kill() ends the process itself.
61
- * The process reads what write() gives until end(); the adapter ends stdin at once where it gives none. The exec
62
- * pre-check (conformance --exec-stream, src/conformance/exec-stream.ts) checks each of these on a machine made by
63
- * hand, with exec alone.
73
+ * - stdout and stderr stay apart. wait() answers the process's own exit code. kill() ends the process in the
74
+ * machine, not only its streams.
75
+ * end() ends stdin where the vendor can (the adapter calls it at once for a command it gives no input); where it
76
+ * can't, end() does nothing, and nothing the adapter runs waits for it: its upload and its label file's write read a
77
+ * length, a root command's input is one line, its bridge ends by kill(). A vendor whose exec comes in pieces (a start, an event stream, a call per write, no end or no kill) builds
78
+ * this from them with framedExec (./hosted/framed-exec.ts), as Daytona's does. The exec pre-check (conformance --exec-stream,
79
+ * src/conformance/exec-stream.ts) checks each of these on a machine made by hand, with exec alone.
80
+ *
81
+ * Every host has it but one whose facts.connect is "dial", which has none (and no upload): its machine's computerd
82
+ * dials the server instead.
64
83
  */
65
- exec(id: string, argv: readonly string[], ctx: HostCall): Promise<MachineProcess>;
84
+ exec?(id: string, argv: readonly string[], ctx: HostCall): Promise<MachineProcess>;
66
85
  /**
67
86
  * Puts bytes at path in the machine, as root. Optional: a vendor with no file API leaves it out, and the adapter
68
- * streams the file through exec's stdin.
87
+ * streams the file through exec's stdin as base64 text, which root decodes (`base64 -d`, in coreutils and busybox).
69
88
  */
70
89
  upload?(id: string, path: string, bytes: Uint8Array, ctx: HostCall): Promise<void>;
71
90
  /**
@@ -80,7 +99,7 @@ export interface MachineHost {
80
99
  * (a HostError limit, in words) when no end the vendor takes lands there without moving it earlier than it is or past
81
100
  * the most: nothing moves then. The adapter reads the end back with get (deadlineOf, the deadline label: a vendor that
82
101
  * keeps no label change reads its moved timer as that label), and init's deadline follows it. Optional: a host without
83
- * it has no extend.
102
+ * it has no extend, and a host with facts.labels "machine" is refused one.
84
103
  */
85
104
  extend?(id: string, endsAt: Date, ctx: HostCall): Promise<void>;
86
105
  /**
@@ -89,6 +108,11 @@ export interface MachineHost {
89
108
  */
90
109
  check?(spec: Partial<ComputerSpec>): Refusal[];
91
110
  }
111
+ /**
112
+ * How far past the most a deadline may reach MachineRequest.backstopAt is: the janitor ends the machine first while the
113
+ * server runs, and the vendor's clock may be off from the server's.
114
+ */
115
+ export declare const BACKSTOP_MARGIN_MS = 300000;
92
116
  /** A host's failure whose code it knows: thrown by a host member, read by the adapter as that code, in these words. */
93
117
  export declare class HostError extends Error {
94
118
  readonly code: ComputerErrorCode;
@@ -112,10 +136,17 @@ export interface MachineRequest {
112
136
  labels: Record<string, string>;
113
137
  /** The spec's lifetime: the vendor's timer (facts.lifetime "vendor"); a janitor's host may leave it. */
114
138
  lifetimeMs: number;
139
+ /**
140
+ * An ISO time a margin past the most the machine's deadline may reach: create + maxLifetimeMs + BACKSTOP_MARGIN_MS. A
141
+ * janitor's host whose vendor has a delete or stop timer of its own sets it here, so the machine still ends when the
142
+ * server that made it is gone. A vendor-lifetime host ignores it.
143
+ */
144
+ backstopAt: string;
115
145
  /**
116
146
  * Whether the machine reaches out: true for an Archil computer's root, which reaches Archil, and for a network open
117
- * or a list, whose egress proxy init starts outside its tools' network (./hosted/network.ts). Its tools' own network
118
- * is init's, loopback alone, read from inside, either way.
147
+ * or a list, whose egress proxy init starts outside its tools' network (./hosted/network.ts), and for every dial
148
+ * machine (boot), which fetches its daemon from the server and dials it. Its tools' own network is init's, loopback
149
+ * alone, read from inside, either way.
119
150
  */
120
151
  egress: boolean;
121
152
  /** facts.daemon "pid1" alone: the machine's main process (the entrypoint that waits for the daemon, then becomes init). */
@@ -126,6 +157,15 @@ export interface MachineRequest {
126
157
  memoryMb?: number;
127
158
  /** With facts.user: the spec's user, uid:gid. */
128
159
  user?: string;
160
+ /**
161
+ * facts.connect "dial" alone: what the machine's environment holds, every name and value as given, in the vendor's
162
+ * secret-env field where it has one. The box image's agentrun-dial reads it (spec/computer/attach.md, Hosted machines
163
+ * that dial): AGENTRUN_ATTACH_URL, AGENTRUN_ATTACH_TOKEN, AGENTRUN_DAEMON_URL, AGENTRUN_DAEMON_SHA256 and
164
+ * AGENTRUN_INIT_ARGS.
165
+ */
166
+ boot?: {
167
+ env: Record<string, string>;
168
+ };
129
169
  }
130
170
  /**
131
171
  * One machine as the vendor reads it back. The adapter holds the rest itself: what create asked is in the labels, what
@@ -133,8 +173,19 @@ export interface MachineRequest {
133
173
  */
134
174
  export interface Machine {
135
175
  id: string;
136
- /** Every label it carries, the adapter's own included. */
176
+ /** Every label it carries, the adapter's own included; with facts.labels "machine", none (the adapter reads them). */
137
177
  labels: Record<string, string>;
178
+ /**
179
+ * With facts.labels "machine": the vendor's native name, the MachineRequest.name create gave it, where the vendor
180
+ * keeps one. A machine of a request's name whose labels are not written yet is the request's (provider.md).
181
+ */
182
+ name?: string;
183
+ /**
184
+ * The image the vendor reads back for this machine. Required in practice with facts.labels "machine": list runs the
185
+ * label read only in a machine of the provider's image option or a box image (isBoxImage), and leaves one with none
186
+ * out, in words.
187
+ */
188
+ image?: string;
138
189
  /**
139
190
  * starting: not yet running; stopped: there, not running, and not being deleted (paused, asleep): listed, so the
140
191
  * janitor still ends it; gone: being deleted, ended, or failed (why says how).
@@ -154,9 +205,9 @@ export interface Machine {
154
205
  export interface MachineProcess {
155
206
  stdout: AsyncIterable<Uint8Array>;
156
207
  stderr: AsyncIterable<Uint8Array>;
157
- /** Writes to its stdin, in order; rejects once the process has ended. */
208
+ /** Writes UTF-8 text to its stdin, in order, whole characters each; rejects once the process has ended. */
158
209
  write(bytes: Uint8Array): Promise<void>;
159
- /** Ends its stdin, so it reads end of file. */
210
+ /** Ends its stdin, so it reads end of file, where the vendor can; else nothing (exec's doc). */
160
211
  end(): Promise<void>;
161
212
  /** Its exit code once it has ended. */
162
213
  wait(): Promise<number>;
@@ -174,9 +225,10 @@ export type HostDescriptor = Pick<ProviderDescriptor, "id" | "label" | "network"
174
225
  */
175
226
  export interface HostFacts {
176
227
  /**
177
- * child: the vendor's agent is the machine's first process and starts init, after the adapter closes the session
178
- * buses in /tmp (/tmp/dbus-*) to the computer's user, since a network namespace does not cut a path socket. pid1:
179
- * init is the machine's main process (Modal's, whose sandbox ends when it does), started by request.command.
228
+ * child: the vendor starts the adapter's processes through exec, and the adapter starts init that way at boot, after
229
+ * it closes the session buses in /tmp (/tmp/dbus-*) to the computer's user, since a network namespace does not cut a
230
+ * path socket. pid1: init is the machine's main process (Modal's, whose sandbox ends when it does), started by
231
+ * request.command.
180
232
  */
181
233
  daemon: "child" | "pid1";
182
234
  isolation: ComputerCapabilities["isolation"];
@@ -194,9 +246,14 @@ export interface HostFacts {
194
246
  /**
195
247
  * The most a machine's labels may be, the adapter's own with the caller's: count, how many; bytes, every name and
196
248
  * value together, the adapter's at their longest. Past either, check() refuses, and so create, before any host call.
197
- * Absent: no bound. packed: the host stores the labels as packLabels packs them (./hosted/values.ts: one name to
198
- * list by, the map in parts of at most valueBytes each) and get answers unpackLabels' map; count and bytes are then
199
- * the packed labels'.
249
+ * Absent: no bound. packed: the adapter packs the labels it gives create (packLabels, ./hosted/values.ts: one name to
250
+ * list by, the map in parts of at most valueBytes each), unpacks those get and list answer, and asks list for that
251
+ * name alone; the host stores and answers them as they are. count and bytes are then the packed labels'. "machine":
252
+ * the vendor keeps no labels, so the adapter writes them as JSON to a root-only file in the machine (LABEL_FILE,
253
+ * ./hosted/scripts.ts) right after it runs, and reads them back from it: at most 64 KiB as JSON, what a run's output
254
+ * keeps (OUTPUT_MAX, ./hosted/process.ts). Only with lifetime "vendor", since a machine whose labels were never
255
+ * written is ended by the vendor's timer alone, and no extend. get and list answer each machine's image
256
+ * (Machine.image): the labels are read only in one of ours.
200
257
  */
201
258
  labels?: {
202
259
  count?: number;
@@ -204,11 +261,19 @@ export interface HostFacts {
204
261
  packed?: {
205
262
  valueBytes?: number;
206
263
  };
207
- };
264
+ } | "machine";
208
265
  /**
209
266
  * Paths of the vendor's image that root runs or reads and whose permissions its template build sets wider than
210
267
  * root's: create makes each root's alone (owned by root, writable by no group or other user), and everything under a
211
268
  * directory, before the daemon's upload, so the computer's user can change nothing root runs. Default none.
212
269
  */
213
270
  rootOnly?: readonly string[];
271
+ /**
272
+ * dial: the machine's computerd dials the server, and the host has no exec and no upload. The vendor boots the box
273
+ * image with MachineRequest.boot.env, where agentrun-dial fetches the server's daemon, checks its sha256, starts init
274
+ * and dials the attach route with the machine's own token; every connection goes over that socket
275
+ * (HostedOptions.dial). Not with labels "machine", which are read through exec. Absent: the adapter connects through
276
+ * exec.
277
+ */
278
+ connect?: "dial";
214
279
  }
package/dist/host.js CHANGED
@@ -1,3 +1,8 @@
1
+ /**
2
+ * How far past the most a deadline may reach MachineRequest.backstopAt is: the janitor ends the machine first while the
3
+ * server runs, and the vendor's clock may be off from the server's.
4
+ */
5
+ export const BACKSTOP_MARGIN_MS = 300_000;
1
6
  /** A host's failure whose code it knows: thrown by a host member, read by the adapter as that code, in these words. */
2
7
  export class HostError extends Error {
3
8
  code;
@@ -0,0 +1,38 @@
1
+ import type { HostCall, MachineProcess } from "../host.js";
2
+ /** One event of a process: output on stdout or stderr, as text or as the base64 of its bytes; or its exit code. */
3
+ export type FramedEvent = {
4
+ stream: "stdout" | "stderr";
5
+ text: string;
6
+ } | {
7
+ stream: "stdout" | "stderr";
8
+ base64: string;
9
+ } | {
10
+ exit: number;
11
+ };
12
+ /** A vendor's exec, as calls about one process: P is what start answers, the vendor's own handle on it (an id). */
13
+ export interface ExecPieces<P> {
14
+ /** Starts argv in the machine as root, within ctx, and answers once it has started. */
15
+ start(argv: readonly string[], ctx: HostCall): Promise<P>;
16
+ /**
17
+ * The process's events from its start, in order; an end with no exit event is an exit the vendor never read (-1),
18
+ * and one that throws fails wait() with its error. framedExec stops reading at the exit event, which returns the
19
+ * iterator: a generator's finally lets go of what it holds.
20
+ */
21
+ events(handle: P): AsyncIterable<FramedEvent>;
22
+ /** One call that hands text to the process's stdin, answered once the vendor took it. */
23
+ write(handle: P, text: string): Promise<void>;
24
+ /**
25
+ * Ends the process's stdin. Leave it out where the vendor has no end of file: end() then does nothing. The cost: a
26
+ * command that reads stdin to its end (cat, a sh reading its script) never ends, and only kill() stops it. Nothing
27
+ * the adapter runs does (its upload reads a length, a root command's input is one line, its bridge ends by kill).
28
+ */
29
+ end?(handle: P): Promise<void>;
30
+ /**
31
+ * Ends the process in the machine. Leave it out where the vendor has none: the process then starts under
32
+ * PID_WRAPPER (./scripts.ts), which writes its pid and its start time on stderr first (framedExec takes that line off),
33
+ * and kill() starts pidKill, which kills that pid, and every process under it, only while that pid has that start time.
34
+ */
35
+ kill?(handle: P): Promise<void>;
36
+ }
37
+ /** argv started through a vendor's pieces, as the MachineProcess exec answers. */
38
+ export declare function framedExec<P>(pieces: ExecPieces<P>, argv: readonly string[], ctx: HostCall): Promise<MachineProcess>;
@@ -0,0 +1,119 @@
1
+ // exec for a vendor whose process comes in pieces: a call that starts it, a stream of its events, a call per write to
2
+ // its stdin, and, where the vendor has them, a call that ends its stdin and one that kills it. framedExec turns those
3
+ // pieces into the MachineProcess the adapter reads (../host.ts, exec), so a vendor writes only its own calls. It owns
4
+ // the rest: the writes go one call after another, in order, each answered before the next starts; output becomes
5
+ // bytes, its events read no faster than the caller reads it; and a vendor with no kill gets one by pid. PROVIDERS.md, "Exec shapes that work", has a worked example.
6
+ import { once } from "node:events";
7
+ import { PassThrough } from "node:stream";
8
+ import { PID_WRAPPER, pidKill, pidLine } from "./scripts.js";
9
+ /** argv started through a vendor's pieces, as the MachineProcess exec answers. */
10
+ export async function framedExec(pieces, argv, ctx) {
11
+ // With no vendor kill, stderr's first line is the pid and its start time (./scripts.ts, PID_WRAPPER): taken off, and
12
+ // the rest is the process's own.
13
+ const line = pieces.kill === undefined ? pidLine() : undefined;
14
+ const handle = await pieces.start(line ? [...PID_WRAPPER, ...argv] : argv, ctx);
15
+ const stdout = new PassThrough();
16
+ const stderr = new PassThrough();
17
+ // ended: the events stopped, so output and writes are done with. exitRead: the process's own exit came among them; a
18
+ // stream that broke without one leaves a process that may still run, which kill() still ends by its pid.
19
+ let ended = false;
20
+ let exitRead = false;
21
+ const killed = new AbortController();
22
+ /**
23
+ * Output on: while its reader is behind (the stream's buffer full), the events wait, until it drains or kill(). A
24
+ * reader that let go (a stream destroyed) drops the rest, so the exit still comes.
25
+ */
26
+ const push = async (stream, bytes) => {
27
+ if (stream.writableEnded || stream.destroyed || stream.write(bytes))
28
+ return;
29
+ // One signal for both waits, aborted after: the one that lost leaves no listener behind.
30
+ const waited = new AbortController();
31
+ const signal = AbortSignal.any([killed.signal, waited.signal]);
32
+ await Promise.race([once(stream, "drain", { signal }), once(stream, "close", { signal })]).catch(() => { });
33
+ waited.abort();
34
+ };
35
+ const toStderr = async (bytes) => {
36
+ const own = line ? line.take(bytes) : bytes;
37
+ if (own.length > 0)
38
+ await push(stderr, own);
39
+ };
40
+ const exited = (async () => {
41
+ let code = -1;
42
+ let broke;
43
+ try {
44
+ for await (const event of pieces.events(handle)) {
45
+ if ("exit" in event) {
46
+ code = event.exit;
47
+ exitRead = true;
48
+ break;
49
+ }
50
+ const bytes = "text" in event ? Buffer.from(event.text, "utf8") : Buffer.from(event.base64, "base64");
51
+ if (event.stream === "stdout")
52
+ await push(stdout, bytes);
53
+ else
54
+ await toStderr(bytes);
55
+ }
56
+ }
57
+ catch (error) {
58
+ // A stream that broke: no exit code was read, and wait() fails in its words.
59
+ broke = error;
60
+ }
61
+ ended = true;
62
+ line?.end();
63
+ stdout.end();
64
+ stderr.end();
65
+ if (broke !== undefined)
66
+ throw broke;
67
+ return code;
68
+ })();
69
+ // Nobody may wait (the bridge ends by kill): a broken stream is then no unhandled rejection.
70
+ exited.catch(() => { });
71
+ // The writes as one queue: each call starts once the one before it answered, and one that failed fails every one after.
72
+ // ignoreBOM: a U+FEFF that starts stdin is text like any other, never a mark to drop.
73
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
74
+ let queue = Promise.resolve();
75
+ const send = (text) => {
76
+ if (ended)
77
+ return Promise.reject(new Error("the process has ended"));
78
+ const sent = queue.then(() => (text === "" ? undefined : pieces.write(handle, text)));
79
+ sent.catch(() => { });
80
+ queue = sent;
81
+ return sent;
82
+ };
83
+ return {
84
+ stdout,
85
+ stderr,
86
+ write: (bytes) => send(decoder.decode(bytes, { stream: true })),
87
+ end: async () => {
88
+ // A process that has ended, as one that read all it wanted can before its end (the upload), has no stdin to end.
89
+ if (ended)
90
+ return;
91
+ await send(decoder.decode());
92
+ await pieces.end?.(handle);
93
+ },
94
+ wait: () => exited,
95
+ kill: async () => {
96
+ killed.abort();
97
+ try {
98
+ if (pieces.kill)
99
+ await pieces.kill(handle);
100
+ else if (line) {
101
+ // Not once its exit was read; and after a stream that broke, only while the pid still has its start time: by
102
+ // then the pid may be another process's.
103
+ const target = await line.pid(ctx.timeoutMs);
104
+ if (target !== undefined && !exitRead) {
105
+ const killer = await pieces.start(pidKill(target), { timeoutMs: ctx.timeoutMs });
106
+ for await (const event of pieces.events(killer))
107
+ if ("exit" in event)
108
+ break;
109
+ }
110
+ }
111
+ }
112
+ catch {
113
+ // Best effort: kill never throws.
114
+ }
115
+ stdout.end();
116
+ stderr.end();
117
+ },
118
+ };
119
+ }
@@ -2,6 +2,8 @@ import { type HostCall, type MachineHost } from "../host.js";
2
2
  import type { ArchilRoot } from "../mount-archil.js";
3
3
  import type { ComputerConnection } from "../provider.js";
4
4
  import { type ComputerErrorCode, type Result } from "../result.js";
5
+ /** The host's exec; a dial host has none, and a call of it throws unsupported, in words. */
6
+ export declare function execOf(host: MachineHost): NonNullable<MachineHost["exec"]>;
5
7
  /** What a call's race adds to the bound it gives the vendor's own call, so the vendor's timeout, not the race, reports a slow call. */
6
8
  export declare const CALL_SLACK_MS = 5000;
7
9
  export declare const seconds: (ms: number) => string;
@@ -45,18 +47,24 @@ export interface RunResult {
45
47
  stdout: string;
46
48
  stderr: string;
47
49
  }
50
+ export declare const OUTPUT_MAX: number;
48
51
  /**
49
- * argv run in the machine as root through exec, stdin (when given) written and ended, waited for until it ends, within
50
- * ms and the caller's signal; a process past them is killed, and the kill waited for at most ms (and CALL_SLACK_MS).
51
- * A non-zero exit is a result, not an error.
52
+ * argv run in the machine as root through exec, stdin (when given: one write per piece, each whole UTF-8 text) written
53
+ * and ended, waited for until it ends, within ms and the caller's signal; a process past them is killed, and the kill
54
+ * waited for at most ms (and CALL_SLACK_MS). A non-zero exit is a result, not an error.
52
55
  */
53
56
  export declare function runToExit(host: MachineHost, id: string, argv: readonly string[], { stdin, ms, signal, what }: {
54
- stdin?: Uint8Array;
57
+ stdin?: Iterable<Uint8Array>;
55
58
  ms: number;
56
59
  signal?: AbortSignal;
57
60
  what: string;
58
61
  }): Promise<Result<RunResult>>;
59
- /** The default upload, for a vendor with no file API: the bytes streamed into `cat` as root through exec's stdin. */
62
+ /**
63
+ * The default upload, for a vendor with no file API: the bytes as base64 text through exec's stdin, in pieces, so a
64
+ * vendor whose stdin takes one request at a time (E2B's sendStdin) is never handed a whole binary, and exec carries text
65
+ * alone. root decodes it into the file (`base64 -d`, which coreutils and busybox both have). head reads the text's length
66
+ * and no more, so the upload never waits for an end of stdin a vendor may not give (hosted/framed-exec.ts).
67
+ */
60
68
  export declare function uploadThroughExec(host: MachineHost, id: string, path: string, bytes: Uint8Array, ms: number, signal?: AbortSignal): Promise<Result<void>>;
61
69
  /**
62
70
  * The root channel into a machine (for the shared Archil steps): argv as root through exec, stdin (one line, then
@@ -5,6 +5,13 @@ import { PassThrough, Writable } from "node:stream";
5
5
  import { DaemonClient } from "../client.js";
6
6
  import { HostError } from "../host.js";
7
7
  import { failFor, ok } from "../result.js";
8
+ /** The host's exec; a dial host has none, and a call of it throws unsupported, in words. */
9
+ export function execOf(host) {
10
+ return (host.exec?.bind(host) ??
11
+ (() => {
12
+ throw new HostError("unsupported", `${host.descriptor.label}'s machines have no exec: they dial this server (facts.connect "dial")`);
13
+ }));
14
+ }
8
15
  /** What a call's race adds to the bound it gives the vendor's own call, so the vendor's timeout, not the race, reports a slow call. */
9
16
  export const CALL_SLACK_MS = 5_000;
10
17
  export const seconds = (ms) => `${ms / 1000} s`;
@@ -139,30 +146,29 @@ async function drain(stream, max) {
139
146
  }
140
147
  return kept;
141
148
  }
142
- const OUTPUT_MAX = 64 * 1024;
149
+ export const OUTPUT_MAX = 64 * 1024;
143
150
  /**
144
- * argv run in the machine as root through exec, stdin (when given) written and ended, waited for until it ends, within
145
- * ms and the caller's signal; a process past them is killed, and the kill waited for at most ms (and CALL_SLACK_MS).
146
- * A non-zero exit is a result, not an error.
151
+ * argv run in the machine as root through exec, stdin (when given: one write per piece, each whole UTF-8 text) written
152
+ * and ended, waited for until it ends, within ms and the caller's signal; a process past them is killed, and the kill
153
+ * waited for at most ms (and CALL_SLACK_MS). A non-zero exit is a result, not an error.
147
154
  */
148
155
  export async function runToExit(host, id, argv, { stdin, ms, signal, what }) {
149
156
  const fail = failFor(host.descriptor.id);
150
- const started = await hostCall(host, what, (ctx) => host.exec(id, argv, ctx), ms, signal);
157
+ const started = await hostCall(host, what, (ctx) => execOf(host)(id, argv, ctx), ms, signal);
151
158
  if (!started.ok)
152
159
  return started;
153
160
  const proc = started.value;
154
161
  const out = drain(proc.stdout, OUTPUT_MAX);
155
162
  const err = drain(proc.stderr, OUTPUT_MAX);
156
163
  const ran = (async () => {
157
- // In pieces, so a vendor whose stdin takes one request at a time (E2B's sendStdin) is never handed a whole binary;
158
- // with none to give, stdin ends at once, so the process reads end of file (one that ended already has no stdin). Not
164
+ // With none to give, stdin ends at once, so the process reads end of file (one that ended already has no stdin). Not
159
165
  // awaited: a vendor's close that stalls (E2B's closeStdin is a request of its own) never holds up a command that
160
166
  // reads no input.
161
167
  if (stdin === undefined)
162
168
  Promise.resolve().then(() => proc.end()).catch(() => { });
163
169
  else {
164
- for (let at = 0; at < stdin.length; at += STDIN_CHUNK)
165
- await proc.write(stdin.subarray(at, at + STDIN_CHUNK));
170
+ for (const piece of stdin)
171
+ await proc.write(piece);
166
172
  await proc.end();
167
173
  }
168
174
  const exitCode = await proc.wait();
@@ -178,10 +184,29 @@ export async function runToExit(host, id, argv, { stdin, ms, signal, what }) {
178
184
  }
179
185
  return result;
180
186
  }
181
- const STDIN_CHUNK = 256 * 1024;
182
- /** The default upload, for a vendor with no file API: the bytes streamed into `cat` as root through exec's stdin. */
187
+ /** A piece of the upload: 192 KiB, which base64 writes as 256 KiB of text, padded at the file's end alone. */
188
+ const UPLOAD_PIECE = 192 * 1024;
189
+ /** The bytes as base64 text, a piece at a time: no more of it in memory at once than one piece. */
190
+ function* base64Pieces(bytes) {
191
+ for (let at = 0; at < bytes.length; at += UPLOAD_PIECE) {
192
+ const piece = Buffer.from(bytes.buffer, bytes.byteOffset + at, Math.min(UPLOAD_PIECE, bytes.length - at));
193
+ yield Buffer.from(piece.toString("base64"), "latin1");
194
+ }
195
+ }
196
+ /**
197
+ * The default upload, for a vendor with no file API: the bytes as base64 text through exec's stdin, in pieces, so a
198
+ * vendor whose stdin takes one request at a time (E2B's sendStdin) is never handed a whole binary, and exec carries text
199
+ * alone. root decodes it into the file (`base64 -d`, which coreutils and busybox both have). head reads the text's length
200
+ * and no more, so the upload never waits for an end of stdin a vendor may not give (hosted/framed-exec.ts).
201
+ */
183
202
  export async function uploadThroughExec(host, id, path, bytes, ms, signal) {
184
- const ran = await runToExit(host, id, ["sh", "-c", 'umask 077 && cat > "$1"', "sh", path], { stdin: bytes, ms, ...(signal ? { signal } : {}), what: `the upload to ${path}` });
203
+ const length = 4 * Math.ceil(bytes.length / 3);
204
+ const ran = await runToExit(host, id, ["sh", "-c", 'umask 077 && head -c "$2" | base64 -d > "$1"', "sh", path, String(length)], {
205
+ stdin: base64Pieces(bytes),
206
+ ms,
207
+ ...(signal ? { signal } : {}),
208
+ what: `the upload to ${path}`,
209
+ });
185
210
  if (!ran.ok)
186
211
  return ran;
187
212
  return ran.value.exitCode === 0 ? ok(undefined) : failFor(host.descriptor.id)("vendor", `the upload to ${path} exited with ${ran.value.exitCode}: ${`${ran.value.stdout} ${ran.value.stderr}`.trim().slice(0, 300)}`);
@@ -194,7 +219,7 @@ export async function uploadThroughExec(host, id, path, bytes, ms, signal) {
194
219
  export function rootOf(host, id, name) {
195
220
  return {
196
221
  run: async (argv, { stdin, timeoutMs, signal }) => {
197
- const ran = await runToExit(host, id, argv, { ...(stdin === undefined ? {} : { stdin: new Uint8Array(Buffer.from(stdin, "utf8")) }), ms: timeoutMs, ...(signal ? { signal } : {}), what: `root's ${argv[0] === undefined ? "command" : argv[0].split("/").pop()} in ${name}` });
222
+ const ran = await runToExit(host, id, argv, { ...(stdin === undefined ? {} : { stdin: [new Uint8Array(Buffer.from(stdin, "utf8"))] }), ms: timeoutMs, ...(signal ? { signal } : {}), what: `root's ${argv[0] === undefined ? "command" : argv[0].split("/").pop()} in ${name}` });
198
223
  return ran.ok ? ok({ exitCode: ran.value.exitCode, output: `${ran.value.stdout}${ran.value.stderr}` }) : ran;
199
224
  },
200
225
  };
@@ -208,7 +233,7 @@ export async function openBridge(host, id, { argv, name, version, requestMs, hel
208
233
  const fail = failFor(host.descriptor.id);
209
234
  // Never signalled, only raced: the bridge lives on after this call. It has no command timeout, so one the vendor
210
235
  // starts after this was given up on is killed as it lands.
211
- const started = await hostCall(host, `starting the daemon's stdio bridge in ${name}`, (ctx) => host.exec(id, argv, { timeoutMs: ctx.timeoutMs }), requestMs, signal, (late) => late.ok && late.value.kill());
236
+ const started = await hostCall(host, `starting the daemon's stdio bridge in ${name}`, (ctx) => execOf(host)(id, argv, { timeoutMs: ctx.timeoutMs }), requestMs, signal, (late) => late.ok && late.value.kill());
212
237
  if (!started.ok) {
213
238
  const { code, message } = started.error;
214
239
  return code === "timeout" || code === "aborted" ? fail(code, `${message}; a bridge that starts after this is killed`) : started;
@@ -1,5 +1,6 @@
1
+ import { type AttachHub, type MachineTokens } from "../attach.js";
1
2
  import { type DesktopOptions } from "../desktop.js";
2
- import type { Machine, MachineHost } from "../host.js";
3
+ import { type Machine, type MachineHost } from "../host.js";
3
4
  import { type ProviderNote } from "../mount-archil.js";
4
5
  import { type AttachedComputer, type AttachContext, type CallContext, type ComputerCapabilities, type ComputerConnection, type ComputerInfo, type ComputerProvider, type ComputerRef, type ComputerSpec, type CreateContext, type CreatedComputer, type NetworkPolicy, type NetworkSpec, type Refusal, type ReleaseContext, type ReleaseHow } from "../provider.js";
5
6
  import { type Result } from "../result.js";
@@ -22,7 +23,10 @@ export interface HostedTimeouts {
22
23
  listMs: number;
23
24
  /** From a delete to get answering none for the machine. */
24
25
  goneMs: number;
25
- /** The first pause between two reads while release waits; the pauses double up to 5 s. */
26
+ /**
27
+ * The first pause between two reads while release waits; the pauses double up to 5 s. The longest pause between two
28
+ * listings while create waits for the new computer to show: those start at 150 ms and double up to it.
29
+ */
26
30
  pollMs: number;
27
31
  /** How long create waits for the listing to show the new computer. */
28
32
  listedMs: number;
@@ -62,6 +66,27 @@ export interface HostedOptions {
62
66
  * Given to the helper's mount and revoke. Unset or empty, the client reaches Archil as the machine's network allows.
63
67
  */
64
68
  archilEgress?: string;
69
+ /**
70
+ * The image this provider's computers start from, where its setting names one, exactly as the vendor reads it back
71
+ * (Machine.image). With facts.labels "machine", list reads labels only in a machine of this image or a box image
72
+ * (isBoxImage, ../box-image.ts), and check refuses a spec of any other.
73
+ */
74
+ image?: string;
75
+ /** What a host whose facts.connect is "dial" needs: create refuses without it, before any call to the vendor. */
76
+ dial?: HostedDial;
77
+ }
78
+ /** The server a dial host's machines reach, and what it holds of them (MachineHost facts.connect "dial"). */
79
+ export interface HostedDial {
80
+ /**
81
+ * The server's public address, AGENTRUN_PUBLIC_URL: https://, which the vendor's machines must reach (http:// only on
82
+ * 127.0.0.1, for tests). They dial its /v2/computers/attach and fetch the daemon from its /v2/computers/daemon, which
83
+ * serves the build at this provider's daemonPath. Empty or unset: create refuses, in words.
84
+ */
85
+ url?: string;
86
+ /** The server's machine tokens: one minted at each create, revoked at its delete. */
87
+ tokens: MachineTokens;
88
+ /** The server's AttachHub, which the server's attach route gives each minted machine's socket. */
89
+ hub: Pick<AttachHub, "online" | "connection" | "revoke">;
65
90
  }
66
91
  export declare const NAME_LABEL = "agentrun.computer.name";
67
92
  /** The image create was asked for: a vendor may report another name for it (a template's id). */
@@ -72,6 +97,11 @@ export declare const MAX_LABEL = "agentrun.computer.max-deadline";
72
97
  export declare const GPU_LABEL = "agentrun.computer.gpu";
73
98
  /** The adapter's timeouts, the caller's over its defaults: what a host reads for its own requestMs or pollMs. */
74
99
  export declare const timeoutsOf: (timeouts?: Partial<HostedTimeouts>) => HostedTimeouts;
100
+ /**
101
+ * The computerd build a hosted machine of arch runs: HostedProvider's default daemonPath, and the file serve's daemon
102
+ * route serves, so the sha256 a dial machine checks (AGENTRUN_DAEMON_SHA256) is this file's.
103
+ */
104
+ export declare function hostedDaemonPath(arch: "amd64" | "arm64"): string;
75
105
  /** An ISO time a label holds, or undefined when it is missing or not the ISO time create writes. */
76
106
  export declare function isoOf(written: string | undefined): Date | undefined;
77
107
  /**
@@ -141,15 +171,27 @@ export declare class HostedProvider implements ComputerProvider {
141
171
  }
142
172
  /**
143
173
  * The host's listing by labels, bounded by ms: only the machines that carry every one of them, since a vendor's listing
144
- * may answer more (MachineHost.list).
174
+ * may answer more (MachineHost.list). A packed host is asked for PACKED_NAME alone, the name's where one is asked, and
175
+ * its machines' labels unpacked. A host that keeps labels in the machine lists none: its machines of another name are
176
+ * left out, and the rest kept for foundBy to read.
145
177
  */
146
178
  export declare function listedBy(host: MachineHost, what: string, labels: Record<string, string>, ms: number, signal?: AbortSignal): Promise<Result<Machine[]>>;
179
+ /** What foundBy reads with: the timeouts, who hears of a machine a listing leaves out, and the provider's image option. */
180
+ type Finding = Pick<HostedTimeouts, "listMs" | "requestMs"> & {
181
+ onNote?: ProviderNote | undefined;
182
+ image?: string | undefined;
183
+ };
147
184
  /**
148
185
  * The listing finds, get answers (MachineHost.list): the machines the host's listing by labels names, each read now by
149
- * readMachine, within requestMs. One the vendor no longer has (not found) is dropped, and so is one whose get carries
150
- * not every label. A read that fails otherwise fails the whole.
186
+ * readMachine, within requestMs, and its label file where the host keeps labels in the machine. One the vendor no longer
187
+ * has (not found) is dropped, and so is one whose get carries not every label, but a machine of the name asked for whose
188
+ * labels are not written yet. A label file's read that fails or does not end within requestMs leaves its machine out of
189
+ * this listing alone, told through onNote by its id: one wedged machine never holds up the rest. A listing by a
190
+ * request's name is the exception: what is left of it may be the request's own, so such a read fails it, as a get that
191
+ * fails fails the whole. The label file is read only in a machine whose listed image is ours (ourImage): another's is
192
+ * left out unread, and one that shows no image is left out in words.
151
193
  */
152
- export declare function foundBy(host: MachineHost, what: string, labels: Record<string, string>, { listMs, requestMs }: Pick<HostedTimeouts, "listMs" | "requestMs">, signal?: AbortSignal): Promise<Result<Machine[]>>;
194
+ export declare function foundBy(host: MachineHost, what: string, labels: Record<string, string>, { listMs, requestMs, onNote, image }: Finding, signal?: AbortSignal): Promise<Result<Machine[]>>;
153
195
  /**
154
196
  * Waits, through waitUntil, until get answers none for a machine after its delete, twice running: the vendor no longer
155
197
  * has it. A machine read gone is still going (a vendor still destroying it), so it holds the wait like any other state.