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