> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch11-gateway-server-architecture/11.2-server-startup-flow-source-analysis.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 11.2 Server Startup Flow Source Code Analysis

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~160,000 tokens, Output \~12,000 tokens (chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

Understanding Gateway's startup flow is understanding "how an OpenClaw instance comes to life from nothing." This section will trace every step from the `openclaw gateway` command to Gateway being fully ready.

## 11.2.1 Entry File `src/entry.ts`

Everything starts from `src/entry.ts`. When a user runs `openclaw gateway`:

```typescript
// src/entry.ts (simplified)
process.title = "openclaw";           // Set process title
installProcessWarningFilter();        // Filter Node.js experimental warnings
normalizeEnv();                       // Normalize environment variables

// Handle experimental warning suppression
if (!ensureExperimentalWarningSuppressed()) {
  // Parse CLI Profile arguments (--profile dev, etc.)
  const parsed = parseCliProfileArgs(process.argv);
  if (parsed.profile) {
    applyCliProfileEnv({ profile: parsed.profile });
  }

  // Dynamically import CLI main module and start
  import("./cli/run-main.js")
    .then(({ runCli }) => runCli(process.argv));
}
```

`ensureExperimentalWarningSuppressed()` is an interesting implementation: Node.js's `--disable-warning=ExperimentalWarning` flag cannot be passed through `NODE_OPTIONS` (Node.js security restriction), so OpenClaw detects when needed and **respawns itself**, adding this flag to the new process's command-line arguments. This is prevented from infinite recursion through the `OPENCLAW_NODE_OPTIONS_READY` environment variable.

## 11.2.2 Gateway CLI Startup

The CLI framework uses **Commander.js**. `src/cli/program.ts` exports `buildProgram()`, which registers all subcommands. The Gateway command is registered in `src/cli/gateway-cli/register.ts`.

When a user executes `openclaw gateway --port 18789`, Commander parses the arguments and calls the Gateway startup function. Key parameters include:

```
--port <number>       # WebSocket/HTTP port (default 18789)
--bind <mode>         # Bind mode: loopback (default) | lan | 0.0.0.0
--verbose             # Verbose logging
--reset               # Reset sessions before startup
--allow-unconfigured  # Allow startup without configuration (Docker scenario)
--token <string>      # Gateway authentication token
```

## 11.2.3 Server Startup Sequence

The core startup logic is in the `startGatewayServer()` function in `src/gateway/server.impl.ts`. This is a large async function that executes the following steps:

### Phase One: Configuration Loading and Validation

```typescript
// 1. Migrate legacy configuration format
migrateLegacyConfig();

// 2. Load and validate configuration
const cfg = loadConfig();

// 3. Read configuration file snapshot (for hot-reload comparison)
const configSnapshot = readConfigFileSnapshot();

// 4. Parse runtime configuration
const runtimeConfig = resolveGatewayRuntimeConfig({
  cfg, port, bind, ...options
});
```

### Phase Two: Infrastructure Initialization

```typescript
// 5. Create subsystem loggers
const log = createSubsystemLogger("gateway");
const logChannels = log.child("channels");
const logCron = log.child("cron");
// ... (a dozen more subsystem loggers)

// 6. Load plugins
const pluginRegistry = loadGatewayPlugins({ cfg, log: logPlugins });

// 7. Initialize sub-agent registry
initSubagentRegistry(cfg);

// 8. Load model catalog
const modelCatalog = await loadGatewayModelCatalog({ cfg });

// 9. Create runtime state
const runtimeState = createGatewayRuntimeState({ cfg, runtimeConfig });
```

### Phase Three: Network Layer Startup

```typescript
// 10. Parse TLS configuration
const tlsRuntime = loadGatewayTlsRuntime({ cfg });

// 11. Create HTTP(S) server
const httpServer = tlsRuntime
  ? createHttpsServer(tlsRuntime.options)
  : createHttpServer();

// 12. Create WebSocket server (mounted on HTTP server)
const wss = new WebSocketServer({ noServer: true });

// 13. Bind port and listen
httpServer.listen(port, bindAddress);
```

### Phase Four: Event and Service Binding

```typescript
// 14. Attach WebSocket connection handlers
attachGatewayWsHandlers({
  wss, clients, port,
  resolvedAuth,
  gatewayMethods: listGatewayMethods(),
  events: GATEWAY_EVENTS,
  extraHandlers: coreGatewayHandlers,
  broadcast,
  context,
  // ...
});

// 15. Set up HTTP routes
// - OpenAI compatible API
// - Open Responses API
// - Console UI static files
// - Canvas/A2UI
// - Webhook endpoints
// - Slack HTTP callbacks

// 16. Start Cron service
const cronService = buildGatewayCronService({ cfg, ... });

// 17. Start configuration hot-reload listener
startGatewayConfigReloader({ cfg, ... });

// 18. Create channel manager
const channelManager = createChannelManager({ cfg, ... });
```

### Phase Five: Sidecar Services Startup

`startGatewaySidecars()` in `src/gateway/server-startup.ts` starts auxiliary services:

```typescript
// 19. Start browser control server (if enabled)
const browserControl = await startBrowserControlServerIfEnabled();

// 20. Start Gmail Watcher (if configured)
await startGmailWatcher(cfg);

// 21. Load and validate internal hooks
const hooks = await loadInternalHooks({ cfg, ... });

// 22. Start channel connections
await startChannels();  // WhatsApp, Telegram, Discord, Slack...

// 23. Start Tailscale exposure (if configured)
await startGatewayTailscaleExposure({ cfg, ... });

// 24. Start service discovery (Bonjour/mDNS)
await startGatewayDiscovery({ cfg, port, ... });

// 25. Start heartbeat
startHeartbeatRunner({ ... });

// 26. Start maintenance timers
startGatewayMaintenanceTimers({ ... });

// 27. Trigger gateway_start plugin hook
triggerInternalHook(createInternalHookEvent("gateway:start"));
```

### Phase Six: Startup Log Output

`logGatewayStartup()` in `src/gateway/server-startup-log.ts` prints the startup summary:

```
🦞 OpenClaw Gateway v2026.2.6-3
   Port:     18789
   Bind:     127.0.0.1 (loopback)
   Model:    anthropic/claude-opus-4-6
   Channels: whatsapp, telegram, discord
   Skills:   12 loaded
   Plugins:  memory-core
   Canvas:   :18793
   Ready in: 2.4s
```

## 11.2.4 Server Implementation Class

`src/gateway/server.impl.ts` is one of the largest files in the entire Gateway. The import list at the top of the file has over 80 lines, involving almost all subsystems.

It exports two key types:

```typescript
export type GatewayServer = {
  close: () => Promise<void>;
  port: number;
  // ...
};

export type GatewayServerOptions = {
  port: number;
  bind: string;
  verbose: boolean;
  // ...
};
```

`startGatewayServer()` returns a `GatewayServer` object containing the close method and runtime metadata. This allows Gateway to be started and stopped programmatically—particularly important in E2E testing.

The subsystem logger creation pattern is worth noting:

```typescript
const log = createSubsystemLogger("gateway");
const logCanvas = log.child("canvas");
const logDiscovery = log.child("discovery");
const logTailscale = log.child("tailscale");
const logChannels = log.child("channels");
const logBrowser = log.child("browser");
const logHealth = log.child("health");
const logCron = log.child("cron");
const logReload = log.child("reload");
const logHooks = log.child("hooks");
const logPlugins = log.child("plugins");
const logWsControl = log.child("ws");
```

Each subsystem has its own logger, created via `.child()`. This allows log output to be filtered by subsystem, which is very useful when debugging.
