bidi-browser-mcp 0.1.9 → 0.2.0
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/LICENSE +21 -21
- package/README.md +398 -343
- package/dist/bin.js +3 -2
- package/dist/config.js +4 -0
- package/dist/connection/bidi-client.d.ts +13 -1
- package/dist/connection/bidi-client.js +59 -8
- package/dist/connection/browser-discovery.d.ts +20 -0
- package/dist/connection/browser-discovery.js +76 -12
- package/dist/connection/chromium-mapper.d.ts +9 -0
- package/dist/connection/chromium-mapper.js +24 -0
- package/dist/connection/event-pipeline.d.ts +15 -2
- package/dist/connection/event-pipeline.js +45 -3
- package/dist/connection/protocol-probe.d.ts +43 -0
- package/dist/connection/protocol-probe.js +112 -0
- package/dist/index.js +6 -0
- package/dist/session/session-manager.d.ts +26 -1
- package/dist/session/session-manager.js +262 -6
- package/dist/snapshot/cache.d.ts +4 -0
- package/dist/snapshot/cache.js +8 -0
- package/dist/snapshot/dom-snapshot.js +190 -181
- package/dist/snapshot/element-script.d.ts +23 -0
- package/dist/snapshot/element-script.js +70 -0
- package/dist/snapshot/token-optimizer.js +26 -8
- package/dist/snapshot/uid-verify.d.ts +43 -0
- package/dist/snapshot/uid-verify.js +154 -0
- package/dist/tools/browser.js +21 -6
- package/dist/tools/context.js +4 -6
- package/dist/tools/interact.d.ts +1 -0
- package/dist/tools/interact.js +593 -0
- package/dist/tools/network.d.ts +1 -0
- package/dist/tools/network.js +166 -0
- package/dist/tools/page.js +53 -2
- package/dist/tools/ping.js +5 -1
- package/dist/tools/script.d.ts +1 -0
- package/dist/tools/script.js +166 -0
- package/dist/types.d.ts +50 -1
- package/dist/utils/bidi-value.d.ts +10 -0
- package/dist/utils/bidi-value.js +56 -0
- package/dist/utils/errors.d.ts +3 -1
- package/dist/utils/errors.js +13 -7
- package/dist/utils/redact.d.ts +16 -0
- package/dist/utils/redact.js +47 -0
- package/package.json +86 -86
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
import { COMMON_PARAMS, defineTool, requireAction } from './base-tool.js';
|
|
2
|
+
import { ActionableError } from '../utils/errors.js';
|
|
3
|
+
import { unwrapBiDiValue } from '../utils/bidi-value.js';
|
|
4
|
+
import { elementScriptSource } from '../snapshot/element-script.js';
|
|
5
|
+
import { resolveElement, resolvePlan } from '../snapshot/element-resolver.js';
|
|
6
|
+
import { ok } from '../utils/result.js';
|
|
7
|
+
const ACTIONS = [
|
|
8
|
+
'click',
|
|
9
|
+
'type',
|
|
10
|
+
'clear',
|
|
11
|
+
'press',
|
|
12
|
+
'check',
|
|
13
|
+
'select',
|
|
14
|
+
'scroll',
|
|
15
|
+
'upload',
|
|
16
|
+
];
|
|
17
|
+
const INPUT_SCHEMA = {
|
|
18
|
+
type: 'object',
|
|
19
|
+
properties: {
|
|
20
|
+
action: {
|
|
21
|
+
type: 'string',
|
|
22
|
+
enum: [...ACTIONS],
|
|
23
|
+
description: 'click: click; type: type text; clear: clear a field; press: one key; check: toggle checkbox/radio; select: pick an option; scroll: scroll element/page; upload: set files on a file input',
|
|
24
|
+
},
|
|
25
|
+
uid: {
|
|
26
|
+
type: 'string',
|
|
27
|
+
description: 'Element uid from page.snapshot (never a raw CSS selector). Optional only for scroll without an element and for press into the focused element.',
|
|
28
|
+
},
|
|
29
|
+
value: {
|
|
30
|
+
type: 'string',
|
|
31
|
+
description: 'Text for type, key name for press (e.g. Enter), or comma-separated file paths for upload.',
|
|
32
|
+
},
|
|
33
|
+
option: {
|
|
34
|
+
type: 'string',
|
|
35
|
+
description: 'Option value, label, or index for select.',
|
|
36
|
+
},
|
|
37
|
+
checked: {
|
|
38
|
+
type: 'boolean',
|
|
39
|
+
description: 'Desired state for check (omitted means toggle).',
|
|
40
|
+
},
|
|
41
|
+
direction: {
|
|
42
|
+
type: 'string',
|
|
43
|
+
enum: ['up', 'down'],
|
|
44
|
+
description: 'Scroll direction when scrolling the page instead of an element.',
|
|
45
|
+
},
|
|
46
|
+
context: COMMON_PARAMS.context,
|
|
47
|
+
timeout: COMMON_PARAMS.timeout,
|
|
48
|
+
},
|
|
49
|
+
required: ['action'],
|
|
50
|
+
additionalProperties: false,
|
|
51
|
+
};
|
|
52
|
+
const OUTPUT_SCHEMA = {
|
|
53
|
+
type: 'object',
|
|
54
|
+
properties: {
|
|
55
|
+
ok: { type: 'boolean' },
|
|
56
|
+
action: { type: 'string' },
|
|
57
|
+
data: { type: ['object', 'null'] },
|
|
58
|
+
error: {
|
|
59
|
+
type: 'object',
|
|
60
|
+
properties: {
|
|
61
|
+
code: { type: 'string' },
|
|
62
|
+
message: { type: 'string' },
|
|
63
|
+
fix: { type: 'string' },
|
|
64
|
+
details: { type: 'object' },
|
|
65
|
+
},
|
|
66
|
+
required: ['code', 'message'],
|
|
67
|
+
},
|
|
68
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
69
|
+
},
|
|
70
|
+
required: ['ok', 'action'],
|
|
71
|
+
additionalProperties: false,
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* Probe for a click (decisions §4/§5): scroll in, measure, hit-test the
|
|
75
|
+
* element center, and describe whatever covers it. The coverer name drives
|
|
76
|
+
* NOT_INTERACTABLE; iframe/shadow crossings get boundary-specific fix text.
|
|
77
|
+
*/
|
|
78
|
+
const CLICK_PROBE_BODY = `(el, args, doc) => {
|
|
79
|
+
el.scrollIntoView({ block: 'nearest' });
|
|
80
|
+
const r = el.getBoundingClientRect();
|
|
81
|
+
const cx = r.x + r.width / 2;
|
|
82
|
+
const cy = r.y + r.height / 2;
|
|
83
|
+
let hit = null;
|
|
84
|
+
try { hit = doc.elementFromPoint(cx, cy); } catch (e) { hit = null; }
|
|
85
|
+
const chainHas = (target) => {
|
|
86
|
+
for (let n = el; n; n = n.parentNode || n.host || null) { if (n === target) return true; }
|
|
87
|
+
return false;
|
|
88
|
+
};
|
|
89
|
+
const inside = hit !== null && (chainHas(hit) || (el.contains ? el.contains(hit) : false));
|
|
90
|
+
let crossing = null;
|
|
91
|
+
if (hit !== null && !inside) {
|
|
92
|
+
const tag = String(hit.tagName || '').toLowerCase();
|
|
93
|
+
if (tag === 'iframe' || tag === 'frame' || tag === 'embed' || tag === 'object') {
|
|
94
|
+
crossing = 'iframe';
|
|
95
|
+
} else {
|
|
96
|
+
const rootOf = (node) => (node && node.getRootNode ? node.getRootNode() : doc);
|
|
97
|
+
crossing = rootOf(hit) === rootOf(el) ? null : 'shadow';
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
let coverer = null;
|
|
101
|
+
if (hit !== null && !inside) {
|
|
102
|
+
const id = hit.id ? '#' + hit.id : '';
|
|
103
|
+
const classes = String(hit.className || '').trim().split(/\\s+/).filter(Boolean).map((c) => '.' + c).join('');
|
|
104
|
+
coverer = String(hit.tagName || '?').toLowerCase() + id + classes;
|
|
105
|
+
}
|
|
106
|
+
return { rect: [r.x, r.y, r.width, r.height], coverer: coverer, crossing: crossing, hasHit: hit !== null };
|
|
107
|
+
}`;
|
|
108
|
+
const FOCUS_BODY = `(el) => {
|
|
109
|
+
el.focus();
|
|
110
|
+
// Typing appends at the caret; focus alone may land at position 0, so move
|
|
111
|
+
// the caret to the end for predictable appends.
|
|
112
|
+
if (el.setSelectionRange) { const n = (el.value ?? '').length; el.setSelectionRange(n, n); }
|
|
113
|
+
}`;
|
|
114
|
+
/** clear: the click comes first; this only re-anchors the selection. */
|
|
115
|
+
const SELECT_ALL_BODY = '(el) => { el.focus(); if (el.select) el.select(); }';
|
|
116
|
+
const READ_VALUE_BODY = `(el) => ({ value: 'value' in el && el.value !== undefined ? String(el.value) : String(el.textContent || '') })`;
|
|
117
|
+
const READ_CHECKED_BODY = `(el) => ({ checked: 'checked' in el ? Boolean(el.checked) : null })`;
|
|
118
|
+
const SCROLL_ELEMENT_BODY = `(el, args, doc) => {
|
|
119
|
+
el.scrollIntoView({ block: 'nearest', inline: 'nearest' });
|
|
120
|
+
const view = doc.defaultView;
|
|
121
|
+
return { x: view ? view.scrollX : 0, y: view ? view.scrollY : 0 };
|
|
122
|
+
}`;
|
|
123
|
+
/** select: exact value, then label, then numeric index (decisions §5). */
|
|
124
|
+
const SELECT_BODY = `(el, args) => {
|
|
125
|
+
if (!el.options) return null;
|
|
126
|
+
const list = [...el.options];
|
|
127
|
+
let found = list.find((o) => o.value === args.option);
|
|
128
|
+
if (!found) found = list.find((o) => o.text === args.option);
|
|
129
|
+
if (!found && /^[0-9]+$/.test(args.option)) found = list[Number(args.option)];
|
|
130
|
+
if (!found) return { missing: list.length };
|
|
131
|
+
el.value = found.value;
|
|
132
|
+
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
133
|
+
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
134
|
+
return { selected: found.value, label: found.text };
|
|
135
|
+
}`;
|
|
136
|
+
const RETURN_ELEMENT_BODY = '(el) => el';
|
|
137
|
+
/**
|
|
138
|
+
* BiDi key actions take a single code point — Firefox rejects named keys —
|
|
139
|
+
* so names map to the WebDriver private-use code points here (§5). The
|
|
140
|
+
* Chromium mapper normalizes names itself; Firefox is the reference family.
|
|
141
|
+
*/
|
|
142
|
+
const KEY_CODEPOINTS = {
|
|
143
|
+
Unidentified: '\uE000',
|
|
144
|
+
Cancel: '\uE001',
|
|
145
|
+
Help: '\uE002',
|
|
146
|
+
Backspace: '\uE003',
|
|
147
|
+
Tab: '\uE004',
|
|
148
|
+
Clear: '\uE005',
|
|
149
|
+
Return: '\uE006',
|
|
150
|
+
Enter: '\uE007',
|
|
151
|
+
Shift: '\uE008',
|
|
152
|
+
Control: '\uE009',
|
|
153
|
+
Alt: '\uE00A',
|
|
154
|
+
Pause: '\uE00B',
|
|
155
|
+
Escape: '\uE00C',
|
|
156
|
+
Space: ' ',
|
|
157
|
+
PageUp: '\uE00E',
|
|
158
|
+
PageDown: '\uE00F',
|
|
159
|
+
End: '\uE010',
|
|
160
|
+
Home: '\uE011',
|
|
161
|
+
ArrowLeft: '\uE012',
|
|
162
|
+
ArrowUp: '\uE013',
|
|
163
|
+
ArrowRight: '\uE014',
|
|
164
|
+
ArrowDown: '\uE015',
|
|
165
|
+
Insert: '\uE016',
|
|
166
|
+
Delete: '\uE017',
|
|
167
|
+
Meta: '\uE03D',
|
|
168
|
+
ZenkakuHankaku: '\uE040',
|
|
169
|
+
...Object.fromEntries(Array.from({ length: 12 }, (_, i) => [`F${i + 1}`, String.fromCharCode(0xe031 + i)])),
|
|
170
|
+
};
|
|
171
|
+
/** Names are validated client-side so the error can list what IS valid. */
|
|
172
|
+
function keyValueOf(name) {
|
|
173
|
+
if (name.length === 1) {
|
|
174
|
+
return name;
|
|
175
|
+
}
|
|
176
|
+
const mapped = KEY_CODEPOINTS[name];
|
|
177
|
+
if (mapped === undefined) {
|
|
178
|
+
throw new ActionableError('INVALID_ARGUMENT', `interact.press does not know the key "${name}".`, {
|
|
179
|
+
fix: `Use a single character or one of: ${Object.keys(KEY_CODEPOINTS).join(', ')}.`,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
return mapped;
|
|
183
|
+
}
|
|
184
|
+
const SCROLL_DELTA = 600;
|
|
185
|
+
function stringArg(args, key) {
|
|
186
|
+
const value = args[key];
|
|
187
|
+
return typeof value === 'string' && value !== '' ? value : undefined;
|
|
188
|
+
}
|
|
189
|
+
function requirePlan(element, uid) {
|
|
190
|
+
if (element === undefined) {
|
|
191
|
+
throw new ActionableError('INTERNAL_ERROR', `No element plan for uid ${uid}.`);
|
|
192
|
+
}
|
|
193
|
+
return resolvePlan(element);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Click with the full §4/§5 contract: probe (rect + hit-test), refuse when
|
|
197
|
+
* covered (NOT_INTERACTABLE, boundary-aware fix), then dispatch one
|
|
198
|
+
* pointerMove/Down/Up at the element center in the element's own context.
|
|
199
|
+
*/
|
|
200
|
+
async function clickElement(session, scriptContext, dispatchContext, plan) {
|
|
201
|
+
const outcome = await callOnElement(session, scriptContext, plan, CLICK_PROBE_BODY);
|
|
202
|
+
const probe = outcome.value;
|
|
203
|
+
if (probe === null || typeof probe !== 'object' || !Array.isArray(probe.rect)) {
|
|
204
|
+
throw new ActionableError('STALE_UID', 'The element changed while the click was prepared.', {
|
|
205
|
+
fix: 'Take a fresh page.snapshot and retry.',
|
|
206
|
+
details: { reason: outcome.value === null ? 'unparsable probe' : 'unexpected probe' },
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
const [x, y, width, height] = probe.rect;
|
|
210
|
+
if (width <= 0 || height <= 0) {
|
|
211
|
+
throw new ActionableError('NOT_INTERACTABLE', `Element has no size (${width}×${height}) and cannot be clicked.`, { fix: 'The element is hidden or collapsed; take a fresh page.snapshot and pick a visible target.' });
|
|
212
|
+
}
|
|
213
|
+
if (probe.coverer !== null) {
|
|
214
|
+
const fix = probe.crossing === 'iframe'
|
|
215
|
+
? 'The click point crosses an iframe boundary; the target is only reachable through its own frame. Take a fresh page.snapshot and act on the element inside the frame.'
|
|
216
|
+
: probe.crossing === 'shadow'
|
|
217
|
+
? 'The click point crosses a shadow/slot boundary; the covering element is not the one you see in the snapshot. Take a fresh page.snapshot and retry.'
|
|
218
|
+
: 'Dismiss or scroll the covering element away, then retry.';
|
|
219
|
+
throw new ActionableError('NOT_INTERACTABLE', `Element is covered by ${probe.coverer}.`, {
|
|
220
|
+
fix,
|
|
221
|
+
details: { coverer: probe.coverer, ...(probe.crossing === null ? {} : { crossing: probe.crossing }) },
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
if (!probe.hasHit) {
|
|
225
|
+
throw new ActionableError('NOT_INTERACTABLE', 'No element is hit at the target center.', {
|
|
226
|
+
fix: 'The element may be outside the visible viewport; scroll it into view and retry.',
|
|
227
|
+
details: { rect: probe.rect },
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
await performInput(session, dispatchContext, [
|
|
231
|
+
{
|
|
232
|
+
type: 'pointer',
|
|
233
|
+
id: 'interact-pointer',
|
|
234
|
+
parameters: { pointerType: 'mouse' },
|
|
235
|
+
actions: [
|
|
236
|
+
{ type: 'pointerMove', x: x + width / 2, y: y + height / 2, duration: 0 },
|
|
237
|
+
{ type: 'pointerDown', button: 0 },
|
|
238
|
+
{ type: 'pointerUp', button: 0 },
|
|
239
|
+
],
|
|
240
|
+
},
|
|
241
|
+
]);
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Dispatch input actions and always release afterwards: a failed dispatch
|
|
245
|
+
* must never leak a held pointer button or key (decisions §5).
|
|
246
|
+
*/
|
|
247
|
+
async function performInput(session, context, actions) {
|
|
248
|
+
try {
|
|
249
|
+
await session.request('input.performActions', { context, actions });
|
|
250
|
+
}
|
|
251
|
+
finally {
|
|
252
|
+
// releaseActions is a no-op when nothing is held; a failure here must not
|
|
253
|
+
// mask the original error, so it is deliberately contained.
|
|
254
|
+
await session.request('input.releaseActions', { context }).catch(() => undefined);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* The element's own browsing context, resolved through the frame chain
|
|
259
|
+
* (decisions §4): each iframe selector is matched against candidate child
|
|
260
|
+
* contexts via window.frameElement. Frameless plans dispatch in the top
|
|
261
|
+
* context. Cross-origin frames cannot resolve — but they cannot verify
|
|
262
|
+
* either, so dispatch is never reached for them.
|
|
263
|
+
*/
|
|
264
|
+
async function resolveDispatchContext(session, topContext, frame) {
|
|
265
|
+
if (frame === undefined || frame.length === 0) {
|
|
266
|
+
return topContext;
|
|
267
|
+
}
|
|
268
|
+
let current = topContext;
|
|
269
|
+
for (const selector of frame) {
|
|
270
|
+
const tree = await session.request('browsingContext.getTree', { root: current });
|
|
271
|
+
const children = directChildContexts(tree, current);
|
|
272
|
+
let next;
|
|
273
|
+
for (const child of children) {
|
|
274
|
+
const probe = await session.request('script.evaluate', {
|
|
275
|
+
expression: `(() => { try { return window.frameElement ? window.frameElement.matches(${JSON.stringify(selector)}) : false; } catch (e) { return false; } })()`,
|
|
276
|
+
awaitPromise: true,
|
|
277
|
+
target: { context: child },
|
|
278
|
+
});
|
|
279
|
+
if (unwrapBiDiValue(probe.result) === true) {
|
|
280
|
+
next = child;
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (next === undefined) {
|
|
285
|
+
throw new ActionableError('ELEMENT_NOT_FOUND', `Could not resolve the iframe (${selector}) that holds the element.`, {
|
|
286
|
+
fix: 'The frame may have navigated away; take a fresh page.snapshot and retry.',
|
|
287
|
+
details: { selector },
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
current = next;
|
|
291
|
+
}
|
|
292
|
+
return current;
|
|
293
|
+
}
|
|
294
|
+
function directChildContexts(tree, parent) {
|
|
295
|
+
const contexts = Array.isArray(tree.contexts) ? tree.contexts : [];
|
|
296
|
+
const root = contexts.find((node) => node !== null && typeof node === 'object' && node.context === parent);
|
|
297
|
+
const source = root ?? contexts[0];
|
|
298
|
+
if (source === null || typeof source !== 'object') {
|
|
299
|
+
return [];
|
|
300
|
+
}
|
|
301
|
+
const children = source.children;
|
|
302
|
+
if (!Array.isArray(children)) {
|
|
303
|
+
return [];
|
|
304
|
+
}
|
|
305
|
+
return children
|
|
306
|
+
.map((child) => (child !== null && typeof child === 'object' ? child.context : undefined))
|
|
307
|
+
.filter((context) => typeof context === 'string');
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Run a body against the element the plan resolves to, in the script
|
|
311
|
+
* context (the plan walks frames internally). Returns the body value, the
|
|
312
|
+
* viewport rect, and the element reference when the body handed the node back.
|
|
313
|
+
*/
|
|
314
|
+
async function callOnElement(session, context, plan, body, extraArgs) {
|
|
315
|
+
const declaration = elementScriptSource(plan, body, extraArgs);
|
|
316
|
+
const result = await session.request('script.callFunction', {
|
|
317
|
+
functionDeclaration: declaration,
|
|
318
|
+
awaitPromise: true,
|
|
319
|
+
// Root ownership: upload needs the element reference usable by
|
|
320
|
+
// input.setFiles; plain values are unaffected.
|
|
321
|
+
resultOwnership: 'root',
|
|
322
|
+
target: { context },
|
|
323
|
+
});
|
|
324
|
+
const record = unwrapBiDiValue(result.result);
|
|
325
|
+
if (record === null || typeof record !== 'object') {
|
|
326
|
+
throw new ActionableError('STALE_UID', 'The element could not be re-resolved for the action.', {
|
|
327
|
+
fix: 'Take a fresh page.snapshot and retry.',
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
if (typeof record.error === 'string' && record.error !== '') {
|
|
331
|
+
throw new ActionableError('STALE_UID', `The element moved on: ${record.error}.`, {
|
|
332
|
+
fix: 'Take a fresh page.snapshot and retry.',
|
|
333
|
+
details: { reason: record.error },
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
const rect = Array.isArray(record.rect) && record.rect.length === 4 ? record.rect : null;
|
|
337
|
+
return {
|
|
338
|
+
value: record.value ?? null,
|
|
339
|
+
rect,
|
|
340
|
+
...(record.element === undefined || record.element === null
|
|
341
|
+
? {}
|
|
342
|
+
: { element: record.element }),
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
function checkedOf(outcome) {
|
|
346
|
+
const value = outcome.value;
|
|
347
|
+
return value !== null && typeof value === 'object' && 'checked' in value
|
|
348
|
+
? value.checked
|
|
349
|
+
: null;
|
|
350
|
+
}
|
|
351
|
+
function valueOf(outcome) {
|
|
352
|
+
const value = outcome.value;
|
|
353
|
+
return value !== null && typeof value === 'object' && 'value' in value
|
|
354
|
+
? value.value
|
|
355
|
+
: null;
|
|
356
|
+
}
|
|
357
|
+
export const interactTool = defineTool({
|
|
358
|
+
name: 'interact',
|
|
359
|
+
title: 'Interact',
|
|
360
|
+
description: 'Act on page elements by snapshot uid: click, type, clear, press, check, select, scroll, upload. The uid is re-verified in the live page before anything is dispatched.',
|
|
361
|
+
toolset: 'core',
|
|
362
|
+
actions: ACTIONS,
|
|
363
|
+
inputSchema: INPUT_SCHEMA,
|
|
364
|
+
outputSchema: OUTPUT_SCHEMA,
|
|
365
|
+
annotations: {
|
|
366
|
+
readOnlyHint: false,
|
|
367
|
+
destructiveHint: true,
|
|
368
|
+
idempotentHint: false,
|
|
369
|
+
openWorldHint: false,
|
|
370
|
+
},
|
|
371
|
+
handler: async (args, ctx) => {
|
|
372
|
+
const action = requireAction(args, 'interact', ACTIONS);
|
|
373
|
+
const session = ctx.session;
|
|
374
|
+
const runtime = session?.runtime;
|
|
375
|
+
if (session === undefined || runtime === undefined) {
|
|
376
|
+
throw new ActionableError('CONNECTION_FAILED', 'No live browser session.', {
|
|
377
|
+
fix: 'Call browser.connect first.',
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
// scroll and press work without an element; everything else needs a uid.
|
|
381
|
+
const uid = stringArg(args, 'uid');
|
|
382
|
+
if (uid === undefined && action !== 'scroll' && action !== 'press') {
|
|
383
|
+
throw new ActionableError('INVALID_ARGUMENT', `interact.${action} requires uid.`, {
|
|
384
|
+
fix: 'Take a page.snapshot first, then pass the element uid.',
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
const context = await runtime.contexts.ensureContext(typeof args.context === 'string' ? args.context : undefined);
|
|
388
|
+
let element;
|
|
389
|
+
if (uid !== undefined) {
|
|
390
|
+
const snapshot = runtime.snapshots.get(context);
|
|
391
|
+
if (snapshot !== undefined) {
|
|
392
|
+
element = resolveElement(snapshot, uid);
|
|
393
|
+
}
|
|
394
|
+
else {
|
|
395
|
+
// The snapshot cache was invalidated by an earlier dispatch (§5), but
|
|
396
|
+
// the recorded plan still resolves the element and verification (§3)
|
|
397
|
+
// guards the dispatch — chained actions need no re-snapshot.
|
|
398
|
+
element = session.planFor(context, uid);
|
|
399
|
+
if (element === undefined) {
|
|
400
|
+
throw new ActionableError('UID_NOT_FOUND', `No snapshot for this context; uid ${uid} is not known to this session.`, {
|
|
401
|
+
fix: 'Call page.snapshot first to get current uids.',
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
// STALE_UID / ELEMENT_NOT_FOUND when the page moved on (decisions §3).
|
|
406
|
+
if (snapshot !== undefined) {
|
|
407
|
+
await session.verifyElement(snapshot, uid);
|
|
408
|
+
}
|
|
409
|
+
else {
|
|
410
|
+
await session.verifyElementPlan(element, context, uid);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
try {
|
|
414
|
+
switch (action) {
|
|
415
|
+
case 'click': {
|
|
416
|
+
const plan = requirePlan(element, uid);
|
|
417
|
+
const dispatchContext = await resolveDispatchContext(session, context, plan.frame);
|
|
418
|
+
await clickElement(session, context, dispatchContext, plan);
|
|
419
|
+
return ok(action, { uid });
|
|
420
|
+
}
|
|
421
|
+
case 'type': {
|
|
422
|
+
const text = stringArg(args, 'value');
|
|
423
|
+
if (text === undefined) {
|
|
424
|
+
throw new ActionableError('INVALID_ARGUMENT', 'interact.type requires value.', {
|
|
425
|
+
fix: 'Pass the text to type.',
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
const plan = requirePlan(element, uid);
|
|
429
|
+
const dispatchContext = await resolveDispatchContext(session, context, plan.frame);
|
|
430
|
+
await callOnElement(session, context, plan, FOCUS_BODY);
|
|
431
|
+
// Per-character key events in one performActions call: controlled
|
|
432
|
+
// components see real key input, and it is a single round trip (§5).
|
|
433
|
+
await performInput(session, dispatchContext, [
|
|
434
|
+
{
|
|
435
|
+
type: 'key',
|
|
436
|
+
id: 'interact-keyboard',
|
|
437
|
+
actions: [...text].flatMap((character) => [
|
|
438
|
+
{ type: 'keyDown', value: character },
|
|
439
|
+
{ type: 'keyUp', value: character },
|
|
440
|
+
]),
|
|
441
|
+
},
|
|
442
|
+
]);
|
|
443
|
+
const read = await callOnElement(session, context, plan, READ_VALUE_BODY);
|
|
444
|
+
return ok(action, { uid, value: valueOf(read) });
|
|
445
|
+
}
|
|
446
|
+
case 'clear': {
|
|
447
|
+
const plan = requirePlan(element, uid);
|
|
448
|
+
const dispatchContext = await resolveDispatchContext(session, context, plan.frame);
|
|
449
|
+
// Click, then select-all, then one Backspace: keyboard-only, so
|
|
450
|
+
// controlled components observe a real deletion event (§5).
|
|
451
|
+
await clickElement(session, context, dispatchContext, plan);
|
|
452
|
+
await callOnElement(session, context, plan, SELECT_ALL_BODY);
|
|
453
|
+
await performInput(session, dispatchContext, [
|
|
454
|
+
{
|
|
455
|
+
type: 'key',
|
|
456
|
+
id: 'interact-keyboard',
|
|
457
|
+
actions: [
|
|
458
|
+
{ type: 'keyDown', value: keyValueOf('Backspace') },
|
|
459
|
+
{ type: 'keyUp', value: keyValueOf('Backspace') },
|
|
460
|
+
],
|
|
461
|
+
},
|
|
462
|
+
]);
|
|
463
|
+
const read = await callOnElement(session, context, plan, READ_VALUE_BODY);
|
|
464
|
+
const finalValue = valueOf(read) ?? '';
|
|
465
|
+
return ok(action, { uid, value: finalValue, cleared: finalValue === '' });
|
|
466
|
+
}
|
|
467
|
+
case 'press': {
|
|
468
|
+
const key = stringArg(args, 'value');
|
|
469
|
+
if (key === undefined) {
|
|
470
|
+
throw new ActionableError('INVALID_ARGUMENT', 'interact.press requires value.', {
|
|
471
|
+
fix: `Pass a key name (${Object.keys(KEY_CODEPOINTS).slice(0, 8).join(', ')} …) or a single character, e.g. Enter.`,
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
// Press into whatever currently has focus; a uid (when given) was
|
|
475
|
+
// verified above but press does not move focus by itself (§5).
|
|
476
|
+
const keyValue = keyValueOf(key);
|
|
477
|
+
await performInput(session, context, [
|
|
478
|
+
{
|
|
479
|
+
type: 'key',
|
|
480
|
+
id: 'interact-keyboard',
|
|
481
|
+
actions: [
|
|
482
|
+
{ type: 'keyDown', value: keyValue },
|
|
483
|
+
{ type: 'keyUp', value: keyValue },
|
|
484
|
+
],
|
|
485
|
+
},
|
|
486
|
+
]);
|
|
487
|
+
return ok(action, { key, ...(uid === undefined ? {} : { uid }) });
|
|
488
|
+
}
|
|
489
|
+
case 'check': {
|
|
490
|
+
const plan = requirePlan(element, uid);
|
|
491
|
+
const before = checkedOf(await callOnElement(session, context, plan, READ_CHECKED_BODY));
|
|
492
|
+
if (before === null) {
|
|
493
|
+
throw new ActionableError('UNSUPPORTED', `interact.check needs a checkbox or radio; element ${uid} is not one.`, { fix: 'Pick a uid whose snapshot entry has the checkbox or radio role.' });
|
|
494
|
+
}
|
|
495
|
+
const desired = typeof args.checked === 'boolean' ? args.checked : undefined;
|
|
496
|
+
if (desired === undefined || before !== desired) {
|
|
497
|
+
// Toggle via a real click; the state is read fresh afterwards and
|
|
498
|
+
// never trusted from the cache (§5).
|
|
499
|
+
const dispatchContext = await resolveDispatchContext(session, context, plan.frame);
|
|
500
|
+
await clickElement(session, context, dispatchContext, plan);
|
|
501
|
+
}
|
|
502
|
+
const after = checkedOf(await callOnElement(session, context, plan, READ_CHECKED_BODY));
|
|
503
|
+
return ok(action, { uid, checked: after });
|
|
504
|
+
}
|
|
505
|
+
case 'select': {
|
|
506
|
+
const option = stringArg(args, 'option');
|
|
507
|
+
if (option === undefined) {
|
|
508
|
+
throw new ActionableError('INVALID_ARGUMENT', 'interact.select requires option.', {
|
|
509
|
+
fix: 'Pass the option value, label, or index.',
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
const plan = requirePlan(element, uid);
|
|
513
|
+
const outcome = await callOnElement(session, context, plan, SELECT_BODY, { option });
|
|
514
|
+
if (outcome.value === null) {
|
|
515
|
+
throw new ActionableError('UNSUPPORTED', `interact.select needs a <select>; element ${uid} is not one.`, { fix: 'Pick a uid whose snapshot entry has the combobox role.' });
|
|
516
|
+
}
|
|
517
|
+
const picked = outcome.value;
|
|
518
|
+
if (typeof picked.missing === 'number') {
|
|
519
|
+
throw new ActionableError('INVALID_ARGUMENT', `interact.select found no option matching "${option}" (${picked.missing} options available).`, { fix: 'Pass an exact option value, label, or index.' });
|
|
520
|
+
}
|
|
521
|
+
return ok(action, {
|
|
522
|
+
uid,
|
|
523
|
+
option: picked.selected ?? null,
|
|
524
|
+
...(picked.label === undefined ? {} : { label: picked.label }),
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
case 'scroll': {
|
|
528
|
+
if (uid !== undefined) {
|
|
529
|
+
const plan = requirePlan(element, uid);
|
|
530
|
+
const outcome = await callOnElement(session, context, plan, SCROLL_ELEMENT_BODY);
|
|
531
|
+
const position = (outcome.value ?? {});
|
|
532
|
+
return ok(action, { uid, x: position.x ?? null, y: position.y ?? null });
|
|
533
|
+
}
|
|
534
|
+
const direction = args.direction === 'up' ? 'up' : 'down';
|
|
535
|
+
const delta = direction === 'up' ? -SCROLL_DELTA : SCROLL_DELTA;
|
|
536
|
+
// Page scroll rides a wheel source (§5), like a user's wheel.
|
|
537
|
+
await performInput(session, context, [
|
|
538
|
+
{
|
|
539
|
+
type: 'wheel',
|
|
540
|
+
id: 'interact-wheel',
|
|
541
|
+
actions: [{ type: 'scroll', x: 0, y: 0, deltaX: 0, deltaY: delta }],
|
|
542
|
+
},
|
|
543
|
+
]);
|
|
544
|
+
const position = await session.request('script.evaluate', {
|
|
545
|
+
expression: '({ x: window.scrollX, y: window.scrollY })',
|
|
546
|
+
awaitPromise: true,
|
|
547
|
+
target: { context },
|
|
548
|
+
});
|
|
549
|
+
const at = (unwrapBiDiValue(position.result) ?? {});
|
|
550
|
+
return ok(action, { direction, x: at.x ?? null, y: at.y ?? null });
|
|
551
|
+
}
|
|
552
|
+
case 'upload': {
|
|
553
|
+
const raw = stringArg(args, 'value');
|
|
554
|
+
if (raw === undefined) {
|
|
555
|
+
throw new ActionableError('INVALID_ARGUMENT', 'interact.upload requires value.', {
|
|
556
|
+
fix: 'Pass one or more absolute file paths, comma-separated.',
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
const files = raw.split(',').map((file) => file.trim()).filter((file) => file !== '');
|
|
560
|
+
if (files.length === 0) {
|
|
561
|
+
throw new ActionableError('INVALID_ARGUMENT', 'interact.upload needs at least one file.', {
|
|
562
|
+
fix: 'Pass at least one absolute file path.',
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
const plan = requirePlan(element, uid);
|
|
566
|
+
const dispatchContext = await resolveDispatchContext(session, context, plan.frame);
|
|
567
|
+
const outcome = await callOnElement(session, context, plan, RETURN_ELEMENT_BODY);
|
|
568
|
+
const sharedId = outcome.element?.sharedId;
|
|
569
|
+
if (typeof sharedId !== 'string' || sharedId === '') {
|
|
570
|
+
throw new ActionableError('SESSION_FAILED', 'The browser did not hand back an element reference for input.setFiles.', { fix: 'Retry once; if it persists, take a fresh page.snapshot and retry.' });
|
|
571
|
+
}
|
|
572
|
+
await session.request('input.setFiles', {
|
|
573
|
+
context: dispatchContext,
|
|
574
|
+
element: { sharedId },
|
|
575
|
+
files,
|
|
576
|
+
});
|
|
577
|
+
return ok(action, { uid, files: files.length });
|
|
578
|
+
}
|
|
579
|
+
default:
|
|
580
|
+
throw new ActionableError('INVALID_ACTION', `Unknown interact action: ${action}.`);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
finally {
|
|
584
|
+
// Any dispatched action (or failed attempt) may have changed the page:
|
|
585
|
+
// drop the cache entry so the next page.snapshot reflects post-action
|
|
586
|
+
// state. Scrolling keeps document-space bounds valid, so it is exempt.
|
|
587
|
+
if (action !== 'scroll') {
|
|
588
|
+
runtime.snapshots.invalidate(context);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
},
|
|
592
|
+
});
|
|
593
|
+
//# sourceMappingURL=interact.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const networkTool: import("../types.js").ToolDefinition;
|