@edlsh/browse-core 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,18 +13,28 @@ const browser = new BrowseSession(environmentConfig, inference, hostClassify, {
13
13
  const output = await browser.run(browserParameters.parse({ action: "start", backend: "local" }), { sessionId, profile, cwd });
14
14
  ```
15
15
 
16
- - `HostIdentity.name` appears in user-facing messages ("Use the MyHost model…"). `integration` tags Browserbase session metadata, names the HAR `creator`, and prefixes the default HAR temp directory.
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.
17
18
  - `ClientInference` supplies Stagehand's default inference. Without it, unconfigured AI calls use Browserbase Model Gateway.
18
19
  - `settings.ts` holds the per-profile `/browse` settings file (`browserbase-ai.json`): `readSettings`, `writeSetting`, and the model-role helpers.
19
20
 
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.
21
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 works in a tab of its own (the launcher takes a launched profile's first tab), with its own refs and selected tab. In an attached browser the user's tabs are left alone unless a conversation selects one by `tabId`. 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
+
22
31
  ## Develop
23
32
 
24
33
  ```sh
25
34
  bun install
26
35
  bun run check && bun test && bun run build
27
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
28
38
  bun run test:hosted # needs BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID
29
39
  ```
30
40
 
@@ -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
+ }
@@ -0,0 +1,194 @@
1
+ import { z } from "zod";
2
+ /** Bumped on any incompatible message change; a client never talks to a broker of another protocol. */
3
+ export declare const BROKER_PROTOCOL = 1;
4
+ declare const json: z.ZodJSONSchema;
5
+ /** A JSON value as it crosses the socket. */
6
+ export type Json = z.infer<typeof json>;
7
+ declare const errorBody: z.ZodObject<{
8
+ code: z.ZodOptional<z.ZodString>;
9
+ name: z.ZodString;
10
+ message: z.ZodString;
11
+ }, z.core.$strip>;
12
+ export type ErrorBody = z.infer<typeof errorBody>;
13
+ /** The part of a conversation's context that crosses to the broker; the signal stays with the caller. */
14
+ declare const runContext: z.ZodObject<{
15
+ sessionId: z.ZodString;
16
+ profile: z.ZodString;
17
+ cwd: z.ZodString;
18
+ backend: z.ZodOptional<z.ZodEnum<{
19
+ browserbase: "browserbase";
20
+ local: "local";
21
+ }>>;
22
+ classifier: z.ZodOptional<z.ZodString>;
23
+ }, z.core.$strip>;
24
+ export type RunContext = z.infer<typeof runContext>;
25
+ export declare const clientMessage: z.ZodUnion<readonly [z.ZodObject<{
26
+ t: z.ZodLiteral<"hello">;
27
+ protocol: z.ZodNumber;
28
+ }, z.core.$strip>, z.ZodObject<{
29
+ t: z.ZodLiteral<"open">;
30
+ conv: z.ZodString;
31
+ identity: z.ZodObject<{
32
+ name: z.ZodString;
33
+ integration: z.ZodString;
34
+ }, z.core.$strip>;
35
+ inference: z.ZodBoolean;
36
+ classify: z.ZodBoolean;
37
+ }, z.core.$strip>, z.ZodObject<{
38
+ t: z.ZodLiteral<"run">;
39
+ id: z.ZodNumber;
40
+ conv: z.ZodString;
41
+ params: z.ZodJSONSchema;
42
+ context: z.ZodObject<{
43
+ sessionId: z.ZodString;
44
+ profile: z.ZodString;
45
+ cwd: z.ZodString;
46
+ backend: z.ZodOptional<z.ZodEnum<{
47
+ browserbase: "browserbase";
48
+ local: "local";
49
+ }>>;
50
+ classifier: z.ZodOptional<z.ZodString>;
51
+ }, z.core.$strip>;
52
+ ai: z.ZodBoolean;
53
+ defaultBackend: z.ZodEnum<{
54
+ browserbase: "browserbase";
55
+ local: "local";
56
+ }>;
57
+ }, z.core.$strip>, z.ZodObject<{
58
+ t: z.ZodLiteral<"cancel">;
59
+ id: z.ZodNumber;
60
+ }, z.core.$strip>, z.ZodObject<{
61
+ t: z.ZodLiteral<"release">;
62
+ id: z.ZodNumber;
63
+ conv: z.ZodString;
64
+ }, z.core.$strip>, z.ZodObject<{
65
+ t: z.ZodLiteral<"answer">;
66
+ cb: z.ZodNumber;
67
+ ok: z.ZodLiteral<true>;
68
+ value: z.ZodJSONSchema;
69
+ }, z.core.$strip>, z.ZodObject<{
70
+ t: z.ZodLiteral<"answer">;
71
+ cb: z.ZodNumber;
72
+ ok: z.ZodLiteral<false>;
73
+ error: z.ZodObject<{
74
+ code: z.ZodOptional<z.ZodString>;
75
+ name: z.ZodString;
76
+ message: z.ZodString;
77
+ }, z.core.$strip>;
78
+ }, z.core.$strip>]>;
79
+ export type ClientMessage = z.infer<typeof clientMessage>;
80
+ export declare const brokerMessage: z.ZodUnion<readonly [z.ZodObject<{
81
+ t: z.ZodLiteral<"hello">;
82
+ protocol: z.ZodNumber;
83
+ }, z.core.$strip>, z.ZodObject<{
84
+ t: z.ZodLiteral<"result">;
85
+ id: z.ZodNumber;
86
+ ok: z.ZodLiteral<true>;
87
+ output: z.ZodJSONSchema;
88
+ }, z.core.$strip>, z.ZodObject<{
89
+ t: z.ZodLiteral<"result">;
90
+ id: z.ZodNumber;
91
+ ok: z.ZodLiteral<false>;
92
+ error: z.ZodObject<{
93
+ code: z.ZodOptional<z.ZodString>;
94
+ name: z.ZodString;
95
+ message: z.ZodString;
96
+ }, z.core.$strip>;
97
+ }, z.core.$strip>, z.ZodObject<{
98
+ t: z.ZodLiteral<"released">;
99
+ id: z.ZodNumber;
100
+ }, z.core.$strip>, z.ZodObject<{
101
+ t: z.ZodLiteral<"ask">;
102
+ cb: z.ZodNumber;
103
+ conv: z.ZodString;
104
+ request: z.ZodDiscriminatedUnion<[z.ZodObject<{
105
+ kind: z.ZodLiteral<"config">;
106
+ context: z.ZodObject<{
107
+ sessionId: z.ZodString;
108
+ profile: z.ZodString;
109
+ cwd: z.ZodString;
110
+ backend: z.ZodOptional<z.ZodEnum<{
111
+ browserbase: "browserbase";
112
+ local: "local";
113
+ }>>;
114
+ classifier: z.ZodOptional<z.ZodString>;
115
+ purpose: z.ZodEnum<{
116
+ ask: "ask";
117
+ browser: "browser";
118
+ ai: "ai";
119
+ jev: "jev";
120
+ }>;
121
+ }, z.core.$strip>;
122
+ }, z.core.$strip>, z.ZodObject<{
123
+ kind: z.ZodLiteral<"generate">;
124
+ params: z.ZodJSONSchema;
125
+ }, z.core.$strip>, z.ZodObject<{
126
+ kind: z.ZodLiteral<"classify">;
127
+ model: z.ZodString;
128
+ request: z.ZodJSONSchema;
129
+ }, z.core.$strip>], "kind">;
130
+ }, z.core.$strip>]>;
131
+ export type BrokerMessage = z.infer<typeof brokerMessage>;
132
+ export type BrokerRequest = Extract<BrokerMessage, {
133
+ t: "ask";
134
+ }>["request"];
135
+ /** A BrowseConfig as it crosses the socket; parsed again on arrival. */
136
+ export declare const browseConfig: z.ZodObject<{
137
+ apiKey: z.ZodOptional<z.ZodString>;
138
+ projectId: z.ZodOptional<z.ZodString>;
139
+ model: z.ZodOptional<z.ZodString>;
140
+ modelApiKey: z.ZodOptional<z.ZodString>;
141
+ jevApiKey: z.ZodOptional<z.ZodString>;
142
+ jevModel: z.ZodOptional<z.ZodString>;
143
+ askModel: z.ZodOptional<z.ZodString>;
144
+ cloudflareAccountId: z.ZodOptional<z.ZodString>;
145
+ cloudflareApiKey: z.ZodOptional<z.ZodString>;
146
+ contextHistoryPath: z.ZodOptional<z.ZodString>;
147
+ region: z.ZodOptional<z.ZodString>;
148
+ localUserDataDir: z.ZodOptional<z.ZodString>;
149
+ localExecutablePath: z.ZodOptional<z.ZodString>;
150
+ allowedDomains: z.ZodOptional<z.ZodArray<z.ZodString>>;
151
+ blockedDomains: z.ZodOptional<z.ZodArray<z.ZodString>>;
152
+ navigationPolicyId: z.ZodOptional<z.ZodString>;
153
+ remoteBrowsers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
154
+ cdpUrl: z.ZodString;
155
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
156
+ extensionCdpUrl: z.ZodOptional<z.ZodString>;
157
+ }, z.core.$strip>>>;
158
+ }, z.core.$strip>;
159
+ /** A host classifier's request and answers as they cross the socket. */
160
+ export declare const classifyRequest: z.ZodObject<{
161
+ state: z.ZodRecord<z.ZodString, z.ZodJSONSchema>;
162
+ questions: z.ZodRecord<z.ZodString, z.ZodDiscriminatedUnion<[z.ZodObject<{
163
+ type: z.ZodLiteral<"choice">;
164
+ instructions: z.ZodString;
165
+ criteria: z.ZodRecord<z.ZodString, z.ZodString>;
166
+ }, z.core.$strip>, z.ZodObject<{
167
+ type: z.ZodLiteral<"bool">;
168
+ instructions: z.ZodString;
169
+ }, z.core.$strip>], "type">>;
170
+ images: z.ZodOptional<z.ZodArray<z.ZodObject<{
171
+ mimeType: z.ZodEnum<{
172
+ "image/png": "image/png";
173
+ "image/jpeg": "image/jpeg";
174
+ }>;
175
+ data: z.ZodString;
176
+ }, z.core.$strip>>>;
177
+ }, z.core.$strip>;
178
+ export declare const classifyAnswers: z.ZodRecord<z.ZodString, z.ZodDiscriminatedUnion<[z.ZodObject<{
179
+ type: z.ZodLiteral<"choice">;
180
+ choice: z.ZodString;
181
+ probabilities: z.ZodRecord<z.ZodString, z.ZodNumber>;
182
+ confidence: z.ZodNumber;
183
+ }, z.core.$strip>, z.ZodObject<{
184
+ type: z.ZodLiteral<"bool">;
185
+ probability: z.ZodNumber;
186
+ }, z.core.$strip>], "type">>;
187
+ /** An error as it crosses the socket: a tool error keeps its code, an abort its name. */
188
+ export declare function errorBodyOf(cause: unknown): ErrorBody;
189
+ /**
190
+ * The broker's socket for one shared browser key. In the user's runtime or temp directory (0700), named by a hash of the
191
+ * key, since a profile path can exceed the 104-byte socket path limit.
192
+ */
193
+ export declare function brokerSocketPath(key: string): string;
194
+ export {};
@@ -0,0 +1,90 @@
1
+ // NDJSON between a host process and the browser broker that owns one shared local browser (see broker.ts).
2
+ import { createHash } from "node:crypto";
3
+ import { mkdirSync, statSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { z } from "zod";
7
+ /** Bumped on any incompatible message change; a client never talks to a broker of another protocol. */
8
+ export const BROKER_PROTOCOL = 1;
9
+ const json = z.json();
10
+ const errorBody = z.object({ code: z.string().optional(), name: z.string(), message: z.string() });
11
+ /** The part of a conversation's context that crosses to the broker; the signal stays with the caller. */
12
+ const runContext = z.object({
13
+ sessionId: z.string(), profile: z.string(), cwd: z.string(),
14
+ backend: z.enum(["browserbase", "local"]).optional(), classifier: z.string().optional(),
15
+ });
16
+ // Plain unions: the answer and result variants share a discriminator value, which discriminatedUnion rejects.
17
+ export const clientMessage = z.union([
18
+ z.object({ t: z.literal("hello"), protocol: z.number().int() }),
19
+ z.object({
20
+ t: z.literal("open"), conv: z.string(), identity: z.object({ name: z.string(), integration: z.string() }),
21
+ inference: z.boolean(), classify: z.boolean(),
22
+ }),
23
+ z.object({ t: z.literal("run"), id: z.number().int(), conv: z.string(), params: json, context: runContext, ai: z.boolean(), defaultBackend: z.enum(["browserbase", "local"]) }),
24
+ z.object({ t: z.literal("cancel"), id: z.number().int() }),
25
+ z.object({ t: z.literal("release"), id: z.number().int(), conv: z.string() }),
26
+ z.object({ t: z.literal("answer"), cb: z.number().int(), ok: z.literal(true), value: json }),
27
+ z.object({ t: z.literal("answer"), cb: z.number().int(), ok: z.literal(false), error: errorBody }),
28
+ ]);
29
+ export const brokerMessage = z.union([
30
+ z.object({ t: z.literal("hello"), protocol: z.number().int() }),
31
+ z.object({ t: z.literal("result"), id: z.number().int(), ok: z.literal(true), output: json }),
32
+ z.object({ t: z.literal("result"), id: z.number().int(), ok: z.literal(false), error: errorBody }),
33
+ z.object({ t: z.literal("released"), id: z.number().int() }),
34
+ z.object({
35
+ t: z.literal("ask"), cb: z.number().int(), conv: z.string(),
36
+ request: z.discriminatedUnion("kind", [
37
+ z.object({ kind: z.literal("config"), context: runContext.extend({ purpose: z.enum(["browser", "ai", "jev", "ask"]) }) }),
38
+ z.object({ kind: z.literal("generate"), params: json }),
39
+ z.object({ kind: z.literal("classify"), model: z.string(), request: json }),
40
+ ]),
41
+ }),
42
+ ]);
43
+ /** A BrowseConfig as it crosses the socket; parsed again on arrival. */
44
+ export const browseConfig = z.object({
45
+ apiKey: z.string().optional(), projectId: z.string().optional(), model: z.string().optional(), modelApiKey: z.string().optional(),
46
+ jevApiKey: z.string().optional(), jevModel: z.string().optional(), askModel: z.string().optional(),
47
+ cloudflareAccountId: z.string().optional(), cloudflareApiKey: z.string().optional(), contextHistoryPath: z.string().optional(),
48
+ region: z.string().optional(), localUserDataDir: z.string().optional(), localExecutablePath: z.string().optional(),
49
+ allowedDomains: z.array(z.string()).optional(), blockedDomains: z.array(z.string()).optional(), navigationPolicyId: z.string().optional(),
50
+ remoteBrowsers: z.record(z.string(), z.object({
51
+ cdpUrl: z.string(), headers: z.record(z.string(), z.string()).optional(), extensionCdpUrl: z.string().optional(),
52
+ })).optional(),
53
+ });
54
+ /** A host classifier's request and answers as they cross the socket. */
55
+ export const classifyRequest = z.object({
56
+ state: z.record(z.string(), z.json()),
57
+ questions: z.record(z.string(), z.discriminatedUnion("type", [
58
+ z.object({ type: z.literal("choice"), instructions: z.string(), criteria: z.record(z.string(), z.string()) }),
59
+ z.object({ type: z.literal("bool"), instructions: z.string() }),
60
+ ])),
61
+ images: z.array(z.object({ mimeType: z.enum(["image/png", "image/jpeg"]), data: z.string() })).optional(),
62
+ });
63
+ export const classifyAnswers = z.record(z.string(), z.discriminatedUnion("type", [
64
+ z.object({ type: z.literal("choice"), choice: z.string(), probabilities: z.record(z.string(), z.number()), confidence: z.number() }),
65
+ z.object({ type: z.literal("bool"), probability: z.number() }),
66
+ ]));
67
+ /** An error as it crosses the socket: a tool error keeps its code, an abort its name. */
68
+ export function errorBodyOf(cause) {
69
+ if (!(cause instanceof Error))
70
+ return { name: "Error", message: String(cause) };
71
+ const code = "code" in cause && cause.name !== "AbortError" ? z.string().safeParse(cause.code) : undefined;
72
+ const body = { name: cause.name, message: cause.message };
73
+ if (code?.success)
74
+ body.code = code.data;
75
+ return body;
76
+ }
77
+ /**
78
+ * The broker's socket for one shared browser key. In the user's runtime or temp directory (0700), named by a hash of the
79
+ * key, since a profile path can exceed the 104-byte socket path limit.
80
+ */
81
+ export function brokerSocketPath(key) {
82
+ const base = process.env.XDG_RUNTIME_DIR || tmpdir();
83
+ const dir = join(base, `browse-brokers-${process.getuid?.() ?? "user"}`);
84
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
85
+ // Another user's directory under a shared /tmp must never carry this user's browser.
86
+ const owner = statSync(dir);
87
+ if (process.getuid && owner.uid !== process.getuid())
88
+ throw new Error(`${dir} belongs to another user.`);
89
+ return join(dir, `${createHash("sha256").update(key).digest("hex").slice(0, 24)}.sock`);
90
+ }
@@ -0,0 +1 @@
1
+ export {};