Generated by: Claude Opus 5 (claude-opus-5) / Claude Opus 4.6 (earlier chapters) Tools: Claude Code + OpenClaw + OpenCode Last updated: 2026-08-02 Source baseline:
v2026.3.9(v2026.3.8-170-g665f67726) GitHub: https://github.com/0xtresser/OpenClaw-Book
The book is organized shallow-to-deep, but you don't have to read it in order. The three layers stand on their own:
| Layer | Parts | Read it to | Source code required? |
|---|---|---|---|
| Usage | Part I (Ch. 1–10) | Install and use OpenClaw | No |
| Implementation | Parts II–X (Ch. 11–42) | Understand how each subsystem works | Yes |
| Insight | Part XI (Ch. 43–45) | Extract transferable design lessons and risk judgment | Better after the implementation layer |
From Chapter 11 on, most chapters end with a 🔬 Source Deep Dive section. It sits closer to the source than the main text and carries a higher information density, tracing the real implementation line by line along with the issues behind it.
The main text is for understanding structure; the deep dive is for understanding trade-offs. If you only want to know what a piece does, the main text is enough. If you're going to modify it, or reproduce it in your own project, read the deep dive.
- Why this book exists, and who it's for
- What OpenClaw is: a personal AI assistant that runs on your own devices
- How the book is organized, and how to read it
- Source version (
v2026.3.9) - Prerequisites: TypeScript basics, Node.js runtime concepts, WebSocket, basic operating-system knowledge
From zero to fluent. No source reading required — follow along and it works.
- 1.1 What is OpenClaw
- 1.2 Core Architecture Overview
- 1.3 Technology Stack Overview
- 1.4 Project Directory Structure
- 2.1 Environment Setup
- 2.2 Onboarding Wizard
- 2.3 Starting the Gateway Daemon
- 2.4 Development Workflow
- 3.1 Telegram Bot: Complete Setup
- 3.2 Discord and Slack
- 3.3 Multi-Channel Strategy and Group Management
- 8.1 Feishu, DingTalk, and WeCom
- 8.2 Cloud Deployment in Practice
- 8.3 Docker Deployment and Production Configuration
- 9.1 Multi-Agent Configuration and Routing
- 9.2 Subagents and Cross-Agent Communication
- 9.3 Team Collaboration and Case Studies
- 10.1 Memory and Knowledge Management
- 10.2 Security Hardening and Permission Management
- 10.3 Customization and Common Questions
- 11.1 Gateway Role and Design Goals
- 11.2 Server Startup Flow Source Analysis
- 11.3 WebSocket Server Implementation
- 11.4 HTTP Layer
- 🔬 11.5 Source Deep Dive: The Assembly Site and the Method Routing Table
- A flat method routing table and the dispatcher's three gates (bidirectional role isolation, scope, control-plane write budget)
startGatewayServer's 15-step assembly sequence and hand-rolled dependency injection- The HTTP stage pipeline; the "agent as model" trade-off in the OpenAI-compatible layer
- The invariant: a node never runs gateway services
- 12.1 Protocol Design Philosophy
- 12.2 TypeBox Type Schema
- 12.3 Core Methods and Events
- 12.4 Authentication and Authorization
- 🔬 12.5 Source Deep Dive: Three Frames, the Handshake, and Four Auth Layers
- Three frame types, and the codegen motive behind the discriminated union
- Why "events don't replay + requests are idempotent" is the correctness basis for reconnecting over a flaky network
- Four auth layers: shared credential → Ed25519 device identity → pairing approval → device token
- Sentinel-IP accounting for browser origins; Tailscale identity headers must be reverse-verified
- 13.1 Session Model Design
- 13.2 Session Routing Source Analysis
- 13.3 Session Lifecycle
- 13.4 Session Pruning
- 13.5 Inter-Session Communication
- 🔬 13.6 Source Deep Dive: Two-Tier Lanes and Three Queue Semantics
session lane(1) ⊂ global lane(N)— about 300 lines of plain Promises- Six queueing modes at a glance;
collect's cross-channel degradation and overflow summarize - The typing indicator's dual-signal convergence point (the extension trap people hit most)
- Session reset "changes the ID without deleting the key"; four costs
- 14.1 Channel Registry
- 14.2 Inbound Message Processing Pipeline
- 14.3 Outbound Message Processing
- 14.4 Multi-Agent Routing
- 🔬 14.5 Source Deep Dive: Seven Gates on the Inbound Pipeline
- Inbound debounce (sliding window, with media and commands forced through)
- The mention gate's three-way decision and zero-width-character scrubbing; blocked messages still enter the history buffer
- The seven-level binding cascade and three-level cache (the config object as a WeakMap key)
- The default session key collapses every DM into one main session — "one person, many entrances"
- 15.1 What is Pi Agent
- 15.2 Agent Loop End-to-End Analysis
- 15.3 Queue and Concurrency Control
- 15.4 Timeout and Abort Mechanisms
- 🔬 15.5 Source Deep Dive: The Full Journey of a Run
- Across 88,000 lines, exactly one statement drives the loop:
session.prompt() - Retry ceilings scale with the number of auth profiles;
attempt.ts's 2,096-line ten-step assembly - The streamFn onion: the single injection point into pi, with each of its seven layers tracing to a real issue
- The streaming event bridge's tag stripping, tool-send deduplication, and three forms of reasoning
- Across 88,000 lines, exactly one statement drives the loop:
- 16.1 Model Selection Mechanism
- 16.2 AuthProfile and Credential Management
- 16.3 Model Catalog and Configuration
- 16.4 Failover Error Handling
- 🔬 16.5 Source Deep Dive: Auth Profile Rotation, Cooldown, and Degradation
- The cost policy is written into the sort function: OAuth subscriptions first, API keys as backstop
- Two critical disciplines: an active window is never extended, and timeouts are never charged
- Four time scales each governing one span; why three structured observability logs are a requirement, not a luxury
- 17.1 Building System Prompts
- 17.2 Workspace and Context File Injection
- 17.3 Identity System
- 17.4 Context Compaction
- 17.5 The Context Engine Plugin System
- 🔬 17.6 Source Deep Dive: Four Lines of Context Defense
- Entry guard → in-request pruning (not persisted) → compaction (persisted) → tool-result truncation
- Folding Anthropic's 5-minute cache TTL into the pruning decision (cost-aware context management)
- compaction-safeguard: better to cancel compaction than emit a bad summary
- The usage-accounting trap:
cacheReadmust not be summed
- 18.1 Streaming Architecture
- 18.2 Block Streaming
- 18.3 Coalescing and Humanized Pacing
- 18.4 Telegram Draft Streaming
- 18.5 Reply Shaping and Suppression
- 🔬 18.6 Source Deep Dive: The Serial Outbound Chain and Chunk Aggregation
pendingstarting at 1 — a reservation count- Splitting (chunk) and merging (coalescer): two components pulling in opposite directions
routeReply's failure fallback: when delivered and delivered-correctly conflict, choose correctly
- 19.1 Channel Adapter Design Pattern
- 19.2 Inbound Message Normalization
- 19.3 Outbound Message Adaptation
- 🔬 19.4 Source Deep Dive: The ChannelPlugin Contract and Dual Registries
- Why there's no unified message bus: unification happens at the contract layer, not the data-flow layer
- Reply routing is deterministic — designing out the "injection reroutes the agent" attack
- The dock / plugin heavy-light split: the single most copyable move in the chapter
- Envelope-header escaping against forgery;
src/web/is actually WhatsApp
- 20.1 WhatsApp Channel
- 20.2 Telegram Channel
- 20.3 Discord Channel
- 20.4 Slack Channel
- 20.5 Other Core Channels
- 🔬 20.6 Source Deep Dive: Three Long-Lived Connections, Two Streaming Modes
- The Telegram watchdog: the probe rides on ordinary
getUpdatestraffic - Block streaming vs. draft streaming, and the throttle kernel they share
sendMayHaveLanded: "I don't know" is a third state that must be modeled- A side-by-side comparison of all 17 channels
- The Telegram watchdog: the probe rides on ordinary
- 21.1 Extension Architecture Design
- 21.2 Extension API Surface
- 21.3 Representative Extension Implementations
- 21.4 Developing Custom Extensions
- 🔬 21.5 Source Deep Dive: The Loader, jiti, and the SDK Surface
- Manifest/execution separation: "validating configuration never becomes running code"
- The jiti bargain: what-you-audit-is-what-runs and zero SDK drift ↔ zero runtime isolation
- Only three boundaries are actually enforced; the rest are documentation boundaries
- Three npm primitives instead of a centralized marketplace;
--ignore-scriptsremoves the supply-chain surface
- 22.1 Tool System Architecture
- 22.2 Tool Registration and Policy
- 22.3 Tool Execution and Result Handling
- 22.4 Execution Approval Mechanism
- 🔬 22.5 Source Deep Dive: The Tool Assembly Pipeline and the Sandbox
- A five-stage assembly line and seven layers of policy filtering; why every tool goes through
customTools exec's three dimensions:securitytakes the minimum,asktakes the maximum — deliberately opposite- The two-phase approval protocol decouples "the LLM calls synchronously" from "a human approves asynchronously"
- The sandbox is not
docker exec: read-only root + cap-drop +configHashauto-rebuild
- A five-stage assembly line and seven layers of policy filtering; why every tool goes through
- 24.1 Browser Architecture Overview
- 24.2 CDP Layer Implementation
- 24.3 Playwright Layer Implementation
- 24.4 Browser Server
- 🔬 24.5 Source Deep Dive: Four Browser Sources and Three Security Gates
- Not headless — it attaches to a real Chrome, with an orange window marker
- The snapshot is an accessibility text tree rather than a screenshot: an order of magnitude better on tokens
- The key SSRF insight: an environment proxy renders DNS pre-checks meaningless
- Auth bootstrap: loopback does not mean safe
- 26.1 Cron System Design
- 26.2 Cron Job Execution
- 26.3 Webhooks and Gmail Pub/Sub
- 🔬 26.4 Source Deep Dive: The Division of Labor Between Cron and Heartbeat
- Two session shapes, strictly validated as a pair at creation time
- Three incident lessons: the
setTimeout(0)hot loop, the restart catch-up storm, and stuck jobs - Deterministic jitter from the SHA-256 of the job id rather than a random number
- The heartbeat's three-part design: yield, economize, stay silent
- 27.1 Node Concepts
- 27.2 Node Registration and Discovery
- 27.3 Node Host Implementation
- 🔬 27.4 Source Deep Dive: Reverse RPC and the Wake Mechanism
- Four layers wrapped around
node.invoke - An operation that changes permissions should not travel the same channel as an ordinary one
- The three-stage APNs wake: the user is only disturbed after the first two fail
- The iOS foreground queue — a patch for the mobile lifecycle, promoted into a mechanism
- Four layers wrapped around
- 28.1 Memory Model Design
- 28.2 Vector Memory Search
- 28.3 Hybrid Search
- 28.4 Advanced Memory Features
- 🔬 28.5 Source Deep Dive: Files as the Source of Truth, and Hybrid Retrieval
- Four layers, in which the vector index is the only binary state — and it can be rebuilt at any time
- Retrieval is the model's behavior, not the framework's (coexisting with LanceDB's opposite extreme)
- LanceDB auto-capture only handles user messages: "avoid the model polluting itself with its own output"
- The flush safety notice cannot be overridden by the user: you may change the tone, not the boundary
- 29.1 Skill Platform Design
- 29.2 Skill Structure
- 29.3 Skill Installation and Management
- 29.4 ClawHub Skill Registry
- 🔬 29.5 Source Deep Dive: Progressive Disclosure and Three-Layer Loading
- Pre-filtering by
requires: the model never recommends a plan that can't run - Four disciplines of progressive disclosure, taking context cost from O(N) to O(1)
- The trust boundary:
SKILL.mdgoes straight into the prompt, and reading it yourself is the only defense
- Pre-filtering by
- 30.1 Internal Hooks
- 30.2 Plugin Hooks
- 🔬 30.3 Source Deep Dive: Two Event Systems and the Hook Package Convention
- How the
session-memoryhook achieves "reset the session without losing memory" - The exception to fire-and-forget:
agent:bootstrapcan modify the bootstrap file list - The Gmail watcher: a representative entry point from the outside world into an agent turn
- How the
- 31.1 Configuration Loading and Parsing
- 31.2 Configuration Type System Deep Dive
- 31.3 Configuration Hot Reload
- 31.4 Legacy Configuration Migration
- 31.5 Environment Variables
- 🔬 31.6 Source Deep Dive: The Five-Stage Read Pipeline and Write-Back Restoration
- Failing closed is the security floor: never silently fall back to a permissive default
- Legacy detection must run before Zod — error-message quality depends on which layer intercepts
- Three write-back techniques: merge-patch projection + env-ref restoration + a prototype-key blocklist
- One counterintuitive hazard: a read operation writes a file
- 32.1 Security Design Principles
- 32.2 DM Pairing System
- 32.3 Sandbox Mechanism
- 32.4 Security Auditing
- 32.5 SOUL Security: The Trust Position of Bootstrap Files — includes the
soul-evilremoval case study - 🔬 32.6 Source Deep Dive: Admission, Secrets, and Audit
- Pairing is session admission, not permission grant (group commands don't inherit DM pairing)
- External content is delimited by a random 16-character id, with homoglyph normalization
- Three secret layers: SecretRef → dual snapshots → redaction (with bounded regexes so it can't DoS itself)
- Audit severity varies with your actual exposure; tools don't pretend to be boundaries
- 33.1 CLI Architecture
- 33.2 Core Command Analysis
- 33.3 Chat Commands
- 🔬 33.4 Source Deep Dive: Two Command Trees and Startup-Speed Paranoia
- The chat command registry: one declaration driving five front ends, with a build-time self-check
- Three layers of startup optimization (version fast-path / route-first / lazy registration placeholders)
- config-guard's "fail closed + allowlist passthrough" avoids a repair deadlock
- DI through narrow interfaces plus default parameters: interfaces small enough to hand-write a test double
- 34.1 Logging System
- 34.2 Media Pipeline
- 34.3 Link and Media Understanding
- 34.4 TTS Text-to-Speech
- 34.5 Polls System
- 🔬 34.6 Source Deep Dive: The Media Candidate Chain and the Vision Short-Circuit
- Probe order instead of a config switch — demoting a configuration problem into a performance problem
- The vision short-circuit: if the main model can see the image, don't paraphrase it second-hand
- Link understanding filters SSRF at the extraction stage — moving the defense forward to the data entry point
- 37.1 Local Deployment
- 37.2 Docker Deployment
- 37.3 Remote Access
- 37.4 Nix Declarative Deployment
- 37.5 VPS Deployment
Source-level deep dive on cross-platform service installation: Appendix F.
- 39.1 Multi-Agent Design
- 39.2 Sub-Agents
- 39.3 Multi-Agent Sandbox Tools
- 🔬 39.4 Source Deep Dive: Subagent Spawning and Cross-Agent Communication
- Depth limits against fork bombs; the system prompt explicitly forbids polling
- Idempotency key = subsession key + run id; late events are swallowed silently with
NO_REPLY - A sandboxed session may not spawn ACP — better to say plainly there's no protection than to offer a fake switch
- 40.1 ACP Protocol Overview
- 40.2 ACP Session Management and Runtime
- 40.3 ACP Control Plane and Integration Patterns
- 🔬 40.4 Source Deep Dive: Two ACP Subsystems Pointing Opposite Ways
- The split between the ACP bridge (being called) and the ACP Runtime (calling)
runIddoing three jobs at once; errors map toend_turn, not a refusal- A deterministic
sessionKeyinstead of a persisted mapping table; "configuration is the desired state"
- 42.1 Project Planning
- 42.2 Core Feature Implementation
- 42.3 Channel Integration
- 42.4 Advanced Features
- 42.5 Deployment and Launch
The first forty-two chapters took OpenClaw apart like a machine, each answering how is this piece implemented?
This part changes the lens: put the magnifying glass down, step back, and extract the shapes that recur across the codebase, the patterns worth stealing, and the risks you need to know about.
Specific line numbers expire. Shapes don't.
- 43.1 Positioning and Evolution
- Four engineering tracks and four renames; the heart is borrowed (pi-mono is embedded, not written)
- The agent's personality is a set of git-manageable Markdown files
- 43.2 Scale and Subsystem Map
- Six verified numbers: 507,227 lines, 1,935 tests, 18,005 commits, 40 extensions, 52 skills
- A reverse index from code to chapter; three counterintuitive facts
- 43.3 AI-Collaborative Development
AGENTS.mdis not a contributing guide — it's a case book of agent mistakes- Three rule categories: AI code pathologies / multi-agent safety / merge gates
- 43.4 Source Reading Paths
- Four paths; use the 1,935 test filenames as the spec
- Anti-recommendation: don't start with the 2,096-line assembly file
- 44.1 A Converged Network Surface, and "Embed, Don't Fork"
- Theme 1: one port, one protocol, one admission path (cost: complexity concentrated, not eliminated)
- Theme 2: pay the architecture tax rather than carry the fork debt — decided by upstream change frequency
- 44.2 Degradation Chains Everywhere
- Theme 3: the same pattern appears independently in six modules — consensus, not reuse
- Four points for getting it right; copying this pattern requires copying the observability
- 44.3 Files as the Source of Truth, Declaration Tables as the Single Truth
- Theme 4: the vector index is the only binary state, defined as a rebuildable derivative
- Theme 5: knowledge needing multi-place consistency collapses into a table + generation/validation
- 44.4 A Trust Model Honest Enough to Be Case Law
- Theme 6: writing "what does not count as a vulnerability" as citable precedent
- Much of it exists to handle AI-generated vulnerability reports
- 44.5 Conversation Experience as a First-Class Engineering Object
- Theme 7: three queueing semantics for three real mental models
- Two-tier lanes solve three constraints in ~300 lines of Promises; the heartbeat's traceless design
- 45.1 Ten Engineering Patterns Worth Stealing
- Selection criterion: they hold up outside OpenClaw's context
- With a "pick by system characteristics" mapping table
- 45.2 Risk and Improvement List
- One verified defect (
systemd.ts:484/528— uninstalling the node stops the gateway) - Three architecture-level risks + seven correctness/maintainability risks
- Every risk is the invoice for one of Chapter 44's advantages
- One verified defect (
- 45.3 A Contrasting Route
- Twelve decision points, nearly all opposite
- Three key contrasts: who errors teach / where trust collapses / the cost curve of channel abstraction
- 45.4 Epilogue: From Tool to Infrastructure
- A working agent takes ~200 lines. What are the other 499,800 doing?
- Three principles to take away
Complete JSON5 config example · full config key reference
Three frame types · the connect handshake (protocol version 3) · all 110 methods · 19 event types · four auth layers
Every built-in tool, its schema and purpose · how the seven-layer policy pipeline trims the set
Dependency map · message sequence diagram · directory-to-chapter reference · three verification techniques
Every technical term in this book, with explanation
- Per-platform quirk patches — launchd's persisted disabled state, systemd's dual-scope bus fallback, schtasks' localized-text trap
- The service file as the source of configuration truth (
readCommandreverse parsing) - One verified defect: systemd install/uninstall ignores the unit-name override
- node-host exec security: a pure-function policy core plus four runtime re-verifications
- The six things people most often get wrong (including the "two pairing systems" warning)
- Four-level transport fallback; three Tailscale modes; credential precedence rules
- OpenAI-compatible API limits, and SSRF defenses are orthogonal to the allowlist
- Port and config key quick reference
| Part | Chapters | Estimated words |
|---|---|---|
| Part I: Getting Started | 10 | ~80,000 |
| Part II: Gateway Control Plane | 4 | ~44,000 |
| Part III: AI Agent Runtime | 4 | ~44,000 |
| Part IV: Multi-Channel Messaging | 3 | ~33,000 |
| Part V: Tool System and Automation | 6 | ~40,000 |
| Part VI: Memory, Skills, Ecosystem | 3 | ~25,000 |
| Part VII: Security, Config, Infrastructure | 4 | ~36,000 |
| Part VIII: Client Apps and Web UI | 2 | ~6,000 |
| Part IX: Deployment and Operations | 2 | ~6,000 |
| Part X: Advanced Topics and Practice | 4 | ~20,000 |
| Part XI: Source Reading and Design Insight | 3 | ~24,000 |
| Appendices | 7 | ~14,000 |
| Total | 45 chapters + 7 appendices | ~372,000 |