@edlsh/browse-core 0.6.4 → 0.8.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/README.md +23 -2
- package/dist/broker-client.d.ts +4 -2
- package/dist/broker-client.js +12 -6
- package/dist/broker-protocol.d.ts +3 -2
- package/dist/broker-protocol.js +11 -7
- package/dist/broker.js +12 -12
- package/dist/cdp-connection.d.ts +18 -0
- package/dist/cdp-connection.js +59 -0
- package/dist/config.d.ts +101 -0
- package/dist/config.js +78 -0
- package/dist/contexts.d.ts +10 -0
- package/dist/contexts.js +27 -0
- package/dist/errors.d.ts +29 -0
- package/dist/errors.js +83 -0
- package/dist/har.d.ts +1 -6
- package/dist/har.js +16 -56
- package/dist/host-model.d.ts +24 -0
- package/dist/host-model.js +35 -0
- package/dist/http-auth.d.ts +14 -0
- package/dist/http-auth.js +114 -0
- package/dist/index.d.ts +10 -13
- package/dist/index.js +11 -15
- package/dist/jev.js +9 -3
- package/dist/page-operations.d.ts +11 -1
- package/dist/page-operations.js +62 -11
- package/dist/real-browser-ai.d.ts +1 -1
- package/dist/real-browser-ai.js +1 -1
- package/dist/real-browser-client.js +1 -1
- package/dist/real-browser-session.d.ts +1 -1
- package/dist/real-browser-session.js +24 -5
- package/dist/schema.d.ts +34 -0
- package/dist/schema.js +29 -6
- package/dist/session-runtime.d.ts +42 -0
- package/dist/session-runtime.js +144 -0
- package/dist/session.d.ts +29 -108
- package/dist/session.js +189 -364
- package/dist/settings.js +47 -6
- package/dist/tool-results.d.ts +28 -0
- package/dist/tool-results.js +40 -0
- package/extensions/http-auth/README.md +27 -0
- package/extensions/http-auth/background.js +85 -0
- package/extensions/http-auth/manifest.json +27 -0
- package/extensions/http-auth/native/README.md +31 -0
- package/extensions/http-auth/native/host.py +97 -0
- package/extensions/http-auth/native/install.py +62 -0
- package/extensions/http-auth/options.html +25 -0
- package/extensions/http-auth/options.js +36 -0
- package/extensions/http-auth/origin.js +16 -0
- package/package.json +14 -2
package/dist/errors.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export class BrowseToolError extends Error {
|
|
2
|
+
code;
|
|
3
|
+
batch;
|
|
4
|
+
/** `batch` is set on a failed batch call. */
|
|
5
|
+
constructor(code, message, batch) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.code = code;
|
|
8
|
+
this.batch = batch;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** Stagehand reports an exception a page script threw as "Uncaught ..."; anything else is not a script error. */
|
|
12
|
+
export function scriptError(message) {
|
|
13
|
+
if (!/^Uncaught\b/.test(message))
|
|
14
|
+
return undefined;
|
|
15
|
+
const detail = message.replace(/^Uncaught\s*(?:\(in promise\)\s*)?/, "").slice(0, 500);
|
|
16
|
+
return new BrowseToolError("script_error", (detail
|
|
17
|
+
? `The script threw: ${detail}.`
|
|
18
|
+
: "The script threw; Stagehand hides the exception message. To see it, wrap the script: (() => { try { ... } catch (e) { return String(e) } })().")
|
|
19
|
+
+ " Side effects before the throw may have happened.");
|
|
20
|
+
}
|
|
21
|
+
export function messageOf(error) {
|
|
22
|
+
return error instanceof Error ? error.message : String(error);
|
|
23
|
+
}
|
|
24
|
+
/** Gives recurring Stagehand failures a code and a next step; anything else passes through unchanged. */
|
|
25
|
+
export function translate(error) {
|
|
26
|
+
if (error instanceof BrowseToolError)
|
|
27
|
+
return error;
|
|
28
|
+
const message = messageOf(error);
|
|
29
|
+
if (/^Request timed out\.?$/i.test(message))
|
|
30
|
+
return new BrowseToolError("timeout", "The browser service timed out; the action may have completed. Inspect status and the page before retrying.");
|
|
31
|
+
if (/Node does not have a layout object/.test(message))
|
|
32
|
+
return new BrowseToolError("not_actionable", "The target has no rendered box. Use select on a native dropdown, or choose a visible element from a fresh snapshot.");
|
|
33
|
+
if (/ERR_BLOCKED_BY_CLIENT/.test(message))
|
|
34
|
+
return new BrowseToolError("domain_blocked", "The browser's domain policy blocked this request. status lists the allowed and blocked domains; close and start again to change them, or ask the user to change the profile's.");
|
|
35
|
+
if (/^No Page found|^Stagehand callback batch page was not found:|^Stagehand has no active page\.|^Stagehand page ".+" was not found;/.test(message))
|
|
36
|
+
return new BrowseToolError("tab_missing", "The tab closed or navigated away during the action. List tabs, select one, and take a snapshot.");
|
|
37
|
+
if (/^Connection error\.?$/.test(message))
|
|
38
|
+
return new BrowseToolError("network_error", "Could not reach Browserbase. Retry once; if it persists, check this machine's network.");
|
|
39
|
+
// Stagehand admits one client per browser and refuses a second while the first is connected.
|
|
40
|
+
if (/A Stagehand client is already connected/.test(message))
|
|
41
|
+
return new BrowseToolError("browser_in_use", "Another Stagehand client is connected to this browser, and a browser takes one at a time: a conversation on another machine, or another tool. Close the browser there, then start again.");
|
|
42
|
+
if (/does not support the client watchdog|requires Chrome 137 or later/.test(message))
|
|
43
|
+
return new BrowseToolError("attach_failed", "This browser cannot take this version of Stagehand: it needs Chrome 137 or newer and the Stagehand extension this tool ships. Update the browser and reinstall the extension in it, then start again.");
|
|
44
|
+
// Stagehand's own per-request limit: the tab stopped answering, typically a busy script.
|
|
45
|
+
const rpc = /^RPC response timed out: (\S+)/.exec(message);
|
|
46
|
+
if (rpc)
|
|
47
|
+
return new BrowseToolError("timeout", `Stagehand got no reply for ${rpc[1]} in time; the action may have completed. The tab may be busy: check status, and if it reports tab_unresponsive, call tab_new and tab_close that tab.`);
|
|
48
|
+
// Page-level waits and navigations that ran out of time, in Stagehand's wording, sometimes wrapped as a page exception.
|
|
49
|
+
const pageTimeout = /^(?:Uncaught (?:\(in promise\) )?(?:Error: )?)?(.*(?:timed out after \d+ ?ms|Timeout \d+ ?ms exceeded).*)$/s.exec(message);
|
|
50
|
+
if (pageTimeout)
|
|
51
|
+
return new BrowseToolError("timeout", `${pageTimeout[1].slice(0, 300)}. The browser was kept; take a snapshot to check the page, or raise timeoutMs.`);
|
|
52
|
+
// Strict structured output (OpenAI models on Model Gateway) rejects schemas with optional properties.
|
|
53
|
+
if (/^Invalid schema for response_format/.test(message)) {
|
|
54
|
+
return new BrowseToolError("invalid_arguments", `The model rejected the extract schema: ${message.slice(0, 300)} List every property in required, and allow null for values that may be missing.`);
|
|
55
|
+
}
|
|
56
|
+
if (/extension world not ready for frame/i.test(message)) {
|
|
57
|
+
return new BrowseToolError("frame_unavailable", "Stagehand cannot reach that document: legacy <frame> pages, browser error pages, and frames still loading are unsupported. Take a snapshot and use its refs, or wait for the page and retry.");
|
|
58
|
+
}
|
|
59
|
+
return error;
|
|
60
|
+
}
|
|
61
|
+
export function abortError(message = "Operation cancelled.") {
|
|
62
|
+
return new BrowseToolError("cancelled", message);
|
|
63
|
+
}
|
|
64
|
+
/** Stops waiting immediately; the caller is responsible for closing the remote browser. */
|
|
65
|
+
export function abortable(promise, signal) {
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
const abort = () => reject(signal.reason ?? abortError());
|
|
68
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
69
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
70
|
+
if (signal.aborted)
|
|
71
|
+
abort();
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
export async function deadline(promise, ms) {
|
|
75
|
+
const controller = new AbortController();
|
|
76
|
+
const timer = setTimeout(() => controller.abort(new BrowseToolError("timeout", "Browser cleanup timed out.")), ms);
|
|
77
|
+
try {
|
|
78
|
+
return await abortable(promise, controller.signal);
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
}
|
|
83
|
+
}
|
package/dist/har.d.ts
CHANGED
|
@@ -52,10 +52,8 @@ export declare function writeCaptureHar(capture: NetworkCapture, path: string, c
|
|
|
52
52
|
* response bodies are kept. Nothing is returned to the caller but counts: the HAR goes only to the file stop writes.
|
|
53
53
|
*/
|
|
54
54
|
export declare class HarRecorder {
|
|
55
|
-
private readonly
|
|
55
|
+
private readonly client;
|
|
56
56
|
private readonly include?;
|
|
57
|
-
private readonly pending;
|
|
58
|
-
private nextId;
|
|
59
57
|
private readonly drafts;
|
|
60
58
|
/** ExtraInfo events can arrive before the event they belong to. */
|
|
61
59
|
private readonly early;
|
|
@@ -64,7 +62,6 @@ export declare class HarRecorder {
|
|
|
64
62
|
private readonly tabs;
|
|
65
63
|
/** setDiscoverTargets also reports targets that already exist: each is attached once. */
|
|
66
64
|
private readonly attached;
|
|
67
|
-
private closed;
|
|
68
65
|
private constructor();
|
|
69
66
|
/**
|
|
70
67
|
* Connects to a browser-level DevTools WebSocket and starts recording every existing and new tab, or with `include`
|
|
@@ -75,8 +72,6 @@ export declare class HarRecorder {
|
|
|
75
72
|
stop(path: string, creator: string): Promise<HarSummary>;
|
|
76
73
|
/** Ends recording without writing anything. */
|
|
77
74
|
close(): void;
|
|
78
|
-
private fail;
|
|
79
|
-
private send;
|
|
80
75
|
/** stop waits for reads in flight, such as response bodies, before writing. */
|
|
81
76
|
private track;
|
|
82
77
|
private attach;
|
package/dist/har.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { chmod, mkdir, writeFile } from "node:fs/promises";
|
|
2
|
+
import { CdpConnection } from "./cdp-connection.js";
|
|
2
3
|
import { dirname } from "node:path";
|
|
3
4
|
// Stagehand 4.3 forwards only console events from CDP, so network capture uses its own connection to the browser target.
|
|
4
5
|
/** A response body larger than this (base64 or text characters) is left out of the HAR and counted instead. */
|
|
@@ -62,10 +63,8 @@ function responseCookies(headers) {
|
|
|
62
63
|
* response bodies are kept. Nothing is returned to the caller but counts: the HAR goes only to the file stop writes.
|
|
63
64
|
*/
|
|
64
65
|
export class HarRecorder {
|
|
65
|
-
|
|
66
|
+
client;
|
|
66
67
|
include;
|
|
67
|
-
pending = new Map();
|
|
68
|
-
nextId = 0;
|
|
69
68
|
drafts = new Map();
|
|
70
69
|
/** ExtraInfo events can arrive before the event they belong to. */
|
|
71
70
|
early = new Map();
|
|
@@ -74,9 +73,8 @@ export class HarRecorder {
|
|
|
74
73
|
tabs = new Map();
|
|
75
74
|
/** setDiscoverTargets also reports targets that already exist: each is attached once. */
|
|
76
75
|
attached = new Set();
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
this.socket = socket;
|
|
76
|
+
constructor(client, include) {
|
|
77
|
+
this.client = client;
|
|
80
78
|
this.include = include;
|
|
81
79
|
}
|
|
82
80
|
/**
|
|
@@ -84,19 +82,12 @@ export class HarRecorder {
|
|
|
84
82
|
* only the tabs it accepts, the popups they open, and tabs passed to follow().
|
|
85
83
|
*/
|
|
86
84
|
static async start(browserUrl, signal, include) {
|
|
87
|
-
const
|
|
88
|
-
const recorder = new HarRecorder(
|
|
89
|
-
|
|
90
|
-
socket.addEventListener("close", () => recorder.fail());
|
|
91
|
-
await new Promise((resolve, reject) => {
|
|
92
|
-
const abort = () => { socket.close(); reject(signal.reason); };
|
|
93
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
94
|
-
socket.addEventListener("open", () => { signal.removeEventListener("abort", abort); resolve(); }, { once: true });
|
|
95
|
-
socket.addEventListener("error", () => { signal.removeEventListener("abort", abort); reject(new Error("Could not open a DevTools connection for recording.")); }, { once: true });
|
|
96
|
-
});
|
|
85
|
+
const client = await CdpConnection.open(browserUrl, signal);
|
|
86
|
+
const recorder = new HarRecorder(client, include);
|
|
87
|
+
client.onEvent = event => recorder.receive(event);
|
|
97
88
|
try {
|
|
98
|
-
await
|
|
99
|
-
const { targetInfos } = await
|
|
89
|
+
await client.send("Target.setDiscoverTargets", { discover: true });
|
|
90
|
+
const { targetInfos } = await client.send("Target.getTargets");
|
|
100
91
|
await Promise.all(targetInfos
|
|
101
92
|
.filter(target => target.type === "page" && (!include || include(target.targetId))).map(target => recorder.attach(target.targetId)));
|
|
102
93
|
}
|
|
@@ -125,24 +116,7 @@ export class HarRecorder {
|
|
|
125
116
|
}
|
|
126
117
|
/** Ends recording without writing anything. */
|
|
127
118
|
close() {
|
|
128
|
-
|
|
129
|
-
return;
|
|
130
|
-
this.socket.close();
|
|
131
|
-
this.fail();
|
|
132
|
-
}
|
|
133
|
-
fail() {
|
|
134
|
-
this.closed = true;
|
|
135
|
-
for (const { reject } of this.pending.values())
|
|
136
|
-
reject(new Error("The recording connection closed."));
|
|
137
|
-
this.pending.clear();
|
|
138
|
-
}
|
|
139
|
-
send(method, params = {}, sessionId) {
|
|
140
|
-
if (this.closed)
|
|
141
|
-
return Promise.reject(new Error("The recording connection closed."));
|
|
142
|
-
const id = ++this.nextId;
|
|
143
|
-
const reply = new Promise((resolve, reject) => this.pending.set(id, { resolve, reject }));
|
|
144
|
-
this.socket.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
|
|
145
|
-
return reply;
|
|
119
|
+
this.client.close();
|
|
146
120
|
}
|
|
147
121
|
/** stop waits for reads in flight, such as response bodies, before writing. */
|
|
148
122
|
track(read) {
|
|
@@ -153,30 +127,16 @@ export class HarRecorder {
|
|
|
153
127
|
if (this.attached.has(targetId))
|
|
154
128
|
return;
|
|
155
129
|
this.attached.add(targetId);
|
|
156
|
-
const { sessionId } = await this.send("Target.attachToTarget", { targetId, flatten: true });
|
|
130
|
+
const { sessionId } = await this.client.send("Target.attachToTarget", { targetId, flatten: true });
|
|
157
131
|
this.tabs.set(sessionId, targetId);
|
|
158
|
-
await this.send("Network.enable", { maxPostDataSize: 1_000_000 }, sessionId);
|
|
132
|
+
await this.client.send("Network.enable", { maxPostDataSize: 1_000_000 }, sessionId);
|
|
159
133
|
}
|
|
160
134
|
/** Records a tab opened after start; a recorder without a tab filter already does. */
|
|
161
135
|
async follow(targetId) {
|
|
162
|
-
if (!this.closed)
|
|
136
|
+
if (!this.client.closed)
|
|
163
137
|
await this.attach(targetId);
|
|
164
138
|
}
|
|
165
|
-
receive(
|
|
166
|
-
if (message.id !== undefined) {
|
|
167
|
-
const entry = this.pending.get(message.id);
|
|
168
|
-
if (!entry)
|
|
169
|
-
return;
|
|
170
|
-
this.pending.delete(message.id);
|
|
171
|
-
if (message.error)
|
|
172
|
-
entry.reject(new Error(message.error.message));
|
|
173
|
-
else
|
|
174
|
-
entry.resolve(message.result);
|
|
175
|
-
return;
|
|
176
|
-
}
|
|
177
|
-
if (this.closed || !message.method)
|
|
178
|
-
return;
|
|
179
|
-
const { method, params, sessionId } = message;
|
|
139
|
+
receive({ method, params, sessionId }) {
|
|
180
140
|
// A new tab starts on Stagehand's extension page before it navigates, so every page target is attached.
|
|
181
141
|
// With a tab filter, a new tab is recorded when it is a popup of a recorded one; follow() adds the rest.
|
|
182
142
|
if (method === "Target.targetCreated" && params.targetInfo.type === "page"
|
|
@@ -205,7 +165,7 @@ export class HarRecorder {
|
|
|
205
165
|
};
|
|
206
166
|
this.drafts.set(key, next);
|
|
207
167
|
if (next.request.hasPostData && next.request.postData === undefined) {
|
|
208
|
-
this.track(this.send("Network.getRequestPostData", { requestId: params.requestId }, sessionId)
|
|
168
|
+
this.track(this.client.send("Network.getRequestPostData", { requestId: params.requestId }, sessionId)
|
|
209
169
|
.then(({ postData }) => { next.request.postData = postData; }));
|
|
210
170
|
}
|
|
211
171
|
return;
|
|
@@ -239,7 +199,7 @@ export class HarRecorder {
|
|
|
239
199
|
draft.encodedDataLength = params.encodedDataLength;
|
|
240
200
|
this.drafts.delete(key);
|
|
241
201
|
this.early.delete(key);
|
|
242
|
-
this.track(this.send("Network.getResponseBody", { requestId: params.requestId }, sessionId)
|
|
202
|
+
this.track(this.client.send("Network.getResponseBody", { requestId: params.requestId }, sessionId)
|
|
243
203
|
.then(({ body, base64Encoded }) => {
|
|
244
204
|
if (body.length > MAX_BODY_CHARS)
|
|
245
205
|
draft.bodyOmitted = true;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ClientGenerate } from "./session.ts";
|
|
2
|
+
export interface HostModelRequest {
|
|
3
|
+
systemPrompt: string[];
|
|
4
|
+
messages: {
|
|
5
|
+
role: "user";
|
|
6
|
+
content: ({
|
|
7
|
+
type: "text";
|
|
8
|
+
text: string;
|
|
9
|
+
} | {
|
|
10
|
+
type: "image";
|
|
11
|
+
data: string;
|
|
12
|
+
mimeType: string;
|
|
13
|
+
})[];
|
|
14
|
+
}[];
|
|
15
|
+
temperature?: number;
|
|
16
|
+
}
|
|
17
|
+
export interface HostModelReply {
|
|
18
|
+
text: string;
|
|
19
|
+
inputTokens: number;
|
|
20
|
+
outputTokens: number;
|
|
21
|
+
cachedInputTokens: number;
|
|
22
|
+
}
|
|
23
|
+
/** Stagehand's single-turn model protocol. The host owns model selection, cancellation, credentials and cost accounting. */
|
|
24
|
+
export declare function hostModelGenerate(complete: (request: HostModelRequest) => Promise<HostModelReply>): ClientGenerate;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Stagehand's single-turn model protocol. The host owns model selection, cancellation, credentials and cost accounting. */
|
|
2
|
+
export function hostModelGenerate(complete) {
|
|
3
|
+
return async (params) => {
|
|
4
|
+
if ("tools" in params && params.tools?.length)
|
|
5
|
+
throw new Error("Stagehand tool calls are not supported on host models.");
|
|
6
|
+
const messages = params.messages.map(message => {
|
|
7
|
+
if (message.role !== "user")
|
|
8
|
+
throw new Error("A host model accepts only single-turn Stagehand requests.");
|
|
9
|
+
const blocks = Array.isArray(message.content) ? message.content : [message.content];
|
|
10
|
+
return { role: "user", content: blocks.map(block => {
|
|
11
|
+
if (block.type === "text")
|
|
12
|
+
return { type: "text", text: block.text };
|
|
13
|
+
if (block.type === "image")
|
|
14
|
+
return { type: "image", mimeType: block.mimeType, data: block.data };
|
|
15
|
+
throw new Error("Unsupported Stagehand content: " + block.type);
|
|
16
|
+
}) };
|
|
17
|
+
});
|
|
18
|
+
const schema = params.responseFormat?.type === "json_schema" ? params.responseFormat.schema : undefined;
|
|
19
|
+
const systemPrompt = params.systemPrompt ? [params.systemPrompt] : [];
|
|
20
|
+
if (schema !== undefined)
|
|
21
|
+
systemPrompt.push("Reply with only one JSON value matching this JSON Schema, with no prose:\n" + JSON.stringify(schema));
|
|
22
|
+
const { text: raw, inputTokens, outputTokens, cachedInputTokens } = await complete({ systemPrompt, messages, temperature: params.temperature });
|
|
23
|
+
const text = raw.trim(), content = { type: "text", text }, usage = { inputTokens, outputTokens, cachedInputTokens, totalTokens: inputTokens + outputTokens };
|
|
24
|
+
if (schema === undefined)
|
|
25
|
+
return { role: "assistant", content, outputFormat: "text", usage };
|
|
26
|
+
let structuredContent;
|
|
27
|
+
try {
|
|
28
|
+
structuredContent = JSON.parse(/^```(?:json)?\s*([\s\S]*?)\s*```$/.exec(text)?.[1] ?? text);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new Error("The host model did not return valid JSON for Stagehand.");
|
|
32
|
+
}
|
|
33
|
+
return { role: "assistant", content, outputFormat: "json_schema", structuredContent, usage };
|
|
34
|
+
};
|
|
35
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { CdpConnection } from "./cdp-connection.ts";
|
|
2
|
+
export interface HttpAuth {
|
|
3
|
+
origin: string;
|
|
4
|
+
username: string;
|
|
5
|
+
password: string;
|
|
6
|
+
/** Also allow this credential to be used in an isolated Browserbase session. */
|
|
7
|
+
hosted?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare function resolveHttpAuth(credentials: HttpAuth | undefined, store: {
|
|
10
|
+
hosted?: boolean;
|
|
11
|
+
origin?: string;
|
|
12
|
+
} | undefined, initialUrl: string | undefined, hosted: boolean, signal: AbortSignal): Promise<HttpAuth>;
|
|
13
|
+
/** Listens before the first navigation. Chrome's auth cache belongs to the isolated browser until it closes. */
|
|
14
|
+
export declare function answerHttpAuth(browserUrl: string, config: HttpAuth, signal: AbortSignal): Promise<CdpConnection>;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { CdpConnection } from "./cdp-connection.js";
|
|
5
|
+
function authenticationOrigin(value, hosted) {
|
|
6
|
+
const url = URL.canParse(value) ? new URL(value) : undefined;
|
|
7
|
+
const loopback = !hosted && url?.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
8
|
+
if (!url || url.username || url.password || url.href !== url.origin + "/" || !(url.protocol === "https:" || loopback)) {
|
|
9
|
+
throw new Error("HTTP authentication requires an exact HTTPS origin. Local loopback HTTP is supported for testing.");
|
|
10
|
+
}
|
|
11
|
+
return url.origin;
|
|
12
|
+
}
|
|
13
|
+
/** Read one explicitly allowed origin through the installed native helper's local stdin/stdout protocol. */
|
|
14
|
+
async function fromStore(origin, signal) {
|
|
15
|
+
const executable = join(homedir(), ".local", "lib", "browse-http-auth", "host.py");
|
|
16
|
+
return new Promise((resolve, reject) => {
|
|
17
|
+
const denied = () => reject(new Error("The configured credential store did not return a login for this origin."));
|
|
18
|
+
const child = execFile(executable, ["--resolve"], { signal, timeout: 30_000, maxBuffer: 64 * 1024, encoding: "utf8" }, (error, stdout) => {
|
|
19
|
+
if (error) {
|
|
20
|
+
denied();
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
try {
|
|
24
|
+
const result = JSON.parse(stdout);
|
|
25
|
+
if (typeof result?.username !== "string" || typeof result?.password !== "string") {
|
|
26
|
+
denied();
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
resolve({ origin, username: result.username, password: result.password });
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
denied();
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
child.stdin?.on("error", denied);
|
|
36
|
+
child.stdin?.end(JSON.stringify({ origin }));
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
export async function resolveHttpAuth(credentials, store, initialUrl, hosted, signal) {
|
|
40
|
+
if (hosted && !(credentials ?? store)?.hosted)
|
|
41
|
+
throw new Error("This profile has not enabled HTTP authentication on Browserbase.");
|
|
42
|
+
if (!credentials && store) {
|
|
43
|
+
if (!initialUrl)
|
|
44
|
+
throw new Error("A start using the credential store needs a URL to select the site's login.");
|
|
45
|
+
const url = new URL(initialUrl);
|
|
46
|
+
if (url.username || url.password)
|
|
47
|
+
throw new Error("Supply the site's URL without credentials.");
|
|
48
|
+
const origin = authenticationOrigin(url.origin, hosted);
|
|
49
|
+
if (store.origin !== undefined && origin !== authenticationOrigin(store.origin, hosted)) {
|
|
50
|
+
throw new Error("The starting URL is outside the origin allowed by this profile's credential store.");
|
|
51
|
+
}
|
|
52
|
+
credentials = await fromStore(origin, signal);
|
|
53
|
+
}
|
|
54
|
+
if (!credentials || !credentials.username || credentials.username.includes(":") || !credentials.password) {
|
|
55
|
+
throw new Error("Configure an HTTP authentication origin, username and password or enable the credential store for this profile.");
|
|
56
|
+
}
|
|
57
|
+
return { ...credentials, origin: authenticationOrigin(credentials.origin, hosted) };
|
|
58
|
+
}
|
|
59
|
+
/** Listens before the first navigation. Chrome's auth cache belongs to the isolated browser until it closes. */
|
|
60
|
+
export async function answerHttpAuth(browserUrl, config, signal) {
|
|
61
|
+
const client = await CdpConnection.open(browserUrl, signal);
|
|
62
|
+
const attempted = new Map();
|
|
63
|
+
const enabling = new Set();
|
|
64
|
+
const close = () => client.close();
|
|
65
|
+
signal.addEventListener("abort", close, { once: true });
|
|
66
|
+
try {
|
|
67
|
+
signal.throwIfAborted();
|
|
68
|
+
client.onEvent = ({ method, params, sessionId }) => {
|
|
69
|
+
if (method === "Target.detachedFromTarget") {
|
|
70
|
+
attempted.delete(params.sessionId);
|
|
71
|
+
}
|
|
72
|
+
else if (method === "Target.attachedToTarget") {
|
|
73
|
+
const targetSession = params.sessionId;
|
|
74
|
+
attempted.set(targetSession, new Set());
|
|
75
|
+
const ready = client.send("Fetch.enable", { handleAuthRequests: true, patterns: [{ urlPattern: config.origin + "/*" }] }, targetSession)
|
|
76
|
+
.finally(async () => { if (params.waitingForDebugger)
|
|
77
|
+
await client.send("Runtime.runIfWaitingForDebugger", {}, targetSession); });
|
|
78
|
+
enabling.add(ready);
|
|
79
|
+
void ready.catch(() => { if (attempted.has(targetSession))
|
|
80
|
+
close(); }).finally(() => enabling.delete(ready));
|
|
81
|
+
}
|
|
82
|
+
else if (method === "Fetch.requestPaused") {
|
|
83
|
+
void client.send("Fetch.continueRequest", { requestId: params.requestId }, sessionId).catch(() => undefined);
|
|
84
|
+
}
|
|
85
|
+
else if (method === "Fetch.authRequired" && sessionId) {
|
|
86
|
+
const { requestId, request, authChallenge } = params;
|
|
87
|
+
const attempts = attempted.get(sessionId);
|
|
88
|
+
const eligible = attempts && authChallenge.source === "Server" && authChallenge.scheme.toLowerCase() === "basic"
|
|
89
|
+
&& authChallenge.origin === config.origin && URL.canParse(request.url) && new URL(request.url).origin === config.origin;
|
|
90
|
+
const provide = eligible && !attempts.has(requestId);
|
|
91
|
+
if (provide)
|
|
92
|
+
attempts.add(requestId);
|
|
93
|
+
const authChallengeResponse = provide
|
|
94
|
+
? { response: "ProvideCredentials", username: config.username, password: config.password }
|
|
95
|
+
: { response: eligible ? "CancelAuth" : "Default" };
|
|
96
|
+
void client.send("Fetch.continueWithAuth", { requestId, authChallengeResponse }, sessionId).catch(() => undefined);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
// Pause new page targets until their challenge listener is installed, including tabs opened by a site.
|
|
100
|
+
await client.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true, filter: [{ type: "page" }, { exclude: true }] });
|
|
101
|
+
await Promise.all(enabling);
|
|
102
|
+
signal.throwIfAborted();
|
|
103
|
+
if (client.closed)
|
|
104
|
+
throw new Error("DevTools disconnected during setup.");
|
|
105
|
+
return client;
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
close();
|
|
109
|
+
throw new Error("Could not enable HTTP authentication on the isolated browser.");
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
signal.removeEventListener("abort", close);
|
|
113
|
+
}
|
|
114
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
export
|
|
2
|
-
export
|
|
3
|
-
export
|
|
4
|
-
export {
|
|
5
|
-
export
|
|
6
|
-
export
|
|
7
|
-
export
|
|
8
|
-
export
|
|
9
|
-
export
|
|
10
|
-
export
|
|
11
|
-
export * from "./jev.ts";
|
|
12
|
-
export * from "./classifier.ts";
|
|
13
|
-
export * from "./command.ts";
|
|
1
|
+
export { BrowseSession, type BrowserOutput, type BrowseSessionOptions, type HostIdentity, type ClientGenerate, type ClientInference } from "./session.ts";
|
|
2
|
+
export { environmentConfig, type BrowseConfig, type ConfigurationContext, type ConfigResolver, type RemoteBrowser, type DomainLists } from "./config.ts";
|
|
3
|
+
export { BrowseToolError, type BatchProgress } from "./errors.ts";
|
|
4
|
+
export { browserParameters, browserBatchParameters, aiParameters, type AIParams, type BrowserParams, type BatchStep, type AskFields } from "./schema.ts";
|
|
5
|
+
export { hostModelGenerate, type HostModelRequest, type HostModelReply } from "./host-model.ts";
|
|
6
|
+
export { nameChromeProfile } from "./chrome-profile.ts";
|
|
7
|
+
export { BROWSER_IDS, localCookieProvider, normalizeCookieDomains, CookieSourceError, type BrowserId, type BrowserCookies, type BrowserProfileMatch, type CookieProvider, type CookieBrowser } from "./browser-cookies.ts";
|
|
8
|
+
export { classifierSpec, ClassifierRefusal, workersAiClassifier, vercelClassifier, type Answer, type ClassifyRequest, type HostClassify } from "./classifier.ts";
|
|
9
|
+
export { SETTINGS_FILE, CONVERSATION_MODEL, DEFAULT_CLASSIFIER, ROLE_KEYS, readSettings, writeSetting, modelRef, roleChoice, classifierOptions, type ModelOption, type ModelRole, type ClassifierInfo, type BrowseSettings } from "./settings.ts";
|
|
10
|
+
export { SETTINGS, SETTING_SUMMARY, USAGE, parseBrowseCommand, browseCompletions, type BrowseCommand, type CompletionSource, type CompletionItem } from "./command.ts";
|
package/dist/index.js
CHANGED
|
@@ -1,15 +1,11 @@
|
|
|
1
|
-
// Host
|
|
2
|
-
export
|
|
3
|
-
export
|
|
4
|
-
export
|
|
5
|
-
|
|
6
|
-
export {
|
|
7
|
-
export
|
|
8
|
-
export
|
|
9
|
-
export
|
|
10
|
-
export
|
|
11
|
-
export
|
|
12
|
-
export * from "./browser-cookies.js";
|
|
13
|
-
export * from "./jev.js";
|
|
14
|
-
export * from "./classifier.js";
|
|
15
|
-
export * from "./command.js";
|
|
1
|
+
// Host integration surface. Serialized worker callbacks and transport internals are not public APIs.
|
|
2
|
+
export { BrowseSession } from "./session.js";
|
|
3
|
+
export { environmentConfig } from "./config.js";
|
|
4
|
+
export { BrowseToolError } from "./errors.js";
|
|
5
|
+
export { browserParameters, browserBatchParameters, aiParameters } from "./schema.js";
|
|
6
|
+
export { hostModelGenerate } from "./host-model.js";
|
|
7
|
+
export { nameChromeProfile } from "./chrome-profile.js";
|
|
8
|
+
export { BROWSER_IDS, localCookieProvider, normalizeCookieDomains, CookieSourceError } from "./browser-cookies.js";
|
|
9
|
+
export { classifierSpec, ClassifierRefusal, workersAiClassifier, vercelClassifier } from "./classifier.js";
|
|
10
|
+
export { SETTINGS_FILE, CONVERSATION_MODEL, DEFAULT_CLASSIFIER, ROLE_KEYS, readSettings, writeSetting, modelRef, roleChoice, classifierOptions } from "./settings.js";
|
|
11
|
+
export { SETTINGS, SETTING_SUMMARY, USAGE, parseBrowseCommand, browseCompletions } from "./command.js";
|
package/dist/jev.js
CHANGED
|
@@ -94,7 +94,8 @@ export function fitsAction(action, candidate, xpath) {
|
|
|
94
94
|
// Stagehand xpath steps are tagName[n]; the last one is the element's own tag.
|
|
95
95
|
const tag = /(?:^|\/)([\w-]+)\[\d+\]$/.exec(xpath)?.[1].toLowerCase();
|
|
96
96
|
if (action === "fill")
|
|
97
|
-
return tag === "
|
|
97
|
+
return tag === "textarea" || (tag !== "select" && Object.hasOwn(FILLABLE, candidate.role))
|
|
98
|
+
|| (tag === "input" && ["Date", "DateTime", "InputTime", "week", "month"].includes(candidate.role));
|
|
98
99
|
if (action === "select")
|
|
99
100
|
return tag === "select";
|
|
100
101
|
return true;
|
|
@@ -119,8 +120,13 @@ export async function pickTarget(candidates, state, choose, signal) {
|
|
|
119
120
|
}
|
|
120
121
|
const won = answers.flatMap((answer, i) => chunks[i].filter(c => c.ref === answer.choice).map(chosen => ({ chosen, confidence: answer.confidence })));
|
|
121
122
|
// Every chunk answered NONE; report how sure the least-sure chunk was.
|
|
122
|
-
if (!won.length)
|
|
123
|
-
|
|
123
|
+
if (!won.length) {
|
|
124
|
+
const confidence = Math.min(...answers.map(a => a.confidence));
|
|
125
|
+
const none = confidence >= JEV_MIN_CONFIDENCE;
|
|
126
|
+
const ranked = none ? [] : chunks.flatMap((chunk, i) => chunk.map(c => ({ ...c, probability: answers[i].probabilities[c.ref] ?? 0 })))
|
|
127
|
+
.sort((a, b) => b.probability - a.probability).slice(0, 5);
|
|
128
|
+
return { none, confidence, ranked };
|
|
129
|
+
}
|
|
124
130
|
// A lone confident winner would face only itself in another round; take it without the extra request.
|
|
125
131
|
if (won.length === 1 && won[0].confidence >= JEV_MIN_CONFIDENCE)
|
|
126
132
|
return { ...won[0], none: false, ranked: [] };
|
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
import type { ExperimentalBatchContext } from "@browserbasehq/stagehand";
|
|
2
2
|
import type { AnsweredDialog } from "./session.ts";
|
|
3
3
|
export interface PageOperation {
|
|
4
|
-
action: "start" | "open" | "back" | "forward" | "reload" | "wait" | "snapshot" | "click" | "fill" | "select" | "press" | "scroll" | "evaluate" | "screenshot" | "tab_select";
|
|
4
|
+
action: "start" | "open" | "back" | "forward" | "reload" | "wait" | "snapshot" | "click" | "fill" | "select" | "press" | "scroll" | "evaluate" | "screenshot" | "tab_select" | "hover" | "upload" | "viewport";
|
|
5
|
+
width?: number;
|
|
6
|
+
height?: number;
|
|
7
|
+
file?: {
|
|
8
|
+
name: string;
|
|
9
|
+
mimeType: string;
|
|
10
|
+
base64: string;
|
|
11
|
+
};
|
|
5
12
|
selector?: string;
|
|
6
13
|
nth?: number;
|
|
7
14
|
/** Snapshot ref to verify before acting: the tab URL, the ref ID (frame ordinal and backend node), and its XPath. */
|
|
@@ -31,6 +38,8 @@ export interface PageOperation {
|
|
|
31
38
|
snapshot?: {
|
|
32
39
|
version: string;
|
|
33
40
|
maxChars: number;
|
|
41
|
+
offset?: number;
|
|
42
|
+
interactive?: boolean;
|
|
34
43
|
};
|
|
35
44
|
readTimeoutMs: number;
|
|
36
45
|
}
|
|
@@ -38,6 +47,7 @@ export interface PageOperation {
|
|
|
38
47
|
export interface PageSnapshot {
|
|
39
48
|
tree: string;
|
|
40
49
|
truncated: boolean;
|
|
50
|
+
nextOffset?: number;
|
|
41
51
|
refs: Record<string, string>;
|
|
42
52
|
}
|
|
43
53
|
export interface PageOperationResult {
|