@howaboua/pi-browser 0.0.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/CHANGELOG.md +9 -0
- package/LICENSE +22 -0
- package/README.md +47 -0
- package/biome.json +31 -0
- package/changelog.ts +337 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +82 -0
- package/dist/remote-worker.d.ts +2 -0
- package/dist/remote-worker.js +3005 -0
- package/dist/src/browser/artifacts.d.ts +13 -0
- package/dist/src/browser/artifacts.js +133 -0
- package/dist/src/browser/bounds.d.ts +4 -0
- package/dist/src/browser/bounds.js +129 -0
- package/dist/src/browser/config.d.ts +11 -0
- package/dist/src/browser/config.js +106 -0
- package/dist/src/browser/help.d.ts +1 -0
- package/dist/src/browser/help.js +27 -0
- package/dist/src/browser/launcher.d.ts +8 -0
- package/dist/src/browser/launcher.js +169 -0
- package/dist/src/browser/operation-executor.d.ts +9 -0
- package/dist/src/browser/operation-executor.js +112 -0
- package/dist/src/browser/operation.d.ts +92 -0
- package/dist/src/browser/operation.js +20 -0
- package/dist/src/browser/parse-operation.d.ts +6 -0
- package/dist/src/browser/parse-operation.js +248 -0
- package/dist/src/browser/remote-helper.d.ts +3 -0
- package/dist/src/browser/remote-helper.js +114 -0
- package/dist/src/browser/remote-process.d.ts +7 -0
- package/dist/src/browser/remote-process.js +78 -0
- package/dist/src/browser/remote.d.ts +4 -0
- package/dist/src/browser/remote.js +73 -0
- package/dist/src/browser/request.d.ts +8 -0
- package/dist/src/browser/request.js +80 -0
- package/dist/src/browser/routes.d.ts +16 -0
- package/dist/src/browser/routes.js +40 -0
- package/dist/src/browser/runtime.d.ts +17 -0
- package/dist/src/browser/runtime.js +61 -0
- package/dist/src/browser/settings.d.ts +2 -0
- package/dist/src/browser/settings.js +164 -0
- package/dist/src/browser/worker-server.d.ts +2 -0
- package/dist/src/browser/worker-server.js +241 -0
- package/dist/src/browser-parameters.d.ts +42 -0
- package/dist/src/browser-parameters.js +113 -0
- package/dist/src/browser-tool.d.ts +48 -0
- package/dist/src/browser-tool.js +71 -0
- package/dist/src/cdp/actions/click.d.ts +4 -0
- package/dist/src/cdp/actions/click.js +56 -0
- package/dist/src/cdp/actions/element.d.ts +22 -0
- package/dist/src/cdp/actions/element.js +126 -0
- package/dist/src/cdp/actions/page.d.ts +7 -0
- package/dist/src/cdp/actions/page.js +127 -0
- package/dist/src/cdp/actions/screenshot.d.ts +10 -0
- package/dist/src/cdp/actions/screenshot.js +96 -0
- package/dist/src/cdp/actions/selector.d.ts +2 -0
- package/dist/src/cdp/actions/selector.js +41 -0
- package/dist/src/cdp/actions/type.d.ts +3 -0
- package/dist/src/cdp/actions/type.js +138 -0
- package/dist/src/cdp/client.d.ts +20 -0
- package/dist/src/cdp/client.js +248 -0
- package/dist/src/cdp/discovery.d.ts +7 -0
- package/dist/src/cdp/discovery.js +153 -0
- package/dist/src/cdp/evaluate.d.ts +3 -0
- package/dist/src/cdp/evaluate.js +31 -0
- package/dist/src/cdp/pages.d.ts +3 -0
- package/dist/src/cdp/pages.js +40 -0
- package/dist/src/cdp/serial.d.ts +1 -0
- package/dist/src/cdp/serial.js +18 -0
- package/dist/src/cdp/session.d.ts +25 -0
- package/dist/src/cdp/session.js +246 -0
- package/dist/src/cdp/snapshot-contract.d.ts +32 -0
- package/dist/src/cdp/snapshot-contract.js +23 -0
- package/dist/src/cdp/snapshot.d.ts +3 -0
- package/dist/src/cdp/snapshot.js +205 -0
- package/dist/src/cdp/types.d.ts +20 -0
- package/dist/src/cdp/types.js +14 -0
- package/dist/src/cdp/url.d.ts +1 -0
- package/dist/src/cdp/url.js +12 -0
- package/index.ts +115 -0
- package/package.json +93 -0
- package/remote-worker.ts +58 -0
- package/src/browser/artifacts.ts +178 -0
- package/src/browser/bounds.ts +159 -0
- package/src/browser/config.ts +162 -0
- package/src/browser/help.ts +30 -0
- package/src/browser/launcher.ts +208 -0
- package/src/browser/operation-executor.ts +251 -0
- package/src/browser/operation.ts +105 -0
- package/src/browser/parse-operation.ts +272 -0
- package/src/browser/remote-helper.ts +137 -0
- package/src/browser/remote-process.ts +85 -0
- package/src/browser/remote.ts +120 -0
- package/src/browser/request.ts +95 -0
- package/src/browser/routes.ts +69 -0
- package/src/browser/runtime.ts +84 -0
- package/src/browser/settings.ts +219 -0
- package/src/browser/worker-server.ts +274 -0
- package/src/browser-parameters.ts +118 -0
- package/src/browser-tool.ts +88 -0
- package/src/cdp/actions/click.ts +126 -0
- package/src/cdp/actions/element.ts +234 -0
- package/src/cdp/actions/page.ts +219 -0
- package/src/cdp/actions/screenshot.ts +176 -0
- package/src/cdp/actions/selector.ts +63 -0
- package/src/cdp/actions/type.ts +224 -0
- package/src/cdp/client.ts +286 -0
- package/src/cdp/discovery.ts +198 -0
- package/src/cdp/evaluate.ts +55 -0
- package/src/cdp/pages.ts +60 -0
- package/src/cdp/serial.ts +23 -0
- package/src/cdp/session.ts +345 -0
- package/src/cdp/snapshot-contract.ts +63 -0
- package/src/cdp/snapshot.ts +273 -0
- package/src/cdp/types.ts +49 -0
- package/src/cdp/url.ts +11 -0
- package/tsconfig.json +7 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { clickCoordinates, clickRef, clickSelector, } from "../cdp/actions/click.js";
|
|
2
|
+
import { html, htmlRef, loadAll, navigate, networkEntries, rawCommand, } from "../cdp/actions/page.js";
|
|
3
|
+
import { captureRef, captureSelector, captureViewport, } from "../cdp/actions/screenshot.js";
|
|
4
|
+
import { typeAtFocus, typeRef } from "../cdp/actions/type.js";
|
|
5
|
+
import { evaluateText } from "../cdp/evaluate.js";
|
|
6
|
+
import { BrowserCdpSession } from "../cdp/session.js";
|
|
7
|
+
import { snapshotData } from "../cdp/snapshot.js";
|
|
8
|
+
import { discardCachedResult, limitedText, readCachedResult, screenshotPath, } from "./artifacts.js";
|
|
9
|
+
import { boundSnapshot, boundTabs } from "./bounds.js";
|
|
10
|
+
import { startBrowser } from "./launcher.js";
|
|
11
|
+
export class BrowserOperationExecutor {
|
|
12
|
+
cdp;
|
|
13
|
+
constructor(cdp) {
|
|
14
|
+
this.cdp = cdp;
|
|
15
|
+
}
|
|
16
|
+
async execute(operation, signal) {
|
|
17
|
+
switch (operation.action) {
|
|
18
|
+
case "start":
|
|
19
|
+
return { result: await startBrowser(signal) };
|
|
20
|
+
case "tabs":
|
|
21
|
+
return boundTabs(await this.cdp.pages(signal), operation.query, operation.offset);
|
|
22
|
+
case "open":
|
|
23
|
+
if ("url" in operation) {
|
|
24
|
+
const opened = await this.cdp.open(operation.url, signal);
|
|
25
|
+
return {
|
|
26
|
+
ref_id: opened.refId,
|
|
27
|
+
url: operation.url,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => boundSnapshot(await snapshotData(tab.cdp, tab.sessionId, tab.elementRefs, {
|
|
31
|
+
refId: tab.refId,
|
|
32
|
+
lineno: operation.lineno,
|
|
33
|
+
responseLength: operation.response_length,
|
|
34
|
+
signal,
|
|
35
|
+
})));
|
|
36
|
+
case "find":
|
|
37
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => boundSnapshot(await snapshotData(tab.cdp, tab.sessionId, tab.elementRefs, {
|
|
38
|
+
refId: tab.refId,
|
|
39
|
+
pattern: operation.pattern,
|
|
40
|
+
lineno: operation.lineno,
|
|
41
|
+
responseLength: operation.response_length,
|
|
42
|
+
signal,
|
|
43
|
+
})));
|
|
44
|
+
case "read_result":
|
|
45
|
+
return readCachedResult(operation);
|
|
46
|
+
case "discard_result":
|
|
47
|
+
return discardCachedResult(operation.handle);
|
|
48
|
+
case "stop":
|
|
49
|
+
await this.cdp.stop(operation.ref_id);
|
|
50
|
+
return {
|
|
51
|
+
stopped: operation.ref_id ?? "all tab daemons",
|
|
52
|
+
};
|
|
53
|
+
case "screenshot":
|
|
54
|
+
return this.screenshot(operation, signal);
|
|
55
|
+
case "evaluate":
|
|
56
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => limitedText({ ref_id: tab.refId }, "value", await evaluateText(tab.cdp, tab.sessionId, operation.expression, signal)));
|
|
57
|
+
case "html":
|
|
58
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => limitedText({ ref_id: tab.refId }, "html", operation.id === undefined
|
|
59
|
+
? await html(tab.cdp, tab.sessionId, operation.selector, signal)
|
|
60
|
+
: await htmlRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, signal)));
|
|
61
|
+
case "network":
|
|
62
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => limitedText({ ref_id: tab.refId }, "entries", await networkEntries(tab.cdp, tab.sessionId, signal)));
|
|
63
|
+
case "raw":
|
|
64
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => limitedText({ ref_id: tab.refId }, "result", await rawCommand(tab.cdp, tab.sessionId, operation.method, operation.params, signal)));
|
|
65
|
+
case "navigate":
|
|
66
|
+
return this.tabResult(operation.ref_id, signal, (tab) => navigate(tab.cdp, tab.sessionId, operation.url, signal));
|
|
67
|
+
case "click":
|
|
68
|
+
return this.tabResult(operation.ref_id, signal, (tab) => {
|
|
69
|
+
if (operation.id !== undefined) {
|
|
70
|
+
return clickRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, signal);
|
|
71
|
+
}
|
|
72
|
+
if (operation.selector) {
|
|
73
|
+
return clickSelector(tab.cdp, tab.sessionId, operation.selector, signal);
|
|
74
|
+
}
|
|
75
|
+
if (operation.x === undefined || operation.y === undefined) {
|
|
76
|
+
throw new Error("click requires id, selector, or x+y");
|
|
77
|
+
}
|
|
78
|
+
return clickCoordinates(tab.cdp, tab.sessionId, operation.x, operation.y, signal);
|
|
79
|
+
});
|
|
80
|
+
case "type":
|
|
81
|
+
return this.tabResult(operation.ref_id, signal, (tab) => operation.id === undefined
|
|
82
|
+
? typeAtFocus(tab.cdp, tab.sessionId, operation.text, signal)
|
|
83
|
+
: typeRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, operation.text, signal));
|
|
84
|
+
case "load_all":
|
|
85
|
+
return this.tabResult(operation.ref_id, signal, (tab) => loadAll(tab.cdp, tab.sessionId, operation.selector, operation.interval_ms, signal));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async screenshot(operation, signal) {
|
|
89
|
+
const file = await screenshotPath(operation);
|
|
90
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => {
|
|
91
|
+
const capture = operation.id !== undefined
|
|
92
|
+
? await captureRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, file, signal)
|
|
93
|
+
: operation.selector
|
|
94
|
+
? await captureSelector(tab.cdp, tab.sessionId, operation.selector, file, signal)
|
|
95
|
+
: await captureViewport(tab.cdp, tab.sessionId, file, signal);
|
|
96
|
+
return {
|
|
97
|
+
ref_id: tab.refId,
|
|
98
|
+
...(operation.id === undefined ? {} : { id: operation.id }),
|
|
99
|
+
...(operation.selector ? { selector: operation.selector } : {}),
|
|
100
|
+
file: capture.file,
|
|
101
|
+
dpr: capture.dpr,
|
|
102
|
+
coordinates: "CSS pixels; screenshot pixels / DPR",
|
|
103
|
+
};
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
async tabResult(refId, signal, action) {
|
|
107
|
+
return this.cdp.withTab(refId, signal, async (tab) => ({
|
|
108
|
+
ref_id: tab.refId,
|
|
109
|
+
result: (await action(tab)) || "ok",
|
|
110
|
+
}));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
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")[];
|
|
4
|
+
export type BrowserAction = (typeof BROWSER_ACTIONS)[number];
|
|
5
|
+
export type BrowserOperation = {
|
|
6
|
+
action: "start";
|
|
7
|
+
} | {
|
|
8
|
+
action: "tabs";
|
|
9
|
+
query?: string | undefined;
|
|
10
|
+
offset: number;
|
|
11
|
+
} | {
|
|
12
|
+
action: "open";
|
|
13
|
+
ref_id: string;
|
|
14
|
+
lineno: number;
|
|
15
|
+
response_length: SnapshotResponseLength;
|
|
16
|
+
} | {
|
|
17
|
+
action: "open";
|
|
18
|
+
url: string;
|
|
19
|
+
} | {
|
|
20
|
+
action: "find";
|
|
21
|
+
ref_id: string;
|
|
22
|
+
pattern: string;
|
|
23
|
+
lineno: number;
|
|
24
|
+
response_length: SnapshotResponseLength;
|
|
25
|
+
} | {
|
|
26
|
+
action: "click";
|
|
27
|
+
ref_id: string;
|
|
28
|
+
id: number;
|
|
29
|
+
selector?: never;
|
|
30
|
+
x?: never;
|
|
31
|
+
y?: never;
|
|
32
|
+
} | {
|
|
33
|
+
action: "click";
|
|
34
|
+
ref_id: string;
|
|
35
|
+
id?: never;
|
|
36
|
+
selector: string;
|
|
37
|
+
x?: never;
|
|
38
|
+
y?: never;
|
|
39
|
+
} | {
|
|
40
|
+
action: "click";
|
|
41
|
+
ref_id: string;
|
|
42
|
+
id?: never;
|
|
43
|
+
selector?: never;
|
|
44
|
+
x: number;
|
|
45
|
+
y: number;
|
|
46
|
+
} | {
|
|
47
|
+
action: "type";
|
|
48
|
+
ref_id: string;
|
|
49
|
+
id?: number | undefined;
|
|
50
|
+
text: string;
|
|
51
|
+
} | {
|
|
52
|
+
action: "screenshot";
|
|
53
|
+
ref_id: string;
|
|
54
|
+
id?: number | undefined;
|
|
55
|
+
selector?: string | undefined;
|
|
56
|
+
} | {
|
|
57
|
+
action: "html";
|
|
58
|
+
ref_id: string;
|
|
59
|
+
id?: number | undefined;
|
|
60
|
+
selector?: string | undefined;
|
|
61
|
+
} | {
|
|
62
|
+
action: "navigate";
|
|
63
|
+
ref_id: string;
|
|
64
|
+
url: string;
|
|
65
|
+
} | {
|
|
66
|
+
action: "evaluate";
|
|
67
|
+
ref_id: string;
|
|
68
|
+
expression: string;
|
|
69
|
+
} | {
|
|
70
|
+
action: "network";
|
|
71
|
+
ref_id: string;
|
|
72
|
+
} | {
|
|
73
|
+
action: "load_all";
|
|
74
|
+
ref_id: string;
|
|
75
|
+
selector: string;
|
|
76
|
+
interval_ms: number;
|
|
77
|
+
} | {
|
|
78
|
+
action: "raw";
|
|
79
|
+
ref_id: string;
|
|
80
|
+
method: string;
|
|
81
|
+
params: Record<string, unknown>;
|
|
82
|
+
} | {
|
|
83
|
+
action: "read_result";
|
|
84
|
+
handle: string;
|
|
85
|
+
offset: number;
|
|
86
|
+
} | {
|
|
87
|
+
action: "discard_result";
|
|
88
|
+
handle: string;
|
|
89
|
+
} | {
|
|
90
|
+
action: "stop";
|
|
91
|
+
ref_id?: string | undefined;
|
|
92
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export const BROWSER_ACTIONS = [
|
|
2
|
+
"help",
|
|
3
|
+
"start",
|
|
4
|
+
"tabs",
|
|
5
|
+
"open",
|
|
6
|
+
"find",
|
|
7
|
+
"click",
|
|
8
|
+
"type",
|
|
9
|
+
"screenshot",
|
|
10
|
+
"html",
|
|
11
|
+
"navigate",
|
|
12
|
+
"evaluate",
|
|
13
|
+
"network",
|
|
14
|
+
"load_all",
|
|
15
|
+
"raw",
|
|
16
|
+
"read_result",
|
|
17
|
+
"discard_result",
|
|
18
|
+
"stop",
|
|
19
|
+
];
|
|
20
|
+
export const OPERATION_ORDER = BROWSER_ACTIONS.filter((action) => action !== "help");
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type BrowserOperation } from "./operation.js";
|
|
2
|
+
export type ActionRequest = BrowserOperation | {
|
|
3
|
+
action: "help";
|
|
4
|
+
};
|
|
5
|
+
export declare function parseActionRequest(value: unknown): ActionRequest;
|
|
6
|
+
export declare function isRecordValue(value: unknown): value is Record<string, unknown>;
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { BROWSER_ACTIONS, } from "./operation.js";
|
|
2
|
+
const fields = (...names) => new Set(["action", ...names]);
|
|
3
|
+
const ACTION_FIELDS = {
|
|
4
|
+
help: fields(),
|
|
5
|
+
start: fields(),
|
|
6
|
+
tabs: fields("query", "offset"),
|
|
7
|
+
open: fields("ref_id", "url", "lineno", "response_length"),
|
|
8
|
+
find: fields("ref_id", "pattern", "lineno", "response_length"),
|
|
9
|
+
click: fields("ref_id", "id", "selector", "x", "y"),
|
|
10
|
+
type: fields("ref_id", "id", "text"),
|
|
11
|
+
screenshot: fields("ref_id", "id", "selector"),
|
|
12
|
+
html: fields("ref_id", "id", "selector"),
|
|
13
|
+
navigate: fields("ref_id", "url"),
|
|
14
|
+
evaluate: fields("ref_id", "expression"),
|
|
15
|
+
network: fields("ref_id"),
|
|
16
|
+
load_all: fields("ref_id", "selector", "interval_ms"),
|
|
17
|
+
raw: fields("ref_id", "method", "params"),
|
|
18
|
+
read_result: fields("handle", "offset"),
|
|
19
|
+
discard_result: fields("handle"),
|
|
20
|
+
stop: fields("ref_id"),
|
|
21
|
+
};
|
|
22
|
+
function isRecord(value) {
|
|
23
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24
|
+
}
|
|
25
|
+
function requiredString(value, field) {
|
|
26
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
27
|
+
throw new Error(`${field} must be a non-empty string`);
|
|
28
|
+
}
|
|
29
|
+
return value.trim();
|
|
30
|
+
}
|
|
31
|
+
function optionalString(value, field) {
|
|
32
|
+
if (value === undefined)
|
|
33
|
+
return undefined;
|
|
34
|
+
return requiredString(value, field);
|
|
35
|
+
}
|
|
36
|
+
function requiredRef(value, action) {
|
|
37
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
38
|
+
throw new Error(`${action} requires a ref_id returned by tabs; call tabs first`);
|
|
39
|
+
}
|
|
40
|
+
return value.trim();
|
|
41
|
+
}
|
|
42
|
+
function offset(value, field = "offset", fallback = 0) {
|
|
43
|
+
if (value === undefined)
|
|
44
|
+
return fallback;
|
|
45
|
+
if (!Number.isInteger(value) || Number(value) < 0) {
|
|
46
|
+
throw new Error(`${field} must be a non-negative integer`);
|
|
47
|
+
}
|
|
48
|
+
return Number(value);
|
|
49
|
+
}
|
|
50
|
+
function line(value) {
|
|
51
|
+
const parsed = offset(value, "lineno", 1);
|
|
52
|
+
if (parsed < 1)
|
|
53
|
+
throw new Error("lineno must be at least 1");
|
|
54
|
+
return parsed;
|
|
55
|
+
}
|
|
56
|
+
function elementId(value) {
|
|
57
|
+
if (value === undefined)
|
|
58
|
+
return undefined;
|
|
59
|
+
if (!Number.isInteger(value) || Number(value) < 1) {
|
|
60
|
+
throw new Error("id must be a positive integer from open/find");
|
|
61
|
+
}
|
|
62
|
+
return Number(value);
|
|
63
|
+
}
|
|
64
|
+
function responseLength(value) {
|
|
65
|
+
if (value === undefined)
|
|
66
|
+
return "medium";
|
|
67
|
+
if (value !== "short" && value !== "medium" && value !== "long") {
|
|
68
|
+
throw new Error("response_length must be one of: short, medium, long");
|
|
69
|
+
}
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
function resultHandle(value) {
|
|
73
|
+
const handle = requiredString(value, "handle");
|
|
74
|
+
if (!/^[a-f0-9-]{36}$/.test(handle)) {
|
|
75
|
+
throw new Error("handle is invalid");
|
|
76
|
+
}
|
|
77
|
+
return handle;
|
|
78
|
+
}
|
|
79
|
+
function browserAction(value) {
|
|
80
|
+
if (typeof value !== "string" ||
|
|
81
|
+
!BROWSER_ACTIONS.includes(value)) {
|
|
82
|
+
throw new Error(`action must be one of: ${BROWSER_ACTIONS.join(", ")}`);
|
|
83
|
+
}
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
export function parseActionRequest(value) {
|
|
87
|
+
if (!isRecord(value))
|
|
88
|
+
throw new Error("input must be a JSON object");
|
|
89
|
+
const action = browserAction(value["action"]);
|
|
90
|
+
const unknown = Object.keys(value).filter((key) => !ACTION_FIELDS[action].has(key));
|
|
91
|
+
if (unknown.length > 0) {
|
|
92
|
+
throw new Error(`unknown ${action} field(s): ${unknown.join(", ")}`);
|
|
93
|
+
}
|
|
94
|
+
if (action === "help" || action === "start")
|
|
95
|
+
return { action };
|
|
96
|
+
if (action === "tabs") {
|
|
97
|
+
const query = optionalString(value["query"], "query");
|
|
98
|
+
return {
|
|
99
|
+
action,
|
|
100
|
+
...(query ? { query } : {}),
|
|
101
|
+
offset: offset(value["offset"]),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
if (action === "open") {
|
|
105
|
+
const refId = optionalString(value["ref_id"], "ref_id");
|
|
106
|
+
const url = optionalString(value["url"], "url");
|
|
107
|
+
if (Boolean(refId) === Boolean(url)) {
|
|
108
|
+
throw new Error("open requires exactly one of ref_id or url");
|
|
109
|
+
}
|
|
110
|
+
if (url)
|
|
111
|
+
return { action, url };
|
|
112
|
+
if (!refId)
|
|
113
|
+
throw new Error("open requires ref_id or url");
|
|
114
|
+
return {
|
|
115
|
+
action,
|
|
116
|
+
ref_id: refId,
|
|
117
|
+
lineno: line(value["lineno"]),
|
|
118
|
+
response_length: responseLength(value["response_length"]),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
if (action === "find") {
|
|
122
|
+
return {
|
|
123
|
+
action,
|
|
124
|
+
ref_id: requiredRef(value["ref_id"], action),
|
|
125
|
+
pattern: requiredString(value["pattern"], "pattern"),
|
|
126
|
+
lineno: line(value["lineno"]),
|
|
127
|
+
response_length: responseLength(value["response_length"]),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
if (action === "read_result") {
|
|
131
|
+
return {
|
|
132
|
+
action,
|
|
133
|
+
handle: resultHandle(value["handle"]),
|
|
134
|
+
offset: offset(value["offset"]),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
if (action === "discard_result") {
|
|
138
|
+
return { action, handle: resultHandle(value["handle"]) };
|
|
139
|
+
}
|
|
140
|
+
if (action === "stop") {
|
|
141
|
+
const refId = optionalString(value["ref_id"], "ref_id");
|
|
142
|
+
return { action, ...(refId ? { ref_id: refId } : {}) };
|
|
143
|
+
}
|
|
144
|
+
const refId = requiredRef(value["ref_id"], action);
|
|
145
|
+
if (action === "network")
|
|
146
|
+
return { action, ref_id: refId };
|
|
147
|
+
if (action === "navigate") {
|
|
148
|
+
return {
|
|
149
|
+
action,
|
|
150
|
+
ref_id: refId,
|
|
151
|
+
url: requiredString(value["url"], "url"),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
if (action === "evaluate") {
|
|
155
|
+
return {
|
|
156
|
+
action,
|
|
157
|
+
ref_id: refId,
|
|
158
|
+
expression: requiredString(value["expression"], "expression"),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
if (action === "click") {
|
|
162
|
+
const id = elementId(value["id"]);
|
|
163
|
+
const selector = optionalString(value["selector"], "selector");
|
|
164
|
+
const hasX = value["x"] !== undefined;
|
|
165
|
+
const hasY = value["y"] !== undefined;
|
|
166
|
+
let coordinates;
|
|
167
|
+
if (hasX !== hasY) {
|
|
168
|
+
throw new Error("click coordinates require both x and y");
|
|
169
|
+
}
|
|
170
|
+
if (hasX &&
|
|
171
|
+
(typeof value["x"] !== "number" ||
|
|
172
|
+
!Number.isFinite(value["x"]) ||
|
|
173
|
+
typeof value["y"] !== "number" ||
|
|
174
|
+
!Number.isFinite(value["y"]))) {
|
|
175
|
+
throw new Error("x and y must be finite CSS-pixel numbers");
|
|
176
|
+
}
|
|
177
|
+
if (typeof value["x"] === "number" && typeof value["y"] === "number") {
|
|
178
|
+
coordinates = { x: value["x"], y: value["y"] };
|
|
179
|
+
}
|
|
180
|
+
if (Number(id !== undefined) + Number(Boolean(selector)) + Number(hasX) !==
|
|
181
|
+
1) {
|
|
182
|
+
throw new Error("click requires exactly one of id, selector, or x+y");
|
|
183
|
+
}
|
|
184
|
+
if (id !== undefined)
|
|
185
|
+
return { action, ref_id: refId, id };
|
|
186
|
+
if (selector)
|
|
187
|
+
return { action, ref_id: refId, selector };
|
|
188
|
+
if (coordinates) {
|
|
189
|
+
return { action, ref_id: refId, ...coordinates };
|
|
190
|
+
}
|
|
191
|
+
throw new Error("click requires id, selector, or x+y");
|
|
192
|
+
}
|
|
193
|
+
if (action === "type") {
|
|
194
|
+
if (typeof value["text"] !== "string" || value["text"].length === 0) {
|
|
195
|
+
throw new Error("text must be a non-empty string");
|
|
196
|
+
}
|
|
197
|
+
const id = elementId(value["id"]);
|
|
198
|
+
return {
|
|
199
|
+
action,
|
|
200
|
+
ref_id: refId,
|
|
201
|
+
...(id === undefined ? {} : { id }),
|
|
202
|
+
text: value["text"],
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
if (action === "screenshot" || action === "html") {
|
|
206
|
+
const id = elementId(value["id"]);
|
|
207
|
+
const selector = optionalString(value["selector"], "selector");
|
|
208
|
+
if (id !== undefined && selector) {
|
|
209
|
+
throw new Error(`${action} accepts id or selector, not both`);
|
|
210
|
+
}
|
|
211
|
+
return {
|
|
212
|
+
action,
|
|
213
|
+
ref_id: refId,
|
|
214
|
+
...(id === undefined ? {} : { id }),
|
|
215
|
+
...(selector ? { selector } : {}),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
if (action === "load_all") {
|
|
219
|
+
const interval = value["interval_ms"] ?? 1_500;
|
|
220
|
+
if (!Number.isInteger(interval) ||
|
|
221
|
+
Number(interval) < 0 ||
|
|
222
|
+
Number(interval) > 60_000) {
|
|
223
|
+
throw new Error("interval_ms must be an integer from 0 to 60000");
|
|
224
|
+
}
|
|
225
|
+
return {
|
|
226
|
+
action,
|
|
227
|
+
ref_id: refId,
|
|
228
|
+
selector: requiredString(value["selector"], "selector"),
|
|
229
|
+
interval_ms: Number(interval),
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
if (action === "raw") {
|
|
233
|
+
const params = value["params"] ?? {};
|
|
234
|
+
if (!isRecord(params)) {
|
|
235
|
+
throw new Error("params must be an object when provided");
|
|
236
|
+
}
|
|
237
|
+
return {
|
|
238
|
+
action,
|
|
239
|
+
ref_id: refId,
|
|
240
|
+
method: requiredString(value["method"], "method"),
|
|
241
|
+
params,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
throw new Error(`unsupported action: ${action}`);
|
|
245
|
+
}
|
|
246
|
+
export function isRecordValue(value) {
|
|
247
|
+
return isRecord(value);
|
|
248
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { abortReason, runProgram } from "./remote-process.js";
|
|
4
|
+
const DEPLOY_TIMEOUT_MS = 20_000;
|
|
5
|
+
const REMOTE_HELPER = "~/.pi/agent/pi-browser-worker.mjs";
|
|
6
|
+
const deployments = new Map();
|
|
7
|
+
let helperSourcePromise;
|
|
8
|
+
const DEPLOY_SOURCE = String.raw `
|
|
9
|
+
const { randomUUID } = require("node:crypto");
|
|
10
|
+
const { mkdir, readFile, rename, unlink, writeFile } = require("node:fs/promises");
|
|
11
|
+
const { homedir } = require("node:os");
|
|
12
|
+
const { dirname, join } = require("node:path");
|
|
13
|
+
const targetValue = process.argv[1];
|
|
14
|
+
const marker = "// @howaboua/pi-browser managed worker";
|
|
15
|
+
const target = targetValue === "~" ? homedir() : targetValue.startsWith("~/") ? join(homedir(), targetValue.slice(2)) : targetValue;
|
|
16
|
+
const chunks = [];
|
|
17
|
+
let size = 0;
|
|
18
|
+
process.stdin.on("data", chunk => { size += chunk.length; if (size > 4 * 1024 * 1024) { process.stderr.write("worker source is too large\n"); process.exit(1); } chunks.push(chunk); });
|
|
19
|
+
process.stdin.on("end", () => { void (async () => {
|
|
20
|
+
const source = Buffer.concat(chunks);
|
|
21
|
+
let existing;
|
|
22
|
+
try { existing = await readFile(target); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
23
|
+
if (existing) {
|
|
24
|
+
if (existing.equals(source)) { process.stdout.write(JSON.stringify({ updated: false, path: target }) + "\n"); return; }
|
|
25
|
+
if (!existing.toString("utf8", 0, 512).includes(marker)) throw new Error(target + " is not owned by pi-browser");
|
|
26
|
+
}
|
|
27
|
+
await mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
28
|
+
const temporary = target + "." + process.pid + "." + randomUUID() + ".tmp";
|
|
29
|
+
try {
|
|
30
|
+
await writeFile(temporary, source, { mode: 0o600, flag: "wx" });
|
|
31
|
+
await rename(temporary, target);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
await unlink(temporary).catch(() => undefined);
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
process.stdout.write(JSON.stringify({ updated: true, path: target }) + "\n");
|
|
37
|
+
})().catch(error => { process.stderr.write(error.message + "\n"); process.exit(1); }); });
|
|
38
|
+
`;
|
|
39
|
+
export function remoteNodeCommand(command) {
|
|
40
|
+
return `${command.nodePath} --preserve-symlinks-main "$HOME"/.pi/agent/pi-browser-worker.mjs`;
|
|
41
|
+
}
|
|
42
|
+
function shellQuote(value) {
|
|
43
|
+
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
44
|
+
}
|
|
45
|
+
function waitFor(promise, signal) {
|
|
46
|
+
if (!signal)
|
|
47
|
+
return promise;
|
|
48
|
+
if (signal.aborted)
|
|
49
|
+
return Promise.reject(abortReason(signal));
|
|
50
|
+
return new Promise((resolveValue, reject) => {
|
|
51
|
+
const abort = () => {
|
|
52
|
+
cleanup();
|
|
53
|
+
reject(abortReason(signal));
|
|
54
|
+
};
|
|
55
|
+
const cleanup = () => signal.removeEventListener("abort", abort);
|
|
56
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
57
|
+
promise.then((value) => {
|
|
58
|
+
cleanup();
|
|
59
|
+
resolveValue(value);
|
|
60
|
+
}, (error) => {
|
|
61
|
+
cleanup();
|
|
62
|
+
reject(error);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
async function readHelperSource() {
|
|
67
|
+
const candidates = [
|
|
68
|
+
fileURLToPath(new URL("../../remote-worker.js", import.meta.url)),
|
|
69
|
+
fileURLToPath(new URL("../../dist/remote-worker.js", import.meta.url)),
|
|
70
|
+
];
|
|
71
|
+
let lastError;
|
|
72
|
+
for (const path of candidates) {
|
|
73
|
+
try {
|
|
74
|
+
return await readFile(path, "utf8");
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
lastError = error;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
throw new Error(`Could not read bundled browser worker: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
|
|
81
|
+
}
|
|
82
|
+
async function deployRemoteHelper(host, command) {
|
|
83
|
+
helperSourcePromise ??= readHelperSource();
|
|
84
|
+
let source;
|
|
85
|
+
try {
|
|
86
|
+
source = await helperSourcePromise;
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
helperSourcePromise = undefined;
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
const deployment = await runProgram("ssh", [
|
|
93
|
+
host,
|
|
94
|
+
`${command.nodePath} -e ${shellQuote(DEPLOY_SOURCE)} ${shellQuote(REMOTE_HELPER)}`,
|
|
95
|
+
], source, AbortSignal.timeout(DEPLOY_TIMEOUT_MS));
|
|
96
|
+
if (deployment.code !== 0) {
|
|
97
|
+
throw new Error(deployment.stderr ||
|
|
98
|
+
deployment.stdout ||
|
|
99
|
+
"could not deploy remote browser worker");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
export async function ensureRemoteHelper(host, command, signal) {
|
|
103
|
+
const key = `${host}\0${command.nodePath}`;
|
|
104
|
+
let deployment = deployments.get(key);
|
|
105
|
+
if (!deployment) {
|
|
106
|
+
deployment = deployRemoteHelper(host, command);
|
|
107
|
+
deployments.set(key, deployment);
|
|
108
|
+
void deployment.catch(() => {
|
|
109
|
+
if (deployments.get(key) === deployment)
|
|
110
|
+
deployments.delete(key);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
await waitFor(deployment, signal);
|
|
114
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface ProcessResult {
|
|
2
|
+
code: number;
|
|
3
|
+
stderr: string;
|
|
4
|
+
stdout: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function abortReason(signal: AbortSignal): Error;
|
|
7
|
+
export declare function runProgram(command: string, args: string[], input: string | undefined, signal?: AbortSignal): Promise<ProcessResult>;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { StringDecoder } from "node:string_decoder";
|
|
3
|
+
const OUTPUT_LIMIT_BYTES = 8 * 1_024 * 1_024;
|
|
4
|
+
export function abortReason(signal) {
|
|
5
|
+
return signal.reason instanceof Error
|
|
6
|
+
? signal.reason
|
|
7
|
+
: new Error("Remote browser operation aborted");
|
|
8
|
+
}
|
|
9
|
+
export function runProgram(command, args, input, signal) {
|
|
10
|
+
if (signal?.aborted)
|
|
11
|
+
return Promise.reject(abortReason(signal));
|
|
12
|
+
return new Promise((resolveValue, reject) => {
|
|
13
|
+
const child = spawn(command, args, {
|
|
14
|
+
stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
|
|
15
|
+
});
|
|
16
|
+
let stdout = "";
|
|
17
|
+
let stderr = "";
|
|
18
|
+
const stdoutDecoder = new StringDecoder("utf8");
|
|
19
|
+
const stderrDecoder = new StringDecoder("utf8");
|
|
20
|
+
let bytes = 0;
|
|
21
|
+
let settled = false;
|
|
22
|
+
let killTimer;
|
|
23
|
+
const running = () => child.exitCode === null && child.signalCode === null;
|
|
24
|
+
const cleanup = () => {
|
|
25
|
+
if (killTimer)
|
|
26
|
+
clearTimeout(killTimer);
|
|
27
|
+
signal?.removeEventListener("abort", abort);
|
|
28
|
+
};
|
|
29
|
+
const finish = (action) => {
|
|
30
|
+
if (settled)
|
|
31
|
+
return;
|
|
32
|
+
settled = true;
|
|
33
|
+
cleanup();
|
|
34
|
+
action();
|
|
35
|
+
};
|
|
36
|
+
const abort = () => {
|
|
37
|
+
if (running())
|
|
38
|
+
child.kill("SIGTERM");
|
|
39
|
+
killTimer = setTimeout(() => {
|
|
40
|
+
if (running())
|
|
41
|
+
child.kill("SIGKILL");
|
|
42
|
+
}, 1_000);
|
|
43
|
+
killTimer.unref?.();
|
|
44
|
+
};
|
|
45
|
+
const append = (target, chunk) => {
|
|
46
|
+
bytes += chunk.length;
|
|
47
|
+
if (bytes > OUTPUT_LIMIT_BYTES) {
|
|
48
|
+
if (running())
|
|
49
|
+
child.kill("SIGKILL");
|
|
50
|
+
finish(() => reject(new Error("Remote browser output exceeded 8 MiB")));
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (target === "stdout")
|
|
54
|
+
stdout += stdoutDecoder.write(chunk);
|
|
55
|
+
else
|
|
56
|
+
stderr += stderrDecoder.write(chunk);
|
|
57
|
+
};
|
|
58
|
+
child.stdout?.on("data", (chunk) => append("stdout", chunk));
|
|
59
|
+
child.stderr?.on("data", (chunk) => append("stderr", chunk));
|
|
60
|
+
child.on("error", (error) => finish(() => reject(error)));
|
|
61
|
+
child.on("close", (code) => finish(() => {
|
|
62
|
+
stdout += stdoutDecoder.end();
|
|
63
|
+
stderr += stderrDecoder.end();
|
|
64
|
+
if (signal?.aborted) {
|
|
65
|
+
reject(abortReason(signal));
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
resolveValue({
|
|
69
|
+
code: code ?? 1,
|
|
70
|
+
stderr: stderr.trim(),
|
|
71
|
+
stdout: stdout.trim(),
|
|
72
|
+
});
|
|
73
|
+
}));
|
|
74
|
+
if (input !== undefined)
|
|
75
|
+
child.stdin?.end(input);
|
|
76
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
77
|
+
});
|
|
78
|
+
}
|