Part VIII · Entrypoints, Startup, SDK, and Remote Control
Chapter 22
Cold Start Mastery: From entrypoints/cli.tsx Through init.ts to main.tsx
Layer: Layer 8 (Entrypoints, Startup, SDK & Remote Control)
Prerequisites: Chapter 01, Chapter 14, Chapter 21
Primary Source Files:
entrypoints/cli.tsx— Zero-import bootstrapper, pre-import env fixes, fast-path command router, early stdin capture, and dynamic handoff tomain.tsx.entrypoints/init.ts— Memoized core initializer enforcing config → safe env → CA certs → signal handlers → mTLS/proxy → API TCP+TLS preconnect ordering, plus post-trust OTLP telemetry.setup.ts— Working-directory and hooks-snapshot lock-in,--worktree/--tmuxprovisioning,tengu_startedcrash-denominator beacon, and bypass-permission safety gates.main.tsx— Top-of-file MDM/keychain prefetches, Commander setup (with-psubcommand skip),preActionhook, trust boundary orchestration, and interactive vs. headless dispatch.interactiveHelpers.tsx&replLauncher.tsx— Interactive onboarding/trust dialog pipeline (showSetupScreens()), lazy REPL mounting (launchRepl()), and Ink exit epilogue (renderAndRun()).utils/startupProfiler.ts&utils/profilerBase.ts— Sampledperf_hookscheckpointing, parallel memory snapshots, andtengu_startup_perfphase telemetry.utils/gracefulShutdown.ts&utils/cleanupRegistry.ts— Cycle-free cleanup registry, Bunsignal-exitworkaround, synchronous terminal reset, bounded teardown phases, andSIGKILLfallback.
Why This Layer Exists
By the end of Chapter 21, every subsystem of Claude Code exists: stores, tools, prompt caches, query(), compaction, memory, permissions, hooks, settings, MCP, plugins, subagents, swarms, and a custom React/Ink terminal renderer. Now they all have to wake up inside a single CLI binary—fast enough to feel instantaneous when a user runs claude --version or pipes text into claude -p, yet disciplined enough to enforce enterprise security boundaries before a single untrusted byte executes.
Three hard systems constraints shape the boot path:
- Monolith import gravity.
main.tsxis 4,683 lines (~785 KB on disk, including its inline base64 source map) whose static import graph pulls in Commander, React, Ink, tools, commands, MCP config parsers, and eleven startup migrations (~135 ms of synchronous module evaluation). Paying that cost for--version, MCP helper servers, daemon workers, ortmuxtrampolines would destroy CLI responsiveness. - Irreversible runtime latches. Several process-level invariants lock in permanently on first use: BoringSSL caches the TLS certificate store on the first handshake; tool modules capture
DISABLE_BACKGROUND_TASKSinto module-levelconsts at import time; WindowsSearchPathWsearches the current directory unless blocked up front; and.claude/settings.jsoninside an untrusted git clone cannot be allowed to setANTHROPIC_BASE_URL,LD_PRELOAD, orNODE_EXTRA_CA_CERTSuntil a human accepts the workspace trust dialog. - Hostile teardown environments. Processes exit on
SIGINT,SIGTERM,SIGHUP, silent macOS TTY revocation, or declined trust dialogs—often with live MCP child processes, unflushed JSONL transcripts, pending 10-second analytics POSTs, and an Ink alternate screen waiting to overwrite the shell prompt.
Snapshot & build-artifact transparency: Compiled
.tsxfiles in this checkout (entrypoints/cli.tsx,main.tsx,interactiveHelpers.tsx,replLauncher.tsx) contain inline base64 source maps and constant-folded external-build literals such as"external" === 'ant'(main.tsx:266,340,428,1137,1531,1763,2013,2223,2819,3064,3581,3816,4370,4381,4405) and"production" === 'test' || isEnvTruthy(false)(interactiveHelpers.tsx:105). In addition, severalfeature('...')-gated targets referenced by the startup router are absent from this snapshot and observed only at their call sites:daemon/workerRegistry.ts,daemon/main.ts,cli/bg.ts,cli/handlers/templateJobs.ts,environment-runner/main.ts,self-hosted-runner/main.ts,utils/udsMessaging.ts,services/contextCollapse/index.ts,utils/attributionHooks.ts,utils/sessionDataUploader.ts,utils/eventLoopStallDetector.ts,ssh/createSSHSession.ts,server/server.ts,assistant/index.ts, andproactive/index.ts.
1. Zero-Import Bootstrap and Fast-Path Branching (entrypoints/cli.tsx)
The Problem
In JavaScript runtimes (Bun and Node.js alike), static import declarations evaluate depth-first before line 1 of the entry module executes. If cli.tsx statically imported config.ts, startupProfiler.ts, or main.tsx, then claude --version would instantiate thousands of modules just to print a build-time version string. Conversely, certain environment fixes must execute before any downstream module evaluates—because waiting until init() is already too late for modules that read process.env at top level.
The Real Implementation
entrypoints/cli.tsx solves both halves by importing only feature from 'bun:bundle' statically, running three surgical process.env patches at module top level, and making every other import inside main() dynamic:
// entrypoints/cli.tsx:1-48
import { feature } from 'bun:bundle';
// Bugfix for corepack auto-pinning, which adds yarnpkg to peoples' package.jsons
process.env.COREPACK_ENABLE_AUTO_PIN = '0';
// Set max heap size for child processes in CCR environments (containers have 16GB)
if (process.env.CLAUDE_CODE_REMOTE === 'true') {
const existing = process.env.NODE_OPTIONS || '';
process.env.NODE_OPTIONS = existing
? `${existing} --max-old-space-size=8192`
: '--max-old-space-size=8192';
}
// Harness-science L0 ablation baseline. Inlined here (not init.ts) because
// BashTool/AgentTool/PowerShellTool capture DISABLE_BACKGROUND_TASKS into
// module-level consts at import time — init() runs too late.
if (feature('ABLATION_BASELINE') && process.env.CLAUDE_CODE_ABLATION_BASELINE) {
for (const k of [
'CLAUDE_CODE_SIMPLE', 'CLAUDE_CODE_DISABLE_THINKING',
'DISABLE_INTERLEAVED_THINKING', 'DISABLE_COMPACT', 'DISABLE_AUTO_COMPACT',
'CLAUDE_CODE_DISABLE_AUTO_MEMORY', 'CLAUDE_CODE_DISABLE_BACKGROUND_TASKS',
]) {
process.env[k] ??= '1';
}
}
async function main(): Promise<void> {
const args = process.argv.slice(2);
// Fast-path for --version/-v: zero module loading needed
if (args.length === 1 && (args[0] === '--version' || args[0] === '-v' || args[0] === '-V')) {
console.log(`${MACRO.VERSION} (Claude Code)`);
return;
}
// For all other paths, load the startup profiler
const { profileCheckpoint } = await import('../utils/startupProfiler.js');
profileCheckpoint('cli_entry');
Immediately after 'cli_entry', cli.tsx walks a ladder of fast-path branches (entrypoints/cli.tsx:53-274). Notice that every feature('...') check is written inline—never wrapped in a helper—so Bun's bundler can dead-code-eliminate the dynamic import() target completely in builds where that flag is off:
| CLI Trigger | Gate / Scope | Loaded Target | Snapshot Status | Notable Startup Rule |
|---|---|---|---|---|
--version / -v / -V |
Always | None (MACRO.VERSION) |
Inlined | Zero imports; exits before profiler |
--dump-system-prompt |
feature('DUMP_SYSTEM_PROMPT') |
config, model, constants/prompts |
Present | Ant-only prompt-eval extractor |
--claude-in-chrome-mcp / --chrome-native-host |
Always | utils/claudeInChrome/* |
Present | Bypasses CLI & Ink completely |
--computer-use-mcp |
feature('CHICAGO_MCP') |
utils/computerUse/mcpServer.ts |
Present | Isolated MCP server process |
--daemon-worker |
feature('DAEMON') |
daemon/workerRegistry.js |
Absent | Precedes daemon; skips enableConfigs() & sinks so workers stay lean |
remote-control / rc / remote / sync / bridge |
feature('BRIDGE_MODE') |
bridge/bridgeMain.ts |
Present | Strict order: enableConfigs → OAuth check → GrowthBook gate → min version → policy limits |
daemon |
feature('DAEMON') |
daemon/main.js |
Absent | Calls enableConfigs() + initSinks() |
ps|logs|attach|kill, --bg/--background |
feature('BG_SESSIONS') |
cli/bg.js |
Absent | Flag literals inlined so bg.js loads only on dispatch |
new|list|reply |
feature('TEMPLATES') |
cli/handlers/templateJobs.js |
Absent | Calls process.exit(0) because mountFleetView's Ink TUI can leave dangling handles |
environment-runner / self-hosted-runner |
feature('BYOC_ENVIRONMENT_RUNNER') / feature('SELF_HOSTED_RUNNER') |
environment-runner/main.js, self-hosted-runner/main.js |
Absent | Headless cloud/BYOC worker loops |
--worktree + --tmux (--tmux=classic) |
Runtime isWorktreeModeEnabled() |
utils/worktree.ts |
Present | Execs into tmux before paying main.tsx load cost; falls through if unhandled |
If none of the fast-paths claim the invocation, entrypoints/cli.tsx:277-298 runs three final pre-main.tsx steps:
- Flag normalization: redirects single-arg
--update/--upgradeintoprocess.argv = [..., 'update']. - Early
--barelatch:if (args.includes('--bare')) process.env.CLAUDE_CODE_SIMPLE = '1'so module-evaluation and Commander option-building gates fire duringmain.tsx's import, not only inside the action handler. - Early keystroke capture (
utils/earlyInput.ts): users frequently typeclaude<Enter>and start typing their prompt immediately whilemain.tsxis still loading. CallingstartCapturingEarlyInput()right beforeawait import('../main.js')puts TTYstdininto raw mode and buffers printable text, grapheme-aware backspaces (lastGrapheme), and newlines while ignoring ANSI escape sequences (utils/earlyInput.ts:29-136).
Hidden Invariants & Failure Modes
- Why
bridgechecks OAuth before GrowthBook (entrypoints/cli.tsx:132-145):getBridgeDisabledReason()awaits live GrowthBook initialization so stale disk cache cannot override a server kill-switch, but withoutgetClaudeAIOAuthTokens()?.accessToken, GrowthBook lacks user identity headers and silently returns defaultfalse. Checking auth first surfacesBRIDGE_LOGIN_ERRORinstead of a misleading "feature disabled" message. - Why early input capture refuses
-p/--print(utils/earlyInput.ts:30-40): enablingsetRawMode(true)disables terminalISIG(kernel translation ofCtrl+CintoSIGINT). In print mode, that would render the process uninterruptible. Even in interactive mode, raw mode meansearlyInput.tsmust explicitly intercept byte3(Ctrl+C) and callprocess.exit(130)(utils/earlyInput.ts:81-86) becausegracefulShutdownhas not been installed yet. - Why
stopCapturingEarlyInput()never callssetRawMode(false)(utils/earlyInput.ts:154-156): it only detaches the'readable'listener. Resetting raw mode right as Ink mounts would race with Ink's own stdin initialization and drop keystrokes. - Top-level
void main()(entrypoints/cli.tsx:302): because the entry promise is unawaited, any synchronous or asyncthrowout of early CLI validation becomes an unhandled rejection—which instream-jsonmode vanishes silently. That is why early validation failures inmain.tsxwrite tostderrand callprocess.exit(1)explicitly (main.tsx:1487-1490).
2. The Strict Boot Sequence: entrypoints/init.ts and Startup Profiling
The Problem
Once main.tsx is loaded and a command is actually executing (not --help), Claude Code must initialize configuration, environment variables, CA certificates, mTLS/proxy agents, TCP+TLS warmup, signal handlers, and telemetry. Every one of those subsystems can silently break another if ordered wrong:
- Fire any
fetch()beforeNODE_EXTRA_CA_CERTSis populated fromsettings.json, and Bun's BoringSSL caches the default CA store without the corporate root certificate for the rest of the process lifetime. - Load
config.tsfrom insideutils/caCerts.ts, andconfig.ts → file.ts → permissions/filesystem.ts → commands.tspulls ~5,300 modules (React, Ink, every slash command) intoproxy.ts/mtls.ts—bloating the Agent SDK bundle from ~0.4 MB to ~10.8 MB (utils/caCertsConfig.ts:1-14). - Apply project-level
.claude/settings.jsonenvironment variables before the trust dialog, and a hostile repository can redirectANTHROPIC_BASE_URLor injectNODE_EXTRA_CA_CERTS/LD_PRELOADduring onboarding.
The Real Implementation
entrypoints/init.ts wraps the entire boot sequence in memoize(async () => ...) so repeated callers share one idempotent initialization promise, and enforces a strict seven-step sequence:
// entrypoints/init.ts:63-160 (abridged for clarity)
enableConfigs()
profileCheckpoint('init_configs_enabled')
// 1. Safe env vars only before trust (full env applied post-trust)
applySafeConfigEnvironmentVariables()
// 2. Copy NODE_EXTRA_CA_CERTS from user config/settings BEFORE any TLS
// handshake so Bun's BoringSSL cert store sees it at first init.
applyExtraCACertsFromConfig()
profileCheckpoint('init_safe_env_vars_applied')
// 3. Install signal handlers before spawning background work
setupGracefulShutdown()
profileCheckpoint('init_after_graceful_shutdown')
// 4. Fire-and-forget non-blocking warmups (1P logger deferred to skip OTel sdk-logs)
void Promise.all([
import('../services/analytics/firstPartyEventLogger.js'),
import('../services/analytics/growthbook.js'),
]).then(([fp, gb]) => {
fp.initialize1PEventLogging()
gb.onGrowthBookRefresh(() => { void fp.reinitialize1PEventLoggingIfConfigChanged() })
})
void populateOAuthAccountInfoIfNeeded()
void initJetBrainsDetection()
void detectCurrentRepository()
if (isEligibleForRemoteManagedSettings()) initializeRemoteManagedSettingsLoadingPromise()
if (isPolicyLimitsEligible()) initializePolicyLimitsLoadingPromise()
recordFirstStartTime()
// 5. Configure mTLS + HTTP/HTTPS proxy agents (NO_PROXY-aware)
configureGlobalMTLS()
configureGlobalAgents()
profileCheckpoint('init_network_configured')
// 6. Overlap Anthropic API TCP+TLS handshake (~100-200ms) with remaining startup
preconnectAnthropicApi()
Walk through the load-bearing engineering details behind each step:
enableConfigs()(utils/config.ts:1334-1356): flipsconfigReadingAllowed = trueand reads~/.claude.jsonwiththrowOnInvalid = true. Guarding config reads behind this latch catches accidental module-init disk reads during development. If~/.claude.jsonis malformed (ConfigParseError),init.ts:216-233branches ongetIsNonInteractiveSession(): non-interactive callers write plain text tostderrand callgracefulShutdownSync(1)(never rendering an Ink dialog that would corrupt JSON consumers such as Desktop'splugin marketplace list --json), while interactive sessions dynamically importInvalidConfigDialog.- Two-phase env loading (
utils/managedEnv.ts:124-199): before trust,applySafeConfigEnvironmentVariables()snapshotsccdSpawnEnvKeysonce whenCLAUDE_CODE_ENTRYPOINT === 'claude-desktop'(so user settings cannot override host-orchestrated vars likeOTEL_LOGS_EXPORTER=consoleand corrupt stdio JSON-RPC), strips SSH-tunnel and host-managed-provider vars viafilterSettingsEnv(), applies all env vars from trusted sources (~/.claude.json,userSettings,flagSettings), computesisRemoteManagedSettingsEligible(), appliespolicySettings, and applies only theSAFE_ENV_VARSallowlist from project-scoped settings. - CA certs split across two modules (
utils/caCertsConfig.ts&utils/caCerts.ts):NODE_EXTRA_CA_CERTSis intentionally excluded fromSAFE_ENV_VARSbecause trusting an attacker's CA defeats TLS. Yet corporate users behind HTTPS proxies need their CA loaded duringinit().applyExtraCACertsFromConfig()resolves this tension by readingNODE_EXTRA_CA_CERTSstrictly from user-controlled~/.claude/settings.jsonand~/.claude.json—never project settings—and writing it toprocess.env. Meanwhile,utils/caCerts.ts:28-50remains completelyconfig.ts-free (preventing the 10.8 MB SDK bloat) and lazy-requires'tls'only when--use-system-ca,--use-openssl-ca, orNODE_EXTRA_CA_CERTSis actually set, because Bun'snode:tlseagerly materializes ~150 Mozilla root certificates (~750 KB heap) on import. - Proxy, mTLS, and
preconnectAnthropicApi()(utils/mtls.ts,utils/proxy.ts,utils/apiPreconnect.ts):configureGlobalAgents()ejects any previous axios request interceptor before installing aNO_PROXY-aware one, and lazy-requiresundici(~1.5 MB deferred on the common no-proxy/no-mTLS path). Only after CA certs and agents are ready doespreconnectAnthropicApi()fire aHEADrequest with a 10-secondAbortSignal.timeoutto warm Bun's global keep-alive pool (utils/apiPreconnect.ts:31-71). It explicitly returns early for Bedrock/Vertex/Foundry (different endpoints) and for proxy/mTLS/ANTHROPIC_UNIX_SOCKET(where the SDK passes a custom dispatcher that never shares the global pool). A comment inutils/apiPreconnect.ts:15-18records the scar: an earlier call site incli.tsxhad to be removed because it ran beforesettings.jsonloaded, warming the wrong pool and locking BoringSSL beforeNODE_EXTRA_CA_CERTSlanded. - CCR upstream proxy & post-trust OTLP telemetry (
entrypoints/init.ts:167-210, 247-340): whenCLAUDE_CODE_REMOTEis truthy,init()lazily bootsupstreamproxy/upstreamproxy.ts(fail-open; covered in Chapter 24), sets up Windows git-bash, registers LSP and swarm-team (gh-32730) cleanups, and creates the scratchpad directory. Customer OpenTelemetry (initializeTelemetryAfterTrust()) stays completely dormant until after trust—deferring ~400 KB of OTel/protobuf inutils/telemetry/instrumentation.ts(and ~700 KB of@grpc/grpc-js) untilwaitForRemoteManagedSettingsToLoad()resolves andapplyConfigEnvironmentVariables()re-applies remote OTEL env vars. Once the meter initializes,setMeterState()incrementsgetSessionCounter()?.add(1)because the earlier startup path executed while the meter was stillnull(entrypoints/init.ts:335-338).
Measuring Every Millisecond: utils/startupProfiler.ts
Every checkpoint above feeds utils/startupProfiler.ts and utils/profilerBase.ts. To keep profiling cost at zero for 99.5% of external runs, sampling is decided once at module load:
// utils/startupProfiler.ts:26-54
const DETAILED_PROFILING = isEnvTruthy(process.env.CLAUDE_CODE_PROFILE_STARTUP)
const STATSIG_SAMPLE_RATE = 0.005
const STATSIG_LOGGING_SAMPLED =
process.env.USER_TYPE === 'ant' || Math.random() < STATSIG_SAMPLE_RATE
const SHOULD_PROFILE = DETAILED_PROFILING || STATSIG_LOGGING_SAMPLED
const memorySnapshots: NodeJS.MemoryUsage[] = []
const PHASE_DEFINITIONS = {
import_time: ['cli_entry', 'main_tsx_imports_loaded'],
init_time: ['init_function_start', 'init_function_end'],
settings_time: ['eagerLoadSettings_start', 'eagerLoadSettings_end'],
total_time: ['cli_entry', 'main_after_run'],
} as const
Two subtle implementation details make the profiler trustworthy:
getPerformance()(utils/profilerBase.ts:14-20) lazy-requiresperf_hooksonly whenSHOULD_PROFILEis true.- Under
CLAUDE_CODE_PROFILE_STARTUP=1, heap/RSS readings are appended to a parallelmemorySnapshots[]array indexed identically toperf.getEntriesByType('mark')—not aMap<string, MemoryUsage>—because checkpoints likeloadSettingsFromDisk_startfire multiple times across plugin cache resets, and aMapwould overwrite earlier snapshots (utils/startupProfiler.ts:38-46). Note also a minor doc drift in the file header (0.1%in comments vs.STATSIG_SAMPLE_RATE = 0.005, i.e., 0.5% in code).
Hidden Invariants & Failure Modes
Post-trust transport invalidation: When workspace trust is later accepted (or bypassed in
-pmode),applyConfigEnvironmentVariables()(utils/managedEnv.ts:187-199) does not just callObject.assign(process.env, ...). It explicitly invokesclearCACertsCache(),clearMTLSCache(),clearProxyCache(), andconfigureGlobalAgents()so any newly trusted proxy or mTLS settings replace the pre-trust transport agents cleanly without stacking duplicate axios interceptors.
- Deadlock protection on remote-settings promises (
entrypoints/init.ts:120-128):init()initializes the loading promises for remote managed settings and policy limits beforeloadRemoteManagedSettings()is even called inmain.tsx'spreAction. Those promises carry internal timeouts so callers (such as Agent SDK tests that never invokeloadRemoteManagedSettings()) never deadlock waiting for them. - Eager beta-tracing race guard (
entrypoints/init.ts:248-303): in non-interactive SDK sessions withisBetaTracingEnabled(),initializeTelemetryAfterTrust()kicksdoInitializeTelemetry()eagerly without waiting for remote settings so the tracer is ready before the first query, while the remote-settings.then()path still callsdoInitializeTelemetry()later—guarded against double-init by thetelemetryInitializedlatch (which resets tofalseon error to allow retries).
3. Winning the Import Race: Parallel Prefetches in main.tsx and setup.ts
The Problem
Evaluating main.tsx's static import graph takes ~135 ms on a warm machine. On macOS, enterprise MDM (plutil) plus two sequential security find-generic-password keychain lookups ("Claude Code-credentials" ~32 ms + "Claude Code" ~33 ms) would add another ~70 ms on top of that—followed by UDS socket binding (~20 ms), command/agent filesystem scans, and MCP config discovery. Running those sequentially turns cold start into a sluggish pause before the first frame even draws.
The Real Implementation
Claude Code eliminates that serial chain by overlapping startup work across four distinct waves:
Wave 0 — Pre-Import Subprocess Launches (main.tsx:1-20)
The very first 20 lines of main.tsx interleave executable statements above line 21's heavy imports:
// main.tsx:9-21
import { profileCheckpoint, profileReport } from './utils/startupProfiler.js';
profileCheckpoint('main_tsx_entry');
import { startMdmRawRead } from './utils/settings/mdm/rawRead.js';
startMdmRawRead();
import { ensureKeychainPrefetchCompleted, startKeychainPrefetch } from './utils/secureStorage/keychainPrefetch.js';
startKeychainPrefetch();
import { feature } from 'bun:bundle'; // Heavy static imports begin here...
Look closely at the two leaf modules invoked here:
utils/settings/mdm/rawRead.ts:55-123imports onlychild_process,fs, andmdm/constants.ts. On macOS, it checksexistsSync(path)synchronously before callingexecFile('plutil', ...): non-MDM laptops skip the ~5 msplutilspawn completely, while MDM machines guaranteeexecFileis the very firstawaitso the OS spawnsplutilbefore the event loop blocks on the remaining imports. On Windows, it firesreg queryforHKLMandHKCUin parallel.utils/secureStorage/keychainPrefetch.ts:69-89spawns both macOSsecurityqueries concurrently (skipped on non-darwin or underisBareMode()). Its comment captures a classic import-graph trap: it imports lightweightmacOsKeychainHelpers.tsinstead ofmacOsKeychainStorage.ts, because the latter pulls inexeca → human-signals → cross-spawn—~58 ms of synchronous module init that would erase the entire savings! It also distinguishesnull("not started") from{ stdout: null }("completed, exit 44 / no entry") and refuses to prime the cache on timeout so the synchronous fallback can retry rather than falsely caching "no key".
Wave 1 — Pre-Commander Normalization, Eager Settings, and preAction (main.tsx:432-967)
When entrypoints/cli.tsx invokes cliMain(), main() runs before Commander parses arguments:
- Windows PATH-hijack shield (
main.tsx:591): setsprocess.env.NoDefaultCurrentDirectoryInExePath = '1'before any child process can spawn, preventing WindowsSearchPathWfrom executing malicious binaries dropped in an untrusted repository's cwd. - Anti-debugging guard (
main.tsx:232-271): top-levelif ("external" !== 'ant' && isBeingDebugged()) process.exit(1). Under Bun single-file executables, application flags fromprocess.argvleak intoprocess.execArgv(Bun issue #11673), so the Bun branch skips matching--debugto avoid falsely killingclaude --debug. - Argv rewriting (
main.tsx:612-795): interceptscc:///cc+unix://(feature('DIRECT_CONNECT')), OS protocol deep links--handle-uriand macOS LaunchServices__CFBundleIdentifier === 'com.anthropic.claude-code-url-handler'(feature('LODESTONE')),claude assistant [sessionId](feature('KAIROS')), andclaude ssh <host> [dir](feature('SSH_REMOTE')). Stashing target parameters into module-level_pendingConnect/_pendingAssistantChat/_pendingSSHand rewritingprocess.argvroutes interactive runs through the default action so they inherit the full REPL instead of a stripped-down subcommand. - Interactive classification &
eagerLoadSettings()(main.tsx:799-855): detectsisNonInteractive = hasPrintFlag || hasInitOnlyFlag || hasSdkUrl || !process.stdout.isTTY, stops early input capture for non-interactive runs, determinesCLAUDE_CODE_ENTRYPOINTandclientType, and parses--settingsand--setting-sourcesviautils/cliArgs.tsbeforeinit()runs.
The 12x Prompt-Cache Scar (
main.tsx:445-457): When a caller passes inline JSON to--settings '{...}',loadSettingsFromFlag()writes it to a temporary file so the settings loader can treat it uniformly. Crucially, the filename usescontentHash: trimmedSettings—never a random UUID. Why? Because the flag-settings file path lands inside the Bash tool's sandboxdenyWithinAllowlist, which is serialized into the tool definition sent to the Anthropic API. In Agent SDK loops where eachquery()spawns a fresh CLI subprocess, a random UUID mutated the tool schema on every call, invalidating the prompt-cache prefix and causing a 12x input token cost penalty.
- Commander
preActionhook (main.tsx:907-967) & the-psubcommand skip (main.tsx:3875-3890): attaching initialization toprogram.hook('preAction')guaranteesclaude --helpnever runsinit()or migrations. When a real command executes,preActionjoins Wave 0 viaawait Promise.all([ensureMdmSettingsLoaded(), ensureKeychainPrefetchCompleted()])(nearly free since both finished during imports), awaitsinit(), setsprocess.title = 'claude', attaches logging/analytics sinks viautils/sinks.ts(so subcommands likedoctorandpluginthat bypasssetup()don't silently drop queued events), wires repeatable--plugin-diroptions (gh-33508), executesrunMigrations()(CURRENT_MIGRATION_VERSION = 11,main.tsx:325-352), and kicks off non-blockingloadRemoteManagedSettings(),loadPolicyLimits(), andfeature('UPLOAD_USER_SETTINGS')sync. Meanwhile, in-p/--printmode (unless acc://URL was rewritten toopen),main.tsx:3883-3890skips registering all 52 subcommands (mcp,auth,plugin,doctor,update, etc.) and jumps straight toprogram.parseAsync(process.argv), saving ~65 ms on every headless invocation.
Wave 2 — Parallel setup(), Commands/Agents, and MCP Config Discovery (main.tsx:1780-2031, setup.ts)
Inside the default Commander action handler, main.tsx parses flags, validates tool permissions (initializeToolPermissionContext()), and kicks off read-only MCP config discovery (mcpConfigPromise, plus claudeaiConfigPromise in -p mode). Then it runs setup() in parallel with command and agent loading:
// main.tsx:1918-1936
const preSetupCwd = getCwd();
// Pure in-memory array pushes (<1ms). Previously ran inside setup() after
// ~20ms of awaits, causing parallel getCommands() to memoize an empty list.
if (process.env.CLAUDE_CODE_ENTRYPOINT !== 'local-agent') {
initBuiltinPlugins();
initBundledSkills();
}
const setupPromise = setup(
preSetupCwd, permissionMode, allowDangerouslySkipPermissions,
worktreeEnabled, worktreeName, tmuxEnabled,
sessionId ? validateUuid(sessionId) : undefined,
worktreePRNumber, messagingSocketPath,
);
const commandsPromise = worktreeEnabled ? null : getCommands(preSetupCwd);
const agentDefsPromise = worktreeEnabled ? null : getAgentDefinitionsWithOverrides(preSetupCwd);
commandsPromise?.catch(() => {});
agentDefsPromise?.catch(() => {});
await setupPromise;
Notice the two subtle guards in those 18 lines:
- Preventing empty bundled-skills memoization:
initBuiltinPlugins()andinitBundledSkills()were pulled out ofsetup.ts(setup.ts:289-292) becausesetup()awaitsstartUdsMessaging()(~20 ms socket bind,feature('UDS_INBOX'), absent from snapshot), allowing the concurrentgetCommands(preSetupCwd)call to race ahead and memoize an empty bundled-skills list. - Worktree serialization & transient rejection suppression: when
--worktreeis enabled,commandsPromiseandagentDefsPromisestaynullbecausesetup()callsprocess.chdir(worktreePath), changing the directory from which commands and agents must load. The.catch(() => {})calls suppress spurious globalunhandledRejectionevents during the ~28 ms window beforePromise.alljoins them atmain.tsx:2029.
Inside setup.ts (setup.ts:56-477), six load-bearing invariants execute in strict order:
- Runtime & identity prep (
setup.ts:69-158): enforces Node >= 18, applies custom--session-id, binds the UDS inbox socket beforeSessionStarthooks can snapshotprocess.env, captures the teammate-mode snapshot, and—in interactive sessions only—detects and restores interrupted iTerm2 or Terminal.app plist setups. - CWD → Hooks Snapshot → Worktree (
setup.ts:160-285):setCwd(cwd)must precedecaptureHooksConfigSnapshot()andinitializeFileChangedWatcher(cwd)so hooks snapshot from the real working directory. If--worktreeis active,setup()checks for either aWorktreeCreatehook or git repo, resolves canonical repo root if invoked inside an existing worktree, creates the worktree (and optionaltmuxsession), callsprocess.chdir(), updatessetOriginalCwd()andsetProjectRoot()(unlike mid-sessionEnterWorktreeTool,--worktreemakes the worktree the session's project root), clears memory caches (clearMemoryFileCaches()), and re-runsupdateHooksConfigSnapshot()against the worktree's.claude/settings.json. - Background registrations & plugin prefetch (
setup.ts:293-370): synchronously registersinitSessionMemory()andfeature('CONTEXT_COLLAPSE')(services/contextCollapse/index.js, absent from snapshot), locks the binary version (lockCurrentVersion()), kicks off plugin hook prefetch + hot-reload (skipped whenCLAUDE_CODE_SYNC_PLUGIN_INSTALLis set in headless mode to avoid racingcopyPluginToVersionedCache, or under--bare), and registers ant undercover repo checks,COMMIT_ATTRIBUTIONhooks (deferred viasetImmediateto keep git spawns out of setup microtasks; module absent from snapshot), session file-access hooks, andfeature('TEAMMEM')watchers. - The
tengu_startedcrash-denominator beacon (setup.ts:371-378):initSinks()immediately followed bylogEvent('tengu_started', {}). A comment documentsinc-3694: a P0 crash insidecheckForReleaseNotes()(line 387) killed the process before any downstream telemetry fired, hiding the outage from release-health dashboards. Placingtengu_startedright after sink attachment establishes an honest denominator for session crash rates. - Bypass-permissions safety gate (
setup.ts:396-442): ifpermissionMode === 'bypassPermissions'orallowDangerouslySkipPermissionsis set, POSIX root (process.getuid() === 0) is rejected unlessIS_SANDBOX === '1'orCLAUDE_CODE_BUBBLEWRAPis set. Forprocess.env.USER_TYPE === 'ant'(exemptinglocal-agentandclaude-desktop),setup()also checksenvDynamic.getIsDocker(),envDynamic.getIsBubblewrapSandbox(), andenv.hasInternetAccess()—refusing to run unless sandboxed with no internet access. - Prior-session exit telemetry (
setup.ts:449-476): emitstengu_exitcarrying the previous session's persisted cost, durations, token counts, and FPS metrics fromprojectConfigwithout clearing them (they are still needed for cost restoration on--resume).
Wave 3 — Non-Interactive Overlap & Post-Render Deferred Prefetches (main.tsx:388-431, 1952-1990)
Right after await setupPromise, non-interactive (-p) sessions immediately call applyConfigEnvironmentVariables() (trust is implicit) and kick off getSystemContext(), getUserContext(), and ensureModelStringsInitialized() (overlapping Bedrock's 100–200 ms profile fetch with commandsPromise). Interactive sessions instead defer heavy process-spawning prefetches (initUser, getUserContext, prefetchSystemContextIfSafe, getRelevantTips, Bedrock/Vertex credential prefetches, countFilesRoundedRg, initializeAnalyticsGates, settingsChangeDetector.initialize(), skillChangeDetector.initialize()) into startDeferredPrefetches() (main.tsx:388-431), which runs only after root.render(element) in renderAndRun() (interactiveHelpers.tsx:98-103)—hiding child-process contention behind the user's thinking/typing window and skipping everything under CLAUDE_CODE_EXIT_AFTER_FIRST_RENDER or --bare.
Hidden Invariants & Failure Modes
- Why
--bare(CLAUDE_CODE_SIMPLE=1) acts as a latency scalpel across all waves: scripted-pcalls have no "user is typing" window to hide background spawns. Passing--bareskips macOS keychain prefetch (keychainPrefetch.ts:70), UDS inbox & teammate snapshots (setup.ts:89-110), session memory & plugin/attribution/release-notes I/O (setup.ts:293-393), claude.ai & auto-discovered MCP configs (main.tsx:1788,1809), startup quota/bootstrap prefetches (main.tsx:2346), versioned plugin sync (main.tsx:2555), andstartDeferredPrefetches()+backgroundHousekeeping(main.tsx:399,2816). - Cold GrowthBook alias crash-loop guard (
main.tsx:2001-2015): for ant builds ("external" === 'ant'in this snapshot), an explicit--modelorANTHROPIC_MODELwith an unpopulatedcachedGrowthBookFeatures['tengu_ant_model_override']awaitsinitializeGrowthBook()before resolving model aliases—otherwise a cold container pod resolves an internal alias raw, hits a 404, and exits before the async disk cache write lands.
4. Trust Boundary, Mode Dispatch, and Interactive vs. Headless Handoff
The Problem
After setup() and commands/agents complete, main.tsx faces a stark fork between two worlds:
- Interactive sessions run inside a user's terminal on potentially untrusted repositories. They must show onboarding/trust dialogs before executing
.claude/settings.jsonenv vars, LSP servers,apiKeyHelper, or.mcp.jsoncommands; they must mount Ink (createRoot, whosepatchConsoleswallowsconsole.error); and they must never block first paint on slow MCP servers or ~500 msSessionStarthooks. - Headless (
-p/ SDK) sessions have no terminal UI and treat workspace trust as implicit. They cannot create an Ink root, must materialize configured MCP tools before turn 1 (since-pis often single-turn), and must hand off an initializedAppStatestore tocli/print.ts.
The Real Implementation
The Interactive Trust Gauntlet (main.tsx:2211-2378, interactiveHelpers.tsx:104-298)
When !isNonInteractiveSession, main.tsx constructs the Ink root (createRoot(ctx.renderOptions)), logs tengu_timer (startup) before any dialog renders—fixing an old bug where logging from REPL's first render measured user dialog-wait time and pushed p99 to ~70s (main.tsx:2231-2238)—and runs showSetupScreens():
Onboarding(if!config.theme || !config.hasCompletedOnboarding).TrustDialog(unlessCLAUBBITis set; fast-paths past dynamic import ifcheckHasTrustDialogAccepted()is already true).- Post-trust unlock (
interactiveHelpers.tsx:144-190): markssetSessionTrustAccepted(true), resets and re-initializes GrowthBook with fresh auth headers, prefetchesgetSystemContext(), approves.mcp.jsonservers andCLAUDE.mdexternal includes, records the repo path for--teleport(updateGithubRepoPathMapping()), callsapplyConfigEnvironmentVariables()(applying full project env vars and rebuilding CA/mTLS/proxy agents), and schedulessetImmediate(() => initializeTelemetryAfterTrust())so OTel's dynamic import resolves after first render. - Conditional consent modals:
GroveDialog,ApproveApiKey(for newANTHROPIC_API_KEYoutside homespace),BypassPermissionsModeDialog,AutoModeOptInDialog(feature('TRANSCRIPT_CLASSIFIER')),DevChannelsDialog(feature('KAIROS') || feature('KAIROS_CHANNELS'), blocking ontengu_harboronly if disk cache is cold/false to fixgh#37026), andClaudeInChromeOnboarding.
Immediately after showSetupScreens() returns (and after validateForceLoginOrg()), main.tsx enforces a critical abort check:
// main.tsx:2308-2321
// If gracefulShutdown was initiated (e.g., user rejected trust dialog),
// process.exitCode will be set. Skip all subsequent operations that could
// trigger code execution before the process exits (e.g. apiKeyHelper).
if (process.exitCode !== undefined) {
logForDebugging('Graceful shutdown initiated, skipping further initialization');
return;
}
// Initialize LSP manager AFTER trust is established (or in non-interactive mode
// where trust is implicit). Prevents plugin LSP servers from executing code
// in untrusted directories before user consent.
initializeLspServerManager();
Next come post-trust settings validation (launchInvalidSettingsDialog), throttled background API prefetches (checkQuotaStatus, fetchBootstrapData, prefetchPassesEligibility, prefetchFastModeStatus—throttled across rapid restarts by GrowthBook tengu_cicada_nap_ms while still enforcing fast-mode org policy from cache via resolveFastModeStatusFromCache(), main.tsx:2344-2375), MCP config resolution (await mcpConfigPromise), and versioned plugin initialization (awaited in headless mode so sync completes before exit, fire-and-forget in interactive mode, skipped in --bare, main.tsx:2555-2570).
The Three Execution Exits from main.tsx
| Mode | Entry Condition (main.tsx) |
MCP & Hook Strategy | State & Downstream Handoff |
|---|---|---|---|
1. --init-only |
main.tsx:2572-2582 |
Applies full env; runs Setup (init) + SessionStart (startup) with forceSyncExecution: true |
gracefulShutdownSync(0) and return |
2. Headless / -p / SDK |
isNonInteractiveSession (main.tsx:2585-2861) |
Awaits connectMcpBatch(regularMcpConfigs); deduplicates plugin:* vs. claude.ai vs. manual .mcp.json (gh-39974) with a 5s cap (CLAUDE_AI_MCP_TIMEOUT_MS); kicks sessionStartHooksPromise early |
Creates headlessStore = createStore(headlessInitialState, onChangeAppState), separates sdkMcpConfigs (type === 'sdk'), lazily imports and invokes runHeadless(...) in cli/print.ts:455 |
| 3. Interactive REPL | Default fallthrough (main.tsx:2863-3807) |
Never awaits mcpPromise or hooksPromise before paint; useManageMCPConnections converges on memoized connectToServer, and REPL receives pendingHookMessages |
Builds initialState, increments numStartups synchronously, dispatches across 6 flavors (--continue, cc:// Direct Connect, claude ssh, claude assistant viewer, --resume/--from-pr/--teleport/--remote, or fresh session) into launchRepl() (replLauncher.tsx:12-22) → renderAndRun() (interactiveHelpers.tsx:98-103) |
Look at two notable scars in the headless vs. interactive split:
- The 5-second
claude.aiMCP cap (main.tsx:2733-2809): makingclaude.aiconnectors blocking in-pmode fixed single-turn connector visibility, but users with 40+ slow connectors sawtengu_startup_perfp99 explode to 76 seconds. RacingclaudeaiConnectagainstCLAUDE_AI_MCP_TIMEOUT_MS = 5_000bounds turn-1 startup while letting slow connectors finish intoheadlessStorein the background for turn 2+. - Why
launchRepl()lives in its own 23-line file (replLauncher.tsx): it dynamically imports./components/App.jsand./screens/REPL.jsonly after every setup screen and session-resolution branch completes, keeping the entire React REPL component tree off themain.tsxstatic import graph for subcommands and-pruns.
Hidden Invariants & Failure Modes
- Early trust gate for
KAIROSassistant mode (main.tsx:1043-1089):.claude/settings.jsoncan declareassistant: trueand append.claude/agents/assistant.md~1,000 lines beforeshowSetupScreens()runs. Therefore theKAIROSblock checkscheckHasTrustDialogAccepted()itself and refuses to activate in untrusted directories (and skips re-initializing the team when--agent-idindicates the process is already a spawned teammate). - Double
SessionStarthook prevention on resume (main.tsx:2432-2440):hooksPromiseis explicitlynullwhenoptions.continue || options.resumeis set, becauseconversationRecovery.tsfires'resume'hooks; firing'startup'too caused hooks to run twice and clobber the first system message (gh-30825). - Preserving
type: 'sdk'MCP entries (main.tsx:1493-1503): the Python Agent SDK passes SDK-hosted MCP servers via--mcp-configrather than theinitializecontrol message. Droppingtype: 'sdk'during dynamic config parsing broke Coworker (inc-5122), somain.tsxpreserves them through policy filtering and extracts them intosdkMcpConfigsforrunHeadless().
5. Bulletproof Teardown: cleanupRegistry.ts and gracefulShutdown.ts
The Problem
Shutting down a terminal agent cleanly is an adversarial distributed-systems problem disguised as process exit:
- 25+ subsystems (
config.ts,sessionStorage.ts,mcp/client.ts,lsp/manager.ts,settings/changeDetector.ts,telemetry/instrumentation.ts,swarm/teamHelpers.ts, etc.) must flush state or reap children—without creating circular imports withgracefulShutdown.ts. - Under Bun, any short-lived
signal-exitv4 subscriber (likeexecafinishing a child command) callingremoveListenerresets the kernelsigaction, silently nuking Claude Code'sSIGTERMhandler! - On macOS, closing a terminal window often revokes the TTY file descriptors without delivering
SIGHUP, stranding an orphaned process forever; and when a PTY is dead,process.exit()itself can throwEIOtrying to flush stdout. - Unmounting Ink at the wrong moment sends a duplicate
EXIT_ALT_SCREEN(1049l/DECRC) afterclaude --resume <id>is printed, jumping the cursor backwards and clobbering the resume hint.
The Real Implementation
First, utils/cleanupRegistry.ts isolates the registration surface in a 25-line, zero-dependency leaf module (const cleanupFunctions = new Set<() => Promise<void>>()), returning an unregister thunk from registerCleanup(fn) and running all registered hooks concurrently via runCleanupFunctions().
Second, setupGracefulShutdown() (utils/gracefulShutdown.ts:237-334) installs process-wide survival armor once via memoize:
// utils/gracefulShutdown.ts:237-297 (abridged)
export const setupGracefulShutdown = memoize(() => {
// Pin signal-exit v4 so its emitter count stays > 0 and v4.unload() never
// calls removeListener — working around a Bun bug where removeListener
// resets the kernel sigaction even when other JS listeners remain.
onExit(() => {})
process.on('SIGINT', () => {
if (process.argv.includes('-p') || process.argv.includes('--print')) return
logForDiagnosticsNoPII('info', 'shutdown_signal', { signal: 'SIGINT' })
void gracefulShutdown(0)
})
process.on('SIGTERM', () => { void gracefulShutdown(143) })
if (process.platform !== 'win32') {
process.on('SIGHUP', () => { void gracefulShutdown(129) })
if (process.stdin.isTTY) {
orphanCheckInterval = setInterval(() => {
if (getIsScrollDraining()) return // Never steal a scroll frame
if (!process.stdout.writable || !process.stdin.readable) {
clearInterval(orphanCheckInterval)
void gracefulShutdown(129)
}
}, 30_000)
orphanCheckInterval.unref()
}
}
// Plus uncaughtException & unhandledRejection analytics/diagnostics listeners
})
Third, gracefulShutdown() (utils/gracefulShutdown.ts:391-523) executes a strictly ordered, budget-bounded teardown pipeline:
- Re-entrancy latch & scaled failsafe timer (
gracefulShutdown.ts:401-429): ifshutdownInProgressis already true, return immediately. Otherwise resolvesessionEndTimeoutMs = getSessionEndHookTimeoutMs()before arming the.unref()'d failsafe timer atMath.max(5000, sessionEndTimeoutMs + 3500)—fixinggh-32712, where a hardcoded 5-second failsafe silently truncated user-configured 10-secondSessionEndhooks. - Synchronous terminal restoration & resume hint FIRST (
gracefulShutdown.ts:59-185, 431-438): runs before any async I/O so even aSIGKILLduring macOS reboot leaves a usable terminal and visible resume command. InsidecleanupTerminalModes(), exact ordering matters:writeSync(1, DISABLE_MOUSE_TRACKING)first, giving the terminal a round-trip to stop sending mouse bytes while React unmounts.- If
inst?.isAltScreenActive, callinst.unmount()directly (falling back towriteSync(1, EXIT_ALT_SCREEN)only if unmount throws). Unmounting whilealtScreenActiveis true keeps the final render on the alt buffer, unsubscribes Ink fromsignal-exit, and writes1049lexactly once. inst?.drainStdin()theninst?.detachForShutdown()so deferredsignal-exithandlers cannot emit redundantEXIT_ALT_SCREENsequences afterprintResumeHint().- Unconditionally
writeSync(1, ...)DISABLE_MODIFY_OTHER_KEYS,DISABLE_KITTY_KEYBOARD,DFE(focus events),DBP(bracketed paste),SHOW_CURSOR,CLEAR_ITERM2_PROGRESS, optionalCLEAR_TAB_STATUS, andCLEAR_TERMINAL_TITLE(respectingCLAUDE_CODE_DISABLE_TERMINAL_TITLE). printResumeHint()prints\nResume this session with:\nclaude --resume <title-or-id>\nat most once (resumeHintPrinted) when TTY + interactive + session file exists.
- Phase 1 — Registered cleanups, capped at 2,000 ms (
gracefulShutdown.ts:439-467): racesrunCleanupFunctions()against a 2-second timeout. Running this before hooks and analytics guarantees session JSONL flush +reAppendSessionMetadata()(utils/sessionStorage.ts:449-462—which re-appends custom titles into the last 64 KB tail window so--resumenever loses/rename) completes even if the network or TTY is dead. - Phase 2 —
SessionEndhooks, capped atsessionEndTimeoutMs(gracefulShutdown.ts:469-480): default 1.5s, configurable viaCLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS, bounded withAbortSignal.timeout(sessionEndTimeoutMs). - Phase 3 —
profileReport()+tengu_cache_eviction_hint(gracefulShutdown.ts:482-499): emits startup perf telemetry and signals inference (viagetLastMainRequestId()) that this session's prompt cache can be evicted—both before analytics shutdown drains the queue. - Phase 4 — Analytics flush, capped at 500 ms (
gracefulShutdown.ts:501-511): racesPromise.all([shutdown1PEventLogging(), shutdownDatadog()])againstsleep(500). Previously unbounded, the 1P exporter awaited 10-second axios POSTs on stalled networks; losing late telemetry is acceptable, hanging exit is not. forceExit(exitCode)(gracefulShutdown.ts:193-232): clears the failsafe timer, callsinstances.get(process.stdout)?.drainStdin()one last time (using the Ink instance method so/dev/ttyoverrides are drained even whenprocess.stdinwas piped!), callsprocess.exit(exitCode), and onEIOfrom a dead PTY falls back toprocess.kill(process.pid, 'SIGKILL').
Hidden Invariants & Failure Modes
- Why
gracefulShutdownSync()setsprocess.exitCodeimmediately (gracefulShutdown.ts:344-359):gracefulShutdownSync()launches the async shutdown without awaiting it, but assignsprocess.exitCode = exitCodesynchronously first. That single assignment is the contractmain.tsx:2312checks right aftershowSetupScreens()to stop initialization dead in its tracks when a user rejects the trust dialog. - Dual
SIGINTlistener coordination (main.tsx:598-606vs.gracefulShutdown.ts:256-267):main.tsxinstalls an earlySIGINTlistener (process.exit(0)) beforeinit()runs so Ctrl+C works during pre-init()parsing, and both listeners explicitlyreturnwhen-p/--printis inprocess.argvsocli/print.tscan abort in-flight queries and shut down cleanly without racing.
Putting the Layer Together
The startup and shutdown architecture forms a single funnel: fast-paths peel off early in cli.tsx, normal executions overlap I/O across four waves into init() and setup(), branch sharply across the workspace trust boundary, and reconverge on gracefulShutdown():
flowchart TD
A["entrypoints/cli.tsx (1 static import: feature)"] --> B{"--version / -v / -V?"}
B -->|"Yes"| Z1["Print MACRO.VERSION & return (0 imports)"]
B -->|"No"| C{"Fast-path flag or subcommand? (MCP, bridge, daemon, bg, tmux...)"}
C -->|"Yes"| Z2["Dynamic import & run isolated handler"]
C -->|"No"| D["--bare -> SIMPLE=1; startCapturingEarlyInput()"]
D --> E["Wave 0: main.tsx top-level startMdmRawRead() + startKeychainPrefetch()"]
E --> F["main.tsx imports (~135ms) + main() argv rewrite + eagerLoadSettings()"]
F --> G["Commander preAction: await MDM + Keychain -> await init() -> runMigrations()"]
G --> H["init.ts: enableConfigs -> safeEnv -> CA certs -> signals -> mTLS/proxy -> preconnectAnthropicApi()"]
H --> I["Wave 2: parallel setup() + getCommands() + getAgentDefinitionsWithOverrides() + mcpConfigPromise"]
I --> J{"Execution Mode?"}
J -->|"init-only"| K1["Sync Setup + SessionStart hooks -> gracefulShutdownSync(0)"]
J -->|"Headless (-p / SDK / non-TTY)"| K2["applyConfigEnv -> headlessStore -> connectMcpBatch (5s claude.ai cap) -> runHeadless()"]
J -->|"Interactive TTY"| K3["createRoot() -> showSetupScreens() -> TrustDialog -> applyConfigEnv -> launchRepl()"]
K2 --> L["gracefulShutdown(): sync terminal reset + resume hint -> 2s cleanups -> SessionEnd -> 500ms analytics -> forceExit()"]
K3 --> L
Zooming in on the parallel overlap windows that keep cold start fast:
Stage A: Import Overlap (cli.tsx -> main.tsx preAction)
cli.tsx : [earlyInput]
Wave 0 : |--plutil / reg query (MDM)------|
: |--security (OAuth + API key)----|
Imports : |======= main.tsx static imports (~135ms) =======|
preAct : [join ~0ms]->init()
Stage B: Post-init() Overlap (init.ts -> Fork -> First Paint)
init() : |-cfg->env->CA->sig->proxy-|
Preconn : |--TCP+TLS HEAD (~100-200ms)----|
Wave 2 : |--setup() (UDS/hooks/worktree)-|
: |--getCommands() + getAgents()--|
: |--mcpConfigPromise (file read)-|
Fork : |-UI/-p-|
PostPnt : |-def-|
How This Snaps Into the Next Layer
Every interactive session exiting main.tsx converges on launchRepl() (replLauncher.tsx:12-22) and the React/Ink REPL already dissected in Chapter 21. Every non-interactive and Agent SDK session exits through two concrete handoffs that open Chapter 23 — Machine-Readable Modes: Headless CLI, Agent SDK, and Control Protocols:
- Headless & SDK execution (
main.tsx:2825-2860→cli/print.ts:455):main.tsxdynamically importsrunHeadless()and hands itinputPrompt(either a string or the liveprocess.stdinAsyncIterablewhen--input-format=stream-json),headlessStore.getState/setState, filteredcommandsHeadless,tools,sdkMcpConfigs,agentDefinitions.activeAgents, and the already-in-flightsessionStartHooksPromise. Insidecli/print.ts,StructuredIOandRemoteIOtake over NDJSON framing, stdout guarding, and SDK control-protocol round-trips. - MCP server mode (
main.tsx:3894-3909→cli/handlers/mcp.ts→entrypoints/mcp.ts):claude mcp servebypasses the default action and exposes Claude Code's own tool loop as an MCP server.
Finally, the remote and bridge branches that cli.tsx (remote-control → bridge/bridgeMain.ts), init.ts (upstreamproxy/upstreamproxy.ts), and main.tsx (DIRECT_CONNECT, --remote, --teleport, --rc) prepared will be unpacked end-to-end in Chapter 24.
Reading Exercises & Code Checkpoints
-
Trace every
--barelatency cut across the startup path: Run:rg -n "isBareMode|CLAUDE_CODE_SIMPLE" entrypoints/cli.tsx main.tsx setup.ts utils/secureStorage/keychainPrefetch.tsVerify which subsystems
--barebypasses at module-eval time versus insidesetup()versus insidemain.tsx, and explain whysetup.ts:334-335refuses to early-return out ofsetup()under--bare. -
Audit every checkpoint feeding
tengu_startup_perf: Run:rg -n "profileCheckpoint\(" entrypoints/ main.tsx setup.tsMatch the checkpoint names against
PHASE_DEFINITIONSinutils/startupProfiler.ts:49-54. Which checkpoint is missing if a user passes--help, and why doesinit_timestay undefined in that case? -
Verify the trust-boundary invariant on environment variables and CA certs: Read
utils/managedEnv.ts:93-199alongsideutils/caCertsConfig.ts:34-88. Identify exactly which config sources can setANTHROPIC_BASE_URLandNODE_EXTRA_CA_CERTSbeforeTrustDialogruns, and trace howapplyConfigEnvironmentVariables()invalidates cached TLS/proxy state after trust is granted. -
Inspect the distributed cleanup registry: Run:
rg -n "registerCleanup\(" entrypoints/ utils/ services/ main.tsxPick three callers (including
utils/sessionStorage.ts:448-464) and trace what happens if one cleanup hangs for 10 seconds duringgracefulShutdown()whileCLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MSis set to8000. What are the exact timeout budgets for Phase 1, Phase 2, Phase 4, and the outer failsafe timer?
Manuscript chapters/22-cold-start-mastery-cli-init-main.md from AtlantisPleb/cc at 5aa286a, synced Nov 24, 2026.