@cydm/pie 4.6.1 → 4.8.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.
@@ -15,12 +15,14 @@ import {
15
15
  readSelfStartTime,
16
16
  rememberToolRouting,
17
17
  resolveBridgeScript,
18
+ resolveSessionLogFile,
18
19
  resolveSessionName,
19
20
  resolveSessionPidFile,
20
21
  resolveSessionPort,
22
+ resolveSessionStartLockFile,
21
23
  resolveSessionStateDir,
22
24
  setSelectedPageId
23
- } from "./chunk-WOGAQ4P5.js";
25
+ } from "./chunk-Z2A5LA5A.js";
24
26
  import "./chunk-OJ6N23UZ.js";
25
27
 
26
28
  // ../../node_modules/chrome-devtools-axi/node_modules/@toon-format/toon/dist/index.mjs
@@ -1618,13 +1620,236 @@ function installSessionStartHooks(options = {}) {
1618
1620
 
1619
1621
  // vendor/chrome-devtools-axi/src/client.ts
1620
1622
  import { execFileSync, spawn as spawn2 } from "node:child_process";
1621
- import { readFileSync as readFileSync3, existsSync as existsSync3, unlinkSync } from "node:fs";
1623
+ import { randomUUID } from "node:crypto";
1624
+ import {
1625
+ closeSync,
1626
+ existsSync as existsSync4,
1627
+ mkdirSync as mkdirSync3,
1628
+ openSync,
1629
+ readFileSync as readFileSync4,
1630
+ statSync as statSync2,
1631
+ unlinkSync as unlinkSync2,
1632
+ writeFileSync as writeFileSync3
1633
+ } from "node:fs";
1622
1634
  import { request } from "node:http";
1623
- import { dirname as dirname3 } from "node:path";
1635
+ import { dirname as dirname4 } from "node:path";
1636
+
1637
+ // vendor/chrome-devtools-axi/src/generation.ts
1638
+ import {
1639
+ existsSync as existsSync3,
1640
+ mkdirSync as mkdirSync2,
1641
+ readFileSync as readFileSync3,
1642
+ unlinkSync,
1643
+ writeFileSync as writeFileSync2
1644
+ } from "node:fs";
1645
+ import { dirname as dirname3, join as join3 } from "node:path";
1646
+ function genFile() {
1647
+ return join3(resolveSessionStateDir(), "snapshot-generation");
1648
+ }
1649
+ function getCurrentGeneration() {
1650
+ const file = genFile();
1651
+ try {
1652
+ if (!existsSync3(file)) return 0;
1653
+ const parsed = Number.parseInt(readFileSync3(file, "utf-8").trim(), 10);
1654
+ return Number.isNaN(parsed) ? 0 : parsed;
1655
+ } catch {
1656
+ return 0;
1657
+ }
1658
+ }
1659
+ function bumpGeneration() {
1660
+ const next = getCurrentGeneration() + 1;
1661
+ const file = genFile();
1662
+ try {
1663
+ mkdirSync2(dirname3(file), { recursive: true });
1664
+ writeFileSync2(file, String(next));
1665
+ } catch {
1666
+ }
1667
+ return next;
1668
+ }
1669
+
1670
+ // vendor/chrome-devtools-axi/src/snapshot.ts
1671
+ function countRefs(snapshot) {
1672
+ const matches = snapshot.match(/\buid=\S+/g);
1673
+ return matches ? matches.length : 0;
1674
+ }
1675
+ function extractRefs(snapshot) {
1676
+ const refs = [];
1677
+ for (const line of snapshot.split("\n")) {
1678
+ const m = line.match(/\buid=(\S+)\s+(\w+)\s+"([^"]*)"/);
1679
+ if (!m) continue;
1680
+ refs.push({ ref: m[1], type: m[2], label: m[3] });
1681
+ }
1682
+ return refs;
1683
+ }
1684
+ function parseStampedUid(arg) {
1685
+ const stripped = arg.startsWith("@") ? arg.slice(1) : arg;
1686
+ const m = stripped.match(/^g(\d+):(.+)$/);
1687
+ if (m) return { uid: m[2], generation: Number.parseInt(m[1], 10) };
1688
+ return { uid: stripped, generation: null };
1689
+ }
1690
+ function stampSnapshotGeneration(snapshot, generation) {
1691
+ return snapshot.replace(/\buid=(\S+)/g, (match, uid) => {
1692
+ if (/^g\d+:/.test(uid)) return match;
1693
+ return `uid=g${generation}:${uid}`;
1694
+ });
1695
+ }
1696
+ function checkUidGeneration(arg, currentGeneration) {
1697
+ const { uid, generation } = parseStampedUid(arg);
1698
+ return {
1699
+ uid,
1700
+ stale: generation !== null && generation !== currentGeneration,
1701
+ refGeneration: generation
1702
+ };
1703
+ }
1704
+ function extractTitle(snapshot) {
1705
+ const rootMatch = snapshot.match(/RootWebArea\s+"([^"]+)"/);
1706
+ if (rootMatch) return rootMatch[1];
1707
+ const headingMatch = snapshot.match(/\bheading\s+"([^"]+)"/);
1708
+ if (headingMatch) return headingMatch[1];
1709
+ return "";
1710
+ }
1711
+ function truncateSnapshot(snapshot, full, limit = 16e3) {
1712
+ const totalLength = snapshot.length;
1713
+ if (full || totalLength <= limit) {
1714
+ return { text: snapshot, truncated: false, totalLength };
1715
+ }
1716
+ const cut = snapshot.lastIndexOf("\n", limit);
1717
+ const text = cut > 0 ? snapshot.slice(0, cut) : snapshot.slice(0, limit);
1718
+ return { text, truncated: true, totalLength };
1719
+ }
1720
+ var MARKER_OVERHEAD = 50;
1721
+ function truncateText(text, limit = 8e3) {
1722
+ const totalLength = text.length;
1723
+ if (totalLength <= limit) {
1724
+ return { text, truncated: false, totalLength };
1725
+ }
1726
+ if (totalLength <= limit + MARKER_OVERHEAD) {
1727
+ return { text, truncated: false, totalLength };
1728
+ }
1729
+ const headBudget = Math.floor(limit * 0.4);
1730
+ const tailBudget = limit - headBudget;
1731
+ const headCut = text.lastIndexOf("\n", headBudget);
1732
+ const head = headCut > 0 ? text.slice(0, headCut) : text.slice(0, headBudget);
1733
+ const tailStart = text.indexOf("\n", totalLength - tailBudget);
1734
+ const tail = tailStart > 0 && tailStart < totalLength ? text.slice(tailStart + 1) : text.slice(totalLength - tailBudget);
1735
+ const omitted = totalLength - head.length - tail.length;
1736
+ const result = `${head}
1737
+
1738
+ ... (${omitted} chars omitted, ${totalLength} total) ...
1739
+
1740
+ ${tail}`;
1741
+ return { text: result, truncated: true, totalLength };
1742
+ }
1743
+ var INPUT_TYPES = ["textbox", "searchbox", "input", "combobox", "textarea"];
1744
+ function isInputType(type) {
1745
+ return INPUT_TYPES.includes(type);
1746
+ }
1747
+
1748
+ // vendor/chrome-devtools-axi/src/uid-freshness.ts
1749
+ var PAGE_GENERATION_KEY = "__chromeDevtoolsAxiSnapshotGeneration";
1750
+ async function captureFreshSnapshot(caller, capture) {
1751
+ const first = await captureSnapshot(caller, capture);
1752
+ const fresh = first.state?.generation === first.generation && first.state.mutations > 0 ? await captureSnapshot(caller, capture) : first;
1753
+ return stampSnapshotGeneration(fresh.snapshot, fresh.generation);
1754
+ }
1755
+ function throwStaleRef(arg, refGeneration, currentGeneration) {
1756
+ const refRaw = arg.startsWith("@") ? arg.slice(1) : arg;
1757
+ const current = currentGeneration ?? "unavailable";
1758
+ throw new CdpError(
1759
+ `Stale ref @${refRaw}: from snapshot generation ${refGeneration}, current is ${current}. Re-snapshot to get fresh refs.`,
1760
+ "STALE_REF",
1761
+ [
1762
+ "Run `chrome-devtools-axi snapshot` to capture current refs, then retry the action"
1763
+ ]
1764
+ );
1765
+ }
1766
+ async function markPageSnapshotGeneration(generation, caller) {
1767
+ const key = JSON.stringify(PAGE_GENERATION_KEY);
1768
+ try {
1769
+ await caller("evaluate_script", {
1770
+ function: `() => {
1771
+ const key = ${key};
1772
+ const previous = globalThis[key];
1773
+ if (previous && previous.observer) previous.observer.disconnect();
1774
+ const state = { generation: ${generation}, mutations: 0, observer: null };
1775
+ const observer = new MutationObserver(() => { state.mutations += 1; });
1776
+ observer.observe(document.documentElement || document, { childList: true, subtree: true, attributes: true, characterData: true });
1777
+ state.observer = observer;
1778
+ globalThis[key] = state;
1779
+ return state.generation;
1780
+ }`
1781
+ });
1782
+ } catch {
1783
+ }
1784
+ }
1785
+ async function captureSnapshot(caller, capture) {
1786
+ const generation = bumpGeneration();
1787
+ await markPageSnapshotGeneration(generation, caller);
1788
+ const snapshot = await capture();
1789
+ return { generation, snapshot, state: await getPageRefState(caller) };
1790
+ }
1791
+ async function getPageRefState(caller) {
1792
+ const key = JSON.stringify(PAGE_GENERATION_KEY);
1793
+ try {
1794
+ const output = await caller("evaluate_script", {
1795
+ function: `() => {
1796
+ const state = globalThis[${key}];
1797
+ if (!state || typeof state.generation !== 'number' || typeof state.mutations !== 'number' || !state.observer) return null;
1798
+ return { generation: state.generation, mutations: state.mutations };
1799
+ }`
1800
+ });
1801
+ const jsonBlock = output.match(/```json\n([\s\S]*?)\n```/);
1802
+ const raw = jsonBlock?.[1] ?? output.replace(/^Script ran on page and returned:\s*/, "");
1803
+ const parsed = JSON.parse(raw.trim());
1804
+ if (typeof parsed !== "object" || parsed === null || typeof parsed.generation !== "number" || typeof parsed.mutations !== "number") {
1805
+ return null;
1806
+ }
1807
+ return parsed;
1808
+ } catch {
1809
+ return null;
1810
+ }
1811
+ }
1812
+ var CLEANUP_OBSERVER_SCRIPT = `() => {
1813
+ const key = ${JSON.stringify(PAGE_GENERATION_KEY)};
1814
+ const previous = globalThis[key];
1815
+ if (previous && previous.observer) {
1816
+ try { previous.observer.disconnect(); } catch {}
1817
+ }
1818
+ try { delete globalThis[key]; } catch { globalThis[key] = undefined; }
1819
+ return true;
1820
+ }`;
1821
+ async function parseUidFresh(arg, caller) {
1822
+ const snapshotGeneration = getCurrentGeneration();
1823
+ const check = checkUidGeneration(arg, snapshotGeneration);
1824
+ if (check.stale) {
1825
+ throwStaleRef(arg, check.refGeneration, snapshotGeneration);
1826
+ }
1827
+ const state = await getPageRefState(caller);
1828
+ if (!state || state.generation !== snapshotGeneration || state.mutations !== 0) {
1829
+ throwStaleRef(
1830
+ arg,
1831
+ parseStampedUid(arg).generation ?? snapshotGeneration,
1832
+ state ? state.generation + state.mutations : null
1833
+ );
1834
+ }
1835
+ return check.uid;
1836
+ }
1837
+
1838
+ // vendor/chrome-devtools-axi/src/client.ts
1624
1839
  var DEFAULT_BRIDGE_TIMEOUT_MS = 3e4;
1840
+ var DEFAULT_APPROVAL_TIMEOUT_MS = 65e3;
1625
1841
  var MIN_BRIDGE_TIMEOUT_MS = 1e3;
1626
1842
  var HEALTH_TIMEOUT_MS = 2e3;
1627
1843
  var DEEP_HEALTH_TIMEOUT_MS = 5e3;
1844
+ var MAX_BRIDGE_LOG_BYTES = 1048576;
1845
+ var START_LOCK_STALE_MS = 15e3;
1846
+ function resolveApprovalTimeoutMs() {
1847
+ const raw = process.env.CHROME_DEVTOOLS_AXI_APPROVAL_TIMEOUT_MS;
1848
+ if (!raw) return DEFAULT_APPROVAL_TIMEOUT_MS;
1849
+ const parsed = Number.parseInt(raw, 10);
1850
+ if (Number.isNaN(parsed) || parsed <= 0) return DEFAULT_APPROVAL_TIMEOUT_MS;
1851
+ return Math.max(parsed, MIN_BRIDGE_TIMEOUT_MS);
1852
+ }
1628
1853
  function resolveBridgeTimeoutMs() {
1629
1854
  const raw = process.env.CHROME_DEVTOOLS_AXI_BRIDGE_TIMEOUT_MS;
1630
1855
  if (!raw) return DEFAULT_BRIDGE_TIMEOUT_MS;
@@ -1644,8 +1869,8 @@ var CdpError = class extends AxiError {
1644
1869
  };
1645
1870
  function readPidFile(pidFile = resolveSessionPidFile()) {
1646
1871
  try {
1647
- if (!existsSync3(pidFile)) return null;
1648
- const data = JSON.parse(readFileSync3(pidFile, "utf-8"));
1872
+ if (!existsSync4(pidFile)) return null;
1873
+ const data = JSON.parse(readFileSync4(pidFile, "utf-8"));
1649
1874
  if (typeof data.pid === "number" && typeof data.port === "number") {
1650
1875
  return data;
1651
1876
  }
@@ -1674,7 +1899,7 @@ function launcherHeader() {
1674
1899
  })();
1675
1900
  return cachedLauncherHeader;
1676
1901
  }
1677
- function httpGet(port, path, timeoutMs = 2e3) {
1902
+ function httpGetWithStatus(port, path, timeoutMs = 2e3) {
1678
1903
  return new Promise((resolve3, reject) => {
1679
1904
  const req = request(
1680
1905
  {
@@ -1691,7 +1916,10 @@ function httpGet(port, path, timeoutMs = 2e3) {
1691
1916
  res.setEncoding("utf8");
1692
1917
  let data = "";
1693
1918
  res.on("data", (chunk) => data += chunk);
1694
- res.on("end", () => resolve3(data));
1919
+ res.on(
1920
+ "end",
1921
+ () => resolve3({ statusCode: res.statusCode ?? 0, body: data })
1922
+ );
1695
1923
  }
1696
1924
  );
1697
1925
  req.on("error", reject);
@@ -1702,6 +1930,9 @@ function httpGet(port, path, timeoutMs = 2e3) {
1702
1930
  req.end();
1703
1931
  });
1704
1932
  }
1933
+ function httpGet(port, path, timeoutMs = 2e3) {
1934
+ return httpGetWithStatus(port, path, timeoutMs).then((r) => r.body);
1935
+ }
1705
1936
  function httpPost(port, path, body, timeoutMs = 12e4) {
1706
1937
  return new Promise((resolve3, reject) => {
1707
1938
  const payload = JSON.stringify(body);
@@ -1739,24 +1970,63 @@ function httpPost(port, path, body, timeoutMs = 12e4) {
1739
1970
  req.end();
1740
1971
  });
1741
1972
  }
1742
- async function checkBridgeHealth(port, opts = {}) {
1973
+ async function probeBridgeHealth(port, opts = {}) {
1743
1974
  try {
1744
- const path = opts.deep ? "/health?deep=1" : "/health";
1745
- const timeoutMs = opts.deep ? DEEP_HEALTH_TIMEOUT_MS : HEALTH_TIMEOUT_MS;
1746
- const resp = await httpGet(port, path, timeoutMs);
1747
- const data = JSON.parse(resp);
1748
- if (data.status !== "ok") return false;
1975
+ const path = opts.deep ? opts.waitMs !== void 0 ? `/health?deep=1&waitMs=${opts.waitMs}` : "/health?deep=1" : "/health";
1976
+ const timeoutMs = opts.deep ? Math.max(DEEP_HEALTH_TIMEOUT_MS, (opts.waitMs ?? 0) + 2500) : HEALTH_TIMEOUT_MS;
1977
+ const { statusCode, body } = await httpGetWithStatus(port, path, timeoutMs);
1978
+ const data = JSON.parse(body);
1749
1979
  if (opts.expectedSession !== void 0 && typeof data.session === "string" && data.session !== opts.expectedSession) {
1750
- return false;
1980
+ return {
1981
+ kind: "unreachable",
1982
+ reason: `session mismatch (expected ${opts.expectedSession}, got ${data.session})`
1983
+ };
1984
+ }
1985
+ if (statusCode === 202 || data.status === "pending") {
1986
+ return {
1987
+ kind: "pending",
1988
+ cdpState: typeof data.cdpState === "string" ? data.cdpState : "awaiting_approval",
1989
+ ...typeof data.pid === "number" && data.pid > 0 ? { pid: data.pid } : {},
1990
+ ...typeof data.waitingMs === "number" ? { waitingMs: data.waitingMs } : {},
1991
+ ...typeof data.logFile === "string" ? { logFile: data.logFile } : {}
1992
+ };
1751
1993
  }
1752
- if (opts.deep && opts.notice) {
1753
- opts.notice.pageIdentityChanged = data.pageIdentityChanged === true;
1994
+ if (data.status === "ok" && statusCode < 400) {
1995
+ const pageIdentityChanged = data.pageIdentityChanged === true;
1996
+ if (opts.deep && opts.notice) {
1997
+ opts.notice.pageIdentityChanged = pageIdentityChanged;
1998
+ }
1999
+ return {
2000
+ kind: "ok",
2001
+ busy: data.busy === true,
2002
+ ...typeof data.cdpState === "string" ? { cdpState: data.cdpState } : {},
2003
+ ...typeof data.dialogPending === "boolean" ? { dialogPending: data.dialogPending } : {},
2004
+ pageIdentityChanged
2005
+ };
1754
2006
  }
1755
- return true;
1756
- } catch {
1757
- return false;
2007
+ if (statusCode === 503 && data.status === "error" && data.mcpDisconnected !== true && (typeof data.reason === "string" || data.error === "CDP target unreachable")) {
2008
+ const reason = typeof data.reason === "string" ? data.reason : typeof data.error === "string" ? data.error : "CDP target unreachable";
2009
+ return {
2010
+ kind: "cdp_error",
2011
+ reason,
2012
+ ...typeof data.cdpState === "string" ? { cdpState: data.cdpState } : {}
2013
+ };
2014
+ }
2015
+ return {
2016
+ kind: "unreachable",
2017
+ reason: `unexpected health response (HTTP ${statusCode})`
2018
+ };
2019
+ } catch (error) {
2020
+ return {
2021
+ kind: "unreachable",
2022
+ reason: error instanceof Error ? error.message : String(error)
2023
+ };
1758
2024
  }
1759
2025
  }
2026
+ async function checkBridgeHealth(port, opts = {}) {
2027
+ const probe = await probeBridgeHealth(port, opts);
2028
+ return probe.kind === "ok";
2029
+ }
1760
2030
  function sleep(ms) {
1761
2031
  return new Promise((r) => setTimeout(r, ms));
1762
2032
  }
@@ -1917,9 +2187,13 @@ async function judgeRecordedBridge(pidInfo, sessionName) {
1917
2187
  const bridge = isBridgeProcess(pidInfo.pid, pidInfo.startTime);
1918
2188
  return { terminate: bridge, killProcessGroup: bridge, targetPid: pidInfo.pid, expectedStartTime: pidInfo.startTime };
1919
2189
  }
1920
- function removePidFile(pidFile) {
2190
+ function removePidFile(pidFile, expectedPid) {
1921
2191
  try {
1922
- unlinkSync(pidFile);
2192
+ if (expectedPid !== void 0) {
2193
+ const current = readPidFile(pidFile);
2194
+ if (!current || current.pid !== expectedPid) return;
2195
+ }
2196
+ unlinkSync2(pidFile);
1923
2197
  } catch {
1924
2198
  }
1925
2199
  }
@@ -1978,26 +2252,80 @@ async function terminateBridgeProcess(pid, opts = {}) {
1978
2252
  }
1979
2253
  return waitForProcessExit(pid, 1e3);
1980
2254
  }
2255
+ function openBridgeLogFd(sessionName) {
2256
+ try {
2257
+ const logFile = resolveSessionLogFile(sessionName);
2258
+ mkdirSync3(dirname4(logFile), { recursive: true });
2259
+ let flags = "a";
2260
+ try {
2261
+ if (existsSync4(logFile) && statSync2(logFile).size >= MAX_BRIDGE_LOG_BYTES) {
2262
+ flags = "w";
2263
+ }
2264
+ } catch {
2265
+ }
2266
+ return openSync(logFile, flags);
2267
+ } catch {
2268
+ return null;
2269
+ }
2270
+ }
1981
2271
  function spawnBridgeProcess(port, sessionName) {
1982
2272
  const bridgeScript = resolveBridgeScript(import.meta.dirname);
1983
- const script = existsSync3(bridgeScript.replace(/\.js$/, ".ts")) ? bridgeScript.replace(/\.js$/, ".ts") : bridgeScript;
2273
+ const script = existsSync4(bridgeScript.replace(/\.js$/, ".ts")) ? bridgeScript.replace(/\.js$/, ".ts") : bridgeScript;
1984
2274
  const runner = script.endsWith(".ts") ? "tsx" : "node";
1985
- const child = spawn2(
1986
- runner === "tsx" ? "npx" : "node",
1987
- runner === "tsx" ? ["tsx", script] : [script],
1988
- {
1989
- stdio: "ignore",
1990
- windowsHide: true,
1991
- env: {
1992
- ...process.env,
1993
- CHROME_DEVTOOLS_AXI_PORT: String(port),
1994
- CHROME_DEVTOOLS_AXI_SESSION: sessionName
1995
- },
1996
- detached: true
2275
+ const logFd = openBridgeLogFd(sessionName);
2276
+ try {
2277
+ const child = spawn2(
2278
+ runner === "tsx" ? "npx" : "node",
2279
+ runner === "tsx" ? ["tsx", script] : [script],
2280
+ {
2281
+ stdio: logFd !== null ? ["ignore", "ignore", logFd] : "ignore",
2282
+ windowsHide: true,
2283
+ env: {
2284
+ ...process.env,
2285
+ CHROME_DEVTOOLS_AXI_PORT: String(port),
2286
+ CHROME_DEVTOOLS_AXI_SESSION: sessionName
2287
+ },
2288
+ detached: true
2289
+ }
2290
+ );
2291
+ child.unref();
2292
+ return child;
2293
+ } finally {
2294
+ if (logFd !== null) {
2295
+ try {
2296
+ closeSync(logFd);
2297
+ } catch {
2298
+ }
1997
2299
  }
2300
+ }
2301
+ }
2302
+ function isAutoConnectEnv() {
2303
+ if (process.env.CHROME_DEVTOOLS_AXI_FRESH === "1") return false;
2304
+ if (resolveSharedMcpMode() !== null) return false;
2305
+ const explicit = process.env.CHROME_DEVTOOLS_AXI_AUTO_CONNECT;
2306
+ const autoConnectUnset = explicit === void 0 || explicit === "";
2307
+ return explicit === "1" || autoConnectUnset && !process.env.CHROME_DEVTOOLS_AXI_BROWSER_URL && !process.env.CHROME_DEVTOOLS_AXI_USER_DATA_DIR;
2308
+ }
2309
+ function notifyWaitingForApproval(sessionName, cdpState, logFile) {
2310
+ if (process.env.CHROME_DEVTOOLS_AXI_QUIET === "1") return;
2311
+ const log = logFile ?? resolveSessionLogFile(sessionName);
2312
+ const msg = cdpState === "awaiting_approval" ? `[chrome-devtools-axi] Waiting for Chrome remote-debugging approval dialog (click "Allow" in Chrome; log: ${log})
2313
+ ` : `[chrome-devtools-axi] Waiting for browser CDP connection (${cdpState}; log: ${log})
2314
+ `;
2315
+ process.stderr.write(msg);
2316
+ }
2317
+ function buildApprovalError(sessionName, reason) {
2318
+ const logFile = resolveSessionLogFile(sessionName);
2319
+ return new CdpError(
2320
+ `Chrome remote-debugging connection was not authorized: ${reason}`,
2321
+ "APPROVAL_REQUIRED",
2322
+ [
2323
+ 'If Chrome showed an "Allow remote debugging?" dialog, click "Allow" and re-run the command (do not restart the bridge while waiting).',
2324
+ "If no dialog appeared, verify chrome://inspect/#remote-debugging is enabled once in Chrome and that Chrome is running.",
2325
+ "For an isolated headless browser without user login state or approval prompts, set CHROME_DEVTOOLS_AXI_FRESH=1.",
2326
+ `Inspect bridge diagnostics at: ${logFile}`
2327
+ ]
1998
2328
  );
1999
- child.unref();
2000
- return child;
2001
2329
  }
2002
2330
  function resolveSharedMcpMode() {
2003
2331
  if (process.env.CHROME_DEVTOOLS_AXI_FRESH === "1") return null;
@@ -2053,111 +2381,528 @@ function buildBridgeEarlyExitError(sessionName, port, code, signal) {
2053
2381
  );
2054
2382
  return new CdpError(message, "BRIDGE_NOT_READY", suggestions);
2055
2383
  }
2056
- async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2384
+ function reclaimStaleStartLock(lockFile, expectedToken) {
2385
+ const reclaimFile = `${lockFile}.reclaim`;
2386
+ for (let attempt = 0; attempt < 2; attempt++) {
2387
+ let fd;
2388
+ try {
2389
+ fd = openSync(reclaimFile, "wx");
2390
+ } catch (error) {
2391
+ if (error.code !== "EEXIST") return;
2392
+ try {
2393
+ if (Date.now() - statSync2(reclaimFile).mtimeMs > 5e3) {
2394
+ unlinkSync2(reclaimFile);
2395
+ continue;
2396
+ }
2397
+ } catch {
2398
+ continue;
2399
+ }
2400
+ return;
2401
+ }
2402
+ try {
2403
+ closeSync(fd);
2404
+ try {
2405
+ const raw = readFileSync4(lockFile, "utf8");
2406
+ const parsed = JSON.parse(raw);
2407
+ if (expectedToken === void 0 || parsed.token === expectedToken) {
2408
+ unlinkSync2(lockFile);
2409
+ }
2410
+ } catch {
2411
+ if (expectedToken === void 0) {
2412
+ try {
2413
+ unlinkSync2(lockFile);
2414
+ } catch {
2415
+ }
2416
+ }
2417
+ }
2418
+ } finally {
2419
+ try {
2420
+ unlinkSync2(reclaimFile);
2421
+ } catch {
2422
+ }
2423
+ }
2424
+ return;
2425
+ }
2426
+ }
2427
+ function tryAcquireStartLock(lockFile, staleMs) {
2428
+ mkdirSync3(dirname4(lockFile), { recursive: true });
2429
+ const token = randomUUID();
2430
+ const payload = JSON.stringify({
2431
+ pid: process.pid,
2432
+ createdAt: Date.now(),
2433
+ token
2434
+ });
2435
+ for (let attempt = 0; attempt < 2; attempt++) {
2436
+ try {
2437
+ const fd = openSync(lockFile, "wx");
2438
+ try {
2439
+ writeFileSync3(fd, payload, "utf8");
2440
+ } finally {
2441
+ closeSync(fd);
2442
+ }
2443
+ let released = false;
2444
+ return {
2445
+ release: () => {
2446
+ if (released) return;
2447
+ released = true;
2448
+ try {
2449
+ const current = JSON.parse(readFileSync4(lockFile, "utf8"));
2450
+ if (current.token === token) unlinkSync2(lockFile);
2451
+ } catch {
2452
+ }
2453
+ }
2454
+ };
2455
+ } catch (error) {
2456
+ if (error.code !== "EEXIST") return null;
2457
+ let stale = false;
2458
+ let observedToken;
2459
+ try {
2460
+ const existing = JSON.parse(readFileSync4(lockFile, "utf8"));
2461
+ const holderPid = typeof existing.pid === "number" ? existing.pid : void 0;
2462
+ const createdAt = typeof existing.createdAt === "number" ? existing.createdAt : 0;
2463
+ observedToken = typeof existing.token === "string" ? existing.token : void 0;
2464
+ if (holderPid !== void 0 && holderPid !== process.pid && !isProcessAlive(holderPid)) {
2465
+ stale = true;
2466
+ } else if (Date.now() - createdAt > staleMs) {
2467
+ stale = true;
2468
+ }
2469
+ } catch {
2470
+ try {
2471
+ if (Date.now() - statSync2(lockFile).mtimeMs > 1e3) stale = true;
2472
+ } catch {
2473
+ stale = true;
2474
+ }
2475
+ }
2476
+ if (stale) {
2477
+ reclaimStaleStartLock(lockFile, observedToken);
2478
+ continue;
2479
+ }
2480
+ return null;
2481
+ }
2482
+ }
2483
+ return null;
2484
+ }
2485
+ function pinPendingGeneration(pidFile, pidInfo, probePid) {
2486
+ if (pidInfo && (probePid === void 0 || pidInfo.pid === probePid)) {
2487
+ return { pid: pidInfo.pid, startTime: pidInfo.startTime };
2488
+ }
2489
+ if (probePid !== void 0) {
2490
+ const disk = readPidFile(pidFile);
2491
+ if (disk && disk.pid === probePid) {
2492
+ return { pid: disk.pid, startTime: disk.startTime };
2493
+ }
2494
+ return {
2495
+ pid: probePid,
2496
+ startTime: inspectProcessIdentity(probePid).startTime ?? void 0
2497
+ };
2498
+ }
2499
+ return void 0;
2500
+ }
2501
+ async function waitForPendingBridge(opts) {
2502
+ const { port, sessionName, pidFile, initialProbe, autoConnect, notice } = opts;
2503
+ const isApprovalWait = initialProbe.cdpState === "awaiting_approval" || autoConnect;
2504
+ if (isApprovalWait) {
2505
+ notifyWaitingForApproval(
2506
+ sessionName,
2507
+ initialProbe.cdpState,
2508
+ initialProbe.logFile
2509
+ );
2510
+ }
2511
+ const waitBudgetMs = isApprovalWait ? resolveApprovalTimeoutMs() : resolveBridgeTimeoutMs();
2512
+ const waitDeadline = Date.now() + waitBudgetMs;
2513
+ const pinnedGeneration = pinPendingGeneration(
2514
+ pidFile,
2515
+ opts.pidInfo,
2516
+ initialProbe.pid
2517
+ );
2518
+ let stillPending = true;
2519
+ let existingError = null;
2520
+ let shouldRespawn = false;
2521
+ while (Date.now() < waitDeadline) {
2522
+ if (pinnedGeneration && !isProcessAlive(pinnedGeneration.pid)) {
2523
+ shouldRespawn = true;
2524
+ break;
2525
+ }
2526
+ await sleep(100);
2527
+ const next = await probeBridgeHealth(port, {
2528
+ deep: true,
2529
+ expectedSession: sessionName,
2530
+ notice
2531
+ });
2532
+ if (next.kind === "ok") return port;
2533
+ if (next.kind === "pending") continue;
2534
+ stillPending = false;
2535
+ if (next.kind === "cdp_error") {
2536
+ if (isApprovalWait) {
2537
+ existingError = next.reason;
2538
+ break;
2539
+ }
2540
+ shouldRespawn = true;
2541
+ break;
2542
+ }
2543
+ shouldRespawn = true;
2544
+ break;
2545
+ }
2546
+ if (shouldRespawn) {
2547
+ if (pinnedGeneration && isProcessAlive(pinnedGeneration.pid)) {
2548
+ try {
2549
+ await stopBridge({ expectedGeneration: pinnedGeneration });
2550
+ } catch {
2551
+ }
2552
+ } else if (pinnedGeneration) {
2553
+ removePidFile(pidFile, pinnedGeneration.pid);
2554
+ }
2555
+ return "respawn";
2556
+ }
2557
+ if (existingError !== null) {
2558
+ throw buildApprovalError(sessionName, existingError);
2559
+ }
2560
+ if (stillPending) {
2561
+ if (pinnedGeneration) {
2562
+ try {
2563
+ await stopBridge({ expectedGeneration: pinnedGeneration });
2564
+ } catch {
2565
+ }
2566
+ }
2567
+ if (isApprovalWait) {
2568
+ throw buildApprovalError(
2569
+ sessionName,
2570
+ `timed out after ${Math.round(waitBudgetMs / 1e3)}s waiting for Chrome approval`
2571
+ );
2572
+ }
2573
+ throw new CdpError(
2574
+ `Bridge deep health probe timed out after ${Math.round(waitBudgetMs / 1e3)}s`,
2575
+ "BRIDGE_NOT_READY",
2576
+ [`Inspect bridge diagnostics at: ${resolveSessionLogFile(sessionName)}`]
2577
+ );
2578
+ }
2579
+ return "respawn";
2580
+ }
2581
+ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2057
2582
  const sessionName = resolveSessionName();
2058
2583
  const port = resolveSessionPort(sessionName);
2059
2584
  const pidFile = resolveSessionPidFile(sessionName);
2585
+ const autoConnect = isAutoConnectEnv();
2060
2586
  const pidInfo = readPidFile(pidFile);
2061
2587
  if (pidInfo && isProcessAlive(pidInfo.pid)) {
2062
- if (await checkBridgeHealth(pidInfo.port, {
2588
+ const existingProbe = await probeBridgeHealth(pidInfo.port, {
2063
2589
  deep: true,
2064
2590
  expectedSession: sessionName,
2065
2591
  notice
2066
- })) {
2592
+ });
2593
+ if (existingProbe.kind === "ok") {
2067
2594
  return pidInfo.port;
2068
2595
  }
2069
- const verdict = await judgeRecordedBridge(pidInfo, sessionName);
2070
- if (verdict.terminate) {
2071
- await terminateBridgeProcess(verdict.targetPid ?? pidInfo.pid, {
2072
- killProcessGroup: verdict.killProcessGroup,
2073
- requireBridgeIdentity: true,
2074
- expectedStartTime: verdict.expectedStartTime
2596
+ if (existingProbe.kind === "pending") {
2597
+ const waited = await waitForPendingBridge({
2598
+ port: pidInfo.port,
2599
+ sessionName,
2600
+ pidFile,
2601
+ initialProbe: existingProbe,
2602
+ pidInfo,
2603
+ autoConnect,
2604
+ notice
2075
2605
  });
2606
+ if (typeof waited === "number") return waited;
2607
+ } else if (existingProbe.kind === "cdp_error" && autoConnect) {
2608
+ throw buildApprovalError(sessionName, existingProbe.reason);
2076
2609
  } else {
2077
- removePidFile(pidFile);
2610
+ const verdict = await judgeRecordedBridge(pidInfo, sessionName);
2611
+ if (verdict.terminate) {
2612
+ await terminateBridgeProcess(verdict.targetPid ?? pidInfo.pid, {
2613
+ killProcessGroup: verdict.killProcessGroup,
2614
+ requireBridgeIdentity: true,
2615
+ expectedStartTime: verdict.expectedStartTime
2616
+ });
2617
+ } else {
2618
+ removePidFile(pidFile, pidInfo.pid);
2619
+ }
2078
2620
  }
2079
2621
  }
2080
- clearSelectedPageId();
2081
- const child = spawnBridge(port, sessionName);
2082
- let childExited = false;
2083
- let exitCode = null;
2084
- let exitSignal = null;
2085
- child.on("exit", (code, signal) => {
2086
- childExited = true;
2087
- exitCode = code;
2088
- exitSignal = signal;
2089
- });
2090
- const timeoutMs = resolveBridgeTimeoutMs();
2091
- const deadline = Date.now() + timeoutMs;
2092
- let sawShallowReady = false;
2093
- while (Date.now() < deadline) {
2094
- if (await checkBridgeHealth(port, {
2622
+ const startLockFile = resolveSessionStartLockFile(sessionName);
2623
+ const lockBudgetMs = Math.max(START_LOCK_STALE_MS, resolveBridgeTimeoutMs());
2624
+ const MAX_RESPAWN_ATTEMPTS = 2;
2625
+ let respawnAttempts = 0;
2626
+ let startLock = null;
2627
+ let lockWaitDeadline = Date.now() + lockBudgetMs;
2628
+ while (true) {
2629
+ startLock = tryAcquireStartLock(startLockFile, lockBudgetMs);
2630
+ if (startLock !== null) {
2631
+ let postLockProbe;
2632
+ try {
2633
+ postLockProbe = await probeBridgeHealth(port, {
2634
+ deep: true,
2635
+ expectedSession: sessionName,
2636
+ notice
2637
+ });
2638
+ } catch (error) {
2639
+ startLock.release();
2640
+ throw error;
2641
+ }
2642
+ if (postLockProbe.kind === "ok") {
2643
+ startLock.release();
2644
+ return port;
2645
+ }
2646
+ if (postLockProbe.kind === "pending") {
2647
+ startLock.release();
2648
+ startLock = null;
2649
+ const waited = await waitForPendingBridge({
2650
+ port,
2651
+ sessionName,
2652
+ pidFile,
2653
+ initialProbe: postLockProbe,
2654
+ pidInfo: null,
2655
+ autoConnect,
2656
+ notice
2657
+ });
2658
+ if (typeof waited === "number") return waited;
2659
+ respawnAttempts += 1;
2660
+ if (respawnAttempts > MAX_RESPAWN_ATTEMPTS) {
2661
+ throw new CdpError(
2662
+ "Bridge repeatedly became unavailable while waiting for readiness",
2663
+ "BRIDGE_NOT_READY",
2664
+ [`Inspect bridge diagnostics at: ${resolveSessionLogFile(sessionName)}`]
2665
+ );
2666
+ }
2667
+ lockWaitDeadline = Date.now() + lockBudgetMs;
2668
+ continue;
2669
+ }
2670
+ if (postLockProbe.kind === "cdp_error") {
2671
+ if (autoConnect) {
2672
+ startLock.release();
2673
+ throw buildApprovalError(sessionName, postLockProbe.reason);
2674
+ }
2675
+ const brokenPid = readPidFile(pidFile);
2676
+ if (brokenPid && isProcessAlive(brokenPid.pid)) {
2677
+ const verdict = await judgeRecordedBridge(brokenPid, sessionName);
2678
+ if (verdict.terminate) {
2679
+ await terminateBridgeProcess(verdict.targetPid ?? brokenPid.pid, {
2680
+ killProcessGroup: verdict.killProcessGroup,
2681
+ requireBridgeIdentity: true,
2682
+ expectedStartTime: verdict.expectedStartTime
2683
+ });
2684
+ } else {
2685
+ removePidFile(pidFile, brokenPid.pid);
2686
+ }
2687
+ }
2688
+ }
2689
+ break;
2690
+ }
2691
+ const racingProbe = await probeBridgeHealth(port, {
2095
2692
  deep: true,
2096
2693
  expectedSession: sessionName,
2097
2694
  notice
2098
- })) {
2695
+ });
2696
+ if (racingProbe.kind === "ok") {
2099
2697
  return port;
2100
2698
  }
2101
- if (childExited) {
2102
- if (await checkBridgeHealth(port, {
2699
+ if (racingProbe.kind === "pending") {
2700
+ const waited = await waitForPendingBridge({
2701
+ port,
2702
+ sessionName,
2703
+ pidFile,
2704
+ initialProbe: racingProbe,
2705
+ pidInfo: null,
2706
+ autoConnect,
2707
+ notice
2708
+ });
2709
+ if (typeof waited === "number") return waited;
2710
+ respawnAttempts += 1;
2711
+ if (respawnAttempts > MAX_RESPAWN_ATTEMPTS) {
2712
+ throw new CdpError(
2713
+ "Bridge repeatedly became unavailable while waiting for readiness",
2714
+ "BRIDGE_NOT_READY",
2715
+ [`Inspect bridge diagnostics at: ${resolveSessionLogFile(sessionName)}`]
2716
+ );
2717
+ }
2718
+ lockWaitDeadline = Date.now() + lockBudgetMs;
2719
+ continue;
2720
+ }
2721
+ if (racingProbe.kind === "cdp_error" && autoConnect) {
2722
+ throw buildApprovalError(sessionName, racingProbe.reason);
2723
+ }
2724
+ if (Date.now() >= lockWaitDeadline) {
2725
+ break;
2726
+ }
2727
+ await sleep(100);
2728
+ }
2729
+ try {
2730
+ clearSelectedPageId();
2731
+ const child = spawnBridge(port, sessionName);
2732
+ let childExited = false;
2733
+ let exitCode = null;
2734
+ let exitSignal = null;
2735
+ child.on("exit", (code, signal) => {
2736
+ childExited = true;
2737
+ exitCode = code;
2738
+ exitSignal = signal;
2739
+ });
2740
+ const timeoutMs = resolveBridgeTimeoutMs();
2741
+ let deadline = Date.now() + timeoutMs;
2742
+ let sawShallowReady = false;
2743
+ let sawApprovalWait = false;
2744
+ let approvalNoticeShown = false;
2745
+ let lastCdpError = null;
2746
+ while (Date.now() < deadline) {
2747
+ const probe = await probeBridgeHealth(port, {
2103
2748
  deep: true,
2104
2749
  expectedSession: sessionName,
2105
2750
  notice
2106
- })) {
2751
+ });
2752
+ if (probe.kind === "ok") {
2107
2753
  return port;
2108
2754
  }
2109
- throw buildBridgeEarlyExitError(sessionName, port, exitCode, exitSignal);
2755
+ if (probe.kind === "pending") {
2756
+ startLock?.release();
2757
+ const isForeignWinner = childExited || probe.pid !== void 0 && child.pid !== void 0 && probe.pid !== child.pid;
2758
+ if (isForeignWinner) {
2759
+ const waited = await waitForPendingBridge({
2760
+ port,
2761
+ sessionName,
2762
+ pidFile,
2763
+ initialProbe: probe,
2764
+ pidInfo: null,
2765
+ autoConnect,
2766
+ notice
2767
+ });
2768
+ if (typeof waited === "number") return waited;
2769
+ throw new CdpError(
2770
+ "Bridge exited while waiting for readiness",
2771
+ "BRIDGE_NOT_READY",
2772
+ [`Inspect bridge diagnostics at: ${resolveSessionLogFile(sessionName)}`]
2773
+ );
2774
+ }
2775
+ sawShallowReady = true;
2776
+ if (probe.cdpState === "awaiting_approval" || autoConnect) {
2777
+ if (!sawApprovalWait) {
2778
+ sawApprovalWait = true;
2779
+ deadline = Math.max(deadline, Date.now() + resolveApprovalTimeoutMs());
2780
+ }
2781
+ if (!approvalNoticeShown) {
2782
+ approvalNoticeShown = true;
2783
+ notifyWaitingForApproval(sessionName, probe.cdpState, probe.logFile);
2784
+ }
2785
+ }
2786
+ await sleep(100);
2787
+ continue;
2788
+ }
2789
+ if (probe.kind === "cdp_error") {
2790
+ startLock?.release();
2791
+ sawShallowReady = true;
2792
+ lastCdpError = probe.reason;
2793
+ if (sawApprovalWait || autoConnect) {
2794
+ sawApprovalWait = true;
2795
+ break;
2796
+ }
2797
+ }
2798
+ if (childExited) {
2799
+ startLock?.release();
2800
+ let recheck = await probeBridgeHealth(port, {
2801
+ deep: true,
2802
+ expectedSession: sessionName,
2803
+ notice
2804
+ });
2805
+ if (recheck.kind === "unreachable" && exitCode === BRIDGE_PORT_IN_USE_EXIT_CODE) {
2806
+ await sleep(150);
2807
+ recheck = await probeBridgeHealth(port, {
2808
+ deep: true,
2809
+ expectedSession: sessionName,
2810
+ notice
2811
+ });
2812
+ }
2813
+ if (recheck.kind === "ok") {
2814
+ return port;
2815
+ }
2816
+ if (recheck.kind === "pending") {
2817
+ const waited = await waitForPendingBridge({
2818
+ port,
2819
+ sessionName,
2820
+ pidFile,
2821
+ initialProbe: recheck,
2822
+ pidInfo: null,
2823
+ autoConnect,
2824
+ notice
2825
+ });
2826
+ if (typeof waited === "number") return waited;
2827
+ throw new CdpError(
2828
+ "Bridge exited while waiting for readiness",
2829
+ "BRIDGE_NOT_READY",
2830
+ [`Inspect bridge diagnostics at: ${resolveSessionLogFile(sessionName)}`]
2831
+ );
2832
+ }
2833
+ if (recheck.kind === "cdp_error" && autoConnect) {
2834
+ sawShallowReady = true;
2835
+ sawApprovalWait = true;
2836
+ lastCdpError = recheck.reason;
2837
+ break;
2838
+ }
2839
+ throw buildBridgeEarlyExitError(sessionName, port, exitCode, exitSignal);
2840
+ }
2841
+ if (!sawShallowReady && await checkBridgeHealth(port, { expectedSession: sessionName })) {
2842
+ startLock?.release();
2843
+ sawShallowReady = true;
2844
+ }
2845
+ await sleep(500);
2110
2846
  }
2111
- if (!sawShallowReady && await checkBridgeHealth(port, { expectedSession: sessionName })) {
2112
- sawShallowReady = true;
2847
+ const shouldRecycle = !(sawApprovalWait && lastCdpError !== null);
2848
+ const failingGeneration = shouldRecycle ? child.pid !== void 0 && childExited === false ? {
2849
+ pid: child.pid,
2850
+ startTime: inspectProcessIdentity(child.pid)?.startTime ?? void 0
2851
+ } : pidInfo !== null && sawShallowReady ? { pid: pidInfo.pid, startTime: pidInfo.startTime } : void 0 : void 0;
2852
+ if (failingGeneration) {
2853
+ try {
2854
+ await stopBridge({ expectedGeneration: failingGeneration });
2855
+ } catch {
2856
+ }
2113
2857
  }
2114
- await sleep(500);
2115
- }
2116
- const failingGeneration = child.pid !== void 0 && childExited === false ? { pid: child.pid, startTime: inspectProcessIdentity(child.pid)?.startTime ?? void 0 } : pidInfo !== null && sawShallowReady ? { pid: pidInfo.pid, startTime: pidInfo.startTime } : void 0;
2117
- if (failingGeneration) {
2118
- try {
2119
- await stopBridge({ expectedGeneration: failingGeneration });
2120
- } catch {
2858
+ if (sawApprovalWait) {
2859
+ throw buildApprovalError(
2860
+ sessionName,
2861
+ lastCdpError ?? `timed out after ${Math.round(resolveApprovalTimeoutMs() / 1e3)}s waiting for Chrome approval`
2862
+ );
2121
2863
  }
2122
- }
2123
- const seconds = Math.round(timeoutMs / 1e3);
2124
- const sharedMcpMode = resolveSharedMcpMode();
2125
- if (sawShallowReady) {
2126
- const autoConnectDefault = !(process.env.CHROME_DEVTOOLS_AXI_FRESH === "1" || process.env.CHROME_DEVTOOLS_AXI_AUTO_CONNECT === "0");
2127
- const suggestions2 = sharedMcpMode ? [
2128
- ...sharedMcpSuggestions(sharedMcpMode),
2129
- "The shared MCP service may be reachable while its attached Chrome target is unavailable."
2130
- ] : autoConnectDefault ? [
2131
- "DEFAULT mode attaches to YOUR running Chrome (login state included). That requires remote debugging enabled ONCE in Chrome: open chrome://inspect/#remote-debugging and follow the dialog, then re-run. Chrome will ask you to approve each connection.",
2132
- "For an isolated headless instance instead (no user login state), set CHROME_DEVTOOLS_AXI_FRESH=1."
2133
- ] : [
2134
- "The Chrome/Electron instance the bridge was attached to may have exited.",
2135
- "Verify the target is still listening on its remote-debugging port, then re-run the command.",
2136
- "If the target was restarted, the bridge has already been recycled \u2014 this run will succeed once the target is reachable."
2864
+ const seconds = Math.round(timeoutMs / 1e3);
2865
+ const logFile = resolveSessionLogFile(sessionName);
2866
+ const sharedMcpMode = resolveSharedMcpMode();
2867
+ if (sawShallowReady) {
2868
+ const suggestions2 = sharedMcpMode ? [
2869
+ ...sharedMcpSuggestions(sharedMcpMode),
2870
+ "The shared MCP service may be reachable while its attached Chrome target is unavailable."
2871
+ ] : autoConnect ? [
2872
+ "DEFAULT mode attaches to YOUR running Chrome (login state included). That requires remote debugging enabled ONCE in Chrome: open chrome://inspect/#remote-debugging and follow the dialog, then re-run. Chrome will ask you to approve each connection.",
2873
+ "For an isolated headless instance instead (no user login state), set CHROME_DEVTOOLS_AXI_FRESH=1."
2874
+ ] : [
2875
+ "The Chrome/Electron instance the bridge was attached to may have exited.",
2876
+ "Verify the target is still listening on its remote-debugging port, then re-run the command.",
2877
+ "If the target was restarted, the bridge has already been recycled \u2014 this run will succeed once the target is reachable."
2878
+ ];
2879
+ suggestions2.push(`Inspect bridge diagnostics at: ${logFile}`);
2880
+ throw new CdpError(
2881
+ lastCdpError ? `Bridge is running but the attached CDP target is unreachable: ${lastCdpError}` : "Bridge is running but the attached CDP target appears to have gone away",
2882
+ "BRIDGE_NOT_READY",
2883
+ suggestions2
2884
+ );
2885
+ }
2886
+ const suggestions = sharedMcpMode === "direct" ? sharedMcpSuggestions("direct") : sharedMcpMode === "proxy" ? sharedMcpSuggestions("proxy") : [
2887
+ "Check that chrome-devtools-mcp is installed: npx chrome-devtools-mcp@latest --help"
2137
2888
  ];
2889
+ if (!sharedMcpMode && !process.env.CHROME_DEVTOOLS_AXI_MCP_PATH?.trim()) {
2890
+ suggestions.push(
2891
+ "If `npx -y chrome-devtools-mcp@latest` is slow on this machine, install mcp globally and set:",
2892
+ ' export CHROME_DEVTOOLS_AXI_MCP_PATH="$(npm prefix -g)/lib/node_modules/chrome-devtools-mcp/build/src/bin/chrome-devtools-mcp.js"'
2893
+ );
2894
+ }
2895
+ suggestions.push(
2896
+ "Or extend the deadline: export CHROME_DEVTOOLS_AXI_BRIDGE_TIMEOUT_MS=60000"
2897
+ );
2138
2898
  throw new CdpError(
2139
- "Bridge is running but the attached CDP target appears to have gone away",
2899
+ `Bridge failed to start within ${seconds}s`,
2140
2900
  "BRIDGE_NOT_READY",
2141
- suggestions2
2142
- );
2143
- }
2144
- const suggestions = sharedMcpMode === "direct" ? sharedMcpSuggestions("direct") : sharedMcpMode === "proxy" ? sharedMcpSuggestions("proxy") : [
2145
- "Check that chrome-devtools-mcp is installed: npx chrome-devtools-mcp@latest --help"
2146
- ];
2147
- if (!sharedMcpMode && !process.env.CHROME_DEVTOOLS_AXI_MCP_PATH?.trim()) {
2148
- suggestions.push(
2149
- "If `npx -y chrome-devtools-mcp@latest` is slow on this machine, install mcp globally and set:",
2150
- ' export CHROME_DEVTOOLS_AXI_MCP_PATH="$(npm prefix -g)/lib/node_modules/chrome-devtools-mcp/build/src/bin/chrome-devtools-mcp.js"'
2901
+ suggestions
2151
2902
  );
2903
+ } finally {
2904
+ startLock?.release();
2152
2905
  }
2153
- suggestions.push(
2154
- "Or extend the deadline: export CHROME_DEVTOOLS_AXI_BRIDGE_TIMEOUT_MS=60000"
2155
- );
2156
- throw new CdpError(
2157
- `Bridge failed to start within ${seconds}s`,
2158
- "BRIDGE_NOT_READY",
2159
- suggestions
2160
- );
2161
2906
  }
2162
2907
  function parseCallResponse(resp) {
2163
2908
  const data = JSON.parse(resp);
@@ -2184,8 +2929,8 @@ var DIR_OUTPUT_ARGS_BY_TOOL = /* @__PURE__ */ new Map([
2184
2929
  ]);
2185
2930
  function nearestExistingAncestor(path) {
2186
2931
  let candidate = path;
2187
- while (!existsSync3(candidate)) {
2188
- const parent = dirname3(candidate);
2932
+ while (!existsSync4(candidate)) {
2933
+ const parent = dirname4(candidate);
2189
2934
  if (parent === candidate) return candidate;
2190
2935
  candidate = parent;
2191
2936
  }
@@ -2196,7 +2941,7 @@ function collectRootDirs(name, args) {
2196
2941
  for (const key of FILE_OUTPUT_ARGS_BY_TOOL.get(name) ?? []) {
2197
2942
  const value = args[key];
2198
2943
  if (typeof value === "string" && value.length > 0) {
2199
- dirs.add(nearestExistingAncestor(dirname3(value)));
2944
+ dirs.add(nearestExistingAncestor(dirname4(value)));
2200
2945
  }
2201
2946
  }
2202
2947
  for (const key of DIR_OUTPUT_ARGS_BY_TOOL.get(name) ?? []) {
@@ -2207,7 +2952,7 @@ function collectRootDirs(name, args) {
2207
2952
  }
2208
2953
  if (name === "upload_file" && Array.isArray(args.filePaths)) {
2209
2954
  for (const file of args.filePaths) {
2210
- if (typeof file === "string") dirs.add(dirname3(file));
2955
+ if (typeof file === "string") dirs.add(dirname4(file));
2211
2956
  }
2212
2957
  }
2213
2958
  return [...dirs];
@@ -2370,240 +3115,89 @@ async function getSessionSnapshotIfRunning() {
2370
3115
  if (!pidInfo || !isProcessAlive(pidInfo.pid)) {
2371
3116
  return null;
2372
3117
  }
2373
- if (!await checkBridgeHealth(pidInfo.port, { expectedSession: sessionName })) {
2374
- return null;
2375
- }
2376
- try {
2377
- const pageId = getSelectedPageId();
2378
- if (pageId === null) return null;
2379
- return await postTool(
2380
- pidInfo.port,
2381
- "take_snapshot",
2382
- { pageId },
2383
- { timeoutMs: 5e3 }
2384
- );
2385
- } catch {
2386
- return null;
2387
- }
2388
- }
2389
- async function stopBridge(options = {}) {
2390
- const pidInfo = readPidFile();
2391
- if (!pidInfo) return "noop";
2392
- if (!isProcessAlive(pidInfo.pid)) return "noop";
2393
- if (options.expectedGeneration && (options.expectedGeneration.pid !== pidInfo.pid || options.expectedGeneration.startTime !== pidInfo.startTime)) {
2394
- return "noop";
2395
- }
2396
- const verdict = await judgeRecordedBridge(pidInfo, resolveSessionName());
2397
- if (!verdict.terminate) return "noop";
2398
- const targetPid = verdict.targetPid ?? pidInfo.pid;
2399
- if (options.expectedGeneration && targetPid !== options.expectedGeneration.pid) {
2400
- return "noop";
2401
- }
2402
- const terminated = await terminateBridgeProcess(targetPid, {
2403
- killProcessGroup: verdict.killProcessGroup,
2404
- requireBridgeIdentity: true,
2405
- expectedStartTime: options.expectedGeneration ? options.expectedGeneration.startTime ?? verdict.expectedStartTime : verdict.expectedStartTime
3118
+ const shallow = await probeBridgeHealth(pidInfo.port, {
3119
+ expectedSession: sessionName
2406
3120
  });
2407
- clearSelectedPageId();
2408
- return terminated ? "stopped" : "failed";
2409
- }
2410
-
2411
- // vendor/chrome-devtools-axi/src/generation.ts
2412
- import {
2413
- existsSync as existsSync4,
2414
- mkdirSync as mkdirSync2,
2415
- readFileSync as readFileSync4,
2416
- unlinkSync as unlinkSync2,
2417
- writeFileSync as writeFileSync2
2418
- } from "node:fs";
2419
- import { dirname as dirname4, join as join3 } from "node:path";
2420
- function genFile() {
2421
- return join3(resolveSessionStateDir(), "snapshot-generation");
2422
- }
2423
- function getCurrentGeneration() {
2424
- const file = genFile();
2425
- try {
2426
- if (!existsSync4(file)) return 0;
2427
- const parsed = Number.parseInt(readFileSync4(file, "utf-8").trim(), 10);
2428
- return Number.isNaN(parsed) ? 0 : parsed;
2429
- } catch {
2430
- return 0;
2431
- }
2432
- }
2433
- function bumpGeneration() {
2434
- const next = getCurrentGeneration() + 1;
2435
- const file = genFile();
2436
- try {
2437
- mkdirSync2(dirname4(file), { recursive: true });
2438
- writeFileSync2(file, String(next));
2439
- } catch {
2440
- }
2441
- return next;
2442
- }
2443
-
2444
- // vendor/chrome-devtools-axi/src/run.ts
2445
- import { mkdtempSync, writeFileSync as writeFileSync3, unlinkSync as unlinkSync3, rmdirSync } from "node:fs";
2446
- import { join as join4 } from "node:path";
2447
- import { tmpdir } from "node:os";
2448
- import { pathToFileURL } from "node:url";
2449
-
2450
- // vendor/chrome-devtools-axi/src/snapshot.ts
2451
- function countRefs(snapshot) {
2452
- const matches = snapshot.match(/\buid=\S+/g);
2453
- return matches ? matches.length : 0;
2454
- }
2455
- function extractRefs(snapshot) {
2456
- const refs = [];
2457
- for (const line of snapshot.split("\n")) {
2458
- const m = line.match(/\buid=(\S+)\s+(\w+)\s+"([^"]*)"/);
2459
- if (!m) continue;
2460
- refs.push({ ref: m[1], type: m[2], label: m[3] });
2461
- }
2462
- return refs;
2463
- }
2464
- function parseStampedUid(arg) {
2465
- const stripped = arg.startsWith("@") ? arg.slice(1) : arg;
2466
- const m = stripped.match(/^g(\d+):(.+)$/);
2467
- if (m) return { uid: m[2], generation: Number.parseInt(m[1], 10) };
2468
- return { uid: stripped, generation: null };
2469
- }
2470
- function stampSnapshotGeneration(snapshot, generation) {
2471
- return snapshot.replace(/\buid=(\S+)/g, (match, uid) => {
2472
- if (/^g\d+:/.test(uid)) return match;
2473
- return `uid=g${generation}:${uid}`;
2474
- });
2475
- }
2476
- function checkUidGeneration(arg, currentGeneration) {
2477
- const { uid, generation } = parseStampedUid(arg);
2478
- return {
2479
- uid,
2480
- stale: generation !== null && generation !== currentGeneration,
2481
- refGeneration: generation
2482
- };
2483
- }
2484
- function extractTitle(snapshot) {
2485
- const rootMatch = snapshot.match(/RootWebArea\s+"([^"]+)"/);
2486
- if (rootMatch) return rootMatch[1];
2487
- const headingMatch = snapshot.match(/\bheading\s+"([^"]+)"/);
2488
- if (headingMatch) return headingMatch[1];
2489
- return "";
2490
- }
2491
- function truncateSnapshot(snapshot, full, limit = 16e3) {
2492
- const totalLength = snapshot.length;
2493
- if (full || totalLength <= limit) {
2494
- return { text: snapshot, truncated: false, totalLength };
2495
- }
2496
- const cut = snapshot.lastIndexOf("\n", limit);
2497
- const text = cut > 0 ? snapshot.slice(0, cut) : snapshot.slice(0, limit);
2498
- return { text, truncated: true, totalLength };
2499
- }
2500
- var MARKER_OVERHEAD = 50;
2501
- function truncateText(text, limit = 8e3) {
2502
- const totalLength = text.length;
2503
- if (totalLength <= limit) {
2504
- return { text, truncated: false, totalLength };
2505
- }
2506
- if (totalLength <= limit + MARKER_OVERHEAD) {
2507
- return { text, truncated: false, totalLength };
2508
- }
2509
- const headBudget = Math.floor(limit * 0.4);
2510
- const tailBudget = limit - headBudget;
2511
- const headCut = text.lastIndexOf("\n", headBudget);
2512
- const head = headCut > 0 ? text.slice(0, headCut) : text.slice(0, headBudget);
2513
- const tailStart = text.indexOf("\n", totalLength - tailBudget);
2514
- const tail = tailStart > 0 && tailStart < totalLength ? text.slice(tailStart + 1) : text.slice(totalLength - tailBudget);
2515
- const omitted = totalLength - head.length - tail.length;
2516
- const result = `${head}
2517
-
2518
- ... (${omitted} chars omitted, ${totalLength} total) ...
2519
-
2520
- ${tail}`;
2521
- return { text: result, truncated: true, totalLength };
2522
- }
2523
- var INPUT_TYPES = ["textbox", "searchbox", "input", "combobox", "textarea"];
2524
- function isInputType(type) {
2525
- return INPUT_TYPES.includes(type);
2526
- }
2527
-
2528
- // vendor/chrome-devtools-axi/src/uid-freshness.ts
2529
- var PAGE_GENERATION_KEY = "__chromeDevtoolsAxiSnapshotGeneration";
2530
- async function captureFreshSnapshot(caller, capture) {
2531
- const first = await captureSnapshot(caller, capture);
2532
- const fresh = first.state?.generation === first.generation && first.state.mutations > 0 ? await captureSnapshot(caller, capture) : first;
2533
- return stampSnapshotGeneration(fresh.snapshot, fresh.generation);
2534
- }
2535
- function throwStaleRef(arg, refGeneration, currentGeneration) {
2536
- const refRaw = arg.startsWith("@") ? arg.slice(1) : arg;
2537
- const current = currentGeneration ?? "unavailable";
2538
- throw new CdpError(
2539
- `Stale ref @${refRaw}: from snapshot generation ${refGeneration}, current is ${current}. Re-snapshot to get fresh refs.`,
2540
- "STALE_REF",
2541
- [
2542
- "Run `chrome-devtools-axi snapshot` to capture current refs, then retry the action"
2543
- ]
2544
- );
2545
- }
2546
- async function markPageSnapshotGeneration(generation, caller) {
2547
- const key = JSON.stringify(PAGE_GENERATION_KEY);
2548
- try {
2549
- await caller("evaluate_script", {
2550
- function: `() => {
2551
- const key = ${key};
2552
- const previous = globalThis[key];
2553
- if (previous && previous.observer) previous.observer.disconnect();
2554
- const state = { generation: ${generation}, mutations: 0, observer: null };
2555
- const observer = new MutationObserver(() => { state.mutations += 1; });
2556
- observer.observe(document.documentElement || document, { childList: true, subtree: true, attributes: true, characterData: true });
2557
- state.observer = observer;
2558
- globalThis[key] = state;
2559
- return state.generation;
2560
- }`
2561
- });
2562
- } catch {
3121
+ if (shallow.kind !== "ok" || shallow.busy || shallow.dialogPending || shallow.cdpState !== void 0 && shallow.cdpState !== "connected") {
3122
+ return null;
2563
3123
  }
2564
- }
2565
- async function captureSnapshot(caller, capture) {
2566
- const generation = bumpGeneration();
2567
- await markPageSnapshotGeneration(generation, caller);
2568
- const snapshot = await capture();
2569
- return { generation, snapshot, state: await getPageRefState(caller) };
2570
- }
2571
- async function getPageRefState(caller) {
2572
- const key = JSON.stringify(PAGE_GENERATION_KEY);
2573
3124
  try {
2574
- const output = await caller("evaluate_script", {
2575
- function: `() => {
2576
- const state = globalThis[${key}];
2577
- if (!state || typeof state.generation !== 'number' || typeof state.mutations !== 'number' || !state.observer) return null;
2578
- return { generation: state.generation, mutations: state.mutations };
2579
- }`
2580
- });
2581
- const jsonBlock = output.match(/```json\n([\s\S]*?)\n```/);
2582
- const raw = jsonBlock?.[1] ?? output.replace(/^Script ran on page and returned:\s*/, "");
2583
- const parsed = JSON.parse(raw.trim());
2584
- if (typeof parsed !== "object" || parsed === null || typeof parsed.generation !== "number" || typeof parsed.mutations !== "number") {
2585
- return null;
2586
- }
2587
- return parsed;
3125
+ const pageId = getSelectedPageId();
3126
+ if (pageId === null) return null;
3127
+ return await postTool(
3128
+ pidInfo.port,
3129
+ "take_snapshot",
3130
+ { pageId },
3131
+ { timeoutMs: 5e3 }
3132
+ );
2588
3133
  } catch {
2589
3134
  return null;
2590
3135
  }
2591
3136
  }
2592
- async function parseUidFresh(arg, caller) {
2593
- const snapshotGeneration = getCurrentGeneration();
2594
- const check = checkUidGeneration(arg, snapshotGeneration);
2595
- if (check.stale) {
2596
- throwStaleRef(arg, check.refGeneration, snapshotGeneration);
3137
+ async function tryCleanupSessionObserver() {
3138
+ let sessionName;
3139
+ let pidInfo;
3140
+ try {
3141
+ sessionName = resolveSessionName();
3142
+ pidInfo = readPidFile(resolveSessionPidFile(sessionName));
3143
+ } catch {
3144
+ return;
2597
3145
  }
2598
- const state = await getPageRefState(caller);
2599
- if (!state || state.generation !== snapshotGeneration || state.mutations !== 0) {
2600
- throwStaleRef(
2601
- arg,
2602
- parseStampedUid(arg).generation ?? snapshotGeneration,
2603
- state ? state.generation + state.mutations : null
3146
+ if (!pidInfo || !isProcessAlive(pidInfo.pid)) return;
3147
+ const pageId = getSelectedPageId();
3148
+ if (pageId === null) return;
3149
+ const shallow = await probeBridgeHealth(pidInfo.port, {
3150
+ expectedSession: sessionName
3151
+ });
3152
+ if (shallow.kind !== "ok" || shallow.busy || shallow.dialogPending || shallow.cdpState !== "connected") {
3153
+ return;
3154
+ }
3155
+ try {
3156
+ await postTool(
3157
+ pidInfo.port,
3158
+ "evaluate_script",
3159
+ {
3160
+ pageId,
3161
+ waitForStableDom: false,
3162
+ function: CLEANUP_OBSERVER_SCRIPT
3163
+ },
3164
+ { timeoutMs: 800 }
2604
3165
  );
3166
+ } catch {
2605
3167
  }
2606
- return check.uid;
3168
+ }
3169
+ async function stopBridge(options = {}) {
3170
+ const pidInfo = readPidFile();
3171
+ if (!pidInfo) return "noop";
3172
+ if (!isProcessAlive(pidInfo.pid)) return "noop";
3173
+ if (options.expectedGeneration && (options.expectedGeneration.pid !== pidInfo.pid || options.expectedGeneration.startTime !== pidInfo.startTime)) {
3174
+ return "noop";
3175
+ }
3176
+ const verdict = await judgeRecordedBridge(pidInfo, resolveSessionName());
3177
+ if (!verdict.terminate) return "noop";
3178
+ const targetPid = verdict.targetPid ?? pidInfo.pid;
3179
+ if (options.expectedGeneration && targetPid !== options.expectedGeneration.pid) {
3180
+ return "noop";
3181
+ }
3182
+ const terminated = await terminateBridgeProcess(targetPid, {
3183
+ killProcessGroup: verdict.killProcessGroup,
3184
+ requireBridgeIdentity: true,
3185
+ expectedStartTime: options.expectedGeneration ? options.expectedGeneration.startTime ?? verdict.expectedStartTime : verdict.expectedStartTime
3186
+ });
3187
+ clearSelectedPageId();
3188
+ return terminated ? "stopped" : "failed";
3189
+ }
3190
+
3191
+ // vendor/chrome-devtools-axi/src/run.ts
3192
+ import { mkdtempSync, writeFileSync as writeFileSync4, unlinkSync as unlinkSync3, rmdirSync } from "node:fs";
3193
+ import { join as join4 } from "node:path";
3194
+ import { tmpdir } from "node:os";
3195
+ import { pathToFileURL } from "node:url";
3196
+
3197
+ // vendor/chrome-devtools-axi/src/paths.ts
3198
+ import { isAbsolute, resolve as resolve2 } from "node:path";
3199
+ function resolveOutputPath(filePath) {
3200
+ return isAbsolute(filePath) ? filePath : resolve2(process.cwd(), filePath);
2607
3201
  }
2608
3202
 
2609
3203
  // vendor/chrome-devtools-axi/src/run.ts
@@ -2675,25 +3269,61 @@ function wrapJsExpression(js) {
2675
3269
  }
2676
3270
  return `() => (${trimmed})`;
2677
3271
  }
3272
+ var ZERO_WIDTH_RE = /[\u200B-\u200D\u2060\uFEFF]/g;
3273
+ function stripZeroWidth(text) {
3274
+ return text.replace(ZERO_WIDTH_RE, "");
3275
+ }
3276
+ function parseJsonOrUndefined(raw) {
3277
+ const trimmed = raw.trim();
3278
+ if (trimmed === "undefined") return void 0;
3279
+ try {
3280
+ return JSON.parse(trimmed);
3281
+ } catch (error) {
3282
+ const detail = error instanceof Error ? error.message : String(error);
3283
+ throw new CdpError(
3284
+ `Failed to parse evaluate_script return value as JSON (${detail}): ${trimmed.slice(0, 200)}`,
3285
+ "BROWSER_ERROR",
3286
+ [
3287
+ "Ensure the evaluated expression returns a JSON-serializable value (or undefined)."
3288
+ ]
3289
+ );
3290
+ }
3291
+ }
2678
3292
  function parseEvalOutput(output) {
2679
- const jsonBlock = output.match(/```json\n([\s\S]*?)\n```/);
3293
+ if (/^# Open dialog\b/m.test(output)) {
3294
+ throw new CdpError(
3295
+ "Cannot read evaluate_script result because a JavaScript dialog is open.",
3296
+ "DIALOG_PENDING",
3297
+ [
3298
+ 'Call `await page.dialog("accept")` or `await page.dialog("dismiss")` before continuing.'
3299
+ ]
3300
+ );
3301
+ }
3302
+ const jsonBlock = output.match(/```json\r?\n([\s\S]*?)\r?\n```(?:\r?\n|$)/);
2680
3303
  if (jsonBlock) {
2681
- try {
2682
- return JSON.parse(jsonBlock[1].trim());
2683
- } catch {
2684
- return jsonBlock[1].trim();
2685
- }
3304
+ return parseJsonOrUndefined(jsonBlock[1]);
2686
3305
  }
2687
3306
  const preamble = "Script ran on page and returned:";
2688
3307
  if (output.includes(preamble)) {
2689
3308
  const raw = output.slice(output.indexOf(preamble) + preamble.length).trim();
2690
- try {
2691
- return JSON.parse(raw);
2692
- } catch {
2693
- return raw;
2694
- }
3309
+ return parseJsonOrUndefined(raw);
3310
+ }
3311
+ throw new CdpError(
3312
+ `Unexpected evaluate_script response format: ${output.trim().slice(0, 200)}`,
3313
+ "BROWSER_ERROR",
3314
+ ["Run `chrome-devtools-axi snapshot` or inspect page state before retrying."]
3315
+ );
3316
+ }
3317
+ function assertNoPendingDialog(result) {
3318
+ if (/^# Open dialog\b/m.test(result)) {
3319
+ throw new CdpError(
3320
+ "The action opened a dialog. Do not replay it; handle the dialog first.",
3321
+ "DIALOG_PENDING",
3322
+ [
3323
+ 'Call `await page.dialog("accept")` or `await page.dialog("dismiss")` in the same session.'
3324
+ ]
3325
+ );
2695
3326
  }
2696
- return output.trim();
2697
3327
  }
2698
3328
  function stripSnapshotHeader(text) {
2699
3329
  const lines = text.split("\n");
@@ -2728,10 +3358,10 @@ function createPageHelper(callTool2) {
2728
3358
  ]);
2729
3359
  }
2730
3360
  try {
2731
- await callTool2("navigate_page", { type: "url", url });
3361
+ assertNoPendingDialog(await callTool2("navigate_page", { type: "url", url }));
2732
3362
  } catch (error) {
2733
3363
  if (!isRecoverableOpenError(error)) throw error;
2734
- await callTool2("new_page", { url });
3364
+ assertNoPendingDialog(await callTool2("new_page", { url }));
2735
3365
  }
2736
3366
  const info = await evalJs(
2737
3367
  `() => ({ url: location.href, status: performance.getEntriesByType('navigation').pop()?.responseStatus ?? null })`
@@ -2750,27 +3380,51 @@ function createPageHelper(callTool2) {
2750
3380
  }
2751
3381
  return evalJs(jsOrFn);
2752
3382
  },
2753
- async wait(msOrSelector, timeout) {
3383
+ async wait(msOrSelector, timeoutOrOpts) {
2754
3384
  if (typeof msOrSelector === "number") {
2755
3385
  await callFunction(`new Promise(r => setTimeout(r, ${msOrSelector}))`);
2756
3386
  } else {
2757
- const ms = timeout ?? DEFAULT_WAIT_TIMEOUT;
3387
+ const opts = typeof timeoutOrOpts === "number" ? { timeout: timeoutOrOpts } : timeoutOrOpts ?? {};
3388
+ const ms = opts.timeout ?? DEFAULT_WAIT_TIMEOUT;
3389
+ const requireVisible = opts.visible === true;
3390
+ const waitForAbsent = opts.absent === true;
2758
3391
  const sel = JSON.stringify(msOrSelector);
2759
3392
  await callFunction(`new Promise((resolve, reject) => {
2760
3393
  const sel = ${sel};
2761
- if (document.querySelector(sel)) { resolve(); return; }
3394
+ const requireVisible = ${JSON.stringify(requireVisible)};
3395
+ const waitForAbsent = ${JSON.stringify(waitForAbsent)};
3396
+ const isVisible = (el) => {
3397
+ if (!el || !el.isConnected) return false;
3398
+ const style = getComputedStyle(el);
3399
+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return false;
3400
+ const rects = el.getClientRects();
3401
+ return rects.length > 0 && Array.from(rects).some(r => r.width > 0 && r.height > 0);
3402
+ };
3403
+ const matches = () => {
3404
+ const nodes = Array.from(document.querySelectorAll(sel));
3405
+ const found = requireVisible ? nodes.some(isVisible) : nodes.length > 0;
3406
+ return waitForAbsent ? !found : found;
3407
+ };
3408
+ if (matches()) { resolve(); return; }
3409
+ const root = document.documentElement || document;
3410
+ const finish = () => {
3411
+ observer.disconnect();
3412
+ clearInterval(poll);
3413
+ clearTimeout(timer);
3414
+ resolve();
3415
+ };
2762
3416
  const observer = new MutationObserver(() => {
2763
- if (document.querySelector(sel)) {
2764
- observer.disconnect();
2765
- clearTimeout(timer);
2766
- resolve();
2767
- }
3417
+ if (matches()) finish();
2768
3418
  });
3419
+ const poll = setInterval(() => {
3420
+ if (matches()) finish();
3421
+ }, 100);
2769
3422
  const timer = setTimeout(() => {
2770
3423
  observer.disconnect();
2771
- reject(new Error('Timeout waiting for: ' + sel));
3424
+ clearInterval(poll);
3425
+ reject(new Error((waitForAbsent ? 'Timeout waiting for absence of: ' : 'Timeout waiting for: ') + sel));
2772
3426
  }, ${ms});
2773
- observer.observe(document.body, { childList: true, subtree: true, attributes: true });
3427
+ observer.observe(root, { childList: true, subtree: true, attributes: true });
2774
3428
  })`);
2775
3429
  }
2776
3430
  },
@@ -2782,49 +3436,162 @@ function createPageHelper(callTool2) {
2782
3436
  },
2783
3437
  async click(refOrSelector) {
2784
3438
  if (isUidRef(refOrSelector)) {
2785
- await callTool2("click", {
3439
+ const res = await callTool2("click", {
2786
3440
  uid: await parseUidFresh(refOrSelector, callTool2)
2787
3441
  });
3442
+ assertNoPendingDialog(res);
2788
3443
  } else {
2789
3444
  const sel = JSON.stringify(refOrSelector);
2790
- await callFunction(`() => {
3445
+ const res = await callFunction(`async () => {
2791
3446
  const el = document.querySelector(${sel});
2792
- if (!el) throw new Error('Element not found: ' + ${sel});
2793
- el.scrollIntoView({ block: 'center' });
3447
+ if (!el || !el.isConnected) throw new Error('Element not found: ' + ${sel});
3448
+ if ('disabled' in el && el.disabled) throw new Error('Element is disabled: ' + ${sel});
3449
+ const isVisible = (node) => {
3450
+ const style = getComputedStyle(node);
3451
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
3452
+ const rects = node.getClientRects();
3453
+ return rects.length > 0 && Array.from(rects).some(r => r.width > 0 && r.height > 0);
3454
+ };
3455
+ if (!isVisible(el)) throw new Error('Element is not visible: ' + ${sel});
3456
+ el.scrollIntoView({ block: 'center', inline: 'center' });
3457
+ await new Promise(r => {
3458
+ let done = false;
3459
+ const finish = () => { if (!done) { done = true; r(); } };
3460
+ const t = setTimeout(finish, 60);
3461
+ if (document.visibilityState === 'visible') {
3462
+ requestAnimationFrame(() => { clearTimeout(t); finish(); });
3463
+ }
3464
+ });
3465
+ if (!el.isConnected || !isVisible(el)) throw new Error('Element became unavailable after scroll: ' + ${sel});
2794
3466
  el.click();
2795
3467
  }`);
3468
+ assertNoPendingDialog(res);
2796
3469
  }
2797
3470
  },
2798
3471
  async fill(refOrSelector, text) {
2799
3472
  if (isUidRef(refOrSelector)) {
2800
- await callTool2("fill", {
3473
+ const res = await callTool2("fill", {
2801
3474
  uid: await parseUidFresh(refOrSelector, callTool2),
2802
3475
  value: text
2803
3476
  });
3477
+ assertNoPendingDialog(res);
2804
3478
  } else {
2805
3479
  const sel = JSON.stringify(refOrSelector);
2806
3480
  const val = JSON.stringify(text);
2807
- await callFunction(`() => {
3481
+ const res = await callFunction(`() => {
2808
3482
  const el = document.querySelector(${sel});
2809
- if (!el) throw new Error('Element not found: ' + ${sel});
3483
+ if (!el || !el.isConnected) throw new Error('Element not found: ' + ${sel});
3484
+ if ('disabled' in el && el.disabled) throw new Error('Element is disabled: ' + ${sel});
3485
+ if ('readOnly' in el && el.readOnly) throw new Error('Element is read-only: ' + ${sel});
2810
3486
  el.focus();
2811
3487
  const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype
2812
3488
  : el instanceof HTMLSelectElement ? HTMLSelectElement.prototype
2813
- : HTMLInputElement.prototype;
2814
- Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, ${val});
3489
+ : el instanceof HTMLInputElement ? HTMLInputElement.prototype
3490
+ : null;
3491
+ const desc = proto ? Object.getOwnPropertyDescriptor(proto, 'value') : null;
3492
+ if (desc && desc.set) desc.set.call(el, ${val});
3493
+ else if ('value' in el) el.value = ${val};
3494
+ else if (el.isContentEditable) el.textContent = ${val};
3495
+ else throw new Error('Element is not a fillable input: ' + ${sel});
2815
3496
  el.dispatchEvent(new Event('input', { bubbles: true }));
2816
3497
  el.dispatchEvent(new Event('change', { bubbles: true }));
2817
3498
  }`);
3499
+ assertNoPendingDialog(res);
2818
3500
  }
2819
3501
  },
2820
3502
  async type(text) {
2821
- await callTool2("type_text", { text });
3503
+ assertNoPendingDialog(await callTool2("type_text", { text }));
2822
3504
  },
2823
3505
  async press(key) {
2824
- await callTool2("press_key", { key });
3506
+ assertNoPendingDialog(await callTool2("press_key", { key }));
2825
3507
  },
2826
3508
  async back() {
2827
- await callTool2("navigate_page", { type: "back" });
3509
+ assertNoPendingDialog(await callTool2("navigate_page", { type: "back" }));
3510
+ },
3511
+ async dialog(action, promptText) {
3512
+ const params = { action };
3513
+ if (promptText !== void 0) params.promptText = promptText;
3514
+ return callTool2("handle_dialog", params);
3515
+ },
3516
+ async network(opts = {}) {
3517
+ const params = {};
3518
+ if (opts.resourceTypes) params.resourceTypes = opts.resourceTypes;
3519
+ if (opts.pageSize !== void 0) params.pageSize = opts.pageSize;
3520
+ if (opts.pageIdx !== void 0) params.pageIdx = opts.pageIdx;
3521
+ if (opts.includePreservedRequests) {
3522
+ params.includePreservedRequests = true;
3523
+ }
3524
+ return callTool2("list_network_requests", params);
3525
+ },
3526
+ async networkGet(reqid, opts = {}) {
3527
+ const params = {};
3528
+ if (reqid !== void 0) params.reqid = reqid;
3529
+ if (opts.requestFilePath) {
3530
+ params.requestFilePath = resolveOutputPath(opts.requestFilePath);
3531
+ }
3532
+ if (opts.responseFilePath) {
3533
+ params.responseFilePath = resolveOutputPath(opts.responseFilePath);
3534
+ }
3535
+ return callTool2("get_network_request", params);
3536
+ },
3537
+ async scroll(directionOrTarget = "down", opts = {}) {
3538
+ const directions = /* @__PURE__ */ new Set(["up", "down", "top", "bottom"]);
3539
+ const isDirection = directions.has(directionOrTarget.toLowerCase());
3540
+ const direction = isDirection ? directionOrTarget.toLowerCase() : opts.direction ?? "down";
3541
+ const amount = opts.amount ?? 500;
3542
+ const wheel = opts.wheel === true;
3543
+ const deltaY = direction === "up" ? -amount : amount;
3544
+ if (isDirection) {
3545
+ await callFunction(`() => {
3546
+ const dir = ${JSON.stringify(direction)};
3547
+ const deltaY = ${JSON.stringify(deltaY)};
3548
+ let handledByWheel = false;
3549
+ if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
3550
+ const target = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2) || document.documentElement;
3551
+ handledByWheel = !target.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
3552
+ }
3553
+ if (handledByWheel) return;
3554
+ if (dir === 'top') window.scrollTo(0, 0);
3555
+ else if (dir === 'bottom') window.scrollTo(0, document.documentElement.scrollHeight || document.body.scrollHeight);
3556
+ else window.scrollBy(0, deltaY);
3557
+ }`);
3558
+ return;
3559
+ }
3560
+ if (isUidRef(directionOrTarget)) {
3561
+ const uid = await parseUidFresh(directionOrTarget, callTool2);
3562
+ await callTool2("evaluate_script", {
3563
+ args: [uid],
3564
+ function: `(el) => {
3565
+ if (!el) throw new Error('Scroll target not found');
3566
+ const dir = ${JSON.stringify(direction)};
3567
+ const deltaY = ${JSON.stringify(deltaY)};
3568
+ let handledByWheel = false;
3569
+ if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
3570
+ handledByWheel = !el.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
3571
+ }
3572
+ if (handledByWheel) return;
3573
+ if (dir === 'top') el.scrollTop = 0;
3574
+ else if (dir === 'bottom') el.scrollTop = el.scrollHeight;
3575
+ else el.scrollBy(0, deltaY);
3576
+ }`
3577
+ });
3578
+ return;
3579
+ }
3580
+ const sel = JSON.stringify(directionOrTarget);
3581
+ await callFunction(`() => {
3582
+ const el = document.querySelector(${sel});
3583
+ if (!el) throw new Error('Scroll target not found: ' + ${sel});
3584
+ const dir = ${JSON.stringify(direction)};
3585
+ const deltaY = ${JSON.stringify(deltaY)};
3586
+ let handledByWheel = false;
3587
+ if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
3588
+ handledByWheel = !el.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
3589
+ }
3590
+ if (handledByWheel) return;
3591
+ if (dir === 'top') el.scrollTop = 0;
3592
+ else if (dir === 'bottom') el.scrollTop = el.scrollHeight;
3593
+ else el.scrollBy(0, deltaY);
3594
+ }`);
2828
3595
  }
2829
3596
  };
2830
3597
  }
@@ -2839,7 +3606,7 @@ async function runScript(content, callTool2) {
2839
3606
  const page = createPageHelper(callTool2);
2840
3607
  const tmpDir = mkdtempSync(join4(tmpdir(), "cda-run-"));
2841
3608
  const tmpFile = join4(tmpDir, "script.mjs");
2842
- writeFileSync3(tmpFile, content, "utf-8");
3609
+ writeFileSync4(tmpFile, content, "utf-8");
2843
3610
  const lines = [];
2844
3611
  const origLog = console.log;
2845
3612
  const captureLog = (...args) => {
@@ -2949,12 +3716,6 @@ function installHooksOrThrow() {
2949
3716
  }
2950
3717
  }
2951
3718
 
2952
- // vendor/chrome-devtools-axi/src/paths.ts
2953
- import { isAbsolute, resolve as resolve2 } from "node:path";
2954
- function resolveOutputPath(filePath) {
2955
- return isAbsolute(filePath) ? filePath : resolve2(process.cwd(), filePath);
2956
- }
2957
-
2958
3719
  // vendor/chrome-devtools-axi/src/cli.ts
2959
3720
  var HOME_DESCRIPTION = "Agent ergonomic interface for controlling Chrome browser session. Prefer this over other browser automation tools.";
2960
3721
  var RAW_STDOUT_MARKER = "__CHROME_DEVTOOLS_AXI_RAW__";
@@ -3122,17 +3883,24 @@ flags:
3122
3883
  examples:
3123
3884
  chrome-devtools-axi press Enter
3124
3885
  chrome-devtools-axi press Tab --full`,
3125
- scroll: `usage: chrome-devtools-axi scroll <direction> [--full]
3126
- Scroll the page in a direction.
3886
+ scroll: `usage: chrome-devtools-axi scroll [direction] [--uid @<uid>|--selector <css>] [--amount <px>] [--wheel] [--full]
3887
+ Scroll the page or a specific scrollable container.
3127
3888
 
3128
3889
  args:
3129
- <direction> up, down, top, or bottom (default: down)
3890
+ [direction] up, down, top, or bottom (default: down)
3130
3891
 
3131
3892
  flags:
3132
- --full Show complete snapshot without truncation
3893
+ --uid @<uid> Scroll the element referenced by a fresh snapshot uid
3894
+ --selector <css> Scroll the first element matching a CSS selector
3895
+ --amount <px> Scroll distance in pixels for up/down (default: 500)
3896
+ --wheel Also dispatch a synthetic DOM WheelEvent (isTrusted=false;
3897
+ for widgets requiring trusted native wheel input, focus and
3898
+ use \`press PageDown\`/\`ArrowDown\` or use computer-use-axi)
3899
+ --full Show complete snapshot without truncation
3133
3900
 
3134
3901
  examples:
3135
3902
  chrome-devtools-axi scroll down
3903
+ chrome-devtools-axi scroll down --selector ".virtual-list" --amount 300 --wheel
3136
3904
  chrome-devtools-axi scroll top --full`,
3137
3905
  back: `usage: chrome-devtools-axi back [--full]
3138
3906
  Navigate back in browser history.
@@ -3143,16 +3911,22 @@ flags:
3143
3911
  examples:
3144
3912
  chrome-devtools-axi back
3145
3913
  chrome-devtools-axi back --full`,
3146
- wait: `usage: chrome-devtools-axi wait <ms|text>
3147
- Wait for a duration or for text to appear on the page.
3914
+ wait: `usage: chrome-devtools-axi wait <ms|text> [--visible] [--absent] [--timeout <ms>]
3915
+ Wait for a duration, for text to appear, or for text to disappear from the page.
3148
3916
 
3149
3917
  args:
3150
- <ms> Milliseconds to wait (numeric)
3151
- <text> Text to wait for (string)
3918
+ <ms> Milliseconds to wait (numeric)
3919
+ <text> Text to wait for (string)
3920
+
3921
+ flags:
3922
+ --visible Only match visible text (ignore hidden/closed dropdown DOM)
3923
+ --absent Wait until matching visible text disappears (e.g. "Loading...")
3924
+ --timeout <ms> Maximum wait duration in milliseconds (default: 30000)
3152
3925
 
3153
3926
  examples:
3154
3927
  chrome-devtools-axi wait 2000
3155
- chrome-devtools-axi wait "Submit"`,
3928
+ chrome-devtools-axi wait "Saved" --visible --timeout 15000
3929
+ chrome-devtools-axi wait "Loading..." --absent --timeout 30000`,
3156
3930
  eval: `usage: chrome-devtools-axi eval <js>
3157
3931
  Evaluate a JavaScript expression in the page context and return the result.
3158
3932
  A bare expression is wrapped as () => (<js>); pass a function (arrow or
@@ -3181,14 +3955,18 @@ script API (available as global \`page\`):
3181
3955
  await page.snapshot() Get the generation-tagged accessibility tree
3182
3956
  await page.wait(ms) Wait by duration
3183
3957
  await page.wait(selector) Wait for CSS selector (30s timeout)
3184
- await page.wait(selector, ms) Wait for CSS selector with timeout
3958
+ await page.wait(selector, opts) Wait with timeout ms or { timeout, visible, absent }
3185
3959
  await page.click("@uid") Click an element by fresh ref
3186
- await page.click(selector) Click via CSS selector
3960
+ await page.click(selector) Click via CSS selector (checks visibility/disabled)
3187
3961
  await page.fill("@uid", text) Fill a form field by fresh ref
3188
3962
  await page.fill(selector, text) Fill via CSS selector, including controlled fields
3189
3963
  await page.type(text) Type at the focused element
3190
3964
  await page.press(key) Press a keyboard key
3191
3965
  await page.back() Navigate back
3966
+ await page.dialog(action, text?) Accept or dismiss an open JS dialog
3967
+ await page.network(opts?) List network requests (supports includePreservedRequests)
3968
+ await page.networkGet(id?, opts?) Inspect a specific network request/response
3969
+ await page.scroll(target?, opts?) Scroll window or container (supports { amount, direction, wheel })
3192
3970
 
3193
3971
  click and fill accept either @uid refs (from snapshot) or CSS selectors. UID actions verify that the page has not mutated since the snapshot and fail with STALE_REF when freshness cannot be confirmed, including for legacy untagged refs.
3194
3972
  page.eval accepts functions, arrow functions, and bare expression strings; no-arg IIFE strings are unwrapped automatically.
@@ -3376,7 +4154,7 @@ args:
3376
4154
 
3377
4155
  examples:
3378
4156
  chrome-devtools-axi console-get 3`,
3379
- network: `usage: chrome-devtools-axi network [--type <type>] [--limit <n>] [--page <n>]
4157
+ network: `usage: chrome-devtools-axi network [--type <type>] [--limit <n>] [--page <n>] [--preserved] [--full]
3380
4158
  List network requests for the current page.
3381
4159
 
3382
4160
  flags:
@@ -3388,12 +4166,14 @@ flags:
3388
4166
  ("all" or omitted returns every request.)
3389
4167
  --limit <n> Maximum requests to return
3390
4168
  --page <n> Page number (0-based)
4169
+ --preserved Include requests preserved across the last 3 navigations/reloads
4170
+ --full Show complete output without 2000-char truncation
3391
4171
 
3392
4172
  examples:
3393
4173
  chrome-devtools-axi network
3394
- chrome-devtools-axi network --type fetch --limit 50
4174
+ chrome-devtools-axi network --type fetch --preserved --full
3395
4175
  chrome-devtools-axi network --type all`,
3396
- "network-get": `usage: chrome-devtools-axi network-get [id] [--response-file <path>] [--request-file <path>]
4176
+ "network-get": `usage: chrome-devtools-axi network-get [id] [--response-file <path>] [--request-file <path>] [--full]
3397
4177
  Get a specific network request. If id is omitted, gets the selected request.
3398
4178
 
3399
4179
  args:
@@ -3402,11 +4182,12 @@ args:
3402
4182
  flags:
3403
4183
  --response-file <path> Save response body to file
3404
4184
  --request-file <path> Save request body to file
4185
+ --full Show complete output without 2000-char truncation
3405
4186
 
3406
4187
  Relative output paths resolve against the directory where you run the CLI.
3407
4188
 
3408
4189
  examples:
3409
- chrome-devtools-axi network-get 42
4190
+ chrome-devtools-axi network-get 42 --full
3410
4191
  chrome-devtools-axi network-get 42 --response-file ./response.json`,
3411
4192
  // Performance
3412
4193
  lighthouse: `usage: chrome-devtools-axi lighthouse [--device <device>] [--mode <mode>] [--output-dir <path>]
@@ -3510,17 +4291,21 @@ function parseScreenshotOutputPath(result) {
3510
4291
  }
3511
4292
  return match[1];
3512
4293
  }
3513
- function formatMcpResult(label, text, suggestions) {
4294
+ function formatMcpResult(label, text, suggestions, full = false, supportsFull = false) {
3514
4295
  const blocks = [];
3515
- const tr = truncateSnapshot(text, false, 2e3);
4296
+ const tr = truncateSnapshot(text, full, 2e3);
3516
4297
  blocks.push(`${label}:
3517
4298
  ${tr.text.trimEnd()}`);
4299
+ const finalSuggestions = [...suggestions];
3518
4300
  if (tr.truncated) {
3519
4301
  blocks[0] += `
3520
4302
  ... (truncated, ${tr.totalLength} chars total)`;
4303
+ if (supportsFull) {
4304
+ finalSuggestions.push("Re-run with --full to see complete output without truncation");
4305
+ }
3521
4306
  }
3522
- if (suggestions.length > 0) {
3523
- blocks.push(renderHelp(suggestions));
4307
+ if (finalSuggestions.length > 0) {
4308
+ blocks.push(renderHelp(finalSuggestions));
3524
4309
  }
3525
4310
  return renderOutput2(blocks);
3526
4311
  }
@@ -3606,10 +4391,120 @@ function parseNetworkArgs(args) {
3606
4391
  } else if (args[i] === "--page" && i + 1 < args.length) {
3607
4392
  const pageIdx = parseOptionalInteger(args[++i]);
3608
4393
  if (pageIdx !== void 0) result.pageIdx = pageIdx;
4394
+ } else if (args[i] === "--preserved") {
4395
+ result.includePreservedRequests = true;
3609
4396
  }
3610
4397
  }
3611
4398
  return result;
3612
4399
  }
4400
+ function parseStrictPositiveInteger(raw) {
4401
+ if (!raw || !/^\d+$/.test(raw)) return void 0;
4402
+ const parsed = Number(raw);
4403
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) return void 0;
4404
+ return parsed;
4405
+ }
4406
+ function parseWaitArgs(args) {
4407
+ let visible = false;
4408
+ let absent = false;
4409
+ let timeout;
4410
+ let afterDoubleDash = false;
4411
+ const positional = [];
4412
+ for (let i = 0; i < args.length; i++) {
4413
+ const a = args[i];
4414
+ if (!afterDoubleDash && a === "--") {
4415
+ afterDoubleDash = true;
4416
+ continue;
4417
+ }
4418
+ if (!afterDoubleDash && a === "--visible") {
4419
+ visible = true;
4420
+ } else if (!afterDoubleDash && a === "--absent") {
4421
+ absent = true;
4422
+ } else if (!afterDoubleDash && a === "--timeout") {
4423
+ if (i + 1 >= args.length) {
4424
+ throw new CdpError("Missing value for --timeout", "VALIDATION_ERROR", [
4425
+ "Pass a positive timeout in milliseconds, e.g. --timeout 15000"
4426
+ ]);
4427
+ }
4428
+ const rawTimeout = args[++i];
4429
+ const parsed = parseStrictPositiveInteger(rawTimeout);
4430
+ if (parsed === void 0) {
4431
+ throw new CdpError(
4432
+ `Invalid --timeout value: ${rawTimeout}`,
4433
+ "VALIDATION_ERROR",
4434
+ ["Pass a positive integer timeout in milliseconds, e.g. --timeout 15000"]
4435
+ );
4436
+ }
4437
+ timeout = parsed;
4438
+ } else {
4439
+ positional.push(a);
4440
+ }
4441
+ }
4442
+ return {
4443
+ target: positional.join(" "),
4444
+ visible,
4445
+ absent,
4446
+ ...timeout !== void 0 ? { timeout } : {}
4447
+ };
4448
+ }
4449
+ function parseScrollArgs(args) {
4450
+ let directionRaw;
4451
+ let uid;
4452
+ let selector;
4453
+ let amount = 500;
4454
+ let wheel = false;
4455
+ for (let i = 0; i < args.length; i++) {
4456
+ const a = args[i];
4457
+ if (a === "--uid") {
4458
+ if (i + 1 >= args.length) {
4459
+ throw new CdpError("Missing value for --uid", "VALIDATION_ERROR", [
4460
+ "Pass a fresh snapshot ref, e.g. --uid @g1:12"
4461
+ ]);
4462
+ }
4463
+ uid = args[++i];
4464
+ } else if (a === "--selector") {
4465
+ if (i + 1 >= args.length) {
4466
+ throw new CdpError("Missing value for --selector", "VALIDATION_ERROR", [
4467
+ 'Pass a CSS selector, e.g. --selector ".virtual-list"'
4468
+ ]);
4469
+ }
4470
+ selector = args[++i];
4471
+ } else if (a === "--amount") {
4472
+ if (i + 1 >= args.length) {
4473
+ throw new CdpError("Missing value for --amount", "VALIDATION_ERROR", [
4474
+ "Pass a positive scroll amount in pixels, e.g. --amount 300"
4475
+ ]);
4476
+ }
4477
+ const rawAmount = args[++i];
4478
+ const parsed = parseStrictPositiveInteger(rawAmount);
4479
+ if (parsed === void 0) {
4480
+ throw new CdpError(
4481
+ `Invalid --amount value: ${rawAmount}`,
4482
+ "VALIDATION_ERROR",
4483
+ ["Pass a positive integer scroll amount in pixels, e.g. --amount 300"]
4484
+ );
4485
+ }
4486
+ amount = parsed;
4487
+ } else if (a === "--wheel") {
4488
+ wheel = true;
4489
+ } else if (!a.startsWith("--")) {
4490
+ directionRaw = a.toLowerCase();
4491
+ }
4492
+ }
4493
+ const direction = directionRaw ?? "down";
4494
+ if (direction !== "up" && direction !== "down" && direction !== "top" && direction !== "bottom") {
4495
+ throw new CdpError(`Unknown scroll direction: ${direction}`, "VALIDATION_ERROR", [
4496
+ "Run `chrome-devtools-axi scroll down` \u2014 directions: up, down, top, bottom"
4497
+ ]);
4498
+ }
4499
+ if (uid && selector) {
4500
+ throw new CdpError(
4501
+ "Specify at most one of --uid or --selector for scroll",
4502
+ "VALIDATION_ERROR",
4503
+ ["Use either `--uid @<uid>` or `--selector <css>`"]
4504
+ );
4505
+ }
4506
+ return { direction, uid, selector, amount, wheel };
4507
+ }
3613
4508
  function parseNetworkGetArgs(args) {
3614
4509
  const result = {};
3615
4510
  for (let i = 0; i < args.length; i++) {
@@ -3894,14 +4789,64 @@ async function handleType(args, full) {
3894
4789
  return formatPageOutput(snapshot, "type", void 0, full);
3895
4790
  }
3896
4791
  async function handleScroll(args, full) {
3897
- const dir = (args[0] ?? "down").toLowerCase();
3898
- const fn = SCROLL_FUNCTIONS[dir];
3899
- if (!fn) {
3900
- throw new CdpError(`Unknown scroll direction: ${dir}`, "VALIDATION_ERROR", [
3901
- "Run `chrome-devtools-axi scroll down` \u2014 directions: up, down, top, bottom"
3902
- ]);
4792
+ const parsed = parseScrollArgs(args);
4793
+ const { direction, uid, selector, amount, wheel } = parsed;
4794
+ const deltaY = direction === "up" ? -amount : amount;
4795
+ if (!uid && !selector && !wheel && amount === 500) {
4796
+ await callTool("evaluate_script", { function: SCROLL_FUNCTIONS[direction] });
4797
+ } else if (uid) {
4798
+ const freshUid = await parseUidFresh2(uid);
4799
+ await callTool("evaluate_script", {
4800
+ args: [freshUid],
4801
+ function: `(el) => {
4802
+ if (!el) throw new Error('Scroll target not found');
4803
+ const dir = ${JSON.stringify(direction)};
4804
+ const deltaY = ${JSON.stringify(deltaY)};
4805
+ let handledByWheel = false;
4806
+ if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
4807
+ handledByWheel = !el.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
4808
+ }
4809
+ if (handledByWheel) return;
4810
+ if (dir === 'top') el.scrollTop = 0;
4811
+ else if (dir === 'bottom') el.scrollTop = el.scrollHeight;
4812
+ else el.scrollBy(0, deltaY);
4813
+ }`
4814
+ });
4815
+ } else if (selector) {
4816
+ const sel = JSON.stringify(selector);
4817
+ await callTool("evaluate_script", {
4818
+ function: `() => {
4819
+ const el = document.querySelector(${sel});
4820
+ if (!el) throw new Error('Scroll target not found: ' + ${sel});
4821
+ const dir = ${JSON.stringify(direction)};
4822
+ const deltaY = ${JSON.stringify(deltaY)};
4823
+ let handledByWheel = false;
4824
+ if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
4825
+ handledByWheel = !el.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
4826
+ }
4827
+ if (handledByWheel) return;
4828
+ if (dir === 'top') el.scrollTop = 0;
4829
+ else if (dir === 'bottom') el.scrollTop = el.scrollHeight;
4830
+ else el.scrollBy(0, deltaY);
4831
+ }`
4832
+ });
4833
+ } else {
4834
+ await callTool("evaluate_script", {
4835
+ function: `() => {
4836
+ const dir = ${JSON.stringify(direction)};
4837
+ const deltaY = ${JSON.stringify(deltaY)};
4838
+ let handledByWheel = false;
4839
+ if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
4840
+ const target = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2) || document.documentElement;
4841
+ handledByWheel = !target.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
4842
+ }
4843
+ if (handledByWheel) return;
4844
+ if (dir === 'top') window.scrollTo(0, 0);
4845
+ else if (dir === 'bottom') window.scrollTo(0, document.documentElement.scrollHeight || document.body.scrollHeight);
4846
+ else window.scrollBy(0, deltaY);
4847
+ }`
4848
+ });
3903
4849
  }
3904
- await callTool("evaluate_script", { function: fn });
3905
4850
  const snapshot = await stampFresh();
3906
4851
  return formatPageOutput(snapshot, "scroll", void 0, full);
3907
4852
  }
@@ -3911,33 +4856,87 @@ async function handleBack(full) {
3911
4856
  return formatPageOutput(snapshot, "back", void 0, full);
3912
4857
  }
3913
4858
  async function handleWait(args) {
3914
- const target = args[0];
4859
+ const { target, visible, absent, timeout } = parseWaitArgs(args);
3915
4860
  if (!target) {
3916
4861
  throw new CdpError(
3917
4862
  "Missing wait target (milliseconds or text)",
3918
4863
  "VALIDATION_ERROR",
3919
4864
  [
3920
4865
  "Run `chrome-devtools-axi wait 2000` to wait 2 seconds",
3921
- 'Run `chrome-devtools-axi wait "Submit"` to wait for text to appear'
4866
+ 'Run `chrome-devtools-axi wait "Submit" --visible` to wait for visible text to appear',
4867
+ 'Run `chrome-devtools-axi wait "Loading..." --absent` to wait for loading text to disappear'
3922
4868
  ]
3923
4869
  );
3924
4870
  }
3925
- const isNumeric = /^\d+$/.test(target);
4871
+ const isNumeric = !absent && !visible && /^\d+$/.test(target);
3926
4872
  if (isNumeric) {
3927
4873
  await callTool("evaluate_script", {
3928
4874
  function: wrapJsExpression(`new Promise(r => setTimeout(r, ${target}))`)
3929
4875
  });
4876
+ } else if (absent) {
4877
+ const ms = timeout ?? 3e4;
4878
+ const normalizedNeedle = stripZeroWidth(target).replace(/\s+/g, " ").trim();
4879
+ if (normalizedNeedle.length === 0) {
4880
+ throw new CdpError(
4881
+ "Wait --absent target must contain visible non-whitespace characters",
4882
+ "VALIDATION_ERROR",
4883
+ ['Run `chrome-devtools-axi wait "Loading..." --absent`']
4884
+ );
4885
+ }
4886
+ const needle = JSON.stringify(normalizedNeedle);
4887
+ await callTool("evaluate_script", {
4888
+ waitForStableDom: false,
4889
+ function: `() => new Promise((resolve, reject) => {
4890
+ const needle = ${needle};
4891
+ const normalize = (s) => String(s || '').replace(/[\\u200B-\\u200D\\u2060\\uFEFF]/g, '').replace(/\\s+/g, ' ').trim();
4892
+ const hasVisibleText = () => {
4893
+ const root = document.body || document.documentElement;
4894
+ if (!root) return false;
4895
+ const visibleText = normalize(root.innerText || '');
4896
+ return needle.length > 0 && visibleText.includes(needle);
4897
+ };
4898
+ if (!hasVisibleText()) { resolve(true); return; }
4899
+ const root = document.documentElement || document;
4900
+ const finish = () => {
4901
+ observer.disconnect();
4902
+ clearInterval(poll);
4903
+ clearTimeout(timer);
4904
+ resolve(true);
4905
+ };
4906
+ const observer = new MutationObserver(() => {
4907
+ if (!hasVisibleText()) finish();
4908
+ });
4909
+ const poll = setInterval(() => {
4910
+ if (!hasVisibleText()) finish();
4911
+ }, 100);
4912
+ const timer = setTimeout(() => {
4913
+ observer.disconnect();
4914
+ clearInterval(poll);
4915
+ reject(new Error('Timeout waiting for text to disappear: ' + needle));
4916
+ }, ${ms});
4917
+ observer.observe(root, { childList: true, subtree: true, attributes: true, characterData: true });
4918
+ })`
4919
+ });
3930
4920
  } else {
3931
- await callTool("wait_for", { text: [target] });
4921
+ const toolArgs = { text: [target] };
4922
+ if (visible) toolArgs.visible = true;
4923
+ if (timeout !== void 0) toolArgs.timeout = timeout;
4924
+ await callTool("wait_for", toolArgs);
3932
4925
  }
3933
4926
  const blocks = [];
3934
- blocks.push(encode({ waited: target }));
4927
+ blocks.push(
4928
+ encode({
4929
+ waited: target,
4930
+ ...visible ? { visible: true } : {},
4931
+ ...absent ? { absent: true } : {}
4932
+ })
4933
+ );
3935
4934
  const suggestions = getSuggestions({ command: "wait" });
3936
4935
  if (suggestions.length > 0) blocks.push(renderHelp(suggestions));
3937
4936
  return renderOutput2(blocks);
3938
4937
  }
3939
4938
  function parseEvalResult(output) {
3940
- const jsonBlock = output.match(/```json\n([\s\S]*?)\n```/);
4939
+ const jsonBlock = output.match(/```json\r?\n([\s\S]*?)\r?\n```(?:\r?\n|$)/);
3941
4940
  if (jsonBlock) return jsonBlock[1].trim();
3942
4941
  const preamble = "Script ran on page and returned:";
3943
4942
  if (output.includes(preamble))
@@ -3978,6 +4977,7 @@ function formatStopOutput(outcome) {
3978
4977
  return encode({ status: outcome === "stopped" ? "stopped" : "stopped (no-op)" });
3979
4978
  }
3980
4979
  async function handleStop() {
4980
+ await tryCleanupSessionObserver();
3981
4981
  const outcome = await stopBridge();
3982
4982
  return formatStopOutput(outcome);
3983
4983
  }
@@ -3992,12 +4992,17 @@ async function handlePages() {
3992
4992
  const rows = pages.map((p) => ` ${p.id},${p.url},${p.selected}`);
3993
4993
  blocks.push(`${header}
3994
4994
  ${rows.join("\n")}`);
3995
- blocks.push(
3996
- renderHelp([
3997
- "Run `chrome-devtools-axi selectpage <id>` to switch tabs",
3998
- "Run `chrome-devtools-axi newpage <url>` to open a new tab"
3999
- ])
4000
- );
4995
+ const help = [
4996
+ "Run `chrome-devtools-axi selectpage <id>` to switch tabs",
4997
+ "Run `chrome-devtools-axi newpage <url>` to open a new tab"
4998
+ ];
4999
+ if (/^# Open dialog\b/m.test(result)) {
5000
+ blocks.push(encode({ dialog: "pending" }));
5001
+ help.unshift(
5002
+ "A JavaScript dialog is open \u2014 run `chrome-devtools-axi dialog accept` or `chrome-devtools-axi dialog dismiss` before page actions"
5003
+ );
5004
+ }
5005
+ blocks.push(renderHelp(help));
4001
5006
  return renderOutput2(blocks);
4002
5007
  }
4003
5008
  async function handleNewPage(args, full) {
@@ -4146,7 +5151,19 @@ async function handleDialog(args) {
4146
5151
  const params = { action };
4147
5152
  const promptText = args.slice(1).join(" ");
4148
5153
  if (promptText) params.promptText = promptText;
4149
- const snapshot = await callWithSnapshot("handle_dialog", params);
5154
+ const result = await callTool("handle_dialog", params);
5155
+ if (/^# Open dialog\b/m.test(result)) {
5156
+ const dialogMatch = result.match(/^# Open dialog[\s\S]*$/m);
5157
+ const blocks = [
5158
+ encode({ dialog: action, nextDialogPending: true }),
5159
+ ...dialogMatch ? [dialogMatch[0].trim()] : [],
5160
+ renderHelp([
5161
+ "Another dialog opened immediately \u2014 run `chrome-devtools-axi dialog accept` or `chrome-devtools-axi dialog dismiss` again"
5162
+ ])
5163
+ ];
5164
+ return renderOutput2(blocks);
5165
+ }
5166
+ const snapshot = await stampFresh();
4150
5167
  return encode({ dialog: action }) + "\n" + formatPageOutput(snapshot, "dialog");
4151
5168
  }
4152
5169
  async function handleUpload(args, full) {
@@ -4199,15 +5216,21 @@ async function handleConsoleGet(args) {
4199
5216
  const result = await callTool("get_console_message", { msgid });
4200
5217
  return formatMcpResult("message", result, []);
4201
5218
  }
4202
- async function handleNetwork(args) {
5219
+ async function handleNetwork(args, full) {
4203
5220
  const parsed = parseNetworkArgs(args);
4204
5221
  const result = await callTool("list_network_requests", parsed);
4205
- return formatMcpResult("network", result, [
4206
- "Run `chrome-devtools-axi network-get <id>` to see request details",
4207
- "Run `chrome-devtools-axi network --type fetch` to filter by type"
4208
- ]);
5222
+ return formatMcpResult(
5223
+ "network",
5224
+ result,
5225
+ [
5226
+ "Run `chrome-devtools-axi network-get <id> --full` to see request/response details",
5227
+ "Run `chrome-devtools-axi network --type fetch --preserved --full` to inspect preserved requests across reloads"
5228
+ ],
5229
+ full,
5230
+ true
5231
+ );
4209
5232
  }
4210
- async function handleNetworkGet(args) {
5233
+ async function handleNetworkGet(args, full) {
4211
5234
  const parsed = parseNetworkGetArgs(args);
4212
5235
  const toolArgs = { ...parsed };
4213
5236
  if (toolArgs.responseFilePath) {
@@ -4217,7 +5240,7 @@ async function handleNetworkGet(args) {
4217
5240
  toolArgs.requestFilePath = resolveOutputPath(toolArgs.requestFilePath);
4218
5241
  }
4219
5242
  const result = await callTool("get_network_request", toolArgs);
4220
- return formatMcpResult("request", result, []);
5243
+ return formatMcpResult("request", result, [], full, true);
4221
5244
  }
4222
5245
  async function handleLighthouse(args) {
4223
5246
  const opts = parseLighthouseArgs(args);
@@ -4334,6 +5357,7 @@ function validateCommandFlags(command, args, allowedFlags, valueFlags, dashPosit
4334
5357
  let positionalArgs = 0;
4335
5358
  for (let i = 0; i < args.length; i++) {
4336
5359
  const arg = args[i];
5360
+ if (arg === "--") return;
4337
5361
  if (positionalArgs === positionalArgsBeforeText) return;
4338
5362
  if (arg === "--help" || allowedFlags.includes(arg)) {
4339
5363
  if (valueFlags.includes(arg)) i += 1;
@@ -4375,8 +5399,8 @@ var COMMAND_HANDLERS = {
4375
5399
  emulate: withoutFullFlag(handleEmulate),
4376
5400
  console: withoutFullFlag(handleConsole),
4377
5401
  "console-get": withoutFullFlag(handleConsoleGet),
4378
- network: withoutFullFlag(handleNetwork),
4379
- "network-get": withoutFullFlag(handleNetworkGet),
5402
+ network: withFullFlag(handleNetwork),
5403
+ "network-get": withFullFlag(handleNetworkGet),
4380
5404
  lighthouse: withoutFullFlag(handleLighthouse),
4381
5405
  "perf-start": withoutFullFlag(handlePerfStart),
4382
5406
  "perf-stop": withoutFullFlag(handlePerfStop),
@@ -4394,9 +5418,9 @@ var COMMAND_FLAGS = {
4394
5418
  fill: ["--full"],
4395
5419
  type: ["--full"],
4396
5420
  press: ["--full"],
4397
- scroll: ["--full"],
5421
+ scroll: ["--full", "--uid", "--selector", "--amount", "--wheel"],
4398
5422
  back: ["--full"],
4399
- wait: [],
5423
+ wait: ["--visible", "--absent", "--timeout"],
4400
5424
  eval: ["--full"],
4401
5425
  run: ["--page-id"],
4402
5426
  hover: ["--full"],
@@ -4419,8 +5443,8 @@ var COMMAND_FLAGS = {
4419
5443
  ],
4420
5444
  console: ["--type", "--limit", "--page"],
4421
5445
  "console-get": [],
4422
- network: ["--type", "--limit", "--page"],
4423
- "network-get": ["--response-file", "--request-file"],
5446
+ network: ["--type", "--limit", "--page", "--preserved", "--full"],
5447
+ "network-get": ["--response-file", "--request-file", "--full"],
4424
5448
  lighthouse: ["--device", "--mode", "--output-dir"],
4425
5449
  "perf-start": ["--no-reload", "--no-auto-stop", "--file"],
4426
5450
  "perf-stop": ["--file"],
@@ -4433,10 +5457,12 @@ var COMMAND_FLAGS = {
4433
5457
  var COMMAND_VALUE_FLAGS = {
4434
5458
  run: ["--page-id"],
4435
5459
  screenshot: ["--uid", "--format"],
5460
+ scroll: ["--uid", "--selector", "--amount"],
5461
+ wait: ["--timeout"],
4436
5462
  emulate: COMMAND_FLAGS.emulate,
4437
5463
  console: COMMAND_FLAGS.console,
4438
- network: COMMAND_FLAGS.network,
4439
- "network-get": COMMAND_FLAGS["network-get"],
5464
+ network: ["--type", "--limit", "--page"],
5465
+ "network-get": ["--response-file", "--request-file"],
4440
5466
  lighthouse: COMMAND_FLAGS.lighthouse,
4441
5467
  "perf-start": ["--file"],
4442
5468
  "perf-stop": COMMAND_FLAGS["perf-stop"]
@@ -4444,14 +5470,14 @@ var COMMAND_VALUE_FLAGS = {
4444
5470
  var COMMAND_POSITIONAL_TEXT_START = {
4445
5471
  fill: 1,
4446
5472
  type: 0,
4447
- wait: 0,
4448
5473
  eval: 0,
4449
5474
  dialog: 1
4450
5475
  };
4451
5476
  var COMMAND_DASH_POSITIONAL_SLOTS = {
4452
5477
  heap: [0],
4453
5478
  upload: [1],
4454
- screenshot: [0]
5479
+ screenshot: [0],
5480
+ wait: [0]
4455
5481
  };
4456
5482
  var COMMANDS = Object.fromEntries(
4457
5483
  Object.entries(COMMAND_HANDLERS).map(([command, handler]) => [
@@ -4504,7 +5530,9 @@ export {
4504
5530
  parsePagesList,
4505
5531
  parsePerfStartArgs,
4506
5532
  parseScreenshotArgs,
5533
+ parseScrollArgs,
4507
5534
  parseUid,
4508
5535
  parseUidFresh2 as parseUidFresh,
5536
+ parseWaitArgs,
4509
5537
  wrapJsExpression
4510
5538
  };