@howaboua/pi-browser 0.0.10 → 0.0.12

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 (39) hide show
  1. package/CHANGELOG.md +11 -4
  2. package/README.md +11 -1
  3. package/biome.json +1 -1
  4. package/dist/extension.d.ts +3 -0
  5. package/dist/extension.js +29 -0
  6. package/dist/index.d.ts +1 -2
  7. package/dist/index.js +1 -100
  8. package/dist/remote-worker.js +137 -116
  9. package/dist/src/browser/config.d.ts +2 -0
  10. package/dist/src/browser/config.js +38 -5
  11. package/dist/src/browser/help.js +7 -7
  12. package/dist/src/browser/voice-start.d.ts +16 -0
  13. package/dist/src/browser/voice-start.js +110 -0
  14. package/dist/src/browser-registration.d.ts +6 -0
  15. package/dist/src/browser-registration.js +103 -0
  16. package/dist/src/browser-tool-definition.d.ts +12 -0
  17. package/dist/src/browser-tool-definition.js +63 -0
  18. package/dist/src/browser-tool.d.ts +1 -4
  19. package/dist/src/browser-tool.js +2 -62
  20. package/dist/src/cdp/session.d.ts +3 -8
  21. package/dist/src/cdp/session.js +1 -104
  22. package/dist/src/cdp/snapshot-tree.d.ts +8 -0
  23. package/dist/src/cdp/snapshot-tree.js +238 -0
  24. package/dist/src/cdp/snapshot.js +2 -234
  25. package/dist/src/cdp/tab-bridge.d.ts +25 -0
  26. package/dist/src/cdp/tab-bridge.js +107 -0
  27. package/index.ts +1 -127
  28. package/package.json +12 -8
  29. package/src/browser/config.ts +48 -7
  30. package/src/browser/help.ts +7 -7
  31. package/src/browser/voice-start.ts +154 -0
  32. package/src/browser-registration.ts +138 -0
  33. package/src/browser-tool-definition.ts +81 -0
  34. package/src/browser-tool.ts +3 -69
  35. package/src/cdp/session.ts +3 -145
  36. package/src/cdp/snapshot-tree.ts +291 -0
  37. package/src/cdp/snapshot.ts +5 -282
  38. package/src/cdp/tab-bridge.ts +149 -0
  39. package/tsconfig.json +1 -1
@@ -1,77 +1,11 @@
1
1
  import { defineTool } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
- import { browserHelp } from "./browser/help.js";
4
- import { isRecordValue } from "./browser/parse-operation.js";
5
- import { parseBrowserRequest } from "./browser/request.js";
6
- import { BrowserRuntime } from "./browser/runtime.js";
7
-
8
- export function prepareBrowserInput(input: unknown): { command: string } {
9
- if (input === undefined) return { command: "help" };
10
- if (typeof input === "string") return { command: input };
11
- if (!isRecordValue(input)) {
12
- throw new Error("browser input must be a command envelope or JSON request");
13
- }
14
- if (Object.hasOwn(input, "command")) {
15
- if (typeof input["command"] !== "string") {
16
- throw new Error(
17
- 'browser command must be "help" or a JSON request string',
18
- );
19
- }
20
- return { ...input, command: input["command"] };
21
- }
22
- // Resume old object calls without changing their stored history representation.
23
- parseBrowserRequest(input);
24
- return { command: JSON.stringify(input) };
25
- }
3
+ import type { BrowserRuntime } from "./browser/runtime.js";
4
+ import { createBrowserTool as createTool } from "./browser-tool-definition.js";
26
5
 
27
6
  export function createBrowserTool(
28
7
  runtime: BrowserRuntime,
29
8
  isGpt = () => false,
30
9
  ) {
31
- return defineTool({
32
- name: "browser",
33
- label: "Browser",
34
- description: "Control logged-in browser",
35
- parameters: Type.Object(
36
- {
37
- command: Type.Optional(
38
- Type.String({ description: "help or JSON request" }),
39
- ),
40
- },
41
- { additionalProperties: false },
42
- ),
43
- prepareArguments: prepareBrowserInput,
44
- async execute(_toolCallId, input, signal, onUpdate, ctx) {
45
- const request = parseBrowserRequest(input.command);
46
- let result = await runtime.execute(request, {
47
- ownerId: ctx.sessionManager.getSessionId(),
48
- signal: signal ?? new AbortController().signal,
49
- onOperation(operation, index, total) {
50
- onUpdate?.({
51
- content: [
52
- {
53
- type: "text",
54
- text:
55
- total === 1
56
- ? `Browser ${operation.action}`
57
- : `Browser ${operation.action} ${index + 1}/${total}`,
58
- },
59
- ],
60
- details: {
61
- action: operation.action,
62
- index: index + 1,
63
- total,
64
- status: "running",
65
- },
66
- });
67
- },
68
- });
69
- if (isGpt() && "help" in request)
70
- result = browserHelp(runtime.hosts, true);
71
- return {
72
- content: [{ type: "text", text: JSON.stringify(result) }],
73
- details: result,
74
- };
75
- },
76
- });
10
+ return createTool({ defineTool, Type }, runtime, isGpt);
77
11
  }
@@ -5,18 +5,11 @@ import {
5
5
  resolvePrefix,
6
6
  } from "./discovery.js";
7
7
  import { waitForTurn } from "./serial.js";
8
+ import { type ActiveTab, TabBridge } from "./tab-bridge.js";
8
9
  import { BrowserTabs } from "./tabs.js";
9
- import type { ElementRefs, PageInfo } from "./types.js";
10
- import { asRecord } from "./types.js";
10
+ import type { PageInfo } from "./types.js";
11
11
 
12
- const TAB_IDLE_MS = 20 * 60 * 1_000;
13
-
14
- export interface ActiveTab {
15
- cdp: CdpClient;
16
- sessionId: string;
17
- elementRefs: ElementRefs;
18
- refId: string;
19
- }
12
+ export type { ActiveTab } from "./tab-bridge.js";
20
13
 
21
14
  interface PendingConnection<T> {
22
15
  controller: AbortController;
@@ -29,141 +22,6 @@ interface BrowserConnection {
29
22
  tabs: BrowserTabs;
30
23
  }
31
24
 
32
- class TabBridge {
33
- readonly elementRefs: ElementRefs = new Map();
34
- readonly targetId: string;
35
- readonly cdp: CdpClient;
36
- readonly sessionId: string;
37
- private tail = Promise.resolve();
38
- private idleTimer: ReturnType<typeof setTimeout> | undefined;
39
- private closed = false;
40
- private backgroundRendering: boolean | undefined = false;
41
- private readonly onClose: () => void;
42
-
43
- private constructor(
44
- targetId: string,
45
- cdp: CdpClient,
46
- sessionId: string,
47
- onClose: () => void,
48
- ) {
49
- this.targetId = targetId;
50
- this.cdp = cdp;
51
- this.sessionId = sessionId;
52
- this.onClose = onClose;
53
- this.resetIdle();
54
- cdp.onEvent("Target.targetDestroyed", (value) => {
55
- const event = asRecord(value, "target destroyed event");
56
- if (event["targetId"] === targetId) this.close(false);
57
- });
58
- cdp.onEvent("Target.detachedFromTarget", (value) => {
59
- const event = asRecord(value, "target detached event");
60
- if (event["sessionId"] === sessionId) this.close(false);
61
- });
62
- cdp.onClose(() => this.close(false));
63
- }
64
-
65
- static async connect(
66
- targetId: string,
67
- onClose: () => void,
68
- signal?: AbortSignal,
69
- ): Promise<TabBridge> {
70
- const cdp = new CdpClient();
71
- try {
72
- await cdp.connect(await getWebSocketUrl(), signal);
73
- const response = asRecord(
74
- await cdp.send(
75
- "Target.attachToTarget",
76
- { targetId, flatten: true },
77
- undefined,
78
- signal,
79
- ),
80
- "Target.attachToTarget response",
81
- );
82
- if (typeof response["sessionId"] !== "string") {
83
- throw new Error("Chrome did not return a tab session");
84
- }
85
- return new TabBridge(targetId, cdp, response["sessionId"], onClose);
86
- } catch (error) {
87
- cdp.close();
88
- throw error;
89
- }
90
- }
91
-
92
- async run<T>(
93
- refId: string,
94
- signal: AbortSignal | undefined,
95
- action: (tab: ActiveTab) => Promise<T>,
96
- ): Promise<T> {
97
- if (this.closed) throw new Error("Tab bridge is closed");
98
- let release!: () => void;
99
- const turn = new Promise<void>((resolveValue) => {
100
- release = resolveValue;
101
- });
102
- const previous = this.tail;
103
- this.tail = previous.then(
104
- () => turn,
105
- () => turn,
106
- );
107
- try {
108
- await waitForTurn(previous, signal);
109
- if (this.closed) throw new Error("Tab bridge is closed");
110
- this.resetIdle();
111
- return await action({
112
- cdp: this.cdp,
113
- sessionId: this.sessionId,
114
- elementRefs: this.elementRefs,
115
- refId,
116
- });
117
- } finally {
118
- release();
119
- }
120
- }
121
-
122
- async setBackgroundRendering(
123
- enabled: boolean,
124
- signal?: AbortSignal,
125
- ): Promise<void> {
126
- if (this.backgroundRendering === enabled) return;
127
- // An interrupted command may already have applied. Keep the state unknown
128
- // until Chrome acknowledges it, so the next action reestablishes it.
129
- this.backgroundRendering = undefined;
130
- await this.cdp.send(
131
- "Emulation.setFocusEmulationEnabled",
132
- { enabled },
133
- this.sessionId,
134
- signal,
135
- );
136
- this.backgroundRendering = enabled;
137
- }
138
-
139
- close(detach = true): void {
140
- if (this.closed) return;
141
- this.closed = true;
142
- if (this.idleTimer) clearTimeout(this.idleTimer);
143
- this.elementRefs.clear();
144
- if (detach) {
145
- void this.cdp
146
- .send(
147
- "Target.detachFromTarget",
148
- { sessionId: this.sessionId },
149
- undefined,
150
- undefined,
151
- )
152
- .catch(() => undefined)
153
- .finally(() => this.cdp.close());
154
- } else {
155
- this.cdp.close();
156
- }
157
- this.onClose();
158
- }
159
-
160
- private resetIdle(): void {
161
- if (this.idleTimer) clearTimeout(this.idleTimer);
162
- this.idleTimer = setTimeout(() => this.close(), TAB_IDLE_MS);
163
- this.idleTimer.unref?.();
164
- }
165
- }
166
-
167
25
  export class BrowserCdpSession {
168
26
  private closing: Promise<void> | undefined;
169
27
  private root: BrowserConnection | undefined;
@@ -0,0 +1,291 @@
1
+ import type { SnapshotElement, SnapshotLine } from "./snapshot-contract.js";
2
+ import type { ElementRefs } from "./types.js";
3
+ import { asRecord } from "./types.js";
4
+
5
+ interface AxValue {
6
+ value?: unknown;
7
+ }
8
+
9
+ interface AxProperty {
10
+ name: string;
11
+ value?: AxValue | undefined;
12
+ }
13
+
14
+ interface AxNode {
15
+ nodeId: string;
16
+ parentId?: string | undefined;
17
+ childIds?: string[] | undefined;
18
+ backendDOMNodeId?: number | undefined;
19
+ ignored?: boolean | undefined;
20
+ role?: AxValue | undefined;
21
+ name?: AxValue | undefined;
22
+ value?: AxValue | undefined;
23
+ properties?: AxProperty[] | undefined;
24
+ }
25
+
26
+ const INTERACTIVE_ROLES = new Set([
27
+ "button",
28
+ "checkbox",
29
+ "combobox",
30
+ "link",
31
+ "listbox",
32
+ "menuitem",
33
+ "option",
34
+ "menuitemcheckbox",
35
+ "menuitemradio",
36
+ "radio",
37
+ "searchbox",
38
+ "slider",
39
+ "spinbutton",
40
+ "switch",
41
+ "tab",
42
+ "textbox",
43
+ "treeitem",
44
+ ]);
45
+ const NEXT_ELEMENT_IDS = new WeakMap<ElementRefs, number>();
46
+
47
+ function axProperty(value: unknown): AxProperty {
48
+ const record = asRecord(value, "accessibility property");
49
+ if (typeof record["name"] !== "string") {
50
+ throw new Error("Accessibility property has no name");
51
+ }
52
+ return {
53
+ name: record["name"],
54
+ ...(record["value"] ? { value: asRecord(record["value"]) } : {}),
55
+ };
56
+ }
57
+
58
+ function axNode(value: unknown): AxNode {
59
+ const record = asRecord(value, "accessibility node");
60
+ if (typeof record["nodeId"] !== "string") {
61
+ throw new Error("Accessibility node has no nodeId");
62
+ }
63
+ return {
64
+ nodeId: record["nodeId"],
65
+ ...(typeof record["parentId"] === "string"
66
+ ? { parentId: record["parentId"] }
67
+ : {}),
68
+ ...(Array.isArray(record["childIds"])
69
+ ? {
70
+ childIds: record["childIds"].filter(
71
+ (id): id is string => typeof id === "string",
72
+ ),
73
+ }
74
+ : {}),
75
+ ...(typeof record["backendDOMNodeId"] === "number"
76
+ ? { backendDOMNodeId: record["backendDOMNodeId"] }
77
+ : {}),
78
+ ...(typeof record["ignored"] === "boolean"
79
+ ? { ignored: record["ignored"] }
80
+ : {}),
81
+ ...(record["role"] ? { role: asRecord(record["role"]) } : {}),
82
+ ...(record["name"] ? { name: asRecord(record["name"]) } : {}),
83
+ ...(record["value"] ? { value: asRecord(record["value"]) } : {}),
84
+ ...(Array.isArray(record["properties"])
85
+ ? { properties: record["properties"].map(axProperty) }
86
+ : {}),
87
+ };
88
+ }
89
+
90
+ function shouldShow(node: AxNode): boolean {
91
+ const role = String(node.role?.value ?? "");
92
+ const name = node.name?.value ?? "";
93
+ const value = node.value?.value;
94
+ if (role === "InlineTextBox") return false;
95
+ if (INTERACTIVE_ROLES.has(role)) return true;
96
+ return (
97
+ role !== "none" &&
98
+ role !== "generic" &&
99
+ !(name === "" && (value === "" || value == null))
100
+ );
101
+ }
102
+
103
+ function orderedChildren(
104
+ node: AxNode,
105
+ nodesById: Map<string, AxNode>,
106
+ childrenByParent: Map<string, AxNode[]>,
107
+ ): AxNode[] {
108
+ const children: AxNode[] = [];
109
+ const seen = new Set<string>();
110
+ for (const childId of node.childIds ?? []) {
111
+ const child = nodesById.get(childId);
112
+ if (child && !seen.has(child.nodeId)) {
113
+ seen.add(child.nodeId);
114
+ children.push(child);
115
+ }
116
+ }
117
+ for (const child of childrenByParent.get(node.nodeId) ?? []) {
118
+ if (!seen.has(child.nodeId)) {
119
+ seen.add(child.nodeId);
120
+ children.push(child);
121
+ }
122
+ }
123
+ return children;
124
+ }
125
+
126
+ function normalizeText(value: unknown): string {
127
+ return String(value ?? "")
128
+ .replace(/\s+/g, " ")
129
+ .trim();
130
+ }
131
+
132
+ function splitText(value: unknown, max = 700): string[] {
133
+ const text = normalizeText(value);
134
+ if (!text) return [];
135
+ const parts: string[] = [];
136
+ for (let start = 0; start < text.length; start += max) {
137
+ parts.push(text.slice(start, start + max));
138
+ }
139
+ return parts;
140
+ }
141
+
142
+ function interactiveState(
143
+ node: AxNode,
144
+ ): Pick<SnapshotElement, "checked" | "selected" | "expanded" | "disabled"> {
145
+ const values = new Map(
146
+ (node.properties ?? []).map((property) => [
147
+ property.name,
148
+ property.value?.value,
149
+ ]),
150
+ );
151
+ const checkedValue = values.get("checked");
152
+ const checked =
153
+ checkedValue === "true"
154
+ ? true
155
+ : checkedValue === "false"
156
+ ? false
157
+ : typeof checkedValue === "boolean" || checkedValue === "mixed"
158
+ ? checkedValue
159
+ : undefined;
160
+ const selected = values.get("selected");
161
+ const expanded = values.get("expanded");
162
+ const disabled = values.get("disabled");
163
+ return {
164
+ ...(checked === undefined ? {} : { checked }),
165
+ ...(typeof selected === "boolean" ? { selected } : {}),
166
+ ...(typeof expanded === "boolean" ? { expanded } : {}),
167
+ ...(typeof disabled === "boolean" ? { disabled } : {}),
168
+ };
169
+ }
170
+
171
+ function interactiveText(
172
+ role: string,
173
+ name: string,
174
+ value: unknown,
175
+ state: ReturnType<typeof interactiveState>,
176
+ ): string {
177
+ const states = [
178
+ state.checked === undefined ? undefined : `checked=${state.checked}`,
179
+ state.selected === undefined ? undefined : `selected=${state.selected}`,
180
+ state.expanded === undefined ? undefined : `expanded=${state.expanded}`,
181
+ state.disabled === undefined ? undefined : `disabled=${state.disabled}`,
182
+ ].filter((entry): entry is string => entry !== undefined);
183
+ return `${role}${name ? ` ${name}` : ""}${
184
+ value === "" || value == null ? "" : ` = ${JSON.stringify(value)}`
185
+ }${states.length > 0 ? ` [${states.join(", ")}]` : ""}`;
186
+ }
187
+
188
+ export function renderSnapshotTree(
189
+ rawNodes: unknown[],
190
+ elementRefs: ElementRefs,
191
+ ) {
192
+ const nodes = rawNodes.map(axNode);
193
+ const nodesById = new Map(nodes.map((node) => [node.nodeId, node]));
194
+ const childrenByParent = new Map<string, AxNode[]>();
195
+ for (const node of nodes) {
196
+ if (!node.parentId) continue;
197
+ const children = childrenByParent.get(node.parentId) ?? [];
198
+ children.push(node);
199
+ childrenByParent.set(node.parentId, children);
200
+ }
201
+
202
+ elementRefs.clear();
203
+ type InternalLine = SnapshotLine & { kind: string };
204
+ const lines: InternalLine[] = [];
205
+ const elements: SnapshotElement[] = [];
206
+ const visited = new Set<string>();
207
+ const nextElementId = () => {
208
+ const id = NEXT_ELEMENT_IDS.get(elementRefs) ?? 1;
209
+ if (!Number.isSafeInteger(id)) {
210
+ throw new Error("Element id limit reached; restart the tab bridge");
211
+ }
212
+ NEXT_ELEMENT_IDS.set(elementRefs, id + 1);
213
+ return id;
214
+ };
215
+ const addLine = (text: string, element?: SnapshotElement, kind = "text") => {
216
+ for (const part of splitText(text)) {
217
+ lines.push({
218
+ line: lines.length + 1,
219
+ text: part,
220
+ kind,
221
+ ...(element ? { element_id: element.id } : {}),
222
+ });
223
+ }
224
+ };
225
+ const addStaticText = (text: string) => {
226
+ const normalized = normalizeText(text);
227
+ if (!normalized) return;
228
+ const previous = lines.at(-1);
229
+ if (
230
+ previous?.kind === "text" &&
231
+ previous.text.length + normalized.length + 1 <= 700
232
+ ) {
233
+ previous.text += ` ${normalized}`;
234
+ return;
235
+ }
236
+ addLine(normalized);
237
+ };
238
+ const visit = (node: AxNode | undefined, parentName = ""): void => {
239
+ if (!node || visited.has(node.nodeId)) return;
240
+ visited.add(node.nodeId);
241
+ const role = String(node.role?.value ?? "");
242
+ const name = normalizeText(node.name?.value ?? "");
243
+ const value = node.value?.value;
244
+ let renderedName = parentName;
245
+ if (!node.ignored && shouldShow(node)) {
246
+ if (INTERACTIVE_ROLES.has(role)) {
247
+ const state = interactiveState(node);
248
+ const text = interactiveText(role, name, value, state);
249
+ if (!node.backendDOMNodeId) {
250
+ addLine(text, undefined, "interactive");
251
+ renderedName = name;
252
+ } else {
253
+ const href =
254
+ role === "link"
255
+ ? node.properties?.find((property) => property.name === "url")
256
+ ?.value?.value
257
+ : undefined;
258
+ const element: SnapshotElement = {
259
+ id: nextElementId(),
260
+ role,
261
+ ...(name ? { name } : {}),
262
+ ...(typeof href === "string" && href ? { href } : {}),
263
+ ...(value === "" || value == null ? {} : { value }),
264
+ ...state,
265
+ };
266
+ elementRefs.set(element.id, node.backendDOMNodeId);
267
+ elements.push(element);
268
+ addLine(`[${element.id}] ${text}`, element, "interactive");
269
+ renderedName = name;
270
+ }
271
+ } else if (role === "StaticText") {
272
+ if (name && name !== parentName) addStaticText(name);
273
+ } else if (role === "heading" || role === "image") {
274
+ if (name) addLine(`${role}: ${name}`, undefined, role);
275
+ renderedName = name || parentName;
276
+ }
277
+ }
278
+ for (const child of orderedChildren(node, nodesById, childrenByParent)) {
279
+ visit(child, renderedName);
280
+ }
281
+ };
282
+
283
+ for (const root of nodes.filter(
284
+ (node) => !node.parentId || !nodesById.has(node.parentId),
285
+ )) {
286
+ visit(root);
287
+ }
288
+ for (const node of nodes) visit(node);
289
+
290
+ return { lines, elements };
291
+ }