@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/agent37.js
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
// The Agent37 host: Agent37 Cloud instances (kind linux, or kind desktop on our box template, agentrun-box, whose Xvfb
|
|
2
|
+
// the adapter starts through the daemon), each a whole VM by default (type "vm"), or a gVisor sandbox
|
|
3
|
+
// (type "default"). The control plane is Agent37's REST API over fetch (https://api.agent37.com/v1, a Bearer key);
|
|
4
|
+
// every command (the daemon's upload, its install, init's start, the stdio bridge) goes over SSH, as root, through the
|
|
5
|
+
// host's own ssh2 package, of which this package names only the slice it uses (Ssh2Module) and imports nothing at load.
|
|
6
|
+
// Agent37 has no SSH port on the internet: the SSH stream rides a binary WebSocket to wss://{id}-22022.agent37.app,
|
|
7
|
+
// which the edge opens for the workspace key in X-Agent37-Key (npm agent37@0.4.1 src/cli.js, wsHandshake and runTunnel),
|
|
8
|
+
// and the instance's sshd then takes the workspace's registered SSH key. Agent37's REST exec is one-shot (no stdin,
|
|
9
|
+
// output only at its end), so it is not used. The rest of the computer is the shared machine-host adapter's
|
|
10
|
+
// (./hosted/provider.ts). Every vendor fact here is cited in the README's Agent37 section.
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { Duplex } from "node:stream";
|
|
13
|
+
import { pemOf, SshExec, SshTunnelError } from "./agent37-ssh.js";
|
|
14
|
+
import { AGENT37, AGENT37_BASE_TEMPLATE } from "./descriptors/agent37.js";
|
|
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 { dateOf, DOMAIN, isWhole } from "./hosted/values.js";
|
|
21
|
+
/** Not a literal, so no type checker or bundler resolves ssh2 from this package. */
|
|
22
|
+
const SSH2_PACKAGE = "ssh2";
|
|
23
|
+
const DEFAULT_API_URL = "https://api.agent37.com";
|
|
24
|
+
const DEFAULT_PROXY_DOMAIN = "agent37.app";
|
|
25
|
+
/** The port the platform's sshd answers on inside every instance, reached as {id}-22022.<domain> (cli.js:21, 720). */
|
|
26
|
+
export const AGENT37_SSH_PORT = 22022;
|
|
27
|
+
/** The platform's web terminal (ttyd), a root shell for whoever reaches it: seen listening on every VM. */
|
|
28
|
+
const AGENT37_TTYD_PORT = 7681;
|
|
29
|
+
/** An instance id: ten lowercase letters and digits, its DNS label (docs: instances/object; cli.js:19). */
|
|
30
|
+
const INSTANCE_ID = /^[a-z0-9]{10}$/;
|
|
31
|
+
/** A template name (cli.js:18), with an optional @<version> pin (docs: templates, pin a template version). */
|
|
32
|
+
const TEMPLATE = /^[a-z][a-z0-9-]{1,62}(@[A-Za-z0-9._-]{1,64})?$/;
|
|
33
|
+
const DAY_MS = 24 * 60 * 60_000;
|
|
34
|
+
/** The instance shapes Agent37 makes, cpu and memory in GB (docs: instance-sizing): 4 vCPU is every type's ceiling. */
|
|
35
|
+
const SHAPES = [
|
|
36
|
+
{ cpu: 2, memory: 4 },
|
|
37
|
+
{ cpu: 4, memory: 8 },
|
|
38
|
+
{ cpu: 4, memory: 16 },
|
|
39
|
+
{ cpu: 4, memory: 32 },
|
|
40
|
+
];
|
|
41
|
+
const MAX_CPUS = 4;
|
|
42
|
+
/** metadata's cap, serialized (docs: instances/edit, "up to 4 KB serialized"). */
|
|
43
|
+
const METADATA_MAX_BYTES = 4096;
|
|
44
|
+
/** A VM boots inside the create's POST, which answers once it runs (docs: instances/create, Defaults). */
|
|
45
|
+
const DEFAULT_CREATE_MS = 300_000;
|
|
46
|
+
/** How much a tunnel may hold unsent before a write waits for it (the WebSocket's bufferedAmount). */
|
|
47
|
+
const TUNNEL_HIGH_WATER = 1024 * 1024;
|
|
48
|
+
const TUNNEL_POLL_MS = 10;
|
|
49
|
+
/** 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. */
|
|
50
|
+
function instanceId(id) {
|
|
51
|
+
if (!INSTANCE_ID.test(id))
|
|
52
|
+
throw new HostError("not_found", `${JSON.stringify(id)} is not an Agent37 instance id (ten lowercase letters and digits)`);
|
|
53
|
+
return id;
|
|
54
|
+
}
|
|
55
|
+
/** The envelope's code: { error: { code } } on the Sandbox API, a flat { error: "<code>" } on transport errors (docs: errors). */
|
|
56
|
+
function envelopeOf(body) {
|
|
57
|
+
const error = body?.error;
|
|
58
|
+
if (typeof error === "string")
|
|
59
|
+
return { code: error, ...(typeof body.message === "string" ? { message: body.message } : {}) };
|
|
60
|
+
if (typeof error === "object" && error !== null) {
|
|
61
|
+
const { code, message } = error;
|
|
62
|
+
return { ...(typeof code === "string" ? { code } : {}), ...(typeof message === "string" ? { message } : {}) };
|
|
63
|
+
}
|
|
64
|
+
return {};
|
|
65
|
+
}
|
|
66
|
+
/** Agent37's codes (docs: errors, Sandbox API codes), each as a ComputerErrorCode; any other is the vendor's. */
|
|
67
|
+
const CODES = {
|
|
68
|
+
not_found: "not_found",
|
|
69
|
+
invalid_api_key: "denied",
|
|
70
|
+
ip_not_allowed: "denied",
|
|
71
|
+
forbidden: "denied",
|
|
72
|
+
invalid_request: "invalid",
|
|
73
|
+
image_too_large: "invalid",
|
|
74
|
+
insufficient_balance: "limit",
|
|
75
|
+
instance_limit_reached: "limit",
|
|
76
|
+
tier_limit: "limit",
|
|
77
|
+
no_capacity: "limit",
|
|
78
|
+
capacity_unavailable: "limit",
|
|
79
|
+
rate_limited: "limit",
|
|
80
|
+
};
|
|
81
|
+
function codeOf(error) {
|
|
82
|
+
const { level } = (error ?? {});
|
|
83
|
+
if (error instanceof HostError)
|
|
84
|
+
return error.code;
|
|
85
|
+
// ssh2 names the stage that failed (lib/client.js): the instance's sshd refused the key, or the handshake timed out.
|
|
86
|
+
if (level === "client-authentication")
|
|
87
|
+
return "denied";
|
|
88
|
+
if (level === "client-timeout")
|
|
89
|
+
return "timeout";
|
|
90
|
+
return "vendor";
|
|
91
|
+
}
|
|
92
|
+
/** Agent37's statuses (docs: instances/object, Statuses) as the adapter's states; failed, deleting and deleted are gone (get answers none for deleted). */
|
|
93
|
+
function stateOf(status) {
|
|
94
|
+
if (status === "running")
|
|
95
|
+
return "running";
|
|
96
|
+
if (["provisioning", "starting", "waking", "restarting", "updating"].includes(status))
|
|
97
|
+
return "starting";
|
|
98
|
+
if (["stopping", "stopped", "sleeping"].includes(status))
|
|
99
|
+
return "stopped";
|
|
100
|
+
if (["failed", "deleting", "deleted"].includes(status))
|
|
101
|
+
return "gone";
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
/** An instance as the adapter reads a machine: its state (a status it does not know is gone, in words), labels, start. */
|
|
105
|
+
function machineOf(instance) {
|
|
106
|
+
const state = stateOf(instance.status);
|
|
107
|
+
// A failed instance always carries a why, Agent37's or ours, so create stops on it as vendor, never as gone.
|
|
108
|
+
const why = instance.status_reason?.message ??
|
|
109
|
+
(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);
|
|
110
|
+
const created = dateOf(instance.created, "s");
|
|
111
|
+
return {
|
|
112
|
+
id: instance.id,
|
|
113
|
+
labels: { ...(instance.metadata ?? {}) },
|
|
114
|
+
state: state ?? "gone",
|
|
115
|
+
...(created ? { createdAt: created } : {}),
|
|
116
|
+
...(why === undefined || (state !== undefined && state !== "gone") ? {} : { why }),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/** The shape a request's cpus and memoryMb ask for, or undefined when they ask for none of Agent37's. */
|
|
120
|
+
function shapeOf(cpus, memoryMb) {
|
|
121
|
+
return SHAPES.find((shape) => (cpus === undefined || shape.cpu === cpus) && (memoryMb === undefined || shape.memory * 1024 === memoryMb));
|
|
122
|
+
}
|
|
123
|
+
const SHAPE_WORDS = SHAPES.map(({ cpu, memory }) => `${cpu} CPUs with ${memory * 1024} MiB`).join(", ");
|
|
124
|
+
/**
|
|
125
|
+
* A WebSocket's binary stream as a Duplex for ssh2: what the socket gives is read, a write is one binary frame, and a
|
|
126
|
+
* write waits while the socket holds more than TUNNEL_HIGH_WATER unsent. Its end closes the socket.
|
|
127
|
+
*/
|
|
128
|
+
function tunnelOf(ws, host) {
|
|
129
|
+
let open = false;
|
|
130
|
+
const duplex = new Duplex({
|
|
131
|
+
read() { },
|
|
132
|
+
write(chunk, _encoding, done) {
|
|
133
|
+
if (ws.readyState !== 1)
|
|
134
|
+
return done(new SshTunnelError(`the SSH tunnel to ${host} is closed`));
|
|
135
|
+
try {
|
|
136
|
+
ws.send(chunk);
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
return done(error);
|
|
140
|
+
}
|
|
141
|
+
const wait = () => {
|
|
142
|
+
if (ws.readyState !== 1)
|
|
143
|
+
done(new SshTunnelError(`the SSH tunnel to ${host} closed while it sent`));
|
|
144
|
+
else if (ws.bufferedAmount <= TUNNEL_HIGH_WATER)
|
|
145
|
+
done();
|
|
146
|
+
else
|
|
147
|
+
setTimeout(wait, TUNNEL_POLL_MS);
|
|
148
|
+
};
|
|
149
|
+
wait();
|
|
150
|
+
},
|
|
151
|
+
final(done) {
|
|
152
|
+
try {
|
|
153
|
+
ws.close(1000);
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
// Closed already.
|
|
157
|
+
}
|
|
158
|
+
done();
|
|
159
|
+
},
|
|
160
|
+
destroy(error, done) {
|
|
161
|
+
try {
|
|
162
|
+
ws.close(1000);
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
// Closed already.
|
|
166
|
+
}
|
|
167
|
+
done(error);
|
|
168
|
+
},
|
|
169
|
+
});
|
|
170
|
+
ws.addEventListener("message", ({ data }) => {
|
|
171
|
+
if (data instanceof ArrayBuffer)
|
|
172
|
+
duplex.push(Buffer.from(data));
|
|
173
|
+
else if (ArrayBuffer.isView(data))
|
|
174
|
+
duplex.push(Buffer.from(data.buffer, data.byteOffset, data.byteLength));
|
|
175
|
+
else if (typeof data === "string")
|
|
176
|
+
duplex.push(Buffer.from(data, "utf8"));
|
|
177
|
+
});
|
|
178
|
+
const opened = new Promise((resolve, reject) => {
|
|
179
|
+
ws.addEventListener("open", () => {
|
|
180
|
+
open = true;
|
|
181
|
+
resolve();
|
|
182
|
+
});
|
|
183
|
+
ws.addEventListener("error", (event) => {
|
|
184
|
+
const error = new SshTunnelError(`the SSH tunnel to ${host} failed${open ? "" : " to open"}${event.message ? `: ${event.message}` : ""}`);
|
|
185
|
+
if (!open)
|
|
186
|
+
reject(error);
|
|
187
|
+
else
|
|
188
|
+
duplex.destroy(error);
|
|
189
|
+
});
|
|
190
|
+
ws.addEventListener("close", ({ code, reason }) => {
|
|
191
|
+
if (!open)
|
|
192
|
+
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`));
|
|
193
|
+
else
|
|
194
|
+
duplex.push(null);
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
opened.catch(() => { });
|
|
198
|
+
return { duplex, opened };
|
|
199
|
+
}
|
|
200
|
+
/** Agent37's instances as a MachineHost (../host.ts). */
|
|
201
|
+
class Agent37Host {
|
|
202
|
+
descriptor = AGENT37;
|
|
203
|
+
facts;
|
|
204
|
+
#apiKey;
|
|
205
|
+
#ssh;
|
|
206
|
+
#client;
|
|
207
|
+
#WebSocket;
|
|
208
|
+
#proxyDomain;
|
|
209
|
+
#declared;
|
|
210
|
+
constructor(options) {
|
|
211
|
+
this.#apiKey = options.apiKey;
|
|
212
|
+
this.#ssh = new SshExec({ ssh2: options.ssh2, privateKey: options.sshKey, tunnelOf: (id) => this.#tunnel(id) });
|
|
213
|
+
this.#client = rest({
|
|
214
|
+
base: options.apiUrl,
|
|
215
|
+
headers: () => ({ Authorization: `Bearer ${options.apiKey}`, Accept: "application/json" }),
|
|
216
|
+
vendor: "agent37",
|
|
217
|
+
fetch: options.fetch,
|
|
218
|
+
timeoutMs: 30_000, // every call gives its own: ctx.timeoutMs
|
|
219
|
+
explain: ({ status, bytes, what }) => {
|
|
220
|
+
const { code, message } = envelopeOf(jsonOf(bytes));
|
|
221
|
+
const known = code === undefined ? undefined : CODES[code];
|
|
222
|
+
return { ...(known === undefined ? {} : { code: known }), message: `${what} answered ${status}${code ? ` ${code}` : ""}${message ? `: ${message}` : ""}` };
|
|
223
|
+
},
|
|
224
|
+
});
|
|
225
|
+
this.#WebSocket = options.WebSocket;
|
|
226
|
+
this.#proxyDomain = options.proxyDomain;
|
|
227
|
+
this.#declared = { type: options.type, region: options.region };
|
|
228
|
+
const runtime = options.type === "vm" ? "vm" : "gvisor";
|
|
229
|
+
this.facts = {
|
|
230
|
+
daemon: "child",
|
|
231
|
+
isolation: runtime,
|
|
232
|
+
lifetime: "janitor",
|
|
233
|
+
maxLifetimeMs: DAY_MS,
|
|
234
|
+
arch: "amd64",
|
|
235
|
+
vendorAgentPorts: [AGENT37_SSH_PORT, AGENT37_TTYD_PORT],
|
|
236
|
+
// The box template has xfwm4 (box/build-agent37.mjs): the apps an agent opens are framed and focused.
|
|
237
|
+
windowManager: true,
|
|
238
|
+
specFields: ["cpus", "memoryMb"],
|
|
239
|
+
labelRules: { maxBytes: METADATA_MAX_BYTES, measure: "json" },
|
|
240
|
+
runtime: () => runtime,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
errorCode(error) {
|
|
244
|
+
return codeOf(error);
|
|
245
|
+
}
|
|
246
|
+
/** The SSH stream to an instance's sshd: a binary WebSocket the edge opens for the workspace key (cli.js wsHandshake), as a Duplex. */
|
|
247
|
+
#tunnel(id) {
|
|
248
|
+
const host = `${id}-${AGENT37_SSH_PORT}.${this.#proxyDomain}`;
|
|
249
|
+
const ws = new this.#WebSocket(`wss://${host}/`, { headers: { "X-Agent37-Key": this.#apiKey } });
|
|
250
|
+
ws.binaryType = "arraybuffer";
|
|
251
|
+
return { ...tunnelOf(ws, host), host };
|
|
252
|
+
}
|
|
253
|
+
/** argv as root over SSH (agent37-ssh.ts): one connection per instance through its tunnel, shared by its execs. */
|
|
254
|
+
async exec(id, argv, ctx) {
|
|
255
|
+
return this.#ssh.exec(instanceId(id), argv, ctx);
|
|
256
|
+
}
|
|
257
|
+
/** One REST call, bounded by ctx: its JSON answer; a failure throws a HostError in Agent37's words. */
|
|
258
|
+
async #rest(method, path, body, ctx) {
|
|
259
|
+
const answer = orThrow(await this.#client.call(method, this.#client.url(path), { ...(body === undefined ? {} : { json: body }), timeoutMs: ctx.timeoutMs }, ctx.signal));
|
|
260
|
+
const parsed = jsonOf(answer.bytes);
|
|
261
|
+
if (parsed === null)
|
|
262
|
+
throw new HostError("vendor", `${method} ${path} answered ${answer.status} with no JSON body`);
|
|
263
|
+
return parsed;
|
|
264
|
+
}
|
|
265
|
+
/** 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 (labelRules). */
|
|
266
|
+
check(given) {
|
|
267
|
+
const refusals = [];
|
|
268
|
+
const { image, cpus, memoryMb } = given;
|
|
269
|
+
if (typeof image === "string" && image !== "" && !TEMPLATE.test(image)) {
|
|
270
|
+
refusals.push({ field: "image", message: `an image is the name of an Agent37 template, optionally pinned as name@version, such as "${AGENT37_BASE_TEMPLATE}"` });
|
|
271
|
+
}
|
|
272
|
+
if (cpus !== undefined && (!isWhole(cpus) || cpus > MAX_CPUS)) {
|
|
273
|
+
refusals.push({ field: "cpus", message: `an Agent37 instance has at most ${MAX_CPUS} CPUs, and Agent37 gives 4 for a larger ask without saying so: ask for 2 or 4` });
|
|
274
|
+
}
|
|
275
|
+
else if ((cpus !== undefined || memoryMb !== undefined) && shapeOf(cpus, memoryMb) === undefined) {
|
|
276
|
+
refusals.push({ field: cpus !== undefined && !SHAPES.some((shape) => shape.cpu === cpus) ? "cpus" : "memoryMb", message: `an Agent37 instance is one of its shapes: ${SHAPE_WORDS}` });
|
|
277
|
+
}
|
|
278
|
+
return refusals;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* POST /v1/instances: the template, the type and region, the size when the spec asks one, the request's name as the
|
|
282
|
+
* instance's name, the labels as metadata, deny-all (or allow-all for an Archil computer's root), auto-sleep off and
|
|
283
|
+
* no public port. It answers once the instance runs (docs: instances/create, Defaults).
|
|
284
|
+
*/
|
|
285
|
+
async create(req, ctx) {
|
|
286
|
+
const shape = req.cpus !== undefined || req.memoryMb !== undefined ? shapeOf(req.cpus, req.memoryMb) : undefined;
|
|
287
|
+
const made = await this.#rest("POST", "/v1/instances", {
|
|
288
|
+
template: req.image,
|
|
289
|
+
type: this.#declared.type,
|
|
290
|
+
region: this.#declared.region,
|
|
291
|
+
...(shape === undefined ? {} : { resources: { cpu: shape.cpu, memory: shape.memory } }),
|
|
292
|
+
name: req.name,
|
|
293
|
+
metadata: req.labels,
|
|
294
|
+
network: req.network === "open" ? "allow-all" : "deny-all",
|
|
295
|
+
auto_sleep: false,
|
|
296
|
+
public_ports: [],
|
|
297
|
+
}, ctx);
|
|
298
|
+
if (typeof made?.id !== "string" || !INSTANCE_ID.test(made.id))
|
|
299
|
+
throw new HostError("vendor", `POST /v1/instances answered no instance id: ${show(made?.id)}`);
|
|
300
|
+
return { id: made.id };
|
|
301
|
+
}
|
|
302
|
+
/** GET /v1/instances/{id}; 404 is not_found, which the adapter reads as none, as is status deleted (docs: instances/get). */
|
|
303
|
+
async get(id, ctx) {
|
|
304
|
+
const instance = await this.#rest("GET", `/v1/instances/${instanceId(id)}`, undefined, ctx);
|
|
305
|
+
// A deleted instance is one Agent37 no longer has, as a 404 is: the wait after a delete ends on it.
|
|
306
|
+
return instance.status === "deleted" ? undefined : machineOf(instance);
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* GET /v1/instances: the whole workspace in one answer, newest first, each the full instance object (docs:
|
|
310
|
+
* instances/list). Agent37 filters nothing: the adapter matches the labels. An answer that says it has more is refused.
|
|
311
|
+
*/
|
|
312
|
+
async list(labels, ctx) {
|
|
313
|
+
void labels;
|
|
314
|
+
const listed = await this.#rest("GET", "/v1/instances", undefined, ctx);
|
|
315
|
+
if (!Array.isArray(listed?.data))
|
|
316
|
+
throw new HostError("vendor", "GET /v1/instances answered no data list");
|
|
317
|
+
if (listed.has_more === true || (listed.next_cursor !== undefined && listed.next_cursor !== null)) {
|
|
318
|
+
throw new HostError("vendor", "GET /v1/instances answered a page with more after it, which Agent37 documents none of: this provider would miss machines");
|
|
319
|
+
}
|
|
320
|
+
return listed.data.filter((instance) => typeof instance?.id === "string").map(machineOf);
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* DELETE /v1/instances/{id}, never signalled; a repeat answers 404, which the adapter reads as done (docs:
|
|
324
|
+
* instances/delete). Once taken, this host's SSH connections to the instance are ended, channels and all.
|
|
325
|
+
*/
|
|
326
|
+
async delete(id, ctx) {
|
|
327
|
+
const path = `/v1/instances/${instanceId(id)}`;
|
|
328
|
+
try {
|
|
329
|
+
await this.#rest("DELETE", path, undefined, { timeoutMs: ctx.timeoutMs });
|
|
330
|
+
}
|
|
331
|
+
catch (error) {
|
|
332
|
+
// A 404 means the instance is gone already: its connections end too, then the adapter reads not_found as done.
|
|
333
|
+
if (error instanceof HostError && error.code === "not_found")
|
|
334
|
+
this.#ssh.closeAll(id);
|
|
335
|
+
throw error;
|
|
336
|
+
}
|
|
337
|
+
this.#ssh.closeAll(id);
|
|
338
|
+
}
|
|
339
|
+
/** The janitor's deadline label moved: GET, then PATCH of the whole metadata, which replaces the stored object (docs: instances/edit). */
|
|
340
|
+
async extend(id, endsAt, ctx) {
|
|
341
|
+
const path = `/v1/instances/${instanceId(id)}`;
|
|
342
|
+
const instance = await this.#rest("GET", path, undefined, ctx);
|
|
343
|
+
await this.#rest("PATCH", path, { metadata: { ...(instance.metadata ?? {}), [DEADLINE_LABEL]: endsAt.toISOString() } }, ctx);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* An Agent37Provider from its options alone; it reads no environment. The key is options.apiKey and the SSH key
|
|
348
|
+
* options.sshKey, nowhere else (serve passes its AGENT37_API_KEY and AGENT37_SSH_KEY, the conformance module what it
|
|
349
|
+
* reads), and ssh2 is the host's package unless given. Throws in words when an option is missing or wrong, never echoing a key.
|
|
350
|
+
*/
|
|
351
|
+
export async function create(options) {
|
|
352
|
+
const { ssh2: given, ...rest } = options ?? {};
|
|
353
|
+
// ssh2 is CommonJS: its Client is a named export of the module, and of its default.
|
|
354
|
+
const loaded = given ?? (await import(SSH2_PACKAGE));
|
|
355
|
+
const ssh2 = typeof loaded.Client === "function" ? loaded : loaded.default;
|
|
356
|
+
return new Agent37Provider({ ...rest, ssh2: ssh2 });
|
|
357
|
+
}
|
|
358
|
+
/** The conformance CLI's module for Agent37: its live switch, the run's cap, its template and the drifted twin. */
|
|
359
|
+
export const conformance = () => import("./conformance/agent37.js");
|
|
360
|
+
/**
|
|
361
|
+
* Computers that are Agent37 instances, on the shared adapter. A spec's image is an Agent37 template's name:
|
|
362
|
+
* "agent37-base", Agent37's plain Linux, for a sandbox; "agentrun-box", our box template with Xvfb, for a desktop.
|
|
363
|
+
*/
|
|
364
|
+
export class Agent37Provider extends HostedProvider {
|
|
365
|
+
constructor(options) {
|
|
366
|
+
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 ?? {};
|
|
367
|
+
if (typeof apiKey !== "string" || apiKey === "")
|
|
368
|
+
throw new Error("options.apiKey, the Agent37 API key, is required: the provider reads no environment, so the caller passes it");
|
|
369
|
+
const privateKey = typeof sshKey === "string" ? pemOf(sshKey) : undefined;
|
|
370
|
+
if (privateKey === undefined)
|
|
371
|
+
throw new Error("options.sshKey must be the contents of an SSH private key (-----BEGIN ... PRIVATE KEY-----), never a path");
|
|
372
|
+
if (typeof ssh2?.Client !== "function")
|
|
373
|
+
throw new Error("options.ssh2 must be the ssh2 package (its Client class): the host installs it, as it does e2b");
|
|
374
|
+
if (typeof fetcher !== "function")
|
|
375
|
+
throw new Error("options.fetch must be a function, as the global fetch is");
|
|
376
|
+
if (typeof WebSocket !== "function")
|
|
377
|
+
throw new Error("options.WebSocket must be a WebSocket class that takes headers, as Node's global one does");
|
|
378
|
+
let api;
|
|
379
|
+
try {
|
|
380
|
+
api = new URL(apiUrl);
|
|
381
|
+
}
|
|
382
|
+
catch {
|
|
383
|
+
throw new Error(`apiUrl must be an https URL such as ${DEFAULT_API_URL}, not ${JSON.stringify(apiUrl)}`);
|
|
384
|
+
}
|
|
385
|
+
if (api.protocol !== "https:" || api.search !== "" || api.hash !== "")
|
|
386
|
+
throw new Error(`apiUrl must be an https URL such as ${DEFAULT_API_URL}, not ${JSON.stringify(apiUrl)}`);
|
|
387
|
+
if (typeof proxyDomain !== "string" || !DOMAIN.test(proxyDomain))
|
|
388
|
+
throw new Error(`proxyDomain must be a host name such as ${DEFAULT_PROXY_DOMAIN}, not ${JSON.stringify(proxyDomain)}`);
|
|
389
|
+
if (type !== "vm" && type !== "default")
|
|
390
|
+
throw new Error(`type is vm or default, not ${JSON.stringify(type)}`);
|
|
391
|
+
if (region !== "us" && region !== "eu" && region !== "ap-south")
|
|
392
|
+
throw new Error(`region is us, eu or ap-south, not ${JSON.stringify(region)}`);
|
|
393
|
+
if (region !== "us" && type !== "vm")
|
|
394
|
+
throw new Error(`Agent37 runs type default in us alone: ${region} takes type vm`);
|
|
395
|
+
const host = new Agent37Host({ apiKey, sshKey: privateKey, ssh2, fetch: fetcher, WebSocket, apiUrl: api.href.replace(/\/+$/, ""), proxyDomain, type, region });
|
|
396
|
+
super(host, { ...rest, timeouts: { createMs: DEFAULT_CREATE_MS, ...timeouts } });
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
/** The workspace a key reaches, in words, for the sweep's scope: the key's sha256 prefix, never the key. */
|
|
400
|
+
export function workspaceOf(apiKey, apiUrl = DEFAULT_API_URL) {
|
|
401
|
+
return `the Agent37 workspace of the key sha256:${createHash("sha256").update(apiKey, "utf8").digest("hex").slice(0, 12)} at ${apiUrl.replace(/\/+$/, "")}`;
|
|
402
|
+
}
|
package/dist/attach.d.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { type Readable, Writable } from "node:stream";
|
|
2
|
+
import { type HelloResult } from "./protocol.js";
|
|
3
|
+
import { type ComputerConnection, type ComputerProvider } from "./provider.js";
|
|
4
|
+
import { type Result } from "./result.js";
|
|
5
|
+
export declare const ATTACH_PATH = "/v2/computers/attach";
|
|
6
|
+
/** The WebSocket subprotocol a driver asks for: the protocol version it speaks. Serve answers with it or refuses. */
|
|
7
|
+
export declare const ATTACH_SUBPROTOCOL = "agentrun.computer.0.2";
|
|
8
|
+
/** Each side pings this often (WebSocket ping frames, not JSON-RPC), so a NAT keeps the path open. */
|
|
9
|
+
export declare const ATTACH_HEARTBEAT_MS = 20000;
|
|
10
|
+
/** A side that hears nothing, not even a pong, for this long closes the socket with ATTACH_CLOSE.idle. */
|
|
11
|
+
export declare const ATTACH_IDLE_MS = 60000;
|
|
12
|
+
/** Serve waits this long for a new socket's hello answer; a socket whose driver pings but never answers is closed idle. */
|
|
13
|
+
export declare const ATTACH_HELLO_MS = 10000;
|
|
14
|
+
/** A pairing code lives this long, and is good once. */
|
|
15
|
+
export declare const PAIRING_CODE_TTL_MS: number;
|
|
16
|
+
/** Eight characters a person reads off a screen and types, with no 0, O, 1 or I: "K7PD-W3QX". */
|
|
17
|
+
export declare const PAIRING_CODE_PATTERN: RegExp;
|
|
18
|
+
/** The longest a driver waits between two dials. */
|
|
19
|
+
export declare const ATTACH_REDIAL_MAX_MS = 60000;
|
|
20
|
+
/** Why a socket closed, as its close code. A driver dials again after any code but the four that need a person. */
|
|
21
|
+
export declare const ATTACH_CLOSE: {
|
|
22
|
+
readonly normal: 1000;
|
|
23
|
+
/** Serve is restarting or the driver is quitting. */
|
|
24
|
+
readonly going: 1001;
|
|
25
|
+
/** A binary frame: the binding is text frames only. */
|
|
26
|
+
readonly binary: 1003;
|
|
27
|
+
/** A frame over maxLineBytes. */
|
|
28
|
+
readonly tooBig: 1009;
|
|
29
|
+
/** The computer's hello is not what it paired as (another kind or os): pair again. */
|
|
30
|
+
readonly mismatch: 4400;
|
|
31
|
+
/** The token is unknown or was revoked: pair again. */
|
|
32
|
+
readonly unauthorized: 4401;
|
|
33
|
+
/** Nothing heard for ATTACH_IDLE_MS, or no answer to serve's hello within ATTACH_HELLO_MS. */
|
|
34
|
+
readonly idle: 4408;
|
|
35
|
+
/** The same computer dialed again; the older socket is closed. */
|
|
36
|
+
readonly replaced: 4409;
|
|
37
|
+
/** The driver speaks another protocol version, or its hello lacks a group its kind needs (kindServed): update it. */
|
|
38
|
+
readonly protocol: 4426;
|
|
39
|
+
};
|
|
40
|
+
/** Whether a driver dials again after a close with this code; false means a person must act (pair, update). */
|
|
41
|
+
export declare const redials: (code: number) => boolean;
|
|
42
|
+
/** How long a driver waits before its redial number `attempt` (from 0): 1 s doubling to ATTACH_REDIAL_MAX_MS, less up to a fifth at random. */
|
|
43
|
+
export declare function redialDelay(attempt: number, random?: () => number): number;
|
|
44
|
+
/** What a driver sends to trade a pairing code for its computer's token: POST /v2/computers/pair. */
|
|
45
|
+
export interface PairRequest {
|
|
46
|
+
code: string;
|
|
47
|
+
/** What the person calls the machine: "Ada's MacBook". */
|
|
48
|
+
name: string;
|
|
49
|
+
/** The driver's hello, so serve knows what it pairs: kind, os, groups and features. */
|
|
50
|
+
hello: HelloResult;
|
|
51
|
+
}
|
|
52
|
+
/** Serve's answer: the computer's id and its token, a secret the driver keeps in the OS's keychain. */
|
|
53
|
+
export interface PairResult {
|
|
54
|
+
computer: string;
|
|
55
|
+
token: string;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* One WebSocket as serve holds it, whatever the library: text frames in and out, and its close. The implementation
|
|
59
|
+
* answers pings and sends its own every ATTACH_HEARTBEAT_MS, closes with ATTACH_CLOSE.idle after ATTACH_IDLE_MS of
|
|
60
|
+
* silence, closes a binary frame with ATTACH_CLOSE.binary and one over maxLineBytes with ATTACH_CLOSE.tooBig.
|
|
61
|
+
*/
|
|
62
|
+
export interface AttachSocket {
|
|
63
|
+
send(text: string): void;
|
|
64
|
+
close(code: number, reason: string): void;
|
|
65
|
+
onText(listener: (text: string) => void): void;
|
|
66
|
+
/** Called once, when the socket closed, by either side or by a drop. */
|
|
67
|
+
onClose(listener: (code: number, reason: string) => void): void;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* A socket as the byte streams of the stdio binding: each frame in becomes a line, each line out a frame. Both serve's
|
|
71
|
+
* client and a driver written in TypeScript (the fake ui driver) speak through it, so the binding adds nothing to the
|
|
72
|
+
* wire. A raw newline in a frame can only be whitespace between JSON tokens, so it is read as a space.
|
|
73
|
+
*/
|
|
74
|
+
export declare function socketStreams(socket: AttachSocket): {
|
|
75
|
+
readable: Readable;
|
|
76
|
+
writable: Writable;
|
|
77
|
+
};
|
|
78
|
+
/** A paired computer, as serve's store keeps it. Its token is not here: serve keeps only the token's hash. */
|
|
79
|
+
export interface PairedComputer {
|
|
80
|
+
id: string;
|
|
81
|
+
name: string;
|
|
82
|
+
/** What it paired as: its hello at pairing. A later hello of another kind or os is refused (ATTACH_CLOSE.mismatch). */
|
|
83
|
+
hello: HelloResult;
|
|
84
|
+
labels: Record<string, string>;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Why a hello may not stand for a paired computer, or undefined. The protocol version must be the server's; the
|
|
88
|
+
* driver's own version may be any: a person's installed app updates on its own schedule, and the server cannot
|
|
89
|
+
* replace it the way a provider replaces a copied daemon.
|
|
90
|
+
*/
|
|
91
|
+
export declare function helloMismatch(paired: PairedComputer, hello: HelloResult): {
|
|
92
|
+
code: number;
|
|
93
|
+
message: string;
|
|
94
|
+
} | undefined;
|
|
95
|
+
/**
|
|
96
|
+
* Serve's attached computers in one process: the live connection of each, by its id. Serve's attach route checks the
|
|
97
|
+
* token, finds the paired computer and hands the socket to accept. A computer has one connection, serve's, which every
|
|
98
|
+
* caller shares (one run holds the computer at a time); a new socket from the same computer replaces the old one.
|
|
99
|
+
*/
|
|
100
|
+
export declare class AttachHub {
|
|
101
|
+
#private;
|
|
102
|
+
constructor({ helloMs }?: {
|
|
103
|
+
helloMs?: number;
|
|
104
|
+
});
|
|
105
|
+
/**
|
|
106
|
+
* Takes a computer's new socket: calls hello on it, and keeps it when the hello is what the computer paired as. The
|
|
107
|
+
* newest dial wins whichever hello answers first: a socket whose hello ends after a newer one went live is closed,
|
|
108
|
+
* never put in its place.
|
|
109
|
+
*/
|
|
110
|
+
accept(paired: PairedComputer, socket: AttachSocket): Promise<Result<HelloResult>>;
|
|
111
|
+
/** Whether the computer is attached now. */
|
|
112
|
+
online(id: string): boolean;
|
|
113
|
+
/** The hello of the computer's live connection: its driver's version and groups now, which an update may change. */
|
|
114
|
+
hello(id: string): HelloResult | undefined;
|
|
115
|
+
/**
|
|
116
|
+
* A connection over the computer's one socket: closing it leaves the socket open, cancels its calls still running and
|
|
117
|
+
* refuses its later ones, and the run's release closes every connection it was given, so a run done with the computer
|
|
118
|
+
* cannot reach it once another run holds it. Undefined while it is not attached.
|
|
119
|
+
*/
|
|
120
|
+
connection(id: string): ComputerConnection | undefined;
|
|
121
|
+
/**
|
|
122
|
+
* Holds the computer for a run, with the run's labels, until its deadline (an agent's hold has none): there the hold
|
|
123
|
+
* ends as a release does, closing the run's connections, and the person's machine runs on. False when another run
|
|
124
|
+
* holds it. The hold's token names this hold and no later one: unclaim with it never ends another run's.
|
|
125
|
+
*/
|
|
126
|
+
claim(id: string, labels: Record<string, string>, deadline?: Date): string | undefined;
|
|
127
|
+
/** The labels of the run that holds the computer, or undefined. */
|
|
128
|
+
claimed(id: string): Record<string, string> | undefined;
|
|
129
|
+
/** The token of the hold on the computer now, or undefined. */
|
|
130
|
+
hold(id: string): string | undefined;
|
|
131
|
+
/** The deadline of the run that holds the computer, or undefined (no hold, or an agent's). */
|
|
132
|
+
deadline(id: string): Date | undefined;
|
|
133
|
+
/**
|
|
134
|
+
* Ends the hold named by its token, and closes the connections it was given. A token of a hold already ended (a late
|
|
135
|
+
* release, after the deadline gave the computer to another run) ends nothing: false.
|
|
136
|
+
*/
|
|
137
|
+
unclaim(id: string, hold: string): boolean;
|
|
138
|
+
/** Ends a computer's attachment: its token was revoked, or the computer was removed. */
|
|
139
|
+
revoke(id: string, why: string): void;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* One paired computer as a provider, id "attached": its capabilities are what it paired as. create claims it for a
|
|
143
|
+
* run (refused while it is offline or another run holds it) and release ends the claim; a person's machine is never
|
|
144
|
+
* made, stopped or deleted by a run. It has no init of ours, so its daemon mode is none.
|
|
145
|
+
*/
|
|
146
|
+
export declare function attachedProvider(paired: PairedComputer, hub: AttachHub): ComputerProvider;
|