@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
|
@@ -3,6 +3,8 @@ import {
|
|
|
3
3
|
clickRef,
|
|
4
4
|
clickSelector,
|
|
5
5
|
} from "../cdp/actions/click.js";
|
|
6
|
+
import { fillElement } from "../cdp/actions/fill.js";
|
|
7
|
+
import { pressKey } from "../cdp/actions/key.js";
|
|
6
8
|
import {
|
|
7
9
|
html,
|
|
8
10
|
htmlRef,
|
|
@@ -17,6 +19,7 @@ import {
|
|
|
17
19
|
captureViewport,
|
|
18
20
|
} from "../cdp/actions/screenshot.js";
|
|
19
21
|
import { typeAtFocus, typeRef } from "../cdp/actions/type.js";
|
|
22
|
+
import { waitForCondition } from "../cdp/actions/wait.js";
|
|
20
23
|
import { evaluateText } from "../cdp/evaluate.js";
|
|
21
24
|
import { type ActiveTab, BrowserCdpSession } from "../cdp/session.js";
|
|
22
25
|
import { snapshotData } from "../cdp/snapshot.js";
|
|
@@ -49,6 +52,7 @@ export class BrowserOperationExecutor {
|
|
|
49
52
|
await this.cdp.pages(signal),
|
|
50
53
|
operation.query,
|
|
51
54
|
operation.offset,
|
|
55
|
+
operation.owned_only,
|
|
52
56
|
);
|
|
53
57
|
case "open":
|
|
54
58
|
if ("url" in operation) {
|
|
@@ -56,6 +60,7 @@ export class BrowserOperationExecutor {
|
|
|
56
60
|
return {
|
|
57
61
|
ref_id: opened.refId,
|
|
58
62
|
url: operation.url,
|
|
63
|
+
owned: true,
|
|
59
64
|
};
|
|
60
65
|
}
|
|
61
66
|
return this.cdp.withTab(operation.ref_id, signal, async (tab) =>
|
|
@@ -80,6 +85,10 @@ export class BrowserOperationExecutor {
|
|
|
80
85
|
}),
|
|
81
86
|
),
|
|
82
87
|
);
|
|
88
|
+
case "show":
|
|
89
|
+
return { shown: await this.cdp.show(operation.ref_id, signal) };
|
|
90
|
+
case "close":
|
|
91
|
+
return { closed: await this.cdp.closeTab(operation.ref_id, signal) };
|
|
83
92
|
case "read_result":
|
|
84
93
|
return readCachedResult(operation);
|
|
85
94
|
case "discard_result":
|
|
@@ -199,6 +208,31 @@ export class BrowserOperationExecutor {
|
|
|
199
208
|
signal,
|
|
200
209
|
),
|
|
201
210
|
);
|
|
211
|
+
case "fill":
|
|
212
|
+
return this.tabResult(operation.ref_id, signal, (tab) =>
|
|
213
|
+
fillElement(
|
|
214
|
+
tab.cdp,
|
|
215
|
+
tab.sessionId,
|
|
216
|
+
tab.elementRefs,
|
|
217
|
+
operation,
|
|
218
|
+
operation.value,
|
|
219
|
+
signal,
|
|
220
|
+
),
|
|
221
|
+
);
|
|
222
|
+
case "press":
|
|
223
|
+
return this.tabResult(operation.ref_id, signal, (tab) =>
|
|
224
|
+
pressKey(tab.cdp, tab.sessionId, operation.key, signal),
|
|
225
|
+
);
|
|
226
|
+
case "wait":
|
|
227
|
+
return this.tabResult(operation.ref_id, signal, (tab) =>
|
|
228
|
+
waitForCondition(
|
|
229
|
+
tab.cdp,
|
|
230
|
+
tab.sessionId,
|
|
231
|
+
operation,
|
|
232
|
+
operation.timeout_ms,
|
|
233
|
+
signal,
|
|
234
|
+
),
|
|
235
|
+
);
|
|
202
236
|
}
|
|
203
237
|
}
|
|
204
238
|
|
package/src/browser/operation.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { WaitCondition } from "../cdp/actions/wait.js";
|
|
1
2
|
import type { SnapshotResponseLength } from "../cdp/snapshot-contract.js";
|
|
2
3
|
|
|
3
4
|
export const BROWSER_ACTIONS = [
|
|
@@ -5,9 +6,14 @@ export const BROWSER_ACTIONS = [
|
|
|
5
6
|
"start",
|
|
6
7
|
"tabs",
|
|
7
8
|
"open",
|
|
9
|
+
"show",
|
|
10
|
+
"close",
|
|
8
11
|
"find",
|
|
9
12
|
"click",
|
|
10
13
|
"type",
|
|
14
|
+
"fill",
|
|
15
|
+
"press",
|
|
16
|
+
"wait",
|
|
11
17
|
"screenshot",
|
|
12
18
|
"html",
|
|
13
19
|
"navigate",
|
|
@@ -28,7 +34,12 @@ export type BrowserAction = (typeof BROWSER_ACTIONS)[number];
|
|
|
28
34
|
|
|
29
35
|
export type BrowserOperation =
|
|
30
36
|
| { action: "start" }
|
|
31
|
-
| {
|
|
37
|
+
| {
|
|
38
|
+
action: "tabs";
|
|
39
|
+
query?: string | undefined;
|
|
40
|
+
offset: number;
|
|
41
|
+
owned_only?: boolean | undefined;
|
|
42
|
+
}
|
|
32
43
|
| {
|
|
33
44
|
action: "open";
|
|
34
45
|
ref_id: string;
|
|
@@ -36,6 +47,7 @@ export type BrowserOperation =
|
|
|
36
47
|
response_length: SnapshotResponseLength;
|
|
37
48
|
}
|
|
38
49
|
| { action: "open"; url: string }
|
|
50
|
+
| { action: "show" | "close"; ref_id: string }
|
|
39
51
|
| {
|
|
40
52
|
action: "find";
|
|
41
53
|
ref_id: string;
|
|
@@ -73,6 +85,12 @@ export type BrowserOperation =
|
|
|
73
85
|
id?: number | undefined;
|
|
74
86
|
text: string;
|
|
75
87
|
}
|
|
88
|
+
| ({ action: "fill"; ref_id: string; value: string | boolean } & (
|
|
89
|
+
| { id: number; selector?: never }
|
|
90
|
+
| { selector: string; id?: never }
|
|
91
|
+
))
|
|
92
|
+
| { action: "press"; ref_id: string; key: string }
|
|
93
|
+
| ({ action: "wait"; ref_id: string; timeout_ms: number } & WaitCondition)
|
|
76
94
|
| {
|
|
77
95
|
action: "screenshot";
|
|
78
96
|
ref_id: string;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { parseKeyChord } from "../cdp/actions/key.js";
|
|
1
2
|
import type { SnapshotResponseLength } from "../cdp/snapshot-contract.js";
|
|
2
3
|
import {
|
|
3
4
|
BROWSER_ACTIONS,
|
|
@@ -12,11 +13,16 @@ const fields = (...names: string[]) => new Set(["action", ...names]);
|
|
|
12
13
|
const ACTION_FIELDS: Record<BrowserAction, ReadonlySet<string>> = {
|
|
13
14
|
help: fields(),
|
|
14
15
|
start: fields(),
|
|
15
|
-
tabs: fields("query", "offset"),
|
|
16
|
+
tabs: fields("query", "offset", "owned_only"),
|
|
16
17
|
open: fields("ref_id", "url", "lineno", "response_length"),
|
|
18
|
+
show: fields("ref_id"),
|
|
19
|
+
close: fields("ref_id"),
|
|
17
20
|
find: fields("ref_id", "pattern", "lineno", "response_length"),
|
|
18
21
|
click: fields("ref_id", "id", "selector", "x", "y"),
|
|
19
22
|
type: fields("ref_id", "id", "text"),
|
|
23
|
+
fill: fields("ref_id", "id", "selector", "value"),
|
|
24
|
+
press: fields("ref_id", "key"),
|
|
25
|
+
wait: fields("ref_id", "selector", "text", "url_includes", "timeout_ms"),
|
|
20
26
|
screenshot: fields("ref_id", "id", "selector"),
|
|
21
27
|
html: fields("ref_id", "id", "selector"),
|
|
22
28
|
navigate: fields("ref_id", "url"),
|
|
@@ -114,10 +120,14 @@ export function parseActionRequest(value: unknown): ActionRequest {
|
|
|
114
120
|
if (action === "help" || action === "start") return { action };
|
|
115
121
|
if (action === "tabs") {
|
|
116
122
|
const query = optionalString(value["query"], "query");
|
|
123
|
+
const ownedOnly = value["owned_only"];
|
|
124
|
+
if (ownedOnly !== undefined && typeof ownedOnly !== "boolean")
|
|
125
|
+
throw new Error("owned_only must be a boolean");
|
|
117
126
|
return {
|
|
118
127
|
action,
|
|
119
128
|
...(query ? { query } : {}),
|
|
120
129
|
offset: offset(value["offset"]),
|
|
130
|
+
...(ownedOnly === undefined ? {} : { owned_only: ownedOnly }),
|
|
121
131
|
};
|
|
122
132
|
}
|
|
123
133
|
if (action === "open") {
|
|
@@ -160,7 +170,8 @@ export function parseActionRequest(value: unknown): ActionRequest {
|
|
|
160
170
|
}
|
|
161
171
|
|
|
162
172
|
const refId = requiredRef(value["ref_id"], action);
|
|
163
|
-
if (action === "network"
|
|
173
|
+
if (action === "network" || action === "show" || action === "close")
|
|
174
|
+
return { action, ref_id: refId };
|
|
164
175
|
if (action === "navigate") {
|
|
165
176
|
return {
|
|
166
177
|
action,
|
|
@@ -234,6 +245,56 @@ export function parseActionRequest(value: unknown): ActionRequest {
|
|
|
234
245
|
...(selector ? { selector } : {}),
|
|
235
246
|
};
|
|
236
247
|
}
|
|
248
|
+
if (action === "fill") {
|
|
249
|
+
const id = elementId(value["id"]);
|
|
250
|
+
const selector = optionalString(value["selector"], "selector");
|
|
251
|
+
if (Number(id !== undefined) + Number(selector !== undefined) !== 1) {
|
|
252
|
+
throw new Error("fill requires exactly one of id or selector");
|
|
253
|
+
}
|
|
254
|
+
const fillValue = value["value"];
|
|
255
|
+
if (typeof fillValue !== "string" && typeof fillValue !== "boolean") {
|
|
256
|
+
throw new Error("value must be text or a boolean for checkbox/radio");
|
|
257
|
+
}
|
|
258
|
+
if (id !== undefined)
|
|
259
|
+
return { action, ref_id: refId, id, value: fillValue };
|
|
260
|
+
if (selector) return { action, ref_id: refId, selector, value: fillValue };
|
|
261
|
+
throw new Error("fill requires id or selector");
|
|
262
|
+
}
|
|
263
|
+
if (action === "press") {
|
|
264
|
+
const key = requiredString(value["key"], "key");
|
|
265
|
+
parseKeyChord(key);
|
|
266
|
+
return { action, ref_id: refId, key };
|
|
267
|
+
}
|
|
268
|
+
if (action === "wait") {
|
|
269
|
+
const conditions = ["selector", "text", "url_includes"] as const;
|
|
270
|
+
const provided = conditions.filter((field) => value[field] !== undefined);
|
|
271
|
+
const field = provided[0];
|
|
272
|
+
if (provided.length !== 1 || !field) {
|
|
273
|
+
throw new Error(
|
|
274
|
+
"wait requires exactly one of selector, text, or url_includes",
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
const match = value[field];
|
|
278
|
+
if (typeof match !== "string" || !match.trim()) {
|
|
279
|
+
throw new Error(`${field} must be a non-empty string`);
|
|
280
|
+
}
|
|
281
|
+
const timeout = value["timeout_ms"] ?? 10_000;
|
|
282
|
+
if (
|
|
283
|
+
!Number.isInteger(timeout) ||
|
|
284
|
+
Number(timeout) < 1 ||
|
|
285
|
+
Number(timeout) > 60_000
|
|
286
|
+
) {
|
|
287
|
+
throw new Error("timeout_ms must be an integer from 1 to 60000");
|
|
288
|
+
}
|
|
289
|
+
const base = {
|
|
290
|
+
action,
|
|
291
|
+
ref_id: refId,
|
|
292
|
+
timeout_ms: Number(timeout),
|
|
293
|
+
} as const;
|
|
294
|
+
if (field === "selector") return { ...base, selector: match };
|
|
295
|
+
if (field === "text") return { ...base, text: match };
|
|
296
|
+
return { ...base, url_includes: match };
|
|
297
|
+
}
|
|
237
298
|
if (action === "load_all") {
|
|
238
299
|
const interval = value["interval_ms"] ?? 1_500;
|
|
239
300
|
if (
|
package/src/browser/remote.ts
CHANGED
|
@@ -85,6 +85,7 @@ async function localizeScreenshots(
|
|
|
85
85
|
export async function executeRemoteBrowser(
|
|
86
86
|
route: BrowserRoute,
|
|
87
87
|
operations: BrowserOperation[],
|
|
88
|
+
ownerId: string,
|
|
88
89
|
signal?: AbortSignal,
|
|
89
90
|
): Promise<Record<string, unknown>> {
|
|
90
91
|
if (!route.remote) {
|
|
@@ -94,7 +95,7 @@ export async function executeRemoteBrowser(
|
|
|
94
95
|
const executed = await runProgram(
|
|
95
96
|
"ssh",
|
|
96
97
|
[route.name, remoteNodeCommand(route.remote)],
|
|
97
|
-
JSON.stringify({ operations }),
|
|
98
|
+
JSON.stringify({ owner_id: ownerId, operations }),
|
|
98
99
|
signal,
|
|
99
100
|
);
|
|
100
101
|
if (executed.code !== 0) {
|
package/src/browser/runtime.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
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 type { BrowserOperation } from "./operation.js";
|
|
5
8
|
import { BrowserOperationExecutor } from "./operation-executor.js";
|
|
@@ -8,14 +11,27 @@ import type { BrowserRequest } from "./request.js";
|
|
|
8
11
|
import { BrowserRoutes, loadBrowserRoutes } from "./routes.js";
|
|
9
12
|
|
|
10
13
|
export interface BrowserExecutionOptions {
|
|
14
|
+
ownerId?: string | undefined;
|
|
11
15
|
signal?: AbortSignal | undefined;
|
|
12
16
|
onOperation?(operation: BrowserOperation, index: number, total: number): void;
|
|
13
17
|
}
|
|
14
18
|
|
|
19
|
+
interface LocalSession {
|
|
20
|
+
activeCalls: number;
|
|
21
|
+
cdp: BrowserCdpSession;
|
|
22
|
+
closing?: Promise<void>;
|
|
23
|
+
lastUsed: number;
|
|
24
|
+
operations: BrowserOperationExecutor;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const LOCAL_SESSION_IDLE_MS = 20 * 60 * 1_000;
|
|
28
|
+
|
|
15
29
|
export class BrowserRuntime {
|
|
16
30
|
readonly hosts: readonly string[];
|
|
17
|
-
private readonly
|
|
18
|
-
private readonly
|
|
31
|
+
private readonly defaultOwnerId = randomUUID();
|
|
32
|
+
private readonly lifetime = new AbortController();
|
|
33
|
+
private closing: Promise<void> | undefined;
|
|
34
|
+
private readonly localSessions = new Map<string, LocalSession>();
|
|
19
35
|
private readonly routes: BrowserRoutes;
|
|
20
36
|
|
|
21
37
|
constructor(routes = loadBrowserRoutes()) {
|
|
@@ -27,9 +43,18 @@ export class BrowserRuntime {
|
|
|
27
43
|
request: BrowserRequest,
|
|
28
44
|
options: BrowserExecutionOptions = {},
|
|
29
45
|
): Promise<Record<string, unknown>> {
|
|
46
|
+
options = {
|
|
47
|
+
...options,
|
|
48
|
+
signal: options.signal
|
|
49
|
+
? AbortSignal.any([options.signal, this.lifetime.signal])
|
|
50
|
+
: this.lifetime.signal,
|
|
51
|
+
};
|
|
30
52
|
options.signal?.throwIfAborted();
|
|
53
|
+
await waitForTurn(this.pruneLocalSessions(), options.signal);
|
|
31
54
|
await pruneArtifacts();
|
|
55
|
+
options.signal?.throwIfAborted();
|
|
32
56
|
if ("help" in request) return browserHelp(this.hosts);
|
|
57
|
+
const ownerId = options.ownerId ?? this.defaultOwnerId;
|
|
33
58
|
if (request.host) {
|
|
34
59
|
const route = this.routes.resolve(request.host);
|
|
35
60
|
if (!route.local) {
|
|
@@ -40,45 +65,109 @@ export class BrowserRuntime {
|
|
|
40
65
|
const result = await executeRemoteBrowser(
|
|
41
66
|
route,
|
|
42
67
|
request.operations,
|
|
68
|
+
ownerId,
|
|
43
69
|
options.signal,
|
|
44
70
|
);
|
|
45
71
|
return { host: request.host, ...result };
|
|
46
72
|
}
|
|
47
73
|
}
|
|
48
|
-
const result = await this.executeLocal(
|
|
74
|
+
const result = await this.executeLocal(
|
|
75
|
+
request.operations,
|
|
76
|
+
ownerId,
|
|
77
|
+
options,
|
|
78
|
+
);
|
|
49
79
|
return request.host ? { host: request.host, ...result } : result;
|
|
50
80
|
}
|
|
51
81
|
|
|
52
|
-
close(): void {
|
|
53
|
-
this.
|
|
82
|
+
close(): Promise<void> {
|
|
83
|
+
if (this.closing) return this.closing;
|
|
84
|
+
this.lifetime.abort(new Error("Browser runtime closed"));
|
|
85
|
+
const closing = [...this.localSessions.values()].map((session) =>
|
|
86
|
+
session.cdp.close(),
|
|
87
|
+
);
|
|
88
|
+
this.localSessions.clear();
|
|
89
|
+
this.closing = Promise.all(closing).then(() => undefined);
|
|
90
|
+
return this.closing;
|
|
54
91
|
}
|
|
55
92
|
|
|
56
93
|
private async executeLocal(
|
|
57
94
|
operations: BrowserOperation[],
|
|
95
|
+
ownerId: string,
|
|
58
96
|
options: BrowserExecutionOptions,
|
|
59
97
|
): Promise<Record<string, unknown>> {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
98
|
+
let pendingClose = this.localSessions.get(ownerId)?.closing;
|
|
99
|
+
while (pendingClose) {
|
|
100
|
+
await waitForTurn(pendingClose, options.signal);
|
|
101
|
+
pendingClose = this.localSessions.get(ownerId)?.closing;
|
|
102
|
+
}
|
|
103
|
+
options.signal?.throwIfAborted();
|
|
104
|
+
const session = this.localSession(ownerId);
|
|
105
|
+
session.activeCalls++;
|
|
106
|
+
try {
|
|
107
|
+
const results: Record<string, unknown>[] = [];
|
|
108
|
+
for (const [index, operation] of operations.entries()) {
|
|
109
|
+
try {
|
|
110
|
+
options.signal?.throwIfAborted();
|
|
111
|
+
options.onOperation?.(operation, index, operations.length);
|
|
112
|
+
results.push(
|
|
113
|
+
await session.operations.execute(operation, options.signal),
|
|
114
|
+
);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
throw new Error(
|
|
117
|
+
`batch failed at ${operation.action}[${index}] after ${results.length} completed operation(s): ${
|
|
118
|
+
error instanceof Error ? error.message : String(error)
|
|
119
|
+
}`,
|
|
120
|
+
);
|
|
121
|
+
}
|
|
72
122
|
}
|
|
123
|
+
const first = results[0];
|
|
124
|
+
if (results.length === 1 && first) return first;
|
|
125
|
+
return {
|
|
126
|
+
results: results.map((result, index) => ({
|
|
127
|
+
operation: operations[index]?.action ?? "unknown",
|
|
128
|
+
index,
|
|
129
|
+
...result,
|
|
130
|
+
})),
|
|
131
|
+
};
|
|
132
|
+
} finally {
|
|
133
|
+
session.activeCalls--;
|
|
134
|
+
session.lastUsed = Date.now();
|
|
73
135
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private localSession(ownerId: string): LocalSession {
|
|
139
|
+
let session = this.localSessions.get(ownerId);
|
|
140
|
+
if (session) return session;
|
|
141
|
+
const cdp = new BrowserCdpSession(
|
|
142
|
+
ownerId,
|
|
143
|
+
join(artifactDirectory(), "tabs"),
|
|
144
|
+
);
|
|
145
|
+
session = {
|
|
146
|
+
activeCalls: 0,
|
|
147
|
+
cdp,
|
|
148
|
+
lastUsed: Date.now(),
|
|
149
|
+
operations: new BrowserOperationExecutor(cdp),
|
|
82
150
|
};
|
|
151
|
+
this.localSessions.set(ownerId, session);
|
|
152
|
+
return session;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private async pruneLocalSessions(now = Date.now()): Promise<void> {
|
|
156
|
+
const closing: Promise<void>[] = [];
|
|
157
|
+
for (const [ownerId, session] of this.localSessions) {
|
|
158
|
+
if (
|
|
159
|
+
!session.closing &&
|
|
160
|
+
session.activeCalls === 0 &&
|
|
161
|
+
now - session.lastUsed >= LOCAL_SESSION_IDLE_MS
|
|
162
|
+
) {
|
|
163
|
+
session.closing = session.cdp.close().finally(() => {
|
|
164
|
+
if (this.localSessions.get(ownerId) === session) {
|
|
165
|
+
this.localSessions.delete(ownerId);
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
if (session.closing) closing.push(session.closing);
|
|
170
|
+
}
|
|
171
|
+
await Promise.all(closing);
|
|
83
172
|
}
|
|
84
173
|
}
|
|
@@ -20,6 +20,11 @@ interface WorkerResponse {
|
|
|
20
20
|
result?: Record<string, unknown>;
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
interface WorkerRequest {
|
|
24
|
+
operations: BrowserOperation[];
|
|
25
|
+
ownerId: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
23
28
|
function workerSocketPath(workerId: string): string {
|
|
24
29
|
if (IS_WINDOWS) return `\\\\.\\pipe\\pi-browser-worker-${workerId}`;
|
|
25
30
|
const directory = process.env["XDG_RUNTIME_DIR"]
|
|
@@ -47,7 +52,7 @@ async function ensureWorkerSocketDirectory(workerId: string): Promise<void> {
|
|
|
47
52
|
if ((info.mode & 0o077) !== 0) await chmod(directory, 0o700);
|
|
48
53
|
}
|
|
49
54
|
|
|
50
|
-
function
|
|
55
|
+
function parseWorkerRequest(input: string): WorkerRequest {
|
|
51
56
|
let value: unknown;
|
|
52
57
|
try {
|
|
53
58
|
value = JSON.parse(input);
|
|
@@ -57,14 +62,25 @@ function parseWorkerOperations(input: string): BrowserOperation[] {
|
|
|
57
62
|
);
|
|
58
63
|
}
|
|
59
64
|
if (!isRecordValue(value)) throw new Error("worker input must be an object");
|
|
60
|
-
const unknown = Object.keys(value).filter(
|
|
65
|
+
const unknown = Object.keys(value).filter(
|
|
66
|
+
(key) => key !== "owner_id" && key !== "operations",
|
|
67
|
+
);
|
|
61
68
|
if (unknown.length > 0) {
|
|
62
69
|
throw new Error(`unknown worker field(s): ${unknown.join(", ")}`);
|
|
63
70
|
}
|
|
71
|
+
if (
|
|
72
|
+
typeof value["owner_id"] !== "string" ||
|
|
73
|
+
value["owner_id"].length === 0 ||
|
|
74
|
+
value["owner_id"].length > 256
|
|
75
|
+
) {
|
|
76
|
+
throw new Error(
|
|
77
|
+
"worker owner_id must be a non-empty string no longer than 256 characters",
|
|
78
|
+
);
|
|
79
|
+
}
|
|
64
80
|
if (!Array.isArray(value["operations"]) || value["operations"].length === 0) {
|
|
65
81
|
throw new Error("worker operations must be a non-empty array");
|
|
66
82
|
}
|
|
67
|
-
|
|
83
|
+
const operations = value["operations"].map((operation, index) => {
|
|
68
84
|
if (!isRecordValue(operation)) {
|
|
69
85
|
throw new Error(`worker operations[${index}] must be an object`);
|
|
70
86
|
}
|
|
@@ -74,6 +90,7 @@ function parseWorkerOperations(input: string): BrowserOperation[] {
|
|
|
74
90
|
}
|
|
75
91
|
return parsed;
|
|
76
92
|
});
|
|
93
|
+
return { operations, ownerId: value["owner_id"] };
|
|
77
94
|
}
|
|
78
95
|
|
|
79
96
|
function readLine(socket: Socket): Promise<string> {
|
|
@@ -121,12 +138,12 @@ async function handleConnection(
|
|
|
121
138
|
socket.once("error", abort);
|
|
122
139
|
let response: WorkerResponse;
|
|
123
140
|
try {
|
|
124
|
-
const
|
|
141
|
+
const request = parseWorkerRequest(await readLine(socket));
|
|
125
142
|
response = {
|
|
126
143
|
ok: true,
|
|
127
144
|
result: await runtime.execute(
|
|
128
|
-
{ operations },
|
|
129
|
-
{ signal: controller.signal },
|
|
145
|
+
{ operations: request.operations },
|
|
146
|
+
{ ownerId: request.ownerId, signal: controller.signal },
|
|
130
147
|
),
|
|
131
148
|
};
|
|
132
149
|
} catch (error) {
|
|
@@ -172,7 +189,7 @@ export async function serveBrowserWorker(workerId: string): Promise<void> {
|
|
|
172
189
|
if (idleTimer) clearTimeout(idleTimer);
|
|
173
190
|
process.removeListener("SIGINT", close);
|
|
174
191
|
process.removeListener("SIGTERM", close);
|
|
175
|
-
runtime.close();
|
|
192
|
+
await runtime.close();
|
|
176
193
|
if (!IS_WINDOWS && ownsSocket) await rm(path, { force: true });
|
|
177
194
|
}
|
|
178
195
|
}
|
|
@@ -25,12 +25,17 @@ export function browserParameters(hosts: readonly string[]) {
|
|
|
25
25
|
minLength: 1,
|
|
26
26
|
description: "Continuation handle returned by browser",
|
|
27
27
|
});
|
|
28
|
+
const fillValue = Type.Union([Type.String(), Type.Boolean()], {
|
|
29
|
+
description: "Replacement text/option; boolean for checkbox/radio",
|
|
30
|
+
});
|
|
31
|
+
const timeout = Type.Optional(Type.Integer({ minimum: 1, maximum: 60_000 }));
|
|
28
32
|
return Type.Union([
|
|
29
33
|
request({ action: StringEnum(["help", "start"] as const) }),
|
|
30
34
|
request({
|
|
31
35
|
action: Type.Literal("tabs"),
|
|
32
36
|
query: Type.Optional(Type.String({ minLength: 1 })),
|
|
33
37
|
offset: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
38
|
+
owned_only: Type.Optional(Type.Boolean()),
|
|
34
39
|
}),
|
|
35
40
|
request({
|
|
36
41
|
action: Type.Literal("open"),
|
|
@@ -49,6 +54,10 @@ export function browserParameters(hosts: readonly string[]) {
|
|
|
49
54
|
lineno: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
50
55
|
response_length: Type.Optional(responseLength),
|
|
51
56
|
}),
|
|
57
|
+
request({
|
|
58
|
+
action: StringEnum(["show", "close"] as const),
|
|
59
|
+
ref_id: refId,
|
|
60
|
+
}),
|
|
52
61
|
request({ action: Type.Literal("click"), ref_id: refId, id: elementId }),
|
|
53
62
|
request({
|
|
54
63
|
action: Type.Literal("click"),
|
|
@@ -67,6 +76,31 @@ export function browserParameters(hosts: readonly string[]) {
|
|
|
67
76
|
id: Type.Optional(elementId),
|
|
68
77
|
text: Type.String({ minLength: 1 }),
|
|
69
78
|
}),
|
|
79
|
+
request({
|
|
80
|
+
action: Type.Literal("fill"),
|
|
81
|
+
ref_id: refId,
|
|
82
|
+
id: elementId,
|
|
83
|
+
value: fillValue,
|
|
84
|
+
}),
|
|
85
|
+
request({
|
|
86
|
+
action: Type.Literal("fill"),
|
|
87
|
+
ref_id: refId,
|
|
88
|
+
selector: Type.String({ minLength: 1 }),
|
|
89
|
+
value: fillValue,
|
|
90
|
+
}),
|
|
91
|
+
request({
|
|
92
|
+
action: Type.Literal("press"),
|
|
93
|
+
ref_id: refId,
|
|
94
|
+
key: Type.String({ minLength: 1 }),
|
|
95
|
+
}),
|
|
96
|
+
...(["selector", "text", "url_includes"] as const).map((condition) =>
|
|
97
|
+
request({
|
|
98
|
+
action: Type.Literal("wait"),
|
|
99
|
+
ref_id: refId,
|
|
100
|
+
[condition]: Type.String({ minLength: 1 }),
|
|
101
|
+
timeout_ms: timeout,
|
|
102
|
+
}),
|
|
103
|
+
),
|
|
70
104
|
request({
|
|
71
105
|
action: StringEnum(["screenshot", "html"] as const),
|
|
72
106
|
ref_id: refId,
|
package/src/browser-tool.ts
CHANGED
|
@@ -45,8 +45,9 @@ export function createBrowserTool(runtime: BrowserRuntime) {
|
|
|
45
45
|
label: "Browser",
|
|
46
46
|
description: "Control logged-in browser; call help before other actions",
|
|
47
47
|
parameters,
|
|
48
|
-
async execute(_toolCallId, input, signal, onUpdate) {
|
|
48
|
+
async execute(_toolCallId, input, signal, onUpdate, ctx) {
|
|
49
49
|
const result = await runtime.execute(browserRequest(input), {
|
|
50
|
+
ownerId: ctx.sessionManager.getSessionId(),
|
|
50
51
|
signal: signal ?? new AbortController().signal,
|
|
51
52
|
onOperation(operation, index, total) {
|
|
52
53
|
onUpdate?.({
|