#!/usr/bin/env node
const require = (await import('node:module')).createRequire(import.meta.url); const __chunk_filename = (await import('node:url')).fileURLToPath(import.meta.url); const __chunk_dirname = (await import('node:path')).dirname(__chunk_filename);
import {
  RELAUNCH_EXIT_CODE,
  getScriptArgs,
  getSpawnConfig
} from "./chunk-CSKXYL76.js";
import "./chunk-YIJWUMMP.js";
import "./chunk-FC67CGD5.js";
import "./chunk-RCJSF5RP.js";
import "./chunk-6HI7VNOG.js";
import "./chunk-TUDYL3X4.js";
import "./chunk-IUUIT4SU.js";
import "./chunk-34MYV7JD.js";

// packages/cli/index.ts
import { spawn } from "node:child_process";
import os from "node:os";
import v8 from "node:v8";
process.on("uncaughtException", (error) => {
  if (error instanceof Error) {
    const message = error.message || "";
    const isPtyResizeError = message === "Cannot resize a pty that has already exited";
    const isEbadfError = message.includes("EBADF") || error.code === "EBADF";
    const isFromNodePty = error.stack?.includes("node-pty") || error.stack?.includes("PtyResize");
    if ((isPtyResizeError || isEbadfError) && isFromNodePty) {
      return;
    }
  }
  if (error instanceof Error) {
    process.stderr.write(error.stack + "\n");
  } else {
    process.stderr.write(String(error) + "\n");
  }
  process.exit(1);
});
async function getMemoryNodeArgs() {
  let autoConfigureMemory = true;
  try {
    const { readFileSync } = await import("node:fs");
    const { join } = await import("node:path");
    const baseDir = process.env["GEMINI_CLI_HOME"] || join(os.homedir(), ".gemini");
    const settingsPath = join(baseDir, "settings.json");
    const rawSettings = readFileSync(settingsPath, "utf8");
    const settings = JSON.parse(rawSettings);
    if (settings?.advanced?.autoConfigureMemory === false) {
      autoConfigureMemory = false;
    }
  } catch {
  }
  if (autoConfigureMemory) {
    const totalMemoryMB = os.totalmem() / (1024 * 1024);
    const heapStats = v8.getHeapStatistics();
    const currentMaxOldSpaceSizeMb = Math.floor(
      heapStats.heap_size_limit / 1024 / 1024
    );
    const targetMaxOldSpaceSizeInMB = Math.floor(totalMemoryMB * 0.5);
    if (targetMaxOldSpaceSizeInMB > currentMaxOldSpaceSizeMb) {
      return [`--max-old-space-size=${targetMaxOldSpaceSizeInMB}`];
    }
  }
  return [];
}
async function run() {
  if (!process.env["GEMINI_CLI_NO_RELAUNCH"] && !process.env["SANDBOX"]) {
    const scriptArgs = getScriptArgs();
    const memoryArgs = await getMemoryNodeArgs();
    const { spawnArgs, env: newEnv } = getSpawnConfig(memoryArgs, scriptArgs);
    let latestAdminSettings = void 0;
    for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) {
      process.on(sig, () => {
      });
    }
    const runner = () => {
      process.stdin.pause();
      const child = spawn(process.execPath, spawnArgs, {
        stdio: ["inherit", "inherit", "inherit", "ipc"],
        env: newEnv
      });
      if (latestAdminSettings) {
        child.send({ type: "admin-settings", settings: latestAdminSettings });
      }
      child.on("message", (msg) => {
        if (msg.type === "admin-settings-update" && msg.settings) {
          latestAdminSettings = msg.settings;
        }
      });
      return new Promise((resolve) => {
        child.on("error", (err) => {
          process.stderr.write(
            "Error: Failed to start child process: " + err.message + "\n"
          );
          resolve(1);
        });
        child.on("close", (code) => {
          process.stdin.resume();
          resolve(code ?? 1);
        });
      });
    };
    while (true) {
      try {
        const exitCode = await runner();
        if (process.platform === "android" || exitCode !== RELAUNCH_EXIT_CODE) {
          process.exit(exitCode);
        }
      } catch (error) {
        process.stdin.resume();
        process.stderr.write(
          `Fatal error: Failed to relaunch the CLI process.
${error instanceof Error ? error.stack ?? error.message : String(error)}
`
        );
        process.exit(1);
      }
    }
  } else {
    const { main } = await import("./gemini-YXO2QQ66.js");
    const { FatalError, writeToStderr } = await import("./dist-6R4J6OFH.js");
    const { runExitCleanup } = await import("./cleanup-SBGWM3G7.js");
    main().catch(async (error) => {
      const cleanupTimeout = setTimeout(() => {
        writeToStderr("Cleanup timed out, forcing exit...\n");
        process.exit(1);
      }, 5e3);
      try {
        await runExitCleanup();
      } catch (cleanupError) {
        writeToStderr(
          `Error during final cleanup: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}
`
        );
      } finally {
        clearTimeout(cleanupTimeout);
      }
      if (error instanceof FatalError) {
        let errorMessage = error.message;
        if (!process.env["NO_COLOR"]) {
          errorMessage = `\x1B[31m${errorMessage}\x1B[0m`;
        }
        writeToStderr(errorMessage + "\n");
        process.exit(error.exitCode);
      }
      writeToStderr("An unexpected critical error occurred:");
      if (error instanceof Error) {
        writeToStderr(error.stack + "\n");
      } else {
        writeToStderr(String(error) + "\n");
      }
      process.exit(1);
    });
  }
}
run();
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
