@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
package/dist/src/cdp/session.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { CdpClient } from "./client.js";
|
|
2
2
|
import { getDisplayPrefixLength, getWebSocketUrl, resolvePrefix, } from "./discovery.js";
|
|
3
|
-
import { getPages, waitForOpenedTarget } from "./pages.js";
|
|
4
3
|
import { waitForTurn } from "./serial.js";
|
|
4
|
+
import { BrowserTabs } from "./tabs.js";
|
|
5
5
|
import { asRecord } from "./types.js";
|
|
6
|
-
import { assertHttpUrl } from "./url.js";
|
|
7
6
|
const TAB_IDLE_MS = 20 * 60 * 1_000;
|
|
8
7
|
class TabBridge {
|
|
9
8
|
elementRefs = new Map();
|
|
@@ -13,6 +12,7 @@ class TabBridge {
|
|
|
13
12
|
tail = Promise.resolve();
|
|
14
13
|
idleTimer;
|
|
15
14
|
closed = false;
|
|
15
|
+
backgroundRendering = false;
|
|
16
16
|
onClose;
|
|
17
17
|
constructor(targetId, cdp, sessionId, onClose) {
|
|
18
18
|
this.targetId = targetId;
|
|
@@ -72,6 +72,15 @@ class TabBridge {
|
|
|
72
72
|
release();
|
|
73
73
|
}
|
|
74
74
|
}
|
|
75
|
+
async setBackgroundRendering(enabled, signal) {
|
|
76
|
+
if (this.backgroundRendering === enabled)
|
|
77
|
+
return;
|
|
78
|
+
// An interrupted command may already have applied. Keep the state unknown
|
|
79
|
+
// until Chrome acknowledges it, so the next action reestablishes it.
|
|
80
|
+
this.backgroundRendering = undefined;
|
|
81
|
+
await this.cdp.send("Emulation.setFocusEmulationEnabled", { enabled }, this.sessionId, signal);
|
|
82
|
+
this.backgroundRendering = enabled;
|
|
83
|
+
}
|
|
75
84
|
close(detach = true) {
|
|
76
85
|
if (this.closed)
|
|
77
86
|
return;
|
|
@@ -98,29 +107,38 @@ class TabBridge {
|
|
|
98
107
|
}
|
|
99
108
|
}
|
|
100
109
|
export class BrowserCdpSession {
|
|
110
|
+
closing;
|
|
101
111
|
root;
|
|
102
112
|
rootPending;
|
|
113
|
+
ownerId;
|
|
114
|
+
ownershipDirectory;
|
|
103
115
|
tabs = new Map();
|
|
104
116
|
tabPromises = new Map();
|
|
117
|
+
constructor(ownerId, ownershipDirectory) {
|
|
118
|
+
this.ownerId = ownerId;
|
|
119
|
+
this.ownershipDirectory = ownershipDirectory;
|
|
120
|
+
}
|
|
105
121
|
async pages(signal) {
|
|
106
|
-
return
|
|
122
|
+
return (await this.rootConnection(signal)).tabs.list(signal);
|
|
107
123
|
}
|
|
108
124
|
async open(url, signal) {
|
|
109
|
-
|
|
125
|
+
return (await this.rootConnection(signal)).tabs.open(url, signal);
|
|
126
|
+
}
|
|
127
|
+
async show(refId, signal) {
|
|
128
|
+
return (await this.rootConnection(signal)).tabs.show(refId, signal);
|
|
129
|
+
}
|
|
130
|
+
async closeTab(refId, signal) {
|
|
110
131
|
const root = await this.rootConnection(signal);
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
return {
|
|
122
|
-
refId: page.targetId.slice(0, prefixLength),
|
|
123
|
-
};
|
|
132
|
+
const resolved = await root.tabs.resolve(refId, signal);
|
|
133
|
+
const targetId = resolved.page.targetId;
|
|
134
|
+
this.stopPendingTab(targetId, "Tab is closing");
|
|
135
|
+
const bridge = this.tabs.get(targetId);
|
|
136
|
+
const close = () => root.tabs.close(targetId, signal);
|
|
137
|
+
const closed = bridge
|
|
138
|
+
? await bridge.run(resolved.refId, signal, close)
|
|
139
|
+
: await close();
|
|
140
|
+
bridge?.close(false);
|
|
141
|
+
return closed.refId;
|
|
124
142
|
}
|
|
125
143
|
async withTab(refId, signal, action) {
|
|
126
144
|
const pages = await this.pages(signal);
|
|
@@ -157,7 +175,12 @@ export class BrowserCdpSession {
|
|
|
157
175
|
}
|
|
158
176
|
}
|
|
159
177
|
const prefixLength = getDisplayPrefixLength(pages.map((page) => page.targetId));
|
|
160
|
-
|
|
178
|
+
const owned = pages.some((page) => page.targetId === targetId && page.owned === true);
|
|
179
|
+
const current = bridge;
|
|
180
|
+
return current.run(targetId.slice(0, prefixLength), signal, async (tab) => {
|
|
181
|
+
await current.setBackgroundRendering(owned, signal);
|
|
182
|
+
return action(tab);
|
|
183
|
+
});
|
|
161
184
|
}
|
|
162
185
|
async stop(refId) {
|
|
163
186
|
if (!refId) {
|
|
@@ -176,6 +199,8 @@ export class BrowserCdpSession {
|
|
|
176
199
|
this.tabs.delete(targetId);
|
|
177
200
|
}
|
|
178
201
|
close() {
|
|
202
|
+
if (this.closing)
|
|
203
|
+
return this.closing;
|
|
179
204
|
for (const targetId of this.tabPromises.keys()) {
|
|
180
205
|
this.stopPendingTab(targetId, "Browser session closed");
|
|
181
206
|
}
|
|
@@ -184,14 +209,27 @@ export class BrowserCdpSession {
|
|
|
184
209
|
this.tabs.clear();
|
|
185
210
|
const rootPending = this.rootPending;
|
|
186
211
|
this.rootPending = undefined;
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
void rootPending.promise.then((client) => client.close(), () => undefined);
|
|
190
|
-
}
|
|
191
|
-
this.root?.close();
|
|
212
|
+
rootPending?.controller.abort(new Error("Browser session closed"));
|
|
213
|
+
const root = this.root;
|
|
192
214
|
this.root = undefined;
|
|
215
|
+
this.closing = (async () => {
|
|
216
|
+
const connected = await rootPending?.promise.catch(() => undefined);
|
|
217
|
+
for (const connection of new Set([root, connected])) {
|
|
218
|
+
if (!connection)
|
|
219
|
+
continue;
|
|
220
|
+
try {
|
|
221
|
+
await connection.tabs.shutdown();
|
|
222
|
+
}
|
|
223
|
+
finally {
|
|
224
|
+
connection.cdp.close();
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
})();
|
|
228
|
+
return this.closing;
|
|
193
229
|
}
|
|
194
230
|
async rootConnection(signal) {
|
|
231
|
+
if (this.closing)
|
|
232
|
+
throw new Error("Browser session closed");
|
|
195
233
|
if (this.root)
|
|
196
234
|
return this.root;
|
|
197
235
|
let pending = this.rootPending;
|
|
@@ -234,13 +272,27 @@ export class BrowserCdpSession {
|
|
|
234
272
|
}
|
|
235
273
|
async connectRoot(signal) {
|
|
236
274
|
const client = new CdpClient();
|
|
237
|
-
|
|
238
|
-
|
|
275
|
+
const url = await getWebSocketUrl();
|
|
276
|
+
try {
|
|
277
|
+
await client.connect(url, signal);
|
|
278
|
+
signal.throwIfAborted();
|
|
279
|
+
if (this.closing)
|
|
280
|
+
throw new Error("Browser session closed");
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
client.close();
|
|
284
|
+
throw error;
|
|
285
|
+
}
|
|
286
|
+
const connection = {
|
|
287
|
+
cdp: client,
|
|
288
|
+
tabs: new BrowserTabs(client, this.ownerId, this.ownershipDirectory, url),
|
|
289
|
+
};
|
|
290
|
+
this.root = connection;
|
|
239
291
|
client.onClose(() => {
|
|
240
|
-
if (this.root !==
|
|
292
|
+
if (this.root !== connection)
|
|
241
293
|
return;
|
|
242
294
|
this.root = undefined;
|
|
243
295
|
});
|
|
244
|
-
return
|
|
296
|
+
return connection;
|
|
245
297
|
}
|
|
246
298
|
}
|
|
@@ -10,6 +10,10 @@ export interface SnapshotElement {
|
|
|
10
10
|
role: string;
|
|
11
11
|
name?: string | undefined;
|
|
12
12
|
value?: unknown;
|
|
13
|
+
checked?: boolean | "mixed" | undefined;
|
|
14
|
+
selected?: boolean | undefined;
|
|
15
|
+
expanded?: boolean | undefined;
|
|
16
|
+
disabled?: boolean | undefined;
|
|
13
17
|
}
|
|
14
18
|
export interface SnapshotResult {
|
|
15
19
|
ref_id?: string | undefined;
|
package/dist/src/cdp/snapshot.js
CHANGED
|
@@ -21,6 +21,16 @@ const INTERACTIVE_ROLES = new Set([
|
|
|
21
21
|
"treeitem",
|
|
22
22
|
]);
|
|
23
23
|
const NEXT_ELEMENT_IDS = new WeakMap();
|
|
24
|
+
function axProperty(value) {
|
|
25
|
+
const record = asRecord(value, "accessibility property");
|
|
26
|
+
if (typeof record["name"] !== "string") {
|
|
27
|
+
throw new Error("Accessibility property has no name");
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
name: record["name"],
|
|
31
|
+
...(record["value"] ? { value: asRecord(record["value"]) } : {}),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
24
34
|
function axNode(value) {
|
|
25
35
|
const record = asRecord(value, "accessibility node");
|
|
26
36
|
if (typeof record["nodeId"] !== "string") {
|
|
@@ -45,6 +55,9 @@ function axNode(value) {
|
|
|
45
55
|
...(record["role"] ? { role: asRecord(record["role"]) } : {}),
|
|
46
56
|
...(record["name"] ? { name: asRecord(record["name"]) } : {}),
|
|
47
57
|
...(record["value"] ? { value: asRecord(record["value"]) } : {}),
|
|
58
|
+
...(Array.isArray(record["properties"])
|
|
59
|
+
? { properties: record["properties"].map(axProperty) }
|
|
60
|
+
: {}),
|
|
48
61
|
};
|
|
49
62
|
}
|
|
50
63
|
function shouldShow(node) {
|
|
@@ -53,6 +66,8 @@ function shouldShow(node) {
|
|
|
53
66
|
const value = node.value?.value;
|
|
54
67
|
if (role === "InlineTextBox")
|
|
55
68
|
return false;
|
|
69
|
+
if (INTERACTIVE_ROLES.has(role))
|
|
70
|
+
return true;
|
|
56
71
|
return (role !== "none" &&
|
|
57
72
|
role !== "generic" &&
|
|
58
73
|
!(name === "" && (value === "" || value == null)));
|
|
@@ -90,6 +105,38 @@ function splitText(value, max = 700) {
|
|
|
90
105
|
}
|
|
91
106
|
return parts;
|
|
92
107
|
}
|
|
108
|
+
function interactiveState(node) {
|
|
109
|
+
const values = new Map((node.properties ?? []).map((property) => [
|
|
110
|
+
property.name,
|
|
111
|
+
property.value?.value,
|
|
112
|
+
]));
|
|
113
|
+
const checkedValue = values.get("checked");
|
|
114
|
+
const checked = checkedValue === "true"
|
|
115
|
+
? true
|
|
116
|
+
: checkedValue === "false"
|
|
117
|
+
? false
|
|
118
|
+
: typeof checkedValue === "boolean" || checkedValue === "mixed"
|
|
119
|
+
? checkedValue
|
|
120
|
+
: undefined;
|
|
121
|
+
const selected = values.get("selected");
|
|
122
|
+
const expanded = values.get("expanded");
|
|
123
|
+
const disabled = values.get("disabled");
|
|
124
|
+
return {
|
|
125
|
+
...(checked === undefined ? {} : { checked }),
|
|
126
|
+
...(typeof selected === "boolean" ? { selected } : {}),
|
|
127
|
+
...(typeof expanded === "boolean" ? { expanded } : {}),
|
|
128
|
+
...(typeof disabled === "boolean" ? { disabled } : {}),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function interactiveText(role, name, value, state) {
|
|
132
|
+
const states = [
|
|
133
|
+
state.checked === undefined ? undefined : `checked=${state.checked}`,
|
|
134
|
+
state.selected === undefined ? undefined : `selected=${state.selected}`,
|
|
135
|
+
state.expanded === undefined ? undefined : `expanded=${state.expanded}`,
|
|
136
|
+
state.disabled === undefined ? undefined : `disabled=${state.disabled}`,
|
|
137
|
+
].filter((entry) => entry !== undefined);
|
|
138
|
+
return `${role}${name ? ` ${name}` : ""}${value === "" || value == null ? "" : ` = ${JSON.stringify(value)}`}${states.length > 0 ? ` [${states.join(", ")}]` : ""}`;
|
|
139
|
+
}
|
|
93
140
|
export async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
|
|
94
141
|
const lineno = positiveInteger(options.lineno ?? 1, "line cursor");
|
|
95
142
|
const responseLength = snapshotResponseLength(options.responseLength);
|
|
@@ -150,17 +197,26 @@ export async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
|
|
|
150
197
|
const value = node.value?.value;
|
|
151
198
|
let renderedName = parentName;
|
|
152
199
|
if (!node.ignored && shouldShow(node)) {
|
|
153
|
-
if (INTERACTIVE_ROLES.has(role)
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
200
|
+
if (INTERACTIVE_ROLES.has(role)) {
|
|
201
|
+
const state = interactiveState(node);
|
|
202
|
+
const text = interactiveText(role, name, value, state);
|
|
203
|
+
if (!node.backendDOMNodeId) {
|
|
204
|
+
addLine(text, undefined, "interactive");
|
|
205
|
+
renderedName = name;
|
|
206
|
+
}
|
|
207
|
+
else {
|
|
208
|
+
const element = {
|
|
209
|
+
id: nextElementId(),
|
|
210
|
+
role,
|
|
211
|
+
...(name ? { name } : {}),
|
|
212
|
+
...(value === "" || value == null ? {} : { value }),
|
|
213
|
+
...state,
|
|
214
|
+
};
|
|
215
|
+
elementRefs.set(element.id, node.backendDOMNodeId);
|
|
216
|
+
elements.push(element);
|
|
217
|
+
addLine(`[${element.id}] ${text}`, element, "interactive");
|
|
218
|
+
renderedName = name;
|
|
219
|
+
}
|
|
164
220
|
}
|
|
165
221
|
else if (role === "StaticText") {
|
|
166
222
|
if (name && name !== parentName)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { CdpConnection, PageInfo } from "./types.js";
|
|
2
|
+
export declare class BrowserTabs {
|
|
3
|
+
private readonly cdp;
|
|
4
|
+
private readonly directory;
|
|
5
|
+
private readonly ownershipDirectory;
|
|
6
|
+
private readonly scope;
|
|
7
|
+
private tail;
|
|
8
|
+
private closed;
|
|
9
|
+
private prepared;
|
|
10
|
+
constructor(cdp: CdpConnection, ownerId: string, directory: string, browserUrl: string);
|
|
11
|
+
list(signal?: AbortSignal): Promise<PageInfo[]>;
|
|
12
|
+
shutdown(): Promise<void>;
|
|
13
|
+
private enqueue;
|
|
14
|
+
private listNow;
|
|
15
|
+
resolve(refId: string, signal?: AbortSignal): Promise<{
|
|
16
|
+
page: PageInfo;
|
|
17
|
+
refId: string;
|
|
18
|
+
}>;
|
|
19
|
+
open(url: string, signal?: AbortSignal): Promise<{
|
|
20
|
+
refId: string;
|
|
21
|
+
}>;
|
|
22
|
+
show(refId: string, signal?: AbortSignal): Promise<string>;
|
|
23
|
+
close(refId: string, signal?: AbortSignal): Promise<{
|
|
24
|
+
targetId: string;
|
|
25
|
+
refId: string;
|
|
26
|
+
}>;
|
|
27
|
+
private targetPath;
|
|
28
|
+
private readOwned;
|
|
29
|
+
private touchDirectory;
|
|
30
|
+
private remember;
|
|
31
|
+
private forget;
|
|
32
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstat, mkdir, readdir, rm, utimes, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { getDisplayPrefixLength, resolvePrefix } from "./discovery.js";
|
|
5
|
+
import { getDisplayedPages, getPageTargets, waitForOpenedTarget, } from "./pages.js";
|
|
6
|
+
import { waitForTurn } from "./serial.js";
|
|
7
|
+
import { asRecord, errorMessage } from "./types.js";
|
|
8
|
+
import { assertHttpUrl } from "./url.js";
|
|
9
|
+
const TARGET_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
10
|
+
const SCOPE_ID = /^[a-f0-9]{64}$/;
|
|
11
|
+
// Listings refresh active scopes. One connection retires at most 32 month-old
|
|
12
|
+
// scopes, bounding cleanup while catching up faster than scopes are created.
|
|
13
|
+
const SCOPE_TTL_MS = 30 * 24 * 60 * 60 * 1_000;
|
|
14
|
+
const SCOPE_PRUNE_LIMIT = 32;
|
|
15
|
+
function missing(error) {
|
|
16
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
17
|
+
}
|
|
18
|
+
async function pruneOwnershipScopes(directory, currentScope, now = Date.now()) {
|
|
19
|
+
let entries;
|
|
20
|
+
try {
|
|
21
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
if (missing(error))
|
|
25
|
+
return;
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
const stale = [];
|
|
29
|
+
for (const entry of entries) {
|
|
30
|
+
if (entry.name === currentScope ||
|
|
31
|
+
!SCOPE_ID.test(entry.name) ||
|
|
32
|
+
!entry.isDirectory())
|
|
33
|
+
continue;
|
|
34
|
+
const path = join(directory, entry.name);
|
|
35
|
+
try {
|
|
36
|
+
const info = await lstat(path);
|
|
37
|
+
if (info.isDirectory() &&
|
|
38
|
+
!info.isSymbolicLink() &&
|
|
39
|
+
now - info.mtimeMs > SCOPE_TTL_MS) {
|
|
40
|
+
stale.push({ path, mtimeMs: info.mtimeMs });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
if (!missing(error))
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
stale.sort((left, right) => left.mtimeMs - right.mtimeMs);
|
|
49
|
+
await Promise.all(stale
|
|
50
|
+
.slice(0, SCOPE_PRUNE_LIMIT)
|
|
51
|
+
.map((scope) => rm(scope.path, { force: true, recursive: true })));
|
|
52
|
+
}
|
|
53
|
+
export class BrowserTabs {
|
|
54
|
+
cdp;
|
|
55
|
+
directory;
|
|
56
|
+
ownershipDirectory;
|
|
57
|
+
scope;
|
|
58
|
+
tail = Promise.resolve();
|
|
59
|
+
closed = false;
|
|
60
|
+
prepared = false;
|
|
61
|
+
constructor(cdp, ownerId, directory, browserUrl) {
|
|
62
|
+
this.cdp = cdp;
|
|
63
|
+
this.ownershipDirectory = directory;
|
|
64
|
+
// Browser endpoint identity changes on restart, so restored tabs do not
|
|
65
|
+
// inherit an old automation session's ownership.
|
|
66
|
+
this.scope = createHash("sha256")
|
|
67
|
+
.update(`${browserUrl}\0${ownerId}`)
|
|
68
|
+
.digest("hex");
|
|
69
|
+
this.directory = join(directory, this.scope);
|
|
70
|
+
}
|
|
71
|
+
list(signal) {
|
|
72
|
+
return this.enqueue(() => this.listNow(signal), signal);
|
|
73
|
+
}
|
|
74
|
+
async shutdown() {
|
|
75
|
+
this.closed = true;
|
|
76
|
+
await this.tail;
|
|
77
|
+
}
|
|
78
|
+
enqueue(action, signal) {
|
|
79
|
+
const pending = this.tail.then(async () => {
|
|
80
|
+
signal?.throwIfAborted();
|
|
81
|
+
if (this.closed)
|
|
82
|
+
throw new Error("Browser session closed");
|
|
83
|
+
if (!this.prepared) {
|
|
84
|
+
await this.touchDirectory();
|
|
85
|
+
await pruneOwnershipScopes(this.ownershipDirectory, this.scope);
|
|
86
|
+
this.prepared = true;
|
|
87
|
+
}
|
|
88
|
+
return action();
|
|
89
|
+
});
|
|
90
|
+
this.tail = pending.then(() => undefined, () => undefined);
|
|
91
|
+
return waitForTurn(pending, signal);
|
|
92
|
+
}
|
|
93
|
+
async listNow(signal) {
|
|
94
|
+
// Read ownership first so a concurrent creation is not pruned against an
|
|
95
|
+
// older browser target snapshot.
|
|
96
|
+
const owned = await this.readOwned();
|
|
97
|
+
const targets = await getPageTargets(this.cdp, signal);
|
|
98
|
+
const pages = getDisplayedPages(targets);
|
|
99
|
+
const known = new Set(owned);
|
|
100
|
+
// Resolve descendants before removing closed openers from the registry.
|
|
101
|
+
let changed = true;
|
|
102
|
+
while (changed) {
|
|
103
|
+
changed = false;
|
|
104
|
+
for (const page of pages) {
|
|
105
|
+
if (!page.openerId ||
|
|
106
|
+
!known.has(page.openerId) ||
|
|
107
|
+
known.has(page.targetId))
|
|
108
|
+
continue;
|
|
109
|
+
await this.remember(page.targetId);
|
|
110
|
+
known.add(page.targetId);
|
|
111
|
+
changed = true;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const live = new Set(targets.map((page) => page.targetId));
|
|
115
|
+
await Promise.all(owned.filter((id) => !live.has(id)).map((id) => this.forget(id)));
|
|
116
|
+
return pages.map((page) => ({ ...page, owned: known.has(page.targetId) }));
|
|
117
|
+
}
|
|
118
|
+
async resolve(refId, signal) {
|
|
119
|
+
const pages = await this.list(signal);
|
|
120
|
+
const ids = pages.map((page) => page.targetId);
|
|
121
|
+
const targetId = resolvePrefix(refId, ids, "target", "Run tabs.");
|
|
122
|
+
const page = pages.find((candidate) => candidate.targetId === targetId);
|
|
123
|
+
if (!page)
|
|
124
|
+
throw new Error("Tab disappeared; run tabs again");
|
|
125
|
+
return { page, refId: targetId.slice(0, getDisplayPrefixLength(ids)) };
|
|
126
|
+
}
|
|
127
|
+
async open(url, signal) {
|
|
128
|
+
assertHttpUrl(url);
|
|
129
|
+
const targetId = await this.enqueue(async () => {
|
|
130
|
+
// Once dispatched, preserve the reply and ownership write even if the
|
|
131
|
+
// caller aborts. Listings and shutdown wait for this critical section.
|
|
132
|
+
let response;
|
|
133
|
+
try {
|
|
134
|
+
response = asRecord(await this.cdp.send("Target.createTarget", { url, background: true }), "Target.createTarget response");
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
throw new Error(`Chrome did not confirm tab creation; a shared tab may exist. Run tabs before retrying: ${errorMessage(error)}`);
|
|
138
|
+
}
|
|
139
|
+
if (typeof response["targetId"] !== "string")
|
|
140
|
+
throw new Error("Chrome did not return a new tab target; run tabs before retrying");
|
|
141
|
+
const created = response["targetId"];
|
|
142
|
+
try {
|
|
143
|
+
await this.remember(created);
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
throw new Error(`Opened tab ${created} but could not save ownership; it remains shared: ${errorMessage(error)}`);
|
|
147
|
+
}
|
|
148
|
+
return created;
|
|
149
|
+
}, signal);
|
|
150
|
+
await waitForOpenedTarget(this.cdp, targetId, url, 5_000, signal);
|
|
151
|
+
const { refId } = await this.resolve(targetId, signal);
|
|
152
|
+
return { refId };
|
|
153
|
+
}
|
|
154
|
+
async show(refId, signal) {
|
|
155
|
+
const resolved = await this.resolve(refId, signal);
|
|
156
|
+
await this.cdp.send("Target.activateTarget", { targetId: resolved.page.targetId }, undefined, signal);
|
|
157
|
+
return resolved.refId;
|
|
158
|
+
}
|
|
159
|
+
async close(refId, signal) {
|
|
160
|
+
const resolved = await this.resolve(refId, signal);
|
|
161
|
+
const targetId = resolved.page.targetId;
|
|
162
|
+
const response = asRecord(await this.cdp.send("Target.closeTarget", { targetId }, undefined, signal), "Target.closeTarget response");
|
|
163
|
+
if (response["success"] !== true)
|
|
164
|
+
throw new Error("Chrome did not close the tab; run tabs to inspect it");
|
|
165
|
+
await this.forget(targetId);
|
|
166
|
+
return { targetId, refId: resolved.refId };
|
|
167
|
+
}
|
|
168
|
+
targetPath(targetId) {
|
|
169
|
+
if (!TARGET_ID.test(targetId))
|
|
170
|
+
throw new Error("Chrome returned an invalid target id");
|
|
171
|
+
return join(this.directory, targetId);
|
|
172
|
+
}
|
|
173
|
+
async readOwned() {
|
|
174
|
+
if (!(await this.touchDirectory()))
|
|
175
|
+
return [];
|
|
176
|
+
try {
|
|
177
|
+
const files = await readdir(this.directory, { withFileTypes: true });
|
|
178
|
+
for (const file of files) {
|
|
179
|
+
if (!file.isFile() || !TARGET_ID.test(file.name))
|
|
180
|
+
throw new Error("Invalid browser ownership record; refusing to infer tab ownership");
|
|
181
|
+
}
|
|
182
|
+
return files.map((file) => file.name);
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
if (missing(error))
|
|
186
|
+
return [];
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
async touchDirectory() {
|
|
191
|
+
try {
|
|
192
|
+
const info = await lstat(this.directory);
|
|
193
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
194
|
+
throw new Error("Invalid browser ownership directory");
|
|
195
|
+
const now = new Date();
|
|
196
|
+
await utimes(this.directory, now, now);
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (missing(error))
|
|
201
|
+
return false;
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
async remember(targetId) {
|
|
206
|
+
const path = this.targetPath(targetId);
|
|
207
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
208
|
+
const info = await lstat(this.directory);
|
|
209
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
210
|
+
throw new Error("Invalid browser ownership directory");
|
|
211
|
+
// One record per target avoids read/modify/write races between clients of
|
|
212
|
+
// the same Pi session and survives reloads or managed-worker upgrades.
|
|
213
|
+
try {
|
|
214
|
+
await writeFile(path, "", { flag: "wx", mode: 0o600 });
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
if (!(error instanceof Error && "code" in error && error.code === "EEXIST"))
|
|
218
|
+
throw error;
|
|
219
|
+
if (!(await lstat(path)).isFile())
|
|
220
|
+
throw new Error("Invalid browser ownership record");
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
async forget(targetId) {
|
|
224
|
+
await rm(this.targetPath(targetId), { force: true });
|
|
225
|
+
}
|
|
226
|
+
}
|
package/dist/src/cdp/types.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ export interface PageInfo {
|
|
|
13
13
|
title: string;
|
|
14
14
|
url: string;
|
|
15
15
|
type?: string;
|
|
16
|
+
openerId?: string;
|
|
17
|
+
owned?: boolean;
|
|
16
18
|
}
|
|
17
19
|
export type ElementRefs = Map<number, number>;
|
|
18
20
|
export declare function asRecord(value: unknown, label?: string): Record<string, unknown>;
|
package/index.ts
CHANGED
|
@@ -28,9 +28,9 @@ export default async function browserExtension(
|
|
|
28
28
|
registerBrowserCommand(pi);
|
|
29
29
|
pi.registerTool(tool);
|
|
30
30
|
const registration = await registerBrowserInCodeMode(pi, tool);
|
|
31
|
-
pi.on("session_shutdown", () => {
|
|
31
|
+
pi.on("session_shutdown", async () => {
|
|
32
32
|
registration?.unregister();
|
|
33
|
-
runtime.close();
|
|
33
|
+
await runtime.close();
|
|
34
34
|
});
|
|
35
35
|
if (configError) {
|
|
36
36
|
pi.on("session_start", (_event, ctx) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@howaboua/pi-browser",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.4",
|
|
4
4
|
"description": "Logged-in browser inspection and control for Pi, Code Mode and Notebook Mode.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"pack:dry": "npm pack --dry-run"
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
|
49
|
-
"@howaboua/pi-codex-conversion": ">=3.0.
|
|
49
|
+
"@howaboua/pi-codex-conversion": ">=3.0.35",
|
|
50
50
|
"@earendil-works/pi-ai": ">=0.84.3",
|
|
51
51
|
"@earendil-works/pi-coding-agent": ">=0.84.3",
|
|
52
52
|
"typebox": "*",
|
|
@@ -58,10 +58,10 @@
|
|
|
58
58
|
}
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
61
|
-
"@howaboua/pi-codex-conversion": "3.0.
|
|
61
|
+
"@howaboua/pi-codex-conversion": "3.0.35",
|
|
62
62
|
"@biomejs/biome": "^2.5.10",
|
|
63
|
-
"@earendil-works/pi-ai": "0.
|
|
64
|
-
"@earendil-works/pi-coding-agent": "0.
|
|
63
|
+
"@earendil-works/pi-ai": "0.86.1",
|
|
64
|
+
"@earendil-works/pi-coding-agent": "0.86.1",
|
|
65
65
|
"@types/node": "^26.2.0",
|
|
66
66
|
"tsx": "^4.23.12",
|
|
67
67
|
"typebox": "1.3.18",
|
package/src/browser/bounds.ts
CHANGED
|
@@ -50,14 +50,17 @@ export function boundTabs(
|
|
|
50
50
|
pages: PageInfo[],
|
|
51
51
|
query: string | undefined,
|
|
52
52
|
offset: number,
|
|
53
|
+
ownedOnly = false,
|
|
53
54
|
): Record<string, unknown> {
|
|
54
55
|
const prefixLength = getDisplayPrefixLength(
|
|
55
56
|
pages.map((page) => page.targetId),
|
|
56
57
|
);
|
|
57
|
-
let filtered =
|
|
58
|
+
let filtered = ownedOnly
|
|
59
|
+
? pages.filter((page) => page.owned === true)
|
|
60
|
+
: pages;
|
|
58
61
|
if (query) {
|
|
59
62
|
const normalized = query.toLowerCase();
|
|
60
|
-
filtered =
|
|
63
|
+
filtered = filtered.filter((page) =>
|
|
61
64
|
`${page.title}\n${page.url}`.toLowerCase().includes(normalized),
|
|
62
65
|
);
|
|
63
66
|
}
|
|
@@ -68,12 +71,14 @@ export function boundTabs(
|
|
|
68
71
|
ref_id: string;
|
|
69
72
|
title: string;
|
|
70
73
|
url: string;
|
|
74
|
+
owned: boolean;
|
|
71
75
|
}> = [];
|
|
72
76
|
for (const page of filtered.slice(offset)) {
|
|
73
77
|
const compact = {
|
|
74
78
|
ref_id: page.targetId.slice(0, prefixLength),
|
|
75
79
|
title: page.title.slice(0, 500),
|
|
76
80
|
url: page.url.slice(0, 8_000),
|
|
81
|
+
owned: page.owned === true,
|
|
77
82
|
};
|
|
78
83
|
if (byteLength({ tabs: [...tabs, compact] }) > OUTPUT_BUDGET_BYTES) {
|
|
79
84
|
break;
|
package/src/browser/help.ts
CHANGED
|
@@ -15,11 +15,16 @@ export function browserHelp(
|
|
|
15
15
|
batch:
|
|
16
16
|
"top-level nonempty action arrays; items omit action/host/response_length; independent only",
|
|
17
17
|
actions: {
|
|
18
|
-
tabs: "query? offset? -> ref_id title url",
|
|
19
|
-
open: "ref_id lineno? response_length? | url",
|
|
18
|
+
tabs: "query? offset? owned_only? -> ref_id title url owned",
|
|
19
|
+
open: "ref_id lineno? response_length? | url; new tabs open in background",
|
|
20
|
+
show: "ref_id; bring tab to foreground",
|
|
21
|
+
close: "ref_id",
|
|
20
22
|
find: "ref_id pattern lineno? response_length?",
|
|
21
23
|
click: "ref_id id|selector|x+y",
|
|
22
24
|
type: "ref_id text id?; id focuses",
|
|
25
|
+
fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
|
|
26
|
+
press: "ref_id key; focused element, e.g. Enter or Control+a",
|
|
27
|
+
wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
|
|
23
28
|
screenshot: "ref_id id?|selector? -> file",
|
|
24
29
|
navigate: "ref_id url",
|
|
25
30
|
html: "ref_id id?|selector?",
|
|
@@ -28,7 +33,7 @@ export function browserHelp(
|
|
|
28
33
|
load_all: "ref_id selector interval_ms?",
|
|
29
34
|
raw: "ref_id method params?",
|
|
30
35
|
start: "",
|
|
31
|
-
stop: "ref_id
|
|
36
|
+
stop: "ref_id?; detach without closing tabs",
|
|
32
37
|
read_result: "handle offset",
|
|
33
38
|
discard_result: "handle",
|
|
34
39
|
},
|