@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.
Files changed (115) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +22 -0
  3. package/README.md +47 -0
  4. package/biome.json +31 -0
  5. package/changelog.ts +337 -0
  6. package/dist/index.d.ts +3 -0
  7. package/dist/index.js +82 -0
  8. package/dist/remote-worker.d.ts +2 -0
  9. package/dist/remote-worker.js +3005 -0
  10. package/dist/src/browser/artifacts.d.ts +13 -0
  11. package/dist/src/browser/artifacts.js +133 -0
  12. package/dist/src/browser/bounds.d.ts +4 -0
  13. package/dist/src/browser/bounds.js +129 -0
  14. package/dist/src/browser/config.d.ts +11 -0
  15. package/dist/src/browser/config.js +106 -0
  16. package/dist/src/browser/help.d.ts +1 -0
  17. package/dist/src/browser/help.js +27 -0
  18. package/dist/src/browser/launcher.d.ts +8 -0
  19. package/dist/src/browser/launcher.js +169 -0
  20. package/dist/src/browser/operation-executor.d.ts +9 -0
  21. package/dist/src/browser/operation-executor.js +112 -0
  22. package/dist/src/browser/operation.d.ts +92 -0
  23. package/dist/src/browser/operation.js +20 -0
  24. package/dist/src/browser/parse-operation.d.ts +6 -0
  25. package/dist/src/browser/parse-operation.js +248 -0
  26. package/dist/src/browser/remote-helper.d.ts +3 -0
  27. package/dist/src/browser/remote-helper.js +114 -0
  28. package/dist/src/browser/remote-process.d.ts +7 -0
  29. package/dist/src/browser/remote-process.js +78 -0
  30. package/dist/src/browser/remote.d.ts +4 -0
  31. package/dist/src/browser/remote.js +73 -0
  32. package/dist/src/browser/request.d.ts +8 -0
  33. package/dist/src/browser/request.js +80 -0
  34. package/dist/src/browser/routes.d.ts +16 -0
  35. package/dist/src/browser/routes.js +40 -0
  36. package/dist/src/browser/runtime.d.ts +17 -0
  37. package/dist/src/browser/runtime.js +61 -0
  38. package/dist/src/browser/settings.d.ts +2 -0
  39. package/dist/src/browser/settings.js +164 -0
  40. package/dist/src/browser/worker-server.d.ts +2 -0
  41. package/dist/src/browser/worker-server.js +241 -0
  42. package/dist/src/browser-parameters.d.ts +42 -0
  43. package/dist/src/browser-parameters.js +113 -0
  44. package/dist/src/browser-tool.d.ts +48 -0
  45. package/dist/src/browser-tool.js +71 -0
  46. package/dist/src/cdp/actions/click.d.ts +4 -0
  47. package/dist/src/cdp/actions/click.js +56 -0
  48. package/dist/src/cdp/actions/element.d.ts +22 -0
  49. package/dist/src/cdp/actions/element.js +126 -0
  50. package/dist/src/cdp/actions/page.d.ts +7 -0
  51. package/dist/src/cdp/actions/page.js +127 -0
  52. package/dist/src/cdp/actions/screenshot.d.ts +10 -0
  53. package/dist/src/cdp/actions/screenshot.js +96 -0
  54. package/dist/src/cdp/actions/selector.d.ts +2 -0
  55. package/dist/src/cdp/actions/selector.js +41 -0
  56. package/dist/src/cdp/actions/type.d.ts +3 -0
  57. package/dist/src/cdp/actions/type.js +138 -0
  58. package/dist/src/cdp/client.d.ts +20 -0
  59. package/dist/src/cdp/client.js +248 -0
  60. package/dist/src/cdp/discovery.d.ts +7 -0
  61. package/dist/src/cdp/discovery.js +153 -0
  62. package/dist/src/cdp/evaluate.d.ts +3 -0
  63. package/dist/src/cdp/evaluate.js +31 -0
  64. package/dist/src/cdp/pages.d.ts +3 -0
  65. package/dist/src/cdp/pages.js +40 -0
  66. package/dist/src/cdp/serial.d.ts +1 -0
  67. package/dist/src/cdp/serial.js +18 -0
  68. package/dist/src/cdp/session.d.ts +25 -0
  69. package/dist/src/cdp/session.js +246 -0
  70. package/dist/src/cdp/snapshot-contract.d.ts +32 -0
  71. package/dist/src/cdp/snapshot-contract.js +23 -0
  72. package/dist/src/cdp/snapshot.d.ts +3 -0
  73. package/dist/src/cdp/snapshot.js +205 -0
  74. package/dist/src/cdp/types.d.ts +20 -0
  75. package/dist/src/cdp/types.js +14 -0
  76. package/dist/src/cdp/url.d.ts +1 -0
  77. package/dist/src/cdp/url.js +12 -0
  78. package/index.ts +115 -0
  79. package/package.json +93 -0
  80. package/remote-worker.ts +58 -0
  81. package/src/browser/artifacts.ts +178 -0
  82. package/src/browser/bounds.ts +159 -0
  83. package/src/browser/config.ts +162 -0
  84. package/src/browser/help.ts +30 -0
  85. package/src/browser/launcher.ts +208 -0
  86. package/src/browser/operation-executor.ts +251 -0
  87. package/src/browser/operation.ts +105 -0
  88. package/src/browser/parse-operation.ts +272 -0
  89. package/src/browser/remote-helper.ts +137 -0
  90. package/src/browser/remote-process.ts +85 -0
  91. package/src/browser/remote.ts +120 -0
  92. package/src/browser/request.ts +95 -0
  93. package/src/browser/routes.ts +69 -0
  94. package/src/browser/runtime.ts +84 -0
  95. package/src/browser/settings.ts +219 -0
  96. package/src/browser/worker-server.ts +274 -0
  97. package/src/browser-parameters.ts +118 -0
  98. package/src/browser-tool.ts +88 -0
  99. package/src/cdp/actions/click.ts +126 -0
  100. package/src/cdp/actions/element.ts +234 -0
  101. package/src/cdp/actions/page.ts +219 -0
  102. package/src/cdp/actions/screenshot.ts +176 -0
  103. package/src/cdp/actions/selector.ts +63 -0
  104. package/src/cdp/actions/type.ts +224 -0
  105. package/src/cdp/client.ts +286 -0
  106. package/src/cdp/discovery.ts +198 -0
  107. package/src/cdp/evaluate.ts +55 -0
  108. package/src/cdp/pages.ts +60 -0
  109. package/src/cdp/serial.ts +23 -0
  110. package/src/cdp/session.ts +345 -0
  111. package/src/cdp/snapshot-contract.ts +63 -0
  112. package/src/cdp/snapshot.ts +273 -0
  113. package/src/cdp/types.ts +49 -0
  114. package/src/cdp/url.ts +11 -0
  115. package/tsconfig.json +7 -0
@@ -0,0 +1,241 @@
1
+ import { spawn } from "node:child_process";
2
+ import { chmod, lstat, mkdir, rm } from "node:fs/promises";
3
+ import { createConnection, createServer } from "node:net";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { StringDecoder } from "node:string_decoder";
7
+ import { isRecordValue, parseActionRequest } from "./parse-operation.js";
8
+ import { BrowserRoutes } from "./routes.js";
9
+ import { BrowserRuntime } from "./runtime.js";
10
+ const INPUT_LIMIT_BYTES = 8 * 1_024 * 1_024;
11
+ const START_TIMEOUT_MS = 5_000;
12
+ const IDLE_TIMEOUT_MS = 20 * 60 * 1_000;
13
+ const IS_WINDOWS = process.platform === "win32";
14
+ function workerSocketPath(workerId) {
15
+ if (IS_WINDOWS)
16
+ return `\\\\.\\pipe\\pi-browser-worker-${workerId}`;
17
+ const directory = process.env["XDG_RUNTIME_DIR"]
18
+ ? join(process.env["XDG_RUNTIME_DIR"], "browser-tool")
19
+ : join(tmpdir(), `browser-tool-${process.getuid?.() ?? "user"}`);
20
+ return join(directory, `worker-${workerId}.sock`);
21
+ }
22
+ async function ensureWorkerSocketDirectory(workerId) {
23
+ if (IS_WINDOWS)
24
+ return;
25
+ const directory = dirname(workerSocketPath(workerId));
26
+ await mkdir(directory, { recursive: true, mode: 0o700 });
27
+ const info = await lstat(directory);
28
+ const uid = process.getuid?.();
29
+ if (info.isSymbolicLink() || !info.isDirectory()) {
30
+ throw new Error(`Browser worker socket directory is not a directory: ${directory}`);
31
+ }
32
+ if (uid === undefined || info.uid !== uid) {
33
+ throw new Error(`Browser worker socket directory is not owned by this user: ${directory}`);
34
+ }
35
+ if ((info.mode & 0o077) !== 0)
36
+ await chmod(directory, 0o700);
37
+ }
38
+ function parseWorkerOperations(input) {
39
+ let value;
40
+ try {
41
+ value = JSON.parse(input);
42
+ }
43
+ catch (error) {
44
+ throw new Error(`worker input must be valid JSON: ${error instanceof Error ? error.message : String(error)}`);
45
+ }
46
+ if (!isRecordValue(value))
47
+ throw new Error("worker input must be an object");
48
+ const unknown = Object.keys(value).filter((key) => key !== "operations");
49
+ if (unknown.length > 0) {
50
+ throw new Error(`unknown worker field(s): ${unknown.join(", ")}`);
51
+ }
52
+ if (!Array.isArray(value["operations"]) || value["operations"].length === 0) {
53
+ throw new Error("worker operations must be a non-empty array");
54
+ }
55
+ return value["operations"].map((operation, index) => {
56
+ if (!isRecordValue(operation)) {
57
+ throw new Error(`worker operations[${index}] must be an object`);
58
+ }
59
+ const parsed = parseActionRequest(operation);
60
+ if (parsed.action === "help") {
61
+ throw new Error("help is not a worker operation");
62
+ }
63
+ return parsed;
64
+ });
65
+ }
66
+ function readLine(socket) {
67
+ return new Promise((resolveValue, reject) => {
68
+ let input = "";
69
+ let bytes = 0;
70
+ const decoder = new StringDecoder("utf8");
71
+ const cleanup = () => {
72
+ socket.off("data", onData);
73
+ socket.off("end", onEnd);
74
+ socket.off("error", onError);
75
+ };
76
+ const onError = (error) => {
77
+ cleanup();
78
+ reject(error);
79
+ };
80
+ const onEnd = () => onError(new Error("Browser worker closed early"));
81
+ const onData = (chunk) => {
82
+ bytes += chunk.length;
83
+ if (bytes > INPUT_LIMIT_BYTES) {
84
+ cleanup();
85
+ reject(new Error("Browser worker input exceeded 8 MiB"));
86
+ return;
87
+ }
88
+ input += decoder.write(chunk);
89
+ const newline = input.indexOf("\n");
90
+ if (newline < 0)
91
+ return;
92
+ cleanup();
93
+ resolveValue(input.slice(0, newline));
94
+ };
95
+ socket.on("data", onData);
96
+ socket.once("end", onEnd);
97
+ socket.once("error", onError);
98
+ });
99
+ }
100
+ async function handleConnection(socket, runtime) {
101
+ const controller = new AbortController();
102
+ const abort = () => controller.abort(new Error("Browser worker requester disconnected"));
103
+ socket.once("close", abort);
104
+ socket.once("error", abort);
105
+ let response;
106
+ try {
107
+ const operations = parseWorkerOperations(await readLine(socket));
108
+ response = {
109
+ ok: true,
110
+ result: await runtime.execute({ operations }, { signal: controller.signal }),
111
+ };
112
+ }
113
+ catch (error) {
114
+ response = {
115
+ ok: false,
116
+ error: error instanceof Error ? error.message : String(error),
117
+ };
118
+ }
119
+ socket.off("close", abort);
120
+ socket.off("error", abort);
121
+ if (!socket.destroyed)
122
+ socket.end(`${JSON.stringify(response)}\n`);
123
+ }
124
+ export async function serveBrowserWorker(workerId) {
125
+ const path = workerSocketPath(workerId);
126
+ await ensureWorkerSocketDirectory(workerId);
127
+ const runtime = new BrowserRuntime(new BrowserRoutes());
128
+ let ownsSocket = false;
129
+ const server = createServer((socket) => {
130
+ resetIdle();
131
+ void handleConnection(socket, runtime).finally(resetIdle);
132
+ });
133
+ let idleTimer;
134
+ const close = () => server.close();
135
+ const resetIdle = () => {
136
+ if (idleTimer)
137
+ clearTimeout(idleTimer);
138
+ idleTimer = setTimeout(close, IDLE_TIMEOUT_MS);
139
+ idleTimer.unref?.();
140
+ };
141
+ process.once("SIGINT", close);
142
+ process.once("SIGTERM", close);
143
+ try {
144
+ await new Promise((resolveValue, reject) => {
145
+ server.once("error", reject);
146
+ server.listen(path, () => {
147
+ ownsSocket = true;
148
+ server.off("error", reject);
149
+ resetIdle();
150
+ });
151
+ server.once("close", resolveValue);
152
+ });
153
+ }
154
+ finally {
155
+ if (idleTimer)
156
+ clearTimeout(idleTimer);
157
+ process.removeListener("SIGINT", close);
158
+ process.removeListener("SIGTERM", close);
159
+ runtime.close();
160
+ if (!IS_WINDOWS && ownsSocket)
161
+ await rm(path, { force: true });
162
+ }
163
+ }
164
+ async function requestOnce(input, workerId, signal) {
165
+ if (signal?.aborted) {
166
+ return Promise.reject(signal.reason ?? new Error("Browser worker request aborted"));
167
+ }
168
+ await ensureWorkerSocketDirectory(workerId);
169
+ if (signal?.aborted) {
170
+ throw signal.reason ?? new Error("Browser worker request aborted");
171
+ }
172
+ return new Promise((resolveValue, reject) => {
173
+ const socket = createConnection(workerSocketPath(workerId));
174
+ const abort = () => {
175
+ socket.destroy();
176
+ reject(signal?.reason ?? new Error("Browser worker request aborted"));
177
+ };
178
+ signal?.addEventListener("abort", abort, { once: true });
179
+ socket.once("connect", () => socket.write(`${input}\n`));
180
+ void readLine(socket).then((line) => {
181
+ signal?.removeEventListener("abort", abort);
182
+ socket.destroy();
183
+ try {
184
+ const response = JSON.parse(line);
185
+ if (!isRecordValue(response) || typeof response["ok"] !== "boolean") {
186
+ throw new Error("Browser worker returned an invalid response");
187
+ }
188
+ resolveValue(response);
189
+ }
190
+ catch (error) {
191
+ reject(error);
192
+ }
193
+ }, (error) => {
194
+ signal?.removeEventListener("abort", abort);
195
+ socket.destroy();
196
+ reject(error);
197
+ });
198
+ });
199
+ }
200
+ function canStartWorker(error) {
201
+ return (error instanceof Error &&
202
+ "code" in error &&
203
+ (error.code === "ENOENT" || error.code === "ECONNREFUSED"));
204
+ }
205
+ export async function requestBrowserWorker(input, entryPath, workerId, signal) {
206
+ try {
207
+ const response = await requestOnce(input, workerId, signal);
208
+ if (!response.ok)
209
+ throw new Error(response.error ?? "Browser worker failed");
210
+ if (!response.result)
211
+ throw new Error("Browser worker returned no result");
212
+ return response.result;
213
+ }
214
+ catch (error) {
215
+ if (!canStartWorker(error))
216
+ throw error;
217
+ }
218
+ if (!IS_WINDOWS)
219
+ await rm(workerSocketPath(workerId), { force: true });
220
+ const child = spawn(process.execPath, ["--preserve-symlinks-main", entryPath, "--daemon"], { detached: true, stdio: "ignore" });
221
+ child.unref();
222
+ const deadline = Date.now() + START_TIMEOUT_MS;
223
+ let lastError;
224
+ while (Date.now() < deadline) {
225
+ try {
226
+ const response = await requestOnce(input, workerId, signal);
227
+ if (!response.ok)
228
+ throw new Error(response.error ?? "Browser worker failed");
229
+ if (!response.result)
230
+ throw new Error("Browser worker returned no result");
231
+ return response.result;
232
+ }
233
+ catch (error) {
234
+ if (!canStartWorker(error))
235
+ throw error;
236
+ lastError = error;
237
+ await new Promise((resolveValue) => setTimeout(resolveValue, 50));
238
+ }
239
+ }
240
+ throw new Error(`Browser worker did not start within ${START_TIMEOUT_MS}ms${lastError instanceof Error ? `: ${lastError.message}` : ""}`);
241
+ }
@@ -0,0 +1,42 @@
1
+ import { type TSchema, Type } from "typebox";
2
+ export declare function browserParameters(hosts: readonly string[]): Type.TUnion<[Type.TObject<{
3
+ [x: string]: TSchema;
4
+ }>, Type.TObject<{
5
+ [x: string]: TSchema;
6
+ }>, Type.TObject<{
7
+ [x: string]: TSchema;
8
+ }>, Type.TObject<{
9
+ [x: string]: TSchema;
10
+ }>, Type.TObject<{
11
+ [x: string]: TSchema;
12
+ }>, Type.TObject<{
13
+ [x: string]: TSchema;
14
+ }>, Type.TObject<{
15
+ [x: string]: TSchema;
16
+ }>, Type.TObject<{
17
+ [x: string]: TSchema;
18
+ }>, Type.TObject<{
19
+ [x: string]: TSchema;
20
+ }>, Type.TObject<{
21
+ [x: string]: TSchema;
22
+ }>, Type.TObject<{
23
+ [x: string]: TSchema;
24
+ }>, Type.TObject<{
25
+ [x: string]: TSchema;
26
+ }>, Type.TObject<{
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;
38
+ }>, Type.TObject<{
39
+ [x: string]: TSchema;
40
+ }>, Type.TObject<{
41
+ [x: string]: TSchema;
42
+ }>]>;
@@ -0,0 +1,113 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import { Type } from "typebox";
3
+ export function browserParameters(hosts) {
4
+ const route = hosts.length > 0
5
+ ? {
6
+ host: Type.Optional(StringEnum(hosts, { description: "Configured browser host" })),
7
+ }
8
+ : {};
9
+ const request = (properties) => Type.Object({ ...route, ...properties }, { additionalProperties: false });
10
+ const refId = Type.String({
11
+ minLength: 1,
12
+ description: "Tab ref_id returned by tabs",
13
+ });
14
+ const elementId = Type.Integer({
15
+ minimum: 1,
16
+ description: "Element id returned by open or find",
17
+ });
18
+ const responseLength = StringEnum(["short", "medium", "long"]);
19
+ const handle = Type.String({
20
+ minLength: 1,
21
+ description: "Continuation handle returned by browser",
22
+ });
23
+ return Type.Union([
24
+ request({ action: StringEnum(["help", "start"]) }),
25
+ request({
26
+ action: Type.Literal("tabs"),
27
+ query: Type.Optional(Type.String({ minLength: 1 })),
28
+ offset: Type.Optional(Type.Integer({ minimum: 0 })),
29
+ }),
30
+ request({
31
+ action: Type.Literal("open"),
32
+ ref_id: refId,
33
+ lineno: Type.Optional(Type.Integer({ minimum: 1 })),
34
+ response_length: Type.Optional(responseLength),
35
+ }),
36
+ request({
37
+ action: Type.Literal("open"),
38
+ url: Type.String({ minLength: 1 }),
39
+ }),
40
+ request({
41
+ action: Type.Literal("find"),
42
+ ref_id: refId,
43
+ pattern: Type.String({ minLength: 1 }),
44
+ lineno: Type.Optional(Type.Integer({ minimum: 1 })),
45
+ response_length: Type.Optional(responseLength),
46
+ }),
47
+ request({ action: Type.Literal("click"), ref_id: refId, id: elementId }),
48
+ request({
49
+ action: Type.Literal("click"),
50
+ ref_id: refId,
51
+ selector: Type.String({ minLength: 1 }),
52
+ }),
53
+ request({
54
+ action: Type.Literal("click"),
55
+ ref_id: refId,
56
+ x: Type.Number(),
57
+ y: Type.Number(),
58
+ }),
59
+ request({
60
+ action: Type.Literal("type"),
61
+ ref_id: refId,
62
+ id: Type.Optional(elementId),
63
+ text: Type.String({ minLength: 1 }),
64
+ }),
65
+ request({
66
+ action: StringEnum(["screenshot", "html"]),
67
+ ref_id: refId,
68
+ }),
69
+ request({
70
+ action: StringEnum(["screenshot", "html"]),
71
+ ref_id: refId,
72
+ id: elementId,
73
+ }),
74
+ request({
75
+ action: StringEnum(["screenshot", "html"]),
76
+ ref_id: refId,
77
+ selector: Type.String({ minLength: 1 }),
78
+ }),
79
+ request({
80
+ action: Type.Literal("navigate"),
81
+ ref_id: refId,
82
+ url: Type.String({ minLength: 1 }),
83
+ }),
84
+ request({
85
+ action: Type.Literal("evaluate"),
86
+ ref_id: refId,
87
+ expression: Type.String({ minLength: 1 }),
88
+ }),
89
+ request({ action: Type.Literal("network"), ref_id: refId }),
90
+ request({
91
+ action: Type.Literal("load_all"),
92
+ ref_id: refId,
93
+ selector: Type.String({ minLength: 1 }),
94
+ interval_ms: Type.Optional(Type.Integer({ minimum: 0, maximum: 60_000 })),
95
+ }),
96
+ request({
97
+ action: Type.Literal("raw"),
98
+ ref_id: refId,
99
+ method: Type.String({ minLength: 1 }),
100
+ params: Type.Optional(Type.Object({}, { additionalProperties: true })),
101
+ }),
102
+ request({
103
+ action: Type.Literal("read_result"),
104
+ handle,
105
+ offset: Type.Optional(Type.Integer({ minimum: 0 })),
106
+ }),
107
+ request({ action: Type.Literal("discard_result"), handle }),
108
+ request({
109
+ action: Type.Literal("stop"),
110
+ ref_id: Type.Optional(refId),
111
+ }),
112
+ ]);
113
+ }
@@ -0,0 +1,48 @@
1
+ import { BROWSER_ACTIONS } from "./browser/operation.js";
2
+ import { BrowserRuntime } from "./browser/runtime.js";
3
+ interface BrowserToolParams {
4
+ action: (typeof BROWSER_ACTIONS)[number];
5
+ }
6
+ export declare function prepareBrowserCodeModeInput(input: unknown): BrowserToolParams;
7
+ export declare function createBrowserTool(runtime: BrowserRuntime): import("@earendil-works/pi-coding-agent").ToolDefinition<import("typebox").TUnion<[import("typebox").TObject<{
8
+ [x: string]: import("typebox").TSchema;
9
+ }>, import("typebox").TObject<{
10
+ [x: string]: import("typebox").TSchema;
11
+ }>, import("typebox").TObject<{
12
+ [x: string]: import("typebox").TSchema;
13
+ }>, import("typebox").TObject<{
14
+ [x: string]: import("typebox").TSchema;
15
+ }>, import("typebox").TObject<{
16
+ [x: string]: import("typebox").TSchema;
17
+ }>, import("typebox").TObject<{
18
+ [x: string]: import("typebox").TSchema;
19
+ }>, import("typebox").TObject<{
20
+ [x: string]: import("typebox").TSchema;
21
+ }>, import("typebox").TObject<{
22
+ [x: string]: import("typebox").TSchema;
23
+ }>, import("typebox").TObject<{
24
+ [x: string]: import("typebox").TSchema;
25
+ }>, import("typebox").TObject<{
26
+ [x: string]: import("typebox").TSchema;
27
+ }>, import("typebox").TObject<{
28
+ [x: string]: import("typebox").TSchema;
29
+ }>, import("typebox").TObject<{
30
+ [x: string]: import("typebox").TSchema;
31
+ }>, import("typebox").TObject<{
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;
43
+ }>, import("typebox").TObject<{
44
+ [x: string]: import("typebox").TSchema;
45
+ }>, import("typebox").TObject<{
46
+ [x: string]: import("typebox").TSchema;
47
+ }>]>, unknown, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>;
48
+ export {};
@@ -0,0 +1,71 @@
1
+ import { defineTool } from "@earendil-works/pi-coding-agent";
2
+ import { BROWSER_ACTIONS } from "./browser/operation.js";
3
+ import { parseBrowserRequest } from "./browser/request.js";
4
+ import { BrowserRuntime } from "./browser/runtime.js";
5
+ import { browserParameters } from "./browser-parameters.js";
6
+ const preparedBrowserRequest = Symbol("preparedBrowserRequest");
7
+ export function prepareBrowserCodeModeInput(input) {
8
+ // Freeform requests can batch operations that the normal Pi schema does not
9
+ // expose. Carry the parsed request beside a schema-valid adapter input.
10
+ const prepared = { action: "help" };
11
+ Object.defineProperty(prepared, preparedBrowserRequest, {
12
+ value: parseBrowserRequest(input),
13
+ });
14
+ return prepared;
15
+ }
16
+ function isPreparedBrowserInput(input) {
17
+ return (typeof input === "object" &&
18
+ input !== null &&
19
+ preparedBrowserRequest in input);
20
+ }
21
+ function browserRequest(input) {
22
+ return isPreparedBrowserInput(input)
23
+ ? input[preparedBrowserRequest]
24
+ : parseBrowserRequest(input);
25
+ }
26
+ export function createBrowserTool(runtime) {
27
+ const parameters = browserParameters(runtime.hosts);
28
+ return defineTool({
29
+ name: "browser",
30
+ label: "Browser",
31
+ description: "Inspect and control logged-in browser tabs with bounded accessibility content, interactive references, continuations and expert CDP actions.",
32
+ parameters,
33
+ promptSnippet: "Help first.",
34
+ promptGuidelines: [
35
+ "browser: tabs -> open; keep ref_id/id/cursors with their result.",
36
+ ...(runtime.hosts.length > 0
37
+ ? [
38
+ "browser: Keep a user-named host on every call and its refs/handles.",
39
+ ]
40
+ : []),
41
+ "browser: Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser.",
42
+ ],
43
+ async execute(_toolCallId, input, signal, onUpdate) {
44
+ const result = await runtime.execute(browserRequest(input), {
45
+ signal: signal ?? new AbortController().signal,
46
+ onOperation(operation, index, total) {
47
+ onUpdate?.({
48
+ content: [
49
+ {
50
+ type: "text",
51
+ text: total === 1
52
+ ? `Browser ${operation.action}`
53
+ : `Browser ${operation.action} ${index + 1}/${total}`,
54
+ },
55
+ ],
56
+ details: {
57
+ action: operation.action,
58
+ index: index + 1,
59
+ total,
60
+ status: "running",
61
+ },
62
+ });
63
+ },
64
+ });
65
+ return {
66
+ content: [{ type: "text", text: JSON.stringify(result) }],
67
+ details: result,
68
+ };
69
+ },
70
+ });
71
+ }
@@ -0,0 +1,4 @@
1
+ import type { CdpConnection, ElementRefs } from "../types.js";
2
+ export declare function clickSelector(cdp: CdpConnection, sessionId: string, selector: string, signal?: AbortSignal): Promise<string>;
3
+ export declare function clickRef(cdp: CdpConnection, sessionId: string, elementRefs: ElementRefs, id: number | string, signal?: AbortSignal): Promise<string>;
4
+ export declare function clickCoordinates(cdp: CdpConnection, sessionId: string, x: number, y: number, signal?: AbortSignal): Promise<string>;
@@ -0,0 +1,56 @@
1
+ import { sleep } from "../discovery.js";
2
+ import { backendCenter, requireElementRef, } from "./element.js";
3
+ import { selectorBackendNode } from "./selector.js";
4
+ function dispatchMouse(cdp, sessionId, type, point, signal) {
5
+ return cdp.send("Input.dispatchMouseEvent", {
6
+ x: point.x,
7
+ y: point.y,
8
+ button: "left",
9
+ clickCount: 1,
10
+ modifiers: 0,
11
+ type,
12
+ }, sessionId, signal);
13
+ }
14
+ async function pressAndRelease(cdp, sessionId, point, signal) {
15
+ let pressed = false;
16
+ try {
17
+ await dispatchMouse(cdp, sessionId, "mousePressed", point, signal);
18
+ pressed = true;
19
+ await sleep(50, signal);
20
+ await dispatchMouse(cdp, sessionId, "mouseReleased", point, signal);
21
+ pressed = false;
22
+ }
23
+ finally {
24
+ if (pressed) {
25
+ await dispatchMouse(cdp, sessionId, "mouseReleased", point, undefined).catch(() => undefined);
26
+ }
27
+ }
28
+ }
29
+ async function clickBackendNode(cdp, sessionId, backendNodeId, signal) {
30
+ const initial = await backendCenter(cdp, sessionId, backendNodeId, true, signal);
31
+ await dispatchMouse(cdp, sessionId, "mouseMoved", initial, signal);
32
+ const point = await backendCenter(cdp, sessionId, backendNodeId, false, signal);
33
+ await pressAndRelease(cdp, sessionId, point, signal);
34
+ return point;
35
+ }
36
+ export async function clickSelector(cdp, sessionId, selector, signal) {
37
+ if (!selector)
38
+ throw new Error("CSS selector required");
39
+ const backendNodeId = await selectorBackendNode(cdp, sessionId, selector, signal);
40
+ const point = await clickBackendNode(cdp, sessionId, backendNodeId, signal);
41
+ return `Clicked <${point.tag}> "${point.text}"`;
42
+ }
43
+ export async function clickRef(cdp, sessionId, elementRefs, id, signal) {
44
+ const ref = requireElementRef(elementRefs, id);
45
+ await clickBackendNode(cdp, sessionId, ref.backendNodeId, signal);
46
+ return `Clicked element ${ref.id}`;
47
+ }
48
+ export async function clickCoordinates(cdp, sessionId, x, y, signal) {
49
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
50
+ throw new Error("x and y must be finite CSS-pixel numbers");
51
+ }
52
+ const point = { x, y };
53
+ await dispatchMouse(cdp, sessionId, "mouseMoved", point, signal);
54
+ await pressAndRelease(cdp, sessionId, point, signal);
55
+ return `Clicked at CSS (${x}, ${y})`;
56
+ }
@@ -0,0 +1,22 @@
1
+ import type { CdpConnection, ElementRefs } from "../types.js";
2
+ export interface ElementPoint {
3
+ x: number;
4
+ y: number;
5
+ tag: string;
6
+ text: string;
7
+ }
8
+ export interface ScreenshotClip {
9
+ x: number;
10
+ y: number;
11
+ width: number;
12
+ height: number;
13
+ scale: number;
14
+ }
15
+ export declare function requireElementRef(elementRefs: ElementRefs, id: number | string): {
16
+ id: number;
17
+ backendNodeId: number;
18
+ };
19
+ export declare function withBackendObject<T>(cdp: CdpConnection, sessionId: string, backendNodeId: number, action: (objectId: string) => Promise<T>, signal?: AbortSignal): Promise<T>;
20
+ export declare function scrollBackendIntoView(cdp: CdpConnection, sessionId: string, backendNodeId: number, signal?: AbortSignal): Promise<void>;
21
+ export declare function backendCenter(cdp: CdpConnection, sessionId: string, backendNodeId: number, scroll?: boolean, signal?: AbortSignal): Promise<ElementPoint>;
22
+ export declare function visibleElementClip(cdp: CdpConnection, sessionId: string, quad: number[], padding?: number, signal?: AbortSignal): Promise<ScreenshotClip>;