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

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 (124) hide show
  1. package/README.md +341 -260
  2. package/box/Dockerfile +18 -1
  3. package/box/README.md +14 -0
  4. package/box/build-daytona.py +2 -2
  5. package/box/build-e2b.mjs +41 -18
  6. package/box/recipe.d.mts +5 -0
  7. package/box/recipe.mjs +43 -0
  8. package/dist/agent37.d.ts +18 -66
  9. package/dist/agent37.js +187 -464
  10. package/dist/box-image.d.ts +14 -0
  11. package/dist/box-image.js +24 -0
  12. package/dist/browserbase.d.ts +0 -6
  13. package/dist/browserbase.js +1 -5
  14. package/dist/client.d.ts +12 -3
  15. package/dist/client.js +39 -4
  16. package/dist/computerd-linux-amd64 +0 -0
  17. package/dist/computerd-linux-arm64 +0 -0
  18. package/dist/computerd.json +4 -0
  19. package/dist/conformance/agent37.d.ts +9 -4
  20. package/dist/conformance/agent37.js +23 -11
  21. package/dist/conformance/browserbase.js +3 -3
  22. package/dist/conformance/cases/apps.d.ts +6 -0
  23. package/dist/conformance/cases/apps.js +18 -5
  24. package/dist/conformance/cases/isolation.d.ts +22 -5
  25. package/dist/conformance/cases/isolation.js +97 -16
  26. package/dist/conformance/cases/mount.js +5 -3
  27. package/dist/conformance/cases/provider.js +41 -0
  28. package/dist/conformance/cli.js +72 -11
  29. package/dist/conformance/daytona.d.ts +9 -20
  30. package/dist/conformance/daytona.js +12 -21
  31. package/dist/conformance/e2b.js +9 -4
  32. package/dist/conformance/exec-stream.d.ts +52 -0
  33. package/dist/conformance/exec-stream.js +493 -0
  34. package/dist/conformance/kernel.js +2 -2
  35. package/dist/conformance/modal.js +1 -1
  36. package/dist/conformance/orgo.js +2 -2
  37. package/dist/conformance/sweep.js +8 -8
  38. package/dist/conformance/types.d.ts +2 -2
  39. package/dist/create-requests.d.ts +1 -1
  40. package/dist/daytona.d.ts +17 -133
  41. package/dist/daytona.js +396 -1452
  42. package/dist/descriptor.d.ts +11 -4
  43. package/dist/descriptor.js +7 -0
  44. package/dist/descriptors/agent37.d.ts +3 -11
  45. package/dist/descriptors/agent37.js +9 -10
  46. package/dist/descriptors/daytona.d.ts +7 -6
  47. package/dist/descriptors/daytona.js +14 -7
  48. package/dist/descriptors/docker.d.ts +13 -1
  49. package/dist/descriptors/docker.js +3 -1
  50. package/dist/descriptors/e2b.d.ts +2 -9
  51. package/dist/descriptors/e2b.js +8 -8
  52. package/dist/descriptors/index.d.ts +25 -24
  53. package/dist/descriptors/index.js +1 -3
  54. package/dist/descriptors/modal.d.ts +2 -6
  55. package/dist/descriptors/modal.js +8 -6
  56. package/dist/descriptors/orgo.js +2 -1
  57. package/dist/descriptors/shared.d.ts +1 -1
  58. package/dist/descriptors/shared.js +2 -2
  59. package/dist/desktop.d.ts +18 -4
  60. package/dist/desktop.js +89 -9
  61. package/dist/docker/egress-main.js +23 -15
  62. package/dist/docker/egress.d.ts +6 -4
  63. package/dist/docker/egress.js +24 -16
  64. package/dist/docker/inspect.d.ts +2 -2
  65. package/dist/docker/inspect.js +5 -5
  66. package/dist/docker.d.ts +6 -11
  67. package/dist/docker.js +13 -16
  68. package/dist/drift.js +4 -4
  69. package/dist/e2b.d.ts +22 -130
  70. package/dist/e2b.js +163 -243
  71. package/dist/host.d.ts +136 -104
  72. package/dist/host.js +8 -1
  73. package/dist/hosted/network.d.ts +23 -0
  74. package/dist/hosted/network.js +77 -0
  75. package/dist/hosted/process.d.ts +24 -8
  76. package/dist/hosted/process.js +80 -44
  77. package/dist/hosted/provider.d.ts +38 -22
  78. package/dist/hosted/provider.js +500 -341
  79. package/dist/hosted/rest.d.ts +74 -0
  80. package/dist/hosted/rest.js +126 -0
  81. package/dist/hosted/scripts.d.ts +21 -3
  82. package/dist/hosted/scripts.js +76 -14
  83. package/dist/hosted/ssh-exec.d.ts +99 -0
  84. package/dist/hosted/ssh-exec.js +464 -0
  85. package/dist/hosted/values.d.ts +26 -0
  86. package/dist/hosted/values.js +63 -0
  87. package/dist/index.d.ts +2 -2
  88. package/dist/index.js +2 -2
  89. package/dist/isolation.d.ts +0 -2
  90. package/dist/isolation.js +3 -4
  91. package/dist/kernel.d.ts +0 -6
  92. package/dist/kernel.js +1 -5
  93. package/dist/kinds.d.ts +3 -1
  94. package/dist/local-chrome.d.ts +0 -6
  95. package/dist/local-chrome.js +1 -5
  96. package/dist/modal.d.ts +15 -86
  97. package/dist/modal.js +67 -185
  98. package/dist/mount-archil.d.ts +13 -8
  99. package/dist/mount-archil.js +27 -17
  100. package/dist/mount.d.ts +10 -4
  101. package/dist/mount.js +8 -4
  102. package/dist/orgo.d.ts +0 -9
  103. package/dist/orgo.js +8 -13
  104. package/dist/phone-harness.d.ts +0 -6
  105. package/dist/phone-harness.js +0 -4
  106. package/dist/protocol.d.ts +4 -1
  107. package/dist/protocol.js +1 -0
  108. package/dist/provider.d.ts +2 -2
  109. package/dist/providers.d.ts +15 -13
  110. package/dist/screen-watch.js +34 -6
  111. package/dist/surface/api.d.ts +14 -11
  112. package/dist/surface/core.d.ts +23 -5
  113. package/dist/surface/core.js +105 -15
  114. package/dist/surface/index.d.ts +1 -1
  115. package/dist/surface/index.js +1 -1
  116. package/dist/surface/outline.d.ts +2 -0
  117. package/dist/surface/outline.js +2 -1
  118. package/dist/surface/script.d.ts +4 -0
  119. package/dist/surface/script.js +11 -3
  120. package/dist/ui-engine.js +19 -3
  121. package/package.json +2 -3
  122. package/box/build-agent37.mjs +0 -177
  123. package/dist/conformance/daytona-sweep.d.ts +0 -18
  124. package/dist/conformance/daytona-sweep.js +0 -126
@@ -0,0 +1,464 @@
1
+ // MachineHost.exec over SSH, for a vendor whose machines run an sshd: one connection per machine shared by its execs,
2
+ // each process under a wrapper that names its process group, through the stream the host gives to the machine's sshd
3
+ // (Agent37's WebSocket tunnel) and as the login the host gives (Agent37's root and key). Every error it throws or
4
+ // rejects with is redacted of the login's secrets. The host's own ssh2 package does the protocol; this package names
5
+ // only the slice it uses (Ssh2Module) and imports nothing at load.
6
+ import { randomBytes } from "node:crypto";
7
+ import { PassThrough } from "node:stream";
8
+ import { boundOf, redact } from "./process.js";
9
+ import { shellLine } from "./scripts.js";
10
+ /**
11
+ * ssh2's keepalive, which also keeps the edge from seeing an idle tunnel (the CLI's ServerAliveInterval is 60 s, cli.js:32).
12
+ * ssh2 pings every KEEPALIVE_MS and ends the connection at the tick after KEEPALIVE_COUNT_MAX pings went unanswered
13
+ * (ssh2@1.17.0 lib/client.js sendKA), so a dead tunnel is noticed at most KEEPALIVE_MS × (KEEPALIVE_COUNT_MAX + 1) =
14
+ * 15 s after its last answer, and every channel on it (the daemon's bridge among them) ends. ssh2's default count of 3
15
+ * with a 30 s interval took 97 s on a deleted instance. Both are set: the bound never rests on ssh2's default.
16
+ */
17
+ const KEEPALIVE_MS = 5_000;
18
+ const KEEPALIVE_COUNT_MAX = 2;
19
+ /**
20
+ * How long a kill waits for its own kill command, then for its channel to close before wait() answers -1 anyway; and
21
+ * how long an ended SSH connection has to close before its tunnel is dropped.
22
+ */
23
+ const KILL_GRACE_MS = 2_000;
24
+ /**
25
+ * How many channels (execs and kills) one SSH connection carries at once; the next opens a second connection. OpenSSH's
26
+ * sshd takes MaxSessions (default 10) sessions on one connection and refuses the next. A vendor does not always say which
27
+ * sshd it runs, so OpenSSH's default is held to; an sshd that takes fewer refuses a channel, which is opened once more on
28
+ * a fresh connection.
29
+ */
30
+ const CHANNELS_PER_CONNECTION = 10;
31
+ /**
32
+ * How long a connection with no channel stays open for the next exec. The adapter's steps (the upload, the install,
33
+ * init's start, the bridge, connect after create) come one after another, each an exec, and the live view's watch
34
+ * opens beside the bridge. An open connection keeps the process alive (ssh2's keepalive timer and the WebSocket's
35
+ * socket are both referenced), so the wait is short: a process that is done with its computers exits at most this late.
36
+ */
37
+ const IDLE_MS = 2_000;
38
+ /**
39
+ * Every command runs under this sh, which writes its pid to $0 first and removes the file when the command ends. The
40
+ * instance's sshd starts each command as a session and group leader (seen live: sh's PID, PGID and SID are one), so
41
+ * the pid names the group a kill ends; ssh2 sends no signal once stdin has ended, and a signal ends one process only.
42
+ */
43
+ const WRAPPER = '{ echo $$ > "$0"; } 2>/dev/null; "$@"; c=$?; rm -f "$0"; exit $c';
44
+ /**
45
+ * The kill: waits up to a second for the pid file, then kills the group when the pid leads one (the process alone
46
+ * otherwise, so a kill never reaches past what it started) and removes the file.
47
+ */
48
+ const KILL_SCRIPT = [
49
+ "i=0",
50
+ 'while [ ! -s "$0" ] && [ $i -lt 10 ]; do sleep 0.1; i=$((i+1)); done',
51
+ 'p=$(cat "$0" 2>/dev/null); rm -f "$0"',
52
+ '[ -n "$p" ] || exit 0',
53
+ 'g=$(cut -d" " -f5 "/proc/$p/stat" 2>/dev/null)',
54
+ // No "--": dash's kill reads it as a pid (seen live: "Illegal number: -").
55
+ 'if [ "$g" = "$p" ]; then kill -KILL "-$p"; else kill -KILL "$p"; fi 2>/dev/null',
56
+ "exit 0",
57
+ ].join("\n");
58
+ /** A tunnel failed before its SSH handshake, or while it carried the stream: the one failure a retry may repeat. */
59
+ export class SshTunnelError extends Error {
60
+ name = "SshTunnelError";
61
+ }
62
+ /** How many times a tunnel that fails before its SSH handshake is opened, and the first pause between (it doubles). */
63
+ const TUNNEL_TRIES = 4;
64
+ const TUNNEL_RETRY_MS = 500;
65
+ /** A bound's own error (boundOf's): the call ran out of time or was aborted, so nothing is tried again. */
66
+ const isBound = (error) => {
67
+ const name = error?.name;
68
+ return name === "TimeoutError" || name === "AbortError";
69
+ };
70
+ /** MachineHost.exec over SSH: argv as the host's login, as channels on one connection per machine, shared by its execs. */
71
+ export class SshExec {
72
+ #ssh2;
73
+ #loginOf;
74
+ #tunnelOf;
75
+ /**
76
+ * The SSH connections to each machine, opening, open, or done and still held, until each ends: one, and a second
77
+ * past CHANNELS_PER_CONNECTION channels. A done one takes no new channel; closeAll ends them all.
78
+ */
79
+ #links = new Map();
80
+ constructor({ ssh2, loginOf, tunnelOf }) {
81
+ this.#ssh2 = ssh2;
82
+ this.#loginOf = loginOf;
83
+ this.#tunnelOf = tunnelOf;
84
+ }
85
+ /** Ends every connection to machine id, channels and all: the vendor calls it once the machine is deleted. */
86
+ closeAll(id) {
87
+ for (const link of [...(this.#links.get(id) ?? [])])
88
+ this.#end(link);
89
+ }
90
+ /**
91
+ * An SSH session as the host's login over the machine's tunnel, its handshake within ctx. A tunnel that fails to
92
+ * open, or closes before the SSH handshake, is opened again after a pause, TUNNEL_TRIES times in all within ctx: an
93
+ * instance fresh from its create can refuse the first (seen live once in eight creates, the daemon's upload
94
+ * refused). Nothing has run before a handshake, so a retry repeats nothing. A refused key or a handshake past its
95
+ * bound is not retried.
96
+ */
97
+ async #ssh(id, ctx) {
98
+ const bound = boundOf(ctx.timeoutMs, ctx.signal, `the SSH connection to ${id}`);
99
+ // Ends the handshake in flight when this call gives up on it (its bound passed, or the caller aborted).
100
+ const givenUp = new AbortController();
101
+ try {
102
+ for (let attempt = 1;; attempt++) {
103
+ try {
104
+ return await Promise.race([this.#handshake(id, ctx.timeoutMs, givenUp.signal), bound.promise]);
105
+ }
106
+ catch (error) {
107
+ const early = error instanceof SshTunnelError || error.level === "client-socket";
108
+ if (!early || attempt >= TUNNEL_TRIES)
109
+ throw error;
110
+ }
111
+ await Promise.race([new Promise((resolve) => setTimeout(resolve, TUNNEL_RETRY_MS * 2 ** (attempt - 1))), bound.promise]);
112
+ }
113
+ }
114
+ catch (error) {
115
+ givenUp.abort();
116
+ throw error;
117
+ }
118
+ finally {
119
+ bound.clear();
120
+ }
121
+ }
122
+ /**
123
+ * One tunnel and one SSH handshake over it. On a failure, or once stop aborts before the handshake is done, the
124
+ * WebSocket (opening or open), the stream and the client are dropped.
125
+ */
126
+ async #handshake(id, timeoutMs, stop) {
127
+ const { duplex, opened, host } = this.#tunnelOf(id);
128
+ const client = new this.#ssh2.Client();
129
+ const givenUp = () => new SshTunnelError(`the SSH tunnel to ${host} was given up on`);
130
+ let quit = () => { };
131
+ const quitted = new Promise((_resolve, reject) => {
132
+ quit = reject;
133
+ });
134
+ quitted.catch(() => { });
135
+ const drop = () => {
136
+ client.destroy();
137
+ duplex.destroy();
138
+ quit(givenUp());
139
+ };
140
+ stop.addEventListener("abort", drop, { once: true });
141
+ const { username, privateKey, password } = this.#loginOf(id);
142
+ try {
143
+ await Promise.race([opened, quitted]);
144
+ await Promise.race([
145
+ new Promise((resolve, reject) => {
146
+ client.once("ready", resolve);
147
+ client.once("error", reject);
148
+ client.connect({ sock: duplex, username, privateKey, password, readyTimeout: timeoutMs, keepaliveInterval: KEEPALIVE_MS, keepaliveCountMax: KEEPALIVE_COUNT_MAX });
149
+ }),
150
+ quitted,
151
+ ]);
152
+ }
153
+ catch (error) {
154
+ drop();
155
+ throw error;
156
+ }
157
+ finally {
158
+ stop.removeEventListener("abort", drop);
159
+ }
160
+ if (stop.aborted) {
161
+ drop();
162
+ throw givenUp();
163
+ }
164
+ // A later error ends the session; its channel's close reports it.
165
+ client.on("error", () => { });
166
+ return client;
167
+ }
168
+ /**
169
+ * A connection to id with one more holder, its handshake within ctx: a link of the machine's that is not done and
170
+ * has room, or a new one. Execs that come together share one handshake, each waiting within its own bound; the
171
+ * handshake is given up once none waits. A link that closed as its handshake ended is let go, and another taken.
172
+ */
173
+ async #lease(id, ctx) {
174
+ const bound = boundOf(ctx.timeoutMs, ctx.signal, `the SSH connection to ${id}`);
175
+ const end = Date.now() + ctx.timeoutMs;
176
+ try {
177
+ for (;;) {
178
+ const link = this.#links.get(id)?.find((one) => !one.done && one.holders < CHANNELS_PER_CONNECTION) ?? this.#open(id, end - Date.now());
179
+ this.#hold(link);
180
+ let got;
181
+ try {
182
+ got = await Promise.race([link.ready.then((client) => ({ client }), (error) => ({ error })), bound.promise]);
183
+ }
184
+ catch (error) {
185
+ this.#letGo(link);
186
+ throw error;
187
+ }
188
+ if (!("error" in got) && !link.done)
189
+ return { link, client: got.client };
190
+ this.#letGo(link);
191
+ if ("error" in got) {
192
+ // A shared handshake is bound by the call that opened it: a call with time of its own left opens another.
193
+ if (got.error?.name === "TimeoutError" && end - Date.now() > TUNNEL_RETRY_MS)
194
+ continue;
195
+ throw got.error;
196
+ }
197
+ }
198
+ }
199
+ finally {
200
+ bound.clear();
201
+ }
202
+ }
203
+ /** A new link to id, its handshake started within timeoutMs, listed for the machine's next execs until it is done. */
204
+ #open(id, timeoutMs) {
205
+ const stop = new AbortController();
206
+ const link = {
207
+ id,
208
+ stop,
209
+ holders: 0,
210
+ done: false,
211
+ ended: false,
212
+ ready: this.#ssh(id, { timeoutMs, signal: stop.signal }).then((client) => {
213
+ link.client = client;
214
+ const gone = () => this.#retire(link);
215
+ client.on("close", gone);
216
+ client.on("end", gone);
217
+ client.on("error", gone);
218
+ // Deleted as it opened.
219
+ if (link.done)
220
+ this.#end(link);
221
+ return client;
222
+ }, (error) => {
223
+ this.#retire(link);
224
+ throw error;
225
+ }),
226
+ };
227
+ link.ready.catch(() => { });
228
+ this.#links.set(id, [...(this.#links.get(id) ?? []), link]);
229
+ return link;
230
+ }
231
+ #hold(link) {
232
+ link.holders++;
233
+ clearTimeout(link.idle);
234
+ link.idle = undefined;
235
+ }
236
+ /**
237
+ * One holder lets go of link. Once none holds it, a done link ends, a handshake no one waits for is given up, and an
238
+ * open connection waits IDLE_MS for the next exec, then ends.
239
+ */
240
+ #letGo(link) {
241
+ link.holders--;
242
+ if (link.holders > 0)
243
+ return;
244
+ if (link.done || link.client === undefined)
245
+ return this.#retire(link);
246
+ link.idle = setTimeout(() => this.#retire(link), IDLE_MS);
247
+ link.idle.unref();
248
+ }
249
+ /** link takes no new channel; it ends at once if none holds it, else when the last lets go (or closeAll ends it). */
250
+ #retire(link) {
251
+ link.done = true;
252
+ clearTimeout(link.idle);
253
+ if (link.holders <= 0)
254
+ this.#end(link);
255
+ }
256
+ /**
257
+ * Ends link, whoever holds it, and drops it from the machine's list: its handshake given up, its client ended (ssh2
258
+ * closes every channel on it), and the tunnel dropped if the connection has not closed within KILL_GRACE_MS. Neither
259
+ * timer keeps the process alive.
260
+ */
261
+ #end(link) {
262
+ link.done = true;
263
+ clearTimeout(link.idle);
264
+ const left = (this.#links.get(link.id) ?? []).filter((one) => one !== link);
265
+ if (left.length > 0)
266
+ this.#links.set(link.id, left);
267
+ else
268
+ this.#links.delete(link.id);
269
+ link.stop.abort();
270
+ const { client } = link;
271
+ if (client === undefined || link.ended)
272
+ return;
273
+ link.ended = true;
274
+ client.end();
275
+ const dropped = setTimeout(() => client.destroy(), KILL_GRACE_MS);
276
+ dropped.unref();
277
+ client.on("close", () => clearTimeout(dropped));
278
+ }
279
+ /**
280
+ * One exec channel on client, opened within ms and signal, and its close: the exit-status, or -1 for an exit by
281
+ * signal or none. Its listeners go on inside ssh2's callback, as it opens: one read off the tunnel can hold the open,
282
+ * the exit and the close together (seen live), and they are emitted before an await after it would resume. A channel
283
+ * that opens after its bound passed is closed: the connection is shared, so nothing else would close it.
284
+ */
285
+ async #channel(client, command, ms, signal, what) {
286
+ const bound = boundOf(ms, signal, what);
287
+ let late = false;
288
+ try {
289
+ return await Promise.race([
290
+ new Promise((resolve, reject) => {
291
+ client.exec(command, (error, channel) => {
292
+ if (error)
293
+ return reject(error);
294
+ if (late) {
295
+ channel.on("error", () => { });
296
+ return channel.close();
297
+ }
298
+ let code = -1;
299
+ channel.on("exit", (status) => {
300
+ code = typeof status === "number" ? status : -1;
301
+ });
302
+ channel.on("error", () => { });
303
+ resolve({ channel, closed: new Promise((done) => channel.on("close", () => done(code))) });
304
+ });
305
+ }),
306
+ bound.promise,
307
+ ]);
308
+ }
309
+ catch (error) {
310
+ late = true;
311
+ throw error;
312
+ }
313
+ finally {
314
+ bound.clear();
315
+ }
316
+ }
317
+ /**
318
+ * command as one channel on a connection to id with room (#lease), within ctx; the channel holds its connection until
319
+ * the caller lets go. A channel that fails to open (the connection died under it, or its sshd took no more sessions)
320
+ * retires that connection and is opened once more on a fresh one.
321
+ */
322
+ async #start(id, command, ctx, what) {
323
+ for (let attempt = 1;; attempt++) {
324
+ const { link, client } = await this.#lease(id, ctx);
325
+ try {
326
+ return { link, ...(await this.#channel(client, command, ctx.timeoutMs, ctx.signal, what)) };
327
+ }
328
+ catch (error) {
329
+ // A channel open that timed out leaves a connection that may be stuck: the next channel takes another.
330
+ if (error?.name !== "AbortError")
331
+ this.#retire(link);
332
+ this.#letGo(link);
333
+ if (isBound(error) || attempt >= 2)
334
+ throw error;
335
+ }
336
+ }
337
+ }
338
+ /**
339
+ * error with machine id's login secrets taken out of its message and stack, in place: its class, name and fields stay,
340
+ * which the adapter reads its code by. ssh2's words can carry the username, and a host's may hold a key.
341
+ */
342
+ #redacted(id, error) {
343
+ const { privateKey, password, secrets = [] } = this.#loginOf(id);
344
+ const hidden = [privateKey, password, ...secrets];
345
+ if (!(error instanceof Error))
346
+ return new Error(redact(String(error), hidden));
347
+ error.message = redact(error.message, hidden);
348
+ if (error.stack !== undefined)
349
+ error.stack = redact(error.stack, hidden);
350
+ return error;
351
+ }
352
+ /**
353
+ * argv as the host's login over SSH, under WRAPPER, as one channel on the machine's shared connection (#start).
354
+ * stdout and stderr are the channel's, piped; end sends end of file. wait answers once the channel closes, with the
355
+ * exit-status, or -1 for an exit by signal or none. kill ends the process group over a channel of its own (on a
356
+ * connection with room), then closes the exec's channel, never a connection; if the close does not come, wait
357
+ * answers -1 and the connection takes no new channel.
358
+ */
359
+ async exec(id, argv, ctx) {
360
+ const pidFile = `/tmp/.agentrun-exec-${randomBytes(8).toString("hex")}`;
361
+ const opened = await this.#start(id, shellLine(["sh", "-c", WRAPPER, pidFile, ...argv]), ctx, `the exec in ${id}`).catch((error) => {
362
+ throw this.#redacted(id, error);
363
+ });
364
+ const { link: held, channel } = opened;
365
+ const stdout = new PassThrough();
366
+ const stderr = new PassThrough();
367
+ channel.pipe(stdout);
368
+ channel.stderr.pipe(stderr);
369
+ let ended = false;
370
+ let closed = false;
371
+ // ssh2 closes every channel when the connection goes (utils.js, ChannelManager.cleanup), so the close is enough.
372
+ let done = () => { };
373
+ const exited = new Promise((resolve) => {
374
+ done = (code) => {
375
+ if (closed)
376
+ return;
377
+ closed = true;
378
+ this.#letGo(held);
379
+ resolve(code);
380
+ };
381
+ });
382
+ void opened.closed.then(done);
383
+ return {
384
+ stdout,
385
+ stderr,
386
+ write: (bytes) => new Promise((resolve, reject) => {
387
+ if (ended || closed)
388
+ return reject(new Error(ended ? "stdin was ended" : "the process has ended"));
389
+ channel.write(bytes, (error) => (error ? reject(this.#redacted(id, error)) : resolve()));
390
+ }),
391
+ end: async () => {
392
+ if (ended || closed)
393
+ return;
394
+ ended = true;
395
+ channel.eof();
396
+ },
397
+ wait: () => exited,
398
+ kill: async () => {
399
+ if (closed)
400
+ return;
401
+ // The pid file is the machine's, so the kill's channel goes on any connection with room, counted like an exec's.
402
+ try {
403
+ const killer = await this.#start(id, shellLine(["sh", "-c", KILL_SCRIPT, pidFile]), { timeoutMs: KILL_GRACE_MS }, `the kill in ${id}`);
404
+ killer.channel.resume();
405
+ killer.channel.stderr.resume();
406
+ killer.channel.eof();
407
+ const grace = boundOf(KILL_GRACE_MS, undefined, `the kill in ${id}`);
408
+ try {
409
+ await Promise.race([killer.closed, grace.promise]);
410
+ }
411
+ catch {
412
+ try {
413
+ killer.channel.close();
414
+ }
415
+ catch {
416
+ // Closed already.
417
+ }
418
+ }
419
+ finally {
420
+ grace.clear();
421
+ this.#letGo(killer.link);
422
+ }
423
+ }
424
+ catch {
425
+ // No connection took the kill in time: closing the channel below is what is left.
426
+ }
427
+ try {
428
+ channel.close();
429
+ }
430
+ catch {
431
+ // Closed already.
432
+ }
433
+ // A close that never comes is a connection that is stuck: it takes no more execs, and wait answers.
434
+ const dropped = setTimeout(() => {
435
+ if (closed)
436
+ return;
437
+ this.#retire(held);
438
+ done(-1);
439
+ }, KILL_GRACE_MS);
440
+ dropped.unref();
441
+ void exited.then(() => clearTimeout(dropped));
442
+ },
443
+ };
444
+ }
445
+ }
446
+ /**
447
+ * A private key in the PEM armor ssh2 reads (its parser wants the BEGIN and END lines on lines of their own), or
448
+ * undefined when text is not one. A key pasted into Settings → Computers comes back on one line, since a password
449
+ * field drops line breaks: its body is wrapped again at 70 characters, as ssh-keygen writes it.
450
+ */
451
+ export function pemOf(text) {
452
+ const armor = /^-----BEGIN ([A-Z0-9 ]*PRIVATE KEY)-----([\s\S]*?)-----END \1-----$/.exec(text.replace(/\r/g, "").trim());
453
+ if (!armor)
454
+ return undefined;
455
+ const [, label, inside] = armor;
456
+ const lines = inside.split("\n").map((line) => line.trim()).filter(Boolean);
457
+ // PEM headers (Proc-Type, DEK-Info) keep their own lines; a key with them was never pasted onto one line.
458
+ if (lines.some((line) => line.includes(":")))
459
+ return `-----BEGIN ${label}-----\n${lines.join("\n")}\n-----END ${label}-----\n`;
460
+ const body = lines.join("").replace(/\s+/g, "");
461
+ if (body === "" || !/^[A-Za-z0-9+/=]+$/.test(body))
462
+ return undefined;
463
+ return `-----BEGIN ${label}-----\n${body.match(/.{1,70}/g)?.join("\n")}\n-----END ${label}-----\n`;
464
+ }
@@ -0,0 +1,26 @@
1
+ import type { HostFacts } from "../host.js";
2
+ import type { ComputerSpec, Refusal } from "../provider.js";
3
+ /** A host name, as a vendor's domain option is one: DNS labels and a top-level name of letters. */
4
+ export declare const DOMAIN: RegExp;
5
+ export declare const isWhole: (value: unknown) => value is number;
6
+ /** A vendor whose computer has its image's size: a spec's cpus or memoryMb, refused in words (computer: "an E2B computer"). */
7
+ export declare function sizeRefusals(spec: Partial<ComputerSpec>, computer: string, image: string): Refusal[];
8
+ /** A time the vendor reports: a Date, an ISO string, or a whole number of ms (or seconds); undefined when it is none of them. */
9
+ export declare function dateOf(value: unknown, unit?: "ms" | "s"): Date | undefined;
10
+ /** The label a packed machine is listed by (packLabels): its value is the machine's name, MachineRequest.name. */
11
+ export declare const PACKED_NAME = "agentrun";
12
+ /**
13
+ * A machine's labels as a vendor whose labels can't hold them as they are stores them (facts.labels.packed): a cap of 5
14
+ * tags, Kubernetes' values, Cloudflare's 16-byte names, a list of strings. PACKED_NAME, the one label a host's list
15
+ * filters on, holds name; the whole map, as JSON, deflated and base64url, goes in parts of at most valueBytes. Every name
16
+ * is at most 11 bytes of [a-z0-9-], every value [A-Za-z0-9_-] with a letter or digit at each end, and no "=", so a
17
+ * host of a string list stores each as name=value. unpackLabels reads the map back exactly. A map that does not fit
18
+ * room (count, bytes and valueBytes, of the packed labels), or whose JSON is past PACKED_JSON_MAX, is refused in words.
19
+ */
20
+ export declare function packLabels(labels: Record<string, string>, name: string, room?: HostFacts["labels"]): {
21
+ labels: Record<string, string>;
22
+ } | {
23
+ problem: string;
24
+ };
25
+ /** The labels packLabels packed in stored, exactly; undefined where stored holds no packed map (a machine not the adapter's). */
26
+ export declare function unpackLabels(stored: Record<string, string>): Record<string, string> | undefined;
@@ -0,0 +1,63 @@
1
+ // Small readings every hosted vendor makes of what its API answers: a whole number, a value in words, a date; and the
2
+ // label codec of a vendor whose labels can't hold the adapter's as they are.
3
+ import { deflateRawSync, inflateRawSync } from "node:zlib";
4
+ /** A host name, as a vendor's domain option is one: DNS labels and a top-level name of letters. */
5
+ export const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
6
+ export const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
7
+ /** A vendor whose computer has its image's size: a spec's cpus or memoryMb, refused in words (computer: "an E2B computer"). */
8
+ export function sizeRefusals(spec, computer, image) {
9
+ return ["cpus", "memoryMb"].filter((field) => spec[field] !== undefined).map((field) => ({ field, message: `${computer} has the size of its ${image}: name a ${image} of the size you need, not ${field}` }));
10
+ }
11
+ /** A time the vendor reports: a Date, an ISO string, or a whole number of ms (or seconds); undefined when it is none of them. */
12
+ export function dateOf(value, unit = "ms") {
13
+ const at = value instanceof Date ? value.getTime() : typeof value === "string" ? Date.parse(value) : isWhole(value) ? value * (unit === "s" ? 1000 : 1) : Number.NaN;
14
+ return Number.isNaN(at) ? undefined : new Date(at);
15
+ }
16
+ /** The label a packed machine is listed by (packLabels): its value is the machine's name, MachineRequest.name. */
17
+ export const PACKED_NAME = "agentrun";
18
+ /** The packed map's parts: agentrun-0, agentrun-1, and on. */
19
+ const PART = `${PACKED_NAME}-`;
20
+ /** The most bytes of a packed map's JSON: unpackLabels inflates no more. */
21
+ const PACKED_JSON_MAX = 1 << 20;
22
+ /**
23
+ * A machine's labels as a vendor whose labels can't hold them as they are stores them (facts.labels.packed): a cap of 5
24
+ * tags, Kubernetes' values, Cloudflare's 16-byte names, a list of strings. PACKED_NAME, the one label a host's list
25
+ * filters on, holds name; the whole map, as JSON, deflated and base64url, goes in parts of at most valueBytes. Every name
26
+ * is at most 11 bytes of [a-z0-9-], every value [A-Za-z0-9_-] with a letter or digit at each end, and no "=", so a
27
+ * host of a string list stores each as name=value. unpackLabels reads the map back exactly. A map that does not fit
28
+ * room (count, bytes and valueBytes, of the packed labels), or whose JSON is past PACKED_JSON_MAX, is refused in words.
29
+ */
30
+ export function packLabels(labels, name, room = {}) {
31
+ const json = Buffer.from(JSON.stringify(labels));
32
+ if (json.length > PACKED_JSON_MAX)
33
+ return { problem: `its labels come to ${json.length} bytes as JSON, past the ${PACKED_JSON_MAX} a packed map holds` };
34
+ const payload = deflateRawSync(json).toString("base64url");
35
+ const { count, bytes, packed } = room;
36
+ // base64url can begin or end with - or _, which a Kubernetes value can't: each part is wrapped in a letter.
37
+ const size = (packed?.valueBytes ?? payload.length + 2) - 2;
38
+ if (size < 1 || Buffer.byteLength(name) > size + 2)
39
+ return { problem: `its labels' values hold at most ${packed?.valueBytes} bytes, too few for the name ${name} and a part of the rest` };
40
+ const parts = [];
41
+ for (let at = 0; at < payload.length; at += size)
42
+ parts.push([`${PART}${parts.length}`, `p${payload.slice(at, at + size)}p`]);
43
+ const all = [[PACKED_NAME, name], ...parts];
44
+ const total = all.reduce((sum, [key, value]) => sum + key.length + Buffer.byteLength(value), 0);
45
+ if ((count !== undefined && all.length > count) || (bytes !== undefined && total > bytes))
46
+ return { problem: `its labels pack into ${all.length} labels of ${total} bytes in all, past the ${[count === undefined ? "" : `${count} labels`, bytes === undefined ? "" : `${bytes} bytes`].filter(Boolean).join(" and ")} it keeps` };
47
+ return { labels: Object.fromEntries(all) };
48
+ }
49
+ /** The labels packLabels packed in stored, exactly; undefined where stored holds no packed map (a machine not the adapter's). */
50
+ export function unpackLabels(stored) {
51
+ let payload = "";
52
+ for (let part = 0; stored[`${PART}${part}`] !== undefined; part++)
53
+ payload += stored[`${PART}${part}`]?.slice(1, -1);
54
+ if (payload === "")
55
+ return undefined;
56
+ try {
57
+ const map = JSON.parse(inflateRawSync(Buffer.from(payload, "base64url"), { maxOutputLength: PACKED_JSON_MAX }).toString());
58
+ return typeof map === "object" && map !== null && !Array.isArray(map) && Object.values(map).every((value) => typeof value === "string") ? map : undefined;
59
+ }
60
+ catch {
61
+ return undefined;
62
+ }
63
+ }
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@ export { pullTar, pullTarStream, pushTar, readFile, writeFile, type PulledTar }
10
10
  export { listProcesses, readAll, type ReadAllResult } from "./processes.js";
11
11
  export { type ActionMapper, createActionMapper, daemonWatch, redactWords, type ScreenFrame, type ScreenFrames, type ScreenWatch, ScreenWatchError, type ScreenWatchHandlers, toAction, type ViewerEvent, type WatchEndCode, watchEndCode, type WatchOptions, watchScreen, } from "./screen-watch.js";
12
12
  export type { HostCall, HostFacts, Machine, MachineHost, MachineProcess, MachineRequest } from "./host.js";
13
- export { HostedProvider, type HostedOptions, type HostedTimeouts, hostedProvider } from "./hosted/provider.js";
13
+ export { HostedProvider, type HostedOptions, type HostedTimeouts } from "./hosted/provider.js";
14
14
  export { type DockerVolume, VOLUME_SUBPATH_ENGINE } from "./docker/volume.js";
15
15
  export { DEFAULT_DOCKER_IMAGE, DOCKER_BASE, DOCKER_RECIPE, DOCKER_RECIPE_HAS, ensureImage, type EnsureImageOptions, IMAGE_REPOSITORY, IMAGE_TIMEOUT_MS, type ImageSource, imageSourceProblem, type Making, RECIPE_LABEL, recipeHash, recipeTag, } from "./docker/image.js";
16
16
  export { EGRESS_IMAGE, EGRESS_LABEL, EGRESS_MOUNT, EGRESS_SOCKET } from "./docker/egress.js";
@@ -24,7 +24,7 @@ export { EPOCH_LABEL, epochOf, epochProblem, IDLE_TTL_LABEL, OWNER_LABEL, OWNER_
24
24
  export { waitUntil, type WaitOptions } from "./wait.js";
25
25
  export { type BuiltinProviderId, type ConformanceModule, descriptorOf, isProviderId, type ProviderEnv, providerFor, type ProviderId, providerIds, type ProviderModule, providerModule, type ProviderOptions, providers, } from "./providers.js";
26
26
  export { type DescriptorKey, type DescriptorSetting, defineProvider, descriptorProblems, type HostCommand, type ParkedConfiguration, type ProviderDescriptor } from "./descriptor.js";
27
- export { AGENT37, AGENT37_BASE_TEMPLATE, AGENT37_BOX_TEMPLATE, BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, type DaytonaGpuSnapshot, DESCRIPTORS, daytonaGpu, daytonaGpuSnapshot, DOCKER, E2B, E2B_BASE_TEMPLATE, E2B_DESKTOP_TEMPLATE, KERNEL, LOCAL, MODAL, MODAL_DEFAULT_IMAGE, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, } from "./descriptors/index.js";
27
+ export { AGENT37, AGENT37_BASE_TEMPLATE, BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, type DaytonaGpuSnapshot, DESCRIPTORS, daytonaGpu, daytonaGpuSnapshot, DOCKER, E2B, KERNEL, LOCAL, MODAL, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, } from "./descriptors/index.js";
28
28
  export type { PhoneLedger, PhoneLedgerEntry } from "./phone-harness.js";
29
29
  export { type ComputerSettingKind, configurationOf, entryOf, imagesOf, type KindCapabilities, kindOf, kindServed, type ProviderEntry, PROVIDERS, SETTING_KIND_NAMES, SETTING_KINDS, type SettingKindSpec, serves, servingRefusals, type TestConnection, type TestConnectionOptions, } from "./kinds.js";
30
30
  export * from "./conformance/index.js";
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ export { checkActions, isKey } from "./actions.js";
9
9
  export { pullTar, pullTarStream, pushTar, readFile, writeFile } from "./files.js";
10
10
  export { listProcesses, readAll } from "./processes.js";
11
11
  export { createActionMapper, daemonWatch, redactWords, ScreenWatchError, toAction, watchEndCode, watchScreen, } from "./screen-watch.js";
12
- export { HostedProvider, hostedProvider } from "./hosted/provider.js";
12
+ export { HostedProvider } from "./hosted/provider.js";
13
13
  // The provider classes and their option types are not here: each provider loads by its id through the registry
14
14
  // (providerFor), or from its own subpath (@parcha/agentrun-computer/docker, /daytona, /modal, /e2b, /agent37, /orgo,
15
15
  // /phone-harness, /browserbase, /kernel, /local: each the provider file's name).
@@ -28,6 +28,6 @@ export { EPOCH_LABEL, epochOf, epochProblem, IDLE_TTL_LABEL, OWNER_LABEL, OWNER_
28
28
  export { waitUntil } from "./wait.js";
29
29
  export { descriptorOf, isProviderId, providerFor, providerIds, providerModule, providers, } from "./providers.js";
30
30
  export { defineProvider, descriptorProblems } from "./descriptor.js";
31
- export { AGENT37, AGENT37_BASE_TEMPLATE, AGENT37_BOX_TEMPLATE, BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, DESCRIPTORS, daytonaGpu, daytonaGpuSnapshot, DOCKER, E2B, E2B_BASE_TEMPLATE, E2B_DESKTOP_TEMPLATE, KERNEL, LOCAL, MODAL, MODAL_DEFAULT_IMAGE, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, } from "./descriptors/index.js";
31
+ export { AGENT37, AGENT37_BASE_TEMPLATE, BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, DESCRIPTORS, daytonaGpu, daytonaGpuSnapshot, DOCKER, E2B, KERNEL, LOCAL, MODAL, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, } from "./descriptors/index.js";
32
32
  export { configurationOf, entryOf, imagesOf, kindOf, kindServed, PROVIDERS, SETTING_KIND_NAMES, SETTING_KINDS, serves, servingRefusals, } from "./kinds.js";
33
33
  export * from "./conformance/index.js";
@@ -2,8 +2,6 @@ import type { ComputerClient } from "./protocol.js";
2
2
  import { type Result } from "./result.js";
3
3
  /** The uid:gid the programs of a remote computer run as by default: the box image's agentrun-tool, no sudo. */
4
4
  export declare const TOOL_USER = "2510:2510";
5
- /** Why a remote provider refuses network open or an allowlist, in words. */
6
- export declare const OWN_NETWORK_ONLY = "a remote computer takes network \"none\" only: its programs run in a network of their own, their loopback alone, so the vendor's agent in it (which runs commands as root) is out of their reach; open and allowlists wait for a proxy out of that network";
7
5
  /**
8
6
  * The drift of a computer's programs' network from their own loopback alone, in words: none when the live interfaces
9
7
  * (up or addressed) of the daemon's network namespace are `lo` alone, else what they are (or that they could not be read).
package/dist/isolation.js CHANGED
@@ -4,14 +4,13 @@
4
4
  // while another process holds the programs' uid, moves itself into a network namespace whose loopback alone is up or
5
5
  // addressed, and refuses vsock and io_uring to every thread (daemon/internal/isolate). A kernel with the tunnel modules
6
6
  // loaded also gives that namespace its fallback tunnels (tunl0, gre0, sit0, ...), down with no address; no program can
7
- // raise them, holding no CAP_NET_ADMIN, and the read-back here proves it through computerd's probe. Network "none" is
8
- // all such a computer takes until a proxy carries open and allowlists out of that namespace.
7
+ // raise them, holding no CAP_NET_ADMIN, and the read-back here proves it through computerd's probe. Under network "open"
8
+ // or a list the namespace is the same: init's relay on its loopback carries the programs' connections out over a Unix
9
+ // socket to the egress proxy init started outside it (hosted/network.ts), which goes to the public internet alone.
9
10
  import { DAEMON_IN_COMPUTER } from "./drift.js";
10
11
  import { fail, failAs, ok } from "./result.js";
11
12
  /** The uid:gid the programs of a remote computer run as by default: the box image's agentrun-tool, no sudo. */
12
13
  export const TOOL_USER = "2510:2510";
13
- /** Why a remote provider refuses network open or an allowlist, in words. */
14
- export const OWN_NETWORK_ONLY = 'a remote computer takes network "none" only: its programs run in a network of their own, their loopback alone, so the vendor\'s agent in it (which runs commands as root) is out of their reach; open and allowlists wait for a proxy out of that network';
15
14
  /**
16
15
  * The drift of a computer's programs' network from their own loopback alone, in words: none when the live interfaces
17
16
  * (up or addressed) of the daemon's network namespace are `lo` alone, else what they are (or that they could not be read).
package/dist/kernel.d.ts CHANGED
@@ -1,6 +1,4 @@
1
1
  import { type BrowserComputerProvider, type BrowserProfiles, type BrowserStream, type ReleaseConfirm, type RestInit, type RestReply } from "./browser.js";
2
- import type { KindCapabilities } from "./kinds.js";
3
- import type { MountKind } from "./mount.js";
4
2
  import { type AttachedComputer, 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 ReleaseHow } from "./provider.js";
5
3
  import { type Result } from "./result.js";
6
4
  export declare const KERNEL_API_URL = "https://api.onkernel.com";
@@ -9,10 +7,6 @@ export declare const KERNEL_CDP_DOMAIN = "kernel.sh";
9
7
  /** Kernel's shortest and longest idle timeout. */
10
8
  export declare const KERNEL_MIN_LIFETIME_MS = 10000;
11
9
  export declare const KERNEL_MAX_LIFETIME_MS = 259200000;
12
- /** A browser takes no mount. */
13
- export declare const MOUNT: readonly MountKind[];
14
- /** The one configuration it offers, its descriptor's: a browser with a CDP target and a live view. */
15
- export declare const CAPABILITIES: readonly KindCapabilities[];
16
10
  /** A browser as Kernel answers it; only what the provider reads. */
17
11
  export interface KernelBrowser {
18
12
  session_id?: unknown;