@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,246 @@
1
+ import { CdpClient } from "./client.js";
2
+ import { getDisplayPrefixLength, getWebSocketUrl, resolvePrefix, } from "./discovery.js";
3
+ import { getPages, waitForOpenedTarget } from "./pages.js";
4
+ import { waitForTurn } from "./serial.js";
5
+ import { asRecord } from "./types.js";
6
+ import { assertHttpUrl } from "./url.js";
7
+ const TAB_IDLE_MS = 20 * 60 * 1_000;
8
+ class TabBridge {
9
+ elementRefs = new Map();
10
+ targetId;
11
+ cdp;
12
+ sessionId;
13
+ tail = Promise.resolve();
14
+ idleTimer;
15
+ closed = false;
16
+ onClose;
17
+ constructor(targetId, cdp, sessionId, onClose) {
18
+ this.targetId = targetId;
19
+ this.cdp = cdp;
20
+ this.sessionId = sessionId;
21
+ this.onClose = onClose;
22
+ this.resetIdle();
23
+ cdp.onEvent("Target.targetDestroyed", (value) => {
24
+ const event = asRecord(value, "target destroyed event");
25
+ if (event["targetId"] === targetId)
26
+ this.close(false);
27
+ });
28
+ cdp.onEvent("Target.detachedFromTarget", (value) => {
29
+ const event = asRecord(value, "target detached event");
30
+ if (event["sessionId"] === sessionId)
31
+ this.close(false);
32
+ });
33
+ cdp.onClose(() => this.close(false));
34
+ }
35
+ static async connect(targetId, onClose, signal) {
36
+ const cdp = new CdpClient();
37
+ try {
38
+ await cdp.connect(await getWebSocketUrl(), signal);
39
+ const response = asRecord(await cdp.send("Target.attachToTarget", { targetId, flatten: true }, undefined, signal), "Target.attachToTarget response");
40
+ if (typeof response["sessionId"] !== "string") {
41
+ throw new Error("Chrome did not return a tab session");
42
+ }
43
+ return new TabBridge(targetId, cdp, response["sessionId"], onClose);
44
+ }
45
+ catch (error) {
46
+ cdp.close();
47
+ throw error;
48
+ }
49
+ }
50
+ async run(refId, signal, action) {
51
+ if (this.closed)
52
+ throw new Error("Tab bridge is closed");
53
+ let release;
54
+ const turn = new Promise((resolveValue) => {
55
+ release = resolveValue;
56
+ });
57
+ const previous = this.tail;
58
+ this.tail = previous.then(() => turn, () => turn);
59
+ try {
60
+ await waitForTurn(previous, signal);
61
+ if (this.closed)
62
+ throw new Error("Tab bridge is closed");
63
+ this.resetIdle();
64
+ return await action({
65
+ cdp: this.cdp,
66
+ sessionId: this.sessionId,
67
+ elementRefs: this.elementRefs,
68
+ refId,
69
+ });
70
+ }
71
+ finally {
72
+ release();
73
+ }
74
+ }
75
+ close(detach = true) {
76
+ if (this.closed)
77
+ return;
78
+ this.closed = true;
79
+ if (this.idleTimer)
80
+ clearTimeout(this.idleTimer);
81
+ this.elementRefs.clear();
82
+ if (detach) {
83
+ void this.cdp
84
+ .send("Target.detachFromTarget", { sessionId: this.sessionId }, undefined, undefined)
85
+ .catch(() => undefined)
86
+ .finally(() => this.cdp.close());
87
+ }
88
+ else {
89
+ this.cdp.close();
90
+ }
91
+ this.onClose();
92
+ }
93
+ resetIdle() {
94
+ if (this.idleTimer)
95
+ clearTimeout(this.idleTimer);
96
+ this.idleTimer = setTimeout(() => this.close(), TAB_IDLE_MS);
97
+ this.idleTimer.unref?.();
98
+ }
99
+ }
100
+ export class BrowserCdpSession {
101
+ root;
102
+ rootPending;
103
+ tabs = new Map();
104
+ tabPromises = new Map();
105
+ async pages(signal) {
106
+ return getPages(await this.rootConnection(signal), signal);
107
+ }
108
+ async open(url, signal) {
109
+ assertHttpUrl(url);
110
+ const root = await this.rootConnection(signal);
111
+ const response = asRecord(await root.send("Target.createTarget", { url }, undefined, signal), "Target.createTarget response");
112
+ if (typeof response["targetId"] !== "string") {
113
+ throw new Error("Chrome did not return a new tab target");
114
+ }
115
+ const page = await waitForOpenedTarget(root, response["targetId"], url, 5_000, signal);
116
+ const pages = await getPages(root, signal);
117
+ if (!pages.some((candidate) => candidate.targetId === page.targetId)) {
118
+ pages.push(page);
119
+ }
120
+ const prefixLength = getDisplayPrefixLength(pages.map((candidate) => candidate.targetId));
121
+ return {
122
+ refId: page.targetId.slice(0, prefixLength),
123
+ };
124
+ }
125
+ async withTab(refId, signal, action) {
126
+ const pages = await this.pages(signal);
127
+ const targetId = resolvePrefix(refId, pages.map((page) => page.targetId), "target", "Run tabs.");
128
+ let bridge = this.tabs.get(targetId);
129
+ if (!bridge) {
130
+ let pending = this.tabPromises.get(targetId);
131
+ if (!pending) {
132
+ const controller = new AbortController();
133
+ const promise = this.connectTab(targetId, controller.signal);
134
+ pending = { controller, promise };
135
+ this.tabPromises.set(targetId, pending);
136
+ void promise.then((value) => {
137
+ pending.value = value;
138
+ }, () => {
139
+ if (this.tabPromises.get(targetId) === pending) {
140
+ this.tabPromises.delete(targetId);
141
+ }
142
+ });
143
+ }
144
+ const connected = await waitForTurn(pending.promise, signal);
145
+ bridge = this.tabs.get(targetId);
146
+ if (!bridge) {
147
+ if (this.tabPromises.get(targetId) !== pending) {
148
+ connected.close();
149
+ throw new Error("Tab bridge was stopped while connecting");
150
+ }
151
+ this.tabPromises.delete(targetId);
152
+ this.tabs.set(targetId, connected);
153
+ bridge = connected;
154
+ }
155
+ else if (bridge !== connected) {
156
+ connected.close();
157
+ }
158
+ }
159
+ const prefixLength = getDisplayPrefixLength(pages.map((page) => page.targetId));
160
+ return bridge.run(targetId.slice(0, prefixLength), signal, action);
161
+ }
162
+ async stop(refId) {
163
+ if (!refId) {
164
+ for (const targetId of this.tabPromises.keys()) {
165
+ this.stopPendingTab(targetId, "All tab bridges were stopped");
166
+ }
167
+ for (const bridge of this.tabs.values())
168
+ bridge.close();
169
+ this.tabs.clear();
170
+ return;
171
+ }
172
+ const pages = await this.pages();
173
+ const targetId = resolvePrefix(refId, pages.map((page) => page.targetId), "target");
174
+ this.stopPendingTab(targetId, "Tab bridge " + refId + " was stopped");
175
+ this.tabs.get(targetId)?.close();
176
+ this.tabs.delete(targetId);
177
+ }
178
+ close() {
179
+ for (const targetId of this.tabPromises.keys()) {
180
+ this.stopPendingTab(targetId, "Browser session closed");
181
+ }
182
+ for (const bridge of this.tabs.values())
183
+ bridge.close();
184
+ this.tabs.clear();
185
+ const rootPending = this.rootPending;
186
+ this.rootPending = undefined;
187
+ if (rootPending) {
188
+ rootPending.controller.abort(new Error("Browser session closed"));
189
+ void rootPending.promise.then((client) => client.close(), () => undefined);
190
+ }
191
+ this.root?.close();
192
+ this.root = undefined;
193
+ }
194
+ async rootConnection(signal) {
195
+ if (this.root)
196
+ return this.root;
197
+ let pending = this.rootPending;
198
+ if (!pending) {
199
+ const controller = new AbortController();
200
+ const promise = this.connectRoot(controller.signal);
201
+ pending = { controller, promise };
202
+ this.rootPending = pending;
203
+ void promise.then((value) => {
204
+ pending.value = value;
205
+ if (this.rootPending === pending)
206
+ this.rootPending = undefined;
207
+ }, () => {
208
+ if (this.rootPending === pending)
209
+ this.rootPending = undefined;
210
+ });
211
+ }
212
+ return waitForTurn(pending.promise, signal);
213
+ }
214
+ async connectTab(targetId, signal) {
215
+ let bridge;
216
+ bridge = await TabBridge.connect(targetId, () => {
217
+ if (bridge && this.tabs.get(targetId) === bridge) {
218
+ this.tabs.delete(targetId);
219
+ }
220
+ const pending = this.tabPromises.get(targetId);
221
+ if (bridge && pending?.value === bridge) {
222
+ this.tabPromises.delete(targetId);
223
+ }
224
+ }, signal);
225
+ return bridge;
226
+ }
227
+ stopPendingTab(targetId, message) {
228
+ const pending = this.tabPromises.get(targetId);
229
+ if (!pending)
230
+ return;
231
+ this.tabPromises.delete(targetId);
232
+ pending.controller.abort(new Error(message));
233
+ void pending.promise.then((bridge) => bridge.close(), () => undefined);
234
+ }
235
+ async connectRoot(signal) {
236
+ const client = new CdpClient();
237
+ await client.connect(await getWebSocketUrl(), signal);
238
+ this.root = client;
239
+ client.onClose(() => {
240
+ if (this.root !== client)
241
+ return;
242
+ this.root = undefined;
243
+ });
244
+ return client;
245
+ }
246
+ }
@@ -0,0 +1,32 @@
1
+ export type SnapshotResponseLength = "short" | "medium" | "long";
2
+ export declare const SNAPSHOT_LIMITS: Record<SnapshotResponseLength, number>;
3
+ export interface SnapshotLine {
4
+ line: number;
5
+ text: string;
6
+ element_id?: number | undefined;
7
+ }
8
+ export interface SnapshotElement {
9
+ id: number;
10
+ role: string;
11
+ name?: string | undefined;
12
+ value?: unknown;
13
+ }
14
+ export interface SnapshotResult {
15
+ ref_id?: string | undefined;
16
+ title: string;
17
+ url: string;
18
+ lineno: number;
19
+ content: SnapshotLine[];
20
+ elements: SnapshotElement[];
21
+ pattern?: string | undefined;
22
+ next_lineno?: number | undefined;
23
+ }
24
+ export interface SnapshotOptions {
25
+ refId?: string | undefined;
26
+ pattern?: string | undefined;
27
+ lineno?: number | string | undefined;
28
+ responseLength?: SnapshotResponseLength | string | undefined;
29
+ signal?: AbortSignal | undefined;
30
+ }
31
+ export declare function positiveInteger(value: number | string, label: string): number;
32
+ export declare function snapshotResponseLength(value: string | undefined): SnapshotResponseLength;
@@ -0,0 +1,23 @@
1
+ export const SNAPSHOT_LIMITS = {
2
+ short: 60,
3
+ medium: 140,
4
+ long: 300,
5
+ };
6
+ export function positiveInteger(value, label) {
7
+ const source = String(value);
8
+ if (!/^[1-9]\d*$/.test(source)) {
9
+ throw new Error(`${label} must be a positive integer`);
10
+ }
11
+ const parsed = Number(source);
12
+ if (!Number.isSafeInteger(parsed)) {
13
+ throw new Error(`${label} must be a safe positive integer`);
14
+ }
15
+ return parsed;
16
+ }
17
+ export function snapshotResponseLength(value) {
18
+ const resolved = value ?? "medium";
19
+ if (resolved !== "short" && resolved !== "medium" && resolved !== "long") {
20
+ throw new Error(`response length must be one of: ${Object.keys(SNAPSHOT_LIMITS).join(", ")}`);
21
+ }
22
+ return resolved;
23
+ }
@@ -0,0 +1,3 @@
1
+ import { type SnapshotOptions, type SnapshotResult } from "./snapshot-contract.js";
2
+ import type { CdpConnection, ElementRefs } from "./types.js";
3
+ export declare function snapshotData(cdp: CdpConnection, sessionId: string, elementRefs: ElementRefs, options?: SnapshotOptions): Promise<SnapshotResult>;
@@ -0,0 +1,205 @@
1
+ import { evaluate } from "./evaluate.js";
2
+ import { positiveInteger, SNAPSHOT_LIMITS, snapshotResponseLength, } from "./snapshot-contract.js";
3
+ import { asRecord } from "./types.js";
4
+ const INTERACTIVE_ROLES = new Set([
5
+ "button",
6
+ "checkbox",
7
+ "combobox",
8
+ "link",
9
+ "listbox",
10
+ "menuitem",
11
+ "option",
12
+ "menuitemcheckbox",
13
+ "menuitemradio",
14
+ "radio",
15
+ "searchbox",
16
+ "slider",
17
+ "spinbutton",
18
+ "switch",
19
+ "tab",
20
+ "textbox",
21
+ "treeitem",
22
+ ]);
23
+ const NEXT_ELEMENT_IDS = new WeakMap();
24
+ function axNode(value) {
25
+ const record = asRecord(value, "accessibility node");
26
+ if (typeof record["nodeId"] !== "string") {
27
+ throw new Error("Accessibility node has no nodeId");
28
+ }
29
+ return {
30
+ nodeId: record["nodeId"],
31
+ ...(typeof record["parentId"] === "string"
32
+ ? { parentId: record["parentId"] }
33
+ : {}),
34
+ ...(Array.isArray(record["childIds"])
35
+ ? {
36
+ childIds: record["childIds"].filter((id) => typeof id === "string"),
37
+ }
38
+ : {}),
39
+ ...(typeof record["backendDOMNodeId"] === "number"
40
+ ? { backendDOMNodeId: record["backendDOMNodeId"] }
41
+ : {}),
42
+ ...(typeof record["ignored"] === "boolean"
43
+ ? { ignored: record["ignored"] }
44
+ : {}),
45
+ ...(record["role"] ? { role: asRecord(record["role"]) } : {}),
46
+ ...(record["name"] ? { name: asRecord(record["name"]) } : {}),
47
+ ...(record["value"] ? { value: asRecord(record["value"]) } : {}),
48
+ };
49
+ }
50
+ function shouldShow(node) {
51
+ const role = String(node.role?.value ?? "");
52
+ const name = node.name?.value ?? "";
53
+ const value = node.value?.value;
54
+ if (role === "InlineTextBox")
55
+ return false;
56
+ return (role !== "none" &&
57
+ role !== "generic" &&
58
+ !(name === "" && (value === "" || value == null)));
59
+ }
60
+ function orderedChildren(node, nodesById, childrenByParent) {
61
+ const children = [];
62
+ const seen = new Set();
63
+ for (const childId of node.childIds ?? []) {
64
+ const child = nodesById.get(childId);
65
+ if (child && !seen.has(child.nodeId)) {
66
+ seen.add(child.nodeId);
67
+ children.push(child);
68
+ }
69
+ }
70
+ for (const child of childrenByParent.get(node.nodeId) ?? []) {
71
+ if (!seen.has(child.nodeId)) {
72
+ seen.add(child.nodeId);
73
+ children.push(child);
74
+ }
75
+ }
76
+ return children;
77
+ }
78
+ function normalizeText(value) {
79
+ return String(value ?? "")
80
+ .replace(/\s+/g, " ")
81
+ .trim();
82
+ }
83
+ function splitText(value, max = 700) {
84
+ const text = normalizeText(value);
85
+ if (!text)
86
+ return [];
87
+ const parts = [];
88
+ for (let start = 0; start < text.length; start += max) {
89
+ parts.push(text.slice(start, start + max));
90
+ }
91
+ return parts;
92
+ }
93
+ export async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
94
+ const lineno = positiveInteger(options.lineno ?? 1, "line cursor");
95
+ const responseLength = snapshotResponseLength(options.responseLength);
96
+ const response = asRecord(await cdp.send("Accessibility.getFullAXTree", {}, sessionId, options.signal), "Accessibility response");
97
+ if (!Array.isArray(response["nodes"])) {
98
+ throw new Error("Accessibility response has no nodes");
99
+ }
100
+ const nodes = response["nodes"].map(axNode);
101
+ const nodesById = new Map(nodes.map((node) => [node.nodeId, node]));
102
+ const childrenByParent = new Map();
103
+ for (const node of nodes) {
104
+ if (!node.parentId)
105
+ continue;
106
+ const children = childrenByParent.get(node.parentId) ?? [];
107
+ children.push(node);
108
+ childrenByParent.set(node.parentId, children);
109
+ }
110
+ elementRefs.clear();
111
+ const lines = [];
112
+ const elements = [];
113
+ const visited = new Set();
114
+ const nextElementId = () => {
115
+ const id = NEXT_ELEMENT_IDS.get(elementRefs) ?? 1;
116
+ if (!Number.isSafeInteger(id)) {
117
+ throw new Error("Element id limit reached; restart the tab bridge");
118
+ }
119
+ NEXT_ELEMENT_IDS.set(elementRefs, id + 1);
120
+ return id;
121
+ };
122
+ const addLine = (text, element, kind = "text") => {
123
+ for (const part of splitText(text)) {
124
+ lines.push({
125
+ line: lines.length + 1,
126
+ text: part,
127
+ kind,
128
+ ...(element ? { element_id: element.id } : {}),
129
+ });
130
+ }
131
+ };
132
+ const addStaticText = (text) => {
133
+ const normalized = normalizeText(text);
134
+ if (!normalized)
135
+ return;
136
+ const previous = lines.at(-1);
137
+ if (previous?.kind === "text" &&
138
+ previous.text.length + normalized.length + 1 <= 700) {
139
+ previous.text += ` ${normalized}`;
140
+ return;
141
+ }
142
+ addLine(normalized);
143
+ };
144
+ const visit = (node, parentName = "") => {
145
+ if (!node || visited.has(node.nodeId))
146
+ return;
147
+ visited.add(node.nodeId);
148
+ const role = String(node.role?.value ?? "");
149
+ const name = normalizeText(node.name?.value ?? "");
150
+ const value = node.value?.value;
151
+ let renderedName = parentName;
152
+ if (!node.ignored && shouldShow(node)) {
153
+ if (INTERACTIVE_ROLES.has(role) && node.backendDOMNodeId) {
154
+ const element = {
155
+ id: nextElementId(),
156
+ role,
157
+ ...(name ? { name } : {}),
158
+ ...(value === "" || value == null ? {} : { value }),
159
+ };
160
+ elementRefs.set(element.id, node.backendDOMNodeId);
161
+ elements.push(element);
162
+ addLine(`[${element.id}] ${role}${name ? ` ${name}` : ""}${value === "" || value == null ? "" : ` = ${JSON.stringify(value)}`}`, element, "interactive");
163
+ renderedName = name;
164
+ }
165
+ else if (role === "StaticText") {
166
+ if (name && name !== parentName)
167
+ addStaticText(name);
168
+ }
169
+ else if (role === "heading" || role === "image") {
170
+ if (name)
171
+ addLine(`${role}: ${name}`, undefined, role);
172
+ renderedName = name || parentName;
173
+ }
174
+ }
175
+ for (const child of orderedChildren(node, nodesById, childrenByParent)) {
176
+ visit(child, renderedName);
177
+ }
178
+ };
179
+ for (const root of nodes.filter((node) => !node.parentId || !nodesById.has(node.parentId))) {
180
+ visit(root);
181
+ }
182
+ for (const node of nodes)
183
+ visit(node);
184
+ const metadata = asRecord(await evaluate(cdp, sessionId, "({title: document.title, url: location.href})", options.signal), "page metadata");
185
+ const pattern = options.pattern?.toLowerCase();
186
+ const matching = pattern
187
+ ? lines.filter((line) => line.text.toLowerCase().includes(pattern))
188
+ : lines;
189
+ const start = lineno - 1;
190
+ const content = matching
191
+ .slice(start, start + SNAPSHOT_LIMITS[responseLength])
192
+ .map(({ kind: _kind, ...line }) => line);
193
+ const visibleIds = new Set(content.flatMap((line) => line.element_id === undefined ? [] : [line.element_id]));
194
+ const hasMore = start + content.length < matching.length;
195
+ return {
196
+ ...(options.refId ? { ref_id: options.refId } : {}),
197
+ title: typeof metadata["title"] === "string" ? metadata["title"] : "",
198
+ url: typeof metadata["url"] === "string" ? metadata["url"] : "",
199
+ lineno: start + 1,
200
+ content,
201
+ elements: elements.filter((element) => visibleIds.has(element.id)),
202
+ ...(options.pattern ? { pattern: options.pattern } : {}),
203
+ ...(hasMore ? { next_lineno: start + content.length + 1 } : {}),
204
+ };
205
+ }
@@ -0,0 +1,20 @@
1
+ export type CdpParams = Record<string, unknown>;
2
+ export interface CdpEventWait {
3
+ promise: Promise<unknown>;
4
+ cancel(): void;
5
+ }
6
+ export interface CdpConnection {
7
+ send(method: string, params?: CdpParams, sessionId?: string, signal?: AbortSignal): Promise<unknown>;
8
+ onEvent(method: string, handler: (params: unknown) => void): () => void;
9
+ waitForEvent(method: string, timeout?: number, signal?: AbortSignal): CdpEventWait;
10
+ }
11
+ export interface PageInfo {
12
+ targetId: string;
13
+ title: string;
14
+ url: string;
15
+ type?: string;
16
+ }
17
+ export type ElementRefs = Map<number, number>;
18
+ export declare function asRecord(value: unknown, label?: string): Record<string, unknown>;
19
+ export declare function asString(value: unknown, label: string): string;
20
+ export declare function errorMessage(error: unknown): string;
@@ -0,0 +1,14 @@
1
+ export function asRecord(value, label = "CDP response") {
2
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
3
+ throw new Error(`${label} is not an object`);
4
+ }
5
+ return value;
6
+ }
7
+ export function asString(value, label) {
8
+ if (typeof value !== "string")
9
+ throw new Error(`${label} is not a string`);
10
+ return value;
11
+ }
12
+ export function errorMessage(error) {
13
+ return error instanceof Error ? error.message : String(error);
14
+ }
@@ -0,0 +1 @@
1
+ export declare function assertHttpUrl(value: string): void;
@@ -0,0 +1,12 @@
1
+ export function assertHttpUrl(value) {
2
+ let parsed;
3
+ try {
4
+ parsed = new URL(value);
5
+ }
6
+ catch {
7
+ throw new Error(`Invalid URL: ${value}`);
8
+ }
9
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
10
+ throw new Error(`Only http/https URLs allowed, got: ${value}`);
11
+ }
12
+ }
package/index.ts ADDED
@@ -0,0 +1,115 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { BrowserRoutes, loadBrowserRoutes } from "./src/browser/routes.js";
3
+ import { BrowserRuntime } from "./src/browser/runtime.js";
4
+ import { registerBrowserCommand } from "./src/browser/settings.js";
5
+ import {
6
+ createBrowserTool,
7
+ prepareBrowserCodeModeInput,
8
+ } from "./src/browser-tool.js";
9
+
10
+ export { createBrowserTool } from "./src/browser-tool.js";
11
+
12
+ const CODE_MODE_PACKAGE = "@howaboua/pi-codex-conversion";
13
+ const CODE_MODE_MODULE = `${CODE_MODE_PACKAGE}/code-mode`;
14
+
15
+ export default async function browserExtension(
16
+ pi: ExtensionAPI,
17
+ ): Promise<void> {
18
+ let configError: string | undefined;
19
+ let routes: BrowserRoutes;
20
+ try {
21
+ routes = loadBrowserRoutes();
22
+ } catch (error) {
23
+ routes = new BrowserRoutes();
24
+ configError = error instanceof Error ? error.message : String(error);
25
+ }
26
+ const runtime = new BrowserRuntime(routes);
27
+ const tool = createBrowserTool(runtime);
28
+ registerBrowserCommand(pi);
29
+ pi.registerTool(tool);
30
+ const registration = await registerBrowserInCodeMode(
31
+ pi,
32
+ tool,
33
+ runtime.hosts.length > 0,
34
+ );
35
+ pi.on("session_shutdown", () => {
36
+ registration?.unregister();
37
+ runtime.close();
38
+ });
39
+ if (configError) {
40
+ pi.on("session_start", (_event, ctx) => {
41
+ ctx.ui.notify(`${configError}. Run /browser to repair it.`, "warning");
42
+ });
43
+ }
44
+ }
45
+
46
+ async function registerBrowserInCodeMode(
47
+ pi: ExtensionAPI,
48
+ tool: ReturnType<typeof createBrowserTool>,
49
+ routed: boolean,
50
+ ) {
51
+ try {
52
+ const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
53
+ await import("@howaboua/pi-codex-conversion/code-mode");
54
+ return registerCodeModeExtensionTools(pi, () => [
55
+ adaptToolForCodeMode(tool, {
56
+ kind: "freeform",
57
+ prepareInput: prepareBrowserCodeModeInput,
58
+ usage: `await tools.browser("help"); await tools.browser(JSON.stringify({ action: "tabs" })) // Logged-in ${
59
+ routed ? "routed " : "local "
60
+ }browser with web__run refs; ask before consequential external actions`,
61
+ }),
62
+ ]);
63
+ } catch (error) {
64
+ if (isMissingCodeModeExtension(error)) return undefined;
65
+ if (isOutdatedCodeModeExtension(error)) {
66
+ throw new Error(
67
+ "Update " +
68
+ CODE_MODE_PACKAGE +
69
+ " to 3.0.24 or newer to use Pi Browser with it",
70
+ { cause: error },
71
+ );
72
+ }
73
+ throw error;
74
+ }
75
+ }
76
+
77
+ function isMissingCodeModeExtension(error: unknown): boolean {
78
+ if (
79
+ !error ||
80
+ typeof error !== "object" ||
81
+ !("code" in error) ||
82
+ !("message" in error) ||
83
+ typeof error.message !== "string"
84
+ ) {
85
+ return false;
86
+ }
87
+ if (
88
+ error.code !== "ERR_MODULE_NOT_FOUND" &&
89
+ error.code !== "MODULE_NOT_FOUND"
90
+ ) {
91
+ return false;
92
+ }
93
+ const missing = error.message.match(
94
+ /Cannot find (?:package|module) ['"]([^'"]+)['"]/,
95
+ )?.[1];
96
+ return missing === CODE_MODE_PACKAGE || missing === CODE_MODE_MODULE;
97
+ }
98
+
99
+ function isOutdatedCodeModeExtension(error: unknown): boolean {
100
+ if (
101
+ !error ||
102
+ typeof error !== "object" ||
103
+ !("code" in error) ||
104
+ !("message" in error) ||
105
+ typeof error.message !== "string"
106
+ )
107
+ return false;
108
+ return (
109
+ (error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" ||
110
+ error.code === "ERR_UNSUPPORTED_DIR_IMPORT") &&
111
+ (error.message.includes(CODE_MODE_MODULE) ||
112
+ (error.message.includes("Package subpath './code-mode'") &&
113
+ error.message.includes(CODE_MODE_PACKAGE)))
114
+ );
115
+ }