@howaboua/pi-browser 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/LICENSE +22 -0
- package/README.md +47 -0
- package/biome.json +31 -0
- package/changelog.ts +337 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +82 -0
- package/dist/remote-worker.d.ts +2 -0
- package/dist/remote-worker.js +3005 -0
- package/dist/src/browser/artifacts.d.ts +13 -0
- package/dist/src/browser/artifacts.js +133 -0
- package/dist/src/browser/bounds.d.ts +4 -0
- package/dist/src/browser/bounds.js +129 -0
- package/dist/src/browser/config.d.ts +11 -0
- package/dist/src/browser/config.js +106 -0
- package/dist/src/browser/help.d.ts +1 -0
- package/dist/src/browser/help.js +27 -0
- package/dist/src/browser/launcher.d.ts +8 -0
- package/dist/src/browser/launcher.js +169 -0
- package/dist/src/browser/operation-executor.d.ts +9 -0
- package/dist/src/browser/operation-executor.js +112 -0
- package/dist/src/browser/operation.d.ts +92 -0
- package/dist/src/browser/operation.js +20 -0
- package/dist/src/browser/parse-operation.d.ts +6 -0
- package/dist/src/browser/parse-operation.js +248 -0
- package/dist/src/browser/remote-helper.d.ts +3 -0
- package/dist/src/browser/remote-helper.js +114 -0
- package/dist/src/browser/remote-process.d.ts +7 -0
- package/dist/src/browser/remote-process.js +78 -0
- package/dist/src/browser/remote.d.ts +4 -0
- package/dist/src/browser/remote.js +73 -0
- package/dist/src/browser/request.d.ts +8 -0
- package/dist/src/browser/request.js +80 -0
- package/dist/src/browser/routes.d.ts +16 -0
- package/dist/src/browser/routes.js +40 -0
- package/dist/src/browser/runtime.d.ts +17 -0
- package/dist/src/browser/runtime.js +61 -0
- package/dist/src/browser/settings.d.ts +2 -0
- package/dist/src/browser/settings.js +164 -0
- package/dist/src/browser/worker-server.d.ts +2 -0
- package/dist/src/browser/worker-server.js +241 -0
- package/dist/src/browser-parameters.d.ts +42 -0
- package/dist/src/browser-parameters.js +113 -0
- package/dist/src/browser-tool.d.ts +48 -0
- package/dist/src/browser-tool.js +71 -0
- package/dist/src/cdp/actions/click.d.ts +4 -0
- package/dist/src/cdp/actions/click.js +56 -0
- package/dist/src/cdp/actions/element.d.ts +22 -0
- package/dist/src/cdp/actions/element.js +126 -0
- package/dist/src/cdp/actions/page.d.ts +7 -0
- package/dist/src/cdp/actions/page.js +127 -0
- package/dist/src/cdp/actions/screenshot.d.ts +10 -0
- package/dist/src/cdp/actions/screenshot.js +96 -0
- package/dist/src/cdp/actions/selector.d.ts +2 -0
- package/dist/src/cdp/actions/selector.js +41 -0
- package/dist/src/cdp/actions/type.d.ts +3 -0
- package/dist/src/cdp/actions/type.js +138 -0
- package/dist/src/cdp/client.d.ts +20 -0
- package/dist/src/cdp/client.js +248 -0
- package/dist/src/cdp/discovery.d.ts +7 -0
- package/dist/src/cdp/discovery.js +153 -0
- package/dist/src/cdp/evaluate.d.ts +3 -0
- package/dist/src/cdp/evaluate.js +31 -0
- package/dist/src/cdp/pages.d.ts +3 -0
- package/dist/src/cdp/pages.js +40 -0
- package/dist/src/cdp/serial.d.ts +1 -0
- package/dist/src/cdp/serial.js +18 -0
- package/dist/src/cdp/session.d.ts +25 -0
- package/dist/src/cdp/session.js +246 -0
- package/dist/src/cdp/snapshot-contract.d.ts +32 -0
- package/dist/src/cdp/snapshot-contract.js +23 -0
- package/dist/src/cdp/snapshot.d.ts +3 -0
- package/dist/src/cdp/snapshot.js +205 -0
- package/dist/src/cdp/types.d.ts +20 -0
- package/dist/src/cdp/types.js +14 -0
- package/dist/src/cdp/url.d.ts +1 -0
- package/dist/src/cdp/url.js +12 -0
- package/index.ts +115 -0
- package/package.json +93 -0
- package/remote-worker.ts +58 -0
- package/src/browser/artifacts.ts +178 -0
- package/src/browser/bounds.ts +159 -0
- package/src/browser/config.ts +162 -0
- package/src/browser/help.ts +30 -0
- package/src/browser/launcher.ts +208 -0
- package/src/browser/operation-executor.ts +251 -0
- package/src/browser/operation.ts +105 -0
- package/src/browser/parse-operation.ts +272 -0
- package/src/browser/remote-helper.ts +137 -0
- package/src/browser/remote-process.ts +85 -0
- package/src/browser/remote.ts +120 -0
- package/src/browser/request.ts +95 -0
- package/src/browser/routes.ts +69 -0
- package/src/browser/runtime.ts +84 -0
- package/src/browser/settings.ts +219 -0
- package/src/browser/worker-server.ts +274 -0
- package/src/browser-parameters.ts +118 -0
- package/src/browser-tool.ts +88 -0
- package/src/cdp/actions/click.ts +126 -0
- package/src/cdp/actions/element.ts +234 -0
- package/src/cdp/actions/page.ts +219 -0
- package/src/cdp/actions/screenshot.ts +176 -0
- package/src/cdp/actions/selector.ts +63 -0
- package/src/cdp/actions/type.ts +224 -0
- package/src/cdp/client.ts +286 -0
- package/src/cdp/discovery.ts +198 -0
- package/src/cdp/evaluate.ts +55 -0
- package/src/cdp/pages.ts +60 -0
- package/src/cdp/serial.ts +23 -0
- package/src/cdp/session.ts +345 -0
- package/src/cdp/snapshot-contract.ts +63 -0
- package/src/cdp/snapshot.ts +273 -0
- package/src/cdp/types.ts +49 -0
- package/src/cdp/url.ts +11 -0
- package/tsconfig.json +7 -0
package/package.json
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@howaboua/pi-browser",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Logged-in browser inspection and control for Pi, Code Mode and Notebook Mode.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Igor Warzocha",
|
|
8
|
+
"homepage": "https://github.com/IgorWarzocha/howaboua-pi-stuff/tree/main/packages/pi-browser#readme",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/IgorWarzocha/howaboua-pi-stuff.git",
|
|
12
|
+
"directory": "packages/pi-browser"
|
|
13
|
+
},
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/IgorWarzocha/howaboua-pi-stuff/issues"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"pi-package",
|
|
19
|
+
"pi-extension",
|
|
20
|
+
"pi",
|
|
21
|
+
"browser",
|
|
22
|
+
"chrome",
|
|
23
|
+
"cdp",
|
|
24
|
+
"code-mode"
|
|
25
|
+
],
|
|
26
|
+
"files": [
|
|
27
|
+
"dist/**/*.js",
|
|
28
|
+
"dist/**/*.d.ts",
|
|
29
|
+
"index.ts",
|
|
30
|
+
"remote-worker.ts",
|
|
31
|
+
"src",
|
|
32
|
+
"README.md",
|
|
33
|
+
"LICENSE",
|
|
34
|
+
"CHANGELOG.md",
|
|
35
|
+
"tsconfig.json",
|
|
36
|
+
"biome.json",
|
|
37
|
+
"changelog.ts"
|
|
38
|
+
],
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json && bun build remote-worker.ts --target=node --format=esm --outfile=dist/remote-worker.js --banner='// @howaboua/pi-browser managed worker'",
|
|
41
|
+
"check": "bun run lint && bun run typecheck && bun run test",
|
|
42
|
+
"prepack": "bun run check && bun run build",
|
|
43
|
+
"typecheck": "tsgo --noEmit",
|
|
44
|
+
"lint": "biome check .",
|
|
45
|
+
"test": "tsx --test tests/**/*.test.ts",
|
|
46
|
+
"pack:dry": "npm pack --dry-run"
|
|
47
|
+
},
|
|
48
|
+
"peerDependencies": {
|
|
49
|
+
"@howaboua/pi-codex-conversion": ">=3.0.24",
|
|
50
|
+
"@earendil-works/pi-ai": ">=0.84.3",
|
|
51
|
+
"@earendil-works/pi-coding-agent": ">=0.84.3",
|
|
52
|
+
"typebox": "*",
|
|
53
|
+
"@earendil-works/pi-tui": "*"
|
|
54
|
+
},
|
|
55
|
+
"peerDependenciesMeta": {
|
|
56
|
+
"@howaboua/pi-codex-conversion": {
|
|
57
|
+
"optional": true
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
"devDependencies": {
|
|
61
|
+
"@howaboua/pi-codex-conversion": "3.0.24",
|
|
62
|
+
"@biomejs/biome": "^2.5.10",
|
|
63
|
+
"@earendil-works/pi-ai": "0.84.4",
|
|
64
|
+
"@earendil-works/pi-coding-agent": "0.84.4",
|
|
65
|
+
"@types/node": "^26.2.0",
|
|
66
|
+
"tsx": "^4.23.12",
|
|
67
|
+
"typebox": "1.3.18",
|
|
68
|
+
"typescript": "^7.0.2"
|
|
69
|
+
},
|
|
70
|
+
"pi": {
|
|
71
|
+
"extensions": [
|
|
72
|
+
"./changelog.ts",
|
|
73
|
+
"./dist/index.js"
|
|
74
|
+
]
|
|
75
|
+
},
|
|
76
|
+
"engines": {
|
|
77
|
+
"node": ">=22.19.0"
|
|
78
|
+
},
|
|
79
|
+
"bin": {
|
|
80
|
+
"pi-browser-worker": "./dist/remote-worker.js"
|
|
81
|
+
},
|
|
82
|
+
"main": "./dist/index.js",
|
|
83
|
+
"types": "./dist/index.d.ts",
|
|
84
|
+
"exports": {
|
|
85
|
+
".": {
|
|
86
|
+
"types": "./dist/index.d.ts",
|
|
87
|
+
"import": "./dist/index.js"
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
"publishConfig": {
|
|
91
|
+
"access": "public"
|
|
92
|
+
}
|
|
93
|
+
}
|
package/remote-worker.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import {
|
|
8
|
+
requestBrowserWorker,
|
|
9
|
+
serveBrowserWorker,
|
|
10
|
+
} from "./src/browser/worker-server.js";
|
|
11
|
+
|
|
12
|
+
async function readStdin(): Promise<string> {
|
|
13
|
+
let input = "";
|
|
14
|
+
process.stdin.setEncoding("utf8");
|
|
15
|
+
for await (const chunk of process.stdin) input += chunk;
|
|
16
|
+
return input;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function main(): Promise<void> {
|
|
20
|
+
const entryPath = fileURLToPath(import.meta.url);
|
|
21
|
+
const workerId = createHash("sha256")
|
|
22
|
+
.update(readFileSync(entryPath))
|
|
23
|
+
.digest("hex")
|
|
24
|
+
.slice(0, 12);
|
|
25
|
+
if (process.argv.includes("--daemon")) {
|
|
26
|
+
await serveBrowserWorker(workerId);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const controller = new AbortController();
|
|
30
|
+
const abort = () => controller.abort(new Error("Remote browser interrupted"));
|
|
31
|
+
process.once("SIGINT", abort);
|
|
32
|
+
process.once("SIGTERM", abort);
|
|
33
|
+
try {
|
|
34
|
+
const result = await requestBrowserWorker(
|
|
35
|
+
await readStdin(),
|
|
36
|
+
entryPath,
|
|
37
|
+
workerId,
|
|
38
|
+
controller.signal,
|
|
39
|
+
);
|
|
40
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
41
|
+
} finally {
|
|
42
|
+
process.removeListener("SIGINT", abort);
|
|
43
|
+
process.removeListener("SIGTERM", abort);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (
|
|
48
|
+
process.argv[1] &&
|
|
49
|
+
realpathSync(fileURLToPath(import.meta.url)) ===
|
|
50
|
+
realpathSync(resolve(process.argv[1]))
|
|
51
|
+
) {
|
|
52
|
+
main().catch((error) => {
|
|
53
|
+
process.stderr.write(
|
|
54
|
+
`pi-browser-worker: ${error instanceof Error ? error.message : String(error)}\n`,
|
|
55
|
+
);
|
|
56
|
+
process.exitCode = 1;
|
|
57
|
+
});
|
|
58
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import {
|
|
2
|
+
mkdir,
|
|
3
|
+
readdir,
|
|
4
|
+
readFile,
|
|
5
|
+
rm,
|
|
6
|
+
stat,
|
|
7
|
+
writeFile,
|
|
8
|
+
} from "node:fs/promises";
|
|
9
|
+
import { tmpdir } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
|
|
12
|
+
const RESULT_TTL_MS = 60 * 60 * 1_000;
|
|
13
|
+
const SCREENSHOT_TTL_MS = 24 * 60 * 60 * 1_000;
|
|
14
|
+
const TEXT_BUDGET_BYTES = 32_000;
|
|
15
|
+
|
|
16
|
+
export function artifactDirectory(): string {
|
|
17
|
+
return process.env["XDG_RUNTIME_DIR"]
|
|
18
|
+
? join(process.env["XDG_RUNTIME_DIR"], "browser-tool")
|
|
19
|
+
: join(tmpdir(), `browser-tool-${process.getuid?.() ?? "user"}`);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function resultPath(handle: string): string {
|
|
23
|
+
return join(artifactDirectory(), `result-${handle}.txt`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function screenshotPath(request: {
|
|
27
|
+
ref_id: string;
|
|
28
|
+
id?: number | undefined;
|
|
29
|
+
selector?: string | undefined;
|
|
30
|
+
}): Promise<string> {
|
|
31
|
+
await mkdir(artifactDirectory(), {
|
|
32
|
+
recursive: true,
|
|
33
|
+
mode: 0o700,
|
|
34
|
+
});
|
|
35
|
+
const suffix =
|
|
36
|
+
request.id !== undefined
|
|
37
|
+
? `-element-${request.id}`
|
|
38
|
+
: request.selector
|
|
39
|
+
? "-element"
|
|
40
|
+
: "";
|
|
41
|
+
const safeRef = request.ref_id.slice(0, 12).replace(/[^A-Za-z0-9_-]/g, "_");
|
|
42
|
+
return join(
|
|
43
|
+
artifactDirectory(),
|
|
44
|
+
`browser-${safeRef}${suffix}-${crypto.randomUUID()}.png`,
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function pruneArtifacts(now = Date.now()): Promise<number> {
|
|
49
|
+
let names: string[];
|
|
50
|
+
try {
|
|
51
|
+
names = await readdir(artifactDirectory());
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (
|
|
54
|
+
error &&
|
|
55
|
+
typeof error === "object" &&
|
|
56
|
+
"code" in error &&
|
|
57
|
+
error.code === "ENOENT"
|
|
58
|
+
) {
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
let removed = 0;
|
|
64
|
+
for (const name of names.filter((candidate) =>
|
|
65
|
+
/^(?:result-[a-f0-9-]{36}\.txt|browser-.*\.png)$/.test(candidate),
|
|
66
|
+
)) {
|
|
67
|
+
const path = join(artifactDirectory(), name);
|
|
68
|
+
try {
|
|
69
|
+
const maxAge = name.startsWith("result-")
|
|
70
|
+
? RESULT_TTL_MS
|
|
71
|
+
: SCREENSHOT_TTL_MS;
|
|
72
|
+
if (now - (await stat(path)).mtimeMs > maxAge) {
|
|
73
|
+
await rm(path, { force: true });
|
|
74
|
+
removed++;
|
|
75
|
+
}
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (
|
|
78
|
+
!error ||
|
|
79
|
+
typeof error !== "object" ||
|
|
80
|
+
!("code" in error) ||
|
|
81
|
+
error.code !== "ENOENT"
|
|
82
|
+
) {
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return removed;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function chunkForJson(
|
|
91
|
+
value: string,
|
|
92
|
+
offset = 0,
|
|
93
|
+
budget = TEXT_BUDGET_BYTES,
|
|
94
|
+
): { text: string; end: number } {
|
|
95
|
+
let bytes = 2;
|
|
96
|
+
let end = offset;
|
|
97
|
+
for (const character of value.slice(offset)) {
|
|
98
|
+
const next = Buffer.byteLength(JSON.stringify(character)) - 2;
|
|
99
|
+
if (bytes + next > budget) break;
|
|
100
|
+
bytes += next;
|
|
101
|
+
end += character.length;
|
|
102
|
+
}
|
|
103
|
+
return { text: value.slice(offset, end), end };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function cacheResult(value: string): Promise<string> {
|
|
107
|
+
const handle = crypto.randomUUID();
|
|
108
|
+
await mkdir(artifactDirectory(), {
|
|
109
|
+
recursive: true,
|
|
110
|
+
mode: 0o700,
|
|
111
|
+
});
|
|
112
|
+
await writeFile(resultPath(handle), value, { mode: 0o600 });
|
|
113
|
+
return handle;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function limitedText(
|
|
117
|
+
base: Record<string, unknown>,
|
|
118
|
+
field: string,
|
|
119
|
+
value: string,
|
|
120
|
+
): Promise<Record<string, unknown>> {
|
|
121
|
+
const chunk = chunkForJson(value);
|
|
122
|
+
if (chunk.end >= value.length) return { ...base, [field]: value };
|
|
123
|
+
const handle = await cacheResult(value);
|
|
124
|
+
return {
|
|
125
|
+
...base,
|
|
126
|
+
[field]: chunk.text,
|
|
127
|
+
truncated: true,
|
|
128
|
+
omitted_chars: value.length - chunk.end,
|
|
129
|
+
result_handle: handle,
|
|
130
|
+
next_offset: chunk.end,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export async function readCachedResult(request: {
|
|
135
|
+
handle: string;
|
|
136
|
+
offset: number;
|
|
137
|
+
}): Promise<Record<string, unknown>> {
|
|
138
|
+
let value: string;
|
|
139
|
+
try {
|
|
140
|
+
value = await readFile(resultPath(request.handle), "utf8");
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (
|
|
143
|
+
error &&
|
|
144
|
+
typeof error === "object" &&
|
|
145
|
+
"code" in error &&
|
|
146
|
+
error.code === "ENOENT"
|
|
147
|
+
) {
|
|
148
|
+
throw new Error(
|
|
149
|
+
`result handle not found: ${request.handle}; check the host or rerun the original action`,
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
if (request.offset > value.length) {
|
|
155
|
+
throw new Error(
|
|
156
|
+
`offset ${request.offset} exceeds result length ${value.length}`,
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
const chunk = chunkForJson(value, request.offset);
|
|
160
|
+
const complete = chunk.end >= value.length;
|
|
161
|
+
if (complete) {
|
|
162
|
+
await rm(resultPath(request.handle), { force: true });
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
handle: request.handle,
|
|
166
|
+
offset: request.offset,
|
|
167
|
+
text: chunk.text,
|
|
168
|
+
complete,
|
|
169
|
+
...(complete ? {} : { next_offset: chunk.end }),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export async function discardCachedResult(
|
|
174
|
+
handle: string,
|
|
175
|
+
): Promise<Record<string, unknown>> {
|
|
176
|
+
await rm(resultPath(handle), { force: true });
|
|
177
|
+
return { discarded: handle };
|
|
178
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { StringDecoder } from "node:string_decoder";
|
|
2
|
+
import { getDisplayPrefixLength } from "../cdp/discovery.js";
|
|
3
|
+
import type {
|
|
4
|
+
SnapshotElement,
|
|
5
|
+
SnapshotResult,
|
|
6
|
+
} from "../cdp/snapshot-contract.js";
|
|
7
|
+
import type { PageInfo } from "../cdp/types.js";
|
|
8
|
+
|
|
9
|
+
const OUTPUT_BUDGET_BYTES = 38_000;
|
|
10
|
+
const SNAPSHOT_TITLE_BYTES = 1_000;
|
|
11
|
+
const SNAPSHOT_URL_BYTES = 8_000;
|
|
12
|
+
const SNAPSHOT_PATTERN_BYTES = 2_000;
|
|
13
|
+
const SNAPSHOT_ELEMENT_NAME_BYTES = 2_000;
|
|
14
|
+
const SNAPSHOT_ELEMENT_VALUE_BYTES = 4_000;
|
|
15
|
+
|
|
16
|
+
function byteLength(value: unknown): number {
|
|
17
|
+
return Buffer.byteLength(JSON.stringify(value));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function truncateUtf8(value: string, maxBytes: number): string {
|
|
21
|
+
const bytes = Buffer.from(value);
|
|
22
|
+
if (bytes.length <= maxBytes) return value;
|
|
23
|
+
return new StringDecoder("utf8").write(bytes.subarray(0, maxBytes));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function boundedElement(element: SnapshotElement): SnapshotElement {
|
|
27
|
+
let value = element.value;
|
|
28
|
+
if (typeof value === "string") {
|
|
29
|
+
value = truncateUtf8(value, SNAPSHOT_ELEMENT_VALUE_BYTES);
|
|
30
|
+
} else if (value !== undefined) {
|
|
31
|
+
const serialized = JSON.stringify(value);
|
|
32
|
+
if (
|
|
33
|
+
serialized &&
|
|
34
|
+
Buffer.byteLength(serialized) > SNAPSHOT_ELEMENT_VALUE_BYTES
|
|
35
|
+
) {
|
|
36
|
+
value = truncateUtf8(serialized, SNAPSHOT_ELEMENT_VALUE_BYTES);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
...element,
|
|
41
|
+
role: truncateUtf8(element.role, 128),
|
|
42
|
+
...(element.name === undefined
|
|
43
|
+
? {}
|
|
44
|
+
: { name: truncateUtf8(element.name, SNAPSHOT_ELEMENT_NAME_BYTES) }),
|
|
45
|
+
...(value === undefined ? {} : { value }),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function boundTabs(
|
|
50
|
+
pages: PageInfo[],
|
|
51
|
+
query: string | undefined,
|
|
52
|
+
offset: number,
|
|
53
|
+
): Record<string, unknown> {
|
|
54
|
+
const prefixLength = getDisplayPrefixLength(
|
|
55
|
+
pages.map((page) => page.targetId),
|
|
56
|
+
);
|
|
57
|
+
let filtered = pages;
|
|
58
|
+
if (query) {
|
|
59
|
+
const normalized = query.toLowerCase();
|
|
60
|
+
filtered = pages.filter((page) =>
|
|
61
|
+
`${page.title}\n${page.url}`.toLowerCase().includes(normalized),
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
if (offset > filtered.length) {
|
|
65
|
+
throw new Error(`offset ${offset} exceeds tab count ${filtered.length}`);
|
|
66
|
+
}
|
|
67
|
+
const tabs: Array<{
|
|
68
|
+
ref_id: string;
|
|
69
|
+
title: string;
|
|
70
|
+
url: string;
|
|
71
|
+
}> = [];
|
|
72
|
+
for (const page of filtered.slice(offset)) {
|
|
73
|
+
const compact = {
|
|
74
|
+
ref_id: page.targetId.slice(0, prefixLength),
|
|
75
|
+
title: page.title.slice(0, 500),
|
|
76
|
+
url: page.url.slice(0, 8_000),
|
|
77
|
+
};
|
|
78
|
+
if (byteLength({ tabs: [...tabs, compact] }) > OUTPUT_BUDGET_BYTES) {
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
tabs.push(compact);
|
|
82
|
+
}
|
|
83
|
+
const remaining = filtered.length - offset - tabs.length;
|
|
84
|
+
return {
|
|
85
|
+
offset,
|
|
86
|
+
tabs,
|
|
87
|
+
...(remaining > 0
|
|
88
|
+
? {
|
|
89
|
+
truncated: true,
|
|
90
|
+
omitted_tabs: remaining,
|
|
91
|
+
next_offset: offset + tabs.length,
|
|
92
|
+
}
|
|
93
|
+
: {}),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function boundSnapshot(page: SnapshotResult): Record<string, unknown> {
|
|
98
|
+
const base = {
|
|
99
|
+
ref_id:
|
|
100
|
+
page.ref_id === undefined ? undefined : truncateUtf8(page.ref_id, 512),
|
|
101
|
+
title: truncateUtf8(page.title, SNAPSHOT_TITLE_BYTES),
|
|
102
|
+
url: truncateUtf8(page.url, SNAPSHOT_URL_BYTES),
|
|
103
|
+
lineno: page.lineno,
|
|
104
|
+
...(page.pattern
|
|
105
|
+
? { pattern: truncateUtf8(page.pattern, SNAPSHOT_PATTERN_BYTES) }
|
|
106
|
+
: {}),
|
|
107
|
+
};
|
|
108
|
+
const elements = new Map<number, SnapshotElement>(
|
|
109
|
+
page.elements.map((element) => [element.id, boundedElement(element)]),
|
|
110
|
+
);
|
|
111
|
+
const content: SnapshotResult["content"] = [];
|
|
112
|
+
const includedElements: SnapshotElement[] = [];
|
|
113
|
+
const includedIds = new Set<number>();
|
|
114
|
+
for (const line of page.content) {
|
|
115
|
+
const nextContent = [...content, line];
|
|
116
|
+
const nextElements = [...includedElements];
|
|
117
|
+
if (
|
|
118
|
+
line.element_id !== undefined &&
|
|
119
|
+
!includedIds.has(line.element_id) &&
|
|
120
|
+
elements.has(line.element_id)
|
|
121
|
+
) {
|
|
122
|
+
const element = elements.get(line.element_id);
|
|
123
|
+
if (element) nextElements.push(element);
|
|
124
|
+
}
|
|
125
|
+
if (
|
|
126
|
+
byteLength({
|
|
127
|
+
...base,
|
|
128
|
+
content: nextContent,
|
|
129
|
+
elements: nextElements,
|
|
130
|
+
}) > OUTPUT_BUDGET_BYTES
|
|
131
|
+
) {
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
134
|
+
content.push(line);
|
|
135
|
+
if (
|
|
136
|
+
line.element_id !== undefined &&
|
|
137
|
+
!includedIds.has(line.element_id) &&
|
|
138
|
+
elements.has(line.element_id)
|
|
139
|
+
) {
|
|
140
|
+
includedIds.add(line.element_id);
|
|
141
|
+
const element = elements.get(line.element_id);
|
|
142
|
+
if (element) includedElements.push(element);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const omitted = content.length < page.content.length;
|
|
146
|
+
return {
|
|
147
|
+
...base,
|
|
148
|
+
content,
|
|
149
|
+
elements: includedElements,
|
|
150
|
+
...(omitted || page.next_lineno
|
|
151
|
+
? {
|
|
152
|
+
truncated: true,
|
|
153
|
+
next_lineno: omitted
|
|
154
|
+
? page.lineno + content.length
|
|
155
|
+
: page.next_lineno,
|
|
156
|
+
}
|
|
157
|
+
: {}),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
mkdirSync,
|
|
4
|
+
readFileSync,
|
|
5
|
+
renameSync,
|
|
6
|
+
rmSync,
|
|
7
|
+
writeFileSync,
|
|
8
|
+
} from "node:fs";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { basename, dirname, join } from "node:path";
|
|
11
|
+
|
|
12
|
+
const DEFAULT_REMOTE_NODE_PATH = "node";
|
|
13
|
+
|
|
14
|
+
export interface BrowserRouteConfig {
|
|
15
|
+
aliases: Record<string, string>;
|
|
16
|
+
hosts: string[];
|
|
17
|
+
remoteNodePath: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface BrowserRouteConfigInput {
|
|
21
|
+
aliases?: Record<string, string>;
|
|
22
|
+
hosts?: string[];
|
|
23
|
+
remoteNodePath?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const ROUTE_NAME = /^[A-Za-z0-9_.-]+$/;
|
|
27
|
+
const REMOTE_WORD = /^[A-Za-z0-9_./:$@=+-]+$/;
|
|
28
|
+
|
|
29
|
+
export function browserConfigPath(): string {
|
|
30
|
+
const agentDir =
|
|
31
|
+
process.env["PI_CODING_AGENT_DIR"]?.trim() ||
|
|
32
|
+
join(homedir(), ".pi", "agent");
|
|
33
|
+
return (
|
|
34
|
+
process.env["PI_BROWSER_CONFIG"]?.trim() ||
|
|
35
|
+
join(agentDir, "pi-browser.json")
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function defaultBrowserRouteConfig(): BrowserRouteConfig {
|
|
40
|
+
return {
|
|
41
|
+
aliases: {},
|
|
42
|
+
hosts: [],
|
|
43
|
+
remoteNodePath: DEFAULT_REMOTE_NODE_PATH,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function normalizeBrowserHostName(
|
|
48
|
+
value: unknown,
|
|
49
|
+
field = "browser host",
|
|
50
|
+
): string {
|
|
51
|
+
if (typeof value !== "string" || !ROUTE_NAME.test(value)) {
|
|
52
|
+
throw new Error(
|
|
53
|
+
`${field} must contain only letters, digits, dot, dash or underscore`,
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function remoteWord(value: unknown, field: string): string {
|
|
60
|
+
if (typeof value !== "string" || !value || !REMOTE_WORD.test(value)) {
|
|
61
|
+
throw new Error(`${field} contains unsupported shell characters`);
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function normalizeBrowserRouteConfig(
|
|
67
|
+
value: unknown,
|
|
68
|
+
): BrowserRouteConfig {
|
|
69
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
70
|
+
throw new Error("pi-browser config must be an object");
|
|
71
|
+
}
|
|
72
|
+
const input = value as BrowserRouteConfigInput;
|
|
73
|
+
const rawHosts = input.hosts ?? [];
|
|
74
|
+
if (!Array.isArray(rawHosts)) {
|
|
75
|
+
throw new Error("pi-browser config hosts must be an array");
|
|
76
|
+
}
|
|
77
|
+
const hosts = rawHosts.map((name) =>
|
|
78
|
+
normalizeBrowserHostName(name, "pi-browser host name"),
|
|
79
|
+
);
|
|
80
|
+
if (new Set(hosts).size !== hosts.length) {
|
|
81
|
+
throw new Error("pi-browser config hosts must be unique");
|
|
82
|
+
}
|
|
83
|
+
const rawAliases = input.aliases ?? {};
|
|
84
|
+
if (typeof rawAliases !== "object" || Array.isArray(rawAliases)) {
|
|
85
|
+
throw new Error("pi-browser config aliases must be an object");
|
|
86
|
+
}
|
|
87
|
+
const aliases: Record<string, string> = {};
|
|
88
|
+
for (const [rawAlias, rawTarget] of Object.entries(rawAliases)) {
|
|
89
|
+
const alias = normalizeBrowserHostName(rawAlias, "pi-browser alias");
|
|
90
|
+
const target = normalizeBrowserHostName(
|
|
91
|
+
rawTarget,
|
|
92
|
+
`pi-browser alias ${alias}`,
|
|
93
|
+
);
|
|
94
|
+
if (!hosts.includes(target)) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
`pi-browser alias ${alias} targets unknown host ${target}`,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
aliases[alias] = target;
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
aliases,
|
|
103
|
+
hosts,
|
|
104
|
+
remoteNodePath: remoteWord(
|
|
105
|
+
input.remoteNodePath ?? DEFAULT_REMOTE_NODE_PATH,
|
|
106
|
+
"pi-browser remoteNodePath",
|
|
107
|
+
),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function readBrowserRouteConfig(
|
|
112
|
+
path = browserConfigPath(),
|
|
113
|
+
): BrowserRouteConfig {
|
|
114
|
+
let source: string;
|
|
115
|
+
try {
|
|
116
|
+
source = readFileSync(path, "utf8");
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (
|
|
119
|
+
error &&
|
|
120
|
+
typeof error === "object" &&
|
|
121
|
+
"code" in error &&
|
|
122
|
+
error.code === "ENOENT"
|
|
123
|
+
) {
|
|
124
|
+
return defaultBrowserRouteConfig();
|
|
125
|
+
}
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
return normalizeBrowserRouteConfig(JSON.parse(source));
|
|
130
|
+
} catch (error) {
|
|
131
|
+
throw new Error(
|
|
132
|
+
`Invalid pi-browser config at ${path}: ${error instanceof Error ? error.message : String(error)}`,
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function writeBrowserRouteConfig(
|
|
138
|
+
config: BrowserRouteConfig,
|
|
139
|
+
path = browserConfigPath(),
|
|
140
|
+
): void {
|
|
141
|
+
const normalized = normalizeBrowserRouteConfig(config);
|
|
142
|
+
if (normalized.hosts.length === 0) {
|
|
143
|
+
rmSync(path, { force: true });
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const directory = dirname(path);
|
|
147
|
+
mkdirSync(directory, { recursive: true });
|
|
148
|
+
const temporary = join(
|
|
149
|
+
directory,
|
|
150
|
+
`.${basename(path)}.${process.pid}.${randomUUID()}.tmp`,
|
|
151
|
+
);
|
|
152
|
+
try {
|
|
153
|
+
writeFileSync(temporary, `${JSON.stringify(normalized, null, 2)}\n`, {
|
|
154
|
+
encoding: "utf8",
|
|
155
|
+
flag: "wx",
|
|
156
|
+
mode: 0o600,
|
|
157
|
+
});
|
|
158
|
+
renameSync(temporary, path);
|
|
159
|
+
} finally {
|
|
160
|
+
rmSync(temporary, { force: true });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export function browserHelp(
|
|
2
|
+
hosts: readonly string[] = [],
|
|
3
|
+
): Record<string, unknown> {
|
|
4
|
+
const routed = hosts.length > 0;
|
|
5
|
+
return {
|
|
6
|
+
input: "Code=JSON.stringify(request); normal=request",
|
|
7
|
+
...(routed ? { host: `${hosts.join("|")} optional` } : {}),
|
|
8
|
+
batch:
|
|
9
|
+
"top-level nonempty action arrays; items omit action/host/response_length; independent only",
|
|
10
|
+
actions: {
|
|
11
|
+
tabs: "query? offset? -> ref_id title url",
|
|
12
|
+
open: "ref_id lineno? response_length? | url",
|
|
13
|
+
find: "ref_id pattern lineno? response_length?",
|
|
14
|
+
click: "ref_id id|selector|x+y",
|
|
15
|
+
type: "ref_id text id?; id focuses",
|
|
16
|
+
screenshot: "ref_id id?|selector? -> file",
|
|
17
|
+
navigate: "ref_id url",
|
|
18
|
+
html: "ref_id id?|selector?",
|
|
19
|
+
evaluate: "ref_id expression",
|
|
20
|
+
network: "ref_id",
|
|
21
|
+
load_all: "ref_id selector interval_ms?",
|
|
22
|
+
raw: "ref_id method params?",
|
|
23
|
+
start: "",
|
|
24
|
+
stop: "ref_id?",
|
|
25
|
+
read_result: `handle offset${routed ? "; same host" : ""}`,
|
|
26
|
+
discard_result: `handle${routed ? "; same host" : ""}`,
|
|
27
|
+
},
|
|
28
|
+
continue: "next_lineno/next_offset; response_length=short|medium|long",
|
|
29
|
+
};
|
|
30
|
+
}
|