@parcha/agentrun-computer 0.1.0-beta.58 → 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.
Files changed (143) hide show
  1. package/README.md +285 -81
  2. package/box/Dockerfile +4 -3
  3. package/box/install.sh +57 -11
  4. package/dist/agent37.d.ts +11 -4
  5. package/dist/agent37.js +217 -19
  6. package/dist/attach.d.ts +24 -4
  7. package/dist/attach.js +50 -19
  8. package/dist/boxd.js +22 -9
  9. package/dist/browser.d.ts +56 -11
  10. package/dist/browser.js +76 -17
  11. package/dist/browserbase.d.ts +20 -5
  12. package/dist/browserbase.js +186 -21
  13. package/dist/child-env.d.ts +11 -0
  14. package/dist/child-env.js +22 -0
  15. package/dist/chrome.d.ts +5 -2
  16. package/dist/chrome.js +5 -2
  17. package/dist/cloudflare.d.ts +2 -0
  18. package/dist/cloudflare.js +5 -3
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/computerd.json +1 -1
  22. package/dist/conformance/agent37.d.ts +20 -40
  23. package/dist/conformance/agent37.js +31 -118
  24. package/dist/conformance/archil.d.ts +13 -3
  25. package/dist/conformance/archil.js +22 -17
  26. package/dist/conformance/boxd.d.ts +8 -31
  27. package/dist/conformance/boxd.js +19 -74
  28. package/dist/conformance/browserbase.d.ts +3 -6
  29. package/dist/conformance/browserbase.js +6 -17
  30. package/dist/conformance/cases/health.js +6 -3
  31. package/dist/conformance/cases/provider.js +4 -1
  32. package/dist/conformance/cli.d.ts +3 -1
  33. package/dist/conformance/cli.js +69 -9
  34. package/dist/conformance/cloudflare.d.ts +3 -6
  35. package/dist/conformance/cloudflare.js +7 -15
  36. package/dist/conformance/daytona.d.ts +6 -20
  37. package/dist/conformance/daytona.js +22 -57
  38. package/dist/conformance/dial-only.d.ts +4 -3
  39. package/dist/conformance/dial-only.js +3 -3
  40. package/dist/conformance/docker.d.ts +4 -5
  41. package/dist/conformance/docker.js +8 -14
  42. package/dist/conformance/e2b.d.ts +10 -36
  43. package/dist/conformance/e2b.js +27 -84
  44. package/dist/conformance/fly.d.ts +3 -6
  45. package/dist/conformance/fly.js +2 -6
  46. package/dist/conformance/groundbox.d.ts +7 -23
  47. package/dist/conformance/groundbox.js +16 -56
  48. package/dist/conformance/index.d.ts +1 -0
  49. package/dist/conformance/index.js +1 -0
  50. package/dist/conformance/kernel.d.ts +3 -6
  51. package/dist/conformance/kernel.js +5 -15
  52. package/dist/conformance/kind.d.ts +0 -6
  53. package/dist/conformance/kind.js +0 -4
  54. package/dist/conformance/local-chrome.d.ts +5 -7
  55. package/dist/conformance/local-chrome.js +7 -11
  56. package/dist/conformance/modal.d.ts +10 -38
  57. package/dist/conformance/modal.js +27 -74
  58. package/dist/conformance/module-kit.d.ts +87 -0
  59. package/dist/conformance/module-kit.js +88 -0
  60. package/dist/conformance/morph.d.ts +7 -23
  61. package/dist/conformance/morph.js +20 -66
  62. package/dist/conformance/orgo.d.ts +5 -10
  63. package/dist/conformance/orgo.js +15 -27
  64. package/dist/conformance/phone-harness.d.ts +3 -5
  65. package/dist/conformance/phone-harness.js +3 -11
  66. package/dist/conformance/runner.d.ts +13 -3
  67. package/dist/conformance/runner.js +32 -11
  68. package/dist/conformance/smolcloud.d.ts +7 -23
  69. package/dist/conformance/smolcloud.js +16 -49
  70. package/dist/conformance/sweep.d.ts +10 -5
  71. package/dist/conformance/sweep.js +91 -38
  72. package/dist/conformance/tti.d.ts +69 -0
  73. package/dist/conformance/tti.js +205 -0
  74. package/dist/conformance/types.d.ts +9 -2
  75. package/dist/daytona.js +60 -20
  76. package/dist/descriptor.d.ts +37 -0
  77. package/dist/descriptor.js +9 -0
  78. package/dist/descriptors/agent37.d.ts +4 -1
  79. package/dist/descriptors/agent37.js +5 -2
  80. package/dist/descriptors/browserbase.d.ts +3 -0
  81. package/dist/descriptors/browserbase.js +4 -0
  82. package/dist/descriptors/docker.d.ts +2 -0
  83. package/dist/descriptors/docker.js +5 -0
  84. package/dist/descriptors/env-names.d.ts +32 -0
  85. package/dist/descriptors/env-names.js +60 -0
  86. package/dist/descriptors/index.d.ts +14 -3
  87. package/dist/descriptors/kernel.d.ts +3 -0
  88. package/dist/descriptors/kernel.js +2 -0
  89. package/dist/descriptors/local-chrome.d.ts +1 -1
  90. package/dist/descriptors/local-chrome.js +5 -3
  91. package/dist/descriptors/phone-harness.d.ts +1 -1
  92. package/dist/descriptors/phone-harness.js +4 -2
  93. package/dist/docker/egress.d.ts +7 -0
  94. package/dist/docker/egress.js +8 -0
  95. package/dist/docker/image.d.ts +5 -1
  96. package/dist/docker/image.js +12 -8
  97. package/dist/docker.d.ts +52 -13
  98. package/dist/docker.js +166 -92
  99. package/dist/drift.js +6 -6
  100. package/dist/e2b.d.ts +2 -2
  101. package/dist/e2b.js +2 -3
  102. package/dist/groundbox.js +6 -6
  103. package/dist/host.d.ts +23 -0
  104. package/dist/hosted/download.d.ts +23 -0
  105. package/dist/hosted/download.js +144 -0
  106. package/dist/hosted/process.d.ts +5 -0
  107. package/dist/hosted/process.js +20 -0
  108. package/dist/hosted/provider.js +120 -48
  109. package/dist/hosted/rest.d.ts +19 -8
  110. package/dist/hosted/rest.js +47 -14
  111. package/dist/hosted/scripts.d.ts +10 -0
  112. package/dist/hosted/scripts.js +23 -2
  113. package/dist/hosted/ssh-exec.d.ts +7 -1
  114. package/dist/hosted/ssh-exec.js +19 -14
  115. package/dist/hosted/ssh-key.d.ts +18 -0
  116. package/dist/hosted/ssh-key.js +36 -0
  117. package/dist/index.d.ts +5 -3
  118. package/dist/index.js +4 -2
  119. package/dist/janitor.d.ts +7 -1
  120. package/dist/janitor.js +2 -2
  121. package/dist/kernel.d.ts +14 -4
  122. package/dist/kernel.js +141 -18
  123. package/dist/local-chrome.d.ts +12 -3
  124. package/dist/local-chrome.js +108 -10
  125. package/dist/local-supervisor.js +1 -0
  126. package/dist/modal.d.ts +6 -5
  127. package/dist/modal.js +7 -7
  128. package/dist/morph.js +5 -8
  129. package/dist/orgo-channel.d.ts +3 -2
  130. package/dist/orgo-channel.js +3 -3
  131. package/dist/orgo-desktop.js +2 -4
  132. package/dist/orgo.d.ts +6 -0
  133. package/dist/orgo.js +158 -15
  134. package/dist/phone-harness.d.ts +7 -5
  135. package/dist/phone-harness.js +60 -61
  136. package/dist/protocol.d.ts +10 -0
  137. package/dist/protocol.js +17 -0
  138. package/dist/provider.d.ts +6 -2
  139. package/dist/screen-watch.d.ts +6 -1
  140. package/dist/screen-watch.js +166 -12
  141. package/dist/vendor-sdk.d.ts +9 -0
  142. package/dist/vendor-sdk.js +26 -0
  143. package/package.json +8 -1
package/dist/attach.js CHANGED
@@ -9,7 +9,7 @@ import { DaemonClient } from "./client.js";
9
9
  import { kindServed } from "./kinds.js";
10
10
  import { EPOCH_LABEL, epochOf } from "./labels.js";
11
11
  import { checkMount, WORKSPACE } from "./mount.js";
12
- import { PROTOCOL_VERSION } from "./protocol.js";
12
+ import { helloProblem, PROTOCOL_VERSION } from "./protocol.js";
13
13
  import { checkLifetime, kindRefusals, runLifetimeMs } from "./provider.js";
14
14
  import { fail, ok } from "./result.js";
15
15
  export const ATTACH_PATH = "/v2/computers/attach";
@@ -29,8 +29,19 @@ export function attachEgressOf(text) {
29
29
  throw new Error(`the attach egress is <IPv4 relay>:<port>, such as 192.0.2.40:18443, a port from 1 to 65535; not ${JSON.stringify(text)}`);
30
30
  return text;
31
31
  }
32
- /** The WebSocket subprotocol a driver asks for: the protocol version it speaks. Serve answers with it or refuses. */
33
- export const ATTACH_SUBPROTOCOL = `agentrun.computer.${PROTOCOL_VERSION}`;
32
+ const SUBPROTOCOL_PREFIX = "agentrun.computer.";
33
+ /** The WebSocket subprotocol a driver asks for: the protocol version it speaks. */
34
+ export const ATTACH_SUBPROTOCOL = `${SUBPROTOCOL_PREFIX}${PROTOCOL_VERSION}`;
35
+ /**
36
+ * The subprotocol of those a driver asked for that serve answers with: this server's own when it is asked for, as the
37
+ * answer tells the driver what the server speaks; else the first naming a protocol version that works with this one
38
+ * (helloProblem: 0.2 or a later 0.x); else undefined, and serve refuses the upgrade.
39
+ */
40
+ export function attachSubprotocolOf(asked) {
41
+ if (asked.includes(ATTACH_SUBPROTOCOL))
42
+ return ATTACH_SUBPROTOCOL;
43
+ return asked.find((one) => one.startsWith(SUBPROTOCOL_PREFIX) && helloProblem(one.slice(SUBPROTOCOL_PREFIX.length), "server") === undefined);
44
+ }
34
45
  /** Each side pings this often (WebSocket ping frames, not JSON-RPC), so a NAT keeps the path open. */
35
46
  export const ATTACH_HEARTBEAT_MS = 20_000;
36
47
  /** A side that hears nothing, not even a pong, for this long closes the socket with ATTACH_CLOSE.idle. */
@@ -60,7 +71,7 @@ export const ATTACH_CLOSE = {
60
71
  idle: 4408,
61
72
  /** The same computer dialed again; the older socket is closed. */
62
73
  replaced: 4409,
63
- /** The driver speaks another protocol version, or its hello lacks a group its kind needs (kindServed): update it. */
74
+ /** The driver speaks a protocol the server does not take (helloProblem), or its hello lacks a group its kind needs (kindServed): update it. */
64
75
  protocol: 4426,
65
76
  };
66
77
  const STOPS = new Set([ATTACH_CLOSE.mismatch, ATTACH_CLOSE.unauthorized, ATTACH_CLOSE.protocol]);
@@ -151,30 +162,50 @@ export class MemoryMachineTokens {
151
162
  export function mintedComputer(machine, { kind, os, arch }) {
152
163
  return { id: machine, name: machine, hello: { protocol: PROTOCOL_VERSION, version: "", os, kind, arch, groups: [] }, labels: {}, minted: true };
153
164
  }
154
- /** Whether protocol version a ("0.3") comes after b ("0.2"), part by part as numbers. */
155
- function laterProtocol(a, b) {
156
- const [x, y] = [a, b].map((version) => version.split(".").map((part) => Number.parseInt(part, 10) || 0));
157
- for (let i = 0; i < Math.max(x.length, y.length); i++)
158
- if ((x[i] ?? 0) !== (y[i] ?? 0))
159
- return (x[i] ?? 0) > (y[i] ?? 0);
160
- return false;
165
+ /**
166
+ * Whether a refused driver's protocol version comes after this server's, so the server is the side to update: a
167
+ * "<major>.<minor>" later part by part as numbers ("1.0" after "0.2"). A version of any other shape ("0.2.1",
168
+ * "0.3-beta") is no server's, so updating the server never helps, and the driver is the side to update. Serve's pairing
169
+ * reads it too.
170
+ */
171
+ export function laterProtocol(protocol) {
172
+ const theirs = /^(\d+)\.(\d+)$/.exec(protocol);
173
+ if (theirs === null)
174
+ return false;
175
+ const [major, minor] = PROTOCOL_VERSION.split(".").map(Number);
176
+ return Number(theirs[1]) !== major ? Number(theirs[1]) > major : Number(theirs[2]) > minor;
177
+ }
178
+ const SERVER_OLDER = "the server is older: it is updated by whoever runs it";
179
+ /** What a person does about a refused driver on `paired`. Serve names no OS and no driver app: one way to update, in
180
+ * the same words for every computer. A minted machine fetched this server's own computerd at boot, so another build
181
+ * there is not one this server gave it. */
182
+ function updateOf(paired) {
183
+ return paired.minted ? `${paired.name} runs a computerd that is not this server's build: create the computer again` : `update the driver on ${paired.name} (the download is on the console's Computers page)`;
184
+ }
185
+ /**
186
+ * The words of serve's 426 at the attach upgrade, when no subprotocol `asked` names a protocol this server takes
187
+ * (attachSubprotocolOf). They name the side to update as helloMismatch does: the server when one asked names a later
188
+ * protocol, else the driver. A driver stops dialing on this 426 as on a 4426 close, and a 0.1 driver, which offers only
189
+ * its own subprotocol, is refused here and never reaches hello.
190
+ */
191
+ export function upgradeRefusal(paired, asked) {
192
+ const newer = asked.some((one) => one.startsWith(SUBPROTOCOL_PREFIX) && laterProtocol(one.slice(SUBPROTOCOL_PREFIX.length)));
193
+ return `this server speaks ${ATTACH_SUBPROTOCOL}, and ${paired.name}'s driver asked for ${asked.join(", ") || "no subprotocol"}: ${newer ? SERVER_OLDER : updateOf(paired)}`;
161
194
  }
162
195
  /**
163
- * Why a hello may not stand for a paired computer, or undefined. The protocol version must be the server's; the
164
- * driver's own version may be any: a person's installed app updates on its own schedule, and the server cannot
196
+ * Why a hello may not stand for a paired computer, or undefined. The protocol version must work with the server's
197
+ * (helloProblem: 0.2 or a later 0.x); the driver's own version may be any: a person's installed app updates on its own schedule, and the server cannot
165
198
  * replace it the way a provider replaces a copied daemon.
166
199
  */
167
200
  export function helloMismatch(paired, hello) {
168
- // Serve names no OS and no driver app: one way to update, in the same words for every computer. A minted machine
169
- // fetched this server's own computerd at boot, so another build there is not one this server gave it.
170
- const update = paired.minted ? `${paired.name} runs a computerd that is not this server's build: create the computer again` : `update the driver on ${paired.name} (the download is on the console's Computers page)`;
201
+ const update = updateOf(paired);
171
202
  const said = hello;
172
203
  if (typeof said !== "object" || said === null || typeof said.protocol !== "string" || typeof said.version !== "string") {
173
204
  return { code: ATTACH_CLOSE.protocol, message: `${paired.name}'s driver answered hello without its protocol and version: ${update}` };
174
205
  }
175
- if (hello.protocol !== PROTOCOL_VERSION) {
176
- const newer = laterProtocol(hello.protocol, PROTOCOL_VERSION) ? "the server is older: it is updated by whoever runs it" : update;
177
- return { code: ATTACH_CLOSE.protocol, message: `${paired.name}'s driver ${hello.version} speaks protocol ${hello.protocol}, and this server ${PROTOCOL_VERSION}: ${newer}` };
206
+ const problem = helloProblem(hello.protocol, "server");
207
+ if (problem) {
208
+ return { code: ATTACH_CLOSE.protocol, message: `${paired.name}'s driver ${hello.version} ${problem}: ${laterProtocol(hello.protocol) ? SERVER_OLDER : update}` };
178
209
  }
179
210
  // Every field serve reads off a live hello (the provider's capabilities, the kind check): one missing is refused
180
211
  // here, never met later as a throw.
package/dist/boxd.js CHANGED
@@ -1,4 +1,4 @@
1
- // The boxd host: boxd machines (KVM microVMs, Ubuntu 24.04) as a MachineHost, through the host's own @boxd-sh/sdk, of
1
+ // The boxd host: boxd machines (KVM microVMs, Ubuntu 24.04) as a MachineHost, through @boxd-sh/sdk (an optional dependency), of
2
2
  // which this file names only the slice it calls (every fact from 0.3.1's dist/*.d.ts) and imports nothing at load.
3
3
  // boxd's agent runs every command in a machine, so computerd is a child. The daemon, the bridge, the probe, idempotent
4
4
  // create, extend and delete-then-wait-gone are the shared adapter's (./hosted/provider.ts). A desktop starts from a
@@ -13,14 +13,13 @@ import { httpsBase } from "./hosted/rest.js";
13
13
  import { shellLine } from "./hosted/scripts.js";
14
14
  import { dateOf } from "./hosted/values.js";
15
15
  import { failFor, ok } from "./result.js";
16
- /** Not a literal, so no type checker or bundler resolves the SDK from this package. */
17
- const BOXD_PACKAGE = "@boxd-sh/sdk";
16
+ import { vendorSdk } from "./vendor-sdk.js";
18
17
  /** A BoxdProvider from its options alone; throws in words when the key is missing, never echoing one. */
19
18
  export async function create(options) {
20
19
  const { apiKey, Boxd: given, ...rest } = options ?? {};
21
20
  if (typeof apiKey !== "string" || apiKey === "")
22
21
  throw new Error("options.apiKey, the boxd API key, is required: the provider reads no environment, so the caller passes it");
23
- const Boxd = given ?? (await import(BOXD_PACKAGE)).Boxd;
22
+ const Boxd = given ?? (await vendorSdk(BOXD.label, "@boxd-sh/sdk")).Boxd;
24
23
  return new BoxdProvider({ ...rest, apiKey, Boxd });
25
24
  }
26
25
  /** The conformance CLI's module for boxd. */
@@ -44,17 +43,31 @@ const STATES = {
44
43
  ...{ pending: "starting", starting: "starting", running: "running", suspended: "running", migrating: "running" },
45
44
  ...{ hibernated: "stopped", stopped: "stopped", failed: "gone", destroyed: "gone" },
46
45
  };
46
+ /** Mozilla's APT signing key (fingerprint 35BAA0B33E9EB396F59CA838C0BA5CE6DC6315A3), where the recipe keeps it, and its sha256. */
47
+ const MOZILLA_KEY = "/etc/apt/keyrings/packages.mozilla.org.asc";
48
+ const MOZILLA_KEY_SHA256 = "3ecc63922b7795eb23fdc449ff9396f9114cb3cf186d6f5b53ad4cc3ebfbb11f";
47
49
  /**
48
- * What a desktop needs that boxd's own image lacks: a stock app, Xfce's text editor (mousepad, from Ubuntu's universe),
49
- * its desktop file checked, run as root on a build machine of boxd's own image. Xvfb is the image's already. The
50
- * snapshot's name carries this line's hash, so a new line is a new snapshot.
50
+ * What a desktop needs that boxd's own image lacks (Xvfb, xdotool and Thunar are the image's already): Xfce's text
51
+ * editor and terminal (mousepad and xfce4-terminal, from Ubuntu's universe) and Firefox ESR, from Mozilla's APT
52
+ * repository, since Ubuntu 24.04's firefox is a snap and a microVM runs no snapd. Mozilla's key is held to its sha256
53
+ * before apt reads anything it signs. Each program and desktop file is checked. Run as root on a build machine of boxd's
54
+ * own image, with no single quote in it (it goes in one pair). The snapshot's name carries this recipe's hash, so a
55
+ * new recipe is a new snapshot.
51
56
  */
52
57
  const DESKTOP_RECIPE = [
53
58
  "set -e",
54
59
  "export DEBIAN_FRONTEND=noninteractive",
55
60
  "apt-get update -qq",
56
- "apt-get install -y -qq --no-install-recommends mousepad >/dev/null",
57
- 'test -f /usr/share/applications/org.xfce.mousepad.desktop || { echo "mousepad brought no org.xfce.mousepad.desktop" >&2; exit 1; }',
61
+ "apt-get install -y -qq --no-install-recommends ca-certificates curl >/dev/null",
62
+ "install -d -m 0755 /etc/apt/keyrings",
63
+ `curl -fsSL https://packages.mozilla.org/apt/repo-signing-key.gpg -o ${MOZILLA_KEY}`,
64
+ `echo "${MOZILLA_KEY_SHA256} ${MOZILLA_KEY}" | sha256sum -c --quiet - || { echo "the APT signing key from packages.mozilla.org is not the one this recipe pins" >&2; exit 1; }`,
65
+ `echo "deb [signed-by=${MOZILLA_KEY}] https://packages.mozilla.org/apt mozilla main" > /etc/apt/sources.list.d/mozilla.list`,
66
+ 'printf "Package: *\\nPin: origin packages.mozilla.org\\nPin-Priority: 1000\\n" > /etc/apt/preferences.d/mozilla',
67
+ "apt-get update -qq",
68
+ "apt-get install -y -qq --no-install-recommends mousepad xfce4-terminal firefox-esr >/dev/null",
69
+ 'for x in mousepad xfce4-terminal firefox-esr; do command -v "$x" >/dev/null || { echo "the desktop has no $x" >&2; exit 1; }; done',
70
+ 'for app in org.xfce.mousepad xfce4-terminal firefox-esr; do test -f "/usr/share/applications/$app.desktop" || { echo "the desktop has no desktop file $app.desktop" >&2; exit 1; }; done',
58
71
  "rm -rf /var/lib/apt/lists/*",
59
72
  ].join("\n");
60
73
  /** The desktop snapshot this package's recipe names: agentrun-desktop-<12 hex of the recipe's sha256>. */
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>>;
package/dist/browser.js CHANGED
@@ -6,6 +6,7 @@ import { randomBytes } from "node:crypto";
6
6
  import { PROTOCOL_VERSION } from "./protocol.js";
7
7
  import { checkGpu, checkLifetime } from "./provider.js";
8
8
  import { errorOf, fail, ok } from "./result.js";
9
+ import { labelsDiffer } from "./create-requests.js";
9
10
  import { BROWSER_IMAGE } from "./descriptors/shared.js";
10
11
  /** A key's or a value's longest, in characters: what both vendors keep of a metadata entry. */
11
12
  const MAX_LABEL = 256;
@@ -58,18 +59,52 @@ export const carries = (held, labels) => typeof held === "object" && held !== nu
58
59
  /** The labels a vendor's metadata holds, its string entries only. */
59
60
  export const labelsOf = (held) => typeof held === "object" && held !== null ? Object.fromEntries(Object.entries(held).filter((entry) => typeof entry[1] === "string")) : {};
60
61
  /**
61
- * The label every create writes beside the spec's, a value of its own: a create whose reply is lost, or whose caller
62
- * cancels it, finds the browser it made by this label alone and releases it. The provider's own: check() refuses it in a
63
- * spec, and no list or attach shows it.
62
+ * The label every create writes beside the spec's, the name of its request (computerNameFor): a create retried, here or
63
+ * in another process, finds the browser the first made by this label (heldBrowser), and a create that made one finds
64
+ * the request's others by it (convergedBrowser). The provider's own: check() refuses it in a spec, and no list or
65
+ * attach shows it.
64
66
  */
65
67
  export const CREATE_LABEL = "agentrun.create";
66
- /** Labels without the provider's create label. */
68
+ /**
69
+ * The label each create's POST writes beside the create label, a random value of that POST's own (newAttempt): a create
70
+ * whose reply is lost, or whose caller cancels it, finds the browser its own POST made by this label alone and releases
71
+ * it, never another create's browser of the same request. The provider's own, as the create label is.
72
+ */
73
+ export const ATTEMPT_LABEL = "agentrun.attempt";
74
+ /** A create attempt's own value of ATTEMPT_LABEL. */
75
+ export const newAttempt = () => randomBytes(8).toString("hex");
76
+ /** Labels without the provider's own, the create and attempt labels. */
67
77
  export const withoutCreateLabel = (labels) => {
68
- const { [CREATE_LABEL]: _, ...rest } = labels;
78
+ const { [CREATE_LABEL]: _, [ATTEMPT_LABEL]: __, ...rest } = labels;
69
79
  return rest;
70
80
  };
71
- /** A create label's value: 16 hex digits, fresh per create. */
72
- export const createLabelValue = () => randomBytes(8).toString("hex");
81
+ /**
82
+ * The order a request's browsers are read in (heldBrowser, a create's converge): the oldest first, by the time the
83
+ * vendor made each, then by id. The same browsers give the same order in every process.
84
+ */
85
+ export const oldestBrowserFirst = (a, b) => String(a.createdAt ?? "").localeCompare(String(b.createdAt ?? "")) || a.id.localeCompare(b.id);
86
+ /**
87
+ * The browser a vendor holds for a create's request (provider.md, Idempotent create), among those its create label finds
88
+ * (found, each with its labels as list shows them): undefined when there is none, so create makes it, else the oldest
89
+ * (oldestBrowserFirst), with how its labels differ from the ones asked (labelsDiffer; empty when it is this spec's). A
90
+ * browser's own options are not read back from the vendor, so a create from another process compares the labels alone.
91
+ */
92
+ export function heldBrowser(asked, found) {
93
+ const first = [...found].sort(oldestBrowserFirst)[0];
94
+ return first === undefined ? undefined : { id: first.id, differ: labelsDiffer(asked, first.labels, "read back") };
95
+ }
96
+ /**
97
+ * Where a create that made a browser stands among its request's (provider.md, Idempotent create). Two creates of one
98
+ * request in two processes can both find no browser by the create label and both make one: CreateRequests holds within
99
+ * one provider alone. So after the vendor's answer the label is listed again (listed; mine, made just now, added when it
100
+ * is not listed yet): "mine" when mine is the oldest, so the create answers it; else the older, which the create
101
+ * answers in place of its own once it has released its own. Every process picks the same one from the same listing.
102
+ */
103
+ export function convergedBrowser(listed, mine) {
104
+ const holders = listed.some((one) => one.id === mine.id) ? [...listed] : [...listed, { ...mine, createdAt: mine.createdAt ?? new Date().toISOString() }];
105
+ const kept = holders.sort(oldestBrowserFirst)[0];
106
+ return kept.id === mine.id ? "mine" : kept;
107
+ }
73
108
  /**
74
109
  * Whether a create that threw may still have made a browser: anything but the vendor's own 4xx answer (a refusal, which
75
110
  * makes nothing). A request not answered, aborted, cut short, or answered 5xx or with a body that is no browser may
@@ -79,17 +114,20 @@ export function createUncertain(error) {
79
114
  const status = error?.status;
80
115
  return !(typeof status === "number" && status >= 400 && status < 500);
81
116
  }
82
- /** How long a lost create's browser is looked for, in all, and how often: a vendor may list it a moment late. */
117
+ /**
118
+ * How long a lost create's browser is looked for and released, in all, and how often: a vendor may list it a moment
119
+ * late. Also the default bound of every other release a create runs for itself (a provider's cleanupMs).
120
+ */
83
121
  export const RECOVER_MS = 30_000;
84
122
  const RECOVER_TRIES = 3;
85
123
  const RECOVER_GAP_MS = 2_000;
86
124
  /**
87
- * After a create whose outcome is unknown: the browsers carrying its create label, found under a signal of the
88
- * recovery's own (the caller's may be what ended the create), each released. The words say what became of them, for the
89
- * create's failure; they never carry a URL.
125
+ * After a create whose outcome is unknown: the browsers carrying its create label, found and released under a signal
126
+ * 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
127
+ * the create's failure; they never carry a URL.
90
128
  */
91
- export async function recoverCreate(what, find, release, sleep) {
92
- const signal = AbortSignal.timeout(RECOVER_MS);
129
+ export async function recoverCreate(what, find, release, sleep, ms = RECOVER_MS) {
130
+ const signal = AbortSignal.timeout(ms);
93
131
  let found = ok([]);
94
132
  for (let tries = 0; tries < RECOVER_TRIES; tries++) {
95
133
  if (tries > 0)
@@ -104,8 +142,13 @@ export async function recoverCreate(what, find, release, sleep) {
104
142
  return `no ${what} carries its create label, so none was made or the vendor does not list it yet; its labels let a sweep find it`;
105
143
  const words = [];
106
144
  for (const id of found.value) {
107
- const released = await release(id);
108
- words.push(released.ok ? `the ${what} it made (${id}) was released` : `the ${what} it made (${id}) was not released (${released.error.code}), and its labels let a sweep find it`);
145
+ const released = await release(id, signal);
146
+ if (released.ok)
147
+ words.push(`the ${what} it made (${id}) was released`);
148
+ else if (signal.aborted)
149
+ words.push(`the ${what} it made (${id}) may still be running: the search and its release did not finish within ${ms / 1000} s, and its labels let a sweep find it`);
150
+ else
151
+ words.push(`the ${what} it made (${id}) was not released (${released.error.code}), and its labels let a sweep find it`);
109
152
  }
110
153
  return words.join("; ");
111
154
  }
@@ -134,8 +177,12 @@ export function checkBrowser(spec, capabilities, vendor, minLifetimeMs = 1) {
134
177
  const problem = labelsProblem(labels);
135
178
  if (problem)
136
179
  refusals.push({ field: "labels", message: problem });
137
- else if (Object.hasOwn(labels, CREATE_LABEL))
138
- refusals.push({ field: "labels", message: `the label ${CREATE_LABEL} is the provider's own: each create writes it, so a lost create finds its browser` });
180
+ else {
181
+ for (const own of [CREATE_LABEL, ATTEMPT_LABEL]) {
182
+ if (Object.hasOwn(labels, own))
183
+ refusals.push({ field: "labels", message: `the label ${own} is the provider's own: each create writes it, so a retried or lost create finds its browser` });
184
+ }
185
+ }
139
186
  }
140
187
  // A browser declares no gpu: one asked is refused, in the words every provider shares.
141
188
  refusals.push(...checkGpu(given.gpu, capabilities));
@@ -177,6 +224,18 @@ export function browserClient(hello, alive) {
177
224
  * up to confirm.polls times. Done means the vendor says it no longer runs, not that the request was sent; a session the
178
225
  * vendor no longer knows ("gone") is released. A session still running is a failure carrying the request's own error.
179
226
  */
227
+ /**
228
+ * A release a create runs for itself (its caller gone, or its browser the newer of the request's two), under a signal of
229
+ * its own that ends after `ms`, never the caller's: one that does not finish by then is a timeout that says the browser
230
+ * may still be running.
231
+ */
232
+ export async function boundedRelease(what, id, ms, release) {
233
+ const signal = AbortSignal.timeout(ms);
234
+ const released = await release(signal);
235
+ if (released.ok || !signal.aborted)
236
+ return released;
237
+ return fail("timeout", `its release did not finish within ${ms / 1000} s, so the ${what} ${id} may still be running`);
238
+ }
180
239
  export async function releaseConfirmed(o) {
181
240
  let failure;
182
241
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -22,6 +22,8 @@ export interface BrowserbaseSession {
22
22
  connectUrl?: string;
23
23
  userMetadata?: Record<string, unknown>;
24
24
  expiresAt?: string;
25
+ /** When Browserbase made the session. */
26
+ createdAt?: string;
25
27
  /** When the session started and ended, as Browserbase records them (no end while it runs). */
26
28
  startedAt?: string;
27
29
  endedAt?: string;
@@ -82,8 +84,6 @@ export declare function browserbaseRest({ apiKey, apiUrl, projectId, fetch: fetc
82
84
  projectId?: string;
83
85
  fetch?: typeof fetch;
84
86
  }): BrowserbaseApi;
85
- /** How long after a saving session ends Browserbase may still be writing its context back. */
86
- export declare const BROWSERBASE_PROFILE_SETTLE_MS = 5000;
87
87
  /** The directory Browserbase syncs a session's downloads from: a driver sets the download behaviour into it. */
88
88
  export declare const BROWSERBASE_DOWNLOADS_PATH = "downloads";
89
89
  export interface BrowserbaseProviderOptions {
@@ -102,7 +102,19 @@ export interface BrowserbaseProviderOptions {
102
102
  fetch?: typeof fetch;
103
103
  confirm?: ReleaseConfirm;
104
104
  sleep?: (ms: number) => Promise<void>;
105
+ /**
106
+ * How long, in all, a cleanup a create runs for itself may take: the release of the browser its POST made once its
107
+ * caller is gone, or once another create of the request made one first, and the search and release after a lost
108
+ * reply. Default RECOVER_MS. The caller's signal never cuts it short.
109
+ */
110
+ cleanupMs?: number;
105
111
  }
112
+ /**
113
+ * A session's signed CDP URL as a driver dials it: on the gateway that fronts the sessions' sockets where a server is
114
+ * behind one (BROWSERBASE_CONNECT_BASE_URL), its path under the gateway's and the signing query kept; else as Browserbase
115
+ * gave it. Only a URL on Browserbase's own domain moves, and a gateway that is no URL moves none.
116
+ */
117
+ export declare function throughGateway(connectUrl: string, connectBase: string | undefined): string;
106
118
  /** Computers that are Browserbase sessions. */
107
119
  export declare class BrowserbaseProvider implements ComputerProvider, BrowserComputerProvider {
108
120
  #private;
@@ -110,7 +122,7 @@ export declare class BrowserbaseProvider implements ComputerProvider, BrowserCom
110
122
  readonly version: string;
111
123
  readonly profiles: BrowserProfiles;
112
124
  readonly downloads: BrowserDownloads;
113
- constructor({ apiKey, projectId, apiUrl, env, fetch: fetcher, confirm, sleep }: BrowserbaseProviderOptions);
125
+ constructor({ apiKey, projectId, apiUrl, env, fetch: fetcher, confirm, sleep, cleanupMs }: BrowserbaseProviderOptions);
114
126
  /**
115
127
  * A browser: Browserbase ends a session at its timeout (lifetime vendor), at most 6 h; it reaches the open web; each
116
128
  * session is its own VM. browser is what its sessions offer beyond the protocol. Its downloads are read through the
@@ -120,8 +132,11 @@ export declare class BrowserbaseProvider implements ComputerProvider, BrowserCom
120
132
  capabilities(): ComputerCapabilities;
121
133
  check(spec: ComputerSpec): Refusal[];
122
134
  /**
123
- * Makes a session at most once: with keepAlive, so a dropped CDP client never ends it, the lifetime as its timeout in
124
- * whole seconds, and the labels as its userMetadata. spec.browser is the session's own options, each refused by check()
135
+ * Makes a session once per request (provider.md, Idempotent create): with keepAlive, so a dropped CDP client never
136
+ * ends it, the lifetime as its timeout in whole seconds, and the labels as its userMetadata, with the request's name
137
+ * (computerNameFor) as its create label. A request whose session Browserbase still runs or starts answers that one,
138
+ * found by its create label; one whose session was released here is refused exists; a create of a request in flight
139
+ * here waits for the first (CreateRequests). spec.browser is the session's own options, each refused by check()
125
140
  * unless declared.
126
141
  */
127
142
  create(spec: ComputerSpec, context: CreateContext): Promise<Result<CreatedComputer>>;