Skip to content

Gateway Quickstart: Launch Your AI Assistant Service

What You'll Learn

By completing this tutorial, you will be able to:

  • Understand the Gateway's core architecture and WebSocket control plane concept
  • Start and configure the Gateway service using CLI
  • Protect Gateway access with Token or Password authentication
  • Manage the lifecycle of multiple channels (WhatsApp, Telegram, Slack, etc.)
  • Interact with Gateway using WebSocket clients
  • Enable secure remote access using Tailscale

Core Concepts

OpenClaw Gateway serves as the central control plane of the system, unifying the coordination of all AI sessions, messaging channels, tools, and events. Think of it as a traffic hub where all messages (from WhatsApp, Telegram, etc.) converge, are processed by Pi Agent, and responses are returned.

Gateway Architecture Overview

┌─────────────────────────────────────────────────────────────┐
│                    OpenClaw Gateway                         │
│                   (ws://127.0.0.1:18789)                   │
├──────────────┬──────────────┬──────────────┬────────────────┤
│   Channels   │   Sessions   │    Tools     │   Control UI   │
│  (Channels)  │  (Sessions)  │   (Tools)    │  (Web UI)      │
├──────────────┴──────────────┴──────────────┴────────────────┤
│              Pi Agent Runtime (RPC Communication Layer)      │
└─────────────────────────────────────────────────────────────┘
         │                     │                     │
         ▼                     ▼                     ▼
   WhatsApp/Telegram     Browser/CDP          Mobile/Node
   Slack/Discord         Canvas/Shell         Devices

Key Component Descriptions:

ComponentFunctionSource Location
WebSocket ServerUnified control plane protocolsrc/gateway/server.impl.ts:157
HTTP APIOpenAI-compatible interfacesrc/gateway/openresponses-http.ts
Channel ManagerMulti-channel lifecycle managementsrc/gateway/server-channels.ts:64
Session ResolverSession key resolution and routingsrc/gateway/sessions-resolve.ts:18
Chat HandlerAgent events and streaming responsessrc/gateway/server-chat.ts:220

Default Port Configuration

ServicePortDescription
Gateway WebSocket/HTTP18789Main control plane port
Canvas Host18793Visualization interface service
Browser ControlDynamically assignedChrome DevTools Protocol

Port Conflict Resolution

If port 18789 is occupied, Gateway will attempt to increment the port. You can also specify a different port using the --port parameter.

Prerequisites

Before starting Gateway, please confirm:

  1. ✅ Initial configuration with openclaw onboard is complete
  2. ✅ Node.js version ≥ 22.12.0
  3. ✅ Configuration file is located at ~/.openclaw/openclaw.json
  4. ✅ At least one AI model provider is configured (Anthropic/OpenAI)

Quick Check Commands:

bash
# Check OpenClaw version
openclaw --version

# Verify configuration validity
openclaw doctor

# View Gateway port configuration
openclaw config get gateway.port

# View complete Gateway configuration
openclaw config get gateway

Starting Gateway

Use the openclaw config command to launch the interactive configuration wizard:

bash
# Launch full configuration wizard
openclaw config

# Or configure only Gateway-related sections
openclaw config --section gateway --section tailscale

The configuration wizard will guide you through the following settings:

ConfigurationOptionsDescription
PortCustom numberDefault 18789
Bind Modeloopback / lan / tailnet / auto / customSee detailed explanation below
Auth Modetoken / passwordToken mode recommended
Tailscaleoff / serve / funnelOptional remote access

Bind Mode Details (from src/config/types.gateway.ts:249-268):

ModeBind AddressUse Case
loopback127.0.0.1Local access only (most secure)
lan0.0.0.0Access within local network
tailnetTailscale IPAccess via Tailscale
autoAuto-selectPrefer loopback, fall back to lan
customCustom IPSpecify a particular address

Method 2: Quick Start (With Existing Configuration)

bash
# Start with default configuration
openclaw gateway

# Specify port and bind mode
openclaw gateway --port 8080 --bind loopback

# Run in foreground (view logs)
openclaw gateway --foreground

You Should See:

┌─────────────────────────────────────────┐
│  OpenClaw Gateway v2026.2.13            │
│  ✓ WebSocket: ws://127.0.0.1:18789     │
│  ✓ Control UI: http://127.0.0.1:18789  │
│  ✓ Auth: Token (mode: token)           │
│  ✓ Channels: 0 running                 │
└─────────────────────────────────────────┘

Method 3: Programmatic Start

Reference: src/gateway/server.impl.ts:157:

typescript
import { startGatewayServer } from "openclaw/gateway";

const server = await startGatewayServer(18789, {
  bind: "loopback",
  controlUiEnabled: true,
  openAiChatCompletionsEnabled: true,
  openResponsesEnabled: true,
  auth: {
    mode: "token",
    token: "your-secure-token",
  },
});

// Shutdown Gateway
await server.close({ reason: "manual shutdown" });

Configuration Details

Gateway Configuration Structure

Configuration file path: ~/.openclaw/openclaw.json

json
{
  "gateway": {
    "port": 18789,
    "mode": "local",
    "bind": "loopback",
    "auth": {
      "mode": "token",
      "token": "your-generated-token",
      "allowTailscale": false,
      "rateLimit": {
        "maxAttempts": 10,
        "windowMs": 60000,
        "lockoutMs": 300000,
        "exemptLoopback": true
      }
    },
    "tailscale": {
      "mode": "off",
      "resetOnExit": false
    },
    "controlUi": {
      "enabled": true,
      "basePath": "/",
      "allowedOrigins": ["http://localhost:3000"]
    },
    "http": {
      "endpoints": {
        "chatCompletions": { "enabled": true },
        "responses": { "enabled": true }
      }
    }
  }
}

Authentication Mode Comparison

Based on src/config/types.gateway.ts:79-92:

FeatureToken ModePassword Mode
Use CaseDevelopment/automation scriptsMulti-user sharing/remote access
SecurityHigh (random string)Medium (depends on password strength)
Tailscale FunnelNot supportedRequired
CLI UsageOPENCLAW_GATEWAY_TOKENInteractive input
Browser AccessURL parameter or HeaderLogin form

Token Generation Recommendations (from src/commands/onboard-helpers.ts):

bash
# Generate a 64-character random token
openssl rand -hex 32

# Set environment variable
echo 'export OPENCLAW_GATEWAY_TOKEN="your-token"' >> ~/.zshrc

Rate Limit Configuration

json
{
  "gateway": {
    "auth": {
      "rateLimit": {
        "maxAttempts": 10,      // Max failed attempts within window
        "windowMs": 60000,      // Sliding window: 1 minute
        "lockoutMs": 300000,    // Lockout duration: 5 minutes
        "exemptLoopback": true  // Exempt local addresses
      }
    }
  }
}

Production Environment Recommendations

For Gateway exposed to the public internet, be sure to enable rateLimit and consider using TLS.

Session Management

Session Concepts

OpenClaw uses Sessions to isolate context for different Agents. Each session contains:

  • Conversation history
  • Agent configuration
  • Tool state
  • Memory data

Session Resolution Strategies

Based on src/gateway/sessions-resolve.ts:18-139:

IdentifierPriorityExample
keyHighest@alice/pi-main
sessionIdMediumsess_abc123
labelLowWork Assistant

CLI Session Operations

bash
# List all sessions
openclaw sessions list

# View session details
openclaw sessions preview --key @alice/pi-main

# Reset session (retain configuration, clear history)
openclaw sessions reset --key @alice/pi-main

# Delete session
openclaw sessions delete --key @alice/pi-main

# Compact session (reduce storage footprint)
openclaw sessions compact --key @alice/pi-main

Session WebSocket API

javascript
// List sessions
ws.send(JSON.stringify({
  method: "sessions.list",
  params: { includeGlobal: true }
}));

// Response format
{
  "sessions": [
    {
      "key": "@alice/pi-main",
      "sessionId": "pi-main",
      "agentId": "pi",
      "label": "Main Assistant",
      "messageCount": 42,
      "lastActiveAt": "2026-02-14T10:30:00Z"
    }
  ]
}

Channel Management

Channel Lifecycle

Based on src/gateway/server-channels.ts:64-308 (ChannelManager):

Config Loading → Account Resolution → Account Startup → Runtime Monitoring → Stop/Restart
      │                │                  │                │                 │
      ▼                ▼                  ▼                ▼                 ▼
  loadConfig    resolveAccount     startAccount       runtime         stopAccount

View Channel Status

bash
# View status of all channels
openclaw channels status

# Deep probe (check connection health)
openclaw channels status --probe

# Start specific channel
openclaw channels start whatsapp

# Stop channel
openclaw channels stop telegram

Status Output Example:

┌───────────┬─────────┬───────────┬─────────────────┐
│ Channel   │ Status  │ Account   │ Last Error      │
├───────────┼─────────┼───────────┼─────────────────┤
│ whatsapp  │ ✓ running│ default  │ -               │
│ telegram  │ ✗ stopped│ bot1     │ not configured  │
│ slack     │ ✗ stopped│ -        │ disabled        │
│ discord   │ ✓ running│ main     │ -               │
└───────────┴─────────┴───────────┴─────────────────┘

Channel Runtime State

Each channel account maintains the following runtime state (ChannelAccountSnapshot):

FieldTypeDescription
accountIdstringAccount identifier
runningbooleanWhether running
connectedbooleanWhether connected
lastStartAtnumberLast startup timestamp
lastStopAtnumberLast shutdown timestamp
lastErrorstringLast error message

API Endpoint Details

WebSocket Control Plane

Connection address: ws://127.0.0.1:18789

Connection Flow:

javascript
const ws = new WebSocket('ws://127.0.0.1:18789');

// 1. Wait for connection challenge
ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  
  if (msg.event === 'connect.challenge') {
    // 2. Send authentication response
    ws.send(JSON.stringify({
      method: 'auth',
      params: {
        token: 'your-gateway-token'  // or password
      }
    }));
  }
  
  if (msg.event === 'agent') {
    // Handle Agent event stream
    console.log('Agent event:', msg.data);
  }
};

Gateway Method List

Based on src/gateway/server-methods-list.ts:3-97:

Core Methods:

MethodDescription
healthHealth check
statusComplete status report
channels.statusChannel status query
config.get/setConfiguration read/write
sessions.list/preview/patchSession management
agents.list/create/update/deleteAgent management
skills.status/install/updateSkill management
cron.list/add/remove/runScheduled tasks
browser.requestBrowser control

Event Subscriptions (GATEWAY_EVENTS):

EventTrigger Timing
connect.challengeConnection authentication challenge
agentAgent event stream
chatChat messages
presenceOnline status changes
healthHealth status updates
node.pair.requestedNode pairing request
exec.approval.requestedExecution approval request

HTTP API (OpenAI Compatible)

Based on src/gateway/openresponses-http.ts:

bash
# Chat Completions API
curl http://127.0.0.1:18789/v1/chat/completions \
  -H "Authorization: Bearer your-token" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-3-5-sonnet",
    "messages": [{"role": "user", "content": "Hello"}]
  }'

# OpenResponses API
curl http://127.0.0.1:18789/v1/responses \
  -H "Authorization: Bearer your-token" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-3-5-sonnet",
    "input": "What is OpenClaw?"
  }'

Enabling HTTP API

By default, the HTTP API is disabled and must be enabled in configuration:

json
{
  "gateway": {
    "http": {
      "endpoints": {
        "chatCompletions": { "enabled": true },
        "responses": { "enabled": true }
      }
    }
  }
}

Best Practices

1. Security Configuration Checklist

markdown
□ Use Token authentication instead of Password (unless Tailscale Funnel is needed)
□ Enable rateLimit to prevent brute force attacks
□ Use TLS in production (configure certPath/keyPath)
□ Limit trustedProxies to known reverse proxy IPs
□ Regularly rotate Gateway Token

2. Performance Optimization Recommendations

ScenarioRecommendation
High concurrencyIncrease rateLimit.maxAttempts and windowMs
Large file uploadsAdjust http.endpoints.responses.maxBodyBytes
Frequent restartsUse reload.mode: "hot" for hot reloading
Multiple channelsStart channels on-demand, avoid running too many simultaneously

3. Troubleshooting Workflow

Gateway won't start?

    ├─→ Check port occupancy: lsof -i :18789

    ├─→ Check configuration validity: openclaw doctor

    ├─→ View detailed logs: openclaw gateway --foreground

    └─→ Reset configuration: openclaw config reset

4. Production Deployment Recommendations

bash
# Use systemd service (Linux)
sudo cat > /etc/systemd/system/openclaw-gateway.service << 'EOF'
[Unit]
Description=OpenClaw Gateway
After=network.target

[Service]
Type=simple
User=openclaw
Environment="OPENCLAW_STATE_DIR=/var/lib/openclaw"
Environment="OPENCLAW_GATEWAY_TOKEN_FILE=/etc/openclaw/token"
ExecStart=/usr/bin/openclaw gateway --bind loopback --port 18789
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl enable --now openclaw-gateway

Checkpoints ✅

Complete the following verifications to ensure Gateway is running properly:

  1. Gateway Startup Check:

    bash
    curl -H "Authorization: Bearer your-token" \
      http://127.0.0.1:18789/v1/health

    Expected return: {"status":"ok"}

  2. WebSocket Connection Check:

    bash
    # Test using wscat
    wscat -c ws://127.0.0.1:18789 \
      -H "Authorization: Bearer your-token"
  3. Channel Status Check:

    bash
    openclaw channels status --probe

Lesson Summary

In this tutorial, you learned:

  • Gateway Architecture: WebSocket control plane unifies Channels, Sessions, and Tools
  • Startup Methods: Interactive configuration, CLI parameters, and programmatic startup
  • Authentication Mechanisms: Token (recommended) and Password mode selection
  • Session Management: Resolution strategies based on key/sessionId/label
  • Channel Lifecycle: Complete flow from start → runtime → stop
  • API Interfaces: WebSocket methods, HTTP OpenAI-compatible interface

Next Step

Continue with Sending Your First Message to experience your first conversation with the AI assistant.


Appendix: Source Code Reference

Click to Expand Source Locations

Last updated: 2026-02-14

FunctionFile PathLine
Gateway config commandsrc/commands/configure.gateway.ts17-229
Gateway server startupsrc/gateway/server.impl.ts157-673
Channel managersrc/gateway/server-channels.ts64-308
Session resolversrc/gateway/sessions-resolve.ts18-139
Chat event handlersrc/gateway/server-chat.ts220-418
Gateway method listsrc/gateway/server-methods-list.ts3-119
Gateway config typessrc/config/types.gateway.ts249-286
WebSocket runtimesrc/gateway/server-ws-runtime.ts9-53
Auth config buildersrc/commands/configure.gateway-auth.ts-

Key Constants:

  • DEFAULT_GATEWAY_PORT = 18789: Default Gateway port
  • DEFAULT_CANVAS_PORT = 18793: Default Canvas host port

Key Functions:

  • startGatewayServer(port, opts): Gateway server entry point
  • createChannelManager(opts): Channel manager factory function
  • resolveSessionKeyFromResolveParams(params): Session key resolution
  • createAgentEventHandler(options): Agent event handler