@howaboua/pi-browser 0.0.3 → 0.0.5

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 (61) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +4 -0
  3. package/dist/index.js +2 -2
  4. package/dist/remote-worker.js +1026 -176
  5. package/dist/src/browser/bounds.d.ts +1 -1
  6. package/dist/src/browser/bounds.js +13 -4
  7. package/dist/src/browser/help.js +11 -6
  8. package/dist/src/browser/operation-executor.js +15 -1
  9. package/dist/src/browser/operation.d.ts +25 -2
  10. package/dist/src/browser/operation.js +5 -0
  11. package/dist/src/browser/parse-operation.js +61 -2
  12. package/dist/src/browser/remote.d.ts +1 -1
  13. package/dist/src/browser/remote.js +2 -2
  14. package/dist/src/browser/runtime.d.ts +8 -3
  15. package/dist/src/browser/runtime.js +91 -25
  16. package/dist/src/browser/worker-server.js +12 -6
  17. package/dist/src/browser-parameters.d.ts +10 -0
  18. package/dist/src/browser-parameters.js +34 -5
  19. package/dist/src/browser-tool.d.ts +10 -0
  20. package/dist/src/browser-tool.js +2 -1
  21. package/dist/src/cdp/actions/click.d.ts +2 -0
  22. package/dist/src/cdp/actions/click.js +1 -1
  23. package/dist/src/cdp/actions/element.js +4 -0
  24. package/dist/src/cdp/actions/fill.d.ts +8 -0
  25. package/dist/src/cdp/actions/fill.js +175 -0
  26. package/dist/src/cdp/actions/key.d.ts +20 -0
  27. package/dist/src/cdp/actions/key.js +166 -0
  28. package/dist/src/cdp/actions/wait.d.ts +9 -0
  29. package/dist/src/cdp/actions/wait.js +95 -0
  30. package/dist/src/cdp/pages.d.ts +2 -1
  31. package/dist/src/cdp/pages.js +8 -4
  32. package/dist/src/cdp/session.d.ts +7 -1
  33. package/dist/src/cdp/session.js +79 -27
  34. package/dist/src/cdp/snapshot-contract.d.ts +6 -0
  35. package/dist/src/cdp/snapshot.js +72 -11
  36. package/dist/src/cdp/tabs.d.ts +32 -0
  37. package/dist/src/cdp/tabs.js +226 -0
  38. package/dist/src/cdp/types.d.ts +2 -0
  39. package/index.ts +2 -2
  40. package/package.json +5 -5
  41. package/src/browser/bounds.ts +14 -3
  42. package/src/browser/help.ts +12 -6
  43. package/src/browser/operation-executor.ts +34 -0
  44. package/src/browser/operation.ts +19 -1
  45. package/src/browser/parse-operation.ts +63 -2
  46. package/src/browser/remote.ts +2 -1
  47. package/src/browser/runtime.ts +115 -26
  48. package/src/browser/worker-server.ts +24 -7
  49. package/src/browser-parameters.ts +131 -96
  50. package/src/browser-tool.ts +2 -1
  51. package/src/cdp/actions/click.ts +1 -1
  52. package/src/cdp/actions/element.ts +4 -0
  53. package/src/cdp/actions/fill.ts +246 -0
  54. package/src/cdp/actions/key.ts +202 -0
  55. package/src/cdp/actions/wait.ts +117 -0
  56. package/src/cdp/pages.ts +9 -6
  57. package/src/cdp/session.ts +98 -46
  58. package/src/cdp/snapshot-contract.ts +6 -0
  59. package/src/cdp/snapshot.ts +92 -17
  60. package/src/cdp/tabs.ts +292 -0
  61. package/src/cdp/types.ts +2 -0
@@ -5,114 +5,149 @@ export function browserParameters(hosts: readonly string[]) {
5
5
  const route: Record<string, TSchema> =
6
6
  hosts.length > 0
7
7
  ? {
8
- host: Type.Optional(
9
- StringEnum(hosts, { description: "Configured browser host" }),
10
- ),
8
+ host: Type.Optional(StringEnum(hosts)),
11
9
  }
12
10
  : {};
13
11
  const request = (properties: Record<string, TSchema>) =>
14
12
  Type.Object({ ...route, ...properties }, { additionalProperties: false });
15
13
  const refId = Type.String({
16
14
  minLength: 1,
17
- description: "Tab ref_id returned by tabs",
18
15
  });
19
16
  const elementId = Type.Integer({
20
17
  minimum: 1,
21
- description: "Element id returned by open or find",
22
18
  });
23
19
  const responseLength = StringEnum(["short", "medium", "long"] as const);
24
20
  const handle = Type.String({
25
21
  minLength: 1,
26
- description: "Continuation handle returned by browser",
27
22
  });
28
- return Type.Union([
29
- request({ action: StringEnum(["help", "start"] as const) }),
30
- request({
31
- action: Type.Literal("tabs"),
32
- query: Type.Optional(Type.String({ minLength: 1 })),
33
- offset: Type.Optional(Type.Integer({ minimum: 0 })),
34
- }),
35
- request({
36
- action: Type.Literal("open"),
37
- ref_id: refId,
38
- lineno: Type.Optional(Type.Integer({ minimum: 1 })),
39
- response_length: Type.Optional(responseLength),
40
- }),
41
- request({
42
- action: Type.Literal("open"),
43
- url: Type.String({ minLength: 1 }),
44
- }),
45
- request({
46
- action: Type.Literal("find"),
47
- ref_id: refId,
48
- pattern: Type.String({ minLength: 1 }),
49
- lineno: Type.Optional(Type.Integer({ minimum: 1 })),
50
- response_length: Type.Optional(responseLength),
51
- }),
52
- request({ action: Type.Literal("click"), ref_id: refId, id: elementId }),
53
- request({
54
- action: Type.Literal("click"),
55
- ref_id: refId,
56
- selector: Type.String({ minLength: 1 }),
57
- }),
58
- request({
59
- action: Type.Literal("click"),
60
- ref_id: refId,
61
- x: Type.Number(),
62
- y: Type.Number(),
63
- }),
64
- request({
65
- action: Type.Literal("type"),
66
- ref_id: refId,
67
- id: Type.Optional(elementId),
68
- text: Type.String({ minLength: 1 }),
69
- }),
70
- request({
71
- action: StringEnum(["screenshot", "html"] as const),
72
- ref_id: refId,
73
- }),
74
- request({
75
- action: StringEnum(["screenshot", "html"] as const),
76
- ref_id: refId,
77
- id: elementId,
78
- }),
79
- request({
80
- action: StringEnum(["screenshot", "html"] as const),
81
- ref_id: refId,
82
- selector: Type.String({ minLength: 1 }),
83
- }),
84
- request({
85
- action: Type.Literal("navigate"),
86
- ref_id: refId,
87
- url: Type.String({ minLength: 1 }),
88
- }),
89
- request({
90
- action: Type.Literal("evaluate"),
91
- ref_id: refId,
92
- expression: Type.String({ minLength: 1 }),
93
- }),
94
- request({ action: Type.Literal("network"), ref_id: refId }),
95
- request({
96
- action: Type.Literal("load_all"),
97
- ref_id: refId,
98
- selector: Type.String({ minLength: 1 }),
99
- interval_ms: Type.Optional(Type.Integer({ minimum: 0, maximum: 60_000 })),
100
- }),
101
- request({
102
- action: Type.Literal("raw"),
103
- ref_id: refId,
104
- method: Type.String({ minLength: 1 }),
105
- params: Type.Optional(Type.Object({}, { additionalProperties: true })),
106
- }),
107
- request({
108
- action: Type.Literal("read_result"),
109
- handle,
110
- offset: Type.Optional(Type.Integer({ minimum: 0 })),
111
- }),
112
- request({ action: Type.Literal("discard_result"), handle }),
113
- request({
114
- action: Type.Literal("stop"),
115
- ref_id: Type.Optional(refId),
116
- }),
117
- ]);
23
+ const fillValue = Type.Union([Type.String(), Type.Boolean()]);
24
+ const timeout = Type.Optional(Type.Integer({ minimum: 1, maximum: 60_000 }));
25
+ return Type.Union(
26
+ [
27
+ request({ action: StringEnum(["help", "start"] as const) }),
28
+ request({
29
+ action: Type.Literal("tabs"),
30
+ query: Type.Optional(Type.String({ minLength: 1 })),
31
+ offset: Type.Optional(Type.Integer({ minimum: 0 })),
32
+ owned_only: Type.Optional(Type.Boolean()),
33
+ }),
34
+ request({
35
+ action: Type.Literal("open"),
36
+ ref_id: refId,
37
+ lineno: Type.Optional(Type.Integer({ minimum: 1 })),
38
+ response_length: Type.Optional(responseLength),
39
+ }),
40
+ request({
41
+ action: Type.Literal("open"),
42
+ url: Type.String({ minLength: 1 }),
43
+ }),
44
+ request({
45
+ action: Type.Literal("find"),
46
+ ref_id: refId,
47
+ pattern: Type.String({ minLength: 1 }),
48
+ lineno: Type.Optional(Type.Integer({ minimum: 1 })),
49
+ response_length: Type.Optional(responseLength),
50
+ }),
51
+ request({
52
+ action: StringEnum(["show", "close"] as const),
53
+ ref_id: refId,
54
+ }),
55
+ request({ action: Type.Literal("click"), ref_id: refId, id: elementId }),
56
+ request({
57
+ action: Type.Literal("click"),
58
+ ref_id: refId,
59
+ selector: Type.String({ minLength: 1 }),
60
+ }),
61
+ request({
62
+ action: Type.Literal("click"),
63
+ ref_id: refId,
64
+ x: Type.Number(),
65
+ y: Type.Number(),
66
+ }),
67
+ request({
68
+ action: Type.Literal("type"),
69
+ ref_id: refId,
70
+ id: Type.Optional(elementId),
71
+ text: Type.String({ minLength: 1 }),
72
+ }),
73
+ request({
74
+ action: Type.Literal("fill"),
75
+ ref_id: refId,
76
+ id: elementId,
77
+ value: fillValue,
78
+ }),
79
+ request({
80
+ action: Type.Literal("fill"),
81
+ ref_id: refId,
82
+ selector: Type.String({ minLength: 1 }),
83
+ value: fillValue,
84
+ }),
85
+ request({
86
+ action: Type.Literal("press"),
87
+ ref_id: refId,
88
+ key: Type.String({ minLength: 1 }),
89
+ }),
90
+ ...(["selector", "text", "url_includes"] as const).map((condition) =>
91
+ request({
92
+ action: Type.Literal("wait"),
93
+ ref_id: refId,
94
+ [condition]: Type.String({ minLength: 1 }),
95
+ timeout_ms: timeout,
96
+ }),
97
+ ),
98
+ request({
99
+ action: StringEnum(["screenshot", "html"] as const),
100
+ ref_id: refId,
101
+ }),
102
+ request({
103
+ action: StringEnum(["screenshot", "html"] as const),
104
+ ref_id: refId,
105
+ id: elementId,
106
+ }),
107
+ request({
108
+ action: StringEnum(["screenshot", "html"] as const),
109
+ ref_id: refId,
110
+ selector: Type.String({ minLength: 1 }),
111
+ }),
112
+ request({
113
+ action: Type.Literal("navigate"),
114
+ ref_id: refId,
115
+ url: Type.String({ minLength: 1 }),
116
+ }),
117
+ request({
118
+ action: Type.Literal("evaluate"),
119
+ ref_id: refId,
120
+ expression: Type.String({ minLength: 1 }),
121
+ }),
122
+ request({ action: Type.Literal("network"), ref_id: refId }),
123
+ request({
124
+ action: Type.Literal("load_all"),
125
+ ref_id: refId,
126
+ selector: Type.String({ minLength: 1 }),
127
+ interval_ms: Type.Optional(
128
+ Type.Integer({ minimum: 0, maximum: 60_000 }),
129
+ ),
130
+ }),
131
+ request({
132
+ action: Type.Literal("raw"),
133
+ ref_id: refId,
134
+ method: Type.String({ minLength: 1 }),
135
+ params: Type.Optional(Type.Object({}, { additionalProperties: true })),
136
+ }),
137
+ request({
138
+ action: Type.Literal("read_result"),
139
+ handle,
140
+ offset: Type.Optional(Type.Integer({ minimum: 0 })),
141
+ }),
142
+ request({ action: Type.Literal("discard_result"), handle }),
143
+ request({
144
+ action: Type.Literal("stop"),
145
+ ref_id: Type.Optional(refId),
146
+ }),
147
+ ],
148
+ {
149
+ description:
150
+ "ref_id: tab from tabs; id: element from open/find; handle: continuation from browser; fill value: replacement text/option or checkbox/radio boolean",
151
+ },
152
+ );
118
153
  }
@@ -45,8 +45,9 @@ export function createBrowserTool(runtime: BrowserRuntime) {
45
45
  label: "Browser",
46
46
  description: "Control logged-in browser; call help before other actions",
47
47
  parameters,
48
- async execute(_toolCallId, input, signal, onUpdate) {
48
+ async execute(_toolCallId, input, signal, onUpdate, ctx) {
49
49
  const result = await runtime.execute(browserRequest(input), {
50
+ ownerId: ctx.sessionManager.getSessionId(),
50
51
  signal: signal ?? new AbortController().signal,
51
52
  onOperation(operation, index, total) {
52
53
  onUpdate?.({
@@ -55,7 +55,7 @@ async function pressAndRelease(
55
55
  }
56
56
  }
57
57
 
58
- async function clickBackendNode(
58
+ export async function clickBackendNode(
59
59
  cdp: CdpConnection,
60
60
  sessionId: string,
61
61
  backendNodeId: number,
@@ -117,6 +117,10 @@ export async function backendCenter(
117
117
  {
118
118
  objectId,
119
119
  functionDeclaration: `function() {
120
+ const view = this.ownerDocument.defaultView;
121
+ if (view && (view.innerWidth <= 0 || view.innerHeight <= 0)) {
122
+ return { ok: false, error: 'Browser viewport is ' + view.innerWidth + 'x' + view.innerHeight + '; restore or resize its window, then retry' };
123
+ }
120
124
  const rect = this.getBoundingClientRect();
121
125
  const style = getComputedStyle(this);
122
126
  const disabled = this.matches(':disabled') ||
@@ -0,0 +1,246 @@
1
+ import type { CdpConnection, ElementRefs } from "../types.js";
2
+ import { asRecord } from "../types.js";
3
+ import { clickBackendNode } from "./click.js";
4
+ import {
5
+ backendCenter,
6
+ requireElementRef,
7
+ withBackendObject,
8
+ } from "./element.js";
9
+ import { pressKey } from "./key.js";
10
+ import { selectorBackendNode } from "./selector.js";
11
+
12
+ // Runs in the element's realm. Native setters bypass framework value trackers;
13
+ // input/change events notify controlled form components of the replacement.
14
+ function prepareFill(this: HTMLElement, value: string | boolean) {
15
+ if (!this.isConnected) throw new Error("Element detached; run open again");
16
+ if (
17
+ this.matches(":disabled") ||
18
+ this.getAttribute("aria-disabled") === "true" ||
19
+ this.closest("[inert]")
20
+ ) {
21
+ throw new Error("Element is disabled or inert");
22
+ }
23
+ const input = this instanceof HTMLInputElement;
24
+ const textarea = this instanceof HTMLTextAreaElement;
25
+ const select = this instanceof HTMLSelectElement;
26
+ if ((input || textarea) && this.readOnly)
27
+ throw new Error("Element is read-only");
28
+ const toggle = input && (this.type === "checkbox" || this.type === "radio");
29
+ if (toggle) {
30
+ if (typeof value !== "boolean")
31
+ throw new Error("Checkbox/radio requires a boolean value");
32
+ if (this.type === "radio" && !value && this.checked) {
33
+ throw new Error(
34
+ "Select another radio option with value true instead of unchecking this one",
35
+ );
36
+ }
37
+ const indeterminate = this.type === "checkbox" && this.indeterminate;
38
+ if (indeterminate && this.checked === value) {
39
+ const setter = Object.getOwnPropertyDescriptor(
40
+ HTMLInputElement.prototype,
41
+ "checked",
42
+ )?.set;
43
+ if (!setter) throw new Error("Checkbox has no native checked setter");
44
+ // A click clears indeterminate and toggles checked. Start from the
45
+ // opposite state so that single click lands on the requested value.
46
+ setter.call(this, !value);
47
+ }
48
+ return {
49
+ kind: "checked",
50
+ expected: value,
51
+ needsClick: this.checked !== value || indeterminate,
52
+ };
53
+ }
54
+ if (typeof value !== "string")
55
+ throw new Error("Text fields and selects require a string value");
56
+ if (
57
+ input &&
58
+ ![
59
+ "text",
60
+ "search",
61
+ "email",
62
+ "url",
63
+ "tel",
64
+ "password",
65
+ "number",
66
+ "date",
67
+ "time",
68
+ "datetime-local",
69
+ "month",
70
+ "week",
71
+ ].includes(this.type)
72
+ ) {
73
+ throw new Error(`Input type ${this.type} does not support fill`);
74
+ }
75
+ if (!input && !textarea && !select && !this.isContentEditable) {
76
+ throw new Error("Element is not an editable form control");
77
+ }
78
+ let replacement = value;
79
+ if (select) {
80
+ if (this.multiple) throw new Error("fill requires a single-select control");
81
+ const options = Array.from(this.options);
82
+ const byValue = options.filter((option) => option.value === value);
83
+ const matches = byValue.length
84
+ ? byValue
85
+ : options.filter((option) => option.label.trim() === value);
86
+ const option = matches[0];
87
+ if (matches.length !== 1 || !option)
88
+ throw new Error("Option value/label must match exactly one option");
89
+ if (option.matches(":disabled")) throw new Error("Option is disabled");
90
+ replacement = option.value;
91
+ }
92
+ this.focus({ preventScroll: true });
93
+ const root = this.getRootNode() as Document | ShadowRoot;
94
+ if (!this.isConnected || root.activeElement !== this) {
95
+ throw new Error("Could not focus element; fill was not sent");
96
+ }
97
+ if (!input && !textarea && !select) {
98
+ const selection = this.ownerDocument.getSelection();
99
+ if (!selection) throw new Error("Could not select editable text");
100
+ const range = this.ownerDocument.createRange();
101
+ range.selectNodeContents(this);
102
+ selection.removeAllRanges();
103
+ selection.addRange(range);
104
+ return { kind: "contenteditable", expected: value };
105
+ }
106
+ const prototype = input
107
+ ? HTMLInputElement.prototype
108
+ : textarea
109
+ ? HTMLTextAreaElement.prototype
110
+ : HTMLSelectElement.prototype;
111
+ const setter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
112
+ if (!setter) throw new Error("Form control has no native value setter");
113
+ if (input || textarea) {
114
+ const probe = this.cloneNode(false) as
115
+ | HTMLInputElement
116
+ | HTMLTextAreaElement;
117
+ setter.call(probe, replacement);
118
+ if (probe.value !== replacement)
119
+ throw new Error(
120
+ "Value is not accepted by this control; fill was not sent",
121
+ );
122
+ }
123
+ setter.call(this, replacement);
124
+ this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
125
+ this.dispatchEvent(new Event("change", { bubbles: true }));
126
+ return { kind: "value", expected: replacement };
127
+ }
128
+
129
+ async function callElement(
130
+ cdp: CdpConnection,
131
+ sessionId: string,
132
+ objectId: string,
133
+ declaration: string,
134
+ value: unknown,
135
+ signal?: AbortSignal,
136
+ ): Promise<Record<string, unknown>> {
137
+ const response = asRecord(
138
+ await cdp.send(
139
+ "Runtime.callFunctionOn",
140
+ {
141
+ objectId,
142
+ functionDeclaration: declaration,
143
+ arguments: [{ value }],
144
+ returnByValue: true,
145
+ },
146
+ sessionId,
147
+ signal,
148
+ ),
149
+ );
150
+ if (response["exceptionDetails"]) {
151
+ const details = asRecord(response["exceptionDetails"]);
152
+ const exception = details["exception"]
153
+ ? asRecord(details["exception"])
154
+ : {};
155
+ throw new Error(
156
+ typeof exception["description"] === "string"
157
+ ? exception["description"]
158
+ : "Fill failed; run open to inspect the control before retrying",
159
+ );
160
+ }
161
+ return asRecord(asRecord(response["result"])["value"], "fill result");
162
+ }
163
+
164
+ export async function fillElement(
165
+ cdp: CdpConnection,
166
+ sessionId: string,
167
+ elementRefs: ElementRefs,
168
+ target: { id: number; selector?: never } | { selector: string; id?: never },
169
+ value: string | boolean,
170
+ signal?: AbortSignal,
171
+ ): Promise<string> {
172
+ const backendNodeId =
173
+ target.id !== undefined
174
+ ? requireElementRef(elementRefs, target.id).backendNodeId
175
+ : await selectorBackendNode(cdp, sessionId, target.selector, signal);
176
+ await backendCenter(cdp, sessionId, backendNodeId, true, signal);
177
+ return withBackendObject(
178
+ cdp,
179
+ sessionId,
180
+ backendNodeId,
181
+ async (objectId) => {
182
+ const prepared = await callElement(
183
+ cdp,
184
+ sessionId,
185
+ objectId,
186
+ prepareFill.toString(),
187
+ value,
188
+ signal,
189
+ );
190
+ if (prepared["kind"] === "checked" && prepared["needsClick"] === true) {
191
+ await clickBackendNode(cdp, sessionId, backendNodeId, signal);
192
+ } else if (prepared["kind"] === "contenteditable") {
193
+ const focused = await callElement(
194
+ cdp,
195
+ sessionId,
196
+ objectId,
197
+ `function() {
198
+ const selection = this.ownerDocument.getSelection();
199
+ return { ok: this.isConnected && this.getRootNode().activeElement === this &&
200
+ selection && this.contains(selection.anchorNode) && this.contains(selection.focusNode) };
201
+ }`,
202
+ null,
203
+ signal,
204
+ );
205
+ if (focused["ok"] !== true)
206
+ throw new Error("Focus or selection changed; fill was not sent");
207
+ if (value === "") await pressKey(cdp, sessionId, "Backspace", signal);
208
+ else
209
+ await cdp.send(
210
+ "Input.insertText",
211
+ { text: value },
212
+ sessionId,
213
+ signal,
214
+ );
215
+ }
216
+ const verified = await callElement(
217
+ cdp,
218
+ sessionId,
219
+ objectId,
220
+ `function(expected) {
221
+ if (!this.isConnected) return { ok: false };
222
+ const toggle = this instanceof HTMLInputElement && (this.type === 'checkbox' || this.type === 'radio');
223
+ // Editable DOM has no value property. Native editing introduces NBSPs
224
+ // and block/BR nodes, so compare equivalent rendered text, not markup.
225
+ if (this.isContentEditable) {
226
+ const normalize = text => text.replace(/\\s+/g, ' ').trim();
227
+ return { ok: normalize(this.innerText) === normalize(expected) };
228
+ }
229
+ const actual = toggle ? this.checked : this.value;
230
+ return { ok: actual === expected && (!toggle || !this.indeterminate) };
231
+ }`,
232
+ prepared["expected"],
233
+ signal,
234
+ );
235
+ if (verified["ok"] !== true) {
236
+ throw new Error(
237
+ "Fill did not retain the requested value; run open to inspect the control before retrying",
238
+ );
239
+ }
240
+ return target.id === undefined
241
+ ? "Filled selected element"
242
+ : `Filled element ${target.id}`;
243
+ },
244
+ signal,
245
+ );
246
+ }