@edlsh/browse-core 0.5.0 → 0.6.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 +14 -0
- package/dist/ask.d.ts +6 -2
- package/dist/ask.js +1 -1
- package/dist/har.d.ts +39 -0
- package/dist/har.js +32 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/jev.d.ts +5 -0
- package/dist/jev.js +31 -0
- package/dist/real-browser-ai.d.ts +16 -0
- package/dist/real-browser-ai.js +52 -0
- package/dist/real-browser-client.d.ts +36 -0
- package/dist/real-browser-client.js +127 -0
- package/dist/real-browser-session.d.ts +57 -0
- package/dist/real-browser-session.js +274 -0
- package/dist/schema.d.ts +4 -0
- package/dist/schema.js +5 -2
- package/dist/session.d.ts +31 -0
- package/dist/session.js +206 -32
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -32,6 +32,20 @@ A persistent profile (`localUserDataDir`) and an attached browser (`cdpUrl` or a
|
|
|
32
32
|
|
|
33
33
|
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).
|
|
34
34
|
|
|
35
|
+
## The user's real browser
|
|
36
|
+
|
|
37
|
+
A profile whose config sets `realBrowser.command` works in the user's own browser through [OpenCode Browse](https://opencode.ai/product/browse) instead of launching one: a local `start` that names no `cdpUrl`, `endpoint`, or `headless` goes there. `command` is the argv that runs OpenCode Browse's MCP server, `["/path/to/browse", "mcp"]` on the machine with the browser or the same behind `ssh` from another one. The browser needs OpenCode Browse's extension, paired once.
|
|
38
|
+
|
|
39
|
+
Each conversation's tabs open in the background in a tab group of its own, and `close` closes that group; the browser and the person's tabs stay. `snapshot` returns OpenCode Browse's outline, whose refs (`e12`) the other actions take as `selector`, alongside CSS, `xpath=`, and `text=` selectors. `handoff` gives the selected tab to the person with a message and returns once they click Continue (ten minutes by default).
|
|
40
|
+
|
|
41
|
+
Stagehand cannot attach to this browser, so what it does elsewhere runs here on the outline and the page's visible text:
|
|
42
|
+
|
|
43
|
+
- `target` and `ask` use the same classifiers and settings.
|
|
44
|
+
- `browse_ai` runs act, observe, and extract on the host's own inference (the `generate` a host lends Stagehand); a host that lends none gets `configuration`. act performs one action.
|
|
45
|
+
- `har_start` and `har_stop` write OpenCode Browse's network capture of the selected tab. It redacts credentials, leaves out the bodies of pages, scripts, styles, and images, and holds at most 1000 requests.
|
|
46
|
+
|
|
47
|
+
`live_view`, `cookie_import`, and saved contexts stay Browserbase's. Blocked domains cannot be enforced here and refuse the start; allowed domains become the tabs' allowed origins. `headless: true`, `cdpUrl`, and `endpoint` still launch or attach a Chrome of this tool's own.
|
|
48
|
+
|
|
35
49
|
## Develop
|
|
36
50
|
|
|
37
51
|
```sh
|
package/dist/ask.d.ts
CHANGED
|
@@ -5,11 +5,15 @@ export declare const EXTRACT_MODEL = "@cf/cloudflare/clairic";
|
|
|
5
5
|
export declare const MAX_TEXT = 100000;
|
|
6
6
|
/** Clef Flash reads 24,576 tokens: about 72k characters of page text leaves room for the questions. */
|
|
7
7
|
export declare const DECIDE_TEXT: Record<string, number>;
|
|
8
|
-
|
|
8
|
+
/** A page as ask reads it: a Stagehand snapshot tree, or text a browser without one supplies ready to read. */
|
|
9
|
+
export type PageState = {
|
|
9
10
|
url: string;
|
|
10
11
|
title: string;
|
|
12
|
+
} & ({
|
|
11
13
|
tree: string;
|
|
12
|
-
}
|
|
14
|
+
} | {
|
|
15
|
+
text: string;
|
|
16
|
+
});
|
|
13
17
|
/** bool answers carry the probability of yes; other answers carry the model's confidence. */
|
|
14
18
|
export type Answer = {
|
|
15
19
|
value: boolean;
|
package/dist/ask.js
CHANGED
|
@@ -70,7 +70,7 @@ async function extractValues(cloudflare, input, signal) {
|
|
|
70
70
|
* answers bool and choice questions; when a call needs both, they run in parallel.
|
|
71
71
|
*/
|
|
72
72
|
export async function askPage(models, page, fields, signal) {
|
|
73
|
-
const full = pageText(page.tree);
|
|
73
|
+
const full = "text" in page ? page.text : pageText(page.tree);
|
|
74
74
|
const decideLimit = Math.min(models.decideText ?? MAX_TEXT, MAX_TEXT);
|
|
75
75
|
const entries = Object.entries(fields);
|
|
76
76
|
const decide = entries.filter(([, field]) => Object.hasOwn(DECISIONS, field.type));
|
package/dist/har.d.ts
CHANGED
|
@@ -8,6 +8,44 @@ export interface HarSummary {
|
|
|
8
8
|
/** HAR has no place for traffic still in flight at stop; it is dropped. */
|
|
9
9
|
unfinished: number;
|
|
10
10
|
}
|
|
11
|
+
type NameValue = {
|
|
12
|
+
name: string;
|
|
13
|
+
value: string;
|
|
14
|
+
};
|
|
15
|
+
interface CapturedBody {
|
|
16
|
+
size?: number;
|
|
17
|
+
mimeType?: string;
|
|
18
|
+
text?: string;
|
|
19
|
+
omitted?: boolean;
|
|
20
|
+
}
|
|
21
|
+
/** A tab's traffic as OpenCode Browse's network capture returns it at stop. */
|
|
22
|
+
export interface NetworkCapture {
|
|
23
|
+
failureCount?: number;
|
|
24
|
+
droppedEntryCount?: number;
|
|
25
|
+
exchanges: {
|
|
26
|
+
startedDateTime: string;
|
|
27
|
+
durationMs?: number;
|
|
28
|
+
request: {
|
|
29
|
+
method: string;
|
|
30
|
+
url: string;
|
|
31
|
+
headers?: NameValue[];
|
|
32
|
+
body?: CapturedBody;
|
|
33
|
+
};
|
|
34
|
+
response?: {
|
|
35
|
+
status: number;
|
|
36
|
+
statusText?: string;
|
|
37
|
+
headers?: NameValue[];
|
|
38
|
+
body?: CapturedBody;
|
|
39
|
+
};
|
|
40
|
+
}[];
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Writes OpenCode Browse's capture of one tab as HAR 1.2 (mode 0600). The capture arrives with credentials redacted
|
|
44
|
+
* and without the bodies of HTML, scripts, styles, and images, so the file holds less than a HarRecorder's does.
|
|
45
|
+
*/
|
|
46
|
+
export declare function writeCaptureHar(capture: NetworkCapture, path: string, creator: string): Promise<HarSummary & {
|
|
47
|
+
dropped: number;
|
|
48
|
+
}>;
|
|
11
49
|
/**
|
|
12
50
|
* Records the network traffic of every tab in one browser as HAR 1.2, over its own DevTools connection to the browser
|
|
13
51
|
* target. Request headers include Cookie and response headers Set-Cookie (from the ExtraInfo events), and request and
|
|
@@ -48,3 +86,4 @@ export declare class HarRecorder {
|
|
|
48
86
|
private finish;
|
|
49
87
|
private entry;
|
|
50
88
|
}
|
|
89
|
+
export {};
|
package/dist/har.js
CHANGED
|
@@ -3,6 +3,38 @@ import { dirname } from "node:path";
|
|
|
3
3
|
// Stagehand 4.3 forwards only console events from CDP, so network capture uses its own connection to the browser target.
|
|
4
4
|
/** A response body larger than this (base64 or text characters) is left out of the HAR and counted instead. */
|
|
5
5
|
const MAX_BODY_CHARS = 5_000_000;
|
|
6
|
+
/**
|
|
7
|
+
* Writes OpenCode Browse's capture of one tab as HAR 1.2 (mode 0600). The capture arrives with credentials redacted
|
|
8
|
+
* and without the bodies of HTML, scripts, styles, and images, so the file holds less than a HarRecorder's does.
|
|
9
|
+
*/
|
|
10
|
+
export async function writeCaptureHar(capture, path, creator) {
|
|
11
|
+
const exchanges = capture.exchanges.filter(exchange => /^(?:https?|wss?):/.test(exchange.request.url));
|
|
12
|
+
const entries = exchanges.map(({ startedDateTime, durationMs = 0, request, response }) => ({
|
|
13
|
+
startedDateTime, time: durationMs,
|
|
14
|
+
request: {
|
|
15
|
+
method: request.method, url: request.url, httpVersion: "",
|
|
16
|
+
// HTTP/2 pseudo-headers repeat the method and URL.
|
|
17
|
+
headers: (request.headers ?? []).filter(header => !header.name.startsWith(":")),
|
|
18
|
+
queryString: URL.canParse(request.url) ? [...new URL(request.url).searchParams].map(([name, value]) => ({ name, value })) : [],
|
|
19
|
+
cookies: [], headersSize: -1, bodySize: request.body?.size ?? 0,
|
|
20
|
+
...(request.body?.text === undefined ? {} : { postData: { mimeType: request.body.mimeType ?? "", text: request.body.text } }),
|
|
21
|
+
},
|
|
22
|
+
response: {
|
|
23
|
+
status: response?.status ?? 0, statusText: response?.statusText ?? "", httpVersion: "", headers: response?.headers ?? [], cookies: [],
|
|
24
|
+
content: { size: response?.body?.size ?? 0, mimeType: response?.body?.mimeType ?? "", ...(response?.body?.text === undefined ? {} : { text: response.body.text }) },
|
|
25
|
+
redirectURL: "", headersSize: -1, bodySize: -1,
|
|
26
|
+
},
|
|
27
|
+
cache: {}, timings: { send: 0, wait: durationMs, receive: 0 },
|
|
28
|
+
}));
|
|
29
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
30
|
+
await writeFile(path, JSON.stringify({ log: { version: "1.2", creator: { name: creator, version: "1" }, pages: [], entries } }), { mode: 0o600 });
|
|
31
|
+
await chmod(path, 0o600);
|
|
32
|
+
const hosts = [...new Set(exchanges.map(exchange => URL.canParse(exchange.request.url) ? new URL(exchange.request.url).host : "").filter(Boolean))];
|
|
33
|
+
return {
|
|
34
|
+
path, entries: entries.length, tabs: 1, hosts: hosts.slice(0, 30), failed: capture.failureCount ?? 0,
|
|
35
|
+
bodiesOmitted: exchanges.filter(exchange => exchange.response?.body?.omitted).length, unfinished: 0, dropped: capture.droppedEntryCount ?? 0,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
6
38
|
/** CDP header objects join repeated headers with newlines; HAR lists each value. */
|
|
7
39
|
function headerList(headers) {
|
|
8
40
|
return Object.entries(headers).flatMap(([name, value]) => String(value).split("\n").map(line => ({ name, value: line })));
|
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 "./real-browser-client.ts";
|
|
6
7
|
export * from "./chrome-profile.ts";
|
|
7
8
|
export * from "./har.ts";
|
|
8
9
|
export * from "./page-operations.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 "./real-browser-client.js";
|
|
8
9
|
export * from "./chrome-profile.js";
|
|
9
10
|
export * from "./har.js";
|
|
10
11
|
export * from "./page-operations.js";
|
package/dist/jev.d.ts
CHANGED
|
@@ -30,6 +30,11 @@ export interface JevPick {
|
|
|
30
30
|
* also carry their adjacent siblings' text, where visible labels such as "checkbox 1" usually live.
|
|
31
31
|
*/
|
|
32
32
|
export declare function treeCandidates(tree: string): Candidate[];
|
|
33
|
+
/**
|
|
34
|
+
* Targetable lines of an OpenCode Browse outline (`- button "Save" [ref=e12 disabled]`) that `action` can operate on.
|
|
35
|
+
* Labels keep the element's states and carry up to two named ancestors, as treeCandidates' do.
|
|
36
|
+
*/
|
|
37
|
+
export declare function outlineCandidates(outline: string, action: string): Candidate[];
|
|
33
38
|
/** Whether `action` can operate on the element at `xpath`: fill needs a text-entry control, select a native <select>. */
|
|
34
39
|
export declare function fitsAction(action: string, candidate: Candidate, xpath: string): boolean;
|
|
35
40
|
/** Tournament over Jev's per-choice option limit; the final round decides whether the pick is confident enough to act. */
|
package/dist/jev.js
CHANGED
|
@@ -58,6 +58,37 @@ export function treeCandidates(tree) {
|
|
|
58
58
|
});
|
|
59
59
|
return candidates;
|
|
60
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Targetable lines of an OpenCode Browse outline (`- button "Save" [ref=e12 disabled]`) that `action` can operate on.
|
|
63
|
+
* Labels keep the element's states and carry up to two named ancestors, as treeCandidates' do.
|
|
64
|
+
*/
|
|
65
|
+
export function outlineCandidates(outline, action) {
|
|
66
|
+
const candidates = [];
|
|
67
|
+
const ancestors = [];
|
|
68
|
+
for (const line of outline.split("\n")) {
|
|
69
|
+
const match = /^(\s*)- ([\w-]+)(?: "((?:[^"\\]|\\.)*)")?(?: \[([^\]]*)\])?/.exec(line);
|
|
70
|
+
if (!match)
|
|
71
|
+
continue;
|
|
72
|
+
const [, indent, role, name = "", attributes = ""] = match;
|
|
73
|
+
const depth = indent.length;
|
|
74
|
+
while (ancestors.length && ancestors.at(-1).depth >= depth)
|
|
75
|
+
ancestors.pop();
|
|
76
|
+
const ref = /(?:^| )ref=(e\d+)/.exec(attributes)?.[1];
|
|
77
|
+
const states = attributes.split(" ").filter(state => state && !state.startsWith("ref="));
|
|
78
|
+
const text = name ? `${role}: ${name}` : role;
|
|
79
|
+
// fill needs a text-entry control it may change; select needs a native <select>, which lists its options.
|
|
80
|
+
const fits = action === "fill" ? Object.hasOwn(FILLABLE, role) && !states.includes("readonly") && !states.includes("options")
|
|
81
|
+
: action === "select" ? states.includes("options")
|
|
82
|
+
: true;
|
|
83
|
+
if (ref && fits && !states.includes("disabled")) {
|
|
84
|
+
const context = ancestors.flatMap(a => a.label ? [a.label] : []).slice(-2);
|
|
85
|
+
const label = `${text}${states.length ? ` [${states.join(" ")}]` : ""}${context.length ? ` (in ${context.join(" > ")})` : ""}`;
|
|
86
|
+
candidates.push({ ref, label: label.slice(0, 240), role: role });
|
|
87
|
+
}
|
|
88
|
+
ancestors.push({ depth, label: name ? text.slice(0, 80) : undefined });
|
|
89
|
+
}
|
|
90
|
+
return candidates;
|
|
91
|
+
}
|
|
61
92
|
/** Whether `action` can operate on the element at `xpath`: fill needs a text-entry control, select a native <select>. */
|
|
62
93
|
export function fitsAction(action, candidate, xpath) {
|
|
63
94
|
// Stagehand xpath steps are tagName[n]; the last one is the element's own tag.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { RealBrowserPage } from "./real-browser-session.ts";
|
|
2
|
+
import { type ClientGenerate } from "./session.ts";
|
|
3
|
+
/** One thing to do to one element, in the shape Stagehand's observe returns: `selector` is a snapshot ref. */
|
|
4
|
+
export interface PageAction {
|
|
5
|
+
selector: string;
|
|
6
|
+
description: string;
|
|
7
|
+
method: "click" | "fill" | "select" | "press";
|
|
8
|
+
arguments: string[];
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The elements an instruction is about, each with the action that would carry it out. `single` asks for the one next
|
|
12
|
+
* action, for act. A ref the outline does not have is the model's invention and is dropped.
|
|
13
|
+
*/
|
|
14
|
+
export declare function observePage(generate: ClientGenerate, page: RealBrowserPage, instruction: string, single: boolean): Promise<PageAction[]>;
|
|
15
|
+
/** What the page says in answer to an instruction, as JSON matching `schema`; without one, as `{ extraction }`. */
|
|
16
|
+
export declare function extractPage(generate: ClientGenerate, page: RealBrowserPage, instruction: string, schema: Record<string, unknown> | undefined): Promise<unknown>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { MAX_TEXT } from "./ask.js";
|
|
2
|
+
import { BrowseToolError } from "./session.js";
|
|
3
|
+
const ACTIONS_SCHEMA = {
|
|
4
|
+
type: "object", additionalProperties: false, required: ["elements"],
|
|
5
|
+
properties: {
|
|
6
|
+
elements: {
|
|
7
|
+
type: "array",
|
|
8
|
+
items: {
|
|
9
|
+
type: "object", additionalProperties: false, required: ["ref", "description", "method", "arguments"],
|
|
10
|
+
properties: {
|
|
11
|
+
ref: { type: "string", description: "The element's ref from the outline, e.g. e12." },
|
|
12
|
+
description: { type: "string", description: "What the element is, in a few words." },
|
|
13
|
+
method: { type: "string", enum: ["click", "fill", "select", "press"] },
|
|
14
|
+
arguments: { type: "array", items: { type: "string" }, description: "fill: the text. select: the option labels or values. press: the key. click: none." },
|
|
15
|
+
},
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
const OUTLINE = "The page is an outline with one element per line, as `- role \"name\" [ref=e12 states]`, indented under its container. Only an element with a ref can be acted on.";
|
|
21
|
+
/** One single-turn request for JSON matching `schema`; the host's model answers it. */
|
|
22
|
+
async function generateJson(generate, systemPrompt, text, schema) {
|
|
23
|
+
// SAFETY: a single user turn of text with a JSON Schema response format is one of the requests ClientGenerate takes;
|
|
24
|
+
// its parameter type is Stagehand's whole model-call union, which this literal does not spell out.
|
|
25
|
+
const reply = await generate({ systemPrompt, messages: [{ role: "user", content: { type: "text", text } }], responseFormat: { type: "json_schema", schema }, temperature: 0 });
|
|
26
|
+
if (reply.outputFormat !== "json_schema")
|
|
27
|
+
throw new BrowseToolError("ai_error", "The model answered in prose where JSON was asked for.");
|
|
28
|
+
return reply.structuredContent;
|
|
29
|
+
}
|
|
30
|
+
function describe(page, instruction) {
|
|
31
|
+
return `Instruction: ${instruction}\nPage title: ${page.title ?? ""}\nURL: ${page.url}`;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The elements an instruction is about, each with the action that would carry it out. `single` asks for the one next
|
|
35
|
+
* action, for act. A ref the outline does not have is the model's invention and is dropped.
|
|
36
|
+
*/
|
|
37
|
+
export async function observePage(generate, page, instruction, single) {
|
|
38
|
+
const task = single
|
|
39
|
+
? "Return the one next action that carries out the instruction, or no elements when the page offers none."
|
|
40
|
+
: "Return every element the instruction is about, each with the action a person would take on it.";
|
|
41
|
+
const reply = await generateJson(generate, `You choose elements on a web page for a browser agent. ${OUTLINE} ${task} Answer with JSON only.`, `${describe(page, instruction)}\n\nOutline:\n${page.outline}`, ACTIONS_SCHEMA);
|
|
42
|
+
const refs = new Set(page.outline.match(/\bref=e\d+/g)?.map(ref => ref.slice(4)));
|
|
43
|
+
return (reply.elements ?? []).flatMap(({ ref, description, method, arguments: args }) => {
|
|
44
|
+
if (typeof ref !== "string" || !refs.has(ref) || (method !== "click" && method !== "fill" && method !== "select" && method !== "press"))
|
|
45
|
+
return [];
|
|
46
|
+
return [{ selector: ref, description: String(description ?? ""), method, arguments: Array.isArray(args) ? args.map(String) : [] }];
|
|
47
|
+
}).slice(0, single ? 1 : undefined);
|
|
48
|
+
}
|
|
49
|
+
/** What the page says in answer to an instruction, as JSON matching `schema`; without one, as `{ extraction }`. */
|
|
50
|
+
export async function extractPage(generate, page, instruction, schema) {
|
|
51
|
+
return generateJson(generate, "You extract information from a web page for a browser agent. Use only what the page says, and null for what it does not say. Answer with JSON only.", `${describe(page, instruction)}\n\nPage text:\n${page.text.slice(0, MAX_TEXT)}`, schema ?? { type: "object", additionalProperties: false, required: ["extraction"], properties: { extraction: { type: "string" } } });
|
|
52
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export interface RealBrowserImage {
|
|
2
|
+
data: string;
|
|
3
|
+
mimeType: string;
|
|
4
|
+
}
|
|
5
|
+
/** A tool's result: its text blocks joined, and the images it carried (a screenshot). */
|
|
6
|
+
export interface RealBrowserResult {
|
|
7
|
+
text: string;
|
|
8
|
+
images: RealBrowserImage[];
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* One `browse mcp` process, started on the first call and again on the call after it exits. Every conversation in the
|
|
12
|
+
* host process shares it: OpenCode Browse keeps the tabs, so nothing about a conversation lives here.
|
|
13
|
+
*/
|
|
14
|
+
export declare class RealBrowserClient {
|
|
15
|
+
private readonly command;
|
|
16
|
+
private readonly client;
|
|
17
|
+
private child?;
|
|
18
|
+
private ready?;
|
|
19
|
+
private readonly pending;
|
|
20
|
+
private nextId;
|
|
21
|
+
private stderr;
|
|
22
|
+
/** `command` is the argv that runs `browse mcp`, on this machine or over SSH on the machine with the browser. */
|
|
23
|
+
constructor(command: readonly string[], client: {
|
|
24
|
+
name: string;
|
|
25
|
+
version: string;
|
|
26
|
+
});
|
|
27
|
+
/** Runs one of OpenCode Browse's tools. A tool's own failure (a refused navigation, a script error) keeps its text. */
|
|
28
|
+
call(tool: "execute" | "tabs" | "status", args: Record<string, unknown>, signal: AbortSignal): Promise<RealBrowserResult>;
|
|
29
|
+
/** Ends the process. OpenCode Browse keeps the tabs agents opened, so closing them is the session's job. */
|
|
30
|
+
close(): void;
|
|
31
|
+
private unreachable;
|
|
32
|
+
private start;
|
|
33
|
+
private send;
|
|
34
|
+
private request;
|
|
35
|
+
private receive;
|
|
36
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// The user's real browser, driven through OpenCode Browse: its MCP server (`browse mcp`) and its browser extension.
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { createInterface } from "node:readline";
|
|
4
|
+
import { BrowseToolError } from "./session.js";
|
|
5
|
+
/** The newest MCP revision this client speaks; the server answers with the one it chose. */
|
|
6
|
+
const MCP_PROTOCOL = "2025-06-18";
|
|
7
|
+
/** A server silent this long is not coming: an SSH hop to a sleeping machine, or a command that waits for input. */
|
|
8
|
+
const CONNECT_TIMEOUT_MS = 20_000;
|
|
9
|
+
/**
|
|
10
|
+
* One `browse mcp` process, started on the first call and again on the call after it exits. Every conversation in the
|
|
11
|
+
* host process shares it: OpenCode Browse keeps the tabs, so nothing about a conversation lives here.
|
|
12
|
+
*/
|
|
13
|
+
export class RealBrowserClient {
|
|
14
|
+
command;
|
|
15
|
+
client;
|
|
16
|
+
child;
|
|
17
|
+
ready;
|
|
18
|
+
pending = new Map();
|
|
19
|
+
nextId = 0;
|
|
20
|
+
stderr = "";
|
|
21
|
+
/** `command` is the argv that runs `browse mcp`, on this machine or over SSH on the machine with the browser. */
|
|
22
|
+
constructor(command, client) {
|
|
23
|
+
this.command = command;
|
|
24
|
+
this.client = client;
|
|
25
|
+
}
|
|
26
|
+
/** Runs one of OpenCode Browse's tools. A tool's own failure (a refused navigation, a script error) keeps its text. */
|
|
27
|
+
async call(tool, args, signal) {
|
|
28
|
+
signal.throwIfAborted();
|
|
29
|
+
await (this.ready ??= this.start().catch(error => { this.ready = undefined; throw error; }));
|
|
30
|
+
const result = await this.request("tools/call", { name: tool, arguments: args }, signal);
|
|
31
|
+
const blocks = result.content ?? [];
|
|
32
|
+
const text = blocks.flatMap(block => block.type === "text" ? [block.text] : []).join("\n");
|
|
33
|
+
if (result.isError)
|
|
34
|
+
throw new BrowseToolError("real_browser_error", text || `OpenCode Browse's ${tool} failed without a message.`);
|
|
35
|
+
return { text, images: blocks.flatMap(block => block.type === "image" ? [{ data: block.data, mimeType: block.mimeType }] : []) };
|
|
36
|
+
}
|
|
37
|
+
/** Ends the process. OpenCode Browse keeps the tabs agents opened, so closing them is the session's job. */
|
|
38
|
+
close() {
|
|
39
|
+
this.child?.kill();
|
|
40
|
+
}
|
|
41
|
+
unreachable(why) {
|
|
42
|
+
const said = this.stderr.trim().replace(/\s+/g, " ").slice(-300);
|
|
43
|
+
return new BrowseToolError("real_browser_unreachable", `OpenCode Browse (${this.command[0]}) ${why}.${said ? ` It said: ${said}.` : ""} `
|
|
44
|
+
+ "Check that the machine with the browser is awake and that `browse status` there reports a connected extension.");
|
|
45
|
+
}
|
|
46
|
+
async start() {
|
|
47
|
+
const [file, ...args] = this.command;
|
|
48
|
+
if (!file)
|
|
49
|
+
throw new BrowseToolError("real_browser_config", "The real browser's command is empty; set it to the argv that runs `browse mcp`.");
|
|
50
|
+
this.stderr = "";
|
|
51
|
+
const child = spawn(file, args, { stdio: ["pipe", "pipe", "pipe"] });
|
|
52
|
+
this.child = child;
|
|
53
|
+
const gone = (why) => {
|
|
54
|
+
if (this.child !== child)
|
|
55
|
+
return;
|
|
56
|
+
this.child = undefined;
|
|
57
|
+
this.ready = undefined;
|
|
58
|
+
const error = this.unreachable(why);
|
|
59
|
+
for (const call of this.pending.values())
|
|
60
|
+
call.reject(error);
|
|
61
|
+
this.pending.clear();
|
|
62
|
+
};
|
|
63
|
+
child.on("error", error => gone(`could not start: ${error.message}`));
|
|
64
|
+
child.on("exit", code => gone(code === null ? "was stopped" : `exited with code ${code}`));
|
|
65
|
+
// A write to a process that just exited fails here; the exit handler already told every caller.
|
|
66
|
+
child.stdin.on("error", () => undefined);
|
|
67
|
+
child.stderr.on("data", chunk => { this.stderr = (this.stderr + String(chunk)).slice(-2000); });
|
|
68
|
+
createInterface({ input: child.stdout }).on("line", line => this.receive(child, line));
|
|
69
|
+
try {
|
|
70
|
+
await this.request("initialize", { protocolVersion: MCP_PROTOCOL, capabilities: {}, clientInfo: this.client }, AbortSignal.timeout(CONNECT_TIMEOUT_MS));
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
child.kill();
|
|
74
|
+
throw error instanceof BrowseToolError ? error : this.unreachable(`did not answer within ${CONNECT_TIMEOUT_MS / 1000} s`);
|
|
75
|
+
}
|
|
76
|
+
this.send(child, { jsonrpc: "2.0", method: "notifications/initialized" });
|
|
77
|
+
}
|
|
78
|
+
send(child, message) {
|
|
79
|
+
child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
80
|
+
}
|
|
81
|
+
request(method, params, signal) {
|
|
82
|
+
const child = this.child;
|
|
83
|
+
if (!child)
|
|
84
|
+
return Promise.reject(this.unreachable("is not running"));
|
|
85
|
+
const id = ++this.nextId;
|
|
86
|
+
return new Promise((resolve, reject) => {
|
|
87
|
+
const abort = () => {
|
|
88
|
+
this.pending.delete(id);
|
|
89
|
+
this.send(child, { jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: id } });
|
|
90
|
+
reject(signal.reason);
|
|
91
|
+
};
|
|
92
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
93
|
+
this.pending.set(id, {
|
|
94
|
+
resolve: value => { signal.removeEventListener("abort", abort); resolve(value); },
|
|
95
|
+
reject: error => { signal.removeEventListener("abort", abort); reject(error); },
|
|
96
|
+
});
|
|
97
|
+
this.send(child, { jsonrpc: "2.0", id, method, params });
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
receive(child, line) {
|
|
101
|
+
let message;
|
|
102
|
+
// A wrapper such as SSH may print a banner on stdout before the server speaks.
|
|
103
|
+
try {
|
|
104
|
+
message = JSON.parse(line);
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (message.method !== undefined) {
|
|
110
|
+
// The server may ask for a ping; it gets nothing else from this client.
|
|
111
|
+
if (message.id !== undefined) {
|
|
112
|
+
this.send(child, message.method === "ping"
|
|
113
|
+
? { jsonrpc: "2.0", id: message.id, result: {} }
|
|
114
|
+
: { jsonrpc: "2.0", id: message.id, error: { code: -32601, message: `${message.method} is not supported` } });
|
|
115
|
+
}
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const call = message.id === undefined ? undefined : this.pending.get(message.id);
|
|
119
|
+
if (!call)
|
|
120
|
+
return;
|
|
121
|
+
this.pending.delete(message.id);
|
|
122
|
+
if (message.error)
|
|
123
|
+
call.reject(new BrowseToolError("real_browser_error", `OpenCode Browse refused the request: ${message.error.message ?? "no message"}`));
|
|
124
|
+
else
|
|
125
|
+
call.resolve(message.result);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { NetworkCapture } from "./har.ts";
|
|
2
|
+
import type { BrowserParams } from "./schema.ts";
|
|
3
|
+
import { type BrowserOutput } from "./session.ts";
|
|
4
|
+
export interface RealBrowserPage {
|
|
5
|
+
tabId: string;
|
|
6
|
+
url: string;
|
|
7
|
+
title: string | null;
|
|
8
|
+
/** OpenCode Browse's outline, with a ref on every element that can be acted on. */
|
|
9
|
+
outline: string;
|
|
10
|
+
/** What a model reads to answer about the page: its visible text, what its fields hold, and its controls with their states. */
|
|
11
|
+
text: string;
|
|
12
|
+
image?: {
|
|
13
|
+
data: string;
|
|
14
|
+
mimeType: string;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
export declare class RealBrowserSession {
|
|
18
|
+
private readonly client;
|
|
19
|
+
private readonly release;
|
|
20
|
+
readonly owner: string;
|
|
21
|
+
private readonly group;
|
|
22
|
+
private readonly allowedOrigins?;
|
|
23
|
+
/** The tab this conversation's next call acts on. */
|
|
24
|
+
private tab?;
|
|
25
|
+
/** Whether this conversation opened a tab, so close has a group to close. */
|
|
26
|
+
private opened;
|
|
27
|
+
private released;
|
|
28
|
+
/** The tab whose network traffic har_start is capturing. */
|
|
29
|
+
private recording?;
|
|
30
|
+
/** `group` titles this conversation's tab group in the browser; `allowedOrigins` fences every tab it opens. */
|
|
31
|
+
static open(command: readonly string[], identity: {
|
|
32
|
+
name: string;
|
|
33
|
+
version: string;
|
|
34
|
+
}, owner: string, group: string, allowedOrigins?: string[]): RealBrowserSession;
|
|
35
|
+
private constructor();
|
|
36
|
+
run(p: BrowserParams, signal: AbortSignal, timeoutMs: number): Promise<BrowserOutput>;
|
|
37
|
+
/** Reads a tab for ask, JEV, and browse_ai in one script, so the outline, the text, and the viewport are of the same page. */
|
|
38
|
+
read(tabId: string | undefined, image: boolean, signal: AbortSignal, timeoutMs: number): Promise<RealBrowserPage>;
|
|
39
|
+
/** Runs one script in a tab and returns what it handed back, with the image when it took a screenshot. */
|
|
40
|
+
private script;
|
|
41
|
+
/** Opens a background tab in this conversation's group and selects it. */
|
|
42
|
+
private newTab;
|
|
43
|
+
/** Ends har_start's capture and returns it with the recorded tab's view. */
|
|
44
|
+
harStop(signal: AbortSignal, timeoutMs: number): Promise<{
|
|
45
|
+
capture: NetworkCapture;
|
|
46
|
+
view: Pick<BrowserOutput, "tabId" | "url" | "title">;
|
|
47
|
+
}>;
|
|
48
|
+
/**
|
|
49
|
+
* batch: the steps run in order, one script each, under one deadline. The first failure stops the rest and nothing
|
|
50
|
+
* is rolled back; the result says how many steps completed.
|
|
51
|
+
*/
|
|
52
|
+
private sequence;
|
|
53
|
+
/** Closes every tab this conversation opened. The browser, and the tabs the person lent, stay. */
|
|
54
|
+
close(signal: AbortSignal): Promise<void>;
|
|
55
|
+
private list;
|
|
56
|
+
private output;
|
|
57
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// One conversation's tabs in the user's real browser, driven through OpenCode Browse (see real-browser-client.ts).
|
|
2
|
+
import { RealBrowserClient } from "./real-browser-client.js";
|
|
3
|
+
import { BrowseToolError } from "./session.js";
|
|
4
|
+
/** One client per command for the conversations using it; the last to close ends its process, so a host can exit. */
|
|
5
|
+
const clients = new Map();
|
|
6
|
+
function toTab(tabId) {
|
|
7
|
+
return /^\d+$/.test(tabId) ? Number(tabId) : tabId;
|
|
8
|
+
}
|
|
9
|
+
/** The arguments a script reads from `p`. */
|
|
10
|
+
const ARGUMENTS = ["url", "selector", "value", "values", "key", "script", "fullPage", "durationMs", "loadState", "state", "deltaX", "deltaY", "x", "y", "message"];
|
|
11
|
+
/**
|
|
12
|
+
* `el` takes a snapshot ref (e12) or a selector; a bare XPath gets the prefix Playwright-style locators need. `timeout`
|
|
13
|
+
* ends a wait for an element or a page before the script's own deadline, whose error would not say what was missing.
|
|
14
|
+
*/
|
|
15
|
+
const PRELUDE = String.raw `const el = selector => /^e\d+$/.test(selector) ? ref(selector) : page.locator(/^\(*\/\//.test(selector) ? "xpath=" + selector : selector);
|
|
16
|
+
let data, shot, extra;`;
|
|
17
|
+
/**
|
|
18
|
+
* What a script hands back. OpenCode Browse returns a string as it is and anything else as JSON, and adds lines of its
|
|
19
|
+
* own around either, so the view travels percent-encoded between markers that survive both. A screenshot has to be
|
|
20
|
+
* returned as a value of its own for the result to carry the image, and `extra` is for a value too large to encode:
|
|
21
|
+
* it comes back as part of the JSON.
|
|
22
|
+
*/
|
|
23
|
+
const EPILOGUE = `const view = "@@browse-core:" + encodeURIComponent(JSON.stringify({ data, url: page.url(), title: await page.title().catch(() => null) })) + "@@";
|
|
24
|
+
return shot || extra !== undefined ? { view, shot, extra } : view;`;
|
|
25
|
+
const VIEW = /@@browse-core:([^@]*)@@/;
|
|
26
|
+
/** Each control as the body of an `execute` script, on OpenCode Browse's Playwright-style `page`. */
|
|
27
|
+
const BODIES = {
|
|
28
|
+
start: "if (p.url) await page.goto(p.url, { timeout });",
|
|
29
|
+
open: "await page.goto(p.url, { timeout });",
|
|
30
|
+
back: "await page.goBack();",
|
|
31
|
+
forward: "await page.goForward();",
|
|
32
|
+
reload: "await page.reload();",
|
|
33
|
+
// The default of 80 lines hides most of a long page.
|
|
34
|
+
snapshot: "data = String(await snapshot({ maxItems: 200 }));",
|
|
35
|
+
click: "await el(p.selector).click({ timeout });",
|
|
36
|
+
fill: "await el(p.selector).fill(p.value, { timeout });",
|
|
37
|
+
select: "data = { selected: await el(p.selector).selectOption(p.values, { timeout }) };",
|
|
38
|
+
press: "await page.keyboard.press(p.key);",
|
|
39
|
+
scroll: "await page.mouse.move(p.x ?? 640, p.y ?? 400); await page.mouse.wheel(p.deltaX ?? 0, p.deltaY ?? 0);",
|
|
40
|
+
wait: `if (p.durationMs !== undefined) await page.waitForTimeout(p.durationMs);
|
|
41
|
+
else if (p.selector !== undefined) await el(p.selector).waitFor({ state: p.state ?? "visible", timeout });
|
|
42
|
+
else await page.waitForLoadState(p.loadState, { timeout });`,
|
|
43
|
+
evaluate: "data = (await page.evaluate(p.script)) ?? null;",
|
|
44
|
+
screenshot: "shot = await page.screenshot({ fullPage: p.fullPage === true });",
|
|
45
|
+
handoff: "data = { handoff: (await handoff(p.message)) ?? null };",
|
|
46
|
+
har_start: 'await browse.network({ action: "start" });',
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* What a page shows and what its form fields hold, read in the page. The outline leaves out what is typed into a
|
|
50
|
+
* field and innerText has no field values at all, so they are listed by label here. Passwords, one-time codes, and
|
|
51
|
+
* card fields are never read; checkboxes and radios are in the outline with their state.
|
|
52
|
+
*/
|
|
53
|
+
const PAGE_TEXT = `(() => {
|
|
54
|
+
const skipped = { password: 1, hidden: 1, file: 1, checkbox: 1, radio: 1, submit: 1, button: 1, reset: 1, image: 1 };
|
|
55
|
+
const values = [];
|
|
56
|
+
for (const el of document.querySelectorAll("input, textarea, select")) {
|
|
57
|
+
if (values.length >= 100) break;
|
|
58
|
+
if (skipped[(el.getAttribute("type") || "").toLowerCase()] || /password|one-time-code|cc-/.test(el.getAttribute("autocomplete") || "")) continue;
|
|
59
|
+
const value = el.tagName === "SELECT" ? Array.from(el.selectedOptions, option => option.label).join(", ") : el.value;
|
|
60
|
+
const label = ((el.labels && el.labels[0] && el.labels[0].innerText) || el.getAttribute("aria-label") || el.getAttribute("placeholder") || el.name || el.id || "").trim().split("\\n")[0];
|
|
61
|
+
if (value && label) values.push(label.slice(0, 80) + ": " + String(value).replace(/\\s+/g, " ").slice(0, 500));
|
|
62
|
+
}
|
|
63
|
+
return { text: document.body ? document.body.innerText : "", values: values.join("\\n") };
|
|
64
|
+
})()`;
|
|
65
|
+
/** A page as ask, JEV, and browse_ai read it: the outline with its refs, the text and field values, and the viewport when asked for. */
|
|
66
|
+
const READ = `data = { outline: String(await snapshot({ maxItems: 200 })), ...await page.evaluate(${JSON.stringify(PAGE_TEXT)}) };
|
|
67
|
+
if (p.image) shot = await page.screenshot({ fullPage: false });`;
|
|
68
|
+
export class RealBrowserSession {
|
|
69
|
+
client;
|
|
70
|
+
release;
|
|
71
|
+
owner;
|
|
72
|
+
group;
|
|
73
|
+
allowedOrigins;
|
|
74
|
+
/** The tab this conversation's next call acts on. */
|
|
75
|
+
tab;
|
|
76
|
+
/** Whether this conversation opened a tab, so close has a group to close. */
|
|
77
|
+
opened = false;
|
|
78
|
+
released = false;
|
|
79
|
+
/** The tab whose network traffic har_start is capturing. */
|
|
80
|
+
recording;
|
|
81
|
+
/** `group` titles this conversation's tab group in the browser; `allowedOrigins` fences every tab it opens. */
|
|
82
|
+
static open(command, identity, owner, group, allowedOrigins) {
|
|
83
|
+
const key = JSON.stringify(command);
|
|
84
|
+
let shared = clients.get(key);
|
|
85
|
+
if (!shared)
|
|
86
|
+
clients.set(key, shared = { client: new RealBrowserClient(command, identity), users: 0 });
|
|
87
|
+
const { client } = shared;
|
|
88
|
+
shared.users++;
|
|
89
|
+
return new RealBrowserSession(client, () => {
|
|
90
|
+
if (--shared.users)
|
|
91
|
+
return;
|
|
92
|
+
clients.delete(key);
|
|
93
|
+
client.close();
|
|
94
|
+
}, owner, group, allowedOrigins);
|
|
95
|
+
}
|
|
96
|
+
constructor(client, release, owner, group, allowedOrigins) {
|
|
97
|
+
this.client = client;
|
|
98
|
+
this.release = release;
|
|
99
|
+
this.owner = owner;
|
|
100
|
+
this.group = group;
|
|
101
|
+
this.allowedOrigins = allowedOrigins;
|
|
102
|
+
}
|
|
103
|
+
async run(p, signal, timeoutMs) {
|
|
104
|
+
if (p.action === "status")
|
|
105
|
+
return this.output(p.action, { data: { state: this.tab === undefined ? "no_tab" : "running", realBrowser: true, group: this.group } });
|
|
106
|
+
if (p.action === "close") {
|
|
107
|
+
await this.close(signal);
|
|
108
|
+
return { action: p.action, sessionId: null, backend: "local", origin: "connected", data: { closed: true, browserClosed: false } };
|
|
109
|
+
}
|
|
110
|
+
if (p.action === "tabs") {
|
|
111
|
+
const tabs = await this.list(signal);
|
|
112
|
+
return this.output(p.action, { data: { tabs: tabs.map(tab => ({ tabId: String(tab.tab), url: tab.url, title: tab.title, selected: tab.tab === this.tab })) } });
|
|
113
|
+
}
|
|
114
|
+
if (p.action === "tab_select" || p.action === "tab_close") {
|
|
115
|
+
const tabs = await this.list(signal);
|
|
116
|
+
const found = tabs.find(tab => String(tab.tab) === p.tabId);
|
|
117
|
+
if (!found)
|
|
118
|
+
throw new BrowseToolError("tab_missing", "This conversation has no such tab in the real browser. Call tabs to list its tabs.");
|
|
119
|
+
if (p.action === "tab_select") {
|
|
120
|
+
this.tab = found.tab;
|
|
121
|
+
return this.output(p.action, { url: found.url, title: found.title });
|
|
122
|
+
}
|
|
123
|
+
await this.client.call("tabs", { action: "close", tab: found.tab }, signal);
|
|
124
|
+
if (this.tab === found.tab)
|
|
125
|
+
this.tab = tabs.find(tab => tab.tab !== found.tab)?.tab;
|
|
126
|
+
return this.output(p.action, { data: { closedTabId: String(found.tab), selectedTabId: this.tab === undefined ? null : String(this.tab) } });
|
|
127
|
+
}
|
|
128
|
+
if (p.action === "tab_new" || ((p.action === "start" || p.action === "open") && this.tab === undefined)) {
|
|
129
|
+
const opened = await this.newTab(p.url, signal);
|
|
130
|
+
return this.output(p.action, { url: opened.url, title: opened.title });
|
|
131
|
+
}
|
|
132
|
+
if (p.action === "har_start") {
|
|
133
|
+
if (this.recording !== undefined)
|
|
134
|
+
throw new BrowseToolError("har_active", "A recording is already running. Call har_stop to write it first.");
|
|
135
|
+
// The capture belongs to a tab, so a recording that starts before any page has a blank one to start in.
|
|
136
|
+
if (this.tab === undefined)
|
|
137
|
+
await this.newTab(undefined, signal);
|
|
138
|
+
}
|
|
139
|
+
if (p.action === "batch")
|
|
140
|
+
return this.sequence(p, signal, timeoutMs);
|
|
141
|
+
const body = p.target === undefined ? BODIES[p.action] : undefined;
|
|
142
|
+
if (body === undefined) {
|
|
143
|
+
throw new BrowseToolError("unsupported_backend", `${p.target === undefined ? p.action : "target"} is not available in the user's real browser. Close it and start with backend "browserbase", or with headless true for a browser of your own.`);
|
|
144
|
+
}
|
|
145
|
+
const args = Object.fromEntries(ARGUMENTS.flatMap(name => p[name] === undefined ? [] : [[name, p[name]]]));
|
|
146
|
+
const { tab, view, image } = await this.script(p.action, p.tabId, args, body, signal, timeoutMs);
|
|
147
|
+
let data = view.data;
|
|
148
|
+
if (p.action === "har_start") {
|
|
149
|
+
this.recording = tab;
|
|
150
|
+
data = { recording: true, note: "Recording this tab only; a tab opened later is not recorded." };
|
|
151
|
+
}
|
|
152
|
+
if (p.action === "snapshot") {
|
|
153
|
+
const tree = String(data), limit = p.maxChars ?? 20_000;
|
|
154
|
+
data = { tree: tree.slice(0, limit), truncated: tree.length > limit };
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
...this.output(p.action, { url: view.url, title: view.title, ...(data === undefined ? {} : { data }) }, tab),
|
|
158
|
+
...(image ? { image: new Uint8Array(Buffer.from(image.data, "base64")) } : {}),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
/** Reads a tab for ask, JEV, and browse_ai in one script, so the outline, the text, and the viewport are of the same page. */
|
|
162
|
+
async read(tabId, image, signal, timeoutMs) {
|
|
163
|
+
const { tab, view, image: shot } = await this.script("read", tabId, { image }, READ, signal, timeoutMs);
|
|
164
|
+
const { outline, text, values } = view.data;
|
|
165
|
+
const controls = outline.replace(/ \[ref=e\d+\]/g, "").replace(/\[ref=e\d+ /g, "[");
|
|
166
|
+
const readable = `${text}${values ? `\n\nField values:\n${values}` : ""}\n\nControls:\n${controls}`;
|
|
167
|
+
return { tabId: String(tab), url: view.url, title: view.title, outline, text: readable, ...(shot ? { image: shot } : {}) };
|
|
168
|
+
}
|
|
169
|
+
/** Runs one script in a tab and returns what it handed back, with the image when it took a screenshot. */
|
|
170
|
+
async script(action, tabId, args, body, signal, timeoutMs) {
|
|
171
|
+
const tab = tabId === undefined ? this.tab : typeof tabId === "string" ? toTab(tabId) : tabId;
|
|
172
|
+
if (tab === undefined)
|
|
173
|
+
throw new BrowseToolError("tab_missing", "No tab is open in the real browser. Call open with a url.");
|
|
174
|
+
const code = [`const p = ${JSON.stringify(args)}, timeout = ${Math.max(500, timeoutMs - 2000)};`, PRELUDE, body, EPILOGUE].join("\n");
|
|
175
|
+
const result = await this.client.call("execute", { tab, code, timeoutMs: Math.max(1500, timeoutMs - 1000) }, signal).catch(error => {
|
|
176
|
+
// A failed script's message starts with the tab it ran in, which the caller already knows, and ends with where in the script it threw.
|
|
177
|
+
if (error instanceof BrowseToolError && error.code === "real_browser_error")
|
|
178
|
+
throw new BrowseToolError(error.code, error.message.replace(/^tab: \S+\s+/, "").replace(/\n\s+at .*$/s, ""));
|
|
179
|
+
throw error;
|
|
180
|
+
});
|
|
181
|
+
const encoded = VIEW.exec(result.text)?.[1];
|
|
182
|
+
if (encoded === undefined)
|
|
183
|
+
throw new BrowseToolError("real_browser_error", `The real browser returned no result for ${action}: ${result.text.slice(0, 300)}`);
|
|
184
|
+
this.tab ??= tab;
|
|
185
|
+
return { tab, view: JSON.parse(decodeURIComponent(encoded)), image: result.images[0], text: result.text };
|
|
186
|
+
}
|
|
187
|
+
/** Opens a background tab in this conversation's group and selects it. */
|
|
188
|
+
async newTab(url, signal) {
|
|
189
|
+
const created = await this.client.call("tabs", {
|
|
190
|
+
action: "new", group: this.group, ...(url ? { url } : {}), ...(this.allowedOrigins ? { allowedOrigins: this.allowedOrigins } : {}),
|
|
191
|
+
}, signal);
|
|
192
|
+
const opened = JSON.parse(created.text);
|
|
193
|
+
this.tab = opened.tab;
|
|
194
|
+
this.opened = true;
|
|
195
|
+
return opened;
|
|
196
|
+
}
|
|
197
|
+
/** Ends har_start's capture and returns it with the recorded tab's view. */
|
|
198
|
+
async harStop(signal, timeoutMs) {
|
|
199
|
+
const recording = this.recording;
|
|
200
|
+
if (recording === undefined)
|
|
201
|
+
throw new BrowseToolError("har_not_started", "No recording is running in this browser. Call har_start, perform the actions, then har_stop.");
|
|
202
|
+
const { view, text } = await this.script("har_stop", recording, {}, 'extra = await browse.network({ action: "stop" });', signal, timeoutMs);
|
|
203
|
+
this.recording = undefined;
|
|
204
|
+
// The capture is the JSON between OpenCode Browse's first line (the tab) and its closing notes.
|
|
205
|
+
const start = text.indexOf("\n\n") + 2, end = text.indexOf("\n\n", start);
|
|
206
|
+
let capture;
|
|
207
|
+
try {
|
|
208
|
+
capture = JSON.parse(text.slice(start, end < 0 ? undefined : end)).extra;
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
throw new BrowseToolError("har_failed", "The recording stopped, but the real browser's reply could not be read, so no HAR was written.");
|
|
212
|
+
}
|
|
213
|
+
return { capture, view: { tabId: String(recording), url: view.url, title: view.title } };
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* batch: the steps run in order, one script each, under one deadline. The first failure stops the rest and nothing
|
|
217
|
+
* is rolled back; the result says how many steps completed.
|
|
218
|
+
*/
|
|
219
|
+
async sequence(p, signal, timeoutMs) {
|
|
220
|
+
// SAFETY: a step is a direct control's arguments, and every direct control is a BrowserParams.
|
|
221
|
+
const steps = p.steps.map(step => ({ ...step, tabId: p.tabId }));
|
|
222
|
+
const began = Date.now();
|
|
223
|
+
const results = [];
|
|
224
|
+
const progress = { total: steps.length, completed: 0, outcomeUnknown: false };
|
|
225
|
+
for (const step of steps) {
|
|
226
|
+
try {
|
|
227
|
+
const { action, url, title, data } = await this.run(step, signal, Math.max(1_000, timeoutMs - (Date.now() - began)));
|
|
228
|
+
results.push({ action, url, title, ...(data === undefined ? {} : { data }) });
|
|
229
|
+
progress.completed = results.length;
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
// A deadline or cancellation leaves the step's outcome unknown, which the caller reports.
|
|
233
|
+
if (signal.aborted || !(error instanceof BrowseToolError))
|
|
234
|
+
throw error;
|
|
235
|
+
progress.failedIndex = results.length;
|
|
236
|
+
// A script that failed did not act; a server that went away may have.
|
|
237
|
+
progress.outcomeUnknown = error.code === "real_browser_unreachable";
|
|
238
|
+
progress.error = { code: error.code, message: error.message.slice(0, 4000) };
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const last = results.at(-1);
|
|
243
|
+
return {
|
|
244
|
+
...this.output(p.action, last ? { url: last.url, title: last.title } : {}),
|
|
245
|
+
// Progress comes before the results, so it survives a host that truncates a long result.
|
|
246
|
+
batch: progress, data: { results },
|
|
247
|
+
...(progress.error ? {
|
|
248
|
+
isError: true, code: progress.error.code,
|
|
249
|
+
note: "The batch stopped at the failed step: later steps did not run, and earlier ones were not rolled back. Inspect the page before repeating anything.",
|
|
250
|
+
} : {}),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/** Closes every tab this conversation opened. The browser, and the tabs the person lent, stay. */
|
|
254
|
+
async close(signal) {
|
|
255
|
+
if (this.released)
|
|
256
|
+
return;
|
|
257
|
+
this.released = true;
|
|
258
|
+
try {
|
|
259
|
+
if (this.opened)
|
|
260
|
+
await this.client.call("tabs", { action: "close", group: this.group }, signal);
|
|
261
|
+
}
|
|
262
|
+
finally {
|
|
263
|
+
this.tab = undefined;
|
|
264
|
+
this.recording = undefined;
|
|
265
|
+
this.release();
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
async list(signal) {
|
|
269
|
+
return JSON.parse((await this.client.call("tabs", { action: "list", group: this.group }, signal)).text).tabs;
|
|
270
|
+
}
|
|
271
|
+
output(action, view, tab = this.tab) {
|
|
272
|
+
return { action, sessionId: null, backend: "local", origin: "connected", ...(tab === undefined ? {} : { tabId: String(tab) }), ...view };
|
|
273
|
+
}
|
|
274
|
+
}
|
package/dist/schema.d.ts
CHANGED
|
@@ -118,6 +118,7 @@ export declare const browserParameters: z.ZodObject<{
|
|
|
118
118
|
years: "years";
|
|
119
119
|
}>>;
|
|
120
120
|
}, z.core.$strict>>>;
|
|
121
|
+
message: z.ZodOptional<z.ZodString>;
|
|
121
122
|
path: z.ZodOptional<z.ZodString>;
|
|
122
123
|
timeoutMs: z.ZodOptional<z.ZodNumber>;
|
|
123
124
|
action: z.ZodEnum<{
|
|
@@ -131,6 +132,7 @@ export declare const browserParameters: z.ZodObject<{
|
|
|
131
132
|
evaluate: "evaluate";
|
|
132
133
|
fill: "fill";
|
|
133
134
|
forward: "forward";
|
|
135
|
+
handoff: "handoff";
|
|
134
136
|
har_start: "har_start";
|
|
135
137
|
har_stop: "har_stop";
|
|
136
138
|
live_view: "live_view";
|
|
@@ -230,6 +232,7 @@ export declare const browserBatchParameters: z.ZodObject<{
|
|
|
230
232
|
years: "years";
|
|
231
233
|
}>>;
|
|
232
234
|
}, z.core.$strict>>>;
|
|
235
|
+
message: z.ZodOptional<z.ZodString>;
|
|
233
236
|
path: z.ZodOptional<z.ZodString>;
|
|
234
237
|
timeoutMs: z.ZodOptional<z.ZodNumber>;
|
|
235
238
|
action: z.ZodEnum<{
|
|
@@ -244,6 +247,7 @@ export declare const browserBatchParameters: z.ZodObject<{
|
|
|
244
247
|
evaluate: "evaluate";
|
|
245
248
|
fill: "fill";
|
|
246
249
|
forward: "forward";
|
|
250
|
+
handoff: "handoff";
|
|
247
251
|
har_start: "har_start";
|
|
248
252
|
har_stop: "har_stop";
|
|
249
253
|
live_view: "live_view";
|
package/dist/schema.js
CHANGED
|
@@ -44,7 +44,7 @@ const ACTIONS = [
|
|
|
44
44
|
"start", "status", "close", "open", "back", "forward", "reload", "snapshot", "ask",
|
|
45
45
|
"click", "fill", "select", "press", "scroll", "wait", "screenshot", "evaluate",
|
|
46
46
|
"tabs", "tab_new", "tab_select", "tab_close", "live_view", "context_create", "cookie_profiles", "cookie_import",
|
|
47
|
-
"har_start", "har_stop",
|
|
47
|
+
"har_start", "har_stop", "handoff",
|
|
48
48
|
];
|
|
49
49
|
/** Every action's arguments. A batch step reuses the direct controls' definitions from here instead of redefining them. */
|
|
50
50
|
const browserFields = {
|
|
@@ -87,6 +87,7 @@ const browserFields = {
|
|
|
87
87
|
fullPage: z.boolean().optional().describe("For screenshot; defaults to viewport only."),
|
|
88
88
|
maxChars: z.number().int().min(1000).max(50_000).optional().describe("Snapshot text limit; default 20000."),
|
|
89
89
|
fields: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/), askField).optional().describe("Required for ask: 1 to 20 named questions about the selected page. text, number, date, datetime, and duration read a value (null when the page does not say); bool answers yes/no; choice picks one of options."),
|
|
90
|
+
message: z.string().trim().min(1).max(500).optional().describe("Required for handoff: what only the person can do in the selected tab, e.g. sign in or approve the 2FA prompt. The call returns once they click Continue. Only in the user's real browser."),
|
|
90
91
|
path: z.string().regex(/^\/.*\.har$/, "path must be an absolute path ending in .har").optional().describe("Only for har_stop: absolute file path for the HAR, e.g. /abs/scratch/capture.har. Default: a new file in the system temp directory."),
|
|
91
92
|
timeoutMs: z.number().int().min(1).max(120_000).optional().describe("Operation deadline; default 30000 (a fixed wait gets durationMs + 5000). Page waits and navigation time out up to 2s earlier. On the deadline the browser is kept if it still responds."),
|
|
92
93
|
};
|
|
@@ -161,7 +162,7 @@ const singleCall = z.object({ action: z.enum(ACTIONS), ...browserFields }).stric
|
|
|
161
162
|
function checkCall(p, ctx) {
|
|
162
163
|
const required = {
|
|
163
164
|
...DIRECT_REQUIRED, ask: ["fields"],
|
|
164
|
-
tab_select: ["tabId"], tab_close: ["tabId"], context_create: ["name"], cookie_import: ["domains"],
|
|
165
|
+
tab_select: ["tabId"], tab_close: ["tabId"], context_create: ["name"], cookie_import: ["domains"], handoff: ["message"],
|
|
165
166
|
};
|
|
166
167
|
for (const field of required[p.action] ?? []) {
|
|
167
168
|
if (p[field] === undefined)
|
|
@@ -169,6 +170,8 @@ function checkCall(p, ctx) {
|
|
|
169
170
|
}
|
|
170
171
|
if (p.path !== undefined && p.action !== "har_stop")
|
|
171
172
|
ctx.addIssue({ code: "custom", path: ["path"], message: "path is only supported for har_stop" });
|
|
173
|
+
if (p.message !== undefined && p.action !== "handoff")
|
|
174
|
+
ctx.addIssue({ code: "custom", path: ["message"], message: "message is only supported for handoff" });
|
|
172
175
|
if (p.fields && (p.action !== "ask" || Object.keys(p.fields).length < 1 || Object.keys(p.fields).length > 20)) {
|
|
173
176
|
ctx.addIssue({ code: "custom", path: ["fields"], message: "fields is only supported for ask, with 1 to 20 entries" });
|
|
174
177
|
}
|
package/dist/session.d.ts
CHANGED
|
@@ -47,6 +47,14 @@ export interface BrowseConfig {
|
|
|
47
47
|
* never reach results), and the URL Stagehand's in-browser extension uses when the browser runs on another machine.
|
|
48
48
|
*/
|
|
49
49
|
remoteBrowsers?: Record<string, RemoteBrowser>;
|
|
50
|
+
/**
|
|
51
|
+
* The user's own browser, through OpenCode Browse: `command` is the argv that runs `browse mcp`, on this machine or
|
|
52
|
+
* over SSH on the machine with the browser. When set, a local start that names no cdpUrl, endpoint, or headless works
|
|
53
|
+
* in that browser instead of launching one.
|
|
54
|
+
*/
|
|
55
|
+
realBrowser?: {
|
|
56
|
+
command: string[];
|
|
57
|
+
};
|
|
50
58
|
}
|
|
51
59
|
/** A browser to attach to. extensionCdpUrl is the browser-level DevTools URL the browser itself reaches without headers. */
|
|
52
60
|
export interface RemoteBrowser {
|
|
@@ -176,6 +184,8 @@ export declare class BrowseSession {
|
|
|
176
184
|
private readonly cookies;
|
|
177
185
|
/** This conversation's calls run in the broker that owns its shared browser, until close. */
|
|
178
186
|
private delegate?;
|
|
187
|
+
/** This conversation's tabs in the user's real browser, until close. */
|
|
188
|
+
private real?;
|
|
179
189
|
/** Stagehand's runtime extension per Browserbase project, uploaded once and reused across conversations and processes. */
|
|
180
190
|
private readonly extensions;
|
|
181
191
|
/** Default inference for every Stagehand instance; without it, unconfigured AI calls use Model Gateway's automatic selection. */
|
|
@@ -207,6 +217,21 @@ export declare class BrowseSession {
|
|
|
207
217
|
private dispatch;
|
|
208
218
|
/** The shared browser a call would open, as the broker keys it: an attached browser or a persistent profile; else none. */
|
|
209
219
|
private sharedKey;
|
|
220
|
+
/** The real-browser session a call would open: a local start that asks for no browser of its own, in a profile that configures one. */
|
|
221
|
+
private realBrowser;
|
|
222
|
+
private inRealBrowser;
|
|
223
|
+
/**
|
|
224
|
+
* ask and JEV in the real browser. They read OpenCode Browse's outline and the page's visible text where a
|
|
225
|
+
* Stagehand browser reads its snapshot tree; the classifiers and their settings are the same.
|
|
226
|
+
*/
|
|
227
|
+
private classifyInRealBrowser;
|
|
228
|
+
/**
|
|
229
|
+
* browse_ai in the real browser: act, observe, and extract on the page's outline and text, with the host's own
|
|
230
|
+
* inference. act performs the one action the model chose; a page that offers none is a failed act, not an error.
|
|
231
|
+
*/
|
|
232
|
+
private aiInRealBrowser;
|
|
233
|
+
/** Closes this conversation's tabs in the real browser; the browser itself is the user's and stays. */
|
|
234
|
+
private closeReal;
|
|
210
235
|
/** Runs a call in the broker; close ends the conversation there, and a lost broker is reopened by the next call. */
|
|
211
236
|
private forward;
|
|
212
237
|
private dropDelegate;
|
|
@@ -309,6 +334,12 @@ export declare class BrowseSession {
|
|
|
309
334
|
* fresh snapshot; no xpath means it declined to act.
|
|
310
335
|
*/
|
|
311
336
|
private locate;
|
|
337
|
+
/** Jev's pick among the candidates; a failed request says whether retrying can help. */
|
|
338
|
+
private pick;
|
|
339
|
+
/** What a call reports when Jev declined to act: its best candidates, each with a selector the caller can use as is. */
|
|
340
|
+
private declined;
|
|
341
|
+
/** ask's models for a profile: Workers AI for the values Clairic reads, and the decision classifier for bool and choice. */
|
|
342
|
+
private askModels;
|
|
312
343
|
private ai;
|
|
313
344
|
}
|
|
314
345
|
export {};
|
package/dist/session.js
CHANGED
|
@@ -7,14 +7,16 @@ import { setTimeout as delay } from "node:timers/promises";
|
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import { askNeeds, askPage, DECIDE_TEXT } from "./ask.js";
|
|
9
9
|
import { guardEndpoint } from "./cdp-guard.js";
|
|
10
|
-
import { HarRecorder } from "./har.js";
|
|
10
|
+
import { HarRecorder, writeCaptureHar } from "./har.js";
|
|
11
11
|
import { nameChromeProfile, refreshExtensionWorkers } from "./chrome-profile.js";
|
|
12
12
|
import { BrokerConnection } from "./broker-client.js";
|
|
13
|
+
import { RealBrowserSession } from "./real-browser-session.js";
|
|
14
|
+
import { extractPage, observePage } from "./real-browser-ai.js";
|
|
13
15
|
import { extensionCacheKey, extensionCachePath, provisionExtension } from "./extension-cache.js";
|
|
14
16
|
import { randomUUID } from "node:crypto";
|
|
15
17
|
import { cancelPageBatch, pageOperation, readOperation, tabsOperation, viewOperation } from "./page-operations.js";
|
|
16
18
|
import { CookieSourceError, localCookieProvider, normalizeCookieDomains } from "./browser-cookies.js";
|
|
17
|
-
import { fitsAction, JEV_MIN_CONFIDENCE, jevChooser, pickTarget, treeCandidates } from "./jev.js";
|
|
19
|
+
import { fitsAction, JEV_MIN_CONFIDENCE, jevChooser, outlineCandidates, pickTarget, treeCandidates } from "./jev.js";
|
|
18
20
|
import { CLEF, classifierName, ClassifierRefusal, classifierSpec, takesImages, VERCEL_JEV, vercelClassifier, WORKERS_AI_JEV, workersAiClassifier } from "./classifier.js";
|
|
19
21
|
/** Whether `domain` is `parent` or one of its subdomains. */
|
|
20
22
|
function within(domain, parent) {
|
|
@@ -379,6 +381,9 @@ function operationTimeout(params, ai) {
|
|
|
379
381
|
return params.timeoutMs;
|
|
380
382
|
if (ai)
|
|
381
383
|
return 120_000;
|
|
384
|
+
// A person signing in or approving a prompt takes longer than any page action.
|
|
385
|
+
if (params.action === "handoff")
|
|
386
|
+
return 600_000;
|
|
382
387
|
const wait = "durationMs" in params ? params.durationMs : undefined;
|
|
383
388
|
return wait ? Math.max(30_000, wait + 5_000) : 30_000;
|
|
384
389
|
}
|
|
@@ -423,6 +428,8 @@ export class BrowseSession {
|
|
|
423
428
|
cookies;
|
|
424
429
|
/** This conversation's calls run in the broker that owns its shared browser, until close. */
|
|
425
430
|
delegate;
|
|
431
|
+
/** This conversation's tabs in the user's real browser, until close. */
|
|
432
|
+
real;
|
|
426
433
|
/** Stagehand's runtime extension per Browserbase project, uploaded once and reused across conversations and processes. */
|
|
427
434
|
extensions = new Map();
|
|
428
435
|
/** Default inference for every Stagehand instance; without it, unconfigured AI calls use Model Gateway's automatic selection. */
|
|
@@ -474,6 +481,8 @@ export class BrowseSession {
|
|
|
474
481
|
await this.closeOwned();
|
|
475
482
|
if (this.delegate && this.delegate.owner !== this.owner(scope))
|
|
476
483
|
await this.dropDelegate();
|
|
484
|
+
if (this.real && this.real.owner !== this.owner(scope))
|
|
485
|
+
await this.closeReal();
|
|
477
486
|
controller.signal.throwIfAborted();
|
|
478
487
|
this.batchSent = false;
|
|
479
488
|
return await abortable(this.dispatch(params, scope, isAi), controller.signal);
|
|
@@ -485,7 +494,8 @@ export class BrowseSession {
|
|
|
485
494
|
throw error;
|
|
486
495
|
const timedOut = error instanceof BrowseToolError && error.code === "timeout";
|
|
487
496
|
// The broker keeps or releases a shared browser by its own deadline; only the outcome here is unknown.
|
|
488
|
-
|
|
497
|
+
// So does OpenCode Browse with the real browser's tabs.
|
|
498
|
+
if (this.delegate || this.real)
|
|
489
499
|
throw new BrowseToolError(timedOut ? "timeout" : "cancelled", `${timedOut ? "Operation timed out" : "Operation cancelled"}; the action may have completed. Take a snapshot before retrying.`);
|
|
490
500
|
await this.stopBatch?.();
|
|
491
501
|
const kept = await this.keepIfResponsive(params.tabId);
|
|
@@ -522,7 +532,7 @@ export class BrowseSession {
|
|
|
522
532
|
this.generation++;
|
|
523
533
|
this.active?.abort(abortError("The conversation ended; browser cleanup requested."));
|
|
524
534
|
// Begin releasing immediately, in case the host cuts shutdown handlers short.
|
|
525
|
-
await Promise.all([this.closeOwned(), this.dropDelegate()]);
|
|
535
|
+
await Promise.all([this.closeOwned(), this.dropDelegate(), this.closeReal()]);
|
|
526
536
|
}
|
|
527
537
|
/** Which credentials resolve for this profile. Starts no browser and leaves the session alone. */
|
|
528
538
|
async readiness(context, signal) {
|
|
@@ -565,6 +575,20 @@ export class BrowseSession {
|
|
|
565
575
|
}
|
|
566
576
|
/** Runs one operation; a dropped connection is repaired and the operation repeated only when that cannot double an action. */
|
|
567
577
|
async dispatch(params, context, ai) {
|
|
578
|
+
// SAFETY: only browse actions open a browser, and browse_ai calls were excluded.
|
|
579
|
+
if (!this.real && !this.delegate && !this.session && !ai && opensBrowser(params))
|
|
580
|
+
this.real = await this.realBrowser(params, context);
|
|
581
|
+
if (this.real) {
|
|
582
|
+
try {
|
|
583
|
+
return await this.inRealBrowser(this.real, params, context, ai);
|
|
584
|
+
}
|
|
585
|
+
catch (error) {
|
|
586
|
+
// OpenCode Browse is gone, and this conversation's tabs with it: the next start may choose another browser.
|
|
587
|
+
if (error instanceof BrowseToolError && error.code === "real_browser_unreachable")
|
|
588
|
+
await this.closeReal();
|
|
589
|
+
throw error;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
568
592
|
if (!this.delegate && !this.session && this.profileBroker && !ai && opensBrowser(params)) {
|
|
569
593
|
// SAFETY: only browse actions open a browser, and browse_ai calls were excluded above.
|
|
570
594
|
const key = await this.sharedKey(params, context);
|
|
@@ -611,6 +635,143 @@ export class BrowseSession {
|
|
|
611
635
|
}
|
|
612
636
|
return config.localUserDataDir ? `launch:${config.localUserDataDir}` : undefined;
|
|
613
637
|
}
|
|
638
|
+
/** The real-browser session a call would open: a local start that asks for no browser of its own, in a profile that configures one. */
|
|
639
|
+
async realBrowser(p, context) {
|
|
640
|
+
if ((p.backend ?? this.defaultBackend) !== "local" || p.cdpUrl || p.endpoint || p.headless !== undefined)
|
|
641
|
+
return undefined;
|
|
642
|
+
// The real browser has the person's logins already; an import is for a browser this tool launches.
|
|
643
|
+
if (p.action === "cookie_import")
|
|
644
|
+
return undefined;
|
|
645
|
+
const config = await this.config(context, "local");
|
|
646
|
+
if (!config.realBrowser?.command.length)
|
|
647
|
+
return undefined;
|
|
648
|
+
const policy = domainLists(config, p);
|
|
649
|
+
// OpenCode Browse fences where a tab may navigate; it has nothing that refuses named domains.
|
|
650
|
+
if (policy?.blockedDomains?.length) {
|
|
651
|
+
throw new BrowseToolError("unsupported_backend", "Blocked domains cannot be enforced in the user's real browser. Start with headless true or backend \"browserbase\" to keep them.");
|
|
652
|
+
}
|
|
653
|
+
return RealBrowserSession.open(config.realBrowser.command, { name: this.identity.integration, version: "1" }, this.owner(context), `${this.identity.name} ${context.sessionId.slice(0, 6)}`, policy?.allowedDomains?.flatMap(domain => [domain, `*.${domain}`]));
|
|
654
|
+
}
|
|
655
|
+
async inRealBrowser(real, params, context, ai) {
|
|
656
|
+
// SAFETY: `ai` marks a browse_ai call, whose arguments are AIParams; every other call's are BrowserParams.
|
|
657
|
+
if (ai)
|
|
658
|
+
return this.aiInRealBrowser(real, params, context);
|
|
659
|
+
const p = params;
|
|
660
|
+
if (p.backend === "browserbase" || p.cdpUrl || p.endpoint || p.headless !== undefined) {
|
|
661
|
+
throw new BrowseToolError("browser_change", "Close the current browser before changing its backend, endpoint, or launch settings.");
|
|
662
|
+
}
|
|
663
|
+
// Listing the cookie sources needs no browser.
|
|
664
|
+
if (p.action === "cookie_profiles")
|
|
665
|
+
return this.browse(p, context);
|
|
666
|
+
if (p.action === "ask" || p.target !== undefined)
|
|
667
|
+
return this.classifyInRealBrowser(real, p, context);
|
|
668
|
+
if (p.action === "har_stop") {
|
|
669
|
+
const { capture, view } = await real.harStop(context.signal, operationTimeout(p, false));
|
|
670
|
+
const path = p.path ?? join(tmpdir(), `${this.identity.integration}-har`, `${new Date().toISOString().replace(/[:.]/g, "-")}.har`);
|
|
671
|
+
const summary = await writeCaptureHar(capture, path, this.identity.integration);
|
|
672
|
+
return {
|
|
673
|
+
action: p.action, sessionId: null, backend: "local", origin: "connected", ...view,
|
|
674
|
+
data: { ...summary, note: "The real browser's capture redacts credentials, leaves out the bodies of pages, scripts, styles, and images, and holds at most 1000 requests. Read the HAR with scripts; for a complete recording, record a browser started with headless true or backend \"browserbase\"." },
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
// Steps run one at a time from here on, so a batch that fails later may have partly run.
|
|
678
|
+
if (p.action === "batch")
|
|
679
|
+
this.batchSent = true;
|
|
680
|
+
const output = await real.run(p, context.signal, operationTimeout(p, false));
|
|
681
|
+
if (p.action === "close")
|
|
682
|
+
this.real = undefined;
|
|
683
|
+
return output;
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* ask and JEV in the real browser. They read OpenCode Browse's outline and the page's visible text where a
|
|
687
|
+
* Stagehand browser reads its snapshot tree; the classifiers and their settings are the same.
|
|
688
|
+
*/
|
|
689
|
+
async classifyInRealBrowser(real, p, context) {
|
|
690
|
+
const purpose = p.action === "ask" ? "ask" : "jev";
|
|
691
|
+
const config = await this.config({ ...context, purpose }, "local");
|
|
692
|
+
const jev = purpose === "jev" ? this.classifier("jev", config) : undefined;
|
|
693
|
+
if (jev && p.visual)
|
|
694
|
+
this.visualAllowed(jev.spec, "jevModel");
|
|
695
|
+
const models = purpose === "ask" ? this.askModels(config, p.fields, p.visual) : undefined;
|
|
696
|
+
const read = await real.read(p.tabId, Boolean(p.visual), context.signal, operationTimeout(p, false));
|
|
697
|
+
const image = read.image && { mimeType: read.image.mimeType === "image/jpeg" ? "image/jpeg" : "image/png", data: read.image.data };
|
|
698
|
+
const view = { sessionId: null, backend: "local", origin: "connected", tabId: read.tabId, url: read.url, title: read.title };
|
|
699
|
+
const title = read.title ?? "";
|
|
700
|
+
if (models) {
|
|
701
|
+
try {
|
|
702
|
+
return { action: p.action, ...view, data: await askPage({ ...models, ...(image ? { images: [image] } : {}) }, { url: read.url, title, text: read.text }, p.fields, context.signal) };
|
|
703
|
+
}
|
|
704
|
+
catch (error) {
|
|
705
|
+
if (context.signal.aborted)
|
|
706
|
+
throw error;
|
|
707
|
+
throw new BrowseToolError("ask_error", `${messageOf(error)} Take a snapshot and read the page instead.`);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
const candidates = outlineCandidates(read.outline, p.action);
|
|
711
|
+
if (!candidates.length)
|
|
712
|
+
throw new BrowseToolError("jev_no_candidates", "The page has no elements this action can target. Take a snapshot to inspect it.");
|
|
713
|
+
const model = classifierName(jev.spec);
|
|
714
|
+
const pick = await this.pick(candidates, { url: read.url, title, action: p.action, request: p.target }, jev.classify, image, context.signal);
|
|
715
|
+
if (!pick.chosen)
|
|
716
|
+
return { action: p.action, ...view, data: { jev: this.declined(model, pick, ref => ref) }, code: pick.none ? "jev_none" : "jev_uncertain", isError: true };
|
|
717
|
+
const output = await real.run({ ...p, target: undefined, visual: undefined, selector: pick.chosen.ref }, context.signal, operationTimeout(p, false));
|
|
718
|
+
return { ...output, data: { ...output.data, jev: { model, label: pick.chosen.label, confidence: pick.confidence } } };
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* browse_ai in the real browser: act, observe, and extract on the page's outline and text, with the host's own
|
|
722
|
+
* inference. act performs the one action the model chose; a page that offers none is a failed act, not an error.
|
|
723
|
+
*/
|
|
724
|
+
async aiInRealBrowser(real, p, context) {
|
|
725
|
+
const generate = this.stagehandModel.model?.generate;
|
|
726
|
+
if (!generate) {
|
|
727
|
+
throw new BrowseToolError("configuration", `browse_ai in the user's real browser runs on the ${this.identity.name} model, which this host does not lend. Use browse with a snapshot and refs, or close and start with backend "browserbase".`);
|
|
728
|
+
}
|
|
729
|
+
let schema;
|
|
730
|
+
try {
|
|
731
|
+
schema = p.schema ? z.fromJSONSchema(p.schema) : undefined;
|
|
732
|
+
}
|
|
733
|
+
catch (error) {
|
|
734
|
+
throw new BrowseToolError("invalid_arguments", `schema is not a supported JSON Schema: ${messageOf(error).slice(0, 300)}`);
|
|
735
|
+
}
|
|
736
|
+
const timeout = operationTimeout(p, true);
|
|
737
|
+
const read = await real.read(p.tabId, false, context.signal, timeout);
|
|
738
|
+
const view = { action: p.action, sessionId: null, backend: "local", origin: "connected", tabId: read.tabId, url: read.url, title: read.title };
|
|
739
|
+
try {
|
|
740
|
+
if (p.action === "extract") {
|
|
741
|
+
const extracted = await extractPage(generate, read, p.instruction, p.schema);
|
|
742
|
+
const checked = schema?.safeParse(extracted);
|
|
743
|
+
if (checked && !checked.success)
|
|
744
|
+
throw new BrowseToolError("ai_error", "The model's answer does not match the schema. Retry, or take a snapshot and read the page.");
|
|
745
|
+
return { ...view, data: extracted };
|
|
746
|
+
}
|
|
747
|
+
const actions = await observePage(generate, read, p.instruction, p.action === "act");
|
|
748
|
+
if (p.action === "observe")
|
|
749
|
+
return { ...view, data: actions };
|
|
750
|
+
const [action] = actions;
|
|
751
|
+
if (!action)
|
|
752
|
+
return { ...view, data: { success: false, message: "The page offers no element that carries out the instruction. Take a snapshot to check the page.", actions: [] }, isError: true, code: "act_failed" };
|
|
753
|
+
const [first = ""] = action.arguments;
|
|
754
|
+
// press acts on the focused element, so the chosen one is clicked into first.
|
|
755
|
+
const steps = action.method === "press"
|
|
756
|
+
? [{ action: "click", selector: action.selector, tabId: read.tabId }, { action: "press", key: first, tabId: read.tabId }]
|
|
757
|
+
: [{ action: action.method, selector: action.selector, tabId: read.tabId, ...(action.method === "fill" ? { value: first } : action.method === "select" ? { values: action.arguments } : {}) }];
|
|
758
|
+
let done;
|
|
759
|
+
for (const step of steps)
|
|
760
|
+
done = await real.run(step, context.signal, timeout);
|
|
761
|
+
return { ...view, url: done?.url ?? read.url, title: done?.title ?? read.title, data: { success: true, message: `${action.method} on ${action.description}`, actions: [action] } };
|
|
762
|
+
}
|
|
763
|
+
catch (error) {
|
|
764
|
+
if (context.signal.aborted || error instanceof BrowseToolError)
|
|
765
|
+
throw error;
|
|
766
|
+
throw new BrowseToolError("ai_error", `${messageOf(error).slice(0, 300)} Use browse with a snapshot and refs instead.`);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
/** Closes this conversation's tabs in the real browser; the browser itself is the user's and stays. */
|
|
770
|
+
async closeReal() {
|
|
771
|
+
const real = this.real;
|
|
772
|
+
this.real = undefined;
|
|
773
|
+
await real?.close(AbortSignal.timeout(5000)).catch(() => undefined);
|
|
774
|
+
}
|
|
614
775
|
/** Runs a call in the broker; close ends the conversation there, and a lost broker is reopened by the next call. */
|
|
615
776
|
async forward(params, context, ai) {
|
|
616
777
|
const { conv, connection } = this.delegate;
|
|
@@ -1504,6 +1665,9 @@ export class BrowseSession {
|
|
|
1504
1665
|
throw new BrowseToolError("cookie_profile_ambiguous", `Several browser profiles have cookies for these domains: ${listed}. Retry with browser and profile set to the one matching the task's account or organization; if the task does not say, ask the user which one.`);
|
|
1505
1666
|
}
|
|
1506
1667
|
async browse(p, context) {
|
|
1668
|
+
if (p.action === "handoff") {
|
|
1669
|
+
throw new BrowseToolError("unsupported_backend", "handoff works in the user's real browser only. On Browserbase use live_view; a launched local browser has a visible window the user can act in.");
|
|
1670
|
+
}
|
|
1507
1671
|
if (p.action === "cookie_profiles") {
|
|
1508
1672
|
const browsers = await this.fromCookies(() => this.cookies.list(p.browser, context.signal));
|
|
1509
1673
|
return { action: p.action, sessionId: null, data: { browsers } };
|
|
@@ -1658,7 +1822,7 @@ export class BrowseSession {
|
|
|
1658
1822
|
// Every other action ran above; what is left names its element by target.
|
|
1659
1823
|
const jev = await this.locate(session, page, p, p.target, context);
|
|
1660
1824
|
if (!jev.xpath)
|
|
1661
|
-
return { ...await this.output(p.action, session, page, { jev: jev.result }), code: jev.
|
|
1825
|
+
return { ...await this.output(p.action, session, page, { jev: jev.result }), code: jev.none ? "jev_none" : "jev_uncertain", isError: true };
|
|
1662
1826
|
const output = await this.direct(session, { ...p, target: undefined, selector: jev.xpath }, context);
|
|
1663
1827
|
return { ...output, data: { ...output.data, jev: jev.result } };
|
|
1664
1828
|
}
|
|
@@ -1670,18 +1834,7 @@ export class BrowseSession {
|
|
|
1670
1834
|
*/
|
|
1671
1835
|
async ask(session, page, p, context) {
|
|
1672
1836
|
const fields = p.fields, visual = p.visual;
|
|
1673
|
-
const
|
|
1674
|
-
const config = await this.purposeConfig(session, context, "ask");
|
|
1675
|
-
const decider = needs.decide ? this.classifier("ask", config) : undefined;
|
|
1676
|
-
if (visual && decider)
|
|
1677
|
-
this.visualAllowed(decider.spec, "askModel");
|
|
1678
|
-
const accountId = config.cloudflareAccountId?.trim(), apiKey = config.cloudflareApiKey?.trim();
|
|
1679
|
-
if (needs.extract && (!accountId || !apiKey))
|
|
1680
|
-
throw new BrowseToolError("ask_not_configured", "Configure CLOUDFLARE_API_KEY and CLOUDFLARE_ACCOUNT_ID (Workers AI) to use ask, or take a snapshot and read the page.");
|
|
1681
|
-
const models = {
|
|
1682
|
-
...(accountId && apiKey ? { cloudflare: { accountId, apiKey } } : {}),
|
|
1683
|
-
...(decider ? { decide: decider.classify, decideText: decider.spec.service === "workers-ai" ? DECIDE_TEXT[decider.spec.model] : undefined } : {}),
|
|
1684
|
-
};
|
|
1837
|
+
const models = this.askModels(await this.purposeConfig(session, context, "ask"), fields, visual);
|
|
1685
1838
|
for (let attempt = 1;; attempt++) {
|
|
1686
1839
|
// One request reads the document's identity, the tree, and the viewport; ask needs no XPaths.
|
|
1687
1840
|
const read = await this.batch(session, p, context, readOperation, { refs: false, image: Boolean(visual) }, page);
|
|
@@ -1721,29 +1874,50 @@ export class BrowseSession {
|
|
|
1721
1874
|
const candidates = treeCandidates(read.tree).filter(c => refs[c.ref] && fitsAction(action, c, refs[c.ref]));
|
|
1722
1875
|
if (!candidates.length)
|
|
1723
1876
|
throw new BrowseToolError("jev_no_candidates", "The page has no elements this action can target. Take a snapshot to inspect it.");
|
|
1724
|
-
|
|
1877
|
+
const pick = await this.pick(candidates, { url, title, action, request: target }, classify, image, context.signal);
|
|
1878
|
+
// Keep this snapshot so returned candidate selectors work without another snapshot.
|
|
1879
|
+
const version = `s${++this.snapshotNumber}`;
|
|
1880
|
+
session.snapshots.set(page.pageId, { version, url, refs });
|
|
1881
|
+
if (pick.chosen)
|
|
1882
|
+
return { xpath: refs[pick.chosen.ref], none: false, result: { model, label: pick.chosen.label, confidence: pick.confidence } };
|
|
1883
|
+
return { xpath: undefined, none: pick.none, result: this.declined(model, pick, ref => `@${version}:${ref}`) };
|
|
1884
|
+
}
|
|
1885
|
+
/** Jev's pick among the candidates; a failed request says whether retrying can help. */
|
|
1886
|
+
async pick(candidates, state, classify, image, signal) {
|
|
1725
1887
|
try {
|
|
1726
|
-
|
|
1888
|
+
return await pickTarget(candidates, state, jevChooser(classify, image && [image]), signal);
|
|
1727
1889
|
}
|
|
1728
1890
|
catch (error) {
|
|
1729
|
-
if (
|
|
1891
|
+
if (signal.aborted)
|
|
1730
1892
|
throw error;
|
|
1731
1893
|
const message = error instanceof Error ? error.message : "Jev request failed.";
|
|
1732
1894
|
// A refused key or empty balance fails every later target too.
|
|
1733
1895
|
throw new BrowseToolError(error instanceof ClassifierRefusal ? "jev_unavailable" : "jev_error", message);
|
|
1734
1896
|
}
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1897
|
+
}
|
|
1898
|
+
/** What a call reports when Jev declined to act: its best candidates, each with a selector the caller can use as is. */
|
|
1899
|
+
declined(model, pick, selector) {
|
|
1900
|
+
return {
|
|
1901
|
+
model, acted: false, match: pick.none ? "none" : "uncertain", confidence: pick.confidence, threshold: JEV_MIN_CONFIDENCE,
|
|
1902
|
+
candidates: pick.ranked.map(c => ({ selector: selector(c.ref), label: c.label, probability: c.probability })),
|
|
1903
|
+
hint: pick.none
|
|
1904
|
+
? "Jev found no listed element matching the target. Take a snapshot to check the page, or describe the element differently."
|
|
1905
|
+
: "Jev was not confident enough to act. Retry with one candidate selector, a more specific target, or a snapshot.",
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
/** ask's models for a profile: Workers AI for the values Clairic reads, and the decision classifier for bool and choice. */
|
|
1909
|
+
askModels(config, fields, visual) {
|
|
1910
|
+
const needs = askNeeds(fields);
|
|
1911
|
+
const decider = needs.decide ? this.classifier("ask", config) : undefined;
|
|
1912
|
+
if (visual && decider)
|
|
1913
|
+
this.visualAllowed(decider.spec, "askModel");
|
|
1914
|
+
const accountId = config.cloudflareAccountId?.trim(), apiKey = config.cloudflareApiKey?.trim();
|
|
1915
|
+
if (needs.extract && (!accountId || !apiKey))
|
|
1916
|
+
throw new BrowseToolError("ask_not_configured", "Configure CLOUDFLARE_API_KEY and CLOUDFLARE_ACCOUNT_ID (Workers AI) to use ask, or take a snapshot and read the page.");
|
|
1917
|
+
return {
|
|
1918
|
+
...(accountId && apiKey ? { cloudflare: { accountId, apiKey } } : {}),
|
|
1919
|
+
...(decider ? { decide: decider.classify, decideText: decider.spec.service === "workers-ai" ? DECIDE_TEXT[decider.spec.model] : undefined } : {}),
|
|
1920
|
+
};
|
|
1747
1921
|
}
|
|
1748
1922
|
async ai(p, context) {
|
|
1749
1923
|
const session = this.current();
|
package/package.json
CHANGED