// Force strict mode and setup for ESM
"use strict";
import {
  appEvents,
  assembleMcpServers,
  buildDisabledSkillNamesProvider,
  getPendingGatedMcpServers,
  getPromptableMcpServers,
  isDebugMode,
  isValidSessionId,
  loadCliConfig,
  loadSandboxConfig,
  parseArguments,
  validateAuthMethod
} from "./chunk-ELI66RUB.js";
import {
  RELAUNCH_EXIT_CODE
} from "./chunk-4GUTCDQF.js";
import "./chunk-AHNXYU4O.js";
import "./chunk-UP5425FW.js";
import {
  getHeadlessYoloSafetyWarning
} from "./chunk-BJBWRCSK.js";
import "./chunk-JS3HF3E4.js";
import "./chunk-3GONHQOA.js";
import "./chunk-OECD6OJV.js";
import "./chunk-J3F7X3LW.js";
import {
  require_undici
} from "./chunk-54YZOP7P.js";
import "./chunk-YBTKKNGO.js";
import "./chunk-RNBYOUGV.js";
import "./chunk-W6X4FGWX.js";
import "./chunk-ALX6BUYW.js";
import "./chunk-OD6TMXL7.js";
import "./chunk-NIOPRZNN.js";
import "./chunk-SEZC2725.js";
import {
  SETTINGS_DIRECTORY_NAME,
  createMinimalSettings,
  getFlattenedSchema,
  getSettingsWarnings,
  getUserSettingsDir,
  initializeLlmOutputLanguage,
  loadSettings,
  preResolveHomeEnvOverrides
} from "./chunk-WVMLL7UN.js";
import {
  initializeI18n,
  resolveLanguageSetting
} from "./chunk-IYOWA7FD.js";
import "./chunk-TLRYABYP.js";
import "./chunk-EDAGQADF.js";
import "./chunk-MX2YXRER.js";
import "./chunk-HI55Z6PR.js";
import "./chunk-UFC57OYT.js";
import "./chunk-OJCECIJA.js";
import {
  ENV_CORRUPTED_PATH,
  ENV_WAS_RECOVERED
} from "./chunk-PPFWEV7G.js";
import "./chunk-7HRRYBVZ.js";
import {
  writeStderrLine
} from "./chunk-Y6Z2O3WR.js";
import "./chunk-QYUE6W3T.js";
import {
  GitWorktreeService,
  QWEN_CODE_SIMPLE_ENV_VAR,
  SessionService,
  canUseRipgrep,
  getAllProviderBaseUrls,
  isBareMode,
  isSessionRuntimeActive,
  persistSessionUsage,
  readWorktreeSession,
  readWorktreeSessionMarker,
  require_shell_quote,
  setStartupEventSink,
  watch,
  worktreeBranchForSlug,
  writeWorktreeSession,
  writeWorktreeSessionMarker
} from "./chunk-SS2LXHYC.js";
import "./chunk-5P5XGNYH.js";
import "./chunk-K5PGHDBN.js";
import "./chunk-SKAZWEV5.js";
import "./chunk-QOMAHFYI.js";
import "./chunk-G7OQ3RFJ.js";
import "./chunk-LKWAVAB5.js";
import "./chunk-MEQWZGK5.js";
import "./chunk-UANCYOOQ.js";
import "./chunk-2MPVVENX.js";
import "./chunk-ZTQ26VBE.js";
import "./chunk-SJBIFVD2.js";
import "./chunk-MLZQVCF3.js";
import "./chunk-S5EQPDTM.js";
import "./chunk-LQ7TMOCE.js";
import "./chunk-E5A7LHNN.js";
import "./chunk-GO6LNQXT.js";
import "./chunk-B236XPGF.js";
import "./chunk-YXK4GPYO.js";
import "./chunk-TOAUDIS7.js";
import "./chunk-NPQWQYU6.js";
import {
  getMCPServerStatus,
  logUserPrompt,
  uiTelemetryService
} from "./chunk-DEUDX7RW.js";
import "./chunk-E6US47KI.js";
import "./chunk-UWCTAVOD.js";
import "./chunk-OFEVLU4C.js";
import "./chunk-OMX7CUOE.js";
import "./chunk-MOUXUCXQ.js";
import "./chunk-BZHLWC6T.js";
import "./chunk-UQFP2FEF.js";
import {
  require_fast_deep_equal
} from "./chunk-4VZH35PN.js";
import "./chunk-TENOUWY2.js";
import "./chunk-GLPV75ES.js";
import "./chunk-22IFUCVR.js";
import "./chunk-T42ACHFI.js";
import "./chunk-YTFBURQD.js";
import "./chunk-YPCPZSZB.js";
import "./chunk-IRJWHZWU.js";
import "./chunk-SYCJMSIJ.js";
import "./chunk-55ZMG67I.js";
import "./chunk-H6BD2ELD.js";
import "./chunk-5IFG2VC4.js";
import "./chunk-64WXLC72.js";
import {
  detectRuntime,
  getOrCreateSharedDispatcher,
  redactProxyCredentials
} from "./chunk-D5KISTLW.js";
import {
  FatalSandboxError,
  Storage,
  createDebugLogger,
  getErrorMessage,
  isDebugLoggingDegraded,
  isSubpath
} from "./chunk-AVQDCKNF.js";
import {
  finalizeStartupProfile,
  isStartupProfilerEnabled,
  profileCheckpoint,
  recordStartupEvent,
  setInteractiveMode
} from "./chunk-ITOGNELQ.js";
import "./chunk-FXGLL2HL.js";
import {
  cleanupCheckpoints,
  registerCleanup,
  runExitCleanup
} from "./chunk-M7DEWH3V.js";
import "./chunk-ZERZSAZL.js";
import "./chunk-QN5NZ3UQ.js";
import "./chunk-BR4QREVK.js";
import "./chunk-Z2Z3GUXZ.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __name,
  __toESM
} from "./chunk-J2S4EL5Y.js";

// packages/cli/src/gemini.tsx
init_esbuild_shims();
import dns from "node:dns";
import os4 from "node:os";
import path6 from "node:path";
import v8 from "node:v8";

// packages/cli/src/config/settingsWatcher.ts
init_esbuild_shims();
import * as fs from "node:fs";
import * as path from "node:path";
var debugLogger = createDebugLogger("SETTINGS_WATCHER");
function collectChangedKeys(before, after, prefix = "") {
  const changed = [];
  const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]);
  for (const key of keys) {
    const keyPath = prefix ? `${prefix}.${key}` : key;
    const beforeValue = before[key];
    const afterValue = after[key];
    if (isPlainObject(beforeValue) && isPlainObject(afterValue)) {
      changed.push(...collectChangedKeys(beforeValue, afterValue, keyPath));
    } else if (JSON.stringify(beforeValue) !== JSON.stringify(afterValue)) {
      changed.push(keyPath);
    }
  }
  return changed;
}
__name(collectChangedKeys, "collectChangedKeys");
function isPlainObject(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
__name(isPlainObject, "isPlainObject");
function isRestartRequiredKey(changedPath) {
  const flattened = getFlattenedSchema();
  const parts = changedPath.split(".");
  for (let i = parts.length; i > 0; i--) {
    const candidate = parts.slice(0, i).join(".");
    const definition = flattened[candidate];
    if (definition) return definition.requiresRestart === true;
  }
  return false;
}
__name(isRestartRequiredKey, "isRestartRequiredKey");
var SettingsWatcher = class _SettingsWatcher {
  static {
    __name(this, "SettingsWatcher");
  }
  settings;
  watchers = /* @__PURE__ */ new Map();
  /**
   * Per-scope watch stage. `bootstrap` watches the parent directory waiting
   * for the missing `.qwen` dir to appear; `target` watches `.qwen` itself.
   */
  watchStage = /* @__PURE__ */ new Map();
  /**
   * Per-scope generation token. Bumped on every promote/demote so that a
   * stale `'all'` callback from a watcher being torn down (chokidar `close()`
   * is async) becomes a no-op instead of stacking watchers.
   */
  watchGeneration = /* @__PURE__ */ new Map();
  changeListeners = /* @__PURE__ */ new Set();
  refreshTimer = null;
  pendingScopeChanges = /* @__PURE__ */ new Set();
  processing = false;
  started = false;
  static DEBOUNCE_MS = 300;
  static LISTENER_TIMEOUT_MS = 3e4;
  constructor(settings) {
    this.settings = settings;
  }
  startWatching() {
    if (this.started) return;
    this.started = true;
    for (const { scope, settingsPath } of this.getScopePaths()) {
      if (!settingsPath) continue;
      const dir = path.dirname(settingsPath);
      if (fs.existsSync(dir)) {
        this.watchTargetDir(scope, settingsPath);
      } else {
        this.watchParentForDir(scope, settingsPath);
      }
    }
  }
  /**
   * Watches the resolved `.qwen` directory for changes to `settings.json`.
   * If `.qwen` itself is removed, demotes back to a parent bootstrap watcher
   * so a later re-creation is still caught.
   */
  watchTargetDir(scope, settingsPath) {
    const dir = path.dirname(settingsPath);
    const targetBasename = path.basename(settingsPath);
    const gen = this.bumpGeneration(scope);
    try {
      const watcher = watch(dir, {
        ignoreInitial: true,
        depth: 0,
        ignored: /* @__PURE__ */ __name((filePath, stats) => {
          if (stats && !stats.isFile() && !stats.isDirectory()) return true;
          return false;
        }, "ignored")
      }).on("all", (event, changedPath) => {
        if (this.watchGeneration.get(scope) !== gen) return;
        if (event === "unlinkDir" && changedPath === dir) {
          void this.demoteScope(scope, settingsPath);
          return;
        }
        if (path.basename(changedPath) !== targetBasename) return;
        this.scheduleRefresh(scope);
      }).on("error", (error) => {
        debugLogger.warn(`Settings watcher error for ${dir}:`, error);
      });
      this.watchers.set(scope, watcher);
      this.watchStage.set(scope, "target");
    } catch (error) {
      debugLogger.warn(
        `Failed to start settings watcher for ${scope} (${dir}):`,
        error
      );
    }
  }
  /**
   * Bootstrap watcher: monitors the parent directory (depth 0) with a strict
   * predicate that only allows the `.qwen` entry through, so unrelated
   * top-level churn is suppressed and the project tree is never recursed.
   * Promotes to a target watcher once `.qwen` appears.
   */
  watchParentForDir(scope, settingsPath) {
    const dir = path.dirname(settingsPath);
    const parentDir = path.dirname(dir);
    const dirBasename = path.basename(dir);
    const gen = this.bumpGeneration(scope);
    try {
      const watcher = watch(parentDir, {
        ignoreInitial: true,
        depth: 0,
        ignored: /* @__PURE__ */ __name((filePath) => filePath !== parentDir && path.basename(filePath) !== dirBasename, "ignored")
      }).on("all", (_event, changedPath) => {
        if (this.watchGeneration.get(scope) !== gen) return;
        if (path.basename(changedPath) !== dirBasename) return;
        void this.promoteScope(scope, settingsPath);
      }).on("error", (error) => {
        debugLogger.warn(
          `Settings bootstrap watcher error for ${parentDir}:`,
          error
        );
      });
      this.watchers.set(scope, watcher);
      this.watchStage.set(scope, "bootstrap");
    } catch (error) {
      debugLogger.warn(
        `Failed to start settings bootstrap watcher for ${scope} (${parentDir}):`,
        error
      );
      return;
    }
    if (fs.existsSync(dir)) {
      void this.promoteScope(scope, settingsPath);
    }
  }
  /** Swaps a scope's bootstrap watcher for a target watcher on `.qwen`. */
  async promoteScope(scope, settingsPath) {
    if (this.watchStage.get(scope) !== "bootstrap") return;
    await this.replaceWatcher(scope);
    if (!this.started) return;
    this.watchTargetDir(scope, settingsPath);
    this.scheduleRefresh(scope);
  }
  /** Swaps a scope's target watcher back to a parent bootstrap watcher. */
  async demoteScope(scope, settingsPath) {
    if (this.watchStage.get(scope) !== "target") return;
    await this.replaceWatcher(scope);
    if (!this.started) return;
    this.watchParentForDir(scope, settingsPath);
    this.scheduleRefresh(scope);
  }
  /**
   * Bumps the scope generation and closes its current watcher, clearing the
   * map entries before the caller opens the next watcher. Bumping first makes
   * any in-flight callback from the closing watcher a no-op.
   */
  async replaceWatcher(scope) {
    this.bumpGeneration(scope);
    const watcher = this.watchers.get(scope);
    this.watchers.delete(scope);
    this.watchStage.delete(scope);
    if (watcher) {
      try {
        await watcher.close();
      } catch (err) {
        debugLogger.warn("Settings watcher close error:", err);
      }
    }
  }
  bumpGeneration(scope) {
    const next = (this.watchGeneration.get(scope) ?? 0) + 1;
    this.watchGeneration.set(scope, next);
    return next;
  }
  stopWatching() {
    if (!this.started) return;
    this.started = false;
    for (const [, watcher] of this.watchers) {
      watcher.close().catch((err) => {
        debugLogger.warn("Settings watcher close error:", err);
      });
    }
    this.watchers.clear();
    this.watchStage.clear();
    for (const scope of this.watchGeneration.keys()) {
      this.bumpGeneration(scope);
    }
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer);
      this.refreshTimer = null;
    }
    this.pendingScopeChanges.clear();
  }
  addChangeListener(listener) {
    this.changeListeners.add(listener);
    return () => {
      this.changeListeners.delete(listener);
    };
  }
  getScopePaths() {
    const paths = [
      {
        scope: "User" /* User */,
        settingsPath: this.settings.user.path
      }
    ];
    if (this.settings.workspaceSettingsActive) {
      paths.push({
        scope: "Workspace" /* Workspace */,
        settingsPath: this.settings.workspace.path
      });
    }
    return paths;
  }
  scheduleRefresh(scope) {
    this.pendingScopeChanges.add(scope);
    if (this.refreshTimer) clearTimeout(this.refreshTimer);
    this.refreshTimer = setTimeout(() => {
      this.refreshTimer = null;
      void this.drainPendingChanges().catch((err) => {
        debugLogger.warn("Settings watcher refresh error:", err);
      });
    }, _SettingsWatcher.DEBOUNCE_MS);
  }
  async drainPendingChanges() {
    if (this.processing) return;
    this.processing = true;
    try {
      while (this.pendingScopeChanges.size > 0) {
        const scopes = new Set(this.pendingScopeChanges);
        this.pendingScopeChanges.clear();
        await this.handleChange(scopes);
      }
    } finally {
      this.processing = false;
    }
  }
  async handleChange(changedScopes) {
    const events = [];
    for (const scope of changedScopes) {
      const file = this.settings.forScope(scope);
      const before = structuredClone(file.settings ?? {});
      const existedBefore = file.rawJson !== void 0;
      this.settings.reloadScopeFromDisk(scope);
      const after = file.settings ?? {};
      const existsNow = file.rawJson !== void 0;
      const changedKeys = collectChangedKeys(before, after);
      if (changedKeys.length === 0) {
        continue;
      }
      const hasHotReloadableChange = changedKeys.some(
        (key) => !isRestartRequiredKey(key)
      );
      if (!hasHotReloadableChange) {
        continue;
      }
      events.push({
        scope,
        path: file.path,
        changeType: !existedBefore && existsNow ? "created" : existedBefore && !existsNow ? "deleted" : "modified"
      });
    }
    if (events.length > 0) {
      await this.notifyListeners(events);
    }
  }
  async notifyListeners(events) {
    const TIMEOUT_MS = _SettingsWatcher.LISTENER_TIMEOUT_MS;
    const withTimeout = /* @__PURE__ */ __name((p) => {
      let timerId;
      const timeoutPromise = new Promise((_, reject) => {
        timerId = setTimeout(
          () => reject(
            new Error(
              `settings change listener timeout after ${TIMEOUT_MS}ms`
            )
          ),
          TIMEOUT_MS
        );
        if (typeof timerId === "object" && timerId !== null && "unref" in timerId) {
          timerId.unref();
        }
      });
      return Promise.race([p, timeoutPromise]).finally(() => {
        if (timerId !== void 0) clearTimeout(timerId);
      });
    }, "withTimeout");
    const results = await Promise.allSettled(
      Array.from(this.changeListeners).map(
        (listener) => withTimeout(Promise.resolve().then(() => listener(events)))
      )
    );
    for (const result of results) {
      if (result.status === "rejected") {
        debugLogger.warn("Settings change listener error:", result.reason);
      }
    }
  }
};

// packages/cli/src/config/hot-reload.ts
init_esbuild_shims();
var import_fast_deep_equal = __toESM(require_fast_deep_equal(), 1);
var debugLogger2 = createDebugLogger("MCP_HOT_RELOAD");
function mcpServersEqual(a, b) {
  return (0, import_fast_deep_equal.default)(a ?? {}, b ?? {});
}
__name(mcpServersEqual, "mcpServersEqual");
function mcpGatingEqual(a, b) {
  const norm = /* @__PURE__ */ __name((xs) => [...xs ?? []].sort(), "norm");
  const allowedEqual = a.allowed === void 0 === (b.allowed === void 0) && (0, import_fast_deep_equal.default)(norm(a.allowed), norm(b.allowed));
  return (0, import_fast_deep_equal.default)(norm(a.excluded), norm(b.excluded)) && allowedEqual && (0, import_fast_deep_equal.default)(norm(a.pending), norm(b.pending));
}
__name(mcpGatingEqual, "mcpGatingEqual");
function recomputeMcpGating(settings, assembled, cwd, bootAllowed) {
  const settingsAllowed = settings.merged.mcp?.allowed?.filter(Boolean);
  const excluded = settings.merged.mcp?.excluded?.filter(Boolean);
  let allowed = settingsAllowed;
  if (bootAllowed) {
    allowed = settingsAllowed ? settingsAllowed.filter((n) => bootAllowed.includes(n)) : [...bootAllowed];
  }
  return {
    allowed,
    excluded: excluded && excluded.length > 0 ? excluded : void 0,
    pending: getPendingGatedMcpServers(assembled, cwd)
  };
}
__name(recomputeMcpGating, "recomputeMcpGating");
function registerMcpHotReload(watcher, settings, config, topTierMcpServers) {
  debugLogger2.debug("registered MCP hot-reload listener on SettingsWatcher");
  return watcher.addChangeListener(async (events) => {
    debugLogger2.debug(
      `settings change fired (${events.length} event(s)): ${events.map((e) => `${e.scope}:${e.changeType}`).join(", ")}`
    );
    const cwd = config.getTargetDir();
    const next = assembleMcpServers(
      settings.merged.mcpServers,
      cwd,
      topTierMcpServers
    );
    const nextGating = recomputeMcpGating(
      settings,
      next,
      cwd,
      config.getCliAllowedMcpServerNames()
    );
    const prevServers = config.getSettingsMcpServers();
    const prevGating = config.getMcpGating();
    debugLogger2.debug(
      `assembled servers: prev=[${Object.keys(prevServers ?? {}).join(
        ", "
      )}] next=[${Object.keys(next).join(", ")}]`
    );
    debugLogger2.debug(
      `gating next: excluded=[${(nextGating.excluded ?? []).join(
        ", "
      )}] allowed=[${(nextGating.allowed ?? []).join(
        ", "
      )}] pending=[${(nextGating.pending ?? []).join(", ")}]`
    );
    const serversChanged = !mcpServersEqual(prevServers, next);
    const gatingChanged = !mcpGatingEqual(prevGating, nextGating);
    if (!serversChanged && !gatingChanged) {
      debugLogger2.debug(
        "no MCP-relevant change (servers + gating unchanged) \u2014 skipping reconcile"
      );
      return;
    }
    debugLogger2.debug(
      `MCP-relevant change detected (serversChanged=${serversChanged} gatingChanged=${gatingChanged}) \u2014 reconciling`
    );
    const promptable = getPromptableMcpServers(next, cwd);
    config.setExcludedMcpServers(nextGating.excluded ?? []);
    config.setAllowedMcpServers(nextGating.allowed);
    config.setPendingMcpServers(nextGating.pending);
    try {
      await config.reinitializeMcpServers(next);
      const finalStatuses = Object.keys(next).map((name) => `${name}=${getMCPServerStatus(name)}`).join(", ");
      debugLogger2.debug(
        `reinitializeMcpServers resolved; final statuses=[${finalStatuses}]`
      );
    } catch (err) {
      debugLogger2.error(
        `reinitializeMcpServers threw: ${err instanceof Error ? err.stack ?? err.message : String(err)}`
      );
      appEvents.emit(
        "log-error" /* LogError */,
        "Failed to reload MCP server settings; existing MCP state may be unchanged. Run with --debug for details."
      );
    }
    if (promptable.length > 0) {
      debugLogger2.debug(
        `gated servers awaiting approval \u2192 emitting ${"mcp-pending-approval-changed" /* McpPendingApprovalChanged */}: [${promptable.join(
          ", "
        )}]`
      );
      appEvents.emit("mcp-pending-approval-changed" /* McpPendingApprovalChanged */);
    }
  });
}
__name(registerMcpHotReload, "registerMcpHotReload");

// packages/cli/src/startup/worktreeStartup.ts
init_esbuild_shims();
import * as path2 from "node:path";
var debugLogger3 = createDebugLogger("WORKTREE_STARTUP");
var DETACHED_HEAD = "HEAD";
async function setupStartupWorktree(rawInput, options) {
  if (rawInput === void 0) return null;
  const trimmed = rawInput.trim();
  const launchCwd = process.cwd();
  const probe = new GitWorktreeService(launchCwd);
  const gitCheck = await probe.checkGitAvailable();
  if (!gitCheck.available) {
    return {
      ok: false,
      error: `--worktree: ${gitCheck.error ?? "git is not available on PATH."}`
    };
  }
  if (/[\\/]\.qwen[\\/]worktrees[\\/]/.test(launchCwd)) {
    return {
      ok: false,
      error: `--worktree: cannot start a new worktree from inside another worktree (cwd: ${launchCwd}). Run from the main checkout.`
    };
  }
  const rawRepoRoot = await probe.getRepoTopLevel();
  if (rawRepoRoot === null) {
    return {
      ok: false,
      error: `--worktree: ${launchCwd} is not a git repository. Run \`git init\` first or relaunch from inside one.`
    };
  }
  const repoRoot = path2.resolve(rawRepoRoot);
  const service = repoRoot === launchCwd ? probe : new GitWorktreeService(repoRoot);
  const prNumber = GitWorktreeService.parsePRReference(trimmed);
  const isPullRequest = prNumber !== null;
  let slug;
  if (prNumber !== null) {
    slug = `pr-${prNumber}`;
  } else if (trimmed.length === 0) {
    slug = GitWorktreeService.generateAutoSlug();
  } else {
    const validation = GitWorktreeService.validateUserWorktreeSlug(trimmed);
    if (validation) {
      return { ok: false, error: `--worktree: ${validation}` };
    }
    slug = trimmed;
  }
  const [originalBranchRaw, originalHeadCommit] = await Promise.all([
    service.getCurrentBranch().catch(() => void 0),
    service.getCurrentCommitHash().catch(() => "")
  ]);
  const originalBranch = originalBranchRaw && originalBranchRaw !== DETACHED_HEAD ? originalBranchRaw : void 0;
  const expectedWorktreePath = service.getUserWorktreePath(slug);
  const expectedBranch = worktreeBranchForSlug(slug);
  let registered = null;
  try {
    registered = await service.getRegisteredWorktreeBranch(expectedWorktreePath);
  } catch {
    registered = null;
  }
  if (registered !== null) {
    if (registered.branch !== expectedBranch) {
      return {
        ok: false,
        error: `--worktree: ${expectedWorktreePath} is already a git worktree, but its branch is ${registered.branch} (expected ${expectedBranch}). Refusing to re-attach. Resolve the conflict manually (e.g. \`git worktree remove ${expectedWorktreePath}\`).`
      };
    }
    const worktreePath2 = path2.resolve(expectedWorktreePath);
    try {
      process.chdir(worktreePath2);
    } catch (error) {
      return {
        ok: false,
        error: `--worktree: failed to chdir into ${worktreePath2} (${error instanceof Error ? error.message : String(error)}).`
      };
    }
    debugLogger3.debug(
      `setupStartupWorktree: re-attached to existing worktree at ${worktreePath2} (branch=${registered.branch})`
    );
    return {
      ok: true,
      context: {
        worktreePath: worktreePath2,
        slug,
        branch: registered.branch,
        repoRoot,
        originalBranch: originalBranch ?? DETACHED_HEAD,
        originalHeadCommit: registered.headCommit,
        isPullRequest,
        wasReattached: true
      }
    };
  }
  let pullRequestHeadSha = null;
  if (prNumber !== null) {
    const fetchRes = await service.fetchPullRequestRef(prNumber);
    if (!fetchRes.success) {
      return { ok: false, error: `--worktree: ${fetchRes.error}` };
    }
    pullRequestHeadSha = await service.resolveRef("FETCH_HEAD");
    if (pullRequestHeadSha === null) {
      return {
        ok: false,
        error: `--worktree: fetched PR #${prNumber} but FETCH_HEAD did not resolve to a commit SHA. Refusing to proceed (the worktree would otherwise branch off an unknown commit).`
      };
    }
  }
  const baseRef = isPullRequest ? pullRequestHeadSha : originalBranch;
  const result = await service.createUserWorktree(slug, baseRef, {
    symlinkDirectories: options?.symlinkDirectories
  });
  if (!result.success || !result.worktree) {
    return {
      ok: false,
      error: `--worktree: ${result.error ?? "failed to create worktree."}`
    };
  }
  const worktreePath = path2.resolve(result.worktree.path);
  try {
    process.chdir(worktreePath);
  } catch (error) {
    return {
      ok: false,
      error: `--worktree: created worktree at ${worktreePath} but failed to chdir into it (${error instanceof Error ? error.message : String(error)}). Run \`cd ${worktreePath}\` manually.`
    };
  }
  return {
    ok: true,
    context: {
      worktreePath,
      slug,
      branch: result.worktree.branch,
      repoRoot,
      originalBranch: originalBranch ?? DETACHED_HEAD,
      // For PR worktrees, the worktree's HEAD starts at the fetched PR
      // tip — not at the parent repo's HEAD. Use the SHA we locked in
      // post-fetch so the exit-dialog rev-list counts only the user's
      // new commits, not the entire PR history.
      originalHeadCommit: isPullRequest ? pullRequestHeadSha : originalHeadCommit,
      isPullRequest,
      wasReattached: false
    }
  };
}
__name(setupStartupWorktree, "setupStartupWorktree");
async function persistStartupWorktreeSidecar(config, context) {
  const sessionId = config.getSessionId();
  const sidecarPath = config.getSessionService().getWorktreeSessionPath(sessionId);
  let overrodeResumedWorktree = false;
  let overriddenSlug;
  let previous = null;
  try {
    previous = await readWorktreeSession(sidecarPath);
  } catch (error) {
    debugLogger3.warn(
      `persistStartupWorktreeSidecar: failed to read existing sidecar at ${sidecarPath} \u2014 treating as "no previous worktree" and proceeding: ${error}`
    );
    previous = null;
  }
  if (previous && previous.slug !== context.slug) {
    overrodeResumedWorktree = true;
    overriddenSlug = previous.slug;
  }
  let shouldWriteMarker = !context.wasReattached;
  if (context.wasReattached) {
    const owner = await readWorktreeSessionMarker(context.worktreePath);
    if (owner === null || owner === sessionId) {
      shouldWriteMarker = true;
    } else {
      const ownerActive = await isSessionRuntimeActive(owner, [
        context.repoRoot,
        context.worktreePath
      ]).catch((error) => {
        debugLogger3.warn(
          `persistStartupWorktreeSidecar: failed to check owner runtime ${owner}: ${error}`
        );
        return true;
      });
      shouldWriteMarker = !ownerActive;
    }
  }
  if (shouldWriteMarker) {
    await writeWorktreeSessionMarker(context.worktreePath, sessionId).catch(
      () => {
      }
    );
  }
  await writeWorktreeSession(sidecarPath, {
    slug: context.slug,
    worktreePath: context.worktreePath,
    worktreeBranch: context.branch,
    originalCwd: context.repoRoot,
    originalBranch: context.originalBranch,
    originalHeadCommit: context.originalHeadCommit
  });
  return { overrodeResumedWorktree, overriddenSlug, sidecarPath };
}
__name(persistStartupWorktreeSidecar, "persistStartupWorktreeSidecar");
function buildStartupWorktreeNotice(context, override) {
  const verb = context.wasReattached ? "Re-attached to worktree" : "Active worktree";
  const base = `[Startup] ${verb}: "${context.slug}" at ${context.worktreePath} (branch: ${context.branch}). Continue using this path for all file operations.`;
  if (override?.overrodeResumedWorktree && override.overriddenSlug) {
    return `${base}
Note: --worktree overrode the resumed session's previous worktree "${override.overriddenSlug}". That worktree directory was left intact; re-attach with \`qwen --worktree ${override.overriddenSlug}\` if needed.`;
  }
  return base;
}
__name(buildStartupWorktreeNotice, "buildStartupWorktreeNotice");

// packages/cli/src/utils/readStdin.ts
init_esbuild_shims();
function takeUtf8Prefix(value, maxBytes) {
  let bytes = 0;
  let end = 0;
  for (const char of value) {
    const charBytes = Buffer.byteLength(char, "utf8");
    if (bytes + charBytes > maxBytes) {
      break;
    }
    bytes += charBytes;
    end += char.length;
  }
  return value.slice(0, end);
}
__name(takeUtf8Prefix, "takeUtf8Prefix");
async function readStdin() {
  const MAX_STDIN_SIZE = 8 * 1024 * 1024;
  return new Promise((resolve2, reject) => {
    let data = "";
    let totalSize = 0;
    let settled = false;
    process.stdin.setEncoding("utf8");
    const pipedInputShouldBeAvailableInMs = 500;
    let pipedInputTimerId = setTimeout(() => {
      onEnd();
    }, pipedInputShouldBeAvailableInMs);
    const onReadable = /* @__PURE__ */ __name(() => {
      let chunk;
      while ((chunk = process.stdin.read()) !== null) {
        if (pipedInputTimerId) {
          clearTimeout(pipedInputTimerId);
          pipedInputTimerId = null;
        }
        const chunkSize = Buffer.byteLength(chunk, "utf8");
        if (totalSize + chunkSize > MAX_STDIN_SIZE) {
          const remainingSize = MAX_STDIN_SIZE - totalSize;
          const prefix = takeUtf8Prefix(chunk, remainingSize);
          data += prefix;
          totalSize += Buffer.byteLength(prefix, "utf8");
          writeStderrLine(
            `Warning: stdin input truncated to ${MAX_STDIN_SIZE} bytes.`
          );
          finish();
          process.stdin.destroy();
          return;
        }
        data += chunk;
        totalSize += chunkSize;
      }
    }, "onReadable");
    const finish = /* @__PURE__ */ __name(() => {
      if (settled) return;
      settled = true;
      cleanup();
      resolve2(data);
    }, "finish");
    const onEnd = /* @__PURE__ */ __name(() => {
      finish();
    }, "onEnd");
    const onError = /* @__PURE__ */ __name((err) => {
      if (settled) return;
      settled = true;
      cleanup();
      reject(err);
    }, "onError");
    const cleanup = /* @__PURE__ */ __name(() => {
      if (pipedInputTimerId) {
        clearTimeout(pipedInputTimerId);
        pipedInputTimerId = null;
      }
      process.stdin.removeListener("readable", onReadable);
      process.stdin.removeListener("end", onEnd);
      process.stdin.removeListener("error", onError);
    }, "cleanup");
    process.stdin.on("readable", onReadable);
    process.stdin.on("end", onEnd);
    process.stdin.on("error", onError);
  });
}
__name(readStdin, "readStdin");

// packages/cli/src/utils/relaunch.ts
init_esbuild_shims();
import { spawn } from "node:child_process";
async function relaunchOnExitCode(runner) {
  while (true) {
    try {
      const exitCode = await runner();
      if (exitCode !== RELAUNCH_EXIT_CODE) {
        process.exit(exitCode);
      }
    } catch (error) {
      process.stdin.resume();
      writeStderrLine("Fatal error: Failed to relaunch the CLI process.");
      writeStderrLine(error instanceof Error ? error.message : String(error));
      process.exit(1);
    }
  }
}
__name(relaunchOnExitCode, "relaunchOnExitCode");
async function relaunchAppInChildProcess(additionalNodeArgs, additionalScriptArgs, options) {
  if (process.env["QWEN_CODE_NO_RELAUNCH"]) {
    return;
  }
  const runner = /* @__PURE__ */ __name(() => {
    const script = process.argv[1];
    const scriptArgs = process.argv.slice(2);
    const nodeArgs = [
      ...process.execArgv,
      ...additionalNodeArgs,
      script,
      ...additionalScriptArgs,
      ...scriptArgs
    ];
    const newEnv = { ...process.env, QWEN_CODE_NO_RELAUNCH: "true" };
    process.stdin.pause();
    const child = spawn(process.execPath, nodeArgs, {
      stdio: "inherit",
      env: newEnv
    });
    try {
      options?.afterSpawn?.();
    } catch (err) {
      child.kill();
      throw err;
    }
    return new Promise((resolve2, reject) => {
      child.on("error", reject);
      child.on("close", (code) => {
        process.stdin.resume();
        resolve2(code ?? 1);
      });
    });
  }, "runner");
  await relaunchOnExitCode(runner);
}
__name(relaunchAppInChildProcess, "relaunchAppInChildProcess");

// packages/cli/src/utils/sandbox.ts
init_esbuild_shims();
var import_shell_quote = __toESM(require_shell_quote(), 1);
import { exec, execSync, spawn as spawn2 } from "node:child_process";
import os2 from "node:os";
import path4 from "node:path";
import fs2 from "node:fs";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { randomBytes } from "node:crypto";

// packages/cli/src/utils/sandboxImageName.ts
init_esbuild_shims();
function parseSandboxImageName(image) {
  const imageWithoutDigest = image.split("@")[0] ?? image;
  const lastSlash = imageWithoutDigest.lastIndexOf("/");
  const lastColon = imageWithoutDigest.lastIndexOf(":");
  const hasTag = lastColon > lastSlash;
  const fullName = hasTag ? imageWithoutDigest.slice(0, lastColon) : imageWithoutDigest;
  const tag = hasTag ? imageWithoutDigest.slice(lastColon + 1) : void 0;
  const name = fullName.split("/").at(-1) || "unknown-image";
  return tag ? `${name}-${tag}` : name;
}
__name(parseSandboxImageName, "parseSandboxImageName");

// packages/cli/src/utils/sandbox-path.ts
init_esbuild_shims();
import path3 from "node:path";
function isContainerPathWithinWorkdir(containerWorkdir, containerPath) {
  const normalize = /* @__PURE__ */ __name((value) => {
    const normalized = path3.posix.normalize(value.replace(/\\/g, "/")).replace(/\/+$/, "").toLowerCase();
    return normalized || "/";
  }, "normalize");
  const normalizedWorkdir = normalize(containerWorkdir);
  const normalizedPath = normalize(containerPath);
  if (normalizedWorkdir === "/") {
    return normalizedPath.startsWith("/");
  }
  return normalizedPath === normalizedWorkdir || normalizedPath.startsWith(`${normalizedWorkdir}/`);
}
__name(isContainerPathWithinWorkdir, "isContainerPathWithinWorkdir");

// packages/cli/src/utils/sandboxMounts.ts
init_esbuild_shims();
import os from "node:os";
function parseSandboxMountSpec(rawMount, platform = os.platform()) {
  const mount = rawMount.trim();
  const mountSeparator = platform === "win32" && /^[A-Za-z]:[\\/]/.test(mount) ? mount.indexOf(":", 2) : mount.indexOf(":");
  const from = mountSeparator === -1 ? mount : mount.slice(0, mountSeparator);
  const rest = mountSeparator === -1 ? "" : mount.slice(mountSeparator + 1);
  const [toPart, optsPart] = rest.split(":");
  return {
    from,
    to: toPart || from,
    opts: optsPart || "ro"
  };
}
__name(parseSandboxMountSpec, "parseSandboxMountSpec");

// packages/cli/src/utils/sandbox.ts
var execAsync = promisify(exec);
function getContainerPath(hostPath) {
  if (os2.platform() !== "win32") {
    return hostPath;
  }
  const withForwardSlashes = hostPath.replace(/\\/g, "/");
  const match = withForwardSlashes.match(/^([A-Z]):\/(.*)/i);
  if (match) {
    return `/${match[1].toLowerCase()}/${match[2]}`;
  }
  return hostPath;
}
__name(getContainerPath, "getContainerPath");
function ensureDirectoryAndGetRealPath(dir) {
  if (!fs2.existsSync(dir)) {
    fs2.mkdirSync(dir, { recursive: true });
  }
  return fs2.realpathSync(dir);
}
__name(ensureDirectoryAndGetRealPath, "ensureDirectoryAndGetRealPath");
var LOCAL_DEV_SANDBOX_IMAGE_NAME = "qwen-code-sandbox";
var SANDBOX_NETWORK_NAME = "qwen-code-sandbox";
var SANDBOX_PROXY_NAME = "qwen-code-sandbox-proxy";
var BUILTIN_SEATBELT_PROFILES = [
  "permissive-open",
  "permissive-closed",
  "permissive-proxied",
  "restrictive-open",
  "restrictive-closed",
  "restrictive-proxied"
];
async function shouldUseCurrentUserInSandbox() {
  const envVar = process.env["SANDBOX_SET_UID_GID"]?.toLowerCase().trim();
  if (envVar === "1" || envVar === "true") {
    return true;
  }
  if (envVar === "0" || envVar === "false") {
    return false;
  }
  if (os2.platform() === "linux") {
    const debugEnv = [process.env["DEBUG"], process.env["DEBUG_MODE"]].some(
      (v) => v === "true" || v === "1"
    );
    if (debugEnv) {
      writeStderrLine(
        "INFO: Using current user UID/GID in Linux sandbox. Set SANDBOX_SET_UID_GID=false to disable."
      );
    }
    return true;
  }
  return false;
}
__name(shouldUseCurrentUserInSandbox, "shouldUseCurrentUserInSandbox");
function ports() {
  return (process.env["SANDBOX_PORTS"] ?? "").split(",").filter((p) => p.trim()).map((p) => p.trim());
}
__name(ports, "ports");
function entrypoint(workdir, cliArgs) {
  const isWindows = os2.platform() === "win32";
  const containerWorkdir = getContainerPath(workdir);
  const shellCmds = [];
  const pathSeparator = isWindows ? ";" : ":";
  let pathSuffix = "";
  if (process.env["PATH"]) {
    const paths = process.env["PATH"].split(pathSeparator);
    for (const p of paths) {
      const containerPath = getContainerPath(p);
      if (isContainerPathWithinWorkdir(containerWorkdir, containerPath)) {
        pathSuffix += `:${containerPath}`;
      }
    }
  }
  if (pathSuffix) {
    shellCmds.push(`export PATH="$PATH${pathSuffix}";`);
  }
  let pythonPathSuffix = "";
  if (process.env["PYTHONPATH"]) {
    const paths = process.env["PYTHONPATH"].split(pathSeparator);
    for (const p of paths) {
      const containerPath = getContainerPath(p);
      if (isContainerPathWithinWorkdir(containerWorkdir, containerPath)) {
        pythonPathSuffix += `:${containerPath}`;
      }
    }
  }
  if (pythonPathSuffix) {
    shellCmds.push(`export PYTHONPATH="$PYTHONPATH${pythonPathSuffix}";`);
  }
  const projectSandboxBashrc = path4.join(
    SETTINGS_DIRECTORY_NAME,
    "sandbox.bashrc"
  );
  if (fs2.existsSync(projectSandboxBashrc)) {
    shellCmds.push(`source ${getContainerPath(projectSandboxBashrc)};`);
  }
  ports().forEach(
    (p) => shellCmds.push(
      `socat TCP4-LISTEN:${p},bind=$(hostname -i),fork,reuseaddr TCP4:127.0.0.1:${p} 2> /dev/null &`
    )
  );
  const quotedCliArgs = cliArgs.slice(2).map((arg) => (0, import_shell_quote.quote)([arg]));
  const cliCmd = false ? process.env["DEBUG"] ? "npm run debug --" : "npm rebuild && npm run start --" : process.env["DEBUG"] ? `node --inspect-brk=0.0.0.0:${process.env["DEBUG_PORT"] || "9229"} $(which qwen)` : "qwen";
  const args = [...shellCmds, cliCmd, ...quotedCliArgs];
  return ["bash", "-c", args.join(" ")];
}
__name(entrypoint, "entrypoint");
async function start_sandbox(config, nodeArgs = [], cliConfig, cliArgs = []) {
  if (config.command === "sandbox-exec") {
    if (process.env["BUILD_SANDBOX"]) {
      throw new FatalSandboxError(
        "Cannot BUILD_SANDBOX when using macOS Seatbelt"
      );
    }
    const profile = process.env["SEATBELT_PROFILE"] ??= "permissive-open";
    let profileFile = fileURLToPath(
      new URL(`sandbox-macos-${profile}.sb`, import.meta.url)
    );
    if (!BUILTIN_SEATBELT_PROFILES.includes(profile)) {
      profileFile = path4.join(
        SETTINGS_DIRECTORY_NAME,
        `sandbox-macos-${profile}.sb`
      );
    }
    if (!fs2.existsSync(profileFile)) {
      throw new FatalSandboxError(
        `Missing macos seatbelt profile file '${profileFile}'`
      );
    }
    writeStderrLine(`using macos seatbelt (profile: ${profile}) ...`);
    const nodeOptions = [
      ...process.env["DEBUG"] ? ["--inspect-brk"] : [],
      ...nodeArgs
    ].join(" ");
    const qwenDir = Storage.getGlobalQwenDir();
    const runtimeDir = Storage.getRuntimeBaseDir();
    fs2.mkdirSync(qwenDir, { recursive: true });
    fs2.mkdirSync(runtimeDir, { recursive: true });
    const args2 = [
      "-D",
      `TARGET_DIR=${fs2.realpathSync(process.cwd())}`,
      "-D",
      `TMP_DIR=${fs2.realpathSync(os2.tmpdir())}`,
      "-D",
      `HOME_DIR=${fs2.realpathSync(os2.homedir())}`,
      "-D",
      `CACHE_DIR=${fs2.realpathSync(execSync(`getconf DARWIN_USER_CACHE_DIR`).toString().trim())}`,
      "-D",
      `QWEN_DIR=${fs2.realpathSync(qwenDir)}`,
      "-D",
      `RUNTIME_DIR=${fs2.realpathSync(runtimeDir)}`
    ];
    const MAX_INCLUDE_DIRS = 5;
    const targetDir = fs2.realpathSync(cliConfig?.getTargetDir() || "");
    const includedDirs = [];
    if (cliConfig) {
      const workspaceContext = cliConfig.getWorkspaceContext();
      const directories = workspaceContext.getDirectories();
      for (const dir of directories) {
        const realDir = fs2.realpathSync(dir);
        if (realDir !== targetDir) {
          includedDirs.push(realDir);
        }
      }
    }
    for (let i = 0; i < MAX_INCLUDE_DIRS; i++) {
      let dirPath = "/dev/null";
      if (i < includedDirs.length) {
        dirPath = includedDirs[i];
      }
      args2.push("-D", `INCLUDE_DIR_${i}=${dirPath}`);
    }
    const finalArgv = cliArgs;
    args2.push(
      "-f",
      profileFile,
      "sh",
      "-c",
      [
        `SANDBOX=sandbox-exec`,
        `NODE_OPTIONS="${nodeOptions}"`,
        ...finalArgv.map((arg) => (0, import_shell_quote.quote)([arg]))
      ].join(" ")
    );
    const proxyCommand2 = process.env["QWEN_SANDBOX_PROXY_COMMAND"];
    let proxyProcess2 = void 0;
    let sandboxProcess2 = void 0;
    const sandboxEnv = { ...process.env };
    if (proxyCommand2) {
      const proxy = process.env["HTTPS_PROXY"] || process.env["https_proxy"] || process.env["HTTP_PROXY"] || process.env["http_proxy"] || "http://localhost:8877";
      sandboxEnv["HTTPS_PROXY"] = proxy;
      sandboxEnv["https_proxy"] = proxy;
      sandboxEnv["HTTP_PROXY"] = proxy;
      sandboxEnv["http_proxy"] = proxy;
      const noProxy = process.env["NO_PROXY"] || process.env["no_proxy"];
      if (noProxy) {
        sandboxEnv["NO_PROXY"] = noProxy;
        sandboxEnv["no_proxy"] = noProxy;
      }
      proxyProcess2 = spawn2("bash", ["-c", proxyCommand2], {
        stdio: ["ignore", "pipe", "pipe"],
        detached: true
      });
      const stopProxy = /* @__PURE__ */ __name(() => {
        writeStderrLine("stopping proxy ...");
        if (proxyProcess2?.pid) {
          process.kill(-proxyProcess2.pid, "SIGTERM");
        }
      }, "stopProxy");
      process.on("exit", stopProxy);
      process.on("SIGINT", stopProxy);
      process.on("SIGTERM", stopProxy);
      proxyProcess2.stderr?.on("data", (data) => {
        writeStderrLine(data.toString());
      });
      proxyProcess2.on("close", (code, signal) => {
        if (sandboxProcess2?.pid) {
          process.kill(-sandboxProcess2.pid, "SIGTERM");
        }
        throw new FatalSandboxError(
          `Proxy command '${proxyCommand2}' exited with code ${code}, signal ${signal}`
        );
      });
      writeStderrLine("waiting for proxy to start ...");
      await execAsync(
        `until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`
      );
    }
    process.stdin.pause();
    sandboxProcess2 = spawn2(config.command, args2, {
      stdio: "inherit"
    });
    return new Promise((resolve2, reject) => {
      sandboxProcess2?.on("error", reject);
      sandboxProcess2?.on("close", (code) => {
        process.stdin.resume();
        resolve2(code ?? 1);
      });
    });
  }
  writeStderrLine(`hopping into sandbox (command: ${config.command}) ...`);
  const gcPath = fs2.realpathSync(process.argv[1]);
  const projectSandboxDockerfile = path4.join(
    SETTINGS_DIRECTORY_NAME,
    "sandbox.Dockerfile"
  );
  const isCustomProjectSandbox = fs2.existsSync(projectSandboxDockerfile);
  const image = config.image;
  const workdir = path4.resolve(process.cwd());
  const containerWorkdir = getContainerPath(workdir);
  if (process.env["BUILD_SANDBOX"]) {
    if (!gcPath.includes("qwen-code/packages/")) {
      throw new FatalSandboxError(
        "Cannot build sandbox using installed Qwen Code binary; run `npm link ./packages/cli` under QwenCode-cli repo to switch to linked binary."
      );
    } else {
      writeStderrLine("building sandbox ...");
      const gcRoot = gcPath.split("/packages/")[0];
      let buildArgs = "";
      const projectSandboxDockerfile2 = path4.join(
        SETTINGS_DIRECTORY_NAME,
        "sandbox.Dockerfile"
      );
      if (isCustomProjectSandbox) {
        writeStderrLine(`using ${projectSandboxDockerfile2} for sandbox`);
        buildArgs += `-f ${path4.resolve(projectSandboxDockerfile2)} -i ${image}`;
      }
      execSync(
        `cd ${gcRoot} && node scripts/build_sandbox.js -s ${buildArgs}`,
        {
          stdio: "inherit",
          env: {
            ...process.env,
            QWEN_SANDBOX: config.command
            // in case sandbox is enabled via flags (see config.ts under cli package)
          }
        }
      );
    }
  }
  if (!await ensureSandboxImageIsPresent(config.command, image)) {
    const remedy = image === LOCAL_DEV_SANDBOX_IMAGE_NAME ? "Try running `npm run build:all` or `npm run build:sandbox` under the qwen-code repo to build it locally, or check the image name and your network connection." : "Please check the image name, your network connection, or notify qwen-code-dev@service.alibaba.com if the issue persists.";
    throw new FatalSandboxError(
      `Sandbox image '${image}' is missing or could not be pulled. ${remedy}`
    );
  }
  const args = ["run", "-i", "--rm", "--init", "--workdir", containerWorkdir];
  if (process.env["SANDBOX_FLAGS"]) {
    const flags = (0, import_shell_quote.parse)(process.env["SANDBOX_FLAGS"], process.env).filter(
      (f) => typeof f === "string"
    );
    args.push(...flags);
  }
  if (process.stdin.isTTY) {
    args.push("-t");
  }
  args.push("--add-host", "host.docker.internal:host-gateway");
  args.push("--volume", `${workdir}:${containerWorkdir}`);
  const userSettingsDirOnHost = getUserSettingsDir();
  const runtimeBaseDirOnHost = Storage.getRuntimeBaseDir();
  const userSettingsDirRealPath = ensureDirectoryAndGetRealPath(
    userSettingsDirOnHost
  );
  const runtimeBaseDirRealPath = ensureDirectoryAndGetRealPath(runtimeBaseDirOnHost);
  const userSettingsDirInSandbox = getContainerPath(
    `/home/node/${SETTINGS_DIRECTORY_NAME}`
  );
  const userSettingsDirContainerPath = getContainerPath(
    userSettingsDirRealPath
  );
  const runtimeBaseDirContainerPath = getContainerPath(runtimeBaseDirRealPath);
  const runtimeCoveredByUserSettings = isSubpath(
    userSettingsDirRealPath,
    runtimeBaseDirRealPath
  );
  const userSettingsCoveredByRuntime = isSubpath(
    runtimeBaseDirRealPath,
    userSettingsDirRealPath
  );
  const runtimeSameAsUserSettings = runtimeCoveredByUserSettings && userSettingsCoveredByRuntime;
  args.push(
    "--volume",
    `${userSettingsDirRealPath}:${userSettingsDirInSandbox}`
  );
  if ((!userSettingsCoveredByRuntime || runtimeSameAsUserSettings) && userSettingsDirInSandbox !== userSettingsDirContainerPath) {
    args.push(
      "--volume",
      `${userSettingsDirRealPath}:${userSettingsDirContainerPath}`
    );
  }
  args.push("--env", `QWEN_HOME=${userSettingsDirContainerPath}`);
  if (!runtimeCoveredByUserSettings) {
    args.push(
      "--volume",
      `${runtimeBaseDirRealPath}:${runtimeBaseDirContainerPath}`
    );
  }
  if (!runtimeSameAsUserSettings) {
    args.push("--env", `QWEN_RUNTIME_DIR=${runtimeBaseDirContainerPath}`);
  }
  args.push("--volume", `${os2.tmpdir()}:${getContainerPath(os2.tmpdir())}`);
  const gcloudConfigDir = path4.join(os2.homedir(), ".config", "gcloud");
  if (fs2.existsSync(gcloudConfigDir)) {
    args.push(
      "--volume",
      `${gcloudConfigDir}:${getContainerPath(gcloudConfigDir)}:ro`
    );
  }
  if (process.env["GOOGLE_APPLICATION_CREDENTIALS"]) {
    const adcFile = process.env["GOOGLE_APPLICATION_CREDENTIALS"];
    if (fs2.existsSync(adcFile)) {
      args.push("--volume", `${adcFile}:${getContainerPath(adcFile)}:ro`);
      args.push(
        "--env",
        `GOOGLE_APPLICATION_CREDENTIALS=${getContainerPath(adcFile)}`
      );
    }
  }
  if (process.env["SANDBOX_MOUNTS"]) {
    for (let mount of process.env["SANDBOX_MOUNTS"].split(",")) {
      if (mount.trim()) {
        const { from, to, opts } = parseSandboxMountSpec(mount);
        mount = `${from}:${to}:${opts}`;
        if (!path4.isAbsolute(from)) {
          throw new FatalSandboxError(
            `Path '${from}' listed in SANDBOX_MOUNTS must be absolute`
          );
        }
        if (!fs2.existsSync(from)) {
          throw new FatalSandboxError(
            `Missing mount path '${from}' listed in SANDBOX_MOUNTS`
          );
        }
        writeStderrLine(`SANDBOX_MOUNTS: ${from} -> ${to} (${opts})`);
        args.push("--volume", mount);
      }
    }
  }
  ports().forEach((p) => args.push("--publish", `${p}:${p}`));
  if (process.env["DEBUG"]) {
    const debugPort = process.env["DEBUG_PORT"] || "9229";
    args.push(`--publish`, `${debugPort}:${debugPort}`);
  }
  const proxyCommand = process.env["QWEN_SANDBOX_PROXY_COMMAND"];
  if (proxyCommand) {
    let proxy = process.env["HTTPS_PROXY"] || process.env["https_proxy"] || process.env["HTTP_PROXY"] || process.env["http_proxy"] || "http://localhost:8877";
    proxy = proxy.replace("localhost", SANDBOX_PROXY_NAME);
    if (proxy) {
      args.push("--env", `HTTPS_PROXY=${proxy}`);
      args.push("--env", `https_proxy=${proxy}`);
      args.push("--env", `HTTP_PROXY=${proxy}`);
      args.push("--env", `http_proxy=${proxy}`);
    }
    const noProxy = process.env["NO_PROXY"] || process.env["no_proxy"];
    if (noProxy) {
      args.push("--env", `NO_PROXY=${noProxy}`);
      args.push("--env", `no_proxy=${noProxy}`);
    }
    if (proxy) {
      execSync(
        `${config.command} network inspect ${SANDBOX_NETWORK_NAME} || ${config.command} network create --internal ${SANDBOX_NETWORK_NAME}`
      );
      args.push("--network", SANDBOX_NETWORK_NAME);
      if (proxyCommand) {
        execSync(
          `${config.command} network inspect ${SANDBOX_PROXY_NAME} || ${config.command} network create ${SANDBOX_PROXY_NAME}`
        );
      }
    }
  }
  const imageName = parseSandboxImageName(image);
  const isIntegrationTest = process.env["QWEN_CODE_INTEGRATION_TEST"] === "true";
  let containerName;
  if (isIntegrationTest) {
    containerName = `qwen-code-integration-test-${randomBytes(4).toString(
      "hex"
    )}`;
    writeStderrLine(`ContainerName: ${containerName}`);
  } else {
    let index = 0;
    const containerNameCheck = execSync(
      `${config.command} ps -a --format "{{.Names}}"`
    ).toString().trim();
    while (containerNameCheck.includes(`${imageName}-${index}`)) {
      index++;
    }
    containerName = `${imageName}-${index}`;
    writeStderrLine(`ContainerName (regular): ${containerName}`);
  }
  args.push("--name", containerName, "--hostname", containerName);
  if (process.env["QWEN_CODE_TEST_VAR"]) {
    args.push(
      "--env",
      `QWEN_CODE_TEST_VAR=${process.env["QWEN_CODE_TEST_VAR"]}`
    );
  }
  for (const envVar of [
    "QWEN_DEBUG_LOG_FILE",
    "QWEN_CODE_LEGACY_MCP_BLOCKING"
  ]) {
    if (process.env[envVar]) {
      args.push("--env", `${envVar}=${process.env[envVar]}`);
    }
  }
  if (process.env["QWEN_CODE_MCP_APPROVALS_PATH"]) {
    args.push(
      "--env",
      `QWEN_CODE_MCP_APPROVALS_PATH=${getContainerPath(
        process.env["QWEN_CODE_MCP_APPROVALS_PATH"]
      )}`
    );
  }
  if (process.env["GEMINI_API_KEY"]) {
    args.push("--env", `GEMINI_API_KEY=${process.env["GEMINI_API_KEY"]}`);
  }
  if (process.env["GOOGLE_API_KEY"]) {
    args.push("--env", `GOOGLE_API_KEY=${process.env["GOOGLE_API_KEY"]}`);
  }
  if (process.env["OPENAI_API_KEY"]) {
    args.push("--env", `OPENAI_API_KEY=${process.env["OPENAI_API_KEY"]}`);
  }
  if (process.env["OPENAI_BASE_URL"]) {
    args.push("--env", `OPENAI_BASE_URL=${process.env["OPENAI_BASE_URL"]}`);
  }
  if (process.env["OPENAI_MODEL"]) {
    args.push("--env", `OPENAI_MODEL=${process.env["OPENAI_MODEL"]}`);
  }
  if (process.env["GOOGLE_GENAI_USE_VERTEXAI"]) {
    args.push(
      "--env",
      `GOOGLE_GENAI_USE_VERTEXAI=${process.env["GOOGLE_GENAI_USE_VERTEXAI"]}`
    );
  }
  if (process.env["GOOGLE_GENAI_USE_GCA"]) {
    args.push(
      "--env",
      `GOOGLE_GENAI_USE_GCA=${process.env["GOOGLE_GENAI_USE_GCA"]}`
    );
  }
  if (process.env["GOOGLE_CLOUD_PROJECT"]) {
    args.push(
      "--env",
      `GOOGLE_CLOUD_PROJECT=${process.env["GOOGLE_CLOUD_PROJECT"]}`
    );
  }
  if (process.env["GOOGLE_CLOUD_LOCATION"]) {
    args.push(
      "--env",
      `GOOGLE_CLOUD_LOCATION=${process.env["GOOGLE_CLOUD_LOCATION"]}`
    );
  }
  if (process.env["GEMINI_MODEL"]) {
    args.push("--env", `GEMINI_MODEL=${process.env["GEMINI_MODEL"]}`);
  }
  if (process.env["TERM"]) {
    args.push("--env", `TERM=${process.env["TERM"]}`);
  }
  if (process.env["COLORTERM"]) {
    args.push("--env", `COLORTERM=${process.env["COLORTERM"]}`);
  }
  for (const envVar of [
    "QWEN_CODE_IDE_SERVER_PORT",
    "QWEN_CODE_IDE_WORKSPACE_PATH",
    "TERM_PROGRAM"
  ]) {
    if (process.env[envVar]) {
      args.push("--env", `${envVar}=${process.env[envVar]}`);
    }
  }
  const virtualEnv = process.env["VIRTUAL_ENV"];
  if (virtualEnv && isContainerPathWithinWorkdir(
    getContainerPath(workdir),
    getContainerPath(virtualEnv)
  )) {
    const sandboxVenvPath = path4.resolve(
      SETTINGS_DIRECTORY_NAME,
      "sandbox.venv"
    );
    if (!fs2.existsSync(sandboxVenvPath)) {
      fs2.mkdirSync(sandboxVenvPath, { recursive: true });
    }
    args.push("--volume", `${sandboxVenvPath}:${getContainerPath(virtualEnv)}`);
    args.push("--env", `VIRTUAL_ENV=${getContainerPath(virtualEnv)}`);
  }
  if (process.env["SANDBOX_ENV"]) {
    for (let env of process.env["SANDBOX_ENV"].split(",")) {
      if (env = env.trim()) {
        if (env.includes("=")) {
          writeStderrLine(`SANDBOX_ENV: ${env}`);
          args.push("--env", env);
        } else {
          throw new FatalSandboxError(
            "SANDBOX_ENV must be a comma-separated list of key=value pairs"
          );
        }
      }
    }
  }
  const existingNodeOptions = process.env["NODE_OPTIONS"] || "";
  const allNodeOptions = [
    ...existingNodeOptions ? [existingNodeOptions] : [],
    ...nodeArgs
  ].join(" ");
  if (allNodeOptions.length > 0) {
    args.push("--env", `NODE_OPTIONS="${allNodeOptions}"`);
  }
  args.push("--env", `SANDBOX=${containerName}`);
  if (config.command === "podman") {
    const emptyAuthFilePath = path4.join(os2.tmpdir(), "empty_auth.json");
    fs2.writeFileSync(emptyAuthFilePath, "{}", "utf-8");
    args.push("--authfile", emptyAuthFilePath);
  }
  let userFlag = "";
  const finalEntrypoint = entrypoint(workdir, cliArgs);
  const useCurrentUser = await shouldUseCurrentUserInSandbox();
  if (useCurrentUser) {
    args.push("--user", "root");
    const uid = execSync("id -u").toString().trim();
    const gid = execSync("id -g").toString().trim();
    const username = "qwen";
    const homeDir = getContainerPath(os2.homedir());
    const setupUserCommands = [
      // Use -f with groupadd to avoid errors if the group already exists.
      `groupadd -f -g ${gid} ${username}`,
      // Create user only if it doesn't exist. Use -o for non-unique UID.
      `id -u ${username} &>/dev/null || useradd -o -u ${uid} -g ${gid} -d ${homeDir} -s /bin/bash ${username}`
    ].join(" && ");
    const originalCommand = finalEntrypoint[2];
    const escapedOriginalCommand = originalCommand.replace(/'/g, "'\\''");
    const suCommand = `su -p ${username} -c '${escapedOriginalCommand}'`;
    finalEntrypoint[2] = `${setupUserCommands} && ${suCommand}`;
    userFlag = `--user ${uid}:${gid}`;
    args.push("--env", `HOME=${os2.homedir()}`);
  } else if (isIntegrationTest) {
    args.push("--user", "root");
    userFlag = "--user root";
  }
  args.push(image);
  args.push(...finalEntrypoint);
  let proxyProcess = void 0;
  let sandboxProcess = void 0;
  if (proxyCommand) {
    const proxyContainerCommand = `${config.command} run --rm --init ${userFlag} --name ${SANDBOX_PROXY_NAME} --network ${SANDBOX_PROXY_NAME} -p 8877:8877 -v ${process.cwd()}:${workdir} --workdir ${workdir} ${image} ${proxyCommand}`;
    const isWindows = os2.platform() === "win32";
    const proxyShell = isWindows ? "cmd.exe" : "bash";
    const proxyShellArgs = isWindows ? ["/c", proxyContainerCommand] : ["-c", proxyContainerCommand];
    proxyProcess = spawn2(proxyShell, proxyShellArgs, {
      stdio: ["ignore", "pipe", "pipe"],
      detached: true
    });
    const stopProxy = /* @__PURE__ */ __name(() => {
      writeStderrLine("stopping proxy container ...");
      execSync(`${config.command} rm -f ${SANDBOX_PROXY_NAME}`);
    }, "stopProxy");
    process.on("exit", stopProxy);
    process.on("SIGINT", stopProxy);
    process.on("SIGTERM", stopProxy);
    proxyProcess.stderr?.on("data", (data) => {
      writeStderrLine(data.toString().trim());
    });
    proxyProcess.on("close", (code, signal) => {
      if (sandboxProcess?.pid) {
        process.kill(-sandboxProcess.pid, "SIGTERM");
      }
      throw new FatalSandboxError(
        `Proxy container command '${proxyContainerCommand}' exited with code ${code}, signal ${signal}`
      );
    });
    writeStderrLine("waiting for proxy to start ...");
    await execAsync(
      `until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`
    );
    await execAsync(
      `${config.command} network connect ${SANDBOX_NETWORK_NAME} ${SANDBOX_PROXY_NAME}`
    );
  }
  process.stdin.pause();
  sandboxProcess = spawn2(config.command, args, {
    stdio: "inherit"
  });
  return new Promise((resolve2, reject) => {
    sandboxProcess.on("error", (err) => {
      writeStderrLine(`Sandbox process error: ${err}`);
      reject(err);
    });
    sandboxProcess?.on("close", (code, signal) => {
      process.stdin.resume();
      if (code !== 0 && code !== null) {
        writeStderrLine(
          `Sandbox process exited with code: ${code}, signal: ${signal}`
        );
      }
      resolve2(code ?? 1);
    });
  });
}
__name(start_sandbox, "start_sandbox");
async function imageExists(sandbox, image) {
  return new Promise((resolve2) => {
    const args = ["images", "-q", image];
    const checkProcess = spawn2(sandbox, args);
    let stdoutData = "";
    if (checkProcess.stdout) {
      checkProcess.stdout.on("data", (data) => {
        stdoutData += data.toString();
      });
    }
    checkProcess.on("error", (err) => {
      writeStderrLine(
        `Failed to start '${sandbox}' command for image check: ${err.message}`
      );
      resolve2(false);
    });
    checkProcess.on("close", () => {
      resolve2(stdoutData.trim() !== "");
    });
  });
}
__name(imageExists, "imageExists");
async function pullImage(sandbox, image) {
  writeStderrLine(`Attempting to pull image ${image} using ${sandbox}...`);
  return new Promise((resolve2) => {
    const args = ["pull", image];
    const pullProcess = spawn2(sandbox, args, { stdio: "pipe" });
    let stderrData = "";
    const onStdoutData = /* @__PURE__ */ __name((data) => {
      writeStderrLine(data.toString().trim());
    }, "onStdoutData");
    const onStderrData = /* @__PURE__ */ __name((data) => {
      stderrData += data.toString();
      writeStderrLine(data.toString().trim());
    }, "onStderrData");
    const onError = /* @__PURE__ */ __name((err) => {
      writeStderrLine(
        `Failed to start '${sandbox} pull ${image}' command: ${err.message}`
      );
      cleanup();
      resolve2(false);
    }, "onError");
    const onClose = /* @__PURE__ */ __name((code) => {
      if (code === 0) {
        writeStderrLine(`Successfully pulled image ${image}.`);
        cleanup();
        resolve2(true);
      } else {
        writeStderrLine(
          `Failed to pull image ${image}. '${sandbox} pull ${image}' exited with code ${code}.`
        );
        if (stderrData.trim()) {
        }
        cleanup();
        resolve2(false);
      }
    }, "onClose");
    const cleanup = /* @__PURE__ */ __name(() => {
      if (pullProcess.stdout) {
        pullProcess.stdout.removeListener("data", onStdoutData);
      }
      if (pullProcess.stderr) {
        pullProcess.stderr.removeListener("data", onStderrData);
      }
      pullProcess.removeListener("error", onError);
      pullProcess.removeListener("close", onClose);
      if (pullProcess.connected) {
        pullProcess.disconnect();
      }
    }, "cleanup");
    if (pullProcess.stdout) {
      pullProcess.stdout.on("data", onStdoutData);
    }
    if (pullProcess.stderr) {
      pullProcess.stderr.on("data", onStderrData);
    }
    pullProcess.on("error", onError);
    pullProcess.on("close", onClose);
  });
}
__name(pullImage, "pullImage");
async function ensureSandboxImageIsPresent(sandbox, image) {
  writeStderrLine(`Checking for sandbox image: ${image}`);
  if (await imageExists(sandbox, image)) {
    writeStderrLine(`Sandbox image ${image} found locally.`);
    return true;
  }
  writeStderrLine(`Sandbox image ${image} not found locally.`);
  if (image === LOCAL_DEV_SANDBOX_IMAGE_NAME) {
    return false;
  }
  if (await pullImage(sandbox, image)) {
    if (await imageExists(sandbox, image)) {
      writeStderrLine(`Sandbox image ${image} is now available after pulling.`);
      return true;
    } else {
      writeStderrLine(
        `Sandbox image ${image} still not found after a pull attempt. This might indicate an issue with the image name or registry, or the pull command reported success but failed to make the image available.`
      );
      return false;
    }
  }
  writeStderrLine(
    `Failed to obtain sandbox image ${image} after check and pull attempt.`
  );
  return false;
}
__name(ensureSandboxImageIsPresent, "ensureSandboxImageIsPresent");

// packages/cli/src/utils/startupWarnings.ts
init_esbuild_shims();
import fs3 from "node:fs/promises";
import os3 from "node:os";
import { join as pathJoin } from "node:path";
var warningsFilePath = pathJoin(os3.tmpdir(), "qwen-code-warnings.txt");
async function getStartupWarnings() {
  try {
    await fs3.access(warningsFilePath);
    const warningsContent = await fs3.readFile(warningsFilePath, "utf-8");
    const warnings = warningsContent.split("\n").filter((line) => line.trim() !== "");
    try {
      await fs3.unlink(warningsFilePath);
    } catch {
      warnings.push("Warning: Could not delete temporary warnings file.");
    }
    return warnings;
  } catch (err) {
    if (err instanceof Error && "code" in err && err.code === "ENOENT") {
      return [];
    }
    return [`Error checking/reading warnings file: ${getErrorMessage(err)}`];
  }
}
__name(getStartupWarnings, "getStartupWarnings");

// packages/cli/src/utils/userStartupWarnings.ts
init_esbuild_shims();
import fs4 from "node:fs/promises";
import path5 from "node:path";
var rootDirectoryCheck = {
  id: "root-directory",
  check: /* @__PURE__ */ __name(async (options) => {
    try {
      const workspaceRealPath = await fs4.realpath(options.workspaceRoot);
      const errorMessage = "Warning: You are running Qwen Code in the root directory. Your entire folder structure will be used for context. It is strongly recommended to run in a project-specific directory.";
      if (path5.dirname(workspaceRealPath) === workspaceRealPath) {
        return errorMessage;
      }
      return null;
    } catch (_err) {
      return "Could not verify the current directory due to a file system error.";
    }
  }, "check")
};
var ripgrepAvailabilityCheck = {
  id: "ripgrep-availability",
  check: /* @__PURE__ */ __name(async (options) => {
    if (!options.useRipgrep) {
      return null;
    }
    try {
      const isAvailable = await canUseRipgrep(options.useBuiltinRipgrep);
      if (!isAvailable) {
        return "Ripgrep not available: Please install ripgrep globally to enable faster file content search. Falling back to built-in grep.";
      }
      return null;
    } catch (error) {
      return `Ripgrep not available: ${error instanceof Error ? error.message : "Unknown error"}. Falling back to built-in grep.`;
    }
  }, "check")
};
var WARNING_CHECKS = [
  rootDirectoryCheck,
  ripgrepAvailabilityCheck
];
async function getUserStartupWarnings(options) {
  const results = await Promise.all(
    WARNING_CHECKS.map((check) => check.check(options))
  );
  return results.filter((msg) => msg !== null);
}
__name(getUserStartupWarnings, "getUserStartupWarnings");

// packages/cli/src/utils/warningHandler.ts
init_esbuild_shims();
var SUPPRESSED_WARNINGS = [
  /MaxListenersExceededWarning.*AbortSignal/
];
function isSuppressed(warning) {
  const text = `${warning.name}: ${warning.message}`;
  return SUPPRESSED_WARNINGS.some((re) => re.test(text));
}
__name(isSuppressed, "isSuppressed");
function isDebugMode2() {
  if (false) return true;
  const truthy = /* @__PURE__ */ __name((v) => !!v && v !== "0" && v.toLowerCase() !== "false", "truthy");
  return truthy(process.env["DEBUG"]) || truthy(process.env["QWEN_DEBUG"]);
}
__name(isDebugMode2, "isDebugMode");
var installedHandler = null;
function initializeWarningHandler() {
  if (installedHandler) return;
  const priorListeners = [...process.listeners("warning")];
  installedHandler = /* @__PURE__ */ __name((warning) => {
    if (!isDebugMode2() && isSuppressed(warning)) return;
    for (const fn of priorListeners) {
      try {
        fn(warning);
      } catch {
      }
    }
  }, "installedHandler");
  process.removeAllListeners("warning");
  process.on("warning", installedHandler);
}
__name(initializeWarningHandler, "initializeWarningHandler");

// packages/cli/src/utils/apiPreconnect.ts
init_esbuild_shims();
var import_undici = __toESM(require_undici(), 1);
var debugLogger4 = createDebugLogger("PRECONNECT");
var preconnectFired = false;
var DEFAULT_BASE_URLS = {
  openai: "https://api.openai.com",
  "qwen-oauth": "https://coding.dashscope.aliyuncs.com",
  anthropic: "https://api.anthropic.com",
  dashscope: "https://dashscope.aliyuncs.com"
};
var ALL_DEFAULT_URLS = [
  ...Object.values(DEFAULT_BASE_URLS),
  ...getAllProviderBaseUrls()
];
function shouldSkipPreconnect() {
  if (process.env["NODE_EXTRA_CA_CERTS"]) {
    debugLogger4.debug("Skipping preconnect: custom CA certificate configured");
    return true;
  }
  return false;
}
__name(shouldSkipPreconnect, "shouldSkipPreconnect");
function isInSandboxMode() {
  return process.env["SANDBOX"] !== void 0;
}
__name(isInSandboxMode, "isInSandboxMode");
function isDefaultBaseUrl(baseUrl) {
  const normalizedInput = baseUrl.toLowerCase().replace(/^https?:\/\//, "").replace(/\/+$/, "");
  return ALL_DEFAULT_URLS.some((defaultUrl) => {
    const normalizedDefault = defaultUrl.toLowerCase().replace(/^https?:\/\//, "").replace(/\/+$/, "");
    return normalizedInput === normalizedDefault || normalizedInput.startsWith(normalizedDefault + "/");
  });
}
__name(isDefaultBaseUrl, "isDefaultBaseUrl");
function getPreconnectTargetUrl(authType, resolvedBaseUrl) {
  if (resolvedBaseUrl && /^https?:\/\//i.test(resolvedBaseUrl)) {
    if (isDefaultBaseUrl(resolvedBaseUrl)) {
      return resolvedBaseUrl;
    }
    debugLogger4.debug(
      "Skipping preconnect: resolved baseUrl is not a default URL"
    );
    return void 0;
  }
  if (authType && DEFAULT_BASE_URLS[authType]) {
    return DEFAULT_BASE_URLS[authType];
  }
  return void 0;
}
__name(getPreconnectTargetUrl, "getPreconnectTargetUrl");
function preconnectApi(authType, options = {}) {
  if (preconnectFired) {
    return;
  }
  if (process.env["QWEN_CODE_DISABLE_PRECONNECT"] === "1") {
    debugLogger4.debug("Preconnect disabled by environment variable");
    preconnectFired = true;
    return;
  }
  if (isInSandboxMode()) {
    debugLogger4.debug("Skipping preconnect: sandbox mode detected");
    preconnectFired = true;
    return;
  }
  if (shouldSkipPreconnect()) {
    preconnectFired = true;
    return;
  }
  if (detectRuntime() !== "node") {
    debugLogger4.debug("Skipping preconnect: unsupported runtime");
    preconnectFired = true;
    return;
  }
  if (!options.proxy) {
    debugLogger4.debug("Skipping preconnect dispatcher: no proxy configured");
    return;
  }
  const proxy = options.proxy;
  const targetUrl = getPreconnectTargetUrl(authType, options.resolvedBaseUrl);
  if (!targetUrl) {
    debugLogger4.debug("No target URL for preconnect");
    return;
  }
  preconnectFired = true;
  debugLogger4.debug(`Preconnecting to: ${targetUrl}`);
  try {
    const dispatcher = getOrCreateSharedDispatcher(proxy);
    (0, import_undici.fetch)(targetUrl, {
      method: "HEAD",
      signal: AbortSignal.timeout(5e3),
      headers: {
        "User-Agent": "QwenCode-Preconnect/1.0"
      },
      dispatcher
    }).then(() => {
      debugLogger4.debug("Preconnect completed");
    }).catch((error) => {
      const redactedError = redactProxyCredentials(String(error));
      debugLogger4.debug(`Preconnect failed (ignored): ${redactedError}`);
    });
  } catch (error) {
    const redactedError = redactProxyCredentials(String(error));
    debugLogger4.debug(`Preconnect failed (ignored): ${redactedError}`);
  }
}
__name(preconnectApi, "preconnectApi");

// packages/cli/src/gemini.tsx
var debugLogger5 = createDebugLogger("STARTUP");
function clearCorruptionEnvVars() {
  delete process.env[ENV_CORRUPTED_PATH];
  delete process.env[ENV_WAS_RECOVERED];
}
__name(clearCorruptionEnvVars, "clearCorruptionEnvVars");
function validateDnsResolutionOrder(order) {
  const defaultValue = "ipv4first";
  if (order === void 0) {
    return defaultValue;
  }
  if (order === "ipv4first" || order === "verbatim") {
    return order;
  }
  writeStderrLine(
    `Invalid value for dnsResolutionOrder in settings: "${order}". Using default "${defaultValue}".`
  );
  return defaultValue;
}
__name(validateDnsResolutionOrder, "validateDnsResolutionOrder");
function getNodeMemoryArgs(isDebugMode3) {
  const totalMemoryMB = os4.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 (isDebugMode3) {
    writeStderrLine(
      `Current heap size ${currentMaxOldSpaceSizeMb.toFixed(2)} MB`
    );
  }
  if (process.env["QWEN_CODE_NO_RELAUNCH"]) {
    return [];
  }
  if (targetMaxOldSpaceSizeInMB > currentMaxOldSpaceSizeMb) {
    if (isDebugMode3) {
      writeStderrLine(
        `Need to relaunch with more memory: ${targetMaxOldSpaceSizeInMB.toFixed(2)} MB`
      );
    }
    return [`--max-old-space-size=${targetMaxOldSpaceSizeInMB}`];
  }
  return [];
}
__name(getNodeMemoryArgs, "getNodeMemoryArgs");
function setupUnhandledRejectionHandler() {
  let unhandledRejectionOccurred = false;
  process.on("unhandledRejection", (reason, _promise) => {
    const errorMessage = `=========================================
This is an unexpected error. Please file a bug report using the /bug tool.
CRITICAL: Unhandled Promise Rejection!
=========================================
Reason: ${reason}${reason instanceof Error && reason.stack ? `
Stack trace:
${reason.stack}` : ""}`;
    appEvents.emit("log-error" /* LogError */, errorMessage);
    if (!unhandledRejectionOccurred) {
      unhandledRejectionOccurred = true;
      appEvents.emit("open-debug-console" /* OpenDebugConsole */);
    }
  });
}
__name(setupUnhandledRejectionHandler, "setupUnhandledRejectionHandler");
function getSignalExitCode(signal) {
  return signal === "SIGINT" ? 130 : 143;
}
__name(getSignalExitCode, "getSignalExitCode");
function installInteractiveSignalHandlers(wasRaw) {
  let cleanupStarted = false;
  const handleSignal = /* @__PURE__ */ __name((signal) => {
    if (process.stdin.isTTY) {
      process.stdin.setRawMode(wasRaw);
    }
    if (cleanupStarted) {
      return;
    }
    cleanupStarted = true;
    void runExitCleanup().catch((error) => {
      debugLogger5.error(`Error during ${signal} cleanup:`, error);
    }).finally(() => {
      process.exit(getSignalExitCode(signal));
    });
  }, "handleSignal");
  const handleSigterm = /* @__PURE__ */ __name(() => {
    handleSignal("SIGTERM");
  }, "handleSigterm");
  const handleSigint = /* @__PURE__ */ __name(() => {
    handleSignal("SIGINT");
  }, "handleSigint");
  process.once("SIGTERM", handleSigterm);
  process.once("SIGINT", handleSigint);
  return () => {
    process.removeListener("SIGTERM", handleSigterm);
    process.removeListener("SIGINT", handleSigint);
  };
}
__name(installInteractiveSignalHandlers, "installInteractiveSignalHandlers");
async function main() {
  profileCheckpoint("main_entry");
  if (isStartupProfilerEnabled()) {
    setStartupEventSink((name, attrs) => recordStartupEvent(name, attrs));
  }
  setupUnhandledRejectionHandler();
  initializeWarningHandler();
  if (process.argv.includes("--bare")) {
    process.env[QWEN_CODE_SIMPLE_ENV_VAR] = "1";
  }
  preResolveHomeEnvOverrides();
  let argv = await parseArguments();
  profileCheckpoint("after_parse_arguments");
  if (isBareMode(argv.bare)) {
    process.env[QWEN_CODE_SIMPLE_ENV_VAR] = "1";
  }
  const settings = isBareMode(argv.bare) ? createMinimalSettings() : loadSettings();
  if (settings.corruptedPath) {
    process.env[ENV_CORRUPTED_PATH] = settings.corruptedPath;
    process.env[ENV_WAS_RECOVERED] = settings.wasRecovered ? "1" : "0";
  }
  await cleanupCheckpoints();
  profileCheckpoint("after_load_settings");
  const settingsWarnings = getSettingsWarnings(settings);
  for (const warning of settingsWarnings) {
    writeStderrLine(warning);
  }
  if (settings.corruptedPath) {
    writeStderrLine(
      "Warning: Settings file had invalid JSON and was reset. A copy of the corrupted file has been saved at: " + settings.corruptedPath
    );
  }
  if (argv.listExtensions) {
    await initializeI18n(
      resolveLanguageSetting(settings.merged.general?.language)
    );
    const { handleList: handleListExtensions } = await import("./list-OKR26DTS.js");
    await handleListExtensions();
    process.exit(0);
  }
  if (argv.promptInteractive && !process.stdin.isTTY) {
    writeStderrLine(
      "Error: The --prompt-interactive flag cannot be used when input is piped from stdin."
    );
    process.exit(1);
  }
  const isDebugMode3 = isDebugMode(argv);
  dns.setDefaultResultOrder(
    validateDnsResolutionOrder(settings.merged.advanced?.dnsResolutionOrder)
  );
  const { themeManager, AUTO_THEME_NAME } = await import("./theme-manager-ALOCHHSJ.js");
  themeManager.loadCustomThemes(settings.merged.ui?.customThemes);
  const configuredTheme = settings.merged.ui?.theme;
  if (configuredTheme && configuredTheme !== AUTO_THEME_NAME) {
    if (!themeManager.setActiveTheme(configuredTheme)) {
      writeStderrLine(`Warning: Theme "${configuredTheme}" not found.`);
    }
  } else {
    themeManager.setActiveTheme(AUTO_THEME_NAME);
  }
  if (!process.env["SANDBOX"]) {
    const memoryArgs = settings.merged.advanced?.autoConfigureMemory ? getNodeMemoryArgs(isDebugMode3) : [];
    const sandboxConfig = await loadSandboxConfig(settings.merged, argv);
    if (sandboxConfig) {
      const partialConfig = await loadCliConfig(
        settings.merged,
        argv,
        void 0,
        [],
        // Pass separated hooks for proper source attribution
        {
          userHooks: settings.getUserHooks(),
          projectHooks: settings.getProjectHooks()
        },
        buildDisabledSkillNamesProvider(settings)
      );
      if (!settings.merged.security?.auth?.useExternal) {
        try {
          const authType = partialConfig.getModelsConfig().getCurrentAuthType();
          if (authType) {
            const err = validateAuthMethod(authType, partialConfig);
            if (err) {
              throw new Error(err);
            }
            await partialConfig.refreshAuth(authType);
          }
        } catch (err) {
          writeStderrLine(`Error authenticating: ${err}`);
          process.exit(1);
        }
      }
      const inputFormat = argv.inputFormat;
      const isAcpMode = argv.acp || argv.experimentalAcp;
      let stdinData = "";
      if (!process.stdin.isTTY && inputFormat !== "stream-json" && !isAcpMode) {
        stdinData = await readStdin();
      }
      const injectStdinIntoArgs = /* @__PURE__ */ __name((args, stdinData2) => {
        const finalArgs = [...args];
        if (stdinData2) {
          const promptIndex = finalArgs.findIndex(
            (arg) => arg === "--prompt" || arg === "-p"
          );
          if (promptIndex > -1 && finalArgs.length > promptIndex + 1) {
            finalArgs[promptIndex + 1] = `${stdinData2}

${finalArgs[promptIndex + 1]}`;
          } else {
            finalArgs.push("--prompt", stdinData2);
          }
        }
        return finalArgs;
      }, "injectStdinIntoArgs");
      const injectSandboxSessionIdIntoArgs = /* @__PURE__ */ __name((args, sessionId2) => {
        const separatorIndex = args.indexOf("--");
        const cliArgs = separatorIndex < 0 ? args : args.slice(0, separatorIndex);
        const hasArg = /* @__PURE__ */ __name((names) => cliArgs.some(
          (arg) => names.some((name) => arg === name || arg.startsWith(`${name}=`))
        ), "hasArg");
        if (hasArg(["--session-id", "--sandbox-session-id"]) || hasArg(["--continue", "-c"]) || hasArg(["--resume", "-r"])) {
          return args;
        }
        const sessionArgs = ["--sandbox-session-id", sessionId2];
        if (separatorIndex < 0) {
          return [...args, ...sessionArgs];
        }
        return [...cliArgs, ...sessionArgs, ...args.slice(separatorIndex)];
      }, "injectSandboxSessionIdIntoArgs");
      const sessionId = partialConfig.getSessionId();
      const sandboxArgs = sessionId ? injectSandboxSessionIdIntoArgs(
        injectStdinIntoArgs(process.argv, stdinData),
        sessionId
      ) : injectStdinIntoArgs(process.argv, stdinData);
      await relaunchOnExitCode(
        () => start_sandbox(sandboxConfig, memoryArgs, partialConfig, sandboxArgs)
      );
      process.exit(0);
    } else {
      await relaunchAppInChildProcess(memoryArgs, [], {
        afterSpawn: clearCorruptionEnvVars
      });
    }
  }
  if (argv.worktree !== void 0) {
    const launchCwdForPaths = process.cwd();
    const looksLikeInlineJson = /* @__PURE__ */ __name((v) => {
      const t = v.trim();
      return t.startsWith("{") || t.startsWith("[");
    }, "looksLikeInlineJson");
    const resolveIfPath = /* @__PURE__ */ __name((v) => {
      if (typeof v !== "string" || v.length === 0) return v;
      if (looksLikeInlineJson(v)) return v;
      return path6.resolve(launchCwdForPaths, v);
    }, "resolveIfPath");
    argv.mcpConfig = resolveIfPath(argv.mcpConfig);
    argv.openaiLoggingDir = resolveIfPath(argv.openaiLoggingDir);
    argv.jsonFile = resolveIfPath(argv.jsonFile);
    argv.inputFile = resolveIfPath(argv.inputFile);
    argv.telemetryOutfile = resolveIfPath(argv.telemetryOutfile);
    if (Array.isArray(argv.includeDirectories)) {
      argv.includeDirectories = argv.includeDirectories.map(
        (d) => typeof d === "string" && d.length > 0 ? path6.resolve(launchCwdForPaths, d) : d
      );
    }
    if (typeof argv.jsonSchema === "string") {
      const trimmedSchema = argv.jsonSchema.trim();
      if (trimmedSchema.startsWith("@")) {
        const rel = trimmedSchema.slice(1);
        if (rel.length > 0 && !path6.isAbsolute(rel)) {
          argv.jsonSchema = "@" + path6.resolve(launchCwdForPaths, rel);
        }
      }
    }
  }
  let startupWorktreeContext = null;
  if (argv.worktree !== void 0 && (argv.acp || argv.experimentalAcp)) {
    writeStderrLine(
      "--worktree cannot be combined with --acp / --experimental-acp. Pass the worktree path as the cwd of the ACP loadSession / newSession request instead."
    );
    process.exit(1);
  }
  {
    const startupRes = await setupStartupWorktree(argv.worktree, {
      symlinkDirectories: settings.merged.worktree?.symlinkDirectories
    });
    if (startupRes !== null) {
      if (!startupRes.ok) {
        writeStderrLine(startupRes.error);
        process.exit(1);
      }
      startupWorktreeContext = startupRes.context;
    }
  }
  if (argv.resume !== void 0) {
    Storage.setRuntimeBaseDir(
      settings.merged.advanced?.runtimeOutputDir,
      process.cwd()
    );
    let resolvedSessionId;
    if (argv.resume === "") {
      const { showResumeSessionPicker } = await import("./StandaloneSessionPicker-2GJLRRLL.js");
      resolvedSessionId = await showResumeSessionPicker();
    } else if (!isValidSessionId(argv.resume)) {
      const sessionService = new SessionService(process.cwd());
      const matches = await sessionService.findSessionsByTitle(argv.resume);
      if (matches.length === 1) {
        resolvedSessionId = matches[0].sessionId;
      } else if (matches.length > 1) {
        writeStderrLine(
          `Multiple sessions found with title "${argv.resume}". Please select one:`
        );
        const { showResumeSessionPicker } = await import("./StandaloneSessionPicker-2GJLRRLL.js");
        resolvedSessionId = await showResumeSessionPicker(
          process.cwd(),
          matches
        );
      }
    }
    if (resolvedSessionId !== void 0) {
      argv = { ...argv, resume: resolvedSessionId };
    } else if (argv.resume === "" || !isValidSessionId(argv.resume)) {
      if (argv.resume !== "") {
        writeStderrLine(`No saved session found with title "${argv.resume}".`);
        process.exit(1);
      } else {
        process.exit(0);
      }
    }
  }
  profileCheckpoint("after_sandbox_check");
  if (!isBareMode(argv.bare)) {
    initializeLlmOutputLanguage(settings.merged.general?.outputLanguage);
  }
  {
    const settingsWatcher = isBareMode(argv.bare) ? void 0 : new SettingsWatcher(settings);
    settingsWatcher?.startWatching();
    const config = await loadCliConfig(
      settings.merged,
      argv,
      process.cwd(),
      argv.extensions,
      // Pass separated hooks for proper source attribution
      {
        userHooks: settings.getUserHooks(),
        projectHooks: settings.getProjectHooks()
      },
      buildDisabledSkillNamesProvider(settings),
      void 0,
      settingsWatcher
    );
    profileCheckpoint("after_load_cli_config");
    if (settingsWatcher) {
      const disposeMcpHotReload = registerMcpHotReload(
        settingsWatcher,
        settings,
        config,
        config.getTopTierMcpServers()
      );
      registerCleanup(disposeMcpHotReload);
    }
    if (startupWorktreeContext) {
      config.setPendingStartupWorktreeNotice(
        buildStartupWorktreeNotice(startupWorktreeContext)
      );
      try {
        const startupWorktreePersist = await persistStartupWorktreeSidecar(
          config,
          startupWorktreeContext
        );
        if (startupWorktreePersist.overrodeResumedWorktree) {
          writeStderrLine(
            `--worktree overrode the resumed session's previous worktree "${startupWorktreePersist.overriddenSlug ?? "(unknown)"}". That worktree directory was left intact on disk.`
          );
        }
        config.setPendingStartupWorktreeNotice(
          buildStartupWorktreeNotice(
            startupWorktreeContext,
            startupWorktreePersist
          )
        );
      } catch (error) {
        debugLogger5.warn(
          `--worktree sidecar persist failed (non-fatal, notice preserved): ${error instanceof Error ? error.message : String(error)}`
        );
      }
    }
    registerCleanup(() => {
      try {
        const metrics = uiTelemetryService.getMetrics();
        const hasActivity = Object.values(metrics.models).some(
          (m) => m.api.totalRequests > 0
        );
        if (!hasActivity) return;
        persistSessionUsage({
          sessionId: config.getSessionId(),
          startTime: uiTelemetryService.getSessionStartTime(),
          endTime: /* @__PURE__ */ new Date(),
          project: config.getProjectRoot(),
          metrics
        });
      } catch {
      }
    });
    registerCleanup(() => config.shutdown());
    try {
      const modelsConfig = config.getModelsConfig();
      const authType = modelsConfig.getCurrentAuthType();
      const resolvedBaseUrl = modelsConfig.getGenerationConfig().baseUrl;
      const proxy = config.getProxy();
      preconnectApi(authType, { resolvedBaseUrl, proxy });
    } catch (error) {
      debugLogger5.debug(
        `Preconnect skipped due to error getting authType: ${error}`
      );
    }
    const wasRaw = process.stdin.isRaw;
    let kittyProtocolDetectionComplete;
    let themeAutoDetectionComplete;
    if (config.isInteractive()) {
      registerCleanup(installInteractiveSignalHandlers(wasRaw));
    }
    if (config.isInteractive() && !wasRaw && process.stdin.isTTY) {
      const { startEarlyInputCapture, stopAndGetCapturedInput } = await import("./earlyInputCapture-Q36IYAUG.js");
      const { detectAndEnableKittyProtocol } = await import("./kittyProtocolDetector-OJRCJLIU.js");
      process.stdin.setRawMode(true);
      startEarlyInputCapture();
      registerCleanup(() => stopAndGetCapturedInput());
      kittyProtocolDetectionComplete = detectAndEnableKittyProtocol();
      if (!configuredTheme || configuredTheme === AUTO_THEME_NAME) {
        themeAutoDetectionComplete = themeManager.resolveAutoThemeAsync().catch((err) => {
          debugLogger5.warn("Async theme auto-detection failed:", err);
        });
      }
    }
    if (config.isInteractive()) {
      const { setMaxSizedBoxDebugging } = await import("./MaxSizedBox-EQQJIZVN.js");
      setMaxSizedBoxDebugging(isDebugMode3);
    }
    const inputFormat = process.stdin.isTTY ? "text" /* TEXT */ : typeof config.getInputFormat === "function" ? config.getInputFormat() : "text" /* TEXT */;
    const { initializeApp } = await import("./initializer-YOHM3QY3.js");
    const initializationResult = await initializeApp(config, settings);
    profileCheckpoint("after_initialize_app");
    if (config.getExperimentalZedIntegration()) {
      const { runAcpAgent } = await import("./acpAgent-Q66LATKG.js");
      await runAcpAgent(config, settings, argv);
      await runExitCleanup();
      process.exit(0);
    }
    if (config.isInteractive()) {
      void import("./scheduler-MYBMUXBM.js").then((m) => m.startBackgroundHousekeeping(config, settings)).catch((err) => {
        debugLogger5.warn("failed to start background housekeeping:", err);
      });
    }
    let input = config.getQuestion();
    const startupWarnings = [
      .../* @__PURE__ */ new Set([
        ...config.isSafeMode() ? [
          "\u26A0 SAFE MODE \u2014 all customizations disabled (hooks, extensions, skills, MCP servers, QWEN.md). Restart without --safe-mode to resume normal operation."
        ] : [],
        ...await getStartupWarnings(),
        ...await getUserStartupWarnings({
          workspaceRoot: process.cwd(),
          useRipgrep: settings.merged.tools?.useRipgrep ?? true,
          useBuiltinRipgrep: settings.merged.tools?.useBuiltinRipgrep ?? true
        }),
        ...getSettingsWarnings(settings),
        ...config.getWarnings(),
        ...config.getModelsConfig().getCurrentAuthType() === "qwen-oauth" /* QWEN_OAUTH */ ? [
          "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan or another provider."
        ] : []
      ])
    ];
    const emittedStartupWarnings = new Set(startupWarnings);
    for (const warning of startupWarnings) {
      writeStderrLine(warning);
    }
    profileCheckpoint("before_render");
    if (config.isInteractive()) {
      if (config.getJsonSchema?.()) {
        writeStderrLine(
          "Error: --json-schema is a headless-only flag. Provide a one-shot prompt via -p / --prompt or pipe one in via stdin."
        );
        await runExitCleanup();
        process.exit(1);
      }
      setInteractiveMode(true);
      await kittyProtocolDetectionComplete;
      await themeAutoDetectionComplete;
      const { startInteractiveUI } = await import("./startInteractiveUI-45QJ5NBD.js");
      await startInteractiveUI(
        config,
        settings,
        startupWarnings,
        process.cwd(),
        initializationResult
      );
      clearCorruptionEnvVars();
      return;
    }
    clearCorruptionEnvVars();
    if (config.getDebugMode()) {
      writeStderrLine("Debug mode enabled");
      writeStderrLine(
        `Logging to: ${Storage.getDebugLogPath(config.getSessionId())}`
      );
      if (isDebugLoggingDegraded()) {
        writeStderrLine(
          "Warning: Debug logging is degraded (write failures occurred)"
        );
      }
    }
    if (!config.isInteractive()) {
      const yoloWarning = getHeadlessYoloSafetyWarning(config);
      if (yoloWarning) writeStderrLine(yoloWarning);
    }
    if (inputFormat !== "stream-json" /* STREAM_JSON */) {
      profileCheckpoint("config_initialize_start");
      await config.initialize();
      for (const warning of config.getWarnings()) {
        if (emittedStartupWarnings.has(warning)) continue;
        emittedStartupWarnings.add(warning);
        writeStderrLine(warning);
      }
      profileCheckpoint("config_initialize_end");
      await config.waitForMcpReady();
      const failedMcpServers = typeof config.getFailedMcpServerNames === "function" ? config.getFailedMcpServerNames() : [];
      if (failedMcpServers.length > 0) {
        writeStderrLine(
          `Warning: MCP server(s) failed to start: ${failedMcpServers.join(", ")}. Continuing with built-in tools and any servers that did connect. Re-run with QWEN_CODE_DEBUG=1 to see per-server reasons.`
        );
      }
      finalizeStartupProfile(config.getSessionId());
    }
    if (inputFormat !== "stream-json" /* STREAM_JSON */ && !process.stdin.isTTY) {
      const stdinData = await readStdin();
      if (stdinData) {
        input = `${stdinData}

${input}`;
      }
    }
    const { validateNonInteractiveAuth } = await import("./validateNonInterActiveAuth-DLNZL36W.js");
    const nonInteractiveConfig = await validateNonInteractiveAuth(
      settings.merged.security?.auth?.useExternal,
      config,
      settings
    );
    const prompt_id = createNonInteractivePromptId(config.getSessionId());
    if (inputFormat === "stream-json" /* STREAM_JSON */) {
      const trimmedInput = (input ?? "").trim();
      const { runNonInteractiveStreamJson } = await import("./session-3BV2MBO3.js");
      await runNonInteractiveStreamJson(
        nonInteractiveConfig,
        trimmedInput.length > 0 ? trimmedInput : "",
        settings
      );
      await runExitCleanup();
      process.exit(process.exitCode ?? 0);
    }
    if (!input) {
      writeStderrLine(
        `No input provided via stdin. Input can be provided by piping data into gemini or using the --prompt option.`
      );
      process.exit(1);
    }
    logUserPrompt(config, {
      "event.name": "user_prompt",
      "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
      prompt: input,
      prompt_id,
      auth_type: config.getContentGeneratorConfig()?.authType,
      prompt_length: input.length
    });
    debugLogger5.debug(`Session ID: ${config.getSessionId()}`);
    const { runNonInteractive } = await import("./nonInteractiveCli-KQFC4FGM.js");
    const exitCode = await runNonInteractive(
      nonInteractiveConfig,
      settings,
      input,
      prompt_id
    );
    await runExitCleanup();
    process.exit(exitCode);
  }
}
__name(main, "main");
function createNonInteractivePromptId(sessionId) {
  return `${sessionId}########0`;
}
__name(createNonInteractivePromptId, "createNonInteractivePromptId");
export {
  createNonInteractivePromptId,
  main,
  setupUnhandledRejectionHandler,
  validateDnsResolutionOrder
};
/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2026 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
