@parcha/agentrun-computer 0.1.0-beta.59 → 0.1.0-beta.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2194,8 +2194,9 @@ A live run must show:
2194
2194
  ```ts
2195
2195
  import { providerFor } from "@parcha/agentrun-computer";
2196
2196
 
2197
- // Both keys are the caller's to pass (serve's AGENT37_API_KEY and AGENT37_SSH_KEY); ssh2 (1.17.0) is an optional dependency.
2198
- const agent37 = await providerFor("agent37", { apiKey, sshKey });
2197
+ // The API key is the caller's to pass (serve's AGENT37_API_KEY); the SSH key is the provider's own unless the caller
2198
+ // gives one (sshKey, serve's AGENT37_SSH_KEY). ssh2 (1.17.0) is an optional dependency.
2199
+ const agent37 = await providerFor("agent37", { apiKey, secrets });
2199
2200
  const made = await agent37.create({ image: "agent37-base", lifetimeMs: 600_000, network: "none" }, { requestId: "r1#3" });
2200
2201
  ```
2201
2202
 
@@ -2207,16 +2208,54 @@ kind `linux`, on type `vm` (a VM with its own kernel, the default) or `default`
2207
2208
  `kind: "desktop"` it is a Linux desktop on `agentrun-box-<recipe hash>`, our public box image registered as a template
2208
2209
  of the key's workspace on its first run ([below](#the-desktop-agentrun-box)).
2209
2210
 
2210
- ### Two keys
2211
-
2212
- `create(options)` takes the workspace's API key as `options.apiKey` and the private half of an SSH key registered on
2213
- the same workspace (`POST /v1/ssh-keys`, or `agent37 ssh-keys add`) as `options.sshKey`, its contents, never a path:
2214
- the provider reads no file and no environment. A key pasted into Settings comes back on one line (a password field
2215
- drops line breaks), so the provider wraps a one-line key's body again before ssh2 reads it. A PKCS#8 key (PEM label
2216
- `PRIVATE KEY`), which ssh2 does not read, is converted first: RSA to PKCS#1, EC to SEC1, Ed25519 to OpenSSH's format. REST takes the API key as
2217
- `Authorization: Bearer <key>`; the SSH tunnel's edge takes the same key in `X-Agent37-Key` (npm `agent37@0.4.1`
2218
- `src/cli.js`, `wsHandshake` and `runTunnel`). Neither key appears in an error, a note or a label: the sweep's scope
2219
- names the API key by its sha256 prefix alone.
2211
+ ### The API key, and the SSH key
2212
+
2213
+ `create(options)` takes the workspace's API key as `options.apiKey`, the one key it needs: the provider reads no file
2214
+ and no environment. REST takes it as `Authorization: Bearer <key>`; the SSH tunnel's edge takes the same key in
2215
+ `X-Agent37-Key` (npm `agent37@0.4.1` `src/cli.js`, `wsHandshake` and `runTunnel`).
2216
+
2217
+ Every command then logs in to the instance's sshd with an SSH key registered on the workspace. By default it is the
2218
+ provider's own:
2219
+
2220
+ - On first use (the first `create` or exec, never at construction) the provider reads `ssh_key` from `options.secrets`,
2221
+ the store it is given (`get(name)` and `putIfAbsent(name, value)`, `ProviderSecrets`; its descriptor declares the
2222
+ option as `secrets`). With none there, it makes an Ed25519 key with `node:crypto` and hands its private half (PKCS#8
2223
+ PEM) to `putIfAbsent`, which keeps it only where no key is and answers the one kept. Of first uses racing on one
2224
+ store, in one process or in several, every one takes the key the store kept, and only that key is registered. In one
2225
+ process, every provider on the same store shares one making of the key and one registration of it on a workspace.
2226
+ Serve's store is the server's sealed one: the row `computer.agent37.ssh_key` in `sealed_keys`, sealed under
2227
+ `AGENTRUN_SEAL_KEY` (AES-256-GCM, as every saved key) and written only where no row is (`ON CONFLICT DO NOTHING`), one
2228
+ key per server store. Given no store (the conformance module, a caller of the package alone), the key lives in the
2229
+ process's memory, one shared by its providers until it exits.
2230
+ - So a server with no seal key (`AGENTRUN_SEAL_KEY` unset) makes and registers a new key each time it restarts. The
2231
+ old one stays on the workspace and counts toward its 20 keys until someone deletes it.
2232
+ - It registers the public half before its first instance, so the instance has it from boot: `GET /v1/ssh-keys` (which
2233
+ echoes no key) matched by fingerprint (`SHA256:`, as `ssh-keygen -l` prints it), else `POST /v1/ssh-keys` with the
2234
+ OpenSSH line and the name `agentrun-<first 12 hex of the key's SHA-256>`. A 409 `ssh_key_exists` is a registration
2235
+ another made, and taken as done. The registration is listed once per store and workspace in a process; the key is
2236
+ reused for every instance.
2237
+ - Agent37 takes at most 20 keys a workspace, and the 21st POST answers 400 `invalid_request`. A workspace at 20 is
2238
+ refused before any instance, code `limit`, in words that name the cap, the `agentrun-…` keys AgentRun registered
2239
+ (`DELETE /v1/ssh-keys/{id}`) and `AGENT37_SSH_KEY`. No key is deleted. A 400 to the POST is read as the cap only when
2240
+ its words say so or the workspace holds 20 keys when listed again; any other is code `vendor`, in Agent37's words.
2241
+ - Agent37 hands a new key to instances already running within about two minutes (docs: agents-api/ssh). A login an
2242
+ sshd refuses within three minutes of the key's registration is tried again every 2 s within the call's own bound; past
2243
+ them, it is `denied`, in words naming the instance, the key's fingerprint and its registration time, and the next call
2244
+ lists the workspace's keys again.
2245
+ - The registration is a note (`onNote`) naming the key by its fingerprint and name. The private half is in no call, note,
2246
+ error, label or log.
2247
+
2248
+ `options.sshKey` (serve's optional `AGENT37_SSH_KEY`) overrides it: the private half of a key already registered on the
2249
+ workspace (`POST /v1/ssh-keys`, or `agent37 ssh-keys add`), its contents, never a path. It is used as given, and nothing
2250
+ is made, stored or registered. A key pasted into Settings comes back on one line (a password field drops line breaks),
2251
+ so the provider wraps a one-line key's body again before ssh2 reads it. A PKCS#8 key (PEM label `PRIVATE KEY`), which
2252
+ ssh2 does not read, is converted first: RSA to PKCS#1, EC to SEC1, Ed25519 to OpenSSH's format. Neither key appears in
2253
+ an error, a note or a label: the sweep's scope names the API key by its sha256 prefix alone.
2254
+
2255
+ What this leaves: a key a server made stays registered after that server's store is gone (its seal key changed, or its
2256
+ store deleted), one more of the workspace's 20, and the next key is made afresh; so does each conformance process's.
2257
+ Two servers on one store that both make the first key at once can register two; the store keeps one, and the other
2258
+ stays on the workspace unused.
2220
2259
 
2221
2260
  ### The mapping
2222
2261
 
@@ -2282,12 +2321,13 @@ read back.
2282
2321
  ### Conformance on Agent37
2283
2322
 
2284
2323
  ```sh
2285
- AGENTRUN_COMPUTER_LIVE_AGENT37=1 COMPUTER_AGENT37_API_KEY=... COMPUTER_AGENT37_SSH_KEY="$(cat key)" \
2324
+ AGENTRUN_COMPUTER_LIVE_AGENT37=1 COMPUTER_AGENT37_API_KEY=... \
2286
2325
  npm run conformance -w @parcha/agentrun-computer -- --provider agent37
2287
2326
  ```
2288
2327
 
2289
2328
  The conformance module, `dist/conformance/agent37.js`, checks `AGENTRUN_COMPUTER_LIVE_AGENT37=1` first, then reads
2290
- `COMPUTER_AGENT37_API_KEY` (`apiKey`, required), `COMPUTER_AGENT37_SSH_KEY` (`sshKey`, required, the key's contents),
2329
+ `COMPUTER_AGENT37_API_KEY` (`apiKey`, required), `COMPUTER_AGENT37_SSH_KEY` (`sshKey`, optional, the contents of a key
2330
+ already on the workspace; unset, the run makes its own for its process and registers it, and it stays on the workspace),
2291
2331
  `COMPUTER_AGENT37_KIND` (`linux`, the default, or `desktop`), `COMPUTER_AGENT37_TEMPLATE` (the run's image, default
2292
2332
  `agent37-base`, or for kind `desktop` the box template `prepareImage()` registers), `COMPUTER_AGENT37_TYPE`, `COMPUTER_AGENT37_REGION`,
2293
2333
  `COMPUTER_AGENT37_API_URL`, `COMPUTER_AGENT37_DAEMON` (`daemonPath`), `COMPUTER_AGENT37_MAX_LIFETIME_MS` and
@@ -2425,6 +2465,18 @@ the protocol's methods in process over Orgo's REST API, as the phone harness and
2425
2465
  `"windows"` (`ORGO_WINDOWS_IMAGE`, Orgo's Windows Server 2019) or `"macos"` (`ORGO_MACOS_IMAGE`): the one the provider was
2426
2466
  built for.
2427
2467
 
2468
+ The Linux desktop makes one computer per request id. Its Orgo name begins with the request's name,
2469
+ `computer-<12 hex of sha256(requestId)>`, then the run's hash, the epoch and the deadline (`src/orgo-names.ts`). Before
2470
+ it makes a computer it lists the workspace's computers and takes the oldest whose name begins with the request's: one
2471
+ that runs with the same labels, image and sizes (its labels file) is answered, one of another spec or no longer
2472
+ running is refused `exists`, and one still being made is waited for. Two processes whose creates of one request
2473
+ both find nothing make two computers, so after Orgo's answer, and again once its computer is up, a create reads the
2474
+ workspace once more: where an older computer of the request is there (by `created_at`, then id), it deletes its own
2475
+ and answers the older, and the oldest keeps its own. A caller's signal that aborts one of those reads deletes the
2476
+ create's own computer (not under that signal) and the create is `aborted`. A name Orgo already holds (two creates in the same second) is
2477
+ answered the same way. The parked desktops name each computer at random, so a create retried there makes a second
2478
+ computer.
2479
+
2428
2480
  - **What each offers.** The protocol groups, by Orgo's calls:
2429
2481
  - `screen`: Orgo's screenshot (`response_format=base64&format=png`). A region is cropped in process. The live view
2430
2482
  polls it about once a second, scaled by Orgo past `maxWidth`.
@@ -2575,11 +2627,26 @@ call and the HTTP status alone, never the vendor's words. The calls are the prov
2575
2627
  its own `fetch`). A thrown error rides the failure as a hidden cause (`causeOf(result)`), not enumerable, so it is in no
2576
2628
  JSON.
2577
2629
 
2578
- Each create writes one more label beside the spec's, `agentrun.create` (`CREATE_LABEL`), with a value of its own. A
2579
- create whose outcome is unknown (its reply lost, cut short, answered 5xx or with no browser, or the caller's signal
2580
- aborted it) never sends a second create: it finds the browsers carrying that label as list does, in every state not
2581
- ended, under a signal of its own bounded at `RECOVER_MS`, releases each, and its failure says so. A 4xx refusal made
2582
- nothing, so nothing is looked for. The label is the provider's own: `check()` refuses it in a spec, and no list or attach shows it.
2630
+ Each create writes one more label beside the spec's, `agentrun.create` (`CREATE_LABEL`), whose value is the request's
2631
+ name, `computer-<12 hex of sha256(requestId)>`. Before it makes a browser, create lists the running and starting
2632
+ browsers with that label: one with the spec's labels is answered, so a retried create, in this process or another,
2633
+ makes no second browser, and one with other labels is refused `exists`; where it finds several, it takes the oldest (by
2634
+ the time the vendor made each, then id). Two processes whose creates of one request both find nothing make two
2635
+ browsers, so after the vendor's answer a create lists the label again: where an older browser of the request is
2636
+ there, it releases its own and answers the older, refused `exists` when the older has ended by then, and the oldest
2637
+ keeps its own. A caller's signal that aborts that listing releases the create's own browser (not under that signal)
2638
+ and the create is `aborted`. The browser's own options (viewport, stealth, profile) are not read back from the vendor, so a create
2639
+ from another process compares the labels alone. A browser released here, or one this provider answered that the vendor
2640
+ has ended on its own (its timeout), leaves its request refused `exists`: the provider keeps each request's browser id. A create whose outcome is unknown (its reply lost, cut short, answered 5xx or with no browser, or the caller's signal
2641
+ aborted it) never sends a second create: each POST also writes `agentrun.attempt` (`ATTEMPT_LABEL`), a random value of
2642
+ its own, and a lost create finds the browsers carrying its attempt label as list does, in every state not ended, under
2643
+ a signal of its own, releases each under it, and its failure says so; that request is then refused `exists`. Every
2644
+ release a create runs for itself (this one, the newer browser's, and the one after an abort) is bounded by the
2645
+ provider's `cleanupMs` option (default `RECOVER_MS`, 30 s), never by the caller's signal: one that does not finish in
2646
+ time fails the create in words that say the browser may still be running, and a retry is answered as above, never
2647
+ stuck behind it. Another create's browser of the same request, even one another process answered, carries another attempt
2648
+ label and is left running. A 4xx refusal made nothing, so nothing is looked for. Both labels are the provider's own:
2649
+ `check()` refuses them in a spec, and no list or attach shows them.
2583
2650
 
2584
2651
  The conformance CLI runs the browser case set for a provider of kind browser: the health cases, then `browser.*`
2585
2652
  (check past the cap, attach by id and by labels, list, CDP `Browser.getVersion` and `Runtime.evaluate` on a `data:`
@@ -2614,6 +2681,17 @@ removes its profile and every other file of it. `list()` and attach by labels fi
2614
2681
  `browser.json` in each browser's directory under the root (default `<tmpdir>/agentrun-local-browser-<uid>`, made 0700,
2615
2682
  refused when another user can write it). That file holds the labels and the deadline.
2616
2683
 
2684
+ A browser's id, and its directory's name, is its request's name, `computer-<12 hex of sha256(requestId)>`, and create
2685
+ makes that directory with `mkdir`, which one create alone wins, then writes `claim.json` in it (its process's pid and
2686
+ the time) before `browser.json`. A create that finds the directory there already, in this process or another on the
2687
+ same root, answers that browser once its Chrome answers, when its labels and network are the ones asked; one of another
2688
+ spec, past its deadline or whose supervisor has ended is refused `exists`. A directory with no `browser.json` whose
2689
+ claim names a process that is gone, or that is older than a create takes (the directory's own time where there is no
2690
+ claim), is a create that crashed: refused `exists` at once ("an earlier create of this request did not finish: create
2691
+ with a new request id"), never waited on past a create's time. A browser released
2692
+ here, or one this provider made that ended on its own (its deadline removed its directory), leaves its request refused
2693
+ `exists`.
2694
+
2617
2695
  Lifetime: each browser runs under a supervisor of its own (`local-supervisor.ts`), a small detached Node process. It
2618
2696
  ends Chrome and removes its files at the deadline, on release, or when Chrome exits, whatever became of the process
2619
2697
  that made the browser. So a run that crashes leaves no Chrome behind once its deadline passes. `list()` reads the
@@ -3480,7 +3558,8 @@ that, when set, names the image of every computer of the provider, as Daytona's
3480
3558
  (whether its machines dial the server: `dial` always, as Fly Machines' and Cloudflare's; `either`, as its `connect`
3481
3559
  option says, which one of its settings fills, as E2B's, Daytona's and Modal's; absent, never), `local`
3482
3560
  (a computer on this host), and
3483
- `ledger` (the option a provider's ledger fills). `connectOf(descriptor, options)` answers `dial` or `exec` for a provider
3561
+ `ledger` (the option a provider's ledger fills), and `secrets` (the option a store of the secrets the provider makes for
3562
+ itself fills, `ProviderSecrets`: Agent37's SSH key; serve passes its sealed store). `connectOf(descriptor, options)` answers `dial` or `exec` for a provider
3484
3563
  made with those options, without building it; its built host's `facts.connect` is the same answer, and a server reads
3485
3564
  it to say where its runs can't take a dial (a runner in a process of its own). `providerFor(id, options)` builds a provider by id from its options and
3486
3565
  refuses an id it does not hold, naming the ones it does. The provider file, `src/<vendor>.ts`, exports what a
package/dist/agent37.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ProviderSecrets } from "./descriptor.js";
1
2
  import { HostedProvider, type HostedOptions, type HostedTimeouts } from "./hosted/provider.js";
2
3
  import { type Ssh2Module } from "./hosted/ssh-exec.js";
3
4
  import type { CallContext } from "./provider.js";
@@ -55,9 +56,14 @@ export interface Agent37ProviderOptions extends Omit<HostedOptions, "maxLifetime
55
56
  apiKey: string;
56
57
  /**
57
58
  * The private half of an SSH key registered on the same workspace (POST /v1/ssh-keys), in OpenSSH or PEM form: its
58
- * contents, never a path. Every command reaches an instance over SSH as root with it.
59
+ * contents, never a path. Every command reaches an instance over SSH as root with it. Absent: the provider's own key.
59
60
  */
60
- sshKey: string;
61
+ sshKey?: string;
62
+ /**
63
+ * Where the provider's own SSH key is kept, with no sshKey: a server's sealed store (its descriptor's `secrets`), one
64
+ * key per store. Absent: this process's memory, one key shared by its providers until it exits.
65
+ */
66
+ secrets?: ProviderSecrets;
61
67
  /** The ssh2 package: the host's own, or anything with the same slice. */
62
68
  ssh2: Ssh2Module;
63
69
  /** The fetch every REST call goes through; default the global one. */
@@ -89,8 +95,9 @@ export interface Agent37Options extends Omit<Agent37ProviderOptions, "ssh2"> {
89
95
  export declare const AGENT37_SSH_PORT = 22022;
90
96
  /**
91
97
  * An Agent37Provider from its options alone; it reads no environment. The key is options.apiKey and the SSH key
92
- * options.sshKey, nowhere else (serve passes its AGENT37_API_KEY and AGENT37_SSH_KEY, the conformance module what it
93
- * reads), and ssh2 is the host's package unless given. Throws in words when an option is missing or wrong, never echoing a key.
98
+ * options.sshKey when given, nowhere else (serve passes its AGENT37_API_KEY, its AGENT37_SSH_KEY when set, and its sealed
99
+ * store as options.secrets; the conformance module what it reads), and ssh2 is the host's package unless given. Throws
100
+ * in words when an option is missing or wrong, never echoing a key.
94
101
  */
95
102
  export declare function create(options: Agent37Options): Promise<Agent37Provider>;
96
103
  /** The conformance CLI's module for Agent37: its live switch, the run's cap, its template and the drifted twin. */
package/dist/agent37.js CHANGED
@@ -5,7 +5,9 @@
5
5
  // ssh2 package (an optional dependency), of which this package names only the slice it uses (Ssh2Module) and imports nothing at load.
6
6
  // Agent37 has no SSH port on the internet: the SSH stream rides a binary WebSocket to wss://{id}-22022.agent37.app,
7
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,
8
+ // and the instance's sshd then takes the workspace's registered SSH keys (docs: agents-api/ssh): the one the caller gives
9
+ // (sshKey), else the provider's own, an ed25519 key it makes on first use, keeps in its store (secrets: a server's
10
+ // sealed one, else this process's memory) and registers with POST /v1/ssh-keys before its first create. Agent37's REST exec is one-shot (no stdin,
9
11
  // output only at its end), so it is not used. The rest of the computer is the shared machine-host adapter's
10
12
  // (./hosted/provider.ts). Every vendor fact here is cited in the README's Agent37 section.
11
13
  import { createHash } from "node:crypto";
@@ -14,10 +16,11 @@ import { boxImageRef, boxRecipeHash } from "./box-image.js";
14
16
  import { AGENT37, AGENT37_BASE_TEMPLATE } from "./descriptors/agent37.js";
15
17
  import { DEADLINE_LABEL, show } from "./drift.js";
16
18
  import { HostError } from "./host.js";
17
- import { orThrow } from "./hosted/process.js";
19
+ import { boundOf, codeOfError, orThrow } from "./hosted/process.js";
18
20
  import { httpsBase, jsonOf, rest } from "./hosted/rest.js";
19
21
  import { HostedProvider } from "./hosted/provider.js";
20
22
  import { pemOf, SshExec, SshTunnelError } from "./hosted/ssh-exec.js";
23
+ import { ed25519PublicOf, newEd25519 } from "./hosted/ssh-key.js";
21
24
  import { dateOf, DOMAIN, isWhole } from "./hosted/values.js";
22
25
  import { failFor, ok } from "./result.js";
23
26
  import { vendorSdk } from "./vendor-sdk.js";
@@ -59,6 +62,68 @@ const REGISTER_MS = 15 * 60_000;
59
62
  const TEMPLATE_READ_MS = 30_000;
60
63
  /** How often a template another registration is making is read again. */
61
64
  const TEMPLATE_POLL_MS = 1_000;
65
+ /** The name the provider's own SSH key is kept under in its store. */
66
+ const SSH_KEY_SECRET = "ssh_key";
67
+ /** Agent37's cap on one workspace's SSH keys: the 21st POST /v1/ssh-keys answers 400 invalid_request (docs: agents-api/ssh). */
68
+ const MAX_SSH_KEYS = 20;
69
+ /**
70
+ * How long after its registration a key may still be on its way to an instance made before it, so a login its sshd
71
+ * refuses is tried again: Agent37 hands a key to running instances "within about two minutes" (docs: agents-api/ssh),
72
+ * and a minute more is allowed. An instance made after the registration has the key from boot.
73
+ */
74
+ const KEY_SETTLE_MS = 3 * 60_000;
75
+ /** Each call of the key's registration: the listing, then the POST. */
76
+ const SSH_KEY_CALL_MS = 30_000;
77
+ /** Where a provider given no store keeps its own key: this process's memory, one key shared by its providers. */
78
+ const PROCESS_SECRETS = (() => {
79
+ const held = new Map();
80
+ return {
81
+ get: async (name) => held.get(name),
82
+ putIfAbsent: async (name, value) => {
83
+ if (!held.has(name))
84
+ held.set(name, value);
85
+ return held.get(name);
86
+ },
87
+ };
88
+ })();
89
+ /** Words in a 400 to POST /v1/ssh-keys that say it is the workspace's cap, not the key. */
90
+ const CAP_SAID = /\b(?:at most|maximum|limit|too many)\b/i;
91
+ /**
92
+ * Each store's own key, on its way or kept: one read, make and putIfAbsent for every provider on the store in this
93
+ * process, so of first uses together one key is made; dropped when it fails.
94
+ */
95
+ const KEPT = new WeakMap();
96
+ /**
97
+ * Each store's registrations of its key, by workspace and fingerprint, and when each was made (ms): one listing and at
98
+ * most one POST /v1/ssh-keys for every provider on the store in this process; dropped when one fails, and when the key
99
+ * is refused past KEY_SETTLE_MS (it may be gone from the workspace).
100
+ */
101
+ const REGISTERED = new WeakMap();
102
+ /** What `held` has under `key`, else `make()` put there: every caller waits on the one promise, dropped when it fails. */
103
+ function sharedBy(held, key, make) {
104
+ const known = held.get(key);
105
+ if (known !== undefined)
106
+ return known;
107
+ const making = make();
108
+ held.set(key, making);
109
+ making.catch(() => {
110
+ if (held.get(key) === making)
111
+ held.delete(key);
112
+ });
113
+ return making;
114
+ }
115
+ /**
116
+ * The ed25519 key `secrets` keeps (PKCS#8 PEM), else a new one kept there by putIfAbsent: of first uses racing on the
117
+ * store, in this process or another, every one answers the key the store kept, and only that one is registered.
118
+ */
119
+ async function keptKey(secrets) {
120
+ const kept = (await secrets.get(SSH_KEY_SECRET)) ?? (await secrets.putIfAbsent(SSH_KEY_SECRET, newEd25519()));
121
+ if (kept === undefined)
122
+ throw new HostError("vendor", "this server's own SSH key could not be kept in its store: it kept none, and read none back");
123
+ if (ed25519PublicOf(kept) === undefined)
124
+ throw new HostError("vendor", `this server's store holds a value as its own SSH key (${SSH_KEY_SECRET}) that is not an ed25519 private key: set AGENT37_SSH_KEY to the private half of a key on the workspace`);
125
+ return kept;
126
+ }
62
127
  /** 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. */
63
128
  function instanceId(id) {
64
129
  if (!INSTANCE_ID.test(id))
@@ -102,6 +167,8 @@ function codeOf(error) {
102
167
  return "timeout";
103
168
  return "vendor";
104
169
  }
170
+ /** A workspace at Agent37's cap of SSH keys, in words: what shows it there (`why`), and the two ways out. Nothing is deleted. */
171
+ const fullOf = (why) => new HostError("limit", `this server's own SSH key could not be registered: Agent37 takes at most ${MAX_SSH_KEYS} SSH keys a workspace, and ${why}. Delete keys the workspace no longer needs (those named agentrun-<hash> were registered by AgentRun; DELETE /v1/ssh-keys/{id}), or set AGENT37_SSH_KEY to the private half of a key already on it`);
105
172
  /** Agent37's statuses (docs: instances/object, Statuses) as the adapter's states; failed, deleting and deleted are gone (get answers none for deleted). */
106
173
  function stateOf(status) {
107
174
  if (status === "running")
@@ -220,9 +287,27 @@ class Agent37Host {
220
287
  #WebSocket;
221
288
  #proxyDomain;
222
289
  #declared;
290
+ #secrets;
291
+ #onNote;
292
+ /** The workspace a registration is made on: the API URL and the API key's SHA-256, never the key. */
293
+ #workspace;
294
+ /** The key every login takes: the given one from the start; the provider's own once kept and registered. */
295
+ #key;
296
+ /** The provider's own key on its way: kept and registered once, every call waiting on the same; dropped when it fails. */
297
+ #ready;
223
298
  constructor(options) {
224
299
  this.#apiKey = options.apiKey;
225
- this.#ssh = new SshExec({ ssh2: options.ssh2, loginOf: () => ({ username: "root", privateKey: options.sshKey }), tunnelOf: (id) => this.#tunnel(id) });
300
+ this.#key = options.sshKey === undefined ? undefined : { privateKey: options.sshKey };
301
+ this.#secrets = options.secrets;
302
+ this.#onNote = options.onNote;
303
+ this.#workspace = `${options.apiUrl} ${createHash("sha256").update(options.apiKey, "utf8").digest("hex")}`;
304
+ this.#ssh = new SshExec({
305
+ ssh2: options.ssh2,
306
+ loginOf: () => ({ username: "root", privateKey: this.#key?.privateKey }),
307
+ tunnelOf: (id) => this.#tunnel(id),
308
+ // The provider's own key may still be on its way to an instance made before its registration.
309
+ deniedUntil: () => (this.#key?.own ? this.#key.own.registeredAt + KEY_SETTLE_MS : 0),
310
+ });
226
311
  this.#client = rest({
227
312
  base: options.apiUrl,
228
313
  headers: () => ({ Authorization: `Bearer ${options.apiKey}`, Accept: "application/json" }),
@@ -261,9 +346,118 @@ class Agent37Host {
261
346
  ws.binaryType = "arraybuffer";
262
347
  return { ...tunnelOf(ws, host), host };
263
348
  }
264
- /** argv as root over SSH (hosted/ssh-exec.ts): one connection per instance through its tunnel, shared by its execs. */
349
+ /**
350
+ * argv as root over SSH (hosted/ssh-exec.ts): one connection per instance through its tunnel, shared by its execs,
351
+ * with the given key or the provider's own (#keyReady), within ctx. The provider's own key refused past KEY_SETTLE_MS
352
+ * after its registration is denied in words, and the next call reads the workspace's keys again (it may be gone).
353
+ */
265
354
  async exec(id, argv, ctx) {
266
- return this.#ssh.exec(instanceId(id), argv, ctx);
355
+ const machine = instanceId(id);
356
+ const end = Date.now() + ctx.timeoutMs;
357
+ const key = await this.#keyReady(ctx);
358
+ try {
359
+ return await this.#ssh.exec(machine, argv, { ...ctx, timeoutMs: Math.max(1, end - Date.now()) });
360
+ }
361
+ catch (error) {
362
+ if (key.own === undefined || codeOf(error) !== "denied")
363
+ throw error;
364
+ if (this.#key === key)
365
+ this.#ready = undefined;
366
+ key.own.forget();
367
+ const { fingerprint, registeredAt } = key.own;
368
+ throw new HostError("denied", `the sshd of Agent37 instance ${machine} refused this server's own SSH key ${fingerprint}, registered on the workspace at ${new Date(registeredAt).toISOString()}: Agent37 hands a key to running instances within about two minutes, and it was tried until ${KEY_SETTLE_MS / 60_000} minutes after its registration. Check that the key is still on the workspace (GET /v1/ssh-keys), or set AGENT37_SSH_KEY to the private half of a key that is`);
369
+ }
370
+ }
371
+ /**
372
+ * The key a login takes, within ctx: the given one, or the provider's own, kept in its store and registered on the
373
+ * workspace once (#ownKey), every call waiting on the same; one that failed is tried afresh by the next call.
374
+ */
375
+ async #keyReady(ctx) {
376
+ if (this.#key !== undefined && this.#key.own === undefined)
377
+ return this.#key;
378
+ if (this.#ready === undefined) {
379
+ const making = this.#ownKey();
380
+ this.#ready = making;
381
+ making.catch(() => {
382
+ if (this.#ready === making)
383
+ this.#ready = undefined;
384
+ });
385
+ }
386
+ const bound = boundOf(ctx.timeoutMs, ctx.signal, "the registration of this server's own SSH key on the Agent37 workspace");
387
+ try {
388
+ return await Promise.race([this.#ready, bound.promise]);
389
+ }
390
+ finally {
391
+ bound.clear();
392
+ }
393
+ }
394
+ /**
395
+ * The provider's own key, the one its store keeps (keptKey), registered on the workspace (#register): the key every
396
+ * login takes from then on. Both are the store's in this process, shared by every provider on it.
397
+ */
398
+ async #ownKey() {
399
+ const secrets = this.#secrets;
400
+ const pem = await sharedBy(KEPT, secrets, () => keptKey(secrets));
401
+ const pub = ed25519PublicOf(pem);
402
+ let registrations = REGISTERED.get(secrets);
403
+ if (registrations === undefined)
404
+ REGISTERED.set(secrets, (registrations = new Map()));
405
+ const at = `${this.#workspace} ${pub.fingerprint}`;
406
+ const registering = sharedBy(registrations, at, () => this.#register(pub));
407
+ const registeredAt = await registering;
408
+ const privateKey = pemOf(pem);
409
+ if (privateKey === undefined)
410
+ throw new HostError("vendor", `this server's own SSH key ${pub.fingerprint} could not be read as SSH reads it`);
411
+ const forget = () => {
412
+ if (registrations.get(at) === registering)
413
+ registrations.delete(at);
414
+ };
415
+ this.#key = { privateKey, own: { fingerprint: pub.fingerprint, registeredAt, forget } };
416
+ return this.#key;
417
+ }
418
+ /**
419
+ * The key on the workspace, and when it was registered (ms): GET /v1/ssh-keys, which echoes no key, matched by
420
+ * fingerprint; else POST /v1/ssh-keys { public_key, name agentrun-<its hash> }, where a 409 ssh_key_exists is a
421
+ * registration another made (docs: agents-api/ssh). A workspace at its 20 keys is refused in words, and no key of it
422
+ * is deleted. Throws a HostError, in Agent37's words.
423
+ */
424
+ async #register({ line, fingerprint, hash }) {
425
+ const name = `agentrun-${hash.slice(0, 12)}`;
426
+ const failed = (error) => {
427
+ const said = error instanceof Error ? error.message : String(error);
428
+ return new HostError(codeOfError(this, error), `this server's own SSH key ${fingerprint} could not be registered on the Agent37 workspace: ${said}`);
429
+ };
430
+ const listed = await this.#rest("GET", "/v1/ssh-keys", undefined, { timeoutMs: SSH_KEY_CALL_MS }).catch((error) => {
431
+ throw failed(error);
432
+ });
433
+ if (!Array.isArray(listed?.data))
434
+ throw failed(new HostError("vendor", "GET /v1/ssh-keys answered no data list"));
435
+ const keys = listed.data;
436
+ const found = keys.find((one) => one?.fingerprint === fingerprint);
437
+ if (found)
438
+ return typeof found.created === "number" && Number.isFinite(found.created) ? found.created * 1000 : Date.now();
439
+ if (keys.length >= MAX_SSH_KEYS)
440
+ throw fullOf(`the workspace holds ${keys.length}`);
441
+ let status;
442
+ try {
443
+ status = orThrow(await this.#client.call("POST", this.#client.url("/v1/ssh-keys"), { json: { public_key: `${line} ${name}`, name }, timeoutMs: SSH_KEY_CALL_MS, accept: (code) => (code >= 200 && code < 300) || code === 409 })).status;
444
+ }
445
+ catch (error) {
446
+ if (!(error instanceof HostError) || error.code !== "invalid")
447
+ throw failed(error);
448
+ // A 400 is the cap when its words say so, or when the workspace holds 20 keys now (taken since the listing);
449
+ // any other is Agent37's refusal of the key, in its words.
450
+ if (CAP_SAID.test(error.message))
451
+ throw fullOf(`Agent37 said so: ${error.message}`);
452
+ const again = await this.#rest("GET", "/v1/ssh-keys", undefined, { timeoutMs: SSH_KEY_CALL_MS }).catch(() => undefined);
453
+ const held = Array.isArray(again?.data) ? again.data.length : 0;
454
+ if (held >= MAX_SSH_KEYS)
455
+ throw fullOf(`the workspace holds ${held}`);
456
+ throw new HostError("vendor", `this server's own SSH key ${fingerprint} could not be registered on the Agent37 workspace: Agent37 refused it: ${error.message}`);
457
+ }
458
+ if (status !== 409)
459
+ this.#onNote?.({ computer: name, note: `this server's own SSH key ${fingerprint} was registered on the Agent37 workspace as ${name}` });
460
+ return Date.now();
267
461
  }
268
462
  /** One REST call, bounded by ctx: its JSON answer; a failure throws a HostError in Agent37's words. */
269
463
  async #rest(method, path, body, ctx) {
@@ -293,13 +487,17 @@ class Agent37Host {
293
487
  * instance's name, the labels as metadata, deny-all (or allow-all where the adapter asks egress: an Archil computer's root, or the
294
488
  * egress proxy of a network open or a list), auto-sleep off and
295
489
  * no public port. It answers once the instance runs (docs: instances/create, Defaults). req.backstopAt is left:
296
- * Agent37 has no delete or stop timer to set it on, so the janitor alone ends an instance.
490
+ * Agent37 has no delete or stop timer to set it on, so the janitor alone ends an instance. The provider's own SSH key
491
+ * is registered first (#keyReady), so the instance has it from boot.
297
492
  */
298
493
  async create(req, ctx) {
299
494
  const bytes = Buffer.byteLength(JSON.stringify(req.labels));
300
495
  if (bytes > METADATA_MAX_BYTES)
301
496
  throw new HostError("invalid", `Agent37 holds an instance's metadata to ${METADATA_MAX_BYTES} bytes as JSON, and this one's would be ${bytes}: give shorter labels`);
302
497
  const shape = req.cpus !== undefined || req.memoryMb !== undefined ? shapeOf(req.cpus, req.memoryMb) : undefined;
498
+ const end = Date.now() + ctx.timeoutMs;
499
+ await this.#keyReady(ctx);
500
+ ctx = { ...ctx, timeoutMs: Math.max(1, end - Date.now()) };
303
501
  const made = await this.#rest("POST", "/v1/instances", {
304
502
  template: req.image,
305
503
  type: this.#declared.type,
@@ -400,8 +598,9 @@ class Agent37Host {
400
598
  }
401
599
  /**
402
600
  * An Agent37Provider from its options alone; it reads no environment. The key is options.apiKey and the SSH key
403
- * options.sshKey, nowhere else (serve passes its AGENT37_API_KEY and AGENT37_SSH_KEY, the conformance module what it
404
- * reads), and ssh2 is the host's package unless given. Throws in words when an option is missing or wrong, never echoing a key.
601
+ * options.sshKey when given, nowhere else (serve passes its AGENT37_API_KEY, its AGENT37_SSH_KEY when set, and its sealed
602
+ * store as options.secrets; the conformance module what it reads), and ssh2 is the host's package unless given. Throws
603
+ * in words when an option is missing or wrong, never echoing a key.
405
604
  */
406
605
  export async function create(options) {
407
606
  const { ssh2: given, ...rest } = options ?? {};
@@ -443,12 +642,14 @@ export class Agent37Provider extends HostedProvider {
443
642
  }
444
643
  }
445
644
  constructor(options) {
446
- const { apiKey, sshKey, ssh2, fetch: fetcher = globalThis.fetch, WebSocket = globalThis.WebSocket, apiUrl = DEFAULT_API_URL, proxyDomain = DEFAULT_PROXY_DOMAIN, type = "vm", region = "us", timeouts = {}, ...rest } = options ?? {};
645
+ const { apiKey, sshKey, secrets = PROCESS_SECRETS, ssh2, fetch: fetcher = globalThis.fetch, WebSocket = globalThis.WebSocket, apiUrl = DEFAULT_API_URL, proxyDomain = DEFAULT_PROXY_DOMAIN, type = "vm", region = "us", timeouts = {}, ...rest } = options ?? {};
447
646
  if (typeof apiKey !== "string" || apiKey === "")
448
647
  throw new Error("options.apiKey, the Agent37 API key, is required: the provider reads no environment, so the caller passes it");
449
648
  const privateKey = typeof sshKey === "string" ? pemOf(sshKey) : undefined;
450
- if (privateKey === undefined)
649
+ if (sshKey !== undefined && privateKey === undefined)
451
650
  throw new Error("options.sshKey must be the contents of an SSH private key (-----BEGIN ... PRIVATE KEY-----), never a path");
651
+ if (typeof secrets?.get !== "function" || typeof secrets.putIfAbsent !== "function")
652
+ throw new Error("options.secrets must be a store of the provider's own secrets, with get and putIfAbsent, as a server's sealed one is");
452
653
  if (typeof ssh2?.Client !== "function")
453
654
  throw new Error("options.ssh2 must be the ssh2 package (its Client class): the host installs it, as it does e2b");
454
655
  if (typeof fetcher !== "function")
@@ -464,7 +665,7 @@ export class Agent37Provider extends HostedProvider {
464
665
  throw new Error(`region is us, eu or ap-south, not ${JSON.stringify(region)}`);
465
666
  if (region !== "us" && type !== "vm")
466
667
  throw new Error(`Agent37 runs type default in us alone: ${region} takes type vm`);
467
- const host = new Agent37Host({ apiKey, sshKey: privateKey, ssh2, fetch: fetcher, WebSocket, apiUrl: api, proxyDomain, type, region });
668
+ const host = new Agent37Host({ apiKey, sshKey: privateKey, secrets, onNote: rest.onNote, ssh2, fetch: fetcher, WebSocket, apiUrl: api, proxyDomain, type, region });
468
669
  super(host, { ...rest, timeouts: { createMs: DEFAULT_CREATE_MS, ...timeouts } });
469
670
  }
470
671
  }
package/dist/browser.d.ts CHANGED
@@ -51,29 +51,68 @@ export declare const carries: (held: unknown, labels: Record<string, string>) =>
51
51
  /** The labels a vendor's metadata holds, its string entries only. */
52
52
  export declare const labelsOf: (held: unknown) => Record<string, string>;
53
53
  /**
54
- * The label every create writes beside the spec's, a value of its own: a create whose reply is lost, or whose caller
55
- * cancels it, finds the browser it made by this label alone and releases it. The provider's own: check() refuses it in a
56
- * spec, and no list or attach shows it.
54
+ * The label every create writes beside the spec's, the name of its request (computerNameFor): a create retried, here or
55
+ * in another process, finds the browser the first made by this label (heldBrowser), and a create that made one finds
56
+ * the request's others by it (convergedBrowser). The provider's own: check() refuses it in a spec, and no list or
57
+ * attach shows it.
57
58
  */
58
59
  export declare const CREATE_LABEL = "agentrun.create";
59
- /** Labels without the provider's create label. */
60
+ /**
61
+ * The label each create's POST writes beside the create label, a random value of that POST's own (newAttempt): a create
62
+ * whose reply is lost, or whose caller cancels it, finds the browser its own POST made by this label alone and releases
63
+ * it, never another create's browser of the same request. The provider's own, as the create label is.
64
+ */
65
+ export declare const ATTEMPT_LABEL = "agentrun.attempt";
66
+ /** A create attempt's own value of ATTEMPT_LABEL. */
67
+ export declare const newAttempt: () => string;
68
+ /** Labels without the provider's own, the create and attempt labels. */
60
69
  export declare const withoutCreateLabel: (labels: Record<string, string>) => Record<string, string>;
61
- /** A create label's value: 16 hex digits, fresh per create. */
62
- export declare const createLabelValue: () => string;
70
+ /** A browser a create label found: its id, when the vendor made it (an ISO time, where it says), and its labels. */
71
+ export interface HeldBrowser {
72
+ id: string;
73
+ createdAt?: string;
74
+ labels: Record<string, string>;
75
+ }
76
+ /**
77
+ * The order a request's browsers are read in (heldBrowser, a create's converge): the oldest first, by the time the
78
+ * vendor made each, then by id. The same browsers give the same order in every process.
79
+ */
80
+ export declare const oldestBrowserFirst: (a: HeldBrowser, b: HeldBrowser) => number;
81
+ /**
82
+ * The browser a vendor holds for a create's request (provider.md, Idempotent create), among those its create label finds
83
+ * (found, each with its labels as list shows them): undefined when there is none, so create makes it, else the oldest
84
+ * (oldestBrowserFirst), with how its labels differ from the ones asked (labelsDiffer; empty when it is this spec's). A
85
+ * browser's own options are not read back from the vendor, so a create from another process compares the labels alone.
86
+ */
87
+ export declare function heldBrowser(asked: Record<string, string>, found: ReadonlyArray<HeldBrowser>): {
88
+ id: string;
89
+ differ: string[];
90
+ } | undefined;
91
+ /**
92
+ * Where a create that made a browser stands among its request's (provider.md, Idempotent create). Two creates of one
93
+ * request in two processes can both find no browser by the create label and both make one: CreateRequests holds within
94
+ * one provider alone. So after the vendor's answer the label is listed again (listed; mine, made just now, added when it
95
+ * is not listed yet): "mine" when mine is the oldest, so the create answers it; else the older, which the create
96
+ * answers in place of its own once it has released its own. Every process picks the same one from the same listing.
97
+ */
98
+ export declare function convergedBrowser(listed: ReadonlyArray<HeldBrowser>, mine: HeldBrowser): "mine" | HeldBrowser;
63
99
  /**
64
100
  * Whether a create that threw may still have made a browser: anything but the vendor's own 4xx answer (a refusal, which
65
101
  * makes nothing). A request not answered, aborted, cut short, or answered 5xx or with a body that is no browser may
66
102
  * have been admitted.
67
103
  */
68
104
  export declare function createUncertain(error: unknown): boolean;
69
- /** How long a lost create's browser is looked for, in all, and how often: a vendor may list it a moment late. */
105
+ /**
106
+ * How long a lost create's browser is looked for and released, in all, and how often: a vendor may list it a moment
107
+ * late. Also the default bound of every other release a create runs for itself (a provider's cleanupMs).
108
+ */
70
109
  export declare const RECOVER_MS = 30000;
71
110
  /**
72
- * After a create whose outcome is unknown: the browsers carrying its create label, found under a signal of the
73
- * recovery's own (the caller's may be what ended the create), each released. The words say what became of them, for the
74
- * create's failure; they never carry a URL.
111
+ * After a create whose outcome is unknown: the browsers carrying its create label, found and released under a signal
112
+ * of the recovery's own, `ms` in all (the caller's may be what ended the create). The words say what became of them, for
113
+ * the create's failure; they never carry a URL.
75
114
  */
76
- export declare function recoverCreate(what: string, find: (signal: AbortSignal) => Promise<Result<string[]>>, release: (id: string) => Promise<Result<void>>, sleep: (ms: number) => Promise<void>): Promise<string>;
115
+ export declare function recoverCreate(what: string, find: (signal: AbortSignal) => Promise<Result<string[]>>, release: (id: string, signal: AbortSignal) => Promise<Result<void>>, sleep: (ms: number) => Promise<void>, ms?: number): Promise<string>;
77
116
  /**
78
117
  * The checks every browser provider makes before a vendor call: the image is chromium, the lifetime is within the
79
118
  * vendor's cap (and at least min), the network is open, the labels are ones the vendor's metadata holds, the session's
@@ -93,6 +132,12 @@ export declare function browserClient(hello: HelloResult, alive: (signal?: Abort
93
132
  * up to confirm.polls times. Done means the vendor says it no longer runs, not that the request was sent; a session the
94
133
  * vendor no longer knows ("gone") is released. A session still running is a failure carrying the request's own error.
95
134
  */
135
+ /**
136
+ * A release a create runs for itself (its caller gone, or its browser the newer of the request's two), under a signal of
137
+ * its own that ends after `ms`, never the caller's: one that does not finish by then is a timeout that says the browser
138
+ * may still be running.
139
+ */
140
+ export declare function boundedRelease(what: string, id: string, ms: number, release: (signal: AbortSignal) => Promise<Result<void>>): Promise<Result<void>>;
96
141
  export declare function releaseConfirmed(o: {
97
142
  request: () => Promise<Result<"gone" | "asked">>;
98
143
  running: () => Promise<Result<boolean>>;