// lib/launcher/index.ts
import { spawn } from "child_process";
import { fileURLToPath } from "url";
import path from "path";
async function waitForServer(port, timeout = 3e4) {
  const start = Date.now();
  while (Date.now() - start < timeout) {
    try {
      const res = await fetch(`http://localhost:${port}/health`);
      if (res.ok) return;
    } catch {
    }
    await new Promise((r) => setTimeout(r, 100));
  }
  throw new Error(`Inspector failed to start within ${timeout}ms`);
}
var INSPECTOR_PORT = 6274;
async function launchInspector(options = {}) {
  const __dirname2 = path.dirname(fileURLToPath(import.meta.url));
  const binPath = path.resolve(__dirname2, "../../../bin/start.js");
  const env = {
    ...Object.fromEntries(
      Object.entries(process.env).filter(([, v]) => v !== void 0)
    )
  };
  if (options.server) {
    const config = {
      mcpServers: {
        [options.server.name]: {
          url: options.server.url,
          ...options.server.headers && { headers: options.server.headers },
          ...options.server.useOAuth && { useOAuth: true }
        }
      }
    };
    env.MCP_CONFIG_DATA = JSON.stringify(config);
    env.MCP_AUTO_CONNECT_SERVER = options.server.name;
  }
  if (options.defaultTab) {
    const tab = options.defaultTab === "chat" ? "chat-v2" : options.defaultTab;
    env.MCP_INITIAL_TAB = tab;
  }
  if (options.verbose) {
    env.VERBOSE_LOGS = "true";
  }
  if (options.cspMode) {
    env.MCP_CSP_MODE = options.cspMode;
  }
  const child = spawn("node", [binPath], {
    env,
    stdio: "inherit",
    detached: false
  });
  await new Promise((resolve, reject) => {
    let resolved = false;
    child.on("error", (err) => {
      if (!resolved) {
        resolved = true;
        reject(new Error(`Failed to spawn inspector process: ${err.message}`));
      }
    });
    waitForServer(INSPECTOR_PORT).then(() => {
      if (!resolved) {
        resolved = true;
        resolve();
      }
    }).catch((err) => {
      if (!resolved) {
        resolved = true;
        reject(err);
      }
    });
  });
  const tabHash = options.defaultTab ? `#${options.defaultTab === "chat" ? "chat-v2" : options.defaultTab}` : "";
  const url = `http://localhost:${INSPECTOR_PORT}${tabHash}`;
  return {
    url,
    process: child,
    stop: async () => {
      child.kill("SIGTERM");
      await new Promise((resolve) => {
        const timeout = setTimeout(() => {
          child.kill("SIGKILL");
          resolve();
        }, 5e3);
        child.on("exit", () => {
          clearTimeout(timeout);
          resolve();
        });
      });
    }
  };
}
export {
  launchInspector
};
//# sourceMappingURL=index.js.map