@howaboua/pi-browser 0.0.3 → 0.0.4
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/CHANGELOG.md +11 -0
- package/README.md +4 -0
- package/dist/index.js +2 -2
- package/dist/remote-worker.js +978 -136
- package/dist/src/browser/bounds.d.ts +1 -1
- package/dist/src/browser/bounds.js +6 -3
- package/dist/src/browser/help.js +8 -3
- package/dist/src/browser/operation-executor.js +15 -1
- package/dist/src/browser/operation.d.ts +25 -2
- package/dist/src/browser/operation.js +5 -0
- package/dist/src/browser/parse-operation.js +61 -2
- package/dist/src/browser/remote.d.ts +1 -1
- package/dist/src/browser/remote.js +2 -2
- package/dist/src/browser/runtime.d.ts +8 -3
- package/dist/src/browser/runtime.js +91 -25
- package/dist/src/browser/worker-server.js +12 -6
- package/dist/src/browser-parameters.d.ts +10 -0
- package/dist/src/browser-parameters.js +32 -0
- package/dist/src/browser-tool.d.ts +10 -0
- package/dist/src/browser-tool.js +2 -1
- package/dist/src/cdp/actions/click.d.ts +2 -0
- package/dist/src/cdp/actions/click.js +1 -1
- package/dist/src/cdp/actions/fill.d.ts +8 -0
- package/dist/src/cdp/actions/fill.js +175 -0
- package/dist/src/cdp/actions/key.d.ts +20 -0
- package/dist/src/cdp/actions/key.js +166 -0
- package/dist/src/cdp/actions/wait.d.ts +9 -0
- package/dist/src/cdp/actions/wait.js +95 -0
- package/dist/src/cdp/pages.d.ts +2 -1
- package/dist/src/cdp/pages.js +8 -4
- package/dist/src/cdp/session.d.ts +7 -1
- package/dist/src/cdp/session.js +79 -27
- package/dist/src/cdp/snapshot-contract.d.ts +4 -0
- package/dist/src/cdp/snapshot.js +67 -11
- package/dist/src/cdp/tabs.d.ts +32 -0
- package/dist/src/cdp/tabs.js +226 -0
- package/dist/src/cdp/types.d.ts +2 -0
- package/index.ts +2 -2
- package/package.json +5 -5
- package/src/browser/bounds.ts +7 -2
- package/src/browser/help.ts +8 -3
- package/src/browser/operation-executor.ts +34 -0
- package/src/browser/operation.ts +19 -1
- package/src/browser/parse-operation.ts +63 -2
- package/src/browser/remote.ts +2 -1
- package/src/browser/runtime.ts +115 -26
- package/src/browser/worker-server.ts +24 -7
- package/src/browser-parameters.ts +34 -0
- package/src/browser-tool.ts +2 -1
- package/src/cdp/actions/click.ts +1 -1
- package/src/cdp/actions/fill.ts +246 -0
- package/src/cdp/actions/key.ts +202 -0
- package/src/cdp/actions/wait.ts +117 -0
- package/src/cdp/pages.ts +9 -6
- package/src/cdp/session.ts +98 -46
- package/src/cdp/snapshot-contract.ts +4 -0
- package/src/cdp/snapshot.ts +86 -17
- package/src/cdp/tabs.ts +292 -0
- package/src/cdp/types.ts +2 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { SnapshotResult } from "../cdp/snapshot-contract.js";
|
|
2
2
|
import type { PageInfo } from "../cdp/types.js";
|
|
3
|
-
export declare function boundTabs(pages: PageInfo[], query: string | undefined, offset: number): Record<string, unknown>;
|
|
3
|
+
export declare function boundTabs(pages: PageInfo[], query: string | undefined, offset: number, ownedOnly?: boolean): Record<string, unknown>;
|
|
4
4
|
export declare function boundSnapshot(page: SnapshotResult): Record<string, unknown>;
|
|
@@ -36,12 +36,14 @@ function boundedElement(element) {
|
|
|
36
36
|
...(value === undefined ? {} : { value }),
|
|
37
37
|
};
|
|
38
38
|
}
|
|
39
|
-
export function boundTabs(pages, query, offset) {
|
|
39
|
+
export function boundTabs(pages, query, offset, ownedOnly = false) {
|
|
40
40
|
const prefixLength = getDisplayPrefixLength(pages.map((page) => page.targetId));
|
|
41
|
-
let filtered =
|
|
41
|
+
let filtered = ownedOnly
|
|
42
|
+
? pages.filter((page) => page.owned === true)
|
|
43
|
+
: pages;
|
|
42
44
|
if (query) {
|
|
43
45
|
const normalized = query.toLowerCase();
|
|
44
|
-
filtered =
|
|
46
|
+
filtered = filtered.filter((page) => `${page.title}\n${page.url}`.toLowerCase().includes(normalized));
|
|
45
47
|
}
|
|
46
48
|
if (offset > filtered.length) {
|
|
47
49
|
throw new Error(`offset ${offset} exceeds tab count ${filtered.length}`);
|
|
@@ -52,6 +54,7 @@ export function boundTabs(pages, query, offset) {
|
|
|
52
54
|
ref_id: page.targetId.slice(0, prefixLength),
|
|
53
55
|
title: page.title.slice(0, 500),
|
|
54
56
|
url: page.url.slice(0, 8_000),
|
|
57
|
+
owned: page.owned === true,
|
|
55
58
|
};
|
|
56
59
|
if (byteLength({ tabs: [...tabs, compact] }) > OUTPUT_BUDGET_BYTES) {
|
|
57
60
|
break;
|
package/dist/src/browser/help.js
CHANGED
|
@@ -11,11 +11,16 @@ export function browserHelp(hosts = []) {
|
|
|
11
11
|
safety: "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
|
|
12
12
|
batch: "top-level nonempty action arrays; items omit action/host/response_length; independent only",
|
|
13
13
|
actions: {
|
|
14
|
-
tabs: "query? offset? -> ref_id title url",
|
|
15
|
-
open: "ref_id lineno? response_length? | url",
|
|
14
|
+
tabs: "query? offset? owned_only? -> ref_id title url owned",
|
|
15
|
+
open: "ref_id lineno? response_length? | url; new tabs open in background",
|
|
16
|
+
show: "ref_id; bring tab to foreground",
|
|
17
|
+
close: "ref_id",
|
|
16
18
|
find: "ref_id pattern lineno? response_length?",
|
|
17
19
|
click: "ref_id id|selector|x+y",
|
|
18
20
|
type: "ref_id text id?; id focuses",
|
|
21
|
+
fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
|
|
22
|
+
press: "ref_id key; focused element, e.g. Enter or Control+a",
|
|
23
|
+
wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
|
|
19
24
|
screenshot: "ref_id id?|selector? -> file",
|
|
20
25
|
navigate: "ref_id url",
|
|
21
26
|
html: "ref_id id?|selector?",
|
|
@@ -24,7 +29,7 @@ export function browserHelp(hosts = []) {
|
|
|
24
29
|
load_all: "ref_id selector interval_ms?",
|
|
25
30
|
raw: "ref_id method params?",
|
|
26
31
|
start: "",
|
|
27
|
-
stop: "ref_id
|
|
32
|
+
stop: "ref_id?; detach without closing tabs",
|
|
28
33
|
read_result: "handle offset",
|
|
29
34
|
discard_result: "handle",
|
|
30
35
|
},
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { clickCoordinates, clickRef, clickSelector, } from "../cdp/actions/click.js";
|
|
2
|
+
import { fillElement } from "../cdp/actions/fill.js";
|
|
3
|
+
import { pressKey } from "../cdp/actions/key.js";
|
|
2
4
|
import { html, htmlRef, loadAll, navigate, networkEntries, rawCommand, } from "../cdp/actions/page.js";
|
|
3
5
|
import { captureRef, captureSelector, captureViewport, } from "../cdp/actions/screenshot.js";
|
|
4
6
|
import { typeAtFocus, typeRef } from "../cdp/actions/type.js";
|
|
7
|
+
import { waitForCondition } from "../cdp/actions/wait.js";
|
|
5
8
|
import { evaluateText } from "../cdp/evaluate.js";
|
|
6
9
|
import { BrowserCdpSession } from "../cdp/session.js";
|
|
7
10
|
import { snapshotData } from "../cdp/snapshot.js";
|
|
@@ -18,13 +21,14 @@ export class BrowserOperationExecutor {
|
|
|
18
21
|
case "start":
|
|
19
22
|
return { result: await startBrowser(signal) };
|
|
20
23
|
case "tabs":
|
|
21
|
-
return boundTabs(await this.cdp.pages(signal), operation.query, operation.offset);
|
|
24
|
+
return boundTabs(await this.cdp.pages(signal), operation.query, operation.offset, operation.owned_only);
|
|
22
25
|
case "open":
|
|
23
26
|
if ("url" in operation) {
|
|
24
27
|
const opened = await this.cdp.open(operation.url, signal);
|
|
25
28
|
return {
|
|
26
29
|
ref_id: opened.refId,
|
|
27
30
|
url: operation.url,
|
|
31
|
+
owned: true,
|
|
28
32
|
};
|
|
29
33
|
}
|
|
30
34
|
return this.cdp.withTab(operation.ref_id, signal, async (tab) => boundSnapshot(await snapshotData(tab.cdp, tab.sessionId, tab.elementRefs, {
|
|
@@ -41,6 +45,10 @@ export class BrowserOperationExecutor {
|
|
|
41
45
|
responseLength: operation.response_length,
|
|
42
46
|
signal,
|
|
43
47
|
})));
|
|
48
|
+
case "show":
|
|
49
|
+
return { shown: await this.cdp.show(operation.ref_id, signal) };
|
|
50
|
+
case "close":
|
|
51
|
+
return { closed: await this.cdp.closeTab(operation.ref_id, signal) };
|
|
44
52
|
case "read_result":
|
|
45
53
|
return readCachedResult(operation);
|
|
46
54
|
case "discard_result":
|
|
@@ -83,6 +91,12 @@ export class BrowserOperationExecutor {
|
|
|
83
91
|
: typeRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, operation.text, signal));
|
|
84
92
|
case "load_all":
|
|
85
93
|
return this.tabResult(operation.ref_id, signal, (tab) => loadAll(tab.cdp, tab.sessionId, operation.selector, operation.interval_ms, signal));
|
|
94
|
+
case "fill":
|
|
95
|
+
return this.tabResult(operation.ref_id, signal, (tab) => fillElement(tab.cdp, tab.sessionId, tab.elementRefs, operation, operation.value, signal));
|
|
96
|
+
case "press":
|
|
97
|
+
return this.tabResult(operation.ref_id, signal, (tab) => pressKey(tab.cdp, tab.sessionId, operation.key, signal));
|
|
98
|
+
case "wait":
|
|
99
|
+
return this.tabResult(operation.ref_id, signal, (tab) => waitForCondition(tab.cdp, tab.sessionId, operation, operation.timeout_ms, signal));
|
|
86
100
|
}
|
|
87
101
|
}
|
|
88
102
|
async screenshot(operation, signal) {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import type { WaitCondition } from "../cdp/actions/wait.js";
|
|
1
2
|
import type { SnapshotResponseLength } from "../cdp/snapshot-contract.js";
|
|
2
|
-
export declare const BROWSER_ACTIONS: readonly ["help", "start", "tabs", "open", "find", "click", "type", "screenshot", "html", "navigate", "evaluate", "network", "load_all", "raw", "read_result", "discard_result", "stop"];
|
|
3
|
-
export declare const OPERATION_ORDER: ("click" | "discard_result" | "evaluate" | "find" | "html" | "load_all" | "navigate" | "network" | "open" | "raw" | "read_result" | "screenshot" | "start" | "stop" | "tabs" | "type")[];
|
|
3
|
+
export declare const BROWSER_ACTIONS: readonly ["help", "start", "tabs", "open", "show", "close", "find", "click", "type", "fill", "press", "wait", "screenshot", "html", "navigate", "evaluate", "network", "load_all", "raw", "read_result", "discard_result", "stop"];
|
|
4
|
+
export declare const OPERATION_ORDER: ("click" | "close" | "discard_result" | "evaluate" | "fill" | "find" | "html" | "load_all" | "navigate" | "network" | "open" | "press" | "raw" | "read_result" | "screenshot" | "show" | "start" | "stop" | "tabs" | "type" | "wait")[];
|
|
4
5
|
export type BrowserAction = (typeof BROWSER_ACTIONS)[number];
|
|
5
6
|
export type BrowserOperation = {
|
|
6
7
|
action: "start";
|
|
@@ -8,6 +9,7 @@ export type BrowserOperation = {
|
|
|
8
9
|
action: "tabs";
|
|
9
10
|
query?: string | undefined;
|
|
10
11
|
offset: number;
|
|
12
|
+
owned_only?: boolean | undefined;
|
|
11
13
|
} | {
|
|
12
14
|
action: "open";
|
|
13
15
|
ref_id: string;
|
|
@@ -16,6 +18,9 @@ export type BrowserOperation = {
|
|
|
16
18
|
} | {
|
|
17
19
|
action: "open";
|
|
18
20
|
url: string;
|
|
21
|
+
} | {
|
|
22
|
+
action: "show" | "close";
|
|
23
|
+
ref_id: string;
|
|
19
24
|
} | {
|
|
20
25
|
action: "find";
|
|
21
26
|
ref_id: string;
|
|
@@ -48,7 +53,25 @@ export type BrowserOperation = {
|
|
|
48
53
|
ref_id: string;
|
|
49
54
|
id?: number | undefined;
|
|
50
55
|
text: string;
|
|
56
|
+
} | ({
|
|
57
|
+
action: "fill";
|
|
58
|
+
ref_id: string;
|
|
59
|
+
value: string | boolean;
|
|
60
|
+
} & ({
|
|
61
|
+
id: number;
|
|
62
|
+
selector?: never;
|
|
51
63
|
} | {
|
|
64
|
+
selector: string;
|
|
65
|
+
id?: never;
|
|
66
|
+
})) | {
|
|
67
|
+
action: "press";
|
|
68
|
+
ref_id: string;
|
|
69
|
+
key: string;
|
|
70
|
+
} | ({
|
|
71
|
+
action: "wait";
|
|
72
|
+
ref_id: string;
|
|
73
|
+
timeout_ms: number;
|
|
74
|
+
} & WaitCondition) | {
|
|
52
75
|
action: "screenshot";
|
|
53
76
|
ref_id: string;
|
|
54
77
|
id?: number | undefined;
|
|
@@ -1,13 +1,19 @@
|
|
|
1
|
+
import { parseKeyChord } from "../cdp/actions/key.js";
|
|
1
2
|
import { BROWSER_ACTIONS, } from "./operation.js";
|
|
2
3
|
const fields = (...names) => new Set(["action", ...names]);
|
|
3
4
|
const ACTION_FIELDS = {
|
|
4
5
|
help: fields(),
|
|
5
6
|
start: fields(),
|
|
6
|
-
tabs: fields("query", "offset"),
|
|
7
|
+
tabs: fields("query", "offset", "owned_only"),
|
|
7
8
|
open: fields("ref_id", "url", "lineno", "response_length"),
|
|
9
|
+
show: fields("ref_id"),
|
|
10
|
+
close: fields("ref_id"),
|
|
8
11
|
find: fields("ref_id", "pattern", "lineno", "response_length"),
|
|
9
12
|
click: fields("ref_id", "id", "selector", "x", "y"),
|
|
10
13
|
type: fields("ref_id", "id", "text"),
|
|
14
|
+
fill: fields("ref_id", "id", "selector", "value"),
|
|
15
|
+
press: fields("ref_id", "key"),
|
|
16
|
+
wait: fields("ref_id", "selector", "text", "url_includes", "timeout_ms"),
|
|
11
17
|
screenshot: fields("ref_id", "id", "selector"),
|
|
12
18
|
html: fields("ref_id", "id", "selector"),
|
|
13
19
|
navigate: fields("ref_id", "url"),
|
|
@@ -95,10 +101,14 @@ export function parseActionRequest(value) {
|
|
|
95
101
|
return { action };
|
|
96
102
|
if (action === "tabs") {
|
|
97
103
|
const query = optionalString(value["query"], "query");
|
|
104
|
+
const ownedOnly = value["owned_only"];
|
|
105
|
+
if (ownedOnly !== undefined && typeof ownedOnly !== "boolean")
|
|
106
|
+
throw new Error("owned_only must be a boolean");
|
|
98
107
|
return {
|
|
99
108
|
action,
|
|
100
109
|
...(query ? { query } : {}),
|
|
101
110
|
offset: offset(value["offset"]),
|
|
111
|
+
...(ownedOnly === undefined ? {} : { owned_only: ownedOnly }),
|
|
102
112
|
};
|
|
103
113
|
}
|
|
104
114
|
if (action === "open") {
|
|
@@ -142,7 +152,7 @@ export function parseActionRequest(value) {
|
|
|
142
152
|
return { action, ...(refId ? { ref_id: refId } : {}) };
|
|
143
153
|
}
|
|
144
154
|
const refId = requiredRef(value["ref_id"], action);
|
|
145
|
-
if (action === "network")
|
|
155
|
+
if (action === "network" || action === "show" || action === "close")
|
|
146
156
|
return { action, ref_id: refId };
|
|
147
157
|
if (action === "navigate") {
|
|
148
158
|
return {
|
|
@@ -215,6 +225,55 @@ export function parseActionRequest(value) {
|
|
|
215
225
|
...(selector ? { selector } : {}),
|
|
216
226
|
};
|
|
217
227
|
}
|
|
228
|
+
if (action === "fill") {
|
|
229
|
+
const id = elementId(value["id"]);
|
|
230
|
+
const selector = optionalString(value["selector"], "selector");
|
|
231
|
+
if (Number(id !== undefined) + Number(selector !== undefined) !== 1) {
|
|
232
|
+
throw new Error("fill requires exactly one of id or selector");
|
|
233
|
+
}
|
|
234
|
+
const fillValue = value["value"];
|
|
235
|
+
if (typeof fillValue !== "string" && typeof fillValue !== "boolean") {
|
|
236
|
+
throw new Error("value must be text or a boolean for checkbox/radio");
|
|
237
|
+
}
|
|
238
|
+
if (id !== undefined)
|
|
239
|
+
return { action, ref_id: refId, id, value: fillValue };
|
|
240
|
+
if (selector)
|
|
241
|
+
return { action, ref_id: refId, selector, value: fillValue };
|
|
242
|
+
throw new Error("fill requires id or selector");
|
|
243
|
+
}
|
|
244
|
+
if (action === "press") {
|
|
245
|
+
const key = requiredString(value["key"], "key");
|
|
246
|
+
parseKeyChord(key);
|
|
247
|
+
return { action, ref_id: refId, key };
|
|
248
|
+
}
|
|
249
|
+
if (action === "wait") {
|
|
250
|
+
const conditions = ["selector", "text", "url_includes"];
|
|
251
|
+
const provided = conditions.filter((field) => value[field] !== undefined);
|
|
252
|
+
const field = provided[0];
|
|
253
|
+
if (provided.length !== 1 || !field) {
|
|
254
|
+
throw new Error("wait requires exactly one of selector, text, or url_includes");
|
|
255
|
+
}
|
|
256
|
+
const match = value[field];
|
|
257
|
+
if (typeof match !== "string" || !match.trim()) {
|
|
258
|
+
throw new Error(`${field} must be a non-empty string`);
|
|
259
|
+
}
|
|
260
|
+
const timeout = value["timeout_ms"] ?? 10_000;
|
|
261
|
+
if (!Number.isInteger(timeout) ||
|
|
262
|
+
Number(timeout) < 1 ||
|
|
263
|
+
Number(timeout) > 60_000) {
|
|
264
|
+
throw new Error("timeout_ms must be an integer from 1 to 60000");
|
|
265
|
+
}
|
|
266
|
+
const base = {
|
|
267
|
+
action,
|
|
268
|
+
ref_id: refId,
|
|
269
|
+
timeout_ms: Number(timeout),
|
|
270
|
+
};
|
|
271
|
+
if (field === "selector")
|
|
272
|
+
return { ...base, selector: match };
|
|
273
|
+
if (field === "text")
|
|
274
|
+
return { ...base, text: match };
|
|
275
|
+
return { ...base, url_includes: match };
|
|
276
|
+
}
|
|
218
277
|
if (action === "load_all") {
|
|
219
278
|
const interval = value["interval_ms"] ?? 1_500;
|
|
220
279
|
if (!Number.isInteger(interval) ||
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { BrowserOperation } from "./operation.js";
|
|
2
2
|
import type { BrowserRoute } from "./routes.js";
|
|
3
3
|
export { remoteNodeCommand } from "./remote-helper.js";
|
|
4
|
-
export declare function executeRemoteBrowser(route: BrowserRoute, operations: BrowserOperation[], signal?: AbortSignal): Promise<Record<string, unknown>>;
|
|
4
|
+
export declare function executeRemoteBrowser(route: BrowserRoute, operations: BrowserOperation[], ownerId: string, signal?: AbortSignal): Promise<Record<string, unknown>>;
|
|
@@ -47,12 +47,12 @@ async function localizeScreenshots(host, operations, result, signal) {
|
|
|
47
47
|
item["file"] = await copyRemoteArtifact(host, item["file"], signal);
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
|
-
export async function executeRemoteBrowser(route, operations, signal) {
|
|
50
|
+
export async function executeRemoteBrowser(route, operations, ownerId, signal) {
|
|
51
51
|
if (!route.remote) {
|
|
52
52
|
throw new Error(`Browser host ${route.name} has no remote command`);
|
|
53
53
|
}
|
|
54
54
|
await ensureRemoteHelper(route.name, route.remote, signal);
|
|
55
|
-
const executed = await runProgram("ssh", [route.name, remoteNodeCommand(route.remote)], JSON.stringify({ operations }), signal);
|
|
55
|
+
const executed = await runProgram("ssh", [route.name, remoteNodeCommand(route.remote)], JSON.stringify({ owner_id: ownerId, operations }), signal);
|
|
56
56
|
if (executed.code !== 0) {
|
|
57
57
|
throw new Error(executed.stderr ||
|
|
58
58
|
executed.stdout ||
|
|
@@ -2,16 +2,21 @@ import type { BrowserOperation } from "./operation.js";
|
|
|
2
2
|
import type { BrowserRequest } from "./request.js";
|
|
3
3
|
import { BrowserRoutes } from "./routes.js";
|
|
4
4
|
export interface BrowserExecutionOptions {
|
|
5
|
+
ownerId?: string | undefined;
|
|
5
6
|
signal?: AbortSignal | undefined;
|
|
6
7
|
onOperation?(operation: BrowserOperation, index: number, total: number): void;
|
|
7
8
|
}
|
|
8
9
|
export declare class BrowserRuntime {
|
|
9
10
|
readonly hosts: readonly string[];
|
|
10
|
-
private readonly
|
|
11
|
-
private readonly
|
|
11
|
+
private readonly defaultOwnerId;
|
|
12
|
+
private readonly lifetime;
|
|
13
|
+
private closing;
|
|
14
|
+
private readonly localSessions;
|
|
12
15
|
private readonly routes;
|
|
13
16
|
constructor(routes?: BrowserRoutes);
|
|
14
17
|
execute(request: BrowserRequest, options?: BrowserExecutionOptions): Promise<Record<string, unknown>>;
|
|
15
|
-
close(): void
|
|
18
|
+
close(): Promise<void>;
|
|
16
19
|
private executeLocal;
|
|
20
|
+
private localSession;
|
|
21
|
+
private pruneLocalSessions;
|
|
17
22
|
}
|
|
@@ -1,23 +1,38 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { waitForTurn } from "../cdp/serial.js";
|
|
1
4
|
import { BrowserCdpSession } from "../cdp/session.js";
|
|
2
|
-
import { pruneArtifacts } from "./artifacts.js";
|
|
5
|
+
import { artifactDirectory, pruneArtifacts } from "./artifacts.js";
|
|
3
6
|
import { browserHelp } from "./help.js";
|
|
4
7
|
import { BrowserOperationExecutor } from "./operation-executor.js";
|
|
5
8
|
import { executeRemoteBrowser } from "./remote.js";
|
|
6
9
|
import { BrowserRoutes, loadBrowserRoutes } from "./routes.js";
|
|
10
|
+
const LOCAL_SESSION_IDLE_MS = 20 * 60 * 1_000;
|
|
7
11
|
export class BrowserRuntime {
|
|
8
12
|
hosts;
|
|
9
|
-
|
|
10
|
-
|
|
13
|
+
defaultOwnerId = randomUUID();
|
|
14
|
+
lifetime = new AbortController();
|
|
15
|
+
closing;
|
|
16
|
+
localSessions = new Map();
|
|
11
17
|
routes;
|
|
12
18
|
constructor(routes = loadBrowserRoutes()) {
|
|
13
19
|
this.routes = routes;
|
|
14
20
|
this.hosts = routes.names;
|
|
15
21
|
}
|
|
16
22
|
async execute(request, options = {}) {
|
|
23
|
+
options = {
|
|
24
|
+
...options,
|
|
25
|
+
signal: options.signal
|
|
26
|
+
? AbortSignal.any([options.signal, this.lifetime.signal])
|
|
27
|
+
: this.lifetime.signal,
|
|
28
|
+
};
|
|
17
29
|
options.signal?.throwIfAborted();
|
|
30
|
+
await waitForTurn(this.pruneLocalSessions(), options.signal);
|
|
18
31
|
await pruneArtifacts();
|
|
32
|
+
options.signal?.throwIfAborted();
|
|
19
33
|
if ("help" in request)
|
|
20
34
|
return browserHelp(this.hosts);
|
|
35
|
+
const ownerId = options.ownerId ?? this.defaultOwnerId;
|
|
21
36
|
if (request.host) {
|
|
22
37
|
const route = this.routes.resolve(request.host);
|
|
23
38
|
if (!route.local) {
|
|
@@ -25,37 +40,88 @@ export class BrowserRuntime {
|
|
|
25
40
|
if (first) {
|
|
26
41
|
options.onOperation?.(first, 0, request.operations.length);
|
|
27
42
|
}
|
|
28
|
-
const result = await executeRemoteBrowser(route, request.operations, options.signal);
|
|
43
|
+
const result = await executeRemoteBrowser(route, request.operations, ownerId, options.signal);
|
|
29
44
|
return { host: request.host, ...result };
|
|
30
45
|
}
|
|
31
46
|
}
|
|
32
|
-
const result = await this.executeLocal(request.operations, options);
|
|
47
|
+
const result = await this.executeLocal(request.operations, ownerId, options);
|
|
33
48
|
return request.host ? { host: request.host, ...result } : result;
|
|
34
49
|
}
|
|
35
50
|
close() {
|
|
36
|
-
this.
|
|
51
|
+
if (this.closing)
|
|
52
|
+
return this.closing;
|
|
53
|
+
this.lifetime.abort(new Error("Browser runtime closed"));
|
|
54
|
+
const closing = [...this.localSessions.values()].map((session) => session.cdp.close());
|
|
55
|
+
this.localSessions.clear();
|
|
56
|
+
this.closing = Promise.all(closing).then(() => undefined);
|
|
57
|
+
return this.closing;
|
|
37
58
|
}
|
|
38
|
-
async executeLocal(operations, options) {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
59
|
+
async executeLocal(operations, ownerId, options) {
|
|
60
|
+
let pendingClose = this.localSessions.get(ownerId)?.closing;
|
|
61
|
+
while (pendingClose) {
|
|
62
|
+
await waitForTurn(pendingClose, options.signal);
|
|
63
|
+
pendingClose = this.localSessions.get(ownerId)?.closing;
|
|
64
|
+
}
|
|
65
|
+
options.signal?.throwIfAborted();
|
|
66
|
+
const session = this.localSession(ownerId);
|
|
67
|
+
session.activeCalls++;
|
|
68
|
+
try {
|
|
69
|
+
const results = [];
|
|
70
|
+
for (const [index, operation] of operations.entries()) {
|
|
71
|
+
try {
|
|
72
|
+
options.signal?.throwIfAborted();
|
|
73
|
+
options.onOperation?.(operation, index, operations.length);
|
|
74
|
+
results.push(await session.operations.execute(operation, options.signal));
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
throw new Error(`batch failed at ${operation.action}[${index}] after ${results.length} completed operation(s): ${error instanceof Error ? error.message : String(error)}`);
|
|
78
|
+
}
|
|
48
79
|
}
|
|
80
|
+
const first = results[0];
|
|
81
|
+
if (results.length === 1 && first)
|
|
82
|
+
return first;
|
|
83
|
+
return {
|
|
84
|
+
results: results.map((result, index) => ({
|
|
85
|
+
operation: operations[index]?.action ?? "unknown",
|
|
86
|
+
index,
|
|
87
|
+
...result,
|
|
88
|
+
})),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
session.activeCalls--;
|
|
93
|
+
session.lastUsed = Date.now();
|
|
49
94
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
95
|
+
}
|
|
96
|
+
localSession(ownerId) {
|
|
97
|
+
let session = this.localSessions.get(ownerId);
|
|
98
|
+
if (session)
|
|
99
|
+
return session;
|
|
100
|
+
const cdp = new BrowserCdpSession(ownerId, join(artifactDirectory(), "tabs"));
|
|
101
|
+
session = {
|
|
102
|
+
activeCalls: 0,
|
|
103
|
+
cdp,
|
|
104
|
+
lastUsed: Date.now(),
|
|
105
|
+
operations: new BrowserOperationExecutor(cdp),
|
|
59
106
|
};
|
|
107
|
+
this.localSessions.set(ownerId, session);
|
|
108
|
+
return session;
|
|
109
|
+
}
|
|
110
|
+
async pruneLocalSessions(now = Date.now()) {
|
|
111
|
+
const closing = [];
|
|
112
|
+
for (const [ownerId, session] of this.localSessions) {
|
|
113
|
+
if (!session.closing &&
|
|
114
|
+
session.activeCalls === 0 &&
|
|
115
|
+
now - session.lastUsed >= LOCAL_SESSION_IDLE_MS) {
|
|
116
|
+
session.closing = session.cdp.close().finally(() => {
|
|
117
|
+
if (this.localSessions.get(ownerId) === session) {
|
|
118
|
+
this.localSessions.delete(ownerId);
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
if (session.closing)
|
|
123
|
+
closing.push(session.closing);
|
|
124
|
+
}
|
|
125
|
+
await Promise.all(closing);
|
|
60
126
|
}
|
|
61
127
|
}
|
|
@@ -35,7 +35,7 @@ async function ensureWorkerSocketDirectory(workerId) {
|
|
|
35
35
|
if ((info.mode & 0o077) !== 0)
|
|
36
36
|
await chmod(directory, 0o700);
|
|
37
37
|
}
|
|
38
|
-
function
|
|
38
|
+
function parseWorkerRequest(input) {
|
|
39
39
|
let value;
|
|
40
40
|
try {
|
|
41
41
|
value = JSON.parse(input);
|
|
@@ -45,14 +45,19 @@ function parseWorkerOperations(input) {
|
|
|
45
45
|
}
|
|
46
46
|
if (!isRecordValue(value))
|
|
47
47
|
throw new Error("worker input must be an object");
|
|
48
|
-
const unknown = Object.keys(value).filter((key) => key !== "operations");
|
|
48
|
+
const unknown = Object.keys(value).filter((key) => key !== "owner_id" && key !== "operations");
|
|
49
49
|
if (unknown.length > 0) {
|
|
50
50
|
throw new Error(`unknown worker field(s): ${unknown.join(", ")}`);
|
|
51
51
|
}
|
|
52
|
+
if (typeof value["owner_id"] !== "string" ||
|
|
53
|
+
value["owner_id"].length === 0 ||
|
|
54
|
+
value["owner_id"].length > 256) {
|
|
55
|
+
throw new Error("worker owner_id must be a non-empty string no longer than 256 characters");
|
|
56
|
+
}
|
|
52
57
|
if (!Array.isArray(value["operations"]) || value["operations"].length === 0) {
|
|
53
58
|
throw new Error("worker operations must be a non-empty array");
|
|
54
59
|
}
|
|
55
|
-
|
|
60
|
+
const operations = value["operations"].map((operation, index) => {
|
|
56
61
|
if (!isRecordValue(operation)) {
|
|
57
62
|
throw new Error(`worker operations[${index}] must be an object`);
|
|
58
63
|
}
|
|
@@ -62,6 +67,7 @@ function parseWorkerOperations(input) {
|
|
|
62
67
|
}
|
|
63
68
|
return parsed;
|
|
64
69
|
});
|
|
70
|
+
return { operations, ownerId: value["owner_id"] };
|
|
65
71
|
}
|
|
66
72
|
function readLine(socket) {
|
|
67
73
|
return new Promise((resolveValue, reject) => {
|
|
@@ -104,10 +110,10 @@ async function handleConnection(socket, runtime) {
|
|
|
104
110
|
socket.once("error", abort);
|
|
105
111
|
let response;
|
|
106
112
|
try {
|
|
107
|
-
const
|
|
113
|
+
const request = parseWorkerRequest(await readLine(socket));
|
|
108
114
|
response = {
|
|
109
115
|
ok: true,
|
|
110
|
-
result: await runtime.execute({ operations }, { signal: controller.signal }),
|
|
116
|
+
result: await runtime.execute({ operations: request.operations }, { ownerId: request.ownerId, signal: controller.signal }),
|
|
111
117
|
};
|
|
112
118
|
}
|
|
113
119
|
catch (error) {
|
|
@@ -156,7 +162,7 @@ export async function serveBrowserWorker(workerId) {
|
|
|
156
162
|
clearTimeout(idleTimer);
|
|
157
163
|
process.removeListener("SIGINT", close);
|
|
158
164
|
process.removeListener("SIGTERM", close);
|
|
159
|
-
runtime.close();
|
|
165
|
+
await runtime.close();
|
|
160
166
|
if (!IS_WINDOWS && ownsSocket)
|
|
161
167
|
await rm(path, { force: true });
|
|
162
168
|
}
|
|
@@ -25,6 +25,16 @@ export declare function browserParameters(hosts: readonly string[]): Type.TUnion
|
|
|
25
25
|
[x: string]: TSchema;
|
|
26
26
|
}>, Type.TObject<{
|
|
27
27
|
[x: string]: TSchema;
|
|
28
|
+
}>, ...Type.TObject<{
|
|
29
|
+
[x: string]: TSchema;
|
|
30
|
+
}>[], Type.TObject<{
|
|
31
|
+
[x: string]: TSchema;
|
|
32
|
+
}>, Type.TObject<{
|
|
33
|
+
[x: string]: TSchema;
|
|
34
|
+
}>, Type.TObject<{
|
|
35
|
+
[x: string]: TSchema;
|
|
36
|
+
}>, Type.TObject<{
|
|
37
|
+
[x: string]: TSchema;
|
|
28
38
|
}>, Type.TObject<{
|
|
29
39
|
[x: string]: TSchema;
|
|
30
40
|
}>, Type.TObject<{
|
|
@@ -20,12 +20,17 @@ export function browserParameters(hosts) {
|
|
|
20
20
|
minLength: 1,
|
|
21
21
|
description: "Continuation handle returned by browser",
|
|
22
22
|
});
|
|
23
|
+
const fillValue = Type.Union([Type.String(), Type.Boolean()], {
|
|
24
|
+
description: "Replacement text/option; boolean for checkbox/radio",
|
|
25
|
+
});
|
|
26
|
+
const timeout = Type.Optional(Type.Integer({ minimum: 1, maximum: 60_000 }));
|
|
23
27
|
return Type.Union([
|
|
24
28
|
request({ action: StringEnum(["help", "start"]) }),
|
|
25
29
|
request({
|
|
26
30
|
action: Type.Literal("tabs"),
|
|
27
31
|
query: Type.Optional(Type.String({ minLength: 1 })),
|
|
28
32
|
offset: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
33
|
+
owned_only: Type.Optional(Type.Boolean()),
|
|
29
34
|
}),
|
|
30
35
|
request({
|
|
31
36
|
action: Type.Literal("open"),
|
|
@@ -44,6 +49,10 @@ export function browserParameters(hosts) {
|
|
|
44
49
|
lineno: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
45
50
|
response_length: Type.Optional(responseLength),
|
|
46
51
|
}),
|
|
52
|
+
request({
|
|
53
|
+
action: StringEnum(["show", "close"]),
|
|
54
|
+
ref_id: refId,
|
|
55
|
+
}),
|
|
47
56
|
request({ action: Type.Literal("click"), ref_id: refId, id: elementId }),
|
|
48
57
|
request({
|
|
49
58
|
action: Type.Literal("click"),
|
|
@@ -62,6 +71,29 @@ export function browserParameters(hosts) {
|
|
|
62
71
|
id: Type.Optional(elementId),
|
|
63
72
|
text: Type.String({ minLength: 1 }),
|
|
64
73
|
}),
|
|
74
|
+
request({
|
|
75
|
+
action: Type.Literal("fill"),
|
|
76
|
+
ref_id: refId,
|
|
77
|
+
id: elementId,
|
|
78
|
+
value: fillValue,
|
|
79
|
+
}),
|
|
80
|
+
request({
|
|
81
|
+
action: Type.Literal("fill"),
|
|
82
|
+
ref_id: refId,
|
|
83
|
+
selector: Type.String({ minLength: 1 }),
|
|
84
|
+
value: fillValue,
|
|
85
|
+
}),
|
|
86
|
+
request({
|
|
87
|
+
action: Type.Literal("press"),
|
|
88
|
+
ref_id: refId,
|
|
89
|
+
key: Type.String({ minLength: 1 }),
|
|
90
|
+
}),
|
|
91
|
+
...["selector", "text", "url_includes"].map((condition) => request({
|
|
92
|
+
action: Type.Literal("wait"),
|
|
93
|
+
ref_id: refId,
|
|
94
|
+
[condition]: Type.String({ minLength: 1 }),
|
|
95
|
+
timeout_ms: timeout,
|
|
96
|
+
})),
|
|
65
97
|
request({
|
|
66
98
|
action: StringEnum(["screenshot", "html"]),
|
|
67
99
|
ref_id: refId,
|
|
@@ -30,6 +30,16 @@ export declare function createBrowserTool(runtime: BrowserRuntime): import("@ear
|
|
|
30
30
|
[x: string]: import("typebox").TSchema;
|
|
31
31
|
}>, import("typebox").TObject<{
|
|
32
32
|
[x: string]: import("typebox").TSchema;
|
|
33
|
+
}>, ...import("typebox").TObject<{
|
|
34
|
+
[x: string]: import("typebox").TSchema;
|
|
35
|
+
}>[], import("typebox").TObject<{
|
|
36
|
+
[x: string]: import("typebox").TSchema;
|
|
37
|
+
}>, import("typebox").TObject<{
|
|
38
|
+
[x: string]: import("typebox").TSchema;
|
|
39
|
+
}>, import("typebox").TObject<{
|
|
40
|
+
[x: string]: import("typebox").TSchema;
|
|
41
|
+
}>, import("typebox").TObject<{
|
|
42
|
+
[x: string]: import("typebox").TSchema;
|
|
33
43
|
}>, import("typebox").TObject<{
|
|
34
44
|
[x: string]: import("typebox").TSchema;
|
|
35
45
|
}>, import("typebox").TObject<{
|
package/dist/src/browser-tool.js
CHANGED
|
@@ -30,8 +30,9 @@ export function createBrowserTool(runtime) {
|
|
|
30
30
|
label: "Browser",
|
|
31
31
|
description: "Control logged-in browser; call help before other actions",
|
|
32
32
|
parameters,
|
|
33
|
-
async execute(_toolCallId, input, signal, onUpdate) {
|
|
33
|
+
async execute(_toolCallId, input, signal, onUpdate, ctx) {
|
|
34
34
|
const result = await runtime.execute(browserRequest(input), {
|
|
35
|
+
ownerId: ctx.sessionManager.getSessionId(),
|
|
35
36
|
signal: signal ?? new AbortController().signal,
|
|
36
37
|
onOperation(operation, index, total) {
|
|
37
38
|
onUpdate?.({
|