@cydm/pie 4.8.0 → 4.10.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 +906 -158
  4. package/dist/builtin/extensions/im-forward/README.md +4 -2
  5. package/dist/builtin/extensions/im-forward/index.js +6875 -3972
  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 +285 -61
  9. package/dist/builtin/extensions/pie-proc/README.md +7 -7
  10. package/dist/builtin/extensions/pie-proc/index.js +493 -107
  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 +26 -24
  15. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +199 -121
  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-ZE754CTH.js → cli-K7ESY3XD.js} +433 -255
  19. package/dist/builtin/skills/computer-use-axi/SKILL.md +25 -8
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +367 -65
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +2 -2
  22. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
  23. package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-5QMS6RQC.js} +353 -287
  24. package/dist/chunks/chunk-6WKBQZWM.js +19 -0
  25. package/dist/chunks/{chunk-LAJXWOKS.js → chunk-7LICWWUE.js} +11 -9
  26. package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BQWHLYYZ.js} +4 -3
  27. package/dist/chunks/{chunk-4PR34UZF.js → chunk-BTUMBUDU.js} +159 -145
  28. package/dist/chunks/{chunk-NHV2CALB.js → chunk-FC5AN5QP.js} +409 -32
  29. package/dist/chunks/{chunk-3W3SXVPB.js → chunk-G2K4GY6N.js} +993 -371
  30. package/dist/chunks/{chunk-BLDI2GRF.js → chunk-HK3FHIAH.js} +1364 -446
  31. package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
  32. package/dist/chunks/{chunk-CGSFBWOM.js → chunk-KWK7KTSZ.js} +4 -3
  33. package/dist/chunks/chunk-OU33ROFD.js +717 -0
  34. package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-XMTRKMBG.js} +104 -22
  35. package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-3TEMOQM5.js} +1 -1
  36. package/dist/chunks/{manager-cli-NEZA46M5.js → manager-cli-Y6HM3MHA.js} +5 -5
  37. package/dist/chunks/{model-registry-3XAHXXTA.js → model-registry-QKJ3YVDS.js} +2 -2
  38. package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-N2ZZQLTZ.js} +5 -5
  39. package/dist/chunks/{src-EGXFJ3WA.js → src-3PSR2AAX.js} +3 -3
  40. package/dist/chunks/{src-B44QWSGM.js → src-D5GN4Q5O.js} +2 -2
  41. package/dist/chunks/{src-CLE5ILN4.js → src-F5N6O2HR.js} +20 -4
  42. package/dist/chunks/{src-Q7LU27C2.js → src-TIDKYA5F.js} +31 -1
  43. package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-JAJHK44G.js} +2 -2
  44. package/dist/cli.js +4123 -2389
  45. package/models.schema.json +271 -0
  46. package/package.json +2 -2
  47. package/dist/builtin/skills/chrome-devtools-axi/chunk-Z2A5LA5A.js +0 -407
  48. package/dist/chunks/chunk-EGZ5TZRM.js +0 -1444
  49. package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
@@ -4,15 +4,19 @@ 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,
18
22
  resolveSessionLogFile,
@@ -21,8 +25,9 @@ import {
21
25
  resolveSessionPort,
22
26
  resolveSessionStartLockFile,
23
27
  resolveSessionStateDir,
24
- setSelectedPageId
25
- } from "./chunk-Z2A5LA5A.js";
28
+ setSelectedPageId,
29
+ writeAllocatedSessionPort
30
+ } from "./chunk-HAUDUMDO.js";
26
31
  import "./chunk-OJ6N23UZ.js";
27
32
 
28
33
  // ../../node_modules/chrome-devtools-axi/node_modules/@toon-format/toon/dist/index.mjs
@@ -1623,192 +1628,20 @@ import { execFileSync, spawn as spawn2 } from "node:child_process";
1623
1628
  import { randomUUID } from "node:crypto";
1624
1629
  import {
1625
1630
  closeSync,
1626
- existsSync as existsSync4,
1627
- mkdirSync as mkdirSync3,
1628
- openSync,
1629
- readFileSync as readFileSync4,
1630
- statSync as statSync2,
1631
- unlinkSync as unlinkSync2,
1632
- writeFileSync as writeFileSync3
1633
- } from "node:fs";
1634
- import { request } from "node:http";
1635
- import { dirname as dirname4 } from "node:path";
1636
-
1637
- // vendor/chrome-devtools-axi/src/generation.ts
1638
- import {
1639
1631
  existsSync as existsSync3,
1640
1632
  mkdirSync as mkdirSync2,
1633
+ openSync,
1641
1634
  readFileSync as readFileSync3,
1635
+ statSync as statSync2,
1642
1636
  unlinkSync,
1643
1637
  writeFileSync as writeFileSync2
1644
1638
  } from "node:fs";
1645
- import { dirname as dirname3, join as join3 } from "node:path";
1646
- function genFile() {
1647
- return join3(resolveSessionStateDir(), "snapshot-generation");
1648
- }
1649
- function getCurrentGeneration() {
1650
- const file = genFile();
1651
- try {
1652
- if (!existsSync3(file)) return 0;
1653
- const parsed = Number.parseInt(readFileSync3(file, "utf-8").trim(), 10);
1654
- return Number.isNaN(parsed) ? 0 : parsed;
1655
- } catch {
1656
- return 0;
1657
- }
1658
- }
1659
- function bumpGeneration() {
1660
- const next = getCurrentGeneration() + 1;
1661
- const file = genFile();
1662
- try {
1663
- mkdirSync2(dirname3(file), { recursive: true });
1664
- writeFileSync2(file, String(next));
1665
- } catch {
1666
- }
1667
- return next;
1668
- }
1669
-
1670
- // vendor/chrome-devtools-axi/src/snapshot.ts
1671
- function countRefs(snapshot) {
1672
- const matches = snapshot.match(/\buid=\S+/g);
1673
- return matches ? matches.length : 0;
1674
- }
1675
- function extractRefs(snapshot) {
1676
- const refs = [];
1677
- for (const line of snapshot.split("\n")) {
1678
- const m = line.match(/\buid=(\S+)\s+(\w+)\s+"([^"]*)"/);
1679
- if (!m) continue;
1680
- refs.push({ ref: m[1], type: m[2], label: m[3] });
1681
- }
1682
- return refs;
1683
- }
1684
- function parseStampedUid(arg) {
1685
- const stripped = arg.startsWith("@") ? arg.slice(1) : arg;
1686
- const m = stripped.match(/^g(\d+):(.+)$/);
1687
- if (m) return { uid: m[2], generation: Number.parseInt(m[1], 10) };
1688
- return { uid: stripped, generation: null };
1689
- }
1690
- function stampSnapshotGeneration(snapshot, generation) {
1691
- return snapshot.replace(/\buid=(\S+)/g, (match, uid) => {
1692
- if (/^g\d+:/.test(uid)) return match;
1693
- return `uid=g${generation}:${uid}`;
1694
- });
1695
- }
1696
- function checkUidGeneration(arg, currentGeneration) {
1697
- const { uid, generation } = parseStampedUid(arg);
1698
- return {
1699
- uid,
1700
- stale: generation !== null && generation !== currentGeneration,
1701
- refGeneration: generation
1702
- };
1703
- }
1704
- function extractTitle(snapshot) {
1705
- const rootMatch = snapshot.match(/RootWebArea\s+"([^"]+)"/);
1706
- if (rootMatch) return rootMatch[1];
1707
- const headingMatch = snapshot.match(/\bheading\s+"([^"]+)"/);
1708
- if (headingMatch) return headingMatch[1];
1709
- return "";
1710
- }
1711
- function truncateSnapshot(snapshot, full, limit = 16e3) {
1712
- const totalLength = snapshot.length;
1713
- if (full || totalLength <= limit) {
1714
- return { text: snapshot, truncated: false, totalLength };
1715
- }
1716
- const cut = snapshot.lastIndexOf("\n", limit);
1717
- const text = cut > 0 ? snapshot.slice(0, cut) : snapshot.slice(0, limit);
1718
- return { text, truncated: true, totalLength };
1719
- }
1720
- var MARKER_OVERHEAD = 50;
1721
- function truncateText(text, limit = 8e3) {
1722
- const totalLength = text.length;
1723
- if (totalLength <= limit) {
1724
- return { text, truncated: false, totalLength };
1725
- }
1726
- if (totalLength <= limit + MARKER_OVERHEAD) {
1727
- return { text, truncated: false, totalLength };
1728
- }
1729
- const headBudget = Math.floor(limit * 0.4);
1730
- const tailBudget = limit - headBudget;
1731
- const headCut = text.lastIndexOf("\n", headBudget);
1732
- const head = headCut > 0 ? text.slice(0, headCut) : text.slice(0, headBudget);
1733
- const tailStart = text.indexOf("\n", totalLength - tailBudget);
1734
- const tail = tailStart > 0 && tailStart < totalLength ? text.slice(tailStart + 1) : text.slice(totalLength - tailBudget);
1735
- const omitted = totalLength - head.length - tail.length;
1736
- const result = `${head}
1737
-
1738
- ... (${omitted} chars omitted, ${totalLength} total) ...
1739
-
1740
- ${tail}`;
1741
- return { text: result, truncated: true, totalLength };
1742
- }
1743
- var INPUT_TYPES = ["textbox", "searchbox", "input", "combobox", "textarea"];
1744
- function isInputType(type) {
1745
- return INPUT_TYPES.includes(type);
1746
- }
1639
+ import { request } from "node:http";
1640
+ import { createServer as createNetServer } from "node:net";
1641
+ import { dirname as dirname3 } from "node:path";
1747
1642
 
1748
- // vendor/chrome-devtools-axi/src/uid-freshness.ts
1643
+ // vendor/chrome-devtools-axi/src/page-observer-script.ts
1749
1644
  var PAGE_GENERATION_KEY = "__chromeDevtoolsAxiSnapshotGeneration";
1750
- async function captureFreshSnapshot(caller, capture) {
1751
- const first = await captureSnapshot(caller, capture);
1752
- const fresh = first.state?.generation === first.generation && first.state.mutations > 0 ? await captureSnapshot(caller, capture) : first;
1753
- return stampSnapshotGeneration(fresh.snapshot, fresh.generation);
1754
- }
1755
- function throwStaleRef(arg, refGeneration, currentGeneration) {
1756
- const refRaw = arg.startsWith("@") ? arg.slice(1) : arg;
1757
- const current = currentGeneration ?? "unavailable";
1758
- throw new CdpError(
1759
- `Stale ref @${refRaw}: from snapshot generation ${refGeneration}, current is ${current}. Re-snapshot to get fresh refs.`,
1760
- "STALE_REF",
1761
- [
1762
- "Run `chrome-devtools-axi snapshot` to capture current refs, then retry the action"
1763
- ]
1764
- );
1765
- }
1766
- async function markPageSnapshotGeneration(generation, caller) {
1767
- const key = JSON.stringify(PAGE_GENERATION_KEY);
1768
- try {
1769
- await caller("evaluate_script", {
1770
- function: `() => {
1771
- const key = ${key};
1772
- const previous = globalThis[key];
1773
- if (previous && previous.observer) previous.observer.disconnect();
1774
- const state = { generation: ${generation}, mutations: 0, observer: null };
1775
- const observer = new MutationObserver(() => { state.mutations += 1; });
1776
- observer.observe(document.documentElement || document, { childList: true, subtree: true, attributes: true, characterData: true });
1777
- state.observer = observer;
1778
- globalThis[key] = state;
1779
- return state.generation;
1780
- }`
1781
- });
1782
- } catch {
1783
- }
1784
- }
1785
- async function captureSnapshot(caller, capture) {
1786
- const generation = bumpGeneration();
1787
- await markPageSnapshotGeneration(generation, caller);
1788
- const snapshot = await capture();
1789
- return { generation, snapshot, state: await getPageRefState(caller) };
1790
- }
1791
- async function getPageRefState(caller) {
1792
- const key = JSON.stringify(PAGE_GENERATION_KEY);
1793
- try {
1794
- const output = await caller("evaluate_script", {
1795
- function: `() => {
1796
- const state = globalThis[${key}];
1797
- if (!state || typeof state.generation !== 'number' || typeof state.mutations !== 'number' || !state.observer) return null;
1798
- return { generation: state.generation, mutations: state.mutations };
1799
- }`
1800
- });
1801
- const jsonBlock = output.match(/```json\n([\s\S]*?)\n```/);
1802
- const raw = jsonBlock?.[1] ?? output.replace(/^Script ran on page and returned:\s*/, "");
1803
- const parsed = JSON.parse(raw.trim());
1804
- if (typeof parsed !== "object" || parsed === null || typeof parsed.generation !== "number" || typeof parsed.mutations !== "number") {
1805
- return null;
1806
- }
1807
- return parsed;
1808
- } catch {
1809
- return null;
1810
- }
1811
- }
1812
1645
  var CLEANUP_OBSERVER_SCRIPT = `() => {
1813
1646
  const key = ${JSON.stringify(PAGE_GENERATION_KEY)};
1814
1647
  const previous = globalThis[key];
@@ -1818,22 +1651,6 @@ var CLEANUP_OBSERVER_SCRIPT = `() => {
1818
1651
  try { delete globalThis[key]; } catch { globalThis[key] = undefined; }
1819
1652
  return true;
1820
1653
  }`;
1821
- async function parseUidFresh(arg, caller) {
1822
- const snapshotGeneration = getCurrentGeneration();
1823
- const check = checkUidGeneration(arg, snapshotGeneration);
1824
- if (check.stale) {
1825
- throwStaleRef(arg, check.refGeneration, snapshotGeneration);
1826
- }
1827
- const state = await getPageRefState(caller);
1828
- if (!state || state.generation !== snapshotGeneration || state.mutations !== 0) {
1829
- throwStaleRef(
1830
- arg,
1831
- parseStampedUid(arg).generation ?? snapshotGeneration,
1832
- state ? state.generation + state.mutations : null
1833
- );
1834
- }
1835
- return check.uid;
1836
- }
1837
1654
 
1838
1655
  // vendor/chrome-devtools-axi/src/client.ts
1839
1656
  var DEFAULT_BRIDGE_TIMEOUT_MS = 3e4;
@@ -1869,8 +1686,8 @@ var CdpError = class extends AxiError {
1869
1686
  };
1870
1687
  function readPidFile(pidFile = resolveSessionPidFile()) {
1871
1688
  try {
1872
- if (!existsSync4(pidFile)) return null;
1873
- const data = JSON.parse(readFileSync4(pidFile, "utf-8"));
1689
+ if (!existsSync3(pidFile)) return null;
1690
+ const data = JSON.parse(readFileSync3(pidFile, "utf-8"));
1874
1691
  if (typeof data.pid === "number" && typeof data.port === "number") {
1875
1692
  return data;
1876
1693
  }
@@ -1887,19 +1704,16 @@ function isProcessAlive(pid) {
1887
1704
  return error?.code !== "ESRCH";
1888
1705
  }
1889
1706
  }
1890
- var cachedLauncherHeader;
1891
1707
  function launcherHeader() {
1892
- cachedLauncherHeader ??= (() => {
1893
- const pid = process.env.PIE_SUPERVISOR_PID?.trim();
1894
- if (pid && Number.isInteger(Number(pid)) && Number(pid) > 0) {
1895
- const startTime = process.env.PIE_SUPERVISOR_START_TIME?.trim() ?? "";
1896
- return `${pid}:${startTime}`;
1897
- }
1898
- return `${process.pid}:${readSelfStartTime() ?? ""}`;
1899
- })();
1900
- 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;
1901
1714
  }
1902
1715
  function httpGetWithStatus(port, path, timeoutMs = 2e3) {
1716
+ const launcher = launcherHeader();
1903
1717
  return new Promise((resolve3, reject) => {
1904
1718
  const req = request(
1905
1719
  {
@@ -1908,9 +1722,7 @@ function httpGetWithStatus(port, path, timeoutMs = 2e3) {
1908
1722
  path,
1909
1723
  method: "GET",
1910
1724
  timeout: timeoutMs,
1911
- // Identify this launcher to the bridge so it can supervise our
1912
- // liveness and reap its detached tree when we die (leak fix).
1913
- headers: { "x-axi-launcher": launcherHeader() }
1725
+ ...launcher ? { headers: { "x-axi-launcher": launcher } } : {}
1914
1726
  },
1915
1727
  (res) => {
1916
1728
  res.setEncoding("utf8");
@@ -1972,7 +1784,28 @@ function httpPost(port, path, body, timeoutMs = 12e4) {
1972
1784
  }
1973
1785
  async function probeBridgeHealth(port, opts = {}) {
1974
1786
  try {
1975
- const path = opts.deep ? opts.waitMs !== void 0 ? `/health?deep=1&waitMs=${opts.waitMs}` : "/health?deep=1" : "/health";
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";
1976
1809
  const timeoutMs = opts.deep ? Math.max(DEEP_HEALTH_TIMEOUT_MS, (opts.waitMs ?? 0) + 2500) : HEALTH_TIMEOUT_MS;
1977
1810
  const { statusCode, body } = await httpGetWithStatus(port, path, timeoutMs);
1978
1811
  const data = JSON.parse(body);
@@ -1982,6 +1815,14 @@ async function probeBridgeHealth(port, opts = {}) {
1982
1815
  reason: `session mismatch (expected ${opts.expectedSession}, got ${data.session})`
1983
1816
  };
1984
1817
  }
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
+ };
1825
+ }
1985
1826
  if (statusCode === 202 || data.status === "pending") {
1986
1827
  return {
1987
1828
  kind: "pending",
@@ -1999,6 +1840,7 @@ async function probeBridgeHealth(port, opts = {}) {
1999
1840
  return {
2000
1841
  kind: "ok",
2001
1842
  busy: data.busy === true,
1843
+ ...typeof data.mode === "string" ? { mode: data.mode } : {},
2002
1844
  ...typeof data.cdpState === "string" ? { cdpState: data.cdpState } : {},
2003
1845
  ...typeof data.dialogPending === "boolean" ? { dialogPending: data.dialogPending } : {},
2004
1846
  pageIdentityChanged
@@ -2193,7 +2035,7 @@ function removePidFile(pidFile, expectedPid) {
2193
2035
  const current = readPidFile(pidFile);
2194
2036
  if (!current || current.pid !== expectedPid) return;
2195
2037
  }
2196
- unlinkSync2(pidFile);
2038
+ unlinkSync(pidFile);
2197
2039
  } catch {
2198
2040
  }
2199
2041
  }
@@ -2224,7 +2066,7 @@ async function terminateBridgeProcess(pid, opts = {}) {
2224
2066
  } catch (error) {
2225
2067
  if (error.code === "ESRCH") return true;
2226
2068
  }
2227
- if (await waitForProcessExit(pid, 2e3)) {
2069
+ if (await waitForProcessExit(pid, 6500)) {
2228
2070
  if (killProcessGroup) {
2229
2071
  try {
2230
2072
  process.kill(-pid, "SIGKILL");
@@ -2255,10 +2097,10 @@ async function terminateBridgeProcess(pid, opts = {}) {
2255
2097
  function openBridgeLogFd(sessionName) {
2256
2098
  try {
2257
2099
  const logFile = resolveSessionLogFile(sessionName);
2258
- mkdirSync3(dirname4(logFile), { recursive: true });
2100
+ mkdirSync2(dirname3(logFile), { recursive: true });
2259
2101
  let flags = "a";
2260
2102
  try {
2261
- if (existsSync4(logFile) && statSync2(logFile).size >= MAX_BRIDGE_LOG_BYTES) {
2103
+ if (existsSync3(logFile) && statSync2(logFile).size >= MAX_BRIDGE_LOG_BYTES) {
2262
2104
  flags = "w";
2263
2105
  }
2264
2106
  } catch {
@@ -2270,7 +2112,7 @@ function openBridgeLogFd(sessionName) {
2270
2112
  }
2271
2113
  function spawnBridgeProcess(port, sessionName) {
2272
2114
  const bridgeScript = resolveBridgeScript(import.meta.dirname);
2273
- const script = existsSync4(bridgeScript.replace(/\.js$/, ".ts")) ? bridgeScript.replace(/\.js$/, ".ts") : bridgeScript;
2115
+ const script = existsSync3(bridgeScript.replace(/\.js$/, ".ts")) ? bridgeScript.replace(/\.js$/, ".ts") : bridgeScript;
2274
2116
  const runner = script.endsWith(".ts") ? "tsx" : "node";
2275
2117
  const logFd = openBridgeLogFd(sessionName);
2276
2118
  try {
@@ -2300,11 +2142,34 @@ function spawnBridgeProcess(port, sessionName) {
2300
2142
  }
2301
2143
  }
2302
2144
  function isAutoConnectEnv() {
2303
- if (process.env.CHROME_DEVTOOLS_AXI_FRESH === "1") return false;
2304
- if (resolveSharedMcpMode() !== null) return false;
2305
- const explicit = process.env.CHROME_DEVTOOLS_AXI_AUTO_CONNECT;
2306
- const autoConnectUnset = explicit === void 0 || explicit === "";
2307
- return explicit === "1" || autoConnectUnset && !process.env.CHROME_DEVTOOLS_AXI_BROWSER_URL && !process.env.CHROME_DEVTOOLS_AXI_USER_DATA_DIR;
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
+ );
2308
2173
  }
2309
2174
  function notifyWaitingForApproval(sessionName, cdpState, logFile) {
2310
2175
  if (process.env.CHROME_DEVTOOLS_AXI_QUIET === "1") return;
@@ -2391,7 +2256,7 @@ function reclaimStaleStartLock(lockFile, expectedToken) {
2391
2256
  if (error.code !== "EEXIST") return;
2392
2257
  try {
2393
2258
  if (Date.now() - statSync2(reclaimFile).mtimeMs > 5e3) {
2394
- unlinkSync2(reclaimFile);
2259
+ unlinkSync(reclaimFile);
2395
2260
  continue;
2396
2261
  }
2397
2262
  } catch {
@@ -2402,22 +2267,22 @@ function reclaimStaleStartLock(lockFile, expectedToken) {
2402
2267
  try {
2403
2268
  closeSync(fd);
2404
2269
  try {
2405
- const raw = readFileSync4(lockFile, "utf8");
2270
+ const raw = readFileSync3(lockFile, "utf8");
2406
2271
  const parsed = JSON.parse(raw);
2407
2272
  if (expectedToken === void 0 || parsed.token === expectedToken) {
2408
- unlinkSync2(lockFile);
2273
+ unlinkSync(lockFile);
2409
2274
  }
2410
2275
  } catch {
2411
2276
  if (expectedToken === void 0) {
2412
2277
  try {
2413
- unlinkSync2(lockFile);
2278
+ unlinkSync(lockFile);
2414
2279
  } catch {
2415
2280
  }
2416
2281
  }
2417
2282
  }
2418
2283
  } finally {
2419
2284
  try {
2420
- unlinkSync2(reclaimFile);
2285
+ unlinkSync(reclaimFile);
2421
2286
  } catch {
2422
2287
  }
2423
2288
  }
@@ -2425,7 +2290,7 @@ function reclaimStaleStartLock(lockFile, expectedToken) {
2425
2290
  }
2426
2291
  }
2427
2292
  function tryAcquireStartLock(lockFile, staleMs) {
2428
- mkdirSync3(dirname4(lockFile), { recursive: true });
2293
+ mkdirSync2(dirname3(lockFile), { recursive: true });
2429
2294
  const token = randomUUID();
2430
2295
  const payload = JSON.stringify({
2431
2296
  pid: process.pid,
@@ -2436,7 +2301,7 @@ function tryAcquireStartLock(lockFile, staleMs) {
2436
2301
  try {
2437
2302
  const fd = openSync(lockFile, "wx");
2438
2303
  try {
2439
- writeFileSync3(fd, payload, "utf8");
2304
+ writeFileSync2(fd, payload, "utf8");
2440
2305
  } finally {
2441
2306
  closeSync(fd);
2442
2307
  }
@@ -2446,8 +2311,8 @@ function tryAcquireStartLock(lockFile, staleMs) {
2446
2311
  if (released) return;
2447
2312
  released = true;
2448
2313
  try {
2449
- const current = JSON.parse(readFileSync4(lockFile, "utf8"));
2450
- if (current.token === token) unlinkSync2(lockFile);
2314
+ const current = JSON.parse(readFileSync3(lockFile, "utf8"));
2315
+ if (current.token === token) unlinkSync(lockFile);
2451
2316
  } catch {
2452
2317
  }
2453
2318
  }
@@ -2457,7 +2322,7 @@ function tryAcquireStartLock(lockFile, staleMs) {
2457
2322
  let stale = false;
2458
2323
  let observedToken;
2459
2324
  try {
2460
- const existing = JSON.parse(readFileSync4(lockFile, "utf8"));
2325
+ const existing = JSON.parse(readFileSync3(lockFile, "utf8"));
2461
2326
  const holderPid = typeof existing.pid === "number" ? existing.pid : void 0;
2462
2327
  const createdAt = typeof existing.createdAt === "number" ? existing.createdAt : 0;
2463
2328
  observedToken = typeof existing.token === "string" ? existing.token : void 0;
@@ -2499,7 +2364,7 @@ function pinPendingGeneration(pidFile, pidInfo, probePid) {
2499
2364
  return void 0;
2500
2365
  }
2501
2366
  async function waitForPendingBridge(opts) {
2502
- const { port, sessionName, pidFile, initialProbe, autoConnect, notice } = opts;
2367
+ const { port, sessionName, pidFile, initialProbe, autoConnect, expectedMode, notice } = opts;
2503
2368
  const isApprovalWait = initialProbe.cdpState === "awaiting_approval" || autoConnect;
2504
2369
  if (isApprovalWait) {
2505
2370
  notifyWaitingForApproval(
@@ -2527,9 +2392,13 @@ async function waitForPendingBridge(opts) {
2527
2392
  const next = await probeBridgeHealth(port, {
2528
2393
  deep: true,
2529
2394
  expectedSession: sessionName,
2395
+ expectedMode,
2530
2396
  notice
2531
2397
  });
2532
2398
  if (next.kind === "ok") return port;
2399
+ if (next.kind === "mode_mismatch") {
2400
+ throw buildModeMismatchError(sessionName, next.runningMode, expectedMode ?? "unknown");
2401
+ }
2533
2402
  if (next.kind === "pending") continue;
2534
2403
  stillPending = false;
2535
2404
  if (next.kind === "cdp_error") {
@@ -2580,20 +2449,35 @@ async function waitForPendingBridge(opts) {
2580
2449
  }
2581
2450
  async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2582
2451
  const sessionName = resolveSessionName();
2583
- const port = resolveSessionPort(sessionName);
2452
+ let port = resolveSessionPort(sessionName);
2453
+ const hasExplicitPort = Boolean(process.env.CHROME_DEVTOOLS_AXI_PORT?.trim());
2584
2454
  const pidFile = resolveSessionPidFile(sessionName);
2585
2455
  const autoConnect = isAutoConnectEnv();
2456
+ const expectedMode = computeTransportModeFingerprint();
2586
2457
  const pidInfo = readPidFile(pidFile);
2587
2458
  if (pidInfo && isProcessAlive(pidInfo.pid)) {
2588
2459
  const existingProbe = await probeBridgeHealth(pidInfo.port, {
2589
2460
  deep: true,
2590
2461
  expectedSession: sessionName,
2462
+ expectedMode,
2591
2463
  notice
2592
2464
  });
2593
2465
  if (existingProbe.kind === "ok") {
2594
2466
  return pidInfo.port;
2595
2467
  }
2596
- if (existingProbe.kind === "pending") {
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") {
2597
2481
  const waited = await waitForPendingBridge({
2598
2482
  port: pidInfo.port,
2599
2483
  sessionName,
@@ -2601,6 +2485,7 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2601
2485
  initialProbe: existingProbe,
2602
2486
  pidInfo,
2603
2487
  autoConnect,
2488
+ expectedMode,
2604
2489
  notice
2605
2490
  });
2606
2491
  if (typeof waited === "number") return waited;
@@ -2614,10 +2499,18 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2614
2499
  requireBridgeIdentity: true,
2615
2500
  expectedStartTime: verdict.expectedStartTime
2616
2501
  });
2502
+ if (pidInfo.ownedProfileDir) {
2503
+ await cleanupOwnedProfileDir(pidInfo.ownedProfileDir);
2504
+ }
2617
2505
  } else {
2618
2506
  removePidFile(pidFile, pidInfo.pid);
2619
2507
  }
2620
2508
  }
2509
+ } else if (pidInfo && pidInfo.ownedProfileDir) {
2510
+ const reaped = await cleanupOwnedProfileDir(pidInfo.ownedProfileDir);
2511
+ if (reaped.clean) {
2512
+ removePidFile(pidFile, pidInfo.pid);
2513
+ }
2621
2514
  }
2622
2515
  const startLockFile = resolveSessionStartLockFile(sessionName);
2623
2516
  const lockBudgetMs = Math.max(START_LOCK_STALE_MS, resolveBridgeTimeoutMs());
@@ -2626,13 +2519,22 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2626
2519
  let startLock = null;
2627
2520
  let lockWaitDeadline = Date.now() + lockBudgetMs;
2628
2521
  while (true) {
2522
+ if (!hasExplicitPort) {
2523
+ const latestPid = readPidFile(pidFile);
2524
+ port = (latestPid && isProcessAlive(latestPid.pid) ? latestPid.port : void 0) ?? resolveSessionPort(sessionName);
2525
+ }
2629
2526
  startLock = tryAcquireStartLock(startLockFile, lockBudgetMs);
2630
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
+ }
2631
2532
  let postLockProbe;
2632
2533
  try {
2633
2534
  postLockProbe = await probeBridgeHealth(port, {
2634
2535
  deep: true,
2635
2536
  expectedSession: sessionName,
2537
+ expectedMode,
2636
2538
  notice
2637
2539
  });
2638
2540
  } catch (error) {
@@ -2643,6 +2545,14 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2643
2545
  startLock.release();
2644
2546
  return port;
2645
2547
  }
2548
+ if (postLockProbe.kind === "mode_mismatch") {
2549
+ startLock.release();
2550
+ throw buildModeMismatchError(
2551
+ sessionName,
2552
+ postLockProbe.runningMode,
2553
+ expectedMode
2554
+ );
2555
+ }
2646
2556
  if (postLockProbe.kind === "pending") {
2647
2557
  startLock.release();
2648
2558
  startLock = null;
@@ -2653,6 +2563,7 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2653
2563
  initialProbe: postLockProbe,
2654
2564
  pidInfo: null,
2655
2565
  autoConnect,
2566
+ expectedMode,
2656
2567
  notice
2657
2568
  });
2658
2569
  if (typeof waited === "number") return waited;
@@ -2691,11 +2602,19 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2691
2602
  const racingProbe = await probeBridgeHealth(port, {
2692
2603
  deep: true,
2693
2604
  expectedSession: sessionName,
2605
+ expectedMode,
2694
2606
  notice
2695
2607
  });
2696
2608
  if (racingProbe.kind === "ok") {
2697
2609
  return port;
2698
2610
  }
2611
+ if (racingProbe.kind === "mode_mismatch") {
2612
+ throw buildModeMismatchError(
2613
+ sessionName,
2614
+ racingProbe.runningMode,
2615
+ expectedMode
2616
+ );
2617
+ }
2699
2618
  if (racingProbe.kind === "pending") {
2700
2619
  const waited = await waitForPendingBridge({
2701
2620
  port,
@@ -2704,6 +2623,7 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2704
2623
  initialProbe: racingProbe,
2705
2624
  pidInfo: null,
2706
2625
  autoConnect,
2626
+ expectedMode,
2707
2627
  notice
2708
2628
  });
2709
2629
  if (typeof waited === "number") return waited;
@@ -2728,15 +2648,22 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2728
2648
  }
2729
2649
  try {
2730
2650
  clearSelectedPageId();
2731
- const child = spawnBridge(port, sessionName);
2651
+ let portCollisionRetried = false;
2652
+ let child = spawnBridge(port, sessionName);
2732
2653
  let childExited = false;
2733
2654
  let exitCode = null;
2734
2655
  let exitSignal = null;
2735
- child.on("exit", (code, signal) => {
2736
- childExited = true;
2737
- exitCode = code;
2738
- exitSignal = signal;
2739
- });
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);
2740
2667
  const timeoutMs = resolveBridgeTimeoutMs();
2741
2668
  let deadline = Date.now() + timeoutMs;
2742
2669
  let sawShallowReady = false;
@@ -2747,11 +2674,15 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2747
2674
  const probe = await probeBridgeHealth(port, {
2748
2675
  deep: true,
2749
2676
  expectedSession: sessionName,
2677
+ expectedMode,
2750
2678
  notice
2751
2679
  });
2752
2680
  if (probe.kind === "ok") {
2753
2681
  return port;
2754
2682
  }
2683
+ if (probe.kind === "mode_mismatch") {
2684
+ throw buildModeMismatchError(sessionName, probe.runningMode, expectedMode);
2685
+ }
2755
2686
  if (probe.kind === "pending") {
2756
2687
  startLock?.release();
2757
2688
  const isForeignWinner = childExited || probe.pid !== void 0 && child.pid !== void 0 && probe.pid !== child.pid;
@@ -2763,6 +2694,7 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2763
2694
  initialProbe: probe,
2764
2695
  pidInfo: null,
2765
2696
  autoConnect,
2697
+ expectedMode,
2766
2698
  notice
2767
2699
  });
2768
2700
  if (typeof waited === "number") return waited;
@@ -2800,6 +2732,7 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2800
2732
  let recheck = await probeBridgeHealth(port, {
2801
2733
  deep: true,
2802
2734
  expectedSession: sessionName,
2735
+ expectedMode,
2803
2736
  notice
2804
2737
  });
2805
2738
  if (recheck.kind === "unreachable" && exitCode === BRIDGE_PORT_IN_USE_EXIT_CODE) {
@@ -2807,8 +2740,25 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2807
2740
  recheck = await probeBridgeHealth(port, {
2808
2741
  deep: true,
2809
2742
  expectedSession: sessionName,
2743
+ expectedMode,
2810
2744
  notice
2811
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
+ );
2812
2762
  }
2813
2763
  if (recheck.kind === "ok") {
2814
2764
  return port;
@@ -2821,6 +2771,7 @@ async function ensureBridge(spawnBridge = spawnBridgeProcess, notice) {
2821
2771
  initialProbe: recheck,
2822
2772
  pidInfo: null,
2823
2773
  autoConnect,
2774
+ expectedMode,
2824
2775
  notice
2825
2776
  });
2826
2777
  if (typeof waited === "number") return waited;
@@ -2929,8 +2880,8 @@ var DIR_OUTPUT_ARGS_BY_TOOL = /* @__PURE__ */ new Map([
2929
2880
  ]);
2930
2881
  function nearestExistingAncestor(path) {
2931
2882
  let candidate = path;
2932
- while (!existsSync4(candidate)) {
2933
- const parent = dirname4(candidate);
2883
+ while (!existsSync3(candidate)) {
2884
+ const parent = dirname3(candidate);
2934
2885
  if (parent === candidate) return candidate;
2935
2886
  candidate = parent;
2936
2887
  }
@@ -2941,7 +2892,7 @@ function collectRootDirs(name, args) {
2941
2892
  for (const key of FILE_OUTPUT_ARGS_BY_TOOL.get(name) ?? []) {
2942
2893
  const value = args[key];
2943
2894
  if (typeof value === "string" && value.length > 0) {
2944
- dirs.add(nearestExistingAncestor(dirname4(value)));
2895
+ dirs.add(nearestExistingAncestor(dirname3(value)));
2945
2896
  }
2946
2897
  }
2947
2898
  for (const key of DIR_OUTPUT_ARGS_BY_TOOL.get(name) ?? []) {
@@ -2952,7 +2903,7 @@ function collectRootDirs(name, args) {
2952
2903
  }
2953
2904
  if (name === "upload_file" && Array.isArray(args.filePaths)) {
2954
2905
  for (const file of args.filePaths) {
2955
- if (typeof file === "string") dirs.add(dirname4(file));
2906
+ if (typeof file === "string") dirs.add(dirname3(file));
2956
2907
  }
2957
2908
  }
2958
2909
  return [...dirs];
@@ -3116,7 +3067,8 @@ async function getSessionSnapshotIfRunning() {
3116
3067
  return null;
3117
3068
  }
3118
3069
  const shallow = await probeBridgeHealth(pidInfo.port, {
3119
- expectedSession: sessionName
3070
+ expectedSession: sessionName,
3071
+ expectedMode: computeTransportModeFingerprint()
3120
3072
  });
3121
3073
  if (shallow.kind !== "ok" || shallow.busy || shallow.dialogPending || shallow.cdpState !== void 0 && shallow.cdpState !== "connected") {
3122
3074
  return null;
@@ -3167,13 +3119,28 @@ async function tryCleanupSessionObserver() {
3167
3119
  }
3168
3120
  }
3169
3121
  async function stopBridge(options = {}) {
3170
- const pidInfo = readPidFile();
3171
- if (!pidInfo) return "noop";
3172
- 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
+ }
3173
3129
  if (options.expectedGeneration && (options.expectedGeneration.pid !== pidInfo.pid || options.expectedGeneration.startTime !== pidInfo.startTime)) {
3174
3130
  return "noop";
3175
3131
  }
3176
- 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);
3177
3144
  if (!verdict.terminate) return "noop";
3178
3145
  const targetPid = verdict.targetPid ?? pidInfo.pid;
3179
3146
  if (options.expectedGeneration && targetPid !== options.expectedGeneration.pid) {
@@ -3184,8 +3151,52 @@ async function stopBridge(options = {}) {
3184
3151
  requireBridgeIdentity: true,
3185
3152
  expectedStartTime: options.expectedGeneration ? options.expectedGeneration.startTime ?? verdict.expectedStartTime : verdict.expectedStartTime
3186
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
+ }
3187
3165
  clearSelectedPageId();
3188
- return terminated ? "stopped" : "failed";
3166
+ return "failed";
3167
+ }
3168
+
3169
+ // vendor/chrome-devtools-axi/src/generation.ts
3170
+ import {
3171
+ existsSync as existsSync4,
3172
+ mkdirSync as mkdirSync3,
3173
+ readFileSync as readFileSync4,
3174
+ unlinkSync as unlinkSync2,
3175
+ writeFileSync as writeFileSync3
3176
+ } from "node:fs";
3177
+ import { dirname as dirname4, join as join3 } from "node:path";
3178
+ function genFile() {
3179
+ return join3(resolveSessionStateDir(), "snapshot-generation");
3180
+ }
3181
+ function getCurrentGeneration() {
3182
+ const file = genFile();
3183
+ try {
3184
+ if (!existsSync4(file)) return 0;
3185
+ const parsed = Number.parseInt(readFileSync4(file, "utf-8").trim(), 10);
3186
+ return Number.isNaN(parsed) ? 0 : parsed;
3187
+ } catch {
3188
+ return 0;
3189
+ }
3190
+ }
3191
+ function bumpGeneration() {
3192
+ const next = getCurrentGeneration() + 1;
3193
+ const file = genFile();
3194
+ try {
3195
+ mkdirSync3(dirname4(file), { recursive: true });
3196
+ writeFileSync3(file, String(next));
3197
+ } catch {
3198
+ }
3199
+ return next;
3189
3200
  }
3190
3201
 
3191
3202
  // vendor/chrome-devtools-axi/src/run.ts
@@ -3200,6 +3211,164 @@ function resolveOutputPath(filePath) {
3200
3211
  return isAbsolute(filePath) ? filePath : resolve2(process.cwd(), filePath);
3201
3212
  }
3202
3213
 
3214
+ // vendor/chrome-devtools-axi/src/snapshot.ts
3215
+ function countRefs(snapshot) {
3216
+ const matches = snapshot.match(/\buid=\S+/g);
3217
+ return matches ? matches.length : 0;
3218
+ }
3219
+ function extractRefs(snapshot) {
3220
+ const refs = [];
3221
+ for (const line of snapshot.split("\n")) {
3222
+ const m = line.match(/\buid=(\S+)\s+(\w+)\s+"([^"]*)"/);
3223
+ if (!m) continue;
3224
+ refs.push({ ref: m[1], type: m[2], label: m[3] });
3225
+ }
3226
+ return refs;
3227
+ }
3228
+ function parseStampedUid(arg) {
3229
+ const stripped = arg.startsWith("@") ? arg.slice(1) : arg;
3230
+ const m = stripped.match(/^g(\d+):(.+)$/);
3231
+ if (m) return { uid: m[2], generation: Number.parseInt(m[1], 10) };
3232
+ return { uid: stripped, generation: null };
3233
+ }
3234
+ function stampSnapshotGeneration(snapshot, generation) {
3235
+ return snapshot.replace(/\buid=(\S+)/g, (match, uid) => {
3236
+ if (/^g\d+:/.test(uid)) return match;
3237
+ return `uid=g${generation}:${uid}`;
3238
+ });
3239
+ }
3240
+ function checkUidGeneration(arg, currentGeneration) {
3241
+ const { uid, generation } = parseStampedUid(arg);
3242
+ return {
3243
+ uid,
3244
+ stale: generation !== null && generation !== currentGeneration,
3245
+ refGeneration: generation
3246
+ };
3247
+ }
3248
+ function extractTitle(snapshot) {
3249
+ const rootMatch = snapshot.match(/RootWebArea\s+"([^"]+)"/);
3250
+ if (rootMatch) return rootMatch[1];
3251
+ const headingMatch = snapshot.match(/\bheading\s+"([^"]+)"/);
3252
+ if (headingMatch) return headingMatch[1];
3253
+ return "";
3254
+ }
3255
+ function truncateSnapshot(snapshot, full, limit = 16e3) {
3256
+ const totalLength = snapshot.length;
3257
+ if (full || totalLength <= limit) {
3258
+ return { text: snapshot, truncated: false, totalLength };
3259
+ }
3260
+ const cut = snapshot.lastIndexOf("\n", limit);
3261
+ const text = cut > 0 ? snapshot.slice(0, cut) : snapshot.slice(0, limit);
3262
+ return { text, truncated: true, totalLength };
3263
+ }
3264
+ var MARKER_OVERHEAD = 50;
3265
+ function truncateText(text, limit = 8e3) {
3266
+ const totalLength = text.length;
3267
+ if (totalLength <= limit) {
3268
+ return { text, truncated: false, totalLength };
3269
+ }
3270
+ if (totalLength <= limit + MARKER_OVERHEAD) {
3271
+ return { text, truncated: false, totalLength };
3272
+ }
3273
+ const headBudget = Math.floor(limit * 0.4);
3274
+ const tailBudget = limit - headBudget;
3275
+ const headCut = text.lastIndexOf("\n", headBudget);
3276
+ const head = headCut > 0 ? text.slice(0, headCut) : text.slice(0, headBudget);
3277
+ const tailStart = text.indexOf("\n", totalLength - tailBudget);
3278
+ const tail = tailStart > 0 && tailStart < totalLength ? text.slice(tailStart + 1) : text.slice(totalLength - tailBudget);
3279
+ const omitted = totalLength - head.length - tail.length;
3280
+ const result = `${head}
3281
+
3282
+ ... (${omitted} chars omitted, ${totalLength} total) ...
3283
+
3284
+ ${tail}`;
3285
+ return { text: result, truncated: true, totalLength };
3286
+ }
3287
+ var INPUT_TYPES = ["textbox", "searchbox", "input", "combobox", "textarea"];
3288
+ function isInputType(type) {
3289
+ return INPUT_TYPES.includes(type);
3290
+ }
3291
+
3292
+ // vendor/chrome-devtools-axi/src/uid-freshness.ts
3293
+ async function captureFreshSnapshot(caller, capture) {
3294
+ const first = await captureSnapshot(caller, capture);
3295
+ const fresh = first.state?.generation === first.generation && first.state.mutations > 0 ? await captureSnapshot(caller, capture) : first;
3296
+ return stampSnapshotGeneration(fresh.snapshot, fresh.generation);
3297
+ }
3298
+ function throwStaleRef(arg, refGeneration, currentGeneration) {
3299
+ const refRaw = arg.startsWith("@") ? arg.slice(1) : arg;
3300
+ const current = currentGeneration ?? "unavailable";
3301
+ throw new CdpError(
3302
+ `Stale ref @${refRaw}: from snapshot generation ${refGeneration}, current is ${current}. Re-snapshot to get fresh refs.`,
3303
+ "STALE_REF",
3304
+ [
3305
+ "Run `chrome-devtools-axi snapshot` to capture current refs, then retry the action"
3306
+ ]
3307
+ );
3308
+ }
3309
+ async function markPageSnapshotGeneration(generation, caller) {
3310
+ const key = JSON.stringify(PAGE_GENERATION_KEY);
3311
+ try {
3312
+ await caller("evaluate_script", {
3313
+ function: `() => {
3314
+ const key = ${key};
3315
+ const previous = globalThis[key];
3316
+ if (previous && previous.observer) previous.observer.disconnect();
3317
+ const state = { generation: ${generation}, mutations: 0, observer: null };
3318
+ const observer = new MutationObserver(() => { state.mutations += 1; });
3319
+ observer.observe(document.documentElement || document, { childList: true, subtree: true, attributes: true, characterData: true });
3320
+ state.observer = observer;
3321
+ globalThis[key] = state;
3322
+ return state.generation;
3323
+ }`
3324
+ });
3325
+ } catch {
3326
+ }
3327
+ }
3328
+ async function captureSnapshot(caller, capture) {
3329
+ const generation = bumpGeneration();
3330
+ await markPageSnapshotGeneration(generation, caller);
3331
+ const snapshot = await capture();
3332
+ return { generation, snapshot, state: await getPageRefState(caller) };
3333
+ }
3334
+ async function getPageRefState(caller) {
3335
+ const key = JSON.stringify(PAGE_GENERATION_KEY);
3336
+ try {
3337
+ const output = await caller("evaluate_script", {
3338
+ function: `() => {
3339
+ const state = globalThis[${key}];
3340
+ if (!state || typeof state.generation !== 'number' || typeof state.mutations !== 'number' || !state.observer) return null;
3341
+ return { generation: state.generation, mutations: state.mutations };
3342
+ }`
3343
+ });
3344
+ const jsonBlock = output.match(/```json\n([\s\S]*?)\n```/);
3345
+ const raw = jsonBlock?.[1] ?? output.replace(/^Script ran on page and returned:\s*/, "");
3346
+ const parsed = JSON.parse(raw.trim());
3347
+ if (typeof parsed !== "object" || parsed === null || typeof parsed.generation !== "number" || typeof parsed.mutations !== "number") {
3348
+ return null;
3349
+ }
3350
+ return parsed;
3351
+ } catch {
3352
+ return null;
3353
+ }
3354
+ }
3355
+ async function parseUidFresh(arg, caller) {
3356
+ const snapshotGeneration = getCurrentGeneration();
3357
+ const check = checkUidGeneration(arg, snapshotGeneration);
3358
+ if (check.stale) {
3359
+ throwStaleRef(arg, check.refGeneration, snapshotGeneration);
3360
+ }
3361
+ const state = await getPageRefState(caller);
3362
+ if (!state || state.generation !== snapshotGeneration || state.mutations !== 0) {
3363
+ throwStaleRef(
3364
+ arg,
3365
+ parseStampedUid(arg).generation ?? snapshotGeneration,
3366
+ state ? state.generation + state.mutations : null
3367
+ );
3368
+ }
3369
+ return check.uid;
3370
+ }
3371
+
3203
3372
  // vendor/chrome-devtools-axi/src/run.ts
3204
3373
  function parseRunPageId(args) {
3205
3374
  if (args.length === 0) return null;
@@ -4804,7 +4973,10 @@ async function handleScroll(args, full) {
4804
4973
  const deltaY = ${JSON.stringify(deltaY)};
4805
4974
  let handledByWheel = false;
4806
4975
  if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
4807
- handledByWheel = !el.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
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;
4808
4980
  }
4809
4981
  if (handledByWheel) return;
4810
4982
  if (dir === 'top') el.scrollTop = 0;
@@ -4822,7 +4994,10 @@ async function handleScroll(args, full) {
4822
4994
  const deltaY = ${JSON.stringify(deltaY)};
4823
4995
  let handledByWheel = false;
4824
4996
  if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
4825
- handledByWheel = !el.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
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;
4826
5001
  }
4827
5002
  if (handledByWheel) return;
4828
5003
  if (dir === 'top') el.scrollTop = 0;
@@ -4838,7 +5013,10 @@ async function handleScroll(args, full) {
4838
5013
  let handledByWheel = false;
4839
5014
  if (${JSON.stringify(wheel)} && (dir === 'up' || dir === 'down')) {
4840
5015
  const target = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2) || document.documentElement;
4841
- handledByWheel = !target.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true, cancelable: true }));
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;
4842
5020
  }
4843
5021
  if (handledByWheel) return;
4844
5022
  if (dir === 'top') window.scrollTo(0, 0);