#!/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-L65GBLSB.js";
import "./chunk-JYX3C2WW.js";
import "./chunk-IEUGA5B3.js";
import "./chunk-W4YMYD53.js";
import "./chunk-664ZODQF.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-APOZRZEF.js");
    const { FatalError, writeToStderr } = await import("./dist-RBJXQVTJ.js");
    const { runExitCleanup } = await import("./cleanup-BX4TG437.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
 */
