Dentro l'IA: Come Funziona clawbot

Comprendere l'ingegneria che trasforma i modelli linguistici da strumenti conversazionali a veri agenti di automazione, spiegata tramite analogia, demistificata tramite architettura.

L'Analogia del Sistema Nervoso Centrale

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).

Questa architettura distribuita è il motivo per cui clawbot può ascoltare contemporaneamente WhatsApp, rispondere tramite Telegram, eseguire un comando shell e aggiornare la sua memoria, tutto in parallelo. L'AI monolitica tradizionale non può farlo perché ogni capacità è strettamente accoppiata. Il design modulare di clawbot tratta ogni componente come un servizio indipendente che comunica attraverso protocolli ben definiti.

Architettura del Sistema clawbot

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

Approfondimento sui Componenti: Come Funziona Ogni Pezzo

🌐 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.

Questa astrazione è potente: aggiungere una nuova piattaforma di messaggistica richiede la scrittura di un plugin di canale, non la modifica dell'intero sistema. Ogni canale è in sandbox: se si blocca, il Gateway tenta automaticamente la riconnessione senza influenzare altri canali.

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

Il Gateway gestisce automaticamente le finestre di contesto: quando una conversazione supera il limite di token del modello, riassume intelligentemente i messaggi più vecchi preservando il contesto critico. Ciò consente conversazioni che si estendono per settimane senza degradazione.

⚙️ 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

Le Skill possono includere script shell, moduli Node.js o codice di integrazione API. L'AI chiama questi strumenti tramite chiamate di funzione strutturate, riceve i risultati e li incorpora nelle risposte. È così che clawbot può controllare case intelligenti, gestire infrastrutture cloud o integrarsi con sistemi interni proprietari: chiunque può scrivere una skill.

Lo Stack Tecnologico: Cosa Alimenta clawbot

Runtime: Node.js 22+

Runtime JavaScript moderno con eccellenti prestazioni I/O asincrone per la comunicazione in tempo reale. Il supporto nativo per WebSockets, HTTP/2 e worker thread consente l'esecuzione parallela di task.

Language: TypeScript

Lo sviluppo type-safe previene intere categorie di bug. La tipizzazione forte per messaggi WebSocket, risposte AI e configurazione garantisce una gestione robusta degli errori.

Communication: WebSocket Protocol

Connessioni bidirezionali e persistenti tra il Gateway e tutti i client. Abilita lo streaming di messaggi in tempo reale, notifiche istantanee e latenza sub-secondo per le risposte AI.

Storage: File-Based State

Conversazioni archiviate come Markdown, configurazione come JSON, skill come cartelle strutturate. Nessuna dipendenza da database: implementazione più semplice, backup più facili, debugging grep-friendly.

WhatsApp: Baileys Library

Implementazione del protocollo WhatsApp Web reverse-engineered. Mantiene una connessione persistente utilizzando lo stesso protocollo utilizzato dal tuo browser: nessuna API non ufficiale o condivisione di numeri di telefono.

Telegram: grammY Framework

Wrapper ufficiale dell'API Bot di Telegram con supporto TypeScript. Supporto per long-polling e webhook per un'implementazione flessibile, caricamento di file, tastiere inline e funzionalità complete del bot.

AI Integration: Provider Abstraction

Interfaccia unificata che supporta Anthropic Claude, OpenAI GPT-4, modelli locali Ollama e Google Gemini. Conversione automatica tra diversi formati API per un passaggio fluido tra i provider.

Security: Sandboxed Execution

Comandi shell eseguiti in ambienti ristretti con permessi configurabili. Confini di fiducia definiti dall'utente prevengono danni accidentali al sistema o operazioni non autorizzate.

Flusso dei Messaggi: Seguire una Richiesta Attraverso il Sistema

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!"

Questa coreografia di 19 passaggi avviene in meno di 2 secondi. L'architettura distribuita consente a ogni componente di lavorare in modo indipendente: il canale WhatsApp non conosce Claude, Claude non conosce WhatsApp, eppure si coordinano senza problemi attraverso l'orchestrazione del Gateway.

Perché Questa Architettura è Importante

La maggior parte degli assistenti AI sono monolitici: tutta la logica in un'unica applicazione, strettamente accoppiata a piattaforme specifiche. Il design distribuito di clawbot abilita capacità impossibili nelle architetture tradizionali:

  • 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

Il design distribuito non riguarda solo la flessibilità, ma è un confine di sicurezza. I canali vengono eseguiti in processi separati con permessi limitati. Se un canale viene compromesso, gli aggressori ottengono accesso solo a quella piattaforma di messaggistica, non all'intero sistema. Il Gateway applica l'autenticazione e il motore di esecuzione applica un'ulteriore sandbox prima che vengano eseguiti comandi di sistema.

Decisioni Tecniche e Compromessi

Perché WebSockets Invece di 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.

Perché Archiviazione su File Invece di un 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.

Perché Node.js Invece di Python/Go/Rust?

Node.js eccelle nei task I/O-bound (comunicazione in tempo reale, chiamate API). Il modello async/await di JavaScript si mappa naturalmente ai flussi di lavoro AI (invia richiesta, attendi risposta, elabora risultato). L'ecosistema npm fornisce librerie mature per ogni piattaforma di messaggistica. TypeScript aggiunge sicurezza senza sacrificare la velocità di sviluppo.

Pronto a Implementare il Tuo?

Comprendere l'architettura è il primo passo. Il secondo è costruirla.

Installation Guide Security Best Practices Browse Source Code