InkdownInkdown
Start writing

Claude-Code

62 files·4 subfolders

Shared Workspace

Claude-Code
codex

01-entry-points

Shared from "Claude-Code" on Inkdown

Entry Points & Initialization

How the application starts up, parses arguments, and boots into a session.


The Boot Sequence

Plain text
Process starts
    │
    ▼
main.tsx (top-level side effects)
    ├─ profileCheckpoint('main_tsx_entry')
    ├─ startMdmRawRead()        — parallel MDM subprocess (macOS)
    ├─ startKeychainPrefetch()  — parallel keychain reads (macOS)
    │
    ▼
main.tsx imports (~135ms of module evaluation)
    │
    ▼
main() function
    ├─ Security: NoDefaultCurrentDirectoryInExePath (Windows)
    ├─ Initialize warning handler
    ├─ Handle deep link URIs (cc://, cc+unix://, --handle-uri)
    ├─ Handle `claude assistant [sessionId]` (KAIROS feature)
    ├─ Handle `claude ssh <host> [dir]` (SSH_REMOTE feature)
    ├─ Determine interactive vs non-interactive mode
    ├─ Set client type (cli, sdk-cli, github-action, remote, etc.)
    ├─ Eager-load settings from --settings flag
    │
    ▼
run() — Commander.js CLI setup
    │
    ▼
preAction hook (fires when a command executes)
    ├─ await MDM + keychain prefetches
    ├─ init() — core initialization
    ├─ process.title = 'claude'
    ├─ initSinks() — logging/analytics sinks
    ├─ Wire --plugin-dir to inline plugins
    ├─ runMigrations() — settings migrations
    ├─ loadRemoteManagedSettings() (non-blocking)
    ├─ loadPolicyLimits() (non-blocking)
    └─ Upload user settings (if enabled)
    │
    ▼
Default command handler
    ├─ setup() — session initialization
    └─ render REPL or run headless
0000_start_here_index_and_recommended_reading_order.md
0100_project_overview_tech_stack_runtime_modes_and_folder_map.md
0200_startup_flow_entry_points_and_cold_start_sequence.md
0300_codebase_modules_layers_state_models_and_schemas.md
0400_system_architecture_and_design_rationale.md
0500_interactive_repl_request_flow_end_to_end.md
0600_headless_sdk_and_print_mode_request_flow_end_to_end.md
0700_mcp_integration_connection_and_tool_call_flow.md
0800_external_services_sdks_storage_and_local_dependencies.md
0900_environment_variables_settings_feature_flags_and_failure_modes.md
1000_non_obvious_patterns_gotchas_and_debugging_traps.md
1100_full_codebase_file_inventory_grouped_by_directory.md
kimi
00-overview.md
01-entrypoints.md
02-state-management.md
03-query-system.md
04-tools-system.md
05-tasks-system.md
06-ui-components.md
07-bridge-remote.md
08-services.md
09-skills-plugins.md
10-commands.md
11-testing-architecture.md
12-permission-system.md
13-build-system.md
14-ink-internals.md
15-git-internals.md
16-context-compaction.md
17-vim-mode.md
18-mailbox-notifications.md
19-session-persistence.md
20-hooks-system.md
21-error-recovery.md
README.md
qwen
00-overview.md
01-entry-points.md
02-query-engine.md
03-tools-and-tasks.md
04-commands-and-skills.md
05-state-management.md
06-ink-rendering.md
07-bridge-remote.md
08-mcp-services.md
09-services-overview.md
10-multi-agent.md
11-system-prompt-constants.md
12-tool-interface.md
13-memory-system.md
14-buddy-companion.md
15-keybindings.md
16-stop-hooks.md
17-vim-mode.md
18-upstreamproxy.md
19-cost-tracking-history.md
20-contexts-styles-onboarding.md
21-hooks.md
22-screens.md
tweets-explain
claude-code-memory-analysis.md
compact
memory-system
agentic-architecture

main.tsx — The Main Entry

Location: src/main.tsx (2000+ lines, the largest file)

Key Responsibilities
  1. Startup optimization: Fires parallel subprocesses (MDM, keychain) at the very top of the file so they complete during module import time (~135ms window).

  2. Feature flag gating: Uses feature('FLAG_NAME') from bun:bundle for dead code elimination. Many features are compiled out of the external build:

    • KAIROS — assistant mode
    • COORDINATOR_MODE — multi-agent orchestration
    • BRIDGE_MODE — remote control
    • VOICE_MODE — voice input
    • SSH_REMOTE — SSH remote sessions
    • DIRECT_CONNECT — direct connect server
    • And many more
  3. URL/deep link handling: Processes cc:// and cc+unix:// URLs for direct connect, and --handle-uri for OS protocol handler integration.

  4. SSH mode: Parses claude ssh <host> [dir] and stashes host/dir for the REPL to pick up. Supports --local, --dangerously-skip-permissions, --permission-mode, --resume, --continue, --model.

  5. Client type detection: Determines how the app was launched:

    • cli — direct terminal usage
    • sdk-cli — non-interactive SDK call
    • github-action — running in GitHub Actions
    • sdk-typescript / sdk-python — SDK usage
    • claude-vscode / claude-desktop — IDE integration
    • remote — remote session via WebSocket
    • local-agent — Desktop's local agent mode
  6. Commander.js setup: Defines all CLI flags and subcommands.

Commander.js Structure
TypeScript
program
  .name('claude')
  .argument('[prompt]')
  .option('-d, --debug [filter]')
  .option('-p, --print')              // headless mode
  .option('--dangerously-skip-permissions')
  .option('--permission-mode <mode>')  // yolo, default, plan, etc.
  .option('--model <model>')
  .option('--settings <path|json>')
  .option('--worktree')
  .option('--continue')
  .option('--resume <sessionId>')
  .option('--add-dir <dir>')
  .option('--plugin-dir <dir>')
  // ... many more options
  .action(defaultAction)              // main interactive/headless path
  // Subcommands: mcp, plugin, auth, doctor, etc.

setup.ts — Session Initialization

Location: src/setup.ts (477 lines)

Called after CLI parsing, before the REPL renders. Sets up the session environment.

What setup() Does
  1. Node version check: Requires Node.js 18+

  2. Session ID: Switches to custom session ID if provided

  3. UDS Messaging Server (Unix Domain Sockets): Starts a local socket server for inter-process communication (Mac/Linux only). Used for swarm teammate communication.

  4. Terminal backup restoration: If a previous setup was interrupted (iTerm2 or Terminal.app), restores original settings.

  5. Set CWD: The most critical call — setCwd(cwd) must happen before anything else that depends on the working directory.

  6. Hooks config snapshot: Captures the current hooks configuration to detect hidden modifications later.

  7. Worktree creation (if --worktree flag):

    • Creates a git worktree (or delegates to WorktreeCreate hook for non-git VCS)
    • Optionally creates a tmux session
    • Switches CWD to the worktree path
    • Sets projectRoot to the worktree
  8. Background jobs:

    • initSessionMemory() — registers memory extraction hooks
    • initContextCollapse() — initializes context collapse service
    • lockCurrentVersion() — prevents deletion by other processes
  9. Plugin prefetch: Loads plugin hooks and sets up hot reload

  10. Attribution hooks (ant-only): Registers commit attribution tracking

  11. Team memory sync watcher: Starts watching for team memory changes

  12. Analytics beacon: Emits tengu_started event (earliest reliable "process started" signal)

  13. API key prefetch: Prefetches if trust is already established

  14. Release notes check: Pre-fetches data for the logo/release notes display

  15. Bypass permissions verification: If --dangerously-skip-permissions, verifies sandbox/isolated environment (Docker, no internet, not root)

  16. Previous session telemetry: Logs tengu_exit from the last session (cost, duration, tokens, FPS)


Migrations

Location: src/migrations/

Run at startup to migrate user settings/config between versions. Current migration version: 11.

Migrations include:

  • migrateAutoUpdatesToSettings — moved auto-update setting to settings.json
  • migrateBypassPermissionsAcceptedToSettings — moved to settings
  • migrateEnableAllProjectMcpServersToSettings — moved to settings
  • resetProToOpusDefault — changed default model
  • migrateSonnet1mToSonnet45 — model string migration
  • migrateLegacyOpusToCurrent — model string migration
  • migrateSonnet45ToSonnet46 — model string migration
  • migrateOpusToOpus1m — model string migration
  • migrateReplBridgeEnabledToRemoteControlAtStartup — renamed setting
  • resetAutoModeOptInForDefaultOffer — auto-mode reset
  • migrateFennecToOpus — ant-only model migration
  • migrateChangelogFromConfig — async, fire-and-forget

Entrypoints

Location: src/entrypoints/

Different ways the application can be launched:

FilePurpose
cli.tsxStandard CLI entry (interactive TUI)
init.tsCore initialization (auth, settings, telemetry)
mcp.tsMCP server mode (claude mcp serve)
sandboxTypes.tsType definitions for sandboxed execution
agentSdkTypes.tsType definitions for agent SDK
sdk/SDK-specific entrypoints
init.ts — Core Initialization

The init() function (called from the preAction hook) handles:

  • Loading settings from all sources (global, project, user, policy, MDM, remote)
  • Applying environment variables from managed settings
  • Initializing telemetry (Statsig/GrowthBook)
  • Setting up the analytics meter and counters
  • Initializing the file system watcher
  • Setting up the native installer version lock

Interactive vs Non-Interactive Mode

Interactive Mode (default)
  • Renders the full TUI with Ink
  • User types prompts, sees streaming responses
  • Commands available via slash commands and keyboard shortcuts
  • Permission prompts for tool execution
Non-Interactive Mode (-p / --print)
  • Headless output — no TUI
  • Used by SDK integrations, CI/CD, scripts
  • Output format: text, stream-json, or markdown
  • Trust dialog is skipped (execution is implicitly trusted)
  • Entry point set to sdk-cli

Key Files Reference

FileLinesPurpose
src/main.tsx~2000CLI entry, Commander.js setup, feature flags
src/setup.ts477Session initialization
src/entrypoints/init.ts~200Core init (auth, settings, telemetry)
src/entrypoints/cli.tsx~100Interactive CLI entry
src/interactiveHelpers.tsx~300Render context, setup screens, exit handling
src/replLauncher.tsx~200Launches the REPL component
src/dialogLaunchers.tsx~100Dialog/wizard launchers
src/migrations/variesStartup migrations