Binnen de AI: Hoe clawbot Werkt

Begrijpen van de engineering die taalmodellen transformeert van conversationele tools tot echte automatiseringsagenten – verklaard door analogie, ontrafeld door architectuur.

De Analogie van het Centrale Zenuwstelsel

Most people think of AI assistants as standalone brains—a single entity that processes and responds. clawbot is different: it's architected like a biological nervous system . Your brain (the AI model) doesn't directly control your muscles; signals travel through nerves (channels), are processed by the spinal cord (Gateway), and execute through motor neurons (system tools).

Deze gedistribueerde architectuur is de reden waarom clawbot tegelijkertijd WhatsApp kan beluisteren, via Telegram kan reageren, een shell-commando kan uitvoeren en zijn geheugen kan bijwerken – allemaal parallel. Traditionele monolithische AI kan dit niet omdat elke functionaliteit nauw met elkaar verbonden is. Het modulaire ontwerp van clawbot behandelt elke component als een onafhankelijke service die communiceert via goed gedefinieerde protocollen.

clawbot Systeemarchitectuur

Input Layer: Communication Channels
💬
WhatsApp
Baileys Protocol
📱
Telegram
grammY Bot API
🎮
Discord
discord.js
💼
Slack
Bolt Framework
Orchestration Layer: The Gateway
🌐
Gateway Hub
WebSocket Server @ :18789
Intelligence Layer: AI Models
🧠
Claude
Anthropic API
GPT-4
OpenAI API
🏠
Ollama
Local Models
Execution Layer: System Control
⚙️
Shell Tools
Command Execution
📁
File System
Read/Write Ops
🌐
Browser
Web Automation
🔌
Integrations
API Connectors

Component Diepteanalyse: Hoe Elk Deel Functioneert

🌐 The Gateway: Central Command

The Gateway is the heart of clawbot—a persistent Node.js process that never sleeps. Why a dedicated service instead of running AI directly in each channel? Three critical reasons:

  • Unified State : Single source of truth for conversation history across all channels
  • Resource Efficiency : One connection to AI APIs instead of 15+ separate connections
  • Fault Isolation : If WhatsApp crashes, Telegram keeps working—channels are replaceable plugins

The Gateway communicates via WebSockets, not HTTP. Why? HTTP requires the client to constantly ask "any updates?" (polling). WebSockets maintain a persistent two-way connection—the Gateway can push messages to channels the instant they're ready, enabling real-time streaming responses.

1. Channel connects to ws://127.0.0.1:18789
2. Authenticates with JWT token or local trust
3. Declares role: "channel:whatsapp"
4. Subscribes to message stream for specific user/group
5. Maintains heartbeat: ping every 30s

💬 Channels: The Sensory Interface

Channels are independent processes that translate between messaging platform protocols and the Gateway's unified message format. Think of them as protocol adapters —WhatsApp speaks Baileys, Telegram speaks Bot API, but both present messages to the Gateway in identical JSON structure.

Deze abstractie is krachtig: het toevoegen van een nieuw berichtenplatform vereist het schrijven van één kanaalplugin, niet het aanpassen van het hele systeem. Elk kanaal is gesandboxed – als het crasht, probeert de Gateway automatisch opnieuw verbinding te maken zonder andere kanalen te beïnvloeden.

User: Sends "Check my calendar" via WhatsApp
Channel: Receives WhatsApp protobuf, converts to JSON
Gateway: Routes to AI model with context
AI: Generates response + tool call to calendar API
Gateway: Executes tool, streams result back
Channel: Converts JSON to WhatsApp format, delivers

🧠 AI Model Router: The Intelligence Backbone

clawbot doesn't lock you into a single AI provider. The model router implements dynamic provider selection : choose Claude for complex reasoning, GPT-4 for creative tasks, or local Ollama for privacy-critical operations—all within the same conversation.

How does this work technically? Each AI provider has a standardized interface (following the OpenAI Completion API pattern). The router maintains connection pools to all configured providers, routes requests based on configured preferences, and handles automatic failover if a provider is unavailable.

Advanced: Custom Model Routing Logic

You can configure custom routing rules in ~/.clawbot/clawbot.json :

  • Route coding tasks to Claude (better at programming)
  • Route creative writing to GPT-4 (more imaginative)
  • Route sensitive data processing to local Ollama (zero external transmission)
  • Automatic fallback to secondary provider if primary fails

💾 Persistent Memory: Conversation State Management

Unlike stateless AI APIs that forget everything between requests, clawbot maintains durable conversation history stored in Markdown files at ~/.clawbot/conversations/ . Each conversation is a complete log of messages, tool executions, and AI responses.

Why Markdown instead of a database? Three reasons:

  • Human-Readable : You can grep, search, and version control your AI conversations
  • Portable : Move your entire conversation history by copying a folder
  • AI-Friendly : AI models can natively understand Markdown formatting for context retrieval

De Gateway beheert automatisch contextvensters – wanneer een gesprek de limiet van het model overschrijdt, vat het intelligent oudere berichten samen met behoud van kritieke context. Dit maakt gesprekken mogelijk die weken duren zonder degradatie.

⚙️ Execution Engine: Safe System Control

This is where clawbot differentiates from chatbots: genuine task execution . When the AI decides a shell command is needed, the execution engine handles it safely through multiple protection layers:

  • Sandboxing : Commands run in restricted environments with limited file system access
  • Permission Gates : User-configurable allowlists/denylists for command patterns
  • Confirmation Prompts : Destructive operations require explicit user approval
  • Audit Logging : Every executed command is logged with timestamp, user, and result
  • Timeout Protection : Commands automatically terminate after configurable duration
1. AI suggests: rm ~/Documents/old-file.txt
2. Execution engine checks permission policy
3. Destructive operation detected → user confirmation required
4. User approves via messaging channel
5. Command executes in sandbox with 30s timeout
6. Result logged: [SUCCESS] File deleted

🔌 Skills System: Extensible Capabilities

Skills are clawbot's plugin system—folders containing SKILL.md files that teach the AI new capabilities. How does a Markdown file extend functionality? The AI reads the skill definition and learns:

  • What the skill does and when to use it
  • What parameters it accepts
  • Example commands that trigger it
  • Expected behavior and edge cases

Skills kunnen shellscripts, Node.js-modules of API-integratiecode bevatten. De AI roept deze tools aan via gestructureerde functieaanroepen, ontvangt resultaten en neemt deze op in reacties. Dit is hoe clawbot slimme huizen kan besturen, cloudinfrastructuur kan beheren of kan integreren met propriëtaire interne systemen – iedereen kan een skill schrijven.

De Technologie Stack: Wat clawbot Aandrijft

Runtime: Node.js 22+

Moderne JavaScript-runtime met uitstekende asynchrone I/O-prestaties voor real-time communicatie. Native ondersteuning voor WebSockets, HTTP/2 en worker threads maakt parallelle taakuitvoering mogelijk.

Language: TypeScript

Type-veilige ontwikkeling voorkomt hele categorieën bugs. Sterke typering voor WebSocket-berichten, AI-reacties en configuratie zorgt voor robuuste foutafhandeling.

Communication: WebSocket Protocol

Bidirectionele, persistente verbindingen tussen Gateway en alle clients. Maakt real-time berichtstreaming, directe meldingen en sub-seconde latentie voor AI-reacties mogelijk.

Storage: File-Based State

Gesprekken opgeslagen als Markdown, configuratie als JSON, skills als gestructureerde mappen. Geen databaseafhankelijkheid – eenvoudigere implementatie, makkelijkere back-ups, grep-vriendelijke debugging.

WhatsApp: Baileys Library

Reverse-engineered WhatsApp Web protocol-implementatie. Onderhoudt een persistente verbinding met hetzelfde protocol als uw browser gebruikt – geen onofficiële API's of delen van telefoonnummers.

Telegram: grammY Framework

Officiële Telegram Bot API-wrapper met TypeScript-ondersteuning. Long-polling en webhook-ondersteuning voor flexibele implementatie, bestandsuploads, inline toetsenborden en volledige botfunctionaliteit.

AI Integration: Provider Abstraction

Uniforme interface die Anthropic Claude, OpenAI GPT-4, Ollama lokale modellen en Google Gemini ondersteunt. Automatische conversie tussen verschillende API-formaten voor naadloze providerwisseling.

Security: Sandboxed Execution

Shell-commando's worden uitgevoerd in beperkte omgevingen met configureerbare permissies. Door de gebruiker gedefinieerde vertrouwensgrenzen voorkomen accidentele systeemschade of ongeautoriseerde operaties.

Berichtstroom: Een Verzoek Door het Systeem Volgen

Let's trace what happens when you send: "Remind me to call Mom in 2 hours" via WhatsApp.

1. WhatsApp Server → Your phone receives message
2. Your Phone → Forwards to linked devices (including clawbot)
3. WhatsApp Channel → Decodes protobuf, extracts message text
4. Channel → Converts to JSON: {"from": "user", "text": "Remind...", "channel": "whatsapp"}
5. Gateway → Receives message via WebSocket
6. Gateway → Loads conversation history from Markdown file
7. Gateway → Appends new message to context
8. AI Router → Routes to configured AI model (e.g., Claude)
9. Claude API → Processes request, identifies "reminder" intent
10. Claude → Calls schedule_reminder(time="+2h", message="Call Mom")
11. Gateway → Executes tool, creates scheduled task
12. Gateway → Receives confirmation from scheduler
13. Claude → Generates human-friendly response
14. Gateway → Streams response back to WhatsApp channel
15. Channel → Converts JSON to WhatsApp format
16. Channel → Sends to WhatsApp servers
17. WhatsApp → Delivers to your phone
18. Scheduler → Waits 2 hours, then triggers reminder
19. Gateway → Sends proactive message: "Time to call Mom!"

Deze choreografie van 19 stappen gebeurt in minder dan 2 seconden. De gedistribueerde architectuur stelt elke component in staat om onafhankelijk te werken – het WhatsApp-kanaal kent Claude niet, Claude kent WhatsApp niet, toch coördineren ze naadloos via de orkestratie van de Gateway.

Waarom Deze Architectuur Belangrijk is

De meeste AI-assistenten zijn monolithisch – alle logica in één applicatie, nauw verbonden met specifieke platforms. Het gedistribueerde ontwerp van clawbot maakt mogelijkheden mogelijk die onmogelijk zijn in traditionele architecturen:

  • Hot-Swappable Components : Upgrade AI models without restarting channels. Replace WhatsApp with Telegram without touching the Gateway.
  • Horizontal Scaling : Run multiple channel instances across different machines, all connecting to one Gateway.
  • Fault Tolerance : If one channel crashes, others continue operating. If the Gateway restarts, channels automatically reconnect.
  • Multi-Tenancy : One Gateway can serve multiple users with isolated conversation spaces—perfect for family deployments.
  • Extensibility : Community members can build new channels, skills, or tools without access to core code.

🔐 Security Through Architecture

Het gedistribueerde ontwerp gaat niet alleen over flexibiliteit – het is een beveiligingsgrens. Kanalen draaien in aparte processen met beperkte permissies. Als een kanaal wordt gecompromitteerd, krijgen aanvallers alleen toegang tot dat berichtenplatform, niet tot uw hele systeem. De Gateway handhaaft authenticatie, en de uitvoeringsengine past aanvullende sandboxing toe voordat systeemcommando's worden uitgevoerd.

Technische Beslissingen en Afwegingen

Waarom WebSockets in plaats van HTTP REST?

HTTP is request-response: client asks, server answers. AI responses often take 5-15 seconds. Without WebSockets, you'd need polling (wasteful) or long-polling (complex). WebSockets enable streaming responses —the AI begins sending words the moment it generates them, creating the perception of instant responsiveness.

Waarom Bestandsopslag in plaats van een Database?

Databases add deployment complexity—installation, configuration, backup strategies. For personal AI (1-10 users), files provide sufficient performance while remaining portable, inspectable, and version-controllable . You can grep your conversation history, back it up with Dropbox, or track changes with Git.

Waarom Node.js in plaats van Python/Go/Rust?

Node.js blinkt uit in I/O-gebonden taken (real-time communicatie, API-aanroepen). JavaScript's async/await-model sluit natuurlijk aan bij AI-workflows (verzoek verzenden, wachten op antwoord, resultaat verwerken). Het npm-ecosysteem biedt volwassen bibliotheken voor elk berichtenplatform. TypeScript voegt veiligheid toe zonder de ontwikkelingssnelheid op te offeren.

Klaar om Uw Eigen te Implementeren?

Het begrijpen van de architectuur is stap één. Stap twee is het bouwen ervan.

Installation Guide Security Best Practices Browse Source Code