@edlsh/browse-core 0.1.0 → 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/dist/broker.js ADDED
@@ -0,0 +1,225 @@
1
+ // The browser broker: one detached process that owns a shared local browser (a persistent profile or an attached
2
+ // browser) and runs every host process's browse calls on it. Stagehand's in-browser runtime admits one client, so
3
+ // several processes can drive one browser only through a single owner. A client starts it on first use (broker-client.ts);
4
+ // it exits once no client has been connected for a while, after the last conversation released the browser.
5
+ import { chmodSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { createServer } from "node:net";
7
+ import { BROKER_PROTOCOL, browseConfig, classifyAnswers, clientMessage, errorBodyOf, } from "./broker-protocol.js";
8
+ import { aiParameters, browserParameters } from "./schema.js";
9
+ import { BrowseSession } from "./session.js";
10
+ const IDLE_EXIT_MS = 30_000;
11
+ const socketPath = process.argv[2];
12
+ if (!socketPath) {
13
+ console.error("usage: broker <socket path>");
14
+ process.exit(2);
15
+ }
16
+ let connections = 0;
17
+ let idle;
18
+ const live = new Set();
19
+ function armIdle() {
20
+ clearTimeout(idle);
21
+ if (!connections)
22
+ idle = setTimeout(() => void stop(), IDLE_EXIT_MS);
23
+ }
24
+ /** A BrowserOutput as JSON: the image as base64, BigInt (cookie timestamps) as strings. */
25
+ function encodeOutput(output) {
26
+ const { image, ...rest } = output;
27
+ const text = JSON.stringify({ ...rest, image: image ? Buffer.from(image).toString("base64") : undefined }, (_key, value) => value?.constructor === BigInt ? String(value) : value);
28
+ return JSON.parse(text);
29
+ }
30
+ class Connection {
31
+ socket;
32
+ sessions = new Map();
33
+ controllers = new Map();
34
+ asks = new Map();
35
+ nextAsk = 1;
36
+ buffer = "";
37
+ constructor(socket) {
38
+ this.socket = socket;
39
+ socket.setEncoding("utf8");
40
+ socket.on("data", chunk => this.data(String(chunk)));
41
+ socket.on("close", () => void this.closed());
42
+ socket.on("error", () => undefined);
43
+ }
44
+ send(message) {
45
+ if (!this.socket.destroyed)
46
+ this.socket.write(`${JSON.stringify(message)}\n`);
47
+ }
48
+ data(chunk) {
49
+ this.buffer += chunk;
50
+ for (let end = this.buffer.indexOf("\n"); end >= 0; end = this.buffer.indexOf("\n")) {
51
+ const line = this.buffer.slice(0, end);
52
+ this.buffer = this.buffer.slice(end + 1);
53
+ if (!line.trim())
54
+ continue;
55
+ let parsed;
56
+ try {
57
+ parsed = clientMessage.safeParse(JSON.parse(line));
58
+ }
59
+ catch {
60
+ parsed = undefined;
61
+ }
62
+ if (!parsed?.success) {
63
+ console.error(`broker: ignored a malformed line from a client`);
64
+ continue;
65
+ }
66
+ void this.handle(parsed.data).catch(error => console.error(`broker: ${error instanceof Error ? error.stack : String(error)}`));
67
+ }
68
+ }
69
+ /** Asks the client that owns `conv` for its configuration, inference, or classifier answers. */
70
+ ask(conv, request) {
71
+ const cb = this.nextAsk++;
72
+ const waiter = Promise.withResolvers();
73
+ this.asks.set(cb, waiter);
74
+ this.send({ t: "ask", cb, conv, request });
75
+ return waiter.promise;
76
+ }
77
+ open(message) {
78
+ const { conv } = message;
79
+ const generate = async (params) => {
80
+ const value = await this.ask(conv, { kind: "generate", params: JSON.parse(JSON.stringify(params)) });
81
+ // SAFETY: the client returns its own Stagehand generate() result, unchanged apart from the JSON round trip.
82
+ return value;
83
+ };
84
+ return new BrowseSession(async ({ signal: _signal, ...context }) => browseConfig.parse(await this.ask(conv, { kind: "config", context })), message.inference ? { generate, describe: async () => "host model" } : undefined, message.classify ? async (model, request) => classifyAnswers.parse(await this.ask(conv, { kind: "classify", model, request: JSON.parse(JSON.stringify(request)) })) : undefined, message.identity, { profileBroker: false });
85
+ }
86
+ async handle(message) {
87
+ switch (message.t) {
88
+ case "hello":
89
+ this.send({ t: "hello", protocol: BROKER_PROTOCOL });
90
+ return;
91
+ case "open":
92
+ if (!this.sessions.has(message.conv))
93
+ this.sessions.set(message.conv, this.open(message));
94
+ return;
95
+ case "run": {
96
+ const session = this.sessions.get(message.conv);
97
+ if (!session) {
98
+ this.send({ t: "result", id: message.id, ok: false, error: { name: "BrowseToolError", code: "no_session", message: "This conversation is not open in the browser broker." } });
99
+ return;
100
+ }
101
+ const controller = new AbortController();
102
+ this.controllers.set(message.id, controller);
103
+ try {
104
+ session.defaultBackend = message.defaultBackend;
105
+ const params = message.ai ? aiParameters.parse(message.params) : browserParameters.parse(message.params);
106
+ const output = await session.run(params, message.context, controller.signal, message.ai);
107
+ this.send({ t: "result", id: message.id, ok: true, output: encodeOutput(output) });
108
+ }
109
+ catch (error) {
110
+ this.send({ t: "result", id: message.id, ok: false, error: errorBodyOf(error) });
111
+ }
112
+ finally {
113
+ this.controllers.delete(message.id);
114
+ }
115
+ return;
116
+ }
117
+ case "cancel":
118
+ this.controllers.get(message.id)?.abort();
119
+ return;
120
+ case "release": {
121
+ const session = this.sessions.get(message.conv);
122
+ this.sessions.delete(message.conv);
123
+ await session?.shutdown().catch(() => undefined);
124
+ this.send({ t: "released", id: message.id });
125
+ return;
126
+ }
127
+ case "answer": {
128
+ const waiter = this.asks.get(message.cb);
129
+ this.asks.delete(message.cb);
130
+ if (message.ok)
131
+ waiter?.resolve(message.value);
132
+ else
133
+ waiter?.reject(Object.assign(new Error(message.error.message), { name: message.error.name }));
134
+ return;
135
+ }
136
+ }
137
+ }
138
+ /** The client went away: release its conversations' tabs, and the browser if they were the last. */
139
+ async closed() {
140
+ if (!live.delete(this))
141
+ return;
142
+ connections--;
143
+ for (const waiter of this.asks.values())
144
+ waiter.reject(new Error("The browse client disconnected."));
145
+ this.asks.clear();
146
+ for (const controller of this.controllers.values())
147
+ controller.abort();
148
+ await Promise.allSettled([...this.sessions.values()].map(session => session.shutdown()));
149
+ this.sessions.clear();
150
+ armIdle();
151
+ }
152
+ async shutdown() {
153
+ this.socket.destroy();
154
+ await this.closed();
155
+ }
156
+ }
157
+ const server = createServer(socket => {
158
+ connections++;
159
+ clearTimeout(idle);
160
+ const connection = new Connection(socket);
161
+ live.add(connection);
162
+ });
163
+ const lockPath = socketPath.replace(/\.sock$/, ".pid");
164
+ /** Whether a process with this pid is running. */
165
+ function alive(pid) {
166
+ try {
167
+ process.kill(pid, 0);
168
+ return true;
169
+ }
170
+ catch (error) {
171
+ return error instanceof Error && "code" in error && error.code === "EPERM";
172
+ }
173
+ }
174
+ /**
175
+ * Becomes this browser's only broker, or reports that another one is. Clients that start brokers at the same moment
176
+ * race here, not at the socket, so a loser never removes the winner's socket file.
177
+ */
178
+ function acquireLock() {
179
+ for (let attempt = 0; attempt < 3; attempt++) {
180
+ try {
181
+ writeFileSync(lockPath, String(process.pid), { flag: "wx", mode: 0o600 });
182
+ return true;
183
+ }
184
+ catch (error) {
185
+ if (!(error instanceof Error && "code" in error && error.code === "EEXIST"))
186
+ throw error;
187
+ }
188
+ const holder = Number.parseInt(readFileSync(lockPath, "utf8"), 10);
189
+ if (Number.isInteger(holder) && holder > 0 && alive(holder))
190
+ return false;
191
+ // The broker holding it died without cleaning up.
192
+ rmSync(lockPath, { force: true });
193
+ }
194
+ return false;
195
+ }
196
+ function cleanup() {
197
+ rmSync(socketPath, { force: true });
198
+ try {
199
+ if (readFileSync(lockPath, "utf8") === String(process.pid))
200
+ rmSync(lockPath, { force: true });
201
+ }
202
+ catch { /* already gone */ }
203
+ }
204
+ server.on("error", error => {
205
+ console.error(`broker: ${error.message}`);
206
+ cleanup();
207
+ process.exit(1);
208
+ });
209
+ async function stop() {
210
+ server.close();
211
+ await Promise.allSettled([...live].map(connection => connection.shutdown()));
212
+ cleanup();
213
+ process.exit(0);
214
+ }
215
+ process.on("SIGTERM", () => void stop());
216
+ process.on("SIGINT", () => void stop());
217
+ process.on("unhandledRejection", error => console.error(`broker: unhandled ${error instanceof Error ? error.stack : String(error)}`));
218
+ if (!acquireLock())
219
+ process.exit(0);
220
+ // Holding the lock, any socket file is a dead broker's.
221
+ rmSync(socketPath, { force: true });
222
+ server.listen(socketPath, () => {
223
+ chmodSync(socketPath, 0o600);
224
+ armIdle();
225
+ });
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Names a Chrome user data dir's default profile, as its toolbar avatar and profile menu show it, so the user can tell
3
+ * which harness owns a window. Skipped while Chrome holds the profile (it rewrites both files on exit) and when either
4
+ * file is not JSON Chrome would read.
5
+ */
6
+ export declare function nameChromeProfile(userDataDir: string, name: string): Promise<void>;
@@ -0,0 +1,52 @@
1
+ import { lstat, mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { z } from "zod";
4
+ /** The JSON files Chrome keeps the default profile's name in; every other key is kept as Chrome wrote it. */
5
+ const chromeJson = z.looseObject({ profile: z.looseObject({}).optional() });
6
+ const localState = z.looseObject({
7
+ profile: z.looseObject({ info_cache: z.record(z.string(), z.looseObject({})).optional() }).optional(),
8
+ });
9
+ async function readJson(path) {
10
+ try {
11
+ return await readFile(path, "utf8");
12
+ }
13
+ catch (error) {
14
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
15
+ return undefined;
16
+ throw error;
17
+ }
18
+ }
19
+ /** Writes through a temporary file, so a crash never leaves Chrome a truncated file. */
20
+ async function replace(path, value) {
21
+ const partial = `${path}.${process.pid}.tmp`;
22
+ await writeFile(partial, JSON.stringify(value), { mode: 0o600 });
23
+ await rename(partial, path);
24
+ }
25
+ /**
26
+ * Names a Chrome user data dir's default profile, as its toolbar avatar and profile menu show it, so the user can tell
27
+ * which harness owns a window. Skipped while Chrome holds the profile (it rewrites both files on exit) and when either
28
+ * file is not JSON Chrome would read.
29
+ */
30
+ export async function nameChromeProfile(userDataDir, name) {
31
+ if (await lstat(join(userDataDir, "SingletonLock")).then(() => true, () => false))
32
+ return;
33
+ const statePath = join(userDataDir, "Local State");
34
+ const preferencesPath = join(userDataDir, "Default", "Preferences");
35
+ const [stateText, preferencesText] = await Promise.all([readJson(statePath), readJson(preferencesPath)]);
36
+ let state, preferences;
37
+ try {
38
+ state = localState.safeParse(stateText === undefined ? {} : JSON.parse(stateText));
39
+ preferences = chromeJson.safeParse(preferencesText === undefined ? {} : JSON.parse(preferencesText));
40
+ }
41
+ catch {
42
+ return;
43
+ }
44
+ if (!state.success || !preferences.success)
45
+ return;
46
+ const profile = state.data.profile ?? {};
47
+ const cache = profile.info_cache ?? {};
48
+ const entry = cache.Default ?? {};
49
+ await mkdir(join(userDataDir, "Default"), { recursive: true, mode: 0o700 });
50
+ await replace(statePath, { ...state.data, profile: { ...profile, info_cache: { ...cache, Default: { ...entry, name, is_using_default_name: false } } } });
51
+ await replace(preferencesPath, { ...preferences.data, profile: { ...preferences.data.profile, name, using_default_name: false } });
52
+ }
package/dist/har.d.ts CHANGED
@@ -15,6 +15,7 @@ export interface HarSummary {
15
15
  */
16
16
  export declare class HarRecorder {
17
17
  private readonly socket;
18
+ private readonly include?;
18
19
  private readonly pending;
19
20
  private nextId;
20
21
  private readonly drafts;
@@ -27,8 +28,11 @@ export declare class HarRecorder {
27
28
  private readonly attached;
28
29
  private closed;
29
30
  private constructor();
30
- /** Connects to a browser-level DevTools WebSocket and starts recording every existing and new tab. */
31
- static start(browserUrl: string, signal: AbortSignal): Promise<HarRecorder>;
31
+ /**
32
+ * Connects to a browser-level DevTools WebSocket and starts recording every existing and new tab, or with `include`
33
+ * only the tabs it accepts, the popups they open, and tabs passed to follow().
34
+ */
35
+ static start(browserUrl: string, signal: AbortSignal, include?: (targetId: string) => boolean): Promise<HarRecorder>;
32
36
  /** Stops recording, waits briefly for bodies being read, and writes the HAR (mode 0600) to path; `creator` names the writing tool. */
33
37
  stop(path: string, creator: string): Promise<HarSummary>;
34
38
  /** Ends recording without writing anything. */
@@ -38,6 +42,8 @@ export declare class HarRecorder {
38
42
  /** stop waits for reads in flight, such as response bodies, before writing. */
39
43
  private track;
40
44
  private attach;
45
+ /** Records a tab opened after start; a recorder without a tab filter already does. */
46
+ follow(targetId: string): Promise<void>;
41
47
  private receive;
42
48
  private finish;
43
49
  private entry;
package/dist/har.js CHANGED
@@ -31,6 +31,7 @@ function responseCookies(headers) {
31
31
  */
32
32
  export class HarRecorder {
33
33
  socket;
34
+ include;
34
35
  pending = new Map();
35
36
  nextId = 0;
36
37
  drafts = new Map();
@@ -42,13 +43,17 @@ export class HarRecorder {
42
43
  /** setDiscoverTargets also reports targets that already exist: each is attached once. */
43
44
  attached = new Set();
44
45
  closed = false;
45
- constructor(socket) {
46
+ constructor(socket, include) {
46
47
  this.socket = socket;
48
+ this.include = include;
47
49
  }
48
- /** Connects to a browser-level DevTools WebSocket and starts recording every existing and new tab. */
49
- static async start(browserUrl, signal) {
50
+ /**
51
+ * Connects to a browser-level DevTools WebSocket and starts recording every existing and new tab, or with `include`
52
+ * only the tabs it accepts, the popups they open, and tabs passed to follow().
53
+ */
54
+ static async start(browserUrl, signal, include) {
50
55
  const socket = new WebSocket(browserUrl);
51
- const recorder = new HarRecorder(socket);
56
+ const recorder = new HarRecorder(socket, include);
52
57
  socket.addEventListener("message", event => recorder.receive(JSON.parse(String(event.data))));
53
58
  socket.addEventListener("close", () => recorder.fail());
54
59
  await new Promise((resolve, reject) => {
@@ -60,7 +65,8 @@ export class HarRecorder {
60
65
  try {
61
66
  await recorder.send("Target.setDiscoverTargets", { discover: true });
62
67
  const { targetInfos } = await recorder.send("Target.getTargets");
63
- await Promise.all(targetInfos.filter(target => target.type === "page").map(target => recorder.attach(target.targetId)));
68
+ await Promise.all(targetInfos
69
+ .filter(target => target.type === "page" && (!include || include(target.targetId))).map(target => recorder.attach(target.targetId)));
64
70
  }
65
71
  catch (error) {
66
72
  recorder.close();
@@ -119,6 +125,11 @@ export class HarRecorder {
119
125
  this.tabs.set(sessionId, targetId);
120
126
  await this.send("Network.enable", { maxPostDataSize: 1_000_000 }, sessionId);
121
127
  }
128
+ /** Records a tab opened after start; a recorder without a tab filter already does. */
129
+ async follow(targetId) {
130
+ if (!this.closed)
131
+ await this.attach(targetId);
132
+ }
122
133
  receive(message) {
123
134
  if (message.id !== undefined) {
124
135
  const entry = this.pending.get(message.id);
@@ -135,7 +146,9 @@ export class HarRecorder {
135
146
  return;
136
147
  const { method, params, sessionId } = message;
137
148
  // A new tab starts on Stagehand's extension page before it navigates, so every page target is attached.
138
- if (method === "Target.targetCreated" && params.targetInfo.type === "page") {
149
+ // With a tab filter, a new tab is recorded when it is a popup of a recorded one; follow() adds the rest.
150
+ if (method === "Target.targetCreated" && params.targetInfo.type === "page"
151
+ && (!this.include || this.include(params.targetInfo.targetId) || this.attached.has(params.targetInfo.openerId))) {
139
152
  this.track(this.attach(params.targetInfo.targetId));
140
153
  return;
141
154
  }
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export * from "./schema.ts";
3
3
  export * from "./settings.ts";
4
4
  export { EXTRACT_MODEL, MAX_TEXT, DECIDE_TEXT, askNeeds, pageText, askPage, type PageState, type Answer as AskAnswer, type AskResult, type AskModels } from "./ask.ts";
5
5
  export * from "./cdp-guard.ts";
6
+ export * from "./chrome-profile.ts";
6
7
  export * from "./har.ts";
7
8
  export * from "./page-operations.ts";
8
9
  export * from "./browser-cookies.ts";
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ export * from "./settings.js";
5
5
  // ask.ts and classifier.ts both name a type Answer; the hosts use the classifier's.
6
6
  export { EXTRACT_MODEL, MAX_TEXT, DECIDE_TEXT, askNeeds, pageText, askPage } from "./ask.js";
7
7
  export * from "./cdp-guard.js";
8
+ export * from "./chrome-profile.js";
8
9
  export * from "./har.js";
9
10
  export * from "./page-operations.js";
10
11
  export * from "./browser-cookies.js";
package/dist/schema.js CHANGED
@@ -47,7 +47,7 @@ export const browserParameters = z.object({
47
47
  "tabs", "tab_new", "tab_select", "tab_close", "live_view", "context_create", "cookie_profiles", "cookie_import",
48
48
  "har_start", "har_stop",
49
49
  ]),
50
- backend: z.enum(["browserbase", "local"]).optional().describe("Only for start. Default browserbase; choose local explicitly for localhost/private sites or at the user's request. Close before changing backends."),
50
+ backend: z.enum(["browserbase", "local"]).optional().describe("Only for start. Default local (or the profile's /browse backend setting); choose browserbase for clean-slate isolation, proxyCountry, a saved contextId, or at the user's request. Close before changing backends."),
51
51
  cdpUrl: z.url({ protocol: /^(?:https?|wss?)$/ }).refine(value => {
52
52
  if (!URL.canParse(value))
53
53
  return false;
package/dist/session.d.ts CHANGED
@@ -76,6 +76,13 @@ export interface HostIdentity {
76
76
  name: string;
77
77
  integration: string;
78
78
  }
79
+ export interface BrowseSessionOptions {
80
+ /**
81
+ * Run shared browsers (persistent profiles and attached browsers) in the browser broker, one process per browser, so
82
+ * conversations in other processes can use them at the same time. Default true; the broker turns it off for itself.
83
+ */
84
+ profileBroker?: boolean;
85
+ }
79
86
  /** A page script that answered a native dialog, as reported in tool output. */
80
87
  export interface AnsweredDialog {
81
88
  type: "alert" | "confirm" | "prompt";
@@ -140,14 +147,17 @@ export declare class BrowseSession {
140
147
  private readonly secrets;
141
148
  /** Cleared for the process lifetime once Browserbase refuses keepAlive for this plan. */
142
149
  private keepAliveAllowed;
150
+ private readonly profileBroker;
151
+ /** This conversation's calls run in the broker that owns its shared browser, until close. */
152
+ private delegate?;
143
153
  /** Stagehand's runtime extension, uploaded once per tool instance instead of on every launch. */
144
154
  private extension?;
145
155
  /** Default inference for every Stagehand instance; without it, unconfigured AI calls use Model Gateway's automatic selection. */
146
156
  private readonly stagehandModel;
147
157
  private readonly describeInference;
148
- /** Backend for a start, open, tab_new, or cookie_import that names none while no browser is open: the profile's /browse backend setting, else the loader's default. */
158
+ /** Backend for a start, open, tab_new, or cookie_import that names none while no browser is open: the profile's /browse backend setting, else the loader's default, else local. */
149
159
  defaultBackend: "browserbase" | "local";
150
- constructor(resolveConfig?: ConfigResolver, inference?: ClientInference, hostClassify?: HostClassify | undefined, identity?: HostIdentity);
160
+ constructor(resolveConfig?: ConfigResolver, inference?: ClientInference, hostClassify?: HostClassify | undefined, identity?: HostIdentity, options?: BrowseSessionOptions);
151
161
  redact(text: string): string;
152
162
  /**
153
163
  * Queues one operation behind this conversation's earlier ones. `ai` marks a browse_ai call; as a function it runs
@@ -169,6 +179,11 @@ export declare class BrowseSession {
169
179
  private owner;
170
180
  /** Runs one operation; a dropped connection is repaired and the operation repeated only when that cannot double an action. */
171
181
  private dispatch;
182
+ /** The shared browser a call would open, as the broker keys it: an attached browser or a persistent profile; else none. */
183
+ private sharedKey;
184
+ /** Runs a call in the broker; close ends the conversation there, and a lost broker is reopened by the next call. */
185
+ private forward;
186
+ private dropDelegate;
172
187
  /** Reattaches to a remote session that outlived its connection; otherwise releases it and reports the loss. */
173
188
  private reconnect;
174
189
  /**
@@ -204,6 +219,27 @@ export declare class BrowseSession {
204
219
  private current;
205
220
  private start;
206
221
  private initialize;
222
+ /**
223
+ * Joins the browser this process shares for a persistent profile or an attached browser, opening it first if needed.
224
+ * The launching conversation takes Chrome's first tab and later ones open their own; in an attached browser the
225
+ * user's tabs stay available and a conversation claims one on first use.
226
+ */
227
+ private joinShared;
228
+ /** Launches a persistent profile or attaches to a browser, with one Stagehand whose default inference follows the AI turn. */
229
+ private openShared;
230
+ /**
231
+ * Releases a shared browser no conversation uses: quits a launched profile's Chrome so it writes its cookies, and only
232
+ * disconnects from an attached one. Set synchronously, so a conversation joining meanwhile opens a fresh browser instead.
233
+ */
234
+ private retire;
235
+ /** Runs a browse_ai call on a shared Stagehand in turn, lending it this conversation's default inference meanwhile. */
236
+ private takeAiTurn;
237
+ /** Closes the tabs a conversation opened in a shared browser; claimed tabs, the user's own, stay open. */
238
+ private closeCreatedTabs;
239
+ /** Whether another conversation sharing this browser uses the tab, or one closed it. */
240
+ private ownedByOther;
241
+ /** The tabs this conversation may use: all of them, except in a shared browser the ones another conversation uses. */
242
+ private visiblePages;
207
243
  /** Starts recording every tab's network traffic over a DevTools connection of its own. */
208
244
  private harStart;
209
245
  private closeOwned;