// @bun
import {
  StdioServerTransport,
  init_stdio
} from "./chunk-nerv0jvx.js";
import {
  init_sink,
  initializeAnalyticsSink
} from "./chunk-ywhrzpcp.js";
import {
  ListToolsRequestSchema,
  init_types
} from "./chunk-5dbk24zg.js";
import {
  init_datadog,
  shutdownDatadog
} from "./chunk-p8qcw3dd.js";
import {
  enableConfigs,
  getDynamicConfig_CACHED_MAY_BE_STALE,
  getSubscriptionType,
  init_auth,
  init_config1 as init_config,
  init_firstPartyEventLogger,
  init_growthbook,
  init_sleep,
  shutdown1PEventLogging,
  sleep
} from "./chunk-1p8q0pgc.js";
import"./chunk-e3g8q4cn.js";
import"./chunk-z1yfevvp.js";
import"./chunk-ctw5jwcd.js";
import"./chunk-0e1xsncc.js";
import"./chunk-vratq94g.js";
import"./chunk-g0j0t6qk.js";
import"./chunk-6kpbgc5w.js";
import {
  init_normalization
} from "./chunk-3c25bcsw.js";
import"./chunk-tjaqa99q.js";
import"./chunk-55wgxwa9.js";
import {
  env,
  init_env
} from "./chunk-w2z5pqd3.js";
import"./chunk-7ymfj7m3.js";
import"./chunk-f5ma3nh5.js";
import"./chunk-v1kzp02e.js";
import"./chunk-n58eyfnk.js";
import"./chunk-p2816w9z.js";
import"./chunk-1rvz0433.js";
import"./chunk-cdz5yb0r.js";
import"./chunk-f2mhrmww.js";
import"./chunk-hrzerbfw.js";
import"./chunk-d18z9pna.js";
import"./chunk-qnfx3qtx.js";
import"./chunk-hjhc4cpt.js";
import"./chunk-vyc0rjyx.js";
import {
  execFileNoThrow,
  init_execFileNoThrow
} from "./chunk-hx2tr4ep.js";
import"./chunk-p7g7pf3f.js";
import"./chunk-8tnsngw2.js";
import"./chunk-8bedvdm1.js";
import"./chunk-7wm5s02e.js";
import {
  errorMessage,
  init_debug,
  init_errors,
  logForDebugging
} from "./chunk-nxsh6de2.js";
import"./chunk-fbv4apne.js";
import {
  init_envUtils,
  isEnvTruthy
} from "./chunk-3r24h7t6.js";
import"./chunk-qqfa0dqg.js";
import"./chunk-hqmz36b3.js";
import"./chunk-4g3v8y12.js";
import"./chunk-7739pg2c.js";
import"./chunk-xszk7n10.js";
import"./chunk-sdj9b9wh.js";
import {
  __esm,
  __export,
  __toCommonJS
} from "./chunk-qp2qdcda.js";

// packages/@ant/computer-use-swift/src/index.ts
var exports_src = {};
__export(exports_src, {
  ComputerUseAPI: () => ComputerUseAPI
});
import { readFileSync, unlinkSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
function jxaSync(script) {
  const result = Bun.spawnSync({
    cmd: ["osascript", "-l", "JavaScript", "-e", script],
    stdout: "pipe",
    stderr: "pipe"
  });
  return new TextDecoder().decode(result.stdout).trim();
}
async function osascript(script) {
  const proc = Bun.spawn(["osascript", "-e", script], {
    stdout: "pipe",
    stderr: "pipe"
  });
  const text = await new Response(proc.stdout).text();
  await proc.exited;
  return text.trim();
}
async function jxa(script) {
  const proc = Bun.spawn(["osascript", "-l", "JavaScript", "-e", script], {
    stdout: "pipe",
    stderr: "pipe"
  });
  const text = await new Response(proc.stdout).text();
  await proc.exited;
  return text.trim();
}
async function captureScreenToBase64(args) {
  const tmpFile = join(tmpdir(), `cu-screenshot-${Date.now()}.png`);
  const proc = Bun.spawn(["screencapture", ...args, tmpFile], {
    stdout: "pipe",
    stderr: "pipe"
  });
  await proc.exited;
  try {
    const buf = readFileSync(tmpFile);
    const base64 = buf.toString("base64");
    const width = buf.readUInt32BE(16);
    const height = buf.readUInt32BE(20);
    return { base64, width, height };
  } finally {
    try {
      unlinkSync(tmpFile);
    } catch {}
  }
}

class ComputerUseAPI {
  apps = appsAPI;
  display = displayAPI;
  screenshot = screenshotAPI;
  async resolvePrepareCapture(allowedBundleIds, _surrogateHost, quality, targetW, targetH, displayId, _autoResolve, _doHide) {
    return this.screenshot.captureExcluding(allowedBundleIds, quality, targetW, targetH, displayId);
  }
}
var displayAPI, appsAPI, screenshotAPI;
var init_src = __esm(() => {
  displayAPI = {
    getSize(displayId) {
      const all = this.listAll();
      if (displayId !== undefined) {
        const found = all.find((d) => d.displayId === displayId);
        if (found)
          return found;
      }
      return all[0] ?? { width: 1920, height: 1080, scaleFactor: 2, displayId: 1 };
    },
    listAll() {
      try {
        const raw = jxaSync(`
        ObjC.import("CoreGraphics");
        var displays = $.CGDisplayCopyAllDisplayModes ? [] : [];
        var active = $.CGGetActiveDisplayList(10, null, Ref());
        var countRef = Ref();
        $.CGGetActiveDisplayList(0, null, countRef);
        var count = countRef[0];
        var idBuf = Ref();
        $.CGGetActiveDisplayList(count, idBuf, countRef);
        var result = [];
        for (var i = 0; i < count; i++) {
          var did = idBuf[i];
          var w = $.CGDisplayPixelsWide(did);
          var h = $.CGDisplayPixelsHigh(did);
          var mode = $.CGDisplayCopyDisplayMode(did);
          var pw = $.CGDisplayModeGetPixelWidth(mode);
          var sf = pw > 0 && w > 0 ? pw / w : 2;
          result.push({width: w, height: h, scaleFactor: sf, displayId: did});
        }
        JSON.stringify(result);
      `);
        return JSON.parse(raw).map((d) => ({
          width: Number(d.width),
          height: Number(d.height),
          scaleFactor: Number(d.scaleFactor),
          displayId: Number(d.displayId)
        }));
      } catch {
        try {
          const raw = jxaSync(`
          ObjC.import("AppKit");
          var screens = $.NSScreen.screens;
          var result = [];
          for (var i = 0; i < screens.count; i++) {
            var s = screens.objectAtIndex(i);
            var frame = s.frame;
            var desc = s.deviceDescription;
            var screenNumber = desc.objectForKey($("NSScreenNumber")).intValue;
            var backingFactor = s.backingScaleFactor;
            result.push({
              width: Math.round(frame.size.width),
              height: Math.round(frame.size.height),
              scaleFactor: backingFactor,
              displayId: screenNumber
            });
          }
          JSON.stringify(result);
        `);
          return JSON.parse(raw).map((d) => ({
            width: Number(d.width),
            height: Number(d.height),
            scaleFactor: Number(d.scaleFactor),
            displayId: Number(d.displayId)
          }));
        } catch {
          return [{ width: 1920, height: 1080, scaleFactor: 2, displayId: 1 }];
        }
      }
    }
  };
  appsAPI = {
    async prepareDisplay(_allowlistBundleIds, _surrogateHost, _displayId) {
      return { activated: "", hidden: [] };
    },
    async previewHideSet(_bundleIds, _displayId) {
      return [];
    },
    async findWindowDisplays(bundleIds) {
      return bundleIds.map((bundleId) => ({ bundleId, displayIds: [1] }));
    },
    async appUnderPoint(_x, _y) {
      try {
        const result = await jxa(`
        ObjC.import("CoreGraphics");
        ObjC.import("AppKit");
        var pt = $.CGPointMake(${_x}, ${_y});
        // Get frontmost app as a fallback
        var app = $.NSWorkspace.sharedWorkspace.frontmostApplication;
        JSON.stringify({bundleId: app.bundleIdentifier.js, displayName: app.localizedName.js});
      `);
        return JSON.parse(result);
      } catch {
        return null;
      }
    },
    async listInstalled() {
      try {
        const result = await osascript(`
        tell application "System Events"
          set appList to ""
          repeat with appFile in (every file of folder "Applications" of startup disk whose name ends with ".app")
            set appPath to POSIX path of (appFile as alias)
            set appName to name of appFile
            set appList to appList & appPath & "|" & appName & "\\n"
          end repeat
          return appList
        end tell
      `);
        return result.split(`
`).filter(Boolean).map((line) => {
          const [path, name] = line.split("|", 2);
          const displayName = (name ?? "").replace(/\.app$/, "");
          return {
            bundleId: `com.app.${displayName.toLowerCase().replace(/\s+/g, "-")}`,
            displayName,
            path: path ?? ""
          };
        });
      } catch {
        return [];
      }
    },
    iconDataUrl(_path) {
      return null;
    },
    listRunning() {
      try {
        const raw = jxaSync(`
        var apps = Application("System Events").applicationProcesses.whose({backgroundOnly: false});
        var result = [];
        for (var i = 0; i < apps.length; i++) {
          try {
            var a = apps[i];
            result.push({bundleId: a.bundleIdentifier(), displayName: a.name()});
          } catch(e) {}
        }
        JSON.stringify(result);
      `);
        return JSON.parse(raw);
      } catch {
        return [];
      }
    },
    async open(bundleId) {
      await osascript(`tell application id "${bundleId}" to activate`);
    },
    async unhide(bundleIds) {
      for (const bundleId of bundleIds) {
        await osascript(`
        tell application "System Events"
          set visible of application process (name of application process whose bundle identifier is "${bundleId}") to true
        end tell
      `);
      }
    }
  };
  screenshotAPI = {
    async captureExcluding(_allowedBundleIds, _quality, _targetW, _targetH, displayId) {
      const args = ["-x"];
      if (displayId !== undefined) {
        args.push("-D", String(displayId));
      }
      return captureScreenToBase64(args);
    },
    async captureRegion(_allowedBundleIds, x, y, w, h, _outW, _outH, _quality, displayId) {
      const args = ["-x", "-R", `${x},${y},${w},${h}`];
      if (displayId !== undefined) {
        args.push("-D", String(displayId));
      }
      return captureScreenToBase64(args);
    }
  };
});

// packages/@ant/computer-use-input/src/index.ts
var exports_src2 = {};
__export(exports_src2, {
  typeText: () => typeText,
  moveMouse: () => moveMouse,
  mouseScroll: () => mouseScroll,
  mouseLocation: () => mouseLocation,
  mouseButton: () => mouseButton,
  keys: () => keys,
  key: () => key,
  isSupported: () => isSupported,
  getFrontmostAppInfo: () => getFrontmostAppInfo,
  ComputerUseInputAPI: () => ComputerUseInputAPI
});
var {$ } = globalThis.Bun;
async function osascript2(script) {
  const result = await $`osascript -e ${script}`.quiet().nothrow().text();
  return result.trim();
}
async function jxa2(script) {
  const result = await $`osascript -l JavaScript -e ${script}`.quiet().nothrow().text();
  return result.trim();
}
function buildMouseJxa(eventType, x, y, btn, clickState) {
  let script = `ObjC.import("CoreGraphics"); var p = $.CGPointMake(${x},${y}); var e = $.CGEventCreateMouseEvent(null, $.${eventType}, p, ${btn});`;
  if (clickState !== undefined) {
    script += ` $.CGEventSetIntegerValueField(e, $.kCGMouseEventClickState, ${clickState});`;
  }
  script += ` $.CGEventPost($.kCGHIDEventTap, e);`;
  return script;
}
async function moveMouse(x, y, _animated) {
  await jxa2(buildMouseJxa("kCGEventMouseMoved", x, y, 0));
}
async function key(keyName, action) {
  if (action === "release")
    return;
  const lower = keyName.toLowerCase();
  const keyCode = KEY_MAP[lower];
  if (keyCode !== undefined) {
    await osascript2(`tell application "System Events" to key code ${keyCode}`);
  } else {
    await osascript2(`tell application "System Events" to keystroke "${keyName.length === 1 ? keyName : lower}"`);
  }
}
async function keys(parts) {
  const modifiers = [];
  let finalKey = null;
  for (const part of parts) {
    const mod = MODIFIER_MAP[part.toLowerCase()];
    if (mod)
      modifiers.push(mod);
    else
      finalKey = part;
  }
  if (!finalKey)
    return;
  const lower = finalKey.toLowerCase();
  const keyCode = KEY_MAP[lower];
  const modStr = modifiers.length > 0 ? ` using {${modifiers.join(", ")}}` : "";
  if (keyCode !== undefined) {
    await osascript2(`tell application "System Events" to key code ${keyCode}${modStr}`);
  } else {
    await osascript2(`tell application "System Events" to keystroke "${finalKey.length === 1 ? finalKey : lower}"${modStr}`);
  }
}
async function mouseLocation() {
  const result = await jxa2('ObjC.import("CoreGraphics"); var e = $.CGEventCreate(null); var p = $.CGEventGetLocation(e); p.x + "," + p.y');
  const [xStr, yStr] = result.split(",");
  return { x: Math.round(Number(xStr)), y: Math.round(Number(yStr)) };
}
async function mouseButton(button, action, count) {
  const pos = await mouseLocation();
  const btn = button === "left" ? 0 : button === "right" ? 1 : 2;
  const downType = btn === 0 ? "kCGEventLeftMouseDown" : btn === 1 ? "kCGEventRightMouseDown" : "kCGEventOtherMouseDown";
  const upType = btn === 0 ? "kCGEventLeftMouseUp" : btn === 1 ? "kCGEventRightMouseUp" : "kCGEventOtherMouseUp";
  if (action === "click") {
    for (let i = 0;i < (count ?? 1); i++) {
      await jxa2(buildMouseJxa(downType, pos.x, pos.y, btn, i + 1));
      await jxa2(buildMouseJxa(upType, pos.x, pos.y, btn, i + 1));
    }
  } else if (action === "press") {
    await jxa2(buildMouseJxa(downType, pos.x, pos.y, btn));
  } else {
    await jxa2(buildMouseJxa(upType, pos.x, pos.y, btn));
  }
}
async function mouseScroll(amount, direction) {
  const script = direction === "vertical" ? `ObjC.import("CoreGraphics"); var e = $.CGEventCreateScrollWheelEvent(null, 0, 1, ${amount}); $.CGEventPost($.kCGHIDEventTap, e);` : `ObjC.import("CoreGraphics"); var e = $.CGEventCreateScrollWheelEvent(null, 0, 2, 0, ${amount}); $.CGEventPost($.kCGHIDEventTap, e);`;
  await jxa2(script);
}
async function typeText(text) {
  const escaped = text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
  await osascript2(`tell application "System Events" to keystroke "${escaped}"`);
}
function getFrontmostAppInfo() {
  try {
    const result = Bun.spawnSync({
      cmd: ["osascript", "-e", `
        tell application "System Events"
          set frontApp to first application process whose frontmost is true
          set appName to name of frontApp
          set bundleId to bundle identifier of frontApp
          return bundleId & "|" & appName
        end tell
      `],
      stdout: "pipe",
      stderr: "pipe"
    });
    const output = new TextDecoder().decode(result.stdout).trim();
    if (!output || !output.includes("|"))
      return null;
    const [bundleId, appName] = output.split("|", 2);
    return { bundleId, appName };
  } catch {
    return null;
  }
}

class ComputerUseInputAPI {
}
var KEY_MAP, MODIFIER_MAP, isSupported;
var init_src2 = __esm(() => {
  KEY_MAP = {
    return: 36,
    enter: 36,
    tab: 48,
    space: 49,
    delete: 51,
    backspace: 51,
    escape: 53,
    esc: 53,
    left: 123,
    right: 124,
    down: 125,
    up: 126,
    f1: 122,
    f2: 120,
    f3: 99,
    f4: 118,
    f5: 96,
    f6: 97,
    f7: 98,
    f8: 100,
    f9: 101,
    f10: 109,
    f11: 103,
    f12: 111,
    home: 115,
    end: 119,
    pageup: 116,
    pagedown: 121
  };
  MODIFIER_MAP = {
    command: "command down",
    cmd: "command down",
    meta: "command down",
    super: "command down",
    shift: "shift down",
    option: "option down",
    alt: "option down",
    control: "control down",
    ctrl: "control down"
  };
  isSupported = process.platform === "darwin";
});

// packages/@ant/computer-use-mcp/src/index.ts
var API_RESIZE_PARAMS = {
  maxWidth: 1280,
  maxHeight: 800,
  maxPixels: 1280 * 800
};
function targetImageSize(physW, physH, _params) {
  const maxW = _params?.maxWidth ?? 1280;
  const maxH = _params?.maxHeight ?? 800;
  const scale = Math.min(1, maxW / physW, maxH / physH);
  return [Math.round(physW * scale), Math.round(physH * scale)];
}
function buildComputerUseTools(_capabilities, _coordinateMode, _installedAppNames) {
  return [];
}
function createComputerUseMcpServer(_adapter, _coordinateMode) {
  return null;
}

// src/utils/computerUse/mcpServer.ts
init_stdio();
init_types();
init_datadog();
init_firstPartyEventLogger();
init_sink();
init_config();
init_debug();
import { homedir } from "os";

// src/utils/computerUse/appNames.ts
var PATH_ALLOWLIST = [
  "/Applications/",
  "/System/Applications/"
];
var NAME_PATTERN_BLOCKLIST = [
  /Helper(?:$|\s\()/,
  /Agent(?:$|\s\()/,
  /Service(?:$|\s\()/,
  /Uninstaller(?:$|\s\()/,
  /Updater(?:$|\s\()/,
  /^\./
];
var ALWAYS_KEEP_BUNDLE_IDS = new Set([
  "com.apple.Safari",
  "com.google.Chrome",
  "com.microsoft.edgemac",
  "org.mozilla.firefox",
  "company.thebrowser.Browser",
  "com.tinyspeck.slackmacgap",
  "us.zoom.xos",
  "com.microsoft.teams2",
  "com.microsoft.teams",
  "com.apple.MobileSMS",
  "com.apple.mail",
  "com.microsoft.Word",
  "com.microsoft.Excel",
  "com.microsoft.Powerpoint",
  "com.microsoft.Outlook",
  "com.apple.iWork.Pages",
  "com.apple.iWork.Numbers",
  "com.apple.iWork.Keynote",
  "com.google.GoogleDocs",
  "notion.id",
  "com.apple.Notes",
  "md.obsidian",
  "com.linear",
  "com.figma.Desktop",
  "com.microsoft.VSCode",
  "com.apple.Terminal",
  "com.googlecode.iterm2",
  "com.github.GitHubDesktop",
  "com.apple.finder",
  "com.apple.iCal",
  "com.apple.systempreferences"
]);
var APP_NAME_ALLOWED = /^[\p{L}\p{M}\p{N}_ .&'()+-]+$/u;
var APP_NAME_MAX_LEN = 40;
var APP_NAME_MAX_COUNT = 50;
function isUserFacingPath(path, homeDir) {
  if (PATH_ALLOWLIST.some((root) => path.startsWith(root)))
    return true;
  if (homeDir) {
    const userApps = homeDir.endsWith("/") ? `${homeDir}Applications/` : `${homeDir}/Applications/`;
    if (path.startsWith(userApps))
      return true;
  }
  return false;
}
function isNoisyName(name) {
  return NAME_PATTERN_BLOCKLIST.some((re) => re.test(name));
}
function sanitizeCore(raw, applyCharFilter) {
  const seen = new Set;
  return raw.map((name) => name.trim()).filter((trimmed) => {
    if (!trimmed)
      return false;
    if (trimmed.length > APP_NAME_MAX_LEN)
      return false;
    if (applyCharFilter && !APP_NAME_ALLOWED.test(trimmed))
      return false;
    if (seen.has(trimmed))
      return false;
    seen.add(trimmed);
    return true;
  }).sort((a, b) => a.localeCompare(b));
}
function sanitizeAppNames(raw) {
  const filtered = sanitizeCore(raw, true);
  if (filtered.length <= APP_NAME_MAX_COUNT)
    return filtered;
  return [
    ...filtered.slice(0, APP_NAME_MAX_COUNT),
    `\u2026 and ${filtered.length - APP_NAME_MAX_COUNT} more`
  ];
}
function sanitizeTrustedNames(raw) {
  return sanitizeCore(raw, false);
}
function filterAppsForDescription(installed, homeDir) {
  const { alwaysKept, rest } = installed.reduce((acc, app) => {
    if (ALWAYS_KEEP_BUNDLE_IDS.has(app.bundleId)) {
      acc.alwaysKept.push(app.displayName);
    } else if (isUserFacingPath(app.path, homeDir) && !isNoisyName(app.displayName)) {
      acc.rest.push(app.displayName);
    }
    return acc;
  }, { alwaysKept: [], rest: [] });
  const sanitizedAlways = sanitizeTrustedNames(alwaysKept);
  const alwaysSet = new Set(sanitizedAlways);
  return [
    ...sanitizedAlways,
    ...sanitizeAppNames(rest).filter((n) => !alwaysSet.has(n))
  ];
}

// src/utils/computerUse/gates.ts
init_growthbook();
init_auth();
init_envUtils();
var DEFAULTS = {
  enabled: false,
  pixelValidation: false,
  clipboardPasteMultiline: true,
  mouseAnimation: true,
  hideBeforeAction: true,
  autoTargetDisplay: true,
  clipboardGuard: true,
  coordinateMode: "pixels"
};
function readConfig() {
  return {
    ...DEFAULTS,
    ...getDynamicConfig_CACHED_MAY_BE_STALE("tengu_malort_pedway", DEFAULTS)
  };
}
function hasRequiredSubscription() {
  if (process.env.USER_TYPE === "ant")
    return true;
  const tier = getSubscriptionType();
  return tier === "max" || tier === "pro";
}
function getChicagoEnabled() {
  if (process.env.USER_TYPE === "ant" && process.env.MONOREPO_ROOT_DIR && !isEnvTruthy(process.env.ALLOW_ANT_COMPUTER_USE_MCP)) {
    return false;
  }
  return hasRequiredSubscription() && readConfig().enabled;
}
function getChicagoSubGates() {
  const { enabled: _e, coordinateMode: _c, ...subGates } = readConfig();
  return subGates;
}
var frozenCoordinateMode;
function getChicagoCoordinateMode() {
  frozenCoordinateMode ??= readConfig().coordinateMode;
  return frozenCoordinateMode;
}

// src/utils/computerUse/hostAdapter.ts
init_debug();
import { format } from "util";

// src/utils/computerUse/common.ts
init_normalization();
init_env();
var COMPUTER_USE_MCP_SERVER_NAME = "computer-use";
var CLI_HOST_BUNDLE_ID = "com.anthropic.claude-code.cli-no-window";
var TERMINAL_BUNDLE_ID_FALLBACK = {
  "iTerm.app": "com.googlecode.iterm2",
  Apple_Terminal: "com.apple.Terminal",
  ghostty: "com.mitchellh.ghostty",
  kitty: "net.kovidgoyal.kitty",
  WarpTerminal: "dev.warp.Warp-Stable",
  vscode: "com.microsoft.VSCode"
};
function getTerminalBundleId() {
  const cfBundleId = process.env.__CFBundleIdentifier;
  if (cfBundleId)
    return cfBundleId;
  return TERMINAL_BUNDLE_ID_FALLBACK[env.terminal ?? ""] ?? null;
}
var CLI_CU_CAPABILITIES = {
  screenshotFiltering: "native",
  platform: "darwin"
};

// src/utils/computerUse/executor.ts
init_debug();
init_errors();
init_execFileNoThrow();
init_sleep();

// src/utils/computerUse/drainRunLoop.ts
init_debug();

// src/utils/withResolvers.ts
function withResolvers() {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
}

// src/utils/computerUse/swiftLoader.ts
var cached;
function requireComputerUseSwift() {
  if (process.platform !== "darwin") {
    throw new Error("@ant/computer-use-swift is macOS-only");
  }
  return cached ??= (init_src(), __toCommonJS(exports_src));
}

// src/utils/computerUse/drainRunLoop.ts
var pump;
var pending = 0;
function drainTick(cu) {
  cu._drainMainRunLoop();
}
function retain() {
  pending++;
  if (pump === undefined) {
    pump = setInterval(drainTick, 1, requireComputerUseSwift());
    logForDebugging("[drainRunLoop] pump started", { level: "verbose" });
  }
}
function release() {
  pending--;
  if (pending <= 0 && pump !== undefined) {
    clearInterval(pump);
    pump = undefined;
    logForDebugging("[drainRunLoop] pump stopped", { level: "verbose" });
    pending = 0;
  }
}
var TIMEOUT_MS = 30000;
function timeoutReject(reject) {
  reject(new Error(`computer-use native call exceeded ${TIMEOUT_MS}ms`));
}
async function drainRunLoop(fn) {
  retain();
  let timer;
  try {
    const work = fn();
    work.catch(() => {});
    const timeout = withResolvers();
    timer = setTimeout(timeoutReject, TIMEOUT_MS, timeout.reject);
    return await Promise.race([work, timeout.promise]);
  } finally {
    clearTimeout(timer);
    release();
  }
}

// src/utils/computerUse/escHotkey.ts
init_debug();
var registered = false;
function notifyExpectedEscape() {
  if (!registered)
    return;
  requireComputerUseSwift().hotkey.notifyExpectedEscape();
}

// src/utils/computerUse/inputLoader.ts
var cached2;
function requireComputerUseInput() {
  if (cached2)
    return cached2;
  const input = (init_src2(), __toCommonJS(exports_src2));
  if (!input.isSupported) {
    throw new Error("@ant/computer-use-input is not supported on this platform");
  }
  return cached2 = input;
}

// src/utils/computerUse/executor.ts
var SCREENSHOT_JPEG_QUALITY = 0.75;
function computeTargetDims(logicalW, logicalH, scaleFactor) {
  const physW = Math.round(logicalW * scaleFactor);
  const physH = Math.round(logicalH * scaleFactor);
  return targetImageSize(physW, physH, API_RESIZE_PARAMS);
}
async function readClipboardViaPbpaste() {
  const { stdout, code } = await execFileNoThrow("pbpaste", [], {
    useCwd: false
  });
  if (code !== 0) {
    throw new Error(`pbpaste exited with code ${code}`);
  }
  return stdout;
}
async function writeClipboardViaPbcopy(text) {
  const { code } = await execFileNoThrow("pbcopy", [], {
    input: text,
    useCwd: false
  });
  if (code !== 0) {
    throw new Error(`pbcopy exited with code ${code}`);
  }
}
function isBareEscape(parts) {
  if (parts.length !== 1)
    return false;
  const lower = parts[0].toLowerCase();
  return lower === "escape" || lower === "esc";
}
var MOVE_SETTLE_MS = 50;
async function moveAndSettle(input, x, y) {
  await input.moveMouse(x, y, false);
  await sleep(MOVE_SETTLE_MS);
}
async function releasePressed(input, pressed) {
  let k;
  while ((k = pressed.pop()) !== undefined) {
    try {
      await input.key(k, "release");
    } catch {}
  }
}
async function withModifiers(input, mods, fn) {
  const pressed = [];
  try {
    for (const m of mods) {
      await input.key(m, "press");
      pressed.push(m);
    }
    return await fn();
  } finally {
    await releasePressed(input, pressed);
  }
}
async function typeViaClipboard(input, text) {
  let saved;
  try {
    saved = await readClipboardViaPbpaste();
  } catch {
    logForDebugging("[computer-use] pbpaste before paste failed; proceeding without restore");
  }
  try {
    await writeClipboardViaPbcopy(text);
    if (await readClipboardViaPbpaste() !== text) {
      throw new Error("Clipboard write did not round-trip.");
    }
    await input.keys(["command", "v"]);
    await sleep(100);
  } finally {
    if (typeof saved === "string") {
      try {
        await writeClipboardViaPbcopy(saved);
      } catch {
        logForDebugging("[computer-use] clipboard restore after paste failed");
      }
    }
  }
}
async function animatedMove(input, targetX, targetY, mouseAnimationEnabled) {
  if (!mouseAnimationEnabled) {
    await moveAndSettle(input, targetX, targetY);
    return;
  }
  const start = await input.mouseLocation();
  const deltaX = targetX - start.x;
  const deltaY = targetY - start.y;
  const distance = Math.hypot(deltaX, deltaY);
  if (distance < 1)
    return;
  const durationSec = Math.min(distance / 2000, 0.5);
  if (durationSec < 0.03) {
    await moveAndSettle(input, targetX, targetY);
    return;
  }
  const frameRate = 60;
  const frameIntervalMs = 1000 / frameRate;
  const totalFrames = Math.floor(durationSec * frameRate);
  for (let frame = 1;frame <= totalFrames; frame++) {
    const t = frame / totalFrames;
    const eased = 1 - Math.pow(1 - t, 3);
    await input.moveMouse(Math.round(start.x + deltaX * eased), Math.round(start.y + deltaY * eased), false);
    if (frame < totalFrames) {
      await sleep(frameIntervalMs);
    }
  }
  await sleep(MOVE_SETTLE_MS);
}
function createCliExecutor(opts) {
  if (process.platform !== "darwin") {
    throw new Error(`createCliExecutor called on ${process.platform}. Computer control is macOS-only.`);
  }
  const cu = requireComputerUseSwift();
  const { getMouseAnimationEnabled, getHideBeforeActionEnabled } = opts;
  const terminalBundleId = getTerminalBundleId();
  const surrogateHost = terminalBundleId ?? CLI_HOST_BUNDLE_ID;
  const withoutTerminal = (allowed) => terminalBundleId === null ? [...allowed] : allowed.filter((id) => id !== terminalBundleId);
  logForDebugging(terminalBundleId ? `[computer-use] terminal ${terminalBundleId} \u2192 surrogate host (hide-exempt, activate-skip, screenshot-excluded)` : "[computer-use] terminal not detected; falling back to sentinel host");
  return {
    capabilities: {
      ...CLI_CU_CAPABILITIES,
      hostBundleId: CLI_HOST_BUNDLE_ID
    },
    async prepareForAction(allowlistBundleIds, displayId) {
      if (!getHideBeforeActionEnabled()) {
        return [];
      }
      return drainRunLoop(async () => {
        try {
          const result = await cu.apps.prepareDisplay(allowlistBundleIds, surrogateHost, displayId);
          if (result.activated) {
            logForDebugging(`[computer-use] prepareForAction: activated ${result.activated}`);
          }
          return result.hidden;
        } catch (err) {
          logForDebugging(`[computer-use] prepareForAction failed; continuing to action: ${errorMessage(err)}`, { level: "warn" });
          return [];
        }
      });
    },
    async previewHideSet(allowlistBundleIds, displayId) {
      return cu.apps.previewHideSet([...allowlistBundleIds, surrogateHost], displayId);
    },
    async getDisplaySize(displayId) {
      return cu.display.getSize(displayId);
    },
    async listDisplays() {
      return cu.display.listAll();
    },
    async findWindowDisplays(bundleIds) {
      return cu.apps.findWindowDisplays(bundleIds);
    },
    async resolvePrepareCapture(opts2) {
      const d = cu.display.getSize(opts2.preferredDisplayId);
      const [targetW, targetH] = computeTargetDims(d.width, d.height, d.scaleFactor);
      return drainRunLoop(() => cu.resolvePrepareCapture(withoutTerminal(opts2.allowedBundleIds), surrogateHost, SCREENSHOT_JPEG_QUALITY, targetW, targetH, opts2.preferredDisplayId, opts2.autoResolve, opts2.doHide));
    },
    async screenshot(opts2) {
      const d = cu.display.getSize(opts2.displayId);
      const [targetW, targetH] = computeTargetDims(d.width, d.height, d.scaleFactor);
      return drainRunLoop(() => cu.screenshot.captureExcluding(withoutTerminal(opts2.allowedBundleIds), SCREENSHOT_JPEG_QUALITY, targetW, targetH, opts2.displayId));
    },
    async zoom(regionLogical, allowedBundleIds, displayId) {
      const d = cu.display.getSize(displayId);
      const [outW, outH] = computeTargetDims(regionLogical.w, regionLogical.h, d.scaleFactor);
      return drainRunLoop(() => cu.screenshot.captureRegion(withoutTerminal(allowedBundleIds), regionLogical.x, regionLogical.y, regionLogical.w, regionLogical.h, outW, outH, SCREENSHOT_JPEG_QUALITY, displayId));
    },
    async key(keySequence, repeat) {
      const input = requireComputerUseInput();
      const parts = keySequence.split("+").filter((p) => p.length > 0);
      const isEsc = isBareEscape(parts);
      const n = repeat ?? 1;
      await drainRunLoop(async () => {
        for (let i = 0;i < n; i++) {
          if (i > 0) {
            await sleep(8);
          }
          if (isEsc) {
            notifyExpectedEscape();
          }
          await input.keys(parts);
        }
      });
    },
    async holdKey(keyNames, durationMs) {
      const input = requireComputerUseInput();
      const pressed = [];
      let orphaned = false;
      try {
        await drainRunLoop(async () => {
          for (const k of keyNames) {
            if (orphaned)
              return;
            if (isBareEscape([k])) {
              notifyExpectedEscape();
            }
            await input.key(k, "press");
            pressed.push(k);
          }
        });
        await sleep(durationMs);
      } finally {
        orphaned = true;
        await drainRunLoop(() => releasePressed(input, pressed));
      }
    },
    async type(text, opts2) {
      const input = requireComputerUseInput();
      if (opts2.viaClipboard) {
        await drainRunLoop(() => typeViaClipboard(input, text));
        return;
      }
      await input.typeText(text);
    },
    readClipboard: readClipboardViaPbpaste,
    writeClipboard: writeClipboardViaPbcopy,
    async moveMouse(x, y) {
      await moveAndSettle(requireComputerUseInput(), x, y);
    },
    async click(x, y, button, count, modifiers) {
      const input = requireComputerUseInput();
      await moveAndSettle(input, x, y);
      if (modifiers && modifiers.length > 0) {
        await drainRunLoop(() => withModifiers(input, modifiers, () => input.mouseButton(button, "click", count)));
      } else {
        await input.mouseButton(button, "click", count);
      }
    },
    async mouseDown() {
      await requireComputerUseInput().mouseButton("left", "press");
    },
    async mouseUp() {
      await requireComputerUseInput().mouseButton("left", "release");
    },
    async getCursorPosition() {
      return requireComputerUseInput().mouseLocation();
    },
    async drag(from, to) {
      const input = requireComputerUseInput();
      if (from !== undefined) {
        await moveAndSettle(input, from.x, from.y);
      }
      await input.mouseButton("left", "press");
      await sleep(MOVE_SETTLE_MS);
      try {
        await animatedMove(input, to.x, to.y, getMouseAnimationEnabled());
      } finally {
        await input.mouseButton("left", "release");
      }
    },
    async scroll(x, y, dx, dy) {
      const input = requireComputerUseInput();
      await moveAndSettle(input, x, y);
      if (dy !== 0) {
        await input.mouseScroll(dy, "vertical");
      }
      if (dx !== 0) {
        await input.mouseScroll(dx, "horizontal");
      }
    },
    async getFrontmostApp() {
      const info = requireComputerUseInput().getFrontmostAppInfo();
      if (!info || !info.bundleId)
        return null;
      return { bundleId: info.bundleId, displayName: info.appName };
    },
    async appUnderPoint(x, y) {
      return cu.apps.appUnderPoint(x, y);
    },
    async listInstalledApps() {
      return drainRunLoop(() => cu.apps.listInstalled());
    },
    async getAppIcon(path) {
      return cu.apps.iconDataUrl(path) ?? undefined;
    },
    async listRunningApps() {
      return cu.apps.listRunning();
    },
    async openApp(bundleId) {
      await cu.apps.open(bundleId);
    }
  };
}

// src/utils/computerUse/hostAdapter.ts
class DebugLogger {
  silly(message, ...args) {
    logForDebugging(format(message, ...args), { level: "debug" });
  }
  debug(message, ...args) {
    logForDebugging(format(message, ...args), { level: "debug" });
  }
  info(message, ...args) {
    logForDebugging(format(message, ...args), { level: "info" });
  }
  warn(message, ...args) {
    logForDebugging(format(message, ...args), { level: "warn" });
  }
  error(message, ...args) {
    logForDebugging(format(message, ...args), { level: "error" });
  }
}
var cached3;
function getComputerUseHostAdapter() {
  if (cached3)
    return cached3;
  cached3 = {
    serverName: COMPUTER_USE_MCP_SERVER_NAME,
    logger: new DebugLogger,
    executor: createCliExecutor({
      getMouseAnimationEnabled: () => getChicagoSubGates().mouseAnimation,
      getHideBeforeActionEnabled: () => getChicagoSubGates().hideBeforeAction
    }),
    ensureOsPermissions: async () => {
      const cu = requireComputerUseSwift();
      const accessibility = cu.tcc.checkAccessibility();
      const screenRecording = cu.tcc.checkScreenRecording();
      return accessibility && screenRecording ? { granted: true } : { granted: false, accessibility, screenRecording };
    },
    isDisabled: () => !getChicagoEnabled(),
    getSubGates: getChicagoSubGates,
    getAutoUnhideEnabled: () => true,
    cropRawPatch: () => null
  };
  return cached3;
}

// src/utils/computerUse/mcpServer.ts
var APP_ENUM_TIMEOUT_MS = 1000;
async function tryGetInstalledAppNames() {
  const adapter = getComputerUseHostAdapter();
  const enumP = adapter.executor.listInstalledApps();
  let timer;
  const timeoutP = new Promise((resolve) => {
    timer = setTimeout(resolve, APP_ENUM_TIMEOUT_MS, undefined);
  });
  const installed = await Promise.race([enumP, timeoutP]).catch(() => {
    return;
  }).finally(() => clearTimeout(timer));
  if (!installed) {
    enumP.catch(() => {});
    logForDebugging(`[Computer Use MCP] app enumeration exceeded ${APP_ENUM_TIMEOUT_MS}ms or failed; tool description omits list`);
    return;
  }
  return filterAppsForDescription(installed, homedir());
}
async function createComputerUseMcpServerForCli() {
  const adapter = getComputerUseHostAdapter();
  const coordinateMode = getChicagoCoordinateMode();
  const server = createComputerUseMcpServer(adapter, coordinateMode);
  const installedAppNames = await tryGetInstalledAppNames();
  const tools = buildComputerUseTools(adapter.executor.capabilities, coordinateMode, installedAppNames);
  server.setRequestHandler(ListToolsRequestSchema, async () => adapter.isDisabled() ? { tools: [] } : { tools });
  return server;
}
async function runComputerUseMcpServer() {
  enableConfigs();
  initializeAnalyticsSink();
  const server = await createComputerUseMcpServerForCli();
  const transport = new StdioServerTransport;
  let exiting = false;
  const shutdownAndExit = async () => {
    if (exiting)
      return;
    exiting = true;
    await Promise.all([shutdown1PEventLogging(), shutdownDatadog()]);
    process.exit(0);
  };
  process.stdin.on("end", () => void shutdownAndExit());
  process.stdin.on("error", () => void shutdownAndExit());
  logForDebugging("[Computer Use MCP] Starting MCP server");
  await server.connect(transport);
  logForDebugging("[Computer Use MCP] MCP server started");
}
export {
  runComputerUseMcpServer,
  createComputerUseMcpServerForCli
};
