@parcha/agentrun-computer 0.1.0-beta.37 → 0.1.0-beta.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +341 -260
- package/box/Dockerfile +18 -1
- package/box/README.md +14 -0
- package/box/build-daytona.py +2 -2
- package/box/build-e2b.mjs +41 -18
- package/box/recipe.d.mts +5 -0
- package/box/recipe.mjs +43 -0
- package/dist/agent37.d.ts +18 -66
- package/dist/agent37.js +187 -464
- package/dist/box-image.d.ts +14 -0
- package/dist/box-image.js +24 -0
- package/dist/browserbase.d.ts +0 -6
- package/dist/browserbase.js +1 -5
- package/dist/client.d.ts +12 -3
- package/dist/client.js +39 -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 +9 -4
- package/dist/conformance/agent37.js +23 -11
- package/dist/conformance/browserbase.js +3 -3
- package/dist/conformance/cases/apps.d.ts +6 -0
- package/dist/conformance/cases/apps.js +18 -5
- package/dist/conformance/cases/isolation.d.ts +22 -5
- package/dist/conformance/cases/isolation.js +97 -16
- package/dist/conformance/cases/mount.js +5 -3
- package/dist/conformance/cases/provider.js +41 -0
- package/dist/conformance/cli.js +72 -11
- package/dist/conformance/daytona.d.ts +9 -20
- package/dist/conformance/daytona.js +12 -21
- package/dist/conformance/e2b.js +9 -4
- package/dist/conformance/exec-stream.d.ts +52 -0
- package/dist/conformance/exec-stream.js +493 -0
- package/dist/conformance/kernel.js +2 -2
- package/dist/conformance/modal.js +1 -1
- package/dist/conformance/orgo.js +2 -2
- package/dist/conformance/sweep.js +8 -8
- package/dist/conformance/types.d.ts +2 -2
- package/dist/create-requests.d.ts +1 -1
- package/dist/daytona.d.ts +17 -133
- package/dist/daytona.js +396 -1452
- package/dist/descriptor.d.ts +11 -4
- package/dist/descriptor.js +7 -0
- package/dist/descriptors/agent37.d.ts +3 -11
- package/dist/descriptors/agent37.js +9 -10
- package/dist/descriptors/daytona.d.ts +7 -6
- package/dist/descriptors/daytona.js +14 -7
- package/dist/descriptors/docker.d.ts +13 -1
- package/dist/descriptors/docker.js +3 -1
- package/dist/descriptors/e2b.d.ts +2 -9
- package/dist/descriptors/e2b.js +8 -8
- package/dist/descriptors/index.d.ts +25 -24
- package/dist/descriptors/index.js +1 -3
- package/dist/descriptors/modal.d.ts +2 -6
- package/dist/descriptors/modal.js +8 -6
- package/dist/descriptors/orgo.js +2 -1
- 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/egress-main.js +23 -15
- package/dist/docker/egress.d.ts +6 -4
- package/dist/docker/egress.js +24 -16
- package/dist/docker/inspect.d.ts +2 -2
- package/dist/docker/inspect.js +5 -5
- package/dist/docker.d.ts +6 -11
- package/dist/docker.js +13 -16
- package/dist/drift.js +4 -4
- package/dist/e2b.d.ts +22 -130
- package/dist/e2b.js +163 -243
- package/dist/host.d.ts +136 -104
- package/dist/host.js +8 -1
- package/dist/hosted/network.d.ts +23 -0
- package/dist/hosted/network.js +77 -0
- package/dist/hosted/process.d.ts +24 -8
- package/dist/hosted/process.js +80 -44
- package/dist/hosted/provider.d.ts +38 -22
- package/dist/hosted/provider.js +500 -341
- package/dist/hosted/rest.d.ts +74 -0
- package/dist/hosted/rest.js +126 -0
- package/dist/hosted/scripts.d.ts +21 -3
- package/dist/hosted/scripts.js +76 -14
- package/dist/hosted/ssh-exec.d.ts +99 -0
- package/dist/hosted/ssh-exec.js +464 -0
- package/dist/hosted/values.d.ts +26 -0
- package/dist/hosted/values.js +63 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/isolation.d.ts +0 -2
- package/dist/isolation.js +3 -4
- package/dist/kernel.d.ts +0 -6
- package/dist/kernel.js +1 -5
- package/dist/kinds.d.ts +3 -1
- package/dist/local-chrome.d.ts +0 -6
- package/dist/local-chrome.js +1 -5
- package/dist/modal.d.ts +15 -86
- package/dist/modal.js +67 -185
- package/dist/mount-archil.d.ts +13 -8
- package/dist/mount-archil.js +27 -17
- package/dist/mount.d.ts +10 -4
- package/dist/mount.js +8 -4
- package/dist/orgo.d.ts +0 -9
- package/dist/orgo.js +8 -13
- package/dist/phone-harness.d.ts +0 -6
- package/dist/phone-harness.js +0 -4
- package/dist/protocol.d.ts +4 -1
- package/dist/protocol.js +1 -0
- package/dist/provider.d.ts +2 -2
- package/dist/providers.d.ts +15 -13
- package/dist/screen-watch.js +34 -6
- package/dist/surface/api.d.ts +14 -11
- package/dist/surface/core.d.ts +23 -5
- package/dist/surface/core.js +105 -15
- package/dist/surface/index.d.ts +1 -1
- package/dist/surface/index.js +1 -1
- package/dist/surface/outline.d.ts +2 -0
- package/dist/surface/outline.js +2 -1
- package/dist/surface/script.d.ts +4 -0
- package/dist/surface/script.js +11 -3
- package/dist/ui-engine.js +19 -3
- package/package.json +2 -3
- package/box/build-agent37.mjs +0 -177
- package/dist/conformance/daytona-sweep.d.ts +0 -18
- package/dist/conformance/daytona-sweep.js +0 -126
package/dist/agent37.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// The Agent37 host: Agent37 Cloud instances (kind linux, or kind desktop on our box template, agentrun-box
|
|
1
|
+
// The Agent37 host: Agent37 Cloud instances (kind linux, or kind desktop on our box template, agentrun-box-<hash>, whose Xvfb
|
|
2
2
|
// the adapter starts through the daemon), each a whole VM by default (type "vm"), or a gVisor sandbox
|
|
3
3
|
// (type "default"). The control plane is Agent37's REST API over fetch (https://api.agent37.com/v1, a Bearer key);
|
|
4
4
|
// every command (the daemon's upload, its install, init's start, the stdio bridge) goes over SSH, as root, through the
|
|
@@ -8,15 +8,18 @@
|
|
|
8
8
|
// and the instance's sshd then takes the workspace's registered SSH key. Agent37's REST exec is one-shot (no stdin,
|
|
9
9
|
// output only at its end), so it is not used. The rest of the computer is the shared machine-host adapter's
|
|
10
10
|
// (./hosted/provider.ts). Every vendor fact here is cited in the README's Agent37 section.
|
|
11
|
-
import { createHash
|
|
12
|
-
import { Duplex
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { Duplex } from "node:stream";
|
|
13
|
+
import { boxImageRef, boxRecipeHash } from "./box-image.js";
|
|
13
14
|
import { AGENT37, AGENT37_BASE_TEMPLATE } from "./descriptors/agent37.js";
|
|
14
|
-
import { DEADLINE_LABEL } from "./drift.js";
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
15
|
+
import { DEADLINE_LABEL, show } from "./drift.js";
|
|
16
|
+
import { HostError } from "./host.js";
|
|
17
|
+
import { orThrow } from "./hosted/process.js";
|
|
18
|
+
import { jsonOf, rest } from "./hosted/rest.js";
|
|
19
|
+
import { HostedProvider } from "./hosted/provider.js";
|
|
20
|
+
import { pemOf, SshExec, SshTunnelError } from "./hosted/ssh-exec.js";
|
|
21
|
+
import { dateOf, DOMAIN, isWhole } from "./hosted/values.js";
|
|
22
|
+
import { failFor, ok } from "./result.js";
|
|
20
23
|
/** Not a literal, so no type checker or bundler resolves ssh2 from this package. */
|
|
21
24
|
const SSH2_PACKAGE = "ssh2";
|
|
22
25
|
const DEFAULT_API_URL = "https://api.agent37.com";
|
|
@@ -29,7 +32,6 @@ const AGENT37_TTYD_PORT = 7681;
|
|
|
29
32
|
const INSTANCE_ID = /^[a-z0-9]{10}$/;
|
|
30
33
|
/** A template name (cli.js:18), with an optional @<version> pin (docs: templates, pin a template version). */
|
|
31
34
|
const TEMPLATE = /^[a-z][a-z0-9-]{1,62}(@[A-Za-z0-9._-]{1,64})?$/;
|
|
32
|
-
const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
|
|
33
35
|
const DAY_MS = 24 * 60 * 60_000;
|
|
34
36
|
/** The instance shapes Agent37 makes, cpu and memory in GB (docs: instance-sizing): 4 vCPU is every type's ceiling. */
|
|
35
37
|
const SHAPES = [
|
|
@@ -39,61 +41,30 @@ const SHAPES = [
|
|
|
39
41
|
{ cpu: 4, memory: 32 },
|
|
40
42
|
];
|
|
41
43
|
const MAX_CPUS = 4;
|
|
42
|
-
/**
|
|
44
|
+
/**
|
|
45
|
+
* metadata's cap, serialized (docs: instances/edit, "up to 4 KB serialized"): check() holds the names and values to it,
|
|
46
|
+
* and create the JSON, its quotes and commas too.
|
|
47
|
+
*/
|
|
43
48
|
const METADATA_MAX_BYTES = 4096;
|
|
44
49
|
/** A VM boots inside the create's POST, which answers once it runs (docs: instances/create, Defaults). */
|
|
45
50
|
const DEFAULT_CREATE_MS = 300_000;
|
|
46
|
-
const DEFAULT_REQUEST_MS = 30_000;
|
|
47
51
|
/** How much a tunnel may hold unsent before a write waits for it (the WebSocket's bufferedAmount). */
|
|
48
52
|
const TUNNEL_HIGH_WATER = 1024 * 1024;
|
|
49
53
|
const TUNNEL_POLL_MS = 10;
|
|
50
|
-
/** How many times a tunnel that fails before its SSH handshake is opened, and the first pause between (it doubles). */
|
|
51
|
-
const TUNNEL_TRIES = 4;
|
|
52
|
-
const TUNNEL_RETRY_MS = 500;
|
|
53
|
-
/** ssh2's keepalive: the CLI's ServerAliveInterval is 60 s (cli.js:32); the edge never sees an idle tunnel. */
|
|
54
|
-
const KEEPALIVE_MS = 30_000;
|
|
55
|
-
/** How long a kill waits for its own kill command, then for the SSH connection to close before it drops the tunnel. */
|
|
56
|
-
const KILL_GRACE_MS = 2_000;
|
|
57
|
-
/**
|
|
58
|
-
* Every command runs under this sh, which writes its pid to $0 first and removes the file when the command ends. The
|
|
59
|
-
* instance's sshd starts each command as a session and group leader (seen live: sh's PID, PGID and SID are one), so
|
|
60
|
-
* the pid names the group a kill ends; ssh2 sends no signal once stdin has ended, and a signal ends one process only.
|
|
61
|
-
*/
|
|
62
|
-
const WRAPPER = '{ echo $$ > "$0"; } 2>/dev/null; "$@"; c=$?; rm -f "$0"; exit $c';
|
|
63
54
|
/**
|
|
64
|
-
*
|
|
65
|
-
*
|
|
55
|
+
* A registration copies the image into the workspace's storage before it answers, "up to a few minutes for a large
|
|
56
|
+
* image" (docs: templates, Register a workspace template): the POST's bound, and the wait on another's registration.
|
|
66
57
|
*/
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
/** The mount kinds an Agent37 computer takes, as capabilities().mount declares them: the run's folder on an Archil disk. */
|
|
78
|
-
export const MOUNT = AGENT37.mounts;
|
|
79
|
-
/** The machine kind and groups of each configuration: kind linux (the default), and kind desktop on the box template. */
|
|
80
|
-
export const CAPABILITIES = AGENT37.capabilities;
|
|
81
|
-
const show = (value) => (value === undefined ? "nothing" : JSON.stringify(value));
|
|
82
|
-
const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
|
|
83
|
-
/** An answer of Agent37's REST API that is not a success: its HTTP status and the envelope's stable code (docs: errors). */
|
|
84
|
-
export class Agent37Error extends Error {
|
|
85
|
-
name = "Agent37Error";
|
|
86
|
-
status;
|
|
87
|
-
code;
|
|
88
|
-
constructor(status, code, message) {
|
|
89
|
-
super(message);
|
|
90
|
-
this.status = status;
|
|
91
|
-
this.code = code;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
/** The SSH tunnel's WebSocket closed or failed before it opened, or while it carried the stream. */
|
|
95
|
-
export class Agent37TunnelError extends Error {
|
|
96
|
-
name = "Agent37TunnelError";
|
|
58
|
+
const REGISTER_MS = 15 * 60_000;
|
|
59
|
+
/** One read of a template. */
|
|
60
|
+
const TEMPLATE_READ_MS = 30_000;
|
|
61
|
+
/** How often a template another registration is making is read again. */
|
|
62
|
+
const TEMPLATE_POLL_MS = 1_000;
|
|
63
|
+
/** An id held to Agent37's form before it reaches a URL or a host name (an id is also a DNS label here): not_found else. */
|
|
64
|
+
function instanceId(id) {
|
|
65
|
+
if (!INSTANCE_ID.test(id))
|
|
66
|
+
throw new HostError("not_found", `${JSON.stringify(id)} is not an Agent37 instance id (ten lowercase letters and digits)`);
|
|
67
|
+
return id;
|
|
97
68
|
}
|
|
98
69
|
/** The envelope's code: { error: { code } } on the Sandbox API, a flat { error: "<code>" } on transport errors (docs: errors). */
|
|
99
70
|
function envelopeOf(body) {
|
|
@@ -122,25 +93,9 @@ const CODES = {
|
|
|
122
93
|
rate_limited: "limit",
|
|
123
94
|
};
|
|
124
95
|
function codeOf(error) {
|
|
125
|
-
const {
|
|
126
|
-
if (
|
|
127
|
-
return
|
|
128
|
-
if (name === "TimeoutError")
|
|
129
|
-
return "timeout";
|
|
130
|
-
if (error instanceof Agent37Error) {
|
|
131
|
-
const known = typeof code === "string" ? CODES[code] : undefined;
|
|
132
|
-
if (known !== undefined)
|
|
133
|
-
return known;
|
|
134
|
-
if (status === 401 || status === 403)
|
|
135
|
-
return "denied";
|
|
136
|
-
if (status === 404)
|
|
137
|
-
return "not_found";
|
|
138
|
-
if (status === 400)
|
|
139
|
-
return "invalid";
|
|
140
|
-
if (status === 402 || status === 429)
|
|
141
|
-
return "limit";
|
|
142
|
-
return "vendor";
|
|
143
|
-
}
|
|
96
|
+
const { level } = (error ?? {});
|
|
97
|
+
if (error instanceof HostError)
|
|
98
|
+
return error.code;
|
|
144
99
|
// ssh2 names the stage that failed (lib/client.js): the instance's sshd refused the key, or the handshake timed out.
|
|
145
100
|
if (level === "client-authentication")
|
|
146
101
|
return "denied";
|
|
@@ -148,24 +103,7 @@ function codeOf(error) {
|
|
|
148
103
|
return "timeout";
|
|
149
104
|
return "vendor";
|
|
150
105
|
}
|
|
151
|
-
/**
|
|
152
|
-
function networkOf(instance) {
|
|
153
|
-
const ports = Array.isArray(instance.public_ports) ? instance.public_ports : [];
|
|
154
|
-
if (ports.length > 0) {
|
|
155
|
-
const numbers = ports.map((port) => port?.port).filter((port) => typeof port === "number");
|
|
156
|
-
return { other: `public ports (${numbers.join(", ") || ports.length}) let anyone in, which this provider never makes` };
|
|
157
|
-
}
|
|
158
|
-
const { network } = instance;
|
|
159
|
-
if (network === "deny-all")
|
|
160
|
-
return "none";
|
|
161
|
-
if (network === "allow-all")
|
|
162
|
-
return "open";
|
|
163
|
-
const allow = network?.allow;
|
|
164
|
-
if (Array.isArray(allow))
|
|
165
|
-
return { other: `an allow list (${allow.length} entries), which this provider never makes` };
|
|
166
|
-
return { other: `Agent37 read back the network ${show(network)}` };
|
|
167
|
-
}
|
|
168
|
-
/** Agent37's statuses (docs: instances/object, Statuses) as the adapter's states. */
|
|
106
|
+
/** Agent37's statuses (docs: instances/object, Statuses) as the adapter's states; failed, deleting and deleted are gone (get answers none for deleted). */
|
|
169
107
|
function stateOf(status) {
|
|
170
108
|
if (status === "running")
|
|
171
109
|
return "running";
|
|
@@ -173,40 +111,23 @@ function stateOf(status) {
|
|
|
173
111
|
return "starting";
|
|
174
112
|
if (["stopping", "stopped", "sleeping"].includes(status))
|
|
175
113
|
return "stopped";
|
|
176
|
-
if (
|
|
177
|
-
return "
|
|
178
|
-
if (status === "deleting" || status === "deleted")
|
|
179
|
-
return "going";
|
|
114
|
+
if (["failed", "deleting", "deleted"].includes(status))
|
|
115
|
+
return "gone";
|
|
180
116
|
return undefined;
|
|
181
117
|
}
|
|
182
|
-
/** An instance as the adapter reads a machine: its state
|
|
183
|
-
function machineOf(instance
|
|
184
|
-
const labels = { ...(instance.metadata ?? {}) };
|
|
185
|
-
const drift = [];
|
|
186
|
-
const mismatch = (field, want, got) => drift.push(`${field}: declared ${show(want)}, read back ${show(got)}`);
|
|
187
|
-
const asked = labels[IMAGE_LABEL];
|
|
188
|
-
if (asked !== undefined && instance.template !== asked)
|
|
189
|
-
mismatch("template", asked, instance.template);
|
|
190
|
-
if (instance.type !== declared.type)
|
|
191
|
-
mismatch("type", declared.type, instance.type);
|
|
192
|
-
if (instance.region !== declared.region)
|
|
193
|
-
mismatch("region", declared.region, instance.region);
|
|
194
|
-
// A sleeping VM wakes cold, its daemon gone (docs: vm-instances, Auto-sleep): auto-sleep stays off.
|
|
195
|
-
if (instance.auto_sleep !== false)
|
|
196
|
-
mismatch("auto_sleep", false, instance.auto_sleep);
|
|
118
|
+
/** An instance as the adapter reads a machine: its state (a status it does not know is gone, in words), labels, start. */
|
|
119
|
+
function machineOf(instance) {
|
|
197
120
|
const state = stateOf(instance.status);
|
|
198
|
-
|
|
199
|
-
const
|
|
121
|
+
// A failed instance always carries a why, Agent37's or ours, so create stops on it as vendor, never as gone.
|
|
122
|
+
const why = instance.status_reason?.message ??
|
|
123
|
+
(state === undefined ? `Agent37 reads the status ${show(instance.status)}, which this provider does not know` : instance.status === "failed" ? "Agent37 reads the instance failed, with no reason given" : undefined);
|
|
124
|
+
const created = dateOf(instance.created, "s");
|
|
200
125
|
return {
|
|
201
126
|
id: instance.id,
|
|
202
|
-
labels,
|
|
203
|
-
state: state ?? "
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
...(isWhole(instance.created) ? { createdAt: new Date(instance.created * 1000) } : {}),
|
|
207
|
-
...(isWhole(cpu) || isWhole(memory) ? { size: { ...(isWhole(cpu) ? { cpus: cpu } : {}), ...(isWhole(memory) ? { memoryMb: memory * 1024 } : {}) } } : {}),
|
|
208
|
-
...(drift.length > 0 ? { drift } : {}),
|
|
209
|
-
...(why === undefined ? {} : { why }),
|
|
127
|
+
labels: { ...(instance.metadata ?? {}) },
|
|
128
|
+
state: state ?? "gone",
|
|
129
|
+
...(created ? { createdAt: created } : {}),
|
|
130
|
+
...(why === undefined || (state !== undefined && state !== "gone") ? {} : { why }),
|
|
210
131
|
};
|
|
211
132
|
}
|
|
212
133
|
/** The shape a request's cpus and memoryMb ask for, or undefined when they ask for none of Agent37's. */
|
|
@@ -224,7 +145,7 @@ function tunnelOf(ws, host) {
|
|
|
224
145
|
read() { },
|
|
225
146
|
write(chunk, _encoding, done) {
|
|
226
147
|
if (ws.readyState !== 1)
|
|
227
|
-
return done(new
|
|
148
|
+
return done(new SshTunnelError(`the SSH tunnel to ${host} is closed`));
|
|
228
149
|
try {
|
|
229
150
|
ws.send(chunk);
|
|
230
151
|
}
|
|
@@ -233,7 +154,7 @@ function tunnelOf(ws, host) {
|
|
|
233
154
|
}
|
|
234
155
|
const wait = () => {
|
|
235
156
|
if (ws.readyState !== 1)
|
|
236
|
-
done(new
|
|
157
|
+
done(new SshTunnelError(`the SSH tunnel to ${host} closed while it sent`));
|
|
237
158
|
else if (ws.bufferedAmount <= TUNNEL_HIGH_WATER)
|
|
238
159
|
done();
|
|
239
160
|
else
|
|
@@ -274,7 +195,7 @@ function tunnelOf(ws, host) {
|
|
|
274
195
|
resolve();
|
|
275
196
|
});
|
|
276
197
|
ws.addEventListener("error", (event) => {
|
|
277
|
-
const error = new
|
|
198
|
+
const error = new SshTunnelError(`the SSH tunnel to ${host} failed${open ? "" : " to open"}${event.message ? `: ${event.message}` : ""}`);
|
|
278
199
|
if (!open)
|
|
279
200
|
reject(error);
|
|
280
201
|
else
|
|
@@ -282,7 +203,7 @@ function tunnelOf(ws, host) {
|
|
|
282
203
|
});
|
|
283
204
|
ws.addEventListener("close", ({ code, reason }) => {
|
|
284
205
|
if (!open)
|
|
285
|
-
reject(new
|
|
206
|
+
reject(new SshTunnelError(`the SSH tunnel to ${host} was refused (closed with ${code ?? "no code"}${reason ? `: ${reason}` : ""}); the edge opens it for the workspace's API key alone`));
|
|
286
207
|
else
|
|
287
208
|
duplex.push(null);
|
|
288
209
|
});
|
|
@@ -290,99 +211,72 @@ function tunnelOf(ws, host) {
|
|
|
290
211
|
opened.catch(() => { });
|
|
291
212
|
return { duplex, opened };
|
|
292
213
|
}
|
|
293
|
-
/** A promise that rejects with the abort's or the bound's error once ms pass or signal aborts. */
|
|
294
|
-
function deadline(ms, signal, what) {
|
|
295
|
-
const bound = bounded(ms, signal);
|
|
296
|
-
let onAbort = () => { };
|
|
297
|
-
const promise = new Promise((_, reject) => {
|
|
298
|
-
onAbort = () => {
|
|
299
|
-
const timedOut = !signal?.aborted;
|
|
300
|
-
const error = new Error(timedOut ? `${what} did not answer within ${ms / 1000} s` : `${what} was aborted`);
|
|
301
|
-
error.name = timedOut ? "TimeoutError" : "AbortError";
|
|
302
|
-
reject(error);
|
|
303
|
-
};
|
|
304
|
-
if (bound.aborted)
|
|
305
|
-
onAbort();
|
|
306
|
-
else
|
|
307
|
-
bound.addEventListener("abort", onAbort, { once: true });
|
|
308
|
-
});
|
|
309
|
-
promise.catch(() => { });
|
|
310
|
-
return { promise, clear: () => bound.removeEventListener("abort", onAbort) };
|
|
311
|
-
}
|
|
312
214
|
/** Agent37's instances as a MachineHost (../host.ts). */
|
|
313
215
|
class Agent37Host {
|
|
314
|
-
|
|
216
|
+
descriptor = AGENT37;
|
|
315
217
|
facts;
|
|
316
218
|
#apiKey;
|
|
317
|
-
#
|
|
318
|
-
#
|
|
319
|
-
#fetch;
|
|
219
|
+
#ssh;
|
|
220
|
+
#client;
|
|
320
221
|
#WebSocket;
|
|
321
|
-
#apiUrl;
|
|
322
222
|
#proxyDomain;
|
|
323
223
|
#declared;
|
|
324
224
|
constructor(options) {
|
|
325
225
|
this.#apiKey = options.apiKey;
|
|
326
|
-
this.#
|
|
327
|
-
this.#
|
|
328
|
-
|
|
226
|
+
this.#ssh = new SshExec({ ssh2: options.ssh2, loginOf: () => ({ username: "root", privateKey: options.sshKey }), tunnelOf: (id) => this.#tunnel(id) });
|
|
227
|
+
this.#client = rest({
|
|
228
|
+
base: options.apiUrl,
|
|
229
|
+
headers: () => ({ Authorization: `Bearer ${options.apiKey}`, Accept: "application/json" }),
|
|
230
|
+
vendor: "agent37",
|
|
231
|
+
fetch: options.fetch,
|
|
232
|
+
timeoutMs: 30_000, // every call gives its own: ctx.timeoutMs
|
|
233
|
+
explain: ({ status, bytes, what }) => {
|
|
234
|
+
const { code, message } = envelopeOf(jsonOf(bytes));
|
|
235
|
+
const known = code === undefined ? undefined : CODES[code];
|
|
236
|
+
return { ...(known === undefined ? {} : { code: known }), message: `${what} answered ${status}${code ? ` ${code}` : ""}${message ? `: ${message}` : ""}` };
|
|
237
|
+
},
|
|
238
|
+
});
|
|
329
239
|
this.#WebSocket = options.WebSocket;
|
|
330
|
-
this.#apiUrl = options.apiUrl;
|
|
331
240
|
this.#proxyDomain = options.proxyDomain;
|
|
332
241
|
this.#declared = { type: options.type, region: options.region };
|
|
333
|
-
const runtime = options.type === "vm" ? "vm" : "gvisor";
|
|
334
242
|
this.facts = {
|
|
335
243
|
daemon: "child",
|
|
336
|
-
|
|
244
|
+
// The adapter holds the probe's kernel to it: gVisor's for type default, never for a VM.
|
|
245
|
+
isolation: options.type === "vm" ? "vm" : "gvisor",
|
|
337
246
|
lifetime: "janitor",
|
|
338
247
|
maxLifetimeMs: DAY_MS,
|
|
339
248
|
arch: "amd64",
|
|
340
249
|
vendorAgentPorts: [AGENT37_SSH_PORT, AGENT37_TTYD_PORT],
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
release: ["delete"],
|
|
345
|
-
specFields: ["cpus", "memoryMb"],
|
|
346
|
-
runtime: () => runtime,
|
|
250
|
+
// The box template is the box image (box/Dockerfile), which has xfwm4: the apps an agent opens are framed and focused.
|
|
251
|
+
windowManager: true,
|
|
252
|
+
labels: { bytes: METADATA_MAX_BYTES },
|
|
347
253
|
};
|
|
348
254
|
}
|
|
349
255
|
errorCode(error) {
|
|
350
256
|
return codeOf(error);
|
|
351
257
|
}
|
|
352
|
-
/**
|
|
258
|
+
/** The SSH stream to an instance's sshd: a binary WebSocket the edge opens for the workspace key (cli.js wsHandshake), as a Duplex. */
|
|
259
|
+
#tunnel(id) {
|
|
260
|
+
const host = `${id}-${AGENT37_SSH_PORT}.${this.#proxyDomain}`;
|
|
261
|
+
const ws = new this.#WebSocket(`wss://${host}/`, { headers: { "X-Agent37-Key": this.#apiKey } });
|
|
262
|
+
ws.binaryType = "arraybuffer";
|
|
263
|
+
return { ...tunnelOf(ws, host), host };
|
|
264
|
+
}
|
|
265
|
+
/** argv as root over SSH (hosted/ssh-exec.ts): one connection per instance through its tunnel, shared by its execs. */
|
|
266
|
+
async exec(id, argv, ctx) {
|
|
267
|
+
return this.#ssh.exec(instanceId(id), argv, ctx);
|
|
268
|
+
}
|
|
269
|
+
/** One REST call, bounded by ctx: its JSON answer; a failure throws a HostError in Agent37's words. */
|
|
353
270
|
async #rest(method, path, body, ctx) {
|
|
354
|
-
const
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
signal: bounded(ctx.timeoutMs, ctx.signal),
|
|
359
|
-
});
|
|
360
|
-
const text = await response.text();
|
|
361
|
-
let parsed;
|
|
362
|
-
try {
|
|
363
|
-
parsed = text === "" ? null : JSON.parse(text);
|
|
364
|
-
}
|
|
365
|
-
catch {
|
|
366
|
-
parsed = undefined;
|
|
367
|
-
}
|
|
368
|
-
if (!response.ok) {
|
|
369
|
-
const { code, message } = envelopeOf(parsed);
|
|
370
|
-
throw new Agent37Error(response.status, code, `${method} ${path} answered ${response.status}${code ? ` ${code}` : ""}${message ? `: ${message}` : ""}`);
|
|
371
|
-
}
|
|
372
|
-
if (parsed === undefined || parsed === null)
|
|
373
|
-
throw new Agent37Error(response.status, undefined, `${method} ${path} answered ${response.status} with no JSON body`);
|
|
271
|
+
const answer = orThrow(await this.#client.call(method, this.#client.url(path), { ...(body === undefined ? {} : { json: body }), timeoutMs: ctx.timeoutMs }, ctx.signal));
|
|
272
|
+
const parsed = jsonOf(answer.bytes);
|
|
273
|
+
if (parsed === null)
|
|
274
|
+
throw new HostError("vendor", `${method} ${path} answered ${answer.status} with no JSON body`);
|
|
374
275
|
return parsed;
|
|
375
276
|
}
|
|
376
|
-
/** An
|
|
377
|
-
|
|
378
|
-
if (!INSTANCE_ID.test(id))
|
|
379
|
-
throw new Agent37Error(404, "not_found", `${JSON.stringify(id)} is not an Agent37 instance id (ten lowercase letters and digits)`);
|
|
380
|
-
return `/v1/instances/${id}`;
|
|
381
|
-
}
|
|
382
|
-
/** An Agent37 template is a name, with an optional @<version>; a size is one of Agent37's four shapes; metadata fits 4 KB. */
|
|
383
|
-
check(spec) {
|
|
277
|
+
/** An Agent37 template is a name, with an optional @<version>; a size is one of Agent37's four shapes. The adapter holds metadata to 4 KB (facts.labels.bytes). */
|
|
278
|
+
check(given) {
|
|
384
279
|
const refusals = [];
|
|
385
|
-
const given = (typeof spec === "object" && spec !== null ? spec : {});
|
|
386
280
|
const { image, cpus, memoryMb } = given;
|
|
387
281
|
if (typeof image === "string" && image !== "" && !TEMPLATE.test(image)) {
|
|
388
282
|
refusals.push({ field: "image", message: `an image is the name of an Agent37 template, optionally pinned as name@version, such as "${AGENT37_BASE_TEMPLATE}"` });
|
|
@@ -393,20 +287,18 @@ class Agent37Host {
|
|
|
393
287
|
else if ((cpus !== undefined || memoryMb !== undefined) && shapeOf(cpus, memoryMb) === undefined) {
|
|
394
288
|
refusals.push({ field: cpus !== undefined && !SHAPES.some((shape) => shape.cpu === cpus) ? "cpus" : "memoryMb", message: `an Agent37 instance is one of its shapes: ${SHAPE_WORDS}` });
|
|
395
289
|
}
|
|
396
|
-
const labels = given.labels;
|
|
397
|
-
if (typeof labels === "object" && labels !== null && !Array.isArray(labels)) {
|
|
398
|
-
const bytes = Buffer.byteLength(JSON.stringify({ ...labels, ...ownLabels(given) }), "utf8");
|
|
399
|
-
if (bytes > METADATA_MAX_BYTES)
|
|
400
|
-
refusals.push({ field: "labels", message: `an Agent37 instance's metadata holds ${METADATA_MAX_BYTES} bytes, the provider's own labels with them; these come to ${bytes}` });
|
|
401
|
-
}
|
|
402
290
|
return refusals;
|
|
403
291
|
}
|
|
404
292
|
/**
|
|
405
293
|
* POST /v1/instances: the template, the type and region, the size when the spec asks one, the request's name as the
|
|
406
|
-
* instance's name, the labels as metadata, deny-all (or allow-all
|
|
294
|
+
* instance's name, the labels as metadata, deny-all (or allow-all where the adapter asks egress: an Archil computer's root, or the
|
|
295
|
+
* egress proxy of a network open or a list), auto-sleep off and
|
|
407
296
|
* no public port. It answers once the instance runs (docs: instances/create, Defaults).
|
|
408
297
|
*/
|
|
409
298
|
async create(req, ctx) {
|
|
299
|
+
const bytes = Buffer.byteLength(JSON.stringify(req.labels));
|
|
300
|
+
if (bytes > METADATA_MAX_BYTES)
|
|
301
|
+
throw new HostError("invalid", `Agent37 holds an instance's metadata to ${METADATA_MAX_BYTES} bytes as JSON, and this one's would be ${bytes}: give shorter labels`);
|
|
410
302
|
const shape = req.cpus !== undefined || req.memoryMb !== undefined ? shapeOf(req.cpus, req.memoryMb) : undefined;
|
|
411
303
|
const made = await this.#rest("POST", "/v1/instances", {
|
|
412
304
|
template: req.image,
|
|
@@ -415,285 +307,96 @@ class Agent37Host {
|
|
|
415
307
|
...(shape === undefined ? {} : { resources: { cpu: shape.cpu, memory: shape.memory } }),
|
|
416
308
|
name: req.name,
|
|
417
309
|
metadata: req.labels,
|
|
418
|
-
network: req.
|
|
310
|
+
network: req.egress ? "allow-all" : "deny-all",
|
|
419
311
|
auto_sleep: false,
|
|
420
312
|
public_ports: [],
|
|
421
313
|
}, ctx);
|
|
422
314
|
if (typeof made?.id !== "string" || !INSTANCE_ID.test(made.id))
|
|
423
|
-
throw new
|
|
424
|
-
return
|
|
315
|
+
throw new HostError("vendor", `POST /v1/instances answered no instance id: ${show(made?.id)}`);
|
|
316
|
+
return { id: made.id };
|
|
425
317
|
}
|
|
426
|
-
/** GET /v1/instances/{id}; 404 is none (docs: instances/get). */
|
|
318
|
+
/** GET /v1/instances/{id}; 404 is not_found, which the adapter reads as none, as is status deleted (docs: instances/get). */
|
|
427
319
|
async get(id, ctx) {
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
catch (error) {
|
|
432
|
-
if (codeOf(error) === "not_found")
|
|
433
|
-
return ok(undefined);
|
|
434
|
-
throw error;
|
|
435
|
-
}
|
|
320
|
+
const instance = await this.#rest("GET", `/v1/instances/${instanceId(id)}`, undefined, ctx);
|
|
321
|
+
// A deleted instance is one Agent37 no longer has, as a 404 is: the wait after a delete ends on it.
|
|
322
|
+
return instance.status === "deleted" ? undefined : machineOf(instance);
|
|
436
323
|
}
|
|
437
324
|
/**
|
|
438
325
|
* GET /v1/instances: the whole workspace in one answer, newest first, each the full instance object (docs:
|
|
439
|
-
* instances/list). Agent37 filters nothing
|
|
326
|
+
* instances/list). Agent37 filters nothing: the adapter matches the labels. An answer that says it has more is refused.
|
|
440
327
|
*/
|
|
441
328
|
async list(labels, ctx) {
|
|
329
|
+
void labels;
|
|
442
330
|
const listed = await this.#rest("GET", "/v1/instances", undefined, ctx);
|
|
443
|
-
if (!Array.isArray(listed
|
|
444
|
-
throw new
|
|
331
|
+
if (!Array.isArray(listed?.data))
|
|
332
|
+
throw new HostError("vendor", "GET /v1/instances answered no data list");
|
|
445
333
|
if (listed.has_more === true || (listed.next_cursor !== undefined && listed.next_cursor !== null)) {
|
|
446
|
-
throw new
|
|
447
|
-
}
|
|
448
|
-
const wanted = Object.entries(labels);
|
|
449
|
-
const machines = [];
|
|
450
|
-
for (const instance of listed.data) {
|
|
451
|
-
if (typeof instance?.id !== "string")
|
|
452
|
-
continue;
|
|
453
|
-
const metadata = instance.metadata ?? {};
|
|
454
|
-
if (wanted.every(([key, value]) => metadata[key] === value))
|
|
455
|
-
machines.push(machineOf(instance, this.#declared));
|
|
334
|
+
throw new HostError("vendor", "GET /v1/instances answered a page with more after it, which Agent37 documents none of: this provider would miss machines");
|
|
456
335
|
}
|
|
457
|
-
return
|
|
458
|
-
}
|
|
459
|
-
/** DELETE /v1/instances/{id}, never signalled; a repeat answers 404, read as done (docs: instances/delete). */
|
|
460
|
-
async delete(id, ctx) {
|
|
461
|
-
try {
|
|
462
|
-
await this.#rest("DELETE", this.#path(id), undefined, { timeoutMs: ctx.timeoutMs });
|
|
463
|
-
}
|
|
464
|
-
catch (error) {
|
|
465
|
-
if (codeOf(error) !== "not_found")
|
|
466
|
-
throw error;
|
|
467
|
-
}
|
|
468
|
-
return ok(undefined);
|
|
469
|
-
}
|
|
470
|
-
/** The janitor's deadline label: GET, then PATCH of the whole metadata, which replaces the stored object (docs: instances/edit). */
|
|
471
|
-
async setLabels(id, labels, ctx) {
|
|
472
|
-
const path = this.#path(id);
|
|
473
|
-
const instance = await this.#rest("GET", path, undefined, ctx);
|
|
474
|
-
await this.#rest("PATCH", path, { metadata: { ...(instance.metadata ?? {}), ...labels } }, ctx);
|
|
475
|
-
return ok(undefined);
|
|
336
|
+
return listed.data.filter((instance) => typeof instance?.id === "string").map(machineOf);
|
|
476
337
|
}
|
|
477
338
|
/**
|
|
478
|
-
*
|
|
479
|
-
*
|
|
480
|
-
* from its create can refuse the first (seen live once in eight creates, the daemon's upload refused). Nothing has
|
|
481
|
-
* run before a handshake, so a retry repeats nothing. A refused key or a handshake past its bound is not retried.
|
|
339
|
+
* DELETE /v1/instances/{id}, never signalled; a repeat answers 404, which the adapter reads as done (docs:
|
|
340
|
+
* instances/delete). Once taken, this host's SSH connections to the instance are ended, channels and all.
|
|
482
341
|
*/
|
|
483
|
-
async
|
|
484
|
-
|
|
485
|
-
throw new Agent37Error(404, "not_found", `${JSON.stringify(id)} is not an Agent37 instance id (ten lowercase letters and digits)`);
|
|
486
|
-
const host = `${id}-${AGENT37_SSH_PORT}.${this.#proxyDomain}`;
|
|
487
|
-
const bound = deadline(ctx.timeoutMs, ctx.signal, `the SSH connection to ${id}`);
|
|
488
|
-
// Ends the handshake in flight when this call gives up on it (its bound passed, or the caller aborted).
|
|
489
|
-
const givenUp = new AbortController();
|
|
342
|
+
async delete(id, ctx) {
|
|
343
|
+
const path = `/v1/instances/${instanceId(id)}`;
|
|
490
344
|
try {
|
|
491
|
-
|
|
492
|
-
try {
|
|
493
|
-
return await Promise.race([this.#handshake(host, ctx.timeoutMs, givenUp.signal), bound.promise]);
|
|
494
|
-
}
|
|
495
|
-
catch (error) {
|
|
496
|
-
const early = error instanceof Agent37TunnelError || error.level === "client-socket";
|
|
497
|
-
if (!early || attempt >= TUNNEL_TRIES)
|
|
498
|
-
throw error;
|
|
499
|
-
}
|
|
500
|
-
await Promise.race([new Promise((resolve) => setTimeout(resolve, TUNNEL_RETRY_MS * 2 ** (attempt - 1))), bound.promise]);
|
|
501
|
-
}
|
|
345
|
+
await this.#rest("DELETE", path, undefined, { timeoutMs: ctx.timeoutMs });
|
|
502
346
|
}
|
|
503
347
|
catch (error) {
|
|
504
|
-
|
|
348
|
+
// A 404 means the instance is gone already: its connections end too, then the adapter reads not_found as done.
|
|
349
|
+
if (error instanceof HostError && error.code === "not_found")
|
|
350
|
+
this.#ssh.closeAll(id);
|
|
505
351
|
throw error;
|
|
506
352
|
}
|
|
507
|
-
|
|
508
|
-
bound.clear();
|
|
509
|
-
}
|
|
353
|
+
this.#ssh.closeAll(id);
|
|
510
354
|
}
|
|
511
|
-
/**
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
const ws = new this.#WebSocket(`wss://${host}/`, { headers: { "X-Agent37-Key": this.#apiKey } });
|
|
517
|
-
ws.binaryType = "arraybuffer";
|
|
518
|
-
const { duplex, opened } = tunnelOf(ws, host);
|
|
519
|
-
const client = new this.#ssh2.Client();
|
|
520
|
-
const givenUp = () => new Agent37TunnelError(`the SSH tunnel to ${host} was given up on`);
|
|
521
|
-
let quit = () => { };
|
|
522
|
-
const quitted = new Promise((_resolve, reject) => {
|
|
523
|
-
quit = reject;
|
|
524
|
-
});
|
|
525
|
-
quitted.catch(() => { });
|
|
526
|
-
const drop = () => {
|
|
527
|
-
client.destroy();
|
|
528
|
-
duplex.destroy();
|
|
529
|
-
quit(givenUp());
|
|
530
|
-
};
|
|
531
|
-
stop.addEventListener("abort", drop, { once: true });
|
|
532
|
-
try {
|
|
533
|
-
await Promise.race([opened, quitted]);
|
|
534
|
-
await Promise.race([
|
|
535
|
-
new Promise((resolve, reject) => {
|
|
536
|
-
client.once("ready", resolve);
|
|
537
|
-
client.once("error", reject);
|
|
538
|
-
client.connect({ sock: duplex, username: "root", privateKey: this.#sshKey, readyTimeout: timeoutMs, keepaliveInterval: KEEPALIVE_MS });
|
|
539
|
-
}),
|
|
540
|
-
quitted,
|
|
541
|
-
]);
|
|
542
|
-
}
|
|
543
|
-
catch (error) {
|
|
544
|
-
drop();
|
|
545
|
-
throw error;
|
|
546
|
-
}
|
|
547
|
-
finally {
|
|
548
|
-
stop.removeEventListener("abort", drop);
|
|
549
|
-
}
|
|
550
|
-
if (stop.aborted) {
|
|
551
|
-
drop();
|
|
552
|
-
throw givenUp();
|
|
553
|
-
}
|
|
554
|
-
// A later error ends the session; its channel's close reports it.
|
|
555
|
-
client.on("error", () => { });
|
|
556
|
-
return client;
|
|
355
|
+
/** The janitor's deadline label moved: GET, then PATCH of the whole metadata, which replaces the stored object (docs: instances/edit). */
|
|
356
|
+
async extend(id, endsAt, ctx) {
|
|
357
|
+
const path = `/v1/instances/${instanceId(id)}`;
|
|
358
|
+
const instance = await this.#rest("GET", path, undefined, ctx);
|
|
359
|
+
await this.#rest("PATCH", path, { metadata: { ...(instance.metadata ?? {}), [DEADLINE_LABEL]: endsAt.toISOString() } }, ctx);
|
|
557
360
|
}
|
|
558
|
-
/**
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
*/
|
|
563
|
-
async #channel(client, command, ms, signal, what) {
|
|
564
|
-
const bound = deadline(ms, signal, what);
|
|
565
|
-
try {
|
|
566
|
-
return await Promise.race([
|
|
567
|
-
new Promise((resolve, reject) => {
|
|
568
|
-
client.exec(command, (error, channel) => {
|
|
569
|
-
if (error)
|
|
570
|
-
return reject(error);
|
|
571
|
-
let code = -1;
|
|
572
|
-
channel.on("exit", (status) => {
|
|
573
|
-
code = typeof status === "number" ? status : -1;
|
|
574
|
-
});
|
|
575
|
-
channel.on("error", () => { });
|
|
576
|
-
resolve({ channel, closed: new Promise((done) => channel.on("close", () => done(code))) });
|
|
577
|
-
});
|
|
578
|
-
}),
|
|
579
|
-
bound.promise,
|
|
580
|
-
]);
|
|
581
|
-
}
|
|
582
|
-
finally {
|
|
583
|
-
bound.clear();
|
|
584
|
-
}
|
|
361
|
+
/** GET /v1/templates/{name}: whether the workspace has it (404: it has not), else a HostError in Agent37's words. */
|
|
362
|
+
async #hasTemplate(name, signal) {
|
|
363
|
+
const read = orThrow(await this.#client.call("GET", this.#client.url(`/v1/templates/${name}`), { timeoutMs: TEMPLATE_READ_MS, accept: (status) => status === 200 || status === 404 }, signal));
|
|
364
|
+
return read.status === 200;
|
|
585
365
|
}
|
|
586
366
|
/**
|
|
587
|
-
*
|
|
588
|
-
*
|
|
589
|
-
*
|
|
590
|
-
*
|
|
367
|
+
* The workspace template `name`, made from the public image `imageRef` when the workspace has none (docs: templates):
|
|
368
|
+
* GET it; on a 404, `registering` is told, then POST /v1/templates { name, image_ref }, which answers once Agent37 has
|
|
369
|
+
* copied the image into the workspace. A 409 is another registration of the name, which this waits for, reading the
|
|
370
|
+
* template until the workspace has it. Throws a HostError in Agent37's words.
|
|
591
371
|
*/
|
|
592
|
-
async
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
return ok({
|
|
619
|
-
stdout,
|
|
620
|
-
stderr,
|
|
621
|
-
write: (bytes) => new Promise((resolve, reject) => {
|
|
622
|
-
if (ended || closed)
|
|
623
|
-
return reject(new Error(ended ? "stdin was ended" : "the process has ended"));
|
|
624
|
-
channel.write(bytes, (error) => (error ? reject(error) : resolve()));
|
|
625
|
-
}),
|
|
626
|
-
end: async () => {
|
|
627
|
-
if (ended || closed)
|
|
628
|
-
return;
|
|
629
|
-
ended = true;
|
|
630
|
-
channel.eof();
|
|
631
|
-
},
|
|
632
|
-
wait: () => exited,
|
|
633
|
-
kill: async () => {
|
|
634
|
-
if (closed)
|
|
635
|
-
return;
|
|
636
|
-
try {
|
|
637
|
-
const killer = await this.#channel(client, shellLine(["sh", "-c", KILL_SCRIPT, pidFile]), KILL_GRACE_MS, undefined, `the kill in ${id}`);
|
|
638
|
-
killer.channel.resume();
|
|
639
|
-
killer.channel.stderr.resume();
|
|
640
|
-
killer.channel.eof();
|
|
641
|
-
const grace = deadline(KILL_GRACE_MS, undefined, `the kill in ${id}`);
|
|
642
|
-
await Promise.race([killer.closed, grace.promise]).finally(grace.clear);
|
|
643
|
-
}
|
|
644
|
-
catch {
|
|
645
|
-
// The connection is gone, or the kill did not answer in time: closing it below is what is left.
|
|
646
|
-
}
|
|
647
|
-
try {
|
|
648
|
-
channel.close();
|
|
649
|
-
}
|
|
650
|
-
catch {
|
|
651
|
-
// Closed already.
|
|
652
|
-
}
|
|
653
|
-
client.end();
|
|
654
|
-
const dropped = setTimeout(() => client.destroy(), KILL_GRACE_MS);
|
|
655
|
-
dropped.unref();
|
|
656
|
-
void exited.then(() => clearTimeout(dropped));
|
|
657
|
-
},
|
|
658
|
-
});
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
|
-
/** The provider's own labels at create, as check() counts them toward metadata's cap: the longest each can be. */
|
|
662
|
-
function ownLabels(spec) {
|
|
663
|
-
const time = new Date(0).toISOString();
|
|
664
|
-
let archil = {};
|
|
665
|
-
if (spec.mount?.kind === "archil") {
|
|
666
|
-
try {
|
|
667
|
-
archil = archilLabels(spec.mount);
|
|
668
|
-
}
|
|
669
|
-
catch {
|
|
670
|
-
// The adapter refuses a mount it cannot read, in its own words.
|
|
372
|
+
async template(name, imageRef, registering, signal) {
|
|
373
|
+
if (await this.#hasTemplate(name, signal))
|
|
374
|
+
return;
|
|
375
|
+
registering();
|
|
376
|
+
const json = { name, image_ref: imageRef, description: `AgentRun's box image ${imageRef}, registered by the server that first needed it` };
|
|
377
|
+
const posted = orThrow(await this.#client.call("POST", this.#client.url("/v1/templates"), { json, timeoutMs: REGISTER_MS, accept: (status) => (status >= 200 && status < 300) || status === 409 }, signal));
|
|
378
|
+
if (posted.status !== 409)
|
|
379
|
+
return;
|
|
380
|
+
const end = Date.now() + REGISTER_MS;
|
|
381
|
+
while (!(await this.#hasTemplate(name, signal))) {
|
|
382
|
+
if (Date.now() > end)
|
|
383
|
+
throw new HostError("timeout", `another registration of ${name} was not done within ${REGISTER_MS / 60_000} minutes`);
|
|
384
|
+
await new Promise((resolve, reject) => {
|
|
385
|
+
const done = () => {
|
|
386
|
+
clearTimeout(timer);
|
|
387
|
+
reject(new HostError("aborted", `the wait on another registration of ${name} was aborted`));
|
|
388
|
+
};
|
|
389
|
+
const timer = setTimeout(() => {
|
|
390
|
+
signal?.removeEventListener("abort", done);
|
|
391
|
+
resolve();
|
|
392
|
+
}, TEMPLATE_POLL_MS);
|
|
393
|
+
if (signal?.aborted)
|
|
394
|
+
done();
|
|
395
|
+
else
|
|
396
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
397
|
+
});
|
|
671
398
|
}
|
|
672
399
|
}
|
|
673
|
-
return { "agentrun.computer": "1", [NAME_LABEL]: "computer-000000000000", [DEADLINE_LABEL]: time, [IMAGE_LABEL]: typeof spec.image === "string" ? spec.image : "", [MAX_LABEL]: time, ...archil };
|
|
674
|
-
}
|
|
675
|
-
/**
|
|
676
|
-
* A private key in the PEM armor ssh2 reads (its parser wants the BEGIN and END lines on lines of their own), or
|
|
677
|
-
* undefined when text is not one. A key pasted into Settings → Computers comes back on one line, since a password
|
|
678
|
-
* field drops line breaks: its body is wrapped again at 70 characters, as ssh-keygen writes it.
|
|
679
|
-
*/
|
|
680
|
-
function pemOf(text) {
|
|
681
|
-
const armor = /^-----BEGIN ([A-Z0-9 ]*PRIVATE KEY)-----([\s\S]*?)-----END \1-----$/.exec(text.replace(/\r/g, "").trim());
|
|
682
|
-
if (!armor)
|
|
683
|
-
return undefined;
|
|
684
|
-
const [, label, inside] = armor;
|
|
685
|
-
const lines = inside.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
686
|
-
// PEM headers (Proc-Type, DEK-Info) keep their own lines; a key with them was never pasted onto one line.
|
|
687
|
-
if (lines.some((line) => line.includes(":")))
|
|
688
|
-
return `-----BEGIN ${label}-----\n${lines.join("\n")}\n-----END ${label}-----\n`;
|
|
689
|
-
const body = lines.join("").replace(/\s+/g, "");
|
|
690
|
-
if (body === "" || !/^[A-Za-z0-9+/=]+$/.test(body))
|
|
691
|
-
return undefined;
|
|
692
|
-
return `-----BEGIN ${label}-----\n${body.match(/.{1,70}/g)?.join("\n")}\n-----END ${label}-----\n`;
|
|
693
|
-
}
|
|
694
|
-
/** The ssh2 module's slice, or why it is not one. */
|
|
695
|
-
function ssh2Problem(ssh2) {
|
|
696
|
-
return typeof ssh2?.Client === "function" ? undefined : "options.ssh2 must be the ssh2 package (its Client class): the host installs it, as it does e2b";
|
|
697
400
|
}
|
|
698
401
|
/**
|
|
699
402
|
* An Agent37Provider from its options alone; it reads no environment. The key is options.apiKey and the SSH key
|
|
@@ -701,33 +404,53 @@ function ssh2Problem(ssh2) {
|
|
|
701
404
|
* reads), and ssh2 is the host's package unless given. Throws in words when an option is missing or wrong, never echoing a key.
|
|
702
405
|
*/
|
|
703
406
|
export async function create(options) {
|
|
704
|
-
const {
|
|
705
|
-
if (typeof apiKey !== "string" || apiKey === "")
|
|
706
|
-
throw new Error("options.apiKey, the Agent37 API key, is required: the provider reads no environment, so the caller passes it");
|
|
707
|
-
if (typeof sshKey !== "string" || sshKey === "")
|
|
708
|
-
throw new Error("options.sshKey, the private half of an SSH key registered on the Agent37 workspace, is required: its contents, never a path");
|
|
407
|
+
const { ssh2: given, ...rest } = options ?? {};
|
|
709
408
|
// ssh2 is CommonJS: its Client is a named export of the module, and of its default.
|
|
710
409
|
const loaded = given ?? (await import(SSH2_PACKAGE));
|
|
711
410
|
const ssh2 = typeof loaded.Client === "function" ? loaded : loaded.default;
|
|
712
|
-
return new Agent37Provider({ ...rest,
|
|
411
|
+
return new Agent37Provider({ ...rest, ssh2: ssh2 });
|
|
713
412
|
}
|
|
714
413
|
/** The conformance CLI's module for Agent37: its live switch, the run's cap, its template and the drifted twin. */
|
|
715
414
|
export const conformance = () => import("./conformance/agent37.js");
|
|
415
|
+
const fail = failFor(AGENT37.id);
|
|
716
416
|
/**
|
|
717
|
-
* Computers that are Agent37 instances, on the shared adapter. A spec's image is an Agent37 template's name
|
|
718
|
-
* "agent37-base", Agent37's plain Linux
|
|
417
|
+
* Computers that are Agent37 instances, on the shared adapter. A spec's image is an Agent37 template's name, such as
|
|
418
|
+
* "agent37-base", Agent37's plain Linux. A server starts every one from the template prepareImage() answers: our box
|
|
419
|
+
* image, registered in the key's own workspace.
|
|
719
420
|
*/
|
|
720
421
|
export class Agent37Provider extends HostedProvider {
|
|
422
|
+
/**
|
|
423
|
+
* The provider contract's prepareImage (its descriptor declares it): the box image the release publishes
|
|
424
|
+
* (box-image.ts), as the workspace template agentrun-box-<recipe hash>, registered from the public image the first
|
|
425
|
+
* time the workspace needs it, so a new recipe is a new template and the one before is left as it is. ok with the
|
|
426
|
+
* template's name; onWait is told "pull" once, before a registration it waits on, never when the workspace has it.
|
|
427
|
+
* A sandbox and a desktop start from the same image.
|
|
428
|
+
*/
|
|
429
|
+
async prepareImage(context = {}) {
|
|
430
|
+
const name = `agentrun-box-${boxRecipeHash()}`;
|
|
431
|
+
const ref = boxImageRef();
|
|
432
|
+
let registering = false;
|
|
433
|
+
try {
|
|
434
|
+
await this.host.template(name, ref, () => {
|
|
435
|
+
registering = true;
|
|
436
|
+
context.onWait?.("pull", ref);
|
|
437
|
+
}, context.signal);
|
|
438
|
+
return ok(name);
|
|
439
|
+
}
|
|
440
|
+
catch (error) {
|
|
441
|
+
const said = error instanceof Error ? error.message : String(error);
|
|
442
|
+
return fail(codeOf(error), registering ? `registering ${ref} as the Agent37 template ${name}: ${said}` : `reading the Agent37 template ${name}: ${said}`);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
721
445
|
constructor(options) {
|
|
722
|
-
const { apiKey, sshKey, ssh2, fetch: fetcher = globalThis.fetch, WebSocket = globalThis.WebSocket, apiUrl = DEFAULT_API_URL, proxyDomain = DEFAULT_PROXY_DOMAIN, type = "vm", region = "us",
|
|
446
|
+
const { apiKey, sshKey, ssh2, fetch: fetcher = globalThis.fetch, WebSocket = globalThis.WebSocket, apiUrl = DEFAULT_API_URL, proxyDomain = DEFAULT_PROXY_DOMAIN, type = "vm", region = "us", timeouts = {}, ...rest } = options ?? {};
|
|
723
447
|
if (typeof apiKey !== "string" || apiKey === "")
|
|
724
|
-
throw new Error("
|
|
448
|
+
throw new Error("options.apiKey, the Agent37 API key, is required: the provider reads no environment, so the caller passes it");
|
|
725
449
|
const privateKey = typeof sshKey === "string" ? pemOf(sshKey) : undefined;
|
|
726
450
|
if (privateKey === undefined)
|
|
727
451
|
throw new Error("options.sshKey must be the contents of an SSH private key (-----BEGIN ... PRIVATE KEY-----), never a path");
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
throw new Error(problem);
|
|
452
|
+
if (typeof ssh2?.Client !== "function")
|
|
453
|
+
throw new Error("options.ssh2 must be the ssh2 package (its Client class): the host installs it, as it does e2b");
|
|
731
454
|
if (typeof fetcher !== "function")
|
|
732
455
|
throw new Error("options.fetch must be a function, as the global fetch is");
|
|
733
456
|
if (typeof WebSocket !== "function")
|
|
@@ -750,7 +473,7 @@ export class Agent37Provider extends HostedProvider {
|
|
|
750
473
|
if (region !== "us" && type !== "vm")
|
|
751
474
|
throw new Error(`Agent37 runs type default in us alone: ${region} takes type vm`);
|
|
752
475
|
const host = new Agent37Host({ apiKey, sshKey: privateKey, ssh2, fetch: fetcher, WebSocket, apiUrl: api.href.replace(/\/+$/, ""), proxyDomain, type, region });
|
|
753
|
-
super(host, { ...rest,
|
|
476
|
+
super(host, { ...rest, timeouts: { createMs: DEFAULT_CREATE_MS, ...timeouts } });
|
|
754
477
|
}
|
|
755
478
|
}
|
|
756
479
|
/** The workspace a key reaches, in words, for the sweep's scope: the key's sha256 prefix, never the key. */
|