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