// @bun
import {
  initSinks
} from "./chunk-amt6g0x8.js";
import {
  initSessionMemory,
  init_sessionMemory
} from "./chunk-cbr01gk0.js";
import {
  getRecentActivity,
  init_logoV2Utils
} from "./chunk-ss69vqh4.js";
import {
  checkForReleaseNotes,
  init_releaseNotes
} from "./chunk-6m71v75w.js";
import {
  initSkillLearning,
  init_runtimeObserver
} from "./chunk-0emnkdsb.js";
import"./chunk-1j8b3rk6.js";
import"./chunk-gv49ez1v.js";
import"./chunk-ewat8vhn.js";
import"./chunk-w9ddp3yf.js";
import"./chunk-v3ey5j7f.js";
import"./chunk-cjjfcsym.js";
import {
  asSessionId,
  captureHooksConfigSnapshot,
  clearMemoryFileCaches,
  createTmuxSessionForWorktree,
  createWorktreeForSession,
  generateTmuxSessionName,
  getCommands,
  getPlanSlug,
  hasWorktreeCreateHook,
  init_Shell,
  init_claudemd,
  init_commands1 as init_commands,
  init_fileChangedWatcher,
  init_hooks1 as init_hooks,
  init_hooksConfigSnapshot,
  init_ids,
  init_nativeInstaller,
  init_plans,
  init_sessionStorage,
  init_worktree,
  initializeFileChangedWatcher,
  lockCurrentVersion,
  saveWorktreeState,
  setCwd,
  updateHooksConfigSnapshot,
  worktreeBranchName
} from "./chunk-cnjb8b86.js";
import"./chunk-k60b56gr.js";
import"./chunk-14p6wvsq.js";
import"./chunk-g4yawavx.js";
import"./chunk-28jd8qjx.js";
import"./chunk-djt39ze3.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-ptxteaeh.js";
import"./chunk-jvzheknj.js";
import"./chunk-6xgts8yv.js";
import"./chunk-cq5x2ww9.js";
import"./chunk-z4ata4ab.js";
import"./chunk-3gv0thgq.js";
import"./chunk-vk8zvq17.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-qn6me9n1.js";
import"./chunk-m13584y2.js";
import"./chunk-zd4jrzbr.js";
import"./chunk-71sdcaq6.js";
import"./chunk-mmtwa757.js";
import"./chunk-tj8te4np.js";
import"./chunk-mshbqz1a.js";
import"./chunk-dr2x4ze7.js";
import"./chunk-8ad8jmrf.js";
import"./chunk-24kv69g3.js";
import"./chunk-bfy3xx3x.js";
import {
  checkAndRestoreTerminalBackup,
  init_appleTerminalBackup
} from "./chunk-2eb4hvmp.js";
import"./chunk-4gyjc4jm.js";
import"./chunk-4spgkgr3.js";
import"./chunk-e8dhxycp.js";
import"./chunk-hf0jvnz1.js";
import"./chunk-9pygs2bc.js";
import"./chunk-60fkafk2.js";
import"./chunk-gaazk5m4.js";
import"./chunk-5p22q3zt.js";
import"./chunk-093ej2sf.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-nde5ym6a.js";
import"./chunk-rqg87cdf.js";
import"./chunk-p16xrfdy.js";
import"./chunk-hkxtwqh5.js";
import"./chunk-8v909swg.js";
import"./chunk-hxjpqg2s.js";
import"./chunk-4nctdw69.js";
import"./chunk-vhghhw4q.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-40rkf49m.js";
import"./chunk-hqxp6b72.js";
import"./chunk-vpdngjbx.js";
import"./chunk-c9mjtja4.js";
import"./chunk-w5hnghah.js";
import"./chunk-egpny0k9.js";
import"./chunk-x59e8cv0.js";
import"./chunk-s76nvx50.js";
import"./chunk-7jyr5758.js";
import {
  envDynamic,
  getCurrentProjectConfig,
  getGlobalConfig,
  init_agentSwarmsEnabled,
  init_auth,
  init_config1 as init_config,
  init_envDynamic,
  isAgentSwarmsEnabled,
  prefetchApiKeyFromApiKeyHelperIfSafe,
  saveGlobalConfig
} from "./chunk-ym4hbqxs.js";
import"./chunk-nkg1b3qw.js";
import"./chunk-c1kx8bry.js";
import"./chunk-epvbnq43.js";
import"./chunk-swgt1px0.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-swz6krys.js";
import"./chunk-7eywm3ed.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import"./chunk-25w7rxtr.js";
import"./chunk-5xfj4jkd.js";
import"./chunk-c1t99xmt.js";
import"./chunk-vwenx8ke.js";
import {
  env,
  init_env
} from "./chunk-8thwr7p8.js";
import"./chunk-v4ypszbb.js";
import"./chunk-bk6ck5c2.js";
import"./chunk-ym6j0wv1.js";
import"./chunk-hjmatcgt.js";
import"./chunk-6mdh70q0.js";
import"./chunk-ch92ycde.js";
import"./chunk-e4dsy4g1.js";
import"./chunk-326zehp8.js";
import"./chunk-kc67kt75.js";
import"./chunk-40t1d75v.js";
import"./chunk-rt34thxn.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import {
  init_startupProfiler,
  profileCheckpoint
} from "./chunk-kgkdmr0x.js";
import"./chunk-hn4w9pkj.js";
import {
  init_source,
  source_default
} from "./chunk-cswpvb8x.js";
import"./chunk-gxyx8b8w.js";
import {
  init_analytics,
  logEvent
} from "./chunk-j1mep9ck.js";
import"./chunk-6x35ffpx.js";
import"./chunk-1zbwhcbt.js";
import"./chunk-ddaxg4xh.js";
import {
  findCanonicalGitRoot,
  findGitRoot,
  getIsGit,
  init_diagLogs,
  init_git,
  logForDiagnosticsNoPII
} from "./chunk-vvh31np8.js";
import"./chunk-tywrrc1m.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-4p0hxk2c.js";
import {
  getCwd,
  init_cwd
} from "./chunk-c4dyxsat.js";
import {
  init_log,
  logError
} from "./chunk-34rn09za.js";
import"./chunk-m28vg9w4.js";
import"./chunk-rk9fgqmg.js";
import"./chunk-nw4zt0y4.js";
import"./chunk-c1yc761e.js";
import"./chunk-c5g9shkw.js";
import {
  errorMessage,
  init_errors
} from "./chunk-k9jzhhww.js";
import"./chunk-kb3758f7.js";
import {
  getIsNonInteractiveSession,
  getProjectRoot,
  getSessionId,
  init_state,
  setOriginalCwd,
  setProjectRoot,
  switchSession
} from "./chunk-xqs9r7pg.js";
import"./chunk-tj0dzck2.js";
import"./chunk-aeysytks.js";
import"./chunk-ns1htxgd.js";
import"./chunk-ztqzmfx1.js";
import {
  init_envUtils,
  isBareMode,
  isEnvTruthy
} from "./chunk-6k1rsk85.js";
import"./chunk-nxzx0ey9.js";
import"./chunk-yes1my80.js";
import"./chunk-pecy49yr.js";
import"./chunk-azbab59e.js";
import"./chunk-3nk9q8dr.js";
import {
  __require
} from "./chunk-hhsxm2yr.js";

// src/setup.ts
init_source();
init_analytics();
init_cwd();
init_releaseNotes();
init_Shell();
init_state();
init_commands();
init_sessionMemory();
init_runtimeObserver();
init_ids();
init_agentSwarmsEnabled();
init_appleTerminalBackup();
init_auth();
init_claudemd();
init_config();
init_diagLogs();
init_env();
init_envDynamic();
init_envUtils();
init_errors();
init_git();
init_fileChangedWatcher();
init_hooksConfigSnapshot();
init_hooks();

// src/utils/iTermBackup.ts
init_config();
init_log();
import { copyFile, stat } from "fs/promises";
import { homedir } from "os";
import { join } from "path";
function markITerm2SetupComplete() {
  saveGlobalConfig((current) => ({
    ...current,
    iterm2SetupInProgress: false
  }));
}
function getIterm2RecoveryInfo() {
  const config = getGlobalConfig();
  return {
    inProgress: config.iterm2SetupInProgress ?? false,
    backupPath: config.iterm2BackupPath || null
  };
}
function getITerm2PlistPath() {
  return join(homedir(), "Library", "Preferences", "com.googlecode.iterm2.plist");
}
async function checkAndRestoreITerm2Backup() {
  const { inProgress, backupPath } = getIterm2RecoveryInfo();
  if (!inProgress) {
    return { status: "no_backup" };
  }
  if (!backupPath) {
    markITerm2SetupComplete();
    return { status: "no_backup" };
  }
  try {
    await stat(backupPath);
  } catch {
    markITerm2SetupComplete();
    return { status: "no_backup" };
  }
  try {
    await copyFile(backupPath, getITerm2PlistPath());
    markITerm2SetupComplete();
    return { status: "restored" };
  } catch (restoreError) {
    logError(new Error(`Failed to restore iTerm2 settings with: ${restoreError}`));
    markITerm2SetupComplete();
    return { status: "failed", backupPath };
  }
}

// src/setup.ts
init_log();
init_logoV2Utils();
init_nativeInstaller();
init_plans();
init_sessionStorage();
init_startupProfiler();
init_worktree();
async function setup(cwd, permissionMode, allowDangerouslySkipPermissions, worktreeEnabled, worktreeName, tmuxEnabled, customSessionId, worktreePRNumber, messagingSocketPath) {
  logForDiagnosticsNoPII("info", "setup_started");
  const nodeVersion = process.version.match(/^v(\d+)\./)?.[1];
  if (!nodeVersion || parseInt(nodeVersion, 10) < 18) {
    console.error(source_default.bold.red("Error: Claude Code requires Node.js version 18 or higher."));
    process.exit(1);
  }
  if (customSessionId) {
    switchSession(asSessionId(customSessionId));
  }
  if (!isBareMode() || messagingSocketPath !== undefined) {
    if (false) {}
  }
  if (!isBareMode() && isAgentSwarmsEnabled()) {
    const { captureTeammateModeSnapshot } = await import("./chunk-hvgvrkp0.js");
    captureTeammateModeSnapshot();
  }
  if (!getIsNonInteractiveSession()) {
    if (isAgentSwarmsEnabled()) {
      const restoredIterm2Backup = await checkAndRestoreITerm2Backup();
      if (restoredIterm2Backup.status === "restored") {
        console.log(source_default.yellow("Detected an interrupted iTerm2 setup. Your original settings have been restored. You may need to restart iTerm2 for the changes to take effect."));
      } else if (restoredIterm2Backup.status === "failed") {
        console.error(source_default.red(`Failed to restore iTerm2 settings. Please manually restore your original settings with: defaults import com.googlecode.iterm2 ${restoredIterm2Backup.backupPath}.`));
      }
    }
    try {
      const restoredTerminalBackup = await checkAndRestoreTerminalBackup();
      if (restoredTerminalBackup.status === "restored") {
        console.log(source_default.yellow("Detected an interrupted Terminal.app setup. Your original settings have been restored. You may need to restart Terminal.app for the changes to take effect."));
      } else if (restoredTerminalBackup.status === "failed") {
        console.error(source_default.red(`Failed to restore Terminal.app settings. Please manually restore your original settings with: defaults import com.apple.Terminal ${restoredTerminalBackup.backupPath}.`));
      }
    } catch (error) {
      logError(error);
    }
  }
  setCwd(cwd);
  const hooksStart = Date.now();
  captureHooksConfigSnapshot();
  logForDiagnosticsNoPII("info", "setup_hooks_captured", {
    duration_ms: Date.now() - hooksStart
  });
  initializeFileChangedWatcher(cwd);
  if (worktreeEnabled) {
    const hasHook = hasWorktreeCreateHook();
    const inGit = await getIsGit();
    if (!hasHook && !inGit) {
      process.stderr.write(source_default.red(`Error: Can only use --worktree in a git repository, but ${source_default.bold(cwd)} is not a git repository. Configure a WorktreeCreate hook in settings.json to use --worktree with other VCS systems.
`));
      process.exit(1);
    }
    const slug = worktreePRNumber ? `pr-${worktreePRNumber}` : worktreeName ?? getPlanSlug();
    let tmuxSessionName;
    if (inGit) {
      const mainRepoRoot = findCanonicalGitRoot(getCwd());
      if (!mainRepoRoot) {
        process.stderr.write(source_default.red(`Error: Could not determine the main git repository root.
`));
        process.exit(1);
      }
      if (mainRepoRoot !== (findGitRoot(getCwd()) ?? getCwd())) {
        logForDiagnosticsNoPII("info", "worktree_resolved_to_main_repo");
        process.chdir(mainRepoRoot);
        setCwd(mainRepoRoot);
      }
      tmuxSessionName = tmuxEnabled ? generateTmuxSessionName(mainRepoRoot, worktreeBranchName(slug)) : undefined;
    } else {
      tmuxSessionName = tmuxEnabled ? generateTmuxSessionName(getCwd(), worktreeBranchName(slug)) : undefined;
    }
    let worktreeSession;
    try {
      worktreeSession = await createWorktreeForSession(getSessionId(), slug, tmuxSessionName, worktreePRNumber ? { prNumber: worktreePRNumber } : undefined);
    } catch (error) {
      process.stderr.write(source_default.red(`Error creating worktree: ${errorMessage(error)}
`));
      process.exit(1);
    }
    logEvent("tengu_worktree_created", { tmux_enabled: tmuxEnabled });
    if (tmuxEnabled && tmuxSessionName) {
      const tmuxResult = await createTmuxSessionForWorktree(tmuxSessionName, worktreeSession.worktreePath);
      if (tmuxResult.created) {
        console.log(source_default.green(`Created tmux session: ${source_default.bold(tmuxSessionName)}
To attach: ${source_default.bold(`tmux attach -t ${tmuxSessionName}`)}`));
      } else {
        console.error(source_default.yellow(`Warning: Failed to create tmux session: ${tmuxResult.error}`));
      }
    }
    process.chdir(worktreeSession.worktreePath);
    setCwd(worktreeSession.worktreePath);
    setOriginalCwd(getCwd());
    setProjectRoot(getCwd());
    saveWorktreeState(worktreeSession);
    clearMemoryFileCaches();
    updateHooksConfigSnapshot();
  }
  logForDiagnosticsNoPII("info", "setup_background_jobs_starting");
  if (!isBareMode()) {
    initSessionMemory();
    initSkillLearning();
    if (false) {}
  }
  lockCurrentVersion();
  logForDiagnosticsNoPII("info", "setup_background_jobs_launched");
  profileCheckpoint("setup_before_prefetch");
  logForDiagnosticsNoPII("info", "setup_prefetch_starting");
  const skipPluginPrefetch = getIsNonInteractiveSession() && isEnvTruthy(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL) || isBareMode();
  if (!skipPluginPrefetch) {
    getCommands(getProjectRoot());
  }
  import("./chunk-yy0rvdrf.js").then((m) => {
    if (!skipPluginPrefetch) {
      m.loadPluginHooks();
      m.setupPluginHookHotReload();
    }
  });
  if (!isBareMode()) {
    if (process.env.USER_TYPE === "ant") {
      import("./chunk-v2zfaqm8.js").then(async (m) => {
        if (await m.isInternalModelRepo()) {
          const { clearSystemPromptSections } = await import("./chunk-bvbsahx0.js");
          clearSystemPromptSections();
        }
      });
    }
    if (true) {
      setImmediate(() => {
        import("./chunk-nb2jk7zj.js").then(({ registerAttributionHooks }) => {
          registerAttributionHooks();
        });
      });
    }
    import("./chunk-88tc1cx6.js").then((m) => m.registerSessionFileAccessHooks());
    if (false) {}
  }
  initSinks();
  logEvent("tengu_started", {});
  prefetchApiKeyFromApiKeyHelperIfSafe(getIsNonInteractiveSession());
  profileCheckpoint("setup_after_prefetch");
  if (!isBareMode()) {
    const { hasReleaseNotes } = await checkForReleaseNotes(getGlobalConfig().lastReleaseNotesSeen);
    if (hasReleaseNotes) {
      await getRecentActivity();
    }
  }
  if (permissionMode === "bypassPermissions" || allowDangerouslySkipPermissions) {
    if (process.platform !== "win32" && typeof process.getuid === "function" && process.getuid() === 0 && process.env.IS_SANDBOX !== "1" && !isEnvTruthy(process.env.CLAUDE_CODE_BUBBLEWRAP)) {
      console.error(`--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons`);
      process.exit(1);
    }
    if (process.env.USER_TYPE === "ant" && process.env.CLAUDE_CODE_ENTRYPOINT !== "local-agent" && process.env.CLAUDE_CODE_ENTRYPOINT !== "claude-desktop") {
      const [isDocker, hasInternet] = await Promise.all([
        envDynamic.getIsDocker(),
        env.hasInternetAccess()
      ]);
      const isBubblewrap = envDynamic.getIsBubblewrapSandbox();
      const isSandbox = process.env.IS_SANDBOX === "1";
      const isSandboxed = isDocker || isBubblewrap || isSandbox;
      if (!isSandboxed || hasInternet) {
        console.error(`--dangerously-skip-permissions can only be used in Docker/sandbox containers with no internet access but got Docker: ${isDocker}, Bubblewrap: ${isBubblewrap}, IS_SANDBOX: ${isSandbox}, hasInternet: ${hasInternet}`);
        process.exit(1);
      }
    }
  }
  if (false) {}
  const projectConfig = getCurrentProjectConfig();
  if (projectConfig.lastCost !== undefined && projectConfig.lastDuration !== undefined) {
    logEvent("tengu_exit", {
      last_session_cost: projectConfig.lastCost,
      last_session_api_duration: projectConfig.lastAPIDuration,
      last_session_tool_duration: projectConfig.lastToolDuration,
      last_session_duration: projectConfig.lastDuration,
      last_session_lines_added: projectConfig.lastLinesAdded,
      last_session_lines_removed: projectConfig.lastLinesRemoved,
      last_session_total_input_tokens: projectConfig.lastTotalInputTokens,
      last_session_total_output_tokens: projectConfig.lastTotalOutputTokens,
      last_session_total_cache_creation_input_tokens: projectConfig.lastTotalCacheCreationInputTokens,
      last_session_total_cache_read_input_tokens: projectConfig.lastTotalCacheReadInputTokens,
      last_session_fps_average: projectConfig.lastFpsAverage,
      last_session_fps_low_1_pct: projectConfig.lastFpsLow1Pct,
      last_session_id: projectConfig.lastSessionId,
      ...projectConfig.lastSessionMetrics
    });
  }
}
export {
  setup
};

//# debugId=F1E0F4EDEDA2ABB264756E2164756E21
//# sourceMappingURL=chunk-exxzv1qx.js.map
