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

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/dist/browser.d.ts CHANGED
@@ -51,29 +51,78 @@ 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;
99
+ /**
100
+ * Whether a lost create's browser (`mine`) is left to another create of its request rather than released: it still runs,
101
+ * no older browser of the request runs (so every converge keeps it), and the request's browsers, ended ones included,
102
+ * hold a newer one, which only another create made: that create's converge answers mine. A lost create whose browser is
103
+ * the request's only one releases it.
104
+ */
105
+ export declare function leftToConverge(mine: string, made: ReadonlyArray<HeldBrowser & {
106
+ live: boolean;
107
+ }>): boolean;
63
108
  /**
64
109
  * Whether a create that threw may still have made a browser: anything but the vendor's own 4xx answer (a refusal, which
65
110
  * makes nothing). A request not answered, aborted, cut short, or answered 5xx or with a body that is no browser may
66
111
  * have been admitted.
67
112
  */
68
113
  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. */
114
+ /**
115
+ * How long a lost create's browser is looked for and released, in all, and how often: a vendor may list it a moment
116
+ * late. Also the default bound of every other release a create runs for itself (a provider's cleanupMs).
117
+ */
70
118
  export declare const RECOVER_MS = 30000;
71
119
  /**
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.
120
+ * After a create whose outcome is unknown: the browsers carrying its create label, found and released under a signal
121
+ * of the recovery's own, `ms` in all (the caller's may be what ended the create), save one `leave` says another create
122
+ * of the request answers (leftToConverge). The words say what became of them, for the create's failure; they never
123
+ * carry a URL.
75
124
  */
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>;
125
+ 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, leave?: (id: string, signal: AbortSignal) => Promise<boolean>): Promise<string>;
77
126
  /**
78
127
  * The checks every browser provider makes before a vendor call: the image is chromium, the lifetime is within the
79
128
  * 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 +142,12 @@ export declare function browserClient(hello: HelloResult, alive: (signal?: Abort
93
142
  * up to confirm.polls times. Done means the vendor says it no longer runs, not that the request was sent; a session the
94
143
  * vendor no longer knows ("gone") is released. A session still running is a failure carrying the request's own error.
95
144
  */
145
+ /**
146
+ * A release a create runs for itself (its caller gone, or its browser the newer of the request's two), under a signal of
147
+ * its own that ends after `ms`, never the caller's: one that does not finish by then is a timeout that says the browser
148
+ * may still be running.
149
+ */
150
+ export declare function boundedRelease(what: string, id: string, ms: number, release: (signal: AbortSignal) => Promise<Result<void>>): Promise<Result<void>>;
96
151
  export declare function releaseConfirmed(o: {
97
152
  request: () => Promise<Result<"gone" | "asked">>;
98
153
  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,66 @@ 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
+ }
108
+ /**
109
+ * Whether a lost create's browser (`mine`) is left to another create of its request rather than released: it still runs,
110
+ * no older browser of the request runs (so every converge keeps it), and the request's browsers, ended ones included,
111
+ * hold a newer one, which only another create made: that create's converge answers mine. A lost create whose browser is
112
+ * the request's only one releases it.
113
+ */
114
+ export function leftToConverge(mine, made) {
115
+ const own = made.find((one) => one.id === mine);
116
+ if (own === undefined || !own.live)
117
+ return false;
118
+ if (made.some((one) => one.id !== mine && one.live && oldestBrowserFirst(one, own) < 0))
119
+ return false;
120
+ return made.some((one) => one.id !== mine && oldestBrowserFirst(own, one) < 0);
121
+ }
73
122
  /**
74
123
  * Whether a create that threw may still have made a browser: anything but the vendor's own 4xx answer (a refusal, which
75
124
  * makes nothing). A request not answered, aborted, cut short, or answered 5xx or with a body that is no browser may
@@ -79,17 +128,21 @@ export function createUncertain(error) {
79
128
  const status = error?.status;
80
129
  return !(typeof status === "number" && status >= 400 && status < 500);
81
130
  }
82
- /** How long a lost create's browser is looked for, in all, and how often: a vendor may list it a moment late. */
131
+ /**
132
+ * How long a lost create's browser is looked for and released, in all, and how often: a vendor may list it a moment
133
+ * late. Also the default bound of every other release a create runs for itself (a provider's cleanupMs).
134
+ */
83
135
  export const RECOVER_MS = 30_000;
84
136
  const RECOVER_TRIES = 3;
85
137
  const RECOVER_GAP_MS = 2_000;
86
138
  /**
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.
139
+ * After a create whose outcome is unknown: the browsers carrying its create label, found and released under a signal
140
+ * of the recovery's own, `ms` in all (the caller's may be what ended the create), save one `leave` says another create
141
+ * of the request answers (leftToConverge). The words say what became of them, for the create's failure; they never
142
+ * carry a URL.
90
143
  */
91
- export async function recoverCreate(what, find, release, sleep) {
92
- const signal = AbortSignal.timeout(RECOVER_MS);
144
+ export async function recoverCreate(what, find, release, sleep, ms = RECOVER_MS, leave) {
145
+ const signal = AbortSignal.timeout(ms);
93
146
  let found = ok([]);
94
147
  for (let tries = 0; tries < RECOVER_TRIES; tries++) {
95
148
  if (tries > 0)
@@ -104,8 +157,17 @@ export async function recoverCreate(what, find, release, sleep) {
104
157
  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
158
  const words = [];
106
159
  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`);
160
+ if (leave !== undefined && (await leave(id, signal))) {
161
+ words.push(`the ${what} it made (${id}) is its request's oldest, which another create of the request answers: it is left running for that create, to its lifetime`);
162
+ continue;
163
+ }
164
+ const released = await release(id, signal);
165
+ if (released.ok)
166
+ words.push(`the ${what} it made (${id}) was released`);
167
+ else if (signal.aborted)
168
+ 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`);
169
+ else
170
+ words.push(`the ${what} it made (${id}) was not released (${released.error.code}), and its labels let a sweep find it`);
109
171
  }
110
172
  return words.join("; ");
111
173
  }
@@ -134,8 +196,12 @@ export function checkBrowser(spec, capabilities, vendor, minLifetimeMs = 1) {
134
196
  const problem = labelsProblem(labels);
135
197
  if (problem)
136
198
  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` });
199
+ else {
200
+ for (const own of [CREATE_LABEL, ATTEMPT_LABEL]) {
201
+ if (Object.hasOwn(labels, own))
202
+ 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` });
203
+ }
204
+ }
139
205
  }
140
206
  // A browser declares no gpu: one asked is refused, in the words every provider shares.
141
207
  refusals.push(...checkGpu(given.gpu, capabilities));
@@ -177,6 +243,18 @@ export function browserClient(hello, alive) {
177
243
  * up to confirm.polls times. Done means the vendor says it no longer runs, not that the request was sent; a session the
178
244
  * vendor no longer knows ("gone") is released. A session still running is a failure carrying the request's own error.
179
245
  */
246
+ /**
247
+ * A release a create runs for itself (its caller gone, or its browser the newer of the request's two), under a signal of
248
+ * its own that ends after `ms`, never the caller's: one that does not finish by then is a timeout that says the browser
249
+ * may still be running.
250
+ */
251
+ export async function boundedRelease(what, id, ms, release) {
252
+ const signal = AbortSignal.timeout(ms);
253
+ const released = await release(signal);
254
+ if (released.ok || !signal.aborted)
255
+ return released;
256
+ return fail("timeout", `its release did not finish within ${ms / 1000} s, so the ${what} ${id} may still be running`);
257
+ }
180
258
  export async function releaseConfirmed(o) {
181
259
  let failure;
182
260
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -8,6 +8,8 @@ export declare const BROWSERBASE_CDP_DOMAIN = "browserbase.com";
8
8
  export declare const BROWSERBASE_MAX_LIFETIME_MS: number;
9
9
  /** Browserbase's shortest session timeout: 60 s. */
10
10
  export declare const BROWSERBASE_MIN_LIFETIME_MS = 60000;
11
+ /** The statuses of a session that runs (PENDING bills once it starts); any other has ended. */
12
+ type SessionStatus = "RUNNING" | "PENDING" | "COMPLETED" | "ERROR" | "TIMED_OUT";
11
13
  /** The userMetadata key a label key is written under: each "." as "_", since Browserbase refuses a dot there. */
12
14
  export declare const metadataKey: (labelKey: string) => string;
13
15
  /** The label key a userMetadata key reads back as: each "_" as ".". */
@@ -22,6 +24,8 @@ export interface BrowserbaseSession {
22
24
  connectUrl?: string;
23
25
  userMetadata?: Record<string, unknown>;
24
26
  expiresAt?: string;
27
+ /** When Browserbase made the session. */
28
+ createdAt?: string;
25
29
  /** When the session started and ended, as Browserbase records them (no end while it runs). */
26
30
  startedAt?: string;
27
31
  endedAt?: string;
@@ -57,7 +61,7 @@ export interface BrowserbaseApi {
57
61
  /** undefined when Browserbase does not know the session (404). */
58
62
  retrieve(id: string, signal?: AbortSignal): Promise<BrowserbaseSession | undefined>;
59
63
  list(query: {
60
- status: "RUNNING" | "PENDING";
64
+ status: SessionStatus;
61
65
  q?: string;
62
66
  }, signal?: AbortSignal): Promise<BrowserbaseSession[]>;
63
67
  /** "gone" when Browserbase does not know the session (404). */
@@ -100,6 +104,12 @@ export interface BrowserbaseProviderOptions {
100
104
  fetch?: typeof fetch;
101
105
  confirm?: ReleaseConfirm;
102
106
  sleep?: (ms: number) => Promise<void>;
107
+ /**
108
+ * How long, in all, a cleanup a create runs for itself may take: the release of the browser its POST made once its
109
+ * caller is gone, or once another create of the request made one first, and the search and release after a lost
110
+ * reply. Default RECOVER_MS. The caller's signal never cuts it short.
111
+ */
112
+ cleanupMs?: number;
103
113
  }
104
114
  /**
105
115
  * A session's signed CDP URL as a driver dials it: on the gateway that fronts the sessions' sockets where a server is
@@ -114,7 +124,7 @@ export declare class BrowserbaseProvider implements ComputerProvider, BrowserCom
114
124
  readonly version: string;
115
125
  readonly profiles: BrowserProfiles;
116
126
  readonly downloads: BrowserDownloads;
117
- constructor({ apiKey, projectId, apiUrl, env, fetch: fetcher, confirm, sleep }: BrowserbaseProviderOptions);
127
+ constructor({ apiKey, projectId, apiUrl, env, fetch: fetcher, confirm, sleep, cleanupMs }: BrowserbaseProviderOptions);
118
128
  /**
119
129
  * A browser: Browserbase ends a session at its timeout (lifetime vendor), at most 6 h; it reaches the open web; each
120
130
  * session is its own VM. browser is what its sessions offer beyond the protocol. Its downloads are read through the
@@ -124,8 +134,11 @@ export declare class BrowserbaseProvider implements ComputerProvider, BrowserCom
124
134
  capabilities(): ComputerCapabilities;
125
135
  check(spec: ComputerSpec): Refusal[];
126
136
  /**
127
- * Makes a session at most once: with keepAlive, so a dropped CDP client never ends it, the lifetime as its timeout in
128
- * whole seconds, and the labels as its userMetadata. spec.browser is the session's own options, each refused by check()
137
+ * Makes a session once per request (provider.md, Idempotent create): with keepAlive, so a dropped CDP client never
138
+ * ends it, the lifetime as its timeout in whole seconds, and the labels as its userMetadata, with the request's name
139
+ * (computerNameFor) as its create label. A request whose session Browserbase still runs or starts answers that one,
140
+ * found by its create label; one whose session was released here is refused exists; a create of a request in flight
141
+ * here waits for the first (CreateRequests). spec.browser is the session's own options, each refused by check()
129
142
  * unless declared.
130
143
  */
131
144
  create(spec: ComputerSpec, context: CreateContext): Promise<Result<CreatedComputer>>;
@@ -168,3 +181,4 @@ export declare class BrowserbaseProvider implements ComputerProvider, BrowserCom
168
181
  export declare function create(options: BrowserbaseProviderOptions): BrowserbaseProvider;
169
182
  /** The conformance CLI's module for Browserbase: its live switch, its image and its notes. */
170
183
  export declare const conformance: () => Promise<typeof import("./conformance/browserbase.js")>;
184
+ export {};