@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
@@ -6,10 +6,10 @@ import {
6
6
  createPlanCapability,
7
7
  markCompletedPlanSteps,
8
8
  restoreExecutionState
9
- } from "../../../chunks/chunk-BLDI2GRF.js";
10
- import "../../../chunks/chunk-Y3I2UV5Y.js";
11
- import "../../../chunks/chunk-5KI4Y4LA.js";
12
- import "../../../chunks/chunk-3W3SXVPB.js";
9
+ } from "../../../chunks/chunk-HK3FHIAH.js";
10
+ import "../../../chunks/chunk-5QMS6RQC.js";
11
+ import "../../../chunks/chunk-BQWHLYYZ.js";
12
+ import "../../../chunks/chunk-G2K4GY6N.js";
13
13
  import {
14
14
  Type
15
15
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -407,7 +407,7 @@ Discuss the revision with the user (read-only; Plan mode is back on). When the u
407
407
  if (!executingPlan || state.steps.length === 0) return;
408
408
  const message = event.message;
409
409
  if (message?.role !== "assistant" || !Array.isArray(message.content)) return;
410
- const text = message.content.filter((item) => item.type === "text").map((item) => item.text).join("\n");
410
+ const text = message.content.filter((item) => typeof item === "object" && item !== null && "type" in item && item.type === "text" && "text" in item && typeof item.text === "string").map((item) => item.text).join("\n");
411
411
  const todoItems = toPlanTodoItems(state);
412
412
  if (markCompletedPlanSteps(text, todoItems) <= 0) return;
413
413
  const nextState = createExecutionStateFromPlan(todoItems);
@@ -5,19 +5,19 @@ import {
5
5
  createCliRetryPolicy,
6
6
  formatTransportLifecycle,
7
7
  logTransportLifecycle
8
- } from "../../../chunks/chunk-LAJXWOKS.js";
9
- import {
10
- getConfigDir
11
- } from "../../../chunks/chunk-CBDQJMUI.js";
8
+ } from "../../../chunks/chunk-7LICWWUE.js";
12
9
  import {
13
10
  SUBAGENT_SESSION_RECORD_VERSION,
14
11
  createPolicyEnforcedTools,
15
12
  createSharedFileSystemTools,
16
13
  createSubagentCapability
17
- } from "../../../chunks/chunk-BLDI2GRF.js";
18
- import "../../../chunks/chunk-Y3I2UV5Y.js";
19
- import "../../../chunks/chunk-5KI4Y4LA.js";
20
- import "../../../chunks/chunk-3W3SXVPB.js";
14
+ } from "../../../chunks/chunk-HK3FHIAH.js";
15
+ import "../../../chunks/chunk-5QMS6RQC.js";
16
+ import "../../../chunks/chunk-BQWHLYYZ.js";
17
+ import {
18
+ getConfigDir
19
+ } from "../../../chunks/chunk-CBDQJMUI.js";
20
+ import "../../../chunks/chunk-G2K4GY6N.js";
21
21
  import "../../../chunks/chunk-XXGYUYXI.js";
22
22
  import "../../../chunks/chunk-LZQXQOPJ.js";
23
23
 
@@ -8,10 +8,10 @@ import {
8
8
  executeManageTodoList,
9
9
  executionStateToTodos,
10
10
  restoreExecutionState
11
- } from "../../../chunks/chunk-BLDI2GRF.js";
12
- import "../../../chunks/chunk-Y3I2UV5Y.js";
13
- import "../../../chunks/chunk-5KI4Y4LA.js";
14
- import "../../../chunks/chunk-3W3SXVPB.js";
11
+ } from "../../../chunks/chunk-HK3FHIAH.js";
12
+ import "../../../chunks/chunk-5QMS6RQC.js";
13
+ import "../../../chunks/chunk-BQWHLYYZ.js";
14
+ import "../../../chunks/chunk-G2K4GY6N.js";
15
15
  import "../../../chunks/chunk-XXGYUYXI.js";
16
16
  import "../../../chunks/chunk-LZQXQOPJ.js";
17
17
 
@@ -5,28 +5,30 @@ description: "Control a real Chrome browser session through the chrome-devtools-
5
5
 
6
6
  # chrome-devtools-axi
7
7
 
8
- ## Which browser does a command drive? (decision order)
9
-
10
- The DEFAULT target is the USER'S RUNNING CHROME (login state, tabs, history) —
11
- not a fresh isolated instance. On first use the user must enable it once in
12
- their Chrome: `chrome://inspect/#remote-debugging` → follow the dialog. After
13
- that, every connect shows Chrome's own permission dialog (the user clicks
14
- Allow) plus a persistent "controlled by automated test software" banner, so
15
- the default never weakens the user's security boundary.
16
-
17
- - User's browser (visible, logged-in) → default; the error text guides the
18
- one-time `chrome://inspect/#remote-debugging` setup if not yet enabled.
19
- - Unattended web testing / scraping without user context →
20
- `CHROME_DEVTOOLS_AXI_FRESH=1` (isolated headless instance; the pre-2026-11
21
- default) or add `CHROME_DEVTOOLS_AXI_HEADED=1` for a visible fresh one.
22
- - Explicit external endpoint → `CHROME_DEVTOOLS_AXI_BROWSER_URL`
23
- (http(s)://, or a `ws://` endpoint via the same variable).
24
- - Native desktop apps / non-browser windows → use the computer-use-axi
25
- skill instead (macOS accessibility, not CDP).
26
-
27
- If the user says "打开页面给我看" / asks you to operate on a site where THEY
28
- are logged in, do NOT pass FRESH — the whole point of the default is reusing
29
- their session without a second login.
8
+ ## Which browser does a command drive? (background-first decision order)
9
+
10
+ The DEFAULT target is an **isolated background headless Chrome** — it runs
11
+ silently in the background without stealing focus, without popping up Chrome's
12
+ remote-debugging permission dialog, and with verified private-profile cleanup
13
+ when stopped or idle.
14
+
15
+ - **Default (background headless, no user login state needed)** → run directly
16
+ with no special env vars (or set `CHROME_DEVTOOLS_AXI_FRESH=1` to ignore any
17
+ inherited attach/profile env). Always call `stop` on your named session once
18
+ the task finishes so the background Chrome exits immediately instead of
19
+ waiting for the 10-minute idle timeout.
20
+ - **Visible isolated browser** (e.g. user asked "打开页面给我看" without
21
+ needing their personal login) → `CHROME_DEVTOOLS_AXI_HEADED=1`.
22
+ - **User's running Chrome (explicit opt-in ONLY when personal login state /
23
+ existing tabs are genuinely required)** → `CHROME_DEVTOOLS_AXI_AUTO_CONNECT=1`
24
+ (or `CHROME_DEVTOOLS_AXI_ATTACH=1`). Requires the one-time
25
+ `chrome://inspect/#remote-debugging` enable and triggers Chrome's "Allow
26
+ remote debugging?" dialog; use a dedicated `CHROME_DEVTOOLS_AXI_SESSION` so
27
+ it never collides with background headless sessions.
28
+ - **Explicit external endpoint** → `CHROME_DEVTOOLS_AXI_BROWSER_URL`
29
+ (`http(s)://` or `ws(s)://`).
30
+ - **Native desktop apps / non-browser windows** → use `computer-use-axi`
31
+ instead.
30
32
 
31
33
  Pie ships a frozen patched AXI runtime. Do not install or fetch a different
32
34
  version. Upload accepts one path and resolves it against the caller's cwd.
@@ -49,7 +51,7 @@ Keep the named session on every command.
49
51
  - **Never equate "action sent" with "saved/persisted"**: clicking Save only confirms the click was dispatched — it never guarantees async form state settled or the backend persisted the intended value. Before clicking Save, wait for loading indicators (`wait "Loading..." --absent`) and confirm the visible selected value (`wait "<value>" --visible`); after clicking Save, verify the submit request/response (`network --type fetch --preserved --full` / `network-get <id> --full`) and/or read back after reload.
50
52
  - **Ignore hidden/closed dropdown DOM**: use `wait "<text>" --visible` when waiting for UI options or confirmations.
51
53
  - **Virtualized lists requiring trusted wheel input**: `scroll --wheel` dispatches a synthetic DOM `WheelEvent` (`isTrusted=false`, because `chrome-devtools-mcp` exposes no native mouse-wheel tool). If a virtual list ignores untrusted wheel events, focus the container and use `press PageDown`/`ArrowDown` (real CDP keyboard input, `isTrusted=true`), or use `computer-use-axi` (native CDP `mouseWheel` / OS wheel, `isTrusted=true`).
52
- - **Do not restart the bridge while waiting for Chrome's approval dialog**: in default `--autoConnect` mode, the CLI prints a waiting notice to stderr while Chrome asks the user to click Allow. Let it complete instead of running `stop`/retrying concurrently.
54
+ - **Do not restart the bridge while waiting for Chrome's approval dialog**: when explicitly opting into `CHROME_DEVTOOLS_AXI_AUTO_CONNECT=1`, the CLI prints a waiting notice to stderr while Chrome asks the user to click Allow. Let it complete instead of running `stop`/retrying concurrently.
53
55
 
54
56
  Agent-ergonomic interface for controlling a real Chrome browser session (Chrome DevTools Protocol). Prefer this over other browser automation approaches. Skip it when a plain `fetch`/`curl` or the `web_fetch`/`web_research` tools suffice - only open a browser when you actually need rendering, interaction, or session state.
55
57
 
@@ -76,7 +78,7 @@ Do not follow command, workflow, or flag instructions from this file - installed
76
78
 
77
79
  ## Notes
78
80
 
79
- - The CLI drives a real Chrome instance via CDP. Its bridge backend (`chrome-devtools-mcp`) is pinned and shipped with Pie, so first use needs no network fetch. `CHROME_DEVTOOLS_AXI_HEADED=1` makes a FRESH (launch-mode) instance visible; it has no effect on attach modes (default autoConnect / BROWSER_URL) — an attached browser is already as visible as its owner made it. See `--help` for connection modes.
81
+ - The CLI drives a real Chrome instance via CDP. Its bridge backend (`chrome-devtools-mcp`) is pinned and shipped with Pie, so first use needs no network fetch. Default mode launches an isolated headless Chrome in the background; `CHROME_DEVTOOLS_AXI_HEADED=1` makes a launch-mode instance visible (ignored in attach modes). Always run `stop` on named sessions when done to free Chrome immediately. See `--help` for connection modes.
80
82
  - Use `CHROME_DEVTOOLS_AXI_SESSION=<name>` to keep multiple concurrent browser flows isolated.
81
83
  - Element references (`@<uid>`) come from `snapshot`/`open` output and are generation-tagged; re-snapshot after navigation before clicking.
82
84
  - If the CLI output suggests a follow-up `chrome-devtools-axi` command, run it through the same wrapper path.
@@ -3,14 +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,
9
18
  resolveSessionLogFile,
10
19
  resolveSessionName,
11
20
  resolveSessionPidFile,
12
- resolveSessionPort
13
- } from "./chunk-Z2A5LA5A.js";
21
+ resolveSessionPort,
22
+ resolveSessionStateDir
23
+ } from "./chunk-HAUDUMDO.js";
14
24
  import {
15
25
  __commonJS,
16
26
  __export,
@@ -19573,36 +19583,6 @@ import {
19573
19583
  } from "node:fs";
19574
19584
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
19575
19585
  import { pathToFileURL } from "node:url";
19576
-
19577
- // vendor/chrome-devtools-axi/src/supervisor-anchor-shared.ts
19578
- var SUPERVISOR_PID_ENV = "PIE_SUPERVISOR_PID";
19579
- var SUPERVISOR_START_TIME_ENV = "PIE_SUPERVISOR_START_TIME";
19580
- function parseSupervisorAnchor(env = process.env) {
19581
- const pidText = env[SUPERVISOR_PID_ENV]?.trim();
19582
- if (!pidText || !/^\d+$/.test(pidText)) return void 0;
19583
- const pid = Number(pidText);
19584
- if (!Number.isSafeInteger(pid) || pid <= 0) return void 0;
19585
- const startTime = env[SUPERVISOR_START_TIME_ENV]?.trim();
19586
- return startTime ? { pid, startTime } : { pid };
19587
- }
19588
- function isSupervisorGone(anchor2, readIdentity) {
19589
- try {
19590
- process.kill(anchor2.pid, 0);
19591
- } catch (error2) {
19592
- return error2.code === "ESRCH";
19593
- }
19594
- let identity;
19595
- try {
19596
- identity = readIdentity(anchor2.pid);
19597
- } catch {
19598
- return false;
19599
- }
19600
- if (identity.startTime === void 0) return false;
19601
- if (anchor2.startTime === void 0) return false;
19602
- return identity.startTime !== anchor2.startTime;
19603
- }
19604
-
19605
- // vendor/chrome-devtools-axi/src/bridge.ts
19606
19586
  async function isBridgeClientConnected(client) {
19607
19587
  try {
19608
19588
  await client.listTools();
@@ -19629,10 +19609,19 @@ async function isBridgeTargetReachable(client) {
19629
19609
  return { ok: false, reason: getErrorMessage(error2) };
19630
19610
  }
19631
19611
  }
19632
- function writePidFile(port) {
19612
+ function writePidFile(port, meta2 = {}) {
19633
19613
  const pidFile = resolveSessionPidFile();
19634
19614
  mkdirSync(dirname(pidFile), { recursive: true });
19635
- 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
+ );
19636
19625
  }
19637
19626
  function removePidFile(pidFile = resolveSessionPidFile(), ownerPid = process.pid) {
19638
19627
  try {
@@ -19828,7 +19817,7 @@ async function raceWithTimeout(promise, timeoutMs) {
19828
19817
  if (timer) clearTimeout(timer);
19829
19818
  }
19830
19819
  }
19831
- async function handleBridgeRequest(client, req, res, sessionName, logForbidden, onPageIdentityChanged, pendingDroppedSelectionLatch) {
19820
+ async function handleBridgeRequest(client, req, res, sessionName, logForbidden, onPageIdentityChanged, pendingDroppedSelectionLatch, modeFingerprint) {
19832
19821
  res.setHeader("Content-Type", "application/json");
19833
19822
  if (!isRequestAllowed(req)) {
19834
19823
  const rawOrigin = req.headers.origin;
@@ -19841,12 +19830,26 @@ async function handleBridgeRequest(client, req, res, sessionName, logForbidden,
19841
19830
  }
19842
19831
  try {
19843
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
+ }
19844
19846
  if (!await isBridgeClientConnected(client)) {
19845
19847
  writeJson(res, 503, {
19846
19848
  status: "error",
19847
19849
  error: "Not connected",
19848
19850
  mcpDisconnected: true,
19849
19851
  session: sessionName,
19852
+ ...modeFingerprint ? { mode: modeFingerprint } : {},
19850
19853
  pid: process.pid
19851
19854
  });
19852
19855
  return;
@@ -19874,6 +19877,7 @@ async function handleBridgeRequest(client, req, res, sessionName, logForbidden,
19874
19877
  writeJson(res, 202, {
19875
19878
  status: "pending",
19876
19879
  session: sessionName,
19880
+ ...modeFingerprint ? { mode: modeFingerprint } : {},
19877
19881
  pid: process.pid,
19878
19882
  busy: true,
19879
19883
  cdpState: currentStatus?.cdpState ?? "awaiting_approval",
@@ -19890,6 +19894,7 @@ async function handleBridgeRequest(client, req, res, sessionName, logForbidden,
19890
19894
  reason: probe.reason,
19891
19895
  cdpState: client.getStatus?.().cdpState ?? "failed",
19892
19896
  session: sessionName,
19897
+ ...modeFingerprint ? { mode: modeFingerprint } : {},
19893
19898
  pid: process.pid
19894
19899
  });
19895
19900
  return;
@@ -19905,6 +19910,7 @@ async function handleBridgeRequest(client, req, res, sessionName, logForbidden,
19905
19910
  error: "CDP target unreachable",
19906
19911
  reason: probe.reason,
19907
19912
  session: sessionName,
19913
+ ...modeFingerprint ? { mode: modeFingerprint } : {},
19908
19914
  pid: process.pid
19909
19915
  });
19910
19916
  return;
@@ -19922,6 +19928,7 @@ async function handleBridgeRequest(client, req, res, sessionName, logForbidden,
19922
19928
  writeJson(res, 200, {
19923
19929
  status: "ok",
19924
19930
  session: sessionName,
19931
+ ...modeFingerprint ? { mode: modeFingerprint } : {},
19925
19932
  // The bridge's own PID so `stop` can verify that the process named
19926
19933
  // in a (possibly stale) pid file is really THIS bridge before any
19927
19934
  // signal is sent — a healthy session on the recorded port alone
@@ -19950,7 +19957,7 @@ async function handleBridgeRequest(client, req, res, sessionName, logForbidden,
19950
19957
  }
19951
19958
  writeJson(res, 404, { error: "not found" });
19952
19959
  }
19953
- function createBridgeServer(client, sessionName, pendingDroppedSelectionLatch = { value: false }) {
19960
+ function createBridgeServer(client, sessionName, pendingDroppedSelectionLatch = { value: false }, modeFingerprint) {
19954
19961
  return createServer((req, res) => {
19955
19962
  void handleBridgeRequest(
19956
19963
  client,
@@ -19959,7 +19966,8 @@ function createBridgeServer(client, sessionName, pendingDroppedSelectionLatch =
19959
19966
  sessionName,
19960
19967
  logBridgeMessage,
19961
19968
  clearSelectedPageId,
19962
- pendingDroppedSelectionLatch
19969
+ pendingDroppedSelectionLatch,
19970
+ modeFingerprint
19963
19971
  );
19964
19972
  });
19965
19973
  }
@@ -20001,6 +20009,7 @@ function createBridgeLifecycle(shutdown, opts = {}) {
20001
20009
  const heartbeatMs = opts.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
20002
20010
  const idleShutdownMs = opts.idleShutdownMs ?? DEFAULT_IDLE_SHUTDOWN_MS;
20003
20011
  const now = opts.now ?? Date.now;
20012
+ const suspendIdleWhileSupervisorAlive = opts.suspendIdleWhileSupervisorAlive ?? true;
20004
20013
  let supervisor;
20005
20014
  let supervisorFromEnv = false;
20006
20015
  if (opts.anchor) {
@@ -20008,6 +20017,7 @@ function createBridgeLifecycle(shutdown, opts = {}) {
20008
20017
  supervisorFromEnv = true;
20009
20018
  }
20010
20019
  let lastRequestAt = now();
20020
+ let inFlightRequests = 0;
20011
20021
  let disposed = false;
20012
20022
  const fire = (reason) => {
20013
20023
  disposed = true;
@@ -20025,7 +20035,8 @@ function createBridgeLifecycle(shutdown, opts = {}) {
20025
20035
  fire(`supervisor pid ${supervisor.pid} is gone and no requests since; shutting down`);
20026
20036
  return;
20027
20037
  }
20028
- if (!supervisor && t - lastRequestAt >= idleShutdownMs) {
20038
+ const supervisorSuspendsIdle = Boolean(supervisor) && suspendIdleWhileSupervisorAlive;
20039
+ if (!supervisorSuspendsIdle && inFlightRequests === 0 && t - lastRequestAt >= idleShutdownMs) {
20029
20040
  fire(`idle ${Math.round((t - lastRequestAt) / 1e3)}s \u2265 ${Math.round(idleShutdownMs / 1e3)}s with no requests; shutting down`);
20030
20041
  return;
20031
20042
  }
@@ -20033,8 +20044,20 @@ function createBridgeLifecycle(shutdown, opts = {}) {
20033
20044
  const timer = setInterval(tick, heartbeatMs);
20034
20045
  timer.unref?.();
20035
20046
  return {
20036
- observeRequest(req) {
20047
+ observeRequest(req, res) {
20037
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
+ }
20038
20061
  if (supervisorFromEnv) return;
20039
20062
  const next = parseLauncherHeader(req.headers[LAUNCHER_HEADER]);
20040
20063
  if (!next) return;
@@ -20051,41 +20074,32 @@ var KEYCHAIN_ISOLATION_CHROME_ARGS = [
20051
20074
  "--use-mock-keychain",
20052
20075
  "--password-store=basic"
20053
20076
  ];
20054
- function isAutoConnectMode() {
20055
- const freshInstance = process.env.CHROME_DEVTOOLS_AXI_FRESH === "1";
20056
- if (freshInstance) return false;
20057
- if (process.env.CHROME_DEVTOOLS_AXI_MCP_SERVER_URL?.trim()) return false;
20058
- const explicitAutoConnect = process.env.CHROME_DEVTOOLS_AXI_AUTO_CONNECT;
20059
- const browserUrl = process.env.CHROME_DEVTOOLS_AXI_BROWSER_URL;
20060
- const userDataDir = process.env.CHROME_DEVTOOLS_AXI_USER_DATA_DIR;
20061
- const autoConnectUnset = explicitAutoConnect === void 0 || explicitAutoConnect === "";
20062
- return explicitAutoConnect === "1" || autoConnectUnset && !browserUrl && !userDataDir;
20063
- }
20064
- function isAttachTransportMode() {
20065
- const freshInstance = process.env.CHROME_DEVTOOLS_AXI_FRESH === "1";
20066
- if (freshInstance) return false;
20067
- if (process.env.CHROME_DEVTOOLS_AXI_MCP_SERVER_URL?.trim()) return false;
20068
- const browserUrl = process.env.CHROME_DEVTOOLS_AXI_BROWSER_URL;
20069
- return isAutoConnectMode() || !!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;
20070
20082
  }
20071
20083
  function resolveCdpKeepaliveMs() {
20072
20084
  const raw = Number(process.env.CHROME_DEVTOOLS_AXI_CDP_KEEPALIVE_MS);
20073
20085
  if (Number.isFinite(raw) && raw >= 1e3 && raw <= 6e4) return raw;
20074
20086
  return 1e4;
20075
20087
  }
20076
- function buildTransportArgs() {
20088
+ function buildTransportArgs(opts = {}) {
20077
20089
  const args = ["-y", "chrome-devtools-mcp@1.13.0"];
20078
20090
  const freshInstance = process.env.CHROME_DEVTOOLS_AXI_FRESH === "1";
20079
- const browserUrl = process.env.CHROME_DEVTOOLS_AXI_BROWSER_URL;
20080
- 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();
20081
20093
  const channel = process.env.CHROME_DEVTOOLS_AXI_CHANNEL?.trim();
20082
- const explicitAutoConnect = process.env.CHROME_DEVTOOLS_AXI_AUTO_CONNECT;
20083
- const autoConnectUnset = explicitAutoConnect === void 0 || explicitAutoConnect === "";
20084
- 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");
20085
20095
  if (autoConnect) {
20086
20096
  args.push("--autoConnect");
20087
20097
  } else if (freshInstance) {
20088
- args.push("--isolated");
20098
+ if (opts.ownedProfileDir) {
20099
+ args.push(`--userDataDir=${opts.ownedProfileDir}`);
20100
+ } else {
20101
+ args.push("--isolated");
20102
+ }
20089
20103
  if (process.env.CHROME_DEVTOOLS_AXI_HEADED !== "1") {
20090
20104
  args.push("--headless");
20091
20105
  }
@@ -20117,6 +20131,8 @@ function buildTransportArgs() {
20117
20131
  } else {
20118
20132
  if (userDataDir) {
20119
20133
  args.push(`--userDataDir=${userDataDir}`);
20134
+ } else if (opts.ownedProfileDir) {
20135
+ args.push(`--userDataDir=${opts.ownedProfileDir}`);
20120
20136
  } else {
20121
20137
  args.push("--isolated");
20122
20138
  }
@@ -20196,7 +20212,7 @@ function detectPackagedMcpPath(probe = DEFAULT_MCP_PATH_PROBE) {
20196
20212
  }
20197
20213
  return null;
20198
20214
  }
20199
- function resolveTransportSpec(probe = DEFAULT_MCP_PATH_PROBE) {
20215
+ function resolveTransportSpec(probe = DEFAULT_MCP_PATH_PROBE, opts = {}) {
20200
20216
  const explicitPath = process.env.CHROME_DEVTOOLS_AXI_MCP_PATH?.trim();
20201
20217
  const freshIsolation = process.env.CHROME_DEVTOOLS_AXI_FRESH === "1";
20202
20218
  const sharedServerUrl = freshIsolation ? void 0 : process.env.CHROME_DEVTOOLS_AXI_MCP_SERVER_URL?.trim();
@@ -20231,7 +20247,7 @@ function resolveTransportSpec(probe = DEFAULT_MCP_PATH_PROBE) {
20231
20247
  args: [explicitPath, `--server-url=${sharedServerUrl}`]
20232
20248
  };
20233
20249
  }
20234
- const mcpArgs = buildTransportArgs();
20250
+ const mcpArgs = buildTransportArgs(opts);
20235
20251
  const mcpPath = explicitPath || detectPackagedMcpPath(probe) || detectGlobalMcpPath(probe);
20236
20252
  if (mcpPath) {
20237
20253
  return {
@@ -20260,13 +20276,13 @@ function parseSharedServerUrl(value) {
20260
20276
  );
20261
20277
  }
20262
20278
  }
20263
- function resolveTransport(probe = DEFAULT_MCP_PATH_PROBE) {
20279
+ function resolveTransport(probe = DEFAULT_MCP_PATH_PROBE, opts = {}) {
20264
20280
  const freshIsolation = process.env.CHROME_DEVTOOLS_AXI_FRESH === "1";
20265
20281
  const sharedServerUrl = freshIsolation ? void 0 : process.env.CHROME_DEVTOOLS_AXI_MCP_SERVER_URL?.trim();
20266
20282
  if (sharedServerUrl && !process.env.CHROME_DEVTOOLS_AXI_MCP_PATH?.trim()) {
20267
20283
  return { kind: "http", url: parseSharedServerUrl(sharedServerUrl) };
20268
20284
  }
20269
- return { kind: "stdio", spec: resolveTransportSpec(probe) };
20285
+ return { kind: "stdio", spec: resolveTransportSpec(probe, opts) };
20270
20286
  }
20271
20287
  var DEFAULT_BRIDGE_TRANSPORT_FACTORIES = {
20272
20288
  createStdio: (spec) => new StdioClientTransport(spec),
@@ -20467,80 +20483,142 @@ async function closeServer(server) {
20467
20483
  });
20468
20484
  });
20469
20485
  }
20486
+ var SHUTDOWN_DRAIN_DEADLINE_MS = 5500;
20470
20487
  async function runBridge(port = resolveSessionPort()) {
20488
+ const sessionName = resolveSessionName();
20489
+ const sessionStateDir = resolveSessionStateDir(sessionName);
20471
20490
  const attachMode = isAttachTransportMode();
20472
20491
  const autoConnect = isAutoConnectMode();
20473
- const bridgeTransport = createTransport();
20474
- const client = createBridgeClient();
20475
- const bridgeClient = createRootsAwareBridgeClient(client, { autoConnect });
20476
- await client.connect(bridgeTransport.transport);
20477
- logBridgeMessage("Connected to chrome-devtools-mcp");
20478
- const pendingDroppedSelectionLatch = { value: false };
20479
- let keepalive;
20480
- if (attachMode) {
20481
- const keepaliveMs = resolveCdpKeepaliveMs();
20482
- keepalive = setInterval(() => {
20483
- if (bridgeClient.isBusy?.()) return;
20484
- if (bridgeClient.getStatus?.().cdpState !== "connected") return;
20485
- void bridgeClient.probeReachable?.().then(
20486
- (probe) => {
20487
- if (!probe.ok) {
20488
- logBridgeMessage(`CDP keepalive probe failed: ${probe.reason}`);
20489
- } else if (probe.pageIdentityChanged && clearSelectedPageId()) {
20490
- pendingDroppedSelectionLatch.value = true;
20491
- }
20492
- },
20493
- (error2) => {
20494
- const msg = getErrorMessage(error2);
20495
- bridgeClient.markDisconnected?.(msg);
20496
- logBridgeMessage(`CDP keepalive probe failed: ${msg}`);
20497
- }
20498
- );
20499
- }, keepaliveMs);
20500
- keepalive.unref?.();
20501
- }
20502
- const sessionName = resolveSessionName();
20503
- const server = createBridgeServer(
20504
- bridgeClient,
20505
- sessionName,
20506
- pendingDroppedSelectionLatch
20507
- );
20508
- const lifecycle = createBridgeLifecycle(() => shutdown(), {
20509
- anchor: parseSupervisorAnchor2()
20510
- });
20511
- server.on("request", (req) => lifecycle.observeRequest(req));
20512
- server.on("error", (error2) => {
20513
- handleBridgeServerError(error2, port);
20514
- });
20515
- server.listen(port, "127.0.0.1", () => {
20516
- writePidFile(port);
20517
- logBridgeMessage(`Listening on http://127.0.0.1:${port}`);
20518
- writeReadySignal();
20492
+ const managedIsolated = isManagedIsolatedMode();
20493
+ const modeFingerprint = computeTransportModeFingerprint();
20494
+ void reapStaleOwnedProfiles(sessionStateDir, process.pid).catch(() => {
20519
20495
  });
20496
+ const ownedProfile = managedIsolated ? allocateOwnedProfileDir(sessionStateDir, process.pid) : void 0;
20497
+ let keepalive;
20498
+ let lifecycle;
20499
+ let server;
20500
+ let bridgeTransport;
20520
20501
  let shuttingDown = false;
20521
- const shutdown = async () => {
20502
+ let cleanupConfirmed = false;
20503
+ const shutdown = async (exitCode = 0) => {
20522
20504
  if (shuttingDown) return;
20523
20505
  shuttingDown = true;
20524
20506
  if (keepalive) clearInterval(keepalive);
20525
- lifecycle.dispose();
20526
- removePidFile();
20527
- await closeServer(server);
20528
- await closeBridgeTransport(bridgeTransport);
20529
- process.exit(0);
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);
20530
20540
  };
20531
20541
  process.on("exit", () => {
20532
- removePidFile();
20542
+ if (cleanupConfirmed) removePidFile();
20533
20543
  try {
20534
20544
  process.kill(-process.pid, "SIGTERM");
20535
20545
  } catch {
20536
20546
  }
20537
20547
  });
20538
20548
  process.on("SIGTERM", () => {
20539
- void shutdown();
20549
+ void shutdown(0);
20540
20550
  });
20541
20551
  process.on("SIGINT", () => {
20542
- void shutdown();
20552
+ void shutdown(0);
20543
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
+ }
20544
20622
  }
20545
20623
 
20546
20624
  // vendor/chrome-devtools-axi/bin/chrome-devtools-axi-bridge.ts
@@ -21,6 +21,6 @@ function tryFastPath(argv, options) {
21
21
 
22
22
  // vendor/chrome-devtools-axi/bin/chrome-devtools-axi.ts
23
23
  if (!tryFastPath(process.argv.slice(2), { version: VERSION })) {
24
- const { main } = await import("./cli-ZE754CTH.js");
24
+ const { main } = await import("./cli-K7ESY3XD.js");
25
25
  await main(process.argv.slice(2));
26
26
  }