OpenClaw for Developers: Architecture, CLI, and API Reference
OpenClaw is more than a personal AI assistant. It's a platform for building agentic systems. This guide explains the architecture, session lifecycle, tool system, CLI commands, and HTTP APIs for developers building on OpenClaw.
Architecture Overview
High-Level Design
┌─────────────────────────────────────────────────┐
│ Messaging Channels │
│ Telegram | WhatsApp | Discord | Slack | ... │
└─────────────────┬───────────────────────────────┘
│
┌────────▼────────┐
│ Gateway │
│ (Node.js) │
└────────┬────────┘
│
┌────────▼────────┐
│ Session Mgr │
└────────┬────────┘
│
┌─────────────┼─────────────┐
│ │ │
┌───▼───┐ ┌────▼────┐ ┌────▼────┐
│Agent 1│ │Agent 2 │ │Agent N │
│Workspace│ │Workspace│ │Workspace│
└───┬───┘ └────┬────┘ └────┬────┘
│ │ │
└────────────┼─────────────┘
│
┌───────▼────────┐
│ Model API │
│ (Anthropic/ │
│ OpenAI/etc.) │
└─────────────────┘
Components
Data Flow
Session Lifecycle
Session Creation
const session = await sessionManager.createSession({
agent: "main",
channel: "telegram",
userId: "123456"
});
What happens:
agent:main:telegram:123456/home/user/clawdAGENTS.md, SOUL.md, MEMORY.md, memory/YYYY-MM-DD.mdMessage Processing
const response = await session.send({
role: "user",
content: "What's the weather in SF?"
});
Flow:
exec curl wttr.in/SF)Context Compaction
When context exceeds limits:
memory/YYYY-MM-DD.mdSession Termination
await session.close();
Cleanup:
Tool System
Tools extend what the assistant can do. OpenClaw provides built-in tools and supports custom tools.
Built-In Tools
- read - read file contents
- write - write/create files
- edit - precise edits via search/replace
- exec - execute shell commands
- browser - control headless Chromium
- web_search - Brave Search API
- web_fetch - fetch page content (Readability)
- nodes - camera, screen, location (mobile nodes)
- message - send messages to channels
- subagents - spawn background agents
Tool Definition (TypeBox Schema)
Tools are defined using TypeBox:
import { Type } from '@sinclair/typebox';
const ReadTool = Type.Object({
file_path: Type.String({ description: 'Path to file' }),
offset: Type.Optional(Type.Number({ description: 'Line offset' })),
limit: Type.Optional(Type.Number({ description: 'Max lines' }))
});
OpenClaw converts this to JSON Schema for the model.
Invoking Tools
Model calls tools via function calling:
{
"tool_use": {
"name": "read",
"input": {
"file_path": "/home/user/notes.md"
}
}
}
Gateway executes:
const result = await tools.read({ file_path: '/home/user/notes.md' });
Returns content to model.
Custom Tools (via Skills)
Create a skill with scripts:
skills/crypto-price/SKILL.md:
## Get Bitcoin Pricebash
curl -s https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd | jq -r .bitcoin.usd
The assistant reads this and runs the command when needed.
Configuration Reference
Config File Location
~/.openclaw/openclaw.json
Top-Level Keys
agents- agent definitions and defaultschannels- Telegram, WhatsApp, Discord configgateway- port, bind, tailscaletools- tool policy, sandbox settingsqmd- memory search collectionswebhooks- webhook endpointsbrowser- browser control settings
Example Config
{
"agents": {
"defaults": {
"model": {
"primary": "anthropic/claude-opus-4-6",
"fallbacks": ["anthropic/claude-sonnet-4-5"]
},
"workspace": "/home/user/clawd",
"contextTokens": 200000,
"timeoutSeconds": 600
},
"list": [
{ "id": "main", "default": true }
]
},
"channels": {
"telegram": {
"enabled": true,
"botToken": "...",
"dmPolicy": "pairing"
}
},
"gateway": {
"port": 18789,
"bind": "127.0.0.1"
},
"tools": {
"sandbox": {
"mode": "non-main"
}
}
}
Validate Config
openclaw doctor
Reports syntax errors and missing fields.
CLI Reference
Gateway Management
openclaw gateway --port 18789 # Start gateway
openclaw gateway stop # Stop gateway
openclaw gateway restart # Restart gateway
openclaw status # Check status
openclaw status --deep # Detailed status
Configuration
openclaw config get agents.defaults.model
openclaw config set agents.defaults.model.primary "openai/gpt-5.2"
openclaw configure # Interactive wizard
Sessions
openclaw sessions list
openclaw sessions history --session agent:main:main
openclaw sessions prune --older-than 7d
Memory
openclaw memory search "query"
openclaw memory index
openclaw memory index --force
openclaw memory status
Cron Jobs
openclaw cron add --name job-name --schedule "0 9 * * *" --message "..."
openclaw cron list
openclaw cron runs --name job-name
openclaw cron edit <id> --schedule "..."
openclaw cron delete <id>
Webhooks
openclaw webhooks add --name hook-name --path /webhooks/test
openclaw webhooks list
openclaw webhooks logs --name hook-name
Security
openclaw security audit
openclaw security audit --deep
openclaw security audit --fix
Channels
openclaw channels login
openclaw channels logout
openclaw channels list
Models
openclaw models list
openclaw models test --model anthropic/claude-opus-4-6
Logs
openclaw logs --tail 50
openclaw logs --follow
openclaw logs --since "2 hours ago"
HTTP APIs
OpenResponses API
Chat completions endpoint (OpenAI-compatible):
curl http://127.0.0.1:18789/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-opus-4-6",
"messages": [
{"role": "user", "content": "Hello!"}
]
}'
Response:
{
"id": "chatcmpl-123",
"object": "chat.completion",
"model": "anthropic/claude-opus-4-6",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I help you?"
}
}
]
}
Tools Invoke API
Direct tool invocation:
curl http://127.0.0.1:18789/api/tools/invoke \
-H "Content-Type: application/json" \
-d '{
"tool": "read",
"input": {
"file_path": "/home/user/notes.md"
}
}'
Response:
{
"result": "# Notes\n\nSome content here..."
}
Health Check
curl http://127.0.0.1:18789/health
Response:
{
"status": "healthy",
"uptime": 12345,
"version": "2026.3.4",
"sessions": 3
}
Building on OpenClaw
Use Case: Custom Bot
Build a custom bot using the OpenResponses API:
import fetch from 'node-fetch';
async function chat(message) {
const resp = await fetch('http://127.0.0.1:18789/v1/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'anthropic/claude-opus-4-6',
messages: [{ role: 'user', content: message }]
})
});
const data = await resp.json();
return data.choices[0].message.content;
}
const response = await chat('What is OpenClaw?');
console.log(response);
Use Case: Automation Script
Trigger OpenClaw tools from scripts:
#!/usr/bin/env bash
set -euo pipefail
# Invoke read tool
curl -s http://127.0.0.1:18789/api/tools/invoke \
-H "Content-Type: application/json" \
-d '{"tool": "read", "input": {"file_path": "notes.md"}}' \
| jq -r .result
Use Case: Custom Skill
Create a skill with API integration:
skills/github-stars/SKILL.md:
## Get GitHub Starsbash
curl -s https://api.github.com/repos/$OWNER/$REPO | jq .stargazers_count
Publish to ClawHub:
clawhub publish ./skills/github-stars --slug github-stars
Advanced Topics
Custom Model Providers
Add a custom provider:
{
"providers": {
"custom": {
"baseURL": "https://custom.api.com/v1",
"apiKey": "...",
"models": [
{
"id": "custom/my-model",
"contextWindow": 128000
}
]
}
}
}
Use it:
{
"model": {
"primary": "custom/my-model"
}
}
Extending the Gateway
Add custom HTTP routes:
import { Gateway } from 'openclaw';
const gateway = new Gateway(config);
gateway.app.get('/custom', (req, res) => {
res.json({ message: 'Custom endpoint' });
});
await gateway.start();
Plugin System
OpenClaw supports plugins for extending functionality:
Example plugin:
export default {
name: 'my-plugin',
version: '1.0.0',
init(gateway) {
gateway.on('message', (msg) => {
console.log('Message received:', msg);
});
}
};
Load it:
{
"plugins": [
{ "path": "./plugins/my-plugin.js" }
]
}
Debugging
Enable Debug Logs
export DEBUG=openclaw:*
openclaw gateway
Inspect Session State
openclaw sessions history --session agent:main:main --json > session.json
jq . session.json
Test Model Connectivity
openclaw models test --model anthropic/claude-opus-4-6
Validate Tools
curl http://127.0.0.1:18789/api/tools/invoke \
-d '{"tool": "read", "input": {"file_path": "test.md"}}'
Best Practices
openclaw.json in gitnpm update -g openclawConclusion
OpenClaw is a platform, not just a chatbot. Understand the architecture, use the CLI, integrate via HTTP APIs, build custom skills, and extend the Gateway. The tooling is designed for developers who want full control.
Build on the platform. 🦞