@agent-om/cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,4751 @@
1
+ import { _ as LOCATOR_ARGS, c as ToolError, d as screenshotOn, f as ATTACH_MS, g as endpointOf, h as discover, l as UsageError, n as sessionDir, o as ALLOW_SCREENSHOT, p as NO_BROWSER, r as sessionFile, t as readSession, u as evalOn, v as commandsFor } from "./session-CeDFN-1x.mjs";
2
+ import { chmodSync, existsSync, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { basename, extname, join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { randomBytes } from "node:crypto";
6
+ import http from "node:http";
7
+ import { chromium } from "playwright";
8
+ /** A line's text cut at this length, saying so. */
9
+ const LINE_MAX = 300;
10
+ /** A rendered link address longer than this loses its query/tail unless read uncut (scope <ref> or limit 0). */
11
+ const HREF_MAX = 80;
12
+ /** Views longer than this collapse link-only chrome landmarks (nav, aside, footer) with an explicit expand hint. */
13
+ const LARGE_VIEW_CHARS = 8e3;
14
+ /** Landmark roles that collapse when link-only on large pages. */
15
+ const COLLAPSIBLE_LANDMARKS = /* @__PURE__ */ new Set([
16
+ "navigation",
17
+ "complementary",
18
+ "contentinfo"
19
+ ]);
20
+ /** Chrome landmark roles inside which link-only child groups (lists/menus) and long direct link bars also fold on large pages. */
21
+ const CHROME_LANDMARKS = /* @__PURE__ */ new Set([
22
+ "navigation",
23
+ "banner",
24
+ "complementary",
25
+ "contentinfo"
26
+ ]);
27
+ /** Container roles eligible for link-only folding inside a chrome landmark. */
28
+ const LINK_GROUP_ROLES = /* @__PURE__ */ new Set([
29
+ "list",
30
+ "menu",
31
+ "menubar",
32
+ "group",
33
+ "generic",
34
+ "navigation"
35
+ ]);
36
+ /** Form/input roles whose presence prevents collapsing a landmark (e.g. a header nav holding the main search box). */
37
+ const LANDMARK_INPUTS = /* @__PURE__ */ new Set([
38
+ "textbox",
39
+ "searchbox",
40
+ "combobox",
41
+ "checkbox",
42
+ "radio",
43
+ "switch",
44
+ "spinbutton",
45
+ "slider",
46
+ "listbox",
47
+ "form"
48
+ ]);
49
+ /** Roles whose presence prevents collapsing a link-only child group inside chrome (keeps search & action buttons visible). */
50
+ const CHROME_GROUP_KEEP = /* @__PURE__ */ new Set([
51
+ ...LANDMARK_INPUTS,
52
+ "button",
53
+ "ToggleButton",
54
+ "PopUpButton"
55
+ ]);
56
+ /** Direct link limit inside a mixed chrome landmark when there are >= 10 direct sibling links. */
57
+ const CHROME_LINK_LIMIT = 6;
58
+ /** Card/item container roles within which identical link addresses are deduplicated. */
59
+ const CARD_ROLES = /* @__PURE__ */ new Set([
60
+ "listitem",
61
+ "article",
62
+ "row"
63
+ ]);
64
+ /** Roles a person acts on. */
65
+ const CONTROLS = /* @__PURE__ */ new Set([
66
+ "button",
67
+ "link",
68
+ "textbox",
69
+ "searchbox",
70
+ "combobox",
71
+ "checkbox",
72
+ "radio",
73
+ "switch",
74
+ "tab",
75
+ "menuitem",
76
+ "menuitemcheckbox",
77
+ "menuitemradio",
78
+ "option",
79
+ "slider",
80
+ "spinbutton",
81
+ "treeitem",
82
+ "listbox",
83
+ "PopUpButton",
84
+ "ToggleButton"
85
+ ]);
86
+ /** Whether a node is something to act on: a control, or what the page makes clickable, focusable or editable. */
87
+ const actable = (n) => CONTROLS.has(n.role) || !!n.clickable || !!n.focusable || !!n.editable;
88
+ /** The facts no role states, in the order a line says them; on a generic node the first is its role's word. */
89
+ const FACTS = [
90
+ "editable",
91
+ "clickable",
92
+ "focusable"
93
+ ];
94
+ /** Roles whose level says where they are (a heading's, a tree item's); elsewhere Chrome's level is a list's nesting, said by the indent. */
95
+ const LEVELED = /* @__PURE__ */ new Set(["heading", "treeitem"]);
96
+ const squash$2 = (s) => s.replace(/\s+/g, " ").trim();
97
+ /** All the text a node shows, its own name and what's inside it. */
98
+ const shown = (n) => squash$2([n.name ?? "", ...(n.children ?? []).map(shown)].join(" "));
99
+ const hasActable = (n) => actable(n) || !!n.meta || !!n.id || (n.children ?? []).some(hasActable);
100
+ /** A closed drop-down's choices, on its own line: the option nodes inside it, and how many there are. */
101
+ function choices(n) {
102
+ if (n.states?.expanded !== false || !(n.role === "combobox" || n.role === "listbox" || n.role === "PopUpButton")) return void 0;
103
+ const options = [];
104
+ const walk = (c) => {
105
+ if (c.role === "option" || c.role === "MenuListOption") options.push(c.name ?? "");
106
+ else c.children?.forEach(walk);
107
+ };
108
+ n.children?.forEach(walk);
109
+ return options.length ? options : void 0;
110
+ }
111
+ /** How much of a closed drop-down's choices its line shows before saying how many more: all of them with no limit (`limit: 0`). */
112
+ const CHOICES_MAX = 240;
113
+ /** Roles that say where something is, named or not: a dialog, a form, a table, a landmark. */
114
+ const STRUCTURE = /* @__PURE__ */ new Set([
115
+ "dialog",
116
+ "alertdialog",
117
+ "form",
118
+ "main",
119
+ "navigation",
120
+ "banner",
121
+ "contentinfo",
122
+ "complementary",
123
+ "region",
124
+ "search",
125
+ "table",
126
+ "grid",
127
+ "treegrid",
128
+ "row",
129
+ "menu",
130
+ "menubar",
131
+ "toolbar",
132
+ "tablist",
133
+ "tree",
134
+ "feed",
135
+ "article",
136
+ "alert",
137
+ "status",
138
+ "log",
139
+ "tabpanel"
140
+ ]);
141
+ /** Items that hold several things: their line keeps one item's things apart from the next's (a list's messages). */
142
+ const GROUPS = /* @__PURE__ */ new Set([
143
+ "listitem",
144
+ "group",
145
+ "cell",
146
+ "gridcell"
147
+ ]);
148
+ /** Whether a line for it says anything: an empty wrapper Chrome keeps (an unnamed image, a plugin's box) says nothing. */
149
+ const says = (n) => ROW_CELLS.has(n.role) || n.role === "text" && /[\p{L}\p{N}]/u.test(n.name ?? "") || actable(n) || STRUCTURE.has(n.role) || GROUPS.has(n.role) && inside(n).length > 1 || !!(n.name || n.value !== void 0 || n.secret || n.href || n.description || n.meta || n.id || Object.keys(n.states ?? {}).some((k) => k !== "level" || LEVELED.has(n.role)));
150
+ /** The cells of a row, by role (the header cells are named by their column already). */
151
+ const ROW_CELLS = /* @__PURE__ */ new Set(["cell", "gridcell"]);
152
+ /**
153
+ * The roles a browser names by what they hold, when nothing else names them: the walk's rule for names (core's
154
+ * walk/self.ts), and the view's for what a name already says. Chrome's own role names among them.
155
+ */
156
+ const NAMED_BY_CONTENTS = /* @__PURE__ */ new Set([
157
+ "button",
158
+ "cell",
159
+ "checkbox",
160
+ "columnheader",
161
+ "DisclosureTriangle",
162
+ "gridcell",
163
+ "heading",
164
+ "link",
165
+ "menuitem",
166
+ "menuitemcheckbox",
167
+ "menuitemradio",
168
+ "option",
169
+ "radio",
170
+ "row",
171
+ "rowheader",
172
+ "switch",
173
+ "tab",
174
+ "tooltip",
175
+ "treeitem",
176
+ "term",
177
+ "LayoutTableCell",
178
+ "PopUpButton",
179
+ "ToggleButton",
180
+ "clickable"
181
+ ]);
182
+ /**
183
+ * Whether a node's name or description already says all a child shows, and the child holds nothing to act on: the
184
+ * child adds nothing. A description is often built from what the node shows (aria-describedby on its own figures).
185
+ * A name says what's inside where it is made of it (a link's, a button's, a cell's). A container (a region, a group,
186
+ * a table) is named by a label, which is the first thing in it where it is in it at all (a table's caption, a group's
187
+ * legend, the heading it's labelled by): so only at its head (`head`) is a child that reads as its name left out.
188
+ * Further in, the same words are the page's own (a "MEMBERS" heading halfway down the region "Members").
189
+ */
190
+ const saidBy = (parent, child, head = true) => {
191
+ if (!parent.name && !parent.description || hasActable(child)) return false;
192
+ const text = squash$2(shown(child));
193
+ if (!text) return false;
194
+ const byContents = NAMED_BY_CONTENTS.has(parent.role) || !!parent.clickable;
195
+ const says = (piece, exact = false) => {
196
+ const want = squash$2(piece).toLowerCase();
197
+ if (!want) return false;
198
+ if (!!parent.description && squash$2(parent.description).toLowerCase().includes(want)) return true;
199
+ if (!parent.name) return false;
200
+ const name = squash$2(parent.name).toLowerCase();
201
+ if (byContents) return name.includes(want);
202
+ return head && (exact ? name === want : name === want);
203
+ };
204
+ return says(text, true) && describedIn(child).every((d) => says(d));
205
+ };
206
+ /** The descriptions in a node and everything inside it. */
207
+ const describedIn = (n) => [...n.description ? [n.description] : [], ...(n.children ?? []).flatMap(describedIn)];
208
+ /**
209
+ * What the view shows inside a node. A named control's name already says what
210
+ * it shows (a link named "100% Payments Heartbeat history…"), so what's
211
+ * inside it is left out unless it can be acted on or says more than the name.
212
+ */
213
+ function inside(n, whole = false, by = n, head = true) {
214
+ const kids = n.children ?? [];
215
+ if (!whole && choices(n)) return [];
216
+ if (!by.name && !by.description) return kids;
217
+ const first = head ? kids.find((c) => says(c) || !!c.children?.length) : void 0;
218
+ return kids.filter((c) => !saidBy(by, c, head && c === first));
219
+ }
220
+ const q = (s) => JSON.stringify(s.length > LINE_MAX ? `${s.slice(0, LINE_MAX)}…` : s);
221
+ /** Whether an address someone typed holds the view's mark for the page's query, and so isn't one to open as it is. */
222
+ const asksForKept = (address) => address.includes("…");
223
+ /**
224
+ * A link's query as the view writes it on a page that has one: where the link has every parameter the page's address
225
+ * has, those it keeps as they are become the mark (`?…`), and only what it changes or adds is written after it
226
+ * (`?…&path=eq.%2Fblog`). A link that drops a parameter of the page's keeps its whole query: the mark would be untrue.
227
+ */
228
+ function queryFrom(u, page) {
229
+ if (!u.search || !page?.search) return u.search;
230
+ const own = new URLSearchParams(page.search);
231
+ const link = new URLSearchParams(u.search);
232
+ const keys = [...new Set(own.keys())];
233
+ if (!keys.every((k) => link.has(k))) return u.search;
234
+ const kept = new Set(keys.filter((k) => JSON.stringify(link.getAll(k)) === JSON.stringify(own.getAll(k))));
235
+ if (!kept.size) return u.search;
236
+ const keyOf = (pair) => {
237
+ try {
238
+ return decodeURIComponent(pair.split("=")[0].replace(/\+/g, " "));
239
+ } catch {
240
+ return pair;
241
+ }
242
+ };
243
+ return `?${["…", ...u.search.slice(1).split("&").filter((pair) => pair && !kept.has(keyOf(pair)))].join("&")}`;
244
+ }
245
+ /**
246
+ * A link's address as the model needs it: the path on this site, the whole address elsewhere, for one to the page's
247
+ * own path only its query (or its part), and for one in the page's folder or below it `./` and the rest, each as a
248
+ * relative address resolves it from the page; its query without what it keeps of the page's own (queryFrom).
249
+ * `base`: the page's address, or only its origin (then nothing is said from the page).
250
+ */
251
+ function where(href, base) {
252
+ try {
253
+ const u = new URL(href);
254
+ const origin = originOf(base);
255
+ if (u.origin !== origin) return href;
256
+ const page = base.length > origin.length ? new URL(base) : void 0;
257
+ const query = queryFrom(u, page);
258
+ if (page && u.pathname === page.pathname) {
259
+ if (query) return `${query}${u.hash}`;
260
+ if (u.hash && !page.search) return u.hash;
261
+ }
262
+ const folder = page ? page.pathname.slice(0, page.pathname.lastIndexOf("/") + 1) : "";
263
+ if (folder.length > 1 && u.pathname.startsWith(folder) && u.pathname.length > folder.length) return `./${u.pathname.slice(folder.length)}${query}${u.hash}`;
264
+ return `${u.pathname}${query}${u.hash}`;
265
+ } catch {
266
+ return href;
267
+ }
268
+ }
269
+ /** A description at least this long, said again on another line, is written as `(as above)`. */
270
+ const SAID_ONCE = 60;
271
+ /** What a line writes for a description, or a hover's controls, an earlier line of the view said already. */
272
+ const AS_ABOVE = "(as above)";
273
+ /** A node's states as its line says them. */
274
+ function statesOf(n, levels = LEVELED.has(n.role)) {
275
+ const st = n.states ?? {};
276
+ const parts = [];
277
+ const range = typeof st.valuemin === "number" && typeof st.valuemax === "number" && st.valuemax > st.valuemin;
278
+ for (const [k, v] of Object.entries(st)) {
279
+ if (k === "level" && !levels) continue;
280
+ if ((k === "valuemin" || k === "valuemax") && !range) continue;
281
+ if (k === "valuetext" && v === n.value) continue;
282
+ parts.push(v === true ? k : `${k}=${typeof v === "string" ? q(v) : v}`);
283
+ }
284
+ return parts;
285
+ }
286
+ /** What the app says of a node, as its line says it; `said`, what this view has written already (a hover's controls said again are `(as above)`). */
287
+ function metaOf(n, said) {
288
+ const m = n.meta;
289
+ if (!m) return [];
290
+ const parts = [];
291
+ if (m.kind) parts.push(`kind=${m.kind}`);
292
+ if (m.risk) parts.push(`risk=${m.risk}`);
293
+ if (m.confirm) parts.push("confirm");
294
+ if (m.requires) parts.push(`requires=${m.requires.join(",")}`);
295
+ if (m.reveals) {
296
+ const shows = q(m.reveals.join(", "));
297
+ const again = said?.has(`hover-shows=${shows}`) && shows.length > 10;
298
+ said?.add(`hover-shows=${shows}`);
299
+ parts.push(`hover-shows=${again ? AS_ABOVE : shows}`);
300
+ }
301
+ if (m.purpose) parts.push(`purpose=${q(m.purpose)}`);
302
+ if (m.action) parts.push(`action=${q(m.action)}`);
303
+ if (m.desc) parts.push(`note=${q(m.desc)}`);
304
+ if (m.value) parts.push(`data=${q(m.value)}`);
305
+ return parts;
306
+ }
307
+ /** Shorten a rendered address longer than HREF_MAX to its path + ?… (or #… / …), keeping short addresses whole. */
308
+ function shortenHref(rendered, uncut) {
309
+ if (uncut || rendered.length <= HREF_MAX) return rendered;
310
+ const qAt = rendered.indexOf("?");
311
+ const hAt = rendered.indexOf("#");
312
+ const cut = qAt >= 0 ? qAt : hAt;
313
+ if (cut > 0 && cut <= HREF_MAX) return `${rendered.slice(0, cut)}${qAt >= 0 ? `?…` : `#…`}`;
314
+ return `${rendered.slice(0, HREF_MAX)}…`;
315
+ }
316
+ /**
317
+ * One node's line, without its indent; `said` holds what this view has written already (long descriptions, hovers'
318
+ * controls); `all`: uncut addresses and closed drop-down choices; `cardHrefs`: links already printed in this card.
319
+ */
320
+ function line(n, base = "", said, all = false, cardHrefs) {
321
+ if (n.role === "text") return `text: ${(n.name ?? "").length > LINE_MAX ? `${(n.name ?? "").slice(0, LINE_MAX)}…` : n.name ?? ""}`;
322
+ const facts = FACTS.filter((f) => n[f]);
323
+ const word = n.role === "generic" && facts.length ? facts[0] : n.role;
324
+ const parts = [word];
325
+ if (n.name) parts.push(q(n.name));
326
+ if (n.ref) parts.push(`[${n.ref}]`);
327
+ if (n.hint) parts.push(`hint=${q(n.hint)}`);
328
+ if (n.value !== void 0) parts.push(`value=${q(n.value)}`);
329
+ if (n.secret) parts.push(`secret=${n.secret}`);
330
+ if (n.credential) parts.push("credential (fill-secret)");
331
+ parts.push(...statesOf(n));
332
+ for (const f of facts) if (f !== word) parts.push(f);
333
+ if (n.href) {
334
+ const rendered = where(n.href, base);
335
+ const first = !all && cardHrefs && rendered.length > 24 ? cardHrefs.get(n.href) : void 0;
336
+ if (first) parts.push(`→ (same as ${first})`);
337
+ else {
338
+ if (!all && cardHrefs && n.ref && rendered.length > 24) cardHrefs.set(n.href, n.ref);
339
+ parts.push(`→ ${shortenHref(rendered, all)}`);
340
+ }
341
+ }
342
+ const options = choices(n);
343
+ if (options) {
344
+ let shown = "";
345
+ let k = 0;
346
+ for (; k < options.length && (all || shown.length < CHOICES_MAX); k++) shown += `${k ? " | " : ""}${JSON.stringify(options[k])}`;
347
+ parts.push(`choices: ${shown}${k < options.length ? ` … ${options.length - k} more${n.ref ? ` (scope ${n.ref} limit 0)` : ""}` : ""}`);
348
+ }
349
+ if (n.description) {
350
+ const again = said && n.description.length >= SAID_ONCE && said.has(n.description);
351
+ said?.add(n.description);
352
+ parts.push(again ? `desc=${AS_ABOVE}` : `desc=${q(n.description)}`);
353
+ }
354
+ parts.push(...metaOf(n, said));
355
+ return parts.join(" ");
356
+ }
357
+ const find$1 = (n, ref) => n.ref === ref ? n : n.children?.reduce((f, c) => f ?? find$1(c, ref), void 0);
358
+ /** The origin of a page's address, for writing its links as paths. */
359
+ function originOf(url) {
360
+ try {
361
+ return new URL(url).origin;
362
+ } catch {
363
+ return "";
364
+ }
365
+ }
366
+ const TABLES = /* @__PURE__ */ new Set([
367
+ "table",
368
+ "grid",
369
+ "treegrid"
370
+ ]);
371
+ const CELLS$1 = /* @__PURE__ */ new Set([
372
+ "cell",
373
+ "gridcell",
374
+ "rowheader",
375
+ "columnheader"
376
+ ]);
377
+ /** What a cell may not hold and still be a value of its row. */
378
+ const NOT_A_VALUE = /* @__PURE__ */ new Set([
379
+ "list",
380
+ "table",
381
+ "grid",
382
+ "treegrid",
383
+ "tree",
384
+ "form",
385
+ "listbox",
386
+ "dialog",
387
+ "menu",
388
+ "menubar",
389
+ "tablist",
390
+ "feed",
391
+ "region",
392
+ "article"
393
+ ]);
394
+ /** Controls a cell may hold and still be a value of its row. */
395
+ const CELL_CONTROLS = 3;
396
+ const cellsOf = (row) => (row.children ?? []).filter((c) => CELLS$1.has(c.role));
397
+ const isRow = (i) => "row" in i;
398
+ /** The topmost controls inside a node (not the node itself). */
399
+ const controlsIn = (n) => (n.children ?? []).flatMap((c) => actable(c) ? [c] : controlsIn(c));
400
+ const holds = (n, roles) => (n.children ?? []).some((c) => roles.has(c.role) || holds(c, roles));
401
+ /** The text a node shows outside its controls, with the exact value behind a part of it as its line says it (`data="…"`). */
402
+ const textOutside = (n) => squash$2((n.children ?? []).map((c) => actable(c) ? "" : c.meta?.value !== void 0 ? `${c.name ?? shown(c)} data=${q(c.meta.value)}` : c.role === "text" || !c.children?.length ? c.name ?? "" : textOutside(c)).join(" "));
403
+ /**
404
+ * What a node's name says beyond the names of what it holds (a cell named "Add line comment # demo" by its button and
405
+ * its code, a header "No Access" and its help icon's label): its own text, which the tree leaves to the name.
406
+ */
407
+ function nameBeyond(n) {
408
+ let s = n.name ?? "";
409
+ const named = (m) => (m.children ?? []).flatMap((c) => c.role !== "text" && c.name ? [c] : named(c));
410
+ for (const c of named(n)) {
411
+ const at = s.indexOf(c.name);
412
+ if (at >= 0) s = `${s.slice(0, at)} ${s.slice(at + c.name.length)}`;
413
+ }
414
+ return squash$2(s);
415
+ }
416
+ /** Whether a node or what it holds, outside its controls, carries what the app says beyond an exact value: a row says it only as a tree. */
417
+ const saysMore = (n) => Object.keys(n.meta ?? {}).some((k) => k !== "value") || (n.children ?? []).some((c) => !actable(c) && saysMore(c));
418
+ const cellText = (s) => (s.length > LINE_MAX ? `${s.slice(0, LINE_MAX)}…` : s).replace(/\|/g, "\\|");
419
+ /** The rows a table holds, through the wrappers between (row groups), and what else it holds, in order. */
420
+ function itemsOf(n, table = n, head = true) {
421
+ const first = head ? (n.children ?? []).find((c) => says(c) || !!c.children?.length) : void 0;
422
+ return (n.children ?? []).flatMap((c) => c.role === "row" ? [c] : c.role === "rowgroup" || !says(c) ? itemsOf(c, table, c === first) : saidBy(table, c, c === first) ? [] : [{ other: c }]);
423
+ }
424
+ /**
425
+ * The forms a value takes in an address, always in this order: as typed, encoded as a part, as a whole address, as a
426
+ * form's data, and encoded twice (a filter's value encoded, then the whole filter as a part: `channel%3AOrganic%2520Search`).
427
+ */
428
+ const inAddress = (v) => [
429
+ v,
430
+ encodeURIComponent(v),
431
+ encodeURI(v),
432
+ new URLSearchParams([["", v]]).toString().slice(1),
433
+ encodeURIComponent(encodeURIComponent(v))
434
+ ];
435
+ /** A table read compactly, or nothing when no row of it can be. */
436
+ function compactTable(table, base) {
437
+ const raw = itemsOf(table);
438
+ const rows = raw.filter((i) => !("other" in i));
439
+ const headers = rows.filter((r) => cellsOf(r).length > 0 && cellsOf(r).every((c) => c.role === "columnheader"));
440
+ if (!rows.length || headers.length > 1) return void 0;
441
+ const header = headers[0];
442
+ const grid = table.role !== "table";
443
+ const heads = header ? cellsOf(header) : [];
444
+ const width = header ? heads.length : Math.max(...rows.map((r) => cellsOf(r).length));
445
+ const columns = heads.length ? heads.map((h, i) => nameBeyond(h) || textOutside(h) || controlsIn(h)[0]?.name || h.name || `${i + 1}`) : Array.from({ length: width }, (_, i) => `${i + 1}`);
446
+ const items = [];
447
+ for (const r of raw) if ("other" in r) items.push({ tree: r.other });
448
+ else if (r === header) continue;
449
+ else items.push(rowOf(r, width, grid) ?? { tree: r });
450
+ const said = /* @__PURE__ */ new Map();
451
+ const body = items.filter(isRow).map((i) => i.row);
452
+ if (!body.length) return void 0;
453
+ sayControls(body, columns, ownColumns(body, columns), base, said);
454
+ return {
455
+ node: table,
456
+ columns,
457
+ heads: heads.map((h) => actable(h) ? [h] : controlsIn(h)),
458
+ items,
459
+ rows: items.filter((i) => isRow(i) || i.tree.role === "row").length,
460
+ grid,
461
+ said
462
+ };
463
+ }
464
+ /**
465
+ * The columns whose every body cell is one control and nothing else, where the rows' controls line says the control's
466
+ * name once and the rows' values, which would only repeat it, are left empty:
467
+ * - a name that is a fixed text around another column's value ("Pause Checkout API" beside the Name "Checkout API"):
468
+ * said once with the column in braces
469
+ * - one name in every row ("Open"): said once as it is
470
+ * Any other column of controls keeps each row's name whole as its value: the projection can't tell a label's fixed
471
+ * text ("Filter reports by Channel: …") from a word the names share as the page shows them ("Demo Blog", "Demo SaaS").
472
+ */
473
+ function ownColumns(body, columns) {
474
+ const own = /* @__PURE__ */ new Map();
475
+ if (body.length < 2) return own;
476
+ for (const c of columns.keys()) {
477
+ const list = body.flatMap((row) => row.controls.filter((k) => k.column === c && k.own).map((k) => ({
478
+ row,
479
+ c: k
480
+ })));
481
+ if (list.length !== body.length) continue;
482
+ const s = aroundAValue(list, columns, c);
483
+ if (s) own.set(c, {
484
+ key: columns[c],
485
+ template: s.template,
486
+ own: true
487
+ });
488
+ if (s || body.every((r) => r.values[c] === body[0].values[c])) for (const r of body) r.values[c] = "";
489
+ }
490
+ return own;
491
+ }
492
+ /** A body row in the compact form, or nothing when it holds what the form can't say. */
493
+ function rowOf(row, width, grid) {
494
+ const cells = cellsOf(row);
495
+ if (cells.length !== width || (row.children ?? []).some((c) => !CELLS$1.has(c.role) && says(c))) return void 0;
496
+ const values = [];
497
+ const controls = [];
498
+ const refs = [];
499
+ for (const [i, cell] of cells.entries()) {
500
+ if (holds(cell, NOT_A_VALUE) || !actable(cell) && saysMore(cell)) return void 0;
501
+ const inner = controlsIn(cell);
502
+ if (inner.length > CELL_CONTROLS) return void 0;
503
+ const self = !grid && actable(cell);
504
+ const text = (self ? shown(cell) : textOutside(cell) || nameBeyond(cell)) + (cell.meta?.value !== void 0 ? ` data=${q(cell.meta.value)}` : "");
505
+ refs.push(grid ? cell : void 0);
506
+ if (self) controls.push({
507
+ node: cell,
508
+ column: i,
509
+ own: true
510
+ });
511
+ const own = !self && inner.length === 1 && !text;
512
+ values.push(own ? inner[0].name ?? "" : text.trim() || (inner.length ? "" : cell.name ?? ""));
513
+ for (const c of inner) controls.push({
514
+ node: c,
515
+ column: i,
516
+ own
517
+ });
518
+ }
519
+ return { row: {
520
+ node: row,
521
+ values,
522
+ controls,
523
+ cells: refs
524
+ } };
525
+ }
526
+ /** How each row's controls are said: what every row holds alike once (by a key), the rest whole on its row. */
527
+ function sayControls(rows, columns, own, base, said) {
528
+ const slots = /* @__PURE__ */ new Map();
529
+ for (const row of rows) {
530
+ const seen = /* @__PURE__ */ new Map();
531
+ for (const c of row.controls) {
532
+ const base = `${c.column}:${c.node.role}`;
533
+ const k = (seen.get(base) ?? 0) + 1;
534
+ seen.set(base, k);
535
+ const slot = `${base}:${k}`;
536
+ (slots.get(slot) ?? slots.set(slot, []).get(slot)).push({
537
+ row,
538
+ c
539
+ });
540
+ }
541
+ }
542
+ for (const list of slots.values()) {
543
+ const first = list[0].c;
544
+ if (list.length < 2 && !first.own) continue;
545
+ const meta = JSON.stringify(metaOf(first.node));
546
+ if (!list.every(({ c }) => JSON.stringify(metaOf(c.node)) === meta)) continue;
547
+ let s;
548
+ if (first.own && columns[first.column] === `${first.column + 1}` && first.node.name && list.every(({ c }) => c.node.name === first.node.name)) s = { key: first.node.name };
549
+ else if (first.own) {
550
+ const title = columns[first.column];
551
+ const one = list.length > 1 && !!first.node.name && first.node.name !== title && list.every(({ c }) => c.node.name === first.node.name);
552
+ s = own.get(first.column) ?? {
553
+ key: title,
554
+ own: true,
555
+ ...one ? { template: first.node.name } : {}
556
+ };
557
+ } else if (list.every(({ c }) => c.node.name === first.node.name)) s = { key: first.node.name || first.node.role };
558
+ else s = aroundAValue(list, columns);
559
+ if (!s) continue;
560
+ if (first.node.href && list.every(({ c }) => c.node.href)) {
561
+ const address = addressAround(list, columns, base);
562
+ if (address) s.address = address;
563
+ }
564
+ for (const { c } of list) said.set(c.node, s);
565
+ }
566
+ for (const row of rows) {
567
+ const keys = row.controls.map((c) => said.get(c.node)?.key);
568
+ for (const c of row.controls) {
569
+ const s = said.get(c.node);
570
+ if (s && keys.filter((k) => k === s.key).length > 1) said.set(c.node, {
571
+ ...s,
572
+ key: `${s.key}@${columns[c.column]}`
573
+ });
574
+ }
575
+ }
576
+ for (const row of rows) for (const c of row.controls) {
577
+ const s = said.get(c.node);
578
+ const name = c.node.name;
579
+ if (s && !s.own && c.own && name && row.values[c.column] === name && (s.key === name || s.key.startsWith(`${name}@`))) row.values[c.column] = "";
580
+ }
581
+ }
582
+ /** A control whose name is a fixed text around one of its row's values, the same column in every row ("Delete Checkout API"). */
583
+ function aroundAValue(list, columns, skip) {
584
+ const name = list[0].c.node.name ?? "";
585
+ for (const [col, title] of columns.entries()) {
586
+ if (col === skip || list.length > 1 && list.every(({ row }) => row.values[col] === list[0].row.values[col])) continue;
587
+ const v = list[0].row.values[col];
588
+ const at = v ? name.indexOf(v) : -1;
589
+ if (at < 0) continue;
590
+ const before = name.slice(0, at);
591
+ const after = name.slice(at + v.length);
592
+ if (!list.every(({ row, c }) => !!row.values[col] && c.node.name === `${before}${row.values[col]}${after}`)) continue;
593
+ return {
594
+ key: squash$2(`${before} ${after}`).replace(/[:\s]+$/, "") || list[0].c.node.role,
595
+ template: `${before}{${title}}${after}`
596
+ };
597
+ }
598
+ }
599
+ /** An address that is a fixed text around one of its row's values (as typed, or encoded as addresses encode it), the same in every row. */
600
+ function addressAround(list, columns, base) {
601
+ if (list.length < 2) return void 0;
602
+ const path = where(list[0].c.node.href, base);
603
+ for (const [col, title] of columns.entries()) {
604
+ if (list.every(({ row }) => row.values[col] === list[0].row.values[col])) continue;
605
+ const forms = inAddress(list[0].row.values[col]);
606
+ for (const [enc, form] of forms.entries()) {
607
+ const at = form ? path.indexOf(form) : -1;
608
+ if (at < 0) continue;
609
+ const before = path.slice(0, at);
610
+ const after = path.slice(at + form.length);
611
+ if (list.every(({ row, c }) => !!row.values[col] && where(c.node.href, base) === `${before}${inAddress(row.values[col])[enc]}${after}`)) return `${before}{${title}}${after}`;
612
+ }
613
+ }
614
+ }
615
+ /** A row's controls, as its line says them. */
616
+ function rowControls(t, row, base, said, all = false) {
617
+ return row.controls.map(({ node }) => {
618
+ const s = t.said.get(node);
619
+ if (s) {
620
+ const parts = [`${s.key} [${node.ref}]`];
621
+ if (node.hint) parts.push(`hint=${q(node.hint)}`);
622
+ if (node.value !== void 0) parts.push(`value=${q(node.value)}`);
623
+ if (node.secret) parts.push(`secret=${node.secret}`);
624
+ if (node.credential) parts.push("credential (fill-secret)");
625
+ parts.push(...statesOf(node));
626
+ if (node.editable) parts.push("editable");
627
+ if (!s.address && node.href) parts.push(`→ ${shortenHref(where(node.href, base), all)}`);
628
+ const options = choices(node);
629
+ if (options) {
630
+ let shown = "";
631
+ let k = 0;
632
+ for (; k < options.length && (all || shown.length < CHOICES_MAX); k++) shown += `${k ? " | " : ""}${JSON.stringify(options[k])}`;
633
+ parts.push(`choices: ${shown}${k < options.length ? ` … ${options.length - k} more${node.ref ? ` (scope ${node.ref} limit 0)` : ""}` : ""}`);
634
+ }
635
+ if (node.description) {
636
+ const again = said && node.description.length >= SAID_ONCE && said.has(node.description);
637
+ said?.add(node.description);
638
+ parts.push(again ? `desc=${AS_ABOVE}` : `desc=${q(node.description)}`);
639
+ }
640
+ return parts.join(" ");
641
+ }
642
+ return line(node, base, said, all);
643
+ });
644
+ }
645
+ /** A body row's head (ref, states, facts, and controls), without its values. */
646
+ function rowHead(t, row, base, said, all = false) {
647
+ const n = row.node;
648
+ const facts = FACTS.filter((f) => n[f]);
649
+ return [
650
+ `row [${n.ref}]`,
651
+ ...statesOf(n, true),
652
+ ...facts,
653
+ ...rowControls(t, row, base, said, all)
654
+ ].join(" ");
655
+ }
656
+ /** A body row's line, without its indent and dash: its ref and states, its controls, then its values. */
657
+ function rowLine(t, row, base, said, all = false) {
658
+ return `${rowHead(t, row, base, said, all)}: ${row.values.map((v, i) => {
659
+ const cell = row.cells[i];
660
+ return `${cellText(v)}${cell ? ` [${cell.ref}]${statesOf(cell).map((s) => ` ${s}`).join("")}` : ""}`;
661
+ }).join(" | ")}`.trimEnd();
662
+ }
663
+ /** What a row is called where a change names it: its first value, or its ref. */
664
+ const rowName = (row) => row.values.find(Boolean) ?? row.node.ref ?? "row";
665
+ /** Every row the view reads compactly, by its ref: its table, and the row as said. */
666
+ function compactRows(root, base) {
667
+ const out = /* @__PURE__ */ new Map();
668
+ const walk = (n) => {
669
+ const t = TABLES.has(n.role) ? compactTable(n, base) : void 0;
670
+ if (t) {
671
+ for (const i of t.items) if ("row" in i && i.row.node.ref) out.set(i.row.node.ref, {
672
+ table: t,
673
+ row: i.row
674
+ });
675
+ }
676
+ n.children?.forEach(walk);
677
+ };
678
+ walk(root);
679
+ return out;
680
+ }
681
+ /** The table's lines under its own: its columns, what its rows' controls are, and its rows. */
682
+ function tableLines(t) {
683
+ const columns = t.columns.some((c, i) => c !== `${i + 1}`) || t.heads.some((h) => h.length) ? `columns: ${t.columns.map((c, i) => {
684
+ const ctl = t.heads[i].map((h) => {
685
+ const name = h.name && h.name !== c ? ` ${q(h.name.includes(c) ? h.name.replace(c, "{column}") : h.name)}` : "";
686
+ return [
687
+ `${h.role}${name} [${h.ref}]`,
688
+ ...statesOf(h),
689
+ ...metaOf(h)
690
+ ].join(" ");
691
+ });
692
+ return `${c}${ctl.length ? ` (${ctl.join(", ")})` : ""}`;
693
+ }).join(" | ")}` : void 0;
694
+ const once = /* @__PURE__ */ new Map();
695
+ for (const i of t.items) if (isRow(i)) for (const { node } of i.row.controls) {
696
+ const s = t.said.get(node);
697
+ if (!s || once.has(s.key)) continue;
698
+ const name = s.template ? ` ${q(s.template)}` : s.own || !node.name || node.name === s.key ? "" : ` ${q(node.name)}`;
699
+ once.set(s.key, [
700
+ `${s.key}: ${node.role}${name}`,
701
+ ...s.address ? [`→ ${s.address}`] : [],
702
+ ...metaOf(node)
703
+ ].join(" "));
704
+ }
705
+ return {
706
+ columns,
707
+ controls: once.size ? `row controls: ${[...once.values()].join("; ")}` : void 0
708
+ };
709
+ }
710
+ /** Count links in a collapsible chrome landmark; undefined if it has inputs or fewer than 6 links. */
711
+ function linkOnlyLandmark(n) {
712
+ if (!COLLAPSIBLE_LANDMARKS.has(n.role) || !n.ref) return void 0;
713
+ let links = 0;
714
+ const scan = (x) => {
715
+ if (LANDMARK_INPUTS.has(x.role) || x.editable) return false;
716
+ if (x.role === "link") links++;
717
+ for (const c of x.children ?? []) if (!scan(c)) return false;
718
+ return true;
719
+ };
720
+ return scan(n) && links >= 6 ? links : void 0;
721
+ }
722
+ /** Count links in a link-only child group inside a mixed chrome landmark (e.g. a nav link list beside a search bar). */
723
+ function linkOnlyGroup(n) {
724
+ if (!LINK_GROUP_ROLES.has(n.role) || !n.ref) return void 0;
725
+ let links = 0;
726
+ const scan = (x) => {
727
+ if (CHROME_GROUP_KEEP.has(x.role) || x.editable) return false;
728
+ if (x.role === "link") links++;
729
+ for (const c of x.children ?? []) if (!scan(c)) return false;
730
+ return true;
731
+ };
732
+ return scan(n) && links >= 6 ? links : void 0;
733
+ }
734
+ /** Find an open modal dialog if one exists on the page. */
735
+ function openModal(n) {
736
+ if ((n.role === "dialog" || n.role === "alertdialog") && n.states?.modal === true && n.ref) return n;
737
+ for (const c of n.children ?? []) {
738
+ const found = openModal(c);
739
+ if (found) return found;
740
+ }
741
+ }
742
+ /** The lines for some nodes and what they hold, under the options' filters and limits; `depth` counts from the first. */
743
+ function tree(nodes, base, o = {}, indent = "", depth = 0, open, collapseLandmarks = false) {
744
+ /** what's inside a node, less what `by` (the node, or the one a wrapper's lines go under) already says; a closed drop-down read on purpose (the scope) lists its options */
745
+ const ins = (n, by = n, head = true) => inside(n, n === open, by, head);
746
+ const words = o.match?.map((w) => w.toLowerCase()).filter(Boolean);
747
+ const filtered = !!(o.interactive || words?.length);
748
+ const limit = o.limit ?? 25;
749
+ const out = [];
750
+ const said = /* @__PURE__ */ new Set();
751
+ /** Whether a node or anything inside it is shown under the filters. */
752
+ const keeps = /* @__PURE__ */ new Map();
753
+ const own = (n) => (!o.interactive || actable(n)) && (!words?.length || words.some((w) => line(n, base, void 0, !limit).toLowerCase().includes(w)));
754
+ const kept = (n) => {
755
+ let k = keeps.get(n);
756
+ if (k === void 0) {
757
+ k = says(n) && own(n) || ins(n).some(kept);
758
+ keeps.set(n, k);
759
+ }
760
+ return k;
761
+ };
762
+ /**
763
+ * What's shown inside a node, a wrapper that says nothing replaced by what it holds, in its place: what the node
764
+ * already says is left out through the wrapper too.
765
+ */
766
+ const shownIn = (n, by = n, head = true) => {
767
+ const kids = ins(n, by, head);
768
+ const first = head ? kids.find((c) => says(c) || !!c.children?.length) : void 0;
769
+ return kids.flatMap((c) => filtered && !kept(c) ? [] : says(c) ? [c] : shownIn(c, by, head && c === first));
770
+ };
771
+ /** A table's lines under its own: its columns, what its rows' controls are, then its rows, cut past the limit. */
772
+ const table = (t, depth, indent) => {
773
+ const inner = `${indent} `;
774
+ if (o.depth !== void 0 && depth >= o.depth) {
775
+ out.push(`${inner}… ${t.rows} rows inside${t.node.ref ? ` (scope ${t.node.ref})` : ""}`);
776
+ return;
777
+ }
778
+ const keepRow = (row, text) => (!o.interactive || t.grid || row.controls.length > 0) && (!words?.length || words.some((w) => text.toLowerCase().includes(w)));
779
+ const items = [];
780
+ for (const i of t.items) if ("row" in i) {
781
+ const text = rowLine(t, i.row, base, said, !limit);
782
+ if (!filtered || keepRow(i.row, text)) items.push({ line: text });
783
+ } else if (!filtered || kept(i.tree)) items.push({ tree: i.tree });
784
+ const { columns, controls } = tableLines(t);
785
+ if (columns && (items.length || !filtered || o.interactive && t.heads.some((h) => h.length))) out.push(`${inner}${columns}`);
786
+ if (controls && items.some((i) => "line" in i)) out.push(`${inner}${controls}`);
787
+ const isRow = (i) => "line" in i || i.tree.role === "row";
788
+ const total = items.filter(isRow).length;
789
+ const head = Math.ceil(limit / 2);
790
+ let r = 0;
791
+ for (const i of items) {
792
+ if (isRow(i) && limit && total > limit) {
793
+ r++;
794
+ if (r > head && r <= total - (limit - head)) {
795
+ if (r === head + 1) out.push(`${inner}… ${total - limit} more rows here${t.node.ref ? ` (scope ${t.node.ref} limit 0 to see all)` : ""}`);
796
+ continue;
797
+ }
798
+ }
799
+ if ("line" in i) out.push(`${inner}- ${i.line}`);
800
+ else walk(i.tree, depth + 1, inner);
801
+ }
802
+ };
803
+ const walk = (n, depth, indent, cardHrefs, inChrome = false) => {
804
+ if (filtered ? !kept(n) : !says(n) && !ins(n).length) return;
805
+ if (!says(n)) {
806
+ for (const c of shownIn(n)) walk(c, depth, indent, cardHrefs, inChrome);
807
+ return;
808
+ }
809
+ const uncut = !limit || n === open;
810
+ if (collapseLandmarks && !filtered && !uncut) {
811
+ const links = linkOnlyLandmark(n) ?? (inChrome ? linkOnlyGroup(n) : void 0);
812
+ if (links !== void 0) {
813
+ out.push(`${indent}- ${line(n, base, said, false)} (${links} links; scope ${n.ref} to expand)`);
814
+ return;
815
+ }
816
+ }
817
+ const t = TABLES.has(n.role) ? compactTable(n, base) : void 0;
818
+ out.push(`${indent}- ${line(n, base, said, uncut, cardHrefs)}${t ? ` ${t.rows} row${t.rows === 1 ? "" : "s"}` : ""}`);
819
+ if (t) {
820
+ table(t, depth, indent);
821
+ return;
822
+ }
823
+ const kids = shownIn(n);
824
+ if (!kids.length) return;
825
+ if (o.depth !== void 0 && depth >= o.depth) {
826
+ out.push(`${indent} … ${kids.length} more inside${n.ref ? ` (scope ${n.ref})` : ""}`);
827
+ return;
828
+ }
829
+ const nextCard = CARD_ROLES.has(n.role) ? /* @__PURE__ */ new Map() : cardHrefs;
830
+ const nextChrome = inChrome || CHROME_LANDMARKS.has(n.role);
831
+ const of = /* @__PURE__ */ new Map();
832
+ for (const c of kids) of.set(c.role, (of.get(c.role) ?? 0) + 1);
833
+ const seen = /* @__PURE__ */ new Map();
834
+ for (const c of kids) {
835
+ const total = of.get(c.role) ?? 0;
836
+ const k = (seen.get(c.role) ?? 0) + 1;
837
+ seen.set(c.role, k);
838
+ const cap = collapseLandmarks && !filtered && !uncut && nextChrome && c.role === "link" && total >= 10 ? Math.min(limit, CHROME_LINK_LIMIT) : limit;
839
+ const head = Math.ceil(cap / 2);
840
+ if (cap && total > cap && k > head && k <= total - (cap - head)) {
841
+ if (k === head + 1) {
842
+ const cut = total - cap;
843
+ const label = c.role === "text" ? `text line${cut > 1 ? "s" : ""}` : `${c.role}${cut > 1 ? "s" : ""}`;
844
+ out.push(`${indent} … ${cut} more ${label} here${n.ref ? ` (scope ${n.ref} limit 0 to see all)` : ""}`);
845
+ }
846
+ continue;
847
+ }
848
+ walk(c, depth + 1, `${indent} `, nextCard, nextChrome);
849
+ }
850
+ };
851
+ for (const n of nodes) walk(n, depth, indent);
852
+ return out;
853
+ }
854
+ /** The page as the model reads it. */
855
+ function view(p, o = {}) {
856
+ const base = p.url;
857
+ const top = o.scope ? find$1(p.root, o.scope) : p.root;
858
+ if (!top) return `${o.scope} is not a ref the page has now: read the whole page.`;
859
+ const declared = [p.context?.screen && `screen ${p.context.screen}`, p.context?.state && p.context.state !== "ready" && p.context.state].filter(Boolean);
860
+ const head = `Page: ${p.title || "(no title)"} (${where(p.url, originOf(p.url))})${declared.length ? `, ${declared.join(", ")}` : ""}`;
861
+ const wholePage = top === p.root && !o.match?.length && o.depth === void 0 && o.limit !== 0 && !o.interactive;
862
+ let lines = top === p.root ? tree(p.root.children ?? [], base, o, "", 1) : tree([top], base, o, "", 0, top);
863
+ if (lines.length) {
864
+ let text = [head, ...lines].join("\n");
865
+ if (wholePage && text.length > LARGE_VIEW_CHARS) {
866
+ const modal = openModal(p.root);
867
+ if (modal) return [
868
+ head,
869
+ "(modal dialog open; snapshot --limit 0 to see the whole page behind it)",
870
+ ...tree([modal], base, o, "", 1, modal)
871
+ ].join("\n");
872
+ lines = tree(p.root.children ?? [], base, o, "", 1, void 0, true);
873
+ text = [head, ...lines].join("\n");
874
+ }
875
+ return text;
876
+ }
877
+ const words = o.match?.filter(Boolean);
878
+ if (words?.length && o.interactive && (top === p.root ? tree(p.root.children ?? [], base, {
879
+ ...o,
880
+ interactive: false
881
+ }, "", 1) : tree([top], base, {
882
+ ...o,
883
+ interactive: false
884
+ }, "", 0, top)).length) return [head, `Nothing that can be acted on matches ${words.join(" or ")}; text does: read again without -i.`].join("\n");
885
+ return [head, words?.length ? `Nothing matches ${words.join(" or ")}.` : o.interactive ? "Nothing to act on." : "The page shows nothing."].join("\n");
886
+ }
887
+ // ../core/src/view/changes.ts
888
+ /** A list of changes at least this share of the whole page's lines is replaced by the page. */
889
+ const WHOLE_PAGE_SHARE = .85;
890
+ /** Fewer than this share of the refs read before still there: another page, read whole. */
891
+ const SAME_PAGE_SHARE = .3;
892
+ /** A node with its focus taken out: where the focus is isn't a change worth saying. */
893
+ const noFocus = (n) => {
894
+ if (!n.states?.focused) return n;
895
+ const { focused: _focused, ...states } = n.states;
896
+ return {
897
+ ...n,
898
+ states
899
+ };
900
+ };
901
+ /** The same, through everything a node holds: once a read, for the rows of its tables. */
902
+ const noFocusAll = (n) => ({
903
+ ...noFocus(n),
904
+ ...n.children ? { children: n.children.map(noFocusAll) } : {}
905
+ });
906
+ /**
907
+ * Every node with a ref, with its parent's ref, its line and the text it holds itself (what text nodes have no ref of
908
+ * their own to say). A row the view reads compactly is one entry, its line the row's: its cells are its values.
909
+ */
910
+ function index(p, base) {
911
+ const m = /* @__PURE__ */ new Map();
912
+ const rows = compactRows(noFocusAll(p.root), base);
913
+ const walk = (n, parent) => {
914
+ const ref = n.ref ?? parent;
915
+ const row = n.ref ? rows.get(n.ref) : void 0;
916
+ if (row) {
917
+ m.set(n.ref, {
918
+ node: n,
919
+ parent,
920
+ line: rowLine(row.table, row.row, base),
921
+ text: "",
922
+ texts: [],
923
+ row
924
+ });
925
+ return;
926
+ }
927
+ if (n.ref) {
928
+ const texts = (n.children ?? []).filter((c) => c.role === "text").map((c) => c.name ?? "");
929
+ m.set(n.ref, {
930
+ node: n,
931
+ parent,
932
+ line: line(noFocus(n), base),
933
+ text: texts.join(" | "),
934
+ texts
935
+ });
936
+ }
937
+ for (const c of n.children ?? []) walk(c, ref);
938
+ };
939
+ walk(p.root);
940
+ return m;
941
+ }
942
+ /** What changed in a row read compactly: each column whose value changed, old → new, and its controls when they did. */
943
+ function rowChanges(was, now, base) {
944
+ const out = [];
945
+ for (const [i, column] of now.table.columns.entries()) {
946
+ const a = was.row.values[i] ?? "";
947
+ const b = now.row.values[i] ?? "";
948
+ if (a !== b) out.push(`${column} ${a || "(empty)"} → ${b || "(empty)"}`);
949
+ }
950
+ const controls = (r) => rowHead(r.table, r.row, base).replace(/^row \[e\d+\] ?/, "") || "(nothing)";
951
+ if (controls(was) !== controls(now)) out.push(`now ${controls(now)} (was ${controls(was)})`);
952
+ return out.join("; ");
953
+ }
954
+ /** How many of a reordered element's children say its new order. */
955
+ const ORDER_SHOWN = 5;
956
+ /** Each ref's children with refs, in the page's order (under refless wrappers too). */
957
+ function childrenOf(entries) {
958
+ const out = /* @__PURE__ */ new Map();
959
+ for (const [ref, e] of entries) if (e.parent) (out.get(e.parent) ?? out.set(e.parent, []).get(e.parent)).push(ref);
960
+ return out;
961
+ }
962
+ /** How long a named element's line may be when it says where a change is. */
963
+ const WHERE_MAX = 120;
964
+ /** How far up the page a change looks for something named to say where it is. */
965
+ const WHERE_UP = 6;
966
+ /** Where a change is: the line of what holds it, and, when that has no name, the nearest named thing around it (the message a new button is in). */
967
+ function whereIs(entries, ref) {
968
+ const holder = ref ? entries.get(ref) : void 0;
969
+ if (!holder) return void 0;
970
+ if (holder.node.name) return holder.line;
971
+ let up = holder.parent;
972
+ for (let k = 0; up && k < WHERE_UP; k++, up = entries.get(up)?.parent) {
973
+ const e = entries.get(up);
974
+ if (e?.node.name && e.node.role !== "document") return `${holder.line}, in ${e.line.length > WHERE_MAX ? `${e.line.slice(0, WHERE_MAX)}…` : e.line}`;
975
+ }
976
+ return holder.line;
977
+ }
978
+ /** Each piece of a list as often as one list has it more than the other: `less` taken from `more`. */
979
+ function beyond(more, less) {
980
+ const left = /* @__PURE__ */ new Map();
981
+ for (const t of less) left.set(t, (left.get(t) ?? 0) + 1);
982
+ return more.filter((t) => {
983
+ const n = left.get(t) ?? 0;
984
+ if (n) left.set(t, n - 1);
985
+ return !n;
986
+ });
987
+ }
988
+ /**
989
+ * What text a node holds now that it didn't, and what it held that it doesn't: only those pieces, never all it holds
990
+ * twice. A node with no ref of its own near loose text is often the whole page, and the same text printed as now and
991
+ * as was has a model take the old value for the new. The same pieces in another order are said as they are now.
992
+ */
993
+ function textChanges(was, now) {
994
+ const added = beyond(now, was);
995
+ const gone = beyond(was, now);
996
+ if (!added.length && !gone.length) return [` text now, in another order: ${now.join(" | ")}`];
997
+ return [...added.length ? [` text added: ${added.join(" | ")}`] : [], ...gone.length ? [` text gone: ${gone.join(" | ")}`] : []];
998
+ }
999
+ /** What changed from `before` to `after`, as the model reads it; the whole page when it's a new page or most of it changed. */
1000
+ function changes(before, after) {
1001
+ const page = () => ({
1002
+ whole: true,
1003
+ text: view(after)
1004
+ });
1005
+ const base = after.url;
1006
+ const was = index(before, base);
1007
+ const now = index(after, base);
1008
+ let kept = 0;
1009
+ for (const ref of was.keys()) if (now.has(ref)) kept++;
1010
+ if (!was.size || kept < was.size * SAME_PAGE_SHARE) return page();
1011
+ const out = [];
1012
+ if (before.url !== after.url) try {
1013
+ const u = new URL(after.url);
1014
+ out.push(`Address now: ${u.pathname}${u.search}${u.hash}`);
1015
+ } catch {
1016
+ out.push(`Address now: ${after.url}`);
1017
+ }
1018
+ if (before.title !== after.title) out.push(`Title now: ${after.title || "(no title)"}`);
1019
+ if (before.context?.screen !== after.context?.screen || before.context?.state !== after.context?.state) {
1020
+ const parts = [after.context?.screen && `screen ${after.context.screen}`, after.context?.state].filter(Boolean);
1021
+ if (parts.length) out.push(`Page state now: ${parts.join(", ")}`);
1022
+ }
1023
+ let lastNew;
1024
+ for (const [ref, e] of now) {
1025
+ if (was.has(ref) || e.parent && !was.has(e.parent) && now.has(e.parent)) continue;
1026
+ const where = e.parent ? now.get(e.parent) : void 0;
1027
+ if (where && saidBy(where.node, e.node, false)) continue;
1028
+ const lines = e.row ? [` - ${e.line}`] : tree([e.node], base, {}, " ");
1029
+ if (!lines.length) continue;
1030
+ const at = whereIs(now, e.parent);
1031
+ const heading = `+ new${at ? ` in ${at}` : ""}:`;
1032
+ if (e.row && lastNew === heading) out.push(...lines);
1033
+ else out.push(heading, ...lines);
1034
+ lastNew = e.row ? heading : void 0;
1035
+ }
1036
+ for (const [ref, e] of was) {
1037
+ if (now.has(ref) || e.parent && !now.has(e.parent) && was.has(e.parent)) continue;
1038
+ const holder = e.parent ? was.get(e.parent) : void 0;
1039
+ if (holder && saidBy(holder.node, e.node, false)) continue;
1040
+ if (e.row) {
1041
+ out.push(`- gone: row [${ref}] (${rowName(e.row.row)})`);
1042
+ continue;
1043
+ }
1044
+ const from = whereIs(was, e.parent);
1045
+ out.push(`- gone: ${e.line}${from && !e.node.name ? ` (from ${from})` : ""}`);
1046
+ }
1047
+ const kidsWas = childrenOf(was);
1048
+ for (const [parent, kids] of childrenOf(now)) {
1049
+ const old = kidsWas.get(parent);
1050
+ if (!old) continue;
1051
+ const had = new Set(old);
1052
+ const rowsOnly = kids.some((k) => now.get(k)?.row);
1053
+ const both = new Set(kids.filter((k) => had.has(k) && (!rowsOnly || now.get(k)?.row)));
1054
+ const seqNow = kids.filter((k) => both.has(k));
1055
+ const seqWas = old.filter((k) => both.has(k));
1056
+ if (seqNow.length < 2 || seqNow.every((k, i) => k === seqWas[i])) continue;
1057
+ const first = seqNow.slice(0, ORDER_SHOWN).map((k) => {
1058
+ const e = now.get(k);
1059
+ const said = e.node.name || e.row && rowName(e.row.row) || e.text || k;
1060
+ return JSON.stringify(said.length > 40 ? `${said.slice(0, 39)}…` : said);
1061
+ });
1062
+ out.push(`~ order now in ${whereIs(now, parent) ?? parent}: ${first.join(", ")}${seqNow.length > ORDER_SHOWN ? `, … (${seqNow.length} in all)` : ""}`);
1063
+ }
1064
+ for (const [ref, e] of now) {
1065
+ const old = was.get(ref);
1066
+ if (!old || old.line === e.line && old.text === e.text) continue;
1067
+ if (e.row && old.row) {
1068
+ out.push(`~ row [${ref}] (${rowName(e.row.row)}): ${rowChanges(old.row, e.row, base)}`);
1069
+ continue;
1070
+ }
1071
+ const at = e.node.name ? void 0 : whereIs(now, e.parent);
1072
+ out.push(`~ now: ${e.line}${at ? ` (in ${at})` : ""}`);
1073
+ if (old.line !== e.line) out.push(` was: ${old.line}`);
1074
+ if (old.text !== e.text) out.push(...textChanges(old.texts, e.texts));
1075
+ }
1076
+ if (!out.length) return {
1077
+ whole: false,
1078
+ none: true,
1079
+ text: "Nothing changed on the page."
1080
+ };
1081
+ const full = view(after);
1082
+ const whole = full.split("\n").length;
1083
+ if (out.length >= whole * WHOLE_PAGE_SHARE) return {
1084
+ whole: true,
1085
+ text: full
1086
+ };
1087
+ return {
1088
+ whole: false,
1089
+ none: false,
1090
+ text: [`Changes on ${after.title || "the page"}:`, ...out].join("\n")
1091
+ };
1092
+ }
1093
+ // ../core/src/view/clock.ts
1094
+ /** The line: the time now in UTC, to the minute, and the time zone the browser's pages show times in, when it's known. */
1095
+ function clockLine(now, zone) {
1096
+ const iso = now.toISOString();
1097
+ return `Now: ${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC${zone ? ` (the browser's time zone: ${zone})` : ""}`;
1098
+ }
1099
+ // ../core/src/view/secrets.ts
1100
+ /** What a secret is replaced with wherever it shows. */
1101
+ const SECRET_MARK = "[secret]";
1102
+ const html = (v) => v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1103
+ /** An encoder that can't take the value (a lone surrogate) gives no form, not an error. */
1104
+ const tryForm = (encode) => {
1105
+ try {
1106
+ return encode();
1107
+ } catch {
1108
+ return;
1109
+ }
1110
+ };
1111
+ /**
1112
+ * Every form a secret takes in text a page writes: as typed, in an address (as
1113
+ * a path or query part, as a whole address, as a form's data), in JSON and in
1114
+ * HTML. Longest first.
1115
+ */
1116
+ function secretForms(value) {
1117
+ const forms = /* @__PURE__ */ new Set([value]);
1118
+ for (const form of [
1119
+ tryForm(() => encodeURIComponent(value)),
1120
+ tryForm(() => encodeURIComponent(encodeURIComponent(value))),
1121
+ tryForm(() => encodeURI(value)),
1122
+ tryForm(() => new URLSearchParams([["", value]]).toString().slice(1)),
1123
+ tryForm(() => JSON.stringify(value).slice(1, -1)),
1124
+ html(value)
1125
+ ]) if (form) forms.add(form);
1126
+ return [...forms].sort((a, b) => b.length - a.length);
1127
+ }
1128
+ const formCache = /* @__PURE__ */ new WeakMap();
1129
+ function cachedForms(secrets) {
1130
+ const hit = formCache.get(secrets);
1131
+ if (hit && hit.len === secrets.length && hit.first === secrets[0] && hit.last === secrets[secrets.length - 1]) return hit.forms;
1132
+ const forms = [...new Set(secrets.flatMap(secretForms))].sort((a, b) => b.length - a.length);
1133
+ formCache.set(secrets, {
1134
+ len: secrets.length,
1135
+ first: secrets[0],
1136
+ last: secrets[secrets.length - 1],
1137
+ forms
1138
+ });
1139
+ return forms;
1140
+ }
1141
+ /**
1142
+ * The text with every form of every secret replaced by SECRET_MARK; the longest
1143
+ * forms first, so none is left half replaced.
1144
+ */
1145
+ function withoutSecrets(text, secrets) {
1146
+ if (!secrets.length) return text;
1147
+ return cachedForms(secrets).reduce((acc, form) => acc.split(form).join(SECRET_MARK), text);
1148
+ }
1149
+ // ../core/src/view/policy.ts
1150
+ /** The nodes from the top down to the one a ref names; nothing when the projection holds no node with that ref. */
1151
+ function pathTo$1(root, ref) {
1152
+ const find = (n, path) => {
1153
+ const here = [...path, n];
1154
+ if (n.ref === ref) return here;
1155
+ for (const c of n.children ?? []) {
1156
+ const found = find(c, here);
1157
+ if (found) return found;
1158
+ }
1159
+ };
1160
+ return find(root, []);
1161
+ }
1162
+ /**
1163
+ * What acting on the node a ref names needs first, or nothing when the projection holds no such ref: a ref the view
1164
+ * never printed (a guess, an element the page keeps out or the view folded into what holds it) names nothing to act
1165
+ * on. `risks` are the risks the host asks the user about beside what the page marks confirm.
1166
+ */
1167
+ function guard(root, ref, risks = []) {
1168
+ const path = pathTo$1(root, ref);
1169
+ if (!path) return void 0;
1170
+ const node = path[path.length - 1];
1171
+ const asking = (n) => !!n.meta?.confirm || !!n.meta?.risk && risks.includes(n.meta.risk);
1172
+ let asks;
1173
+ for (let k = path.length - 1; k >= 0 && !asks; k--) {
1174
+ const n = path[k];
1175
+ if ((n === node || actable(n)) && asking(n)) asks = n;
1176
+ }
1177
+ return {
1178
+ node,
1179
+ ...asks ? { asks } : {},
1180
+ credential: path.some((n) => !!n.credential)
1181
+ };
1182
+ }
1183
+ // ../core/src/view/content.ts
1184
+ /** The page's text between the markers. `nonce`: random, the same for a session, never shown to the page. */
1185
+ function pageContent(text, origin, nonce) {
1186
+ return `--- AGENT_OM_PAGE_CONTENT nonce=${nonce} origin=${origin || "unknown"} ---\n${text}\n--- END_AGENT_OM_PAGE_CONTENT nonce=${nonce} ---`;
1187
+ }
1188
+ // ../core/src/view/query.ts
1189
+ var QueryError = class extends Error {
1190
+ constructor(message) {
1191
+ super(message);
1192
+ this.name = "QueryError";
1193
+ }
1194
+ };
1195
+ const FILTERS = [
1196
+ "role",
1197
+ "name",
1198
+ "exact",
1199
+ "match",
1200
+ "within"
1201
+ ];
1202
+ const CELLS = /* @__PURE__ */ new Set([
1203
+ "cell",
1204
+ "gridcell",
1205
+ "columnheader",
1206
+ "rowheader"
1207
+ ]);
1208
+ const TABLE_ROLES = /* @__PURE__ */ new Set([
1209
+ "table",
1210
+ "grid",
1211
+ "treegrid"
1212
+ ]);
1213
+ /** The words of a node: its name, or the text and control labels/values inside it. */
1214
+ function nodeText(n, skipTables = false) {
1215
+ if (n.name) return n.name;
1216
+ const parts = [];
1217
+ const collect = (x) => {
1218
+ if (skipTables && x !== n && TABLE_ROLES.has(x.role)) return;
1219
+ if (x.role === "text") {
1220
+ if (x.name) parts.push(x.name);
1221
+ return;
1222
+ }
1223
+ if (x !== n && x.name) {
1224
+ parts.push(x.name);
1225
+ if (x.value !== void 0 && x.value !== x.name) parts.push(x.value);
1226
+ return;
1227
+ }
1228
+ if (x !== n && x.value !== void 0) parts.push(x.value);
1229
+ for (const c of x.children ?? []) collect(c);
1230
+ };
1231
+ collect(n);
1232
+ return parts.join(" ").replace(/\s+/g, " ").trim();
1233
+ }
1234
+ /** A node as a script gets it: what it is, its aggregated text when it holds children, and its line as the view writes it. */
1235
+ function projectItem(n) {
1236
+ const { children, ...own } = n;
1237
+ const text = children?.length ? nodeText(n) : void 0;
1238
+ return {
1239
+ ...own,
1240
+ ...text ? { text } : {},
1241
+ line: line(n)
1242
+ };
1243
+ }
1244
+ function* nodes(n) {
1245
+ yield n;
1246
+ for (const c of n.children ?? []) yield* nodes(c);
1247
+ }
1248
+ const byRef = (p, ref) => {
1249
+ for (const n of nodes(p.root)) if (n.ref === ref) return n;
1250
+ };
1251
+ /** A filter's words as text, or refused: a filter the tool can't read is never taken for no filter. */
1252
+ function texts(value, of, one = false) {
1253
+ if (value === void 0) return void 0;
1254
+ const list = Array.isArray(value) && !one ? value : [value];
1255
+ for (const w of list) if (typeof w !== "string") throw new QueryError(`om.find's ${of} takes text${one ? "" : ", or a list of texts"}, and got ${JSON.stringify(w)}`);
1256
+ return list;
1257
+ }
1258
+ /** What a node's line starts with: its role, or for one with no role of its own, the fact the view says in its place (clickable, editable, focusable). */
1259
+ const wordOf = (n) => line(n).split(" ", 1)[0].replace(/:$/, "");
1260
+ /**
1261
+ * The nodes of the page a filter takes: by role (the word its line starts with, so `clickable` finds what the view
1262
+ * calls that), by a part of the name, by any of some words anywhere in the line, inside a ref or node.
1263
+ */
1264
+ function findNodes(p, f = {}) {
1265
+ const unknown = Object.keys(f).filter((k) => !FILTERS.includes(k));
1266
+ if (unknown.length) throw new QueryError(`om.find takes ${FILTERS.join(", ")}, and got ${unknown.join(", ")}: filter by anything else on what it gives back (its states, value, href)`);
1267
+ const within = typeof f.within === "object" && f.within !== null && typeof f.within.ref === "string" ? f.within.ref : f.within;
1268
+ if (within !== void 0 && (typeof within !== "string" || !/^e\d+$/.test(within))) throw new QueryError(`om.find's within takes a ref (e12, or a node om.find gave), and got ${JSON.stringify(f.within)}: find what holds it first`);
1269
+ if (f.exact !== void 0 && typeof f.exact !== "boolean") throw new QueryError(`om.find's exact is true or false, and got ${JSON.stringify(f.exact)}`);
1270
+ const top = within ? byRef(p, within) : p.root;
1271
+ if (!top) throw new QueryError(`${within} is not a ref the page has now: read the page again (om.snapshot())`);
1272
+ const roles = texts(f.role, "role");
1273
+ const name = texts(f.name, "name", true)?.[0].toLowerCase();
1274
+ const words = texts(f.match, "match")?.map((w) => w.toLowerCase());
1275
+ const out = [];
1276
+ for (const n of nodes(top)) {
1277
+ if (n === top && within) continue;
1278
+ if (roles && !roles.includes(n.role) && !roles.includes(wordOf(n))) continue;
1279
+ if (name !== void 0 && !(f.exact ? (n.name ?? "").toLowerCase() === name : (n.name ?? "").toLowerCase().includes(name))) continue;
1280
+ if (words && !words.some((w) => line(n).toLowerCase().includes(w))) continue;
1281
+ out.push(projectItem(n));
1282
+ }
1283
+ return out;
1284
+ }
1285
+ /** Direct rows of this table, skipping any nested tables inside its cells. */
1286
+ function ownRows(t) {
1287
+ const out = [];
1288
+ const walk = (n) => {
1289
+ for (const c of n.children ?? []) if (c.role === "row") out.push(c);
1290
+ else if (!TABLE_ROLES.has(c.role)) walk(c);
1291
+ };
1292
+ walk(t);
1293
+ return out;
1294
+ }
1295
+ /** A table as data: its columns, and a row each with its cells' words and what in it can be acted on. */
1296
+ function extractTable(p, ref) {
1297
+ const t = byRef(p, ref);
1298
+ if (!t) throw new QueryError(`${ref} is not a ref the page has now: read the page again (om.snapshot())`);
1299
+ if (!TABLE_ROLES.has(t.role)) throw new QueryError(`${ref} is a ${t.role}, not a table: om.find({ role: 'table' }) lists the page's tables`);
1300
+ const rows = ownRows(t);
1301
+ const cellsOf = (r) => (r.children ?? []).filter((c) => CELLS.has(c.role));
1302
+ const head = rows.find((r) => cellsOf(r).some((c) => c.role === "columnheader"));
1303
+ return {
1304
+ columns: head ? cellsOf(head).map((c) => nodeText(c, true)) : [],
1305
+ rows: rows.filter((r) => r !== head).map((r) => ({
1306
+ ...r.ref ? { ref: r.ref } : {},
1307
+ cells: cellsOf(r).map((c) => nodeText(c, true)),
1308
+ controls: [...nodes(r)].filter((n) => n !== r && n.ref && n.role !== "text" && !CELLS.has(n.role)).map(projectItem)
1309
+ }))
1310
+ };
1311
+ }
1312
+ const ID_CHAR = /[A-Za-z0-9_$]/;
1313
+ const REGEX_BEFORE_KW = /* @__PURE__ */ new Set([
1314
+ "return",
1315
+ "case",
1316
+ "throw",
1317
+ "typeof",
1318
+ "void",
1319
+ "delete",
1320
+ "in",
1321
+ "of",
1322
+ "await",
1323
+ "yield",
1324
+ "new",
1325
+ "else",
1326
+ "do"
1327
+ ]);
1328
+ const REGEX_BEFORE_CH = /* @__PURE__ */ new Set([
1329
+ "(",
1330
+ "[",
1331
+ "{",
1332
+ ",",
1333
+ ";",
1334
+ ":",
1335
+ "?",
1336
+ "=",
1337
+ "!",
1338
+ "&",
1339
+ "|",
1340
+ "^",
1341
+ "~",
1342
+ "+",
1343
+ "-",
1344
+ "*",
1345
+ "%",
1346
+ "<",
1347
+ ">"
1348
+ ]);
1349
+ /**
1350
+ * Rewrite top-level lexical declarations (`const`, and `let` when targeting `var`) at nesting depth 0 so consecutive
1351
+ * REPL scripts can redeclare temporary names without failing on `Identifier '...' has already been declared`, while
1352
+ * leaving block/loop/function declarations, strings, templates, comments and regex literals untouched.
1353
+ */
1354
+ function relaxTopDecl(code, target = "let", reserved = /* @__PURE__ */ new Set()) {
1355
+ const out = [];
1356
+ let depth = 0;
1357
+ const tplBraces = [];
1358
+ let lastWord = "";
1359
+ let lastNonWs = "";
1360
+ let i = 0;
1361
+ const n = code.length;
1362
+ while (i < n) {
1363
+ const ch = code[i];
1364
+ if (ch === "/" && code[i + 1] === "/") {
1365
+ const start = i;
1366
+ i += 2;
1367
+ while (i < n && code[i] !== "\n") i++;
1368
+ out.push(code.slice(start, i));
1369
+ continue;
1370
+ }
1371
+ if (ch === "/" && code[i + 1] === "*") {
1372
+ const start = i;
1373
+ i += 2;
1374
+ while (i < n && !(code[i] === "*" && code[i + 1] === "/")) i++;
1375
+ i = Math.min(n, i + 2);
1376
+ out.push(code.slice(start, i));
1377
+ continue;
1378
+ }
1379
+ if (ch === "'" || ch === "\"") {
1380
+ const start = i;
1381
+ const quote = ch;
1382
+ i++;
1383
+ while (i < n && code[i] !== quote) {
1384
+ if (code[i] === "\\") i++;
1385
+ i++;
1386
+ }
1387
+ if (i < n) i++;
1388
+ out.push(code.slice(start, i));
1389
+ lastWord = "";
1390
+ lastNonWs = quote;
1391
+ continue;
1392
+ }
1393
+ if (ch === "`") {
1394
+ const start = i;
1395
+ i++;
1396
+ while (i < n) {
1397
+ if (code[i] === "\\") {
1398
+ i += 2;
1399
+ continue;
1400
+ }
1401
+ if (code[i] === "`") {
1402
+ i++;
1403
+ break;
1404
+ }
1405
+ if (code[i] === "$" && code[i + 1] === "{") {
1406
+ i += 2;
1407
+ tplBraces.push(depth);
1408
+ depth++;
1409
+ break;
1410
+ }
1411
+ i++;
1412
+ }
1413
+ out.push(code.slice(start, i));
1414
+ lastWord = "";
1415
+ lastNonWs = code[i - 1] ?? "`";
1416
+ continue;
1417
+ }
1418
+ if (ch === "/" && (!lastNonWs || REGEX_BEFORE_CH.has(lastNonWs) || REGEX_BEFORE_KW.has(lastWord))) {
1419
+ const start = i;
1420
+ i++;
1421
+ let inClass = false;
1422
+ while (i < n && code[i] !== "\n") {
1423
+ if (code[i] === "\\") {
1424
+ i += 2;
1425
+ continue;
1426
+ }
1427
+ if (code[i] === "[") inClass = true;
1428
+ else if (code[i] === "]") inClass = false;
1429
+ else if (code[i] === "/" && !inClass) {
1430
+ i++;
1431
+ while (i < n && /[a-z]/i.test(code[i])) i++;
1432
+ break;
1433
+ }
1434
+ i++;
1435
+ }
1436
+ out.push(code.slice(start, i));
1437
+ lastWord = "";
1438
+ lastNonWs = "/";
1439
+ continue;
1440
+ }
1441
+ if (ch === "}" && tplBraces.length && depth - 1 === tplBraces[tplBraces.length - 1]) {
1442
+ tplBraces.pop();
1443
+ depth--;
1444
+ const start = i;
1445
+ i++;
1446
+ while (i < n) {
1447
+ if (code[i] === "\\") {
1448
+ i += 2;
1449
+ continue;
1450
+ }
1451
+ if (code[i] === "`") {
1452
+ i++;
1453
+ break;
1454
+ }
1455
+ if (code[i] === "$" && code[i + 1] === "{") {
1456
+ i += 2;
1457
+ tplBraces.push(depth);
1458
+ depth++;
1459
+ break;
1460
+ }
1461
+ i++;
1462
+ }
1463
+ out.push(code.slice(start, i));
1464
+ lastWord = "";
1465
+ lastNonWs = code[i - 1] ?? "`";
1466
+ continue;
1467
+ }
1468
+ if (ch === "{" || ch === "(" || ch === "[") {
1469
+ depth++;
1470
+ out.push(ch);
1471
+ lastWord = "";
1472
+ lastNonWs = ch;
1473
+ i++;
1474
+ continue;
1475
+ }
1476
+ if (ch === "}" || ch === ")" || ch === "]") {
1477
+ if (depth > 0) depth--;
1478
+ out.push(ch);
1479
+ lastWord = "";
1480
+ lastNonWs = ch;
1481
+ i++;
1482
+ continue;
1483
+ }
1484
+ if (ID_CHAR.test(ch) && !/[0-9]/.test(ch)) {
1485
+ const start = i;
1486
+ while (i < n && ID_CHAR.test(code[i])) i++;
1487
+ const word = code.slice(start, i);
1488
+ if (depth === 0 && lastNonWs !== "." && (word === "const" || target === "var" && word === "let")) {
1489
+ let j = i;
1490
+ while (j < n && /\s/.test(code[j])) j++;
1491
+ const next = code[j] ?? "";
1492
+ if (j > i && (next === "{" || next === "[" || ID_CHAR.test(next) && !/[0-9]/.test(next))) {
1493
+ let nextWord = "";
1494
+ if (ID_CHAR.test(next)) {
1495
+ let k = j;
1496
+ while (k < n && ID_CHAR.test(code[k])) k++;
1497
+ nextWord = code.slice(j, k);
1498
+ }
1499
+ if (!nextWord || !reserved.has(nextWord)) {
1500
+ out.push(target);
1501
+ lastWord = target;
1502
+ lastNonWs = target[target.length - 1];
1503
+ continue;
1504
+ }
1505
+ }
1506
+ }
1507
+ out.push(word);
1508
+ lastWord = word;
1509
+ lastNonWs = word[word.length - 1];
1510
+ continue;
1511
+ }
1512
+ out.push(ch);
1513
+ if (!/\s/.test(ch)) {
1514
+ lastWord = "";
1515
+ lastNonWs = ch;
1516
+ }
1517
+ i++;
1518
+ }
1519
+ return out.join("");
1520
+ }
1521
+ // ../core/src/vocabulary.ts
1522
+ /**
1523
+ * The projection's vocabulary: the single source of truth for every fixed value
1524
+ * a reader of the page reads or emits. The readers import these, and
1525
+ * docs.test.ts fails if docs/semantic-projection.md or docs/guidelines.md
1526
+ * disagree with them. Change a value here and the docs must follow.
1527
+ */
1528
+ /** Marks an element as a node with a stable id. */
1529
+ const ID_ATTRIBUTE = "data-agentom-id";
1530
+ const STATE_ATTRIBUTE = "data-agentom-state";
1531
+ /** The states a screen declares; others are reported and left out. */
1532
+ const SCREEN_STATES = [
1533
+ "loading",
1534
+ "ready",
1535
+ "error"
1536
+ ];
1537
+ /** `safe` is the default and is never emitted. */
1538
+ const RISK_LEVELS = [
1539
+ "safe",
1540
+ "sensitive",
1541
+ "destructive"
1542
+ ];
1543
+ /** The only valid data-agentom-confirmation value (projected as confirmationRequired: true). */
1544
+ const CONFIRMATION_VALUES = ["required"];
1545
+ /** autocomplete tokens that mark a field as secret (https://html.spec.whatwg.org/#autofill). */
1546
+ const SECRET_AUTOCOMPLETE_TOKENS = [
1547
+ "current-password",
1548
+ "new-password",
1549
+ "one-time-code",
1550
+ "cc-number",
1551
+ "cc-csc",
1552
+ "cc-exp",
1553
+ "cc-exp-month",
1554
+ "cc-exp-year"
1555
+ ];
1556
+ // ../core/src/walk/merge.ts
1557
+ /** Roles a person acts on: a pointer cursor on one says nothing new. */
1558
+ const INTERACTIVE = /* @__PURE__ */ new Set([
1559
+ "button",
1560
+ "link",
1561
+ "textbox",
1562
+ "searchbox",
1563
+ "combobox",
1564
+ "checkbox",
1565
+ "radio",
1566
+ "switch",
1567
+ "tab",
1568
+ "menuitem",
1569
+ "menuitemcheckbox",
1570
+ "menuitemradio",
1571
+ "option",
1572
+ "slider",
1573
+ "spinbutton",
1574
+ "treeitem",
1575
+ "listbox",
1576
+ "ListBoxOption",
1577
+ "MenuListOption",
1578
+ "PopUpButton",
1579
+ "ToggleButton"
1580
+ ]);
1581
+ /** Wrappers that say nothing of their own: folded away unless the app or the DOM gives them something. */
1582
+ const FOLD = /* @__PURE__ */ new Set([
1583
+ "generic",
1584
+ "none",
1585
+ "paragraph",
1586
+ "LabelText",
1587
+ "Section",
1588
+ "emphasis",
1589
+ "strong",
1590
+ "code",
1591
+ "time",
1592
+ "abbr",
1593
+ "mark",
1594
+ "subscript",
1595
+ "superscript",
1596
+ "Pre",
1597
+ "Div",
1598
+ "MenuListPopup",
1599
+ "Canvas",
1600
+ "SvgRoot",
1601
+ "group",
1602
+ "presentation",
1603
+ "Iframe",
1604
+ "ruby"
1605
+ ]);
1606
+ /** Roles of a field whose value is what it holds: an editable region with one holds its text as its value, not as text inside. */
1607
+ const FIELD_ROLES = /* @__PURE__ */ new Set([
1608
+ "textbox",
1609
+ "searchbox",
1610
+ "combobox"
1611
+ ]);
1612
+ /** Chrome's roles for a table it judged laid out, not data. */
1613
+ const LAYOUT_TABLE = /* @__PURE__ */ new Set([
1614
+ "LayoutTable",
1615
+ "LayoutTableRow",
1616
+ "LayoutTableCell"
1617
+ ]);
1618
+ /** Attributes that name an element whatever it holds. */
1619
+ const NAMING = [
1620
+ "aria-label",
1621
+ "aria-labelledby",
1622
+ "title"
1623
+ ];
1624
+ /** Ignored by Chrome only for having nothing to say: such an element is kept when the DOM gives it something. */
1625
+ const UNINTERESTING = /* @__PURE__ */ new Set(["uninteresting", "presentationalRole"]);
1626
+ /** Properties kept as states when true, and how each is named. */
1627
+ const TRUE_STATES = {
1628
+ focused: "focused",
1629
+ disabled: "disabled",
1630
+ required: "required",
1631
+ readonly: "readonly",
1632
+ modal: "modal",
1633
+ multiselectable: "multiselectable",
1634
+ busy: "busy"
1635
+ };
1636
+ /** Properties whose every value says something (false too: a box not checked, a section collapsed). */
1637
+ const ANY_STATES = /* @__PURE__ */ new Set([
1638
+ "checked",
1639
+ "expanded",
1640
+ "pressed"
1641
+ ]);
1642
+ /** States that would tell a secret: whether a secret choice is chosen. */
1643
+ const SECRET_STATES = [
1644
+ "checked",
1645
+ "selected",
1646
+ "pressed",
1647
+ "valuetext",
1648
+ "valuemin",
1649
+ "valuemax"
1650
+ ];
1651
+ const FIELD_TAGS = /* @__PURE__ */ new Set([
1652
+ "INPUT",
1653
+ "TEXTAREA",
1654
+ "SELECT"
1655
+ ]);
1656
+ const SECRET_TOKENS = new Set(SECRET_AUTOCOMPLETE_TOKENS);
1657
+ const RISKS = new Set(RISK_LEVELS.filter((r) => r !== "safe"));
1658
+ const ANY_RISK = new Set(RISK_LEVELS);
1659
+ const STATES = new Set(SCREEN_STATES);
1660
+ /** aria-current's values that say something (`false` is the default). */
1661
+ const CURRENT = /* @__PURE__ */ new Set([
1662
+ "page",
1663
+ "step",
1664
+ "location",
1665
+ "date",
1666
+ "time",
1667
+ "true"
1668
+ ]);
1669
+ const CONFIRM = new Set(CONFIRMATION_VALUES);
1670
+ /** A secret shorter than this isn't searched for in other text (it would match by chance); its field's own value is still left out. */
1671
+ const SCRUB_MIN = 3;
1672
+ const squash$1 = (s) => s.replace(/\s+/g, " ").trim();
1673
+ /** What an element says of itself, which a name or description can be built from. */
1674
+ const SAYS = [
1675
+ "aria-label",
1676
+ "title",
1677
+ "alt",
1678
+ "placeholder",
1679
+ "aria-description"
1680
+ ];
1681
+ /**
1682
+ * A text with each of these taken out where it stands as words of its own (not inside a longer word), longest first,
1683
+ * but only as often as the text holds it beyond what `shown` (what the same elements show that isn't kept out) holds:
1684
+ * a word a person sees in the name stays, though a kept-out part says it too (an ignored icon titled "New" beside the
1685
+ * word New). Worked out only when a piece is in the text.
1686
+ */
1687
+ function without(s, pieces, shown) {
1688
+ let out = s;
1689
+ let seen;
1690
+ for (const p of [...new Set(pieces)].sort((a, b) => b.length - a.length)) {
1691
+ const escaped = p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1692
+ const word = () => new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "gu");
1693
+ const here = out.match(word())?.length ?? 0;
1694
+ if (!here) continue;
1695
+ seen ??= shown();
1696
+ let extra = here - Math.max(0, ...seen.map((t) => t.match(word())?.length ?? 0));
1697
+ if (extra > 0) out = out.replace(word(), (m) => extra-- > 0 ? " " : m);
1698
+ }
1699
+ return squash$1(out);
1700
+ }
1701
+ const str = (v) => v === void 0 || v === null ? "" : String(v);
1702
+ /** What these elements show that isn't kept out, joined both ways Chrome joins parts (inline ones with nothing between, blocks with a space). */
1703
+ const keptInOf = (dom, sources) => {
1704
+ const parts = sources.flatMap((k) => dom.keptIn(k));
1705
+ return [squash$1(parts.join("")), squash$1(parts.join(" "))];
1706
+ };
1707
+ /** The DOM, indexed: each element's tag, attributes, parent, own cursor and display, and what it holds. */
1708
+ var Dom = class {
1709
+ index = /* @__PURE__ */ new Map();
1710
+ backend = [];
1711
+ tag = [];
1712
+ attrs = [];
1713
+ parent = [];
1714
+ mainLength;
1715
+ cursor = [];
1716
+ display = [];
1717
+ input = /* @__PURE__ */ new Map();
1718
+ chosen = /* @__PURE__ */ new Set();
1719
+ /** kept out: data-agentom-ignore, or text the app redacts */
1720
+ dropped = [];
1721
+ secret = [];
1722
+ /** a secret field for a credential: a password field, or one whose autocomplete says it takes one */
1723
+ credential = [];
1724
+ /** a choice whose being chosen is a secret field's value (an option of a secret drop-down): listed, never said to be chosen */
1725
+ secretChoice = [];
1726
+ /** inside data-agentom-redact: its text is kept out, the fields in it are secret */
1727
+ redacted = [];
1728
+ url;
1729
+ title;
1730
+ /** each element's children, in order */
1731
+ children = /* @__PURE__ */ new Map();
1732
+ /** a text node's text */
1733
+ text = /* @__PURE__ */ new Map();
1734
+ /** what's kept out at or under each element, worked out when first asked */
1735
+ keptOutUnder = /* @__PURE__ */ new Map();
1736
+ /** the elements by their id attribute, made when first asked */
1737
+ byId;
1738
+ /** the labels by the id their for attribute names, made when first asked */
1739
+ labelsFor;
1740
+ /** whether anything on the page is kept out: most pages keep nothing out, and need no looking */
1741
+ anyKeptOut = false;
1742
+ constructor(snapshot) {
1743
+ const s = snapshot.strings;
1744
+ const top = snapshot.documents[0];
1745
+ this.url = s[top.documentURL] ?? "";
1746
+ this.title = s[top.title] ?? "";
1747
+ this.mainLength = top.nodes.backendNodeId.length;
1748
+ const isEditableAttr = (a) => {
1749
+ const v = a.get("contenteditable");
1750
+ return v !== void 0 && v.toLowerCase() !== "false";
1751
+ };
1752
+ let offset = 0;
1753
+ for (const doc of snapshot.documents) {
1754
+ const n = doc.nodes;
1755
+ const len = n.backendNodeId.length;
1756
+ for (const rare of [n.inputValue, n.textValue]) rare?.index.forEach((i, k) => this.input.set(offset + i, s[rare.value[k]] ?? ""));
1757
+ n.optionSelected?.index.forEach((i) => this.chosen.add(offset + i));
1758
+ n.nodeValue?.forEach((v, i) => {
1759
+ if (v >= 0 && s[n.nodeName[i]] === "#text") this.text.set(offset + i, s[v] ?? "");
1760
+ });
1761
+ for (let i = 0; i < len; i++) {
1762
+ const gi = offset + i;
1763
+ const bid = n.backendNodeId[i];
1764
+ this.backend[gi] = bid;
1765
+ const p = n.parentIndex[i];
1766
+ this.parent[gi] = p >= 0 ? offset + p : -1;
1767
+ this.index.set(bid, gi);
1768
+ this.tag[gi] = (s[n.nodeName[i]] ?? "").toUpperCase();
1769
+ const a = /* @__PURE__ */ new Map();
1770
+ const flat = n.attributes[i] ?? [];
1771
+ for (let k = 0; k + 1 < flat.length; k += 2) a.set(s[flat[k]].toLowerCase(), s[flat[k + 1]] ?? "");
1772
+ this.attrs[gi] = a;
1773
+ }
1774
+ doc.layout.nodeIndex.forEach((i, k) => {
1775
+ this.cursor[offset + i] = s[doc.layout.styles[k][0]];
1776
+ this.display[offset + i] = s[doc.layout.styles[k][1]];
1777
+ });
1778
+ offset += len;
1779
+ }
1780
+ this.parent.forEach((p, i) => {
1781
+ if (p >= 0) (this.children.get(p) ?? this.children.set(p, []).get(p)).push(i);
1782
+ });
1783
+ const redacted = this.redacted;
1784
+ const ignored = [];
1785
+ const holdsField = [];
1786
+ for (let i = 0; i < this.tag.length; i++) if (FIELD_TAGS.has(this.tag[i]) || isEditableAttr(this.attrs[i])) for (let p = i; p >= 0 && !holdsField[p]; p = this.parent[p]) holdsField[p] = true;
1787
+ for (let i = 0; i < this.tag.length; i++) {
1788
+ const p = this.parent[i];
1789
+ const a = this.attrs[i];
1790
+ ignored[i] = p >= 0 && ignored[p] || a.has("data-agentom-ignore");
1791
+ redacted[i] = p >= 0 && redacted[p] || a.has("data-agentom-redact");
1792
+ const redactsText = a.has("data-agentom-redact") && !holdsField[i];
1793
+ this.dropped[i] = ignored[i] || redactsText || p >= 0 && this.dropped[p];
1794
+ if (this.dropped[i]) this.anyKeptOut = true;
1795
+ const tag = this.tag[i];
1796
+ const tokens = (a.get("autocomplete") ?? "").toLowerCase().split(/\s+/);
1797
+ const field = FIELD_TAGS.has(tag) || isEditableAttr(a);
1798
+ const choice = tag === "OPTION" || tag === "OPTGROUP" || [
1799
+ "option",
1800
+ "checkbox",
1801
+ "radio",
1802
+ "switch",
1803
+ "menuitemcheckbox",
1804
+ "menuitemradio"
1805
+ ].includes(a.get("role") ?? "");
1806
+ this.credential[i] = tag === "INPUT" && (a.get("type") ?? "").toLowerCase() === "password" || FIELD_TAGS.has(tag) && tokens.some((t) => SECRET_TOKENS.has(t));
1807
+ this.secret[i] = field && redacted[i] || this.credential[i];
1808
+ this.secretChoice[i] = choice && redacted[i] || (tag === "OPTION" || tag === "OPTGROUP") && p >= 0 && (this.secret[p] || this.secretChoice[p]);
1809
+ }
1810
+ }
1811
+ /** What the page declares of itself: the first element in the document with each attribute. */
1812
+ context(warn) {
1813
+ let screen;
1814
+ let state;
1815
+ for (let i = 0; i < this.mainLength && (screen === void 0 || state === void 0); i++) {
1816
+ if (this.dropped[i]) continue;
1817
+ const a = this.attrs[i];
1818
+ if (screen === void 0 && a.has("data-agentom-screen")) screen = a.get("data-agentom-screen").trim() || void 0;
1819
+ if (state === void 0 && a.has("data-agentom-state")) {
1820
+ const v = a.get(STATE_ATTRIBUTE).trim();
1821
+ if (STATES.has(v)) state = v;
1822
+ else {
1823
+ state = "";
1824
+ warn({
1825
+ code: "invalid-value",
1826
+ target: this.ref(i),
1827
+ field: STATE_ATTRIBUTE,
1828
+ message: `${STATE_ATTRIBUTE}="${v}" isn't one of ${SCREEN_STATES.join(", ")}`
1829
+ });
1830
+ }
1831
+ }
1832
+ }
1833
+ const out = {
1834
+ ...screen ? { screen } : {},
1835
+ ...state ? { state } : {}
1836
+ };
1837
+ return Object.keys(out).length ? out : void 0;
1838
+ }
1839
+ /** Every problem with the app's metadata, on any element of the page that isn't kept out. */
1840
+ warnings() {
1841
+ const out = [];
1842
+ const ids = /* @__PURE__ */ new Map();
1843
+ for (let i = 0; i < this.tag.length; i++) {
1844
+ if (this.dropped[i]) continue;
1845
+ const id = this.attrs[i].get(ID_ATTRIBUTE)?.trim();
1846
+ if (id) ids.set(id, (ids.get(id) ?? 0) + 1);
1847
+ }
1848
+ const reported = /* @__PURE__ */ new Set();
1849
+ for (let i = 0; i < this.tag.length; i++) {
1850
+ if (this.dropped[i]) continue;
1851
+ const a = this.attrs[i];
1852
+ const target = this.ref(i);
1853
+ const id = a.get(ID_ATTRIBUTE)?.trim();
1854
+ if (id && (ids.get(id) ?? 0) > 1 && !reported.has(id)) {
1855
+ reported.add(id);
1856
+ out.push({
1857
+ code: "duplicate-id",
1858
+ target,
1859
+ field: ID_ATTRIBUTE,
1860
+ message: `${ID_ATTRIBUTE}="${id}" is on ${ids.get(id)} elements`
1861
+ });
1862
+ }
1863
+ const risk = a.get("data-agentom-risk")?.trim();
1864
+ if (risk !== void 0 && !ANY_RISK.has(risk)) out.push({
1865
+ code: "invalid-value",
1866
+ target,
1867
+ field: "data-agentom-risk",
1868
+ message: `data-agentom-risk="${risk}" isn't one of ${RISK_LEVELS.join(", ")}`
1869
+ });
1870
+ const confirmation = a.get("data-agentom-confirmation")?.trim();
1871
+ if (confirmation !== void 0 && !CONFIRM.has(confirmation)) out.push({
1872
+ code: "invalid-value",
1873
+ target,
1874
+ field: "data-agentom-confirmation",
1875
+ message: `data-agentom-confirmation="${confirmation}" isn't ${CONFIRMATION_VALUES.join(" or ")}`
1876
+ });
1877
+ for (const r of (a.get("data-agentom-requires") ?? "").split(/\s+/).filter(Boolean)) if (!ids.has(r)) out.push({
1878
+ code: "unresolved-requirement",
1879
+ target,
1880
+ field: "data-agentom-requires",
1881
+ message: `data-agentom-requires names "${r}", which no element on the page has as its ${ID_ATTRIBUTE}`
1882
+ });
1883
+ }
1884
+ return out;
1885
+ }
1886
+ /** An element's ref: Chrome's DOM node id. */
1887
+ ref(i) {
1888
+ return `e${this.backend[i]}`;
1889
+ }
1890
+ /** Whether a secret field holds something: typed text, or a chosen option of a drop-down. */
1891
+ holds(i) {
1892
+ if ((this.input.get(i) ?? "") !== "") return true;
1893
+ if (this.tag[i] !== "SELECT") return false;
1894
+ for (const c of this.chosen) for (let p = this.parent[c]; p >= 0; p = this.parent[p]) if (p === i) return true;
1895
+ return false;
1896
+ }
1897
+ /** What a nameless control's markup calls it (see OmNode.hint): looked for in it and the first few elements inside it. */
1898
+ hint(i) {
1899
+ const queue = [i];
1900
+ const words = (v) => v.replace(/^#/, "").replace(/^(?:icon|ico|svg)[-_]/, "").replace(/\.[a-z0-9]+$/, "");
1901
+ let own;
1902
+ for (let seen = 0; queue.length && seen < HINT_SCAN; seen++) {
1903
+ const k = queue.shift();
1904
+ const a = this.attrs[k];
1905
+ for (const t of TOOLTIP) {
1906
+ const v = a.get(t)?.trim();
1907
+ if (v) return v;
1908
+ }
1909
+ for (const t of TEST_ID) {
1910
+ const v = a.get(t)?.trim();
1911
+ if (v) return words(v);
1912
+ }
1913
+ for (const c of (a.get("class") ?? "").split(/\s+/)) {
1914
+ const m = ICON_CLASS.exec(c);
1915
+ if (m && !ICON_STYLE.test(m[1])) return m[1];
1916
+ }
1917
+ const use = this.tag[k].toLowerCase() === "use" ? a.get("href") ?? a.get("xlink:href") : void 0;
1918
+ if (use && use.includes("#")) return words(use.slice(use.indexOf("#")));
1919
+ const src = this.tag[k] === "IMG" ? a.get("src") : void 0;
1920
+ if (src && !src.startsWith("data:")) return words(src.split(/[?#]/)[0].split("/").pop() ?? "");
1921
+ if (k === i) {
1922
+ const id = a.get("id") ?? a.get("name");
1923
+ if (id && WORDY_ID.test(id)) own = id;
1924
+ }
1925
+ queue.push(...(this.children.get(k) ?? []).filter((c) => !this.dropped[c]));
1926
+ }
1927
+ return own;
1928
+ }
1929
+ /** A link's address, as the page resolves it. */
1930
+ href(i) {
1931
+ const h = this.attrs[i].get("href");
1932
+ if (!h) return void 0;
1933
+ try {
1934
+ return new URL(h, this.url).href;
1935
+ } catch {
1936
+ return h;
1937
+ }
1938
+ }
1939
+ /** Whether it's a tab stop of its own: a tabindex of 0 or more. */
1940
+ tabStop(i) {
1941
+ const t = this.attrs[i].get("tabindex")?.trim();
1942
+ return t !== void 0 && t !== "" && Number.isInteger(Number(t)) && Number(t) >= 0;
1943
+ }
1944
+ /** Whether its text is edited in place (contenteditable) and nothing around it is: the region's own root. */
1945
+ editableRoot(i) {
1946
+ const on = (k) => {
1947
+ const v = this.attrs[k].get("contenteditable")?.trim().toLowerCase();
1948
+ return v === "" || v === "true" || v === "plaintext-only";
1949
+ };
1950
+ if (!on(i)) return false;
1951
+ for (let p = this.parent[i]; p >= 0; p = this.parent[p]) if (on(p)) return false;
1952
+ return true;
1953
+ }
1954
+ /** The text of each part under an element that's hidden from readers (aria-hidden): a widget's placeholder in an editor. */
1955
+ hiddenTexts(i) {
1956
+ const out = [];
1957
+ const textOf = (k) => (this.text.get(k) ?? "") + (this.children.get(k) ?? []).map(textOf).join("");
1958
+ const visit = (k) => {
1959
+ for (const c of this.children.get(k) ?? []) if (this.attrs[c]?.get("aria-hidden")?.trim().toLowerCase() === "true") {
1960
+ const t = textOf(c);
1961
+ if (t) out.push(t);
1962
+ } else visit(c);
1963
+ };
1964
+ visit(i);
1965
+ return out;
1966
+ }
1967
+ /** Whether it sets a pointer cursor of its own: its parent's isn't one. */
1968
+ ownPointer(i) {
1969
+ if (this.cursor[i] !== "pointer") return false;
1970
+ for (let p = this.parent[i]; p >= 0; p = this.parent[p]) if (this.cursor[p] !== void 0) return this.cursor[p] !== "pointer";
1971
+ return true;
1972
+ }
1973
+ /** Whether it sits in a line of text (inline, or an inline-block, -flex or -grid box), not a block of its own. */
1974
+ inline(i) {
1975
+ return (this.display[i] ?? "inline").startsWith("inline") || this.display[i] === "contents";
1976
+ }
1977
+ /** Whether it's a table's cell (as laid out): its text is set apart from its neighbours' by a space, as Chrome sets it apart in a name. */
1978
+ cell(i) {
1979
+ return this.display[i] === "table-cell";
1980
+ }
1981
+ /**
1982
+ * The box of its own in a line (inline-block, -flex, -grid) a node is in, within its block; -1 for none. Text in
1983
+ * different boxes is set apart by a space, as Chrome sets it apart in a name and a person sees it: read from the DOM,
1984
+ * as Chrome's tree keeps some such boxes and not others.
1985
+ */
1986
+ boxOf(i) {
1987
+ for (let p = this.parent[i]; p >= 0; p = this.parent[p]) {
1988
+ if (this.display[p]?.startsWith("inline-")) return p;
1989
+ if (!this.inline(p)) return -1;
1990
+ }
1991
+ return -1;
1992
+ }
1993
+ /**
1994
+ * What's kept out (data-agentom-ignore, or redact on what holds no field) at or under an element: its text, and what
1995
+ * its elements say of themselves. A name or description Chrome built from it must not say it.
1996
+ */
1997
+ keptOut(i) {
1998
+ const known = this.keptOutUnder.get(i);
1999
+ if (known) return known;
2000
+ let out = [];
2001
+ if (this.dropped[i]) {
2002
+ const texts = [];
2003
+ const stack = [i];
2004
+ while (stack.length) {
2005
+ const k = stack.pop();
2006
+ const t = this.text.get(k);
2007
+ if (t !== void 0) texts.push(t);
2008
+ for (const a of SAYS) {
2009
+ const v = squash$1(this.attrs[k]?.get(a) ?? "");
2010
+ if (v) out.push(v);
2011
+ }
2012
+ const kids = this.children.get(k) ?? [];
2013
+ for (let c = kids.length - 1; c >= 0; c--) stack.push(kids[c]);
2014
+ }
2015
+ for (const whole of [texts.join(""), texts.join(" ")]) if (squash$1(whole)) out.push(squash$1(whole));
2016
+ for (const t of texts) if (squash$1(t).length >= SCRUB_MIN) out.push(squash$1(t));
2017
+ } else for (const c of this.children.get(i) ?? []) {
2018
+ const under = this.keptOut(c);
2019
+ if (under.length) out = out.length ? out.concat(under) : under;
2020
+ }
2021
+ this.keptOutUnder.set(i, out);
2022
+ return out;
2023
+ }
2024
+ /** The elements an id-reference attribute names (aria-labelledby, aria-describedby), that are on the page. */
2025
+ named(i, attribute) {
2026
+ const ids = (this.attrs[i].get(attribute) ?? "").split(/\s+/).filter(Boolean);
2027
+ if (!ids.length) return [];
2028
+ if (!this.byId) {
2029
+ this.byId = /* @__PURE__ */ new Map();
2030
+ for (let k = 0; k < this.tag.length; k++) {
2031
+ const id = this.attrs[k].get("id");
2032
+ if (id && !this.byId.has(id)) this.byId.set(id, k);
2033
+ }
2034
+ }
2035
+ return ids.map((id) => this.byId.get(id)).filter((k) => k !== void 0);
2036
+ }
2037
+ /**
2038
+ * What's kept out that an element's name could be built from, in the order Chrome names: the elements its
2039
+ * aria-labelledby names; none when its own aria-label names it (the author's words); else what's inside it and in
2040
+ * its labels.
2041
+ */
2042
+ keptOutOfName(i) {
2043
+ if (!this.anyKeptOut) return [];
2044
+ return this.nameSources(i).flatMap((k) => this.keptOut(k));
2045
+ }
2046
+ /** What the elements an element's name can be built from show that isn't kept out (see `without`), joined both ways. */
2047
+ keptInOfName(i) {
2048
+ return keptInOf(this, this.nameSources(i));
2049
+ }
2050
+ /**
2051
+ * What's at or under an element that isn't kept out: its text and what its elements say of themselves, in document
2052
+ * order.
2053
+ */
2054
+ keptIn(i) {
2055
+ const parts = [];
2056
+ const stack = [i];
2057
+ while (stack.length) {
2058
+ const k = stack.pop();
2059
+ if (this.dropped[k]) continue;
2060
+ const t = this.text.get(k);
2061
+ if (t !== void 0) parts.push(t);
2062
+ for (const a of SAYS) {
2063
+ const v = squash$1(this.attrs[k]?.get(a) ?? "");
2064
+ if (v) parts.push(v);
2065
+ }
2066
+ const kids = this.children.get(k) ?? [];
2067
+ for (let c = kids.length - 1; c >= 0; c--) stack.push(kids[c]);
2068
+ }
2069
+ return parts;
2070
+ }
2071
+ /** The elements an element's name can be built from, in the order Chrome names: what aria-labelledby names; none for an aria-label; else itself and its labels. */
2072
+ nameSources(i) {
2073
+ const by = this.named(i, "aria-labelledby");
2074
+ if (by.length) return by;
2075
+ if (this.attrs[i].get("aria-label")?.trim()) return [];
2076
+ const id = this.attrs[i].get("id");
2077
+ const labels = [];
2078
+ for (let p = this.parent[i]; p >= 0; p = this.parent[p]) if (this.tag[p] === "LABEL") labels.push(p);
2079
+ if (id && FIELD_TAGS.has(this.tag[i])) {
2080
+ if (!this.labelsFor) {
2081
+ this.labelsFor = /* @__PURE__ */ new Map();
2082
+ for (let k = 0; k < this.tag.length; k++) {
2083
+ const f = this.tag[k] === "LABEL" ? this.attrs[k].get("for") : void 0;
2084
+ if (f) (this.labelsFor.get(f) ?? this.labelsFor.set(f, []).get(f)).push(k);
2085
+ }
2086
+ }
2087
+ labels.push(...this.labelsFor.get(id) ?? []);
2088
+ }
2089
+ return [i, ...labels];
2090
+ }
2091
+ /** What's kept out that an element's description could be built from: the elements its aria-describedby names. */
2092
+ keptOutOfDescription(i) {
2093
+ if (!this.anyKeptOut) return [];
2094
+ return this.named(i, "aria-describedby").flatMap((k) => this.keptOut(k));
2095
+ }
2096
+ /** The elements not in the accessibility tree (by DOM node id) that carry an id or metadata, with what they carry. */
2097
+ holders(inTree) {
2098
+ const out = /* @__PURE__ */ new Map();
2099
+ for (let i = 0; i < this.tag.length; i++) {
2100
+ const tag = this.tag[i];
2101
+ if (this.dropped[i] || inTree.has(this.backend[i]) || !tag || tag.startsWith("#")) continue;
2102
+ const a = this.attrs[i];
2103
+ if (tag !== "TIME" && tag !== "DATA" && ![...a.keys()].some((k) => k.startsWith("data-agentom-"))) continue;
2104
+ const m = this.meta(i);
2105
+ if (m.id || m.meta) out.set(i, m);
2106
+ }
2107
+ return out;
2108
+ }
2109
+ /** Every secret field's value, longest first: what's searched for in all other text. */
2110
+ secrets() {
2111
+ const values = /* @__PURE__ */ new Set();
2112
+ for (const [i, v] of this.input) if (this.secret[i] && v.length >= SCRUB_MIN) values.add(v);
2113
+ return [...values].sort((a, b) => b.length - a.length);
2114
+ }
2115
+ meta(i) {
2116
+ const a = this.attrs[i];
2117
+ const meta = {};
2118
+ for (const k of [
2119
+ "kind",
2120
+ "desc",
2121
+ "value",
2122
+ "action",
2123
+ "purpose"
2124
+ ]) {
2125
+ const v = a.get(`data-agentom-${k}`)?.trim();
2126
+ if (v) meta[k] = v;
2127
+ }
2128
+ if (!meta.value) {
2129
+ const given = this.tag[i] === "TIME" ? a.get("datetime") : this.tag[i] === "DATA" ? a.get("value") : void 0;
2130
+ if (given?.trim()) meta.value = given.trim();
2131
+ }
2132
+ const risk = a.get("data-agentom-risk")?.trim();
2133
+ if (risk && RISKS.has(risk)) meta.risk = risk;
2134
+ if (CONFIRM.has(a.get("data-agentom-confirmation")?.trim() ?? "")) meta.confirm = true;
2135
+ const requires = [...new Set((a.get("data-agentom-requires") ?? "").split(/\s+/).filter(Boolean))];
2136
+ if (requires.length) meta.requires = requires;
2137
+ const reveals = [...new Set((a.get("data-agentom-reveals") ?? "").split(",").map((r) => r.trim()).filter(Boolean))];
2138
+ if (reveals.length) meta.reveals = reveals;
2139
+ const id = a.get(ID_ATTRIBUTE)?.trim();
2140
+ return {
2141
+ ...id ? { id } : {},
2142
+ ...Object.keys(meta).length ? { meta } : {}
2143
+ };
2144
+ }
2145
+ };
2146
+ /** An icon set's class names the icon it draws: lucide-trash-2, fa-pen, bi-x-lg, icon-close… (not a set's style or size classes). */
2147
+ const ICON_CLASS = /^(?:lucide|fa|fas|far|bi|icon|ti|ri|mdi|ph|hi|feather|octicon|glyphicon|material-icons|codicon)-([a-z0-9][a-z0-9-]*)$/;
2148
+ const ICON_STYLE = /^(?:solid|regular|light|thin|duotone|brands|sharp|fw|lg|xs|sm|xl|[0-9]+x|spin|pulse|inverse|outline|filled|rounded|small|large|button|wrapper|container)$/;
2149
+ /** An id or name written in words (add-row, deleteButton), not one a framework made up (_r_k_, base-ui-12, :r3:). */
2150
+ const WORDY_ID = /^[A-Za-z][a-z0-9]*(?:[A-Z][a-z0-9]+|[-_.][a-z][a-z0-9]*)+$|^[a-z]{3,}$/;
2151
+ const TEST_ID = [
2152
+ "data-testid",
2153
+ "data-test-id",
2154
+ "data-test",
2155
+ "data-cy",
2156
+ "data-qa",
2157
+ "data-icon"
2158
+ ];
2159
+ /** Where a tooltip library keeps a control's tooltip text: words the app wrote for people. */
2160
+ const TOOLTIP = [
2161
+ "data-tooltip",
2162
+ "data-tooltip-content",
2163
+ "data-tip",
2164
+ "data-title",
2165
+ "data-original-title",
2166
+ "data-bs-original-title"
2167
+ ];
2168
+ /** How many elements inside a control are looked at for its hint. */
2169
+ const HINT_SCAN = 40;
2170
+ /** Text between two nodes kept apart: what separates blocks. */
2171
+ const BREAK = Symbol("break");
2172
+ const isText = (x) => x !== BREAK && x.role === "text";
2173
+ /** The text a run of items shows, when it's text and nothing else (no element, no block apart). */
2174
+ const onlyText = (items) => {
2175
+ const inner = items.filter((x, k) => !(x === BREAK && (k === 0 || k === items.length - 1)));
2176
+ if (!inner.length || !inner.every(isText)) return void 0;
2177
+ return squash$1(inner.map((t) => t.raw).join("")) || void 0;
2178
+ };
2179
+ /** Adjacent text within one block merged; blocks kept apart; a text that only repeats the name of a field beside it (its label) left out. */
2180
+ function settle$2(items, name, apart) {
2181
+ const out = [];
2182
+ let run = "";
2183
+ let last;
2184
+ const flush = () => {
2185
+ const t = squash$1(run);
2186
+ run = "";
2187
+ last = void 0;
2188
+ if (t) out.push({
2189
+ role: "text",
2190
+ name: t
2191
+ });
2192
+ };
2193
+ for (const x of items) if (x === BREAK) flush();
2194
+ else if (isText(x)) {
2195
+ if (run && last && apart?.(last.at, x.at)) run += " ";
2196
+ run += x.raw;
2197
+ last = x;
2198
+ } else {
2199
+ flush();
2200
+ out.push(x);
2201
+ }
2202
+ flush();
2203
+ const own = name ? squash$1(name) : "";
2204
+ return out.filter((n, k) => {
2205
+ if (n.role !== "text") return true;
2206
+ const t = n.name;
2207
+ if (own && own.includes(t)) return false;
2208
+ return ![out[k - 1], out[k + 1]].filter((m) => m && m.role !== "text" && m.name).some((m) => squash$1(m.name).replace(/[:*]\s*$/, "") === t.replace(/[:*]\s*$/, ""));
2209
+ });
2210
+ }
2211
+ /** The order states are said in, whatever order the tree gave them: the same page reads the same however it was read. */
2212
+ const STATE_ORDER = [
2213
+ "focused",
2214
+ "disabled",
2215
+ "required",
2216
+ "readonly",
2217
+ "invalid",
2218
+ "checked",
2219
+ "selected",
2220
+ "pressed",
2221
+ "expanded",
2222
+ "haspopup",
2223
+ "modal",
2224
+ "multiselectable",
2225
+ "busy",
2226
+ "current",
2227
+ "level",
2228
+ "valuemin",
2229
+ "valuemax",
2230
+ "valuetext"
2231
+ ];
2232
+ function ordered(states) {
2233
+ const out = {};
2234
+ for (const k of STATE_ORDER) if (k in states) out[k] = states[k];
2235
+ for (const k of Object.keys(states)) if (!(k in out)) out[k] = states[k];
2236
+ return out;
2237
+ }
2238
+ /**
2239
+ * Merge a page's accessibility tree and DOM snapshot into its projection. `filled`: secrets the reader filled into the
2240
+ * page, taken out of everything as a secret field's value is.
2241
+ */
2242
+ function merge({ ax, dom: snapshot }, filled = []) {
2243
+ const dom = new Dom(snapshot);
2244
+ const byId = new Map(ax.map((n) => [n.nodeId, n]));
2245
+ const root = ax.find((n) => n.parentId === void 0) ?? ax[0];
2246
+ const refOf = /* @__PURE__ */ new Map();
2247
+ /** Whether two pieces of text are in different boxes of a line (a label beside an email), and so set apart. */
2248
+ const apart = (a, b) => dom.boxOf(a) !== dom.boxOf(b);
2249
+ const holders = dom.holders(new Set(ax.flatMap((n) => n.backendDOMNodeId !== void 0 ? [n.backendDOMNodeId] : [])));
2250
+ /** The element below `p`, nearest `p`, that is a holder around a DOM node, when there is one. */
2251
+ const holderOf = (k, p) => {
2252
+ if (k === void 0) return void 0;
2253
+ let found;
2254
+ for (let q = dom.parent[k]; q >= 0; q = dom.parent[q]) {
2255
+ if (q === p) return found;
2256
+ if (holders.has(q)) found = q;
2257
+ }
2258
+ };
2259
+ /** What a node holds, with each run of it inside one holder put in the holder's node. */
2260
+ const held = (items, p) => {
2261
+ if (!holders.size || p === void 0) return items;
2262
+ const out = [];
2263
+ let group = [];
2264
+ let current;
2265
+ const flush = () => {
2266
+ if (current === void 0) out.push(...group);
2267
+ else {
2268
+ const m = holders.get(current);
2269
+ const n = {
2270
+ role: "generic",
2271
+ ref: `e${dom.backend[current]}`,
2272
+ ...m.id ? { id: m.id } : {},
2273
+ ...m.meta ? { meta: m.meta } : {}
2274
+ };
2275
+ const only = m.meta?.value !== void 0 ? onlyText(group) : void 0;
2276
+ if (only) n.name = only;
2277
+ if (n.id) refOf.set(n.id, n.ref);
2278
+ const children = settle$2(group, n.name, apart);
2279
+ if (children.length) n.children = children;
2280
+ out.push(n);
2281
+ }
2282
+ group = [];
2283
+ };
2284
+ for (const x of items) {
2285
+ const h = x === BREAK ? current : holderOf(isText(x) ? x.at : x.ref ? dom.index.get(Number(x.ref.slice(1))) : void 0, p);
2286
+ if (h !== current) {
2287
+ flush();
2288
+ current = h;
2289
+ }
2290
+ group.push(x);
2291
+ }
2292
+ flush();
2293
+ return out;
2294
+ };
2295
+ const build = (node) => {
2296
+ if (!node) return [];
2297
+ const di = node.backendDOMNodeId !== void 0 ? dom.index.get(node.backendDOMNodeId) : void 0;
2298
+ if (di !== void 0 && dom.dropped[di]) return [];
2299
+ const layout = LAYOUT_TABLE.has(str(node.role?.value));
2300
+ const role = layout ? "generic" : str(node.role?.value);
2301
+ if (role === "InlineTextBox" || role === "ListMarker") return [];
2302
+ if (role === "LineBreak") return [BREAK];
2303
+ if (role === "StaticText") {
2304
+ if (di === void 0 || dom.redacted[di]) return [];
2305
+ const raw = str(node.name?.value);
2306
+ return raw ? [{
2307
+ role: "text",
2308
+ raw,
2309
+ at: di
2310
+ }] : [];
2311
+ }
2312
+ const editor = di !== void 0 && dom.editableRoot(di);
2313
+ const kids = di !== void 0 && (dom.tag[di] === "INPUT" || dom.tag[di] === "TEXTAREA" || editor && FIELD_ROLES.has(role)) ? [] : held((node.childIds ?? []).flatMap((id) => build(byId.get(id))), di);
2314
+ const given = di !== void 0 ? dom.meta(di) : {};
2315
+ const holdsControl = kids.some((k) => k !== BREAK && (INTERACTIVE.has(k.role) || k.clickable || k.focusable || k.editable));
2316
+ const pointer = di !== void 0 && dom.ownPointer(di) && !INTERACTIVE.has(role) && !holdsControl;
2317
+ const tabStop = di !== void 0 && FOLD.has(role) && dom.tabStop(di) && !holdsControl;
2318
+ const editable = di !== void 0 && !INTERACTIVE.has(role) && dom.editableRoot(di);
2319
+ const cell = di !== void 0 && dom.cell(di);
2320
+ const block = di === void 0 || !dom.inline(di) && !cell;
2321
+ const space = () => ({
2322
+ role: "text",
2323
+ raw: " ",
2324
+ at: di
2325
+ });
2326
+ const around = (items) => block ? [
2327
+ BREAK,
2328
+ ...items,
2329
+ BREAK
2330
+ ] : cell ? [
2331
+ space(),
2332
+ ...items,
2333
+ space()
2334
+ ] : items;
2335
+ const named = di !== void 0 && NAMING.some((a) => dom.attrs[di].has(a));
2336
+ if (layout && !named && di !== void 0 && !kids.some((k) => k !== BREAK)) {
2337
+ const t = squash$1(str(node.name?.value));
2338
+ if (t) return around([{
2339
+ role: "text",
2340
+ raw: t,
2341
+ at: di
2342
+ }]);
2343
+ }
2344
+ if (node.ignored && !((given.id || given.meta || pointer || tabStop || editable) && (node.ignoredReasons ?? []).every((r) => UNINTERESTING.has(r.name)))) return around(kids);
2345
+ let name = layout && !named ? "" : squash$1(str(node.name?.value));
2346
+ let description = squash$1(str(node.description?.value));
2347
+ if (di !== void 0 && role !== "RootWebArea") {
2348
+ if (name) name = without(name, dom.keptOutOfName(di), () => dom.keptInOfName(di));
2349
+ if (description) description = without(description, dom.keptOutOfDescription(di), () => keptInOf(dom, dom.named(di, "aria-describedby")));
2350
+ }
2351
+ const out = { role: node.ignored ? "generic" : role };
2352
+ if (node.backendDOMNodeId !== void 0) out.ref = `e${node.backendDOMNodeId}`;
2353
+ if (name) out.name = name;
2354
+ if (description) out.description = description;
2355
+ let value = str(node.value?.value);
2356
+ if (editor && value) {
2357
+ for (const t of dom.hiddenTexts(di)) {
2358
+ const at = value.indexOf(t);
2359
+ if (at >= 0) value = value.slice(0, at) + value.slice(at + t.length);
2360
+ }
2361
+ if (!value.trim()) value = "";
2362
+ }
2363
+ if (value !== "") out.value = value;
2364
+ const states = {};
2365
+ for (const p of node.properties ?? []) {
2366
+ const v = p.value?.value;
2367
+ if (typeof v === "boolean" && (ANY_STATES.has(p.name) || p.name === "selected")) {
2368
+ if (v || p.name !== "selected") states[p.name] = v;
2369
+ } else if (p.name in TRUE_STATES) {
2370
+ if (v === true || v === "true" || v === 1) states[TRUE_STATES[p.name]] = true;
2371
+ } else if (ANY_STATES.has(p.name)) {
2372
+ if (v !== void 0 && !(p.name === "pressed" && v === "false" && role !== "button" && role !== "ToggleButton")) states[p.name] = v === "true" ? true : v === "false" ? false : String(v);
2373
+ } else if (p.name === "selected") {
2374
+ if (v === true || v === "true") states.selected = true;
2375
+ } else if (p.name === "invalid") {
2376
+ if (v && v !== "false") states.invalid = v === "true" ? true : String(v);
2377
+ } else if (p.name === "level" || p.name === "valuemin" || p.name === "valuemax") {
2378
+ if (typeof v === "number") states[p.name] = v;
2379
+ } else if (p.name === "valuetext") {
2380
+ if (v) states.valuetext = String(v);
2381
+ } else if (p.name === "hasPopup") {
2382
+ if (v && v !== "false") states.haspopup = String(v);
2383
+ }
2384
+ }
2385
+ if (role === "link" && di !== void 0) {
2386
+ const href = dom.href(di);
2387
+ if (href) out.href = href;
2388
+ }
2389
+ const current = di !== void 0 ? dom.attrs[di].get("aria-current")?.trim() : void 0;
2390
+ if (current && CURRENT.has(current)) states.current = current === "true" ? true : current;
2391
+ if (Object.keys(states).length) out.states = ordered(states);
2392
+ if (pointer) out.clickable = true;
2393
+ if (tabStop) out.focusable = true;
2394
+ if (editable) out.editable = true;
2395
+ if (given.id) out.id = given.id;
2396
+ if (given.meta) out.meta = given.meta;
2397
+ if (di !== void 0 && (dom.secret[di] || dom.secretChoice[di])) {
2398
+ if (dom.secret[di]) out.secret = dom.holds(di) ? "filled" : "empty";
2399
+ if (dom.credential[di]) out.credential = true;
2400
+ delete out.value;
2401
+ for (const s of SECRET_STATES) if (out.states) delete out.states[s];
2402
+ if (out.states && !Object.keys(out.states).length) delete out.states;
2403
+ }
2404
+ if ((pointer || tabStop) && !editable && !out.name) {
2405
+ const shown = squash$1(kids.filter(isText).map((t) => t.raw).join(""));
2406
+ if (shown) out.name = shown;
2407
+ }
2408
+ if (!out.name && di !== void 0 && (INTERACTIVE.has(out.role) || out.clickable || out.focusable || out.editable)) {
2409
+ const hint = dom.hint(di);
2410
+ if (hint) out.hint = hint;
2411
+ }
2412
+ if (!out.name && out.meta?.value !== void 0) {
2413
+ const only = onlyText(kids);
2414
+ if (only) out.name = only;
2415
+ }
2416
+ const says = out.name || out.hint || out.description || out.value !== void 0 || out.states || out.clickable || out.focusable || out.editable || out.id || out.meta || out.secret || out.href;
2417
+ if (FOLD.has(out.role) && !says) return around(kids);
2418
+ if (out.id && out.ref) refOf.set(out.id, out.ref);
2419
+ const children = settle$2(kids, out.name, apart);
2420
+ if (children.length) out.children = children;
2421
+ return [out];
2422
+ };
2423
+ const top = build(root);
2424
+ const rootNode = top.length === 1 && top[0] !== BREAK && top[0].role === "RootWebArea" ? top[0] : {
2425
+ role: "RootWebArea",
2426
+ children: settle$2(top, void 0, apart)
2427
+ };
2428
+ rootNode.role = "document";
2429
+ delete rootNode.states;
2430
+ const resolve = (n) => {
2431
+ if (n.meta?.requires) n.meta.requires = n.meta.requires.map((id) => refOf.get(id) ?? id);
2432
+ n.children?.forEach(resolve);
2433
+ };
2434
+ resolve(rootNode);
2435
+ const secrets = [.../* @__PURE__ */ new Set([...dom.secrets(), ...filled.filter((v) => v.length >= SCRUB_MIN)])].sort((a, b) => b.length - a.length);
2436
+ scrub(rootNode, secrets);
2437
+ const warnings = dom.warnings();
2438
+ const context = dom.context((w) => warnings.push(w));
2439
+ if (secrets.length) {
2440
+ if (context?.screen) context.screen = withoutSecrets(context.screen, secrets);
2441
+ for (const w of warnings) w.message = withoutSecrets(w.message, secrets);
2442
+ }
2443
+ return {
2444
+ url: withoutSecrets(dom.url, secrets),
2445
+ title: withoutSecrets(dom.title, secrets),
2446
+ ...context ? { context } : {},
2447
+ root: rootNode,
2448
+ ...warnings.length ? { warnings } : {}
2449
+ };
2450
+ }
2451
+ /**
2452
+ * Every secret value taken out of every string the projection holds, in every form it takes there (core's view entry,
2453
+ * secretForms): a name can repeat what a field holds (a combobox named by its value, a label read back), a link can
2454
+ * carry it encoded.
2455
+ */
2456
+ function scrub(node, secrets) {
2457
+ if (!secrets.length) return;
2458
+ const clean = (s) => withoutSecrets(s, secrets);
2459
+ const walk = (n) => {
2460
+ if (n.name) n.name = clean(n.name);
2461
+ if (n.description) n.description = clean(n.description);
2462
+ if (n.hint) n.hint = clean(n.hint);
2463
+ if (n.id) n.id = clean(n.id);
2464
+ if (n.value !== void 0) n.value = clean(n.value);
2465
+ if (n.href) n.href = clean(n.href);
2466
+ if (n.states) {
2467
+ for (const [k, v] of Object.entries(n.states)) if (typeof v === "string") n.states[k] = clean(v);
2468
+ }
2469
+ if (n.meta) {
2470
+ for (const k of [
2471
+ "desc",
2472
+ "value",
2473
+ "action",
2474
+ "purpose",
2475
+ "kind"
2476
+ ]) if (n.meta[k]) n.meta[k] = clean(n.meta[k]);
2477
+ if (n.meta.reveals) n.meta.reveals = n.meta.reveals.map(clean);
2478
+ if (n.meta.requires) n.meta.requires = n.meta.requires.map(clean);
2479
+ }
2480
+ n.children?.forEach(walk);
2481
+ };
2482
+ walk(node);
2483
+ }
2484
+ // ../core/src/walk/raw.ts
2485
+ /** The computed styles read for every element drawn (the merge reads the first two; a change in any of them is a change). */
2486
+ const STYLES = [
2487
+ "cursor",
2488
+ "display",
2489
+ "visibility"
2490
+ ];
2491
+ // ../cdp-reader/src/read.ts
2492
+ const enabled = /* @__PURE__ */ new WeakSet();
2493
+ /** Enable Chrome's accessibility domain once per CDP session. */
2494
+ async function enableAccessibility(cdp) {
2495
+ if (enabled.has(cdp)) return;
2496
+ await cdp.send("Accessibility.enable");
2497
+ enabled.add(cdp);
2498
+ }
2499
+ /** Read a page as it is now. */
2500
+ async function readPage(cdp) {
2501
+ await enableAccessibility(cdp);
2502
+ const [{ nodes }, dom] = await Promise.all([cdp.send("Accessibility.getFullAXTree"), snapshot(cdp)]);
2503
+ return {
2504
+ ax: nodes,
2505
+ dom
2506
+ };
2507
+ }
2508
+ /** The page's DOM snapshot now. */
2509
+ async function snapshot(cdp) {
2510
+ return await cdp.send("DOMSnapshot.captureSnapshot", { computedStyles: [...STYLES] });
2511
+ }
2512
+ /** Read whole when the changed parts hold more than this share of the page. */
2513
+ const PARTIAL_SHARE = .3;
2514
+ /** …or when there are more changed parts than this. */
2515
+ const PARTIAL_PARTS = 50;
2516
+ const ELEMENT = 1;
2517
+ /** Attributes that name or describe another element by id. */
2518
+ const REFERS = ["aria-labelledby", "aria-describedby"];
2519
+ /** Form controls a label names when it holds them. */
2520
+ const LABELABLE = /* @__PURE__ */ new Set([
2521
+ "INPUT",
2522
+ "SELECT",
2523
+ "TEXTAREA",
2524
+ "BUTTON",
2525
+ "METER",
2526
+ "OUTPUT",
2527
+ "PROGRESS"
2528
+ ]);
2529
+ /** One page read again and again: whole the first time, then only what changed where it can. */
2530
+ var Reader = class {
2531
+ last;
2532
+ /** What the last read did. */
2533
+ lastRead;
2534
+ cdp;
2535
+ options;
2536
+ constructor(cdp, options = {}) {
2537
+ this.cdp = cdp;
2538
+ this.options = options;
2539
+ }
2540
+ /** The page's projection now. */
2541
+ async read() {
2542
+ return merge(await this.raw());
2543
+ }
2544
+ /** Forget the last read: the next one is whole. */
2545
+ reset() {
2546
+ this.last = void 0;
2547
+ }
2548
+ /** Chrome's accessibility tree and the DOM snapshot now, read whole or in part. */
2549
+ async raw() {
2550
+ const last = this.last;
2551
+ const from = this.options.partialFrom ?? 1e4;
2552
+ if (!last) return this.whole("first read", from);
2553
+ if (last.raw.ax.length < from) return this.whole("small page", from);
2554
+ await enableAccessibility(this.cdp);
2555
+ const [dom, focus, states] = await Promise.all([
2556
+ snapshot(this.cdp),
2557
+ focused(this.cdp),
2558
+ fieldStates(this.cdp)
2559
+ ]);
2560
+ if (last.states === void 0 || states !== last.states) return this.whole("a field state changed", from, {
2561
+ dom,
2562
+ focus,
2563
+ states
2564
+ });
2565
+ const facts = new Facts(dom);
2566
+ const plan = compare(last.facts ?? new Facts(last.raw.dom), facts, last.focus, focus, last.had ?? domIds(last.raw.ax));
2567
+ if ("whole" in plan) return this.whole(plan.whole, from, {
2568
+ dom,
2569
+ focus,
2570
+ states
2571
+ });
2572
+ const changed = plan.roots.length > 0 || plan.body !== void 0;
2573
+ let ax = last.raw.ax;
2574
+ if (changed) try {
2575
+ ax = await this.splice(last.raw.ax, plan.roots, plan.body);
2576
+ } catch {
2577
+ return this.whole("splice failed", from, {
2578
+ dom,
2579
+ focus,
2580
+ states
2581
+ });
2582
+ }
2583
+ const raw = {
2584
+ ax,
2585
+ dom
2586
+ };
2587
+ if (this.options.verify) await this.check(raw);
2588
+ this.last = {
2589
+ raw,
2590
+ focus,
2591
+ facts,
2592
+ had: changed ? domIds(raw.ax) : last.had,
2593
+ states
2594
+ };
2595
+ this.lastRead = {
2596
+ kind: "partial",
2597
+ parts: plan.roots.length
2598
+ };
2599
+ return raw;
2600
+ }
2601
+ async whole(why, from, prefetched) {
2602
+ let raw;
2603
+ let focus = prefetched?.focus;
2604
+ let states = prefetched?.states;
2605
+ if (prefetched) {
2606
+ await enableAccessibility(this.cdp);
2607
+ const { nodes } = await this.cdp.send("Accessibility.getFullAXTree");
2608
+ raw = {
2609
+ ax: nodes,
2610
+ dom: prefetched.dom
2611
+ };
2612
+ } else if (from === 0 || this.last && this.last.raw.ax.length >= from) {
2613
+ [focus, states] = await Promise.all([focused(this.cdp), fieldStates(this.cdp)]);
2614
+ raw = await readPage(this.cdp);
2615
+ } else raw = await readPage(this.cdp);
2616
+ this.last = {
2617
+ raw,
2618
+ focus,
2619
+ states
2620
+ };
2621
+ this.lastRead = {
2622
+ kind: "whole",
2623
+ why
2624
+ };
2625
+ return raw;
2626
+ }
2627
+ /** The last tree with each part read again: a part's nodes replaced by Chrome's now, its ancestors refreshed. */
2628
+ async splice(ax, roots, body) {
2629
+ const byId = new Map(ax.map((n) => [n.nodeId, n]));
2630
+ const byBackend = new Map(ax.flatMap((n) => n.backendDOMNodeId !== void 0 ? [[n.backendDOMNodeId, n]] : []));
2631
+ const reads = await Promise.all(roots.map((backendNodeId) => Promise.all([this.cdp.send("Accessibility.queryAXTree", { backendNodeId }).catch(() => ({ nodes: [] })), this.cdp.send("Accessibility.getPartialAXTree", {
2632
+ backendNodeId,
2633
+ fetchRelatives: true
2634
+ }).catch(() => ({ nodes: [] }))])));
2635
+ const bodyNow = body !== void 0 ? (await this.cdp.send("Accessibility.getPartialAXTree", {
2636
+ backendNodeId: body,
2637
+ fetchRelatives: false
2638
+ })).nodes.find((n) => n.backendDOMNodeId === body) : void 0;
2639
+ const drop = (id) => {
2640
+ const n = byId.get(id);
2641
+ if (!n) return;
2642
+ byId.delete(id);
2643
+ n.childIds?.forEach(drop);
2644
+ };
2645
+ /** a part's own node that Chrome made anew: its old id → its new one */
2646
+ const renamed = /* @__PURE__ */ new Map();
2647
+ const parts = [];
2648
+ const ancestors = /* @__PURE__ */ new Map();
2649
+ roots.forEach((backendNodeId, k) => {
2650
+ const [part, around] = reads[k];
2651
+ const old = byBackend.get(backendNodeId);
2652
+ const top = part.nodes.find((n) => n.backendDOMNodeId === backendNodeId);
2653
+ if (old && top && old.nodeId !== top.nodeId) renamed.set(old.nodeId, top.nodeId);
2654
+ if (old) drop(old.nodeId);
2655
+ parts.push(...part.nodes);
2656
+ const inPart = new Set(part.nodes.map((n) => n.nodeId));
2657
+ for (const n of around.nodes) if (!inPart.has(n.nodeId) && !(n.parentId !== void 0 && inPart.has(n.parentId))) ancestors.set(n.nodeId, n);
2658
+ });
2659
+ for (const n of parts) byId.set(n.nodeId, asWhole(n));
2660
+ for (const [id, n] of ancestors) {
2661
+ const had = byId.get(id)?.childIds ?? n.childIds;
2662
+ byId.set(id, asWhole({
2663
+ ...n,
2664
+ childIds: had?.map((c) => renamed.get(c) ?? c)
2665
+ }));
2666
+ }
2667
+ if (bodyNow) {
2668
+ const kept = new Set(bodyNow.childIds);
2669
+ for (const c of byId.get(bodyNow.nodeId)?.childIds ?? []) if (!kept.has(c)) drop(c);
2670
+ byId.set(bodyNow.nodeId, asWhole(bodyNow));
2671
+ }
2672
+ return [...byId.values()];
2673
+ }
2674
+ async check(raw) {
2675
+ const partial = JSON.stringify(merge(raw));
2676
+ const whole = JSON.stringify(merge(await readPage(this.cdp)));
2677
+ if (partial !== whole) {
2678
+ let k = 0;
2679
+ while (k < partial.length && partial[k] === whole[k]) k++;
2680
+ throw new Error(`a partial read differs from a whole one at ${k}:\n partial: …${partial.slice(Math.max(0, k - 120), k + 120)}\n whole: …${whole.slice(Math.max(0, k - 120), k + 120)}`);
2681
+ }
2682
+ }
2683
+ };
2684
+ /**
2685
+ * A node read in part, the way a whole read has it: there an ignored node has
2686
+ * no role or name of its own (a part's read gives an ignored label's text its
2687
+ * name, which would then be said twice), and no child is listed twice.
2688
+ */
2689
+ function asWhole(n) {
2690
+ const childIds = n.childIds && [...new Set(n.childIds)];
2691
+ if (!n.ignored) return {
2692
+ ...n,
2693
+ childIds
2694
+ };
2695
+ const { nodeId, ignored, ignoredReasons, parentId, backendDOMNodeId } = n;
2696
+ return {
2697
+ nodeId,
2698
+ ignored,
2699
+ ignoredReasons,
2700
+ role: { value: "none" },
2701
+ parentId,
2702
+ childIds,
2703
+ backendDOMNodeId
2704
+ };
2705
+ }
2706
+ /** The DOM node ids that have a node in an accessibility tree. */
2707
+ function domIds(ax) {
2708
+ return new Set(ax.flatMap((n) => n.backendDOMNodeId !== void 0 ? [n.backendDOMNodeId] : []));
2709
+ }
2710
+ /** The DOM node id of the element that has the focus, unless it's the page itself. */
2711
+ async function focused(cdp) {
2712
+ try {
2713
+ const { result } = await cdp.send("Runtime.evaluate", { expression: `(() => { let a = document.activeElement; while (a && a.shadowRoot && a.shadowRoot.activeElement) a = a.shadowRoot.activeElement; return a === document.body || a === document.documentElement ? null : a })()` });
2714
+ if (!result.objectId) return void 0;
2715
+ const { node } = await cdp.send("DOM.describeNode", { objectId: result.objectId });
2716
+ await cdp.send("Runtime.releaseObject", { objectId: result.objectId });
2717
+ return node.backendNodeId;
2718
+ } catch {
2719
+ return;
2720
+ }
2721
+ }
2722
+ /**
2723
+ * The states fields hold in properties only, which no DOM snapshot shows: each field (in open shadow roots too) that
2724
+ * is indeterminate or invalid, by its place in the page. Compared as one string: a change means a whole read.
2725
+ */
2726
+ async function fieldStates(cdp) {
2727
+ const expression = `(() => {
2728
+ const out = []
2729
+ let k = 0
2730
+ const look = (root) => {
2731
+ for (const el of root.querySelectorAll('*')) {
2732
+ if (el.shadowRoot) look(el.shadowRoot)
2733
+ if (!(el instanceof HTMLInputElement || el instanceof HTMLSelectElement || el instanceof HTMLTextAreaElement)) continue
2734
+ k++
2735
+ const said = (el.indeterminate ? 'i' : '') + (el.willValidate && !el.validity.valid ? 'v' : '')
2736
+ if (said) out.push(k + said)
2737
+ }
2738
+ }
2739
+ look(document)
2740
+ return out.join(',')
2741
+ })()`;
2742
+ try {
2743
+ const { result } = await cdp.send("Runtime.evaluate", {
2744
+ expression,
2745
+ returnByValue: true
2746
+ });
2747
+ return result.value;
2748
+ } catch {
2749
+ return;
2750
+ }
2751
+ }
2752
+ /** A DOM snapshot indexed for comparing: each node's facts that the accessibility tree depends on, as strings. */
2753
+ var Facts = class {
2754
+ s;
2755
+ n;
2756
+ url;
2757
+ byBackend = /* @__PURE__ */ new Map();
2758
+ drawn = /* @__PURE__ */ new Map();
2759
+ input = /* @__PURE__ */ new Map();
2760
+ checked = /* @__PURE__ */ new Set();
2761
+ chosen = /* @__PURE__ */ new Set();
2762
+ /** each node's previous sibling, by DOM node id (-1: first) */
2763
+ before = [];
2764
+ ids = /* @__PURE__ */ new Map();
2765
+ /** an id → the elements naming or describing another by it */
2766
+ referrers = /* @__PURE__ */ new Map();
2767
+ /** a label → the control it names */
2768
+ labels = /* @__PURE__ */ new Map();
2769
+ /** elements with aria-owns, and the ids they own */
2770
+ owners = /* @__PURE__ */ new Set();
2771
+ owned = /* @__PURE__ */ new Set();
2772
+ constructor(snap) {
2773
+ const doc = snap.documents[0];
2774
+ this.s = snap.strings;
2775
+ this.n = doc.nodes;
2776
+ this.url = this.s[doc.documentURL] ?? "";
2777
+ const n = this.n;
2778
+ const last = /* @__PURE__ */ new Map();
2779
+ for (let i = 0; i < n.backendNodeId.length; i++) {
2780
+ this.byBackend.set(n.backendNodeId[i], i);
2781
+ const p = n.parentIndex[i];
2782
+ this.before[i] = p >= 0 && last.has(p) ? n.backendNodeId[last.get(p)] : -1;
2783
+ last.set(p, i);
2784
+ const attrs = n.attributes[i] ?? [];
2785
+ for (let k = 0; k + 1 < attrs.length; k += 2) {
2786
+ const name = this.s[attrs[k]].toLowerCase();
2787
+ const value = this.s[attrs[k + 1]] ?? "";
2788
+ if (name === "id" && value) this.ids.set(value, i);
2789
+ else if (REFERS.includes(name)) for (const id of value.split(/\s+/).filter(Boolean)) (this.referrers.get(id) ?? this.referrers.set(id, []).get(id)).push(i);
2790
+ else if (name === "aria-owns") {
2791
+ this.owners.add(i);
2792
+ value.split(/\s+/).filter(Boolean).forEach((id) => this.owned.add(id));
2793
+ }
2794
+ }
2795
+ }
2796
+ doc.layout.nodeIndex.forEach((i, k) => this.drawn.set(i, `${doc.layout.styles[k].map((x) => this.s[x]).join("|")}|${this.s[doc.layout.text?.[k] ?? -1] ?? ""}`));
2797
+ for (const rare of [n.inputValue, n.textValue]) rare?.index.forEach((i, k) => this.input.set(i, this.s[rare.value[k]] ?? ""));
2798
+ n.inputChecked?.index.forEach((i) => this.checked.add(i));
2799
+ n.optionSelected?.index.forEach((i) => this.chosen.add(i));
2800
+ for (let i = 0; i < n.backendNodeId.length; i++) {
2801
+ if (this.tag(i) !== "LABEL") continue;
2802
+ const f = this.attr(i, "for");
2803
+ if (f !== void 0) {
2804
+ const c = this.ids.get(f);
2805
+ if (c !== void 0) this.labels.set(i, c);
2806
+ continue;
2807
+ }
2808
+ for (let j = i + 1; j < n.backendNodeId.length && this.within(j, i); j++) if (LABELABLE.has(this.tag(j)) && !(this.tag(j) === "INPUT" && this.attr(j, "type") === "hidden")) {
2809
+ this.labels.set(i, j);
2810
+ break;
2811
+ }
2812
+ }
2813
+ }
2814
+ /** An element's tag in capitals, as HTML says it (a page served as XHTML says it in lowercase). */
2815
+ tag(i) {
2816
+ return (this.s[this.n.nodeName[i]] ?? "").toUpperCase();
2817
+ }
2818
+ attr(i, name) {
2819
+ const attrs = this.n.attributes[i] ?? [];
2820
+ for (let k = 0; k + 1 < attrs.length; k += 2) if (this.s[attrs[k]].toLowerCase() === name) return this.s[attrs[k + 1]] ?? "";
2821
+ }
2822
+ attrs(i) {
2823
+ return (this.n.attributes[i] ?? []).map((x) => this.s[x]).join("\0");
2824
+ }
2825
+ text(i) {
2826
+ const v = this.n.nodeValue?.[i];
2827
+ return v === void 0 || v < 0 ? "" : this.s[v] ?? "";
2828
+ }
2829
+ parent(i) {
2830
+ return this.n.parentIndex[i];
2831
+ }
2832
+ /** Whether node j is inside node i. */
2833
+ within(j, i) {
2834
+ for (let p = this.parent(j); p >= 0; p = this.parent(p)) if (p === i) return true;
2835
+ return false;
2836
+ }
2837
+ backend(i) {
2838
+ return this.n.backendNodeId[i];
2839
+ }
2840
+ };
2841
+ /** Attributes whose change reaches what an element holds only through how it's drawn. */
2842
+ const DRAWN_ONLY = /^(?:class|style|data-(?!agentom-).*)$/;
2843
+ /** Whether all that changed about an element, besides how it's drawn, is attributes in DRAWN_ONLY. */
2844
+ function drawnOnly(o, j, a, i) {
2845
+ const map = (f, k) => {
2846
+ const out = /* @__PURE__ */ new Map();
2847
+ const flat = f.n.attributes[k] ?? [];
2848
+ for (let x = 0; x + 1 < flat.length; x += 2) out.set(f.s[flat[x]].toLowerCase(), f.s[flat[x + 1]] ?? "");
2849
+ return out;
2850
+ };
2851
+ const before = map(o, j);
2852
+ const after = map(a, i);
2853
+ for (const name of /* @__PURE__ */ new Set([...before.keys(), ...after.keys()])) if (before.get(name) !== after.get(name) && !DRAWN_ONLY.test(name)) return false;
2854
+ return o.text(j) === a.text(i) && o.input.get(j) === a.input.get(i) && o.checked.has(j) === a.checked.has(i) && o.chosen.has(j) === a.chosen.has(i);
2855
+ }
2856
+ function compare(o, a, focusBefore, focusAfter, had) {
2857
+ if (o.url !== a.url) return { whole: "new address" };
2858
+ if (o.backend(0) !== a.backend(0)) return { whole: "new document" };
2859
+ const points = [];
2860
+ const was = (i) => o.byBackend.get(a.backend(i));
2861
+ for (let i = 0; i < a.n.backendNodeId.length; i++) {
2862
+ const j = was(i);
2863
+ if (j === void 0) {
2864
+ points.push({
2865
+ i,
2866
+ inside: false
2867
+ });
2868
+ continue;
2869
+ }
2870
+ if (!((a.parent(i) >= 0 ? a.backend(a.parent(i)) : -1) === (o.parent(j) >= 0 ? o.backend(o.parent(j)) : -1) && a.before[i] === o.before[j] && a.attrs(i) === o.attrs(j) && a.text(i) === o.text(j) && a.drawn.get(i) === o.drawn.get(j) && a.input.get(i) === o.input.get(j) && a.checked.has(i) === o.checked.has(j) && a.chosen.has(i) === o.chosen.has(j))) points.push({
2871
+ i,
2872
+ inside: false
2873
+ });
2874
+ }
2875
+ const gone = [];
2876
+ for (let j = 0; j < o.n.backendNodeId.length; j++) {
2877
+ if (a.byBackend.has(o.backend(j))) continue;
2878
+ gone.push(j);
2879
+ const p = o.parent(j);
2880
+ const at = p >= 0 ? a.byBackend.get(o.backend(p)) : void 0;
2881
+ if (at !== void 0) points.push({
2882
+ i: at,
2883
+ inside: true
2884
+ });
2885
+ }
2886
+ for (const f of [focusBefore, focusAfter]) {
2887
+ const i = f !== void 0 && focusBefore !== focusAfter ? a.byBackend.get(f) : void 0;
2888
+ if (i !== void 0) points.push({
2889
+ i,
2890
+ inside: false
2891
+ });
2892
+ }
2893
+ const reach = (f, start, add) => {
2894
+ for (let k = start; k >= 0; k = f.parent(k)) {
2895
+ if (f.n.nodeType[k] !== ELEMENT) continue;
2896
+ if (f.owners.has(k)) return "aria-owns";
2897
+ const id = f.attr(k, "id");
2898
+ if (id) {
2899
+ if (f.owned.has(id)) return "aria-owns";
2900
+ f.referrers.get(id)?.forEach(add);
2901
+ }
2902
+ const control = f.labels.get(k);
2903
+ if (control !== void 0) add(control);
2904
+ }
2905
+ };
2906
+ const more = [];
2907
+ const addNow = (k) => more.push({
2908
+ i: k,
2909
+ inside: false
2910
+ });
2911
+ const addThen = (k) => {
2912
+ const i = a.byBackend.get(o.backend(k));
2913
+ if (i !== void 0) more.push({
2914
+ i,
2915
+ inside: false
2916
+ });
2917
+ };
2918
+ for (const p of points) {
2919
+ if (a.n.nodeType[p.i] === ELEMENT && !p.inside && (a.tag(p.i) === "DIALOG" || a.attr(p.i, "aria-modal") !== void 0)) return { whole: "a dialog changed" };
2920
+ const why = reach(a, p.i, addNow) ?? (was(p.i) !== void 0 ? reach(o, was(p.i), addThen) : void 0);
2921
+ if (why) return { whole: why };
2922
+ }
2923
+ for (const j of gone) {
2924
+ if (o.n.nodeType[j] === ELEMENT && (o.tag(j) === "DIALOG" || o.attr(j, "aria-modal") !== void 0)) return { whole: "a dialog changed" };
2925
+ const why = reach(o, j, addThen);
2926
+ if (why) return { whole: why };
2927
+ }
2928
+ points.push(...more);
2929
+ const html = a.n.nodeName.findIndex((_, i) => a.n.nodeType[i] === ELEMENT && a.tag(i) === "HTML");
2930
+ const body = a.n.nodeName.findIndex((_, i) => a.n.nodeType[i] === ELEMENT && a.tag(i) === "BODY" && a.parent(i) === html);
2931
+ if (html < 0 || body < 0 || !had.has(a.backend(body))) return { whole: "a page with no body" };
2932
+ const childOfBody = (i) => {
2933
+ while (a.parent(i) !== body) i = a.parent(i);
2934
+ return i;
2935
+ };
2936
+ let list = false;
2937
+ const roots = /* @__PURE__ */ new Set();
2938
+ for (const p of points) {
2939
+ let inHead = false;
2940
+ for (let k = p.i; k >= 0; k = a.parent(k)) {
2941
+ if (a.tag(k) === "TITLE") return { whole: "the title changed" };
2942
+ if (a.tag(k) === "HEAD") inHead = true;
2943
+ }
2944
+ if (inHead) continue;
2945
+ if (p.i === body && p.inside) {
2946
+ list = true;
2947
+ continue;
2948
+ }
2949
+ if (p.i === body && was(body) !== void 0 && drawnOnly(o, was(body), a, body)) {
2950
+ list = true;
2951
+ continue;
2952
+ }
2953
+ if (p.i === body || p.i === html || a.parent(p.i) < 0 || !a.within(p.i, body)) return { whole: "a change at the top of the page" };
2954
+ let k = p.inside ? p.i : a.parent(p.i);
2955
+ while (k !== body && !had.has(a.backend(k))) k = a.parent(k);
2956
+ if (k === body) {
2957
+ roots.add(childOfBody(p.i));
2958
+ list = true;
2959
+ } else roots.add(k);
2960
+ }
2961
+ const inPart = [];
2962
+ let size = 0;
2963
+ const top = [];
2964
+ for (let i = 0; i < a.n.backendNodeId.length; i++) {
2965
+ const p = a.parent(i);
2966
+ const parentIn = p >= 0 && inPart[p];
2967
+ inPart[i] = parentIn || roots.has(i);
2968
+ if (inPart[i]) size++;
2969
+ if (roots.has(i) && !parentIn) top.push(a.backend(i));
2970
+ }
2971
+ if (top.length > PARTIAL_PARTS) return { whole: "too many changed parts" };
2972
+ if (size > PARTIAL_SHARE * a.n.backendNodeId.length) return { whole: "most of the page changed" };
2973
+ return {
2974
+ roots: top,
2975
+ ...list ? { body: a.backend(body) } : {}
2976
+ };
2977
+ }
2978
+ /** …or read as it is after this long. */
2979
+ const SETTLE_MAX_MS = 5e3;
2980
+ /** A request open longer than this (a long poll) no longer counts. */
2981
+ const LONG_REQUEST_MS = 2e3;
2982
+ /**
2983
+ * The kinds of request a page is waited on for: those whose answer the page acts on. A document, a script and a
2984
+ * stylesheet make or change what it shows; data it fetched is what its scripts were waiting for. A picture, a font,
2985
+ * a sound or a beacon says nothing the page then shows as text or as a control (an advertiser's or a tracker's pixel
2986
+ * is a picture, and a page can load dozens for seconds after everything on it is there); a WebSocket and an
2987
+ * EventSource stay open by design. What a page does when a picture has come (a script's onload) is a change to the
2988
+ * DOM, and is waited for as one.
2989
+ */
2990
+ const WAITED_FOR = /* @__PURE__ */ new Set([
2991
+ "document",
2992
+ "script",
2993
+ "stylesheet",
2994
+ "fetch",
2995
+ "xhr"
2996
+ ]);
2997
+ const POLL_MS = 40;
2998
+ /** Wait until the page is quiet, or `maxMs`; whether it settled, and what was still going on when it didn't. */
2999
+ async function settle$1(o) {
3000
+ const maxMs = o.maxMs ?? 5e3;
3001
+ const start = Date.now();
3002
+ let lastChange = start;
3003
+ let lastCount;
3004
+ let firstCount;
3005
+ let quietNet = start;
3006
+ let sawNet = !o.action;
3007
+ let now;
3008
+ for (;;) {
3009
+ now = await o.now().catch(() => void 0);
3010
+ const t = Date.now();
3011
+ if (!now || now.changes !== lastCount) lastChange = t;
3012
+ if (now) {
3013
+ lastCount = now.changes;
3014
+ firstCount ??= now.changes;
3015
+ }
3016
+ const open = [...o.inFlight()].filter((r) => t - r.started < LONG_REQUEST_MS);
3017
+ if (open.length) {
3018
+ quietNet = t;
3019
+ sawNet = true;
3020
+ }
3021
+ const needNet = sawNet ? 500 : 120;
3022
+ const needDom = sawNet ? 300 : 120;
3023
+ const domQuiet = now?.idleMs !== void 0 ? Math.min(t - lastChange, now.idleMs) : t - lastChange;
3024
+ if (t - quietNet >= needNet && domQuiet >= needDom && !now?.busy && now) return { settled: true };
3025
+ if (t - start >= maxMs) {
3026
+ const pending = [];
3027
+ if (open.length) pending.push(`${open.length} request${open.length > 1 ? "s" : ""} in flight: ${open.slice(0, 5).map((r) => r.said).join(", ")}`);
3028
+ if (now?.busy) pending.push(`${now.busy} element${now.busy > 1 ? "s" : ""} aria-busy`);
3029
+ if (domQuiet < needDom) pending.push(`the DOM still changing (${Math.max(0, (lastCount ?? 0) - (firstCount ?? 0))} changes in ${maxMs / 1e3} s)`);
3030
+ return {
3031
+ settled: false,
3032
+ pending
3033
+ };
3034
+ }
3035
+ await new Promise((r) => setTimeout(r, POLL_MS));
3036
+ }
3037
+ }
3038
+ const tracked = /* @__PURE__ */ new WeakMap();
3039
+ /** The requests a page has in flight from now on, of the kinds it is waited on for: watched once, for as long as the page lives. */
3040
+ function requestsOf(page) {
3041
+ let open = tracked.get(page);
3042
+ if (!open) {
3043
+ const map = /* @__PURE__ */ new Map();
3044
+ open = map;
3045
+ tracked.set(page, map);
3046
+ page.on("request", (r) => {
3047
+ if (WAITED_FOR.has(r.resourceType())) map.set(r, Date.now());
3048
+ });
3049
+ page.on("requestfinished", (r) => map.delete(r));
3050
+ page.on("requestfailed", (r) => map.delete(r));
3051
+ }
3052
+ const map = open;
3053
+ return () => [...map].map(([r, started]) => ({
3054
+ started,
3055
+ said: `${r.method()} ${r.url()}`
3056
+ }));
3057
+ }
3058
+ // src/page.ts
3059
+ /** Counts the page's DOM changes (throttling style animation ticks and ignoring no-op attrs and data-agentom-ignore), installed in every document it loads. */
3060
+ const WATCH = `(() => {
3061
+ if (window.__agentomChanges !== undefined) return
3062
+ window.__agentomChanges = 0
3063
+ window.__agentomLastChange = performance.now()
3064
+ const STYLE_QUIET_MS = 200
3065
+ const lastStyle = new WeakMap()
3066
+ const ignored = (n) => !!(n instanceof Element ? n : n.parentElement)?.closest('[data-agentom-ignore]')
3067
+ const start = () => new MutationObserver((records) => {
3068
+ const now = performance.now()
3069
+ let counted = false
3070
+ for (const r of records) {
3071
+ if (r.type === 'childList') {
3072
+ let allIgnored = true
3073
+ for (const n of r.addedNodes) if (!ignored(n)) { allIgnored = false; break }
3074
+ if (allIgnored) for (const n of r.removedNodes) if (!ignored(n)) { allIgnored = false; break }
3075
+ if (allIgnored) continue
3076
+ } else if (ignored(r.target)) continue
3077
+ if (r.type === 'attributes') {
3078
+ const el = r.target
3079
+ if (el.getAttribute(r.attributeName) === r.oldValue) continue
3080
+ if (r.attributeName === 'style') {
3081
+ const prev = lastStyle.get(el)
3082
+ lastStyle.set(el, now)
3083
+ if (prev !== undefined && now - prev < STYLE_QUIET_MS) continue
3084
+ }
3085
+ }
3086
+ counted = true
3087
+ }
3088
+ if (counted) {
3089
+ window.__agentomChanges++
3090
+ window.__agentomLastChange = now
3091
+ }
3092
+ }).observe(document, { subtree: true, childList: true, attributes: true, attributeOldValue: true, characterData: true })
3093
+ if (document.documentElement) start(); else document.addEventListener('DOMContentLoaded', start)
3094
+ })()`;
3095
+ const sessions = /* @__PURE__ */ new WeakMap();
3096
+ const readers = /* @__PURE__ */ new WeakMap();
3097
+ const declaredPages = /* @__PURE__ */ new WeakSet();
3098
+ /** Watch a page from its next load on: its requests and its DOM changes. */
3099
+ async function watch(page) {
3100
+ if (watched.has(page)) return;
3101
+ watched.add(page);
3102
+ page.on("framenavigated", (f) => {
3103
+ if (f === page.mainFrame()) declaredPages.delete(page);
3104
+ });
3105
+ requestsOf(page);
3106
+ await page.addInitScript(WATCH);
3107
+ await page.evaluate(WATCH).catch(() => {});
3108
+ }
3109
+ const watched = /* @__PURE__ */ new WeakSet();
3110
+ function cdp(page) {
3111
+ let s = sessions.get(page);
3112
+ if (!s) {
3113
+ s = page.context().newCDPSession(page);
3114
+ sessions.set(page, s);
3115
+ }
3116
+ return s;
3117
+ }
3118
+ /**
3119
+ * Wait until the page is quiet (cdp-reader's settle: no request in flight and no DOM change for a moment, nothing it
3120
+ * marks aria-busy), or until it's waited long enough. Says whether it settled.
3121
+ */
3122
+ async function settle(page, maxMs = SETTLE_MAX_MS, action = false) {
3123
+ return (await settle$1({
3124
+ now: async () => {
3125
+ const res = await page.evaluate(`window.__agentomChanges === undefined ? null : [window.__agentomChanges, document.querySelectorAll('[aria-busy="true"]').length, Math.max(0, performance.now() - (window.__agentomLastChange ?? 0))]`);
3126
+ if (!res) return void 0;
3127
+ return {
3128
+ changes: res[0],
3129
+ busy: res[1],
3130
+ idleMs: res[2]
3131
+ };
3132
+ },
3133
+ inFlight: requestsOf(page),
3134
+ maxMs,
3135
+ action
3136
+ })).settled;
3137
+ }
3138
+ /** The page's projection now: on a large page, only what changed since the last read is read again. */
3139
+ async function read(page) {
3140
+ let r = readers.get(page);
3141
+ if (!r) {
3142
+ r = cdp(page).then((s) => new Reader(s));
3143
+ readers.set(page, r);
3144
+ }
3145
+ return (await r).read();
3146
+ }
3147
+ /** The node a ref names in a projection. */
3148
+ function nodeOf(p, ref) {
3149
+ const find = (n) => n.ref === ref ? n : n.children?.map(find).find(Boolean);
3150
+ return find(p.root);
3151
+ }
3152
+ /** The nodes from the top down to a ref's node. */
3153
+ function pathTo(p, ref) {
3154
+ const find = (n, path) => n.ref === ref ? [...path, n] : n.children?.map((c) => find(c, [...path, n])).find(Boolean);
3155
+ return find(p.root, []);
3156
+ }
3157
+ /**
3158
+ * A function the page runs, written as text: tsx compiles a function of this
3159
+ * file into code that names helpers the page doesn't have, so what the page
3160
+ * runs is built from a string.
3161
+ */
3162
+ const inPage = (params, body) => new Function(...params, body);
3163
+ /**
3164
+ * Where an element is handed between Chrome's protocol and Playwright, in the page's own world (neither can reach the
3165
+ * other's objects any other way). The page's scripts live there too, so the names are new in each run of the tool,
3166
+ * which a page can't have taken beforehand, and each is declared as a script's variable before it's used: a property
3167
+ * of the page's global object that can't be redefined, so a page that finds the name once it's there can't turn it
3168
+ * into a getter of its own. It can still write to it; what was handed over is checked against the ref before
3169
+ * anything is done with it, and a page that wrote another element in its place is acted on nowhere.
3170
+ */
3171
+ const HELD = `__agentom_${randomBytes(12).toString("hex")}`;
3172
+ const CHAIN = `__agentom_${randomBytes(12).toString("hex")}`;
3173
+ const declared = async (page, session) => {
3174
+ if (declaredPages.has(page)) return;
3175
+ await session.send("Runtime.evaluate", { expression: `var ${HELD}, ${CHAIN}` });
3176
+ declaredPages.add(page);
3177
+ };
3178
+ /** The element a ref names (Chrome's DOM node id; a text's names its parent), or undefined when it's gone. */
3179
+ async function elementOf(page, ref) {
3180
+ if (!/^e\d+$/.test(ref)) return void 0;
3181
+ const session = await cdp(page);
3182
+ let objectId;
3183
+ try {
3184
+ const { object } = await session.send("DOM.resolveNode", { backendNodeId: Number(ref.slice(1)) });
3185
+ objectId = object.objectId;
3186
+ if (!objectId) return void 0;
3187
+ await declared(page, session);
3188
+ const { result } = await session.send("Runtime.callFunctionOn", {
3189
+ objectId,
3190
+ functionDeclaration: `function () { const el = this.nodeType === 1 ? this : this.parentElement; ${HELD} = el; return !!el && el.isConnected }`,
3191
+ returnByValue: true
3192
+ });
3193
+ if (result.value !== true) return void 0;
3194
+ const el = (await page.evaluateHandle(HELD)).asElement() ?? void 0;
3195
+ const { result: same } = await session.send("Runtime.callFunctionOn", {
3196
+ objectId,
3197
+ functionDeclaration: `function () { const el = this.nodeType === 1 ? this : this.parentElement; const same = ${HELD} === el; ${HELD} = undefined; return same }`,
3198
+ returnByValue: true
3199
+ });
3200
+ if (same.value === true) return el;
3201
+ await el?.dispose().catch(() => {});
3202
+ return;
3203
+ } catch {
3204
+ return;
3205
+ } finally {
3206
+ if (objectId) await session.send("Runtime.releaseObject", { objectId }).catch(() => {});
3207
+ }
3208
+ }
3209
+ /** The ref of the projected node an element is in: the element's own, else its nearest projected ancestor's. */
3210
+ async function refAround(page, el, p) {
3211
+ const refs = /* @__PURE__ */ new Set();
3212
+ const walk = (n) => {
3213
+ if (n.ref) refs.add(n.ref);
3214
+ n.children?.forEach(walk);
3215
+ };
3216
+ walk(p.root);
3217
+ const session = await cdp(page);
3218
+ await declared(page, session);
3219
+ const depth = await el.evaluate(inPage(["el"], `const a = []; for (let n = el; n; n = n.parentElement) a.push(n); ${CHAIN} = a; return a.length`));
3220
+ try {
3221
+ for (let k = 0; k < depth; k++) {
3222
+ const { result } = await session.send("Runtime.evaluate", { expression: `${CHAIN}[${k}]` });
3223
+ if (!result.objectId) continue;
3224
+ try {
3225
+ const { node } = await session.send("DOM.describeNode", { objectId: result.objectId });
3226
+ if (refs.has(`e${node.backendNodeId}`)) return `e${node.backendNodeId}`;
3227
+ } finally {
3228
+ await session.send("Runtime.releaseObject", { objectId: result.objectId }).catch(() => {});
3229
+ }
3230
+ }
3231
+ return;
3232
+ } finally {
3233
+ await session.send("Runtime.evaluate", { expression: `${CHAIN} = undefined` }).catch(() => {});
3234
+ }
3235
+ }
3236
+ /** How much of what a script says the agent is told. */
3237
+ const SCRIPT_MAX = 2e4;
3238
+ /** The commands a script can't call: those of the session, those that need what only the shell has, and itself. */
3239
+ const NOT_IN_SCRIPTS = /* @__PURE__ */ new Set(["script", "fill-secret"]);
3240
+ /** A command's name as a script calls it: switch-tab as switchTab. */
3241
+ const camel = (name) => name.replace(/-(\w)/g, (_, c) => c.toUpperCase());
3242
+ function find(p, f = {}) {
3243
+ try {
3244
+ return findNodes(p, f);
3245
+ } catch (e) {
3246
+ if (e instanceof QueryError) throw new ToolError(e.message);
3247
+ throw e;
3248
+ }
3249
+ }
3250
+ function table(p, ref) {
3251
+ try {
3252
+ return extractTable(p, ref);
3253
+ } catch (e) {
3254
+ if (e instanceof QueryError) throw new ToolError(e.message);
3255
+ throw e;
3256
+ }
3257
+ }
3258
+ /** Commands whose element is an option (`--ref`), not a word in its place. */
3259
+ const REF_OPTION = /* @__PURE__ */ new Set(["eval"]);
3260
+ /** A script's arguments as the command line's: words in order, and an object for its options; a node stands for its ref. */
3261
+ function asArgs(name, values) {
3262
+ const a = {
3263
+ _: [],
3264
+ flags: {}
3265
+ };
3266
+ const none = values.findIndex((v) => v === null || v === void 0);
3267
+ if (none >= 0) throw new ToolError(`om.${camel(name)} got nothing as its ${[
3268
+ "first",
3269
+ "second",
3270
+ "third"
3271
+ ][none] ?? `${none + 1}th`} argument: what it came from found nothing (om.find gives a list: check its length before taking [0])`);
3272
+ for (const v of values) if (v && typeof v === "object" && !Array.isArray(v)) {
3273
+ const o = v;
3274
+ if (typeof o.ref === "string" && typeof o.role === "string") {
3275
+ if (REF_OPTION.has(name)) a.flags.ref = o.ref;
3276
+ else a._.push(o.ref);
3277
+ continue;
3278
+ }
3279
+ for (const [k, x] of Object.entries(o)) if (x === true) a.flags[k] = true;
3280
+ else if (x !== false && x !== void 0 && x !== null) a.flags[k] = Array.isArray(x) ? x.map(String).join(",") : String(x);
3281
+ } else if (Array.isArray(v)) a._.push(...v.map(String));
3282
+ else if (v !== void 0 && v !== null) a._.push(String(v));
3283
+ return a;
3284
+ }
3285
+ /** What a script calls through `om`, run as the command line runs it, or as data. */
3286
+ async function dispatch(s, box, name, values) {
3287
+ if (!box.running) throw new ToolError("no script is running: this call came from one that has ended");
3288
+ if (box.aborted || Date.now() > box.deadline) {
3289
+ box.aborted = true;
3290
+ throw new ToolError("the script ran out of time, and was stopped");
3291
+ }
3292
+ if (name === "find" || name === "table" || name === "read") {
3293
+ const held = box.read && Date.now() - box.read.at < 500 ? box.read.p : void 0;
3294
+ const p = held ?? await readNow(s);
3295
+ if (!held) box.read = {
3296
+ p,
3297
+ at: Date.now()
3298
+ };
3299
+ rememberShown(s, p);
3300
+ s.last ??= p;
3301
+ return name === "read" ? p : name === "find" ? find(p, values[0] ?? {}) : table(p, String(values[0]?.ref ?? values[0]));
3302
+ }
3303
+ box.read = void 0;
3304
+ try {
3305
+ if (name !== "eval") return await runCommand(s, name, asArgs(name, values), {});
3306
+ s.evaluated = void 0;
3307
+ await runCommand(s, name, asArgs(name, values), {});
3308
+ const got = s.evaluated;
3309
+ if (!got || got.kind === "none") return void 0;
3310
+ if (got.kind === "text") return got.said;
3311
+ try {
3312
+ return JSON.parse(got.said);
3313
+ } catch {
3314
+ return got.said;
3315
+ }
3316
+ } finally {
3317
+ box.read = void 0;
3318
+ }
3319
+ }
3320
+ /** What the sandbox page is given once: `om`, `print`, and what they say. Its own words, never the page's. */
3321
+ const prelude = (commands) => `
3322
+ (() => {
3323
+ const said = []
3324
+ globalThis.__said = said
3325
+ const shown = (v) => typeof v === 'string' ? v : v === undefined ? 'undefined' : JSON.stringify(v)
3326
+ globalThis.print = (...values) => { said.push(values.map(shown).join(' ')) }
3327
+ const call = async (name, values) => {
3328
+ const r = JSON.parse(await globalThis.__om(name, JSON.stringify(values)))
3329
+ if (!r.ok) throw new Error(r.error)
3330
+ return r.value
3331
+ }
3332
+ const om = {}
3333
+ for (const [name, as] of ${JSON.stringify(commands.map((c) => [c, camel(c)]))}) om[as] = (...values) => call(name, values)
3334
+ // a regular expression for the name or the words is tested here, on what the tool found by the rest of the
3335
+ // filter: here a slow one ends with the script, and in the tool it would stop every command
3336
+ const isRe = (w) => w instanceof RegExp
3337
+ const listed = (m) => m === undefined ? [] : Array.isArray(m) ? m : [m]
3338
+ const has = (w, text) => {
3339
+ if (isRe(w)) return new RegExp(w.source, w.flags.replace(/[gy]/g, '')).test(text)
3340
+ if (typeof w !== 'string') throw new Error("om.find's match takes text or a regular expression, and got " + JSON.stringify(w))
3341
+ return text.toLowerCase().includes(w.toLowerCase())
3342
+ }
3343
+ om.find = async (filter = {}) => {
3344
+ const { name, match, ...rest } = filter
3345
+ const here = { name: isRe(name), match: listed(match).some(isRe) }
3346
+ let found = await call('find', [{ ...rest, ...(here.name || name === undefined ? {} : { name }), ...(here.match || match === undefined ? {} : { match }) }])
3347
+ if (here.name) found = found.filter((n) => has(name, n.name ?? ''))
3348
+ if (here.match) found = found.filter((n) => listed(match).some((w) => has(w, n.line)))
3349
+ return found
3350
+ }
3351
+ om.table = (ref) => call('table', [ref])
3352
+ om.read = () => call('read', [])
3353
+ globalThis.om = Object.freeze(om)
3354
+ })()
3355
+ `;
3356
+ /** The session's sandbox, made the first time a script runs: a context of its own in its browser, or a browser of its own beside the user's. */
3357
+ async function sandboxOf(s) {
3358
+ if (s.sandbox) return s.sandbox;
3359
+ const own = s.attached ? null : s.page.context().browser();
3360
+ let launched;
3361
+ let context;
3362
+ if (own) context = await own.newContext();
3363
+ else {
3364
+ launched = await chromium.launch({ headless: true }).catch((e) => {
3365
+ throw new ToolError(`scripts run in a browser of the tool's own, which didn't start (${e.message.split("\n")[0]}): agent-om install`);
3366
+ });
3367
+ context = await launched.newContext();
3368
+ }
3369
+ await context.route("**/*", (route) => route.abort());
3370
+ await context.routeWebSocket(/.*/, (ws) => ws.close());
3371
+ const page = await context.newPage();
3372
+ const box = {
3373
+ page,
3374
+ cdp: await context.newCDPSession(page),
3375
+ close: async () => {
3376
+ await context.close().catch(() => {});
3377
+ await launched?.close().catch(() => {});
3378
+ },
3379
+ deadline: 0,
3380
+ aborted: false,
3381
+ running: false
3382
+ };
3383
+ await page.exposeFunction("__om", async (name, json) => {
3384
+ try {
3385
+ return JSON.stringify({
3386
+ ok: true,
3387
+ value: await dispatch(s, box, name, JSON.parse(json))
3388
+ });
3389
+ } catch (e) {
3390
+ const message = e instanceof Error ? e.message : String(e);
3391
+ const about = e instanceof ToolError && e.quoting !== void 0 ? `\n${e.quoting}` : "";
3392
+ return JSON.stringify({
3393
+ ok: false,
3394
+ error: `${message}${about}`
3395
+ });
3396
+ }
3397
+ });
3398
+ const on = [...s.allowEval ? ["eval"] : [], ...s.allowScreenshot ? ["screenshot"] : []];
3399
+ const commands = commandsFor("cli", on).filter((c) => c.group !== "session" && !NOT_IN_SCRIPTS.has(c.name)).map((c) => c.name);
3400
+ await page.evaluate(prelude(commands));
3401
+ s.sandbox = box;
3402
+ return box;
3403
+ }
3404
+ /**
3405
+ * Run a script in the session's sandbox, as a console runs what's typed (what it declares stays for the next), and
3406
+ * say what it printed and what its last expression was. A command it calls that fails stops it, unless it catches the
3407
+ * error; what it printed before is said with why it stopped. Given up after `ms`.
3408
+ */
3409
+ async function runScript(s, script, ms) {
3410
+ const box = await sandboxOf(s);
3411
+ box.deadline = Date.now() + ms;
3412
+ box.aborted = false;
3413
+ box.running = true;
3414
+ box.read = void 0;
3415
+ await box.page.evaluate("globalThis.__said.length = 0");
3416
+ let timer;
3417
+ const late = new Promise((r) => {
3418
+ timer = setTimeout(() => {
3419
+ box.aborted = true;
3420
+ box.cdp.send("Runtime.terminateExecution").catch(() => {});
3421
+ r("late");
3422
+ }, ms);
3423
+ });
3424
+ const expression = relaxTopDecl(script, "let");
3425
+ const evaluated = box.cdp.send("Runtime.evaluate", {
3426
+ expression,
3427
+ replMode: true,
3428
+ awaitPromise: true,
3429
+ returnByValue: true
3430
+ });
3431
+ const r = await Promise.race([evaluated, late]).finally(() => {
3432
+ clearTimeout(timer);
3433
+ box.running = false;
3434
+ });
3435
+ const said = (await box.page.evaluate("globalThis.__said.splice(0)").catch(() => [])).join("\n");
3436
+ const cut = (text) => text.length > SCRIPT_MAX ? `${text.slice(0, SCRIPT_MAX)}… (${text.length - SCRIPT_MAX} more characters cut: print less)` : text;
3437
+ if (r === "late") {
3438
+ s.sandbox = void 0;
3439
+ await box.close();
3440
+ throw new UsageError(cut(`the script ran out of time (${Math.round(ms / 1e3)} s), and was stopped; what it declared went with it, so declare it again${said ? `. It printed:\n${said}` : ""}`));
3441
+ }
3442
+ if (r.exceptionDetails) {
3443
+ let why = (r.exceptionDetails.exception?.description ?? r.exceptionDetails.text ?? "it failed").replace(/^Error: /, "").split("\n at ")[0];
3444
+ const declared = /Identifier '([^']+)' has already been declared/.exec(why);
3445
+ if (declared) why += `: ${declared[1]} is taken (an earlier script declared it, or the sandbox page has it of its own); use another name, or put the script in { … }`;
3446
+ throw new UsageError(cut(`the script stopped: ${why}${said ? `\nit printed before:\n${said}` : ""}`));
3447
+ }
3448
+ return cut([said, r.result?.type === "undefined" ? "" : typeof r.result?.value === "string" ? r.result.value : r.result && "value" in r.result ? JSON.stringify(r.result.value) : r.result?.description ?? ""].filter(Boolean).join("\n") || "the script ran, and printed nothing");
3449
+ }
3450
+ // src/commands.ts
3451
+ /** How many refs a session remembers what they were (the oldest are let go first). */
3452
+ const SHOWN_MAX = 5e4;
3453
+ /** Remember each ref's role and name so a gone ref can suggest a replacement. */
3454
+ function rememberShown(s, now) {
3455
+ const walk = (n) => {
3456
+ if (n.ref && n.name) s.shown.set(n.ref, `${n.role}\u0000${n.name}`);
3457
+ for (const c of n.children ?? []) walk(c);
3458
+ };
3459
+ walk(now.root);
3460
+ if (s.shown.size > SHOWN_MAX) for (const k of [...s.shown.keys()].slice(0, s.shown.size - SHOWN_MAX)) s.shown.delete(k);
3461
+ }
3462
+ /** The page as the agent read it now: what the next changes are counted from, and what each of its refs was. */
3463
+ function readAs(s, now) {
3464
+ s.last = now;
3465
+ rememberShown(s, now);
3466
+ }
3467
+ /** What every refusal of a ref the page doesn't have says: the one message, whatever the reason it has none. */
3468
+ const noRef = (ref, how = "") => `${ref} is not a ref the page has now${how}: read the page again (agent-om snapshot).`;
3469
+ /**
3470
+ * What a gone ref's message says, and a fact with it when there is one: that the page now has exactly one thing of the
3471
+ * role and name the ref had. Whether that is the same thing drawn again is the reader's to judge: nothing is acted on.
3472
+ */
3473
+ async function goneRef(s, ref, how = "") {
3474
+ const now = await readNow(s).catch(() => void 0);
3475
+ const like = now && oneLike(s, ref, now);
3476
+ return `${noRef(ref, how)}${like ? ` The page now has one ${like.role} named ${JSON.stringify(like.name)}: ${like.ref}.` : ""}`;
3477
+ }
3478
+ /** The one node on the page now of the role and name a gone ref had, if there's exactly one. */
3479
+ function oneLike(s, ref, now) {
3480
+ const was = s.shown.get(ref);
3481
+ if (!was) return void 0;
3482
+ const found = [];
3483
+ const walk = (n) => {
3484
+ if (n.ref && n.ref !== ref && `${n.role}\u0000${n.name ?? ""}` === was) found.push(n);
3485
+ for (const c of n.children ?? []) walk(c);
3486
+ };
3487
+ walk(now.root);
3488
+ return found.length === 1 ? found[0] : void 0;
3489
+ }
3490
+ /** How long a script may run: it ends before the session gives up a command (two minutes), so it can say what it did. */
3491
+ const SCRIPT_MS = 1e5;
3492
+ /** How long an action's answer waits for a download it started before saying it isn't finished. */
3493
+ const DOWNLOAD_WAIT_MS = 3e4;
3494
+ /** A file the page downloads, saved in the session's folder under the name the page gives it (never over another), and said. */
3495
+ function saveDownload(s, d) {
3496
+ const name = basename(d.suggestedFilename()).replace(/[^\w.\- ()]/g, "_") || "download";
3497
+ mkdirSync(s.downloads, { recursive: true });
3498
+ let file = join(s.downloads, name);
3499
+ for (let k = 2; existsSync(file); k++) file = join(s.downloads, `${basename(name, extname(name))} (${k})${extname(name)}`);
3500
+ const saving = d.saveAs(file).then(() => void s.beside.push(`the page downloaded ${name} (${size(statSync(file).size)}): saved as ${file}`), () => void s.beside.push(`the page started downloading ${name}, but it failed: ${d.url()}`));
3501
+ s.saving.add(saving);
3502
+ saving.finally(() => s.saving.delete(saving));
3503
+ }
3504
+ const size = (bytes) => bytes < 1024 ? `${bytes} bytes` : bytes < 1048576 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`;
3505
+ /** Until the downloads being saved are saved, or a while: one still going is said, and said again when it's done. */
3506
+ async function downloaded(s) {
3507
+ if (!s.saving.size) return;
3508
+ const all = Promise.all([...s.saving]);
3509
+ if (await Promise.race([all.then(() => false), new Promise((r) => setTimeout(() => r(true), DOWNLOAD_WAIT_MS))])) s.beside.push(`a download isn't finished yet: it is said when it is (in ${s.downloads})`);
3510
+ }
3511
+ const KEPT = 200;
3512
+ const keep = (list, item) => {
3513
+ list.push(item);
3514
+ if (list.length > KEPT) list.shift();
3515
+ };
3516
+ /** An address without what it asks (`?…`) or its fragment: a query can carry a token. */
3517
+ function bare(url) {
3518
+ try {
3519
+ const u = new URL(url);
3520
+ return `${u.origin}${u.pathname}${u.search ? "?…" : ""}`;
3521
+ } catch {
3522
+ return url.split(/[?#]/)[0] ?? url;
3523
+ }
3524
+ }
3525
+ /** Follow what a tab's page logs and asks for. */
3526
+ function listen(tab) {
3527
+ tab.page.on("console", (m) => {
3528
+ const where = m.location();
3529
+ keep(tab.logged, {
3530
+ level: m.type(),
3531
+ text: m.text().slice(0, 500),
3532
+ ...where.url ? { where: `${bare(where.url)}:${where.lineNumber + 1}` } : {}
3533
+ });
3534
+ });
3535
+ tab.page.on("pageerror", (e) => keep(tab.logged, {
3536
+ level: "error",
3537
+ text: `uncaught: ${String(e.message).slice(0, 500)}`
3538
+ }));
3539
+ tab.page.on("requestfinished", (r) => void r.response().then((res) => keep(tab.requested, {
3540
+ method: r.method(),
3541
+ status: res?.status() ?? 0,
3542
+ url: r.url(),
3543
+ kind: r.resourceType()
3544
+ }), () => {}));
3545
+ tab.page.on("requestfailed", (r) => keep(tab.requested, {
3546
+ method: r.method(),
3547
+ status: "failed",
3548
+ url: r.url(),
3549
+ kind: r.resourceType(),
3550
+ error: r.failure()?.errorText ?? ""
3551
+ }));
3552
+ }
3553
+ const tabOf = (s, page) => s.tabs.find((t) => t.page === page);
3554
+ /** Work in another tab: the page read there before is what its next changes are counted from. */
3555
+ function switchTo(s, tab) {
3556
+ const from = tabOf(s, s.page);
3557
+ if (from) from.last = s.last;
3558
+ s.page = tab.page;
3559
+ s.last = tab.last;
3560
+ }
3561
+ /** How long an action waits for its element to take it (shown, still, enabled, not covered). */
3562
+ const STEP_MS = 5e3;
3563
+ /** Candidates listed when a text names several elements. */
3564
+ const CANDIDATES = 8;
3565
+ const flag = (a, name) => typeof a.flags[name] === "string" ? a.flags[name] : void 0;
3566
+ /** The element a command acts on: a ref from the view, or --text (what it shows) for one the view gives no ref. */
3567
+ async function target(s, a, now) {
3568
+ const text = flag(a, "text");
3569
+ if (text !== void 0) return byText(s, a, text, now);
3570
+ const ref = a._[0];
3571
+ if (!ref) throw new ToolError("give a ref from the view (e12), or --text \"what it shows\"");
3572
+ if (!/^e\d+$/.test(ref)) throw new ToolError(`'${ref}' isn't a ref: refs are written e12, as the view shows them`);
3573
+ const node = nodeOf(now, ref);
3574
+ const el = await elementOf(s.page, ref);
3575
+ if (!el) throw new ToolError(await goneRef(s, ref));
3576
+ const g = guard(now.root, ref);
3577
+ if (!node || !g) throw new ToolError(noRef(ref));
3578
+ return {
3579
+ el,
3580
+ ref,
3581
+ ...g,
3582
+ name: line(node, now.url)
3583
+ };
3584
+ }
3585
+ /**
3586
+ * What on the page shows a text, as a person would find it: shown, not inside what the page keeps out (ignored,
3587
+ * redacted, a secret field), and showing it with the session's secrets taken out, so a search never finds a secret
3588
+ * the session filled, nor tells a right guess of one from a wrong one.
3589
+ */
3590
+ async function showing(s, text, exact) {
3591
+ const all = s.page.getByText(text, { exact });
3592
+ const shown = [];
3593
+ const keptOut = inPage(["el"], `return !!el.closest('[data-agentom-ignore], [data-agentom-redact]') || (el.localName === 'input' && el.type === 'password')`);
3594
+ const wanted = squash(text);
3595
+ const shows = (t) => {
3596
+ if (!s.secrets.length) return true;
3597
+ const said = withoutSecrets(squash(t), s.secrets);
3598
+ return exact ? said === wanted : said.toLowerCase().includes(wanted.toLowerCase());
3599
+ };
3600
+ const total = await all.count();
3601
+ for (let k = 0; k < total; k++) {
3602
+ const one = all.nth(k);
3603
+ if (await one.isVisible() && !await one.evaluate(keptOut) && shows(await one.innerText().catch(() => ""))) shown.push(one);
3604
+ }
3605
+ return shown;
3606
+ }
3607
+ async function byText(s, a, text, now) {
3608
+ const exact = a.flags.exact === true;
3609
+ const nthFlag = flag(a, "nth");
3610
+ const nth = nthFlag === void 0 ? void 0 : Number(nthFlag);
3611
+ if (nth !== void 0 && !(Number.isInteger(nth) && nth >= 1)) throw new ToolError("--nth <n>: 1 for the first, 2 for the second…");
3612
+ const shown = await showing(s, text, exact);
3613
+ if (!shown.length) {
3614
+ const named = [];
3615
+ const want = squash(text).toLowerCase();
3616
+ const walk = (n) => {
3617
+ const name = squash(n.name ?? "").toLowerCase();
3618
+ if (n.ref && name && (exact ? name === want : name.includes(want))) named.push(n);
3619
+ for (const c of n.children ?? []) walk(c);
3620
+ };
3621
+ walk(now.root);
3622
+ if (named.length && named.length <= CANDIDATES) throw new ToolError(`nothing on the page shows ${JSON.stringify(text)}${exact ? " exactly" : ""} as text, but ${named.length === 1 ? "this is" : "these are"} named so: ${named.map((n) => `${n.role} ${JSON.stringify(n.name)} [${n.ref}]`).join("; ")}. Act on its ref`);
3623
+ throw new ToolError(`nothing on the page shows ${JSON.stringify(text)}${exact ? " exactly" : ""}: read the page (agent-om snapshot --match <word>) to see what does`);
3624
+ }
3625
+ if (shown.length > 1 && nth === void 0) {
3626
+ const lines = [];
3627
+ for (const [k, loc] of shown.slice(0, CANDIDATES).entries()) {
3628
+ const el = await loc.elementHandle();
3629
+ const around = await refAround(s.page, el, now);
3630
+ const node = around ? nodeOf(now, around) : void 0;
3631
+ const what = squash(await loc.innerText()).slice(0, 80);
3632
+ lines.push(` --nth ${k + 1}: ${JSON.stringify(what)}${node ? ` in ${line(node)}` : ""}`);
3633
+ }
3634
+ throw new UsageError(`${shown.length} things show ${JSON.stringify(text)}; say which with --nth (or use a ref):\n${lines.join("\n")}${shown.length > CANDIDATES ? `\n … ${shown.length - CANDIDATES} more` : ""}`);
3635
+ }
3636
+ const pick = shown[(nth ?? 1) - 1];
3637
+ if (!pick) throw new ToolError(`only ${shown.length} things show ${JSON.stringify(text)}`);
3638
+ const el = await pick.elementHandle();
3639
+ const labelled = (await el.evaluateHandle(inPage(["el"], "const l = el.closest(\"label\"); return (l && l.control) || null"))).asElement();
3640
+ const guards = [];
3641
+ for (const of of [el, labelled]) {
3642
+ const around = of ? await refAround(s.page, of, now) : void 0;
3643
+ const g = around ? guard(now.root, around) : void 0;
3644
+ if (g) guards.push(g);
3645
+ }
3646
+ const asks = guards.find((g) => g.asks)?.asks;
3647
+ return {
3648
+ el,
3649
+ ...asks ? { asks } : {},
3650
+ credential: guards.some((g) => g.credential),
3651
+ name: `the ${nth ? `${ordinal(nth)} ` : ""}element showing ${JSON.stringify(text)}`
3652
+ };
3653
+ }
3654
+ const squash = (x) => x.replace(/\s+/g, " ").trim();
3655
+ const ordinal = (n) => `${n}${n % 10 === 1 && n !== 11 ? "st" : n % 10 === 2 && n !== 12 ? "nd" : n % 10 === 3 && n !== 13 ? "rd" : "th"}`;
3656
+ /** What covers an element where a pointer would land, as the view names it. */
3657
+ async function coveredBy(s, t, now) {
3658
+ const box = await t.el.boundingBox().catch(() => null);
3659
+ if (!box) return void 0;
3660
+ const session = await cdp(s.page);
3661
+ try {
3662
+ const at = await session.send("DOM.getNodeForLocation", {
3663
+ x: Math.round(box.x + box.width / 2),
3664
+ y: Math.round(box.y + box.height / 2),
3665
+ includeUserAgentShadowDOM: false
3666
+ });
3667
+ const el = await elementOf(s.page, `e${at.backendNodeId}`);
3668
+ if (!el) return void 0;
3669
+ if (await el.evaluate(inPage(["el", "target"], "return target.contains(el)"), t.el)) return void 0;
3670
+ const around = await refAround(s.page, el, now);
3671
+ const path = around ? pathTo(now, around) : void 0;
3672
+ const holder = path?.find((n) => [
3673
+ "dialog",
3674
+ "alertdialog",
3675
+ "menu",
3676
+ "listbox",
3677
+ "tooltip",
3678
+ "banner"
3679
+ ].includes(n.role)) ?? path?.at(-1);
3680
+ if (holder) return line(holder);
3681
+ const open = openOverlay(now.root);
3682
+ return open ? `something with no ref, while ${line(open)} is open,` : "something with no ref";
3683
+ } catch {
3684
+ return;
3685
+ }
3686
+ }
3687
+ /** The dialog, menu or list of choices open on the page, if one is: what a backdrop that covers the page belongs with. */
3688
+ function openOverlay(n) {
3689
+ if (["dialog", "alertdialog"].includes(n.role) || ["menu", "listbox"].includes(n.role) && n.states?.expanded !== false) return n;
3690
+ for (const c of n.children ?? []) {
3691
+ const f = openOverlay(c);
3692
+ if (f) return f;
3693
+ }
3694
+ }
3695
+ /** Run an action on a target; when it can't be done in time, say why and what to try. */
3696
+ async function act(s, t, verb, now, run) {
3697
+ const on = s.page;
3698
+ try {
3699
+ await run();
3700
+ } catch (e) {
3701
+ const message = String(e.message ?? e);
3702
+ if (e instanceof UsageError) throw e;
3703
+ if (/has been closed|Target closed/i.test(message) && on.isClosed()) return;
3704
+ if (/not an <input>|not an input|not editable|Element is not an/i.test(message) && (verb === "fill" || verb === "type into")) throw new UsageError(notAField(t));
3705
+ if (/selectOption|not a <select>|Element is not a <select>/i.test(message)) throw new UsageError(`${t.name} is not a native drop-down`);
3706
+ if (/not attached to the DOM|Node is detached/i.test(message)) throw new ToolError(t.ref ? await goneRef(s, t.ref, " (the page drew it anew while this waited for it)") : `${t.name} is not on the page now (the page drew it anew): read the page again (agent-om snapshot).`);
3707
+ if (e.name === "TimeoutError" || /timeout/i.test(message)) {
3708
+ const over = await coveredBy(s, t, now);
3709
+ if (over) throw new UsageError(`couldn't ${verb} ${t.name}: ${over} is over it, where a person's pointer would land. Close that first (its close button, or press Escape)`);
3710
+ if (!await t.el.isVisible().catch(() => false)) throw new UsageError(`couldn't ${verb} ${t.name}: it isn't shown now (hidden, or in a part that's closed). Open what holds it first`);
3711
+ if (!await t.el.isEnabled().catch(() => true)) throw new UsageError(`couldn't ${verb} ${t.name}: it's disabled. Something else has to be done first`);
3712
+ throw new UsageError(`couldn't ${verb} ${t.name} within ${STEP_MS / 1e3} s: it kept moving`);
3713
+ }
3714
+ throw new UsageError(`couldn't ${verb} ${t.name}: ${message.split("\n")[0]}`);
3715
+ }
3716
+ }
3717
+ /** Where everything that scrolls under a point is scrolled to (the page included): the same before and after a wheel turn means nothing moved. */
3718
+ const SCROLLED = `
3719
+ const [px, py] = p
3720
+ const out = [window.scrollX, window.scrollY]
3721
+ for (let e = document.elementFromPoint(px, py); e; e = e.parentElement) out.push(e.scrollTop, e.scrollLeft)
3722
+ return out
3723
+ `;
3724
+ /** Whether an element takes typed text: a text field, a text area, something edited in place. */
3725
+ const TAKES_TEXT = `
3726
+ if (el.isContentEditable) return true
3727
+ if (el.localName === 'textarea') return !el.disabled && !el.readOnly
3728
+ if (el.localName === 'input') return !el.disabled && !el.readOnly && !['button', 'submit', 'reset', 'checkbox', 'radio', 'file', 'image', 'range', 'color', 'hidden'].includes(el.type)
3729
+ return false
3730
+ `;
3731
+ /** What to say when a target takes no text: the field inside it, if it holds one. */
3732
+ function notAField(t) {
3733
+ const field = t.node && firstInside(t.node, (n) => [
3734
+ "textbox",
3735
+ "searchbox",
3736
+ "combobox",
3737
+ "spinbutton"
3738
+ ].includes(n.role) && n !== t.node);
3739
+ return `${t.name} is not a text field, so nothing was typed${field ? `; it holds ${line(field)}: type into that` : ". Click it to see whether a field opens"}`;
3740
+ }
3741
+ function firstInside(n, test) {
3742
+ if (test(n)) return n;
3743
+ for (const c of n.children ?? []) {
3744
+ const f = firstInside(c, test);
3745
+ if (f) return f;
3746
+ }
3747
+ }
3748
+ /**
3749
+ * The markup of an element and a few levels inside it, for what no accessible
3750
+ * name or state says (a box ticked only by a class, a row's own test id). It
3751
+ * reads attributes and text, never a field's value; nothing inside
3752
+ * data-agentom-ignore, and no text inside data-agentom-redact or a secret field;
3753
+ * inside data-agentom-redact, only the attributes that say what an element is
3754
+ * (a title, a label, an address or the app's data can say the secret).
3755
+ */
3756
+ const INSPECT = `
3757
+ const KEEP = /^(class|id|role|type|name|href|src|alt|title|placeholder|for|disabled|checked|selected|hidden|tabindex|contenteditable|data-.*|aria-.*)$/
3758
+ const REDACTED_KEEP = /^(class|id|role|type|name|for|disabled|hidden|tabindex|data-agentom-id|data-agentom-ignore)$/
3759
+ const TOKENS = new Set(${JSON.stringify(SECRET_AUTOCOMPLETE_TOKENS)})
3760
+ const MAX = 30, DEPTH = 3
3761
+ const out = []
3762
+ let n = 0
3763
+ for (let k = 0; k < up && el.parentElement && el.parentElement !== document.body; k++) el = el.parentElement
3764
+ const short = (e) => e.tagName.toLowerCase() + (e.id ? '#' + e.id : '') + (e.getAttribute('class') ? '.' + e.getAttribute('class').trim().split(/\\s+/).slice(0, 3).join('.') : '')
3765
+ const outer = []
3766
+ for (let p = el.parentElement, k = 0; p && p !== document.body && k < 3; p = p.parentElement, k++) outer.unshift(short(p))
3767
+ if (outer.length) out.push('(inside ' + outer.join(' > ') + '; --parent 1 inspects what holds it)')
3768
+ // core's isSecretField, as a string: a password, a field whose autocomplete is a secret token, a choice of one, data-agentom-redact
3769
+ const field = (e) => (e.localName === 'input' || e.localName === 'select' || e.localName === 'textarea') && (e.getAttribute('autocomplete') || '').toLowerCase().split(/\\s+/).some((t) => TOKENS.has(t))
3770
+ const secret = (e) => !!e.closest('[data-agentom-redact]') || (e.localName === 'input' && e.type === 'password') || field(e) || (e.localName === 'option' && !!e.closest('select') && field(e.closest('select')))
3771
+ const walk = (e, depth) => {
3772
+ if (n >= MAX || e.closest('[data-agentom-ignore]')) return
3773
+ n++
3774
+ const redacted = !!e.closest('[data-agentom-redact]')
3775
+ const attrs = [...e.attributes].filter((x) => (redacted ? REDACTED_KEEP : KEEP).test(x.name) && !(x.name === 'data-agentom-redact')).map((x) => x.value === '' ? x.name : x.name + '=' + JSON.stringify(x.value.length > 120 ? x.value.slice(0, 120) + '…' : x.value))
3776
+ const own = secret(e) ? '' : [...e.childNodes].filter((c) => c.nodeType === 3).map((c) => c.nodeValue).join(' ').replace(/\\s+/g, ' ').trim()
3777
+ const state = []
3778
+ if ('checked' in e && (e.type === 'checkbox' || e.type === 'radio') && !secret(e)) state.push(e.checked ? '(checked now)' : '(not checked now)')
3779
+ out.push(' '.repeat(depth) + '<' + e.tagName.toLowerCase() + (attrs.length ? ' ' + attrs.join(' ') : '') + '>' + (own ? ' ' + JSON.stringify(own.length > 80 ? own.slice(0, 80) + '…' : own) : '') + (state.length ? ' ' + state.join(' ') : ''))
3780
+ if (depth < DEPTH && !secret(e)) for (const c of e.children) walk(c, depth + 1)
3781
+ }
3782
+ walk(el, 0)
3783
+ if (n >= MAX) out.push('… more inside (inspect a ref inside it)')
3784
+ return out
3785
+ `;
3786
+ /**
3787
+ * What the page keeps out, as text, for what eval returns: every secret field's value (a secret drop-down's chosen
3788
+ * text too), every text inside data-agentom-redact, and what data-agentom-ignore holds, in the document and its open
3789
+ * shadow roots. Core's keptOutTexts, as a string (by core's isSecretField).
3790
+ */
3791
+ const KEPT_OUT = `
3792
+ const TOKENS = new Set(${JSON.stringify(SECRET_AUTOCOMPLETE_TOKENS)})
3793
+ const tokened = (e) => (e.localName === 'input' || e.localName === 'select' || e.localName === 'textarea') && (e.getAttribute('autocomplete') || '').toLowerCase().split(/\\s+/).some((t) => TOKENS.has(t))
3794
+ const secret = (e) => !!e.closest('[data-agentom-redact]') || (e.localName === 'input' && e.type === 'password') || tokened(e)
3795
+ const out = new Set()
3796
+ const add = (v) => { const t = (v || '').trim(); if (t.length >= 3) out.add(t) }
3797
+ const roots = [document]
3798
+ for (let i = 0; i < roots.length; i++) for (const el of roots[i].querySelectorAll('*')) if (el.shadowRoot) roots.push(el.shadowRoot)
3799
+ for (const r of roots) for (const el of r.querySelectorAll('*')) {
3800
+ if ((el.localName === 'input' || el.localName === 'textarea') && secret(el)) add(el.value)
3801
+ if (el.localName === 'select' && secret(el)) for (const o of el.selectedOptions) { add(o.value); add(o.text) }
3802
+ if (el.matches('[data-agentom-redact], [data-agentom-ignore]')) add(el.innerText || el.textContent)
3803
+ if (el.matches('[data-agentom-redact]')) { const texts = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); for (let t = texts.nextNode(); t; t = texts.nextNode()) add(t.nodeValue) }
3804
+ }
3805
+ return [...out]
3806
+ `;
3807
+ /** How much of what eval returns the agent is told. */
3808
+ const EVAL_MAX = 1e4;
3809
+ /**
3810
+ * A script, as eval runs it: an async function's body, what it returns said as text (JSON for anything but a text),
3811
+ * with what kind of thing it was: a script of the tool's that asked for it gets the value back, not the text.
3812
+ */
3813
+ const evalScript = (script) => `(async () => {
3814
+ const v = await (async () => {
3815
+ ${script}
3816
+ })()
3817
+ if (typeof v === 'string') return { kind: 'text', said: v }
3818
+ if (v === undefined) return { kind: 'none', said: 'nothing (undefined)' }
3819
+ try { const j = JSON.stringify(v); return j === undefined ? { kind: 'text', said: String(v) } : { kind: 'json', said: j } } catch { return { kind: 'text', said: String(v) } }
3820
+ })()`;
3821
+ /**
3822
+ * Black boxes over what the projection keeps out, for a screenshot (removed with UNMASK after it): what the app keeps
3823
+ * out (data-agentom-redact, data-agentom-ignore), a secret field that shows what it holds (a password field shows
3824
+ * dots), and any field or text showing a secret the session filled. Placed on the document, so a whole-page capture
3825
+ * covers them where they are. The page side's masks, by the same rule (core's isSecretField, as a string).
3826
+ */
3827
+ const MASK = `
3828
+ const TOKENS = new Set(${JSON.stringify(SECRET_AUTOCOMPLETE_TOKENS)})
3829
+ const OWN = '__agentom_masks'
3830
+ document.getElementById(OWN)?.remove()
3831
+ const tokened = (e) => (e.localName === 'input' || e.localName === 'select' || e.localName === 'textarea') && (e.getAttribute('autocomplete') || '').toLowerCase().split(/\\s+/).some((t) => TOKENS.has(t))
3832
+ const secretField = (e) => !!e.closest('[data-agentom-redact]') || tokened(e)
3833
+ // the document and every open shadow root in it: the projection reads them, so they're masked too
3834
+ const roots = [document]
3835
+ for (let i = 0; i < roots.length; i++) for (const el of roots[i].querySelectorAll('*')) if (el.shadowRoot) roots.push(el.shadowRoot)
3836
+ const everywhere = (selector) => roots.flatMap((r) => [...r.querySelectorAll(selector)])
3837
+ const out = []
3838
+ const add = (el) => { if (!out.some((o) => o === el || o.contains(el))) out.push(el) }
3839
+ for (const el of everywhere('[data-agentom-redact], [data-agentom-ignore]')) {
3840
+ if (el.id === OWN || el.parentElement?.closest('[data-agentom-redact], [data-agentom-ignore]')) continue
3841
+ add(el)
3842
+ }
3843
+ const shown = secrets.filter((v) => v.length >= 3)
3844
+ const shows = (s) => shown.some((v) => s.includes(v))
3845
+ for (const el of everywhere('input, textarea, select')) {
3846
+ const value = el.value || ''
3847
+ if ((secretField(el) && el.type !== 'password' && value) || (value && shows(value))) add(el)
3848
+ }
3849
+ if (shown.length) {
3850
+ for (const r of roots) {
3851
+ const top = r === document ? document.body : r
3852
+ if (!top) continue
3853
+ const texts = document.createTreeWalker(top, NodeFilter.SHOW_TEXT)
3854
+ for (let t = texts.nextNode(); t; t = texts.nextNode()) if (t.parentElement && shows(t.nodeValue || '')) add(t.parentElement)
3855
+ }
3856
+ }
3857
+ const areas = out.map((el) => el.getBoundingClientRect()).filter((r) => r.width > 0 && r.height > 0)
3858
+ if (!areas.length) return 0
3859
+ const host = document.createElement('div')
3860
+ host.id = OWN
3861
+ host.setAttribute('data-agentom-ignore', '')
3862
+ host.style.cssText = 'position:absolute;left:0;top:0;width:0;height:0;overflow:visible;z-index:2147483647;pointer-events:none;'
3863
+ const shadow = host.attachShadow({ mode: 'closed' })
3864
+ for (const r of areas) {
3865
+ const box = document.createElement('div')
3866
+ box.style.cssText = 'position:absolute;background:#000;left:' + Math.floor(r.left + scrollX) + 'px;top:' + Math.floor(r.top + scrollY) + 'px;width:' + (Math.ceil(r.width) + 1) + 'px;height:' + (Math.ceil(r.height) + 1) + 'px;'
3867
+ shadow.append(box)
3868
+ }
3869
+ document.documentElement.append(host)
3870
+ return areas.length
3871
+ `;
3872
+ const UNMASK = `document.getElementById('__agentom_masks')?.remove()`;
3873
+ /** What a key pressed on an element sets off: Enter in a field submits its form through the form's default button (or the form, with none); anything else acts on the element. */
3874
+ const SETS_OFF = `
3875
+ const key = combo.split('+').pop()
3876
+ if (key !== 'Enter' || el.localName !== 'input' || !el.form) return el
3877
+ const button = Array.from(el.form.elements).find((e) => (e.localName === 'button' && e.type === 'submit') || (e.localName === 'input' && (e.type === 'submit' || e.type === 'image')))
3878
+ return button || el.form
3879
+ `;
3880
+ /** What the app asks to be confirmed (data-agentom-confirmation): refused unless the command says --confirm. */
3881
+ function confirmFirst(t, a) {
3882
+ const asking = t.asks ?? t.node;
3883
+ if (asking?.meta?.confirm && a.flags.confirm !== true) throw new ToolError("This must be confirmed first: the page says so. If the user's request asks for exactly this, run the same command with --confirm; if not, ask the user. It is:", asking === t.node ? t.name : `${t.name} in ${line(asking)}`);
3884
+ }
3885
+ /** A credential field takes only what the user gives through fill-secret: a model never types one. */
3886
+ function noCredential(t) {
3887
+ if (t.node?.credential || t.credential) throw new ToolError(`This is a credential field: fill it with agent-om fill-secret ${t.ref ?? "<ref>"} <VARIABLE> (the value comes from the user, never typed). It is:`, t.name);
3888
+ }
3889
+ /** Everything a command says, with every secret the session filled taken out. */
3890
+ /** The text with the session's secrets taken out, in every form a page writes them (core's view entry, secretForms). */
3891
+ const said = (s, text) => withoutSecrets(text, s.secrets);
3892
+ /** Every string in it with these secrets taken out. */
3893
+ function scrubbed(value, secrets) {
3894
+ if (!secrets.length) return value;
3895
+ if (typeof value === "string") return withoutSecrets(value, secrets);
3896
+ if (Array.isArray(value)) return value.map((v) => scrubbed(v, secrets));
3897
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, scrubbed(v, secrets)]));
3898
+ return value;
3899
+ }
3900
+ /**
3901
+ * The page as read, with every secret the session filled taken out of every string in it before anything looks at it:
3902
+ * what --match, a script's om.find and the changes compare is never a secret, so no search can tell a right guess of
3903
+ * one from a wrong one.
3904
+ */
3905
+ const readNow = async (s) => scrubbed(await read(s.page), s.secrets);
3906
+ /**
3907
+ * After an action: wait for the page, then say what was done, what happened
3908
+ * beside it, and what changed. When the action opened a tab (a popup, a link to
3909
+ * a new tab), the agent is in it now and reads it whole; when it closed the
3910
+ * agent's tab (a sign-in window, once signed in), the agent is back in the tab
3911
+ * that opened it and reads what changed there.
3912
+ */
3913
+ async function after(s, done, action = true) {
3914
+ const from = s.page;
3915
+ let settled = await settle(s.page, void 0, action).catch(() => true);
3916
+ await tabsOpened(s);
3917
+ await downloaded(s);
3918
+ const moved = [];
3919
+ if (s.closed) moved.push(s.closed);
3920
+ s.closed = void 0;
3921
+ for (const tab of s.fresh.splice(0)) if (tab.opener === s.page) {
3922
+ const opener = tabOf(s, s.page);
3923
+ switchTo(s, tab);
3924
+ moved.push(`the page opened a new tab (tab ${tab.n}) at ${tab.page.url()}: you are in it now. agent-om switch-tab ${opener?.n ?? 1} goes back`);
3925
+ } else moved.push(opened(tab));
3926
+ if (s.page !== from) settled = await settle(s.page, void 0, false).catch(() => true);
3927
+ const now = await readNow(s);
3928
+ const lines = [
3929
+ done,
3930
+ ...s.beside.splice(0),
3931
+ ...moved
3932
+ ];
3933
+ if (!settled) lines.push("(the page was still changing; read it again if something seems missing)");
3934
+ if (s.last) lines.push(changes(s.last, now).text);
3935
+ else lines.push(view(now));
3936
+ readAs(s, now);
3937
+ return lines.join("\n");
3938
+ }
3939
+ /** A command that acts on one target. */
3940
+ const step = (verb, done, run, check) => async (s, a) => {
3941
+ const ref = flag(a, "text") === void 0 ? a._[0] : void 0;
3942
+ const now = (ref && s.last && s.last.url === s.page.url() && nodeOf(s.last, ref) ? s.last : void 0) ?? await readNow(s);
3943
+ const t = await target(s, a, now);
3944
+ try {
3945
+ confirmFirst(t, a);
3946
+ check?.(t, a);
3947
+ await act(s, t, verb, now, () => run(s, t, a));
3948
+ return await after(s, `${done} ${t.name}`);
3949
+ } finally {
3950
+ await t.el.dispose().catch(() => {});
3951
+ }
3952
+ };
3953
+ /** The text a command types: what follows the target. */
3954
+ const textOf = (a) => {
3955
+ const text = flag(a, "text") !== void 0 ? a._[0] : a._[1];
3956
+ if (text === void 0) throw new ToolError("give the text: agent-om fill <ref> \"text\"");
3957
+ return text;
3958
+ };
3959
+ /**
3960
+ * The time now, and the time zone the browser's pages show times in: a page seldom says either, and "the last 7
3961
+ * days" or "still down" can't be worked out without them. The time is the tool's own clock; the zone is asked of the
3962
+ * page, which can make it say anything, so only the name of a real time zone is taken from it, and a page that
3963
+ * doesn't answer is left out.
3964
+ */
3965
+ async function nowLine(s) {
3966
+ let timer;
3967
+ const zone = await Promise.race([s.page.evaluate("Intl.DateTimeFormat().resolvedOptions().timeZone").catch(() => void 0), new Promise((r) => timer = setTimeout(() => r(void 0), 2e3))]);
3968
+ clearTimeout(timer);
3969
+ return clockLine(/* @__PURE__ */ new Date(), isTimeZone(zone) ? zone : void 0);
3970
+ }
3971
+ /** Whether a value is a time zone's name, as this machine knows them: nothing else a page says is repeated as the tool's words. */
3972
+ function isTimeZone(zone) {
3973
+ if (typeof zone !== "string" || !/^[A-Za-z0-9_+\-/]{1,64}$/.test(zone)) return false;
3974
+ try {
3975
+ new Intl.DateTimeFormat("en", { timeZone: zone });
3976
+ return true;
3977
+ } catch {
3978
+ return false;
3979
+ }
3980
+ }
3981
+ /** How a command asks for the page narrowed as it's printed: snapshot's options, and open's for the page it loads. */
3982
+ function narrowed(a) {
3983
+ const o = {};
3984
+ const depth = flag(a, "depth");
3985
+ if (depth !== void 0) o.depth = Number(depth);
3986
+ if (a.flags.interactive === true || a.flags.i === true) o.interactive = true;
3987
+ const match = flag(a, "match");
3988
+ if (match) o.match = match.split(/\\?[,|]/).map((w) => w.trim()).filter(Boolean);
3989
+ const limit = flag(a, "limit");
3990
+ if (limit !== void 0) o.limit = Number(limit);
3991
+ return o;
3992
+ }
3993
+ const COMMANDS = {
3994
+ async open(s, a) {
3995
+ const where = a._[0];
3996
+ if (!where) throw new ToolError("agent-om open <address or path>");
3997
+ if (asksForKept(where)) throw new ToolError(`'${where}' isn't an address: … stands for this page's own query, which the link keeps. Click the link to follow it, or write the query out (agent-om url gives the page's)`);
3998
+ const base = s.page.url().startsWith("http") ? s.page.url() : void 0;
3999
+ let url;
4000
+ try {
4001
+ url = new URL(where, base).href;
4002
+ } catch {
4003
+ throw new ToolError(`'${where}' isn't an address (https://…) or, once a page is open, a path on its site (/settings)`);
4004
+ }
4005
+ if (s.allowed && !s.allowed.includes(new URL(url).origin)) throw new ToolError(`${new URL(url).origin} isn't one of the sites this session may open: ${s.allowed.join(", ")}`);
4006
+ await watch(s.page);
4007
+ try {
4008
+ await s.page.goto(url, { waitUntil: "domcontentloaded" });
4009
+ } catch (e) {
4010
+ if (!/Download is starting/i.test(String(e.message))) throw e;
4011
+ await new Promise((r) => setTimeout(r, 100));
4012
+ await downloaded(s);
4013
+ return [...s.beside.splice(0)].join("\n") || "the address is a file to download, but nothing was saved";
4014
+ }
4015
+ await settle(s.page);
4016
+ const now = await readNow(s);
4017
+ readAs(s, now);
4018
+ return [
4019
+ ...s.beside.splice(0),
4020
+ await nowLine(s),
4021
+ view(now, narrowed(a))
4022
+ ].join("\n");
4023
+ },
4024
+ async snapshot(s, a) {
4025
+ const now = await readNow(s);
4026
+ const o = narrowed(a);
4027
+ const scope = flag(a, "scope") ?? a._[0];
4028
+ if (scope) o.scope = scope;
4029
+ readAs(s, now);
4030
+ return scope ? view(now, o) : `${await nowLine(s)}\n${view(now, o)}`;
4031
+ },
4032
+ async changes(s) {
4033
+ const now = await readNow(s);
4034
+ const out = s.last ? changes(s.last, now).text : view(now);
4035
+ readAs(s, now);
4036
+ return out;
4037
+ },
4038
+ click: step("click", "clicked", (_s, t) => t.el.click({ timeout: STEP_MS })),
4039
+ dblclick: step("double-click", "double-clicked", (_s, t) => t.el.dblclick({ timeout: STEP_MS })),
4040
+ hover: step("hover over", "hovering over", (_s, t) => t.el.hover({ timeout: STEP_MS })),
4041
+ check: step("check", "checked", (_s, t) => t.el.check({ timeout: STEP_MS })),
4042
+ uncheck: step("uncheck", "unchecked", (_s, t) => t.el.uncheck({ timeout: STEP_MS })),
4043
+ fill: step("fill", "filled", (_s, t, a) => t.el.fill(textOf(a), { timeout: STEP_MS }), noCredential),
4044
+ type: step("type into", "typed into", async (s, t, a) => {
4045
+ if (!await t.el.evaluate(inPage(["el"], TAKES_TEXT))) throw new UsageError(notAField(t));
4046
+ await t.el.focus();
4047
+ if (!await t.el.evaluate(inPage(["el"], "return el === document.activeElement || el.contains(document.activeElement)"))) throw new UsageError(`${t.name} didn't take the focus, so nothing was typed. Click it first, or fill it`);
4048
+ await s.page.keyboard.type(textOf(a));
4049
+ }, noCredential),
4050
+ async select(s, a) {
4051
+ const now = await readNow(s);
4052
+ const t = await target(s, a, now);
4053
+ confirmFirst(t, a);
4054
+ const values = flag(a, "text") !== void 0 ? a._ : a._.slice(1);
4055
+ if (!values.length) throw new ToolError("agent-om select <ref> <choice…>");
4056
+ if (await t.el.evaluate(inPage(["el"], "return el.localName === \"select\""))) {
4057
+ await act(s, t, "choose in", now, async () => {
4058
+ const options = await t.el.evaluate(inPage(["el"], "return [...el.options].map((o) => ({ value: o.value, label: o.label.trim() }))"));
4059
+ const wanted = values.map((v) => options.find((o) => o.label === v) ?? options.find((o) => o.value === v) ?? options.find((o) => o.label.toLowerCase().includes(v.toLowerCase())));
4060
+ const missing = values.filter((_, k) => !wanted[k]);
4061
+ if (missing.length) throw new UsageError(`${t.name} has no choice ${missing.map((m) => JSON.stringify(m)).join(", ")}; its choices: ${options.map((o) => JSON.stringify(o.label)).join(", ")}`);
4062
+ await t.el.selectOption(wanted.map((o) => ({ value: o.value })), { timeout: STEP_MS });
4063
+ });
4064
+ return after(s, `chose ${values.map((v) => JSON.stringify(v)).join(", ")} in ${t.name}`);
4065
+ }
4066
+ if (!(t.node?.states?.expanded === true || await t.el.getAttribute("aria-expanded").catch(() => null) === "true")) await act(s, t, "open", now, () => t.el.click({ timeout: STEP_MS }));
4067
+ for (const v of values) {
4068
+ await settle(s.page, 2e3);
4069
+ const exact = s.page.getByRole("option", {
4070
+ name: v,
4071
+ exact: true
4072
+ });
4073
+ const loose = s.page.getByRole("option", { name: v });
4074
+ const option = await exact.count() ? exact.first() : await loose.count() ? loose.first() : void 0;
4075
+ if (!option) {
4076
+ const shown = await s.page.getByRole("option").allInnerTexts().catch(() => []);
4077
+ throw new UsageError(`${t.name} opened, but shows no option ${JSON.stringify(v)}${shown.length ? `; it shows: ${shown.slice(0, 20).map((o) => JSON.stringify(squash(o))).join(", ")}` : "; it shows no options: maybe type into its search box first"}`);
4078
+ }
4079
+ await option.click({ timeout: STEP_MS });
4080
+ }
4081
+ return after(s, `chose ${values.map((v) => JSON.stringify(v)).join(", ")} in ${t.name}`);
4082
+ },
4083
+ async press(s, a) {
4084
+ const byTextTarget = flag(a, "text") !== void 0;
4085
+ const hasTarget = byTextTarget || a._.length > 1;
4086
+ const key = byTextTarget ? a._[0] : a._.length > 1 ? a._[1] : a._[0];
4087
+ if (!key) throw new ToolError("agent-om press <key> (Enter, Escape, Tab, ArrowDown, Control+A…), or press <ref> <key>");
4088
+ const now = await readNow(s);
4089
+ const t = hasTarget ? await target(s, byTextTarget ? {
4090
+ ...a,
4091
+ _: []
4092
+ } : {
4093
+ ...a,
4094
+ _: [a._[0]]
4095
+ }, now) : void 0;
4096
+ const off = await (t?.el ?? await s.page.evaluateHandle("(() => { let a = document.activeElement; while (a && a.shadowRoot && a.shadowRoot.activeElement) a = a.shadowRoot.activeElement; return a || document.body })()")).evaluateHandle(inPage(["el", "combo"], SETS_OFF), key);
4097
+ const ref = await refAround(s.page, off, now);
4098
+ const g = ref ? guard(now.root, ref) : void 0;
4099
+ const node = g?.node ?? (ref ? nodeOf(now, ref) : void 0);
4100
+ const asks = g?.asks ?? (off === t?.el ? t?.asks : void 0);
4101
+ confirmFirst({
4102
+ el: off,
4103
+ ...ref ? { ref } : {},
4104
+ ...node ? { node } : {},
4105
+ ...asks ? { asks } : {},
4106
+ name: node ? line(node, now.url) : t?.name ?? "the focused element"
4107
+ }, a);
4108
+ if (t) {
4109
+ await act(s, t, `press ${key} on`, now, () => t.el.press(key, { timeout: STEP_MS }));
4110
+ return after(s, `pressed ${key} on ${t.name}`);
4111
+ }
4112
+ await s.page.keyboard.press(key);
4113
+ return after(s, `pressed ${key}`);
4114
+ },
4115
+ async scroll(s, a) {
4116
+ const up = a.flags.up === true;
4117
+ const by = Number(flag(a, "by") ?? 0) || await s.page.evaluate("window.innerHeight * 0.8");
4118
+ let moved = true;
4119
+ const wheel = async (x, y) => {
4120
+ await s.page.mouse.move(x, y);
4121
+ const where = await s.page.evaluate(inPage(["p"], SCROLLED), [x, y]);
4122
+ await s.page.mouse.wheel(0, up ? -by : by);
4123
+ await s.page.waitForTimeout(150);
4124
+ moved = (await s.page.evaluate(inPage(["p"], SCROLLED), [x, y])).join() !== where.join();
4125
+ };
4126
+ const still = () => moved ? "" : `\nnothing scrolled: what's under the pointer is already at its ${up ? "top" : "bottom"}, or doesn't scroll. If a list should hold more, try another part of it (a ref inside it), or the app's search`;
4127
+ if (a._[0] || flag(a, "text") !== void 0) {
4128
+ const now = await readNow(s);
4129
+ const t = await target(s, a, now);
4130
+ if (up || a.flags.down === true) {
4131
+ await act(s, t, "scroll in", now, async () => {
4132
+ await t.el.scrollIntoViewIfNeeded({ timeout: STEP_MS });
4133
+ const box = await t.el.boundingBox();
4134
+ if (!box) throw new UsageError(`${t.name} isn't shown, so there's nothing to scroll in`);
4135
+ const view = s.page.viewportSize() ?? {
4136
+ width: 1280,
4137
+ height: 900
4138
+ };
4139
+ const x = Math.max(0, Math.min(view.width - 1, box.x + box.width / 2));
4140
+ const y = Math.max(0, Math.min(view.height - 1, Math.max(box.y, 0) / 2 + Math.min(box.y + box.height, view.height) / 2));
4141
+ await wheel(x, y);
4142
+ });
4143
+ return after(s, `scrolled ${t.name} ${up ? "up" : "down"}${still()}`);
4144
+ }
4145
+ await act(s, t, "scroll to", now, () => t.el.scrollIntoViewIfNeeded({ timeout: STEP_MS }));
4146
+ return after(s, `scrolled to ${t.name}`);
4147
+ }
4148
+ const view = s.page.viewportSize() ?? {
4149
+ width: 1280,
4150
+ height: 900
4151
+ };
4152
+ await wheel(view.width / 2, view.height / 2);
4153
+ return after(s, `scrolled the page ${up ? "up" : "down"}${still()}`);
4154
+ },
4155
+ async inspect(s, a) {
4156
+ const t = await target(s, a, await readNow(s));
4157
+ const up = Number(flag(a, "parent") ?? 0);
4158
+ if (!(Number.isInteger(up) && up >= 0)) throw new ToolError("--parent <n>: how many levels out from the element (1: what holds it)");
4159
+ const lines = await t.el.evaluate(inPage(["el", "up"], INSPECT), up);
4160
+ return [`${up ? `${up} level${up > 1 ? "s" : ""} out from ` : ""}${t.name}, in the page's markup:`, ...lines].join("\n");
4161
+ },
4162
+ async upload(s, a) {
4163
+ const now = await readNow(s);
4164
+ const t = await target(s, a, now);
4165
+ confirmFirst(t, a);
4166
+ const files = flag(a, "text") !== void 0 ? a._ : a._.slice(1);
4167
+ if (!files.length) throw new ToolError("agent-om upload <ref> <file…>");
4168
+ await act(s, t, "upload to", now, () => t.el.setInputFiles(files, { timeout: STEP_MS }));
4169
+ return after(s, `chose ${files.length} file${files.length > 1 ? "s" : ""} for ${t.name}`);
4170
+ },
4171
+ async "fill-secret"(s, a, env) {
4172
+ const variable = flag(a, "text") !== void 0 ? a._[0] : a._[1];
4173
+ if (!variable) throw new ToolError("agent-om fill-secret <ref> <VARIABLE>: the value comes from the environment variable, and is never shown");
4174
+ const site = env[`${variable}_ORIGIN`];
4175
+ if (site === void 0) throw new ToolError(`$${variable} isn't tied to a site: fill-secret takes only a variable the user tied to the site it's for, with ${variable}_ORIGIN (https://example.com). If this secret is for this page's site, ask the user to set both. fill-secret is for a field marked credential; a field marked secret but not credential (a webhook's address) takes fill, with what the user's request gives`);
4176
+ let wanted;
4177
+ try {
4178
+ wanted = new URL(site).origin;
4179
+ } catch {
4180
+ throw new ToolError(`$${variable}_ORIGIN isn't a site (https://example.com): ask the user to set it again`);
4181
+ }
4182
+ if (originOf(s.page.url()) !== wanted) throw new ToolError(`$${variable} is for ${wanted}, and this page is ${originOf(s.page.url())}: it wasn't filled. Fill it only on ${wanted}`);
4183
+ const value = env[variable];
4184
+ if (value === void 0) throw new ToolError(`$${variable} isn't set: ask the user to set it`);
4185
+ if (value && !s.secrets.includes(value)) s.secrets.push(value);
4186
+ const now = await readNow(s);
4187
+ const t = await target(s, a, now);
4188
+ await act(s, t, "fill", now, () => t.el.fill(value, { timeout: STEP_MS }));
4189
+ return after(s, `filled ${t.name} from $${variable}`);
4190
+ },
4191
+ async back(s) {
4192
+ await s.page.goBack({ waitUntil: "domcontentloaded" });
4193
+ return after(s, `went back to ${s.page.url()}`, false);
4194
+ },
4195
+ async reload(s) {
4196
+ await s.page.reload({ waitUntil: "domcontentloaded" });
4197
+ s.last = void 0;
4198
+ return after(s, "reloaded the page", false);
4199
+ },
4200
+ async wait(s, a) {
4201
+ const text = flag(a, "text");
4202
+ if (text !== void 0) {
4203
+ const until = Date.now() + 3e4;
4204
+ while (!(await showing(s, text, false)).length) {
4205
+ if (Date.now() > until) throw new ToolError(`${JSON.stringify(text)} didn't show within 30 s: read the page (agent-om snapshot --match <word>) to see what it shows instead`);
4206
+ await s.page.waitForTimeout(250);
4207
+ }
4208
+ return after(s, `${JSON.stringify(text)} shows`);
4209
+ }
4210
+ const ms = Math.min(Number(a._[0] ?? 1e3) || 1e3, 3e4);
4211
+ await s.page.waitForTimeout(ms);
4212
+ return after(s, `waited ${ms} ms`);
4213
+ },
4214
+ async screenshot(s, a) {
4215
+ if (!s.allowScreenshot) throw new ToolError(`screenshot is off in this session: Agent OM works from text projection without screenshots by default. To enable it, the user must start a session with --allow-screenshot (and confirm the warning) or set ${ALLOW_SCREENSHOT}=1. Use snapshot, inspect, or script instead.`);
4216
+ const file = a._[0];
4217
+ if (!file) throw new ToolError("agent-om screenshot <file.png>");
4218
+ await s.page.evaluate(inPage(["secrets"], MASK), s.secrets);
4219
+ try {
4220
+ await s.page.screenshot({
4221
+ path: file,
4222
+ fullPage: a.flags.full === true
4223
+ });
4224
+ } finally {
4225
+ await s.page.evaluate(UNMASK).catch(() => {});
4226
+ }
4227
+ return `saved ${file}`;
4228
+ },
4229
+ async url(s) {
4230
+ return said(s, s.page.url());
4231
+ },
4232
+ async script(s, a) {
4233
+ const script = a._[0];
4234
+ if (!script?.trim()) throw new ToolError("agent-om script '<script>', or the script from stdin: agent-om script <<'JS' … JS");
4235
+ return runScript(s, script, SCRIPT_MS);
4236
+ },
4237
+ async eval(s, a) {
4238
+ if (!s.allowEval) throw new ToolError("eval is off in this session: it's the user's to turn on. Do it with the other commands, or say in your answer what couldn't be done");
4239
+ const script = a._[0];
4240
+ if (!script) throw new ToolError("agent-om eval \"<script>\": a function's body, run in the page (return document.title)");
4241
+ const keptOut = async () => [...s.secrets, ...await s.page.evaluate(inPage([], KEPT_OUT)).catch(() => [])];
4242
+ const ref = flag(a, "ref");
4243
+ let el;
4244
+ if (ref !== void 0) {
4245
+ if (!/^e\d+$/.test(ref)) throw new ToolError(`'${ref}' isn't a ref: refs are written e12, as the view shows them`);
4246
+ const now = await readNow(s);
4247
+ const node = nodeOf(now, ref);
4248
+ const g = guard(now.root, ref);
4249
+ el = await elementOf(s.page, ref);
4250
+ if (!el) throw new ToolError(await goneRef(s, ref));
4251
+ if (!node || !g) throw new ToolError(noRef(ref));
4252
+ }
4253
+ let got;
4254
+ try {
4255
+ got = el ? await el.evaluate(inPage(["el"], `return ${evalScript(script)}`)) : await s.page.evaluate(evalScript(script));
4256
+ } catch (e) {
4257
+ const message = (e instanceof Error ? e.message : String(e)).replace(/^page\.evaluate: /, "").split("\n")[0] ?? "";
4258
+ throw new UsageError(withoutSecrets(`the script failed: ${message}`, await keptOut()));
4259
+ }
4260
+ const kept = await keptOut();
4261
+ const text = String(got.said);
4262
+ s.evaluated = {
4263
+ kind: got.kind,
4264
+ said: withoutSecrets(text, kept)
4265
+ };
4266
+ return after(s, `ran the script; it returned: ${withoutSecrets(text.length > EVAL_MAX ? `${text.slice(0, EVAL_MAX)}… (${text.length - EVAL_MAX} more characters cut: return less)` : text, kept)}`);
4267
+ },
4268
+ async "save-state"(s, a) {
4269
+ const file = a._[0];
4270
+ if (!file) throw new ToolError("agent-om save-state <file.json>");
4271
+ if (s.attached) throw new ToolError("this session is attached to the user's own browser, whose sign-ins are theirs: save-state keeps a browser of the tool's own. Its sign-ins are already there");
4272
+ const state = await s.page.context().storageState();
4273
+ writeFileSync(file, JSON.stringify(state, null, 2), { mode: 384 });
4274
+ chmodSync(file, 384);
4275
+ const sites = /* @__PURE__ */ new Set([...state.cookies.map((c) => c.domain.replace(/^\./, "")), ...state.origins.map((o) => new URL(o.origin).hostname)]);
4276
+ return `saved the cookies and storage of ${sites.size} site${sites.size === 1 ? "" : "s"} to ${file} (only you can read it): agent-om start --state ${file} is signed in the same. It holds sign-ins: never print it or send it anywhere`;
4277
+ },
4278
+ async console(s, a) {
4279
+ const tab = tabOf(s, s.page);
4280
+ if (!tab) return "nothing";
4281
+ const errors = a.flags.errors === true;
4282
+ const shown = tab.logged.splice(0).filter((m) => !errors || m.level === "error" || m.level === "warning");
4283
+ if (!shown.length) return `the page logged nothing${errors ? " that is an error or a warning" : ""} since you last asked`;
4284
+ return shown.map((m) => `${m.level}: ${m.text}${m.where ? ` (${m.where})` : ""}`).join("\n");
4285
+ },
4286
+ async network(s, a) {
4287
+ const tab = tabOf(s, s.page);
4288
+ if (!tab) return "nothing";
4289
+ const failed = a.flags.failed === true;
4290
+ const shown = tab.requested.splice(0).filter((r) => !failed || r.status === "failed" || r.status >= 400);
4291
+ if (!shown.length) return `no request${failed ? " failed" : ""} since you last asked`;
4292
+ return shown.map((r) => `${r.method} ${r.status === "failed" ? `failed (${r.error})` : r.status} ${bare(r.url)} (${r.kind})`).join("\n");
4293
+ },
4294
+ async tabs(s) {
4295
+ return (await Promise.all(s.tabs.map(async (t) => {
4296
+ const title = await t.page.title().catch(() => "");
4297
+ const opener = t.opener && tabOf(s, t.opener);
4298
+ return `tab ${t.n}: ${title || "(untitled)"} — ${t.page.url()}${opener ? ` (opened by tab ${opener.n})` : ""}${t.page === s.page ? " (current)" : ""}`;
4299
+ }))).join("\n");
4300
+ },
4301
+ async "switch-tab"(s, a) {
4302
+ const n = Number(a._[0]);
4303
+ const tab = s.tabs.find((t) => t.n === n);
4304
+ if (!tab) throw new ToolError(`there is no tab ${a._[0] ?? ""}: agent-om tabs lists them`);
4305
+ switchTo(s, tab);
4306
+ await settle(s.page);
4307
+ const now = await readNow(s);
4308
+ const out = s.last ? `you are in tab ${n} now; what changed since you last read it:\n${changes(s.last, now).text}` : `you are in tab ${n} now\n${view(now)}`;
4309
+ readAs(s, now);
4310
+ return out;
4311
+ }
4312
+ };
4313
+ /** What may run when the agent's tab closed between commands: reading, and moving to a tab, but no action with a ref read in the old tab. */
4314
+ const AFTER_MOVE = /* @__PURE__ */ new Set([
4315
+ "snapshot",
4316
+ "changes",
4317
+ "url",
4318
+ "tabs",
4319
+ "switch-tab",
4320
+ "open",
4321
+ "back",
4322
+ "reload",
4323
+ "wait",
4324
+ "screenshot"
4325
+ ]);
4326
+ const TABLE = new Map(commandsFor("cli", ["eval", "screenshot"]).map((c) => [c.name, c]));
4327
+ /** Refuse words a command has no place for, rather than leave them out unsaid: `snapshot e1 e2`, `fill e5 two words`. */
4328
+ function tooMany(name, a) {
4329
+ const command = TABLE.get(name);
4330
+ if (!command) return;
4331
+ const places = command.args.filter((g) => /^\[?</.test(g.cli));
4332
+ if (places.at(-1)?.kind === "texts") return;
4333
+ const max = places.length - (command.locates && flag(a, "text") !== void 0 && places[0]?.kind === "ref" ? 1 : 0);
4334
+ if (a._.length <= max) return;
4335
+ const takes = places.length ? `takes ${places.map((g) => g.cli).join(" ")}` : "takes no words, only options";
4336
+ throw new ToolError(`${name} ${takes}, and got ${a._.length} words: ${a._.map((w) => JSON.stringify(w)).join(" ")}. Put text that has spaces in quotes; for several elements, run the command once for each`);
4337
+ }
4338
+ /** Options every command takes: which session, and help. */
4339
+ const EVERYWHERE = ["session", "help"];
4340
+ /** Options of a command that aren't arguments in the table: taking what must be confirmed, accepting the browser's own dialog. */
4341
+ const ON_ACTIONS = ["confirm", "accept"];
4342
+ /** The options a command takes: its arguments' in the table, what locates an element with no ref, and the tool's own. */
4343
+ function optionsOf(command) {
4344
+ const names = new Set(EVERYWHERE);
4345
+ const add = (cli) => {
4346
+ for (const [, name] of cli.matchAll(/--([a-z-]+)/g)) names.add(name);
4347
+ if (/(^|\[)-i\b/.test(cli)) names.add("interactive").add("i");
4348
+ };
4349
+ for (const g of command.args) add(g.cli);
4350
+ if (command.group === "act") for (const name of ON_ACTIONS) names.add(name);
4351
+ if (command.name !== "snapshot" && command.args.some((g) => g.kind === "ref")) for (const g of LOCATOR_ARGS) add(g.cli);
4352
+ if (command.name === "snapshot") names.add("scope");
4353
+ return names;
4354
+ }
4355
+ /** Refuse an option a command doesn't take, rather than leave it out unsaid: `back --match Tag` would print the whole page. */
4356
+ function noSuchOption(name, a) {
4357
+ const command = TABLE.get(name);
4358
+ if (!command) return;
4359
+ const takes = optionsOf(command);
4360
+ const bad = Object.keys(a.flags).filter((f) => !takes.has(f));
4361
+ if (!bad.length) return;
4362
+ const own = command.args.filter((g) => /--|-i\b/.test(g.cli)).map((g) => g.cli);
4363
+ throw new ToolError(`${name} takes no ${bad.map((f) => `--${f}`).join(", ")}${own.length ? `: it takes ${own.join(" ")}` : ""} (agent-om help)`);
4364
+ }
4365
+ /** Every command, said with the session's secrets taken out, and refused before a page is open. */
4366
+ async function runCommand(s, name, a, env) {
4367
+ const command = COMMANDS[name];
4368
+ if (!command) throw new ToolError(`no command '${name}' (agent-om help)`);
4369
+ tooMany(name, a);
4370
+ noSuchOption(name, a);
4371
+ for (const tab of s.fresh.splice(0)) s.beside.push(opened(tab));
4372
+ if (s.closed) {
4373
+ const closed = s.closed;
4374
+ s.closed = void 0;
4375
+ if (!AFTER_MOVE.has(name)) throw new UsageError(`${closed}. Nothing was done: read this tab first (agent-om snapshot), then act on what it shows`);
4376
+ s.beside.unshift(closed);
4377
+ }
4378
+ if (name !== "open" && name !== "tabs" && name !== "switch-tab" && s.page.url() === "about:blank") throw new ToolError("no page is open yet: agent-om open <address> first");
4379
+ s.accept = a.flags.accept === true;
4380
+ try {
4381
+ const out = await command(s, a, env);
4382
+ return said(s, s.beside.length ? [...s.beside.splice(0), out].join("\n") : out);
4383
+ } catch (e) {
4384
+ if (e instanceof ToolError) throw new ToolError(said(s, e.message), e.quoting === void 0 ? void 0 : said(s, e.quoting));
4385
+ if (e instanceof UsageError) throw new UsageError(said(s, e.message));
4386
+ throw e;
4387
+ } finally {
4388
+ s.accept = false;
4389
+ }
4390
+ }
4391
+ /**
4392
+ * Keep the agent's tabs to some sites: a page load anywhere else (a link, a redirect, a script's) is stopped and
4393
+ * said. Only what is asked of another site is looked at, and only a tab's own page is stopped: a page still loads its
4394
+ * scripts, images and frames from wherever it does. It keeps the agent on the sites, not the network off the others.
4395
+ */
4396
+ async function keepTo(s, context, origins) {
4397
+ s.allowed = origins;
4398
+ const elsewhere = (url) => /^https?:$/.test(url.protocol) && !origins.includes(url.origin);
4399
+ await context.route(elsewhere, async (route) => {
4400
+ const r = route.request();
4401
+ if (r.isNavigationRequest() && r.frame().parentFrame() === null && s.tabs.some((t) => t.page === r.frame().page())) {
4402
+ s.beside.push(`the page tried to go to ${new URL(r.url()).origin}, which isn't one of the sites this session may open: stopped`);
4403
+ return route.fulfill({ status: 204 });
4404
+ }
4405
+ return route.continue();
4406
+ });
4407
+ }
4408
+ /** How long a tab a page opened is waited for: loaded (10 s), then watched (3 s), and a little over. */
4409
+ const OPENING_MS = 15e3;
4410
+ /** The tabs pages are opening, joined to the session: waited for, but never longer than OPENING_MS (a window that stops answering never finishes joining). */
4411
+ async function tabsOpened(s) {
4412
+ const until = Date.now() + OPENING_MS;
4413
+ while (s.opening.size && Date.now() < until) await Promise.race([Promise.all([...s.opening]), new Promise((r) => setTimeout(r, until - Date.now()))]);
4414
+ }
4415
+ /** Whether a page still answers: one running a script that never ends doesn't. */
4416
+ async function answers(page, ms = 2e3) {
4417
+ return Promise.race([page.evaluate("1").then(() => true, () => true), new Promise((r) => setTimeout(() => r(false), ms))]);
4418
+ }
4419
+ /**
4420
+ * A tab whose page stopped answering (a script that never ends) can't be read or acted on, and a command on it
4421
+ * never ends: the agent's own is closed and a new tab takes its place, the agent told how to load the page again;
4422
+ * a tab of the user's is left as it is.
4423
+ */
4424
+ async function replaceStuck(s) {
4425
+ const stuck = s.page;
4426
+ const tab = tabOf(s, stuck);
4427
+ const url = stuck.url();
4428
+ if (tab && !tab.own) return `the page stopped answering (a script on it never ends), and it is the user's tab, so it was left as it is: ask the user`;
4429
+ const fresh = await stuck.context().newPage();
4430
+ await tabsOpened(s);
4431
+ const t = tabOf(s, fresh) ?? adopt(s, fresh, void 0, true);
4432
+ t.own = true;
4433
+ s.fresh = s.fresh.filter((f) => f !== t);
4434
+ switchTo(s, t);
4435
+ s.last = void 0;
4436
+ const others = s.tabs.filter((o) => o.own && o.page !== stuck && o.page !== fresh && !o.page.isClosed());
4437
+ const frozen = (await Promise.all(others.map(async (o) => await answers(o.page, 1e3) ? void 0 : o.page))).filter((p) => !!p);
4438
+ await Promise.all([stuck, ...frozen].map((p) => p.close({ runBeforeUnload: false }).catch(() => {})));
4439
+ return `the page stopped answering (a script on it never ends), so its tab was closed and tab ${t.n} opened in its place: agent-om open ${url} loads it again`;
4440
+ }
4441
+ const opened = (tab) => `a page opened a new tab (tab ${tab.n}) at ${tab.page.url()}: agent-om switch-tab ${tab.n} works in it`;
4442
+ /**
4443
+ * A tab joins the session: its native dialogs answered and said, and its
4444
+ * closing followed. When the agent's own tab closes (a sign-in window closing
4445
+ * itself, once signed in), the agent goes back to the tab that opened it.
4446
+ */
4447
+ function adopt(s, page, opener, own) {
4448
+ const tab = {
4449
+ page,
4450
+ n: ++s.count,
4451
+ own,
4452
+ logged: [],
4453
+ requested: [],
4454
+ ...opener ? { opener } : {}
4455
+ };
4456
+ s.tabs.push(tab);
4457
+ answerDialogs(s, page);
4458
+ listen(tab);
4459
+ page.on("download", (d) => saveDownload(s, d));
4460
+ page.on("close", () => {
4461
+ s.tabs = s.tabs.filter((t) => t !== tab);
4462
+ s.fresh = s.fresh.filter((t) => t !== tab);
4463
+ if (s.page !== page) return;
4464
+ const back = (tab.opener && tabOf(s, tab.opener)) ?? s.tabs.at(-1);
4465
+ if (!back) return;
4466
+ switchTo(s, back);
4467
+ s.closed = `tab ${tab.n} closed itself; you are back in tab ${back.n}${back.page === tab.opener ? ", which opened it" : ""}`;
4468
+ });
4469
+ return tab;
4470
+ }
4471
+ function session(page, options = {}) {
4472
+ const s = {
4473
+ page,
4474
+ secrets: [],
4475
+ shown: /* @__PURE__ */ new Map(),
4476
+ beside: [],
4477
+ accept: false,
4478
+ tabs: [],
4479
+ count: 0,
4480
+ opening: /* @__PURE__ */ new Set(),
4481
+ fresh: [],
4482
+ downloads: options.downloads ?? join(tmpdir(), "agent-om", "downloads"),
4483
+ ...options.attached ? { attached: true } : {},
4484
+ ...options.allowEval ? { allowEval: true } : {},
4485
+ ...options.allowScreenshot ? { allowScreenshot: true } : {},
4486
+ saving: /* @__PURE__ */ new Set()
4487
+ };
4488
+ adopt(s, page, void 0, options.first ?? true);
4489
+ for (const other of options.others ?? []) adopt(s, other, void 0, false);
4490
+ page.context().on("page", (tab) => {
4491
+ if (tabOf(s, tab)) return;
4492
+ const by = s.page;
4493
+ const ready = (async () => {
4494
+ const opener = await tab.opener().catch(() => null);
4495
+ const ours = !!opener && !!tabOf(s, opener);
4496
+ if (!ours && options.follow === "opened") return;
4497
+ const t = adopt(s, tab, ours ? opener : by, ours);
4498
+ await tab.waitForLoadState("domcontentloaded", { timeout: 1e4 }).catch(() => {});
4499
+ await Promise.race([watch(tab).catch(() => {}), new Promise((r) => setTimeout(r, 3e3))]);
4500
+ if (!tab.isClosed()) s.fresh.push(t);
4501
+ })();
4502
+ s.opening.add(ready);
4503
+ ready.finally(() => s.opening.delete(ready));
4504
+ });
4505
+ return s;
4506
+ }
4507
+ /** A page's native dialogs: an alert or a leave-page question answered and said, a confirm or prompt dismissed unless the command says --accept. */
4508
+ function answerDialogs(s, page) {
4509
+ page.on("dialog", (d) => {
4510
+ const message = JSON.stringify(squash(d.message()).slice(0, 300));
4511
+ if (d.type() === "beforeunload" || d.type() === "alert") {
4512
+ s.beside.push(d.type() === "alert" ? `the browser showed an alert: ${message} (closed)` : "the page asked to confirm leaving it: left");
4513
+ d.accept().catch(() => {});
4514
+ } else if (s.accept) {
4515
+ s.beside.push(`the browser asked ${message}: accepted`);
4516
+ d.accept().catch(() => {});
4517
+ } else {
4518
+ s.beside.push(`the browser asked ${message}: dismissed, so the action went no further. If the user's request means yes, take the same action again with --accept`);
4519
+ d.dismiss().catch(() => {});
4520
+ }
4521
+ });
4522
+ }
4523
+ // src/server.ts
4524
+ const IDLE_MS = Number(process.env.AGENT_OM_IDLE_MS) || 72e5;
4525
+ /** The longest a command may take (longer than its longest wait: a text to show, a download), before the page is checked for a script that never ends. */
4526
+ const COMMAND_MS = Number(process.env.AGENT_OM_COMMAND_MS) || 12e4;
4527
+ /** The commands whose answer holds none of the page's text: an address, a file written. */
4528
+ const PLAIN = /* @__PURE__ */ new Set([
4529
+ "url",
4530
+ "screenshot",
4531
+ "save-state"
4532
+ ]);
4533
+ /** The browser and the tab the session starts in: launched, or attached to with the tabs its level lets it touch. */
4534
+ async function open(o) {
4535
+ if (o.cdp || o.autoConnect) {
4536
+ const endpoints = o.cdp ? [endpointOf(o.cdp)] : discover();
4537
+ if (!endpoints.length) throw new Error(NO_BROWSER);
4538
+ let browser;
4539
+ let failed = "";
4540
+ process.stderr.write(`waiting for the browser to let this session in: Chrome asks the user to allow remote debugging, each time a session attaches; up to ${ATTACH_MS / 1e3} s\n`);
4541
+ for (const endpoint of endpoints) {
4542
+ browser = await chromium.connectOverCDP(endpoint, { timeout: ATTACH_MS }).catch((e) => void (failed = (e.message.split("\n")[0] ?? "").replace(/\.+$/, "")));
4543
+ if (browser) break;
4544
+ }
4545
+ if (!browser) throw new Error(`couldn't attach to the browser${o.cdp ? ` at ${o.cdp}` : ""}: ${failed}. If Chrome asked to allow remote debugging, allow it and start again`);
4546
+ process.stderr.write("attached\n");
4547
+ const context = browser.contexts()[0];
4548
+ if (!context) throw new Error("the browser has no window to work in");
4549
+ const level = o.tabs ?? "own";
4550
+ const theirs = context.pages();
4551
+ let page;
4552
+ if (level === "active") {
4553
+ const showing = [];
4554
+ for (const p of theirs) if (await p.evaluate("document.visibilityState").catch(() => "") === "visible") showing.push(p);
4555
+ if (showing.length !== 1) throw new Error(`--tabs active takes the tab in front, but ${showing.length ? `${showing.length} windows each show one` : "no tab shows"}: leave one window open, or use --tabs own`);
4556
+ page = showing[0];
4557
+ } else page = await context.newPage();
4558
+ return {
4559
+ browser,
4560
+ context,
4561
+ page,
4562
+ attached: true,
4563
+ first: level !== "active",
4564
+ level,
4565
+ others: level === "all" ? theirs.filter((p) => p !== page) : []
4566
+ };
4567
+ }
4568
+ const launch = {
4569
+ headless: !o.headed,
4570
+ ...o.executable ? { executablePath: o.executable } : {}
4571
+ };
4572
+ const context = o.profile ? await chromium.launchPersistentContext(o.profile, {
4573
+ ...launch,
4574
+ viewport: o.viewport
4575
+ }) : await (await chromium.launch(launch)).newContext({
4576
+ viewport: o.viewport,
4577
+ ...o.state ? { storageState: o.state } : {}
4578
+ });
4579
+ const page = context.pages()[0] ?? await context.newPage();
4580
+ return {
4581
+ browser: context.browser(),
4582
+ context,
4583
+ page,
4584
+ attached: false,
4585
+ first: true,
4586
+ level: void 0,
4587
+ others: []
4588
+ };
4589
+ }
4590
+ async function serve(o) {
4591
+ mkdirSync(sessionDir(o.name), {
4592
+ recursive: true,
4593
+ mode: 448
4594
+ });
4595
+ const { browser, context, page, attached, first, level, others } = await open(o);
4596
+ await watch(page);
4597
+ const s = session(page, {
4598
+ downloads: join(sessionDir(o.name), "downloads"),
4599
+ follow: level && level !== "all" ? "opened" : "any",
4600
+ others,
4601
+ first,
4602
+ attached,
4603
+ allowEval: evalOn(process.env, attached),
4604
+ allowScreenshot: o.allowScreenshot === true || screenshotOn(process.env)
4605
+ });
4606
+ if (o.allowedOrigins?.length) await keepTo(s, context, o.allowedOrigins);
4607
+ if (level) s.beside.push(`attached to the running browser: ${level === "own" ? "you work only in the tabs you open, and those they open" : level === "active" ? "you work in the tab that was in front, and the tabs you open" : "every tab of this browser is yours: agent-om tabs lists them"}`);
4608
+ const token = randomBytes(24).toString("hex");
4609
+ const nonce = randomBytes(16).toString("hex");
4610
+ let queue = Promise.resolve();
4611
+ const end = async () => {
4612
+ if (readSession(o.name)?.pid === process.pid) rmSync(sessionFile(o.name), { force: true });
4613
+ await s.sandbox?.close();
4614
+ if (attached) {
4615
+ for (const t of s.tabs) if (t.own) await t.page.close().catch(() => {});
4616
+ await browser?.close().catch(() => {});
4617
+ } else {
4618
+ await context.close().catch(() => {});
4619
+ await browser?.close().catch(() => {});
4620
+ }
4621
+ process.exit(0);
4622
+ };
4623
+ context.on("close", () => void end());
4624
+ browser?.on("disconnected", () => void end());
4625
+ let idle = setTimeout(() => void end(), IDLE_MS);
4626
+ const used = () => {
4627
+ clearTimeout(idle);
4628
+ idle = setTimeout(() => void queue.finally(end), IDLE_MS);
4629
+ };
4630
+ const server = http.createServer((req, res) => {
4631
+ let raw = "";
4632
+ req.on("data", (c) => raw += c);
4633
+ req.on("end", () => {
4634
+ const reply = (r, status = 200) => {
4635
+ res.writeHead(status, { "content-type": "application/json" });
4636
+ res.end(JSON.stringify(r));
4637
+ };
4638
+ let request;
4639
+ try {
4640
+ request = JSON.parse(raw);
4641
+ } catch {
4642
+ return reply({
4643
+ ok: false,
4644
+ error: "not JSON"
4645
+ }, 400);
4646
+ }
4647
+ if (request.token !== token) return reply({
4648
+ ok: false,
4649
+ error: "wrong token"
4650
+ }, 403);
4651
+ used();
4652
+ if (request.cmd === "stop") {
4653
+ reply({
4654
+ ok: true,
4655
+ out: "stopped"
4656
+ });
4657
+ queue.finally(end);
4658
+ return;
4659
+ }
4660
+ const run = async () => {
4661
+ if (request.cmd === "status") return {
4662
+ ok: true,
4663
+ out: `session '${o.name}' on ${s.page.url()} (pid ${process.pid})`
4664
+ };
4665
+ try {
4666
+ const late = Symbol("late");
4667
+ const out = await Promise.race([runCommand(s, request.cmd, request.args, request.env ?? {}), new Promise((r) => setTimeout(() => r(late), COMMAND_MS))]);
4668
+ if (out === late) {
4669
+ if (!await answers(s.page)) return {
4670
+ ok: false,
4671
+ error: await replaceStuck(s)
4672
+ };
4673
+ return {
4674
+ ok: false,
4675
+ error: `${request.cmd} took longer than ${COMMAND_MS / 1e3} s, and was given up; the page still answers: read it (agent-om snapshot)`
4676
+ };
4677
+ }
4678
+ return {
4679
+ ok: true,
4680
+ out: PLAIN.has(request.cmd) ? out : pageContent(out, originOf(s.page.url()), nonce)
4681
+ };
4682
+ } catch (e) {
4683
+ if (e instanceof ToolError) {
4684
+ const about = e.quoting === void 0 ? "" : `\n${PLAIN.has(request.cmd) ? e.quoting : pageContent(e.quoting, originOf(s.page.url()), nonce)}`;
4685
+ return {
4686
+ ok: false,
4687
+ error: `${e.message}${about}`
4688
+ };
4689
+ }
4690
+ const message = e instanceof UsageError ? e.message : String(e.message ?? e).split("\n")[0];
4691
+ return {
4692
+ ok: false,
4693
+ error: PLAIN.has(request.cmd) ? message : pageContent(message, originOf(s.page.url()), nonce)
4694
+ };
4695
+ }
4696
+ };
4697
+ const next = queue.then(run);
4698
+ queue = next.catch(() => {});
4699
+ next.then((r) => reply(r));
4700
+ });
4701
+ });
4702
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
4703
+ const port = server.address().port;
4704
+ const other = await claim(o.name, {
4705
+ port,
4706
+ token,
4707
+ pid: process.pid
4708
+ });
4709
+ if (other) {
4710
+ process.stderr.write(`a session named '${o.name}' is running already (pid ${other.pid}): this one (pid ${process.pid}) stopped\n`);
4711
+ server.close();
4712
+ await end();
4713
+ }
4714
+ }
4715
+ /** The session's name for this process: undefined once it holds it, or the live session that holds it already. */
4716
+ async function claim(name, mine) {
4717
+ const file = sessionFile(name);
4718
+ const text = JSON.stringify(mine);
4719
+ try {
4720
+ writeFileSync(file, text, {
4721
+ mode: 384,
4722
+ flag: "wx"
4723
+ });
4724
+ return;
4725
+ } catch (e) {
4726
+ if (e.code !== "EEXIST") throw e;
4727
+ }
4728
+ const other = readSession(name);
4729
+ if (other && other.pid !== process.pid && await alive(other)) return other;
4730
+ writeFileSync(file, text, { mode: 384 });
4731
+ }
4732
+ /** Whether a session answers on its port, with its token. */
4733
+ async function alive(s) {
4734
+ try {
4735
+ return (await (await fetch(`http://127.0.0.1:${s.port}/`, {
4736
+ method: "POST",
4737
+ body: JSON.stringify({
4738
+ token: s.token,
4739
+ cmd: "status",
4740
+ args: {
4741
+ _: [],
4742
+ flags: {}
4743
+ }
4744
+ }),
4745
+ signal: AbortSignal.timeout(2e3)
4746
+ })).json()).ok === true;
4747
+ } catch {
4748
+ return false;
4749
+ }
4750
+ }
4751
+ export { serve };