深夜提醒

现在是深夜,建议您注意休息,不要熬夜哦~

🏮 🏮 🏮

新年快乐

祝君万事如意心想事成!

share-image
中
ESC

OpenClaw Architecture Deep Dive: Building Your Own Personal AI Assistant

English 阅读中文版

“EXFOLIATE! EXFOLIATE!” —— a space lobster (probably)

Introduction

In an age where AI assistants are everywhere, most products host user data in the cloud and provide services via an API. But if you want an AI assistant that is truly your own — one that runs on your own devices, connects to the messaging tools you use, and executes the automation tasks you write — then OpenClaw may be the answer you’ve been looking for.

After several days of deep research and source reading, in this article I’ll walk you through OpenClaw’s architecture design, its core components, and how it achieves a “local-first, privacy-first” AI assistant experience.
OpenClaw Architecture Deep Dive: Building Your Own Personal AI Assistant

What Is OpenClaw?

OpenClaw is a self-hosted personal AI assistant gateway, developed by the team behind Pi. Its core idea can be summed up in one sentence:

AI that actually does things. It runs on your devices, in your channels, with your rules.

Main Features

  • Multi-platform messaging integration: 20+ channels including WhatsApp, Telegram, Slack, Discord, Signal, iMessage, Feishu, LINE, and more
  • Local-first architecture: The Gateway runs on your devices (macOS, Linux, Windows WSL2)
  • Multi-agent support: Run multiple independent AI agents simultaneously
  • Rich tool ecosystem: Browser control, scheduled tasks, file system operations, Canvas visualization
  • Companion mobile apps: iOS/Android node apps with voice wake-up and continuous conversation
  • Skill system: An extensible skill system that defines new capabilities via SKILL.md

Architecture Overview

OpenClaw uses a layered architecture design, with the Gateway at its core, around which all components are built:

┌─────────────────────────────────────────────────────────────┐
│ Messaging Channels │
│ WhatsApp Telegram Slack Discord Signal iMessage │
│ Feishu LINE Matrix WebChat ... │
└─────────────────────────┬───────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Gateway (control plane) │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Session │ │ Agent │ │ Tools │ │
│ │ Manager │ │ Runtime │ │ (exec/ │ │
│ │ │ │ (pi-mono) │ │ browser/ │ │
│ └─────────────┘ └─────────────┘ │ cron/...) │ │
│ └─────────────┘ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Skills │ │ Cron │ │ Canvas │ │
│ │ Registry │ │ Jobs │ │ Host │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────┬───────────────────────────────────┘
│
┌───────────────┼───────────────┐
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ CLI │ │ Web UI │ │ Node │
│(terminal)│ │(dashboard)│ │ (mobile) │
└──────────┘ └──────────┘ └──────────┘

Core Design Principles

  1. Single Gateway: One Gateway instance controls all messaging channels, avoiding multi-instance conflicts with libraries like Baileys/WhatsApp
  2. WebSocket long connections: All clients communicate with the Gateway over WebSocket, supporting real-time event pushes
  3. Local-first: Binds to 127.0.0.1:18789 by default, keeping data local
  4. Explicit security: All high-risk operations (like executing commands) require explicit configuration, rather than being open by default

Core Components in Detail

1. Gateway

The Gateway is the control plane of the whole system, responsible for:

  • Channel management: Maintaining connections to platforms like WhatsApp and Telegram
  • Message routing: Routing messages to different Agents according to configuration
  • Session management: Maintaining session state, history, and context
  • Tool execution: Managing tool execution and security policies

The Gateway uses TypeBox to define protocol schemas, ensuring type safety:

// WebSocket protocol structure
{type: "req", id, method, params} → {type: "res", id, ok, payload|error}
{type: "event", event, payload, seq?, stateVersion?}

2. Agent Runtime

OpenClaw uses the embedded runtime of pi-mono, but session management and tool invocation are entirely controlled by OpenClaw itself.

Workspace is the core concept of an Agent:

~/.openclaw/workspace/
├── AGENTS.md # Operating instructions and "memory"
├── SOUL.md # Persona, boundaries, tone
├── TOOLS.md # User-maintained tool descriptions
├── BOOTSTRAP.md # First-run ritual (deleted after completion)
├── IDENTITY.md # Agent name/emoji
└── USER.md # User profile

These files are automatically injected into the Agent’s context at session startup, becoming part of the system prompt.

3. Skills System

Skills are OpenClaw’s extension mechanism, using a format compatible with AgentSkills:

---
name: weread
description: "WeRead AI summary assistant"
metadata:
{ "openclaw": { "emoji": "📚", "requires": { "bins": ["python3"] } } }
---

# WeRead Assistant

## When to Use

Use this skill when the user asks about WeRead.

## Commands

```bash
python3 /path/to/weread_books.py --list

Skill loading priority:

Workspace Skills (highest) → ~/.openclaw/skills → Bundled Skills (lowest)


### 4. Tools

OpenClaw provides a rich set of built-in tools:

| Tool | Function | Security level |
|------|------|----------|
| `read` / `write` / `edit` | File system operations | Restricted by workspace |
| `exec` | Execute shell commands | Requires safeBins configuration |
| `browser` | Browser control (CDP) | Separate Chrome instance |
| `cron` | Scheduled tasks | May affect persistent state |
| `canvas` | Visual interface | Runs in a sandbox |
| `sessions_spawn` | Spawn sub-agents | May create background tasks |

Tool security is controlled by the **Profile** system:

- `minimal`: Basic tools only
- `messaging`: Suited to message processing
- `coding`: Development-related tools
- `full`: All tools (use with caution)

### 5. Channels

OpenClaw supports 20+ messaging channels, each with a dedicated adapter:

| Channel | Library/Protocol | Feature |
|------|---------|------|
| WhatsApp | Baileys | The most stable WhatsApp library |
| Telegram | grammY | Feature-rich Bot API |
| Slack | Bolt | Enterprise-grade integration |
| Discord | discord.js | Community-friendly |
| Signal | signal-cli | Privacy-first |
| Feishu | Official API | The Feishu ecosystem |

**Security mechanisms**:
- DM pairing (`dmPolicy: pairing`): Unknown users need a pairing code to talk to the bot
- Group mention (`requireMention`): In a group, the bot only responds when @-mentioned
- Allowlist (`allowFrom`): Restricts which users/groups are allowed

## Deep Dive: The Message Flow Mechanism

When a message arrives from WhatsApp, the processing flow is as follows:

```mermaid
sequenceDiagram
participant User
participant WhatsApp
participant Gateway
participant Agent
participant Tools

User->>WhatsApp: Send message
WhatsApp->>Gateway: Baileys event
Gateway->>Gateway: 1. Verify pairing status
Gateway->>Gateway: 2. Resolve sessionKey
Gateway->>Gateway: 3. Apply group policy
Gateway->>Agent: 4. Create/resume session
Agent->>Agent: 5. Build system prompt
Agent->>Gateway: 6. Request tool call
Gateway->>Tools: 7. Execute tool (e.g. exec)
Tools-->>Gateway: Return result
Gateway-->>Agent: Pass tool output
Agent-->>Gateway: Generate reply
Gateway-->>WhatsApp: Send response
WhatsApp-->>User: Display message

The Mystery of the Session Key

OpenClaw uses sessionKey to route messages to the right session:

agent:<agentId>:<channel>:<context>

For example:
- agent:main:main # main session
- agent:main:whatsapp:direct # WhatsApp DM isolation
- agent:main:slack:channel # Slack channel isolation

session.dmScope configures the isolation level for DMs:

  • main: All DMs go to the main session (default)
  • per-channel-peer: Independent session per channel + user
  • per-account-channel-peer: For multi-account scenarios

Security Architecture: Trust Boundaries and Execution Control

OpenClaw uses a personal-assistant trust model, rather than multi-tenant isolation:

Default assumption: the Gateway runs within a trusted operator boundary.

Three Layers of Security Defense

  1. Network layer:

    • Binds to 127.0.0.1 by default (local only)
    • Supports Token/Password authentication
    • Device pairing (auto-approved locally, explicitly approved remotely)
  2. Channel layer:

    • DM pairing policy (pairing/allowlist/open/disabled)
    • Group mention requirement
    • Allowlist control
  3. Tool layer:

    • tools.profile controls the available tool set
    • tools.exec.safeBins restricts executable binaries
    • tools.exec.ask configures pre-execution confirmation (off/on-miss/always)
    • Sandbox mode (Docker isolation)

Why Does the exec Tool Need Special Configuration?

In OpenClaw 2026.3.8, the exec tool by default does not include interpreters like bash/python in safeBins, because:

interpreter/runtime binaries in safeBins are unsafe without explicit hardened profiles

This is a deliberate security design — the ability to execute arbitrary code must be explicitly enabled.

Extensions: The Plugin System and MCP

OpenClaw’s architecture encourages extending functionality via Plugins:

  • Extensions: Located in the extensions/ directory, such as Feishu, Matrix, Mattermost
  • NPM packages: Plugins that can be published and installed independently
  • MCP support: Bridging MCP servers through mcporter

The design philosophy of MCP (Model Context Protocol) is similar to OpenClaw’s Skill system — both aim to standardize how AI tools are integrated.

Practical Deployment Modes

Mode One: Local Development Workstation

# Install
npm install -g openclaw@latest

# Initialize
openclaw onboard --install-daemon

# Start the Gateway
openclaw gateway --port 18789

Suits: developers, privacy-sensitive users

Mode Two: VPS + Tailscale

# Run the Gateway on a VPS, bound to loopback
openclaw gateway --bind loopback --port 18789

# Access locally via Tailscale
# macOS/iOS/Android nodes auto-discover

Suits: users who need access anywhere, anytime

Mode Three: Docker Deployment

docker run -d \
-v ~/.openclaw:/root/.openclaw \
-p 18789:18789 \
openclaw/openclaw:latest

Suits: server environments, scenarios needing isolation

Hands-On Experience with the WeRead Skill

In my attempt to create a Skill for WeRead, I came to understand OpenClaw’s working mechanism deeply:

Challenges Encountered

  1. Tool not injected: In the default config, the exec tool is enabled, but interpreters (python3/bash) require explicit safeBins configuration
  2. System Prompt structure: Skills are just a “manual” for the LLM; the actual tool definitions are controlled by the Gateway
  3. Timeout issue: Local model calls may time out; timeoutSeconds needs to be set reasonably

The Final Approach

For scenarios that need to run local scripts, the most stable approach at present is:

  1. Shell Wrapper: Define a function in ~/.bashrc to bypass OpenClaw’s tool system
  2. Feishu Bot: Trigger via Webhook and let the bot execute the command directly
  3. Wait for fixes: Follow GitHub Issues and wait for improvements to tool configuration

Summary: OpenClaw’s Unique Value

In an age where AI services are increasingly centralized, OpenClaw offers a decentralized alternative:

Feature Cloud AI service OpenClaw
Data privacy Data uploaded to a provider Data kept local
Customization Limited by platform capabilities Fully extensible (Skills/Plugins)
Integration Closed ecosystem Open channels (20+ messaging platforms)
Cost API call fees Self-hosting cost
Reliability Depends on the provider Fully under your own control

OpenClaw is best for:

  • Privacy-first users: Those unwilling to upload sensitive conversations to the cloud
  • Heavy customization: Those needing deep integration of specific tools and flows
  • Multi-platform: Those managing messages across multiple messaging channels
  • Tech enthusiasts: Developers willing to invest time in self-hosting and customization

Reference Resources


This article is based on a source-code analysis of OpenClaw 2026.3.8. The project iterates quickly, and some details may change with future versions.

文章作者:阿文
文章链接: https://www.awen.me/post/8ebb5e3.html
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 阿文的博客!
本文于 2026-03-10 19:30 发布,已超过半年(220天),请注意甄别内容是否已过期。

评论

0 条评论
😀😃😄 😁😅😂 🤣😊😇 🙂🙃😉 😌😍🥰 😘😗😙 😚😋😛 😝😜🤪 🤨🧐🤓 😎🥸🤩 🥳😏😒 😞😔😟 😕🙁☹️ 😣😖😫 😩🥺😢 😭😤😠 😡🤬🤯 😳🥵🥶 😱😨😰 😥😓🤗 🤔🤭🤫 🤥😶😐 😑😬🙄 😯😦😧 😮😲🥱 😴🤤😪 😵🤐🥴 🤢🤮🤧 😷🤒🤕 🤑🤠😈 👿👹👺 🤡💩👻 💀☠️👽 👾🤖🎃 😺😸😹 😻😼😽 🙀😿😾 👍👎👏 🙌👐🤲 🤝🤜🤛 ✌️🤞🤟 🤘👌🤏 👈👉👆 👇☝️✋ 🤚🖐️🖖 👋🤙💪 🦾🖕✍️ 🙏💅🤳 💯💢💥 💫💦💨 🕳️💣💬 👁️‍🗨️🗨️🗯️ 💭💤❤️ 🧡💛💚 💙💜🖤 🤍🤎💔 ❣️💕💞 💓💗💖 💘💝💟 ☮️✝️☪️ 🕉️☸️✡️ 🔯🕎☯️ ☦️🛐⛎ ♈♉♊ ♋♌♍ ♎♏♐ ♑♒♓ 🆔⚛️🉑 ☢️☣️📴 📳🈶🈚 🈸🈺🈷️ ✴️🆚💮 🉐㊙️㊗️ 🈴🈵🈹 🈲🅰️🅱️ 🆎🆑🅾️ 🆘❌⭕ 🛑⛔📛 🚫💯💢 ♨️🚷🚯 🚳🚱🔞 📵🚭❗ ❕❓❔ ‼️⁉️🔅 🔆〽️⚠️ 🚸🔱⚜️ 🔰♻️✅ 🈯💹❇️ ✳️❎🌐 💠Ⓜ️🌀 💤🏧🚾 ♿🅿️🈳 🈂🛂🛃 🛄🛅🛗 🚀🛸🚁 🚉🚆🚅 ✈️🛫🛬 🛩️💺🛰️
加载中...

留言反馈

😀😃😄 😁😅😂 🤣😊😇 🙂🙃😉 😌😍🥰 😘😗😙 😚😋😛 😝😜🤪 🤨🧐🤓 😎🥸🤩 🥳😏😒 😞😔😟 😕🙁☹️ 😣😖😫 😩🥺😢 😭😤😠 😡🤬🤯 😳🥵🥶 😱😨😰 😥😓🤗 🤔🤭🤫 🤥😶😐 😑😬🙄 😯😦😧 😮😲🥱 😴🤤😪 😵🤐🥴 🤢🤮🤧 😷🤒🤕 🤑🤠😈 👿👹👺 🤡💩👻 💀☠️👽 👾🤖🎃 😺😸😹 😻😼😽 🙀😿😾 👍👎👏 🙌👐🤲 🤝🤜🤛 ✌️🤞🤟 🤘👌🤏 👈👉👆 👇☝️✋ 🤚🖐️🖖 👋🤙💪 🦾🖕✍️ 🙏💅🤳 💯💢💥 💫💦💨 🕳️💣💬 👁️‍🗨️🗨️🗯️ 💭💤❤️ 🧡💛💚 💙💜🖤 🤍🤎💔 ❣️💕💞 💓💗💖 💘💝💟 ☮️✝️☪️ 🕉️☸️✡️ 🔯🕎☯️ ☦️🛐⛎ ♈♉♊ ♋♌♍ ♎♏♐ ♑♒♓ 🆔⚛️🉑 ☢️☣️📴 📳🈶🈚 🈸🈺🈷️ ✴️🆚💮 🉐㊙️㊗️ 🈴🈵🈹 🈲🅰️🅱️ 🆎🆑🅾️ 🆘❌⭕ 🛑⛔📛 🚫💯💢 ♨️🚷🚯 🚳🚱🔞 📵🚭❗ ❕❓❔ ‼️⁉️🔅 🔆〽️⚠️ 🚸🔱⚜️ 🔰♻️✅ 🈯💹❇️ ✳️❎🌐 💠Ⓜ️🌀 💤🏧🚾 ♿🅿️🈳 🈂🛂🛃 🛄🛅🛗 🚀🛸🚁 🚉🚆🚅 ✈️🛫🛬 🛩️💺🛰️