codex-browser-use 0.0.0-stage → 4.8.2

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/src/ax-tree.js ADDED
@@ -0,0 +1,889 @@
1
+ const TEXT_PRUNABLE_PARENT_ROLES = new Set([
2
+ "button", "link", "tab", "menuitem", "menuitemcheckbox", "menuitemradio",
3
+ "option", "heading", "checkbox", "radio", "switch", "treeitem", "label",
4
+ "RadioButton", "ToggleButton",
5
+ ]);
6
+
7
+ const STATEFUL_PROPERTIES = new Set([
8
+ "checked", "disabled", "editable", "expanded", "focused", "haspopup",
9
+ "invalid", "modal", "multiselectable", "pressed", "readonly", "required",
10
+ "selected",
11
+ ]);
12
+
13
+ const INTERACTIVE_ROLES = new Set([
14
+ "button", "link", "textbox", "searchbox", "combobox", "checkbox",
15
+ "radio", "switch", "slider", "spinbutton", "tab", "menuitem",
16
+ "menuitemcheckbox", "menuitemradio", "option", "treeitem",
17
+ "RadioButton", "ToggleButton",
18
+ ]);
19
+
20
+ const STRUCTURAL_LANDMARK_ROLES = new Set([
21
+ "heading", "main", "navigation", "dialog", "alert", "alertdialog",
22
+ "form", "region",
23
+ ]);
24
+
25
+ const COLLAPSIBLE_ITEM_ROLES = new Set([
26
+ "listitem", "row", "option", "treeitem",
27
+ ]);
28
+
29
+ /**
30
+ * Determine whether a node carries focused, editable, valued, selected, or checked state.
31
+ * @param {string} value
32
+ * @param {Map<string, unknown>} propMap
33
+ * @returns {boolean}
34
+ */
35
+ function hasInteractiveState(value, propMap) {
36
+ if (value) return true;
37
+ if (propMap.get("focused") === true) return true;
38
+ if (propMap.get("editable") === true) return true;
39
+ if (propMap.get("selected") === true) return true;
40
+ const checked = propMap.get("checked");
41
+ if (checked === true || (typeof checked === "string" && checked !== "false")) return true;
42
+ return false;
43
+ }
44
+
45
+ /**
46
+ * Precompute subtree interactivity flags so landmarks can be kept iff they contain
47
+ * interactive descendants.
48
+ * @param {Array<Record<string, any>>} roots
49
+ * @param {Map<string, Record<string, any>>} byId
50
+ * @param {Map<string, Array<Record<string, any>>>} children
51
+ * @param {(node: Record<string, any>, role: string, name: string, value: string) => boolean} isTransparentFn
52
+ * @param {number} maxTextLength
53
+ * @returns {Map<string, {directlyInteractive:boolean, hasInteractiveDescendant:boolean}>}
54
+ */
55
+ function computeInteractiveMetadata(roots, byId, children, isTransparentFn, maxTextLength) {
56
+ const meta = new Map();
57
+ const visiting = new Set();
58
+
59
+ const analyze = (node) => {
60
+ if (!node || typeof node.nodeId !== "string") {
61
+ return { directlyInteractive: false, hasInteractiveDescendant: false };
62
+ }
63
+ const existing = meta.get(node.nodeId);
64
+ if (existing) return existing;
65
+ if (visiting.has(node.nodeId)) {
66
+ return { directlyInteractive: false, hasInteractiveDescendant: false };
67
+ }
68
+ visiting.add(node.nodeId);
69
+
70
+ const role = node.role?.value ?? "unknown";
71
+ const name = truncateText(normalizeText(node.name?.value), maxTextLength);
72
+ const value = truncateText(normalizeText(node.value?.value), maxTextLength);
73
+ const propMap = readPropertyMap(node.properties);
74
+ const transparent = isTransparentFn(node, role, name, value);
75
+ const directlyInteractive = !transparent && (
76
+ INTERACTIVE_ROLES.has(role) || hasInteractiveState(value, propMap)
77
+ );
78
+
79
+ const ordered = Array.isArray(node.childIds) && node.childIds.length > 0
80
+ ? node.childIds.map((id) => byId.get(id)).filter(Boolean)
81
+ : children.get(node.nodeId) ?? [];
82
+ let hasInteractiveDescendant = false;
83
+ for (const child of ordered) {
84
+ const childInfo = analyze(child);
85
+ if (childInfo.directlyInteractive || childInfo.hasInteractiveDescendant) {
86
+ hasInteractiveDescendant = true;
87
+ }
88
+ }
89
+
90
+ visiting.delete(node.nodeId);
91
+ const info = { directlyInteractive, hasInteractiveDescendant };
92
+ meta.set(node.nodeId, info);
93
+ return info;
94
+ };
95
+
96
+ for (const root of roots) analyze(root);
97
+ return meta;
98
+ }
99
+
100
+ /**
101
+ * Collapse internal whitespace and trim surrounding spaces.
102
+ * @param {unknown} value
103
+ * @returns {string}
104
+ */
105
+ function normalizeText(value) {
106
+ if (value === undefined || value === null) return "";
107
+ return String(value).replace(/\s+/gu, " ").trim();
108
+ }
109
+
110
+ /**
111
+ * Truncate a string cleanly with an ellipsis when exceeding maxLength.
112
+ * @param {string} text
113
+ * @param {number} maxLength
114
+ * @returns {string}
115
+ */
116
+ function truncateText(text, maxLength) {
117
+ if (text.length <= maxLength) return text;
118
+ return `${text.slice(0, Math.max(0, maxLength - 1))}…`;
119
+ }
120
+
121
+ /**
122
+ * Extract named CDP AX property values into a lookup map.
123
+ * @param {unknown} properties
124
+ * @returns {Map<string, unknown>}
125
+ */
126
+ function readPropertyMap(properties) {
127
+ const map = new Map();
128
+ if (!Array.isArray(properties)) return map;
129
+ for (const property of properties) {
130
+ if (typeof property?.name === "string") {
131
+ map.set(property.name, property?.value?.value);
132
+ }
133
+ }
134
+ return map;
135
+ }
136
+
137
+ /**
138
+ * Format compact state tokens for an AX node.
139
+ * @param {Map<string, unknown>} propMap
140
+ * @returns {{states:string, actions:string[]}}
141
+ */
142
+ function formatNodeStates(propMap) {
143
+ const parts = [];
144
+ const actions = [];
145
+ for (const [name, raw] of propMap) {
146
+ if (!STATEFUL_PROPERTIES.has(name)) continue;
147
+ if (raw === true) {
148
+ parts.push(name);
149
+ if (name === "expanded") actions.push("Collapse");
150
+ } else if (name === "expanded" && raw === false) {
151
+ parts.push("expanded=false");
152
+ actions.push("Expand");
153
+ } else if (typeof raw === "string" || typeof raw === "number") {
154
+ parts.push(`${name}=${raw}`);
155
+ }
156
+ }
157
+ const level = propMap.get("level");
158
+ if (typeof level === "number" && Number.isFinite(level)) {
159
+ parts.push(`level=${level}`);
160
+ }
161
+ return {
162
+ states: parts.length ? `[${parts.join(" ")}]` : "",
163
+ actions,
164
+ };
165
+ }
166
+
167
+ /**
168
+ * Strip the leading numeric index from a rendered AX line for structural comparison.
169
+ * @param {string} line
170
+ * @returns {string}
171
+ */
172
+ function bodyOfLine(line) {
173
+ return line.replace(/^(\s*)\d+\s+/u, "$1");
174
+ }
175
+
176
+ /**
177
+ * Build a compact, indexed accessibility snapshot from CDP AX nodes.
178
+ * Preserves backwards compatibility with the original v3 snapshot format while
179
+ * pruning redundant StaticText children and emitting stable node keys for diffing.
180
+ * @param {Array<Record<string, any>>} nodes
181
+ * @param {{maxLines?:number, maxTextLength?:number, startIndex?:number, baseDepth?:number, frameId?:string|null, sessionId?:string|null}} [options]
182
+ * @returns {{lines:string[], index:Map<string,{backendDOMNodeId:number|null, role:string, name:string, frameId:string|null, sessionId:string|null, actions:string[], dialogControl?:string}>, entries:Array<{idx:number, key:string, line:string, body:string, role:string, name:string, depth:number, frameId:string|null}>, count:number, nextIndex:number, truncated:boolean}}
183
+ */
184
+ function buildAxTreeGraph(nodes) {
185
+ const byId = new Map();
186
+ for (const node of Array.isArray(nodes) ? nodes : []) {
187
+ if (node && typeof node.nodeId === "string") byId.set(node.nodeId, node);
188
+ }
189
+ /** @type {Map<string, Array<Record<string, any>>>} */
190
+ const children = new Map();
191
+ /** @type {Array<Record<string, any>>} */
192
+ const roots = [];
193
+ for (const node of Array.isArray(nodes) ? nodes : []) {
194
+ if (!node || typeof node.nodeId !== "string") continue;
195
+ const parent = typeof node.parentId === "string" ? byId.get(node.parentId) : undefined;
196
+ if (parent) {
197
+ const list = children.get(parent.nodeId) ?? [];
198
+ list.push(node);
199
+ children.set(parent.nodeId, list);
200
+ } else {
201
+ roots.push(node);
202
+ }
203
+ }
204
+ return { byId, children, roots };
205
+ }
206
+
207
+ /**
208
+ * Resolve ordered children of a node, optionally unwrapping transparent nodes
209
+ * so consecutive repeated items under generic wrappers stay grouped at one depth.
210
+ * @param {Array<Record<string, any>>} rawList
211
+ * @param {Map<string, Record<string, any>>} byId
212
+ * @param {Map<string, Array<Record<string, any>>>} children
213
+ * @param {(node: Record<string, any>, role: string, name: string, value: string) => boolean} isTransparentFn
214
+ * @param {number} maxTextLength
215
+ * @param {boolean} unwrapTransparent
216
+ * @returns {Array<Record<string, any>>}
217
+ */
218
+ function resolveSequenceNodes(rawList, byId, children, isTransparentFn, maxTextLength, unwrapTransparent) {
219
+ if (!unwrapTransparent) return rawList;
220
+ const out = [];
221
+ const stack = [...rawList].reverse();
222
+ const seen = new Set();
223
+ while (stack.length > 0) {
224
+ const curr = stack.pop();
225
+ if (!curr || (typeof curr.nodeId === "string" && seen.has(curr.nodeId))) continue;
226
+ if (typeof curr.nodeId === "string") seen.add(curr.nodeId);
227
+ const role = curr.role?.value ?? "unknown";
228
+ const name = truncateText(normalizeText(curr.name?.value), maxTextLength);
229
+ const value = truncateText(normalizeText(curr.value?.value), maxTextLength);
230
+ if (isTransparentFn(curr, role, name, value)) {
231
+ const grand = Array.isArray(curr.childIds) && curr.childIds.length > 0
232
+ ? curr.childIds.map((id) => byId.get(id)).filter(Boolean)
233
+ : children.get(curr.nodeId) ?? [];
234
+ for (let i = grand.length - 1; i >= 0; i--) stack.push(grand[i]);
235
+ } else {
236
+ out.push(curr);
237
+ }
238
+ }
239
+ return out;
240
+ }
241
+
242
+ /**
243
+ * Determine whether a non-transparent node should be emitted in `interactive` mode.
244
+ * @param {Record<string, any>} node
245
+ * @param {string} role
246
+ * @param {string} name
247
+ * @param {Map<string, {directlyInteractive:boolean, hasInteractiveDescendant:boolean}>} interactiveMeta
248
+ * @param {boolean} includeRootWebArea
249
+ * @returns {boolean}
250
+ */
251
+ function shouldKeepInteractiveNode(node, role, name, interactiveMeta, includeRootWebArea) {
252
+ const info = interactiveMeta?.get(node.nodeId);
253
+ if (info?.directlyInteractive) return true;
254
+ if (role === "heading") return Boolean(name) || Boolean(info?.hasInteractiveDescendant);
255
+ if (STRUCTURAL_LANDMARK_ROLES.has(role)) return Boolean(info?.hasInteractiveDescendant);
256
+ if (includeRootWebArea && role === "RootWebArea") return Boolean(info?.hasInteractiveDescendant);
257
+ return false;
258
+ }
259
+
260
+ /**
261
+ * Traverse a sibling sequence, collapsing runs of > 5 consecutive items sharing
262
+ * a collapsible role (`listitem`, `row`, `option`, `treeitem`) when enabled.
263
+ */
264
+ function visitCollapsibleSequence({
265
+ items,
266
+ depth,
267
+ indentOffset = 0,
268
+ ancestor,
269
+ shouldCollapse,
270
+ maxLines,
271
+ lines,
272
+ setTruncated,
273
+ isTruncated,
274
+ visitNode,
275
+ }) {
276
+ if (!shouldCollapse) {
277
+ for (const item of items) visitNode(item, depth, ancestor);
278
+ return;
279
+ }
280
+ let i = 0;
281
+ while (i < items.length && !isTruncated()) {
282
+ const role = items[i].role?.value ?? "unknown";
283
+ if (!COLLAPSIBLE_ITEM_ROLES.has(role)) {
284
+ visitNode(items[i], depth, ancestor);
285
+ i += 1;
286
+ continue;
287
+ }
288
+ let j = i + 1;
289
+ while (j < items.length && (items[j].role?.value ?? "unknown") === role) {
290
+ j += 1;
291
+ }
292
+ const runLen = j - i;
293
+ if (runLen <= 5) {
294
+ for (let k = i; k < j; k++) visitNode(items[k], depth, ancestor);
295
+ } else {
296
+ for (let k = i; k < i + 3; k++) visitNode(items[k], depth, ancestor);
297
+ if (!isTruncated()) {
298
+ if (lines.length >= maxLines) {
299
+ setTruncated();
300
+ return;
301
+ }
302
+ const omitted = runLen - 4;
303
+ lines.push(`${" ".repeat(indentOffset + depth)}... (+${omitted} similar ${role} items omitted)`);
304
+ }
305
+ if (!isTruncated()) {
306
+ visitNode(items[j - 1], depth, ancestor);
307
+ }
308
+ }
309
+ i = j;
310
+ }
311
+ }
312
+
313
+ export function buildAxState(nodes, {
314
+ maxLines = 2_000,
315
+ maxTextLength = 240,
316
+ startIndex = 0,
317
+ baseDepth = 0,
318
+ frameId = null,
319
+ sessionId = null,
320
+ mode = "full",
321
+ collapseRepeated,
322
+ } = {}) {
323
+ const effectiveMode = mode === "compact" || mode === "interactive" ? mode : "full";
324
+ const shouldCollapse = collapseRepeated ?? (effectiveMode === "compact");
325
+ const { byId, children, roots } = buildAxTreeGraph(nodes);
326
+ const isTransparent = (node, role, _name, value) => {
327
+ if (node.ignored === true || role === "none" || role === "LineBreak" || role === "InlineTextBox") {
328
+ return true;
329
+ }
330
+ if (role === "generic") {
331
+ if (effectiveMode === "interactive") {
332
+ return !hasInteractiveState(value, readPropertyMap(node.properties));
333
+ }
334
+ return true;
335
+ }
336
+ return false;
337
+ };
338
+ const interactiveMeta = effectiveMode === "interactive"
339
+ ? computeInteractiveMetadata(roots, byId, children, isTransparent, maxTextLength)
340
+ : null;
341
+
342
+ const lines = [];
343
+ const entries = [];
344
+ const index = new Map();
345
+ let next = startIndex;
346
+ let truncated = false;
347
+
348
+ /**
349
+ * @param {Record<string, any>} node
350
+ * @param {number} depth
351
+ * @param {{role:string, name:string}|null} ancestor
352
+ */
353
+ const visit = (node, depth, ancestor) => {
354
+ if (truncated) return;
355
+ const role = node.role?.value ?? "unknown";
356
+ const name = truncateText(normalizeText(node.name?.value), maxTextLength);
357
+ const value = truncateText(normalizeText(node.value?.value), maxTextLength);
358
+ const transparent = isTransparent(node, role, name, value);
359
+
360
+ // Prune StaticText nodes whose text duplicates their interactive/heading ancestor's accessible name.
361
+ if (!transparent && role === "StaticText" && ancestor &&
362
+ TEXT_PRUNABLE_PARENT_ROLES.has(ancestor.role) && ancestor.name &&
363
+ (name === ancestor.name || ancestor.name.includes(name))) {
364
+ return;
365
+ }
366
+
367
+ let emit = !transparent;
368
+ if (emit && effectiveMode === "compact" && role === "StaticText" && !name && !value) {
369
+ emit = false;
370
+ }
371
+ if (emit && effectiveMode === "interactive") {
372
+ emit = shouldKeepInteractiveNode(node, role, name, interactiveMeta, true);
373
+ }
374
+
375
+ let nextAncestor = ancestor;
376
+ if (emit) {
377
+ if (lines.length >= maxLines) {
378
+ truncated = true;
379
+ return;
380
+ }
381
+ const idx = next++;
382
+ const propMap = readPropertyMap(node.properties);
383
+ const { states, actions } = formatNodeStates(propMap);
384
+ const backendDOMNodeId = Number.isSafeInteger(node.backendDOMNodeId) ? node.backendDOMNodeId : null;
385
+ if (backendDOMNodeId !== null) {
386
+ index.set(String(idx), {
387
+ backendDOMNodeId,
388
+ role,
389
+ name,
390
+ frameId,
391
+ sessionId,
392
+ actions,
393
+ });
394
+ }
395
+ let line = `${" ".repeat(depth)}${idx} ${role}`;
396
+ if (name) line += ` "${name}"`;
397
+ if (value) line += ` (value: "${value}")`;
398
+ if (role === "link") {
399
+ const url = normalizeText(propMap.get("url"));
400
+ if (url && !/^javascript:/iu.test(url)) {
401
+ line += ` (url: "${truncateText(url, 120)}")`;
402
+ }
403
+ }
404
+ const placeholder = normalizeText(propMap.get("placeholder"));
405
+ if (placeholder && placeholder !== name && placeholder !== value) {
406
+ line += ` (placeholder: "${truncateText(placeholder, 80)}")`;
407
+ }
408
+ if (states) line += ` ${states}`;
409
+ const body = bodyOfLine(line);
410
+ const scope = frameId ?? "main";
411
+ const key = backendDOMNodeId !== null
412
+ ? `${scope}:node:${backendDOMNodeId}:${role}`
413
+ : `${scope}:pos:${depth}:${role}:${name}`;
414
+ lines.push(line);
415
+ entries.push({ idx, key, line, body, role, name, depth, frameId });
416
+ nextAncestor = { role, name };
417
+ }
418
+
419
+ const childDepth = emit ? depth + 1 : depth;
420
+ const rawChildren = Array.isArray(node.childIds) && node.childIds.length > 0
421
+ ? node.childIds.map((id) => byId.get(id)).filter(Boolean)
422
+ : children.get(node.nodeId) ?? [];
423
+ const ordered = resolveSequenceNodes(rawChildren, byId, children, isTransparent, maxTextLength, shouldCollapse);
424
+ visitCollapsibleSequence({
425
+ items: ordered,
426
+ depth: childDepth,
427
+ ancestor: nextAncestor,
428
+ shouldCollapse,
429
+ maxLines,
430
+ lines,
431
+ setTruncated: () => { truncated = true; },
432
+ isTruncated: () => truncated,
433
+ visitNode: visit,
434
+ });
435
+ };
436
+
437
+ const effectiveRoots = resolveSequenceNodes(roots, byId, children, isTransparent, maxTextLength, shouldCollapse);
438
+ visitCollapsibleSequence({
439
+ items: effectiveRoots,
440
+ depth: baseDepth,
441
+ ancestor: null,
442
+ shouldCollapse,
443
+ maxLines,
444
+ lines,
445
+ setTruncated: () => { truncated = true; },
446
+ isTruncated: () => truncated,
447
+ visitNode: visit,
448
+ });
449
+ return {
450
+ lines,
451
+ index,
452
+ entries,
453
+ count: next - startIndex,
454
+ nextIndex: next,
455
+ truncated,
456
+ };
457
+ }
458
+
459
+ /**
460
+ * Merge main-frame and child-iframe AX node lists into one sequentially indexed tree.
461
+ * @param {Array<{nodes:Array<Record<string, any>>, frameId:string|null, sessionId:string|null, url?:string, depth?:number}>} frames
462
+ * @param {{maxLines?:number, maxTextLength?:number, mode?:"full"|"compact"|"interactive", collapseRepeated?:boolean}} [options]
463
+ */
464
+ export function mergeFrameAxStates(frames, {
465
+ maxLines = 2_000,
466
+ maxTextLength = 240,
467
+ mode = "full",
468
+ collapseRepeated,
469
+ } = {}) {
470
+ const lines = [];
471
+ const entries = [];
472
+ const index = new Map();
473
+ let nextIndex = 0;
474
+ let truncated = false;
475
+
476
+ for (let i = 0; i < frames.length; i++) {
477
+ const remaining = maxLines - lines.length;
478
+ if (remaining <= 0) {
479
+ truncated = true;
480
+ break;
481
+ }
482
+ const frame = frames[i];
483
+ const isChild = i > 0;
484
+ const baseDepth = isChild ? Math.max(1, frame.depth ?? 1) : 0;
485
+ const snapshot = buildAxState(frame.nodes, {
486
+ maxLines: isChild ? Math.max(0, remaining - 1) : remaining,
487
+ maxTextLength,
488
+ startIndex: nextIndex,
489
+ baseDepth,
490
+ frameId: frame.frameId ?? null,
491
+ sessionId: frame.sessionId ?? null,
492
+ mode,
493
+ collapseRepeated,
494
+ });
495
+ if (isChild && snapshot.lines.length > 0) {
496
+ const urlHint = frame.url ? ` (${truncateText(normalizeText(frame.url), 100)})` : "";
497
+ lines.push(`${" ".repeat(Math.max(0, baseDepth - 1))}[iframe ${frame.frameId ?? i}${urlHint}]`);
498
+ }
499
+ lines.push(...snapshot.lines);
500
+ entries.push(...snapshot.entries);
501
+ for (const [k, v] of snapshot.index) index.set(k, v);
502
+ nextIndex = snapshot.nextIndex;
503
+ if (snapshot.truncated) {
504
+ truncated = true;
505
+ break;
506
+ }
507
+ }
508
+
509
+ return {
510
+ lines,
511
+ index,
512
+ entries,
513
+ count: nextIndex,
514
+ truncated,
515
+ };
516
+ }
517
+
518
+ /**
519
+ * Compute a compact structural diff between two AX snapshots of the same document.
520
+ * Falls back to full mode when the page changed documentKey or rewrote >65% of nodes.
521
+ * @param {{documentKey?:string, entries:Array<{idx:number, key:string, line:string, body:string}>}|null|undefined} previous
522
+ * @param {{documentKey?:string, lines:string[], entries:Array<{idx:number, key:string, line:string, body:string}>}} current
523
+ * @returns {{mode:"unchanged"|"diff"|"full", lines:string[], added:number, changed:number, removed:number}}
524
+ */
525
+ export function buildAxDiff(previous, current) {
526
+ if (!previous || (previous.documentKey && current.documentKey && previous.documentKey !== current.documentKey)) {
527
+ return { mode: "full", lines: current.lines, added: current.entries.length, changed: 0, removed: 0 };
528
+ }
529
+
530
+ const prevByKey = new Map();
531
+ for (const entry of previous.entries) prevByKey.set(entry.key, entry);
532
+ const currByKey = new Map();
533
+ for (const entry of current.entries) currByKey.set(entry.key, entry);
534
+
535
+ const changed = [];
536
+ const added = [];
537
+ let removed = 0;
538
+
539
+ for (const entry of current.entries) {
540
+ const prev = prevByKey.get(entry.key);
541
+ if (!prev) {
542
+ added.push(entry.line.trimStart());
543
+ } else if (prev.body !== entry.body) {
544
+ changed.push(entry.line.trimStart());
545
+ }
546
+ }
547
+ for (const entry of previous.entries) {
548
+ if (!currByKey.has(entry.key)) removed += 1;
549
+ }
550
+
551
+ if (added.length === 0 && changed.length === 0 && removed === 0) {
552
+ return {
553
+ mode: "unchanged",
554
+ lines: ["No accessibility changes since last snapshot. Existing element indices remain valid."],
555
+ added: 0,
556
+ changed: 0,
557
+ removed: 0,
558
+ };
559
+ }
560
+
561
+ const total = Math.max(1, current.entries.length);
562
+ if (added.length + changed.length > Math.ceil(total * 0.65)) {
563
+ return {
564
+ mode: "full",
565
+ lines: current.lines,
566
+ added: added.length,
567
+ changed: changed.length,
568
+ removed,
569
+ };
570
+ }
571
+
572
+ const lines = [
573
+ `[diff summary: +${added.length} added, ~${changed.length} changed, -${removed} removed; element indices updated to current tree]`,
574
+ ];
575
+ if (changed.length > 0) {
576
+ lines.push("[changed]");
577
+ for (const item of changed) lines.push(` ~ ${item}`);
578
+ }
579
+ if (added.length > 0) {
580
+ lines.push("[added]");
581
+ for (const item of added) lines.push(` + ${item}`);
582
+ }
583
+ return {
584
+ mode: "diff",
585
+ lines,
586
+ added: added.length,
587
+ changed: changed.length,
588
+ removed,
589
+ };
590
+ }
591
+
592
+ /**
593
+ * Render an open JavaScript dialog as an actionable AX tree so inspection never hangs.
594
+ * @param {{type:string, message?:string, defaultPrompt?:string, url?:string}} dialog
595
+ * @param {{tab_id:string, title?:string, url?:string}} tabMeta
596
+ */
597
+ export function buildDialogAxState(dialog, tabMeta) {
598
+ const type = dialog.type || "alert";
599
+ const message = normalizeText(dialog.message || "");
600
+ const index = new Map();
601
+ const lines = [
602
+ `0 alertdialog "JavaScript ${type} dialog"`,
603
+ ` 1 StaticText "${truncateText(message, 400)}"`,
604
+ ];
605
+ let nextIdx = 2;
606
+
607
+ if (type === "prompt") {
608
+ const idx = nextIdx++;
609
+ const promptVal = normalizeText(dialog.defaultPrompt ?? "");
610
+ index.set(String(idx), {
611
+ backendDOMNodeId: null,
612
+ role: "textbox",
613
+ name: "Prompt input",
614
+ frameId: null,
615
+ sessionId: null,
616
+ actions: [],
617
+ dialogControl: "prompt",
618
+ });
619
+ lines.push(` ${idx} textbox "Prompt input"${promptVal ? ` (value: "${promptVal}")` : ""}`);
620
+ }
621
+
622
+ if (type === "confirm" || type === "prompt" || type === "beforeunload") {
623
+ const okIdx = nextIdx++;
624
+ index.set(String(okIdx), {
625
+ backendDOMNodeId: null,
626
+ role: "button",
627
+ name: "OK",
628
+ frameId: null,
629
+ sessionId: null,
630
+ actions: [],
631
+ dialogControl: "accept",
632
+ });
633
+ lines.push(` ${okIdx} button "OK"`);
634
+ }
635
+
636
+ const dismissIdx = nextIdx++;
637
+ const dismissLabel = type === "alert" ? "OK" : "Cancel";
638
+ index.set(String(dismissIdx), {
639
+ backendDOMNodeId: null,
640
+ role: "button",
641
+ name: dismissLabel,
642
+ frameId: null,
643
+ sessionId: null,
644
+ actions: [],
645
+ dialogControl: type === "alert" ? "accept" : "dismiss",
646
+ });
647
+ lines.push(` ${dismissIdx} button "${dismissLabel}"`);
648
+
649
+ const title = tabMeta.title || "";
650
+ const url = tabMeta.url || dialog.url || "";
651
+ const axText = [
652
+ `Title: ${title}`,
653
+ `URL: ${url}`,
654
+ "<ax_state>",
655
+ ...lines,
656
+ "</ax_state>",
657
+ ].join("\n");
658
+
659
+ return {
660
+ tab_id: tabMeta.tab_id,
661
+ title,
662
+ url,
663
+ axText,
664
+ lines,
665
+ entries: lines.map((line, i) => ({
666
+ idx: i,
667
+ key: `dialog:${i}`,
668
+ line,
669
+ body: bodyOfLine(line),
670
+ role: "dialog",
671
+ name: type,
672
+ depth: i === 0 ? 0 : 1,
673
+ frameId: null,
674
+ })),
675
+ index,
676
+ elementCount: lines.length,
677
+ dialog: { type, message },
678
+ screenshotBase64: null,
679
+ };
680
+ }
681
+
682
+ /**
683
+ * Format CDP AX nodes into a compact, Playwright-style YAML ARIA tree
684
+ * ideal for 1-line `.split('\n').filter(...)` queries without index clutter.
685
+ * @param {Array<Record<string, any>>} nodes
686
+ * @param {{maxLines?:number, maxTextLength?:number, baseDepth?:number, mode?:"full"|"compact"|"interactive", collapseRepeated?:boolean}} [options]
687
+ * @returns {{text:string, lineCount:number, truncated:boolean}}
688
+ */
689
+ export function formatAriaSnapshot(nodes, {
690
+ maxLines = 2_000,
691
+ maxTextLength = 240,
692
+ baseDepth = 0,
693
+ mode = "full",
694
+ collapseRepeated,
695
+ rootBackendDOMNodeId,
696
+ } = {}) {
697
+ const effectiveMode = mode === "compact" || mode === "interactive" ? mode : "full";
698
+ const shouldCollapse = collapseRepeated ?? (effectiveMode === "compact");
699
+ const { byId, children, roots } = buildAxTreeGraph(nodes);
700
+ const scopedRoot = Number.isSafeInteger(rootBackendDOMNodeId)
701
+ ? (nodes ?? []).find((n) => n.backendDOMNodeId === rootBackendDOMNodeId) ?? null
702
+ : undefined;
703
+ if (scopedRoot === null) {
704
+ return {
705
+ text: "",
706
+ lineCount: 0,
707
+ truncated: false,
708
+ matched: false,
709
+ };
710
+ }
711
+ const activeRoots = scopedRoot ? [scopedRoot] : roots;
712
+ const isTransparent = (node, role, name, value) => {
713
+ if (node.ignored === true || role === "none" || role === "LineBreak" ||
714
+ role === "InlineTextBox" || role === "RootWebArea") {
715
+ return true;
716
+ }
717
+ if (role === "generic") {
718
+ if (effectiveMode === "interactive") {
719
+ return !hasInteractiveState(value, readPropertyMap(node.properties));
720
+ }
721
+ return !name && !value;
722
+ }
723
+ return false;
724
+ };
725
+ const interactiveMeta = effectiveMode === "interactive"
726
+ ? computeInteractiveMetadata(activeRoots, byId, children, isTransparent, maxTextLength)
727
+ : null;
728
+ const lines = [];
729
+ let truncated = false;
730
+
731
+ const formatYamlBadges = (propMap) => {
732
+ const badges = [];
733
+ const checked = propMap.get("checked");
734
+ if (checked === true) badges.push("[checked]");
735
+ else if (typeof checked === "string" && checked !== "false") badges.push(`[checked=${checked}]`);
736
+ if (propMap.get("selected") === true) badges.push("[selected]");
737
+ if (propMap.get("focused") === true) badges.push("[active]");
738
+ if (propMap.get("disabled") === true) badges.push("[disabled]");
739
+ if (propMap.get("expanded") === true) badges.push("[expanded]");
740
+ const pressed = propMap.get("pressed");
741
+ if (pressed === true) badges.push("[pressed]");
742
+ else if (typeof pressed === "string" && pressed !== "false") badges.push(`[pressed=${pressed}]`);
743
+ if (propMap.get("required") === true) badges.push("[required]");
744
+ const level = propMap.get("level");
745
+ if (typeof level === "number" && Number.isFinite(level)) badges.push(`[level=${level}]`);
746
+ return badges.length ? ` ${badges.join(" ")}` : "";
747
+ };
748
+
749
+ /**
750
+ * @param {Record<string, any>} node
751
+ * @param {number} depth
752
+ * @param {{role:string, name:string}|null} ancestor
753
+ */
754
+ const visit = (node, depth, ancestor) => {
755
+ if (truncated) return;
756
+ const role = node.role?.value ?? "unknown";
757
+ const name = truncateText(normalizeText(node.name?.value), maxTextLength);
758
+ const value = truncateText(normalizeText(node.value?.value), maxTextLength);
759
+ const transparent = isTransparent(node, role, name, value);
760
+
761
+ if (!transparent && role === "StaticText" && ancestor &&
762
+ TEXT_PRUNABLE_PARENT_ROLES.has(ancestor.role) && ancestor.name &&
763
+ (name === ancestor.name || ancestor.name.includes(name))) {
764
+ return;
765
+ }
766
+
767
+ let emit = !transparent;
768
+ if (emit && effectiveMode === "interactive") {
769
+ emit = shouldKeepInteractiveNode(node, role, name, interactiveMeta, false);
770
+ }
771
+
772
+ let nextAncestor = ancestor;
773
+ if (emit) {
774
+ if (lines.length >= maxLines) {
775
+ truncated = true;
776
+ return;
777
+ }
778
+ const indent = " ".repeat(baseDepth + depth);
779
+ if (role === "StaticText") {
780
+ if (name) lines.push(`${indent}- text: ${name}`);
781
+ } else {
782
+ const propMap = readPropertyMap(node.properties);
783
+ const badges = formatYamlBadges(propMap);
784
+ let line = `${indent}- ${role}`;
785
+ if (name) line += ` "${name.replaceAll('"', '\\"')}"`;
786
+ line += badges;
787
+ if (value && value !== name) line += `: ${value}`;
788
+ lines.push(line);
789
+
790
+ if (role === "link") {
791
+ const url = normalizeText(propMap.get("url"));
792
+ if (url && !/^javascript:/iu.test(url) && lines.length < maxLines) {
793
+ lines.push(`${indent} - /url: ${truncateText(url, 160)}`);
794
+ }
795
+ }
796
+ }
797
+ nextAncestor = { role, name };
798
+ }
799
+
800
+ const childDepth = emit ? depth + 1 : depth;
801
+ const rawChildren = Array.isArray(node.childIds) && node.childIds.length > 0
802
+ ? node.childIds.map((id) => byId.get(id)).filter(Boolean)
803
+ : children.get(node.nodeId) ?? [];
804
+ const ordered = resolveSequenceNodes(rawChildren, byId, children, isTransparent, maxTextLength, shouldCollapse);
805
+ visitCollapsibleSequence({
806
+ items: ordered,
807
+ depth: childDepth,
808
+ indentOffset: baseDepth,
809
+ ancestor: nextAncestor,
810
+ shouldCollapse,
811
+ maxLines,
812
+ lines,
813
+ setTruncated: () => { truncated = true; },
814
+ isTruncated: () => truncated,
815
+ visitNode: visit,
816
+ });
817
+ };
818
+
819
+ const effectiveRoots = resolveSequenceNodes(activeRoots, byId, children, isTransparent, maxTextLength, shouldCollapse);
820
+ visitCollapsibleSequence({
821
+ items: effectiveRoots,
822
+ depth: 0,
823
+ indentOffset: baseDepth,
824
+ ancestor: null,
825
+ shouldCollapse,
826
+ maxLines,
827
+ lines,
828
+ setTruncated: () => { truncated = true; },
829
+ isTruncated: () => truncated,
830
+ visitNode: visit,
831
+ });
832
+ return {
833
+ text: lines.join("\n"),
834
+ lineCount: lines.length,
835
+ truncated,
836
+ ...(scopedRoot ? { matched: true } : {}),
837
+ };
838
+ }
839
+
840
+ /**
841
+ * Merge main-frame and child-iframe ARIA snapshots into one clean indented YAML tree.
842
+ * @param {Array<{nodes:Array<Record<string, any>>, frameId:string|null, url?:string, depth?:number}>} frames
843
+ * @param {{maxLines?:number, maxTextLength?:number, mode?:"full"|"compact"|"interactive", collapseRepeated?:boolean}} [options]
844
+ * @returns {{text:string, lineCount:number, truncated:boolean}}
845
+ */
846
+ export function mergeFrameAriaSnapshots(frames, {
847
+ maxLines = 2_000,
848
+ maxTextLength = 240,
849
+ mode = "full",
850
+ collapseRepeated,
851
+ } = {}) {
852
+ const lines = [];
853
+ let truncated = false;
854
+
855
+ for (let i = 0; i < frames.length; i++) {
856
+ const remaining = maxLines - lines.length;
857
+ if (remaining <= 0) {
858
+ truncated = true;
859
+ break;
860
+ }
861
+ const frame = frames[i];
862
+ const isChild = i > 0;
863
+ const baseDepth = isChild ? Math.max(1, frame.depth ?? 1) : 0;
864
+ const snapshot = formatAriaSnapshot(frame.nodes ?? [], {
865
+ maxLines: isChild ? Math.max(0, remaining - 1) : remaining,
866
+ maxTextLength,
867
+ baseDepth,
868
+ mode,
869
+ collapseRepeated,
870
+ });
871
+ if (!snapshot.text) continue;
872
+ const frameLines = snapshot.text.split("\n");
873
+ if (isChild && frameLines.length > 0) {
874
+ const urlHint = frame.url ? ` (${truncateText(normalizeText(frame.url), 100)})` : "";
875
+ lines.push(`${" ".repeat(Math.max(0, baseDepth - 1))}[iframe ${frame.frameId ?? i}${urlHint}]`);
876
+ }
877
+ lines.push(...frameLines);
878
+ if (snapshot.truncated) {
879
+ truncated = true;
880
+ break;
881
+ }
882
+ }
883
+
884
+ return {
885
+ text: lines.join("\n"),
886
+ lineCount: lines.length,
887
+ truncated,
888
+ };
889
+ }