@parcha/agentrun-computer 0.1.0-beta.35 → 0.1.0-beta.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +423 -323
  3. package/box/Dockerfile +3 -1
  4. package/box/agentrun-archil +59 -7
  5. package/box/build-agent37.mjs +177 -0
  6. package/box/build-daytona.py +20 -4
  7. package/dist/agent37.d.ts +165 -0
  8. package/dist/agent37.js +759 -0
  9. package/dist/attach.d.ts +146 -0
  10. package/dist/attach.js +469 -0
  11. package/dist/browser.d.ts +61 -10
  12. package/dist/browser.js +125 -3
  13. package/dist/browserbase.d.ts +46 -23
  14. package/dist/browserbase.js +162 -17
  15. package/dist/chrome.d.ts +3 -4
  16. package/dist/chrome.js +6 -11
  17. package/dist/client.d.ts +33 -1
  18. package/dist/client.js +53 -0
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/conformance/agent37.d.ts +96 -0
  22. package/dist/conformance/agent37.js +154 -0
  23. package/dist/conformance/cases/apps.d.ts +5 -0
  24. package/dist/conformance/cases/apps.js +160 -73
  25. package/dist/conformance/cases/health.js +14 -0
  26. package/dist/conformance/cases/index.js +2 -0
  27. package/dist/conformance/cases/provider.js +27 -1
  28. package/dist/conformance/cases/screen.d.ts +3 -0
  29. package/dist/conformance/cases/screen.js +18 -0
  30. package/dist/conformance/cases/settings.d.ts +29 -23
  31. package/dist/conformance/cases/settings.js +76 -58
  32. package/dist/conformance/cases/touch.js +19 -17
  33. package/dist/conformance/cases/ui.d.ts +2 -0
  34. package/dist/conformance/cases/ui.js +475 -0
  35. package/dist/conformance/cli.d.ts +9 -0
  36. package/dist/conformance/cli.js +28 -3
  37. package/dist/conformance/daytona.d.ts +4 -0
  38. package/dist/conformance/daytona.js +5 -0
  39. package/dist/conformance/e2b.d.ts +6 -0
  40. package/dist/conformance/e2b.js +9 -2
  41. package/dist/conformance/fixture.d.ts +1 -1
  42. package/dist/conformance/fixture.js +25 -1
  43. package/dist/conformance/modal.d.ts +17 -13
  44. package/dist/conformance/modal.js +18 -9
  45. package/dist/conformance/orgo.d.ts +3 -3
  46. package/dist/conformance/orgo.js +6 -8
  47. package/dist/conformance/phone-harness.d.ts +6 -2
  48. package/dist/conformance/phone-harness.js +21 -4
  49. package/dist/conformance/report.js +1 -1
  50. package/dist/conformance/runner.js +23 -4
  51. package/dist/conformance/sweep.d.ts +50 -0
  52. package/dist/conformance/sweep.js +187 -0
  53. package/dist/conformance/types.d.ts +11 -3
  54. package/dist/conformance/ui-fixture.d.ts +56 -0
  55. package/dist/conformance/ui-fixture.js +43 -0
  56. package/dist/create-requests.d.ts +51 -0
  57. package/dist/create-requests.js +121 -0
  58. package/dist/daytona.d.ts +15 -5
  59. package/dist/daytona.js +58 -38
  60. package/dist/descriptor.d.ts +29 -2
  61. package/dist/descriptor.js +13 -0
  62. package/dist/descriptors/agent37.d.ts +41 -0
  63. package/dist/descriptors/agent37.js +28 -0
  64. package/dist/descriptors/browserbase.d.ts +1 -0
  65. package/dist/descriptors/browserbase.js +2 -0
  66. package/dist/descriptors/daytona.d.ts +23 -2
  67. package/dist/descriptors/daytona.js +34 -2
  68. package/dist/descriptors/index.d.ts +66 -3
  69. package/dist/descriptors/index.js +5 -3
  70. package/dist/descriptors/kernel.d.ts +1 -0
  71. package/dist/descriptors/kernel.js +2 -0
  72. package/dist/descriptors/modal.d.ts +4 -0
  73. package/dist/descriptors/modal.js +11 -1
  74. package/dist/descriptors/orgo.d.ts +13 -1
  75. package/dist/descriptors/orgo.js +9 -3
  76. package/dist/descriptors/phone-harness.d.ts +6 -1
  77. package/dist/descriptors/phone-harness.js +5 -2
  78. package/dist/docker/egress.d.ts +4 -3
  79. package/dist/docker/egress.js +7 -6
  80. package/dist/docker.d.ts +7 -4
  81. package/dist/docker.js +278 -34
  82. package/dist/e2b.d.ts +9 -165
  83. package/dist/e2b.js +282 -1342
  84. package/dist/fake-ui-driver.d.ts +97 -0
  85. package/dist/fake-ui-driver.js +717 -0
  86. package/dist/host.d.ts +182 -0
  87. package/dist/host.js +1 -0
  88. package/dist/hosted/process.d.ts +67 -0
  89. package/dist/hosted/process.js +228 -0
  90. package/dist/hosted/provider.d.ts +146 -0
  91. package/dist/hosted/provider.js +1364 -0
  92. package/dist/hosted/scripts.d.ts +76 -0
  93. package/dist/{child.js → hosted/scripts.js} +93 -12
  94. package/dist/index.d.ts +11 -7
  95. package/dist/index.js +10 -7
  96. package/dist/janitor.d.ts +5 -4
  97. package/dist/janitor.js +1 -1
  98. package/dist/kernel.d.ts +17 -27
  99. package/dist/kernel.js +94 -18
  100. package/dist/kinds.d.ts +17 -5
  101. package/dist/kinds.js +20 -4
  102. package/dist/labels.d.ts +10 -2
  103. package/dist/labels.js +30 -7
  104. package/dist/local-chrome.d.ts +5 -5
  105. package/dist/local-chrome.js +10 -5
  106. package/dist/modal.d.ts +23 -181
  107. package/dist/modal.js +273 -1232
  108. package/dist/mount-archil.d.ts +25 -3
  109. package/dist/mount-archil.js +39 -8
  110. package/dist/orgo-channel.d.ts +3 -2
  111. package/dist/orgo-channel.js +5 -2
  112. package/dist/orgo-desktop.d.ts +23 -9
  113. package/dist/orgo-desktop.js +328 -66
  114. package/dist/orgo-names.d.ts +129 -3
  115. package/dist/orgo-names.js +211 -8
  116. package/dist/orgo-workspaces.d.ts +47 -0
  117. package/dist/orgo-workspaces.js +94 -0
  118. package/dist/orgo.d.ts +27 -10
  119. package/dist/orgo.js +411 -81
  120. package/dist/phone-harness.d.ts +31 -21
  121. package/dist/phone-harness.js +510 -681
  122. package/dist/png.d.ts +4 -0
  123. package/dist/png.js +27 -0
  124. package/dist/protocol.d.ts +338 -30
  125. package/dist/protocol.js +96 -3
  126. package/dist/provider.d.ts +97 -7
  127. package/dist/provider.js +24 -3
  128. package/dist/result.d.ts +1 -1
  129. package/dist/surface/api.d.ts +248 -0
  130. package/dist/surface/api.js +1 -0
  131. package/dist/surface/core.d.ts +42 -0
  132. package/dist/surface/core.js +393 -0
  133. package/dist/surface/index.d.ts +5 -0
  134. package/dist/surface/index.js +3 -0
  135. package/dist/surface/outline.d.ts +8 -0
  136. package/dist/surface/outline.js +50 -0
  137. package/dist/surface/script.d.ts +10 -0
  138. package/dist/surface/script.js +92 -0
  139. package/dist/ui-engine.d.ts +114 -0
  140. package/dist/ui-engine.js +798 -0
  141. package/package.json +17 -1
  142. package/dist/child.d.ts +0 -42
  143. package/dist/conformance/e2b-diagnose.d.ts +0 -16
  144. package/dist/conformance/e2b-diagnose.js +0 -61
  145. package/dist/conformance/e2b-sweep.d.ts +0 -18
  146. package/dist/conformance/e2b-sweep.js +0 -132
  147. package/dist/conformance/modal-sweep.d.ts +0 -22
  148. package/dist/conformance/modal-sweep.js +0 -213
@@ -0,0 +1,759 @@
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, randomBytes } from "node:crypto";
12
+ import { Duplex, PassThrough } from "node:stream";
13
+ import { AGENT37, AGENT37_BASE_TEMPLATE } from "./descriptors/agent37.js";
14
+ import { DEADLINE_LABEL } from "./drift.js";
15
+ import { bounded } from "./hosted/process.js";
16
+ import { HostedProvider, IMAGE_LABEL, MAX_LABEL, NAME_LABEL } from "./hosted/provider.js";
17
+ import { shellLine } from "./hosted/scripts.js";
18
+ import { archilLabels } from "./mount-archil.js";
19
+ import { ok } from "./result.js";
20
+ /** Not a literal, so no type checker or bundler resolves ssh2 from this package. */
21
+ const SSH2_PACKAGE = "ssh2";
22
+ const DEFAULT_API_URL = "https://api.agent37.com";
23
+ const DEFAULT_PROXY_DOMAIN = "agent37.app";
24
+ /** The port the platform's sshd answers on inside every instance, reached as {id}-22022.<domain> (cli.js:21, 720). */
25
+ export const AGENT37_SSH_PORT = 22022;
26
+ /** The platform's web terminal (ttyd), a root shell for whoever reaches it: seen listening on every VM. */
27
+ const AGENT37_TTYD_PORT = 7681;
28
+ /** An instance id: ten lowercase letters and digits, its DNS label (docs: instances/object; cli.js:19). */
29
+ const INSTANCE_ID = /^[a-z0-9]{10}$/;
30
+ /** A template name (cli.js:18), with an optional @<version> pin (docs: templates, pin a template version). */
31
+ 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
+ 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
+ const DEFAULT_REQUEST_MS = 30_000;
47
+ /** How much a tunnel may hold unsent before a write waits for it (the WebSocket's bufferedAmount). */
48
+ const TUNNEL_HIGH_WATER = 1024 * 1024;
49
+ 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
+ /**
64
+ * The kill: waits up to a second for the pid file, then kills the group when the pid leads one (the process alone
65
+ * otherwise, so a kill never reaches past what it started) and removes the file.
66
+ */
67
+ const KILL_SCRIPT = [
68
+ "i=0",
69
+ 'while [ ! -s "$0" ] && [ $i -lt 10 ]; do sleep 0.1; i=$((i+1)); done',
70
+ 'p=$(cat "$0" 2>/dev/null); rm -f "$0"',
71
+ '[ -n "$p" ] || exit 0',
72
+ 'g=$(cut -d" " -f5 "/proc/$p/stat" 2>/dev/null)',
73
+ // No "--": dash's kill reads it as a pid (seen live: "Illegal number: -").
74
+ 'if [ "$g" = "$p" ]; then kill -KILL "-$p"; else kill -KILL "$p"; fi 2>/dev/null',
75
+ "exit 0",
76
+ ].join("\n");
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";
97
+ }
98
+ /** The envelope's code: { error: { code } } on the Sandbox API, a flat { error: "<code>" } on transport errors (docs: errors). */
99
+ function envelopeOf(body) {
100
+ const error = body?.error;
101
+ if (typeof error === "string")
102
+ return { code: error, ...(typeof body.message === "string" ? { message: body.message } : {}) };
103
+ if (typeof error === "object" && error !== null) {
104
+ const { code, message } = error;
105
+ return { ...(typeof code === "string" ? { code } : {}), ...(typeof message === "string" ? { message } : {}) };
106
+ }
107
+ return {};
108
+ }
109
+ /** Agent37's codes (docs: errors, Sandbox API codes), each as a ComputerErrorCode; any other is the vendor's. */
110
+ const CODES = {
111
+ not_found: "not_found",
112
+ invalid_api_key: "denied",
113
+ ip_not_allowed: "denied",
114
+ forbidden: "denied",
115
+ invalid_request: "invalid",
116
+ image_too_large: "invalid",
117
+ insufficient_balance: "limit",
118
+ instance_limit_reached: "limit",
119
+ tier_limit: "limit",
120
+ no_capacity: "limit",
121
+ capacity_unavailable: "limit",
122
+ rate_limited: "limit",
123
+ };
124
+ function codeOf(error) {
125
+ const { name, code, status, level } = (error ?? {});
126
+ if (name === "AbortError")
127
+ return "aborted";
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
+ }
144
+ // ssh2 names the stage that failed (lib/client.js): the instance's sshd refused the key, or the handshake timed out.
145
+ if (level === "client-authentication")
146
+ return "denied";
147
+ if (level === "client-timeout")
148
+ return "timeout";
149
+ return "vendor";
150
+ }
151
+ /** An instance's network as Agent37 reads it back, with its public ports: "allow-all" open, "deny-all" none. */
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. */
169
+ function stateOf(status) {
170
+ if (status === "running")
171
+ return "running";
172
+ if (["provisioning", "starting", "waking", "restarting", "updating"].includes(status))
173
+ return "starting";
174
+ if (["stopping", "stopped", "sleeping"].includes(status))
175
+ return "stopped";
176
+ if (status === "failed")
177
+ return "failed";
178
+ if (status === "deleting" || status === "deleted")
179
+ return "going";
180
+ return undefined;
181
+ }
182
+ /** An instance as the adapter reads a machine: its state, labels, network, template, size, and its create's drift. */
183
+ function machineOf(instance, declared) {
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);
197
+ const state = stateOf(instance.status);
198
+ const why = instance.status_reason?.message ?? (state === undefined ? `Agent37 reads the status ${show(instance.status)}, which this provider does not know` : undefined);
199
+ const { cpu, memory } = instance.resources ?? {};
200
+ return {
201
+ id: instance.id,
202
+ labels,
203
+ state: state ?? "failed",
204
+ network: networkOf(instance),
205
+ image: { resolved: instance.image_digest ?? instance.template },
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 }),
210
+ };
211
+ }
212
+ /** The shape a request's cpus and memoryMb ask for, or undefined when they ask for none of Agent37's. */
213
+ function shapeOf(cpus, memoryMb) {
214
+ return SHAPES.find((shape) => (cpus === undefined || shape.cpu === cpus) && (memoryMb === undefined || shape.memory * 1024 === memoryMb));
215
+ }
216
+ const SHAPE_WORDS = SHAPES.map(({ cpu, memory }) => `${cpu} CPUs with ${memory * 1024} MiB`).join(", ");
217
+ /**
218
+ * A WebSocket's binary stream as a Duplex for ssh2: what the socket gives is read, a write is one binary frame, and a
219
+ * write waits while the socket holds more than TUNNEL_HIGH_WATER unsent. Its end closes the socket.
220
+ */
221
+ function tunnelOf(ws, host) {
222
+ let open = false;
223
+ const duplex = new Duplex({
224
+ read() { },
225
+ write(chunk, _encoding, done) {
226
+ if (ws.readyState !== 1)
227
+ return done(new Agent37TunnelError(`the SSH tunnel to ${host} is closed`));
228
+ try {
229
+ ws.send(chunk);
230
+ }
231
+ catch (error) {
232
+ return done(error);
233
+ }
234
+ const wait = () => {
235
+ if (ws.readyState !== 1)
236
+ done(new Agent37TunnelError(`the SSH tunnel to ${host} closed while it sent`));
237
+ else if (ws.bufferedAmount <= TUNNEL_HIGH_WATER)
238
+ done();
239
+ else
240
+ setTimeout(wait, TUNNEL_POLL_MS);
241
+ };
242
+ wait();
243
+ },
244
+ final(done) {
245
+ try {
246
+ ws.close(1000);
247
+ }
248
+ catch {
249
+ // Closed already.
250
+ }
251
+ done();
252
+ },
253
+ destroy(error, done) {
254
+ try {
255
+ ws.close(1000);
256
+ }
257
+ catch {
258
+ // Closed already.
259
+ }
260
+ done(error);
261
+ },
262
+ });
263
+ ws.addEventListener("message", ({ data }) => {
264
+ if (data instanceof ArrayBuffer)
265
+ duplex.push(Buffer.from(data));
266
+ else if (ArrayBuffer.isView(data))
267
+ duplex.push(Buffer.from(data.buffer, data.byteOffset, data.byteLength));
268
+ else if (typeof data === "string")
269
+ duplex.push(Buffer.from(data, "utf8"));
270
+ });
271
+ const opened = new Promise((resolve, reject) => {
272
+ ws.addEventListener("open", () => {
273
+ open = true;
274
+ resolve();
275
+ });
276
+ ws.addEventListener("error", (event) => {
277
+ const error = new Agent37TunnelError(`the SSH tunnel to ${host} failed${open ? "" : " to open"}${event.message ? `: ${event.message}` : ""}`);
278
+ if (!open)
279
+ reject(error);
280
+ else
281
+ duplex.destroy(error);
282
+ });
283
+ ws.addEventListener("close", ({ code, reason }) => {
284
+ if (!open)
285
+ reject(new Agent37TunnelError(`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
+ else
287
+ duplex.push(null);
288
+ });
289
+ });
290
+ opened.catch(() => { });
291
+ return { duplex, opened };
292
+ }
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
+ /** Agent37's instances as a MachineHost (../host.ts). */
313
+ class Agent37Host {
314
+ id = "agent37";
315
+ facts;
316
+ #apiKey;
317
+ #sshKey;
318
+ #ssh2;
319
+ #fetch;
320
+ #WebSocket;
321
+ #apiUrl;
322
+ #proxyDomain;
323
+ #declared;
324
+ constructor(options) {
325
+ this.#apiKey = options.apiKey;
326
+ this.#sshKey = options.sshKey;
327
+ this.#ssh2 = options.ssh2;
328
+ this.#fetch = options.fetch;
329
+ this.#WebSocket = options.WebSocket;
330
+ this.#apiUrl = options.apiUrl;
331
+ this.#proxyDomain = options.proxyDomain;
332
+ this.#declared = { type: options.type, region: options.region };
333
+ const runtime = options.type === "vm" ? "vm" : "gvisor";
334
+ this.facts = {
335
+ daemon: "child",
336
+ isolation: runtime,
337
+ lifetime: "janitor",
338
+ maxLifetimeMs: DAY_MS,
339
+ arch: "amd64",
340
+ vendorAgentPorts: [AGENT37_SSH_PORT, AGENT37_TTYD_PORT],
341
+ networkReadBack: true,
342
+ network: [...AGENT37.network],
343
+ mounts: [...MOUNT],
344
+ release: ["delete"],
345
+ specFields: ["cpus", "memoryMb"],
346
+ runtime: () => runtime,
347
+ };
348
+ }
349
+ errorCode(error) {
350
+ return codeOf(error);
351
+ }
352
+ /** One REST call: the key as a Bearer token, JSON both ways, bounded by ctx; a failure throws Agent37Error in Agent37's words. */
353
+ async #rest(method, path, body, ctx) {
354
+ const response = await this.#fetch(`${this.#apiUrl}${path}`, {
355
+ method,
356
+ headers: { Authorization: `Bearer ${this.#apiKey}`, Accept: "application/json", ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
357
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
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`);
374
+ return parsed;
375
+ }
376
+ /** An instance's REST path, its id held to Agent37's form first: an id is also a DNS label here. */
377
+ #path(id) {
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) {
384
+ const refusals = [];
385
+ const given = (typeof spec === "object" && spec !== null ? spec : {});
386
+ const { image, cpus, memoryMb } = given;
387
+ if (typeof image === "string" && image !== "" && !TEMPLATE.test(image)) {
388
+ refusals.push({ field: "image", message: `an image is the name of an Agent37 template, optionally pinned as name@version, such as "${AGENT37_BASE_TEMPLATE}"` });
389
+ }
390
+ if (cpus !== undefined && (!isWhole(cpus) || cpus > MAX_CPUS)) {
391
+ 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` });
392
+ }
393
+ else if ((cpus !== undefined || memoryMb !== undefined) && shapeOf(cpus, memoryMb) === undefined) {
394
+ 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
+ }
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
+ return refusals;
403
+ }
404
+ /**
405
+ * 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 for an Archil computer's root), auto-sleep off and
407
+ * no public port. It answers once the instance runs (docs: instances/create, Defaults).
408
+ */
409
+ async create(req, ctx) {
410
+ const shape = req.cpus !== undefined || req.memoryMb !== undefined ? shapeOf(req.cpus, req.memoryMb) : undefined;
411
+ const made = await this.#rest("POST", "/v1/instances", {
412
+ template: req.image,
413
+ type: this.#declared.type,
414
+ region: this.#declared.region,
415
+ ...(shape === undefined ? {} : { resources: { cpu: shape.cpu, memory: shape.memory } }),
416
+ name: req.name,
417
+ metadata: req.labels,
418
+ network: req.network === "open" ? "allow-all" : "deny-all",
419
+ auto_sleep: false,
420
+ public_ports: [],
421
+ }, ctx);
422
+ if (typeof made?.id !== "string" || !INSTANCE_ID.test(made.id))
423
+ throw new Agent37Error(201, undefined, `POST /v1/instances answered no instance id: ${show(made?.id)}`);
424
+ return ok({ id: made.id });
425
+ }
426
+ /** GET /v1/instances/{id}; 404 is none (docs: instances/get). */
427
+ async get(id, ctx) {
428
+ try {
429
+ return ok(machineOf(await this.#rest("GET", this.#path(id), undefined, ctx), this.#declared));
430
+ }
431
+ catch (error) {
432
+ if (codeOf(error) === "not_found")
433
+ return ok(undefined);
434
+ throw error;
435
+ }
436
+ }
437
+ /**
438
+ * GET /v1/instances: the whole workspace in one answer, newest first, each the full instance object (docs:
439
+ * instances/list). Agent37 filters nothing, so the labels are matched here; an answer that says it has more is refused.
440
+ */
441
+ async list(labels, ctx) {
442
+ const listed = await this.#rest("GET", "/v1/instances", undefined, ctx);
443
+ if (!Array.isArray(listed.data))
444
+ throw new Agent37Error(200, undefined, "GET /v1/instances answered no data list");
445
+ if (listed.has_more === true || (listed.next_cursor !== undefined && listed.next_cursor !== null)) {
446
+ throw new Agent37Error(200, undefined, "GET /v1/instances answered a page with more after it, which Agent37 documents none of: this provider would miss machines");
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));
456
+ }
457
+ return ok(machines);
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);
476
+ }
477
+ /**
478
+ * An SSH session as root over the instance's tunnel, its handshake within ctx. A tunnel that fails to open, or closes
479
+ * before the SSH handshake, is opened again after a pause, TUNNEL_TRIES times in all within ctx: an instance fresh
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.
482
+ */
483
+ async #ssh(id, ctx) {
484
+ if (!INSTANCE_ID.test(id))
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();
490
+ try {
491
+ for (let attempt = 1;; attempt++) {
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
+ }
502
+ }
503
+ catch (error) {
504
+ givenUp.abort();
505
+ throw error;
506
+ }
507
+ finally {
508
+ bound.clear();
509
+ }
510
+ }
511
+ /**
512
+ * One tunnel and one SSH handshake over it. On a failure, or once stop aborts before the handshake is done, the
513
+ * WebSocket (opening or open), the stream and the client are dropped.
514
+ */
515
+ async #handshake(host, timeoutMs, stop) {
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;
557
+ }
558
+ /**
559
+ * One exec channel on client, opened within ms and signal, and its close: the exit-status, or -1 for an exit by
560
+ * signal or none. Its listeners go on inside ssh2's callback, as it opens: one read off the tunnel can hold the open,
561
+ * the exit and the close together (seen live), and they are emitted before an await after it would resume.
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
+ }
585
+ }
586
+ /**
587
+ * argv as root over SSH, one connection per process, under WRAPPER. stdout and stderr are the channel's, piped; with
588
+ * no stdin, end of file is sent at once, and end sends it later. wait answers once the channel closes, with the
589
+ * exit-status, or -1 for an exit by signal or none. kill ends the process group over a second channel of the same
590
+ * connection, then closes the channel and the connection, and drops the tunnel if the close does not come.
591
+ */
592
+ async exec(id, argv, { stdin }, ctx) {
593
+ const client = await this.#ssh(id, ctx);
594
+ const pidFile = `/tmp/.agentrun-exec-${randomBytes(8).toString("hex")}`;
595
+ let opened;
596
+ try {
597
+ opened = await this.#channel(client, shellLine(["sh", "-c", WRAPPER, pidFile, ...argv]), ctx.timeoutMs, ctx.signal, `the exec in ${id}`);
598
+ }
599
+ catch (error) {
600
+ client.destroy();
601
+ throw error;
602
+ }
603
+ const { channel } = opened;
604
+ const stdout = new PassThrough();
605
+ const stderr = new PassThrough();
606
+ channel.pipe(stdout);
607
+ channel.stderr.pipe(stderr);
608
+ let ended = !stdin;
609
+ if (!stdin)
610
+ channel.eof();
611
+ let closed = false;
612
+ // ssh2 closes every channel when the connection goes (utils.js, ChannelManager.cleanup), so the close is enough.
613
+ const exited = opened.closed.then((code) => {
614
+ closed = true;
615
+ client.end();
616
+ return code;
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.
671
+ }
672
+ }
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
+ }
698
+ /**
699
+ * An Agent37Provider from its options alone; it reads no environment. The key is options.apiKey and the SSH key
700
+ * options.sshKey, nowhere else (serve passes its AGENT37_API_KEY and AGENT37_SSH_KEY, the conformance module what it
701
+ * 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
+ */
703
+ export async function create(options) {
704
+ const { apiKey, sshKey, ssh2: given, ...rest } = options ?? {};
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");
709
+ // ssh2 is CommonJS: its Client is a named export of the module, and of its default.
710
+ const loaded = given ?? (await import(SSH2_PACKAGE));
711
+ const ssh2 = typeof loaded.Client === "function" ? loaded : loaded.default;
712
+ return new Agent37Provider({ ...rest, apiKey, sshKey, ssh2: ssh2 });
713
+ }
714
+ /** The conformance CLI's module for Agent37: its live switch, the run's cap, its template and the drifted twin. */
715
+ export const conformance = () => import("./conformance/agent37.js");
716
+ /**
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, for a sandbox; "agentrun-box", our box template with Xvfb, for a desktop.
719
+ */
720
+ export class Agent37Provider extends HostedProvider {
721
+ 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", maxLifetimeMs = DAY_MS, timeouts = {}, ...rest } = options ?? {};
723
+ if (typeof apiKey !== "string" || apiKey === "")
724
+ throw new Error("an Agent37 API key is required");
725
+ const privateKey = typeof sshKey === "string" ? pemOf(sshKey) : undefined;
726
+ if (privateKey === undefined)
727
+ throw new Error("options.sshKey must be the contents of an SSH private key (-----BEGIN ... PRIVATE KEY-----), never a path");
728
+ const problem = ssh2Problem(ssh2);
729
+ if (problem)
730
+ throw new Error(problem);
731
+ if (typeof fetcher !== "function")
732
+ throw new Error("options.fetch must be a function, as the global fetch is");
733
+ if (typeof WebSocket !== "function")
734
+ throw new Error("options.WebSocket must be a WebSocket class that takes headers, as Node's global one does");
735
+ let api;
736
+ try {
737
+ api = new URL(apiUrl);
738
+ }
739
+ catch {
740
+ throw new Error(`apiUrl must be an https URL such as ${DEFAULT_API_URL}, not ${JSON.stringify(apiUrl)}`);
741
+ }
742
+ if (api.protocol !== "https:" || api.search !== "" || api.hash !== "")
743
+ throw new Error(`apiUrl must be an https URL such as ${DEFAULT_API_URL}, not ${JSON.stringify(apiUrl)}`);
744
+ if (typeof proxyDomain !== "string" || !DOMAIN.test(proxyDomain))
745
+ throw new Error(`proxyDomain must be a host name such as ${DEFAULT_PROXY_DOMAIN}, not ${JSON.stringify(proxyDomain)}`);
746
+ if (type !== "vm" && type !== "default")
747
+ throw new Error(`type is vm or default, not ${JSON.stringify(type)}`);
748
+ if (region !== "us" && region !== "eu" && region !== "ap-south")
749
+ throw new Error(`region is us, eu or ap-south, not ${JSON.stringify(region)}`);
750
+ if (region !== "us" && type !== "vm")
751
+ throw new Error(`Agent37 runs type default in us alone: ${region} takes type vm`);
752
+ const host = new Agent37Host({ apiKey, sshKey: privateKey, ssh2, fetch: fetcher, WebSocket, apiUrl: api.href.replace(/\/+$/, ""), proxyDomain, type, region });
753
+ super(host, { ...rest, label: "Agent37", maxLifetimeMs, timeouts: { createMs: DEFAULT_CREATE_MS, requestMs: DEFAULT_REQUEST_MS, ...timeouts } });
754
+ }
755
+ }
756
+ /** The workspace a key reaches, in words, for the sweep's scope: the key's sha256 prefix, never the key. */
757
+ export function workspaceOf(apiKey, apiUrl = DEFAULT_API_URL) {
758
+ return `the Agent37 workspace of the key sha256:${createHash("sha256").update(apiKey, "utf8").digest("hex").slice(0, 12)} at ${apiUrl.replace(/\/+$/, "")}`;
759
+ }