@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
@@ -3,13 +3,24 @@ import { createRequire as __axiRequire } from "node:module"; const require = __a
3
3
  import {
4
4
  BRIDGE_PORT_IN_USE_EXIT_CODE,
5
5
  PAGE_IDENTITY_CHANGED_ERROR,
6
+ allocateOwnedProfileDir,
7
+ cleanupOwnedProfileDir,
6
8
  clearSelectedPageId,
9
+ computeTransportModeFingerprint,
7
10
  inspectProcessIdentity,
11
+ isAttachTransportMode,
12
+ isAutoConnectMode,
13
+ isManagedIsolatedMode,
14
+ isSupervisorGone,
15
+ parseSupervisorAnchor,
8
16
  readSelfStartTime,
17
+ reapStaleOwnedProfiles,
18
+ resolveSessionLogFile,
9
19
  resolveSessionName,
10
20
  resolveSessionPidFile,
11
- resolveSessionPort
12
- } from "./chunk-WOGAQ4P5.js";
21
+ resolveSessionPort,
22
+ resolveSessionStateDir
23
+ } from "./chunk-HAUDUMDO.js";
13
24
  import {
14
25
  __commonJS,
15
26
  __export,
@@ -19572,36 +19583,6 @@ import {
19572
19583
  } from "node:fs";
19573
19584
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
19574
19585
  import { pathToFileURL } from "node:url";
19575
-
19576
- // vendor/chrome-devtools-axi/src/supervisor-anchor-shared.ts
19577
- var SUPERVISOR_PID_ENV = "PIE_SUPERVISOR_PID";
19578
- var SUPERVISOR_START_TIME_ENV = "PIE_SUPERVISOR_START_TIME";
19579
- function parseSupervisorAnchor(env = process.env) {
19580
- const pidText = env[SUPERVISOR_PID_ENV]?.trim();
19581
- if (!pidText || !/^\d+$/.test(pidText)) return void 0;
19582
- const pid = Number(pidText);
19583
- if (!Number.isSafeInteger(pid) || pid <= 0) return void 0;
19584
- const startTime = env[SUPERVISOR_START_TIME_ENV]?.trim();
19585
- return startTime ? { pid, startTime } : { pid };
19586
- }
19587
- function isSupervisorGone(anchor2, readIdentity) {
19588
- try {
19589
- process.kill(anchor2.pid, 0);
19590
- } catch (error2) {
19591
- return error2.code === "ESRCH";
19592
- }
19593
- let identity;
19594
- try {
19595
- identity = readIdentity(anchor2.pid);
19596
- } catch {
19597
- return false;
19598
- }
19599
- if (identity.startTime === void 0) return false;
19600
- if (anchor2.startTime === void 0) return false;
19601
- return identity.startTime !== anchor2.startTime;
19602
- }
19603
-
19604
- // vendor/chrome-devtools-axi/src/bridge.ts
19605
19586
  async function isBridgeClientConnected(client) {
19606
19587
  try {
19607
19588
  await client.listTools();
@@ -19628,10 +19609,19 @@ async function isBridgeTargetReachable(client) {
19628
19609
  return { ok: false, reason: getErrorMessage(error2) };
19629
19610
  }
19630
19611
  }
19631
- function writePidFile(port) {
19612
+ function writePidFile(port, meta2 = {}) {
19632
19613
  const pidFile = resolveSessionPidFile();
19633
19614
  mkdirSync(dirname(pidFile), { recursive: true });
19634
- writeFileSync(pidFile, JSON.stringify({ pid: process.pid, port, startTime: readSelfStartTime() }));
19615
+ writeFileSync(
19616
+ pidFile,
19617
+ JSON.stringify({
19618
+ pid: process.pid,
19619
+ port,
19620
+ startTime: readSelfStartTime(),
19621
+ ...meta2.mode ? { mode: meta2.mode } : {},
19622
+ ...meta2.ownedProfileDir ? { ownedProfileDir: meta2.ownedProfileDir } : {}
19623
+ })
19624
+ );
19635
19625
  }
19636
19626
  function removePidFile(pidFile = resolveSessionPidFile(), ownerPid = process.pid) {
19637
19627
  try {
@@ -19790,7 +19780,44 @@ async function handleCallRequest(client, req, res, onPageIdentityChanged) {
19790
19780
  }
19791
19781
  writeJson(res, 200, { result: text });
19792
19782
  }
19793
- async function handleBridgeRequest(client, req, res, sessionName, logForbidden, onPageIdentityChanged) {
19783
+ var DEFAULT_DEEP_HEALTH_WAIT_MS = 2500;
19784
+ var MAX_DEEP_HEALTH_WAIT_MS = 3e4;
19785
+ function parseDeepHealthWaitMs(url2) {
19786
+ const queryStart = url2.indexOf("?");
19787
+ if (queryStart === -1) return DEFAULT_DEEP_HEALTH_WAIT_MS;
19788
+ const params = new URLSearchParams(url2.slice(queryStart + 1));
19789
+ const raw = params.get("waitMs");
19790
+ if (!raw) return DEFAULT_DEEP_HEALTH_WAIT_MS;
19791
+ const parsed = Number.parseInt(raw, 10);
19792
+ if (!Number.isFinite(parsed) || parsed < 0) return DEFAULT_DEEP_HEALTH_WAIT_MS;
19793
+ return Math.min(parsed, MAX_DEEP_HEALTH_WAIT_MS);
19794
+ }
19795
+ async function raceWithTimeout(promise, timeoutMs) {
19796
+ if (timeoutMs <= 0) {
19797
+ let settled = false;
19798
+ let value;
19799
+ await Promise.race([
19800
+ promise.then((v) => {
19801
+ settled = true;
19802
+ value = v;
19803
+ }),
19804
+ new Promise((resolve2) => setImmediate(resolve2))
19805
+ ]);
19806
+ return settled ? { settled: true, value } : { settled: false };
19807
+ }
19808
+ let timer;
19809
+ try {
19810
+ return await Promise.race([
19811
+ promise.then((value) => ({ settled: true, value })),
19812
+ new Promise((resolve2) => {
19813
+ timer = setTimeout(() => resolve2({ settled: false }), timeoutMs);
19814
+ })
19815
+ ]);
19816
+ } finally {
19817
+ if (timer) clearTimeout(timer);
19818
+ }
19819
+ }
19820
+ async function handleBridgeRequest(client, req, res, sessionName, logForbidden, onPageIdentityChanged, pendingDroppedSelectionLatch, modeFingerprint) {
19794
19821
  res.setHeader("Content-Type", "application/json");
19795
19822
  if (!isRequestAllowed(req)) {
19796
19823
  const rawOrigin = req.headers.origin;
@@ -19803,35 +19830,115 @@ async function handleBridgeRequest(client, req, res, sessionName, logForbidden,
19803
19830
  }
19804
19831
  try {
19805
19832
  if (req.method === "GET" && (req.url === "/health" || req.url?.startsWith("/health?"))) {
19833
+ const parsedHealthUrl = new URL(req.url, "http://127.0.0.1");
19834
+ const requestedMode = parsedHealthUrl.searchParams.get("mode");
19835
+ if (requestedMode && (!modeFingerprint || requestedMode !== modeFingerprint)) {
19836
+ writeJson(res, 409, {
19837
+ status: "mode_mismatch",
19838
+ error: "Transport mode mismatch",
19839
+ session: sessionName,
19840
+ ...modeFingerprint ? { mode: modeFingerprint } : {},
19841
+ pid: process.pid,
19842
+ busy: client.isBusy?.() ?? false
19843
+ });
19844
+ return;
19845
+ }
19806
19846
  if (!await isBridgeClientConnected(client)) {
19807
- writeJson(res, 503, { status: "error", error: "Not connected" });
19847
+ writeJson(res, 503, {
19848
+ status: "error",
19849
+ error: "Not connected",
19850
+ mcpDisconnected: true,
19851
+ session: sessionName,
19852
+ ...modeFingerprint ? { mode: modeFingerprint } : {},
19853
+ pid: process.pid
19854
+ });
19808
19855
  return;
19809
19856
  }
19810
19857
  const deep = req.url.includes("deep=1");
19858
+ const statusBefore = client.getStatus?.();
19859
+ const busyBefore = client.isBusy?.() ?? false;
19860
+ const probeInFlight = statusBefore?.probeInFlight ?? false;
19811
19861
  let droppedSelection = false;
19812
- if (deep && !client.isBusy?.()) {
19813
- const probe = await isBridgeTargetReachable(client);
19814
- if (!probe.ok) {
19815
- writeJson(res, 503, {
19816
- status: "error",
19817
- error: "CDP target unreachable",
19818
- reason: probe.reason
19862
+ if (deep && (!busyBefore || probeInFlight)) {
19863
+ if (client.probeReachable) {
19864
+ const waitMs = parseDeepHealthWaitMs(req.url);
19865
+ const probePromise = client.probeReachable();
19866
+ let responded = false;
19867
+ void probePromise.then((probe2) => {
19868
+ if (!responded || !probe2.ok || !probe2.pageIdentityChanged) return;
19869
+ if (onPageIdentityChanged?.() === true && pendingDroppedSelectionLatch) {
19870
+ pendingDroppedSelectionLatch.value = true;
19871
+ }
19819
19872
  });
19820
- return;
19821
- }
19822
- if (probe.pageIdentityChanged) {
19823
- droppedSelection = onPageIdentityChanged?.() === true;
19873
+ const raced = await raceWithTimeout(probePromise, waitMs);
19874
+ if (!raced.settled) {
19875
+ responded = true;
19876
+ const currentStatus = client.getStatus?.();
19877
+ writeJson(res, 202, {
19878
+ status: "pending",
19879
+ session: sessionName,
19880
+ ...modeFingerprint ? { mode: modeFingerprint } : {},
19881
+ pid: process.pid,
19882
+ busy: true,
19883
+ cdpState: currentStatus?.cdpState ?? "awaiting_approval",
19884
+ ...currentStatus?.waitingMs !== void 0 ? { waitingMs: currentStatus.waitingMs } : {},
19885
+ logFile: resolveSessionLogFile(sessionName)
19886
+ });
19887
+ return;
19888
+ }
19889
+ const probe = raced.value;
19890
+ if (!probe.ok) {
19891
+ writeJson(res, 503, {
19892
+ status: "error",
19893
+ error: "CDP target unreachable",
19894
+ reason: probe.reason,
19895
+ cdpState: client.getStatus?.().cdpState ?? "failed",
19896
+ session: sessionName,
19897
+ ...modeFingerprint ? { mode: modeFingerprint } : {},
19898
+ pid: process.pid
19899
+ });
19900
+ return;
19901
+ }
19902
+ if (probe.pageIdentityChanged) {
19903
+ droppedSelection = onPageIdentityChanged?.() === true;
19904
+ }
19905
+ } else {
19906
+ const probe = await isBridgeTargetReachable(client);
19907
+ if (!probe.ok) {
19908
+ writeJson(res, 503, {
19909
+ status: "error",
19910
+ error: "CDP target unreachable",
19911
+ reason: probe.reason,
19912
+ session: sessionName,
19913
+ ...modeFingerprint ? { mode: modeFingerprint } : {},
19914
+ pid: process.pid
19915
+ });
19916
+ return;
19917
+ }
19918
+ if (probe.pageIdentityChanged) {
19919
+ droppedSelection = onPageIdentityChanged?.() === true;
19920
+ }
19824
19921
  }
19825
19922
  }
19923
+ if (deep && pendingDroppedSelectionLatch?.value) {
19924
+ droppedSelection = true;
19925
+ pendingDroppedSelectionLatch.value = false;
19926
+ }
19927
+ const statusAfter = client.getStatus?.();
19826
19928
  writeJson(res, 200, {
19827
19929
  status: "ok",
19828
19930
  session: sessionName,
19931
+ ...modeFingerprint ? { mode: modeFingerprint } : {},
19829
19932
  // The bridge's own PID so `stop` can verify that the process named
19830
19933
  // in a (possibly stale) pid file is really THIS bridge before any
19831
19934
  // signal is sent — a healthy session on the recorded port alone
19832
19935
  // must not authorize killing an unrelated reused PID.
19833
19936
  pid: process.pid,
19834
19937
  busy: client.isBusy?.() ?? false,
19938
+ ...statusAfter ? {
19939
+ cdpState: statusAfter.cdpState,
19940
+ dialogPending: statusAfter.dialogPending
19941
+ } : {},
19835
19942
  ...droppedSelection ? { pageIdentityChanged: true } : {}
19836
19943
  });
19837
19944
  return;
@@ -19850,7 +19957,7 @@ async function handleBridgeRequest(client, req, res, sessionName, logForbidden,
19850
19957
  }
19851
19958
  writeJson(res, 404, { error: "not found" });
19852
19959
  }
19853
- function createBridgeServer(client, sessionName) {
19960
+ function createBridgeServer(client, sessionName, pendingDroppedSelectionLatch = { value: false }, modeFingerprint) {
19854
19961
  return createServer((req, res) => {
19855
19962
  void handleBridgeRequest(
19856
19963
  client,
@@ -19858,7 +19965,9 @@ function createBridgeServer(client, sessionName) {
19858
19965
  res,
19859
19966
  sessionName,
19860
19967
  logBridgeMessage,
19861
- clearSelectedPageId
19968
+ clearSelectedPageId,
19969
+ pendingDroppedSelectionLatch,
19970
+ modeFingerprint
19862
19971
  );
19863
19972
  });
19864
19973
  }
@@ -19900,6 +20009,7 @@ function createBridgeLifecycle(shutdown, opts = {}) {
19900
20009
  const heartbeatMs = opts.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
19901
20010
  const idleShutdownMs = opts.idleShutdownMs ?? DEFAULT_IDLE_SHUTDOWN_MS;
19902
20011
  const now = opts.now ?? Date.now;
20012
+ const suspendIdleWhileSupervisorAlive = opts.suspendIdleWhileSupervisorAlive ?? true;
19903
20013
  let supervisor;
19904
20014
  let supervisorFromEnv = false;
19905
20015
  if (opts.anchor) {
@@ -19907,6 +20017,7 @@ function createBridgeLifecycle(shutdown, opts = {}) {
19907
20017
  supervisorFromEnv = true;
19908
20018
  }
19909
20019
  let lastRequestAt = now();
20020
+ let inFlightRequests = 0;
19910
20021
  let disposed = false;
19911
20022
  const fire = (reason) => {
19912
20023
  disposed = true;
@@ -19924,7 +20035,8 @@ function createBridgeLifecycle(shutdown, opts = {}) {
19924
20035
  fire(`supervisor pid ${supervisor.pid} is gone and no requests since; shutting down`);
19925
20036
  return;
19926
20037
  }
19927
- if (!supervisor && t - lastRequestAt >= idleShutdownMs) {
20038
+ const supervisorSuspendsIdle = Boolean(supervisor) && suspendIdleWhileSupervisorAlive;
20039
+ if (!supervisorSuspendsIdle && inFlightRequests === 0 && t - lastRequestAt >= idleShutdownMs) {
19928
20040
  fire(`idle ${Math.round((t - lastRequestAt) / 1e3)}s \u2265 ${Math.round(idleShutdownMs / 1e3)}s with no requests; shutting down`);
19929
20041
  return;
19930
20042
  }
@@ -19932,8 +20044,20 @@ function createBridgeLifecycle(shutdown, opts = {}) {
19932
20044
  const timer = setInterval(tick, heartbeatMs);
19933
20045
  timer.unref?.();
19934
20046
  return {
19935
- observeRequest(req) {
20047
+ observeRequest(req, res) {
19936
20048
  lastRequestAt = now();
20049
+ if (res && !res.writableEnded && !res.destroyed) {
20050
+ inFlightRequests++;
20051
+ let done = false;
20052
+ const release = () => {
20053
+ if (done) return;
20054
+ done = true;
20055
+ inFlightRequests = Math.max(0, inFlightRequests - 1);
20056
+ lastRequestAt = now();
20057
+ };
20058
+ res.once("finish", release);
20059
+ res.once("close", release);
20060
+ }
19937
20061
  if (supervisorFromEnv) return;
19938
20062
  const next = parseLauncherHeader(req.headers[LAUNCHER_HEADER]);
19939
20063
  if (!next) return;
@@ -19950,33 +20074,32 @@ var KEYCHAIN_ISOLATION_CHROME_ARGS = [
19950
20074
  "--use-mock-keychain",
19951
20075
  "--password-store=basic"
19952
20076
  ];
19953
- function isAttachTransportMode() {
19954
- const explicitAutoConnect = process.env.CHROME_DEVTOOLS_AXI_AUTO_CONNECT;
19955
- const freshInstance = process.env.CHROME_DEVTOOLS_AXI_FRESH === "1";
19956
- const browserUrl = process.env.CHROME_DEVTOOLS_AXI_BROWSER_URL;
19957
- const userDataDir = process.env.CHROME_DEVTOOLS_AXI_USER_DATA_DIR;
19958
- const autoConnectUnset = explicitAutoConnect === void 0 || explicitAutoConnect === "";
19959
- const autoConnect = !freshInstance && (explicitAutoConnect === "1" || autoConnectUnset && !browserUrl && !userDataDir);
19960
- return autoConnect || !freshInstance && !!browserUrl;
20077
+ var DEFAULT_MANAGED_IDLE_SHUTDOWN_MS = 10 * 6e4;
20078
+ function resolveIdleShutdownMs(attachMode) {
20079
+ const raw = Number(process.env.CHROME_DEVTOOLS_AXI_IDLE_TIMEOUT_MS);
20080
+ if (Number.isFinite(raw) && raw >= 5e3 && raw <= 864e5) return raw;
20081
+ return attachMode ? DEFAULT_IDLE_SHUTDOWN_MS : DEFAULT_MANAGED_IDLE_SHUTDOWN_MS;
19961
20082
  }
19962
20083
  function resolveCdpKeepaliveMs() {
19963
20084
  const raw = Number(process.env.CHROME_DEVTOOLS_AXI_CDP_KEEPALIVE_MS);
19964
20085
  if (Number.isFinite(raw) && raw >= 1e3 && raw <= 6e4) return raw;
19965
20086
  return 1e4;
19966
20087
  }
19967
- function buildTransportArgs() {
20088
+ function buildTransportArgs(opts = {}) {
19968
20089
  const args = ["-y", "chrome-devtools-mcp@1.13.0"];
19969
20090
  const freshInstance = process.env.CHROME_DEVTOOLS_AXI_FRESH === "1";
19970
- const browserUrl = process.env.CHROME_DEVTOOLS_AXI_BROWSER_URL;
19971
- const userDataDir = process.env.CHROME_DEVTOOLS_AXI_USER_DATA_DIR;
20091
+ const browserUrl = process.env.CHROME_DEVTOOLS_AXI_BROWSER_URL?.trim();
20092
+ const userDataDir = process.env.CHROME_DEVTOOLS_AXI_USER_DATA_DIR?.trim();
19972
20093
  const channel = process.env.CHROME_DEVTOOLS_AXI_CHANNEL?.trim();
19973
- const explicitAutoConnect = process.env.CHROME_DEVTOOLS_AXI_AUTO_CONNECT;
19974
- const autoConnectUnset = explicitAutoConnect === void 0 || explicitAutoConnect === "";
19975
- const autoConnect = !freshInstance && (explicitAutoConnect === "1" || autoConnectUnset && !browserUrl && !userDataDir);
20094
+ const autoConnect = !freshInstance && (process.env.CHROME_DEVTOOLS_AXI_AUTO_CONNECT === "1" || process.env.CHROME_DEVTOOLS_AXI_ATTACH === "1");
19976
20095
  if (autoConnect) {
19977
20096
  args.push("--autoConnect");
19978
20097
  } else if (freshInstance) {
19979
- args.push("--isolated");
20098
+ if (opts.ownedProfileDir) {
20099
+ args.push(`--userDataDir=${opts.ownedProfileDir}`);
20100
+ } else {
20101
+ args.push("--isolated");
20102
+ }
19980
20103
  if (process.env.CHROME_DEVTOOLS_AXI_HEADED !== "1") {
19981
20104
  args.push("--headless");
19982
20105
  }
@@ -20008,6 +20131,8 @@ function buildTransportArgs() {
20008
20131
  } else {
20009
20132
  if (userDataDir) {
20010
20133
  args.push(`--userDataDir=${userDataDir}`);
20134
+ } else if (opts.ownedProfileDir) {
20135
+ args.push(`--userDataDir=${opts.ownedProfileDir}`);
20011
20136
  } else {
20012
20137
  args.push("--isolated");
20013
20138
  }
@@ -20087,7 +20212,7 @@ function detectPackagedMcpPath(probe = DEFAULT_MCP_PATH_PROBE) {
20087
20212
  }
20088
20213
  return null;
20089
20214
  }
20090
- function resolveTransportSpec(probe = DEFAULT_MCP_PATH_PROBE) {
20215
+ function resolveTransportSpec(probe = DEFAULT_MCP_PATH_PROBE, opts = {}) {
20091
20216
  const explicitPath = process.env.CHROME_DEVTOOLS_AXI_MCP_PATH?.trim();
20092
20217
  const freshIsolation = process.env.CHROME_DEVTOOLS_AXI_FRESH === "1";
20093
20218
  const sharedServerUrl = freshIsolation ? void 0 : process.env.CHROME_DEVTOOLS_AXI_MCP_SERVER_URL?.trim();
@@ -20122,7 +20247,7 @@ function resolveTransportSpec(probe = DEFAULT_MCP_PATH_PROBE) {
20122
20247
  args: [explicitPath, `--server-url=${sharedServerUrl}`]
20123
20248
  };
20124
20249
  }
20125
- const mcpArgs = buildTransportArgs();
20250
+ const mcpArgs = buildTransportArgs(opts);
20126
20251
  const mcpPath = explicitPath || detectPackagedMcpPath(probe) || detectGlobalMcpPath(probe);
20127
20252
  if (mcpPath) {
20128
20253
  return {
@@ -20151,13 +20276,13 @@ function parseSharedServerUrl(value) {
20151
20276
  );
20152
20277
  }
20153
20278
  }
20154
- function resolveTransport(probe = DEFAULT_MCP_PATH_PROBE) {
20279
+ function resolveTransport(probe = DEFAULT_MCP_PATH_PROBE, opts = {}) {
20155
20280
  const freshIsolation = process.env.CHROME_DEVTOOLS_AXI_FRESH === "1";
20156
20281
  const sharedServerUrl = freshIsolation ? void 0 : process.env.CHROME_DEVTOOLS_AXI_MCP_SERVER_URL?.trim();
20157
20282
  if (sharedServerUrl && !process.env.CHROME_DEVTOOLS_AXI_MCP_PATH?.trim()) {
20158
20283
  return { kind: "http", url: parseSharedServerUrl(sharedServerUrl) };
20159
20284
  }
20160
- return { kind: "stdio", spec: resolveTransportSpec(probe) };
20285
+ return { kind: "stdio", spec: resolveTransportSpec(probe, opts) };
20161
20286
  }
20162
20287
  var DEFAULT_BRIDGE_TRANSPORT_FACTORIES = {
20163
20288
  createStdio: (spec) => new StdioClientTransport(spec),
@@ -20202,7 +20327,7 @@ function rootUrisEqual(a, b) {
20202
20327
  if (a.length !== b.length) return false;
20203
20328
  return a.every((root, i) => root.uri === b[i]?.uri);
20204
20329
  }
20205
- function createRootsAwareBridgeClient(client) {
20330
+ function createRootsAwareBridgeClient(client, opts = {}) {
20206
20331
  let currentRoots = [];
20207
20332
  let confirmedRoots = [];
20208
20333
  let onRootsFetched = null;
@@ -20259,26 +20384,90 @@ function createRootsAwareBridgeClient(client) {
20259
20384
  }
20260
20385
  let pendingCalls = 0;
20261
20386
  let dialogPending = false;
20387
+ let cdpState = "unconnected";
20388
+ let lastError;
20389
+ let probePromise = null;
20390
+ let probeStartedAt = 0;
20262
20391
  async function trackedCall(request) {
20263
20392
  const result = await client.callTool(request);
20264
20393
  const text = extractToolText(getToolContent(result));
20265
- if (/^# Open dialog\b/m.test(text)) dialogPending = true;
20266
- if (request.name === "handle_dialog" && !isToolResultError(result)) dialogPending = false;
20394
+ const isErr = isToolResultError(result);
20395
+ const hasOpenDialog = /^# Open dialog\b/m.test(text);
20396
+ if (request.name === "handle_dialog" && (!isErr || /no open dialog/i.test(text)) || !isErr && request.name !== "list_pages" && !hasOpenDialog) {
20397
+ dialogPending = false;
20398
+ }
20399
+ if (hasOpenDialog) {
20400
+ dialogPending = true;
20401
+ }
20402
+ if (!isErr) {
20403
+ cdpState = "connected";
20404
+ lastError = void 0;
20405
+ }
20267
20406
  return result;
20268
20407
  }
20408
+ function callTool(request, roots) {
20409
+ if (request.name === "handle_dialog") return trackedCall(request);
20410
+ pendingCalls++;
20411
+ return enqueue(async () => {
20412
+ if (roots) await applyRootsNow(roots);
20413
+ return trackedCall(request);
20414
+ }).finally(() => {
20415
+ pendingCalls--;
20416
+ });
20417
+ }
20418
+ function probeReachable() {
20419
+ if (probePromise) return probePromise;
20420
+ probeStartedAt = Date.now();
20421
+ if (cdpState !== "connected") {
20422
+ cdpState = opts.autoConnect ? "awaiting_approval" : "connecting";
20423
+ }
20424
+ let current = null;
20425
+ current = (async () => {
20426
+ try {
20427
+ const result = await callTool({ name: "list_pages", arguments: {} });
20428
+ if (isToolResultError(result)) {
20429
+ const reason = extractToolText(getToolContent(result)) || 'Tool "list_pages" failed';
20430
+ cdpState = "failed";
20431
+ lastError = reason;
20432
+ return { ok: false, reason };
20433
+ }
20434
+ cdpState = "connected";
20435
+ lastError = void 0;
20436
+ return {
20437
+ ok: true,
20438
+ pageIdentityChanged: didMcpPageIdentityChange(result)
20439
+ };
20440
+ } catch (error2) {
20441
+ const reason = getErrorMessage(error2);
20442
+ cdpState = "failed";
20443
+ lastError = reason;
20444
+ return { ok: false, reason };
20445
+ } finally {
20446
+ if (probePromise === current) {
20447
+ probePromise = null;
20448
+ probeStartedAt = 0;
20449
+ }
20450
+ }
20451
+ })();
20452
+ probePromise = current;
20453
+ return current;
20454
+ }
20269
20455
  return {
20270
20456
  isBusy: () => pendingCalls > 0 || dialogPending,
20271
- listTools: () => client.listTools(),
20272
- callTool: (request, roots) => {
20273
- if (request.name === "handle_dialog") return trackedCall(request);
20274
- pendingCalls++;
20275
- return enqueue(async () => {
20276
- if (roots) await applyRootsNow(roots);
20277
- return trackedCall(request);
20278
- }).finally(() => {
20279
- pendingCalls--;
20280
- });
20457
+ getStatus: () => ({
20458
+ cdpState,
20459
+ dialogPending,
20460
+ probeInFlight: probePromise !== null,
20461
+ ...probeStartedAt > 0 ? { waitingMs: Date.now() - probeStartedAt } : {},
20462
+ ...lastError !== void 0 ? { lastError } : {}
20463
+ }),
20464
+ probeReachable,
20465
+ markDisconnected: (reason) => {
20466
+ cdpState = "failed";
20467
+ lastError = reason;
20281
20468
  },
20469
+ listTools: () => client.listTools(),
20470
+ callTool,
20282
20471
  close: () => client.close(),
20283
20472
  applyRoots: (dirs) => enqueue(() => applyRootsNow(dirs))
20284
20473
  };
@@ -20294,63 +20483,142 @@ async function closeServer(server) {
20294
20483
  });
20295
20484
  });
20296
20485
  }
20486
+ var SHUTDOWN_DRAIN_DEADLINE_MS = 5500;
20297
20487
  async function runBridge(port = resolveSessionPort()) {
20298
- const bridgeTransport = createTransport();
20299
- const client = createBridgeClient();
20300
- const bridgeClient = createRootsAwareBridgeClient(client);
20301
- await client.connect(bridgeTransport.transport);
20302
- logBridgeMessage("Connected to chrome-devtools-mcp");
20303
- const attachMode = isAttachTransportMode();
20304
- if (attachMode) {
20305
- const keepaliveMs = resolveCdpKeepaliveMs();
20306
- const keepalive = setInterval(() => {
20307
- if (bridgeClient.isBusy?.()) return;
20308
- bridgeClient.callTool({ name: "list_pages", arguments: {} }).then(
20309
- () => void 0,
20310
- (error2) => logBridgeMessage(
20311
- `CDP keepalive probe failed: ${getErrorMessage(error2)}`
20312
- )
20313
- );
20314
- }, keepaliveMs);
20315
- keepalive.unref?.();
20316
- }
20317
20488
  const sessionName = resolveSessionName();
20318
- const server = createBridgeServer(bridgeClient, sessionName);
20319
- const lifecycle = createBridgeLifecycle(() => shutdown(), {
20320
- anchor: parseSupervisorAnchor2()
20321
- });
20322
- server.on("request", (req) => lifecycle.observeRequest(req));
20323
- server.on("error", (error2) => {
20324
- handleBridgeServerError(error2, port);
20325
- });
20326
- server.listen(port, "127.0.0.1", () => {
20327
- writePidFile(port);
20328
- logBridgeMessage(`Listening on http://127.0.0.1:${port}`);
20329
- writeReadySignal();
20489
+ const sessionStateDir = resolveSessionStateDir(sessionName);
20490
+ const attachMode = isAttachTransportMode();
20491
+ const autoConnect = isAutoConnectMode();
20492
+ const managedIsolated = isManagedIsolatedMode();
20493
+ const modeFingerprint = computeTransportModeFingerprint();
20494
+ void reapStaleOwnedProfiles(sessionStateDir, process.pid).catch(() => {
20330
20495
  });
20496
+ const ownedProfile = managedIsolated ? allocateOwnedProfileDir(sessionStateDir, process.pid) : void 0;
20497
+ let keepalive;
20498
+ let lifecycle;
20499
+ let server;
20500
+ let bridgeTransport;
20331
20501
  let shuttingDown = false;
20332
- const shutdown = async () => {
20502
+ let cleanupConfirmed = false;
20503
+ const shutdown = async (exitCode = 0) => {
20333
20504
  if (shuttingDown) return;
20334
20505
  shuttingDown = true;
20335
- lifecycle.dispose();
20336
- removePidFile();
20337
- await closeServer(server);
20338
- await closeBridgeTransport(bridgeTransport);
20339
- process.exit(0);
20506
+ if (keepalive) clearInterval(keepalive);
20507
+ lifecycle?.dispose();
20508
+ const drainTasks = [];
20509
+ if (server) {
20510
+ drainTasks.push(closeServer(server).catch(() => {
20511
+ }));
20512
+ }
20513
+ if (bridgeTransport) {
20514
+ drainTasks.push(closeBridgeTransport(bridgeTransport).catch(() => {
20515
+ }));
20516
+ }
20517
+ if (drainTasks.length > 0) {
20518
+ await raceWithTimeout(Promise.allSettled(drainTasks), SHUTDOWN_DRAIN_DEADLINE_MS);
20519
+ }
20520
+ let finalExitCode = exitCode;
20521
+ if (ownedProfile) {
20522
+ const reaped = await cleanupOwnedProfileDir(
20523
+ ownedProfile.profileDir,
20524
+ ownedProfile.manifestPath
20525
+ ).catch(() => ({ clean: false, remainingPids: [] }));
20526
+ cleanupConfirmed = reaped.clean;
20527
+ if (!reaped.clean) {
20528
+ logBridgeMessage(
20529
+ `Owned Chrome cleanup incomplete for ${ownedProfile.profileDir} (remaining=${reaped.remainingPids.join(",") || "unknown"})`
20530
+ );
20531
+ if (finalExitCode === 0) finalExitCode = 1;
20532
+ }
20533
+ } else {
20534
+ cleanupConfirmed = true;
20535
+ }
20536
+ if (cleanupConfirmed) {
20537
+ removePidFile();
20538
+ }
20539
+ process.exit(finalExitCode);
20340
20540
  };
20341
20541
  process.on("exit", () => {
20342
- removePidFile();
20542
+ if (cleanupConfirmed) removePidFile();
20343
20543
  try {
20344
20544
  process.kill(-process.pid, "SIGTERM");
20345
20545
  } catch {
20346
20546
  }
20347
20547
  });
20348
20548
  process.on("SIGTERM", () => {
20349
- void shutdown();
20549
+ void shutdown(0);
20350
20550
  });
20351
20551
  process.on("SIGINT", () => {
20352
- void shutdown();
20552
+ void shutdown(0);
20353
20553
  });
20554
+ try {
20555
+ const selection = resolveTransport(
20556
+ DEFAULT_MCP_PATH_PROBE,
20557
+ ownedProfile ? { ownedProfileDir: ownedProfile.profileDir } : {}
20558
+ );
20559
+ bridgeTransport = createTransport(selection);
20560
+ const client = createBridgeClient();
20561
+ const bridgeClient = createRootsAwareBridgeClient(client, { autoConnect });
20562
+ await client.connect(bridgeTransport.transport);
20563
+ logBridgeMessage(`Connected to chrome-devtools-mcp (mode=${modeFingerprint})`);
20564
+ const pendingDroppedSelectionLatch = { value: false };
20565
+ if (attachMode) {
20566
+ const keepaliveMs = resolveCdpKeepaliveMs();
20567
+ keepalive = setInterval(() => {
20568
+ if (bridgeClient.isBusy?.()) return;
20569
+ if (bridgeClient.getStatus?.().cdpState !== "connected") return;
20570
+ void bridgeClient.probeReachable?.().then(
20571
+ (probe) => {
20572
+ if (!probe.ok) {
20573
+ logBridgeMessage(`CDP keepalive probe failed: ${probe.reason}`);
20574
+ } else if (probe.pageIdentityChanged && clearSelectedPageId()) {
20575
+ pendingDroppedSelectionLatch.value = true;
20576
+ }
20577
+ },
20578
+ (error2) => {
20579
+ const msg = getErrorMessage(error2);
20580
+ bridgeClient.markDisconnected?.(msg);
20581
+ logBridgeMessage(`CDP keepalive probe failed: ${msg}`);
20582
+ }
20583
+ );
20584
+ }, keepaliveMs);
20585
+ keepalive.unref?.();
20586
+ }
20587
+ server = createBridgeServer(
20588
+ bridgeClient,
20589
+ sessionName,
20590
+ pendingDroppedSelectionLatch,
20591
+ modeFingerprint
20592
+ );
20593
+ const supervisorAnchor = parseSupervisorAnchor2();
20594
+ const suspendIdleWhileSupervisorAlive = attachMode;
20595
+ const idleShutdownMs = resolveIdleShutdownMs(attachMode);
20596
+ lifecycle = createBridgeLifecycle(() => shutdown(0), {
20597
+ anchor: supervisorAnchor,
20598
+ idleShutdownMs,
20599
+ suspendIdleWhileSupervisorAlive
20600
+ });
20601
+ logBridgeMessage(
20602
+ `Lifecycle: mode=${modeFingerprint}, supervisor=${supervisorAnchor ? supervisorAnchor.pid : "none"}, idleMs=${idleShutdownMs}, suspendIdle=${suspendIdleWhileSupervisorAlive}`
20603
+ );
20604
+ server.on("request", (req, res) => lifecycle?.observeRequest(req, res));
20605
+ server.on("error", (error2) => {
20606
+ handleBridgeServerError(error2, port, (code) => {
20607
+ void shutdown(code);
20608
+ });
20609
+ });
20610
+ server.listen(port, "127.0.0.1", () => {
20611
+ writePidFile(port, {
20612
+ mode: modeFingerprint,
20613
+ ...ownedProfile ? { ownedProfileDir: ownedProfile.profileDir } : {}
20614
+ });
20615
+ logBridgeMessage(`Listening on http://127.0.0.1:${port}`);
20616
+ writeReadySignal();
20617
+ });
20618
+ } catch (error2) {
20619
+ logBridgeMessage(`Bridge startup failed: ${getErrorMessage(error2)}`);
20620
+ await shutdown(1);
20621
+ }
20354
20622
  }
20355
20623
 
20356
20624
  // vendor/chrome-devtools-axi/bin/chrome-devtools-axi-bridge.ts