@parcha/agentrun-computer 0.0.0-placeholder → 0.1.0-beta.32
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/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +2400 -1
- package/box/Dockerfile +69 -0
- package/box/agentrun-archil +168 -0
- package/box/build-daytona.py +26 -0
- package/box/build-e2b.mjs +32 -0
- package/box/build-modal.py +17 -0
- package/dist/actions.d.ts +18 -0
- package/dist/actions.js +139 -0
- package/dist/browser.d.ts +151 -0
- package/dist/browser.js +305 -0
- package/dist/browserbase.d.ts +139 -0
- package/dist/browserbase.js +408 -0
- package/dist/child.d.ts +40 -0
- package/dist/child.js +127 -0
- package/dist/client.d.ts +22 -0
- package/dist/client.js +136 -0
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/conformance/archil.d.ts +68 -0
- package/dist/conformance/archil.js +152 -0
- package/dist/conformance/browserbase.d.ts +35 -0
- package/dist/conformance/browserbase.js +45 -0
- package/dist/conformance/cases/apps.d.ts +2 -0
- package/dist/conformance/cases/apps.js +155 -0
- package/dist/conformance/cases/browser.d.ts +4 -0
- package/dist/conformance/cases/browser.js +105 -0
- package/dist/conformance/cases/drift.d.ts +2 -0
- package/dist/conformance/cases/drift.js +64 -0
- package/dist/conformance/cases/exec.d.ts +2 -0
- package/dist/conformance/cases/exec.js +125 -0
- package/dist/conformance/cases/files.d.ts +2 -0
- package/dist/conformance/cases/files.js +294 -0
- package/dist/conformance/cases/health.d.ts +2 -0
- package/dist/conformance/cases/health.js +71 -0
- package/dist/conformance/cases/index.d.ts +9 -0
- package/dist/conformance/cases/index.js +37 -0
- package/dist/conformance/cases/input.d.ts +12 -0
- package/dist/conformance/cases/input.js +109 -0
- package/dist/conformance/cases/isolation.d.ts +21 -0
- package/dist/conformance/cases/isolation.js +92 -0
- package/dist/conformance/cases/lifetime.d.ts +2 -0
- package/dist/conformance/cases/lifetime.js +64 -0
- package/dist/conformance/cases/mount.d.ts +2 -0
- package/dist/conformance/cases/mount.js +252 -0
- package/dist/conformance/cases/process.d.ts +2 -0
- package/dist/conformance/cases/process.js +240 -0
- package/dist/conformance/cases/provider.d.ts +2 -0
- package/dist/conformance/cases/provider.js +302 -0
- package/dist/conformance/cases/screen.d.ts +9 -0
- package/dist/conformance/cases/screen.js +230 -0
- package/dist/conformance/cases/settings.d.ts +57 -0
- package/dist/conformance/cases/settings.js +142 -0
- package/dist/conformance/cases/touch.d.ts +2 -0
- package/dist/conformance/cases/touch.js +117 -0
- package/dist/conformance/cases/util.d.ts +7 -0
- package/dist/conformance/cases/util.js +8 -0
- package/dist/conformance/cdp.d.ts +13 -0
- package/dist/conformance/cdp.js +88 -0
- package/dist/conformance/cli.d.ts +29 -0
- package/dist/conformance/cli.js +231 -0
- package/dist/conformance/daytona-sweep.d.ts +18 -0
- package/dist/conformance/daytona-sweep.js +118 -0
- package/dist/conformance/daytona.d.ts +83 -0
- package/dist/conformance/daytona.js +107 -0
- package/dist/conformance/docker.d.ts +38 -0
- package/dist/conformance/docker.js +70 -0
- package/dist/conformance/drift-daemon.d.ts +8 -0
- package/dist/conformance/drift-daemon.js +41 -0
- package/dist/conformance/e2b-diagnose.d.ts +16 -0
- package/dist/conformance/e2b-diagnose.js +61 -0
- package/dist/conformance/e2b-sweep.d.ts +18 -0
- package/dist/conformance/e2b-sweep.js +125 -0
- package/dist/conformance/e2b.d.ts +74 -0
- package/dist/conformance/e2b.js +111 -0
- package/dist/conformance/fixture.d.ts +65 -0
- package/dist/conformance/fixture.js +98 -0
- package/dist/conformance/index.d.ts +8 -0
- package/dist/conformance/index.js +8 -0
- package/dist/conformance/kernel.d.ts +31 -0
- package/dist/conformance/kernel.js +40 -0
- package/dist/conformance/kind.d.ts +23 -0
- package/dist/conformance/kind.js +58 -0
- package/dist/conformance/modal-sweep.d.ts +22 -0
- package/dist/conformance/modal-sweep.js +190 -0
- package/dist/conformance/modal.d.ts +69 -0
- package/dist/conformance/modal.js +76 -0
- package/dist/conformance/orgo.d.ts +41 -0
- package/dist/conformance/orgo.js +69 -0
- package/dist/conformance/phone-harness.d.ts +61 -0
- package/dist/conformance/phone-harness.js +241 -0
- package/dist/conformance/png.d.ts +16 -0
- package/dist/conformance/png.js +132 -0
- package/dist/conformance/report.d.ts +2 -0
- package/dist/conformance/report.js +86 -0
- package/dist/conformance/runner.d.ts +11 -0
- package/dist/conformance/runner.js +585 -0
- package/dist/conformance/tar.d.ts +13 -0
- package/dist/conformance/tar.js +105 -0
- package/dist/conformance/types.d.ts +257 -0
- package/dist/conformance/types.js +24 -0
- package/dist/daemon-copy.d.ts +40 -0
- package/dist/daemon-copy.js +259 -0
- package/dist/daytona.d.ts +178 -0
- package/dist/daytona.js +1484 -0
- package/dist/desktop.d.ts +24 -0
- package/dist/desktop.js +68 -0
- package/dist/docker/egress-main.d.ts +1 -0
- package/dist/docker/egress-main.js +68 -0
- package/dist/docker/egress-proxy.d.ts +53 -0
- package/dist/docker/egress-proxy.js +450 -0
- package/dist/docker/egress-table.d.ts +39 -0
- package/dist/docker/egress-table.js +197 -0
- package/dist/docker/egress.d.ts +109 -0
- package/dist/docker/egress.js +318 -0
- package/dist/docker/image.d.ts +49 -0
- package/dist/docker/image.js +302 -0
- package/dist/docker/stage.d.ts +21 -0
- package/dist/docker/stage.js +290 -0
- package/dist/docker/volume.d.ts +24 -0
- package/dist/docker/volume.js +67 -0
- package/dist/docker.d.ts +150 -0
- package/dist/docker.js +1200 -0
- package/dist/drift.d.ts +200 -0
- package/dist/drift.js +416 -0
- package/dist/e2b.d.ts +335 -0
- package/dist/e2b.js +1515 -0
- package/dist/entry.d.ts +2 -0
- package/dist/entry.js +24 -0
- package/dist/files.d.ts +50 -0
- package/dist/files.js +208 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +26 -0
- package/dist/isolation.d.ts +29 -0
- package/dist/isolation.js +71 -0
- package/dist/janitor.d.ts +50 -0
- package/dist/janitor.js +135 -0
- package/dist/kernel.d.ts +113 -0
- package/dist/kernel.js +358 -0
- package/dist/kinds.d.ts +79 -0
- package/dist/kinds.js +133 -0
- package/dist/labels.d.ts +23 -0
- package/dist/labels.js +50 -0
- package/dist/modal.d.ts +302 -0
- package/dist/modal.js +1374 -0
- package/dist/mount-archil.d.ts +164 -0
- package/dist/mount-archil.js +471 -0
- package/dist/mount.d.ts +57 -0
- package/dist/mount.js +104 -0
- package/dist/orgo-channel.d.ts +96 -0
- package/dist/orgo-channel.js +391 -0
- package/dist/orgo.d.ts +139 -0
- package/dist/orgo.js +1006 -0
- package/dist/phone-harness.d.ts +185 -0
- package/dist/phone-harness.js +1420 -0
- package/dist/processes.d.ts +24 -0
- package/dist/processes.js +40 -0
- package/dist/protocol.d.ts +729 -0
- package/dist/protocol.js +54 -0
- package/dist/provider.d.ts +245 -0
- package/dist/provider.js +37 -0
- package/dist/providers.d.ts +68 -0
- package/dist/providers.js +25 -0
- package/dist/result.d.ts +15 -0
- package/dist/result.js +2 -0
- package/dist/screen-watch.d.ts +150 -0
- package/dist/screen-watch.js +490 -0
- package/dist/test-connection.d.ts +17 -0
- package/dist/test-connection.js +26 -0
- package/dist/wait.d.ts +23 -0
- package/dist/wait.js +65 -0
- package/package.json +64 -1
package/dist/modal.js
ADDED
|
@@ -0,0 +1,1374 @@
|
|
|
1
|
+
// The Modal provisioner, VM runtime only: every call through the host's own Modal JS SDK client, of which this package
|
|
2
|
+
// names only the slice it uses (ModalSdk) and imports nothing. Every SDK fact below is cited in the README's Modal
|
|
3
|
+
// section, from modal-client@64880502 (js/src) and Modal's docs.
|
|
4
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import { Readable, Writable } from "node:stream";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { DaemonClient } from "./client.js";
|
|
9
|
+
import { COMPUTER_LABEL, DAEMON_IN_COMPUTER, DEADLINE_LABEL, DEFAULT_CPUS, DEFAULT_MEMORY_MB, helloDrift, probeNetworkDrift, probeNotes, probeReportOf, WORK, } from "./drift.js";
|
|
10
|
+
import { OWN_NETWORK_ONLY, probeOwnNetworkDrift, TOOL_USER } from "./isolation.js";
|
|
11
|
+
import { releaseOlder } from "./janitor.js";
|
|
12
|
+
import { EPOCH_LABEL, epochOf, RUN_LABEL } from "./labels.js";
|
|
13
|
+
import { checkMount, readBackOf } from "./mount.js";
|
|
14
|
+
import { ARCHIL_HELPER, ARCHIL_MOUNT_LABEL, ARCHIL_TOOL_UID, archilMount, archilRefusals, archilRelease, claimEpoch, mountDrift, readArchilMount, recordedArchil as recordedArchilOf, syncingClient, } from "./mount-archil.js";
|
|
15
|
+
import { checkLifetime, } from "./provider.js";
|
|
16
|
+
import { fail, ok } from "./result.js";
|
|
17
|
+
import { daemonWatch } from "./screen-watch.js";
|
|
18
|
+
import { connectionError } from "./test-connection.js";
|
|
19
|
+
import { waitUntil } from "./wait.js";
|
|
20
|
+
/** The mount kinds a Modal computer takes, as capabilities().mount declares them: the run's folder on an Archil disk. */
|
|
21
|
+
export const MOUNT = ["archil"];
|
|
22
|
+
/** The machine kind and groups of its one configuration: a linux computer. */
|
|
23
|
+
export const CAPABILITIES = [{ kind: "linux", groups: ["exec", "files", "processes"] }];
|
|
24
|
+
/** A registry tag for linux/amd64 that Modal can pull: the default when a setting names no image. */
|
|
25
|
+
export const MODAL_DEFAULT_IMAGE = "debian:bookworm-slim";
|
|
26
|
+
/** The SDK's default server (modal-client@64880502:js/src/config.ts:143). */
|
|
27
|
+
export const MODAL_DEFAULT_SERVER_URL = "https://api.modal.com:443";
|
|
28
|
+
/** Not a literal, so no type checker or bundler resolves the SDK from this package. */
|
|
29
|
+
const MODAL_PACKAGE = "modal";
|
|
30
|
+
/** The construction now running, or the last one: the next waits for it, so two never overlap. */
|
|
31
|
+
let constructing = Promise.resolve();
|
|
32
|
+
/**
|
|
33
|
+
* A Modal client given the token passed in, and nothing of the environment: a tokenId and tokenSecret passed to
|
|
34
|
+
* ModalClient replace what the environment or the profile held, and clear any OAuth credentials (client.ts:124-148), so a
|
|
35
|
+
* MODAL_TOKEN_ID or ~/.modal.toml on the host is never used. The key goes only to options.serverUrl, else the SDK's
|
|
36
|
+
* default (config.ts:143). ModalClient cannot take a server explicitly: it declares `endpoint` (client.ts:51) and never
|
|
37
|
+
* reads it, and the control-plane client is made from the profile's serverUrl (client.ts:131, 175, 281), which getProfile
|
|
38
|
+
* takes from MODAL_SERVER_URL before any profile's server_url (config.ts:140-143), the profile being MODAL_PROFILE's or the
|
|
39
|
+
* active one in MODAL_CONFIG_PATH or ~/.modal.toml (config.ts:76-82, 126-137).
|
|
40
|
+
*
|
|
41
|
+
* So this is the library's one touch of the environment, a guard and not a setting (README, Settings): an ambient
|
|
42
|
+
* MODAL_SERVER_URL is refused, and MODAL_SERVER_URL is set to the chosen server only while the client is constructed,
|
|
43
|
+
* and put back after, so no profile can redirect the key. process.env is the whole process's: constructions run one at a
|
|
44
|
+
* time, each waiting for the last, so none sees another's server. The modal package is the host's: it is imported only
|
|
45
|
+
* here.
|
|
46
|
+
*/
|
|
47
|
+
export async function modalClient({ tokenId, tokenSecret, serverUrl = MODAL_DEFAULT_SERVER_URL, ModalClient }) {
|
|
48
|
+
if (typeof tokenId !== "string" || tokenId === "" || typeof tokenSecret !== "string" || tokenSecret === "") {
|
|
49
|
+
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");
|
|
50
|
+
}
|
|
51
|
+
if (typeof serverUrl !== "string" || !URL.canParse(serverUrl))
|
|
52
|
+
throw new Error("options.serverUrl is the Modal server's URL, such as https://api.modal.com:443");
|
|
53
|
+
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}`;
|
|
54
|
+
if (process.env.MODAL_SERVER_URL)
|
|
55
|
+
throw new Error(ambient);
|
|
56
|
+
const Client = ModalClient ?? (await import(MODAL_PACKAGE)).ModalClient;
|
|
57
|
+
// getProfile reads MODAL_SERVER_URL from process.env when the client is constructed (client.ts:123), and the
|
|
58
|
+
// control-plane client is made then (client.ts:175); afterwards process.env is as it was. One construction at a time.
|
|
59
|
+
const turn = constructing.then(() => {
|
|
60
|
+
if (process.env.MODAL_SERVER_URL)
|
|
61
|
+
throw new Error(ambient);
|
|
62
|
+
const before = process.env.MODAL_SERVER_URL;
|
|
63
|
+
process.env.MODAL_SERVER_URL = serverUrl;
|
|
64
|
+
try {
|
|
65
|
+
return new Client({ tokenId, tokenSecret });
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
if (before === undefined)
|
|
69
|
+
delete process.env.MODAL_SERVER_URL;
|
|
70
|
+
else
|
|
71
|
+
process.env.MODAL_SERVER_URL = before;
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
constructing = turn.catch(() => undefined);
|
|
75
|
+
return turn;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* A ModalProvider from its options alone: the client as modalClient makes it from the token and server passed in, the
|
|
79
|
+
* app (required), and the daemon copied from options.daemonImage when given, else uploaded (options.daemonPath, else this
|
|
80
|
+
* package's build): given both, the image wins and no upload path is passed on, as the class takes one or the other. It
|
|
81
|
+
* reads no environment but the guard modalClient keeps: serve passes its MODAL_TOKEN_ID, MODAL_TOKEN_SECRET and
|
|
82
|
+
* AGENTRUN_BOX_APP, the conformance module the settings it reads. The app and the token are checked before any client
|
|
83
|
+
* is made, and neither is ever echoed.
|
|
84
|
+
*/
|
|
85
|
+
export async function create(options) {
|
|
86
|
+
const { tokenId, tokenSecret, serverUrl, ModalClient, daemonImage, daemonPath, ...rest } = options ?? {};
|
|
87
|
+
if (typeof rest.app !== "string" || rest.app.trim() === "")
|
|
88
|
+
throw new Error("options.app, the Modal app its sandboxes live in, is required");
|
|
89
|
+
const daemon = daemonImage !== undefined ? { daemonImage } : daemonPath !== undefined ? { daemonPath } : {};
|
|
90
|
+
const sdk = await modalClient({ tokenId, tokenSecret, ...(serverUrl === undefined ? {} : { serverUrl }), ...(ModalClient ? { ModalClient } : {}) });
|
|
91
|
+
return new ModalProvider({ ...rest, ...daemon, sdk });
|
|
92
|
+
}
|
|
93
|
+
/** The conformance CLI's module for Modal: its live switch, the run's 30-minute cap and the drifted twin. */
|
|
94
|
+
export const conformance = () => import("./conformance/modal.js");
|
|
95
|
+
const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
96
|
+
const NAME = /^computer-[0-9a-f]{12}$/;
|
|
97
|
+
/** A sandbox id as the SDK takes one; ownership is decided by its tags, never by its shape. */
|
|
98
|
+
const SANDBOX_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
99
|
+
/** An image Modal already holds, by its id, as box/build-modal.py prints it: opened with images.fromId, never pulled. */
|
|
100
|
+
const MODAL_IMAGE_ID = /^im-[A-Za-z0-9]+$/;
|
|
101
|
+
const NAME_TAG = `${COMPUTER_LABEL}.name`;
|
|
102
|
+
const SPEC_TAG = `${COMPUTER_LABEL}.spec`;
|
|
103
|
+
/** "A Sandbox can carry up to 10 tags" (guide/sandboxes#tagging); the provider uses four. */
|
|
104
|
+
const MAX_TAGS = 10;
|
|
105
|
+
const OWN_TAGS = 4;
|
|
106
|
+
/** "a timeout of up to 24 hours" (guide/sandboxes#timeouts). */
|
|
107
|
+
const MAX_LIFETIME_MS = 24 * 60 * 60 * 1000;
|
|
108
|
+
/** A registry reference pinned by digest. */
|
|
109
|
+
const PINNED = /^[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[0-9]{1,5})?(?:\/[a-z0-9]+(?:[._-][a-z0-9]+)*)*@sha256:[0-9a-f]{64}$/;
|
|
110
|
+
/** A workdir becomes a Dockerfile WORKDIR line, so it holds no space, quote or variable. */
|
|
111
|
+
const WORKDIR = /^\/[A-Za-z0-9._/-]*$/;
|
|
112
|
+
const USER = /^(\d+)(?::(\d+))?$/;
|
|
113
|
+
const MAX_ID = 4_294_967_294;
|
|
114
|
+
const USER_FORM = "a uid or uid:gid in numbers, such as 1000:1000; a name is refused, since the image may not have it";
|
|
115
|
+
/** A user that is root: uid 0, however written, or the name, with or without a group. */
|
|
116
|
+
const ROOT_USER = /^(?:0+|root)(?::|$)/;
|
|
117
|
+
const isRootUser = (value) => typeof value === "string" && ROOT_USER.test(value);
|
|
118
|
+
/**
|
|
119
|
+
* Why a Modal computer never runs as root. Init leaves root no capability, yet uid 0 still owns /, /opt and
|
|
120
|
+
* /opt/agentrun, so it can rename a program of its own over the daemon; no file mode stops the owner of every directory
|
|
121
|
+
* above it. Every connection is Modal's exec of that path, outside the daemon, with Modal's own root capabilities.
|
|
122
|
+
*/
|
|
123
|
+
const ROOT = "a Modal computer does not run as root: each connection is Modal's exec of the daemon's stdio bridge, which runs /opt/agentrun/computerd outside the daemon with Modal's own root capabilities, and a root computer user, though init leaves it no capability, owns /, /opt and /opt/agentrun, so it could replace what that exec runs; ask for another uid, such as 1000:1000";
|
|
124
|
+
/** A probe target: host:port, over TCP, or host:port/udp, a DNS query over UDP. */
|
|
125
|
+
const TARGET = /^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9.-]+):[0-9]{1,5}(?:\/udp)?$/;
|
|
126
|
+
/** Modal's own default request (guide/sandbox-resources, "Pay for what you use"): a spec's sizes are limits, as in Docker. */
|
|
127
|
+
const CPU_REQUEST = 0.125;
|
|
128
|
+
const MEMORY_REQUEST_MIB = 128;
|
|
129
|
+
/** "1 core = 2 vCPUs" (guide/sandbox-resources): a spec's cpus are CPUs, Modal's cpu is physical cores. */
|
|
130
|
+
const CPUS_PER_CORE = 2;
|
|
131
|
+
const DEFAULT_TIMEOUTS = {
|
|
132
|
+
createMs: 600_000,
|
|
133
|
+
callMs: 60_000,
|
|
134
|
+
helloMs: 30_000,
|
|
135
|
+
probeMs: 30_000,
|
|
136
|
+
listMs: 120_000,
|
|
137
|
+
uploadMs: 300_000,
|
|
138
|
+
releaseMs: 120_000,
|
|
139
|
+
releasePollMs: 500,
|
|
140
|
+
mountMs: 120_000,
|
|
141
|
+
};
|
|
142
|
+
/** The user an Archil computer's tools run as: the image's agentrun-tool, with no sudo and no capability. */
|
|
143
|
+
const ARCHIL_USER = `${ARCHIL_TOOL_UID}:${ARCHIL_TOOL_UID}`;
|
|
144
|
+
/**
|
|
145
|
+
* What an Archil computer's entrypoint waits for, beside the daemon, before it becomes init: root makes it through exec
|
|
146
|
+
* once the run's folder is mounted, so no tool program runs before that. The daemon's directory is root's alone.
|
|
147
|
+
*/
|
|
148
|
+
export const ARCHIL_GATE = "/opt/agentrun/archil-mounted";
|
|
149
|
+
/** The longest pause between two of release's polls. */
|
|
150
|
+
const RELEASE_POLL_MAX_MS = 5_000;
|
|
151
|
+
/** The daemon this package builds for Modal's architecture: images must be linux/amd64 (guide/existing-images). */
|
|
152
|
+
const DEFAULT_DAEMON_PATH = fileURLToPath(new URL("./computerd-linux-amd64", import.meta.url));
|
|
153
|
+
/** The SDK's own bytes per stdin message when it streams (task_command_router_client.ts:193): each writeBytes is one call. */
|
|
154
|
+
const UPLOAD_CHUNK = 256 * 1024;
|
|
155
|
+
/** The pause before the bridge is tried again while init is not yet listening. */
|
|
156
|
+
const LISTEN_RETRY_MS = 250;
|
|
157
|
+
/**
|
|
158
|
+
* The sandbox's command when the daemon is uploaded: wait, bounded, for the daemon to be moved into place executable,
|
|
159
|
+
* then become it with exec, so init is the sandbox's main process and the sandbox ends when init does. POSIX sh and
|
|
160
|
+
* tools in BusyBox and coreutils alike; `date +%s` bounds the wait however long a sleep takes, and in whole seconds it
|
|
161
|
+
* ends after more than w seconds and less than w + 3. An Archil computer's (`--gate <path>` before init's arguments)
|
|
162
|
+
* also waits for the gate, which root makes once the run's folder is mounted; a gate there before it starts (an image
|
|
163
|
+
* that holds one) is not this computer's, and goes first.
|
|
164
|
+
*/
|
|
165
|
+
const ENTRYPOINT_SCRIPT = [
|
|
166
|
+
"# agentrun-computer: entrypoint",
|
|
167
|
+
"d=$1; w=$2; h=$3; shift 3",
|
|
168
|
+
'g=; if [ "${1-}" = --gate ]; then g=$2; shift 2; rm -f "$g"; fi',
|
|
169
|
+
"end=$(( $(date +%s) + $w ))",
|
|
170
|
+
'until [ -f "$d" ] && [ -x "$d" ] && { [ -z "$g" ] || [ -f "$g" ]; }; do',
|
|
171
|
+
'\tif [ "$(date +%s)" -gt "$end" ]; then',
|
|
172
|
+
'\t\tif [ -f "$d" ] && [ -x "$d" ]; then echo "agentrun-computer: the Archil mount was not made within $w s ($g is not there), so this computer ends" >&2',
|
|
173
|
+
'\t\telse echo "agentrun-computer: the daemon did not arrive at $d within $w s, so this computer ends" >&2; fi',
|
|
174
|
+
"\t\texit 3",
|
|
175
|
+
"\tfi",
|
|
176
|
+
"\tsleep 0.2 2>/dev/null || sleep 1",
|
|
177
|
+
"done",
|
|
178
|
+
'export HOME="$h"',
|
|
179
|
+
'exec "$d" "$@"',
|
|
180
|
+
].join("\n");
|
|
181
|
+
/** held PATH: every component of PATH up to / is owned by uid 0 with no group or other write, and not a link; else it
|
|
182
|
+
* says which is not and returns 1. The same rule as the Daytona provider's install. */
|
|
183
|
+
const HELD = 'held() { x=$1; while :; do set -- $(ls -ldn "$x" 2>/dev/null); case "$1" in ?????[!w]??[!w]?|?????[!w]??[!w]?.) ;; *) false ;; esac && [ "$3" = 0 ] || { echo "the daemon at $d is not root\'s alone: $x is ${1:-missing}, owner ${3:-none}"; return 1; }; [ "$x" = / ] && return 0; x=${x%/*}; x=${x:-/}; done; }';
|
|
184
|
+
/**
|
|
185
|
+
* The upload, run through exec as root (Modal containers always run as root): stdin to a part file beside the daemon's
|
|
186
|
+
* path, its sha256 printed, and the part moved into place last, only when it is the one named. The rename is what the
|
|
187
|
+
* entrypoint waits for, so it never starts a daemon half written or not the one uploaded.
|
|
188
|
+
*/
|
|
189
|
+
const UPLOAD_SCRIPT = [
|
|
190
|
+
"# agentrun-computer: upload",
|
|
191
|
+
'd=$1; s=$2; b=${d%/*}; p="$b/.computerd.part"',
|
|
192
|
+
// The daemon's path must be root's alone, every directory up to /: each connection runs it as root through Modal's
|
|
193
|
+
// exec, so a path a non-root computer user could change would let that user swap what root runs. A path another
|
|
194
|
+
// user can change is refused with nothing installed; the daemon's own directory is made root's (0755) first.
|
|
195
|
+
HELD,
|
|
196
|
+
'[ -d "${b%/*}" ] || mkdir -p -m 0755 "${b%/*}" || { echo "making ${b%/*} failed"; exit 4; }',
|
|
197
|
+
'held "${b%/*}" || exit 7',
|
|
198
|
+
'[ -L "$b" ] && { echo "the daemon at $d is not root\'s alone: $b is a symbolic link"; exit 7; }',
|
|
199
|
+
'mkdir -p "$b" && chown 0:0 "$b" && chmod 0755 "$b" || { echo "making $b root\'s failed"; exit 4; }',
|
|
200
|
+
'cat > "$p" && chmod 0755 "$p" || { echo "writing the daemon to $p failed"; exit 4; }',
|
|
201
|
+
'r=$(sha256sum "$p" | cut -c1-64)',
|
|
202
|
+
'echo "sha256 $r"',
|
|
203
|
+
'[ "$r" = "$s" ] || { echo "the daemon written to $p reads sha256 $r, not $s, so it is not moved into place"; exit 5; }',
|
|
204
|
+
'mv -f "$p" "$d" || { echo "moving the daemon into $d failed"; exit 6; }',
|
|
205
|
+
'held "$d" || exit 7',
|
|
206
|
+
].join("\n");
|
|
207
|
+
/**
|
|
208
|
+
* The image route's hold step, run as root while the computer's image is built, right after the daemon is copied in:
|
|
209
|
+
* the daemon's directory and binary are made root's (0755), a link is refused, and the whole path up to / is held to
|
|
210
|
+
* the same rule as the upload's. A path another user can change fails the build, so no computer is made from it.
|
|
211
|
+
*/
|
|
212
|
+
const HOLD_SCRIPT = [
|
|
213
|
+
"# agentrun-computer: hold",
|
|
214
|
+
'd=$1; b=${d%/*}',
|
|
215
|
+
HELD,
|
|
216
|
+
'held "${b%/*}" || exit 7',
|
|
217
|
+
'[ -L "$b" ] && { echo "the daemon at $d is not root\'s alone: $b is a symbolic link"; exit 7; }',
|
|
218
|
+
'chown 0:0 "$b" "$d" && chmod 0755 "$b" "$d" || { echo "making $d root\'s failed"; exit 4; }',
|
|
219
|
+
'held "$d" || exit 7',
|
|
220
|
+
].join("\n");
|
|
221
|
+
/**
|
|
222
|
+
* Init's arguments, after the daemon's path: the one place they are built, for the image route's command and the
|
|
223
|
+
* entrypoint alike. Init and every tool run in a network namespace of their own, loopback alone (--own-network), an
|
|
224
|
+
* Archil computer's too: its archil client and serve run through exec as root, outside it.
|
|
225
|
+
*/
|
|
226
|
+
function initArgs({ deadline, user }) {
|
|
227
|
+
return ["init", "--deadline", deadline, "--user", user, "--own-network"];
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* The commands the provider sends into a sandbox when it uploads the daemon, exactly: the sandbox's command
|
|
231
|
+
* (entrypoint, which also waits for `gate` when given: an Archil computer's), the upload, and a connection's bridge
|
|
232
|
+
* (stdio). Exported so a test can run them where Modal would.
|
|
233
|
+
*/
|
|
234
|
+
export function modalCommands({ deadline = "", user = TOOL_USER, waitSeconds = 360, sha256 = "", daemon = DAEMON_IN_COMPUTER, home = WORK, gate, } = {}) {
|
|
235
|
+
return {
|
|
236
|
+
entrypoint: ["sh", "-c", ENTRYPOINT_SCRIPT, "sh", daemon, String(waitSeconds), home, ...(gate === undefined ? [] : ["--gate", gate]), ...initArgs({ deadline, user })],
|
|
237
|
+
upload: ["sh", "-c", UPLOAD_SCRIPT, "sh", daemon, sha256],
|
|
238
|
+
hold: ["sh", "-c", HOLD_SCRIPT, "sh", daemon],
|
|
239
|
+
stdio: [daemon, "stdio"],
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Public anycast resolvers, by address: with no network, not even DNS works (guide/sandbox-networking). TCP to 443, and
|
|
244
|
+
* DNS over UDP to 53, the classic path out where TCP is dropped, over IPv4 and IPv6.
|
|
245
|
+
*/
|
|
246
|
+
const DEFAULT_PROBE_TARGETS = ["1.1.1.1:443", "8.8.8.8:443", "[2606:4700:4700::1111]:443", "1.1.1.1:53/udp", "[2606:4700:4700::1111]:53/udp"];
|
|
247
|
+
/** How long close waits for the stdio bridge to exit once its stdin has ended. Modal has no kill for an exec. */
|
|
248
|
+
const CLOSE_WAIT_MS = 5_000;
|
|
249
|
+
const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "cpus", "memoryMb", "pids", "labels", "workdir", "user", "mount"]);
|
|
250
|
+
const NUL = "a NUL byte cannot be passed to Modal";
|
|
251
|
+
const FIXED = "a Modal computer's network is fixed at create: Modal cannot update the policy of a sandbox made with blockNetwork, and updates only an allowlist set at create; create a new computer";
|
|
252
|
+
const STOP = "Modal has no stop that keeps a sandbox: terminate is a sandbox's only end, and a sandbox that has finished cannot run again; release it with delete";
|
|
253
|
+
const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
|
|
254
|
+
const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
|
|
255
|
+
const show = (value) => (value === undefined ? "nothing" : JSON.stringify(value));
|
|
256
|
+
const seconds = (ms) => `${ms / 1000} s`;
|
|
257
|
+
const pause = (ms, signal) => new Promise((resolve) => {
|
|
258
|
+
const timer = setTimeout(done, ms);
|
|
259
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
260
|
+
function done() {
|
|
261
|
+
clearTimeout(timer);
|
|
262
|
+
signal?.removeEventListener("abort", done);
|
|
263
|
+
resolve();
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
/** Everything a stream gives, as text; what it gave before an error, if it errs. */
|
|
267
|
+
async function textOf(source) {
|
|
268
|
+
let text = "";
|
|
269
|
+
try {
|
|
270
|
+
for await (const chunk of source)
|
|
271
|
+
text = (text + Buffer.from(chunk).toString("utf8")).slice(-8192);
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
// What was read is what there is.
|
|
275
|
+
}
|
|
276
|
+
return text;
|
|
277
|
+
}
|
|
278
|
+
const words = (error) => {
|
|
279
|
+
const name = error?.name;
|
|
280
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
281
|
+
return `${typeof name === "string" && name !== "Error" ? `${name}: ` : ""}${message}`.replace(/\s+/g, " ").slice(0, 300);
|
|
282
|
+
};
|
|
283
|
+
/** The SDK names its errors (js/src/errors.ts); a call that failed on the wire carries a gRPC status code. */
|
|
284
|
+
function codeOf(error) {
|
|
285
|
+
const { name, code } = (error ?? {});
|
|
286
|
+
if (name === "NotFoundError" || code === 5)
|
|
287
|
+
return "not_found";
|
|
288
|
+
if (name === "InvalidError" || code === 3)
|
|
289
|
+
return "invalid";
|
|
290
|
+
// gRPC's UNAUTHENTICATED and PERMISSION_DENIED: a token Modal refused.
|
|
291
|
+
if (code === 16 || code === 7)
|
|
292
|
+
return "denied";
|
|
293
|
+
return "modal";
|
|
294
|
+
}
|
|
295
|
+
/** Settles with the promise's result, or a timeout or abort in words once ms pass or signal aborts. */
|
|
296
|
+
function race(promise, what, ms, signal) {
|
|
297
|
+
if (signal?.aborted) {
|
|
298
|
+
promise.catch(() => { });
|
|
299
|
+
return Promise.resolve(fail("aborted", `${what} was aborted`));
|
|
300
|
+
}
|
|
301
|
+
return new Promise((settle) => {
|
|
302
|
+
const timer = setTimeout(() => done(fail("timeout", `${what} did not answer within ${seconds(ms)}`)), ms);
|
|
303
|
+
const onAbort = () => done(fail("aborted", `${what} was aborted`));
|
|
304
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
305
|
+
let settled = false;
|
|
306
|
+
function done(result) {
|
|
307
|
+
if (settled)
|
|
308
|
+
return;
|
|
309
|
+
settled = true;
|
|
310
|
+
clearTimeout(timer);
|
|
311
|
+
signal?.removeEventListener("abort", onAbort);
|
|
312
|
+
settle(result);
|
|
313
|
+
}
|
|
314
|
+
promise.then((value) => done(ok(value)), (error) => done(fail(codeOf(error), `${what} failed: ${words(error)}`)));
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
/** A signal that aborts after ms, or with signal. Its timer holds the event loop, as AbortSignal.timeout's does not. */
|
|
318
|
+
function within(ms, signal) {
|
|
319
|
+
const controller = new AbortController();
|
|
320
|
+
const timer = setTimeout(() => controller.abort(), ms);
|
|
321
|
+
const onAbort = () => controller.abort();
|
|
322
|
+
if (signal?.aborted)
|
|
323
|
+
controller.abort();
|
|
324
|
+
else
|
|
325
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
326
|
+
return {
|
|
327
|
+
signal: controller.signal,
|
|
328
|
+
clear: () => {
|
|
329
|
+
clearTimeout(timer);
|
|
330
|
+
signal?.removeEventListener("abort", onAbort);
|
|
331
|
+
},
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
/** Calls run and races it; a run that throws at once is an error like one that rejects. */
|
|
335
|
+
function call(what, run, ms, signal) {
|
|
336
|
+
if (signal?.aborted)
|
|
337
|
+
return Promise.resolve(fail("aborted", `${what} was aborted before it was called`));
|
|
338
|
+
let promise;
|
|
339
|
+
try {
|
|
340
|
+
promise = Promise.resolve(run());
|
|
341
|
+
}
|
|
342
|
+
catch (error) {
|
|
343
|
+
return Promise.resolve(fail(codeOf(error), `${what} failed: ${words(error)}`));
|
|
344
|
+
}
|
|
345
|
+
return race(promise, what, ms, signal);
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* The one wait after a terminate, which returns before Modal has ended the sandbox (sandbox.ts:1292-1296, 2238-2251):
|
|
349
|
+
* polls through waitUntil until poll reads an exit code (null while it runs, sandbox.ts:2761-2771) or Modal no longer
|
|
350
|
+
* knows the sandbox. Past boundMs it is a timeout, and on the signal's abort an abort, each saying what poll last read;
|
|
351
|
+
* it never reports a sandbox finished that it did not read finished. release delete, a create that refuses its
|
|
352
|
+
* sandbox, and modal-sweep --after all wait through it.
|
|
353
|
+
*/
|
|
354
|
+
export async function untilFinished(poll, { name, boundMs, callMs, minMs, maxMs, signal }) {
|
|
355
|
+
const finished = await waitUntil((readSignal) => call(`poll of ${name}`, poll, callMs, readSignal), (polled) => (polled.ok && polled.value !== null) || (!polled.ok && polled.error.code === "not_found"), {
|
|
356
|
+
boundMs,
|
|
357
|
+
signal,
|
|
358
|
+
minMs,
|
|
359
|
+
maxMs,
|
|
360
|
+
what: `${name} to finish after its terminate`,
|
|
361
|
+
describe: (polled) => (!polled.ok ? polled.error.message : polled.value === null ? "poll read null: it still runs" : `poll read exit code ${polled.value}`),
|
|
362
|
+
});
|
|
363
|
+
return finished.ok ? ok(undefined) : finished;
|
|
364
|
+
}
|
|
365
|
+
/** Bytes as Buffers, which the daemon client reads lines from. */
|
|
366
|
+
async function* buffers(source) {
|
|
367
|
+
for await (const chunk of source)
|
|
368
|
+
yield Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
|
369
|
+
}
|
|
370
|
+
function labelProblem(key, value) {
|
|
371
|
+
if (typeof value !== "string")
|
|
372
|
+
return `the label ${key} must be a string`;
|
|
373
|
+
if (key.includes("\0") || value.includes("\0"))
|
|
374
|
+
return `the label ${JSON.stringify(key)}: ${NUL}`;
|
|
375
|
+
if (key === "")
|
|
376
|
+
return "a label's name must be non-empty";
|
|
377
|
+
if (key === COMPUTER_LABEL || key.startsWith(`${COMPUTER_LABEL}.`))
|
|
378
|
+
return `the label ${key} is in the provider's own namespace (${COMPUTER_LABEL})`;
|
|
379
|
+
// Modal records the mount in its spec tag, so this label is read nowhere here; it is refused as Daytona and E2B
|
|
380
|
+
// refuse it, so one spec meets the same rule on every provider with an Archil mount.
|
|
381
|
+
if (key === ARCHIL_MOUNT_LABEL)
|
|
382
|
+
return `the label ${key} is the provider's own: it records an Archil computer's mount`;
|
|
383
|
+
return undefined;
|
|
384
|
+
}
|
|
385
|
+
/** Why labels cannot be a tag filter, or undefined when they can. */
|
|
386
|
+
function filterProblem(labels) {
|
|
387
|
+
if (typeof labels !== "object" || labels === null || Array.isArray(labels))
|
|
388
|
+
return "labels must map names to strings";
|
|
389
|
+
for (const [key, value] of Object.entries(labels)) {
|
|
390
|
+
if (typeof value !== "string")
|
|
391
|
+
return `the label ${key} must be a string`;
|
|
392
|
+
if (key === "" || key.includes("\0") || value.includes("\0"))
|
|
393
|
+
return `the label ${JSON.stringify(key)} must be a non-empty name with no NUL byte`;
|
|
394
|
+
}
|
|
395
|
+
return undefined;
|
|
396
|
+
}
|
|
397
|
+
/** "uid:gid" for a user in numbers (a uid alone is its own gid), or undefined when it is not one. */
|
|
398
|
+
function userOf(value) {
|
|
399
|
+
const match = typeof value === "string" ? USER.exec(value) : null;
|
|
400
|
+
if (match === null)
|
|
401
|
+
return undefined;
|
|
402
|
+
const [uid, gid] = [Number(match[1]), Number(match[2] ?? match[1])];
|
|
403
|
+
return uid <= MAX_ID && gid <= MAX_ID ? `${uid}:${gid}` : undefined;
|
|
404
|
+
}
|
|
405
|
+
/** Only a sandbox this provider made counts: its tag, a name of its making, and the name asked for when one is. */
|
|
406
|
+
const ours = (tags, name) => tags[COMPUTER_LABEL] === "1" && NAME.test(tags[NAME_TAG] ?? "") && (name === undefined || tags[NAME_TAG] === name);
|
|
407
|
+
/** The deadline tag as create writes it, an ISO time, or undefined. */
|
|
408
|
+
function deadlineOf(tags) {
|
|
409
|
+
const written = tags[DEADLINE_LABEL];
|
|
410
|
+
const at = written === undefined ? Number.NaN : Date.parse(written);
|
|
411
|
+
return Number.isNaN(at) || new Date(at).toISOString() !== written ? undefined : new Date(at);
|
|
412
|
+
}
|
|
413
|
+
/** The spec tag, parsed, or a sentence saying why it is not the one create writes. */
|
|
414
|
+
function recordedOf(tags) {
|
|
415
|
+
try {
|
|
416
|
+
const value = JSON.parse(tags[SPEC_TAG] ?? "");
|
|
417
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value))
|
|
418
|
+
return value;
|
|
419
|
+
}
|
|
420
|
+
catch {
|
|
421
|
+
// Not JSON: said below.
|
|
422
|
+
}
|
|
423
|
+
return `spec: the tag ${SPEC_TAG} reads ${show(tags[SPEC_TAG])}, not the spec create writes`;
|
|
424
|
+
}
|
|
425
|
+
/** The network a computer was created with, as list reports it: a tag only the host's token writes. */
|
|
426
|
+
function recordedNetwork(tags) {
|
|
427
|
+
const recorded = recordedOf(tags);
|
|
428
|
+
if (typeof recorded !== "string" && (recorded.network === "none" || recorded.network === "open"))
|
|
429
|
+
return recorded.network;
|
|
430
|
+
return { other: `the tag ${SPEC_TAG} names no network this provider makes` };
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* The Archil mount a computer's spec tag records (recordedArchilOf, shared), or undefined when it records none: the
|
|
434
|
+
* tag's mount, under the epoch the tag recorded it at, which must be the label's.
|
|
435
|
+
*/
|
|
436
|
+
function recordedArchil(tags) {
|
|
437
|
+
const recorded = recordedOf(tags);
|
|
438
|
+
if (typeof recorded === "string" || recorded.mount === undefined)
|
|
439
|
+
return undefined;
|
|
440
|
+
const read = epochOf(tags);
|
|
441
|
+
const { kind, disk, region, folder, epoch: was } = (recorded.mount ?? {});
|
|
442
|
+
if (kind !== "archil" || typeof disk !== "string" || typeof region !== "string" || typeof folder !== "string") {
|
|
443
|
+
return recordedArchilOf(tags, { other: `the tag ${SPEC_TAG} records a mount this provider never makes` });
|
|
444
|
+
}
|
|
445
|
+
const mount = { kind, disk, region, folder };
|
|
446
|
+
if (read.ok && was !== read.value) {
|
|
447
|
+
return recordedArchilOf(tags, { mount, other: `the tag ${SPEC_TAG} records the mount under epoch ${show(was)}, yet the label ${EPOCH_LABEL} reads ${read.value}` });
|
|
448
|
+
}
|
|
449
|
+
return recordedArchilOf(tags, { mount });
|
|
450
|
+
}
|
|
451
|
+
/** Every way the probe's report differs from what the computer should be. */
|
|
452
|
+
function probeDrift(probe, expected) {
|
|
453
|
+
const found = [];
|
|
454
|
+
const user = `${probe.uid}:${probe.gid}`;
|
|
455
|
+
if (expected.user !== undefined && user !== expected.user)
|
|
456
|
+
found.push(`user: declared ${expected.user}, read back ${user} (the uid:gid the daemon's programs run as)`);
|
|
457
|
+
if (/gvisor/i.test(probe.kernel))
|
|
458
|
+
found.push(`runtime: declared vm, read back gVisor (the kernel reports ${JSON.stringify(probe.kernel)})`);
|
|
459
|
+
if (expected.network === "none")
|
|
460
|
+
found.push(...probeNetworkDrift(probe));
|
|
461
|
+
// Its own network: the live interfaces lo alone (a kernel's quiet tunnels are none), and none it could bring up.
|
|
462
|
+
found.push(...probeOwnNetworkDrift(probe));
|
|
463
|
+
return found;
|
|
464
|
+
}
|
|
465
|
+
/** Every way the tags read back differ from those create gave. */
|
|
466
|
+
function tagDrift(given, read) {
|
|
467
|
+
const found = [];
|
|
468
|
+
for (const [key, value] of Object.entries(given))
|
|
469
|
+
if (read[key] !== value)
|
|
470
|
+
found.push(`tag ${key}: declared ${show(value)}, read back ${show(read[key])}`);
|
|
471
|
+
for (const [key, value] of Object.entries(read))
|
|
472
|
+
if (!(key in given))
|
|
473
|
+
found.push(`tag ${key}: none declared, read back ${show(value)}`);
|
|
474
|
+
return found;
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Computers that are Modal sandboxes on the VM runtime. The daemon is uploaded right after create, streamed through an
|
|
478
|
+
* exec's stdin, while the sandbox's command, a small sh entrypoint, waits for it and then becomes `computerd init`; or,
|
|
479
|
+
* with daemonImage, it comes in as a layer of the computer's image (COPY --from) and is the command itself. A
|
|
480
|
+
* connection is `computerd stdio` through exec, so a computer with network none is still reached, and needs no network
|
|
481
|
+
* to get its daemon either way. Modal ends each sandbox at its timeout, so the lifetime is the vendor's. Modal reads no
|
|
482
|
+
* network policy back, so the daemon's probe stands for one: network none is honoured only when none of its addresses
|
|
483
|
+
* answers (an address that accepts and sends nothing back is named in the read-back's notes), and an allowlist is
|
|
484
|
+
* refused until the live bypass cases pass.
|
|
485
|
+
*/
|
|
486
|
+
export class ModalProvider {
|
|
487
|
+
id = "modal";
|
|
488
|
+
version = VERSION;
|
|
489
|
+
#sdk;
|
|
490
|
+
#appName;
|
|
491
|
+
#daemonImage;
|
|
492
|
+
#daemonPath;
|
|
493
|
+
#maxLifetimeMs;
|
|
494
|
+
#user;
|
|
495
|
+
#timeouts;
|
|
496
|
+
#probeTargets;
|
|
497
|
+
#onNote;
|
|
498
|
+
#app;
|
|
499
|
+
constructor({ sdk, app, daemonImage, daemonPath, maxLifetimeMs = MAX_LIFETIME_MS, user, timeouts = {}, probeTargets = DEFAULT_PROBE_TARGETS, onNote }) {
|
|
500
|
+
this.#onNote = onNote;
|
|
501
|
+
const lacks = [
|
|
502
|
+
["apps.fromName", sdk?.apps?.fromName],
|
|
503
|
+
["images.fromRegistry", sdk?.images?.fromRegistry],
|
|
504
|
+
["sandboxes.create", sdk?.sandboxes?.create],
|
|
505
|
+
["sandboxes.fromId", sdk?.sandboxes?.fromId],
|
|
506
|
+
["sandboxes.list", sdk?.sandboxes?.list],
|
|
507
|
+
].filter(([, fn]) => typeof fn !== "function");
|
|
508
|
+
if (lacks.length > 0)
|
|
509
|
+
throw new Error(`options.sdk must be a Modal client; it lacks ${lacks.map(([name]) => name).join(", ")}`);
|
|
510
|
+
if (typeof app !== "string" || app.trim() === "")
|
|
511
|
+
throw new Error("options.app, the Modal app's name, is required");
|
|
512
|
+
if (daemonImage !== undefined && daemonPath !== undefined) {
|
|
513
|
+
throw new Error("give daemonImage or daemonPath, not both: the daemon is copied from an image or uploaded, one of them");
|
|
514
|
+
}
|
|
515
|
+
if (daemonImage !== undefined && (typeof daemonImage !== "string" || !PINNED.test(daemonImage))) {
|
|
516
|
+
throw new Error(`the daemon image ${JSON.stringify(daemonImage)} must be pinned by digest, such as ghcr.io/<owner>/computerd@sha256:<64 hex digits>`);
|
|
517
|
+
}
|
|
518
|
+
if (daemonPath !== undefined && (typeof daemonPath !== "string" || daemonPath === ""))
|
|
519
|
+
throw new Error("daemonPath must be the path of the daemon binary");
|
|
520
|
+
if (!isWhole(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > MAX_LIFETIME_MS) {
|
|
521
|
+
throw new Error(`maxLifetimeMs must be a whole number of ms above 0 and at most 24 hours (${MAX_LIFETIME_MS} ms), Modal's longest timeout`);
|
|
522
|
+
}
|
|
523
|
+
const given = user === undefined ? TOOL_USER : userOf(user);
|
|
524
|
+
if (given === undefined)
|
|
525
|
+
throw new Error(`the provider's user ${JSON.stringify(user)} must be ${USER_FORM}`);
|
|
526
|
+
if (given.startsWith("0:"))
|
|
527
|
+
throw new Error(`the provider's user ${user} is root; ${ROOT}`);
|
|
528
|
+
if (given.endsWith(":0"))
|
|
529
|
+
throw new Error(`the provider's user ${user} is in root's group (gid 0); a computer is in group 0 only when its spec asks`);
|
|
530
|
+
const merged = { ...DEFAULT_TIMEOUTS, ...timeouts };
|
|
531
|
+
for (const [key, value] of Object.entries(merged)) {
|
|
532
|
+
if (!isNumber(value) || value <= 0)
|
|
533
|
+
throw new Error(`timeouts.${key} must be a number of ms above 0`);
|
|
534
|
+
}
|
|
535
|
+
if (!Array.isArray(probeTargets) || probeTargets.length === 0)
|
|
536
|
+
throw new Error("probeTargets must name at least one address for the probe");
|
|
537
|
+
const bad = probeTargets.find((target) => typeof target !== "string" || !TARGET.test(target));
|
|
538
|
+
if (bad !== undefined)
|
|
539
|
+
throw new Error(`the probe target ${JSON.stringify(bad)} is not host:port or host:port/udp`);
|
|
540
|
+
this.#sdk = sdk;
|
|
541
|
+
this.#appName = app;
|
|
542
|
+
this.#daemonImage = daemonImage;
|
|
543
|
+
this.#daemonPath = daemonPath ?? DEFAULT_DAEMON_PATH;
|
|
544
|
+
this.#maxLifetimeMs = maxLifetimeMs;
|
|
545
|
+
this.#user = given;
|
|
546
|
+
this.#timeouts = merged;
|
|
547
|
+
this.#probeTargets = [...probeTargets];
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* daemon pid1: the sandbox's command is init itself (with daemonImage) or the entrypoint that execs into it, and Modal
|
|
551
|
+
* finishes the sandbox when that main process exits (sandbox.ts:384-388), so init's exit ends the computer. Whether
|
|
552
|
+
* Modal gives that process the number 1 is not documented; init reaps as a subreaper either way. maxLifetimeMs is this
|
|
553
|
+
* instance's cap: Modal's 24 hours unless the provider was made with less. Init starts with --own-network whatever
|
|
554
|
+
* Modal runs in the sandbox (no listener of its own there is documented, so no port is declared), and network none is
|
|
555
|
+
* all a computer takes until a proxy carries open out of the daemon's own network.
|
|
556
|
+
*/
|
|
557
|
+
capabilities() {
|
|
558
|
+
return {
|
|
559
|
+
kind: "linux",
|
|
560
|
+
lifetime: "vendor",
|
|
561
|
+
network: ["none"],
|
|
562
|
+
networkReadBack: false,
|
|
563
|
+
isolation: "vm",
|
|
564
|
+
os: "linux",
|
|
565
|
+
daemon: "pid1",
|
|
566
|
+
groups: ["exec", "files", "processes"],
|
|
567
|
+
maxLifetimeMs: this.#maxLifetimeMs,
|
|
568
|
+
// Never root: see ROOT.
|
|
569
|
+
user: ["uid"],
|
|
570
|
+
release: ["delete"],
|
|
571
|
+
mount: [...MOUNT],
|
|
572
|
+
vendorAgentPorts: [],
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
/** What hello must report: this package's version, the kind and groups declared, and Modal's one architecture. */
|
|
576
|
+
#expected() {
|
|
577
|
+
const { kind, groups } = this.capabilities();
|
|
578
|
+
return { version: VERSION, kind, groups, arch: "amd64" };
|
|
579
|
+
}
|
|
580
|
+
check(spec) {
|
|
581
|
+
const refusals = [];
|
|
582
|
+
const refuse = (field, message) => refusals.push({ field, message });
|
|
583
|
+
const given = (typeof spec === "object" && spec !== null ? spec : {});
|
|
584
|
+
const { image, lifetimeMs, network, cpus, memoryMb, pids, labels, workdir, user, mount } = given;
|
|
585
|
+
if (typeof image !== "string" || image.trim() === "" || image.startsWith("-") || /\s/.test(image)) {
|
|
586
|
+
refuse("image", `an image is required: a registry tag for linux/amd64 that Modal can pull, such as ${MODAL_DEFAULT_IMAGE}`);
|
|
587
|
+
}
|
|
588
|
+
else if (image.includes("\0"))
|
|
589
|
+
refuse("image", NUL);
|
|
590
|
+
refusals.push(...checkLifetime(lifetimeMs, this.capabilities()));
|
|
591
|
+
if (network === "open" || (typeof network === "object" && network !== null && "allow" in network))
|
|
592
|
+
refuse("network", OWN_NETWORK_ONLY);
|
|
593
|
+
else if (network !== "none")
|
|
594
|
+
refuse("network", 'network is required: "none"');
|
|
595
|
+
if (cpus !== undefined && !(isNumber(cpus) && cpus >= CPU_REQUEST * CPUS_PER_CORE)) {
|
|
596
|
+
refuse("cpus", `cpus must be a number of CPUs of at least ${CPU_REQUEST * CPUS_PER_CORE}: Modal counts physical cores, 2 CPUs each, and requests ${CPU_REQUEST} of one by default`);
|
|
597
|
+
}
|
|
598
|
+
if (memoryMb !== undefined && !(isWhole(memoryMb) && memoryMb > 0))
|
|
599
|
+
refuse("memoryMb", "memoryMb must be a whole number of MiB above 0");
|
|
600
|
+
if (pids !== undefined)
|
|
601
|
+
refuse("pids", "a Modal computer has no pids limit to set, since Modal offers none; leave pids unset");
|
|
602
|
+
if (labels !== undefined) {
|
|
603
|
+
const entries = typeof labels === "object" && labels !== null && !Array.isArray(labels) ? Object.entries(labels) : undefined;
|
|
604
|
+
const bad = entries === undefined ? "labels must map names to strings" : entries.map(([key, value]) => labelProblem(key, value)).find(Boolean);
|
|
605
|
+
if (bad)
|
|
606
|
+
refuse("labels", bad);
|
|
607
|
+
else if ((entries?.length ?? 0) > MAX_TAGS - OWN_TAGS) {
|
|
608
|
+
refuse("labels", `a Modal sandbox carries at most ${MAX_TAGS} tags and this provider uses ${OWN_TAGS}, so a computer takes at most ${MAX_TAGS - OWN_TAGS} labels`);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
if (workdir !== undefined && !(typeof workdir === "string" && WORKDIR.test(workdir))) {
|
|
612
|
+
refuse("workdir", "workdir must be an absolute path of letters, digits and . _ - / only: it becomes the image's WORKDIR");
|
|
613
|
+
}
|
|
614
|
+
if (isRootUser(user))
|
|
615
|
+
refuse("user", ROOT);
|
|
616
|
+
else if (user !== undefined && userOf(user) === undefined)
|
|
617
|
+
refuse("user", `user must be ${USER_FORM}`);
|
|
618
|
+
refusals.push(...checkMount(mount, MOUNT), ...archilRefusals(given));
|
|
619
|
+
const archil = mount?.kind === "archil";
|
|
620
|
+
if (archil && user !== undefined && !isRootUser(user) && userOf(user) !== ARCHIL_USER) {
|
|
621
|
+
refuse("user", `a computer with an Archil mount runs its tools as agentrun-tool, ${ARCHIL_USER}, the user its image makes with no way to root; leave user unset or ask for ${ARCHIL_USER}`);
|
|
622
|
+
}
|
|
623
|
+
for (const [field, value] of Object.entries(given)) {
|
|
624
|
+
if (SPEC_FIELDS.has(field) || value === undefined)
|
|
625
|
+
continue;
|
|
626
|
+
if (field === "gpu")
|
|
627
|
+
refuse(field, "this provider makes VM computers, and Modal offers GPUs on the gVisor runtime only");
|
|
628
|
+
else
|
|
629
|
+
refuse(field, `a Modal computer does not support ${field}`);
|
|
630
|
+
}
|
|
631
|
+
return refusals;
|
|
632
|
+
}
|
|
633
|
+
async create(spec, { signal } = {}) {
|
|
634
|
+
const refusals = this.check(spec);
|
|
635
|
+
if (refusals.length > 0)
|
|
636
|
+
return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
|
|
637
|
+
let daemon;
|
|
638
|
+
if (this.#daemonImage === undefined) {
|
|
639
|
+
let bytes;
|
|
640
|
+
try {
|
|
641
|
+
bytes = readFileSync(this.#daemonPath);
|
|
642
|
+
}
|
|
643
|
+
catch {
|
|
644
|
+
return fail("not_found", `no daemon binary at ${this.#daemonPath}: run npm run build:daemon -w @parcha/agentrun-computer, or give daemonImage`);
|
|
645
|
+
}
|
|
646
|
+
daemon = { bytes, sha256: createHash("sha256").update(bytes).digest("hex") };
|
|
647
|
+
}
|
|
648
|
+
if (signal?.aborted)
|
|
649
|
+
return fail("aborted", "create was aborted before Modal was called");
|
|
650
|
+
const app = await this.#theApp(signal);
|
|
651
|
+
if (!app.ok)
|
|
652
|
+
return app;
|
|
653
|
+
const name = `computer-${randomBytes(6).toString("hex")}`;
|
|
654
|
+
const deadline = new Date(Date.now() + spec.lifetimeMs).toISOString();
|
|
655
|
+
// An Archil mount is made under the run's claim (check() held the spec to both labels), for the tool user alone.
|
|
656
|
+
const archil = spec.mount?.kind === "archil" ? { mount: spec.mount, run: spec.labels?.[RUN_LABEL], epoch: claimEpoch(spec.labels) } : undefined;
|
|
657
|
+
const user = archil === undefined ? (userOf(spec.user) ?? this.#user) : ARCHIL_USER;
|
|
658
|
+
const workdir = spec.workdir ?? WORK;
|
|
659
|
+
const cpus = spec.cpus ?? DEFAULT_CPUS;
|
|
660
|
+
const memoryMb = spec.memoryMb ?? DEFAULT_MEMORY_MB;
|
|
661
|
+
const recorded = {
|
|
662
|
+
image: spec.image,
|
|
663
|
+
user,
|
|
664
|
+
network: spec.network,
|
|
665
|
+
cpus,
|
|
666
|
+
memoryMb,
|
|
667
|
+
workdir,
|
|
668
|
+
runtime: "vm",
|
|
669
|
+
...(archil === undefined ? {} : { mount: readBackOf(archil.mount, archil.epoch) }),
|
|
670
|
+
};
|
|
671
|
+
const tags = { ...spec.labels, [COMPUTER_LABEL]: "1", [NAME_TAG]: name, [DEADLINE_LABEL]: deadline, [SPEC_TAG]: JSON.stringify(recorded) };
|
|
672
|
+
// With daemonImage the daemon comes in as a layer of the computer's own image, there before the command starts.
|
|
673
|
+
// Without, the command is the entrypoint, which waits for the upload below. Either way the computer needs no
|
|
674
|
+
// network to get it. HOME is a directory init gives the computer's user.
|
|
675
|
+
// The image route holds the daemon's path to root's alone in the image itself (exec form, no shell quoting): each
|
|
676
|
+
// connection runs it as root through Modal's exec, so a path a non-root computer user could change fails the build.
|
|
677
|
+
const copy = this.#daemonImage === undefined ? [] : [`COPY --from=${this.#daemonImage} /computerd ${DAEMON_IN_COMPUTER}`, `RUN ${JSON.stringify(modalCommands().hold)}`];
|
|
678
|
+
// An im-... image is one Modal already holds (box/build-modal.py's Archil image): opened by its id. Anything else is a
|
|
679
|
+
// registry tag.
|
|
680
|
+
let base;
|
|
681
|
+
if (MODAL_IMAGE_ID.test(spec.image)) {
|
|
682
|
+
const fromId = this.#sdk.images.fromId;
|
|
683
|
+
if (typeof fromId !== "function")
|
|
684
|
+
return fail("invalid", `the image ${spec.image} is a Modal image id, and options.sdk has no images.fromId to open it: pass the SDK's own ModalClient`);
|
|
685
|
+
const opened = await call(`images.fromId(${spec.image})`, () => fromId.call(this.#sdk.images, spec.image), this.#timeouts.callMs, signal);
|
|
686
|
+
if (!opened.ok)
|
|
687
|
+
return opened;
|
|
688
|
+
base = opened.value;
|
|
689
|
+
}
|
|
690
|
+
else
|
|
691
|
+
base = this.#sdk.images.fromRegistry(spec.image);
|
|
692
|
+
const image = base.dockerfileCommands([...copy, `ENV HOME=${WORK}`, `WORKDIR ${workdir}`]);
|
|
693
|
+
const { uploadMs, callMs } = this.#timeouts;
|
|
694
|
+
// An Archil computer's command is always the entrypoint, which waits for the gate as well as the daemon: init, and
|
|
695
|
+
// so every tool, starts only once the run's folder is mounted.
|
|
696
|
+
const gate = archil === undefined ? undefined : ARCHIL_GATE;
|
|
697
|
+
const waitMs = uploadMs + callMs + (gate === undefined ? 0 : this.#archilMs());
|
|
698
|
+
const command = daemon === undefined && gate === undefined
|
|
699
|
+
? [DAEMON_IN_COMPUTER, ...initArgs({ deadline, user })]
|
|
700
|
+
: modalCommands({ deadline, user, waitSeconds: Math.ceil(waitMs / 1000), home: WORK, ...(gate === undefined ? {} : { gate }) }).entrypoint;
|
|
701
|
+
const cpuLimit = cpus / CPUS_PER_CORE;
|
|
702
|
+
const params = {
|
|
703
|
+
runtime: "vm",
|
|
704
|
+
command,
|
|
705
|
+
// Modal ends the sandbox at its timeout: the lifetime, in the whole seconds the SDK takes.
|
|
706
|
+
timeoutMs: Math.ceil(spec.lifetimeMs / 1000) * 1000,
|
|
707
|
+
workdir,
|
|
708
|
+
cpu: Math.min(CPU_REQUEST, cpuLimit),
|
|
709
|
+
cpuLimit,
|
|
710
|
+
memoryMiB: Math.min(MEMORY_REQUEST_MIB, memoryMb),
|
|
711
|
+
memoryLimitMiB: memoryMb,
|
|
712
|
+
// An Archil computer's root reaches Archil, so Modal's network stays on: its tools' network none is init's own,
|
|
713
|
+
// read back by the probe from inside, as the tool user, like every network none here.
|
|
714
|
+
...(spec.network === "none" && archil === undefined ? { blockNetwork: true } : {}),
|
|
715
|
+
tags,
|
|
716
|
+
};
|
|
717
|
+
let creating;
|
|
718
|
+
try {
|
|
719
|
+
creating = Promise.resolve(this.#sdk.sandboxes.create(app.value, image, params));
|
|
720
|
+
}
|
|
721
|
+
catch (error) {
|
|
722
|
+
return fail(codeOf(error), `sandboxes.create failed: ${words(error)}`);
|
|
723
|
+
}
|
|
724
|
+
const created = await race(creating, "sandboxes.create", this.#timeouts.createMs, signal);
|
|
725
|
+
if (!created.ok) {
|
|
726
|
+
if (created.error.code === "timeout" || created.error.code === "aborted") {
|
|
727
|
+
// The SDK's create goes on without us: a sandbox it makes after this is terminated as it lands.
|
|
728
|
+
creating.then((sandbox) => this.#terminate(sandbox, name)).catch(() => { });
|
|
729
|
+
return fail(created.error.code, `${created.error.message}; a sandbox it makes after this is terminated`);
|
|
730
|
+
}
|
|
731
|
+
return created;
|
|
732
|
+
}
|
|
733
|
+
const sandbox = created.value;
|
|
734
|
+
const ref = { id: sandbox.sandboxId, name };
|
|
735
|
+
// From here the computer exists: every step takes the caller's signal, and an abort or a mismatch terminates it.
|
|
736
|
+
const uploaded = daemon === undefined ? ok(undefined) : await this.#upload(sandbox, name, daemon, signal);
|
|
737
|
+
// The run's folder, after the daemon is in place (serve runs it) and before init starts (the gate).
|
|
738
|
+
const root = this.#root(sandbox, name);
|
|
739
|
+
const mounted = uploaded.ok && archil !== undefined ? await this.#mountArchil(root, ref, archil, signal) : uploaded;
|
|
740
|
+
const checked = mounted.ok ? await this.#checkCreated(sandbox, ref, tags, recorded, signal) : mounted;
|
|
741
|
+
// A folder mounted for a computer create gives up on is let go before the terminate, never signalled.
|
|
742
|
+
const letGo = async () => {
|
|
743
|
+
if (archil !== undefined && mounted.ok)
|
|
744
|
+
await archilRelease({ root, client: undefined, timeoutMs: this.#timeouts.mountMs });
|
|
745
|
+
};
|
|
746
|
+
if (signal?.aborted) {
|
|
747
|
+
await letGo();
|
|
748
|
+
const after = await this.#terminate(sandbox, name, signal);
|
|
749
|
+
return fail("aborted", `create was aborted after Modal made the sandbox; the computer ${name} ${after}`);
|
|
750
|
+
}
|
|
751
|
+
if (checked.ok)
|
|
752
|
+
return ok(checked.value.length > 0 ? { ...ref, notes: checked.value } : ref);
|
|
753
|
+
// Read before the terminate, which would end it with its own code: whether the sandbox's command had already ended.
|
|
754
|
+
const why = await this.#endedWords(sandbox, archil?.mount.token, signal);
|
|
755
|
+
await letGo();
|
|
756
|
+
const after = await this.#terminate(sandbox, name, signal);
|
|
757
|
+
return fail(checked.error.code, `the computer ${name} ${after}: ${checked.error.message}${why}`);
|
|
758
|
+
}
|
|
759
|
+
/**
|
|
760
|
+
* When a create's sandbox has already finished, its command's exit code and the tail of its output (stdout, then
|
|
761
|
+
* stderr; the token, if any, cut), in words to append; nothing while it runs or when that cannot be read.
|
|
762
|
+
*/
|
|
763
|
+
async #endedWords(sandbox, token, signal) {
|
|
764
|
+
const { callMs } = this.#timeouts;
|
|
765
|
+
const polled = await call("poll of the sandbox", () => sandbox.poll(), callMs, signal);
|
|
766
|
+
if (!polled.ok || polled.value === null)
|
|
767
|
+
return "";
|
|
768
|
+
const read = async (stream) => {
|
|
769
|
+
if (typeof stream?.readText !== "function")
|
|
770
|
+
return "";
|
|
771
|
+
const text = await call("the sandbox's output", () => stream.readText(), callMs, signal);
|
|
772
|
+
return text.ok ? text.value : "";
|
|
773
|
+
};
|
|
774
|
+
let output = `${await read(sandbox.stdout)} ${await read(sandbox.stderr)}`.replace(/\s+/g, " ").trim();
|
|
775
|
+
if (token)
|
|
776
|
+
output = output.replaceAll(token, "[token]");
|
|
777
|
+
return `; its command exited ${polled.value}${output === "" ? ", with no output" : `: ${output.length > 500 ? `…${output.slice(-500)}` : output}`}`;
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* Streams the daemon into the sandbox through one exec's stdin, in binary mode, and checks the sha256 the upload
|
|
781
|
+
* prints against the one sent. Bounded by uploadMs as a whole: the exec's start, every write, and its exit.
|
|
782
|
+
*/
|
|
783
|
+
async #upload(sandbox, name, daemon, signal) {
|
|
784
|
+
const what = `the daemon's upload into ${name}`;
|
|
785
|
+
const { upload } = modalCommands({ sha256: daemon.sha256 });
|
|
786
|
+
const run = async () => {
|
|
787
|
+
const program = await sandbox.exec(upload, { mode: "binary" });
|
|
788
|
+
const stdout = textOf(program.stdout);
|
|
789
|
+
const stderr = textOf(program.stderr);
|
|
790
|
+
let streaming;
|
|
791
|
+
try {
|
|
792
|
+
for (let at = 0; at < daemon.bytes.length; at += UPLOAD_CHUNK)
|
|
793
|
+
await program.stdin.writeBytes(new Uint8Array(daemon.bytes.subarray(at, at + UPLOAD_CHUNK)));
|
|
794
|
+
await program.stdin.close();
|
|
795
|
+
}
|
|
796
|
+
catch (error) {
|
|
797
|
+
// The script may have stopped reading (it says why); an end of input lets cat end, and the sha256 check fail.
|
|
798
|
+
streaming = error;
|
|
799
|
+
await program.stdin.close().catch(() => { });
|
|
800
|
+
}
|
|
801
|
+
const exitCode = await program.wait();
|
|
802
|
+
return { exitCode, stdout: await stdout, stderr: await stderr, streaming };
|
|
803
|
+
};
|
|
804
|
+
const done = await call(what, run, this.#timeouts.uploadMs, signal);
|
|
805
|
+
if (!done.ok)
|
|
806
|
+
return done;
|
|
807
|
+
const { exitCode, stdout, stderr, streaming } = done.value;
|
|
808
|
+
if (exitCode !== 0)
|
|
809
|
+
return fail("refused", `the daemon's upload exited with ${exitCode}: ${`${stdout} ${stderr}`.replace(/\s+/g, " ").trim().slice(0, 500)}`);
|
|
810
|
+
if (streaming !== undefined)
|
|
811
|
+
return fail(codeOf(streaming), `${what} failed while streaming: ${words(streaming)}`);
|
|
812
|
+
const read = /^sha256 ([0-9a-f]{64})$/m.exec(stdout)?.[1];
|
|
813
|
+
if (read !== daemon.sha256) {
|
|
814
|
+
return fail("refused", `it did not match its spec: daemon: uploaded sha256 ${daemon.sha256}, the file in the computer reads back ${show(read)}`);
|
|
815
|
+
}
|
|
816
|
+
return ok(undefined);
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* The longest an Archil computer's entrypoint waits for the gate after the upload: each root step (the preflight,
|
|
820
|
+
* mount, a revoke, serve and the gate) within mountMs, and the takeover's listing and its releases.
|
|
821
|
+
*/
|
|
822
|
+
#archilMs() {
|
|
823
|
+
const { mountMs, listMs, releaseMs } = this.#timeouts;
|
|
824
|
+
return 6 * mountMs + listMs + 2 * releaseMs;
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* The root channel into a sandbox: Modal's exec, which runs as root (Modal containers always do), outside computerd.
|
|
828
|
+
* stdin, when given, is written as given and closed; otherwise stdin is closed at once. What the program printed is
|
|
829
|
+
* both streams, stdout first. An error is the SDK's, in words that never hold what stdin was given.
|
|
830
|
+
*/
|
|
831
|
+
#root(sandbox, name) {
|
|
832
|
+
return {
|
|
833
|
+
run: (argv, { stdin, timeoutMs, signal }) => call(`root's ${argv[0] === ARCHIL_HELPER ? `agentrun-archil ${argv[1]}` : argv[0]} in ${name}`, async () => {
|
|
834
|
+
const program = await sandbox.exec([...argv], { mode: "binary" });
|
|
835
|
+
const stdout = textOf(program.stdout);
|
|
836
|
+
const stderr = textOf(program.stderr);
|
|
837
|
+
try {
|
|
838
|
+
if (stdin !== undefined)
|
|
839
|
+
await program.stdin.writeBytes(new Uint8Array(Buffer.from(stdin, "utf8")));
|
|
840
|
+
}
|
|
841
|
+
finally {
|
|
842
|
+
await program.stdin.close().catch(() => { });
|
|
843
|
+
}
|
|
844
|
+
const exitCode = await program.wait();
|
|
845
|
+
return { exitCode, output: `${await stdout}${await stderr}` };
|
|
846
|
+
}, timeoutMs, signal),
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
/** The shared Archil steps (archilMount) through root, with the takeover of this provider's lower epochs; then the gate. */
|
|
850
|
+
async #mountArchil(root, computer, { mount, run, epoch }, signal) {
|
|
851
|
+
const { mountMs, callMs } = this.#timeouts;
|
|
852
|
+
const made = await archilMount({ root, mount, self: computer, releaseOlder: () => releaseOlder(this, run, epoch, signal ? { signal } : {}), timeoutMs: mountMs, ...(signal ? { signal } : {}) });
|
|
853
|
+
if (!made.ok)
|
|
854
|
+
return made;
|
|
855
|
+
const gate = await root.run(["touch", ARCHIL_GATE], { timeoutMs: callMs, ...(signal ? { signal } : {}) });
|
|
856
|
+
if (!gate.ok)
|
|
857
|
+
return fail(gate.error.code, `the gate init waits for could not be made: ${gate.error.message}`);
|
|
858
|
+
if (gate.value.exitCode !== 0)
|
|
859
|
+
return fail("refused", `the gate init waits for could not be made (exit ${gate.value.exitCode}): ${gate.value.output.trim().slice(0, 300)}`);
|
|
860
|
+
return ok(undefined);
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* What is mounted at /workspace, read from inside through computerd (its /proc/self/mounts), exclusive when the
|
|
864
|
+
* resident serve answers a sync; undefined when nothing is mounted there.
|
|
865
|
+
*/
|
|
866
|
+
#readMount(connection, name, archil, signal) {
|
|
867
|
+
return readArchilMount(connection.client, archil, { name, timeoutMs: this.#timeouts.helloMs, ...(signal ? { signal } : {}) });
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Terminates a sandbox create gives up on and waits, as release delete does, until poll reads it finished, so a
|
|
871
|
+
* refused create leaves nothing listed; and says how that went. The terminate does not take the caller's signal, so
|
|
872
|
+
* an aborted create still sends it, within callMs; the wait does, within releaseMs, so an abort ends it and the words
|
|
873
|
+
* say the sandbox may still be ending. A sandbox that lands after create gave up is given no signal.
|
|
874
|
+
*/
|
|
875
|
+
async #terminate(sandbox, name, signal) {
|
|
876
|
+
const ended = await call(`terminate of ${name}`, () => sandbox.terminate(), this.#timeouts.callMs);
|
|
877
|
+
if (!ended.ok && ended.error.code !== "not_found")
|
|
878
|
+
return `could not be terminated (${ended.error.message})`;
|
|
879
|
+
const finished = await this.#untilFinished(sandbox, name, signal);
|
|
880
|
+
return finished.ok ? "was terminated" : `was terminated, and may still be ending (${finished.error.message})`;
|
|
881
|
+
}
|
|
882
|
+
/** untilFinished on sandbox, bounded by releaseMs, its pauses from releasePollMs. */
|
|
883
|
+
#untilFinished(sandbox, name, signal) {
|
|
884
|
+
const { releaseMs, releasePollMs, callMs } = this.#timeouts;
|
|
885
|
+
return untilFinished(() => sandbox.poll(), { name, boundMs: releaseMs, callMs, minMs: Math.min(releasePollMs, RELEASE_POLL_MAX_MS), maxMs: RELEASE_POLL_MAX_MS, signal });
|
|
886
|
+
}
|
|
887
|
+
/**
|
|
888
|
+
* The drift check after create: the sandbox runs, its tags read back as given, and the daemon and probe match. Its
|
|
889
|
+
* value is the probe's notes, what it recorded that does not refuse the computer.
|
|
890
|
+
*/
|
|
891
|
+
async #checkCreated(sandbox, ref, tags, recorded, signal) {
|
|
892
|
+
const polled = await call(`poll of ${ref.name}`, () => sandbox.poll(), this.#timeouts.callMs, signal);
|
|
893
|
+
if (!polled.ok)
|
|
894
|
+
return polled;
|
|
895
|
+
if (polled.value !== null)
|
|
896
|
+
return fail("refused", `it had finished, with exit code ${polled.value}, before its drift check`);
|
|
897
|
+
const read = await call(`getTags of ${ref.id}`, () => sandbox.getTags(), this.#timeouts.callMs, signal);
|
|
898
|
+
if (!read.ok)
|
|
899
|
+
return read;
|
|
900
|
+
// Init may not be listening yet when create's answer, or the upload, comes back: the bridge is tried until hello.
|
|
901
|
+
const archil = recordedArchil(tags);
|
|
902
|
+
const inside = await this.#inside(sandbox, ref.name, signal, true, archil);
|
|
903
|
+
if (!inside.ok)
|
|
904
|
+
return inside;
|
|
905
|
+
const found = [
|
|
906
|
+
...tagDrift(tags, read.value),
|
|
907
|
+
...helloDrift(inside.value.hello, this.#expected()),
|
|
908
|
+
...probeDrift(inside.value.probe, { user: recorded.user, network: recorded.network }),
|
|
909
|
+
...(archil === undefined ? [] : mountDrift(archil.expected, inside.value.mount)),
|
|
910
|
+
];
|
|
911
|
+
return found.length === 0 ? ok(probeNotes(inside.value.probe, recorded.network)) : fail("refused", `it did not match its spec: ${found.join("; ")}`);
|
|
912
|
+
}
|
|
913
|
+
/** One connection's hello and the probe through it, and an Archil computer's mount read back, the connection closed after. */
|
|
914
|
+
async #inside(sandbox, name, signal, patient = false, archil) {
|
|
915
|
+
const opened = patient ? await this.#openWhenListening(sandbox, name, signal) : await this.#open(sandbox, name, signal);
|
|
916
|
+
if (!opened.ok)
|
|
917
|
+
return opened;
|
|
918
|
+
try {
|
|
919
|
+
const probe = await this.#probe(opened.value, name, signal);
|
|
920
|
+
if (!probe.ok)
|
|
921
|
+
return probe;
|
|
922
|
+
if (archil === undefined)
|
|
923
|
+
return ok({ hello: opened.value.hello, probe: probe.value });
|
|
924
|
+
const mount = await this.#readMount(opened.value, name, archil, signal);
|
|
925
|
+
if (!mount.ok)
|
|
926
|
+
return mount;
|
|
927
|
+
return ok({ hello: opened.value.hello, probe: probe.value, ...(mount.value === undefined ? {} : { mount: mount.value }) });
|
|
928
|
+
}
|
|
929
|
+
finally {
|
|
930
|
+
await opened.value.close();
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
/** `computerd probe` through the daemon, so it runs as the computer's own user. */
|
|
934
|
+
async #probe(connection, name, signal) {
|
|
935
|
+
const { probeMs } = this.#timeouts;
|
|
936
|
+
const bound = within(probeMs, signal);
|
|
937
|
+
const argv = [DAEMON_IN_COMPUTER, "probe", ...this.#probeTargets.flatMap((target) => ["--connect", target])];
|
|
938
|
+
const ran = await connection.client.call("exec.run", { argv, timeoutMs: probeMs }, { signal: bound.signal });
|
|
939
|
+
bound.clear();
|
|
940
|
+
if (!ran.ok) {
|
|
941
|
+
if (signal?.aborted)
|
|
942
|
+
return fail("aborted", `the probe in ${name} was aborted`);
|
|
943
|
+
if (ran.error.code === "aborted")
|
|
944
|
+
return fail("timeout", `the probe in ${name} did not answer within ${seconds(probeMs)}`);
|
|
945
|
+
return fail(ran.error.code, `the probe in ${name} failed: ${ran.error.message}`);
|
|
946
|
+
}
|
|
947
|
+
const { exitCode, stdout, stderr, timedOut } = ran.value;
|
|
948
|
+
if (timedOut)
|
|
949
|
+
return fail("timeout", `the probe in ${name} did not end within ${seconds(probeMs)}`);
|
|
950
|
+
if (exitCode !== 0) {
|
|
951
|
+
return fail("refused", `the probe in ${name} exited with ${exitCode}: ${Buffer.from(stderr, "base64").toString("utf8").trim().slice(0, 300)}`);
|
|
952
|
+
}
|
|
953
|
+
const report = probeReportOf(stdout);
|
|
954
|
+
if ("not" in report)
|
|
955
|
+
return fail("refused", `the probe in ${name} ${report.not}`);
|
|
956
|
+
return ok(report);
|
|
957
|
+
}
|
|
958
|
+
/** The app, looked up (and made when missing) once per provider; a failed lookup is tried again next time. */
|
|
959
|
+
async #theApp(signal) {
|
|
960
|
+
if (this.#app)
|
|
961
|
+
return ok(this.#app);
|
|
962
|
+
const found = await call(`apps.fromName ${this.#appName}`, () => this.#sdk.apps.fromName(this.#appName, { createIfMissing: true }), this.#timeouts.callMs, signal);
|
|
963
|
+
if (found.ok)
|
|
964
|
+
this.#app = found.value;
|
|
965
|
+
return found;
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* Settings' test: the provider's app read without making it (createIfMissing false), which makes nothing. An app not
|
|
969
|
+
* made yet is a connection all the same: the token was taken, and the first computer makes the app.
|
|
970
|
+
*/
|
|
971
|
+
async testConnection({ signal } = {}) {
|
|
972
|
+
const found = await call(`apps.fromName ${this.#appName}`, () => this.#sdk.apps.fromName(this.#appName, { createIfMissing: false }), this.#timeouts.callMs, signal);
|
|
973
|
+
if (found.ok)
|
|
974
|
+
return ok({ detail: `Modal answered: the app ${this.#appName} is there` });
|
|
975
|
+
if (found.error.code === "not_found")
|
|
976
|
+
return ok({ detail: `Modal answered: no app ${this.#appName} yet; the first computer makes it` });
|
|
977
|
+
const error = connectionError(found.error);
|
|
978
|
+
return fail(error.code, error.message);
|
|
979
|
+
}
|
|
980
|
+
/** The sandbox with an id and the tags it carries; one Modal does not know is not_found. */
|
|
981
|
+
async #find(id, signal) {
|
|
982
|
+
const sandbox = await call("sandboxes.fromId", () => this.#sdk.sandboxes.fromId(id), this.#timeouts.callMs, signal);
|
|
983
|
+
if (!sandbox.ok)
|
|
984
|
+
return sandbox;
|
|
985
|
+
const tags = await call(`getTags of ${id}`, () => sandbox.value.getTags(), this.#timeouts.callMs, signal);
|
|
986
|
+
if (!tags.ok)
|
|
987
|
+
return tags.error.code === "not_found" ? fail("not_found", `no Modal computer has the id ${id}`) : tags;
|
|
988
|
+
return ok({ sandbox: sandbox.value, tags: tags.value });
|
|
989
|
+
}
|
|
990
|
+
/** This provider's sandbox for ref, or why not. */
|
|
991
|
+
async #own(ref, signal) {
|
|
992
|
+
const found = await this.#find(ref.id, signal);
|
|
993
|
+
if (!found.ok)
|
|
994
|
+
return found;
|
|
995
|
+
if (!ours(found.value.tags, ref.name))
|
|
996
|
+
return fail("not_found", `no Modal computer named ${ref.name} has the id ${ref.id}`);
|
|
997
|
+
return found;
|
|
998
|
+
}
|
|
999
|
+
/** The live view: screen.watch on a connection of the watch's own (daemonWatch); a sandbox has no screen. */
|
|
1000
|
+
watch(ref, handlers, options) {
|
|
1001
|
+
return daemonWatch(this, ref, handlers, options);
|
|
1002
|
+
}
|
|
1003
|
+
async connect(ref) {
|
|
1004
|
+
const problem = refProblem(ref);
|
|
1005
|
+
if (problem)
|
|
1006
|
+
return fail("invalid", problem);
|
|
1007
|
+
const found = await this.#own(ref);
|
|
1008
|
+
if (!found.ok)
|
|
1009
|
+
return found;
|
|
1010
|
+
const root = rootRecorded(found.value.tags, ref.name);
|
|
1011
|
+
if (root)
|
|
1012
|
+
return root;
|
|
1013
|
+
const opened = await this.#open(found.value.sandbox, ref.name);
|
|
1014
|
+
if (!opened.ok)
|
|
1015
|
+
return opened;
|
|
1016
|
+
const drift = helloDrift(opened.value.hello, this.#expected());
|
|
1017
|
+
// An Archil computer's client syncs the run's folder after every call that may change it, before it answers.
|
|
1018
|
+
if (drift.length === 0)
|
|
1019
|
+
return recordedArchil(found.value.tags) === undefined ? opened : ok({ ...opened.value, client: syncingClient(opened.value.client) });
|
|
1020
|
+
await opened.value.close();
|
|
1021
|
+
return fail("refused", `the daemon in ${ref.name} does not match this provider: ${drift.join("; ")}`);
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* #open, tried again while the bridge finds no daemon listening, until hello or helloMs in all. For a computer just
|
|
1025
|
+
* made, whose init may not have made its socket yet.
|
|
1026
|
+
*/
|
|
1027
|
+
async #openWhenListening(sandbox, name, signal) {
|
|
1028
|
+
const until = Date.now() + this.#timeouts.helloMs;
|
|
1029
|
+
for (;;) {
|
|
1030
|
+
const opened = await this.#open(sandbox, name, signal, until);
|
|
1031
|
+
if (opened.ok || !opened.notListening || signal?.aborted || Date.now() + LISTEN_RETRY_MS >= until)
|
|
1032
|
+
return opened;
|
|
1033
|
+
await pause(LISTEN_RETRY_MS, signal);
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* One connection to the computer's daemon over `computerd stdio` through exec, after hello, unchecked. One deadline,
|
|
1038
|
+
* until (helloMs from now by default), bounds the exec's start and hello together: the start takes at most callMs of
|
|
1039
|
+
* it and hello what is left. Modal's exec goes on when the start is given up on (a timeout or the caller's abort), so
|
|
1040
|
+
* a bridge that lands after that has its stdin closed as it lands, and ends, as a late sandbox create is terminated.
|
|
1041
|
+
*/
|
|
1042
|
+
async #open(sandbox, name, signal, until = Date.now() + this.#timeouts.helloMs) {
|
|
1043
|
+
const what = `exec of the daemon's stdio bridge in ${name}`;
|
|
1044
|
+
const { helloMs: totalMs, callMs } = this.#timeouts;
|
|
1045
|
+
if (signal?.aborted)
|
|
1046
|
+
return fail("aborted", `${what} was aborted before it was called`);
|
|
1047
|
+
let starting;
|
|
1048
|
+
try {
|
|
1049
|
+
starting = Promise.resolve(sandbox.exec([DAEMON_IN_COMPUTER, "stdio"], { mode: "binary" }));
|
|
1050
|
+
}
|
|
1051
|
+
catch (error) {
|
|
1052
|
+
return fail(codeOf(error), `${what} failed: ${words(error)}`);
|
|
1053
|
+
}
|
|
1054
|
+
const startMs = Math.max(1, Math.min(callMs, until - Date.now()));
|
|
1055
|
+
const started = await race(starting, what, startMs, signal);
|
|
1056
|
+
if (!started.ok) {
|
|
1057
|
+
if (started.error.code === "timeout" || started.error.code === "aborted") {
|
|
1058
|
+
starting.then((late) => late.stdin.close()).catch(() => { });
|
|
1059
|
+
if (started.error.code === "timeout" && startMs < callMs) {
|
|
1060
|
+
return fail("timeout", `the daemon in ${name} did not answer hello within ${seconds(totalMs)}: the exec of its stdio bridge had not started; a bridge that starts after this is closed`);
|
|
1061
|
+
}
|
|
1062
|
+
return fail(started.error.code, `${started.error.message}; a bridge that starts after this is closed`);
|
|
1063
|
+
}
|
|
1064
|
+
return started;
|
|
1065
|
+
}
|
|
1066
|
+
const program = started.value;
|
|
1067
|
+
let stderr = "";
|
|
1068
|
+
const stderrRead = (async () => {
|
|
1069
|
+
for await (const chunk of program.stderr)
|
|
1070
|
+
stderr = (stderr + Buffer.from(chunk).toString("utf8")).slice(-4096);
|
|
1071
|
+
})().catch(() => { });
|
|
1072
|
+
const readable = Readable.from(buffers(program.stdout), { objectMode: false });
|
|
1073
|
+
const writable = new Writable({
|
|
1074
|
+
write(chunk, _encoding, done) {
|
|
1075
|
+
program.stdin.writeBytes(new Uint8Array(chunk)).then(() => done(), done);
|
|
1076
|
+
},
|
|
1077
|
+
final(done) {
|
|
1078
|
+
program.stdin.close().then(() => done(), done);
|
|
1079
|
+
},
|
|
1080
|
+
});
|
|
1081
|
+
const client = new DaemonClient({ readable, writable });
|
|
1082
|
+
let closing;
|
|
1083
|
+
// Modal has no kill for an exec: the bridge ends when its stdin does, which close gives it.
|
|
1084
|
+
const close = () => (closing ??= (async () => {
|
|
1085
|
+
client.close();
|
|
1086
|
+
await race(program.wait(), "the stdio bridge's exit", CLOSE_WAIT_MS);
|
|
1087
|
+
})());
|
|
1088
|
+
const bound = within(Math.max(1, until - Date.now()), signal);
|
|
1089
|
+
const hello = await client.call("hello", { client: `@parcha/agentrun-computer ${VERSION}` }, { signal: bound.signal });
|
|
1090
|
+
bound.clear();
|
|
1091
|
+
if (!hello.ok) {
|
|
1092
|
+
if (hello.error.code === "gone")
|
|
1093
|
+
await race(stderrRead, "the stdio bridge's stderr", 1000);
|
|
1094
|
+
await close();
|
|
1095
|
+
if (signal?.aborted)
|
|
1096
|
+
return fail("aborted", `hello to the daemon in ${name} was aborted`);
|
|
1097
|
+
if (hello.error.code === "aborted")
|
|
1098
|
+
return fail("timeout", `the daemon in ${name} did not answer hello within ${seconds(totalMs)}`);
|
|
1099
|
+
if (hello.error.code !== "gone")
|
|
1100
|
+
return hello;
|
|
1101
|
+
return { ...fail("modal", `cannot reach the daemon in ${name}: ${stderr.trim() || hello.error.message}`), notListening: true };
|
|
1102
|
+
}
|
|
1103
|
+
return ok({ client, hello: hello.value, close });
|
|
1104
|
+
}
|
|
1105
|
+
async attach(ref, { signal } = {}) {
|
|
1106
|
+
const given = (typeof ref === "object" && ref !== null ? ref : {});
|
|
1107
|
+
if ((given.id === undefined) === (given.labels === undefined))
|
|
1108
|
+
return fail("invalid", "attach takes { id } or { labels }, one of them");
|
|
1109
|
+
if (given.id !== undefined) {
|
|
1110
|
+
const id = given.id;
|
|
1111
|
+
if (typeof id !== "string" || !SANDBOX_ID.test(id))
|
|
1112
|
+
return fail("invalid", `${String(id)} is not a Modal sandbox id`);
|
|
1113
|
+
const found = await this.#find(id, signal);
|
|
1114
|
+
if (!found.ok)
|
|
1115
|
+
return found;
|
|
1116
|
+
if (!ours(found.value.tags))
|
|
1117
|
+
return fail("not_found", `no Modal computer has the id ${id}`);
|
|
1118
|
+
return this.#attached(found.value.sandbox, found.value.tags, signal);
|
|
1119
|
+
}
|
|
1120
|
+
const problem = filterProblem(given.labels);
|
|
1121
|
+
if (problem)
|
|
1122
|
+
return fail("invalid", problem);
|
|
1123
|
+
const labels = given.labels;
|
|
1124
|
+
if (Object.keys(labels).length === 0)
|
|
1125
|
+
return fail("invalid", "attach by labels needs at least one label");
|
|
1126
|
+
const listed = await this.list(labels, { signal });
|
|
1127
|
+
if (!listed.ok)
|
|
1128
|
+
return listed;
|
|
1129
|
+
const words = JSON.stringify(labels);
|
|
1130
|
+
if (listed.value.length === 0)
|
|
1131
|
+
return fail("not_found", `no Modal computer has the labels ${words}`);
|
|
1132
|
+
if (listed.value.length > 1)
|
|
1133
|
+
return fail("invalid", `${listed.value.length} computers match the labels ${words}: ${listed.value.map((info) => info.ref.name).join(", ")}`);
|
|
1134
|
+
const match = listed.value[0].ref;
|
|
1135
|
+
const found = await this.#own(match, signal);
|
|
1136
|
+
if (!found.ok)
|
|
1137
|
+
return found;
|
|
1138
|
+
return this.#attached(found.value.sandbox, found.value.tags, signal);
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* The drift check of a computer attach did not make: the spec create recorded in its tags, held to what check()
|
|
1142
|
+
* allows, then hello and the probe, as at create. Modal reads back none of the spec, so the user, runtime and network
|
|
1143
|
+
* none are what the probe reports from inside; image and sizes are as recorded. A drifted computer is left running.
|
|
1144
|
+
*/
|
|
1145
|
+
async #attached(sandbox, tags, signal) {
|
|
1146
|
+
const name = tags[NAME_TAG];
|
|
1147
|
+
const ref = { id: sandbox.sandboxId, name };
|
|
1148
|
+
const polled = await call(`poll of ${name}`, () => sandbox.poll(), this.#timeouts.callMs, signal);
|
|
1149
|
+
if (!polled.ok)
|
|
1150
|
+
return polled;
|
|
1151
|
+
if (polled.value !== null)
|
|
1152
|
+
return fail("not_found", `the Modal computer ${name} has finished, with exit code ${polled.value}`);
|
|
1153
|
+
const found = [];
|
|
1154
|
+
const deadline = deadlineOf(tags);
|
|
1155
|
+
if (deadline === undefined)
|
|
1156
|
+
found.push(`deadline: the tag ${DEADLINE_LABEL} reads ${show(tags[DEADLINE_LABEL])}, not the ISO time create writes`);
|
|
1157
|
+
else if (deadline.getTime() > Date.now() + MAX_LIFETIME_MS + 60_000)
|
|
1158
|
+
found.push(`deadline: ${deadline.toISOString()} is past the 24 hours Modal allows`);
|
|
1159
|
+
const recorded = recordedOf(tags);
|
|
1160
|
+
if (typeof recorded === "string")
|
|
1161
|
+
found.push(recorded);
|
|
1162
|
+
else {
|
|
1163
|
+
if (recorded.runtime !== "vm")
|
|
1164
|
+
found.push(`runtime: the tag ${SPEC_TAG} says ${show(recorded.runtime)}; this provider makes vm computers`);
|
|
1165
|
+
const { image, network, cpus, memoryMb, workdir, user } = recorded;
|
|
1166
|
+
const refusals = this.check({ image, lifetimeMs: 1, network, cpus, memoryMb, workdir, user });
|
|
1167
|
+
found.push(...refusals.map(({ field, message }) => `${field}: ${message}, as recorded at create`));
|
|
1168
|
+
// No exec in a computer whose user is root: the bridge would run what that user could have replaced.
|
|
1169
|
+
if (isRootUser(user))
|
|
1170
|
+
return fail("refused", `the computer ${name} does not match this provider, so attach refuses it and it is left as it is: ${found.join("; ")}`);
|
|
1171
|
+
}
|
|
1172
|
+
const archil = recordedArchil(tags);
|
|
1173
|
+
const inside = await this.#inside(sandbox, name, signal, false, archil);
|
|
1174
|
+
if (!inside.ok)
|
|
1175
|
+
return inside;
|
|
1176
|
+
const { hello, probe, mount } = inside.value;
|
|
1177
|
+
found.push(...helloDrift(hello, this.#expected()));
|
|
1178
|
+
if (typeof recorded !== "string")
|
|
1179
|
+
found.push(...probeDrift(probe, { user: recorded.user, network: recorded.network }));
|
|
1180
|
+
// The mount read back from inside is the one the spec tag records, under the computer's epoch label.
|
|
1181
|
+
if (archil !== undefined)
|
|
1182
|
+
found.push(...mountDrift(archil.expected, mount));
|
|
1183
|
+
if (found.length > 0 || typeof recorded === "string" || deadline === undefined) {
|
|
1184
|
+
return fail("refused", `the computer ${name} does not match this provider, so attach refuses it and it is left as it is: ${found.join("; ")}`);
|
|
1185
|
+
}
|
|
1186
|
+
const { image, network, cpus, memoryMb, workdir } = recorded;
|
|
1187
|
+
const notes = probeNotes(probe, network);
|
|
1188
|
+
return ok({
|
|
1189
|
+
...ref,
|
|
1190
|
+
spec: { image, user: `${probe.uid}:${probe.gid}`, network, cpus, memoryMb, workdir, deadline, kind: hello.kind, ...(archil === undefined || mount === undefined ? {} : { mount }) },
|
|
1191
|
+
...(notes.length > 0 ? { notes } : {}),
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
/**
|
|
1195
|
+
* Every running computer this provider made that carries all of these labels. Modal's list asks for running sandboxes
|
|
1196
|
+
* only (includeFinished: false, sandbox.ts:1135-1140), yet a sandbox terminated a moment ago is still listed: each one
|
|
1197
|
+
* listed is polled, and one that poll reads finished (an exit code, not null, sandbox.ts:2761-2771) or no longer
|
|
1198
|
+
* finds is left out.
|
|
1199
|
+
*/
|
|
1200
|
+
async list(labels, { signal } = {}) {
|
|
1201
|
+
const problem = filterProblem(labels);
|
|
1202
|
+
if (problem)
|
|
1203
|
+
return fail("invalid", problem);
|
|
1204
|
+
const until = Date.now() + this.#timeouts.listMs;
|
|
1205
|
+
const left = () => Math.max(1, until - Date.now());
|
|
1206
|
+
const app = await this.#theApp(signal);
|
|
1207
|
+
if (!app.ok)
|
|
1208
|
+
return app;
|
|
1209
|
+
let iterator;
|
|
1210
|
+
try {
|
|
1211
|
+
iterator = this.#sdk.sandboxes.list({ appId: app.value.appId, tags: { ...labels, [COMPUTER_LABEL]: "1" } })[Symbol.asyncIterator]();
|
|
1212
|
+
}
|
|
1213
|
+
catch (error) {
|
|
1214
|
+
return fail(codeOf(error), `sandboxes.list failed: ${words(error)}`);
|
|
1215
|
+
}
|
|
1216
|
+
const infos = [];
|
|
1217
|
+
const stop = (result) => {
|
|
1218
|
+
Promise.resolve(iterator.return?.()).catch(() => { });
|
|
1219
|
+
return result;
|
|
1220
|
+
};
|
|
1221
|
+
for (;;) {
|
|
1222
|
+
const next = await race(iterator.next(), "sandboxes.list", left(), signal);
|
|
1223
|
+
if (!next.ok)
|
|
1224
|
+
return stop(next);
|
|
1225
|
+
if (next.value.done)
|
|
1226
|
+
break;
|
|
1227
|
+
const sandbox = next.value.value;
|
|
1228
|
+
const tags = await call(`getTags of ${sandbox.sandboxId}`, () => sandbox.getTags(), Math.min(this.#timeouts.callMs, left()), signal);
|
|
1229
|
+
if (!tags.ok) {
|
|
1230
|
+
// A sandbox that finished between the list and its tags is left out.
|
|
1231
|
+
if (tags.error.code === "not_found")
|
|
1232
|
+
continue;
|
|
1233
|
+
return stop(tags);
|
|
1234
|
+
}
|
|
1235
|
+
if (!ours(tags.value) || !Object.entries(labels).every(([key, value]) => tags.value[key] === value))
|
|
1236
|
+
continue;
|
|
1237
|
+
const polled = await call(`poll of ${sandbox.sandboxId}`, () => sandbox.poll(), Math.min(this.#timeouts.callMs, left()), signal);
|
|
1238
|
+
if (!polled.ok) {
|
|
1239
|
+
if (polled.error.code === "not_found")
|
|
1240
|
+
continue;
|
|
1241
|
+
return stop(polled);
|
|
1242
|
+
}
|
|
1243
|
+
if (polled.value !== null)
|
|
1244
|
+
continue;
|
|
1245
|
+
// list execs into no computer: an Archil computer's mount is the one its spec tag records, under its epoch label.
|
|
1246
|
+
const archil = recordedArchil(tags.value);
|
|
1247
|
+
infos.push({
|
|
1248
|
+
ref: { id: sandbox.sandboxId, name: tags.value[NAME_TAG] },
|
|
1249
|
+
labels: { ...tags.value },
|
|
1250
|
+
deadline: deadlineOf(tags.value),
|
|
1251
|
+
state: "running",
|
|
1252
|
+
network: recordedNetwork(tags.value),
|
|
1253
|
+
...(archil === undefined ? {} : { mount: archil.expected }),
|
|
1254
|
+
});
|
|
1255
|
+
}
|
|
1256
|
+
return ok(infos);
|
|
1257
|
+
}
|
|
1258
|
+
/**
|
|
1259
|
+
* Modal reads no policy back. Open is open, nothing being wider; none is read back by the probe from inside, and is
|
|
1260
|
+
* another network in words when any of its addresses answered (an address that only accepted, and sent nothing back,
|
|
1261
|
+
* leaves it none). A change is refused: it is fixed at create.
|
|
1262
|
+
*/
|
|
1263
|
+
async network(ref, policy, { signal } = {}) {
|
|
1264
|
+
const problem = refProblem(ref);
|
|
1265
|
+
if (problem)
|
|
1266
|
+
return fail("invalid", problem);
|
|
1267
|
+
if (policy !== undefined && policy !== "none") {
|
|
1268
|
+
const wider = policy === "open" || (typeof policy === "object" && policy !== null && "allow" in policy);
|
|
1269
|
+
return fail("refused", wider ? `${OWN_NETWORK_ONLY}; ${FIXED}` : `${FIXED}; a network is "none"`);
|
|
1270
|
+
}
|
|
1271
|
+
const found = await this.#own(ref, signal);
|
|
1272
|
+
if (!found.ok)
|
|
1273
|
+
return found;
|
|
1274
|
+
const recorded = recordedNetwork(found.value.tags);
|
|
1275
|
+
if (typeof recorded !== "string")
|
|
1276
|
+
return fail("refused", `the computer ${ref.name}: ${"other" in recorded ? recorded.other : JSON.stringify(recorded)}`);
|
|
1277
|
+
if (policy !== undefined && policy !== recorded)
|
|
1278
|
+
return fail("refused", `${FIXED}: ${ref.name} was created with network ${recorded}, not ${policy}`);
|
|
1279
|
+
let read = recorded;
|
|
1280
|
+
if (recorded === "none") {
|
|
1281
|
+
const root = rootRecorded(found.value.tags, ref.name);
|
|
1282
|
+
if (root)
|
|
1283
|
+
return root;
|
|
1284
|
+
const inside = await this.#inside(found.value.sandbox, ref.name, signal);
|
|
1285
|
+
if (!inside.ok)
|
|
1286
|
+
return inside;
|
|
1287
|
+
const { reached } = inside.value.probe;
|
|
1288
|
+
if (reached.length > 0)
|
|
1289
|
+
read = { other: `created with network none, yet from inside an answer came back from ${reached.join(", ")}` };
|
|
1290
|
+
}
|
|
1291
|
+
if (policy === undefined || policy === read)
|
|
1292
|
+
return ok(read);
|
|
1293
|
+
return fail("refused", `${ref.name} was asked to keep network ${policy}, and reads back: ${typeof read === "string" ? read : JSON.stringify(read)}`);
|
|
1294
|
+
}
|
|
1295
|
+
/**
|
|
1296
|
+
* delete terminates, and is idempotent: a sandbox already finished, or one Modal no longer knows, is ok. Modal ends a
|
|
1297
|
+
* sandbox asynchronously (terminate returns before it has finished unless asked to wait, sandbox.ts:1292-1296 and
|
|
1298
|
+
* 2238-2251), so delete then polls through untilFinished, as a refusing create does, with pauses that double from
|
|
1299
|
+
* releasePollMs to 5 s, until poll reads an exit code (null while it runs, sandbox.ts:2761-2771) or Modal no longer
|
|
1300
|
+
* knows it, within releaseMs and the caller's signal. Past releaseMs it is a timeout that says what poll last read,
|
|
1301
|
+
* never done. An Archil computer that still runs lets go of the run's folder first (archilRelease: the final sync
|
|
1302
|
+
* through computerd, then checkin as root); the terminate runs whatever that answers. A folder not let go cleanly
|
|
1303
|
+
* loses nothing (every call that changed it synced, and the next claim revokes the hold), so it is said through
|
|
1304
|
+
* onNote, and the release succeeds once the sandbox is gone.
|
|
1305
|
+
*/
|
|
1306
|
+
async release(ref, how, { signal } = {}) {
|
|
1307
|
+
const problem = refProblem(ref);
|
|
1308
|
+
if (problem)
|
|
1309
|
+
return fail("invalid", problem);
|
|
1310
|
+
if (how !== "stop" && how !== "delete")
|
|
1311
|
+
return fail("invalid", `release is "stop" or "delete", not ${String(how)}`);
|
|
1312
|
+
if (how === "stop")
|
|
1313
|
+
return fail("unsupported", STOP);
|
|
1314
|
+
const found = await this.#find(ref.id, signal);
|
|
1315
|
+
if (!found.ok)
|
|
1316
|
+
return found.error.code === "not_found" ? ok(undefined) : found;
|
|
1317
|
+
if (!ours(found.value.tags, ref.name))
|
|
1318
|
+
return fail("not_found", `no Modal computer named ${ref.name} has the id ${ref.id}`);
|
|
1319
|
+
const { sandbox, tags } = found.value;
|
|
1320
|
+
const letGo = recordedArchil(tags) === undefined ? ok(undefined) : await this.#letGo(sandbox, ref.name, signal);
|
|
1321
|
+
const deleted = await this.#delete(sandbox, ref, signal);
|
|
1322
|
+
if (letGo.ok)
|
|
1323
|
+
return deleted;
|
|
1324
|
+
if (!deleted.ok)
|
|
1325
|
+
return fail(deleted.error.code, `${deleted.error.message}; and ${letGo.error.message}`);
|
|
1326
|
+
this.#onNote?.({ computer: ref.name, note: `${ref.name} was terminated, and ${letGo.error.message}` });
|
|
1327
|
+
return deleted;
|
|
1328
|
+
}
|
|
1329
|
+
/** An Archil computer's folder let go, when the sandbox still runs: there is nothing to let go in one that finished. */
|
|
1330
|
+
async #letGo(sandbox, name, signal) {
|
|
1331
|
+
const polled = await call(`poll of ${name}`, () => sandbox.poll(), this.#timeouts.callMs, signal);
|
|
1332
|
+
if ((polled.ok && polled.value !== null) || (!polled.ok && polled.error.code === "not_found"))
|
|
1333
|
+
return ok(undefined);
|
|
1334
|
+
const opened = await this.#open(sandbox, name, signal);
|
|
1335
|
+
try {
|
|
1336
|
+
return await archilRelease({ root: this.#root(sandbox, name), client: opened.ok ? opened.value.client : undefined, timeoutMs: this.#timeouts.mountMs, ...(signal ? { signal } : {}) });
|
|
1337
|
+
}
|
|
1338
|
+
finally {
|
|
1339
|
+
if (opened.ok)
|
|
1340
|
+
await opened.value.close();
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
/** release delete's terminate and its wait for the end: see release. */
|
|
1344
|
+
async #delete(sandbox, ref, signal) {
|
|
1345
|
+
const ended = await call(`terminate of ${ref.name}`, () => sandbox.terminate(), this.#timeouts.callMs, signal);
|
|
1346
|
+
if (!ended.ok && ended.error.code === "not_found")
|
|
1347
|
+
return ok(undefined);
|
|
1348
|
+
if (!ended.ok && (ended.error.code === "timeout" || ended.error.code === "aborted"))
|
|
1349
|
+
return ended;
|
|
1350
|
+
if (!ended.ok) {
|
|
1351
|
+
const polled = await call(`poll of ${ref.name}`, () => sandbox.poll(), this.#timeouts.callMs, signal);
|
|
1352
|
+
return polled.ok && polled.value !== null ? ok(undefined) : ended;
|
|
1353
|
+
}
|
|
1354
|
+
const finished = await this.#untilFinished(sandbox, ref.name, signal);
|
|
1355
|
+
if (finished.ok)
|
|
1356
|
+
return ok(undefined);
|
|
1357
|
+
return fail(finished.error.code, `release delete of ${ref.name} is not done: ${finished.error.message}`);
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
/** A refusal for a computer whose spec tag records a root user, before any exec in it (see ROOT); else undefined. */
|
|
1361
|
+
function rootRecorded(tags, name) {
|
|
1362
|
+
const recorded = recordedOf(tags);
|
|
1363
|
+
if (typeof recorded === "string" || !isRootUser(recorded.user))
|
|
1364
|
+
return undefined;
|
|
1365
|
+
return fail("refused", `the computer ${name} was made with user ${recorded.user}, so this provider runs nothing in it: ${ROOT}`);
|
|
1366
|
+
}
|
|
1367
|
+
/** Why ref is not a Modal computer's ref, or undefined. */
|
|
1368
|
+
function refProblem(ref) {
|
|
1369
|
+
if (typeof ref?.name !== "string" || !NAME.test(ref.name))
|
|
1370
|
+
return `${String(ref?.name)} is not the name of a Modal computer (computer-<12 hex digits>)`;
|
|
1371
|
+
if (typeof ref.id !== "string" || !SANDBOX_ID.test(ref.id))
|
|
1372
|
+
return `${String(ref.id)} is not a Modal sandbox id`;
|
|
1373
|
+
return undefined;
|
|
1374
|
+
}
|