@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.
@@ -75,11 +75,17 @@ export interface SshExecOptions {
75
75
  /** The login to machine id. */
76
76
  loginOf: (id: string) => SshLogin;
77
77
  tunnelOf: SshTunnelOf;
78
+ /**
79
+ * Until when (ms since the epoch) a login machine id's sshd refuses is tried again, every DENIED_RETRY_MS within the
80
+ * call's bound: a key the vendor is still handing its machines (Agent37's, minutes after its registration). Absent,
81
+ * or past: a refused login fails at once.
82
+ */
83
+ deniedUntil?: (id: string) => number;
78
84
  }
79
85
  /** MachineHost.exec over SSH: argv as the host's login, as channels on one connection per machine, shared by its execs. */
80
86
  export declare class SshExec {
81
87
  #private;
82
- constructor({ ssh2, loginOf, tunnelOf }: SshExecOptions);
88
+ constructor({ ssh2, loginOf, tunnelOf, deniedUntil }: SshExecOptions);
83
89
  /** Ends every connection to machine id, channels and all: the vendor calls it once the machine is deleted. */
84
90
  closeAll(id: string): void;
85
91
  /**
@@ -7,6 +7,7 @@ import { createPrivateKey, randomBytes } from "node:crypto";
7
7
  import { PassThrough } from "node:stream";
8
8
  import { boundOf, redact } from "./process.js";
9
9
  import { PID_WRAPPER, pidKill, pidStderr, shellLine } from "./scripts.js";
10
+ import { sshString } from "./ssh-key.js";
10
11
  /**
11
12
  * ssh2's keepalive, which also keeps the edge from seeing an idle tunnel (the CLI's ServerAliveInterval is 60 s, cli.js:32).
12
13
  * ssh2 pings every KEEPALIVE_MS and ends the connection at the tick after KEEPALIVE_COUNT_MAX pings went unanswered
@@ -47,20 +48,24 @@ const isBound = (error) => {
47
48
  const name = error?.name;
48
49
  return name === "TimeoutError" || name === "AbortError";
49
50
  };
51
+ /** The pause between two logins an sshd refused, while deniedUntil says the key may still reach it. */
52
+ const DENIED_RETRY_MS = 2_000;
50
53
  /** MachineHost.exec over SSH: argv as the host's login, as channels on one connection per machine, shared by its execs. */
51
54
  export class SshExec {
52
55
  #ssh2;
53
56
  #loginOf;
54
57
  #tunnelOf;
58
+ #deniedUntil;
55
59
  /**
56
60
  * The SSH connections to each machine, opening, open, or done and still held, until each ends: one, and a second
57
61
  * past CHANNELS_PER_CONNECTION channels. A done one takes no new channel; closeAll ends them all.
58
62
  */
59
63
  #links = new Map();
60
- constructor({ ssh2, loginOf, tunnelOf }) {
64
+ constructor({ ssh2, loginOf, tunnelOf, deniedUntil }) {
61
65
  this.#ssh2 = ssh2;
62
66
  this.#loginOf = loginOf;
63
67
  this.#tunnelOf = tunnelOf;
68
+ this.#deniedUntil = deniedUntil;
64
69
  }
65
70
  /** Ends every connection to machine id, channels and all: the vendor calls it once the machine is deleted. */
66
71
  closeAll(id) {
@@ -71,24 +76,31 @@ export class SshExec {
71
76
  * An SSH session as the host's login over the machine's tunnel, its handshake within ctx. A tunnel that fails to
72
77
  * open, or closes before the SSH handshake, is opened again after a pause, TUNNEL_TRIES times in all within ctx: an
73
78
  * instance fresh from its create can refuse the first (seen live once in eight creates, the daemon's upload
74
- * refused). Nothing has run before a handshake, so a retry repeats nothing. A refused key or a handshake past its
75
- * bound is not retried.
79
+ * refused). Nothing has run before a handshake, so a retry repeats nothing. A refused key is tried again only while
80
+ * deniedUntil says it may still reach the machine; a handshake past its bound is not retried.
76
81
  */
77
82
  async #ssh(id, ctx) {
78
83
  const bound = boundOf(ctx.timeoutMs, ctx.signal, `the SSH connection to ${id}`);
79
84
  // Ends the handshake in flight when this call gives up on it (its bound passed, or the caller aborted).
80
85
  const givenUp = new AbortController();
81
86
  try {
82
- for (let attempt = 1;; attempt++) {
87
+ for (let attempt = 1;;) {
88
+ let pause;
83
89
  try {
84
90
  return await Promise.race([this.#handshake(id, ctx.timeoutMs, givenUp.signal), bound.promise]);
85
91
  }
86
92
  catch (error) {
87
- const early = error instanceof SshTunnelError || error.level === "client-socket";
88
- if (!early || attempt >= TUNNEL_TRIES)
93
+ const level = error.level;
94
+ const left = level === "client-authentication" ? (this.#deniedUntil?.(id) ?? 0) - Date.now() : 0;
95
+ const early = error instanceof SshTunnelError || level === "client-socket";
96
+ if (left > 0)
97
+ pause = Math.min(DENIED_RETRY_MS, left);
98
+ else if (early && attempt < TUNNEL_TRIES)
99
+ pause = TUNNEL_RETRY_MS * 2 ** (attempt++ - 1);
100
+ else
89
101
  throw error;
90
102
  }
91
- await Promise.race([new Promise((resolve) => setTimeout(resolve, TUNNEL_RETRY_MS * 2 ** (attempt - 1))), bound.promise]);
103
+ await Promise.race([new Promise((resolve) => setTimeout(resolve, pause)), bound.promise]);
92
104
  }
93
105
  }
94
106
  catch (error) {
@@ -474,13 +486,6 @@ function fromPkcs8(pem) {
474
486
  return openSshEd25519(key);
475
487
  return undefined;
476
488
  }
477
- /** An SSH string (RFC 4251 §5): its uint32 length, then its bytes. */
478
- const sshString = (bytes) => {
479
- const body = Buffer.from(bytes);
480
- const length = Buffer.alloc(4);
481
- length.writeUInt32BE(body.length);
482
- return Buffer.concat([length, body]);
483
- };
484
489
  /**
485
490
  * An Ed25519 private key in OpenSSH's own format, unencrypted (openssh-portable PROTOCOL.key; sshkey.c writes it so):
486
491
  * "openssh-key-v1\0", cipher "none", KDF "none", empty KDF options, the key count 1, the public key blob (RFC 8709 §4:
@@ -0,0 +1,18 @@
1
+ /** An SSH string (RFC 4251 §5): its uint32 length, then its bytes. */
2
+ export declare const sshString: (bytes: Uint8Array | string) => Buffer;
3
+ /** A new ed25519 private key, as PKCS#8 PEM. */
4
+ export declare function newEd25519(): string;
5
+ /** The public half of an ed25519 key, as SSH reads it. */
6
+ export interface SshPublicKey {
7
+ /** One OpenSSH line, "ssh-ed25519 <blob in base64>", with no comment. */
8
+ readonly line: string;
9
+ /** "SHA256:" and the blob's SHA-256 in base64 with no padding (ssh-keygen -l). */
10
+ readonly fingerprint: string;
11
+ /** The blob's SHA-256 in hex: a name made from it says which key without being one. */
12
+ readonly hash: string;
13
+ }
14
+ /**
15
+ * The public half of `pem`, a PKCS#8 ed25519 private key, or undefined when it is not one. The blob is RFC 8709 §4's:
16
+ * the string "ssh-ed25519", then the 32-byte public key, each length-prefixed.
17
+ */
18
+ export declare function ed25519PublicOf(pem: string): SshPublicKey | undefined;
@@ -0,0 +1,36 @@
1
+ // An SSH key a provider makes for itself: ed25519, its private half as PKCS#8 PEM (what node:crypto writes, and what
2
+ // pemOf in ./ssh-exec.ts turns into the OpenSSH form ssh2 reads), its public half as one OpenSSH line, and that line's
3
+ // fingerprint as OpenSSH and the vendors print it.
4
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync } from "node:crypto";
5
+ /** An SSH string (RFC 4251 §5): its uint32 length, then its bytes. */
6
+ export const sshString = (bytes) => {
7
+ const body = Buffer.from(bytes);
8
+ const length = Buffer.alloc(4);
9
+ length.writeUInt32BE(body.length);
10
+ return Buffer.concat([length, body]);
11
+ };
12
+ /** A new ed25519 private key, as PKCS#8 PEM. */
13
+ export function newEd25519() {
14
+ return generateKeyPairSync("ed25519").privateKey.export({ type: "pkcs8", format: "pem" });
15
+ }
16
+ /**
17
+ * The public half of `pem`, a PKCS#8 ed25519 private key, or undefined when it is not one. The blob is RFC 8709 §4's:
18
+ * the string "ssh-ed25519", then the 32-byte public key, each length-prefixed.
19
+ */
20
+ export function ed25519PublicOf(pem) {
21
+ let x;
22
+ try {
23
+ const key = createPrivateKey(pem);
24
+ if (key.asymmetricKeyType !== "ed25519")
25
+ return undefined;
26
+ x = createPublicKey(key).export({ format: "jwk" }).x;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ if (typeof x !== "string")
32
+ return undefined;
33
+ const blob = Buffer.concat([sshString("ssh-ed25519"), sshString(Buffer.from(x, "base64url"))]);
34
+ const digest = createHash("sha256").update(blob).digest();
35
+ return { line: `ssh-ed25519 ${blob.toString("base64")}`, fingerprint: `SHA256:${digest.toString("base64").replace(/=+$/, "")}`, hash: digest.toString("hex") };
36
+ }
package/dist/index.d.ts CHANGED
@@ -19,7 +19,7 @@ export { DEFAULT_DOCKER_IMAGE, DOCKER_BASE, DOCKER_RECIPE, DOCKER_RECIPE_HAS, en
19
19
  export { ADB_ENV_NAMES, adbEnv, BASE_ENV_NAMES, CHROME_ENV_NAMES, childEnv, chromeEnv, DOCKER_ENV_NAMES, dockerEnv, type HostEnv } from "./child-env.js";
20
20
  export { containerSigns, EGRESS_IMAGE, EGRESS_LABEL, EGRESS_MOUNT, EGRESS_SOCKET } from "./docker/egress.js";
21
21
  export { ARCHIL_HELPER, ARCHIL_SYNC_SOCKET, ARCHIL_TOOL_UID, ARCHIL_TOOL_USER, ARCHIL_VERSION, type ArchilMount, type ArchilEgress, type ArchilMountOptions, type ArchilRoot, type ProviderNote, archilEgressOf, archilLabels, archilMount, archilReadBack, archilRefusals, archilRelease, archilSync, claimEpoch, helperSha256, MOUNT_LABEL, mountDrift, mountWords, type RecordedFolder, type RecordedSource, readMount, recordedFolder, recordedMount, SYNC_LABELS, syncingClient, } from "./mount-archil.js";
22
- export { type BrowserComputerProvider, type BrowserDownloads, type BrowserFile, type BrowserProfiles, type BrowserSessionUsage, browserSpecRefusals, type BrowserStream, isBrowserProvider, BrowserVendorError, CREATE_LABEL, causeOf, memoryUrls, RECOVER_MS, type ReleaseConfirm, type RestReply, type UrlStore, } from "./browser.js";
22
+ export { type BrowserComputerProvider, type BrowserDownloads, type BrowserFile, type BrowserProfiles, type BrowserSessionUsage, browserSpecRefusals, type BrowserStream, isBrowserProvider, BrowserVendorError, CREATE_LABEL, ATTEMPT_LABEL, causeOf, memoryUrls, RECOVER_MS, type ReleaseConfirm, type RestReply, type UrlStore, } from "./browser.js";
23
23
  export { CHROME_ENV, CHROME_FLAGS, checkChrome, chromeFence, findChrome, killTree, NO_CHROME } from "./chrome.js";
24
24
  export { DAEMON_IN_COMPUTER, helloDrift, type HelloExpected } from "./drift.js";
25
25
  export { drift, hostOf, inspectDrift, mountOf, networkOf, type DockerHost, type DockerInfo, type DockerInspect, type DriftExpected } from "./docker/inspect.js";
@@ -27,7 +27,7 @@ export { type ReleasedOlder, releaseOlder, sweep, type SweepOptions, type Swept
27
27
  export { EPOCH_LABEL, epochOf, epochProblem, IDLE_TTL_LABEL, OWNER_LABEL, OWNER_SERVER_LABEL, ownerFilter, ownerLabels, ownerOf, RUN_HASH_LABEL, RUN_LABEL, runHash, runLabels, runProblem } from "./labels.js";
28
28
  export { waitUntil, type WaitOptions } from "./wait.js";
29
29
  export { type BuiltinProviderId, type ConformanceModule, descriptorOf, isProviderId, type ProviderEnv, providerFor, type ProviderId, providerIds, type ProviderModule, providerModule, type ProviderOptions, providers, } from "./providers.js";
30
- export { connectOf, type DescriptorKey, type DescriptorSetting, defineProvider, descriptorProblems, type HostCommand, mountsOf, type ParkedConfiguration, type ProviderDescriptor } from "./descriptor.js";
30
+ export { connectOf, type DescriptorKey, type DescriptorSetting, defineProvider, descriptorProblems, type HostCommand, mountsOf, type ParkedConfiguration, type ProviderDescriptor, type ProviderSecrets } from "./descriptor.js";
31
31
  export { AGENT37, AGENT37_BASE_TEMPLATE, BOXD, BOXD_DEFAULT_IMAGE, BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, type DaytonaGpuSnapshot, DESCRIPTORS, daytonaGpu, daytonaGpuSnapshot, DOCKER, E2B, GROUNDBOX, GROUNDBOX_OWN_IMAGE, KERNEL, LOCAL, MODAL, MORPH, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, SMOLCLOUD, } from "./descriptors/index.js";
32
32
  export type { PhoneLedger, PhoneLedgerEntry } from "./phone-harness.js";
33
33
  export { configurationOf, entryOf, imagesOf, type KindCapabilities, kindOf, kindServed, type ProviderEntry, PROVIDERS, serves, servingRefusals, type TestConnection, type TestConnectionOptions, } from "./kinds.js";
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ export { DEFAULT_DOCKER_IMAGE, DOCKER_BASE, DOCKER_RECIPE, DOCKER_RECIPE_HAS, en
21
21
  export { ADB_ENV_NAMES, adbEnv, BASE_ENV_NAMES, CHROME_ENV_NAMES, childEnv, chromeEnv, DOCKER_ENV_NAMES, dockerEnv } from "./child-env.js";
22
22
  export { containerSigns, EGRESS_IMAGE, EGRESS_LABEL, EGRESS_MOUNT, EGRESS_SOCKET } from "./docker/egress.js";
23
23
  export { ARCHIL_HELPER, ARCHIL_SYNC_SOCKET, ARCHIL_TOOL_UID, ARCHIL_TOOL_USER, ARCHIL_VERSION, archilEgressOf, archilLabels, archilMount, archilReadBack, archilRefusals, archilRelease, archilSync, claimEpoch, helperSha256, MOUNT_LABEL, mountDrift, mountWords, readMount, recordedFolder, recordedMount, SYNC_LABELS, syncingClient, } from "./mount-archil.js";
24
- export { browserSpecRefusals, isBrowserProvider, BrowserVendorError, CREATE_LABEL, causeOf, memoryUrls, RECOVER_MS, } from "./browser.js";
24
+ export { browserSpecRefusals, isBrowserProvider, BrowserVendorError, CREATE_LABEL, ATTEMPT_LABEL, causeOf, memoryUrls, RECOVER_MS, } from "./browser.js";
25
25
  // Local Chrome's provider class is on its provider id's subpath (@parcha/agentrun-computer/local-chrome), as every
26
26
  // provider's is; the Chrome helpers it runs on are not a provider and stay here.
27
27
  export { CHROME_ENV, CHROME_FLAGS, checkChrome, chromeFence, findChrome, killTree, NO_CHROME } from "./chrome.js";
package/dist/kernel.d.ts CHANGED
@@ -15,6 +15,8 @@ export interface KernelBrowser {
15
15
  /** The live view's URL: a secret. */
16
16
  browser_live_view_url?: unknown;
17
17
  tags?: unknown;
18
+ /** When Kernel made the browser. */
19
+ created_at?: unknown;
18
20
  deleted_at?: unknown;
19
21
  }
20
22
  /**
@@ -39,6 +41,12 @@ export interface KernelProviderOptions {
39
41
  fetch?: typeof fetch;
40
42
  confirm?: ReleaseConfirm;
41
43
  sleep?: (ms: number) => Promise<void>;
44
+ /**
45
+ * How long, in all, a cleanup a create runs for itself may take: the release of the browser its POST made once its
46
+ * caller is gone, or once another create of the request made one first, and the search and release after a lost
47
+ * reply. Default RECOVER_MS. The caller's signal never cuts it short.
48
+ */
49
+ cleanupMs?: number;
42
50
  }
43
51
  /** Computers that are Kernel browsers. */
44
52
  export declare class KernelProvider implements ComputerProvider, BrowserComputerProvider {
@@ -46,7 +54,7 @@ export declare class KernelProvider implements ComputerProvider, BrowserComputer
46
54
  readonly id = "kernel";
47
55
  readonly version: string;
48
56
  readonly profiles: BrowserProfiles;
49
- constructor({ apiKey, apiUrl, env, fetch: fetcher, confirm, sleep }: KernelProviderOptions);
57
+ constructor({ apiKey, apiUrl, env, fetch: fetcher, confirm, sleep, cleanupMs }: KernelProviderOptions);
50
58
  /**
51
59
  * A browser: Kernel ends a browser after its idle timeout (lifetime vendor), at most 72 h; it reaches the open web;
52
60
  * each browser is its own VM. Kernel's replays and file APIs are not wired here, so recordings and downloads are not
@@ -56,9 +64,11 @@ export declare class KernelProvider implements ComputerProvider, BrowserComputer
56
64
  capabilities(): ComputerCapabilities;
57
65
  check(spec: ComputerSpec): Refusal[];
58
66
  /**
59
- * Makes a browser at most once, with the lifetime as its idle timeout in whole seconds and the labels as its tags.
60
- * spec.browser is the session's own options, each refused by check() unless declared; a profile is made first if
61
- * Kernel does not know it.
67
+ * Makes a browser once per request (provider.md, Idempotent create), with the lifetime as its idle timeout in whole
68
+ * seconds and the labels as its tags, with the request's name (computerNameFor) as its create label. A request whose
69
+ * browser Kernel still holds undeleted answers that one, found by its create label; one whose browser was deleted here
70
+ * is refused exists; a create of a request in flight here waits for the first (CreateRequests). spec.browser is the
71
+ * session's own options, each refused by check() unless declared; a profile is made first if Kernel does not know it.
62
72
  */
63
73
  create(spec: ComputerSpec, context: CreateContext): Promise<Result<CreatedComputer>>;
64
74
  /**
package/dist/kernel.js CHANGED
@@ -20,7 +20,8 @@ import { randomBytes } from "node:crypto";
20
20
  import { readFileSync } from "node:fs";
21
21
  import { KERNEL } from "./descriptors/kernel.js";
22
22
  import { BROWSER_IMAGE } from "./descriptors/shared.js";
23
- import { cdpUrlProblem, browserClient, browserHello, BrowserVendorError, CREATE_LABEL, carries, causeOf, checkBrowser, createLabelValue, createUncertain, DEFAULT_CONFIRM, defaultSleep, idProblem, labelsOf, labelsProblem, memoryUrls, pointerOk, queryable, recoverCreate, releaseConfirmed, restCall, causedFail, vendorFailure, withoutCreateLabel, } from "./browser.js";
23
+ import { cdpUrlProblem, browserClient, browserHello, BrowserVendorError, CREATE_LABEL, carries, causeOf, checkBrowser, createUncertain, DEFAULT_CONFIRM, ATTEMPT_LABEL, convergedBrowser, heldBrowser, newAttempt, defaultSleep, idProblem, labelsOf, labelsProblem, memoryUrls, pointerOk, queryable, RECOVER_MS, recoverCreate, releaseConfirmed, boundedRelease, restCall, causedFail, vendorFailure, withoutCreateLabel, } from "./browser.js";
24
+ import { CreateRequests, endedWords, labelsDiffer, otherSpecWords } from "./create-requests.js";
24
25
  import { httpsBase } from "./hosted/rest.js";
25
26
  import { runLifetimeMs, } from "./provider.js";
26
27
  import { failFor, ok, vendorFail } from "./result.js";
@@ -38,6 +39,8 @@ export const KERNEL_MIN_LIFETIME_MS = 10_000;
38
39
  export const KERNEL_MAX_LIFETIME_MS = 259_200_000;
39
40
  /** The most pages a list reads before it fails rather than run on. */
40
41
  const MAX_PAGES = 100;
42
+ /** A browser as its create label finds it. */
43
+ const heldOf = ({ id, tags, createdAt }) => ({ id, labels: tags, ...(createdAt === undefined ? {} : { createdAt }) });
41
44
  /** Kernel's REST API over fetch: the default request. */
42
45
  export function kernelRest({ apiKey, apiUrl = KERNEL_API_URL, fetch: fetcher = fetch }) {
43
46
  const o = { vendor: NAME, fetch: fetcher, base: httpsBase(apiUrl, "the Kernel API URL"), headers: { Authorization: `Bearer ${apiKey}` } };
@@ -60,7 +63,18 @@ export class KernelProvider {
60
63
  #live;
61
64
  #confirm;
62
65
  #sleep;
63
- constructor({ apiKey, apiUrl, env = {}, fetch: fetcher, confirm = DEFAULT_CONFIRM, sleep = defaultSleep }) {
66
+ /** The bound of each cleanup a create runs for itself (cleanupMs). */
67
+ #cleanupMs;
68
+ /** Idempotent create's in-process half: one browser per request id (provider.md). */
69
+ #requests = new CreateRequests();
70
+ /** The request's name of each browser this provider made or found for a create, by id: its release ends the request. */
71
+ #requestOf = new Map();
72
+ /**
73
+ * The browser each request's create answered, by the request's name, kept past its release: a request whose browser
74
+ * ended on its own (its timeout, the vendor) is refused exists, as one released here is, never made again.
75
+ */
76
+ #madeFor = new Map();
77
+ constructor({ apiKey, apiUrl, env = {}, fetch: fetcher, confirm = DEFAULT_CONFIRM, sleep = defaultSleep, cleanupMs = RECOVER_MS }) {
64
78
  if (typeof apiKey !== "string" || apiKey === "")
65
79
  throw new Error("set options.apiKey to a Kernel API key: the provider reads no environment");
66
80
  const api = apiUrl || env.KERNEL_BASE_URL?.trim() || undefined;
@@ -69,6 +83,7 @@ export class KernelProvider {
69
83
  this.#live = memoryUrls();
70
84
  this.#confirm = confirm;
71
85
  this.#sleep = sleep;
86
+ this.#cleanupMs = cleanupMs;
72
87
  }
73
88
  /**
74
89
  * A browser: Kernel ends a browser after its idle timeout (lifetime vendor), at most 72 h; it reaches the open web;
@@ -94,24 +109,51 @@ export class KernelProvider {
94
109
  return checkBrowser(spec, this.capabilities(), NAME, KERNEL_MIN_LIFETIME_MS);
95
110
  }
96
111
  /**
97
- * Makes a browser at most once, with the lifetime as its idle timeout in whole seconds and the labels as its tags.
98
- * spec.browser is the session's own options, each refused by check() unless declared; a profile is made first if
99
- * Kernel does not know it.
112
+ * Makes a browser once per request (provider.md, Idempotent create), with the lifetime as its idle timeout in whole
113
+ * seconds and the labels as its tags, with the request's name (computerNameFor) as its create label. A request whose
114
+ * browser Kernel still holds undeleted answers that one, found by its create label; one whose browser was deleted here
115
+ * is refused exists; a create of a request in flight here waits for the first (CreateRequests). spec.browser is the
116
+ * session's own options, each refused by check() unless declared; a profile is made first if Kernel does not know it.
100
117
  */
101
118
  async create(spec, context) {
102
- const signal = context?.signal;
103
119
  const refusals = this.check(spec);
104
- if (refusals.length > 0)
105
- return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
120
+ return this.#requests.create(spec, context, {
121
+ refuse: fail,
122
+ ...(refusals.length > 0 ? { refused: refusals.map(({ field, message }) => `${field}: ${message}`).join("; ") } : {}),
123
+ make: async (request) => {
124
+ const made = await this.#createNamed(spec, request, context.signal);
125
+ if (made.ok)
126
+ this.#madeFor.set(request, made.value.id);
127
+ return made;
128
+ },
129
+ });
130
+ }
131
+ /** Everything create does under the request's name: the browser Kernel holds under it, or a new one. */
132
+ async #createNamed(spec, request, signal) {
106
133
  if (signal?.aborted)
107
134
  return fail("aborted", "create was aborted before Kernel was called");
135
+ const held = await this.#browsers({ [CREATE_LABEL]: request }, signal);
136
+ if (!held.ok)
137
+ return held;
138
+ const found = heldBrowser(spec.labels ?? {}, held.value.map(heldOf));
139
+ if (found !== undefined) {
140
+ if (found.differ.length > 0)
141
+ return fail("exists", otherSpecWords(`${request} (browser ${found.id})`, "was made", found.differ));
142
+ this.#requestOf.set(found.id, request);
143
+ return ok(refOf(found.id));
144
+ }
145
+ const ended = await this.#ended(spec, request, signal);
146
+ if (ended !== undefined)
147
+ return ended;
108
148
  const options = spec.browser;
109
149
  if (options?.profile !== undefined) {
110
150
  const ensured = await this.#ensureProfile(options.profile.pointer, signal);
111
151
  if (!ensured.ok)
112
152
  return causedFail(ensured.error.code, `the profile could not be made ready: ${ensured.error.message}; no browser was made`, causeOf(ensured), "kernel");
113
153
  }
114
- const written = { [CREATE_LABEL]: createLabelValue(), ...spec.labels };
154
+ // The request's label, which a retry and a converge find it by, and this POST's own, which its recovery finds it by.
155
+ const attempt = { [ATTEMPT_LABEL]: newAttempt() };
156
+ const written = { [CREATE_LABEL]: request, ...attempt, ...spec.labels };
115
157
  const body = {
116
158
  ...(options !== undefined ? { stealth: false } : {}),
117
159
  ...(options?.viewport ? { viewport: { width: options.viewport.width, height: options.viewport.height } } : {}),
@@ -128,8 +170,10 @@ export class KernelProvider {
128
170
  const failed = vendorFailure("kernel", NAME, "POST /browsers", error);
129
171
  if (failed.ok || !createUncertain(error))
130
172
  return failed;
131
- // The browser may have been made though its answer never came: found by its create label, never made again.
132
- return causedFail(failed.error.code, `${failed.error.message}; ${await this.#recover(written)}`, causeOf(failed), "kernel");
173
+ // The browser may have been made though its answer never came: found by this POST's attempt label and deleted,
174
+ // and the request is ended, so it is never made again.
175
+ this.#requests.end(request);
176
+ return causedFail(failed.error.code, `${failed.error.message}; ${await this.#recover(attempt)}`, causeOf(failed), "kernel");
133
177
  }
134
178
  const browser = (made.json ?? {});
135
179
  const id = text(browser.session_id);
@@ -138,8 +182,17 @@ export class KernelProvider {
138
182
  return vendorFailure("kernel", NAME, "POST /browsers", new BrowserVendorError(NAME, "POST /browsers", made.status, "no_session"));
139
183
  if (idProblem(id, NAME) !== undefined) {
140
184
  const failed = vendorFailure("kernel", NAME, "POST /browsers", new BrowserVendorError(NAME, "POST /browsers", made.status, "no_session"));
141
- return failed.ok ? failed : fail(failed.error.code, `${failed.error.message}; ${await this.#recover(written)}`);
185
+ if (failed.ok)
186
+ return failed;
187
+ this.#requests.end(request);
188
+ return fail(failed.error.code, `${failed.error.message}; ${await this.#recover(attempt)}`);
142
189
  }
190
+ this.#requests.made(request);
191
+ // Another process's create of this request may have made one too (#converge): the older is answered.
192
+ const converged = await this.#converge(spec, request, { id, tags: {}, ...(text(browser.created_at) === "" ? {} : { createdAt: text(browser.created_at) }) }, signal);
193
+ if (converged !== undefined)
194
+ return converged;
195
+ this.#requestOf.set(id, request);
143
196
  const unusable = cdpUrlProblem(url, NAME, CDP_DOMAIN);
144
197
  if (unusable !== undefined) {
145
198
  // The browser is made and billed until its idle timeout: deleted here, not left to a later sweep.
@@ -152,6 +205,64 @@ export class KernelProvider {
152
205
  this.#live.set(id, live);
153
206
  return ok(refOf(id));
154
207
  }
208
+ /**
209
+ * The one browser a request keeps (convergedBrowser): the request's create label listed again once Kernel made mine.
210
+ * Undefined when mine is the oldest (or the listing fails: the create goes on with its own); an abort deletes mine,
211
+ * never under the caller's signal, and the create is aborted. Else mine is deleted,
212
+ * never under the caller's signal, and the older answered: refused exists when it is gone by then, or when its labels
213
+ * are another spec's.
214
+ */
215
+ async #converge(spec, request, mine, signal) {
216
+ const listed = await this.#browsers({ [CREATE_LABEL]: request }, signal);
217
+ if (!listed.ok) {
218
+ if (listed.error.code !== "aborted" && !signal?.aborted)
219
+ return undefined;
220
+ // The caller is gone: the browser this POST made is deleted, never under the caller's signal.
221
+ this.#requests.end(request);
222
+ const released = await boundedRelease("browser", mine.id, this.#cleanupMs, (bound) => this.#releaseBrowser(mine.id, bound));
223
+ return fail("aborted", `create was aborted once Kernel had made the browser ${mine.id}; ${released.ok ? "the browser was released" : `the browser could not be released (${released.error.message}), and its tags let a sweep find it`}`);
224
+ }
225
+ const kept = convergedBrowser(listed.value.map(heldOf), heldOf(mine));
226
+ if (kept === "mine")
227
+ return undefined;
228
+ const released = await boundedRelease("browser", mine.id, this.#cleanupMs, (bound) => this.#releaseBrowser(mine.id, bound));
229
+ if (!released.ok)
230
+ return fail(released.error.code, `${request} keeps the browser ${kept.id}, the older of its two, and the browser ${mine.id} made for it could not be deleted (${released.error.message})`);
231
+ const alive = await this.#alive(kept.id, signal);
232
+ if (!alive.ok)
233
+ return alive;
234
+ if (!alive.value) {
235
+ this.#requests.end(request);
236
+ return fail("exists", endedWords(request));
237
+ }
238
+ const differ = labelsDiffer(spec.labels ?? {}, kept.labels, "read back");
239
+ if (differ.length > 0)
240
+ return fail("exists", otherSpecWords(`${request} (browser ${kept.id})`, "was made", differ));
241
+ this.#requestOf.set(kept.id, request);
242
+ return ok(refOf(kept.id));
243
+ }
244
+ /**
245
+ * A request this provider answered a browser for before, which its create label no longer finds: refused exists, the
246
+ * request ended, once Kernel reads that browser as gone too; one it still holds (a listing that left it out) is
247
+ * answered when its labels are this spec's. Undefined for a request with no browser here yet.
248
+ */
249
+ async #ended(spec, request, signal) {
250
+ const before = this.#madeFor.get(request);
251
+ if (before === undefined)
252
+ return undefined;
253
+ const read = await this.#running(before, signal);
254
+ if (!read.ok && read.error.code !== "not_found" && read.error.code !== "gone")
255
+ return read;
256
+ if (!read.ok) {
257
+ this.#requests.end(request);
258
+ return fail("exists", endedWords(request));
259
+ }
260
+ const differ = labelsDiffer(spec.labels ?? {}, withoutCreateLabel(labelsOf(read.value.tags)), "read back");
261
+ if (differ.length > 0)
262
+ return fail("exists", otherSpecWords(`${request} (browser ${before})`, "was made", differ));
263
+ this.#requestOf.set(before, request);
264
+ return ok(refOf(before));
265
+ }
155
266
  /** A browser names only a profile Kernel knows: made if it is not (GET, then POST); a 409 is another process making it. */
156
267
  async #ensureProfile(name, signal) {
157
268
  try {
@@ -203,16 +314,16 @@ export class KernelProvider {
203
314
  }
204
315
  /**
205
316
  * The browsers a lost create made, released: what recoverCreate says of them. They are found as list finds any, by the
206
- * tags the create wrote (its create label first, so the query names it, then the run's), through #browsers: another
207
- * browser of the same run carries a create label of its own and is left alone. #browsers reads every state not
208
- * deleted, so a browser still starting is found and released too.
317
+ * attempt label its POST wrote (ATTEMPT_LABEL), through #browsers: another create's browser, of this request or
318
+ * another, carries an attempt label of its own and is left alone, even one another instance has answered. #browsers
319
+ * reads every state not deleted, so a browser still starting is found and released too.
209
320
  */
210
321
  #recover(labels) {
211
322
  const find = async (signal) => {
212
323
  const found = await this.#browsers(labels, signal);
213
324
  return found.ok ? ok(found.value.map((b) => b.id)) : found;
214
325
  };
215
- return recoverCreate("browser", find, (id) => this.release(refOf(id), "delete"), this.#sleep);
326
+ return recoverCreate("browser", find, (id, signal) => this.release(refOf(id), "delete", { signal }), this.#sleep, this.#cleanupMs);
216
327
  }
217
328
  /**
218
329
  * Settings' test: one page of the organization's active browsers (GET /browsers?status=active), which makes nothing.
@@ -322,7 +433,8 @@ export class KernelProvider {
322
433
  const id = text(row?.session_id);
323
434
  if (id !== "" && !row.deleted_at && carries(row.tags, labels) && !seen.has(id)) {
324
435
  seen.add(id);
325
- found.push({ id, tags: withoutCreateLabel(labelsOf(row.tags)) });
436
+ const createdAt = text(row.created_at);
437
+ found.push({ id, tags: withoutCreateLabel(labelsOf(row.tags)), ...(createdAt === "" ? {} : { createdAt }) });
326
438
  }
327
439
  }
328
440
  if (page.headers.get("x-has-more") !== "true")
@@ -391,6 +503,17 @@ export class KernelProvider {
391
503
  const problem = idProblem(id, NAME);
392
504
  if (problem)
393
505
  return fail("invalid", problem);
506
+ // The request's browser is ended here: a later create of it is refused exists, never made again.
507
+ const request = this.#requestOf.get(id);
508
+ if (request !== undefined)
509
+ this.#requests.end(request);
510
+ const released = await this.#releaseBrowser(id, signal);
511
+ if (released.ok)
512
+ this.#requestOf.delete(id);
513
+ return released;
514
+ }
515
+ /** Deletes the browser and waits until Kernel reads it as gone; the request it was made for is not ended. */
516
+ async #releaseBrowser(id, signal) {
394
517
  const released = await releaseConfirmed({
395
518
  request: async () => {
396
519
  try {
@@ -45,7 +45,13 @@ export declare class LocalBrowserProvider implements ComputerProvider {
45
45
  /** The Chrome this provider runs: the option's, else one found; null when there is none. */
46
46
  executable(): string | null;
47
47
  check(spec: ComputerSpec): Refusal[];
48
- /** Starts Chrome under a supervisor of its own, waits until its DevTools socket answers, and hands back its ref. */
48
+ /**
49
+ * Starts Chrome under a supervisor of its own, waits until its DevTools socket answers, and hands back its ref: once
50
+ * per request (provider.md, Idempotent create). The request's name (computerNameFor) is the browser's id and its
51
+ * directory's name, which mkdir claims for one create alone. A request whose directory is already under the root
52
+ * answers that browser, from this process or another (#taken); one whose browser was released here is refused
53
+ * exists; a create of a request in flight here waits for the first (CreateRequests).
54
+ */
49
55
  create(spec: ComputerSpec, context: CreateContext): Promise<Result<CreatedComputer>>;
50
56
  /**
51
57
  * Settings' test: finds the Chrome and starts it once, headless, on a blank page, with its sandbox on (chrome.ts