@cydm/pie 4.7.0 → 4.9.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.
Files changed (49) hide show
  1. package/README.md +51 -27
  2. package/dist/builtin/extensions/ask-user/index.js +4 -4
  3. package/dist/builtin/extensions/cron/index.js +916 -162
  4. package/dist/builtin/extensions/im-forward/README.md +24 -7
  5. package/dist/builtin/extensions/im-forward/index.js +6823 -3683
  6. package/dist/builtin/extensions/memory/index.js +76 -28
  7. package/dist/builtin/extensions/pie-ipc/README.md +2 -2
  8. package/dist/builtin/extensions/pie-ipc/index.js +421 -27
  9. package/dist/builtin/extensions/pie-proc/README.md +7 -7
  10. package/dist/builtin/extensions/pie-proc/index.js +453 -97
  11. package/dist/builtin/extensions/plan-mode/index.js +5 -5
  12. package/dist/builtin/extensions/subagent/index.js +8 -8
  13. package/dist/builtin/extensions/todo/index.js +4 -4
  14. package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +35 -24
  15. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +391 -123
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chunk-HAUDUMDO.js +795 -0
  18. package/dist/builtin/skills/chrome-devtools-axi/{cli-NLPMVDGG.js → cli-K7ESY3XD.js} +1437 -231
  19. package/dist/builtin/skills/computer-use-axi/SKILL.md +26 -8
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +465 -83
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +75 -22
  22. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
  23. package/dist/chunks/{chunk-3W3SXVPB.js → chunk-4UIUMTHG.js} +993 -371
  24. package/dist/chunks/chunk-6WKBQZWM.js +19 -0
  25. package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BA4Z27XT.js} +4 -3
  26. package/dist/chunks/{chunk-BLDI2GRF.js → chunk-DBDU3RRN.js} +1364 -446
  27. package/dist/chunks/{chunk-LAJXWOKS.js → chunk-EEC5PJTC.js} +11 -9
  28. package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
  29. package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-LRHNAG4V.js} +349 -288
  30. package/dist/chunks/chunk-OU33ROFD.js +717 -0
  31. package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-PN6B54VT.js} +104 -22
  32. package/dist/chunks/{chunk-NHV2CALB.js → chunk-WYXUF4MP.js} +388 -32
  33. package/dist/chunks/{chunk-4PR34UZF.js → chunk-Z5KL6AO2.js} +159 -145
  34. package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-RASJSVZY.js} +1 -1
  35. package/dist/chunks/{manager-cli-NEZA46M5.js → manager-cli-Y6HM3MHA.js} +5 -5
  36. package/dist/chunks/{model-registry-3XAHXXTA.js → model-registry-5TLYILYR.js} +2 -2
  37. package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-VPKDBV23.js} +5 -5
  38. package/dist/chunks/{src-B44QWSGM.js → src-2XI5P62J.js} +2 -2
  39. package/dist/chunks/{src-EGXFJ3WA.js → src-6QGGDHIW.js} +3 -3
  40. package/dist/chunks/{src-Q7LU27C2.js → src-CCEENRKC.js} +31 -1
  41. package/dist/chunks/{src-CLE5ILN4.js → src-DI4MCAGT.js} +20 -4
  42. package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-SYVWIPPW.js} +2 -2
  43. package/dist/cli.js +1918 -1489
  44. package/models.schema.json +271 -0
  45. package/package.json +2 -2
  46. package/dist/builtin/skills/chrome-devtools-axi/chunk-WOGAQ4P5.js +0 -399
  47. package/dist/chunks/chunk-7UAUDXZW.js +0 -1425
  48. package/dist/chunks/{chunk-CGSFBWOM.js → chunk-WBL73KRI.js} +3 -3
  49. package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
@@ -4,23 +4,30 @@ import {
4
4
  } from "./chunk-42SGITKJ.js";
5
5
  import {
6
6
  BRIDGE_PORT_IN_USE_EXIT_CODE,
7
+ DEFAULT_SESSION_NAME,
7
8
  PAGE_IDENTITY_CHANGED_ERROR,
9
+ cleanupOwnedProfileDir,
10
+ clearAllocatedSessionPort,
8
11
  clearSelectedPageId,
12
+ computeTransportModeFingerprint,
9
13
  createdPageIdFromPageLists,
10
14
  getSelectedPageId,
11
15
  inspectProcessIdentity,
16
+ isAutoConnectMode,
12
17
  needsPageId,
13
18
  overlaySessionSelected,
14
19
  parsePagesList,
15
- readSelfStartTime,
16
20
  rememberToolRouting,
17
21
  resolveBridgeScript,
22
+ resolveSessionLogFile,
18
23
  resolveSessionName,
19
24
  resolveSessionPidFile,
20
25
  resolveSessionPort,
26
+ resolveSessionStartLockFile,
21
27
  resolveSessionStateDir,
22
- setSelectedPageId
23
- } from "./chunk-WOGAQ4P5.js";
28
+ setSelectedPageId,
29
+ writeAllocatedSessionPort
30
+ } from "./chunk-HAUDUMDO.js";
24
31
  import "./chunk-OJ6N23UZ.js";
25
32
 
26
33
  // ../../node_modules/chrome-devtools-axi/node_modules/@toon-format/toon/dist/index.mjs
@@ -1618,13 +1625,48 @@ function installSessionStartHooks(options = {}) {
1618
1625
 
1619
1626
  // vendor/chrome-devtools-axi/src/client.ts
1620
1627
  import { execFileSync, spawn as spawn2 } from "node:child_process";
1621
- import { readFileSync as readFileSync3, existsSync as existsSync3, unlinkSync } from "node:fs";
1628
+ import { randomUUID } from "node:crypto";
1629
+ import {
1630
+ closeSync,
1631
+ existsSync as existsSync3,
1632
+ mkdirSync as mkdirSync2,
1633
+ openSync,
1634
+ readFileSync as readFileSync3,
1635
+ statSync as statSync2,
1636
+ unlinkSync,
1637
+ writeFileSync as writeFileSync2
1638
+ } from "node:fs";
1622
1639
  import { request } from "node:http";
1640
+ import { createServer as createNetServer } from "node:net";
1623
1641
  import { dirname as dirname3 } from "node:path";
1642
+
1643
+ // vendor/chrome-devtools-axi/src/page-observer-script.ts
1644
+ var PAGE_GENERATION_KEY = "__chromeDevtoolsAxiSnapshotGeneration";
1645
+ var CLEANUP_OBSERVER_SCRIPT = `() => {
1646
+ const key = ${JSON.stringify(PAGE_GENERATION_KEY)};
1647
+ const previous = globalThis[key];
1648
+ if (previous && previous.observer) {
1649
+ try { previous.observer.disconnect(); } catch {}
1650
+ }
1651
+ try { delete globalThis[key]; } catch { globalThis[key] = undefined; }
1652
+ return true;
1653
+ }`;
1654
+
1655
+ // vendor/chrome-devtools-axi/src/client.ts
1624
1656
  var DEFAULT_BRIDGE_TIMEOUT_MS = 3e4;
1657
+ var DEFAULT_APPROVAL_TIMEOUT_MS = 65e3;
1625
1658
  var MIN_BRIDGE_TIMEOUT_MS = 1e3;
1626
1659
  var HEALTH_TIMEOUT_MS = 2e3;
1627
1660
  var DEEP_HEALTH_TIMEOUT_MS = 5e3;
1661
+ var MAX_BRIDGE_LOG_BYTES = 1048576;
1662
+ var START_LOCK_STALE_MS = 15e3;
1663
+ function resolveApprovalTimeoutMs() {
1664
+ const raw = process.env.CHROME_DEVTOOLS_AXI_APPROVAL_TIMEOUT_MS;
1665
+ if (!raw) return DEFAULT_APPROVAL_TIMEOUT_MS;
1666
+ const parsed = Number.parseInt(raw, 10);
1667
+ if (Number.isNaN(parsed) || parsed <= 0) return DEFAULT_APPROVAL_TIMEOUT_MS;
1668
+ return Math.max(parsed, MIN_BRIDGE_TIMEOUT_MS);
1669
+ }
1628
1670
  function resolveBridgeTimeoutMs() {
1629
1671
  const raw = process.env.CHROME_DEVTOOLS_AXI_BRIDGE_TIMEOUT_MS;
1630
1672
  if (!raw) return DEFAULT_BRIDGE_TIMEOUT_MS;
@@ -1662,19 +1704,16 @@ function isProcessAlive(pid) {
1662
1704
  return error?.code !== "ESRCH";
1663
1705
  }
1664
1706
  }
1665
- var cachedLauncherHeader;
1666
1707
  function launcherHeader() {
1667
- cachedLauncherHeader ??= (() => {
1668
- const pid = process.env.PIE_SUPERVISOR_PID?.trim();
1669
- if (pid && Number.isInteger(Number(pid)) && Number(pid) > 0) {
1670
- const startTime = process.env.PIE_SUPERVISOR_START_TIME?.trim() ?? "";
1671
- return `${pid}:${startTime}`;
1672
- }
1673
- return `${process.pid}:${readSelfStartTime() ?? ""}`;
1674
- })();
1675
- return cachedLauncherHeader;
1708
+ const pid = process.env.PIE_SUPERVISOR_PID?.trim();
1709
+ if (pid && /^\d+$/.test(pid) && Number(pid) > 0) {
1710
+ const startTime = process.env.PIE_SUPERVISOR_START_TIME?.trim() ?? "";
1711
+ return `${pid}:${startTime}`;
1712
+ }
1713
+ return void 0;
1676
1714
  }
1677
- function httpGet(port, path, timeoutMs = 2e3) {
1715
+ function httpGetWithStatus(port, path, timeoutMs = 2e3) {
1716
+ const launcher = launcherHeader();
1678
1717
  return new Promise((resolve3, reject) => {
1679
1718
  const req = request(
1680
1719
  {
@@ -1683,15 +1722,16 @@ function httpGet(port, path, timeoutMs = 2e3) {
1683
1722
  path,
1684
1723
  method: "GET",
1685
1724
  timeout: timeoutMs,
1686
- // Identify this launcher to the bridge so it can supervise our
1687
- // liveness and reap its detached tree when we die (leak fix).
1688
- headers: { "x-axi-launcher": launcherHeader() }
1725
+ ...launcher ? { headers: { "x-axi-launcher": launcher } } : {}
1689
1726
  },
1690
1727
  (res) => {
1691
1728
  res.setEncoding("utf8");
1692
1729
  let data = "";
1693
1730
  res.on("data", (chunk) => data += chunk);
1694
- res.on("end", () => resolve3(data));
1731
+ res.on(
1732
+ "end",
1733
+ () => resolve3({ statusCode: res.statusCode ?? 0, body: data })
1734
+ );
1695
1735
  }
1696
1736
  );
1697
1737
  req.on("error", reject);
@@ -1702,6 +1742,9 @@ function httpGet(port, path, timeoutMs = 2e3) {
1702
1742
  req.end();
1703
1743
  });
1704
1744
  }
1745
+ function httpGet(port, path, timeoutMs = 2e3) {
1746
+ return httpGetWithStatus(port, path, timeoutMs).then((r) => r.body);
1747
+ }
1705
1748
  function httpPost(port, path, body, timeoutMs = 12e4) {
1706
1749
  return new Promise((resolve3, reject) => {
1707
1750
  const payload = JSON.stringify(body);
@@ -1739,24 +1782,93 @@ function httpPost(port, path, body, timeoutMs = 12e4) {
1739
1782
  req.end();
1740
1783
  });
1741
1784
  }
1742
- async function checkBridgeHealth(port, opts = {}) {
1785
+ async function probeBridgeHealth(port, opts = {}) {
1743
1786
  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;
1787
+ if (opts.deep && opts.expectedMode !== void 0) {
1788
+ const preflight = await probeBridgeHealth(port, {
1789
+ deep: false,
1790
+ expectedSession: opts.expectedSession,
1791
+ expectedMode: opts.expectedMode
1792
+ });
1793
+ if (preflight.kind !== "ok" && preflight.kind !== "pending") {
1794
+ return preflight;
1795
+ }
1796
+ }
1797
+ const params = new URLSearchParams();
1798
+ if (opts.deep) {
1799
+ params.set("deep", "1");
1800
+ if (opts.waitMs !== void 0) {
1801
+ params.set("waitMs", String(opts.waitMs));
1802
+ }
1803
+ }
1804
+ if (opts.expectedMode !== void 0) {
1805
+ params.set("mode", opts.expectedMode);
1806
+ }
1807
+ const query = params.toString();
1808
+ const path = query.length > 0 ? `/health?${query}` : "/health";
1809
+ const timeoutMs = opts.deep ? Math.max(DEEP_HEALTH_TIMEOUT_MS, (opts.waitMs ?? 0) + 2500) : HEALTH_TIMEOUT_MS;
1810
+ const { statusCode, body } = await httpGetWithStatus(port, path, timeoutMs);
1811
+ const data = JSON.parse(body);
1749
1812
  if (opts.expectedSession !== void 0 && typeof data.session === "string" && data.session !== opts.expectedSession) {
1750
- return false;
1813
+ return {
1814
+ kind: "unreachable",
1815
+ reason: `session mismatch (expected ${opts.expectedSession}, got ${data.session})`
1816
+ };
1751
1817
  }
1752
- if (opts.deep && opts.notice) {
1753
- opts.notice.pageIdentityChanged = data.pageIdentityChanged === true;
1818
+ if (opts.expectedMode !== void 0 && (typeof data.mode !== "string" || data.mode !== opts.expectedMode)) {
1819
+ return {
1820
+ kind: "mode_mismatch",
1821
+ runningMode: typeof data.mode === "string" && data.mode.length > 0 ? data.mode : "unknown (legacy bridge)",
1822
+ busy: data.busy === true,
1823
+ ...typeof data.pid === "number" && data.pid > 0 ? { pid: data.pid } : {}
1824
+ };
1754
1825
  }
1755
- return true;
1756
- } catch {
1757
- return false;
1826
+ if (statusCode === 202 || data.status === "pending") {
1827
+ return {
1828
+ kind: "pending",
1829
+ cdpState: typeof data.cdpState === "string" ? data.cdpState : "awaiting_approval",
1830
+ ...typeof data.pid === "number" && data.pid > 0 ? { pid: data.pid } : {},
1831
+ ...typeof data.waitingMs === "number" ? { waitingMs: data.waitingMs } : {},
1832
+ ...typeof data.logFile === "string" ? { logFile: data.logFile } : {}
1833
+ };
1834
+ }
1835
+ if (data.status === "ok" && statusCode < 400) {
1836
+ const pageIdentityChanged = data.pageIdentityChanged === true;
1837
+ if (opts.deep && opts.notice) {
1838
+ opts.notice.pageIdentityChanged = pageIdentityChanged;
1839
+ }
1840
+ return {
1841
+ kind: "ok",
1842
+ busy: data.busy === true,
1843
+ ...typeof data.mode === "string" ? { mode: data.mode } : {},
1844
+ ...typeof data.cdpState === "string" ? { cdpState: data.cdpState } : {},
1845
+ ...typeof data.dialogPending === "boolean" ? { dialogPending: data.dialogPending } : {},
1846
+ pageIdentityChanged
1847
+ };
1848
+ }
1849
+ if (statusCode === 503 && data.status === "error" && data.mcpDisconnected !== true && (typeof data.reason === "string" || data.error === "CDP target unreachable")) {
1850
+ const reason = typeof data.reason === "string" ? data.reason : typeof data.error === "string" ? data.error : "CDP target unreachable";
1851
+ return {
1852
+ kind: "cdp_error",
1853
+ reason,
1854
+ ...typeof data.cdpState === "string" ? { cdpState: data.cdpState } : {}
1855
+ };
1856
+ }
1857
+ return {
1858
+ kind: "unreachable",
1859
+ reason: `unexpected health response (HTTP ${statusCode})`
1860
+ };
1861
+ } catch (error) {
1862
+ return {
1863
+ kind: "unreachable",
1864
+ reason: error instanceof Error ? error.message : String(error)
1865
+ };
1758
1866
  }
1759
1867
  }
1868
+ async function checkBridgeHealth(port, opts = {}) {
1869
+ const probe = await probeBridgeHealth(port, opts);
1870
+ return probe.kind === "ok";
1871
+ }
1760
1872
  function sleep(ms) {
1761
1873
  return new Promise((r) => setTimeout(r, ms));
1762
1874
  }
@@ -1917,8 +2029,12 @@ async function judgeRecordedBridge(pidInfo, sessionName) {
1917
2029
  const bridge = isBridgeProcess(pidInfo.pid, pidInfo.startTime);
1918
2030
  return { terminate: bridge, killProcessGroup: bridge, targetPid: pidInfo.pid, expectedStartTime: pidInfo.startTime };
1919
2031
  }
1920
- function removePidFile(pidFile) {
2032
+ function removePidFile(pidFile, expectedPid) {
1921
2033
  try {
2034
+ if (expectedPid !== void 0) {
2035
+ const current = readPidFile(pidFile);
2036
+ if (!current || current.pid !== expectedPid) return;
2037
+ }
1922
2038
  unlinkSync(pidFile);
1923
2039
  } catch {
1924
2040
  }
@@ -1950,7 +2066,7 @@ async function terminateBridgeProcess(pid, opts = {}) {
1950
2066
  } catch (error) {
1951
2067
  if (error.code === "ESRCH") return true;
1952
2068
  }
1953
- if (await waitForProcessExit(pid, 2e3)) {
2069
+ if (await waitForProcessExit(pid, 6500)) {
1954
2070
  if (killProcessGroup) {
1955
2071
  try {
1956
2072
  process.kill(-pid, "SIGKILL");
@@ -1978,26 +2094,103 @@ async function terminateBridgeProcess(pid, opts = {}) {
1978
2094
  }
1979
2095
  return waitForProcessExit(pid, 1e3);
1980
2096
  }
2097
+ function openBridgeLogFd(sessionName) {
2098
+ try {
2099
+ const logFile = resolveSessionLogFile(sessionName);
2100
+ mkdirSync2(dirname3(logFile), { recursive: true });
2101
+ let flags = "a";
2102
+ try {
2103
+ if (existsSync3(logFile) && statSync2(logFile).size >= MAX_BRIDGE_LOG_BYTES) {
2104
+ flags = "w";
2105
+ }
2106
+ } catch {
2107
+ }
2108
+ return openSync(logFile, flags);
2109
+ } catch {
2110
+ return null;
2111
+ }
2112
+ }
1981
2113
  function spawnBridgeProcess(port, sessionName) {
1982
2114
  const bridgeScript = resolveBridgeScript(import.meta.dirname);
1983
2115
  const script = existsSync3(bridgeScript.replace(/\.js$/, ".ts")) ? bridgeScript.replace(/\.js$/, ".ts") : bridgeScript;
1984
2116
  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
2117
+ const logFd = openBridgeLogFd(sessionName);
2118
+ try {
2119
+ const child = spawn2(
2120
+ runner === "tsx" ? "npx" : "node",
2121
+ runner === "tsx" ? ["tsx", script] : [script],
2122
+ {
2123
+ stdio: logFd !== null ? ["ignore", "ignore", logFd] : "ignore",
2124
+ windowsHide: true,
2125
+ env: {
2126
+ ...process.env,
2127
+ CHROME_DEVTOOLS_AXI_PORT: String(port),
2128
+ CHROME_DEVTOOLS_AXI_SESSION: sessionName
2129
+ },
2130
+ detached: true
2131
+ }
2132
+ );
2133
+ child.unref();
2134
+ return child;
2135
+ } finally {
2136
+ if (logFd !== null) {
2137
+ try {
2138
+ closeSync(logFd);
2139
+ } catch {
2140
+ }
1997
2141
  }
2142
+ }
2143
+ }
2144
+ function isAutoConnectEnv() {
2145
+ return isAutoConnectMode();
2146
+ }
2147
+ function allocateLoopbackPort() {
2148
+ return new Promise((resolvePort, rejectPort) => {
2149
+ const srv = createNetServer();
2150
+ srv.once("error", rejectPort);
2151
+ srv.listen(0, "127.0.0.1", () => {
2152
+ const addr = srv.address();
2153
+ const allocated = addr && typeof addr === "object" && typeof addr.port === "number" ? addr.port : 0;
2154
+ srv.close((closeErr) => {
2155
+ if (closeErr || allocated <= 0) {
2156
+ rejectPort(closeErr ?? new Error("Failed to allocate loopback port"));
2157
+ return;
2158
+ }
2159
+ resolvePort(allocated);
2160
+ });
2161
+ });
2162
+ });
2163
+ }
2164
+ function buildModeMismatchError(sessionName, runningMode, expectedMode) {
2165
+ return new CdpError(
2166
+ `Session "${sessionName}" is already running in mode "${runningMode}", which does not match requested mode "${expectedMode}"`,
2167
+ "MODE_MISMATCH",
2168
+ [
2169
+ `Use a dedicated named session so modes never collide: CHROME_DEVTOOLS_AXI_SESSION=<other-name> ...`,
2170
+ `Or stop the existing "${sessionName}" bridge first: chrome-devtools-axi stop`
2171
+ ]
2172
+ );
2173
+ }
2174
+ function notifyWaitingForApproval(sessionName, cdpState, logFile) {
2175
+ if (process.env.CHROME_DEVTOOLS_AXI_QUIET === "1") return;
2176
+ const log = logFile ?? resolveSessionLogFile(sessionName);
2177
+ const msg = cdpState === "awaiting_approval" ? `[chrome-devtools-axi] Waiting for Chrome remote-debugging approval dialog (click "Allow" in Chrome; log: ${log})
2178
+ ` : `[chrome-devtools-axi] Waiting for browser CDP connection (${cdpState}; log: ${log})
2179
+ `;
2180
+ process.stderr.write(msg);
2181
+ }
2182
+ function buildApprovalError(sessionName, reason) {
2183
+ const logFile = resolveSessionLogFile(sessionName);
2184
+ return new CdpError(
2185
+ `Chrome remote-debugging connection was not authorized: ${reason}`,
2186
+ "APPROVAL_REQUIRED",
2187
+ [
2188
+ 'If Chrome showed an "Allow remote debugging?" dialog, click "Allow" and re-run the command (do not restart the bridge while waiting).',
2189
+ "If no dialog appeared, verify chrome://inspect/#remote-debugging is enabled once in Chrome and that Chrome is running.",
2190
+ "For an isolated headless browser without user login state or approval prompts, set CHROME_DEVTOOLS_AXI_FRESH=1.",
2191
+ `Inspect bridge diagnostics at: ${logFile}`
2192
+ ]
1998
2193
  );
1999
- child.unref();
2000
- return child;
2001
2194
  }
2002
2195
  function resolveSharedMcpMode() {
2003
2196
  if (process.env.CHROME_DEVTOOLS_AXI_FRESH === "1") return null;
@@ -2053,111 +2246,614 @@ function buildBridgeEarlyExitError(sessionName, port, code, signal) {
2053
2246
  );
2054
2247
  return new CdpError(message, "BRIDGE_NOT_READY", suggestions);
2055
2248
  }
2249
+ function reclaimStaleStartLock(lockFile, expectedToken) {
2250
+ const reclaimFile = `${lockFile}.reclaim`;
2251
+ for (let attempt = 0; attempt < 2; attempt++) {
2252
+ let fd;
2253
+ try {
2254
+ fd = openSync(reclaimFile, "wx");
2255
+ } catch (error) {
2256
+ if (error.code !== "EEXIST") return;
2257
+ try {
2258
+ if (Date.now() - statSync2(reclaimFile).mtimeMs > 5e3) {
2259
+ unlinkSync(reclaimFile);
2260
+ continue;
2261
+ }
2262
+ } catch {
2263
+ continue;
2264
+ }
2265
+ return;
2266
+ }
2267
+ try {
2268
+ closeSync(fd);
2269
+ try {
2270
+ const raw = readFileSync3(lockFile, "utf8");
2271
+ const parsed = JSON.parse(raw);
2272
+ if (expectedToken === void 0 || parsed.token === expectedToken) {
2273
+ unlinkSync(lockFile);
2274
+ }
2275
+ } catch {
2276
+ if (expectedToken === void 0) {
2277
+ try {
2278
+ unlinkSync(lockFile);
2279
+ } catch {
2280
+ }
2281
+ }
2282
+ }
2283
+ } finally {
2284
+ try {
2285
+ unlinkSync(reclaimFile);
2286
+ } catch {
2287
+ }
2288
+ }
2289
+ return;
2290
+ }
2291
+ }
2292
+ function tryAcquireStartLock(lockFile, staleMs) {
2293
+ mkdirSync2(dirname3(lockFile), { recursive: true });
2294
+ const token = randomUUID();
2295
+ const payload = JSON.stringify({
2296
+ pid: process.pid,
2297
+ createdAt: Date.now(),
2298
+ token
2299
+ });
2300
+ for (let attempt = 0; attempt < 2; attempt++) {
2301
+ try {
2302
+ const fd = openSync(lockFile, "wx");
2303
+ try {
2304
+ writeFileSync2(fd, payload, "utf8");
2305
+ } finally {
2306
+ closeSync(fd);
2307
+ }
2308
+ let released = false;
2309
+ return {
2310
+ release: () => {
2311
+ if (released) return;
2312
+ released = true;
2313
+ try {
2314
+ const current = JSON.parse(readFileSync3(lockFile, "utf8"));
2315
+ if (current.token === token) unlinkSync(lockFile);
2316
+ } catch {
2317
+ }
2318
+ }
2319
+ };
2320
+ } catch (error) {
2321
+ if (error.code !== "EEXIST") return null;
2322
+ let stale = false;
2323
+ let observedToken;
2324
+ try {
2325
+ const existing = JSON.parse(readFileSync3(lockFile, "utf8"));
2326
+ const holderPid = typeof existing.pid === "number" ? existing.pid : void 0;
2327
+ const createdAt = typeof existing.createdAt === "number" ? existing.createdAt : 0;
2328
+ observedToken = typeof existing.token === "string" ? existing.token : void 0;
2329
+ if (holderPid !== void 0 && holderPid !== process.pid && !isProcessAlive(holderPid)) {
2330
+ stale = true;
2331
+ } else if (Date.now() - createdAt > staleMs) {
2332
+ stale = true;
2333
+ }
2334
+ } catch {
2335
+ try {
2336
+ if (Date.now() - statSync2(lockFile).mtimeMs > 1e3) stale = true;
2337
+ } catch {
2338
+ stale = true;
2339
+ }
2340
+ }
2341
+ if (stale) {
2342
+ reclaimStaleStartLock(lockFile, observedToken);
2343
+ continue;
2344
+ }
2345
+ return null;
2346
+ }
2347
+ }
2348
+ return null;
2349
+ }
2350
+ function pinPendingGeneration(pidFile, pidInfo, probePid) {
2351
+ if (pidInfo && (probePid === void 0 || pidInfo.pid === probePid)) {
2352
+ return { pid: pidInfo.pid, startTime: pidInfo.startTime };
2353
+ }
2354
+ if (probePid !== void 0) {
2355
+ const disk = readPidFile(pidFile);
2356
+ if (disk && disk.pid === probePid) {
2357
+ return { pid: disk.pid, startTime: disk.startTime };
2358
+ }
2359
+ return {
2360
+ pid: probePid,
2361
+ startTime: inspectProcessIdentity(probePid).startTime ?? void 0
2362
+ };
2363
+ }
2364
+ return void 0;
2365
+ }
2366
+ async function waitForPendingBridge(opts) {
2367
+ const { port, sessionName, pidFile, initialProbe, autoConnect, expectedMode, notice } = opts;
2368
+ const isApprovalWait = initialProbe.cdpState === "awaiting_approval" || autoConnect;
2369
+ if (isApprovalWait) {
2370
+ notifyWaitingForApproval(
2371
+ sessionName,
2372
+ initialProbe.cdpState,
2373
+ initialProbe.logFile
2374
+ );
2375
+ }
2376
+ const waitBudgetMs = isApprovalWait ? resolveApprovalTimeoutMs() : resolveBridgeTimeoutMs();
2377
+ const waitDeadline = Date.now() + waitBudgetMs;
2378
+ const pinnedGeneration = pinPendingGeneration(
2379
+ pidFile,
2380
+ opts.pidInfo,
2381
+ initialProbe.pid
2382
+ );
2383
+ let stillPending = true;
2384
+ let existingError = null;
2385
+ let shouldRespawn = false;
2386
+ while (Date.now() < waitDeadline) {
2387
+ if (pinnedGeneration && !isProcessAlive(pinnedGeneration.pid)) {
2388
+ shouldRespawn = true;
2389
+ break;
2390
+ }
2391
+ await sleep(100);
2392
+ const next = await probeBridgeHealth(port, {
2393
+ deep: true,
2394
+ expectedSession: sessionName,
2395
+ expectedMode,
2396
+ notice
2397
+ });
2398
+ if (next.kind === "ok") return port;
2399
+ if (next.kind === "mode_mismatch") {
2400
+ throw buildModeMismatchError(sessionName, next.runningMode, expectedMode ?? "unknown");
2401
+ }
2402
+ if (next.kind === "pending") continue;
2403
+ stillPending = false;
2404
+ if (next.kind === "cdp_error") {
2405
+ if (isApprovalWait) {
2406
+ existingError = next.reason;
2407
+ break;
2408
+ }
2409
+ shouldRespawn = true;
2410
+ break;
2411
+ }
2412
+ shouldRespawn = true;
2413
+ break;
2414
+ }
2415
+ if (shouldRespawn) {
2416
+ if (pinnedGeneration && isProcessAlive(pinnedGeneration.pid)) {
2417
+ try {
2418
+ await stopBridge({ expectedGeneration: pinnedGeneration });
2419
+ } catch {
2420
+ }
2421
+ } else if (pinnedGeneration) {
2422
+ removePidFile(pidFile, pinnedGeneration.pid);
2423
+ }
2424
+ return "respawn";
2425
+ }
2426
+ if (existingError !== null) {
2427
+ throw buildApprovalError(sessionName, existingError);
2428
+ }
2429
+ if (stillPending) {
2430
+ if (pinnedGeneration) {
2431
+ try {
2432
+ await stopBridge({ expectedGeneration: pinnedGeneration });
2433
+ } catch {
2434
+ }
2435
+ }
2436
+ if (isApprovalWait) {
2437
+ throw buildApprovalError(
2438
+ sessionName,
2439
+ `timed out after ${Math.round(waitBudgetMs / 1e3)}s waiting for Chrome approval`
2440
+ );
2441
+ }
2442
+ throw new CdpError(
2443
+ `Bridge deep health probe timed out after ${Math.round(waitBudgetMs / 1e3)}s`,
2444
+ "BRIDGE_NOT_READY",
2445
+ [`Inspect bridge diagnostics at: ${resolveSessionLogFile(sessionName)}`]
2446
+ );
2447
+ }
2448
+ return "respawn";
2449
+ }
2056
2450
  async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2057
2451
  const sessionName = resolveSessionName();
2058
- const port = resolveSessionPort(sessionName);
2452
+ let port = resolveSessionPort(sessionName);
2453
+ const hasExplicitPort = Boolean(process.env.CHROME_DEVTOOLS_AXI_PORT?.trim());
2059
2454
  const pidFile = resolveSessionPidFile(sessionName);
2455
+ const autoConnect = isAutoConnectEnv();
2456
+ const expectedMode = computeTransportModeFingerprint();
2060
2457
  const pidInfo = readPidFile(pidFile);
2061
2458
  if (pidInfo && isProcessAlive(pidInfo.pid)) {
2062
- if (await checkBridgeHealth(pidInfo.port, {
2459
+ const existingProbe = await probeBridgeHealth(pidInfo.port, {
2063
2460
  deep: true,
2064
2461
  expectedSession: sessionName,
2462
+ expectedMode,
2065
2463
  notice
2066
- })) {
2464
+ });
2465
+ if (existingProbe.kind === "ok") {
2067
2466
  return pidInfo.port;
2068
2467
  }
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
2468
+ if (existingProbe.kind === "mode_mismatch") {
2469
+ if (existingProbe.runningMode.startsWith("isolated-") && !existingProbe.busy) {
2470
+ await stopBridge({
2471
+ expectedGeneration: { pid: pidInfo.pid, startTime: pidInfo.startTime }
2472
+ });
2473
+ } else {
2474
+ throw buildModeMismatchError(
2475
+ sessionName,
2476
+ existingProbe.runningMode,
2477
+ expectedMode
2478
+ );
2479
+ }
2480
+ } else if (existingProbe.kind === "pending") {
2481
+ const waited = await waitForPendingBridge({
2482
+ port: pidInfo.port,
2483
+ sessionName,
2484
+ pidFile,
2485
+ initialProbe: existingProbe,
2486
+ pidInfo,
2487
+ autoConnect,
2488
+ expectedMode,
2489
+ notice
2075
2490
  });
2491
+ if (typeof waited === "number") return waited;
2492
+ } else if (existingProbe.kind === "cdp_error" && autoConnect) {
2493
+ throw buildApprovalError(sessionName, existingProbe.reason);
2076
2494
  } else {
2077
- removePidFile(pidFile);
2495
+ const verdict = await judgeRecordedBridge(pidInfo, sessionName);
2496
+ if (verdict.terminate) {
2497
+ await terminateBridgeProcess(verdict.targetPid ?? pidInfo.pid, {
2498
+ killProcessGroup: verdict.killProcessGroup,
2499
+ requireBridgeIdentity: true,
2500
+ expectedStartTime: verdict.expectedStartTime
2501
+ });
2502
+ if (pidInfo.ownedProfileDir) {
2503
+ await cleanupOwnedProfileDir(pidInfo.ownedProfileDir);
2504
+ }
2505
+ } else {
2506
+ removePidFile(pidFile, pidInfo.pid);
2507
+ }
2508
+ }
2509
+ } else if (pidInfo && pidInfo.ownedProfileDir) {
2510
+ const reaped = await cleanupOwnedProfileDir(pidInfo.ownedProfileDir);
2511
+ if (reaped.clean) {
2512
+ removePidFile(pidFile, pidInfo.pid);
2078
2513
  }
2079
2514
  }
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, {
2515
+ const startLockFile = resolveSessionStartLockFile(sessionName);
2516
+ const lockBudgetMs = Math.max(START_LOCK_STALE_MS, resolveBridgeTimeoutMs());
2517
+ const MAX_RESPAWN_ATTEMPTS = 2;
2518
+ let respawnAttempts = 0;
2519
+ let startLock = null;
2520
+ let lockWaitDeadline = Date.now() + lockBudgetMs;
2521
+ while (true) {
2522
+ if (!hasExplicitPort) {
2523
+ const latestPid = readPidFile(pidFile);
2524
+ port = (latestPid && isProcessAlive(latestPid.pid) ? latestPid.port : void 0) ?? resolveSessionPort(sessionName);
2525
+ }
2526
+ startLock = tryAcquireStartLock(startLockFile, lockBudgetMs);
2527
+ if (startLock !== null) {
2528
+ if (!hasExplicitPort) {
2529
+ const latestPid = readPidFile(pidFile);
2530
+ port = (latestPid && isProcessAlive(latestPid.pid) ? latestPid.port : void 0) ?? resolveSessionPort(sessionName);
2531
+ }
2532
+ let postLockProbe;
2533
+ try {
2534
+ postLockProbe = await probeBridgeHealth(port, {
2535
+ deep: true,
2536
+ expectedSession: sessionName,
2537
+ expectedMode,
2538
+ notice
2539
+ });
2540
+ } catch (error) {
2541
+ startLock.release();
2542
+ throw error;
2543
+ }
2544
+ if (postLockProbe.kind === "ok") {
2545
+ startLock.release();
2546
+ return port;
2547
+ }
2548
+ if (postLockProbe.kind === "mode_mismatch") {
2549
+ startLock.release();
2550
+ throw buildModeMismatchError(
2551
+ sessionName,
2552
+ postLockProbe.runningMode,
2553
+ expectedMode
2554
+ );
2555
+ }
2556
+ if (postLockProbe.kind === "pending") {
2557
+ startLock.release();
2558
+ startLock = null;
2559
+ const waited = await waitForPendingBridge({
2560
+ port,
2561
+ sessionName,
2562
+ pidFile,
2563
+ initialProbe: postLockProbe,
2564
+ pidInfo: null,
2565
+ autoConnect,
2566
+ expectedMode,
2567
+ notice
2568
+ });
2569
+ if (typeof waited === "number") return waited;
2570
+ respawnAttempts += 1;
2571
+ if (respawnAttempts > MAX_RESPAWN_ATTEMPTS) {
2572
+ throw new CdpError(
2573
+ "Bridge repeatedly became unavailable while waiting for readiness",
2574
+ "BRIDGE_NOT_READY",
2575
+ [`Inspect bridge diagnostics at: ${resolveSessionLogFile(sessionName)}`]
2576
+ );
2577
+ }
2578
+ lockWaitDeadline = Date.now() + lockBudgetMs;
2579
+ continue;
2580
+ }
2581
+ if (postLockProbe.kind === "cdp_error") {
2582
+ if (autoConnect) {
2583
+ startLock.release();
2584
+ throw buildApprovalError(sessionName, postLockProbe.reason);
2585
+ }
2586
+ const brokenPid = readPidFile(pidFile);
2587
+ if (brokenPid && isProcessAlive(brokenPid.pid)) {
2588
+ const verdict = await judgeRecordedBridge(brokenPid, sessionName);
2589
+ if (verdict.terminate) {
2590
+ await terminateBridgeProcess(verdict.targetPid ?? brokenPid.pid, {
2591
+ killProcessGroup: verdict.killProcessGroup,
2592
+ requireBridgeIdentity: true,
2593
+ expectedStartTime: verdict.expectedStartTime
2594
+ });
2595
+ } else {
2596
+ removePidFile(pidFile, brokenPid.pid);
2597
+ }
2598
+ }
2599
+ }
2600
+ break;
2601
+ }
2602
+ const racingProbe = await probeBridgeHealth(port, {
2095
2603
  deep: true,
2096
2604
  expectedSession: sessionName,
2605
+ expectedMode,
2097
2606
  notice
2098
- })) {
2607
+ });
2608
+ if (racingProbe.kind === "ok") {
2099
2609
  return port;
2100
2610
  }
2101
- if (childExited) {
2102
- if (await checkBridgeHealth(port, {
2611
+ if (racingProbe.kind === "mode_mismatch") {
2612
+ throw buildModeMismatchError(
2613
+ sessionName,
2614
+ racingProbe.runningMode,
2615
+ expectedMode
2616
+ );
2617
+ }
2618
+ if (racingProbe.kind === "pending") {
2619
+ const waited = await waitForPendingBridge({
2620
+ port,
2621
+ sessionName,
2622
+ pidFile,
2623
+ initialProbe: racingProbe,
2624
+ pidInfo: null,
2625
+ autoConnect,
2626
+ expectedMode,
2627
+ notice
2628
+ });
2629
+ if (typeof waited === "number") return waited;
2630
+ respawnAttempts += 1;
2631
+ if (respawnAttempts > MAX_RESPAWN_ATTEMPTS) {
2632
+ throw new CdpError(
2633
+ "Bridge repeatedly became unavailable while waiting for readiness",
2634
+ "BRIDGE_NOT_READY",
2635
+ [`Inspect bridge diagnostics at: ${resolveSessionLogFile(sessionName)}`]
2636
+ );
2637
+ }
2638
+ lockWaitDeadline = Date.now() + lockBudgetMs;
2639
+ continue;
2640
+ }
2641
+ if (racingProbe.kind === "cdp_error" && autoConnect) {
2642
+ throw buildApprovalError(sessionName, racingProbe.reason);
2643
+ }
2644
+ if (Date.now() >= lockWaitDeadline) {
2645
+ break;
2646
+ }
2647
+ await sleep(100);
2648
+ }
2649
+ try {
2650
+ clearSelectedPageId();
2651
+ let portCollisionRetried = false;
2652
+ let child = spawnBridge(port, sessionName);
2653
+ let childExited = false;
2654
+ let exitCode = null;
2655
+ let exitSignal = null;
2656
+ const attachExitWatcher = (proc) => {
2657
+ childExited = false;
2658
+ exitCode = null;
2659
+ exitSignal = null;
2660
+ proc.on("exit", (code, signal) => {
2661
+ childExited = true;
2662
+ exitCode = code;
2663
+ exitSignal = signal;
2664
+ });
2665
+ };
2666
+ attachExitWatcher(child);
2667
+ const timeoutMs = resolveBridgeTimeoutMs();
2668
+ let deadline = Date.now() + timeoutMs;
2669
+ let sawShallowReady = false;
2670
+ let sawApprovalWait = false;
2671
+ let approvalNoticeShown = false;
2672
+ let lastCdpError = null;
2673
+ while (Date.now() < deadline) {
2674
+ const probe = await probeBridgeHealth(port, {
2103
2675
  deep: true,
2104
2676
  expectedSession: sessionName,
2677
+ expectedMode,
2105
2678
  notice
2106
- })) {
2679
+ });
2680
+ if (probe.kind === "ok") {
2107
2681
  return port;
2108
2682
  }
2109
- throw buildBridgeEarlyExitError(sessionName, port, exitCode, exitSignal);
2683
+ if (probe.kind === "mode_mismatch") {
2684
+ throw buildModeMismatchError(sessionName, probe.runningMode, expectedMode);
2685
+ }
2686
+ if (probe.kind === "pending") {
2687
+ startLock?.release();
2688
+ const isForeignWinner = childExited || probe.pid !== void 0 && child.pid !== void 0 && probe.pid !== child.pid;
2689
+ if (isForeignWinner) {
2690
+ const waited = await waitForPendingBridge({
2691
+ port,
2692
+ sessionName,
2693
+ pidFile,
2694
+ initialProbe: probe,
2695
+ pidInfo: null,
2696
+ autoConnect,
2697
+ expectedMode,
2698
+ notice
2699
+ });
2700
+ if (typeof waited === "number") return waited;
2701
+ throw new CdpError(
2702
+ "Bridge exited while waiting for readiness",
2703
+ "BRIDGE_NOT_READY",
2704
+ [`Inspect bridge diagnostics at: ${resolveSessionLogFile(sessionName)}`]
2705
+ );
2706
+ }
2707
+ sawShallowReady = true;
2708
+ if (probe.cdpState === "awaiting_approval" || autoConnect) {
2709
+ if (!sawApprovalWait) {
2710
+ sawApprovalWait = true;
2711
+ deadline = Math.max(deadline, Date.now() + resolveApprovalTimeoutMs());
2712
+ }
2713
+ if (!approvalNoticeShown) {
2714
+ approvalNoticeShown = true;
2715
+ notifyWaitingForApproval(sessionName, probe.cdpState, probe.logFile);
2716
+ }
2717
+ }
2718
+ await sleep(100);
2719
+ continue;
2720
+ }
2721
+ if (probe.kind === "cdp_error") {
2722
+ startLock?.release();
2723
+ sawShallowReady = true;
2724
+ lastCdpError = probe.reason;
2725
+ if (sawApprovalWait || autoConnect) {
2726
+ sawApprovalWait = true;
2727
+ break;
2728
+ }
2729
+ }
2730
+ if (childExited) {
2731
+ startLock?.release();
2732
+ let recheck = await probeBridgeHealth(port, {
2733
+ deep: true,
2734
+ expectedSession: sessionName,
2735
+ expectedMode,
2736
+ notice
2737
+ });
2738
+ if (recheck.kind === "unreachable" && exitCode === BRIDGE_PORT_IN_USE_EXIT_CODE) {
2739
+ await sleep(150);
2740
+ recheck = await probeBridgeHealth(port, {
2741
+ deep: true,
2742
+ expectedSession: sessionName,
2743
+ expectedMode,
2744
+ notice
2745
+ });
2746
+ if (recheck.kind === "unreachable" && !hasExplicitPort && sessionName !== DEFAULT_SESSION_NAME && !portCollisionRetried) {
2747
+ portCollisionRetried = true;
2748
+ port = await allocateLoopbackPort();
2749
+ writeAllocatedSessionPort(sessionName, port);
2750
+ child = spawnBridge(port, sessionName);
2751
+ attachExitWatcher(child);
2752
+ deadline = Math.max(deadline, Date.now() + timeoutMs);
2753
+ continue;
2754
+ }
2755
+ }
2756
+ if (recheck.kind === "mode_mismatch") {
2757
+ throw buildModeMismatchError(
2758
+ sessionName,
2759
+ recheck.runningMode,
2760
+ expectedMode
2761
+ );
2762
+ }
2763
+ if (recheck.kind === "ok") {
2764
+ return port;
2765
+ }
2766
+ if (recheck.kind === "pending") {
2767
+ const waited = await waitForPendingBridge({
2768
+ port,
2769
+ sessionName,
2770
+ pidFile,
2771
+ initialProbe: recheck,
2772
+ pidInfo: null,
2773
+ autoConnect,
2774
+ expectedMode,
2775
+ notice
2776
+ });
2777
+ if (typeof waited === "number") return waited;
2778
+ throw new CdpError(
2779
+ "Bridge exited while waiting for readiness",
2780
+ "BRIDGE_NOT_READY",
2781
+ [`Inspect bridge diagnostics at: ${resolveSessionLogFile(sessionName)}`]
2782
+ );
2783
+ }
2784
+ if (recheck.kind === "cdp_error" && autoConnect) {
2785
+ sawShallowReady = true;
2786
+ sawApprovalWait = true;
2787
+ lastCdpError = recheck.reason;
2788
+ break;
2789
+ }
2790
+ throw buildBridgeEarlyExitError(sessionName, port, exitCode, exitSignal);
2791
+ }
2792
+ if (!sawShallowReady && await checkBridgeHealth(port, { expectedSession: sessionName })) {
2793
+ startLock?.release();
2794
+ sawShallowReady = true;
2795
+ }
2796
+ await sleep(500);
2110
2797
  }
2111
- if (!sawShallowReady && await checkBridgeHealth(port, { expectedSession: sessionName })) {
2112
- sawShallowReady = true;
2798
+ const shouldRecycle = !(sawApprovalWait && lastCdpError !== null);
2799
+ const failingGeneration = shouldRecycle ? child.pid !== void 0 && childExited === false ? {
2800
+ pid: child.pid,
2801
+ startTime: inspectProcessIdentity(child.pid)?.startTime ?? void 0
2802
+ } : pidInfo !== null && sawShallowReady ? { pid: pidInfo.pid, startTime: pidInfo.startTime } : void 0 : void 0;
2803
+ if (failingGeneration) {
2804
+ try {
2805
+ await stopBridge({ expectedGeneration: failingGeneration });
2806
+ } catch {
2807
+ }
2113
2808
  }
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 {
2809
+ if (sawApprovalWait) {
2810
+ throw buildApprovalError(
2811
+ sessionName,
2812
+ lastCdpError ?? `timed out after ${Math.round(resolveApprovalTimeoutMs() / 1e3)}s waiting for Chrome approval`
2813
+ );
2121
2814
  }
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."
2815
+ const seconds = Math.round(timeoutMs / 1e3);
2816
+ const logFile = resolveSessionLogFile(sessionName);
2817
+ const sharedMcpMode = resolveSharedMcpMode();
2818
+ if (sawShallowReady) {
2819
+ const suggestions2 = sharedMcpMode ? [
2820
+ ...sharedMcpSuggestions(sharedMcpMode),
2821
+ "The shared MCP service may be reachable while its attached Chrome target is unavailable."
2822
+ ] : autoConnect ? [
2823
+ "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.",
2824
+ "For an isolated headless instance instead (no user login state), set CHROME_DEVTOOLS_AXI_FRESH=1."
2825
+ ] : [
2826
+ "The Chrome/Electron instance the bridge was attached to may have exited.",
2827
+ "Verify the target is still listening on its remote-debugging port, then re-run the command.",
2828
+ "If the target was restarted, the bridge has already been recycled \u2014 this run will succeed once the target is reachable."
2829
+ ];
2830
+ suggestions2.push(`Inspect bridge diagnostics at: ${logFile}`);
2831
+ throw new CdpError(
2832
+ 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",
2833
+ "BRIDGE_NOT_READY",
2834
+ suggestions2
2835
+ );
2836
+ }
2837
+ const suggestions = sharedMcpMode === "direct" ? sharedMcpSuggestions("direct") : sharedMcpMode === "proxy" ? sharedMcpSuggestions("proxy") : [
2838
+ "Check that chrome-devtools-mcp is installed: npx chrome-devtools-mcp@latest --help"
2137
2839
  ];
2840
+ if (!sharedMcpMode && !process.env.CHROME_DEVTOOLS_AXI_MCP_PATH?.trim()) {
2841
+ suggestions.push(
2842
+ "If `npx -y chrome-devtools-mcp@latest` is slow on this machine, install mcp globally and set:",
2843
+ ' export CHROME_DEVTOOLS_AXI_MCP_PATH="$(npm prefix -g)/lib/node_modules/chrome-devtools-mcp/build/src/bin/chrome-devtools-mcp.js"'
2844
+ );
2845
+ }
2846
+ suggestions.push(
2847
+ "Or extend the deadline: export CHROME_DEVTOOLS_AXI_BRIDGE_TIMEOUT_MS=60000"
2848
+ );
2138
2849
  throw new CdpError(
2139
- "Bridge is running but the attached CDP target appears to have gone away",
2850
+ `Bridge failed to start within ${seconds}s`,
2140
2851
  "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"'
2852
+ suggestions
2151
2853
  );
2854
+ } finally {
2855
+ startLock?.release();
2152
2856
  }
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
2857
  }
2162
2858
  function parseCallResponse(resp) {
2163
2859
  const data = JSON.parse(resp);
@@ -2370,7 +3066,11 @@ async function getSessionSnapshotIfRunning() {
2370
3066
  if (!pidInfo || !isProcessAlive(pidInfo.pid)) {
2371
3067
  return null;
2372
3068
  }
2373
- if (!await checkBridgeHealth(pidInfo.port, { expectedSession: sessionName })) {
3069
+ const shallow = await probeBridgeHealth(pidInfo.port, {
3070
+ expectedSession: sessionName,
3071
+ expectedMode: computeTransportModeFingerprint()
3072
+ });
3073
+ if (shallow.kind !== "ok" || shallow.busy || shallow.dialogPending || shallow.cdpState !== void 0 && shallow.cdpState !== "connected") {
2374
3074
  return null;
2375
3075
  }
2376
3076
  try {
@@ -2386,14 +3086,61 @@ async function getSessionSnapshotIfRunning() {
2386
3086
  return null;
2387
3087
  }
2388
3088
  }
3089
+ async function tryCleanupSessionObserver() {
3090
+ let sessionName;
3091
+ let pidInfo;
3092
+ try {
3093
+ sessionName = resolveSessionName();
3094
+ pidInfo = readPidFile(resolveSessionPidFile(sessionName));
3095
+ } catch {
3096
+ return;
3097
+ }
3098
+ if (!pidInfo || !isProcessAlive(pidInfo.pid)) return;
3099
+ const pageId = getSelectedPageId();
3100
+ if (pageId === null) return;
3101
+ const shallow = await probeBridgeHealth(pidInfo.port, {
3102
+ expectedSession: sessionName
3103
+ });
3104
+ if (shallow.kind !== "ok" || shallow.busy || shallow.dialogPending || shallow.cdpState !== "connected") {
3105
+ return;
3106
+ }
3107
+ try {
3108
+ await postTool(
3109
+ pidInfo.port,
3110
+ "evaluate_script",
3111
+ {
3112
+ pageId,
3113
+ waitForStableDom: false,
3114
+ function: CLEANUP_OBSERVER_SCRIPT
3115
+ },
3116
+ { timeoutMs: 800 }
3117
+ );
3118
+ } catch {
3119
+ }
3120
+ }
2389
3121
  async function stopBridge(options = {}) {
2390
- const pidInfo = readPidFile();
2391
- if (!pidInfo) return "noop";
2392
- if (!isProcessAlive(pidInfo.pid)) return "noop";
3122
+ const sessionName = resolveSessionName();
3123
+ const pidFile = resolveSessionPidFile(sessionName);
3124
+ const pidInfo = readPidFile(pidFile);
3125
+ if (!pidInfo) {
3126
+ if (!options.expectedGeneration) clearAllocatedSessionPort(sessionName);
3127
+ return "noop";
3128
+ }
2393
3129
  if (options.expectedGeneration && (options.expectedGeneration.pid !== pidInfo.pid || options.expectedGeneration.startTime !== pidInfo.startTime)) {
2394
3130
  return "noop";
2395
3131
  }
2396
- const verdict = await judgeRecordedBridge(pidInfo, resolveSessionName());
3132
+ if (!isProcessAlive(pidInfo.pid)) {
3133
+ if (pidInfo.ownedProfileDir) {
3134
+ const reaped = await cleanupOwnedProfileDir(pidInfo.ownedProfileDir);
3135
+ if (!reaped.clean) return "failed";
3136
+ removePidFile(pidFile, pidInfo.pid);
3137
+ clearSelectedPageId();
3138
+ if (!options.expectedGeneration) clearAllocatedSessionPort(sessionName);
3139
+ return "stopped";
3140
+ }
3141
+ return "noop";
3142
+ }
3143
+ const verdict = await judgeRecordedBridge(pidInfo, sessionName);
2397
3144
  if (!verdict.terminate) return "noop";
2398
3145
  const targetPid = verdict.targetPid ?? pidInfo.pid;
2399
3146
  if (options.expectedGeneration && targetPid !== options.expectedGeneration.pid) {
@@ -2404,17 +3151,28 @@ async function stopBridge(options = {}) {
2404
3151
  requireBridgeIdentity: true,
2405
3152
  expectedStartTime: options.expectedGeneration ? options.expectedGeneration.startTime ?? verdict.expectedStartTime : verdict.expectedStartTime
2406
3153
  });
3154
+ let profileClean = true;
3155
+ if (terminated && pidInfo.ownedProfileDir) {
3156
+ const reaped = await cleanupOwnedProfileDir(pidInfo.ownedProfileDir);
3157
+ profileClean = reaped.clean;
3158
+ }
3159
+ if (terminated && profileClean) {
3160
+ removePidFile(pidFile, pidInfo.pid);
3161
+ clearSelectedPageId();
3162
+ if (!options.expectedGeneration) clearAllocatedSessionPort(sessionName);
3163
+ return "stopped";
3164
+ }
2407
3165
  clearSelectedPageId();
2408
- return terminated ? "stopped" : "failed";
3166
+ return "failed";
2409
3167
  }
2410
3168
 
2411
3169
  // vendor/chrome-devtools-axi/src/generation.ts
2412
3170
  import {
2413
3171
  existsSync as existsSync4,
2414
- mkdirSync as mkdirSync2,
3172
+ mkdirSync as mkdirSync3,
2415
3173
  readFileSync as readFileSync4,
2416
3174
  unlinkSync as unlinkSync2,
2417
- writeFileSync as writeFileSync2
3175
+ writeFileSync as writeFileSync3
2418
3176
  } from "node:fs";
2419
3177
  import { dirname as dirname4, join as join3 } from "node:path";
2420
3178
  function genFile() {
@@ -2434,19 +3192,25 @@ function bumpGeneration() {
2434
3192
  const next = getCurrentGeneration() + 1;
2435
3193
  const file = genFile();
2436
3194
  try {
2437
- mkdirSync2(dirname4(file), { recursive: true });
2438
- writeFileSync2(file, String(next));
3195
+ mkdirSync3(dirname4(file), { recursive: true });
3196
+ writeFileSync3(file, String(next));
2439
3197
  } catch {
2440
3198
  }
2441
3199
  return next;
2442
3200
  }
2443
3201
 
2444
3202
  // vendor/chrome-devtools-axi/src/run.ts
2445
- import { mkdtempSync, writeFileSync as writeFileSync3, unlinkSync as unlinkSync3, rmdirSync } from "node:fs";
3203
+ import { mkdtempSync, writeFileSync as writeFileSync4, unlinkSync as unlinkSync3, rmdirSync } from "node:fs";
2446
3204
  import { join as join4 } from "node:path";
2447
3205
  import { tmpdir } from "node:os";
2448
3206
  import { pathToFileURL } from "node:url";
2449
3207
 
3208
+ // vendor/chrome-devtools-axi/src/paths.ts
3209
+ import { isAbsolute, resolve as resolve2 } from "node:path";
3210
+ function resolveOutputPath(filePath) {
3211
+ return isAbsolute(filePath) ? filePath : resolve2(process.cwd(), filePath);
3212
+ }
3213
+
2450
3214
  // vendor/chrome-devtools-axi/src/snapshot.ts
2451
3215
  function countRefs(snapshot) {
2452
3216
  const matches = snapshot.match(/\buid=\S+/g);
@@ -2526,7 +3290,6 @@ function isInputType(type) {
2526
3290
  }
2527
3291
 
2528
3292
  // vendor/chrome-devtools-axi/src/uid-freshness.ts
2529
- var PAGE_GENERATION_KEY = "__chromeDevtoolsAxiSnapshotGeneration";
2530
3293
  async function captureFreshSnapshot(caller, capture) {
2531
3294
  const first = await captureSnapshot(caller, capture);
2532
3295
  const fresh = first.state?.generation === first.generation && first.state.mutations > 0 ? await captureSnapshot(caller, capture) : first;
@@ -2675,25 +3438,61 @@ function wrapJsExpression(js) {
2675
3438
  }
2676
3439
  return `() => (${trimmed})`;
2677
3440
  }
3441
+ var ZERO_WIDTH_RE = /[\u200B-\u200D\u2060\uFEFF]/g;
3442
+ function stripZeroWidth(text) {
3443
+ return text.replace(ZERO_WIDTH_RE, "");
3444
+ }
3445
+ function parseJsonOrUndefined(raw) {
3446
+ const trimmed = raw.trim();
3447
+ if (trimmed === "undefined") return void 0;
3448
+ try {
3449
+ return JSON.parse(trimmed);
3450
+ } catch (error) {
3451
+ const detail = error instanceof Error ? error.message : String(error);
3452
+ throw new CdpError(
3453
+ `Failed to parse evaluate_script return value as JSON (${detail}): ${trimmed.slice(0, 200)}`,
3454
+ "BROWSER_ERROR",
3455
+ [
3456
+ "Ensure the evaluated expression returns a JSON-serializable value (or undefined)."
3457
+ ]
3458
+ );
3459
+ }
3460
+ }
2678
3461
  function parseEvalOutput(output) {
2679
- const jsonBlock = output.match(/```json\n([\s\S]*?)\n```/);
3462
+ if (/^# Open dialog\b/m.test(output)) {
3463
+ throw new CdpError(
3464
+ "Cannot read evaluate_script result because a JavaScript dialog is open.",
3465
+ "DIALOG_PENDING",
3466
+ [
3467
+ 'Call `await page.dialog("accept")` or `await page.dialog("dismiss")` before continuing.'
3468
+ ]
3469
+ );
3470
+ }
3471
+ const jsonBlock = output.match(/```json\r?\n([\s\S]*?)\r?\n```(?:\r?\n|$)/);
2680
3472
  if (jsonBlock) {
2681
- try {
2682
- return JSON.parse(jsonBlock[1].trim());
2683
- } catch {
2684
- return jsonBlock[1].trim();
2685
- }
3473
+ return parseJsonOrUndefined(jsonBlock[1]);
2686
3474
  }
2687
3475
  const preamble = "Script ran on page and returned:";
2688
3476
  if (output.includes(preamble)) {
2689
3477
  const raw = output.slice(output.indexOf(preamble) + preamble.length).trim();
2690
- try {
2691
- return JSON.parse(raw);
2692
- } catch {
2693
- return raw;
2694
- }
3478
+ return parseJsonOrUndefined(raw);
3479
+ }
3480
+ throw new CdpError(
3481
+ `Unexpected evaluate_script response format: ${output.trim().slice(0, 200)}`,
3482
+ "BROWSER_ERROR",
3483
+ ["Run `chrome-devtools-axi snapshot` or inspect page state before retrying."]
3484
+ );
3485
+ }
3486
+ function assertNoPendingDialog(result) {
3487
+ if (/^# Open dialog\b/m.test(result)) {
3488
+ throw new CdpError(
3489
+ "The action opened a dialog. Do not replay it; handle the dialog first.",
3490
+ "DIALOG_PENDING",
3491
+ [
3492
+ 'Call `await page.dialog("accept")` or `await page.dialog("dismiss")` in the same session.'
3493
+ ]
3494
+ );
2695
3495
  }
2696
- return output.trim();
2697
3496
  }
2698
3497
  function stripSnapshotHeader(text) {
2699
3498
  const lines = text.split("\n");
@@ -2728,10 +3527,10 @@ function createPageHelper(callTool2) {
2728
3527
  ]);
2729
3528
  }
2730
3529
  try {
2731
- await callTool2("navigate_page", { type: "url", url });
3530
+ assertNoPendingDialog(await callTool2("navigate_page", { type: "url", url }));
2732
3531
  } catch (error) {
2733
3532
  if (!isRecoverableOpenError(error)) throw error;
2734
- await callTool2("new_page", { url });
3533
+ assertNoPendingDialog(await callTool2("new_page", { url }));
2735
3534
  }
2736
3535
  const info = await evalJs(
2737
3536
  `() => ({ url: location.href, status: performance.getEntriesByType('navigation').pop()?.responseStatus ?? null })`
@@ -2750,27 +3549,51 @@ function createPageHelper(callTool2) {
2750
3549
  }
2751
3550
  return evalJs(jsOrFn);
2752
3551
  },
2753
- async wait(msOrSelector, timeout) {
3552
+ async wait(msOrSelector, timeoutOrOpts) {
2754
3553
  if (typeof msOrSelector === "number") {
2755
3554
  await callFunction(`new Promise(r => setTimeout(r, ${msOrSelector}))`);
2756
3555
  } else {
2757
- const ms = timeout ?? DEFAULT_WAIT_TIMEOUT;
3556
+ const opts = typeof timeoutOrOpts === "number" ? { timeout: timeoutOrOpts } : timeoutOrOpts ?? {};
3557
+ const ms = opts.timeout ?? DEFAULT_WAIT_TIMEOUT;
3558
+ const requireVisible = opts.visible === true;
3559
+ const waitForAbsent = opts.absent === true;
2758
3560
  const sel = JSON.stringify(msOrSelector);
2759
3561
  await callFunction(`new Promise((resolve, reject) => {
2760
3562
  const sel = ${sel};
2761
- if (document.querySelector(sel)) { resolve(); return; }
3563
+ const requireVisible = ${JSON.stringify(requireVisible)};
3564
+ const waitForAbsent = ${JSON.stringify(waitForAbsent)};
3565
+ const isVisible = (el) => {
3566
+ if (!el || !el.isConnected) return false;
3567
+ const style = getComputedStyle(el);
3568
+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return false;
3569
+ const rects = el.getClientRects();
3570
+ return rects.length > 0 && Array.from(rects).some(r => r.width > 0 && r.height > 0);
3571
+ };
3572
+ const matches = () => {
3573
+ const nodes = Array.from(document.querySelectorAll(sel));
3574
+ const found = requireVisible ? nodes.some(isVisible) : nodes.length > 0;
3575
+ return waitForAbsent ? !found : found;
3576
+ };
3577
+ if (matches()) { resolve(); return; }
3578
+ const root = document.documentElement || document;
3579
+ const finish = () => {
3580
+ observer.disconnect();
3581
+ clearInterval(poll);
3582
+ clearTimeout(timer);
3583
+ resolve();
3584
+ };
2762
3585
  const observer = new MutationObserver(() => {
2763
- if (document.querySelector(sel)) {
2764
- observer.disconnect();
2765
- clearTimeout(timer);
2766
- resolve();
2767
- }
3586
+ if (matches()) finish();
2768
3587
  });
3588
+ const poll = setInterval(() => {
3589
+ if (matches()) finish();
3590
+ }, 100);
2769
3591
  const timer = setTimeout(() => {
2770
3592
  observer.disconnect();
2771
- reject(new Error('Timeout waiting for: ' + sel));
3593
+ clearInterval(poll);
3594
+ reject(new Error((waitForAbsent ? 'Timeout waiting for absence of: ' : 'Timeout waiting for: ') + sel));
2772
3595
  }, ${ms});
2773
- observer.observe(document.body, { childList: true, subtree: true, attributes: true });
3596
+ observer.observe(root, { childList: true, subtree: true, attributes: true });
2774
3597
  })`);
2775
3598
  }
2776
3599
  },
@@ -2782,49 +3605,162 @@ function createPageHelper(callTool2) {
2782
3605
  },
2783
3606
  async click(refOrSelector) {
2784
3607
  if (isUidRef(refOrSelector)) {
2785
- await callTool2("click", {
3608
+ const res = await callTool2("click", {
2786
3609
  uid: await parseUidFresh(refOrSelector, callTool2)
2787
3610
  });
3611
+ assertNoPendingDialog(res);
2788
3612
  } else {
2789
3613
  const sel = JSON.stringify(refOrSelector);
2790
- await callFunction(`() => {
3614
+ const res = await callFunction(`async () => {
2791
3615
  const el = document.querySelector(${sel});
2792
- if (!el) throw new Error('Element not found: ' + ${sel});
2793
- el.scrollIntoView({ block: 'center' });
3616
+ if (!el || !el.isConnected) throw new Error('Element not found: ' + ${sel});
3617
+ if ('disabled' in el && el.disabled) throw new Error('Element is disabled: ' + ${sel});
3618
+ const isVisible = (node) => {
3619
+ const style = getComputedStyle(node);
3620
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
3621
+ const rects = node.getClientRects();
3622
+ return rects.length > 0 && Array.from(rects).some(r => r.width > 0 && r.height > 0);
3623
+ };
3624
+ if (!isVisible(el)) throw new Error('Element is not visible: ' + ${sel});
3625
+ el.scrollIntoView({ block: 'center', inline: 'center' });
3626
+ await new Promise(r => {
3627
+ let done = false;
3628
+ const finish = () => { if (!done) { done = true; r(); } };
3629
+ const t = setTimeout(finish, 60);
3630
+ if (document.visibilityState === 'visible') {
3631
+ requestAnimationFrame(() => { clearTimeout(t); finish(); });
3632
+ }
3633
+ });
3634
+ if (!el.isConnected || !isVisible(el)) throw new Error('Element became unavailable after scroll: ' + ${sel});
2794
3635
  el.click();
2795
3636
  }`);
3637
+ assertNoPendingDialog(res);
2796
3638
  }
2797
3639
  },
2798
3640
  async fill(refOrSelector, text) {
2799
3641
  if (isUidRef(refOrSelector)) {
2800
- await callTool2("fill", {
3642
+ const res = await callTool2("fill", {
2801
3643
  uid: await parseUidFresh(refOrSelector, callTool2),
2802
3644
  value: text
2803
3645
  });
3646
+ assertNoPendingDialog(res);
2804
3647
  } else {
2805
3648
  const sel = JSON.stringify(refOrSelector);
2806
3649
  const val = JSON.stringify(text);
2807
- await callFunction(`() => {
3650
+ const res = await callFunction(`() => {
2808
3651
  const el = document.querySelector(${sel});
2809
- if (!el) throw new Error('Element not found: ' + ${sel});
3652
+ if (!el || !el.isConnected) throw new Error('Element not found: ' + ${sel});
3653
+ if ('disabled' in el && el.disabled) throw new Error('Element is disabled: ' + ${sel});
3654
+ if ('readOnly' in el && el.readOnly) throw new Error('Element is read-only: ' + ${sel});
2810
3655
  el.focus();
2811
3656
  const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype
2812
3657
  : el instanceof HTMLSelectElement ? HTMLSelectElement.prototype
2813
- : HTMLInputElement.prototype;
2814
- Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, ${val});
3658
+ : el instanceof HTMLInputElement ? HTMLInputElement.prototype
3659
+ : null;
3660
+ const desc = proto ? Object.getOwnPropertyDescriptor(proto, 'value') : null;
3661
+ if (desc && desc.set) desc.set.call(el, ${val});
3662
+ else if ('value' in el) el.value = ${val};
3663
+ else if (el.isContentEditable) el.textContent = ${val};
3664
+ else throw new Error('Element is not a fillable input: ' + ${sel});
2815
3665
  el.dispatchEvent(new Event('input', { bubbles: true }));
2816
3666
  el.dispatchEvent(new Event('change', { bubbles: true }));
2817
3667
  }`);
3668
+ assertNoPendingDialog(res);
2818
3669
  }
2819
3670
  },
2820
3671
  async type(text) {
2821
- await callTool2("type_text", { text });
3672
+ assertNoPendingDialog(await callTool2("type_text", { text }));
2822
3673
  },
2823
3674
  async press(key) {
2824
- await callTool2("press_key", { key });
3675
+ assertNoPendingDialog(await callTool2("press_key", { key }));
2825
3676
  },
2826
3677
  async back() {
2827
- await callTool2("navigate_page", { type: "back" });
3678
+ assertNoPendingDialog(await callTool2("navigate_page", { type: "back" }));
3679
+ },
3680
+ async dialog(action, promptText) {
3681
+ const params = { action };
3682
+ if (promptText !== void 0) params.promptText = promptText;
3683
+ return callTool2("handle_dialog", params);
3684
+ },
3685
+ async network(opts = {}) {
3686
+ const params = {};
3687
+ if (opts.resourceTypes) params.resourceTypes = opts.resourceTypes;
3688
+ if (opts.pageSize !== void 0) params.pageSize = opts.pageSize;
3689
+ if (opts.pageIdx !== void 0) params.pageIdx = opts.pageIdx;
3690
+ if (opts.includePreservedRequests) {
3691
+ params.includePreservedRequests = true;
3692
+ }
3693
+ return callTool2("list_network_requests", params);
3694
+ },
3695
+ async networkGet(reqid, opts = {}) {
3696
+ const params = {};
3697
+ if (reqid !== void 0) params.reqid = reqid;
3698
+ if (opts.requestFilePath) {
3699
+ params.requestFilePath = resolveOutputPath(opts.requestFilePath);
3700
+ }
3701
+ if (opts.responseFilePath) {
3702
+ params.responseFilePath = resolveOutputPath(opts.responseFilePath);
3703
+ }
3704
+ return callTool2("get_network_request", params);
3705
+ },
3706
+ async scroll(directionOrTarget = "down", opts = {}) {
3707
+ const directions = /* @__PURE__ */ new Set(["up", "down", "top", "bottom"]);
3708
+ const isDirection = directions.has(directionOrTarget.toLowerCase());
3709
+ const direction = isDirection ? directionOrTarget.toLowerCase() : opts.direction ?? "down";
3710
+ const amount = opts.amount ?? 500;
3711
+ const wheel = opts.wheel === true;
3712
+ const deltaY = direction === "up" ? -amount : amount;
3713
+ if (isDirection) {
3714
+ await callFunction(`() => {
3715
+ const dir = ${JSON.stringify(direction)};
3716
+ const deltaY = ${JSON.stringify(deltaY)};
3717
+ let handledByWheel = false;
3718
+ if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
3719
+ const target = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2) || document.documentElement;
3720
+ handledByWheel = !target.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
3721
+ }
3722
+ if (handledByWheel) return;
3723
+ if (dir === 'top') window.scrollTo(0, 0);
3724
+ else if (dir === 'bottom') window.scrollTo(0, document.documentElement.scrollHeight || document.body.scrollHeight);
3725
+ else window.scrollBy(0, deltaY);
3726
+ }`);
3727
+ return;
3728
+ }
3729
+ if (isUidRef(directionOrTarget)) {
3730
+ const uid = await parseUidFresh(directionOrTarget, callTool2);
3731
+ await callTool2("evaluate_script", {
3732
+ args: [uid],
3733
+ function: `(el) => {
3734
+ if (!el) throw new Error('Scroll target not found');
3735
+ const dir = ${JSON.stringify(direction)};
3736
+ const deltaY = ${JSON.stringify(deltaY)};
3737
+ let handledByWheel = false;
3738
+ if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
3739
+ handledByWheel = !el.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
3740
+ }
3741
+ if (handledByWheel) return;
3742
+ if (dir === 'top') el.scrollTop = 0;
3743
+ else if (dir === 'bottom') el.scrollTop = el.scrollHeight;
3744
+ else el.scrollBy(0, deltaY);
3745
+ }`
3746
+ });
3747
+ return;
3748
+ }
3749
+ const sel = JSON.stringify(directionOrTarget);
3750
+ await callFunction(`() => {
3751
+ const el = document.querySelector(${sel});
3752
+ if (!el) throw new Error('Scroll target not found: ' + ${sel});
3753
+ const dir = ${JSON.stringify(direction)};
3754
+ const deltaY = ${JSON.stringify(deltaY)};
3755
+ let handledByWheel = false;
3756
+ if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
3757
+ handledByWheel = !el.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
3758
+ }
3759
+ if (handledByWheel) return;
3760
+ if (dir === 'top') el.scrollTop = 0;
3761
+ else if (dir === 'bottom') el.scrollTop = el.scrollHeight;
3762
+ else el.scrollBy(0, deltaY);
3763
+ }`);
2828
3764
  }
2829
3765
  };
2830
3766
  }
@@ -2839,7 +3775,7 @@ async function runScript(content, callTool2) {
2839
3775
  const page = createPageHelper(callTool2);
2840
3776
  const tmpDir = mkdtempSync(join4(tmpdir(), "cda-run-"));
2841
3777
  const tmpFile = join4(tmpDir, "script.mjs");
2842
- writeFileSync3(tmpFile, content, "utf-8");
3778
+ writeFileSync4(tmpFile, content, "utf-8");
2843
3779
  const lines = [];
2844
3780
  const origLog = console.log;
2845
3781
  const captureLog = (...args) => {
@@ -2949,12 +3885,6 @@ function installHooksOrThrow() {
2949
3885
  }
2950
3886
  }
2951
3887
 
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
3888
  // vendor/chrome-devtools-axi/src/cli.ts
2959
3889
  var HOME_DESCRIPTION = "Agent ergonomic interface for controlling Chrome browser session. Prefer this over other browser automation tools.";
2960
3890
  var RAW_STDOUT_MARKER = "__CHROME_DEVTOOLS_AXI_RAW__";
@@ -3122,17 +4052,24 @@ flags:
3122
4052
  examples:
3123
4053
  chrome-devtools-axi press Enter
3124
4054
  chrome-devtools-axi press Tab --full`,
3125
- scroll: `usage: chrome-devtools-axi scroll <direction> [--full]
3126
- Scroll the page in a direction.
4055
+ scroll: `usage: chrome-devtools-axi scroll [direction] [--uid @<uid>|--selector <css>] [--amount <px>] [--wheel] [--full]
4056
+ Scroll the page or a specific scrollable container.
3127
4057
 
3128
4058
  args:
3129
- <direction> up, down, top, or bottom (default: down)
4059
+ [direction] up, down, top, or bottom (default: down)
3130
4060
 
3131
4061
  flags:
3132
- --full Show complete snapshot without truncation
4062
+ --uid @<uid> Scroll the element referenced by a fresh snapshot uid
4063
+ --selector <css> Scroll the first element matching a CSS selector
4064
+ --amount <px> Scroll distance in pixels for up/down (default: 500)
4065
+ --wheel Also dispatch a synthetic DOM WheelEvent (isTrusted=false;
4066
+ for widgets requiring trusted native wheel input, focus and
4067
+ use \`press PageDown\`/\`ArrowDown\` or use computer-use-axi)
4068
+ --full Show complete snapshot without truncation
3133
4069
 
3134
4070
  examples:
3135
4071
  chrome-devtools-axi scroll down
4072
+ chrome-devtools-axi scroll down --selector ".virtual-list" --amount 300 --wheel
3136
4073
  chrome-devtools-axi scroll top --full`,
3137
4074
  back: `usage: chrome-devtools-axi back [--full]
3138
4075
  Navigate back in browser history.
@@ -3143,16 +4080,22 @@ flags:
3143
4080
  examples:
3144
4081
  chrome-devtools-axi back
3145
4082
  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.
4083
+ wait: `usage: chrome-devtools-axi wait <ms|text> [--visible] [--absent] [--timeout <ms>]
4084
+ Wait for a duration, for text to appear, or for text to disappear from the page.
3148
4085
 
3149
4086
  args:
3150
- <ms> Milliseconds to wait (numeric)
3151
- <text> Text to wait for (string)
4087
+ <ms> Milliseconds to wait (numeric)
4088
+ <text> Text to wait for (string)
4089
+
4090
+ flags:
4091
+ --visible Only match visible text (ignore hidden/closed dropdown DOM)
4092
+ --absent Wait until matching visible text disappears (e.g. "Loading...")
4093
+ --timeout <ms> Maximum wait duration in milliseconds (default: 30000)
3152
4094
 
3153
4095
  examples:
3154
4096
  chrome-devtools-axi wait 2000
3155
- chrome-devtools-axi wait "Submit"`,
4097
+ chrome-devtools-axi wait "Saved" --visible --timeout 15000
4098
+ chrome-devtools-axi wait "Loading..." --absent --timeout 30000`,
3156
4099
  eval: `usage: chrome-devtools-axi eval <js>
3157
4100
  Evaluate a JavaScript expression in the page context and return the result.
3158
4101
  A bare expression is wrapped as () => (<js>); pass a function (arrow or
@@ -3181,14 +4124,18 @@ script API (available as global \`page\`):
3181
4124
  await page.snapshot() Get the generation-tagged accessibility tree
3182
4125
  await page.wait(ms) Wait by duration
3183
4126
  await page.wait(selector) Wait for CSS selector (30s timeout)
3184
- await page.wait(selector, ms) Wait for CSS selector with timeout
4127
+ await page.wait(selector, opts) Wait with timeout ms or { timeout, visible, absent }
3185
4128
  await page.click("@uid") Click an element by fresh ref
3186
- await page.click(selector) Click via CSS selector
4129
+ await page.click(selector) Click via CSS selector (checks visibility/disabled)
3187
4130
  await page.fill("@uid", text) Fill a form field by fresh ref
3188
4131
  await page.fill(selector, text) Fill via CSS selector, including controlled fields
3189
4132
  await page.type(text) Type at the focused element
3190
4133
  await page.press(key) Press a keyboard key
3191
4134
  await page.back() Navigate back
4135
+ await page.dialog(action, text?) Accept or dismiss an open JS dialog
4136
+ await page.network(opts?) List network requests (supports includePreservedRequests)
4137
+ await page.networkGet(id?, opts?) Inspect a specific network request/response
4138
+ await page.scroll(target?, opts?) Scroll window or container (supports { amount, direction, wheel })
3192
4139
 
3193
4140
  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
4141
  page.eval accepts functions, arrow functions, and bare expression strings; no-arg IIFE strings are unwrapped automatically.
@@ -3376,7 +4323,7 @@ args:
3376
4323
 
3377
4324
  examples:
3378
4325
  chrome-devtools-axi console-get 3`,
3379
- network: `usage: chrome-devtools-axi network [--type <type>] [--limit <n>] [--page <n>]
4326
+ network: `usage: chrome-devtools-axi network [--type <type>] [--limit <n>] [--page <n>] [--preserved] [--full]
3380
4327
  List network requests for the current page.
3381
4328
 
3382
4329
  flags:
@@ -3388,12 +4335,14 @@ flags:
3388
4335
  ("all" or omitted returns every request.)
3389
4336
  --limit <n> Maximum requests to return
3390
4337
  --page <n> Page number (0-based)
4338
+ --preserved Include requests preserved across the last 3 navigations/reloads
4339
+ --full Show complete output without 2000-char truncation
3391
4340
 
3392
4341
  examples:
3393
4342
  chrome-devtools-axi network
3394
- chrome-devtools-axi network --type fetch --limit 50
4343
+ chrome-devtools-axi network --type fetch --preserved --full
3395
4344
  chrome-devtools-axi network --type all`,
3396
- "network-get": `usage: chrome-devtools-axi network-get [id] [--response-file <path>] [--request-file <path>]
4345
+ "network-get": `usage: chrome-devtools-axi network-get [id] [--response-file <path>] [--request-file <path>] [--full]
3397
4346
  Get a specific network request. If id is omitted, gets the selected request.
3398
4347
 
3399
4348
  args:
@@ -3402,11 +4351,12 @@ args:
3402
4351
  flags:
3403
4352
  --response-file <path> Save response body to file
3404
4353
  --request-file <path> Save request body to file
4354
+ --full Show complete output without 2000-char truncation
3405
4355
 
3406
4356
  Relative output paths resolve against the directory where you run the CLI.
3407
4357
 
3408
4358
  examples:
3409
- chrome-devtools-axi network-get 42
4359
+ chrome-devtools-axi network-get 42 --full
3410
4360
  chrome-devtools-axi network-get 42 --response-file ./response.json`,
3411
4361
  // Performance
3412
4362
  lighthouse: `usage: chrome-devtools-axi lighthouse [--device <device>] [--mode <mode>] [--output-dir <path>]
@@ -3510,17 +4460,21 @@ function parseScreenshotOutputPath(result) {
3510
4460
  }
3511
4461
  return match[1];
3512
4462
  }
3513
- function formatMcpResult(label, text, suggestions) {
4463
+ function formatMcpResult(label, text, suggestions, full = false, supportsFull = false) {
3514
4464
  const blocks = [];
3515
- const tr = truncateSnapshot(text, false, 2e3);
4465
+ const tr = truncateSnapshot(text, full, 2e3);
3516
4466
  blocks.push(`${label}:
3517
4467
  ${tr.text.trimEnd()}`);
4468
+ const finalSuggestions = [...suggestions];
3518
4469
  if (tr.truncated) {
3519
4470
  blocks[0] += `
3520
4471
  ... (truncated, ${tr.totalLength} chars total)`;
4472
+ if (supportsFull) {
4473
+ finalSuggestions.push("Re-run with --full to see complete output without truncation");
4474
+ }
3521
4475
  }
3522
- if (suggestions.length > 0) {
3523
- blocks.push(renderHelp(suggestions));
4476
+ if (finalSuggestions.length > 0) {
4477
+ blocks.push(renderHelp(finalSuggestions));
3524
4478
  }
3525
4479
  return renderOutput2(blocks);
3526
4480
  }
@@ -3606,10 +4560,120 @@ function parseNetworkArgs(args) {
3606
4560
  } else if (args[i] === "--page" && i + 1 < args.length) {
3607
4561
  const pageIdx = parseOptionalInteger(args[++i]);
3608
4562
  if (pageIdx !== void 0) result.pageIdx = pageIdx;
4563
+ } else if (args[i] === "--preserved") {
4564
+ result.includePreservedRequests = true;
3609
4565
  }
3610
4566
  }
3611
4567
  return result;
3612
4568
  }
4569
+ function parseStrictPositiveInteger(raw) {
4570
+ if (!raw || !/^\d+$/.test(raw)) return void 0;
4571
+ const parsed = Number(raw);
4572
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) return void 0;
4573
+ return parsed;
4574
+ }
4575
+ function parseWaitArgs(args) {
4576
+ let visible = false;
4577
+ let absent = false;
4578
+ let timeout;
4579
+ let afterDoubleDash = false;
4580
+ const positional = [];
4581
+ for (let i = 0; i < args.length; i++) {
4582
+ const a = args[i];
4583
+ if (!afterDoubleDash && a === "--") {
4584
+ afterDoubleDash = true;
4585
+ continue;
4586
+ }
4587
+ if (!afterDoubleDash && a === "--visible") {
4588
+ visible = true;
4589
+ } else if (!afterDoubleDash && a === "--absent") {
4590
+ absent = true;
4591
+ } else if (!afterDoubleDash && a === "--timeout") {
4592
+ if (i + 1 >= args.length) {
4593
+ throw new CdpError("Missing value for --timeout", "VALIDATION_ERROR", [
4594
+ "Pass a positive timeout in milliseconds, e.g. --timeout 15000"
4595
+ ]);
4596
+ }
4597
+ const rawTimeout = args[++i];
4598
+ const parsed = parseStrictPositiveInteger(rawTimeout);
4599
+ if (parsed === void 0) {
4600
+ throw new CdpError(
4601
+ `Invalid --timeout value: ${rawTimeout}`,
4602
+ "VALIDATION_ERROR",
4603
+ ["Pass a positive integer timeout in milliseconds, e.g. --timeout 15000"]
4604
+ );
4605
+ }
4606
+ timeout = parsed;
4607
+ } else {
4608
+ positional.push(a);
4609
+ }
4610
+ }
4611
+ return {
4612
+ target: positional.join(" "),
4613
+ visible,
4614
+ absent,
4615
+ ...timeout !== void 0 ? { timeout } : {}
4616
+ };
4617
+ }
4618
+ function parseScrollArgs(args) {
4619
+ let directionRaw;
4620
+ let uid;
4621
+ let selector;
4622
+ let amount = 500;
4623
+ let wheel = false;
4624
+ for (let i = 0; i < args.length; i++) {
4625
+ const a = args[i];
4626
+ if (a === "--uid") {
4627
+ if (i + 1 >= args.length) {
4628
+ throw new CdpError("Missing value for --uid", "VALIDATION_ERROR", [
4629
+ "Pass a fresh snapshot ref, e.g. --uid @g1:12"
4630
+ ]);
4631
+ }
4632
+ uid = args[++i];
4633
+ } else if (a === "--selector") {
4634
+ if (i + 1 >= args.length) {
4635
+ throw new CdpError("Missing value for --selector", "VALIDATION_ERROR", [
4636
+ 'Pass a CSS selector, e.g. --selector ".virtual-list"'
4637
+ ]);
4638
+ }
4639
+ selector = args[++i];
4640
+ } else if (a === "--amount") {
4641
+ if (i + 1 >= args.length) {
4642
+ throw new CdpError("Missing value for --amount", "VALIDATION_ERROR", [
4643
+ "Pass a positive scroll amount in pixels, e.g. --amount 300"
4644
+ ]);
4645
+ }
4646
+ const rawAmount = args[++i];
4647
+ const parsed = parseStrictPositiveInteger(rawAmount);
4648
+ if (parsed === void 0) {
4649
+ throw new CdpError(
4650
+ `Invalid --amount value: ${rawAmount}`,
4651
+ "VALIDATION_ERROR",
4652
+ ["Pass a positive integer scroll amount in pixels, e.g. --amount 300"]
4653
+ );
4654
+ }
4655
+ amount = parsed;
4656
+ } else if (a === "--wheel") {
4657
+ wheel = true;
4658
+ } else if (!a.startsWith("--")) {
4659
+ directionRaw = a.toLowerCase();
4660
+ }
4661
+ }
4662
+ const direction = directionRaw ?? "down";
4663
+ if (direction !== "up" && direction !== "down" && direction !== "top" && direction !== "bottom") {
4664
+ throw new CdpError(`Unknown scroll direction: ${direction}`, "VALIDATION_ERROR", [
4665
+ "Run `chrome-devtools-axi scroll down` \u2014 directions: up, down, top, bottom"
4666
+ ]);
4667
+ }
4668
+ if (uid && selector) {
4669
+ throw new CdpError(
4670
+ "Specify at most one of --uid or --selector for scroll",
4671
+ "VALIDATION_ERROR",
4672
+ ["Use either `--uid @<uid>` or `--selector <css>`"]
4673
+ );
4674
+ }
4675
+ return { direction, uid, selector, amount, wheel };
4676
+ }
3613
4677
  function parseNetworkGetArgs(args) {
3614
4678
  const result = {};
3615
4679
  for (let i = 0; i < args.length; i++) {
@@ -3894,14 +4958,73 @@ async function handleType(args, full) {
3894
4958
  return formatPageOutput(snapshot, "type", void 0, full);
3895
4959
  }
3896
4960
  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
- ]);
4961
+ const parsed = parseScrollArgs(args);
4962
+ const { direction, uid, selector, amount, wheel } = parsed;
4963
+ const deltaY = direction === "up" ? -amount : amount;
4964
+ if (!uid && !selector && !wheel && amount === 500) {
4965
+ await callTool("evaluate_script", { function: SCROLL_FUNCTIONS[direction] });
4966
+ } else if (uid) {
4967
+ const freshUid = await parseUidFresh2(uid);
4968
+ await callTool("evaluate_script", {
4969
+ args: [freshUid],
4970
+ function: `(el) => {
4971
+ if (!el) throw new Error('Scroll target not found');
4972
+ const dir = ${JSON.stringify(direction)};
4973
+ const deltaY = ${JSON.stringify(deltaY)};
4974
+ let handledByWheel = false;
4975
+ if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
4976
+ const beforeElTop = el.scrollTop;
4977
+ const beforeWinY = window.scrollY;
4978
+ const prevented = !el.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
4979
+ handledByWheel = prevented || el.scrollTop !== beforeElTop || window.scrollY !== beforeWinY;
4980
+ }
4981
+ if (handledByWheel) return;
4982
+ if (dir === 'top') el.scrollTop = 0;
4983
+ else if (dir === 'bottom') el.scrollTop = el.scrollHeight;
4984
+ else el.scrollBy(0, deltaY);
4985
+ }`
4986
+ });
4987
+ } else if (selector) {
4988
+ const sel = JSON.stringify(selector);
4989
+ await callTool("evaluate_script", {
4990
+ function: `() => {
4991
+ const el = document.querySelector(${sel});
4992
+ if (!el) throw new Error('Scroll target not found: ' + ${sel});
4993
+ const dir = ${JSON.stringify(direction)};
4994
+ const deltaY = ${JSON.stringify(deltaY)};
4995
+ let handledByWheel = false;
4996
+ if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
4997
+ const beforeElTop = el.scrollTop;
4998
+ const beforeWinY = window.scrollY;
4999
+ const prevented = !el.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
5000
+ handledByWheel = prevented || el.scrollTop !== beforeElTop || window.scrollY !== beforeWinY;
5001
+ }
5002
+ if (handledByWheel) return;
5003
+ if (dir === 'top') el.scrollTop = 0;
5004
+ else if (dir === 'bottom') el.scrollTop = el.scrollHeight;
5005
+ else el.scrollBy(0, deltaY);
5006
+ }`
5007
+ });
5008
+ } else {
5009
+ await callTool("evaluate_script", {
5010
+ function: `() => {
5011
+ const dir = ${JSON.stringify(direction)};
5012
+ const deltaY = ${JSON.stringify(deltaY)};
5013
+ let handledByWheel = false;
5014
+ if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
5015
+ const target = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2) || document.documentElement;
5016
+ const beforeTargetTop = target.scrollTop;
5017
+ const beforeWinY = window.scrollY;
5018
+ const prevented = !target.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
5019
+ handledByWheel = prevented || target.scrollTop !== beforeTargetTop || window.scrollY !== beforeWinY;
5020
+ }
5021
+ if (handledByWheel) return;
5022
+ if (dir === 'top') window.scrollTo(0, 0);
5023
+ else if (dir === 'bottom') window.scrollTo(0, document.documentElement.scrollHeight || document.body.scrollHeight);
5024
+ else window.scrollBy(0, deltaY);
5025
+ }`
5026
+ });
3903
5027
  }
3904
- await callTool("evaluate_script", { function: fn });
3905
5028
  const snapshot = await stampFresh();
3906
5029
  return formatPageOutput(snapshot, "scroll", void 0, full);
3907
5030
  }
@@ -3911,33 +5034,87 @@ async function handleBack(full) {
3911
5034
  return formatPageOutput(snapshot, "back", void 0, full);
3912
5035
  }
3913
5036
  async function handleWait(args) {
3914
- const target = args[0];
5037
+ const { target, visible, absent, timeout } = parseWaitArgs(args);
3915
5038
  if (!target) {
3916
5039
  throw new CdpError(
3917
5040
  "Missing wait target (milliseconds or text)",
3918
5041
  "VALIDATION_ERROR",
3919
5042
  [
3920
5043
  "Run `chrome-devtools-axi wait 2000` to wait 2 seconds",
3921
- 'Run `chrome-devtools-axi wait "Submit"` to wait for text to appear'
5044
+ 'Run `chrome-devtools-axi wait "Submit" --visible` to wait for visible text to appear',
5045
+ 'Run `chrome-devtools-axi wait "Loading..." --absent` to wait for loading text to disappear'
3922
5046
  ]
3923
5047
  );
3924
5048
  }
3925
- const isNumeric = /^\d+$/.test(target);
5049
+ const isNumeric = !absent && !visible && /^\d+$/.test(target);
3926
5050
  if (isNumeric) {
3927
5051
  await callTool("evaluate_script", {
3928
5052
  function: wrapJsExpression(`new Promise(r => setTimeout(r, ${target}))`)
3929
5053
  });
5054
+ } else if (absent) {
5055
+ const ms = timeout ?? 3e4;
5056
+ const normalizedNeedle = stripZeroWidth(target).replace(/\s+/g, " ").trim();
5057
+ if (normalizedNeedle.length === 0) {
5058
+ throw new CdpError(
5059
+ "Wait --absent target must contain visible non-whitespace characters",
5060
+ "VALIDATION_ERROR",
5061
+ ['Run `chrome-devtools-axi wait "Loading..." --absent`']
5062
+ );
5063
+ }
5064
+ const needle = JSON.stringify(normalizedNeedle);
5065
+ await callTool("evaluate_script", {
5066
+ waitForStableDom: false,
5067
+ function: `() => new Promise((resolve, reject) => {
5068
+ const needle = ${needle};
5069
+ const normalize = (s) => String(s || '').replace(/[\\u200B-\\u200D\\u2060\\uFEFF]/g, '').replace(/\\s+/g, ' ').trim();
5070
+ const hasVisibleText = () => {
5071
+ const root = document.body || document.documentElement;
5072
+ if (!root) return false;
5073
+ const visibleText = normalize(root.innerText || '');
5074
+ return needle.length > 0 && visibleText.includes(needle);
5075
+ };
5076
+ if (!hasVisibleText()) { resolve(true); return; }
5077
+ const root = document.documentElement || document;
5078
+ const finish = () => {
5079
+ observer.disconnect();
5080
+ clearInterval(poll);
5081
+ clearTimeout(timer);
5082
+ resolve(true);
5083
+ };
5084
+ const observer = new MutationObserver(() => {
5085
+ if (!hasVisibleText()) finish();
5086
+ });
5087
+ const poll = setInterval(() => {
5088
+ if (!hasVisibleText()) finish();
5089
+ }, 100);
5090
+ const timer = setTimeout(() => {
5091
+ observer.disconnect();
5092
+ clearInterval(poll);
5093
+ reject(new Error('Timeout waiting for text to disappear: ' + needle));
5094
+ }, ${ms});
5095
+ observer.observe(root, { childList: true, subtree: true, attributes: true, characterData: true });
5096
+ })`
5097
+ });
3930
5098
  } else {
3931
- await callTool("wait_for", { text: [target] });
5099
+ const toolArgs = { text: [target] };
5100
+ if (visible) toolArgs.visible = true;
5101
+ if (timeout !== void 0) toolArgs.timeout = timeout;
5102
+ await callTool("wait_for", toolArgs);
3932
5103
  }
3933
5104
  const blocks = [];
3934
- blocks.push(encode({ waited: target }));
5105
+ blocks.push(
5106
+ encode({
5107
+ waited: target,
5108
+ ...visible ? { visible: true } : {},
5109
+ ...absent ? { absent: true } : {}
5110
+ })
5111
+ );
3935
5112
  const suggestions = getSuggestions({ command: "wait" });
3936
5113
  if (suggestions.length > 0) blocks.push(renderHelp(suggestions));
3937
5114
  return renderOutput2(blocks);
3938
5115
  }
3939
5116
  function parseEvalResult(output) {
3940
- const jsonBlock = output.match(/```json\n([\s\S]*?)\n```/);
5117
+ const jsonBlock = output.match(/```json\r?\n([\s\S]*?)\r?\n```(?:\r?\n|$)/);
3941
5118
  if (jsonBlock) return jsonBlock[1].trim();
3942
5119
  const preamble = "Script ran on page and returned:";
3943
5120
  if (output.includes(preamble))
@@ -3978,6 +5155,7 @@ function formatStopOutput(outcome) {
3978
5155
  return encode({ status: outcome === "stopped" ? "stopped" : "stopped (no-op)" });
3979
5156
  }
3980
5157
  async function handleStop() {
5158
+ await tryCleanupSessionObserver();
3981
5159
  const outcome = await stopBridge();
3982
5160
  return formatStopOutput(outcome);
3983
5161
  }
@@ -3992,12 +5170,17 @@ async function handlePages() {
3992
5170
  const rows = pages.map((p) => ` ${p.id},${p.url},${p.selected}`);
3993
5171
  blocks.push(`${header}
3994
5172
  ${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
- );
5173
+ const help = [
5174
+ "Run `chrome-devtools-axi selectpage <id>` to switch tabs",
5175
+ "Run `chrome-devtools-axi newpage <url>` to open a new tab"
5176
+ ];
5177
+ if (/^# Open dialog\b/m.test(result)) {
5178
+ blocks.push(encode({ dialog: "pending" }));
5179
+ help.unshift(
5180
+ "A JavaScript dialog is open \u2014 run `chrome-devtools-axi dialog accept` or `chrome-devtools-axi dialog dismiss` before page actions"
5181
+ );
5182
+ }
5183
+ blocks.push(renderHelp(help));
4001
5184
  return renderOutput2(blocks);
4002
5185
  }
4003
5186
  async function handleNewPage(args, full) {
@@ -4146,7 +5329,19 @@ async function handleDialog(args) {
4146
5329
  const params = { action };
4147
5330
  const promptText = args.slice(1).join(" ");
4148
5331
  if (promptText) params.promptText = promptText;
4149
- const snapshot = await callWithSnapshot("handle_dialog", params);
5332
+ const result = await callTool("handle_dialog", params);
5333
+ if (/^# Open dialog\b/m.test(result)) {
5334
+ const dialogMatch = result.match(/^# Open dialog[\s\S]*$/m);
5335
+ const blocks = [
5336
+ encode({ dialog: action, nextDialogPending: true }),
5337
+ ...dialogMatch ? [dialogMatch[0].trim()] : [],
5338
+ renderHelp([
5339
+ "Another dialog opened immediately \u2014 run `chrome-devtools-axi dialog accept` or `chrome-devtools-axi dialog dismiss` again"
5340
+ ])
5341
+ ];
5342
+ return renderOutput2(blocks);
5343
+ }
5344
+ const snapshot = await stampFresh();
4150
5345
  return encode({ dialog: action }) + "\n" + formatPageOutput(snapshot, "dialog");
4151
5346
  }
4152
5347
  async function handleUpload(args, full) {
@@ -4199,15 +5394,21 @@ async function handleConsoleGet(args) {
4199
5394
  const result = await callTool("get_console_message", { msgid });
4200
5395
  return formatMcpResult("message", result, []);
4201
5396
  }
4202
- async function handleNetwork(args) {
5397
+ async function handleNetwork(args, full) {
4203
5398
  const parsed = parseNetworkArgs(args);
4204
5399
  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
- ]);
5400
+ return formatMcpResult(
5401
+ "network",
5402
+ result,
5403
+ [
5404
+ "Run `chrome-devtools-axi network-get <id> --full` to see request/response details",
5405
+ "Run `chrome-devtools-axi network --type fetch --preserved --full` to inspect preserved requests across reloads"
5406
+ ],
5407
+ full,
5408
+ true
5409
+ );
4209
5410
  }
4210
- async function handleNetworkGet(args) {
5411
+ async function handleNetworkGet(args, full) {
4211
5412
  const parsed = parseNetworkGetArgs(args);
4212
5413
  const toolArgs = { ...parsed };
4213
5414
  if (toolArgs.responseFilePath) {
@@ -4217,7 +5418,7 @@ async function handleNetworkGet(args) {
4217
5418
  toolArgs.requestFilePath = resolveOutputPath(toolArgs.requestFilePath);
4218
5419
  }
4219
5420
  const result = await callTool("get_network_request", toolArgs);
4220
- return formatMcpResult("request", result, []);
5421
+ return formatMcpResult("request", result, [], full, true);
4221
5422
  }
4222
5423
  async function handleLighthouse(args) {
4223
5424
  const opts = parseLighthouseArgs(args);
@@ -4334,6 +5535,7 @@ function validateCommandFlags(command, args, allowedFlags, valueFlags, dashPosit
4334
5535
  let positionalArgs = 0;
4335
5536
  for (let i = 0; i < args.length; i++) {
4336
5537
  const arg = args[i];
5538
+ if (arg === "--") return;
4337
5539
  if (positionalArgs === positionalArgsBeforeText) return;
4338
5540
  if (arg === "--help" || allowedFlags.includes(arg)) {
4339
5541
  if (valueFlags.includes(arg)) i += 1;
@@ -4375,8 +5577,8 @@ var COMMAND_HANDLERS = {
4375
5577
  emulate: withoutFullFlag(handleEmulate),
4376
5578
  console: withoutFullFlag(handleConsole),
4377
5579
  "console-get": withoutFullFlag(handleConsoleGet),
4378
- network: withoutFullFlag(handleNetwork),
4379
- "network-get": withoutFullFlag(handleNetworkGet),
5580
+ network: withFullFlag(handleNetwork),
5581
+ "network-get": withFullFlag(handleNetworkGet),
4380
5582
  lighthouse: withoutFullFlag(handleLighthouse),
4381
5583
  "perf-start": withoutFullFlag(handlePerfStart),
4382
5584
  "perf-stop": withoutFullFlag(handlePerfStop),
@@ -4394,9 +5596,9 @@ var COMMAND_FLAGS = {
4394
5596
  fill: ["--full"],
4395
5597
  type: ["--full"],
4396
5598
  press: ["--full"],
4397
- scroll: ["--full"],
5599
+ scroll: ["--full", "--uid", "--selector", "--amount", "--wheel"],
4398
5600
  back: ["--full"],
4399
- wait: [],
5601
+ wait: ["--visible", "--absent", "--timeout"],
4400
5602
  eval: ["--full"],
4401
5603
  run: ["--page-id"],
4402
5604
  hover: ["--full"],
@@ -4419,8 +5621,8 @@ var COMMAND_FLAGS = {
4419
5621
  ],
4420
5622
  console: ["--type", "--limit", "--page"],
4421
5623
  "console-get": [],
4422
- network: ["--type", "--limit", "--page"],
4423
- "network-get": ["--response-file", "--request-file"],
5624
+ network: ["--type", "--limit", "--page", "--preserved", "--full"],
5625
+ "network-get": ["--response-file", "--request-file", "--full"],
4424
5626
  lighthouse: ["--device", "--mode", "--output-dir"],
4425
5627
  "perf-start": ["--no-reload", "--no-auto-stop", "--file"],
4426
5628
  "perf-stop": ["--file"],
@@ -4433,10 +5635,12 @@ var COMMAND_FLAGS = {
4433
5635
  var COMMAND_VALUE_FLAGS = {
4434
5636
  run: ["--page-id"],
4435
5637
  screenshot: ["--uid", "--format"],
5638
+ scroll: ["--uid", "--selector", "--amount"],
5639
+ wait: ["--timeout"],
4436
5640
  emulate: COMMAND_FLAGS.emulate,
4437
5641
  console: COMMAND_FLAGS.console,
4438
- network: COMMAND_FLAGS.network,
4439
- "network-get": COMMAND_FLAGS["network-get"],
5642
+ network: ["--type", "--limit", "--page"],
5643
+ "network-get": ["--response-file", "--request-file"],
4440
5644
  lighthouse: COMMAND_FLAGS.lighthouse,
4441
5645
  "perf-start": ["--file"],
4442
5646
  "perf-stop": COMMAND_FLAGS["perf-stop"]
@@ -4444,14 +5648,14 @@ var COMMAND_VALUE_FLAGS = {
4444
5648
  var COMMAND_POSITIONAL_TEXT_START = {
4445
5649
  fill: 1,
4446
5650
  type: 0,
4447
- wait: 0,
4448
5651
  eval: 0,
4449
5652
  dialog: 1
4450
5653
  };
4451
5654
  var COMMAND_DASH_POSITIONAL_SLOTS = {
4452
5655
  heap: [0],
4453
5656
  upload: [1],
4454
- screenshot: [0]
5657
+ screenshot: [0],
5658
+ wait: [0]
4455
5659
  };
4456
5660
  var COMMANDS = Object.fromEntries(
4457
5661
  Object.entries(COMMAND_HANDLERS).map(([command, handler]) => [
@@ -4504,7 +5708,9 @@ export {
4504
5708
  parsePagesList,
4505
5709
  parsePerfStartArgs,
4506
5710
  parseScreenshotArgs,
5711
+ parseScrollArgs,
4507
5712
  parseUid,
4508
5713
  parseUidFresh2 as parseUidFresh,
5714
+ parseWaitArgs,
4509
5715
  wrapJsExpression
4510
5716
  };