@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,272 @@
1
+ import type { SnapshotResponseLength } from "../cdp/snapshot-contract.js";
2
+ import {
3
+ BROWSER_ACTIONS,
4
+ type BrowserAction,
5
+ type BrowserOperation,
6
+ } from "./operation.js";
7
+
8
+ export type ActionRequest = BrowserOperation | { action: "help" };
9
+
10
+ const fields = (...names: string[]) => new Set(["action", ...names]);
11
+
12
+ const ACTION_FIELDS: Record<BrowserAction, ReadonlySet<string>> = {
13
+ help: fields(),
14
+ start: fields(),
15
+ tabs: fields("query", "offset"),
16
+ open: fields("ref_id", "url", "lineno", "response_length"),
17
+ find: fields("ref_id", "pattern", "lineno", "response_length"),
18
+ click: fields("ref_id", "id", "selector", "x", "y"),
19
+ type: fields("ref_id", "id", "text"),
20
+ screenshot: fields("ref_id", "id", "selector"),
21
+ html: fields("ref_id", "id", "selector"),
22
+ navigate: fields("ref_id", "url"),
23
+ evaluate: fields("ref_id", "expression"),
24
+ network: fields("ref_id"),
25
+ load_all: fields("ref_id", "selector", "interval_ms"),
26
+ raw: fields("ref_id", "method", "params"),
27
+ read_result: fields("handle", "offset"),
28
+ discard_result: fields("handle"),
29
+ stop: fields("ref_id"),
30
+ };
31
+
32
+ function isRecord(value: unknown): value is Record<string, unknown> {
33
+ return typeof value === "object" && value !== null && !Array.isArray(value);
34
+ }
35
+
36
+ function requiredString(value: unknown, field: string): string {
37
+ if (typeof value !== "string" || !value.trim()) {
38
+ throw new Error(`${field} must be a non-empty string`);
39
+ }
40
+ return value.trim();
41
+ }
42
+
43
+ function optionalString(value: unknown, field: string): string | undefined {
44
+ if (value === undefined) return undefined;
45
+ return requiredString(value, field);
46
+ }
47
+
48
+ function requiredRef(value: unknown, action: BrowserAction): string {
49
+ if (typeof value !== "string" || !value.trim()) {
50
+ throw new Error(
51
+ `${action} requires a ref_id returned by tabs; call tabs first`,
52
+ );
53
+ }
54
+ return value.trim();
55
+ }
56
+
57
+ function offset(value: unknown, field = "offset", fallback = 0): number {
58
+ if (value === undefined) return fallback;
59
+ if (!Number.isInteger(value) || Number(value) < 0) {
60
+ throw new Error(`${field} must be a non-negative integer`);
61
+ }
62
+ return Number(value);
63
+ }
64
+
65
+ function line(value: unknown): number {
66
+ const parsed = offset(value, "lineno", 1);
67
+ if (parsed < 1) throw new Error("lineno must be at least 1");
68
+ return parsed;
69
+ }
70
+
71
+ function elementId(value: unknown): number | undefined {
72
+ if (value === undefined) return undefined;
73
+ if (!Number.isInteger(value) || Number(value) < 1) {
74
+ throw new Error("id must be a positive integer from open/find");
75
+ }
76
+ return Number(value);
77
+ }
78
+
79
+ function responseLength(value: unknown): SnapshotResponseLength {
80
+ if (value === undefined) return "medium";
81
+ if (value !== "short" && value !== "medium" && value !== "long") {
82
+ throw new Error("response_length must be one of: short, medium, long");
83
+ }
84
+ return value;
85
+ }
86
+
87
+ function resultHandle(value: unknown): string {
88
+ const handle = requiredString(value, "handle");
89
+ if (!/^[a-f0-9-]{36}$/.test(handle)) {
90
+ throw new Error("handle is invalid");
91
+ }
92
+ return handle;
93
+ }
94
+
95
+ function browserAction(value: unknown): BrowserAction {
96
+ if (
97
+ typeof value !== "string" ||
98
+ !BROWSER_ACTIONS.includes(value as BrowserAction)
99
+ ) {
100
+ throw new Error(`action must be one of: ${BROWSER_ACTIONS.join(", ")}`);
101
+ }
102
+ return value as BrowserAction;
103
+ }
104
+
105
+ export function parseActionRequest(value: unknown): ActionRequest {
106
+ if (!isRecord(value)) throw new Error("input must be a JSON object");
107
+ const action = browserAction(value["action"]);
108
+ const unknown = Object.keys(value).filter(
109
+ (key) => !ACTION_FIELDS[action].has(key),
110
+ );
111
+ if (unknown.length > 0) {
112
+ throw new Error(`unknown ${action} field(s): ${unknown.join(", ")}`);
113
+ }
114
+ if (action === "help" || action === "start") return { action };
115
+ if (action === "tabs") {
116
+ const query = optionalString(value["query"], "query");
117
+ return {
118
+ action,
119
+ ...(query ? { query } : {}),
120
+ offset: offset(value["offset"]),
121
+ };
122
+ }
123
+ if (action === "open") {
124
+ const refId = optionalString(value["ref_id"], "ref_id");
125
+ const url = optionalString(value["url"], "url");
126
+ if (Boolean(refId) === Boolean(url)) {
127
+ throw new Error("open requires exactly one of ref_id or url");
128
+ }
129
+ if (url) return { action, url };
130
+ if (!refId) throw new Error("open requires ref_id or url");
131
+ return {
132
+ action,
133
+ ref_id: refId,
134
+ lineno: line(value["lineno"]),
135
+ response_length: responseLength(value["response_length"]),
136
+ };
137
+ }
138
+ if (action === "find") {
139
+ return {
140
+ action,
141
+ ref_id: requiredRef(value["ref_id"], action),
142
+ pattern: requiredString(value["pattern"], "pattern"),
143
+ lineno: line(value["lineno"]),
144
+ response_length: responseLength(value["response_length"]),
145
+ };
146
+ }
147
+ if (action === "read_result") {
148
+ return {
149
+ action,
150
+ handle: resultHandle(value["handle"]),
151
+ offset: offset(value["offset"]),
152
+ };
153
+ }
154
+ if (action === "discard_result") {
155
+ return { action, handle: resultHandle(value["handle"]) };
156
+ }
157
+ if (action === "stop") {
158
+ const refId = optionalString(value["ref_id"], "ref_id");
159
+ return { action, ...(refId ? { ref_id: refId } : {}) };
160
+ }
161
+
162
+ const refId = requiredRef(value["ref_id"], action);
163
+ if (action === "network") return { action, ref_id: refId };
164
+ if (action === "navigate") {
165
+ return {
166
+ action,
167
+ ref_id: refId,
168
+ url: requiredString(value["url"], "url"),
169
+ };
170
+ }
171
+ if (action === "evaluate") {
172
+ return {
173
+ action,
174
+ ref_id: refId,
175
+ expression: requiredString(value["expression"], "expression"),
176
+ };
177
+ }
178
+ if (action === "click") {
179
+ const id = elementId(value["id"]);
180
+ const selector = optionalString(value["selector"], "selector");
181
+ const hasX = value["x"] !== undefined;
182
+ const hasY = value["y"] !== undefined;
183
+ let coordinates: { x: number; y: number } | undefined;
184
+ if (hasX !== hasY) {
185
+ throw new Error("click coordinates require both x and y");
186
+ }
187
+ if (
188
+ hasX &&
189
+ (typeof value["x"] !== "number" ||
190
+ !Number.isFinite(value["x"]) ||
191
+ typeof value["y"] !== "number" ||
192
+ !Number.isFinite(value["y"]))
193
+ ) {
194
+ throw new Error("x and y must be finite CSS-pixel numbers");
195
+ }
196
+ if (typeof value["x"] === "number" && typeof value["y"] === "number") {
197
+ coordinates = { x: value["x"], y: value["y"] };
198
+ }
199
+ if (
200
+ Number(id !== undefined) + Number(Boolean(selector)) + Number(hasX) !==
201
+ 1
202
+ ) {
203
+ throw new Error("click requires exactly one of id, selector, or x+y");
204
+ }
205
+ if (id !== undefined) return { action, ref_id: refId, id };
206
+ if (selector) return { action, ref_id: refId, selector };
207
+ if (coordinates) {
208
+ return { action, ref_id: refId, ...coordinates };
209
+ }
210
+ throw new Error("click requires id, selector, or x+y");
211
+ }
212
+ if (action === "type") {
213
+ if (typeof value["text"] !== "string" || value["text"].length === 0) {
214
+ throw new Error("text must be a non-empty string");
215
+ }
216
+ const id = elementId(value["id"]);
217
+ return {
218
+ action,
219
+ ref_id: refId,
220
+ ...(id === undefined ? {} : { id }),
221
+ text: value["text"],
222
+ };
223
+ }
224
+ if (action === "screenshot" || action === "html") {
225
+ const id = elementId(value["id"]);
226
+ const selector = optionalString(value["selector"], "selector");
227
+ if (id !== undefined && selector) {
228
+ throw new Error(`${action} accepts id or selector, not both`);
229
+ }
230
+ return {
231
+ action,
232
+ ref_id: refId,
233
+ ...(id === undefined ? {} : { id }),
234
+ ...(selector ? { selector } : {}),
235
+ };
236
+ }
237
+ if (action === "load_all") {
238
+ const interval = value["interval_ms"] ?? 1_500;
239
+ if (
240
+ !Number.isInteger(interval) ||
241
+ Number(interval) < 0 ||
242
+ Number(interval) > 60_000
243
+ ) {
244
+ throw new Error("interval_ms must be an integer from 0 to 60000");
245
+ }
246
+ return {
247
+ action,
248
+ ref_id: refId,
249
+ selector: requiredString(value["selector"], "selector"),
250
+ interval_ms: Number(interval),
251
+ };
252
+ }
253
+ if (action === "raw") {
254
+ const params = value["params"] ?? {};
255
+ if (!isRecord(params)) {
256
+ throw new Error("params must be an object when provided");
257
+ }
258
+ return {
259
+ action,
260
+ ref_id: refId,
261
+ method: requiredString(value["method"], "method"),
262
+ params,
263
+ };
264
+ }
265
+ throw new Error(`unsupported action: ${action}`);
266
+ }
267
+
268
+ export function isRecordValue(
269
+ value: unknown,
270
+ ): value is Record<string, unknown> {
271
+ return isRecord(value);
272
+ }
@@ -0,0 +1,137 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { fileURLToPath } from "node:url";
3
+ import { abortReason, runProgram } from "./remote-process.js";
4
+ import type { BrowserRemoteCommand } from "./routes.js";
5
+
6
+ const DEPLOY_TIMEOUT_MS = 20_000;
7
+ const REMOTE_HELPER = "~/.pi/agent/pi-browser-worker.mjs";
8
+ const deployments = new Map<string, Promise<void>>();
9
+ let helperSourcePromise: Promise<string> | undefined;
10
+
11
+ const DEPLOY_SOURCE = String.raw`
12
+ const { randomUUID } = require("node:crypto");
13
+ const { mkdir, readFile, rename, unlink, writeFile } = require("node:fs/promises");
14
+ const { homedir } = require("node:os");
15
+ const { dirname, join } = require("node:path");
16
+ const targetValue = process.argv[1];
17
+ const marker = "// @howaboua/pi-browser managed worker";
18
+ const target = targetValue === "~" ? homedir() : targetValue.startsWith("~/") ? join(homedir(), targetValue.slice(2)) : targetValue;
19
+ const chunks = [];
20
+ let size = 0;
21
+ 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); });
22
+ process.stdin.on("end", () => { void (async () => {
23
+ const source = Buffer.concat(chunks);
24
+ let existing;
25
+ try { existing = await readFile(target); } catch (error) { if (error.code !== "ENOENT") throw error; }
26
+ if (existing) {
27
+ if (existing.equals(source)) { process.stdout.write(JSON.stringify({ updated: false, path: target }) + "\n"); return; }
28
+ if (!existing.toString("utf8", 0, 512).includes(marker)) throw new Error(target + " is not owned by pi-browser");
29
+ }
30
+ await mkdir(dirname(target), { recursive: true, mode: 0o700 });
31
+ const temporary = target + "." + process.pid + "." + randomUUID() + ".tmp";
32
+ try {
33
+ await writeFile(temporary, source, { mode: 0o600, flag: "wx" });
34
+ await rename(temporary, target);
35
+ } catch (error) {
36
+ await unlink(temporary).catch(() => undefined);
37
+ throw error;
38
+ }
39
+ process.stdout.write(JSON.stringify({ updated: true, path: target }) + "\n");
40
+ })().catch(error => { process.stderr.write(error.message + "\n"); process.exit(1); }); });
41
+ `;
42
+
43
+ export function remoteNodeCommand(command: BrowserRemoteCommand): string {
44
+ return `${command.nodePath} --preserve-symlinks-main "$HOME"/.pi/agent/pi-browser-worker.mjs`;
45
+ }
46
+
47
+ function shellQuote(value: string): string {
48
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
49
+ }
50
+
51
+ function waitFor<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
52
+ if (!signal) return promise;
53
+ if (signal.aborted) return Promise.reject(abortReason(signal));
54
+ return new Promise((resolveValue, reject) => {
55
+ const abort = () => {
56
+ cleanup();
57
+ reject(abortReason(signal));
58
+ };
59
+ const cleanup = () => signal.removeEventListener("abort", abort);
60
+ signal.addEventListener("abort", abort, { once: true });
61
+ promise.then(
62
+ (value) => {
63
+ cleanup();
64
+ resolveValue(value);
65
+ },
66
+ (error) => {
67
+ cleanup();
68
+ reject(error);
69
+ },
70
+ );
71
+ });
72
+ }
73
+
74
+ async function readHelperSource(): Promise<string> {
75
+ const candidates = [
76
+ fileURLToPath(new URL("../../remote-worker.js", import.meta.url)),
77
+ fileURLToPath(new URL("../../dist/remote-worker.js", import.meta.url)),
78
+ ];
79
+ let lastError: unknown;
80
+ for (const path of candidates) {
81
+ try {
82
+ return await readFile(path, "utf8");
83
+ } catch (error) {
84
+ lastError = error;
85
+ }
86
+ }
87
+ throw new Error(
88
+ `Could not read bundled browser worker: ${lastError instanceof Error ? lastError.message : String(lastError)}`,
89
+ );
90
+ }
91
+
92
+ async function deployRemoteHelper(
93
+ host: string,
94
+ command: BrowserRemoteCommand,
95
+ ): Promise<void> {
96
+ helperSourcePromise ??= readHelperSource();
97
+ let source: string;
98
+ try {
99
+ source = await helperSourcePromise;
100
+ } catch (error) {
101
+ helperSourcePromise = undefined;
102
+ throw error;
103
+ }
104
+ const deployment = await runProgram(
105
+ "ssh",
106
+ [
107
+ host,
108
+ `${command.nodePath} -e ${shellQuote(DEPLOY_SOURCE)} ${shellQuote(REMOTE_HELPER)}`,
109
+ ],
110
+ source,
111
+ AbortSignal.timeout(DEPLOY_TIMEOUT_MS),
112
+ );
113
+ if (deployment.code !== 0) {
114
+ throw new Error(
115
+ deployment.stderr ||
116
+ deployment.stdout ||
117
+ "could not deploy remote browser worker",
118
+ );
119
+ }
120
+ }
121
+
122
+ export async function ensureRemoteHelper(
123
+ host: string,
124
+ command: BrowserRemoteCommand,
125
+ signal?: AbortSignal,
126
+ ): Promise<void> {
127
+ const key = `${host}\0${command.nodePath}`;
128
+ let deployment = deployments.get(key);
129
+ if (!deployment) {
130
+ deployment = deployRemoteHelper(host, command);
131
+ deployments.set(key, deployment);
132
+ void deployment.catch(() => {
133
+ if (deployments.get(key) === deployment) deployments.delete(key);
134
+ });
135
+ }
136
+ await waitFor(deployment, signal);
137
+ }
@@ -0,0 +1,85 @@
1
+ import { spawn } from "node:child_process";
2
+ import { StringDecoder } from "node:string_decoder";
3
+
4
+ const OUTPUT_LIMIT_BYTES = 8 * 1_024 * 1_024;
5
+
6
+ export interface ProcessResult {
7
+ code: number;
8
+ stderr: string;
9
+ stdout: string;
10
+ }
11
+
12
+ export function abortReason(signal: AbortSignal): Error {
13
+ return signal.reason instanceof Error
14
+ ? signal.reason
15
+ : new Error("Remote browser operation aborted");
16
+ }
17
+
18
+ export function runProgram(
19
+ command: string,
20
+ args: string[],
21
+ input: string | undefined,
22
+ signal?: AbortSignal,
23
+ ): Promise<ProcessResult> {
24
+ if (signal?.aborted) return Promise.reject(abortReason(signal));
25
+ return new Promise((resolveValue, reject) => {
26
+ const child = spawn(command, args, {
27
+ stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
28
+ });
29
+ let stdout = "";
30
+ let stderr = "";
31
+ const stdoutDecoder = new StringDecoder("utf8");
32
+ const stderrDecoder = new StringDecoder("utf8");
33
+ let bytes = 0;
34
+ let settled = false;
35
+ let killTimer: ReturnType<typeof setTimeout> | undefined;
36
+ const running = () => child.exitCode === null && child.signalCode === null;
37
+ const cleanup = () => {
38
+ if (killTimer) clearTimeout(killTimer);
39
+ signal?.removeEventListener("abort", abort);
40
+ };
41
+ const finish = (action: () => void) => {
42
+ if (settled) return;
43
+ settled = true;
44
+ cleanup();
45
+ action();
46
+ };
47
+ const abort = () => {
48
+ if (running()) child.kill("SIGTERM");
49
+ killTimer = setTimeout(() => {
50
+ if (running()) child.kill("SIGKILL");
51
+ }, 1_000);
52
+ killTimer.unref?.();
53
+ };
54
+ const append = (target: "stderr" | "stdout", chunk: Buffer) => {
55
+ bytes += chunk.length;
56
+ if (bytes > OUTPUT_LIMIT_BYTES) {
57
+ if (running()) child.kill("SIGKILL");
58
+ finish(() => reject(new Error("Remote browser output exceeded 8 MiB")));
59
+ return;
60
+ }
61
+ if (target === "stdout") stdout += stdoutDecoder.write(chunk);
62
+ else stderr += stderrDecoder.write(chunk);
63
+ };
64
+ child.stdout?.on("data", (chunk: Buffer) => append("stdout", chunk));
65
+ child.stderr?.on("data", (chunk: Buffer) => append("stderr", chunk));
66
+ child.on("error", (error) => finish(() => reject(error)));
67
+ child.on("close", (code) =>
68
+ finish(() => {
69
+ stdout += stdoutDecoder.end();
70
+ stderr += stderrDecoder.end();
71
+ if (signal?.aborted) {
72
+ reject(abortReason(signal));
73
+ return;
74
+ }
75
+ resolveValue({
76
+ code: code ?? 1,
77
+ stderr: stderr.trim(),
78
+ stdout: stdout.trim(),
79
+ });
80
+ }),
81
+ );
82
+ if (input !== undefined) child.stdin?.end(input);
83
+ signal?.addEventListener("abort", abort, { once: true });
84
+ });
85
+ }
@@ -0,0 +1,120 @@
1
+ import { mkdir, rm } from "node:fs/promises";
2
+ import { basename, join } from "node:path";
3
+ import { artifactDirectory } from "./artifacts.js";
4
+ import type { BrowserOperation } from "./operation.js";
5
+ import { ensureRemoteHelper, remoteNodeCommand } from "./remote-helper.js";
6
+ import { runProgram } from "./remote-process.js";
7
+ import type { BrowserRoute } from "./routes.js";
8
+
9
+ const SAFE_REMOTE_FILE = /^\/[A-Za-z0-9_./-]+$/;
10
+
11
+ export { remoteNodeCommand } from "./remote-helper.js";
12
+
13
+ function isRecord(value: unknown): value is Record<string, unknown> {
14
+ return value !== null && typeof value === "object" && !Array.isArray(value);
15
+ }
16
+
17
+ async function copyRemoteArtifact(
18
+ host: string,
19
+ remoteFile: string,
20
+ signal?: AbortSignal,
21
+ ): Promise<string> {
22
+ if (!SAFE_REMOTE_FILE.test(remoteFile)) {
23
+ throw new Error(
24
+ `remote browser returned an unsafe artifact path: ${remoteFile}`,
25
+ );
26
+ }
27
+ await mkdir(artifactDirectory(), { recursive: true, mode: 0o700 });
28
+ const localFile = join(
29
+ artifactDirectory(),
30
+ `${host}-${basename(remoteFile)}`,
31
+ );
32
+ const copied = await runProgram(
33
+ "scp",
34
+ ["-q", `${host}:${remoteFile}`, localFile],
35
+ undefined,
36
+ signal,
37
+ );
38
+ if (copied.code !== 0) {
39
+ throw new Error(
40
+ copied.stderr || copied.stdout || "could not copy remote screenshot",
41
+ );
42
+ }
43
+ try {
44
+ const removed = await runProgram(
45
+ "ssh",
46
+ [host, `/usr/bin/rm -- ${remoteFile}`],
47
+ undefined,
48
+ signal,
49
+ );
50
+ if (removed.code !== 0) {
51
+ throw new Error(
52
+ removed.stderr ||
53
+ removed.stdout ||
54
+ "copied screenshot but could not remove remote artifact",
55
+ );
56
+ }
57
+ return localFile;
58
+ } catch (error) {
59
+ await rm(localFile, { force: true });
60
+ throw error;
61
+ }
62
+ }
63
+
64
+ async function localizeScreenshots(
65
+ host: string,
66
+ operations: BrowserOperation[],
67
+ result: Record<string, unknown>,
68
+ signal?: AbortSignal,
69
+ ): Promise<void> {
70
+ for (const [index, operation] of operations.entries()) {
71
+ if (operation.action !== "screenshot") continue;
72
+ const item =
73
+ operations.length === 1
74
+ ? result
75
+ : Array.isArray(result["results"])
76
+ ? result["results"][index]
77
+ : undefined;
78
+ if (!isRecord(item) || typeof item["file"] !== "string") {
79
+ throw new Error(`remote screenshot result ${index} has no file path`);
80
+ }
81
+ item["file"] = await copyRemoteArtifact(host, item["file"], signal);
82
+ }
83
+ }
84
+
85
+ export async function executeRemoteBrowser(
86
+ route: BrowserRoute,
87
+ operations: BrowserOperation[],
88
+ signal?: AbortSignal,
89
+ ): Promise<Record<string, unknown>> {
90
+ if (!route.remote) {
91
+ throw new Error(`Browser host ${route.name} has no remote command`);
92
+ }
93
+ await ensureRemoteHelper(route.name, route.remote, signal);
94
+ const executed = await runProgram(
95
+ "ssh",
96
+ [route.name, remoteNodeCommand(route.remote)],
97
+ JSON.stringify({ operations }),
98
+ signal,
99
+ );
100
+ if (executed.code !== 0) {
101
+ throw new Error(
102
+ executed.stderr ||
103
+ executed.stdout ||
104
+ `remote browser exited with code ${executed.code}`,
105
+ );
106
+ }
107
+ let value: unknown;
108
+ try {
109
+ value = JSON.parse(executed.stdout);
110
+ } catch (error) {
111
+ throw new Error(
112
+ `remote browser returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`,
113
+ );
114
+ }
115
+ if (!isRecord(value)) {
116
+ throw new Error("remote browser result is not an object");
117
+ }
118
+ await localizeScreenshots(route.name, operations, value, signal);
119
+ return value;
120
+ }
@@ -0,0 +1,95 @@
1
+ import { type BrowserOperation, OPERATION_ORDER } from "./operation.js";
2
+ import { isRecordValue, parseActionRequest } from "./parse-operation.js";
3
+
4
+ export type BrowserRequest =
5
+ | { help: true }
6
+ | { operations: BrowserOperation[]; host?: string | undefined };
7
+
8
+ const BATCH_FIELDS = new Set(["host", "response_length", ...OPERATION_ORDER]);
9
+
10
+ function requestHost(value: unknown): string | undefined {
11
+ if (value === undefined) return undefined;
12
+ if (typeof value !== "string" || !value.trim()) {
13
+ throw new Error("host must be a non-empty string");
14
+ }
15
+ return value.trim();
16
+ }
17
+
18
+ export function parseBrowserRequest(input: unknown): BrowserRequest {
19
+ let value = input;
20
+ if (typeof input === "string") {
21
+ const text = input.trim();
22
+ if (text === "help") return { help: true };
23
+ try {
24
+ value = JSON.parse(text);
25
+ } catch (error) {
26
+ throw new Error(
27
+ `input must be "help" or valid JSON: ${
28
+ error instanceof Error ? error.message : String(error)
29
+ }`,
30
+ );
31
+ }
32
+ }
33
+ if (!isRecordValue(value)) {
34
+ throw new Error("input must be a JSON object");
35
+ }
36
+ if (Object.hasOwn(value, "action")) {
37
+ const host = requestHost(value["host"]);
38
+ const { host: _host, ...actionValue } = value;
39
+ const operation = parseActionRequest(actionValue);
40
+ return operation.action === "help"
41
+ ? { help: true }
42
+ : { operations: [operation], ...(host ? { host } : {}) };
43
+ }
44
+ const unknown = Object.keys(value).filter((key) => !BATCH_FIELDS.has(key));
45
+ if (unknown.length > 0) {
46
+ throw new Error(`unknown browser field(s): ${unknown.join(", ")}`);
47
+ }
48
+ const host = requestHost(value["host"]);
49
+ const responseLength = value["response_length"] ?? "medium";
50
+ if (
51
+ responseLength !== "short" &&
52
+ responseLength !== "medium" &&
53
+ responseLength !== "long"
54
+ ) {
55
+ throw new Error("response_length must be one of: short, medium, long");
56
+ }
57
+ const operations: BrowserOperation[] = [];
58
+ for (const action of OPERATION_ORDER) {
59
+ const items = value[action];
60
+ if (items === undefined) continue;
61
+ if (!Array.isArray(items) || items.length === 0) {
62
+ throw new Error(`${action} must be a non-empty array`);
63
+ }
64
+ for (const [index, item] of items.entries()) {
65
+ if (!isRecordValue(item)) {
66
+ throw new Error(`${action}[${index}] must be an object`);
67
+ }
68
+ const reserved = ["action", "host", "response_length"].filter((key) =>
69
+ Object.hasOwn(item, key),
70
+ );
71
+ if (reserved.length > 0) {
72
+ throw new Error(
73
+ `${action}[${index}] has top-level field(s): ${reserved.join(", ")}`,
74
+ );
75
+ }
76
+ const parsed = parseActionRequest({
77
+ action,
78
+ ...item,
79
+ ...(action === "open" || action === "find"
80
+ ? { response_length: responseLength }
81
+ : {}),
82
+ });
83
+ if (parsed.action === "help") {
84
+ throw new Error("help is not a batch operation");
85
+ }
86
+ operations.push(parsed);
87
+ }
88
+ }
89
+ if (operations.length === 0) {
90
+ throw new Error(
91
+ `provide at least one operation: ${OPERATION_ORDER.join(", ")}`,
92
+ );
93
+ }
94
+ return { operations, ...(host ? { host } : {}) };
95
+ }