@agent-om/cli 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { _ as
|
|
2
|
-
import { chmodSync,
|
|
3
|
-
import { tmpdir } from "node:os";
|
|
1
|
+
import { _ as endpointOf, d as evalOn, f as screenshotOn, g as discover, i as sessionsHome, l as ToolError, m as NO_BROWSER, n as sessionDir, p as ATTACH_MS, r as sessionFile, s as ALLOW_SCREENSHOT, t as readSession, u as UsageError, v as LOCATOR_ARGS, y as commandsFor } from "./session-lYFPsBGa.mjs";
|
|
2
|
+
import { chmodSync, closeSync, mkdirSync, openSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
4
3
|
import { basename, extname, join } from "node:path";
|
|
5
|
-
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
6
5
|
import http from "node:http";
|
|
7
6
|
import { chromium } from "playwright";
|
|
8
7
|
/** A line's text cut at this length, saying so. */
|
|
@@ -192,16 +191,16 @@ const saidBy = (parent, child, head = true) => {
|
|
|
192
191
|
const text = squash$2(shown(child));
|
|
193
192
|
if (!text) return false;
|
|
194
193
|
const byContents = NAMED_BY_CONTENTS.has(parent.role) || !!parent.clickable;
|
|
195
|
-
const says = (piece
|
|
194
|
+
const says = (piece) => {
|
|
196
195
|
const want = squash$2(piece).toLowerCase();
|
|
197
196
|
if (!want) return false;
|
|
198
197
|
if (!!parent.description && squash$2(parent.description).toLowerCase().includes(want)) return true;
|
|
199
198
|
if (!parent.name) return false;
|
|
200
199
|
const name = squash$2(parent.name).toLowerCase();
|
|
201
200
|
if (byContents) return name.includes(want);
|
|
202
|
-
return head &&
|
|
201
|
+
return head && name === want;
|
|
203
202
|
};
|
|
204
|
-
return says(text
|
|
203
|
+
return says(text) && describedIn(child).every((d) => says(d));
|
|
205
204
|
};
|
|
206
205
|
/** The descriptions in a node and everything inside it. */
|
|
207
206
|
const describedIn = (n) => [...n.description ? [n.description] : [], ...(n.children ?? []).flatMap(describedIn)];
|
|
@@ -421,16 +420,23 @@ function itemsOf(n, table = n, head = true) {
|
|
|
421
420
|
const first = head ? (n.children ?? []).find((c) => says(c) || !!c.children?.length) : void 0;
|
|
422
421
|
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
422
|
}
|
|
423
|
+
const tryEncode = (fn) => {
|
|
424
|
+
try {
|
|
425
|
+
return fn();
|
|
426
|
+
} catch {
|
|
427
|
+
return "";
|
|
428
|
+
}
|
|
429
|
+
};
|
|
424
430
|
/**
|
|
425
431
|
* 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
432
|
* form's data, and encoded twice (a filter's value encoded, then the whole filter as a part: `channel%3AOrganic%2520Search`).
|
|
427
433
|
*/
|
|
428
434
|
const inAddress = (v) => [
|
|
429
435
|
v,
|
|
430
|
-
encodeURIComponent(v),
|
|
431
|
-
encodeURI(v),
|
|
436
|
+
tryEncode(() => encodeURIComponent(v)),
|
|
437
|
+
tryEncode(() => encodeURI(v)),
|
|
432
438
|
new URLSearchParams([["", v]]).toString().slice(1),
|
|
433
|
-
encodeURIComponent(encodeURIComponent(v))
|
|
439
|
+
tryEncode(() => encodeURIComponent(encodeURIComponent(v)))
|
|
434
440
|
];
|
|
435
441
|
/** A table read compactly, or nothing when no row of it can be. */
|
|
436
442
|
function compactTable(table, base) {
|
|
@@ -608,7 +614,10 @@ function addressAround(list, columns, base) {
|
|
|
608
614
|
if (at < 0) continue;
|
|
609
615
|
const before = path.slice(0, at);
|
|
610
616
|
const after = path.slice(at + form.length);
|
|
611
|
-
if (list.every(({ row, c }) =>
|
|
617
|
+
if (list.every(({ row, c }) => {
|
|
618
|
+
const encoded = row.values[col] ? inAddress(row.values[col])[enc] : "";
|
|
619
|
+
return !!encoded && where(c.node.href, base) === `${before}${encoded}${after}`;
|
|
620
|
+
})) return `${before}{${title}}${after}`;
|
|
612
621
|
}
|
|
613
622
|
}
|
|
614
623
|
}
|
|
@@ -1114,6 +1123,7 @@ const tryForm = (encode) => {
|
|
|
1114
1123
|
* HTML. Longest first.
|
|
1115
1124
|
*/
|
|
1116
1125
|
function secretForms(value) {
|
|
1126
|
+
if (!value) return [];
|
|
1117
1127
|
const forms = /* @__PURE__ */ new Set([value]);
|
|
1118
1128
|
for (const form of [
|
|
1119
1129
|
tryForm(() => encodeURIComponent(value)),
|
|
@@ -1128,12 +1138,10 @@ function secretForms(value) {
|
|
|
1128
1138
|
const formCache = /* @__PURE__ */ new WeakMap();
|
|
1129
1139
|
function cachedForms(secrets) {
|
|
1130
1140
|
const hit = formCache.get(secrets);
|
|
1131
|
-
if (hit && hit.
|
|
1141
|
+
if (hit && hit.items.length === secrets.length && hit.items.every((v, i) => v === secrets[i])) return hit.forms;
|
|
1132
1142
|
const forms = [...new Set(secrets.flatMap(secretForms))].sort((a, b) => b.length - a.length);
|
|
1133
1143
|
formCache.set(secrets, {
|
|
1134
|
-
|
|
1135
|
-
first: secrets[0],
|
|
1136
|
-
last: secrets[secrets.length - 1],
|
|
1144
|
+
items: [...secrets],
|
|
1137
1145
|
forms
|
|
1138
1146
|
});
|
|
1139
1147
|
return forms;
|
|
@@ -1346,6 +1354,264 @@ const REGEX_BEFORE_CH = /* @__PURE__ */ new Set([
|
|
|
1346
1354
|
"<",
|
|
1347
1355
|
">"
|
|
1348
1356
|
]);
|
|
1357
|
+
/** Parse bound identifier names in a declarator list starting at `start` (after `const`/`let`/`var`), returning names and the end offset. */
|
|
1358
|
+
function parseDeclList(src, start) {
|
|
1359
|
+
const names = [];
|
|
1360
|
+
let i = start;
|
|
1361
|
+
const n = src.length;
|
|
1362
|
+
const skipWs = () => {
|
|
1363
|
+
while (i < n) {
|
|
1364
|
+
if (/\s/.test(src[i])) {
|
|
1365
|
+
i++;
|
|
1366
|
+
continue;
|
|
1367
|
+
}
|
|
1368
|
+
if (src[i] === "/" && src[i + 1] === "/") {
|
|
1369
|
+
i += 2;
|
|
1370
|
+
while (i < n && src[i] !== "\n") i++;
|
|
1371
|
+
continue;
|
|
1372
|
+
}
|
|
1373
|
+
if (src[i] === "/" && src[i + 1] === "*") {
|
|
1374
|
+
i += 2;
|
|
1375
|
+
while (i < n && !(src[i] === "*" && src[i + 1] === "/")) i++;
|
|
1376
|
+
i = Math.min(n, i + 2);
|
|
1377
|
+
continue;
|
|
1378
|
+
}
|
|
1379
|
+
break;
|
|
1380
|
+
}
|
|
1381
|
+
};
|
|
1382
|
+
const skipString = () => {
|
|
1383
|
+
const q = src[i++];
|
|
1384
|
+
while (i < n && src[i] !== q) {
|
|
1385
|
+
if (src[i] === "\\") i++;
|
|
1386
|
+
i++;
|
|
1387
|
+
}
|
|
1388
|
+
if (i < n) i++;
|
|
1389
|
+
};
|
|
1390
|
+
const readId = () => {
|
|
1391
|
+
skipWs();
|
|
1392
|
+
if (i >= n || !ID_CHAR.test(src[i]) || /[0-9]/.test(src[i])) return "";
|
|
1393
|
+
const s = i;
|
|
1394
|
+
while (i < n && ID_CHAR.test(src[i])) i++;
|
|
1395
|
+
return src.slice(s, i);
|
|
1396
|
+
};
|
|
1397
|
+
const skipExpr = (stopChars, initialNonWs = "=") => {
|
|
1398
|
+
let d = 0;
|
|
1399
|
+
const tpl = [];
|
|
1400
|
+
let lastWord = "";
|
|
1401
|
+
let lastNonWs = initialNonWs;
|
|
1402
|
+
const scanTemplateBody = () => {
|
|
1403
|
+
while (i < n) {
|
|
1404
|
+
if (src[i] === "\\") {
|
|
1405
|
+
i += 2;
|
|
1406
|
+
continue;
|
|
1407
|
+
}
|
|
1408
|
+
if (src[i] === "`") {
|
|
1409
|
+
i++;
|
|
1410
|
+
break;
|
|
1411
|
+
}
|
|
1412
|
+
if (src[i] === "$" && src[i + 1] === "{") {
|
|
1413
|
+
i += 2;
|
|
1414
|
+
tpl.push(d);
|
|
1415
|
+
d++;
|
|
1416
|
+
break;
|
|
1417
|
+
}
|
|
1418
|
+
i++;
|
|
1419
|
+
}
|
|
1420
|
+
lastWord = "";
|
|
1421
|
+
lastNonWs = src[i - 1] ?? "`";
|
|
1422
|
+
};
|
|
1423
|
+
while (i < n) {
|
|
1424
|
+
const c = src[i];
|
|
1425
|
+
if (c === "/" && src[i + 1] === "/") {
|
|
1426
|
+
i += 2;
|
|
1427
|
+
while (i < n && src[i] !== "\n") i++;
|
|
1428
|
+
continue;
|
|
1429
|
+
}
|
|
1430
|
+
if (c === "/" && src[i + 1] === "*") {
|
|
1431
|
+
i += 2;
|
|
1432
|
+
while (i < n && !(src[i] === "*" && src[i + 1] === "/")) i++;
|
|
1433
|
+
i = Math.min(n, i + 2);
|
|
1434
|
+
continue;
|
|
1435
|
+
}
|
|
1436
|
+
if (c === "'" || c === "\"") {
|
|
1437
|
+
skipString();
|
|
1438
|
+
lastWord = "";
|
|
1439
|
+
lastNonWs = c;
|
|
1440
|
+
continue;
|
|
1441
|
+
}
|
|
1442
|
+
if (c === "`") {
|
|
1443
|
+
i++;
|
|
1444
|
+
scanTemplateBody();
|
|
1445
|
+
continue;
|
|
1446
|
+
}
|
|
1447
|
+
if (c === "/" && (!lastNonWs || REGEX_BEFORE_CH.has(lastNonWs) || REGEX_BEFORE_KW.has(lastWord))) {
|
|
1448
|
+
i++;
|
|
1449
|
+
let inClass = false;
|
|
1450
|
+
while (i < n && src[i] !== "\n") {
|
|
1451
|
+
if (src[i] === "\\") {
|
|
1452
|
+
i += 2;
|
|
1453
|
+
continue;
|
|
1454
|
+
}
|
|
1455
|
+
if (src[i] === "[") inClass = true;
|
|
1456
|
+
else if (src[i] === "]") inClass = false;
|
|
1457
|
+
else if (src[i] === "/" && !inClass) {
|
|
1458
|
+
i++;
|
|
1459
|
+
while (i < n && /[a-z]/i.test(src[i])) i++;
|
|
1460
|
+
break;
|
|
1461
|
+
}
|
|
1462
|
+
i++;
|
|
1463
|
+
}
|
|
1464
|
+
lastWord = "";
|
|
1465
|
+
lastNonWs = "/";
|
|
1466
|
+
continue;
|
|
1467
|
+
}
|
|
1468
|
+
if (c === "}" && tpl.length && d - 1 === tpl[tpl.length - 1]) {
|
|
1469
|
+
tpl.pop();
|
|
1470
|
+
d--;
|
|
1471
|
+
i++;
|
|
1472
|
+
scanTemplateBody();
|
|
1473
|
+
continue;
|
|
1474
|
+
}
|
|
1475
|
+
if (c === "(" || c === "[" || c === "{") {
|
|
1476
|
+
d++;
|
|
1477
|
+
lastWord = "";
|
|
1478
|
+
lastNonWs = c;
|
|
1479
|
+
i++;
|
|
1480
|
+
continue;
|
|
1481
|
+
}
|
|
1482
|
+
if (c === ")" || c === "]" || c === "}") {
|
|
1483
|
+
if (d === 0) return;
|
|
1484
|
+
d--;
|
|
1485
|
+
lastWord = "";
|
|
1486
|
+
lastNonWs = c;
|
|
1487
|
+
i++;
|
|
1488
|
+
continue;
|
|
1489
|
+
}
|
|
1490
|
+
if (d === 0 && !tpl.length && stopChars.includes(c)) return;
|
|
1491
|
+
if (ID_CHAR.test(c) && !/[0-9]/.test(c)) {
|
|
1492
|
+
const s = i;
|
|
1493
|
+
while (i < n && ID_CHAR.test(src[i])) i++;
|
|
1494
|
+
lastWord = src.slice(s, i);
|
|
1495
|
+
lastNonWs = lastWord[lastWord.length - 1];
|
|
1496
|
+
continue;
|
|
1497
|
+
}
|
|
1498
|
+
if (!/\s/.test(c)) {
|
|
1499
|
+
lastWord = "";
|
|
1500
|
+
lastNonWs = c;
|
|
1501
|
+
}
|
|
1502
|
+
i++;
|
|
1503
|
+
}
|
|
1504
|
+
};
|
|
1505
|
+
const parsePattern = () => {
|
|
1506
|
+
skipWs();
|
|
1507
|
+
if (i >= n) return;
|
|
1508
|
+
if (src[i] === "{") {
|
|
1509
|
+
i++;
|
|
1510
|
+
while (i < n) {
|
|
1511
|
+
skipWs();
|
|
1512
|
+
if (src[i] === "}") {
|
|
1513
|
+
i++;
|
|
1514
|
+
return;
|
|
1515
|
+
}
|
|
1516
|
+
if (src.slice(i, i + 3) === "...") {
|
|
1517
|
+
i += 3;
|
|
1518
|
+
const id = readId();
|
|
1519
|
+
if (id) names.push(id);
|
|
1520
|
+
} else if (src[i] === "'" || src[i] === "\"") {
|
|
1521
|
+
skipString();
|
|
1522
|
+
skipWs();
|
|
1523
|
+
if (src[i] === ":") {
|
|
1524
|
+
i++;
|
|
1525
|
+
parsePattern();
|
|
1526
|
+
}
|
|
1527
|
+
} else if (src[i] === "[") {
|
|
1528
|
+
i++;
|
|
1529
|
+
skipExpr("]", "[");
|
|
1530
|
+
if (src[i] === "]") i++;
|
|
1531
|
+
skipWs();
|
|
1532
|
+
if (src[i] === ":") {
|
|
1533
|
+
i++;
|
|
1534
|
+
parsePattern();
|
|
1535
|
+
}
|
|
1536
|
+
} else if (/[0-9]/.test(src[i])) {
|
|
1537
|
+
while (i < n && /[0-9a-zA-Z_.]/.test(src[i])) i++;
|
|
1538
|
+
skipWs();
|
|
1539
|
+
if (src[i] === ":") {
|
|
1540
|
+
i++;
|
|
1541
|
+
parsePattern();
|
|
1542
|
+
}
|
|
1543
|
+
} else {
|
|
1544
|
+
const key = readId();
|
|
1545
|
+
skipWs();
|
|
1546
|
+
if (src[i] === ":") {
|
|
1547
|
+
i++;
|
|
1548
|
+
parsePattern();
|
|
1549
|
+
} else if (key) names.push(key);
|
|
1550
|
+
}
|
|
1551
|
+
skipWs();
|
|
1552
|
+
if (src[i] === "=") {
|
|
1553
|
+
i++;
|
|
1554
|
+
skipExpr(",}", "=");
|
|
1555
|
+
}
|
|
1556
|
+
skipWs();
|
|
1557
|
+
if (src[i] === ",") i++;
|
|
1558
|
+
else if (src[i] === "}") {
|
|
1559
|
+
i++;
|
|
1560
|
+
return;
|
|
1561
|
+
} else return;
|
|
1562
|
+
}
|
|
1563
|
+
} else if (src[i] === "[") {
|
|
1564
|
+
i++;
|
|
1565
|
+
while (i < n) {
|
|
1566
|
+
skipWs();
|
|
1567
|
+
if (src[i] === "]") {
|
|
1568
|
+
i++;
|
|
1569
|
+
return;
|
|
1570
|
+
}
|
|
1571
|
+
if (src[i] === ",") {
|
|
1572
|
+
i++;
|
|
1573
|
+
continue;
|
|
1574
|
+
}
|
|
1575
|
+
if (src.slice(i, i + 3) === "...") {
|
|
1576
|
+
i += 3;
|
|
1577
|
+
parsePattern();
|
|
1578
|
+
} else parsePattern();
|
|
1579
|
+
skipWs();
|
|
1580
|
+
if (src[i] === "=") {
|
|
1581
|
+
i++;
|
|
1582
|
+
skipExpr(",]", "=");
|
|
1583
|
+
}
|
|
1584
|
+
skipWs();
|
|
1585
|
+
if (src[i] === ",") i++;
|
|
1586
|
+
else if (src[i] === "]") {
|
|
1587
|
+
i++;
|
|
1588
|
+
return;
|
|
1589
|
+
} else return;
|
|
1590
|
+
}
|
|
1591
|
+
} else {
|
|
1592
|
+
const id = readId();
|
|
1593
|
+
if (id) names.push(id);
|
|
1594
|
+
}
|
|
1595
|
+
};
|
|
1596
|
+
for (;;) {
|
|
1597
|
+
parsePattern();
|
|
1598
|
+
skipWs();
|
|
1599
|
+
if (src[i] === "=") {
|
|
1600
|
+
i++;
|
|
1601
|
+
skipExpr(",;\n", "=");
|
|
1602
|
+
}
|
|
1603
|
+
skipWs();
|
|
1604
|
+
if (src[i] === ",") {
|
|
1605
|
+
i++;
|
|
1606
|
+
continue;
|
|
1607
|
+
}
|
|
1608
|
+
break;
|
|
1609
|
+
}
|
|
1610
|
+
return {
|
|
1611
|
+
names,
|
|
1612
|
+
end: i
|
|
1613
|
+
};
|
|
1614
|
+
}
|
|
1349
1615
|
/**
|
|
1350
1616
|
* Rewrite top-level lexical declarations (`const`, and `let` when targeting `var`) at nesting depth 0 so consecutive
|
|
1351
1617
|
* REPL scripts can redeclare temporary names without failing on `Identifier '...' has already been declared`, while
|
|
@@ -1490,13 +1756,7 @@ function relaxTopDecl(code, target = "let", reserved = /* @__PURE__ */ new Set()
|
|
|
1490
1756
|
while (j < n && /\s/.test(code[j])) j++;
|
|
1491
1757
|
const next = code[j] ?? "";
|
|
1492
1758
|
if (j > i && (next === "{" || next === "[" || ID_CHAR.test(next) && !/[0-9]/.test(next))) {
|
|
1493
|
-
|
|
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)) {
|
|
1759
|
+
if (!(reserved.size > 0 && parseDeclList(code, j).names.some((id) => reserved.has(id)))) {
|
|
1500
1760
|
out.push(target);
|
|
1501
1761
|
lastWord = target;
|
|
1502
1762
|
lastNonWs = target[target.length - 1];
|
|
@@ -1653,6 +1913,21 @@ const FIELD_TAGS = /* @__PURE__ */ new Set([
|
|
|
1653
1913
|
"TEXTAREA",
|
|
1654
1914
|
"SELECT"
|
|
1655
1915
|
]);
|
|
1916
|
+
const INPUT_BUTTONS = /* @__PURE__ */ new Set([
|
|
1917
|
+
"submit",
|
|
1918
|
+
"button",
|
|
1919
|
+
"reset",
|
|
1920
|
+
"image"
|
|
1921
|
+
]);
|
|
1922
|
+
const INPUT_CHOICES = /* @__PURE__ */ new Set(["checkbox", "radio"]);
|
|
1923
|
+
const CHOICE_ROLES = /* @__PURE__ */ new Set([
|
|
1924
|
+
"option",
|
|
1925
|
+
"checkbox",
|
|
1926
|
+
"radio",
|
|
1927
|
+
"switch",
|
|
1928
|
+
"menuitemcheckbox",
|
|
1929
|
+
"menuitemradio"
|
|
1930
|
+
]);
|
|
1656
1931
|
const SECRET_TOKENS = new Set(SECRET_AUTOCOMPLETE_TOKENS);
|
|
1657
1932
|
const RISKS = new Set(RISK_LEVELS.filter((r) => r !== "safe"));
|
|
1658
1933
|
const ANY_RISK = new Set(RISK_LEVELS);
|
|
@@ -1688,13 +1963,29 @@ function without(s, pieces, shown) {
|
|
|
1688
1963
|
let out = s;
|
|
1689
1964
|
let seen;
|
|
1690
1965
|
for (const p of [...new Set(pieces)].sort((a, b) => b.length - a.length)) {
|
|
1966
|
+
if (!p) continue;
|
|
1691
1967
|
const escaped = p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1692
1968
|
const word = () => new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "gu");
|
|
1693
1969
|
const here = out.match(word())?.length ?? 0;
|
|
1694
|
-
if (
|
|
1970
|
+
if (here) {
|
|
1971
|
+
seen ??= shown();
|
|
1972
|
+
let extra = here - Math.max(0, ...seen.map((t) => t.match(word())?.length ?? 0));
|
|
1973
|
+
if (extra > 0) out = out.replace(word(), (m) => extra-- > 0 ? " " : m);
|
|
1974
|
+
continue;
|
|
1975
|
+
}
|
|
1976
|
+
if (!out.includes(p)) continue;
|
|
1695
1977
|
seen ??= shown();
|
|
1696
|
-
|
|
1697
|
-
|
|
1978
|
+
const literal = () => new RegExp(escaped, "g");
|
|
1979
|
+
let extra = (out.match(literal())?.length ?? 0) - Math.max(0, ...seen.map((t) => t.match(literal())?.length ?? 0));
|
|
1980
|
+
if (extra <= 0) continue;
|
|
1981
|
+
if (p.length >= SCRUB_MIN) out = out.replace(literal(), (m) => extra-- > 0 ? "" : m);
|
|
1982
|
+
else if (extra === 1) for (let at = out.indexOf(p); at >= 0; at = out.indexOf(p, at + 1)) {
|
|
1983
|
+
const candidate = squash$1(out.slice(0, at) + out.slice(at + p.length));
|
|
1984
|
+
if (seen.includes(candidate)) {
|
|
1985
|
+
out = candidate;
|
|
1986
|
+
break;
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1698
1989
|
}
|
|
1699
1990
|
return squash$1(out);
|
|
1700
1991
|
}
|
|
@@ -1745,10 +2036,6 @@ var Dom = class {
|
|
|
1745
2036
|
this.url = s[top.documentURL] ?? "";
|
|
1746
2037
|
this.title = s[top.title] ?? "";
|
|
1747
2038
|
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
2039
|
let offset = 0;
|
|
1753
2040
|
for (const doc of snapshot.documents) {
|
|
1754
2041
|
const n = doc.nodes;
|
|
@@ -1783,29 +2070,39 @@ var Dom = class {
|
|
|
1783
2070
|
const redacted = this.redacted;
|
|
1784
2071
|
const ignored = [];
|
|
1785
2072
|
const holdsField = [];
|
|
1786
|
-
|
|
2073
|
+
const inputType = (i) => this.tag[i] === "INPUT" ? (this.attrs[i].get("type") ?? "").toLowerCase() : "";
|
|
2074
|
+
const isChoiceInput = (i) => this.tag[i] === "INPUT" && INPUT_CHOICES.has(inputType(i));
|
|
2075
|
+
const isButtonInput = (i) => this.tag[i] === "INPUT" && INPUT_BUTTONS.has(inputType(i));
|
|
2076
|
+
const isValueField = (i) => this.tag[i] === "TEXTAREA" || this.tag[i] === "SELECT" || this.tag[i] === "INPUT" && !INPUT_BUTTONS.has(inputType(i)) && !INPUT_CHOICES.has(inputType(i)) || this.editableRoot(i);
|
|
2077
|
+
const isChoice = (i) => isChoiceInput(i) || this.tag[i] === "OPTION" || this.tag[i] === "OPTGROUP" || CHOICE_ROLES.has(this.attrs[i].get("role") ?? "");
|
|
2078
|
+
const isKeptControl = (i) => this.tag[i] === "LABEL" || this.tag[i] === "LEGEND" || this.tag[i] === "BUTTON" || isButtonInput(i) || this.attrs[i].get("role") === "button";
|
|
2079
|
+
for (let i = 0; i < this.tag.length; i++) if (isValueField(i) || isChoice(i)) for (let p = i; p >= 0 && !holdsField[p]; p = this.parent[p]) holdsField[p] = true;
|
|
2080
|
+
const holdsKeptInRedact = [];
|
|
2081
|
+
for (let i = 0; i < this.tag.length; i++) {
|
|
2082
|
+
if (this.attrs[i].has("data-agentom-redact") && !holdsField[i]) continue;
|
|
2083
|
+
if (isValueField(i) || isChoice(i) || isKeptControl(i)) for (let p = i; p >= 0 && !holdsKeptInRedact[p]; p = this.parent[p]) {
|
|
2084
|
+
if (this.attrs[p].has("data-agentom-redact") && !holdsField[p]) break;
|
|
2085
|
+
holdsKeptInRedact[p] = true;
|
|
2086
|
+
}
|
|
2087
|
+
}
|
|
2088
|
+
const inKept = [];
|
|
1787
2089
|
for (let i = 0; i < this.tag.length; i++) {
|
|
1788
2090
|
const p = this.parent[i];
|
|
1789
2091
|
const a = this.attrs[i];
|
|
1790
2092
|
ignored[i] = p >= 0 && ignored[p] || a.has("data-agentom-ignore");
|
|
1791
2093
|
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
2094
|
const tag = this.tag[i];
|
|
1796
2095
|
const tokens = (a.get("autocomplete") ?? "").toLowerCase().split(/\s+/);
|
|
1797
|
-
const
|
|
1798
|
-
const choice =
|
|
1799
|
-
|
|
1800
|
-
|
|
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];
|
|
2096
|
+
const valueField = isValueField(i);
|
|
2097
|
+
const choice = isChoice(i);
|
|
2098
|
+
this.credential[i] = tag === "INPUT" && inputType(i) === "password" || valueField && FIELD_TAGS.has(tag) && tokens.some((t) => SECRET_TOKENS.has(t));
|
|
2099
|
+
this.secret[i] = valueField && redacted[i] || this.credential[i];
|
|
1808
2100
|
this.secretChoice[i] = choice && redacted[i] || (tag === "OPTION" || tag === "OPTGROUP") && p >= 0 && (this.secret[p] || this.secretChoice[p]);
|
|
2101
|
+
const redactsText = a.has("data-agentom-redact") && !holdsField[i];
|
|
2102
|
+
inKept[i] = !redactsText && (isKeptControl(i) || this.secretChoice[i] || p >= 0 && inKept[p]);
|
|
2103
|
+
const inheritedRedactDrop = redacted[i] && !holdsKeptInRedact[i] && !inKept[i];
|
|
2104
|
+
this.dropped[i] = ignored[i] || redactsText || inheritedRedactDrop || p >= 0 && this.dropped[p];
|
|
2105
|
+
if (this.dropped[i]) this.anyKeptOut = true;
|
|
1809
2106
|
}
|
|
1810
2107
|
}
|
|
1811
2108
|
/** What the page declares of itself: the first element in the document with each attribute. */
|
|
@@ -1887,11 +2184,44 @@ var Dom = class {
|
|
|
1887
2184
|
ref(i) {
|
|
1888
2185
|
return `e${this.backend[i]}`;
|
|
1889
2186
|
}
|
|
1890
|
-
/**
|
|
2187
|
+
/** The enclosing <select> of an option, or -1 if none. */
|
|
2188
|
+
selectOf(i) {
|
|
2189
|
+
for (let p = this.parent[i]; p >= 0; p = this.parent[p]) if (this.tag[p] === "SELECT") return p;
|
|
2190
|
+
return -1;
|
|
2191
|
+
}
|
|
2192
|
+
/** All text inside an element, in document order. */
|
|
2193
|
+
textContent(i) {
|
|
2194
|
+
let out = "";
|
|
2195
|
+
const stack = [i];
|
|
2196
|
+
while (stack.length) {
|
|
2197
|
+
const k = stack.pop();
|
|
2198
|
+
const t = this.text.get(k);
|
|
2199
|
+
if (t !== void 0) out += t;
|
|
2200
|
+
const kids = this.children.get(k) ?? [];
|
|
2201
|
+
for (let c = kids.length - 1; c >= 0; c--) stack.push(kids[c]);
|
|
2202
|
+
}
|
|
2203
|
+
return out;
|
|
2204
|
+
}
|
|
2205
|
+
/** An editable region's own text, leaving out aria-hidden placeholders. */
|
|
2206
|
+
editableText(i) {
|
|
2207
|
+
let out = "";
|
|
2208
|
+
const stack = [i];
|
|
2209
|
+
while (stack.length) {
|
|
2210
|
+
const k = stack.pop();
|
|
2211
|
+
if (k !== i && this.attrs[k]?.get("aria-hidden")?.trim().toLowerCase() === "true") continue;
|
|
2212
|
+
const t = this.text.get(k);
|
|
2213
|
+
if (t !== void 0) out += t;
|
|
2214
|
+
const kids = this.children.get(k) ?? [];
|
|
2215
|
+
for (let c = kids.length - 1; c >= 0; c--) stack.push(kids[c]);
|
|
2216
|
+
}
|
|
2217
|
+
return out.trim();
|
|
2218
|
+
}
|
|
2219
|
+
/** Whether a secret field holds something: typed text, edited text, or a chosen option of a drop-down. */
|
|
1891
2220
|
holds(i) {
|
|
1892
2221
|
if ((this.input.get(i) ?? "") !== "") return true;
|
|
2222
|
+
if (this.editableRoot(i)) return this.editableText(i) !== "";
|
|
1893
2223
|
if (this.tag[i] !== "SELECT") return false;
|
|
1894
|
-
for (const c of this.chosen)
|
|
2224
|
+
for (const c of this.chosen) if (this.selectOf(c) === i) return true;
|
|
1895
2225
|
return false;
|
|
1896
2226
|
}
|
|
1897
2227
|
/** What a nameless control's markup calls it (see OmNode.hint): looked for in it and the first few elements inside it. */
|
|
@@ -2106,10 +2436,27 @@ var Dom = class {
|
|
|
2106
2436
|
}
|
|
2107
2437
|
return out;
|
|
2108
2438
|
}
|
|
2109
|
-
/** Every secret field's value, longest first: what's searched for in all other text. */
|
|
2110
|
-
secrets() {
|
|
2439
|
+
/** Every secret field's value (and chosen text/value of a secret drop-down), longest first: what's searched for in all other text. */
|
|
2440
|
+
secrets(excludeSelect) {
|
|
2111
2441
|
const values = /* @__PURE__ */ new Set();
|
|
2112
|
-
|
|
2442
|
+
const add = (v) => {
|
|
2443
|
+
if (v.length >= SCRUB_MIN) values.add(v);
|
|
2444
|
+
};
|
|
2445
|
+
for (const [i, v] of this.input) if (this.secret[i]) add(v);
|
|
2446
|
+
for (let i = 0; i < this.tag.length; i++) if (this.secret[i] && this.editableRoot(i)) {
|
|
2447
|
+
const raw = this.editableText(i);
|
|
2448
|
+
add(raw);
|
|
2449
|
+
add(squash$1(raw));
|
|
2450
|
+
}
|
|
2451
|
+
for (const c of this.chosen) {
|
|
2452
|
+
const s = this.selectOf(c);
|
|
2453
|
+
if (s >= 0 && s !== excludeSelect && this.secret[s]) {
|
|
2454
|
+
add(this.attrs[c].get("value")?.trim() ?? "");
|
|
2455
|
+
const txt = this.textContent(c).trim();
|
|
2456
|
+
add(txt);
|
|
2457
|
+
add(squash$1(txt));
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2113
2460
|
return [...values].sort((a, b) => b.length - a.length);
|
|
2114
2461
|
}
|
|
2115
2462
|
meta(i) {
|
|
@@ -2432,8 +2779,23 @@ function merge({ ax, dom: snapshot }, filled = []) {
|
|
|
2432
2779
|
n.children?.forEach(resolve);
|
|
2433
2780
|
};
|
|
2434
2781
|
resolve(rootNode);
|
|
2435
|
-
const
|
|
2436
|
-
|
|
2782
|
+
const filledSecrets = filled.filter((v) => v.length >= SCRUB_MIN);
|
|
2783
|
+
const secrets = [.../* @__PURE__ */ new Set([...dom.secrets(), ...filledSecrets])].sort((a, b) => b.length - a.length);
|
|
2784
|
+
const otherForSelect = /* @__PURE__ */ new Map();
|
|
2785
|
+
const secretsForNode = (ref) => {
|
|
2786
|
+
if (!ref) return secrets;
|
|
2787
|
+
const di = dom.index.get(Number(ref.slice(1)));
|
|
2788
|
+
if (di === void 0 || dom.tag[di] !== "OPTION" || !dom.secretChoice[di]) return secrets;
|
|
2789
|
+
const s = dom.selectOf(di);
|
|
2790
|
+
if (s < 0) return secrets;
|
|
2791
|
+
let other = otherForSelect.get(s);
|
|
2792
|
+
if (!other) {
|
|
2793
|
+
other = [.../* @__PURE__ */ new Set([...dom.secrets(s), ...filledSecrets])].sort((a, b) => b.length - a.length);
|
|
2794
|
+
otherForSelect.set(s, other);
|
|
2795
|
+
}
|
|
2796
|
+
return other;
|
|
2797
|
+
};
|
|
2798
|
+
scrub(rootNode, secrets, secretsForNode);
|
|
2437
2799
|
const warnings = dom.warnings();
|
|
2438
2800
|
const context = dom.context((w) => warnings.push(w));
|
|
2439
2801
|
if (secrets.length) {
|
|
@@ -2453,11 +2815,14 @@ function merge({ ax, dom: snapshot }, filled = []) {
|
|
|
2453
2815
|
* secretForms): a name can repeat what a field holds (a combobox named by its value, a label read back), a link can
|
|
2454
2816
|
* carry it encoded.
|
|
2455
2817
|
*/
|
|
2456
|
-
function scrub(node, secrets) {
|
|
2818
|
+
function scrub(node, secrets, forNode) {
|
|
2457
2819
|
if (!secrets.length) return;
|
|
2458
2820
|
const clean = (s) => withoutSecrets(s, secrets);
|
|
2459
2821
|
const walk = (n) => {
|
|
2460
|
-
if (n.name)
|
|
2822
|
+
if (n.name) {
|
|
2823
|
+
const list = forNode ? forNode(n.ref) : secrets;
|
|
2824
|
+
n.name = list.length ? withoutSecrets(n.name, list) : n.name;
|
|
2825
|
+
}
|
|
2461
2826
|
if (n.description) n.description = clean(n.description);
|
|
2462
2827
|
if (n.hint) n.hint = clean(n.hint);
|
|
2463
2828
|
if (n.id) n.id = clean(n.id);
|
|
@@ -2562,6 +2927,11 @@ var Reader = class {
|
|
|
2562
2927
|
focus,
|
|
2563
2928
|
states
|
|
2564
2929
|
});
|
|
2930
|
+
if (dom.documents.length > 1 || last.raw.dom.documents.length > 1) return this.whole("iframes present", from, {
|
|
2931
|
+
dom,
|
|
2932
|
+
focus,
|
|
2933
|
+
states
|
|
2934
|
+
});
|
|
2565
2935
|
const facts = new Facts(dom);
|
|
2566
2936
|
const plan = compare(last.facts ?? new Facts(last.raw.dom), facts, last.focus, focus, last.had ?? domIds(last.raw.ax));
|
|
2567
2937
|
if ("whole" in plan) return this.whole(plan.whole, from, {
|
|
@@ -2612,7 +2982,10 @@ var Reader = class {
|
|
|
2612
2982
|
} else if (from === 0 || this.last && this.last.raw.ax.length >= from) {
|
|
2613
2983
|
[focus, states] = await Promise.all([focused(this.cdp), fieldStates(this.cdp)]);
|
|
2614
2984
|
raw = await readPage(this.cdp);
|
|
2615
|
-
} else
|
|
2985
|
+
} else {
|
|
2986
|
+
raw = await readPage(this.cdp);
|
|
2987
|
+
if (raw.ax.length >= from) [focus, states] = await Promise.all([focused(this.cdp), fieldStates(this.cdp)]);
|
|
2988
|
+
}
|
|
2616
2989
|
this.last = {
|
|
2617
2990
|
raw,
|
|
2618
2991
|
focus,
|
|
@@ -2709,14 +3082,17 @@ function domIds(ax) {
|
|
|
2709
3082
|
}
|
|
2710
3083
|
/** The DOM node id of the element that has the focus, unless it's the page itself. */
|
|
2711
3084
|
async function focused(cdp) {
|
|
3085
|
+
let objectId;
|
|
2712
3086
|
try {
|
|
2713
3087
|
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
|
-
|
|
2715
|
-
|
|
2716
|
-
await cdp.send("
|
|
3088
|
+
objectId = result.objectId;
|
|
3089
|
+
if (!objectId) return void 0;
|
|
3090
|
+
const { node } = await cdp.send("DOM.describeNode", { objectId });
|
|
2717
3091
|
return node.backendNodeId;
|
|
2718
3092
|
} catch {
|
|
2719
3093
|
return;
|
|
3094
|
+
} finally {
|
|
3095
|
+
if (objectId) await cdp.send("Runtime.releaseObject", { objectId }).catch(() => {});
|
|
2720
3096
|
}
|
|
2721
3097
|
}
|
|
2722
3098
|
/**
|
|
@@ -2785,8 +3161,9 @@ var Facts = class {
|
|
|
2785
3161
|
for (let k = 0; k + 1 < attrs.length; k += 2) {
|
|
2786
3162
|
const name = this.s[attrs[k]].toLowerCase();
|
|
2787
3163
|
const value = this.s[attrs[k + 1]] ?? "";
|
|
2788
|
-
if (name === "id" && value)
|
|
2789
|
-
|
|
3164
|
+
if (name === "id" && value) {
|
|
3165
|
+
if (!this.ids.has(value)) this.ids.set(value, i);
|
|
3166
|
+
} 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
3167
|
else if (name === "aria-owns") {
|
|
2791
3168
|
this.owners.add(i);
|
|
2792
3169
|
value.split(/\s+/).filter(Boolean).forEach((id) => this.owned.add(id));
|
|
@@ -2805,7 +3182,7 @@ var Facts = class {
|
|
|
2805
3182
|
if (c !== void 0) this.labels.set(i, c);
|
|
2806
3183
|
continue;
|
|
2807
3184
|
}
|
|
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")) {
|
|
3185
|
+
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")?.toLowerCase() === "hidden")) {
|
|
2809
3186
|
this.labels.set(i, j);
|
|
2810
3187
|
break;
|
|
2811
3188
|
}
|
|
@@ -2975,6 +3352,13 @@ function compare(o, a, focusBefore, focusAfter, had) {
|
|
|
2975
3352
|
...list ? { body: a.backend(body) } : {}
|
|
2976
3353
|
};
|
|
2977
3354
|
}
|
|
3355
|
+
// ../cdp-reader/src/settle.ts
|
|
3356
|
+
/** Settled: no request in flight for this long… */
|
|
3357
|
+
const NET_QUIET_MS = 500;
|
|
3358
|
+
/** …no DOM change for this long, and nothing marked aria-busy… */
|
|
3359
|
+
const DOM_QUIET_MS = 300;
|
|
3360
|
+
/** Fast grace window after an in-page action that starts no waited-for network request. */
|
|
3361
|
+
const ACTION_QUIET_MS = 120;
|
|
2978
3362
|
/** …or read as it is after this long. */
|
|
2979
3363
|
const SETTLE_MAX_MS = 5e3;
|
|
2980
3364
|
/** A request open longer than this (a long poll) no longer counts. */
|
|
@@ -3018,8 +3402,8 @@ async function settle$1(o) {
|
|
|
3018
3402
|
quietNet = t;
|
|
3019
3403
|
sawNet = true;
|
|
3020
3404
|
}
|
|
3021
|
-
const needNet = sawNet ?
|
|
3022
|
-
const needDom = sawNet ?
|
|
3405
|
+
const needNet = sawNet ? NET_QUIET_MS : ACTION_QUIET_MS;
|
|
3406
|
+
const needDom = sawNet ? DOM_QUIET_MS : ACTION_QUIET_MS;
|
|
3023
3407
|
const domQuiet = now?.idleMs !== void 0 ? Math.min(t - lastChange, now.idleMs) : t - lastChange;
|
|
3024
3408
|
if (t - quietNet >= needNet && domQuiet >= needDom && !now?.busy && now) return { settled: true };
|
|
3025
3409
|
if (t - start >= maxMs) {
|
|
@@ -3044,16 +3428,25 @@ function requestsOf(page) {
|
|
|
3044
3428
|
open = map;
|
|
3045
3429
|
tracked.set(page, map);
|
|
3046
3430
|
page.on("request", (r) => {
|
|
3047
|
-
if (WAITED_FOR.has(r.resourceType()))
|
|
3431
|
+
if (!WAITED_FOR.has(r.resourceType())) return;
|
|
3432
|
+
const now = Date.now();
|
|
3433
|
+
for (const [req, started] of map) if (now - started >= LONG_REQUEST_MS) map.delete(req);
|
|
3434
|
+
map.set(r, now);
|
|
3048
3435
|
});
|
|
3049
3436
|
page.on("requestfinished", (r) => map.delete(r));
|
|
3050
3437
|
page.on("requestfailed", (r) => map.delete(r));
|
|
3051
3438
|
}
|
|
3052
3439
|
const map = open;
|
|
3053
|
-
return () =>
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3440
|
+
return () => {
|
|
3441
|
+
const now = Date.now();
|
|
3442
|
+
const out = [];
|
|
3443
|
+
for (const [r, started] of map) if (now - started >= LONG_REQUEST_MS) map.delete(r);
|
|
3444
|
+
else out.push({
|
|
3445
|
+
started,
|
|
3446
|
+
said: `${r.method()} ${r.url()}`
|
|
3447
|
+
});
|
|
3448
|
+
return out;
|
|
3449
|
+
};
|
|
3057
3450
|
}
|
|
3058
3451
|
// src/page.ts
|
|
3059
3452
|
/** 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. */
|
|
@@ -3216,27 +3609,55 @@ async function refAround(page, el, p) {
|
|
|
3216
3609
|
walk(p.root);
|
|
3217
3610
|
const session = await cdp(page);
|
|
3218
3611
|
await declared(page, session);
|
|
3219
|
-
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
|
|
3228
|
-
|
|
3612
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
3613
|
+
const depth = await el.evaluate(inPage(["el"], `const a = []; for (let n = el; n; n = n.parentElement || (n.getRootNode && n.getRootNode().host) || null) a.push(n); ${CHAIN} = a; return a.length`));
|
|
3614
|
+
let tampered = false;
|
|
3615
|
+
try {
|
|
3616
|
+
for (let k = 0; k < depth; k++) {
|
|
3617
|
+
const { result } = await session.send("Runtime.evaluate", { expression: `Array.isArray(${CHAIN}) ? ${CHAIN}[${k}] : undefined` });
|
|
3618
|
+
if (!result.objectId) {
|
|
3619
|
+
tampered = true;
|
|
3620
|
+
break;
|
|
3621
|
+
}
|
|
3622
|
+
try {
|
|
3623
|
+
const { node } = await session.send("DOM.describeNode", { objectId: result.objectId });
|
|
3624
|
+
const ref = `e${node.backendNodeId}`;
|
|
3625
|
+
if (!refs.has(ref)) continue;
|
|
3626
|
+
await session.send("Runtime.callFunctionOn", {
|
|
3627
|
+
objectId: result.objectId,
|
|
3628
|
+
functionDeclaration: `function () { ${HELD} = this }`
|
|
3629
|
+
});
|
|
3630
|
+
const matchesEl = await el.evaluate(inPage(["el", "k"], `let n = el; for (let i = 0; i < k && n; i++) n = n.parentElement || (n.getRootNode && n.getRootNode().host) || null; return !!n && n === ${HELD} && Array.isArray(${CHAIN}) && ${CHAIN}[0] === el && ${CHAIN}[k] === ${HELD}`), k);
|
|
3631
|
+
const { result: same } = await session.send("Runtime.callFunctionOn", {
|
|
3632
|
+
objectId: result.objectId,
|
|
3633
|
+
functionDeclaration: `function () { const ok = ${HELD} === this; ${HELD} = undefined; return ok }`,
|
|
3634
|
+
returnByValue: true
|
|
3635
|
+
});
|
|
3636
|
+
if (matchesEl && same.value === true) return ref;
|
|
3637
|
+
tampered = true;
|
|
3638
|
+
break;
|
|
3639
|
+
} finally {
|
|
3640
|
+
await session.send("Runtime.releaseObject", { objectId: result.objectId }).catch(() => {});
|
|
3641
|
+
}
|
|
3642
|
+
}
|
|
3643
|
+
if (!tampered) {
|
|
3644
|
+
if (await el.evaluate(inPage(["el"], `return Array.isArray(${CHAIN}) && ${CHAIN}.length === ${depth} && ${CHAIN}[0] === el`))) return void 0;
|
|
3229
3645
|
}
|
|
3646
|
+
} finally {
|
|
3647
|
+
await session.send("Runtime.evaluate", { expression: `${CHAIN} = undefined; ${HELD} = undefined` }).catch(() => {});
|
|
3230
3648
|
}
|
|
3231
|
-
return;
|
|
3232
|
-
} finally {
|
|
3233
|
-
await session.send("Runtime.evaluate", { expression: `${CHAIN} = undefined` }).catch(() => {});
|
|
3234
3649
|
}
|
|
3650
|
+
throw new ToolError("the page interfered while verifying the element: refusing to act");
|
|
3235
3651
|
}
|
|
3236
3652
|
/** How much of what a script says the agent is told. */
|
|
3237
3653
|
const SCRIPT_MAX = 2e4;
|
|
3238
3654
|
/** The commands a script can't call: those of the session, those that need what only the shell has, and itself. */
|
|
3239
3655
|
const NOT_IN_SCRIPTS = /* @__PURE__ */ new Set(["script", "fill-secret"]);
|
|
3656
|
+
/** The commands a script is allowed to call through `om`, enforced on the Node side as well as exposed in the prelude. */
|
|
3657
|
+
function allowedScriptCommands(s) {
|
|
3658
|
+
const on = [...s.allowEval ? ["eval"] : [], ...s.allowScreenshot ? ["screenshot"] : []];
|
|
3659
|
+
return new Set(commandsFor("cli", on).filter((c) => c.group !== "session" && !NOT_IN_SCRIPTS.has(c.name)).map((c) => c.name));
|
|
3660
|
+
}
|
|
3240
3661
|
/** A command's name as a script calls it: switch-tab as switchTab. */
|
|
3241
3662
|
const camel = (name) => name.replace(/-(\w)/g, (_, c) => c.toUpperCase());
|
|
3242
3663
|
function find(p, f = {}) {
|
|
@@ -3300,6 +3721,7 @@ async function dispatch(s, box, name, values) {
|
|
|
3300
3721
|
s.last ??= p;
|
|
3301
3722
|
return name === "read" ? p : name === "find" ? find(p, values[0] ?? {}) : table(p, String(values[0]?.ref ?? values[0]));
|
|
3302
3723
|
}
|
|
3724
|
+
if (!allowedScriptCommands(s).has(name)) throw new ToolError(`'${name}' cannot be called from a script`);
|
|
3303
3725
|
box.read = void 0;
|
|
3304
3726
|
try {
|
|
3305
3727
|
if (name !== "eval") return await runCommand(s, name, asArgs(name, values), {});
|
|
@@ -3395,8 +3817,7 @@ async function sandboxOf(s) {
|
|
|
3395
3817
|
});
|
|
3396
3818
|
}
|
|
3397
3819
|
});
|
|
3398
|
-
const
|
|
3399
|
-
const commands = commandsFor("cli", on).filter((c) => c.group !== "session" && !NOT_IN_SCRIPTS.has(c.name)).map((c) => c.name);
|
|
3820
|
+
const commands = [...allowedScriptCommands(s)];
|
|
3400
3821
|
await page.evaluate(prelude(commands));
|
|
3401
3822
|
s.sandbox = box;
|
|
3402
3823
|
return box;
|
|
@@ -3435,6 +3856,7 @@ async function runScript(s, script, ms) {
|
|
|
3435
3856
|
const said = (await box.page.evaluate("globalThis.__said.splice(0)").catch(() => [])).join("\n");
|
|
3436
3857
|
const cut = (text) => text.length > SCRIPT_MAX ? `${text.slice(0, SCRIPT_MAX)}… (${text.length - SCRIPT_MAX} more characters cut: print less)` : text;
|
|
3437
3858
|
if (r === "late") {
|
|
3859
|
+
evaluated.catch(() => {});
|
|
3438
3860
|
s.sandbox = void 0;
|
|
3439
3861
|
await box.close();
|
|
3440
3862
|
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}` : ""}`));
|
|
@@ -3493,11 +3915,30 @@ const SCRIPT_MS = 1e5;
|
|
|
3493
3915
|
const DOWNLOAD_WAIT_MS = 3e4;
|
|
3494
3916
|
/** A file the page downloads, saved in the session's folder under the name the page gives it (never over another), and said. */
|
|
3495
3917
|
function saveDownload(s, d) {
|
|
3496
|
-
|
|
3497
|
-
|
|
3918
|
+
let name = basename(d.suggestedFilename()).replace(/[^\w.\- ()]/g, "_").trim();
|
|
3919
|
+
if (!name || /^\.+$/.test(name)) name = "download";
|
|
3920
|
+
mkdirSync(s.downloads, {
|
|
3921
|
+
recursive: true,
|
|
3922
|
+
mode: 448
|
|
3923
|
+
});
|
|
3924
|
+
const ext = extname(name);
|
|
3925
|
+
const stem = basename(name, ext);
|
|
3498
3926
|
let file = join(s.downloads, name);
|
|
3499
|
-
for (let k =
|
|
3500
|
-
|
|
3927
|
+
for (let k = 1;; k++) {
|
|
3928
|
+
const candidate = k === 1 ? join(s.downloads, name) : join(s.downloads, `${stem} (${k})${ext}`);
|
|
3929
|
+
try {
|
|
3930
|
+
const fd = openSync(candidate, "wx", 384);
|
|
3931
|
+
closeSync(fd);
|
|
3932
|
+
file = candidate;
|
|
3933
|
+
break;
|
|
3934
|
+
} catch (e) {
|
|
3935
|
+
if (e.code !== "EEXIST") throw e;
|
|
3936
|
+
}
|
|
3937
|
+
}
|
|
3938
|
+
const saving = d.saveAs(file).then(() => void s.beside.push(`the page downloaded ${name} (${size(statSync(file).size)}): saved as ${file}`), () => {
|
|
3939
|
+
rmSync(file, { force: true });
|
|
3940
|
+
s.beside.push(`the page started downloading ${name}, but it failed: ${said(s, d.url())}`);
|
|
3941
|
+
});
|
|
3501
3942
|
s.saving.add(saving);
|
|
3502
3943
|
saving.finally(() => s.saving.delete(saving));
|
|
3503
3944
|
}
|
|
@@ -3506,7 +3947,13 @@ const size = (bytes) => bytes < 1024 ? `${bytes} bytes` : bytes < 1048576 ? `${M
|
|
|
3506
3947
|
async function downloaded(s) {
|
|
3507
3948
|
if (!s.saving.size) return;
|
|
3508
3949
|
const all = Promise.all([...s.saving]);
|
|
3509
|
-
|
|
3950
|
+
let timer;
|
|
3951
|
+
if (await Promise.race([all.then(() => false), new Promise((r) => {
|
|
3952
|
+
timer = setTimeout(() => r(true), DOWNLOAD_WAIT_MS);
|
|
3953
|
+
})]).finally(() => clearTimeout(timer))) {
|
|
3954
|
+
all.catch(() => {});
|
|
3955
|
+
s.beside.push(`a download isn't finished yet: it is said when it is (in ${s.downloads})`);
|
|
3956
|
+
}
|
|
3510
3957
|
}
|
|
3511
3958
|
const KEPT = 200;
|
|
3512
3959
|
const keep = (list, item) => {
|
|
@@ -3523,18 +3970,18 @@ function bare(url) {
|
|
|
3523
3970
|
}
|
|
3524
3971
|
}
|
|
3525
3972
|
/** Follow what a tab's page logs and asks for. */
|
|
3526
|
-
function listen(tab) {
|
|
3973
|
+
function listen(s, tab) {
|
|
3527
3974
|
tab.page.on("console", (m) => {
|
|
3528
3975
|
const where = m.location();
|
|
3529
3976
|
keep(tab.logged, {
|
|
3530
3977
|
level: m.type(),
|
|
3531
|
-
text: m.text().slice(0, 500),
|
|
3532
|
-
...where.url ? { where: `${bare(where.url)}:${where.lineNumber + 1}` } : {}
|
|
3978
|
+
text: said(s, m.text()).slice(0, 500),
|
|
3979
|
+
...where.url ? { where: `${said(s, bare(where.url))}:${where.lineNumber + 1}` } : {}
|
|
3533
3980
|
});
|
|
3534
3981
|
});
|
|
3535
3982
|
tab.page.on("pageerror", (e) => keep(tab.logged, {
|
|
3536
3983
|
level: "error",
|
|
3537
|
-
text: `uncaught: ${String(e.message).slice(0, 500)}`
|
|
3984
|
+
text: `uncaught: ${said(s, String(e.message)).slice(0, 500)}`
|
|
3538
3985
|
}));
|
|
3539
3986
|
tab.page.on("requestfinished", (r) => void r.response().then((res) => keep(tab.requested, {
|
|
3540
3987
|
method: r.method(),
|
|
@@ -3574,7 +4021,10 @@ async function target(s, a, now) {
|
|
|
3574
4021
|
const el = await elementOf(s.page, ref);
|
|
3575
4022
|
if (!el) throw new ToolError(await goneRef(s, ref));
|
|
3576
4023
|
const g = guard(now.root, ref);
|
|
3577
|
-
if (!node || !g)
|
|
4024
|
+
if (!node || !g) {
|
|
4025
|
+
await el.dispose().catch(() => {});
|
|
4026
|
+
throw new ToolError(noRef(ref));
|
|
4027
|
+
}
|
|
3578
4028
|
return {
|
|
3579
4029
|
el,
|
|
3580
4030
|
ref,
|
|
@@ -3626,30 +4076,42 @@ async function byText(s, a, text, now) {
|
|
|
3626
4076
|
const lines = [];
|
|
3627
4077
|
for (const [k, loc] of shown.slice(0, CANDIDATES).entries()) {
|
|
3628
4078
|
const el = await loc.elementHandle();
|
|
3629
|
-
|
|
3630
|
-
|
|
3631
|
-
|
|
3632
|
-
|
|
4079
|
+
try {
|
|
4080
|
+
const around = await refAround(s.page, el, now);
|
|
4081
|
+
const node = around ? nodeOf(now, around) : void 0;
|
|
4082
|
+
const what = squash(await loc.innerText()).slice(0, 80);
|
|
4083
|
+
lines.push(` --nth ${k + 1}: ${JSON.stringify(what)}${node ? ` in ${line(node)}` : ""}`);
|
|
4084
|
+
} finally {
|
|
4085
|
+
await el?.dispose().catch(() => {});
|
|
4086
|
+
}
|
|
3633
4087
|
}
|
|
3634
4088
|
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
4089
|
}
|
|
3636
4090
|
const pick = shown[(nth ?? 1) - 1];
|
|
3637
4091
|
if (!pick) throw new ToolError(`only ${shown.length} things show ${JSON.stringify(text)}`);
|
|
3638
4092
|
const el = await pick.elementHandle();
|
|
3639
|
-
const
|
|
3640
|
-
const
|
|
3641
|
-
|
|
3642
|
-
const
|
|
3643
|
-
const
|
|
3644
|
-
|
|
4093
|
+
const labelledHandle = await el.evaluateHandle(inPage(["el"], "const l = el.closest(\"label\"); return (l && l.control) || null"));
|
|
4094
|
+
const labelled = labelledHandle.asElement();
|
|
4095
|
+
try {
|
|
4096
|
+
const guards = [];
|
|
4097
|
+
for (const of of [el, labelled]) {
|
|
4098
|
+
const around = of ? await refAround(s.page, of, now) : void 0;
|
|
4099
|
+
const g = around ? guard(now.root, around) : void 0;
|
|
4100
|
+
if (g) guards.push(g);
|
|
4101
|
+
}
|
|
4102
|
+
const asks = guards.find((g) => g.asks)?.asks;
|
|
4103
|
+
return {
|
|
4104
|
+
el,
|
|
4105
|
+
...asks ? { asks } : {},
|
|
4106
|
+
credential: guards.some((g) => g.credential),
|
|
4107
|
+
name: `the ${nth ? `${ordinal(nth)} ` : ""}element showing ${JSON.stringify(text)}`
|
|
4108
|
+
};
|
|
4109
|
+
} catch (e) {
|
|
4110
|
+
await el.dispose().catch(() => {});
|
|
4111
|
+
throw e;
|
|
4112
|
+
} finally {
|
|
4113
|
+
await labelledHandle.dispose().catch(() => {});
|
|
3645
4114
|
}
|
|
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
4115
|
}
|
|
3654
4116
|
const squash = (x) => x.replace(/\s+/g, " ").trim();
|
|
3655
4117
|
const ordinal = (n) => `${n}${n % 10 === 1 && n !== 11 ? "st" : n % 10 === 2 && n !== 12 ? "nd" : n % 10 === 3 && n !== 13 ? "rd" : "th"}`;
|
|
@@ -3666,20 +4128,24 @@ async function coveredBy(s, t, now) {
|
|
|
3666
4128
|
});
|
|
3667
4129
|
const el = await elementOf(s.page, `e${at.backendNodeId}`);
|
|
3668
4130
|
if (!el) return void 0;
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
|
|
4131
|
+
try {
|
|
4132
|
+
if (await el.evaluate(inPage(["el", "target"], "return target.contains(el)"), t.el)) return void 0;
|
|
4133
|
+
const around = await refAround(s.page, el, now);
|
|
4134
|
+
const path = around ? pathTo(now, around) : void 0;
|
|
4135
|
+
const holder = path?.find((n) => [
|
|
4136
|
+
"dialog",
|
|
4137
|
+
"alertdialog",
|
|
4138
|
+
"menu",
|
|
4139
|
+
"listbox",
|
|
4140
|
+
"tooltip",
|
|
4141
|
+
"banner"
|
|
4142
|
+
].includes(n.role)) ?? path?.at(-1);
|
|
4143
|
+
if (holder) return line(holder);
|
|
4144
|
+
const open = openOverlay(now.root);
|
|
4145
|
+
return open ? `something with no ref, while ${line(open)} is open,` : "something with no ref";
|
|
4146
|
+
} finally {
|
|
4147
|
+
await el.dispose().catch(() => {});
|
|
4148
|
+
}
|
|
3683
4149
|
} catch {
|
|
3684
4150
|
return;
|
|
3685
4151
|
}
|
|
@@ -3936,12 +4402,39 @@ async function after(s, done, action = true) {
|
|
|
3936
4402
|
readAs(s, now);
|
|
3937
4403
|
return lines.join("\n");
|
|
3938
4404
|
}
|
|
4405
|
+
/** Live DOM security attribute check for cached refs so in-place SPA mutations on the same URL cannot bypass guard(). */
|
|
4406
|
+
const LIVE_GUARD = `
|
|
4407
|
+
const TOKENS = new Set(${JSON.stringify(SECRET_AUTOCOMPLETE_TOKENS)})
|
|
4408
|
+
let hidden = false, confirm = false, credential = false
|
|
4409
|
+
for (let n = el; n; n = n.parentElement || (n.getRootNode && n.getRootNode().host) || null) {
|
|
4410
|
+
if (n.hasAttribute('data-agentom-ignore') || n.getAttribute('aria-hidden') === 'true') hidden = true
|
|
4411
|
+
if (n.getAttribute('data-agentom-confirmation') === 'required') confirm = true
|
|
4412
|
+
if (n.localName === 'input' && n.type === 'password') credential = true
|
|
4413
|
+
if ((n.localName === 'input' || n.localName === 'select' || n.localName === 'textarea') && (n.getAttribute('autocomplete') || '').toLowerCase().split(/\\s+/).some((t) => TOKENS.has(t))) credential = true
|
|
4414
|
+
}
|
|
4415
|
+
return { hidden, confirm, credential }
|
|
4416
|
+
`;
|
|
3939
4417
|
/** A command that acts on one target. */
|
|
3940
4418
|
const step = (verb, done, run, check) => async (s, a) => {
|
|
3941
4419
|
const ref = flag(a, "text") === void 0 ? a._[0] : void 0;
|
|
3942
|
-
const
|
|
3943
|
-
|
|
4420
|
+
const cached = ref && s.last && s.last.url === s.page.url() && nodeOf(s.last, ref) ? s.last : void 0;
|
|
4421
|
+
let now = cached ?? await readNow(s);
|
|
4422
|
+
let t = await target(s, a, now);
|
|
3944
4423
|
try {
|
|
4424
|
+
if (cached) {
|
|
4425
|
+
const live = await t.el.evaluate(inPage(["el"], LIVE_GUARD)).catch(() => ({
|
|
4426
|
+
hidden: true,
|
|
4427
|
+
confirm: true,
|
|
4428
|
+
credential: true
|
|
4429
|
+
}));
|
|
4430
|
+
const cachedConfirm = !!(t.asks ?? t.node)?.meta?.confirm;
|
|
4431
|
+
const cachedCredential = !!(t.node?.credential || t.credential);
|
|
4432
|
+
if (live.hidden || live.confirm && !cachedConfirm || live.credential && !cachedCredential) {
|
|
4433
|
+
await t.el.dispose().catch(() => {});
|
|
4434
|
+
now = await readNow(s);
|
|
4435
|
+
t = await target(s, a, now);
|
|
4436
|
+
}
|
|
4437
|
+
}
|
|
3945
4438
|
confirmFirst(t, a);
|
|
3946
4439
|
check?.(t, a);
|
|
3947
4440
|
await act(s, t, verb, now, () => run(s, t, a));
|
|
@@ -3982,12 +4475,20 @@ function isTimeZone(zone) {
|
|
|
3982
4475
|
function narrowed(a) {
|
|
3983
4476
|
const o = {};
|
|
3984
4477
|
const depth = flag(a, "depth");
|
|
3985
|
-
if (depth !== void 0)
|
|
4478
|
+
if (depth !== void 0) {
|
|
4479
|
+
const n = Number(depth);
|
|
4480
|
+
if (!Number.isInteger(n) || n < 0) throw new ToolError(`--depth <n>: a whole number (0 or more), got '${depth}'`);
|
|
4481
|
+
o.depth = n;
|
|
4482
|
+
}
|
|
3986
4483
|
if (a.flags.interactive === true || a.flags.i === true) o.interactive = true;
|
|
3987
4484
|
const match = flag(a, "match");
|
|
3988
4485
|
if (match) o.match = match.split(/\\?[,|]/).map((w) => w.trim()).filter(Boolean);
|
|
3989
4486
|
const limit = flag(a, "limit");
|
|
3990
|
-
if (limit !== void 0)
|
|
4487
|
+
if (limit !== void 0) {
|
|
4488
|
+
const n = Number(limit);
|
|
4489
|
+
if (!Number.isInteger(n) || n < 0) throw new ToolError(`--limit <n>: a whole number (0 or more; 0 for none cut), got '${limit}'`);
|
|
4490
|
+
o.limit = n;
|
|
4491
|
+
}
|
|
3991
4492
|
return o;
|
|
3992
4493
|
}
|
|
3993
4494
|
const COMMANDS = {
|
|
@@ -4002,7 +4503,10 @@ const COMMANDS = {
|
|
|
4002
4503
|
} catch {
|
|
4003
4504
|
throw new ToolError(`'${where}' isn't an address (https://…) or, once a page is open, a path on its site (/settings)`);
|
|
4004
4505
|
}
|
|
4005
|
-
if (s.allowed
|
|
4506
|
+
if (s.allowed) {
|
|
4507
|
+
const parsed = new URL(url);
|
|
4508
|
+
if (parsed.protocol === "data:" || !s.allowed.includes(parsed.origin)) throw new ToolError(`${parsed.protocol === "data:" ? "data: URL" : parsed.origin} isn't one of the sites this session may open: ${s.allowed.join(", ")}`);
|
|
4509
|
+
}
|
|
4006
4510
|
await watch(s.page);
|
|
4007
4511
|
try {
|
|
4008
4512
|
await s.page.goto(url, { waitUntil: "domcontentloaded" });
|
|
@@ -4050,35 +4554,40 @@ const COMMANDS = {
|
|
|
4050
4554
|
async select(s, a) {
|
|
4051
4555
|
const now = await readNow(s);
|
|
4052
4556
|
const t = await target(s, a, now);
|
|
4053
|
-
|
|
4054
|
-
|
|
4055
|
-
|
|
4056
|
-
|
|
4057
|
-
|
|
4058
|
-
|
|
4059
|
-
|
|
4060
|
-
|
|
4061
|
-
|
|
4062
|
-
|
|
4063
|
-
|
|
4064
|
-
|
|
4065
|
-
|
|
4066
|
-
|
|
4067
|
-
|
|
4068
|
-
await
|
|
4069
|
-
const
|
|
4070
|
-
|
|
4071
|
-
exact
|
|
4072
|
-
|
|
4073
|
-
|
|
4074
|
-
|
|
4075
|
-
|
|
4076
|
-
const
|
|
4077
|
-
|
|
4557
|
+
try {
|
|
4558
|
+
confirmFirst(t, a);
|
|
4559
|
+
noCredential(t);
|
|
4560
|
+
const values = flag(a, "text") !== void 0 ? a._ : a._.slice(1);
|
|
4561
|
+
if (!values.length) throw new ToolError("agent-om select <ref> <choice…>");
|
|
4562
|
+
if (await t.el.evaluate(inPage(["el"], "return el.localName === \"select\""))) {
|
|
4563
|
+
await act(s, t, "choose in", now, async () => {
|
|
4564
|
+
const options = await t.el.evaluate(inPage(["el"], "return [...el.options].map((o) => ({ value: o.value, label: o.label.trim() }))"));
|
|
4565
|
+
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())));
|
|
4566
|
+
const missing = values.filter((_, k) => !wanted[k]);
|
|
4567
|
+
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(", ")}`);
|
|
4568
|
+
await t.el.selectOption(wanted.map((o) => ({ value: o.value })), { timeout: STEP_MS });
|
|
4569
|
+
});
|
|
4570
|
+
return await after(s, `chose ${values.map((v) => JSON.stringify(v)).join(", ")} in ${t.name}`);
|
|
4571
|
+
}
|
|
4572
|
+
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 }));
|
|
4573
|
+
for (const v of values) {
|
|
4574
|
+
await settle(s.page, 2e3);
|
|
4575
|
+
const exact = s.page.getByRole("option", {
|
|
4576
|
+
name: v,
|
|
4577
|
+
exact: true
|
|
4578
|
+
});
|
|
4579
|
+
const loose = s.page.getByRole("option", { name: v });
|
|
4580
|
+
const option = await exact.count() ? exact.first() : await loose.count() ? loose.first() : void 0;
|
|
4581
|
+
if (!option) {
|
|
4582
|
+
const shown = await s.page.getByRole("option").allInnerTexts().catch(() => []);
|
|
4583
|
+
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"}`);
|
|
4584
|
+
}
|
|
4585
|
+
await option.click({ timeout: STEP_MS });
|
|
4078
4586
|
}
|
|
4079
|
-
await
|
|
4587
|
+
return await after(s, `chose ${values.map((v) => JSON.stringify(v)).join(", ")} in ${t.name}`);
|
|
4588
|
+
} finally {
|
|
4589
|
+
await t.el.dispose().catch(() => {});
|
|
4080
4590
|
}
|
|
4081
|
-
return after(s, `chose ${values.map((v) => JSON.stringify(v)).join(", ")} in ${t.name}`);
|
|
4082
4591
|
},
|
|
4083
4592
|
async press(s, a) {
|
|
4084
4593
|
const byTextTarget = flag(a, "text") !== void 0;
|
|
@@ -4093,28 +4602,41 @@ const COMMANDS = {
|
|
|
4093
4602
|
...a,
|
|
4094
4603
|
_: [a._[0]]
|
|
4095
4604
|
}, now) : void 0;
|
|
4096
|
-
|
|
4097
|
-
|
|
4098
|
-
|
|
4099
|
-
|
|
4100
|
-
|
|
4101
|
-
|
|
4102
|
-
|
|
4103
|
-
|
|
4104
|
-
|
|
4105
|
-
|
|
4106
|
-
|
|
4107
|
-
|
|
4108
|
-
|
|
4109
|
-
|
|
4110
|
-
|
|
4605
|
+
let focused;
|
|
4606
|
+
let off;
|
|
4607
|
+
try {
|
|
4608
|
+
off = await (t?.el ?? (focused = 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);
|
|
4609
|
+
const ref = await refAround(s.page, off, now);
|
|
4610
|
+
const g = ref ? guard(now.root, ref) : void 0;
|
|
4611
|
+
const node = g?.node ?? (ref ? nodeOf(now, ref) : void 0);
|
|
4612
|
+
const asks = g?.asks ?? (off === t?.el ? t?.asks : void 0);
|
|
4613
|
+
confirmFirst({
|
|
4614
|
+
el: off,
|
|
4615
|
+
...ref ? { ref } : {},
|
|
4616
|
+
...node ? { node } : {},
|
|
4617
|
+
...asks ? { asks } : {},
|
|
4618
|
+
name: node ? line(node, now.url) : t?.name ?? "the focused element"
|
|
4619
|
+
}, a);
|
|
4620
|
+
if (t) {
|
|
4621
|
+
await act(s, t, `press ${key} on`, now, () => t.el.press(key, { timeout: STEP_MS }));
|
|
4622
|
+
return await after(s, `pressed ${key} on ${t.name}`);
|
|
4623
|
+
}
|
|
4624
|
+
await s.page.keyboard.press(key);
|
|
4625
|
+
return await after(s, `pressed ${key}`);
|
|
4626
|
+
} finally {
|
|
4627
|
+
await off?.dispose().catch(() => {});
|
|
4628
|
+
await focused?.dispose().catch(() => {});
|
|
4629
|
+
await t?.el.dispose().catch(() => {});
|
|
4111
4630
|
}
|
|
4112
|
-
await s.page.keyboard.press(key);
|
|
4113
|
-
return after(s, `pressed ${key}`);
|
|
4114
4631
|
},
|
|
4115
4632
|
async scroll(s, a) {
|
|
4116
4633
|
const up = a.flags.up === true;
|
|
4117
|
-
const
|
|
4634
|
+
const byFlag = flag(a, "by");
|
|
4635
|
+
let by;
|
|
4636
|
+
if (byFlag !== void 0) {
|
|
4637
|
+
by = Number(byFlag);
|
|
4638
|
+
if (!Number.isFinite(by) || by <= 0 || by > 1e5) throw new ToolError(`--by <px>: a positive number of pixels (up to 100000), got '${byFlag}'`);
|
|
4639
|
+
} else by = await s.page.evaluate("window.innerHeight * 0.8");
|
|
4118
4640
|
let moved = true;
|
|
4119
4641
|
const wheel = async (x, y) => {
|
|
4120
4642
|
await s.page.mouse.move(x, y);
|
|
@@ -4127,23 +4649,27 @@ const COMMANDS = {
|
|
|
4127
4649
|
if (a._[0] || flag(a, "text") !== void 0) {
|
|
4128
4650
|
const now = await readNow(s);
|
|
4129
4651
|
const t = await target(s, a, now);
|
|
4130
|
-
|
|
4131
|
-
|
|
4132
|
-
await
|
|
4133
|
-
|
|
4134
|
-
|
|
4135
|
-
|
|
4136
|
-
|
|
4137
|
-
|
|
4138
|
-
|
|
4139
|
-
|
|
4140
|
-
|
|
4141
|
-
|
|
4142
|
-
|
|
4143
|
-
|
|
4652
|
+
try {
|
|
4653
|
+
if (up || a.flags.down === true) {
|
|
4654
|
+
await act(s, t, "scroll in", now, async () => {
|
|
4655
|
+
await t.el.scrollIntoViewIfNeeded({ timeout: STEP_MS });
|
|
4656
|
+
const box = await t.el.boundingBox();
|
|
4657
|
+
if (!box) throw new UsageError(`${t.name} isn't shown, so there's nothing to scroll in`);
|
|
4658
|
+
const view = s.page.viewportSize() ?? {
|
|
4659
|
+
width: 1280,
|
|
4660
|
+
height: 900
|
|
4661
|
+
};
|
|
4662
|
+
const x = Math.max(0, Math.min(view.width - 1, box.x + box.width / 2));
|
|
4663
|
+
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));
|
|
4664
|
+
await wheel(x, y);
|
|
4665
|
+
});
|
|
4666
|
+
return await after(s, `scrolled ${t.name} ${up ? "up" : "down"}${still()}`);
|
|
4667
|
+
}
|
|
4668
|
+
await act(s, t, "scroll to", now, () => t.el.scrollIntoViewIfNeeded({ timeout: STEP_MS }));
|
|
4669
|
+
return await after(s, `scrolled to ${t.name}`);
|
|
4670
|
+
} finally {
|
|
4671
|
+
await t.el.dispose().catch(() => {});
|
|
4144
4672
|
}
|
|
4145
|
-
await act(s, t, "scroll to", now, () => t.el.scrollIntoViewIfNeeded({ timeout: STEP_MS }));
|
|
4146
|
-
return after(s, `scrolled to ${t.name}`);
|
|
4147
4673
|
}
|
|
4148
4674
|
const view = s.page.viewportSize() ?? {
|
|
4149
4675
|
width: 1280,
|
|
@@ -4154,19 +4680,27 @@ const COMMANDS = {
|
|
|
4154
4680
|
},
|
|
4155
4681
|
async inspect(s, a) {
|
|
4156
4682
|
const t = await target(s, a, await readNow(s));
|
|
4157
|
-
|
|
4158
|
-
|
|
4159
|
-
|
|
4160
|
-
|
|
4683
|
+
try {
|
|
4684
|
+
const up = Number(flag(a, "parent") ?? 0);
|
|
4685
|
+
if (!(Number.isInteger(up) && up >= 0)) throw new ToolError("--parent <n>: how many levels out from the element (1: what holds it)");
|
|
4686
|
+
const lines = await t.el.evaluate(inPage(["el", "up"], INSPECT), up);
|
|
4687
|
+
return [`${up ? `${up} level${up > 1 ? "s" : ""} out from ` : ""}${t.name}, in the page's markup:`, ...lines].join("\n");
|
|
4688
|
+
} finally {
|
|
4689
|
+
await t.el.dispose().catch(() => {});
|
|
4690
|
+
}
|
|
4161
4691
|
},
|
|
4162
4692
|
async upload(s, a) {
|
|
4163
4693
|
const now = await readNow(s);
|
|
4164
4694
|
const t = await target(s, a, now);
|
|
4165
|
-
|
|
4166
|
-
|
|
4167
|
-
|
|
4168
|
-
|
|
4169
|
-
|
|
4695
|
+
try {
|
|
4696
|
+
confirmFirst(t, a);
|
|
4697
|
+
const files = flag(a, "text") !== void 0 ? a._ : a._.slice(1);
|
|
4698
|
+
if (!files.length) throw new ToolError("agent-om upload <ref> <file…>");
|
|
4699
|
+
await act(s, t, "upload to", now, () => t.el.setInputFiles(files, { timeout: STEP_MS }));
|
|
4700
|
+
return await after(s, `chose ${files.length} file${files.length > 1 ? "s" : ""} for ${t.name}`);
|
|
4701
|
+
} finally {
|
|
4702
|
+
await t.el.dispose().catch(() => {});
|
|
4703
|
+
}
|
|
4170
4704
|
},
|
|
4171
4705
|
async "fill-secret"(s, a, env) {
|
|
4172
4706
|
const variable = flag(a, "text") !== void 0 ? a._[0] : a._[1];
|
|
@@ -4185,8 +4719,13 @@ const COMMANDS = {
|
|
|
4185
4719
|
if (value && !s.secrets.includes(value)) s.secrets.push(value);
|
|
4186
4720
|
const now = await readNow(s);
|
|
4187
4721
|
const t = await target(s, a, now);
|
|
4188
|
-
|
|
4189
|
-
|
|
4722
|
+
try {
|
|
4723
|
+
confirmFirst(t, a);
|
|
4724
|
+
await act(s, t, "fill", now, () => t.el.fill(value, { timeout: STEP_MS }));
|
|
4725
|
+
return await after(s, `filled ${t.name} from $${variable}`);
|
|
4726
|
+
} finally {
|
|
4727
|
+
await t.el.dispose().catch(() => {});
|
|
4728
|
+
}
|
|
4190
4729
|
},
|
|
4191
4730
|
async back(s) {
|
|
4192
4731
|
await s.page.goBack({ waitUntil: "domcontentloaded" });
|
|
@@ -4207,7 +4746,13 @@ const COMMANDS = {
|
|
|
4207
4746
|
}
|
|
4208
4747
|
return after(s, `${JSON.stringify(text)} shows`);
|
|
4209
4748
|
}
|
|
4210
|
-
const
|
|
4749
|
+
const raw = a._[0];
|
|
4750
|
+
let ms = 1e3;
|
|
4751
|
+
if (raw !== void 0) {
|
|
4752
|
+
const n = Number(raw);
|
|
4753
|
+
if (!Number.isFinite(n) || n < 0) throw new ToolError(`wait <ms>: a non-negative number of milliseconds (up to 30000), got '${raw}'`);
|
|
4754
|
+
ms = Math.min(n, 3e4);
|
|
4755
|
+
}
|
|
4211
4756
|
await s.page.waitForTimeout(ms);
|
|
4212
4757
|
return after(s, `waited ${ms} ms`);
|
|
4213
4758
|
},
|
|
@@ -4241,29 +4786,33 @@ const COMMANDS = {
|
|
|
4241
4786
|
const keptOut = async () => [...s.secrets, ...await s.page.evaluate(inPage([], KEPT_OUT)).catch(() => [])];
|
|
4242
4787
|
const ref = flag(a, "ref");
|
|
4243
4788
|
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
4789
|
try {
|
|
4255
|
-
|
|
4256
|
-
|
|
4257
|
-
|
|
4258
|
-
|
|
4790
|
+
if (ref !== void 0) {
|
|
4791
|
+
if (!/^e\d+$/.test(ref)) throw new ToolError(`'${ref}' isn't a ref: refs are written e12, as the view shows them`);
|
|
4792
|
+
const now = await readNow(s);
|
|
4793
|
+
const node = nodeOf(now, ref);
|
|
4794
|
+
const g = guard(now.root, ref);
|
|
4795
|
+
el = await elementOf(s.page, ref);
|
|
4796
|
+
if (!el) throw new ToolError(await goneRef(s, ref));
|
|
4797
|
+
if (!node || !g) throw new ToolError(noRef(ref));
|
|
4798
|
+
}
|
|
4799
|
+
let got;
|
|
4800
|
+
try {
|
|
4801
|
+
got = el ? await el.evaluate(inPage(["el"], `return ${evalScript(script)}`)) : await s.page.evaluate(evalScript(script));
|
|
4802
|
+
} catch (e) {
|
|
4803
|
+
const message = (e instanceof Error ? e.message : String(e)).replace(/^page\.evaluate: /, "").split("\n")[0] ?? "";
|
|
4804
|
+
throw new UsageError(withoutSecrets(`the script failed: ${message}`, await keptOut()));
|
|
4805
|
+
}
|
|
4806
|
+
const kept = await keptOut();
|
|
4807
|
+
const clean = withoutSecrets(String(got.said), kept);
|
|
4808
|
+
s.evaluated = {
|
|
4809
|
+
kind: got.kind,
|
|
4810
|
+
said: clean
|
|
4811
|
+
};
|
|
4812
|
+
return await after(s, `ran the script; it returned: ${clean.length > EVAL_MAX ? `${clean.slice(0, EVAL_MAX)}… (${clean.length - EVAL_MAX} more characters cut: return less)` : clean}`);
|
|
4813
|
+
} finally {
|
|
4814
|
+
await el?.dispose().catch(() => {});
|
|
4259
4815
|
}
|
|
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
4816
|
},
|
|
4268
4817
|
async "save-state"(s, a) {
|
|
4269
4818
|
const file = a._[0];
|
|
@@ -4348,7 +4897,7 @@ function optionsOf(command) {
|
|
|
4348
4897
|
};
|
|
4349
4898
|
for (const g of command.args) add(g.cli);
|
|
4350
4899
|
if (command.group === "act") for (const name of ON_ACTIONS) names.add(name);
|
|
4351
|
-
if (command.
|
|
4900
|
+
if (command.locates) for (const g of LOCATOR_ARGS) add(g.cli);
|
|
4352
4901
|
if (command.name === "snapshot") names.add("scope");
|
|
4353
4902
|
return names;
|
|
4354
4903
|
}
|
|
@@ -4395,12 +4944,33 @@ async function runCommand(s, name, a, env) {
|
|
|
4395
4944
|
*/
|
|
4396
4945
|
async function keepTo(s, context, origins) {
|
|
4397
4946
|
s.allowed = origins;
|
|
4398
|
-
const elsewhere = (url) => /^https?:$/.test(url.protocol) && !origins.includes(url.origin);
|
|
4947
|
+
const elsewhere = (url) => /^https?:$/.test(url.protocol) && !origins.includes(url.origin) || url.protocol === "data:";
|
|
4399
4948
|
await context.route(elsewhere, async (route) => {
|
|
4400
4949
|
const r = route.request();
|
|
4401
|
-
if (r.isNavigationRequest()
|
|
4402
|
-
|
|
4403
|
-
|
|
4950
|
+
if (r.isNavigationRequest()) {
|
|
4951
|
+
let frame;
|
|
4952
|
+
try {
|
|
4953
|
+
frame = r.frame();
|
|
4954
|
+
} catch {
|
|
4955
|
+
frame = void 0;
|
|
4956
|
+
}
|
|
4957
|
+
if (!frame || frame.parentFrame() === null) {
|
|
4958
|
+
let ours = !s.attached;
|
|
4959
|
+
if (!ours && frame) {
|
|
4960
|
+
const page = frame.page();
|
|
4961
|
+
ours = s.tabs.some((t) => t.page === page);
|
|
4962
|
+
if (!ours) {
|
|
4963
|
+
const pending = s.pendingTabs.get(page);
|
|
4964
|
+
if (pending) ours = await pending.catch(() => false);
|
|
4965
|
+
}
|
|
4966
|
+
}
|
|
4967
|
+
if (ours) {
|
|
4968
|
+
const u = new URL(r.url());
|
|
4969
|
+
const label = u.protocol === "data:" ? "data: URL" : u.origin;
|
|
4970
|
+
s.beside.push(`the page tried to go to ${label}, which isn't one of the sites this session may open: stopped`);
|
|
4971
|
+
return route.fulfill({ status: 204 });
|
|
4972
|
+
}
|
|
4973
|
+
}
|
|
4404
4974
|
}
|
|
4405
4975
|
return route.continue();
|
|
4406
4976
|
});
|
|
@@ -4410,11 +4980,23 @@ const OPENING_MS = 15e3;
|
|
|
4410
4980
|
/** 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
4981
|
async function tabsOpened(s) {
|
|
4412
4982
|
const until = Date.now() + OPENING_MS;
|
|
4413
|
-
while (s.opening.size && Date.now() < until)
|
|
4983
|
+
while (s.opening.size && Date.now() < until) {
|
|
4984
|
+
const all = Promise.all([...s.opening]);
|
|
4985
|
+
let timer;
|
|
4986
|
+
if (await Promise.race([all.then(() => false), new Promise((r) => {
|
|
4987
|
+
timer = setTimeout(() => r(true), Math.max(0, until - Date.now()));
|
|
4988
|
+
})]).finally(() => clearTimeout(timer))) {
|
|
4989
|
+
all.catch(() => {});
|
|
4990
|
+
break;
|
|
4991
|
+
}
|
|
4992
|
+
}
|
|
4414
4993
|
}
|
|
4415
4994
|
/** Whether a page still answers: one running a script that never ends doesn't. */
|
|
4416
4995
|
async function answers(page, ms = 2e3) {
|
|
4417
|
-
|
|
4996
|
+
let timer;
|
|
4997
|
+
return Promise.race([page.evaluate("1").then(() => true, () => true), new Promise((r) => {
|
|
4998
|
+
timer = setTimeout(() => r(false), ms);
|
|
4999
|
+
})]).finally(() => clearTimeout(timer));
|
|
4418
5000
|
}
|
|
4419
5001
|
/**
|
|
4420
5002
|
* A tab whose page stopped answering (a script that never ends) can't be read or acted on, and a command on it
|
|
@@ -4424,9 +5006,10 @@ async function answers(page, ms = 2e3) {
|
|
|
4424
5006
|
async function replaceStuck(s) {
|
|
4425
5007
|
const stuck = s.page;
|
|
4426
5008
|
const tab = tabOf(s, stuck);
|
|
4427
|
-
const url = stuck.url();
|
|
5009
|
+
const url = said(s, stuck.url());
|
|
4428
5010
|
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
5011
|
const fresh = await stuck.context().newPage();
|
|
5012
|
+
await watch(fresh).catch(() => {});
|
|
4430
5013
|
await tabsOpened(s);
|
|
4431
5014
|
const t = tabOf(s, fresh) ?? adopt(s, fresh, void 0, true);
|
|
4432
5015
|
t.own = true;
|
|
@@ -4455,7 +5038,13 @@ function adopt(s, page, opener, own) {
|
|
|
4455
5038
|
};
|
|
4456
5039
|
s.tabs.push(tab);
|
|
4457
5040
|
answerDialogs(s, page);
|
|
4458
|
-
listen(tab);
|
|
5041
|
+
listen(s, tab);
|
|
5042
|
+
page.on("framenavigated", (frame) => {
|
|
5043
|
+
if (s.allowed && frame === page.mainFrame() && frame.url().startsWith("data:")) {
|
|
5044
|
+
s.beside.push(`the page tried to go to data: URL, which isn't one of the sites this session may open: stopped`);
|
|
5045
|
+
page.goBack({ waitUntil: "domcontentloaded" }).catch(() => page.goto("about:blank").catch(() => {}));
|
|
5046
|
+
}
|
|
5047
|
+
});
|
|
4459
5048
|
page.on("download", (d) => saveDownload(s, d));
|
|
4460
5049
|
page.on("close", () => {
|
|
4461
5050
|
s.tabs = s.tabs.filter((t) => t !== tab);
|
|
@@ -4478,26 +5067,47 @@ function session(page, options = {}) {
|
|
|
4478
5067
|
tabs: [],
|
|
4479
5068
|
count: 0,
|
|
4480
5069
|
opening: /* @__PURE__ */ new Set(),
|
|
5070
|
+
pendingTabs: /* @__PURE__ */ new Map(),
|
|
4481
5071
|
fresh: [],
|
|
4482
|
-
downloads: options.downloads ?? join(
|
|
5072
|
+
downloads: options.downloads ?? join(sessionsHome(), "downloads"),
|
|
4483
5073
|
...options.attached ? { attached: true } : {},
|
|
4484
5074
|
...options.allowEval ? { allowEval: true } : {},
|
|
4485
5075
|
...options.allowScreenshot ? { allowScreenshot: true } : {},
|
|
4486
5076
|
saving: /* @__PURE__ */ new Set()
|
|
4487
5077
|
};
|
|
4488
5078
|
adopt(s, page, void 0, options.first ?? true);
|
|
4489
|
-
for (const other of options.others ?? [])
|
|
5079
|
+
for (const other of options.others ?? []) {
|
|
5080
|
+
adopt(s, other, void 0, false);
|
|
5081
|
+
watch(other).catch(() => {});
|
|
5082
|
+
}
|
|
4490
5083
|
page.context().on("page", (tab) => {
|
|
4491
5084
|
if (tabOf(s, tab)) return;
|
|
4492
5085
|
const by = s.page;
|
|
5086
|
+
let resolveOurs;
|
|
5087
|
+
const pending = new Promise((r) => {
|
|
5088
|
+
resolveOurs = r;
|
|
5089
|
+
});
|
|
5090
|
+
s.pendingTabs.set(tab, pending);
|
|
4493
5091
|
const ready = (async () => {
|
|
4494
|
-
|
|
4495
|
-
|
|
4496
|
-
|
|
4497
|
-
|
|
4498
|
-
|
|
4499
|
-
|
|
4500
|
-
|
|
5092
|
+
try {
|
|
5093
|
+
const opener = await tab.opener().catch(() => null);
|
|
5094
|
+
const ours = !!opener && !!tabOf(s, opener);
|
|
5095
|
+
if (!ours && options.follow === "opened") {
|
|
5096
|
+
resolveOurs(false);
|
|
5097
|
+
return;
|
|
5098
|
+
}
|
|
5099
|
+
const t = adopt(s, tab, ours ? opener : by, ours);
|
|
5100
|
+
resolveOurs(true);
|
|
5101
|
+
await tab.waitForLoadState("domcontentloaded", { timeout: 1e4 }).catch(() => {});
|
|
5102
|
+
let timer;
|
|
5103
|
+
await Promise.race([watch(tab).catch(() => {}), new Promise((r) => {
|
|
5104
|
+
timer = setTimeout(r, 3e3);
|
|
5105
|
+
})]).finally(() => clearTimeout(timer));
|
|
5106
|
+
if (!tab.isClosed()) s.fresh.push(t);
|
|
5107
|
+
} finally {
|
|
5108
|
+
resolveOurs(false);
|
|
5109
|
+
s.pendingTabs.delete(tab);
|
|
5110
|
+
}
|
|
4501
5111
|
})();
|
|
4502
5112
|
s.opening.add(ready);
|
|
4503
5113
|
ready.finally(() => s.opening.delete(ready));
|
|
@@ -4507,7 +5117,7 @@ function session(page, options = {}) {
|
|
|
4507
5117
|
/** 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
5118
|
function answerDialogs(s, page) {
|
|
4509
5119
|
page.on("dialog", (d) => {
|
|
4510
|
-
const message = JSON.stringify(squash(d.message()).slice(0, 300));
|
|
5120
|
+
const message = JSON.stringify(squash(said(s, d.message())).slice(0, 300));
|
|
4511
5121
|
if (d.type() === "beforeunload" || d.type() === "alert") {
|
|
4512
5122
|
s.beside.push(d.type() === "alert" ? `the browser showed an alert: ${message} (closed)` : "the page asked to confirm leaving it: left");
|
|
4513
5123
|
d.accept().catch(() => {});
|
|
@@ -4524,6 +5134,13 @@ function answerDialogs(s, page) {
|
|
|
4524
5134
|
const IDLE_MS = Number(process.env.AGENT_OM_IDLE_MS) || 72e5;
|
|
4525
5135
|
/** 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
5136
|
const COMMAND_MS = Number(process.env.AGENT_OM_COMMAND_MS) || 12e4;
|
|
5137
|
+
/** Maximum accepted JSON request body size (2 MB). */
|
|
5138
|
+
const MAX_BODY_BYTES = 2097152;
|
|
5139
|
+
function validToken(got, expected) {
|
|
5140
|
+
if (typeof got !== "string") return false;
|
|
5141
|
+
const buf = Buffer.from(got, "utf8");
|
|
5142
|
+
return buf.length === expected.length && timingSafeEqual(buf, expected);
|
|
5143
|
+
}
|
|
4527
5144
|
/** The commands whose answer holds none of the page's text: an address, a file written. */
|
|
4528
5145
|
const PLAIN = /* @__PURE__ */ new Set([
|
|
4529
5146
|
"url",
|
|
@@ -4544,26 +5161,31 @@ async function open(o) {
|
|
|
4544
5161
|
}
|
|
4545
5162
|
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
5163
|
process.stderr.write("attached\n");
|
|
4547
|
-
|
|
4548
|
-
|
|
4549
|
-
|
|
4550
|
-
|
|
4551
|
-
|
|
4552
|
-
|
|
4553
|
-
|
|
4554
|
-
|
|
4555
|
-
|
|
4556
|
-
|
|
4557
|
-
|
|
4558
|
-
|
|
4559
|
-
|
|
4560
|
-
|
|
4561
|
-
|
|
4562
|
-
|
|
4563
|
-
|
|
4564
|
-
|
|
4565
|
-
|
|
4566
|
-
|
|
5164
|
+
try {
|
|
5165
|
+
const context = browser.contexts()[0];
|
|
5166
|
+
if (!context) throw new Error("the browser has no window to work in");
|
|
5167
|
+
const level = o.tabs ?? "own";
|
|
5168
|
+
const theirs = context.pages();
|
|
5169
|
+
let page;
|
|
5170
|
+
if (level === "active") {
|
|
5171
|
+
const showing = [];
|
|
5172
|
+
for (const p of theirs) if (await p.evaluate("document.visibilityState").catch(() => "") === "visible") showing.push(p);
|
|
5173
|
+
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`);
|
|
5174
|
+
page = showing[0];
|
|
5175
|
+
} else page = await context.newPage();
|
|
5176
|
+
return {
|
|
5177
|
+
browser,
|
|
5178
|
+
context,
|
|
5179
|
+
page,
|
|
5180
|
+
attached: true,
|
|
5181
|
+
first: level !== "active",
|
|
5182
|
+
level,
|
|
5183
|
+
others: level === "all" ? theirs.filter((p) => p !== page) : []
|
|
5184
|
+
};
|
|
5185
|
+
} catch (e) {
|
|
5186
|
+
await browser.close().catch(() => {});
|
|
5187
|
+
throw e;
|
|
5188
|
+
}
|
|
4567
5189
|
}
|
|
4568
5190
|
const launch = {
|
|
4569
5191
|
headless: !o.headed,
|
|
@@ -4594,6 +5216,7 @@ async function serve(o) {
|
|
|
4594
5216
|
});
|
|
4595
5217
|
const { browser, context, page, attached, first, level, others } = await open(o);
|
|
4596
5218
|
await watch(page);
|
|
5219
|
+
for (const other of others) await watch(other).catch(() => {});
|
|
4597
5220
|
const s = session(page, {
|
|
4598
5221
|
downloads: join(sessionDir(o.name), "downloads"),
|
|
4599
5222
|
follow: level && level !== "all" ? "opened" : "any",
|
|
@@ -4606,9 +5229,17 @@ async function serve(o) {
|
|
|
4606
5229
|
if (o.allowedOrigins?.length) await keepTo(s, context, o.allowedOrigins);
|
|
4607
5230
|
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
5231
|
const token = randomBytes(24).toString("hex");
|
|
5232
|
+
const tokenBuf = Buffer.from(token, "utf8");
|
|
4609
5233
|
const nonce = randomBytes(16).toString("hex");
|
|
4610
5234
|
let queue = Promise.resolve();
|
|
5235
|
+
let server;
|
|
5236
|
+
let expectedHost = "";
|
|
5237
|
+
let ending = false;
|
|
4611
5238
|
const end = async () => {
|
|
5239
|
+
if (ending) return;
|
|
5240
|
+
ending = true;
|
|
5241
|
+
clearTimeout(idle);
|
|
5242
|
+
server?.close();
|
|
4612
5243
|
if (readSession(o.name)?.pid === process.pid) rmSync(sessionFile(o.name), { force: true });
|
|
4613
5244
|
await s.sandbox?.close();
|
|
4614
5245
|
if (attached) {
|
|
@@ -4622,19 +5253,48 @@ async function serve(o) {
|
|
|
4622
5253
|
};
|
|
4623
5254
|
context.on("close", () => void end());
|
|
4624
5255
|
browser?.on("disconnected", () => void end());
|
|
5256
|
+
process.once("SIGINT", () => void end());
|
|
5257
|
+
process.once("SIGTERM", () => void end());
|
|
4625
5258
|
let idle = setTimeout(() => void end(), IDLE_MS);
|
|
4626
5259
|
const used = () => {
|
|
4627
5260
|
clearTimeout(idle);
|
|
4628
5261
|
idle = setTimeout(() => void queue.finally(end), IDLE_MS);
|
|
4629
5262
|
};
|
|
4630
|
-
|
|
4631
|
-
|
|
4632
|
-
|
|
5263
|
+
server = http.createServer((req, res) => {
|
|
5264
|
+
const reply = (r, status = 200) => {
|
|
5265
|
+
if (res.writableEnded) return;
|
|
5266
|
+
res.writeHead(status, { "content-type": "application/json" });
|
|
5267
|
+
res.end(JSON.stringify(r));
|
|
5268
|
+
};
|
|
5269
|
+
if (req.method !== "POST") return reply({
|
|
5270
|
+
ok: false,
|
|
5271
|
+
error: "method not allowed"
|
|
5272
|
+
}, 405);
|
|
5273
|
+
if (expectedHost && req.headers.host !== expectedHost) return reply({
|
|
5274
|
+
ok: false,
|
|
5275
|
+
error: "forbidden host"
|
|
5276
|
+
}, 403);
|
|
5277
|
+
const chunks = [];
|
|
5278
|
+
let total = 0;
|
|
5279
|
+
let tooLarge = false;
|
|
5280
|
+
req.on("data", (c) => {
|
|
5281
|
+
if (tooLarge) return;
|
|
5282
|
+
const buf = typeof c === "string" ? Buffer.from(c, "utf8") : c;
|
|
5283
|
+
total += buf.length;
|
|
5284
|
+
if (total > MAX_BODY_BYTES) {
|
|
5285
|
+
tooLarge = true;
|
|
5286
|
+
reply({
|
|
5287
|
+
ok: false,
|
|
5288
|
+
error: "request too large"
|
|
5289
|
+
}, 413);
|
|
5290
|
+
req.resume();
|
|
5291
|
+
return;
|
|
5292
|
+
}
|
|
5293
|
+
chunks.push(buf);
|
|
5294
|
+
});
|
|
4633
5295
|
req.on("end", () => {
|
|
4634
|
-
|
|
4635
|
-
|
|
4636
|
-
res.end(JSON.stringify(r));
|
|
4637
|
-
};
|
|
5296
|
+
if (tooLarge) return;
|
|
5297
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
4638
5298
|
let request;
|
|
4639
5299
|
try {
|
|
4640
5300
|
request = JSON.parse(raw);
|
|
@@ -4644,7 +5304,7 @@ async function serve(o) {
|
|
|
4644
5304
|
error: "not JSON"
|
|
4645
5305
|
}, 400);
|
|
4646
5306
|
}
|
|
4647
|
-
if (request.token
|
|
5307
|
+
if (!validToken(request.token, tokenBuf)) return reply({
|
|
4648
5308
|
ok: false,
|
|
4649
5309
|
error: "wrong token"
|
|
4650
5310
|
}, 403);
|
|
@@ -4664,11 +5324,17 @@ async function serve(o) {
|
|
|
4664
5324
|
};
|
|
4665
5325
|
try {
|
|
4666
5326
|
const late = Symbol("late");
|
|
4667
|
-
|
|
5327
|
+
let timer;
|
|
5328
|
+
const cmdPromise = runCommand(s, request.cmd, request.args, request.env ?? {});
|
|
5329
|
+
const out = await Promise.race([cmdPromise, new Promise((r) => {
|
|
5330
|
+
timer = setTimeout(() => r(late), COMMAND_MS);
|
|
5331
|
+
})]).finally(() => clearTimeout(timer));
|
|
4668
5332
|
if (out === late) {
|
|
5333
|
+
cmdPromise.catch(() => {});
|
|
5334
|
+
const stuckOrigin = originOf(s.page.url());
|
|
4669
5335
|
if (!await answers(s.page)) return {
|
|
4670
5336
|
ok: false,
|
|
4671
|
-
error: await replaceStuck(s)
|
|
5337
|
+
error: pageContent(await replaceStuck(s), stuckOrigin, nonce)
|
|
4672
5338
|
};
|
|
4673
5339
|
return {
|
|
4674
5340
|
ok: false,
|
|
@@ -4701,6 +5367,7 @@ async function serve(o) {
|
|
|
4701
5367
|
});
|
|
4702
5368
|
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
4703
5369
|
const port = server.address().port;
|
|
5370
|
+
expectedHost = `127.0.0.1:${port}`;
|
|
4704
5371
|
const other = await claim(o.name, {
|
|
4705
5372
|
port,
|
|
4706
5373
|
token,
|
|
@@ -4716,14 +5383,19 @@ async function serve(o) {
|
|
|
4716
5383
|
async function claim(name, mine) {
|
|
4717
5384
|
const file = sessionFile(name);
|
|
4718
5385
|
const text = JSON.stringify(mine);
|
|
4719
|
-
|
|
4720
|
-
|
|
4721
|
-
|
|
4722
|
-
|
|
4723
|
-
|
|
4724
|
-
|
|
4725
|
-
|
|
4726
|
-
|
|
5386
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
5387
|
+
try {
|
|
5388
|
+
writeFileSync(file, text, {
|
|
5389
|
+
mode: 384,
|
|
5390
|
+
flag: "wx"
|
|
5391
|
+
});
|
|
5392
|
+
return;
|
|
5393
|
+
} catch (e) {
|
|
5394
|
+
if (e.code !== "EEXIST") throw e;
|
|
5395
|
+
}
|
|
5396
|
+
const other = readSession(name);
|
|
5397
|
+
if (other && other.pid !== process.pid && await alive(other)) return other;
|
|
5398
|
+
rmSync(file, { force: true });
|
|
4727
5399
|
}
|
|
4728
5400
|
const other = readSession(name);
|
|
4729
5401
|
if (other && other.pid !== process.pid && await alive(other)) return other;
|