@edlsh/browse-core 0.0.0-stage → 0.2.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Enzo Lucchesi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # @edlsh/browse-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The host-neutral browser core behind [omp-browse](https://github.com/edlsh/omp-browse), [pi-browse](https://github.com/edlsh/pi-browse), and hermes-browse. It drives Browserbase sessions, local Chrome/Chromium, and remote browsers over CDP, runs Stagehand `act`/`observe`/`extract`, and implements JEV targeting, `ask`, HAR capture, cookie import, and the `/browse` settings command parser. Hosts add tool registration, a model adapter, and UI.
4
+
5
+ The package ships compiled ESM (`dist/`) so Bun and Node (including jiti) load it the same way.
6
+
7
+ ## Use
8
+
9
+ ```ts
10
+ import { BrowseSession, browserParameters, environmentConfig } from "@edlsh/browse-core";
11
+
12
+ const browser = new BrowseSession(environmentConfig, inference, hostClassify, { name: "MyHost", integration: "my-host-browse" });
13
+ const output = await browser.run(browserParameters.parse({ action: "start", backend: "local" }), { sessionId, profile, cwd });
14
+ ```
15
+
16
+ - `HostIdentity.name` appears in user-facing messages ("Use the MyHost model…") and names persistent local Chrome profiles `<name> browse` before each launch, so the toolbar avatar shows which harness owns a window. `integration` tags Browserbase session metadata, names the HAR `creator`, and prefixes the default HAR temp directory.
17
+ - `nameChromeProfile(userDataDir, name)` sets that name on a profile the host launches itself; it leaves a profile Chrome holds untouched.
18
+ - `ClientInference` supplies Stagehand's default inference. Without it, unconfigured AI calls use Browserbase Model Gateway.
19
+ - `settings.ts` holds the per-profile `/browse` settings file (`browserbase-ai.json`): `readSettings`, `writeSetting`, and the model-role helpers.
20
+
21
+ Stagehand is pinned to 4.3.0 and used unmodified. `overrides` forces zod 4.6.7 because of GHSA-mrhx-c7xc-m3w5 in Stagehand's zod pin. Run both real-browser suites before upgrading Stagehand.
22
+
23
+ ## Shared browsers
24
+
25
+ New browsers start locally unless the host or the profile's `/browse backend` setting chooses Browserbase.
26
+
27
+ A persistent profile (`localUserDataDir`) and an attached browser (`cdpUrl` or a named endpoint) are shared: any number of conversations, in one process or several (omp, pi, and Hermes at once), drive the same browser without closing it under each other. Stagehand's in-browser runtime admits one client, so the first conversation starts a broker (`dist/broker.js`, one detached process per browser, socket under `$XDG_RUNTIME_DIR` or the temp directory, mode 0600) that owns the browser and runs every conversation's calls on it. Each conversation keeps its own tabs, refs, and selected tab. Another conversation's tabs are hidden from `tabs` and `tab_select`, and `har_start` records only its own. A `browse_ai` call runs on the caller's own inference, one call at a time. `close` closes only the caller's tabs. The last conversation to leave quits a launched profile (so its cookies are written) or disconnects from an attached browser, and the broker exits 30 s after its last client.
28
+
29
+ Conversations sharing a browser must agree on its launch options: a `start` asking for a different `headless` mode, or different allowed or blocked domains, gets `shared_browser`. Temporary-profile launches stay private to their conversation. `BrowseSessionOptions.profileBroker: false` keeps shared browsers in-process (the broker uses this for itself).
30
+
31
+ ## Develop
32
+
33
+ ```sh
34
+ bun install
35
+ bun run check && bun test && bun run build
36
+ CHROME_PATH=/path/to/chrome bun run test:local # real local browser
37
+ CHROME_PATH=/path/to/chrome bun run test:shared # two processes on one persistent profile
38
+ bun run test:hosted # needs BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID
39
+ ```
40
+
41
+ Releases go through release-please; publishing uses npm trusted publishing from `publish.yml`.
package/dist/ask.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { type Classify, type ClassifyImage, type Cloudflare } from "./classifier.ts";
2
+ import type { AskFields } from "./schema.ts";
3
+ export declare const EXTRACT_MODEL = "@cf/cloudflare/clairic";
4
+ /** About 25k tokens: leaves room for the questions in Clairic's and Clef's 65k-token contexts. */
5
+ export declare const MAX_TEXT = 100000;
6
+ /** Clef Flash reads 24,576 tokens: about 72k characters of page text leaves room for the questions. */
7
+ export declare const DECIDE_TEXT: Record<string, number>;
8
+ export interface PageState {
9
+ url: string;
10
+ title: string;
11
+ tree: string;
12
+ }
13
+ /** bool answers carry the probability of yes; other answers carry the model's confidence. */
14
+ export type Answer = {
15
+ value: boolean;
16
+ probability: number;
17
+ } | {
18
+ value: string | number | null;
19
+ confidence: number;
20
+ };
21
+ export interface AskResult {
22
+ answers: Record<string, Answer>;
23
+ truncated?: true;
24
+ }
25
+ /**
26
+ * Where ask's two halves run: values on Clairic (Workers AI), bool and choice on `decide`, which reads at most
27
+ * `decideText` characters and also judges `images`. Clairic reads text only.
28
+ */
29
+ export interface AskModels {
30
+ cloudflare?: Cloudflare;
31
+ decide?: Classify;
32
+ decideText?: number;
33
+ images?: ClassifyImage[];
34
+ }
35
+ /** Which models a set of fields needs: a decision classifier for bool and choice, Clairic for everything else. */
36
+ export declare function askNeeds(fields: AskFields): {
37
+ decide: boolean;
38
+ extract: boolean;
39
+ };
40
+ /**
41
+ * Readable text of a Stagehand snapshot tree: named nodes as `role: name`, text nodes as plain lines, and unnamed
42
+ * nodes only when they carry a state such as `checkbox [checked]`. Text repeating the line above is dropped.
43
+ */
44
+ export declare function pageText(tree: string): string;
45
+ /**
46
+ * Answers typed questions about one page from its snapshot text. Clairic extracts values and the decision classifier
47
+ * answers bool and choice questions; when a call needs both, they run in parallel.
48
+ */
49
+ export declare function askPage(models: AskModels, page: PageState, fields: AskFields, signal: AbortSignal): Promise<AskResult>;
package/dist/ask.js ADDED
@@ -0,0 +1,108 @@
1
+ import { z } from "zod";
2
+ import { cloudflareRefusal } from "./classifier.js";
3
+ const API = "https://api.cloudflare.com/client/v4/accounts";
4
+ export const EXTRACT_MODEL = "@cf/cloudflare/clairic";
5
+ /** About 25k tokens: leaves room for the questions in Clairic's and Clef's 65k-token contexts. */
6
+ export const MAX_TEXT = 100_000;
7
+ /** Clef Flash reads 24,576 tokens: about 72k characters of page text leaves room for the questions. */
8
+ export const DECIDE_TEXT = { "@cf/cloudflare/clef-flash": 72_000 };
9
+ /** Bool and choice questions go to the decision classifier (Clef by default); every other field type is a value Clairic reads from the page. */
10
+ const DECISIONS = { bool: true, choice: true };
11
+ const envelope = z.object({ result: z.object({ answers: z.record(z.string(), z.unknown()) }) });
12
+ // Clairic answers null when the page does not determine the value (p_null above its default 0.5).
13
+ const extracted = z.object({ value: z.union([z.string(), z.number(), z.null()]), confidence: z.number().optional() });
14
+ /** Which models a set of fields needs: a decision classifier for bool and choice, Clairic for everything else. */
15
+ export function askNeeds(fields) {
16
+ const types = Object.values(fields).map(field => field.type);
17
+ return { decide: types.some(type => Object.hasOwn(DECISIONS, type)), extract: types.some(type => !Object.hasOwn(DECISIONS, type)) };
18
+ }
19
+ /**
20
+ * Readable text of a Stagehand snapshot tree: named nodes as `role: name`, text nodes as plain lines, and unnamed
21
+ * nodes only when they carry a state such as `checkbox [checked]`. Text repeating the line above is dropped.
22
+ */
23
+ export function pageText(tree) {
24
+ const lines = [];
25
+ for (const line of tree.split("\n")) {
26
+ const text = /^\s*\[\d+-\d+\] (.+)$/.exec(line)?.[1];
27
+ if (!text)
28
+ continue;
29
+ const role = text.split(/[:\s]/, 1)[0];
30
+ if (role === "InlineTextBox" || role === "LineBreak")
31
+ continue;
32
+ const name = text.startsWith(`${role}: `) ? text.slice(role.length + 2) : "";
33
+ if (!name && !text.includes("["))
34
+ continue;
35
+ const entry = role === "StaticText" ? name : text;
36
+ const previous = lines.at(-1);
37
+ if (previous !== entry && !(name && previous?.endsWith(name)))
38
+ lines.push(entry);
39
+ }
40
+ return lines.join("\n");
41
+ }
42
+ /** One Clairic run; a network error, 429, or 5xx gets one immediate retry. Response bodies are not echoed. */
43
+ async function extractValues(cloudflare, input, signal) {
44
+ for (let attempt = 1;; attempt++) {
45
+ let response;
46
+ try {
47
+ response = await fetch(`${API}/${encodeURIComponent(cloudflare.accountId)}/ai/run/${EXTRACT_MODEL}`, {
48
+ method: "POST", signal, body: JSON.stringify(input),
49
+ headers: { Authorization: `Bearer ${cloudflare.apiKey}`, "Content-Type": "application/json" },
50
+ });
51
+ }
52
+ catch (error) {
53
+ if (signal.aborted || attempt === 2)
54
+ throw signal.aborted ? error : new Error("Workers AI request failed with a network error.");
55
+ continue;
56
+ }
57
+ if (response.ok) {
58
+ const parsed = envelope.safeParse(await response.json().catch(() => undefined));
59
+ if (!parsed.success)
60
+ throw new Error("Workers AI returned an unexpected response.");
61
+ return parsed.data.result.answers;
62
+ }
63
+ const transient = response.status === 429 || response.status >= 500;
64
+ if (!transient || attempt === 2)
65
+ throw new Error(cloudflareRefusal(response.status));
66
+ }
67
+ }
68
+ /**
69
+ * Answers typed questions about one page from its snapshot text. Clairic extracts values and the decision classifier
70
+ * answers bool and choice questions; when a call needs both, they run in parallel.
71
+ */
72
+ export async function askPage(models, page, fields, signal) {
73
+ const full = pageText(page.tree);
74
+ const decideLimit = Math.min(models.decideText ?? MAX_TEXT, MAX_TEXT);
75
+ const entries = Object.entries(fields);
76
+ const decide = entries.filter(([, field]) => Object.hasOwn(DECISIONS, field.type));
77
+ const extract = entries.filter(([, field]) => !Object.hasOwn(DECISIONS, field.type));
78
+ const questions = Object.fromEntries(decide.map(([name, field]) => [name, field.type === "bool"
79
+ ? { type: "bool", instructions: field.instructions }
80
+ : { type: "choice", instructions: field.instructions, criteria: Object.fromEntries(field.options.map(option => [option, option])) }]));
81
+ const [decided, read] = await Promise.all([
82
+ decide.length ? models.decide({ state: { url: page.url, title: page.title, text: full.slice(0, decideLimit) }, questions, ...(models.images?.length ? { images: models.images } : {}) }, signal) : {},
83
+ extract.length ? extractValues(models.cloudflare, {
84
+ model: "clairic", state: `${page.title}\n${page.url}\n\n${full.slice(0, MAX_TEXT)}`,
85
+ fields: Object.fromEntries(extract.map(([name, field]) => [name, { type: field.type, instructions: field.instructions, ...(field.unit ? { unit: field.unit } : {}) }])),
86
+ }, signal) : {},
87
+ ]);
88
+ const answers = {};
89
+ for (const [name, field] of entries) {
90
+ if (field.type === "bool" || field.type === "choice") {
91
+ const answer = decided[name];
92
+ if (answer?.type === "bool" && field.type === "bool")
93
+ answers[name] = { value: answer.probability >= 0.5, probability: answer.probability };
94
+ else if (answer?.type === "choice" && field.type === "choice")
95
+ answers[name] = { value: answer.choice, confidence: answer.confidence };
96
+ else
97
+ throw new Error("The decision classifier returned an unexpected answer.");
98
+ }
99
+ else {
100
+ const answer = extracted.safeParse(read[name]);
101
+ if (!answer.success)
102
+ throw new Error("Workers AI returned an unexpected answer.");
103
+ answers[name] = { value: answer.data.value, confidence: answer.data.confidence ?? 0 };
104
+ }
105
+ }
106
+ const truncated = (decide.length > 0 && full.length > decideLimit) || (extract.length > 0 && full.length > MAX_TEXT);
107
+ return { answers, ...(truncated ? { truncated: true } : {}) };
108
+ }
@@ -0,0 +1,39 @@
1
+ import { type RunContext } from "./broker-protocol.ts";
2
+ import type { HostClassify } from "./classifier.ts";
3
+ import { type BrowserOutput, type ClientGenerate, type ConfigResolver, type HostIdentity } from "./session.ts";
4
+ import type { AIParams, BrowserParams } from "./schema.ts";
5
+ /** What a conversation in this process lends the broker. */
6
+ export interface BrokerHandlers {
7
+ resolveConfig: ConfigResolver;
8
+ generate?: ClientGenerate;
9
+ classify?: HostClassify;
10
+ }
11
+ export declare class BrokerConnection {
12
+ private readonly socket;
13
+ private readonly socketPath;
14
+ private readonly runs;
15
+ private readonly conversations;
16
+ private hello;
17
+ private nextId;
18
+ private buffer;
19
+ private ended;
20
+ private constructor();
21
+ /** Whether the broker went away; the next call starts or finds a new one. */
22
+ get closed(): boolean;
23
+ /** The connection for a shared browser key, starting its broker if none answers. */
24
+ static for(key: string): Promise<BrokerConnection>;
25
+ private static open;
26
+ private send;
27
+ private hold;
28
+ private release;
29
+ private data;
30
+ private receive;
31
+ private answer;
32
+ private fail;
33
+ /** Opens a conversation in the broker; its calls then run on the shared browser. */
34
+ openConversation(conv: string, identity: HostIdentity, handlers: BrokerHandlers): void;
35
+ /** Runs one call in the broker. A cancel is passed on, and the broker's own account of the outcome awaited briefly. */
36
+ run(conv: string, params: BrowserParams | AIParams, context: RunContext, ai: boolean, defaultBackend: "browserbase" | "local", signal: AbortSignal): Promise<BrowserOutput>;
37
+ /** Ends a conversation in the broker: its tabs close, and the browser goes with the last conversation. */
38
+ closeConversation(conv: string): Promise<void>;
39
+ }
@@ -0,0 +1,254 @@
1
+ // A host process's side of the browser broker (broker.ts): one socket per shared browser, carrying every conversation
2
+ // in this process that uses it. The broker asks back for configuration, Stagehand inference, and host classifiers.
3
+ import { spawn } from "node:child_process";
4
+ import { closeSync, openSync } from "node:fs";
5
+ import { connect } from "node:net";
6
+ import { extname } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { setTimeout as delay } from "node:timers/promises";
9
+ import { z } from "zod";
10
+ import { BROKER_PROTOCOL, brokerMessage, brokerSocketPath, classifyRequest, errorBodyOf, } from "./broker-protocol.js";
11
+ import { BrowseToolError } from "./session.js";
12
+ const CONNECT_TIMEOUT_MS = 15_000;
13
+ /** After a cancel, how long a call still waits for the broker's own account of what happened. */
14
+ const CANCEL_GRACE_MS = 15_000;
15
+ function errorOf(body) {
16
+ if (body.code)
17
+ return new BrowseToolError(body.code, body.message);
18
+ return Object.assign(new Error(body.message), { name: body.name });
19
+ }
20
+ const encodedOutput = z.looseObject({ action: z.string(), sessionId: z.string().nullable(), image: z.string().optional() });
21
+ function decodeOutput(value) {
22
+ const { image, ...rest } = encodedOutput.parse(value);
23
+ // SAFETY: the broker sends a BrowserOutput it produced, with only the image re-encoded as base64.
24
+ const output = rest;
25
+ if (image)
26
+ output.image = new Uint8Array(Buffer.from(image, "base64"));
27
+ return output;
28
+ }
29
+ /** Variables the broker and its Chrome need; the host's secrets stay behind, since configuration arrives per call. */
30
+ const BROKER_ENV = ["PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "LC_ALL", "TMPDIR", "TZ", "DISPLAY", "WAYLAND_DISPLAY",
31
+ "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "XAUTHORITY", "CHROME_PATH"];
32
+ function startBroker(socketPath) {
33
+ // The source tree runs broker.ts under Bun; the published package runs broker.js under Node or Bun.
34
+ const script = fileURLToPath(new URL(`./broker${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
35
+ const env = { BUN_BE_BUN: "1" };
36
+ for (const name of BROKER_ENV) {
37
+ const value = process.env[name];
38
+ if (value)
39
+ env[name] = value;
40
+ }
41
+ const log = openSync(socketPath.replace(/\.sock$/, ".log"), "a", 0o600);
42
+ try {
43
+ // OMP is a compiled Bun binary: BUN_BE_BUN makes its execPath run the script as Bun would. Node and Bun ignore it.
44
+ spawn(process.execPath, [script, socketPath], { detached: true, stdio: ["ignore", log, log], env }).unref();
45
+ }
46
+ finally {
47
+ closeSync(log);
48
+ }
49
+ }
50
+ function dial(socketPath) {
51
+ const { promise, resolve, reject } = Promise.withResolvers();
52
+ const socket = connect(socketPath);
53
+ socket.once("connect", () => { socket.off("error", reject); resolve(socket); });
54
+ socket.once("error", reject);
55
+ return promise;
56
+ }
57
+ const connections = new Map();
58
+ export class BrokerConnection {
59
+ socket;
60
+ socketPath;
61
+ runs = new Map();
62
+ conversations = new Map();
63
+ hello = Promise.withResolvers();
64
+ nextId = 1;
65
+ buffer = "";
66
+ ended = false;
67
+ constructor(socket, socketPath) {
68
+ this.socket = socket;
69
+ this.socketPath = socketPath;
70
+ socket.setEncoding("utf8");
71
+ socket.on("data", chunk => this.data(String(chunk)));
72
+ socket.on("close", () => this.fail());
73
+ socket.on("error", () => undefined);
74
+ // An idle connection must not keep the host process alive; calls in flight hold it.
75
+ socket.unref();
76
+ }
77
+ /** Whether the broker went away; the next call starts or finds a new one. */
78
+ get closed() { return this.ended; }
79
+ /** The connection for a shared browser key, starting its broker if none answers. */
80
+ static for(key) {
81
+ const socketPath = brokerSocketPath(key);
82
+ let connection = connections.get(socketPath);
83
+ if (!connection) {
84
+ connection = BrokerConnection.open(socketPath);
85
+ connections.set(socketPath, connection);
86
+ connection.catch(() => { if (connections.get(socketPath) === connection)
87
+ connections.delete(socketPath); });
88
+ }
89
+ return connection;
90
+ }
91
+ static async open(socketPath) {
92
+ let socket;
93
+ try {
94
+ socket = await dial(socketPath);
95
+ }
96
+ catch {
97
+ startBroker(socketPath);
98
+ for (const deadline = Date.now() + CONNECT_TIMEOUT_MS; !socket && Date.now() < deadline;) {
99
+ await delay(100);
100
+ socket = await dial(socketPath).catch(() => undefined);
101
+ }
102
+ }
103
+ if (!socket)
104
+ throw new BrowseToolError("broker_unavailable", `Could not start the shared browser service; see ${socketPath.replace(/\.sock$/, ".log")}.`);
105
+ const connection = new BrokerConnection(socket, socketPath);
106
+ connection.send({ t: "hello", protocol: BROKER_PROTOCOL });
107
+ socket.ref();
108
+ const protocol = await Promise.race([connection.hello.promise, delay(5_000).then(() => undefined)]).finally(() => socket.unref());
109
+ if (protocol !== BROKER_PROTOCOL) {
110
+ socket.destroy();
111
+ throw new BrowseToolError("broker_version", `The shared browser service for this browser speaks protocol ${protocol ?? "unknown"}, not ${BROKER_PROTOCOL}. Close the browser in every other conversation using it, then start again.`);
112
+ }
113
+ return connection;
114
+ }
115
+ send(message) {
116
+ if (!this.ended)
117
+ this.socket.write(`${JSON.stringify(message)}\n`);
118
+ }
119
+ hold() { this.socket.ref(); }
120
+ release() { if (!this.runs.size)
121
+ this.socket.unref(); }
122
+ data(chunk) {
123
+ this.buffer += chunk;
124
+ for (let end = this.buffer.indexOf("\n"); end >= 0; end = this.buffer.indexOf("\n")) {
125
+ const line = this.buffer.slice(0, end);
126
+ this.buffer = this.buffer.slice(end + 1);
127
+ if (!line.trim())
128
+ continue;
129
+ let parsed;
130
+ try {
131
+ parsed = brokerMessage.safeParse(JSON.parse(line));
132
+ }
133
+ catch {
134
+ parsed = undefined;
135
+ }
136
+ if (parsed?.success)
137
+ this.receive(parsed.data);
138
+ }
139
+ }
140
+ receive(message) {
141
+ switch (message.t) {
142
+ case "hello":
143
+ this.hello.resolve(message.protocol);
144
+ return;
145
+ case "result": {
146
+ const waiter = this.runs.get(message.id);
147
+ this.runs.delete(message.id);
148
+ if (message.ok)
149
+ waiter?.resolve(message.output);
150
+ else
151
+ waiter?.reject(errorOf(message.error));
152
+ this.release();
153
+ return;
154
+ }
155
+ case "released": {
156
+ const waiter = this.runs.get(message.id);
157
+ this.runs.delete(message.id);
158
+ waiter?.resolve(undefined);
159
+ this.release();
160
+ return;
161
+ }
162
+ case "ask":
163
+ void this.answer(message.cb, message.conv, message.request);
164
+ return;
165
+ }
166
+ }
167
+ async answer(cb, conv, request) {
168
+ const handlers = this.conversations.get(conv);
169
+ try {
170
+ if (!handlers)
171
+ throw new Error("The conversation this request belongs to has ended.");
172
+ let value;
173
+ if (request.kind === "config") {
174
+ value = await handlers.resolveConfig({ ...request.context, signal: AbortSignal.timeout(60_000) });
175
+ }
176
+ else if (request.kind === "generate") {
177
+ if (!handlers.generate)
178
+ throw new Error("This conversation has no Stagehand inference to lend.");
179
+ // SAFETY: the broker forwards Stagehand's own generate() parameters, unchanged apart from the JSON round trip.
180
+ value = await handlers.generate(request.params);
181
+ }
182
+ else {
183
+ if (!handlers.classify)
184
+ throw new Error("This conversation has no host classifier.");
185
+ const parsed = classifyRequest.parse(request.request);
186
+ value = await handlers.classify(request.model, parsed, AbortSignal.timeout(120_000));
187
+ }
188
+ // JSON drops undefined fields, which the schema on the other side treats as absent.
189
+ this.send({ t: "answer", cb, ok: true, value: JSON.parse(JSON.stringify(value ?? null)) });
190
+ }
191
+ catch (error) {
192
+ this.send({ t: "answer", cb, ok: false, error: errorBodyOf(error) });
193
+ }
194
+ }
195
+ fail() {
196
+ if (this.ended)
197
+ return;
198
+ this.ended = true;
199
+ if (connections.get(this.socketPath))
200
+ connections.delete(this.socketPath);
201
+ this.hello.resolve(-1);
202
+ const lost = new BrowseToolError("session_lost", "The shared browser service stopped; the action may have completed. Start again.");
203
+ for (const waiter of this.runs.values())
204
+ waiter.reject(lost);
205
+ this.runs.clear();
206
+ this.conversations.clear();
207
+ }
208
+ /** Opens a conversation in the broker; its calls then run on the shared browser. */
209
+ openConversation(conv, identity, handlers) {
210
+ this.conversations.set(conv, handlers);
211
+ this.send({ t: "open", conv, identity, inference: Boolean(handlers.generate), classify: Boolean(handlers.classify) });
212
+ }
213
+ /** Runs one call in the broker. A cancel is passed on, and the broker's own account of the outcome awaited briefly. */
214
+ async run(conv, params, context, ai, defaultBackend, signal) {
215
+ if (this.ended)
216
+ throw new BrowseToolError("session_lost", "The shared browser service stopped. Start again.");
217
+ const id = this.nextId++;
218
+ const waiter = Promise.withResolvers();
219
+ this.runs.set(id, waiter);
220
+ this.hold();
221
+ const onAbort = () => {
222
+ this.send({ t: "cancel", id });
223
+ setTimeout(() => waiter.reject(new BrowseToolError("cancelled", "Operation cancelled; the shared browser service did not confirm the outcome. Take a snapshot before retrying.")), CANCEL_GRACE_MS).unref();
224
+ };
225
+ signal.addEventListener("abort", onAbort, { once: true });
226
+ this.send({ t: "run", id, conv, params: JSON.parse(JSON.stringify(params)), context, ai, defaultBackend });
227
+ try {
228
+ return decodeOutput(await waiter.promise);
229
+ }
230
+ finally {
231
+ signal.removeEventListener("abort", onAbort);
232
+ this.runs.delete(id);
233
+ this.release();
234
+ }
235
+ }
236
+ /** Ends a conversation in the broker: its tabs close, and the browser goes with the last conversation. */
237
+ async closeConversation(conv) {
238
+ if (this.ended)
239
+ return;
240
+ const id = this.nextId++;
241
+ const waiter = Promise.withResolvers();
242
+ this.runs.set(id, waiter);
243
+ this.hold();
244
+ this.send({ t: "release", id, conv });
245
+ try {
246
+ await Promise.race([waiter.promise, delay(10_000)]);
247
+ }
248
+ finally {
249
+ this.conversations.delete(conv);
250
+ this.runs.delete(id);
251
+ this.release();
252
+ }
253
+ }
254
+ }