@parcha/agentrun-computer 0.1.0-beta.37 → 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.
Files changed (93) hide show
  1. package/README.md +259 -203
  2. package/box/Dockerfile +18 -1
  3. package/box/README.md +13 -0
  4. package/box/build-agent37.mjs +8 -27
  5. package/box/build-daytona.py +2 -2
  6. package/box/build-e2b.mjs +41 -18
  7. package/box/recipe.mjs +43 -0
  8. package/dist/agent37-ssh.d.ts +89 -0
  9. package/dist/agent37-ssh.js +445 -0
  10. package/dist/agent37.d.ts +2 -63
  11. package/dist/agent37.js +104 -461
  12. package/dist/browserbase.d.ts +0 -6
  13. package/dist/browserbase.js +1 -5
  14. package/dist/client.d.ts +12 -3
  15. package/dist/client.js +39 -4
  16. package/dist/computerd-linux-amd64 +0 -0
  17. package/dist/computerd-linux-arm64 +0 -0
  18. package/dist/computerd.json +4 -0
  19. package/dist/conformance/cases/apps.d.ts +6 -0
  20. package/dist/conformance/cases/apps.js +18 -5
  21. package/dist/conformance/cases/isolation.d.ts +7 -5
  22. package/dist/conformance/cases/isolation.js +44 -14
  23. package/dist/conformance/cases/mount.js +1 -1
  24. package/dist/conformance/cli.js +66 -6
  25. package/dist/conformance/daytona.d.ts +9 -20
  26. package/dist/conformance/daytona.js +12 -21
  27. package/dist/conformance/exec-stream.d.ts +45 -0
  28. package/dist/conformance/exec-stream.js +486 -0
  29. package/dist/conformance/sweep.js +8 -8
  30. package/dist/conformance/types.d.ts +2 -2
  31. package/dist/create-requests.d.ts +1 -1
  32. package/dist/daytona.d.ts +20 -131
  33. package/dist/daytona.js +405 -1450
  34. package/dist/descriptor.d.ts +6 -1
  35. package/dist/descriptor.js +7 -0
  36. package/dist/descriptors/agent37.d.ts +1 -1
  37. package/dist/descriptors/agent37.js +1 -1
  38. package/dist/descriptors/daytona.d.ts +6 -5
  39. package/dist/descriptors/daytona.js +9 -5
  40. package/dist/descriptors/index.d.ts +4 -5
  41. package/dist/descriptors/shared.d.ts +1 -1
  42. package/dist/descriptors/shared.js +2 -2
  43. package/dist/desktop.d.ts +18 -4
  44. package/dist/desktop.js +89 -9
  45. package/dist/docker.d.ts +0 -6
  46. package/dist/docker.js +1 -5
  47. package/dist/drift.js +4 -4
  48. package/dist/e2b.d.ts +10 -128
  49. package/dist/e2b.js +130 -233
  50. package/dist/host.d.ts +106 -87
  51. package/dist/host.js +8 -1
  52. package/dist/hosted/process.d.ts +22 -8
  53. package/dist/hosted/process.js +75 -44
  54. package/dist/hosted/provider.d.ts +35 -21
  55. package/dist/hosted/provider.js +312 -261
  56. package/dist/hosted/rest.d.ts +66 -0
  57. package/dist/hosted/rest.js +121 -0
  58. package/dist/hosted/scripts.d.ts +8 -2
  59. package/dist/hosted/scripts.js +27 -2
  60. package/dist/hosted/values.d.ts +5 -0
  61. package/dist/hosted/values.js +8 -0
  62. package/dist/index.d.ts +1 -1
  63. package/dist/index.js +1 -1
  64. package/dist/kernel.d.ts +0 -6
  65. package/dist/kernel.js +1 -5
  66. package/dist/kinds.d.ts +3 -1
  67. package/dist/local-chrome.d.ts +0 -6
  68. package/dist/local-chrome.js +1 -5
  69. package/dist/modal.d.ts +7 -84
  70. package/dist/modal.js +50 -174
  71. package/dist/mount-archil.d.ts +8 -4
  72. package/dist/mount-archil.js +22 -11
  73. package/dist/mount.d.ts +10 -4
  74. package/dist/mount.js +8 -4
  75. package/dist/orgo.d.ts +0 -9
  76. package/dist/orgo.js +2 -9
  77. package/dist/phone-harness.d.ts +0 -6
  78. package/dist/phone-harness.js +0 -4
  79. package/dist/protocol.d.ts +4 -1
  80. package/dist/protocol.js +1 -0
  81. package/dist/provider.d.ts +2 -2
  82. package/dist/providers.d.ts +11 -12
  83. package/dist/screen-watch.js +34 -6
  84. package/dist/surface/api.d.ts +14 -2
  85. package/dist/surface/core.d.ts +16 -3
  86. package/dist/surface/core.js +95 -13
  87. package/dist/surface/outline.d.ts +2 -0
  88. package/dist/surface/outline.js +2 -1
  89. package/dist/surface/script.js +2 -0
  90. package/dist/ui-engine.js +19 -3
  91. package/package.json +2 -3
  92. package/dist/conformance/daytona-sweep.d.ts +0 -18
  93. package/dist/conformance/daytona-sweep.js +0 -126
package/dist/agent37.js CHANGED
@@ -8,15 +8,16 @@
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, randomBytes } from "node:crypto";
12
- import { Duplex, PassThrough } from "node:stream";
11
+ import { createHash } from "node:crypto";
12
+ import { Duplex } from "node:stream";
13
+ import { pemOf, SshExec, SshTunnelError } from "./agent37-ssh.js";
13
14
  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";
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";
20
21
  /** Not a literal, so no type checker or bundler resolves ssh2 from this package. */
21
22
  const SSH2_PACKAGE = "ssh2";
22
23
  const DEFAULT_API_URL = "https://api.agent37.com";
@@ -29,7 +30,6 @@ const AGENT37_TTYD_PORT = 7681;
29
30
  const INSTANCE_ID = /^[a-z0-9]{10}$/;
30
31
  /** A template name (cli.js:18), with an optional @<version> pin (docs: templates, pin a template version). */
31
32
  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
33
  const DAY_MS = 24 * 60 * 60_000;
34
34
  /** The instance shapes Agent37 makes, cpu and memory in GB (docs: instance-sizing): 4 vCPU is every type's ceiling. */
35
35
  const SHAPES = [
@@ -43,57 +43,14 @@ const MAX_CPUS = 4;
43
43
  const METADATA_MAX_BYTES = 4096;
44
44
  /** A VM boots inside the create's POST, which answers once it runs (docs: instances/create, Defaults). */
45
45
  const DEFAULT_CREATE_MS = 300_000;
46
- const DEFAULT_REQUEST_MS = 30_000;
47
46
  /** How much a tunnel may hold unsent before a write waits for it (the WebSocket's bufferedAmount). */
48
47
  const TUNNEL_HIGH_WATER = 1024 * 1024;
49
48
  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";
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;
97
54
  }
98
55
  /** The envelope's code: { error: { code } } on the Sandbox API, a flat { error: "<code>" } on transport errors (docs: errors). */
99
56
  function envelopeOf(body) {
@@ -122,25 +79,9 @@ const CODES = {
122
79
  rate_limited: "limit",
123
80
  };
124
81
  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
- }
82
+ const { level } = (error ?? {});
83
+ if (error instanceof HostError)
84
+ return error.code;
144
85
  // ssh2 names the stage that failed (lib/client.js): the instance's sshd refused the key, or the handshake timed out.
145
86
  if (level === "client-authentication")
146
87
  return "denied";
@@ -148,24 +89,7 @@ function codeOf(error) {
148
89
  return "timeout";
149
90
  return "vendor";
150
91
  }
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. */
92
+ /** Agent37's statuses (docs: instances/object, Statuses) as the adapter's states; failed, deleting and deleted are gone (get answers none for deleted). */
169
93
  function stateOf(status) {
170
94
  if (status === "running")
171
95
  return "running";
@@ -173,40 +97,23 @@ function stateOf(status) {
173
97
  return "starting";
174
98
  if (["stopping", "stopped", "sleeping"].includes(status))
175
99
  return "stopped";
176
- if (status === "failed")
177
- return "failed";
178
- if (status === "deleting" || status === "deleted")
179
- return "going";
100
+ if (["failed", "deleting", "deleted"].includes(status))
101
+ return "gone";
180
102
  return undefined;
181
103
  }
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);
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) {
197
106
  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 ?? {};
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");
200
111
  return {
201
112
  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 }),
113
+ labels: { ...(instance.metadata ?? {}) },
114
+ state: state ?? "gone",
115
+ ...(created ? { createdAt: created } : {}),
116
+ ...(why === undefined || (state !== undefined && state !== "gone") ? {} : { why }),
210
117
  };
211
118
  }
212
119
  /** The shape a request's cpus and memoryMb ask for, or undefined when they ask for none of Agent37's. */
@@ -224,7 +131,7 @@ function tunnelOf(ws, host) {
224
131
  read() { },
225
132
  write(chunk, _encoding, done) {
226
133
  if (ws.readyState !== 1)
227
- return done(new Agent37TunnelError(`the SSH tunnel to ${host} is closed`));
134
+ return done(new SshTunnelError(`the SSH tunnel to ${host} is closed`));
228
135
  try {
229
136
  ws.send(chunk);
230
137
  }
@@ -233,7 +140,7 @@ function tunnelOf(ws, host) {
233
140
  }
234
141
  const wait = () => {
235
142
  if (ws.readyState !== 1)
236
- done(new Agent37TunnelError(`the SSH tunnel to ${host} closed while it sent`));
143
+ done(new SshTunnelError(`the SSH tunnel to ${host} closed while it sent`));
237
144
  else if (ws.bufferedAmount <= TUNNEL_HIGH_WATER)
238
145
  done();
239
146
  else
@@ -274,7 +181,7 @@ function tunnelOf(ws, host) {
274
181
  resolve();
275
182
  });
276
183
  ws.addEventListener("error", (event) => {
277
- const error = new Agent37TunnelError(`the SSH tunnel to ${host} failed${open ? "" : " to open"}${event.message ? `: ${event.message}` : ""}`);
184
+ const error = new SshTunnelError(`the SSH tunnel to ${host} failed${open ? "" : " to open"}${event.message ? `: ${event.message}` : ""}`);
278
185
  if (!open)
279
186
  reject(error);
280
187
  else
@@ -282,7 +189,7 @@ function tunnelOf(ws, host) {
282
189
  });
283
190
  ws.addEventListener("close", ({ code, reason }) => {
284
191
  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`));
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`));
286
193
  else
287
194
  duplex.push(null);
288
195
  });
@@ -290,44 +197,32 @@ function tunnelOf(ws, host) {
290
197
  opened.catch(() => { });
291
198
  return { duplex, opened };
292
199
  }
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
200
  /** Agent37's instances as a MachineHost (../host.ts). */
313
201
  class Agent37Host {
314
- id = "agent37";
202
+ descriptor = AGENT37;
315
203
  facts;
316
204
  #apiKey;
317
- #sshKey;
318
- #ssh2;
319
- #fetch;
205
+ #ssh;
206
+ #client;
320
207
  #WebSocket;
321
- #apiUrl;
322
208
  #proxyDomain;
323
209
  #declared;
324
210
  constructor(options) {
325
211
  this.#apiKey = options.apiKey;
326
- this.#sshKey = options.sshKey;
327
- this.#ssh2 = options.ssh2;
328
- this.#fetch = options.fetch;
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
+ });
329
225
  this.#WebSocket = options.WebSocket;
330
- this.#apiUrl = options.apiUrl;
331
226
  this.#proxyDomain = options.proxyDomain;
332
227
  this.#declared = { type: options.type, region: options.region };
333
228
  const runtime = options.type === "vm" ? "vm" : "gvisor";
@@ -338,51 +233,38 @@ class Agent37Host {
338
233
  maxLifetimeMs: DAY_MS,
339
234
  arch: "amd64",
340
235
  vendorAgentPorts: [AGENT37_SSH_PORT, AGENT37_TTYD_PORT],
341
- networkReadBack: true,
342
- network: [...AGENT37.network],
343
- mounts: [...MOUNT],
344
- release: ["delete"],
236
+ // The box template has xfwm4 (box/build-agent37.mjs): the apps an agent opens are framed and focused.
237
+ windowManager: true,
345
238
  specFields: ["cpus", "memoryMb"],
239
+ labelRules: { maxBytes: METADATA_MAX_BYTES, measure: "json" },
346
240
  runtime: () => runtime,
347
241
  };
348
242
  }
349
243
  errorCode(error) {
350
244
  return codeOf(error);
351
245
  }
352
- /** One REST call: the key as a Bearer token, JSON both ways, bounded by ctx; a failure throws Agent37Error in Agent37's words. */
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. */
353
258
  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`);
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`);
374
263
  return parsed;
375
264
  }
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) {
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) {
384
267
  const refusals = [];
385
- const given = (typeof spec === "object" && spec !== null ? spec : {});
386
268
  const { image, cpus, memoryMb } = given;
387
269
  if (typeof image === "string" && image !== "" && !TEMPLATE.test(image)) {
388
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}"` });
@@ -393,12 +275,6 @@ class Agent37Host {
393
275
  else if ((cpus !== undefined || memoryMb !== undefined) && shapeOf(cpus, memoryMb) === undefined) {
394
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}` });
395
277
  }
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
278
  return refusals;
403
279
  }
404
280
  /**
@@ -420,280 +296,52 @@ class Agent37Host {
420
296
  public_ports: [],
421
297
  }, ctx);
422
298
  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 });
299
+ throw new HostError("vendor", `POST /v1/instances answered no instance id: ${show(made?.id)}`);
300
+ return { id: made.id };
425
301
  }
426
- /** GET /v1/instances/{id}; 404 is none (docs: instances/get). */
302
+ /** GET /v1/instances/{id}; 404 is not_found, which the adapter reads as none, as is status deleted (docs: instances/get). */
427
303
  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
- }
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);
436
307
  }
437
308
  /**
438
309
  * 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.
310
+ * instances/list). Agent37 filters nothing: the adapter matches the labels. An answer that says it has more is refused.
440
311
  */
441
312
  async list(labels, ctx) {
313
+ void labels;
442
314
  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");
315
+ if (!Array.isArray(listed?.data))
316
+ throw new HostError("vendor", "GET /v1/instances answered no data list");
445
317
  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);
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");
549
319
  }
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;
320
+ return listed.data.filter((instance) => typeof instance?.id === "string").map(machineOf);
557
321
  }
558
322
  /**
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.
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.
562
325
  */
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;
326
+ async delete(id, ctx) {
327
+ const path = `/v1/instances/${instanceId(id)}`;
596
328
  try {
597
- opened = await this.#channel(client, shellLine(["sh", "-c", WRAPPER, pidFile, ...argv]), ctx.timeoutMs, ctx.signal, `the exec in ${id}`);
329
+ await this.#rest("DELETE", path, undefined, { timeoutMs: ctx.timeoutMs });
598
330
  }
599
331
  catch (error) {
600
- client.destroy();
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);
601
335
  throw error;
602
336
  }
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
- });
337
+ this.#ssh.closeAll(id);
659
338
  }
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
- }
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);
672
344
  }
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
345
  }
698
346
  /**
699
347
  * An Agent37Provider from its options alone; it reads no environment. The key is options.apiKey and the SSH key
@@ -701,15 +349,11 @@ function ssh2Problem(ssh2) {
701
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.
702
350
  */
703
351
  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");
352
+ const { ssh2: given, ...rest } = options ?? {};
709
353
  // ssh2 is CommonJS: its Client is a named export of the module, and of its default.
710
354
  const loaded = given ?? (await import(SSH2_PACKAGE));
711
355
  const ssh2 = typeof loaded.Client === "function" ? loaded : loaded.default;
712
- return new Agent37Provider({ ...rest, apiKey, sshKey, ssh2: ssh2 });
356
+ return new Agent37Provider({ ...rest, ssh2: ssh2 });
713
357
  }
714
358
  /** The conformance CLI's module for Agent37: its live switch, the run's cap, its template and the drifted twin. */
715
359
  export const conformance = () => import("./conformance/agent37.js");
@@ -719,15 +363,14 @@ export const conformance = () => import("./conformance/agent37.js");
719
363
  */
720
364
  export class Agent37Provider extends HostedProvider {
721
365
  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 ?? {};
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 ?? {};
723
367
  if (typeof apiKey !== "string" || apiKey === "")
724
- throw new Error("an Agent37 API key is required");
368
+ throw new Error("options.apiKey, the Agent37 API key, is required: the provider reads no environment, so the caller passes it");
725
369
  const privateKey = typeof sshKey === "string" ? pemOf(sshKey) : undefined;
726
370
  if (privateKey === undefined)
727
371
  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);
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");
731
374
  if (typeof fetcher !== "function")
732
375
  throw new Error("options.fetch must be a function, as the global fetch is");
733
376
  if (typeof WebSocket !== "function")
@@ -750,7 +393,7 @@ export class Agent37Provider extends HostedProvider {
750
393
  if (region !== "us" && type !== "vm")
751
394
  throw new Error(`Agent37 runs type default in us alone: ${region} takes type vm`);
752
395
  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 } });
396
+ super(host, { ...rest, timeouts: { createMs: DEFAULT_CREATE_MS, ...timeouts } });
754
397
  }
755
398
  }
756
399
  /** The workspace a key reaches, in words, for the sweep's scope: the key's sha256 prefix, never the key. */