@parcha/agentrun-computer 0.1.0-beta.55 → 0.1.0-beta.57

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.
package/README.md CHANGED
@@ -628,7 +628,9 @@ by its rectangle), so a longer one ends the connection before anything is alloca
628
628
  answers once none of its windows shows and none of its launches runs, a launch that never showed a window included.
629
629
  - `screen.shot` is a PNG of the root window or a region inside it (one outside is `invalid`), with `scale` 1 and
630
630
  `cursor` from `QueryPointer`. A connection holds one shot, until it is read to its end or the next shot; a
631
- `screen.read` of another id is `not_found`.
631
+ `screen.read` of another id is `not_found`. A cancelled shot stops waiting for the server's replies at once and
632
+ gives the display back. Known limit: a shot cancelled while its request is still being written, to an X server that
633
+ has stopped reading its socket, waits out that write's 30 s bound first.
632
634
  - `input.actions` checks the whole batch first, as `checkActions` does, and on X11 also refuses: a touch action
633
635
  (`unsupported`: X11 has no touch), a pixel scroll (`unsupported`: the wheel turns in clicks), a point or click count
634
636
  that is not whole (`invalid`), an unknown field, and text with a character no key types (a control character other
@@ -837,14 +839,21 @@ key.
837
839
  makes its Unix socket there (0600); the computer mounts it read-only at `/opt/agentrun/egress` (`EGRESS_MOUNT`).
838
840
  - **The proxy container** `computer-<hex>-egress`: `node` in `EGRESS_IMAGE` (node:22.23.5-trixie-slim, pinned by
839
841
  digest; `new DockerProvider({ daemonPath, egress: { image } })` replaces it) runs `dist/docker/egress-main.js`, this
840
- package's own build, bound read-only with its `package.json`. It is on Docker's default bridge alone, publishes no
841
- port, and runs as the computer's uid:gid with a read-only root, `--cap-drop ALL`, `no-new-privileges`, 256 MiB, 64
842
+ package's own build, bound read-only with its `package.json`. It is on the provider's egress bridge alone (below),
843
+ publishes no port, and runs as the computer's uid:gid with a read-only root, `--cap-drop ALL`, `no-new-privileges`, 256 MiB, 64
842
844
  pids, half a CPU (a fixed quota, not the computer's own cpus), 1024 open files and a bounded log. Its argv holds the list (or `--open public`), the computer's deadline (it ends itself then), this machine's own
843
845
  public addresses (refused as `this-host`), and `egress.hint`, the words a refusal adds (printable ASCII).
844
846
  `EGRESS_IMAGE` is the one place its digest is written. `create` pulls it at the first allow computer when the host
845
847
  lacks it (see Lifetime), so a host with no registry access pulls it ahead, reading the name from this package:
846
848
  `docker pull "$(node --input-type=module -e 'import { EGRESS_IMAGE } from "@parcha/agentrun-computer"; console.log(EGRESS_IMAGE)')"`
847
849
  (in this repository, from `packages/computer` after a build: `node -e 'import("./dist/index.js").then((m) => console.log(m.EGRESS_IMAGE))'`).
850
+ - **The egress bridge** `agentrun-egress`: one user-defined bridge every proxy on the Docker host shares, with
851
+ inter-container traffic off (`com.docker.network.bridge.enable_icc=false`) and the label
852
+ `agentrun.computer.egress-network=1`. The first allow or open `create` makes it, and nothing removes it. No other
853
+ workload's container is on it, so none can reach a proxy or ARP-spoof the gateway the proxies go out through, as one
854
+ with `NET_RAW` could on Docker's default bridge. A `create` that finds a network of that name made otherwise (inter-container
855
+ traffic on, internal, not a local bridge, or without the label) refuses in words and makes nothing; remove that
856
+ network (`docker network rm agentrun-egress`) and create again. A proxy on any other network reads back as other.
848
857
  - **The computer**: init gets `--egress /opt/agentrun/egress/egress.sock`, listens on port 3128 of its own loopback,
849
858
  carries each connection to the socket, and gives every program it starts `HTTP_PROXY` and `HTTPS_PROXY` (and their
850
859
  lowercase forms) naming that port, with `NO_PROXY` naming the loopback itself. A program that ignores them reaches
@@ -1368,8 +1377,8 @@ unless they start with `modal_proto/`. Docs: modal.com, read 2026-11-05.
1368
1377
  `create(options)` in `dist/modal.js` builds a real client from `options.tokenId` and `options.tokenSecret`, and the
1369
1378
  provider in `options.app` (required: without it, it refuses in words naming the option, before any client). It reads no
1370
1379
  setting from the environment (see [Settings](#settings)) and passes the token to `ModalClient` explicitly, so a
1371
- `MODAL_TOKEN_ID` or `MODAL_TOKEN_SECRET` on the host is never used. The key goes only to `options.serverUrl`, else the
1372
- SDK's default `https://api.modal.com:443`: since the client cannot take a server, it refuses while `MODAL_SERVER_URL`
1380
+ `MODAL_TOKEN_ID` or `MODAL_TOKEN_SECRET` on the host is never used. The key goes only to `options.serverUrl` (https
1381
+ alone), else the SDK's default `https://api.modal.com:443`: since the client cannot take a server, it refuses while `MODAL_SERVER_URL`
1373
1382
  is set, and sets it to its choice only while it constructs the client, one construction at a time and put back after
1374
1383
  each, so neither `MODAL_PROFILE` nor a profile in `MODAL_CONFIG_PATH` or `~/.modal.toml` can redirect the key. The
1375
1384
  daemon is uploaded from `options.daemonPath`, else `dist/computerd-linux-amd64`, so a run publishes nothing.
@@ -2807,7 +2816,7 @@ explicitly, so the SDK takes none of them from the environment.
2807
2816
  | `apiKey` | the boxd API key | required |
2808
2817
  | `org` | the org machines are made in and listed from, by name or id | the key's own |
2809
2818
  | `region` | the region machines are made in (`fra`, `nyc`) | the API's home region |
2810
- | `baseUrl` | the API's address | `https://boxd.sh:9443` |
2819
+ | `baseUrl` | the API's address, https alone | `https://boxd.sh:9443` |
2811
2820
  | `vcpu`, `memory` | a boxd size: 1 and `4G`, 2 and `8G`, 4 and `16G`, or 8 and `32G`; both or neither; a sandbox's alone | the org's default |
2812
2821
  | `kind` | `linux` or `desktop` (from the desktop snapshot) | `linux` |
2813
2822
  | `maxLifetimeMs` | the longest lifetime `check` takes, at most 30 days | 24 h |
@@ -2931,7 +2940,7 @@ node packages/computer/dist/conformance/sweep.js --provider smolcloud --before /
2931
2940
  ```
2932
2941
 
2933
2942
  The conformance module, `dist/conformance/smolcloud.js`, checks `AGENTRUN_COMPUTER_LIVE_SMOLCLOUD=1` first, then reads
2934
- `COMPUTER_SMOLCLOUD_API_KEY` (`apiKey`, required), `COMPUTER_SMOLCLOUD_API_URL` (`apiUrl`) and
2943
+ `COMPUTER_SMOLCLOUD_API_KEY` (`apiKey`, required), `COMPUTER_SMOLCLOUD_API_URL` (`apiUrl`, https alone) and
2935
2944
  `COMPUTER_SMOLCLOUD_IMAGE` (the run's image, default the box image), never `SMOLCLOUD_API_KEY`. Every computer of a run
2936
2945
  lives at most 30 minutes. The live sweep is the shared one; its scope is the key's account.
2937
2946
 
@@ -3003,8 +3012,7 @@ What Groundbox refuses or this host works around:
3003
3012
  should Groundbox start it after all; every other dropped socket closes with 4000, which leaves it running. A new
3004
3013
  socket counts as reading on only once Groundbox says something on it, so a peer that takes each attach and stays
3005
3014
  silent fails the stream after 5 minutes instead of holding `wait()` forever.
3006
- - The API URL is https; http is taken only to a loopback host (127.0.0.0/8, `::1`, `localhost`), since the key rides
3007
- every call and the stream's upgrade.
3015
+ - The API URL is https alone, loopback included, since the key rides every call and the stream's upgrade.
3008
3016
  - On the box image and any other public image Groundbox runs a command as root. On Groundbox's own image and its
3009
3017
  templates it runs as the image's user, `runner` (uid 1001), with passwordless sudo, which the adapter's scripts use;
3010
3018
  `daemonUser` may not be 1001 there.
package/dist/agent37.js CHANGED
@@ -15,7 +15,7 @@ import { AGENT37, AGENT37_BASE_TEMPLATE } from "./descriptors/agent37.js";
15
15
  import { DEADLINE_LABEL, show } from "./drift.js";
16
16
  import { HostError } from "./host.js";
17
17
  import { orThrow } from "./hosted/process.js";
18
- import { jsonOf, rest } from "./hosted/rest.js";
18
+ import { httpsBase, jsonOf, rest } from "./hosted/rest.js";
19
19
  import { HostedProvider } from "./hosted/provider.js";
20
20
  import { pemOf, SshExec, SshTunnelError } from "./hosted/ssh-exec.js";
21
21
  import { dateOf, DOMAIN, isWhole } from "./hosted/values.js";
@@ -456,15 +456,9 @@ export class Agent37Provider extends HostedProvider {
456
456
  throw new Error("options.fetch must be a function, as the global fetch is");
457
457
  if (typeof WebSocket !== "function")
458
458
  throw new Error("options.WebSocket must be a WebSocket class that takes headers, as Node's global one does");
459
- let api;
460
- try {
461
- api = new URL(apiUrl);
462
- }
463
- catch {
464
- throw new Error(`apiUrl must be an https URL such as ${DEFAULT_API_URL}, not ${JSON.stringify(apiUrl)}`);
465
- }
466
- if (api.protocol !== "https:" || api.search !== "" || api.hash !== "")
467
- throw new Error(`apiUrl must be an https URL such as ${DEFAULT_API_URL}, not ${JSON.stringify(apiUrl)}`);
459
+ const api = new URL(httpsBase(apiUrl, "the Agent37 API URL"));
460
+ if (api.search !== "" || api.hash !== "")
461
+ throw new Error(`the Agent37 API URL takes no query or fragment, as ${DEFAULT_API_URL} has none: ${JSON.stringify(apiUrl)}`);
468
462
  if (typeof proxyDomain !== "string" || !DOMAIN.test(proxyDomain))
469
463
  throw new Error(`proxyDomain must be a host name such as ${DEFAULT_PROXY_DOMAIN}, not ${JSON.stringify(proxyDomain)}`);
470
464
  if (type !== "vm" && type !== "default")
package/dist/boxd.d.ts CHANGED
@@ -94,7 +94,7 @@ export interface BoxdProviderOptions extends HostedOptions {
94
94
  org?: string;
95
95
  /** "fra", "nyc", ... Unset: the API's home region. */
96
96
  region?: string;
97
- /** Default https://boxd.sh:9443, the SDK's own. */
97
+ /** https alone; default https://boxd.sh:9443, the SDK's own. */
98
98
  baseUrl?: string;
99
99
  /** A boxd size, both or neither: 1 and 4G, 2 and 8G, 4 and 16G, 8 and 32G. Unset: the org's default. */
100
100
  vcpu?: number;
package/dist/boxd.js CHANGED
@@ -9,6 +9,7 @@ import { DEADLINE_LABEL, show } from "./drift.js";
9
9
  import { HostError } from "./host.js";
10
10
  import { CALL_SLACK_MS, codeOfError, orThrow, race, runChecked, until } from "./hosted/process.js";
11
11
  import { HostedProvider, mayHaveMade } from "./hosted/provider.js";
12
+ import { httpsBase } from "./hosted/rest.js";
12
13
  import { shellLine } from "./hosted/scripts.js";
13
14
  import { dateOf } from "./hosted/values.js";
14
15
  import { failFor, ok } from "./result.js";
@@ -409,7 +410,7 @@ export class BoxdProvider extends HostedProvider {
409
410
  const kind = rest.kind === "desktop" ? "desktop" : "linux";
410
411
  if (kind === "desktop" && vcpu !== undefined)
411
412
  throw new Error("a boxd desktop starts from a snapshot, which keeps the size it was captured at: name no vcpu or memory for kind desktop");
412
- const client = { apiKey, baseURL: baseUrl, region };
413
+ const client = { apiKey, baseURL: httpsBase(baseUrl, "the boxd API URL"), region };
413
414
  const { machines, snapshots } = new Boxd({ ...client, timeout: rest.timeouts?.requestMs ?? REQUEST_MS });
414
415
  const creator = new Boxd({ ...client, timeout: rest.timeouts?.createMs ?? CREATE_MS, maxRetries: 0 }).machines;
415
416
  const size = vcpu === undefined ? undefined : { vcpu, memory: memory };
@@ -9,7 +9,7 @@ import { DEFAULT_CPUS, DEFAULT_MEMORY_MB, show } from "./drift.js";
9
9
  import { HostError } from "./host.js";
10
10
  import { orThrow } from "./hosted/process.js";
11
11
  import { HostedProvider } from "./hosted/provider.js";
12
- import { jsonOf, rest } from "./hosted/rest.js";
12
+ import { httpsBase, jsonOf, rest } from "./hosted/rest.js";
13
13
  import { dateOf } from "./hosted/values.js";
14
14
  import { fail, ok } from "./result.js";
15
15
  import { connectionError } from "./test-connection.js";
@@ -164,11 +164,12 @@ export class CloudflareProvider extends HostedProvider {
164
164
  const { relayUrl, relayToken, fetch: fetcher = globalThis.fetch, timeouts = {}, ...rest } = options ?? {};
165
165
  if (typeof relayToken !== "string" || relayToken === "")
166
166
  throw new Error("options.relayToken, the relay's RELAY_TOKEN, is required: the provider reads no environment, so the caller passes it");
167
- if (typeof relayUrl !== "string" || !URL.canParse(relayUrl) || new URL(relayUrl).protocol !== "https:")
168
- throw new Error(`options.relayUrl is the relay Worker's https address, as wrangler deploy printed it, not ${JSON.stringify(relayUrl)}`);
167
+ if (typeof relayUrl !== "string" || relayUrl === "")
168
+ throw new Error("options.relayUrl, the relay Worker's https address as wrangler deploy printed it, is required");
169
+ const base = httpsBase(relayUrl, "the Cloudflare relay URL");
169
170
  if (typeof fetcher !== "function")
170
171
  throw new Error("options.fetch must be a function, as the global fetch is");
171
- const host = new CloudflareHost({ relayUrl, relayToken, fetch: fetcher });
172
+ const host = new CloudflareHost({ relayUrl: base, relayToken, fetch: fetcher });
172
173
  super(host, { ...rest, timeouts: { ...CLOUDFLARE_TIMEOUTS, ...timeouts } });
173
174
  this.#relay = host;
174
175
  }
Binary file
Binary file
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "0.1.0-beta.55",
3
- "source": "sha256:5c8354f05971b8dbef31c6da6280d72a3cb272a2dbd24515e724441d9d6034ca"
2
+ "version": "0.1.0-beta.57",
3
+ "source": "sha256:724f889fc95233b98e71e6ff4456498fb220f704db4ca2caed5772e3984ba4de"
4
4
  }
@@ -20,6 +20,22 @@ export declare const EGRESS_READY_MS = 10000;
20
20
  export declare const CODE_FILES: string[];
21
21
  /** The proxy container's name, and the volume's, for computer `name`. */
22
22
  export declare const egressNameOf: (name: string) => string;
23
+ /** The bridge every egress proxy is on, and the label and option it is made with (egressNetworkArgs). */
24
+ export declare const EGRESS_NETWORK = "agentrun-egress";
25
+ export declare const EGRESS_NETWORK_LABEL = "agentrun.computer.egress-network";
26
+ /** `docker network create` of EGRESS_NETWORK: a local bridge with inter-container traffic off, carrying its label. */
27
+ export declare function egressNetworkArgs(): string[];
28
+ /** What `docker network inspect` reports of a network that egressNetworkProblem reads. */
29
+ export interface DockerNetworkInspect {
30
+ Name?: string;
31
+ Driver?: string;
32
+ Scope?: string;
33
+ Internal?: boolean;
34
+ Options?: Record<string, string> | null;
35
+ Labels?: Record<string, string> | null;
36
+ }
37
+ /** Why the network named EGRESS_NETWORK is not one egressNetworkArgs makes, in words, or undefined when it is. */
38
+ export declare function egressNetworkProblem(network: DockerNetworkInspect): string | undefined;
23
39
  /** Where the proxy's code is on this machine: this package's dist/docker, and its package.json, which makes Node read
24
40
  * the files as modules. */
25
41
  export interface EgressCode {
@@ -95,8 +111,8 @@ export interface EgressOwner {
95
111
  /**
96
112
  * A computer's network through its proxy, read back from the proxy container's inspect: "open" where its argv holds
97
113
  * `--open public`, else the list its argv holds, when the container is
98
- * the computer's own (its label and deadline), running while the computer runs, and as create makes one (Docker's
99
- * default bridge alone, no port, the computer's user, a read-only root, no capability or privilege, exactly its volume
114
+ * the computer's own (its label and deadline), running while the computer runs, and as create makes one (the
115
+ * provider's bridge EGRESS_NETWORK alone, no port, the computer's user, a read-only root, no capability or privilege, exactly its volume
100
116
  * and its code, `code`'s when given), refusing every one of `local`, the Docker host's own addresses the provider
101
117
  * requires now (more is fine). Anything less is `{ other }` in words, never an allowlist. A host whose addresses
102
118
  * changed since the proxy was made reads as other: fail closed.
@@ -8,10 +8,14 @@
8
8
  // - The volume `<computer>-egress`: a tmpfs of 1 MiB, mode 0700, owned by the computer's uid:gid. The proxy's Unix
9
9
  // socket is made in it; the computer mounts it read-only at EGRESS_MOUNT.
10
10
  // - The proxy container `<computer>-egress`: this package's own proxy (egress-main.ts, egress-proxy.ts, egress-table.ts,
11
- // bound read-only from dist/docker with the package's package.json), in a pinned Node image, on Docker's default
12
- // bridge alone, publishing no port, as the computer's uid:gid, with a read-only root, no capability, no privilege to
13
- // gain, and bounded memory, pids and log. Its argv holds the list (or `--open public`), the computer's deadline (it ends itself then), the
11
+ // bound read-only from dist/docker with the package's package.json), in a pinned Node image, on the provider's own
12
+ // bridge alone (EGRESS_NETWORK), publishing no port, as the computer's uid:gid, with a read-only root, no capability,
13
+ // no privilege to gain, and bounded memory, pids and log. Its argv holds the list (or `--open public`), the computer's deadline (it ends itself then), the
14
14
  // Docker host's own public addresses (refused as this host's) and the hint. It holds no key.
15
+ // - The network EGRESS_NETWORK: one user-defined bridge every proxy of every provider on this Docker host shares, made
16
+ // by the first create that needs it and never removed. Inter-container traffic on it is off (enable_icc=false), and
17
+ // no other workload's container is on it: on Docker's default bridge, one with NET_RAW could ARP-spoof the gateway
18
+ // every proxy goes out through. Each proxy holds no capability, NET_RAW included.
15
19
  // - The computer: init gets `--egress <socket>` and relays its loopback port 3128 to the socket, and tells every program
16
20
  // it starts that port is its HTTP and HTTPS proxy. A program that ignores that reaches nothing: there is no route.
17
21
  // - Both carry the label EGRESS_LABEL=<computer>; release finds the proxy and the volume by it, never by name alone.
@@ -50,6 +54,29 @@ export const CODE_FILES = ["egress-main.js", "egress-proxy.js", "egress-table.js
50
54
  const EXAMPLE = '["pypi.org", "*.pythonhosted.org", "93.184.215.0/24"]';
51
55
  /** The proxy container's name, and the volume's, for computer `name`. */
52
56
  export const egressNameOf = (name) => `${name}-egress`;
57
+ /** The bridge every egress proxy is on, and the label and option it is made with (egressNetworkArgs). */
58
+ export const EGRESS_NETWORK = "agentrun-egress";
59
+ export const EGRESS_NETWORK_LABEL = "agentrun.computer.egress-network";
60
+ const NO_ICC = "com.docker.network.bridge.enable_icc";
61
+ /** `docker network create` of EGRESS_NETWORK: a local bridge with inter-container traffic off, carrying its label. */
62
+ export function egressNetworkArgs() {
63
+ return ["network", "create", "--driver", "bridge", "--opt", `${NO_ICC}=false`, "--label", `${EGRESS_NETWORK_LABEL}=1`, EGRESS_NETWORK];
64
+ }
65
+ /** Why the network named EGRESS_NETWORK is not one egressNetworkArgs makes, in words, or undefined when it is. */
66
+ export function egressNetworkProblem(network) {
67
+ const found = [];
68
+ if (network.Name !== EGRESS_NETWORK)
69
+ found.push(`is named ${show(network.Name)}`);
70
+ if (network.Driver !== "bridge" || network.Scope !== "local")
71
+ found.push(`has driver ${show(network.Driver)} and scope ${show(network.Scope)}, not a local bridge`);
72
+ if (network.Internal === true)
73
+ found.push("is internal, so no proxy on it reaches the internet");
74
+ if (network.Options?.[NO_ICC] !== "false")
75
+ found.push(`has ${NO_ICC} ${show(network.Options?.[NO_ICC])}, not "false"`);
76
+ if (network.Labels?.[EGRESS_NETWORK_LABEL] !== "1")
77
+ found.push(`does not carry the label ${EGRESS_NETWORK_LABEL}=1`);
78
+ return found.length === 0 ? undefined : `the Docker network ${EGRESS_NETWORK} ${found.join(", ")}: it is not the one this provider makes for its egress proxies; remove it (docker network rm ${EGRESS_NETWORK}) and create again`;
79
+ }
53
80
  /** This package's own build: the directory this file is in, and the package's package.json. */
54
81
  export function egressCode() {
55
82
  return { dir: fileURLToPath(new URL(".", import.meta.url)).replace(/\/$/, ""), packageJson: fileURLToPath(new URL("../../package.json", import.meta.url)) };
@@ -174,7 +201,7 @@ export function egressRunArgs({ name, user, image, allow, local, deadline, code,
174
201
  args.push("--log-driver", PROXY_LOG.driver);
175
202
  for (const [key, value] of Object.entries(PROXY_LOG.options))
176
203
  args.push("--log-opt", `${key}=${value}`);
177
- args.push("--network", "bridge");
204
+ args.push("--network", EGRESS_NETWORK);
178
205
  args.push("--mount", `type=volume,src=${proxy},dst=${PROXY_VOLUME}`);
179
206
  if (code.volume === undefined) {
180
207
  args.push("--mount", `type=bind,src=${code.dir},dst=${PROXY_CODE},readonly`, "--mount", `type=bind,src=${code.packageJson},dst=${PROXY_PACKAGE},readonly`);
@@ -198,8 +225,8 @@ const blank = (value) => value === undefined || value === null || value === "" |
198
225
  /**
199
226
  * A computer's network through its proxy, read back from the proxy container's inspect: "open" where its argv holds
200
227
  * `--open public`, else the list its argv holds, when the container is
201
- * the computer's own (its label and deadline), running while the computer runs, and as create makes one (Docker's
202
- * default bridge alone, no port, the computer's user, a read-only root, no capability or privilege, exactly its volume
228
+ * the computer's own (its label and deadline), running while the computer runs, and as create makes one (the
229
+ * provider's bridge EGRESS_NETWORK alone, no port, the computer's user, a read-only root, no capability or privilege, exactly its volume
203
230
  * and its code, `code`'s when given), refusing every one of `local`, the Docker host's own addresses the provider
204
231
  * requires now (more is fine). Anything less is `{ other }` in words, never an allowlist. A host whose addresses
205
232
  * changed since the proxy was made reads as other: fail closed.
@@ -224,8 +251,15 @@ export function egressOf(proxy, owner, code, local = []) {
224
251
  if (owner.running && proxy.State?.Running !== true)
225
252
  return other(`is not running (exit code ${show(proxy.State?.ExitCode)}): the computer reaches nothing`);
226
253
  const networks = Object.keys(proxy.NetworkSettings?.Networks ?? {});
227
- if (host.NetworkMode !== "bridge" || networks.length !== 1 || networks[0] !== "bridge")
228
- return other(`is on network mode ${String(host.NetworkMode)} and networks ${networks.join(", ") || "none"}, not Docker's default bridge alone`);
254
+ // The network by name: create checked it is the provider's bridge (egressNetworkProblem) before the proxy joined it,
255
+ // and Docker removes no network a running container is on, nor changes a network's options.
256
+ if (host.NetworkMode !== EGRESS_NETWORK || networks.length !== 1 || networks[0] !== EGRESS_NETWORK) {
257
+ // Docker's default bridge alone: where this provider put every proxy before the egress bridge.
258
+ if (host.NetworkMode === "bridge" && networks.length === 1 && networks[0] === "bridge") {
259
+ return other(`is on Docker's default bridge: an earlier release of this provider made it there, before the egress bridge ${EGRESS_NETWORK}; delete the computer and create it again`);
260
+ }
261
+ return other(`is on network mode ${String(host.NetworkMode)} and networks ${networks.join(", ") || "none"}, not the provider's bridge ${EGRESS_NETWORK} alone`);
262
+ }
229
263
  if (host.Privileged !== false)
230
264
  return other("is privileged");
231
265
  const capDrop = host.CapDrop;
@@ -125,7 +125,7 @@ export function networkOf(inspected, proxy, code, local) {
125
125
  if (none)
126
126
  return "none";
127
127
  // Open goes through the egress proxy: a computer on a network of Docker's is one this provider never makes.
128
- return { other: where };
128
+ return { other: `${where}, which this provider never makes` };
129
129
  }
130
130
  if (!none)
131
131
  return { other: `${where}, with an egress volume or relay, which this provider never makes` };
package/dist/docker.d.ts CHANGED
@@ -150,7 +150,7 @@ export declare class DockerProvider implements ComputerProvider {
150
150
  /**
151
151
  * Stops or deletes the computer, then its egress proxy, found by its label (EGRESS_LABEL=<name>), and on delete its
152
152
  * egress volume, found the same way: a container or volume of the proxy's name without that label is never touched.
153
- * Each is ok when already gone.
153
+ * Each is ok when already gone, or once gone when Docker answers that its removal is already in progress (#gone).
154
154
  */
155
155
  release(ref: ComputerRef, how: ReleaseHow): Promise<Result<void>>;
156
156
  }
package/dist/docker.js CHANGED
@@ -12,7 +12,7 @@ import { DESKTOP_GROUPS, desktopOf, startDisplay } from "./desktop.js";
12
12
  import { COMPUTER_LABEL, DAEMON_IN_COMPUTER, DEADLINE_LABEL, DEFAULT_CPUS, DEFAULT_MEMORY_MB, DEFAULT_PIDS, helloDrift, WORK, } from "./drift.js";
13
13
  import { CPU_PERIOD_US, DAEMON_DIR_IN_COMPUTER, drift, egressShaped, hostOf, inspectDrift, mountOf, networkOf, samePolicy, tmpfsOf, } from "./docker/inspect.js";
14
14
  import { DOCKER_RECIPE, ensureImage, imageSourceProblem } from "./docker/image.js";
15
- import { ALLOW_PORTS, allowOf, containerSigns, EGRESS_IMAGE, EGRESS_LABEL, EGRESS_MOUNT, EGRESS_READY_MS, EGRESS_SOCKET, egressCode, egressCodeProblem, egressNameOf, egressRunArgs, egressVolumeArgs, hostAddresses, MAX_ALLOW, policyWords, RELAY_FLAG, } from "./docker/egress.js";
15
+ import { ALLOW_PORTS, allowOf, containerSigns, EGRESS_IMAGE, EGRESS_LABEL, EGRESS_MOUNT, EGRESS_NETWORK, EGRESS_READY_MS, EGRESS_SOCKET, egressCode, egressCodeProblem, egressNameOf, egressNetworkArgs, egressNetworkProblem, egressRunArgs, egressVolumeArgs, hostAddresses, MAX_ALLOW, policyWords, RELAY_FLAG, } from "./docker/egress.js";
16
16
  import { daemonStage, daemonVerified, egressStage, egressStaged } from "./docker/stage.js";
17
17
  import { EGRESS_READY } from "./docker/egress-proxy.js";
18
18
  import { OLD_ENGINE, outsideWords, subpathOf, VOLUME_SUBPATH_ENGINE, volumeMount, volumeOf } from "./docker/volume.js";
@@ -131,6 +131,10 @@ const INFO_FORMAT = '{"Architecture":{{json .Architecture}},"SecurityOptions":{{
131
131
  const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
132
132
  const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
133
133
  const noSuchContainer = (stderr) => /no such container/i.test(stderr);
134
+ /** Docker's answer to a docker rm of a container another removal of which is under way: it is going away (#gone). */
135
+ const removalUnderWay = (stderr) => /removal of container \S+ is already in progress/i.test(stderr);
136
+ /** Docker's words for a network it does not have: the CLI's "No such network", or the daemon's "network ... not found". */
137
+ const NO_SUCH_NETWORK = /no such network|network \S+ not found/i;
134
138
  /** Docker's words for a docker run whose --name another container holds. */
135
139
  const nameTaken = (stderr) => /Conflict\. The container name "[^"]*" is already in use/.test(stderr);
136
140
  const nameOf = (report) => (report.Name ?? "").replace(/^\//, "");
@@ -504,7 +508,11 @@ export class DockerProvider {
504
508
  const lifetimeFrom = Date.now();
505
509
  const deadline = new Date(lifetimeFrom + runLifetimeMs(spec)).toISOString();
506
510
  if (allow !== undefined) {
507
- // The proxy first, ready before the computer exists: a computer never runs with a network it cannot reach.
511
+ // The egress bridge first: one of its name this provider did not make is refused before anything is made.
512
+ const network = await this.#egressNetwork(signal);
513
+ if (!network.ok)
514
+ return fail(network.error.code, network.error.message);
515
+ // The proxy next, ready before the computer exists: a computer never runs with a network it cannot reach.
508
516
  const started = await this.#startEgress(name, user, deadline, allow, spec.labels ?? {}, attempt, signal);
509
517
  if (!started.ok) {
510
518
  // Another create of this request, in another process, runs its proxy: what it makes is the request's.
@@ -750,6 +758,38 @@ export class DockerProvider {
750
758
  return late();
751
759
  }
752
760
  }
761
+ /**
762
+ * The bridge every egress proxy is on (EGRESS_NETWORK), made when Docker has none of its name, and read back as the
763
+ * one egressNetworkArgs makes: a network of that name made otherwise is refused in words, and nothing is made. Two
764
+ * creates that both find none both make it; the one Docker refuses as already there reads it back.
765
+ */
766
+ async #egressNetwork(signal) {
767
+ const inspect = () => this.#run(["network", "inspect", "--format", "{{json .}}", EGRESS_NETWORK], signal);
768
+ let found = await inspect();
769
+ if (!found.ok)
770
+ return found;
771
+ if (found.value.exitCode !== 0 && NO_SUCH_NETWORK.test(found.value.stderr)) {
772
+ const made = await this.#run(egressNetworkArgs(), signal);
773
+ if (!made.ok)
774
+ return made;
775
+ if (made.value.exitCode !== 0 && !/already exists/i.test(made.value.stderr))
776
+ return vendorFail("docker", `docker network create ${EGRESS_NETWORK} failed: ${made.value.stderr.trim()}`);
777
+ found = await inspect();
778
+ if (!found.ok)
779
+ return found;
780
+ }
781
+ if (found.value.exitCode !== 0)
782
+ return vendorFail("docker", `docker network inspect ${EGRESS_NETWORK} failed: ${found.value.stderr.trim()}`);
783
+ let network;
784
+ try {
785
+ network = JSON.parse(found.value.stdout);
786
+ }
787
+ catch {
788
+ return vendorFail("docker", `docker network inspect ${EGRESS_NETWORK} wrote what is not JSON: ${found.value.stdout.slice(0, 200)}`);
789
+ }
790
+ const problem = egressNetworkProblem(network ?? {});
791
+ return problem === undefined ? ok(undefined) : fail("refused", problem);
792
+ }
753
793
  /** Starts the desktop's X server through the daemon and waits until hello declares the display (startDisplay). */
754
794
  async #startDisplay(ref, desktop, signal) {
755
795
  const opened = await this.#open(ref, signal);
@@ -913,8 +953,9 @@ export class DockerProvider {
913
953
  if (!proxy.ok)
914
954
  return proxy;
915
955
  const network = networkOf(report, proxy.value, this.#code, this.#hostLocal());
956
+ // Its own words say what is wrong: an old proxy's say what made it and what to do.
916
957
  if (typeof network !== "string" && "other" in network)
917
- found.push(`network: ${network.other}, which this provider never makes`);
958
+ found.push(`network: ${network.other}`);
918
959
  const deadline = config.Labels?.[DEADLINE_LABEL] ?? "";
919
960
  const at = Date.parse(deadline);
920
961
  if (Number.isNaN(at) || new Date(at).toISOString() !== deadline) {
@@ -1158,8 +1199,9 @@ export class DockerProvider {
1158
1199
  const ran = await this.#run(["rm", "--force", proxy.Id], signal);
1159
1200
  if (!ran.ok)
1160
1201
  return ran;
1161
- if (ran.value.exitCode !== 0 && !noSuchContainer(ran.value.stderr))
1162
- return vendorFail("docker", `docker rm of the egress proxy ${nameOf(proxy)} failed: ${ran.value.stderr.trim()}`);
1202
+ const gone = await this.#gone(ran.value, proxy.Id, `docker rm of the egress proxy ${nameOf(proxy)}`, AbortSignal.timeout(SETTLE_MS), signal);
1203
+ if (!gone.ok)
1204
+ return gone;
1163
1205
  removed.push(nameOf(proxy));
1164
1206
  }
1165
1207
  }
@@ -1230,7 +1272,7 @@ export class DockerProvider {
1230
1272
  /**
1231
1273
  * Stops or deletes the computer, then its egress proxy, found by its label (EGRESS_LABEL=<name>), and on delete its
1232
1274
  * egress volume, found the same way: a container or volume of the proxy's name without that label is never touched.
1233
- * Each is ok when already gone.
1275
+ * Each is ok when already gone, or once gone when Docker answers that its removal is already in progress (#gone).
1234
1276
  */
1235
1277
  async release(ref, how) {
1236
1278
  if (!NAME.test(ref.name))
@@ -1262,8 +1304,9 @@ export class DockerProvider {
1262
1304
  const container = await this.#run(["rm", "--force", id], bound);
1263
1305
  if (!container.ok)
1264
1306
  return container;
1265
- if (container.value.exitCode !== 0 && !noSuchContainer(container.value.stderr))
1266
- return vendorFail("docker", `docker rm ${proxy} failed: ${container.value.stderr.trim()}`);
1307
+ const gone = await this.#gone(container.value, id, `docker rm ${proxy}`, bound);
1308
+ if (!gone.ok)
1309
+ return gone;
1267
1310
  }
1268
1311
  const volumes = await this.#run(["volume", "ls", ...filters, "--format", "{{.Name}}"], bound);
1269
1312
  if (!volumes.ok)
@@ -1317,11 +1360,13 @@ export class DockerProvider {
1317
1360
  const mine = report?.Config?.Labels?.[ATTEMPT_LABEL] === attempt;
1318
1361
  // By the id looked at, never by the name, which another create may hold by the time rm runs.
1319
1362
  if (mine) {
1320
- const removed = await this.#run(["rm", "--force", "--volumes", String(report.Id)], AbortSignal.timeout(SETTLE_MS));
1363
+ const bound = AbortSignal.timeout(SETTLE_MS);
1364
+ const removed = await this.#run(["rm", "--force", "--volumes", String(report.Id)], bound);
1321
1365
  if (!removed.ok)
1322
1366
  return removed;
1323
- if (removed.value.exitCode !== 0 && !noSuchContainer(removed.value.stderr))
1324
- return vendorFail("docker", `docker rm ${name} failed: ${removed.value.stderr.trim()}`);
1367
+ const gone = await this.#gone(removed.value, String(report.Id), `docker rm ${name}`, bound);
1368
+ if (!gone.ok)
1369
+ return gone;
1325
1370
  }
1326
1371
  const proxy = await this.#removeProxy(name, attempt);
1327
1372
  return proxy.ok ? ok(report !== undefined && !mine) : proxy;
@@ -1332,8 +1377,9 @@ export class DockerProvider {
1332
1377
  const ran = await this.#run(args);
1333
1378
  if (!ran.ok)
1334
1379
  return ran;
1335
- if (ran.value.exitCode !== 0 && !noSuchContainer(ran.value.stderr))
1336
- return vendorFail("docker", `docker ${args[0]} ${ref.name} failed: ${ran.value.stderr.trim()}`);
1380
+ const gone = await this.#gone(ran.value, ref.name, `docker ${args[0]} ${ref.name}`, AbortSignal.timeout(SETTLE_MS));
1381
+ if (!gone.ok)
1382
+ return gone;
1337
1383
  const label = `label=${EGRESS_LABEL}=${ref.name}`;
1338
1384
  const proxies = await this.#run(["ps", "-a", "--no-trunc", "--filter", label, "--format", "{{.ID}}"]);
1339
1385
  if (!proxies.ok)
@@ -1344,8 +1390,9 @@ export class DockerProvider {
1344
1390
  const ended = await this.#run(how === "stop" ? ["stop", id] : ["rm", "--force", id]);
1345
1391
  if (!ended.ok)
1346
1392
  return ended;
1347
- if (ended.value.exitCode !== 0 && !noSuchContainer(ended.value.stderr))
1348
- return vendorFail("docker", `docker ${how === "stop" ? "stop" : "rm"} of ${ref.name}'s egress proxy failed: ${ended.value.stderr.trim()}`);
1393
+ const gone = await this.#gone(ended.value, id, `docker ${how === "stop" ? "stop" : "rm"} of ${ref.name}'s egress proxy`, AbortSignal.timeout(SETTLE_MS));
1394
+ if (!gone.ok)
1395
+ return gone;
1349
1396
  }
1350
1397
  if (how === "stop")
1351
1398
  return ok(undefined);
@@ -1363,6 +1410,32 @@ export class DockerProvider {
1363
1410
  }
1364
1411
  return ok(undefined);
1365
1412
  }
1413
+ /**
1414
+ * Whether the docker rm (or stop) that answered `ran` left container `key` gone, `what` naming the call: ok on exit 0
1415
+ * or "No such container". "Removal of container ... is already in progress" means another removal of it is under way,
1416
+ * so it is going away: it is looked for, SETTLE_EVERY_MS apart, until it is gone (ok), the caller's `signal` aborts
1417
+ * (aborted), or `bound` runs out with it still there (a failure that names it). Every other answer is the failure it is.
1418
+ */
1419
+ async #gone(ran, key, what, bound, signal) {
1420
+ if (ran.exitCode === 0 || noSuchContainer(ran.stderr))
1421
+ return ok(undefined);
1422
+ if (!removalUnderWay(ran.stderr))
1423
+ return vendorFail("docker", `${what} failed: ${ran.stderr.trim()}`);
1424
+ const from = Date.now();
1425
+ const either = signal ? AbortSignal.any([signal, bound]) : bound;
1426
+ for (;;) {
1427
+ const look = await this.#inspect([key], either, "{{json .Id}}");
1428
+ if (look.ok && look.value.length === 0)
1429
+ return ok(undefined);
1430
+ if (signal?.aborted)
1431
+ return fail("aborted", `${what} was aborted while docker was still removing ${key}`);
1432
+ if (bound.aborted)
1433
+ return vendorFail("docker", `${what} failed: docker answered that the removal of ${key} was already in progress, and it was still there ${Math.round((Date.now() - from) / 1000)} s later`);
1434
+ if (!look.ok)
1435
+ return look;
1436
+ await sleep(SETTLE_EVERY_MS, undefined, { signal: either }).catch(() => undefined);
1437
+ }
1438
+ }
1366
1439
  /** Inspects containers by name or id, whole or only the fields a format names; one that is gone is left out. */
1367
1440
  async #inspect(keys, signal, format = "{{json .}}") {
1368
1441
  const ran = await this.#run(["inspect", "--type", "container", "--format", format, ...keys], signal);
package/dist/groundbox.js CHANGED
@@ -93,18 +93,19 @@ const DIR_PREFIX = "/tmp/.agentrun-exec-";
93
93
  * The sh every command starts under ($1 its directory, then the argv). It makes the directory with mode 0700, as
94
94
  * mktemp -d does, and a path already there is never its own: the command does not start (exit 126). In it, the fifo
95
95
  * and the record of its own pid and start time (as PID_WRAPPER's line, for the kill; written whole and then renamed,
96
- * so the kill never reads half of it). Once both are there it puts MARK on stderr, before any byte of the argv's: a
97
- * write and the kill wait for it (Groundbox says `started` before the sh has run), so neither polls. It runs the argv
98
- * with the fifo as its stdin, opened to read and write, so the fifo never reads end of file between two writers; then it
99
- * removes the directory and exits as the argv did.
96
+ * so the kill never reads half of it). Once both are there it puts its mark (markOf) on stderr, before any byte of the
97
+ * argv's: a write and the kill wait for it (Groundbox says `started` before the sh has run), so neither polls. The sh
98
+ * holds the fifo open to read and write until it exits, so a write's open never waits for a reader, even once the argv
99
+ * has ended; the argv has it as its stdin, so the fifo never reads end of file between two writers. Then it removes the
100
+ * directory and exits as the argv did.
100
101
  */
101
102
  const START_SCRIPT = [
102
103
  "d=$1; shift",
103
104
  'mkdir -m 700 "$d" 2>/dev/null || { echo "agentrun: $d is already there, so it is not one this command made: the command did not start" >&2; exit 126; }',
104
- 'mkfifo -m 600 "$d/in" || exit 126',
105
+ 'mkfifo -m 600 "$d/in" && exec 3<>"$d/in" || exit 126',
105
106
  'echo "$$ $(s=$(cat /proc/$$/stat 2>/dev/null) && set -- ${s##*") "} && echo "${20}")" >"$d/pid.new" && mv -f "$d/pid.new" "$d/pid" || exit 126',
106
- "echo >&2",
107
- '"$@" 0<>"$d/in"; c=$?',
107
+ 'echo "agentrun-ready:${d##*-}" >&2',
108
+ '"$@" <&3 3<&-; c=$?',
108
109
  'rm -rf "$d"; exit $c',
109
110
  ].join("\n");
110
111
  /**
@@ -115,15 +116,19 @@ const START_SCRIPT = [
115
116
  const OWN_DIR = `cd -P "$d" 2>/dev/null && [ "$(pwd -P)" = "$(cd -P "\${d%/*}" && pwd -P)/\${d##*/}" ] && [ "$(stat -c %u:%a .)" = "$(id -u):700" ] || { echo "$d is not the command's own directory" >&2; exit 4; }`;
116
117
  /** The check of one file in it ($1 its name): not a link, and this user's. */
117
118
  const ownFile = (name) => `[ ! -L ${name} ] && [ "$(stat -c %u ${name})" = "$(id -u)" ] || { echo "$d/${name} is not the command's own" >&2; exit 4; }`;
118
- /** START_SCRIPT's mark, the first byte on stderr once the command's directory, fifo and pid record are made: a newline (`echo >&2`), which no refusal of the sh starts with. */
119
- const MARK = 0x0a;
119
+ /**
120
+ * START_SCRIPT's mark for the command whose directory is `dir`, a whole line on stderr once its directory, fifo and pid
121
+ * record are made: it names the directory's random part, so no other line (a wrapper's warning, another command's mark)
122
+ * reads as it.
123
+ */
124
+ const markOf = (dir) => Buffer.from(`agentrun-ready:${dir.slice(dir.lastIndexOf("-") + 1)}\n`);
120
125
  /**
121
126
  * One write ($1 the command's directory), sent once START_SCRIPT's mark came: its stdin into the fifo there. With no
122
- * fifo the command has ended (its sh removed it): exit 3. The write opens `in`, then checks it is still the fifo before
123
- * cat writes a byte: a fifo that went between the checks and the open leaves a file of the write's own, removed with
124
- * nothing in it, and a command that ends while cat writes leaves it no reader; exit 3 for both. Once cat has put every
125
- * byte in the fifo the write is made, though the command may read them, end, and its sh remove the directory before the
126
- * write answers.
127
+ * fifo the command has ended (its sh removed it): exit 3. The write opens `in`, which never waits for a reader since
128
+ * START_SCRIPT's sh holds the fifo open to the end, then checks it is still the fifo before cat writes a byte: a fifo
129
+ * that went between the checks and the open leaves a file of the write's own, removed with nothing in it, and a command
130
+ * that ends while cat writes leaves it no reader; exit 3 for both. Once cat has put every byte in the fifo the write is
131
+ * made, though the command may read them, end, and its sh remove the directory before the write answers.
127
132
  */
128
133
  const WRITE_SCRIPT = [
129
134
  'd=$1; [ -p "$d/in" ] || exit 3',
@@ -375,7 +380,7 @@ class GroundboxHost {
375
380
  }, argv, ctx);
376
381
  }
377
382
  /**
378
- * Answers once START_SCRIPT's mark came (or the first of a refusal's words, or the stream ended), or STEP_MS passed:
383
+ * Answers once START_SCRIPT's mark came (or the stream ended, as a start its sh refused does), or STEP_MS passed:
379
384
  * before it, the command's directory may not be made yet. The script that follows checks what is there either way.
380
385
  */
381
386
  async #begun(command) {
@@ -393,7 +398,8 @@ class GroundboxHost {
393
398
  async #start(id, argv, ctx) {
394
399
  let begin;
395
400
  const begun = new Promise((done) => (begin = done));
396
- const command = { sandbox: id, dir: `${DIR_PREFIX}${randomBytes(8).toString("hex")}`, seq: 0, marked: false, begun, begin, events: [], queued: 0, paused: false, resuming: false, ended: false, wake: () => { }, quiet: () => { } };
401
+ const dir = `${DIR_PREFIX}${randomBytes(8).toString("hex")}`;
402
+ const command = { sandbox: id, dir, seq: 0, mark: markOf(dir), marked: false, held: Buffer.alloc(0), lineStart: true, begun, begin, events: [], queued: 0, paused: false, resuming: false, ended: false, wake: () => { }, quiet: () => { } };
397
403
  const first = { type: "start", args: ["sh", "-c", START_SCRIPT, "sh", command.dir, ...argv], resumable: true, encoding: "base64", timeout_s: EXEC_STREAM_MAX_S };
398
404
  try {
399
405
  await this.#connect(command, first, ctx);
@@ -409,14 +415,61 @@ class GroundboxHost {
409
415
  * ends a command still running). A write or a kill still waiting for the mark goes on to its script.
410
416
  */
411
417
  #end(command, failure) {
412
- if (!command.ended)
418
+ if (!command.ended) {
413
419
  command.failure ??= failure;
420
+ this.#release(command);
421
+ }
414
422
  command.ended = true;
415
423
  command.quiet();
416
424
  command.socket?.close(END);
417
425
  command.begin();
418
426
  command.wake();
419
427
  }
428
+ /** Output read, queued for #events. */
429
+ #queue(command, stream, base64) {
430
+ if (base64 === "")
431
+ return;
432
+ command.events.push({ stream, base64 });
433
+ command.queued += bytesOf(base64);
434
+ }
435
+ /**
436
+ * stderr read before START_SCRIPT's mark, a whole line: the mark is taken off and settles begun, and the rest is
437
+ * queued as it is. Bytes that may still be the mark's start (a line's first bytes, matching it so far) are held for the
438
+ * next chunk, never more than the mark's length; anything else is queued at once, so a refusal's words are stderr whole.
439
+ */
440
+ #unmark(command, chunk) {
441
+ const bytes = command.held.length === 0 ? chunk : Buffer.concat([command.held, chunk]);
442
+ const { mark } = command;
443
+ command.held = Buffer.alloc(0);
444
+ const lineAfter = (from) => {
445
+ const newline = bytes.indexOf(0x0a, from);
446
+ return newline === -1 ? bytes.length : newline + 1;
447
+ };
448
+ for (let at = command.lineStart ? 0 : lineAfter(0); at < bytes.length; at = lineAfter(at)) {
449
+ const line = bytes.subarray(at, at + mark.length);
450
+ if (line.length === mark.length && line.equals(mark)) {
451
+ this.#queue(command, "stderr", bytes.subarray(0, at).toString("base64"));
452
+ command.marked = true;
453
+ command.begin();
454
+ this.#queue(command, "stderr", bytes.subarray(at + mark.length).toString("base64"));
455
+ return;
456
+ }
457
+ if (line.length < mark.length && line.equals(mark.subarray(0, line.length))) {
458
+ this.#queue(command, "stderr", bytes.subarray(0, at).toString("base64"));
459
+ command.held = Buffer.from(line);
460
+ command.lineStart = true;
461
+ return;
462
+ }
463
+ }
464
+ this.#queue(command, "stderr", bytes.toString("base64"));
465
+ if (bytes.length > 0)
466
+ command.lineStart = bytes[bytes.length - 1] === 0x0a;
467
+ }
468
+ /** The stream ended with no mark: what was held as its possible start is stderr after all. */
469
+ #release(command) {
470
+ this.#queue(command, "stderr", command.held.toString("base64"));
471
+ command.held = Buffer.alloc(0);
472
+ }
420
473
  /**
421
474
  * One socket of the command's stream: `first` is its start, or an attach from the position read to. It answers once
422
475
  * the socket is the command's (a start: Groundbox said `started`; an attach: Groundbox said anything on it, so a peer
@@ -503,20 +556,11 @@ class GroundboxHost {
503
556
  ready();
504
557
  }
505
558
  else if ((message.type === "stdout" || message.type === "stderr") && typeof message.data === "string") {
506
- let base64 = message.data;
507
- // stderr's first byte lets the writes and the kill go as it comes, read or not: START_SCRIPT's mark, taken off,
508
- // or the first of the words of a start its sh refused, kept.
509
- if (message.type === "stderr" && !command.marked && base64 !== "") {
510
- const bytes = Buffer.from(base64, "base64");
511
- command.marked = true;
512
- command.begin();
513
- if (bytes[0] === MARK)
514
- base64 = bytes.subarray(1).toString("base64");
515
- }
516
- if (base64 !== "") {
517
- command.events.push({ stream: message.type, base64 });
518
- command.queued += bytesOf(base64);
519
- }
559
+ // Before START_SCRIPT's mark, stderr is read for it: the mark lets the writes and the kill go as it comes, read or not.
560
+ if (message.type === "stderr" && !command.marked)
561
+ this.#unmark(command, Buffer.from(message.data, "base64"));
562
+ else
563
+ this.#queue(command, message.type, message.data);
520
564
  if (typeof message.seq === "number")
521
565
  command.seq = message.seq;
522
566
  // Everything up to seq is queued: a socket opened later attaches from there, and nothing is lost or read twice.
@@ -527,6 +571,7 @@ class GroundboxHost {
527
571
  this.#end(command, new Error(`Groundbox no longer keeps ${String(message.bytes)} bytes of the command's output, lost while its stream was down`));
528
572
  }
529
573
  else if (message.type === "exit" && typeof message.exit_code === "number") {
574
+ this.#release(command);
530
575
  command.events.push({ exit: message.exit_code });
531
576
  this.#end(command);
532
577
  }
@@ -73,7 +73,9 @@ export interface Rest {
73
73
  }
74
74
  /**
75
75
  * An API's https base URL, with no trailing slash, so a key never crosses in the clear; throws in words on another,
76
- * loopback http included. Every provider that sends a key takes its URL through it.
76
+ * loopback http included. Every provider that takes a URL from its caller and sends a key to it takes the URL through
77
+ * it: Agent37, boxd, Browserbase, the Cloudflare relay, Daytona, Groundbox, Kernel, Modal, Morph, Orgo, the phone
78
+ * harness and smol cloud. E2B takes a host name and Fly nothing, and each builds its https URL itself.
77
79
  */
78
80
  export declare function httpsBase(url: string, what: string): string;
79
81
  export declare function rest(options: RestOptions): Rest;
@@ -43,7 +43,9 @@ function redirected(cause) {
43
43
  const NO_BODY = { async *[Symbol.asyncIterator]() { } };
44
44
  /**
45
45
  * An API's https base URL, with no trailing slash, so a key never crosses in the clear; throws in words on another,
46
- * loopback http included. Every provider that sends a key takes its URL through it.
46
+ * loopback http included. Every provider that takes a URL from its caller and sends a key to it takes the URL through
47
+ * it: Agent37, boxd, Browserbase, the Cloudflare relay, Daytona, Groundbox, Kernel, Modal, Morph, Orgo, the phone
48
+ * harness and smol cloud. E2B takes a host name and Fly nothing, and each builds its https URL itself.
47
49
  */
48
50
  export function httpsBase(url, what) {
49
51
  let parsed;
package/dist/modal.d.ts CHANGED
@@ -38,7 +38,7 @@ export interface ModalClientOptions {
38
38
  /** The Modal token's id and secret. Serve passes its MODAL_TOKEN_ID and MODAL_TOKEN_SECRET; the conformance module the token it reads. */
39
39
  tokenId: string;
40
40
  tokenSecret: string;
41
- /** The server the token goes to; default the SDK's, https://api.modal.com:443. */
41
+ /** The server the token goes to, https alone; default the SDK's, https://api.modal.com:443. */
42
42
  serverUrl?: string;
43
43
  /** The SDK's ModalClient; imported from the host's modal package by default. */
44
44
  ModalClient?: ModalClientConstructor;
package/dist/modal.js CHANGED
@@ -3,6 +3,7 @@ import { MODAL } from "./descriptors/modal.js";
3
3
  import { DEFAULT_CPUS, DEFAULT_MEMORY_MB, WORK } from "./drift.js";
4
4
  import { HostError } from "./host.js";
5
5
  import { HostedProvider } from "./hosted/provider.js";
6
+ import { httpsBase } from "./hosted/rest.js";
6
7
  import { AGENTRUN_DIAL, PID_WRAPPER, pidKill, pidStderr } from "./hosted/scripts.js";
7
8
  import { connectOf, kindRefusal } from "./descriptor.js";
8
9
  import { isWhole } from "./hosted/values.js";
@@ -34,8 +35,7 @@ export async function modalClient({ tokenId, tokenSecret, serverUrl = MODAL_DEFA
34
35
  if (typeof tokenId !== "string" || tokenId === "" || typeof tokenSecret !== "string" || tokenSecret === "") {
35
36
  throw new Error("the Modal provider needs options.tokenId and options.tokenSecret, a Modal token: it reads none from the environment, so the caller passes it");
36
37
  }
37
- if (typeof serverUrl !== "string" || !URL.canParse(serverUrl))
38
- throw new Error("options.serverUrl is the Modal server's URL, such as https://api.modal.com:443");
38
+ const server = httpsBase(serverUrl, "the Modal server URL (options.serverUrl)");
39
39
  const ambient = `the Modal provider refuses to start while MODAL_SERVER_URL is set: the SDK would send the key there. Unset it, and pass the server as options.serverUrl if it is not ${MODAL_DEFAULT_SERVER_URL}`;
40
40
  if (process.env.MODAL_SERVER_URL)
41
41
  throw new Error(ambient);
@@ -46,7 +46,7 @@ export async function modalClient({ tokenId, tokenSecret, serverUrl = MODAL_DEFA
46
46
  if (process.env.MODAL_SERVER_URL)
47
47
  throw new Error(ambient);
48
48
  const before = process.env.MODAL_SERVER_URL;
49
- process.env.MODAL_SERVER_URL = serverUrl;
49
+ process.env.MODAL_SERVER_URL = server;
50
50
  try {
51
51
  return new Client({ tokenId, tokenSecret });
52
52
  }
package/dist/morph.js CHANGED
@@ -22,7 +22,7 @@ import { proxyFor, tunnelThrough } from "./env-proxy.js";
22
22
  import { HostError } from "./host.js";
23
23
  import { orThrow, pause, runToExit, uploadThroughExec } from "./hosted/process.js";
24
24
  import { HostedProvider, isoOf, MAX_LABEL } from "./hosted/provider.js";
25
- import { jsonOf, rest } from "./hosted/rest.js";
25
+ import { httpsBase, jsonOf, rest } from "./hosted/rest.js";
26
26
  import { pemOf, SshExec, SshTunnelError } from "./hosted/ssh-exec.js";
27
27
  import { DOMAIN, dateOf, sizeRefusals } from "./hosted/values.js";
28
28
  import { failFor, ok } from "./result.js";
@@ -481,15 +481,9 @@ export class MorphProvider extends HostedProvider {
481
481
  throw new Error("options.ssh2 must be the ssh2 package (its Client class): the host installs it, as it does for Agent37");
482
482
  if (typeof fetcher !== "function")
483
483
  throw new Error("options.fetch must be a function, as the global fetch is");
484
- let api;
485
- try {
486
- api = new URL(apiUrl);
487
- }
488
- catch {
489
- throw new Error(`apiUrl must be an https URL such as ${DEFAULT_API_URL}, not ${JSON.stringify(apiUrl)}`);
490
- }
491
- if (api.protocol !== "https:" || api.search !== "" || api.hash !== "")
492
- throw new Error(`apiUrl must be an https URL such as ${DEFAULT_API_URL}, not ${JSON.stringify(apiUrl)}`);
484
+ const api = new URL(httpsBase(apiUrl, "the Morph API URL"));
485
+ if (api.search !== "" || api.hash !== "")
486
+ throw new Error(`the Morph API URL takes no query or fragment, as ${DEFAULT_API_URL} has none: ${JSON.stringify(apiUrl)}`);
493
487
  if (typeof sshHost !== "string" || !(DOMAIN.test(sshHost) || isIP(sshHost) !== 0))
494
488
  throw new Error(`sshHost must be a host name such as ${DEFAULT_SSH_HOST}, not ${JSON.stringify(sshHost)}`);
495
489
  if (!Number.isSafeInteger(sshPort) || sshPort < 1 || sshPort > 65_535)
@@ -33,6 +33,7 @@ import { readFileSync } from "node:fs";
33
33
  import { checkActions } from "./actions.js";
34
34
  import { readPng } from "./conformance/png.js";
35
35
  import { MACOS_GROUPS, ORGO_MACOS_IMAGE, ORGO_WINDOWS_IMAGE, WINDOWS_GROUPS } from "./descriptors/orgo.js";
36
+ import { httpsBase } from "./hosted/rest.js";
36
37
  import { EPOCH_LABEL, OWNER_LABEL, OWNER_SERVER_LABEL, ownerLabels, RUN_HASH_LABEL, RUN_LABEL, runHash } from "./labels.js";
37
38
  import { checkMount } from "./mount.js";
38
39
  import { ORGO_API_URL, orgoRest } from "./orgo-channel.js";
@@ -356,15 +357,9 @@ export class OrgoDesktopProvider {
356
357
  throw new Error("options.apiKey, an Orgo API key, is required");
357
358
  if (workspaceId !== undefined && (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId)))
358
359
  throw new Error("options.workspaceId, the Orgo workspace this deployment's computers live in, is an Orgo workspace id when given");
359
- let url;
360
- try {
361
- url = new URL(apiUrl);
362
- }
363
- catch {
364
- throw new Error("options.apiUrl is not a URL");
365
- }
366
- if (url.protocol !== "https:" || url.username !== "" || url.password !== "")
367
- throw new Error("options.apiUrl must be https, with no credentials in it: the key goes to it");
360
+ const url = new URL(httpsBase(apiUrl, "the Orgo API URL"));
361
+ if (url.username !== "" || url.password !== "")
362
+ throw new Error("the Orgo API URL holds no credentials: the key goes to it");
368
363
  if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > MAX_LIFETIME_MS)
369
364
  throw new Error(`maxLifetimeMs must be a whole number of ms above 0 and at most 720 h (${MAX_LIFETIME_MS} ms)`);
370
365
  const merged = { ...DEFAULTS, ...timeouts };
package/dist/orgo.js CHANGED
@@ -15,6 +15,7 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
15
15
  import { readFileSync } from "node:fs";
16
16
  import { fileURLToPath } from "node:url";
17
17
  import { networkRefusal } from "./hosted/network.js";
18
+ import { httpsBase } from "./hosted/rest.js";
18
19
  import { childCommands, daemonDrift } from "./hosted/scripts.js";
19
20
  import { DaemonClient } from "./client.js";
20
21
  import { ORGO, ORGO_BASE_IMAGE } from "./descriptors/orgo.js";
@@ -196,15 +197,9 @@ export class OrgoProvider {
196
197
  throw new Error("options.apiKey, an Orgo API key, is required");
197
198
  if (workspaceId !== undefined && (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId)))
198
199
  throw new Error("options.workspaceId, the Orgo workspace this deployment's computers live in, is an Orgo workspace id when given");
199
- let url;
200
- try {
201
- url = new URL(apiUrl);
202
- }
203
- catch {
204
- throw new Error("options.apiUrl is not a URL");
205
- }
206
- if (url.protocol !== "https:" || url.username !== "" || url.password !== "")
207
- throw new Error("options.apiUrl must be https, with no credentials in it: the key goes to it");
200
+ const url = new URL(httpsBase(apiUrl, "the Orgo API URL"));
201
+ if (url.username !== "" || url.password !== "")
202
+ throw new Error("the Orgo API URL holds no credentials: the key goes to it");
208
203
  if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > MAX_LIFETIME_MS)
209
204
  throw new Error(`maxLifetimeMs must be a whole number of ms above 0 and at most Orgo's 720 h (${MAX_LIFETIME_MS} ms)`);
210
205
  const ids = USER.exec(user);
@@ -112,7 +112,7 @@ export interface PhoneProviderOptions {
112
112
  apiKey: string;
113
113
  /** Which phone: "android", a temporary cloud emulator (the default). "ios" is refused until it is built. */
114
114
  platform?: "android" | "ios";
115
- /** The API's base URL; default PHONE_HARNESS_URL. */
115
+ /** The API's base URL, https alone; default PHONE_HARNESS_URL. */
116
116
  baseUrl?: string;
117
117
  /** fetch; default the global one. Tests give a fake. */
118
118
  fetch?: typeof globalThis.fetch;
@@ -18,6 +18,7 @@ import { fileURLToPath } from "node:url";
18
18
  import { DaemonClient } from "./client.js";
19
19
  import { CreateRequests, endedWords, labelsDiffer, otherSpecWords } from "./create-requests.js";
20
20
  import { PHONE_GROUPS, PHONE_HARNESS } from "./descriptors/phone-harness.js";
21
+ import { httpsBase } from "./hosted/rest.js";
21
22
  import { PROTOCOL_VERSION } from "./protocol.js";
22
23
  import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
23
24
  import { failFor, ok, vendorFail } from "./result.js";
@@ -376,7 +377,7 @@ export class PhoneHarnessProvider {
376
377
  if (platform !== "android")
377
378
  throw new Error(`platform ${show(platform)} is not one of android, ios`);
378
379
  this.#apiKey = apiKey;
379
- this.#baseUrl = (options.baseUrl ?? PHONE_HARNESS_URL).replace(/\/+$/, "");
380
+ this.#baseUrl = httpsBase(options.baseUrl ?? PHONE_HARNESS_URL, "the phone harness URL");
380
381
  this.#fetch = options.fetch ?? globalThis.fetch;
381
382
  const adb = options.adb;
382
383
  if (adb !== undefined && typeof adb !== "string" && !(typeof adb?.run === "function" && typeof adb?.server === "function" && typeof adb?.open === "function")) {
@@ -458,6 +459,8 @@ export class PhoneHarnessProvider {
458
459
  method,
459
460
  headers: { Authorization: `Bearer ${this.#apiKey}`, Accept: "application/json", ...(body === undefined ? {} : { "Content-Type": "application/json" }), ...headers },
460
461
  ...(body === undefined ? {} : { body: JSON.stringify(body) }),
462
+ // Never followed: the key's header would go on to wherever a redirect points, as rest.ts's client refuses too.
463
+ redirect: "error",
461
464
  signal: either,
462
465
  });
463
466
  }
@@ -43,7 +43,8 @@ export function redactWords(words) {
43
43
  .replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+/gi, "[a secret]")
44
44
  // A secret-named parameter, its name with a prefix or suffix too: api_key=, access_token=, client_secret=.
45
45
  .replace(/\b[\w-]*(?:token|password|passwd|secret|key|jwt|auth|code|signingKey|credential)[\w-]*=[^\s&"';,]+/gi, "[a secret]")
46
- .replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9._-]*/g, "[a secret]")
46
+ // A token from the first "eyJ" of its run, glued to a word ("id_eyJ...") too.
47
+ .replace(/eyJ(?<!eyJ[A-Za-z0-9_-]*?eyJ)[A-Za-z0-9_-]+\.[A-Za-z0-9._-]*/g, "[a secret]")
47
48
  .replace(/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, "[a secret]")
48
49
  .replace(/\bgh[pousr]_[A-Za-z0-9]{16,}/g, "[a secret]")
49
50
  .replace(/\b(?:sk|pk|pck|ph|tok|pw|jwt)_[A-Za-z0-9_-]{6,}/g, "[a secret]")
@@ -4,7 +4,7 @@ import { type Result } from "./result.js";
4
4
  export interface SmolcloudProviderOptions extends Omit<HostedOptions, "kind" | "desktop"> {
5
5
  /** The smol cloud API key. The caller passes it; this provider never reads it from the environment. */
6
6
  apiKey: string;
7
- /** The REST API; default https://api.smolmachines.com. */
7
+ /** The REST API, https alone; default https://api.smolmachines.com. */
8
8
  apiUrl?: string;
9
9
  /** The fetch every call goes through; default the global one. */
10
10
  fetch?: typeof fetch;
package/dist/smolcloud.js CHANGED
@@ -14,7 +14,7 @@ import { framedExec } from "./hosted/framed-exec.js";
14
14
  import { networkFormOf } from "./hosted/network.js";
15
15
  import { orThrow, pause } from "./hosted/process.js";
16
16
  import { HostedProvider } from "./hosted/provider.js";
17
- import { jsonOf, rest } from "./hosted/rest.js";
17
+ import { httpsBase, jsonOf, rest } from "./hosted/rest.js";
18
18
  import { shellLine } from "./hosted/scripts.js";
19
19
  import { ok } from "./result.js";
20
20
  export async function create(options) {
@@ -249,6 +249,6 @@ export class SmolcloudProvider extends HostedProvider {
249
249
  const { apiKey, apiUrl = DEFAULT_API_URL, fetch, maxLifetimeMs = DAY_MS, ...rest } = options ?? {};
250
250
  if (typeof apiKey !== "string" || apiKey === "")
251
251
  throw new Error("options.apiKey, the smol cloud API key, is required: the provider reads no environment, so the caller passes it");
252
- super(new SmolcloudHost({ apiKey, apiUrl, ...(fetch ? { fetch } : {}) }), { ...rest, maxLifetimeMs });
252
+ super(new SmolcloudHost({ apiKey, apiUrl: httpsBase(apiUrl, "the smol cloud API URL"), ...(fetch ? { fetch } : {}) }), { ...rest, maxLifetimeMs });
253
253
  }
254
254
  }
@@ -49,11 +49,9 @@ export declare class FolderSync {
49
49
  now?: () => number;
50
50
  });
51
51
  /**
52
- * `entries` (the sink's copy of the folder) pushed into the computer's folder as one streaming tar, each file at
53
- * PUSHED_MTIME, then the baseline taken: the rule a push into a synced folder keeps, in one place. `entries` is read
54
- * only as pushTar reads it, so an abort or a failing source ends it as it ends any push (a source that throws is a
55
- * failed push, and the source is let go). A failure says which step it was: "could not be pushed into the computer:
56
- * ..." or "pushed into the computer could not be listed: ...", its code kept.
52
+ * Pushes `entries` into the folder as one tar (none: an empty tar), each file at PUSHED_MTIME, then takes the
53
+ * baseline. A failure names its step ("could not be pushed into the computer: ..." or "pushed into the computer could
54
+ * not be listed: ..."), its code kept; a source that throws or an abort ends it as any push ends.
57
55
  */
58
56
  push(entries: AsyncIterable<TarEntry> | Iterable<TarEntry>, options?: {
59
57
  signal?: AbortSignal;
@@ -132,11 +132,9 @@ export class FolderSync {
132
132
  this.#now = now;
133
133
  }
134
134
  /**
135
- * `entries` (the sink's copy of the folder) pushed into the computer's folder as one streaming tar, each file at
136
- * PUSHED_MTIME, then the baseline taken: the rule a push into a synced folder keeps, in one place. `entries` is read
137
- * only as pushTar reads it, so an abort or a failing source ends it as it ends any push (a source that throws is a
138
- * failed push, and the source is let go). A failure says which step it was: "could not be pushed into the computer:
139
- * ..." or "pushed into the computer could not be listed: ...", its code kept.
135
+ * Pushes `entries` into the folder as one tar (none: an empty tar), each file at PUSHED_MTIME, then takes the
136
+ * baseline. A failure names its step ("could not be pushed into the computer: ..." or "pushed into the computer could
137
+ * not be listed: ..."), its code kept; a source that throws or an abort ends it as any push ends.
140
138
  */
141
139
  async push(entries, options = {}) {
142
140
  const stamped = (async function* () {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-computer",
3
- "version": "0.1.0-beta.55",
3
+ "version": "0.1.0-beta.57",
4
4
  "description": "The open platform's computer protocol: a daemon in every computer, and one provisioner per vendor, starting with Docker.",
5
5
  "keywords": [
6
6
  "agentrun",