Spaces:
Sleeping
Sleeping
feat: add WhatsApp pairing guardian, improve DNS resolution, and implement workspace sync status reporting
Browse filesFiles changed (10)
- .env.example+3-7
- Dockerfile+8-3
- README.md+81-51
- dns-fix.js+102-13
- health-server.js+467-19
- iframe-fix.cjsAdded+45
- keep-alive.sh+2-2
- start.sh+35-3
- wa-guardian.jsAdded+126
- workspace-sync.py+45-2
131 unmodified lines13213313413513613713822 unmodified lines161162163164165166167168169170171172131 unmodified lines# If set, users can log in with this password instead of the token# OPENCLAW_PASSWORD=your_password_here# ββ OPTIONAL: Telegram Integration ββ# Get bot token from: https://t.me/BotFatherTELEGRAM_BOT_TOKEN=your_bot_token_here22 unmodified lines# Workspace auto-sync interval (seconds). Default: 600.SYNC_INTERVAL=600# ββ OPTIONAL: Advanced ββ# Pin OpenClaw version. Default: latestOPENCLAW_VERSION=latest# Health endpoint port. Default: 7861HEALTH_PORT=7861# Trusted proxies (comma-separated IPs)# Fixes "Proxy headers detected from untrusted address" behind reverse proxies131 unmodified lines13213313413513613713822 unmodified lines161162163164165166167168131 unmodified lines# If set, users can log in with this password instead of the token# OPENCLAW_PASSWORD=your_password_here# ββ OPTIONAL: Chat Integrations ββ# Get bot token from: https://t.me/BotFatherTELEGRAM_BOT_TOKEN=your_bot_token_here22 unmodified lines# Workspace auto-sync interval (seconds). Default: 600.SYNC_INTERVAL=600# Webhooks: Standard POST notifications for lifecycle events# WEBHOOK_URL=https://your-webhook-endpoint.com/log# Trusted proxies (comma-separated IPs)# Fixes "Proxy headers detected from untrusted address" behind reverse proxies
3 unmodified lines4567891011121316 unmodified lines3031323334353637383940414243444546474849505152533 unmodified lines# Multi-stage build: uses pre-built OpenClaw image for fast builds# ββ Stage 1: Pull pre-built OpenClaw ββFROM ghcr.io/openclaw/openclaw:latest AS openclaw# ββ Stage 2: Runtime ββFROM node:22-slim# Install system dependenciesRUN apt-get update && apt-get install -y \16 unmodified lines# Symlink openclaw CLI so it's available globallyRUN ln -s /home/node/.openclaw/openclaw-app/openclaw.mjs /usr/local/bin/openclaw 2>/dev/null || \npm install -g openclaw@latest# Copy HuggingClaw filesCOPY --chown=1000:1000 dns-fix.js /opt/dns-fix.jsCOPY --chown=1000:1000 health-server.js /home/node/app/health-server.jsCOPY --chown=1000:1000 start.sh /home/node/app/start.shCOPY --chown=1000:1000 keep-alive.sh /home/node/app/keep-alive.shCOPY --chown=1000:1000 workspace-sync.py /home/node/app/workspace-sync.pyRUN chmod +x /home/node/app/start.sh /home/node/app/keep-alive.shUSER nodeENV HOME=/home/node \PATH=/home/node/.local/bin:/usr/local/bin:$PATH \NODE_OPTIONS="--require /opt/dns-fix.js"WORKDIR /home/node/appEXPOSE 7860CMD ["/home/node/app/start.sh"]3 unmodified lines45678910111213141516 unmodified lines3233343536373839404142434445464748495051525354555657583 unmodified lines# Multi-stage build: uses pre-built OpenClaw image for fast builds# ββ Stage 1: Pull pre-built OpenClaw ββARG OPENCLAW_VERSION=latestFROM ghcr.io/openclaw/openclaw:${OPENCLAW_VERSION} AS openclaw# ββ Stage 2: Runtime ββFROM node:22-slimARG OPENCLAW_VERSION=latest# Install system dependenciesRUN apt-get update && apt-get install -y \16 unmodified lines# Symlink openclaw CLI so it's available globallyRUN ln -s /home/node/.openclaw/openclaw-app/openclaw.mjs /usr/local/bin/openclaw 2>/dev/null || \npm install -g openclaw@${OPENCLAW_VERSION}# Copy HuggingClaw filesCOPY --chown=1000:1000 dns-fix.js /opt/dns-fix.jsCOPY --chown=1000:1000 health-server.js /home/node/app/health-server.jsCOPY --chown=1000:1000 iframe-fix.cjs /home/node/app/iframe-fix.cjsCOPY --chown=1000:1000 start.sh /home/node/app/start.shCOPY --chown=1000:1000 keep-alive.sh /home/node/app/keep-alive.shCOPY --chown=1000:1000 wa-guardian.js /home/node/app/wa-guardian.jsCOPY --chown=1000:1000 workspace-sync.py /home/node/app/workspace-sync.pyRUN chmod +x /home/node/app/start.sh /home/node/app/keep-alive.shUSER nodeENV HOME=/home/node \OPENCLAW_VERSION=${OPENCLAW_VERSION} \PATH=/home/node/.local/bin:/usr/local/bin:$PATH \NODE_OPTIONS="--require /opt/dns-fix.js"WORKDIR /home/node/appEXPOSE 7861CMD ["/home/node/app/start.sh"]
3 unmodified lines456789104 unmodified lines151617181920211 unmodified line2324252627282912 unmodified lines4243444546474820 unmodified lines69707172737411 unmodified lines8687888990913 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616729 unmodified lines19719819920020120220320455 unmodified lines2602612622632642652663 unmodified linescolorFrom: bluecolorTo: purplesdk: dockerapp_port: 7860pinned: truelicense: mit---4 unmodified lines[](https://huggingface.co/spaces)[](https://github.com/openclaw/openclaw)**Your always-on AI assistant β free, no server needed.** HuggingClaw runs [OpenClaw](https://openclaw.ai) on HuggingFace Spaces, giving you a 24/7 AI chat assistant Telegram. It works with *any* large language model (LLM) β Claude, ChatGPT, Gemini, etc. β and even supports custom models via [OpenRouter](https://openrouter.ai). Deploy in minutes on the free HF Spaces tier (2 vCPU, 16GB RAM, 50GB) with automatic workspace backup to a HuggingFace Dataset so your chat history and settings persist across restarts.## Table of Contents1 unmodified line- [π₯ Video Tutorial](#-video-tutorial)- [π Quick Start](#-quick-start)- [π± Telegram Setup *(Optional)*](#-telegram-setup-optional)- [πΎ Workspace Backup *(Optional)*](#-workspace-backup-optional)- [βοΈ Full Configuration Reference](#-full-configuration-reference)- [π€ LLM Providers](#-llm-providers)- [π» Local Development](#-local-development)12 unmodified lines- π³ **Fast Builds:** Uses a pre-built OpenClaw Docker image to deploy in minutes.- πΎ **Workspace Backup:** Chats and settings sync to a private HF Dataset via the `huggingface_hub` (Git fallback), preserving data automatically.- π **Always-On:** Built-in keep-alive pings prevent the HF Space from sleeping, so the assistant is always online.- π₯ **Multi-User Telegram:** Configure one or more user IDs to control who can message the bot.- π **Flexible Auth:** Secure the Control UI with either a gateway token or password.- π **100% HF-Native:** Runs entirely on HuggingFaceβs free infrastructure (2 vCPU, 16GB RAM).20 unmodified lines> [!TIP]> HuggingClaw is completely flexible! You only need these three secrets to get started. You can set other secrets later.### Step 3: Deploy & RunThat's it! The Space will build the container and start up automatically. You can monitor the build process in the **Logs** tab.11 unmodified linesAfter restarting, the bot should appear online on Telegram.## πΎ Workspace Backup *(Optional)*For persistent chat history and configuration:3 unmodified linesOptionally set `BACKUP_DATASET_NAME` (default: `huggingclaw-backup`) to choose the HF Dataset name. On first run, HuggingClaw will create (or use) the private Dataset repo `HF_USERNAME/SPACE-backup`, then restore your workspace on startup and sync changes every 10 minutes. The workspace is also saved on graceful shutdown. This ensures your data survives restarts.## βοΈ Full Configuration ReferenceSee `.env.example` for complete settings. Key environment variables:### Core| Variable | Description ||----------------|---------------------------------------|| `LLM_API_KEY` | LLM provider API key (e.g. OpenAI, Anthropic, etc.) || `LLM_MODEL` | Model ID (prefix `<provider>/`, auto-detected from prefix) || `GATEWAY_TOKEN`| Gateway token for Control UI access (required) |### Background Services| Variable | Default | Description ||----------------------|---------|-----------------------------------|| `KEEP_ALIVE_INTERVAL`| `300` | Self-ping interval in seconds (0 to disable) || `SYNC_INTERVAL` | `600` | Workspace sync interval (sec.) to HF Dataset |### Security| Variable | Description ||---------------------|---------------------------------------------------|| `OPENCLAW_PASSWORD` | (optional) Enable simple password auth instead of token || `TRUSTED_PROXIES` | Comma-separated IPs of HF proxies (for reverse-proxy fixes) || `ALLOWED_ORIGINS` | Comma-separated allowed origins for Control UI (e.g. `https://your-space.hf.space`) |### Workspace Backup| Variable | Default | Description ||---------------------|-------------------|------------------------------------------------|| `HF_USERNAME` | β | Your HuggingFace username || `HF_TOKEN` | β | HF token with write access (for backups) || `BACKUP_DATASET_NAME`| `huggingclaw-backup`| Dataset name for backup repo (auto-created) || `WORKSPACE_GIT_USER`| `openclaw@example.com` | Git commit email for workspace commits || `WORKSPACE_GIT_NAME`| `OpenClaw Bot` | Git commit name for workspace commits |### Advanced| Variable | Default | Description ||---------------------|-----------|-------------------------------------|| `OPENCLAW_VERSION` | `latest` | Pin a specific OpenClaw version || `HEALTH_PORT` | `7861` | Internal health endpoint port |## π€ LLM ProvidersHuggingClaw supports **all providers** from OpenClaw. Set `LLM_MODEL=<provider/model>` and the provider is auto-detected. For example:| Provider | Prefix | Example Model | API Key Source ||---------------|---------------|--------------------------------|-----------------------------------|| **Anthropic** | `anthropic/` | `anthropic/claude-sonnet-4-6` | [Anthropic Console](https://console.anthropic.com/) || **OpenAI** | `openai/` | `openai/gpt-5.4` | [OpenAI Platform](https://platform.openai.com/) || **Google** | `google/` | `google/gemini-2.5-flash` | [AI Studio](https://ai.google.dev/) || **DeepSeek** | `deepseek/` | `deepseek/deepseek-v3.2` | [DeepSeek](https://platform.deepseek.com) || **xAI (Grok)**| `xai/` | `xai/grok-4` | [xAI](https://console.x.ai) || **Mistral** | `mistral/` | `mistral/mistral-large-latest` | [Mistral Console](https://console.mistral.ai) || **Moonshot** | `moonshot/` | `moonshot/kimi-k2.5` | [Moonshot](https://platform.moonshot.cn) || **Cohere** | `cohere/` | `cohere/command-a` | [Cohere Dashboard](https://dashboard.cohere.com) || **Groq** | `groq/` | `groq/mixtral-8x7b-32768` | [Groq](https://console.groq.com) || **MiniMax** | `minimax/` | `minimax/minimax-m2.7` | [MiniMax](https://platform.minimax.io) || **NVIDIA** | `nvidia/` | `nvidia/nemotron-3-super-120b-a12b` | [NVIDIA API](https://api.nvidia.com) || **Z.ai (GLM)**| `zai/` | `zai/glm-5` | [Z.ai](https://z.ai) || **Volcengine**| `volcengine/` | `volcengine/doubao-seed-1-8-251228` | [Volcengine](https://www.volcengine.com) || **HuggingFace**| `huggingface/`| `huggingface/deepseek-ai/DeepSeek-R1` | [HF Tokens](https://huggingface.co/settings/tokens) || **OpenCode Zen**| `opencode/` | `opencode/claude-opus-4-6` | [OpenCode.ai](https://opencode.ai/auth) || **OpenCode Go**| `opencode-go/`| `opencode-go/kimi-k2.5` | [OpenCode.ai](https://opencode.ai/auth) || **Kilo Gateway**| `kilocode/` | `kilocode/anthropic/claude-opus-4.6` | [Kilo.ai](https://kilo.ai) |### OpenRouter β 200+ Models with One Key29 unmodified lines**With Docker:**```bashdocker build -t huggingclaw .docker run -p 7860:7860 --env-file .env huggingclaw```**Without Docker:**55 unmodified lines- **Space keeps sleeping:** Check logs for `Keep-alive` messages. Ensure `KEEP_ALIVE_INTERVAL` isnβt set to `0`.- **Auth errors / proxy:** If you see reverse-proxy auth errors, add the logged IPs under `TRUSTED_PROXIES` (from logs `remote=x.x.x.x`).- **UI blocked (CORS):** Set `ALLOWED_ORIGINS=https://your-space-name.hf.space`.- **Version mismatches:** You can pin a specific OpenClaw version via the `OPENCLAW_VERSION` secret.## π Links3 unmodified lines45678910114 unmodified lines161718192021221 unmodified line2425262728293031323312 unmodified lines46474849505152535420 unmodified lines757677787980818211 unmodified lines9495969798991001011021031041051061073 unmodified lines11111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619729 unmodified lines22722822923023123223323455 unmodified lines2902912922932942952963 unmodified linescolorFrom: bluecolorTo: purplesdk: dockerapp_port: 7861base_path: /dashboardpinned: truelicense: mit---4 unmodified lines[](https://huggingface.co/spaces)[](https://github.com/openclaw/openclaw)**Your always-on AI assistant β free, no server needed.** HuggingClaw runs [OpenClaw](https://openclaw.ai) on HuggingFace Spaces, giving you a 24/7 AI chat assistant on Telegram and WhatsApp. It works with *any* large language model (LLM) β Claude, ChatGPT, Gemini, etc. β and even supports custom models via [OpenRouter](https://openrouter.ai). Deploy in minutes on the free HF Spaces tier (2 vCPU, 16GB RAM, 50GB) with automatic workspace backup to a HuggingFace Dataset so your chat history and settings persist across restarts.## Table of Contents1 unmodified line- [π₯ Video Tutorial](#-video-tutorial)- [π Quick Start](#-quick-start)- [π± Telegram Setup *(Optional)*](#-telegram-setup-optional)- [π¬ WhatsApp Setup *(Optional)*](#-whatsapp-setup-optional)- [πΎ Workspace Backup *(Optional)*](#-workspace-backup-optional)- [π Dashboard & Monitoring](#-dashboard--monitoring)- [π Webhooks *(Optional)*](#-webhooks-optional)- [βοΈ Full Configuration Reference](#-full-configuration-reference)- [π€ LLM Providers](#-llm-providers)- [π» Local Development](#-local-development)12 unmodified lines- π³ **Fast Builds:** Uses a pre-built OpenClaw Docker image to deploy in minutes.- πΎ **Workspace Backup:** Chats and settings sync to a private HF Dataset via the `huggingface_hub` (Git fallback), preserving data automatically.- π **Always-On:** Built-in keep-alive pings prevent the HF Space from sleeping, so the assistant is always online.- π₯ **Multi-User Messaging:** Support for Telegram (multi-user) and WhatsApp (pairing).- π **Visual Dashboard:** Beautiful Web UI to monitor uptime, sync status, and active models.- π **Webhooks:** Get notified on restarts or backup failures via standard webhooks.- π **Flexible Auth:** Secure the Control UI with either a gateway token or password.- π **100% HF-Native:** Runs entirely on HuggingFaceβs free infrastructure (2 vCPU, 16GB RAM).20 unmodified lines> [!TIP]> HuggingClaw is completely flexible! You only need these three secrets to get started. You can set other secrets later.Optional: if you want to pin a specific OpenClaw release instead of `latest`, add `OPENCLAW_VERSION` under **Variables** in your Space settings. For Docker Spaces, HF passes Variables as build args during image build, so this should be a Variable, not a Secret.### Step 3: Deploy & RunThat's it! The Space will build the container and start up automatically. You can monitor the build process in the **Logs** tab.11 unmodified linesAfter restarting, the bot should appear online on Telegram.## π¬ WhatsApp Setup *(Optional)*To use WhatsApp:1. Visit your Space URL. It opens the dashboard at `/dashboard` by default, then click **Open Control UI**.2. In the Control UI, go to **Channels** β **WhatsApp** β **Login**.3. Scan the QR code with your phone. π±## πΎ Workspace Backup *(Optional)*For persistent chat history and configuration:3 unmodified linesOptionally set `BACKUP_DATASET_NAME` (default: `huggingclaw-backup`) to choose the HF Dataset name. On first run, HuggingClaw will create (or use) the private Dataset repo `HF_USERNAME/SPACE-backup`, then restore your workspace on startup and sync changes every 10 minutes. The workspace is also saved on graceful shutdown. This ensures your data survives restarts.## π Dashboard & MonitoringHuggingClaw now features a built-in dashboard at `/dashboard`, served from the same public HF Space URL as the Control UI:- **Uptime Tracking:** Real-time uptime monitoring.- **Sync Status:** Visual indicators for workspace backup operations.- **Model Info:** See which LLM is currently powering your assistant.## π Webhooks *(Optional)*Get notified when your Space restarts or if a backup fails:- Set `WEBHOOK_URL` to your endpoint (e.g., Make.com, IFTTT, Discord Webhook).- HuggingClaw sends a POST JSON payload with event details.## βοΈ Full Configuration ReferenceSee `.env.example` for runtime settings. Key configuration values:### Core| Variable | Description ||-----------------|-------------------------------------------------------------|| `LLM_API_KEY` | LLM provider API key (e.g. OpenAI, Anthropic, etc.) || `LLM_MODEL` | Model ID (prefix `<provider>/`, auto-detected from prefix) || `GATEWAY_TOKEN` | Gateway token for Control UI access (required) |### Background Services| Variable | Default | Description ||-----------------------|---------|---------------------------------------------|| `KEEP_ALIVE_INTERVAL` | `300` | Self-ping interval in seconds (0 to disable)|| `SYNC_INTERVAL` | `600` | Workspace sync interval (sec.) to HF Dataset|### Security| Variable | Description ||----------------------|---------------------------------------------------------|| `OPENCLAW_PASSWORD` | (optional) Enable simple password auth instead of token || `TRUSTED_PROXIES` | Comma-separated IPs of HF proxies || `ALLOWED_ORIGINS` | Comma-separated allowed origins for Control UI |### Workspace Backup| Variable | Default | Description ||-----------------------|----------------------|--------------------------------------|| `HF_USERNAME` | β | Your HuggingFace username || `HF_TOKEN` | β | HF token with write access || `BACKUP_DATASET_NAME` | `huggingclaw-backup` | Dataset name for backup repo || `WORKSPACE_GIT_USER` | `openclaw@example.com`| Git commit email for workspace sync || `WORKSPACE_GIT_NAME` | `OpenClaw Bot` | Git commit name for workspace sync |### Advanced| Variable | Default | Description ||--------------------|----------|-------------------------------------|| `OPENCLAW_VERSION` | `latest` | Build-time pin for the OpenClaw image tag |## π€ LLM ProvidersHuggingClaw supports **all providers** from OpenClaw. Set `LLM_MODEL=<provider/model>` and the provider is auto-detected. For example:| Provider | Prefix | Example Model | API Key Source ||------------------|-----------------|---------------------------------------|------------------------------------------------------|| **Anthropic** | `anthropic/` | `anthropic/claude-sonnet-4-6` | [Anthropic Console](https://console.anthropic.com/) || **OpenAI** | `openai/` | `openai/gpt-5.4` | [OpenAI Platform](https://platform.openai.com/) || **Google** | `google/` | `google/gemini-2.5-flash` | [AI Studio](https://ai.google.dev/) || **DeepSeek** | `deepseek/` | `deepseek/deepseek-v3.2` | [DeepSeek](https://platform.deepseek.com) || **xAI (Grok)** | `xai/` | `xai/grok-4` | [xAI](https://console.x.ai) || **Mistral** | `mistral/` | `mistral/mistral-large-latest` | [Mistral Console](https://console.mistral.ai) || **Moonshot** | `moonshot/` | `moonshot/kimi-k2.5` | [Moonshot](https://platform.moonshot.cn) || **Cohere** | `cohere/` | `cohere/command-a` | [Cohere Dashboard](https://dashboard.cohere.com) || **Groq** | `groq/` | `groq/mixtral-8x7b-32768` | [Groq](https://console.groq.com) || **MiniMax** | `minimax/` | `minimax/minimax-m2.7` | [MiniMax](https://platform.minimax.io) || **NVIDIA** | `nvidia/` | `nvidia/nemotron-3-super-120b-a12b` | [NVIDIA API](https://api.nvidia.com) || **Z.ai (GLM)** | `zai/` | `zai/glm-5` | [Z.ai](https://z.ai) || **Volcengine** | `volcengine/` | `volcengine/doubao-seed-1-8-251228` | [Volcengine](https://www.volcengine.com) || **HuggingFace** | `huggingface/` | `huggingface/deepseek-ai/DeepSeek-R1` | [HF Tokens](https://huggingface.co/settings/tokens) || **OpenCode Zen** | `opencode/` | `opencode/claude-opus-4-6` | [OpenCode.ai](https://opencode.ai/auth) || **OpenCode Go** | `opencode-go/` | `opencode-go/kimi-k2.5` | [OpenCode.ai](https://opencode.ai/auth) || **Kilo Gateway** | `kilocode/` | `kilocode/anthropic/claude-opus-4.6` | [Kilo.ai](https://kilo.ai) |### OpenRouter β 200+ Models with One Key29 unmodified lines**With Docker:**```bashdocker build --build-arg OPENCLAW_VERSION=latest -t huggingclaw .docker run -p 7861:7861 --env-file .env huggingclaw```**Without Docker:**55 unmodified lines- **Space keeps sleeping:** Check logs for `Keep-alive` messages. Ensure `KEEP_ALIVE_INTERVAL` isnβt set to `0`.- **Auth errors / proxy:** If you see reverse-proxy auth errors, add the logged IPs under `TRUSTED_PROXIES` (from logs `remote=x.x.x.x`).- **UI blocked (CORS):** Set `ALLOWED_ORIGINS=https://your-space-name.hf.space`.- **Version mismatches:** Pin a specific OpenClaw build with the `OPENCLAW_VERSION` Variable in HF Spaces, or `--build-arg OPENCLAW_VERSION=...` locally.## π Links
12345678910111213141516171819// Fix HF Spaces DNS: internal resolver can't resolve discord.com / api.telegram.org// Override dns.lookup (used by http/https) to use Google/Cloudflare DNSconst dns = require('dns');const { Resolver } = dns;const resolver = new Resolver();resolver.setServers(['8.8.8.8', '1.1.1.1']);const origLookup = dns.lookup;dns.lookup = function(hostname, options, callback) {if (typeof options === 'function') { callback = options; options = { family: 0 }; }resolver.resolve4(hostname, (err, addresses) => {if (err || !addresses || !addresses.length) return origLookup.call(dns, hostname, options, callback);if (options && options.all) {callback(null, addresses.map(a => ({ address: a, family: 4 })));} else {callback(null, addresses[0], 4);}});};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108/*** DNS fix preload script for HF Spaces.** Patches Node.js dns.lookup to:* 1. Try system DNS first* 2. Fall back to DNS-over-HTTPS (Cloudflare) if system DNS fails* (This is needed because HF Spaces intercepts/blocks some domains like* WhatsApp web or Telegram API via standard UDP DNS).** Loaded via: NODE_OPTIONS="--require /opt/dns-fix.js"*/"use strict";const dns = require("dns");const https = require("https");// In-memory cache for runtime DoH resolutionsconst runtimeCache = new Map(); // hostname -> { ip, expiry }// DNS-over-HTTPS resolverfunction dohResolve(hostname, callback) {// Check runtime cacheconst cached = runtimeCache.get(hostname);if (cached && cached.expiry > Date.now()) {return callback(null, cached.ip);}const url = `https://1.1.1.1/dns-query?name=${encodeURIComponent(hostname)}&type=A`;const req = https.get(url,{ headers: { Accept: "application/dns-json" }, timeout: 15000 },(res) => {let body = "";res.on("data", (c) => (body += c));res.on("end", () => {try {const data = JSON.parse(body);const aRecords = (data.Answer || []).filter((a) => a.type === 1);if (aRecords.length === 0) {return callback(new Error(`DoH: no A record for ${hostname}`));}const ip = aRecords[0].data;const ttl = Math.max((aRecords[0].TTL || 300) * 1000, 60000);runtimeCache.set(hostname, { ip, expiry: Date.now() + ttl });callback(null, ip);} catch (e) {callback(new Error(`DoH parse error: ${e.message}`));}});});req.on("error", (e) => callback(new Error(`DoH request failed: ${e.message}`)));req.on("timeout", () => {req.destroy();callback(new Error("DoH request timed out"));});}// Monkey-patch dns.lookupconst origLookup = dns.lookup;dns.lookup = function patchedLookup(hostname, options, callback) {// Normalize arguments (options is optional, can be number or object)if (typeof options === "function") {callback = options;options = {};}if (typeof options === "number") {options = { family: options };}options = options || {};// Skip patching for localhost, IPs, and internal domainsif (!hostname ||hostname === "localhost" ||hostname === "0.0.0.0" ||hostname === "127.0.0.1" ||hostname === "::1" ||/^\d+\.\d+\.\d+\.\d+$/.test(hostname) ||/^::/.test(hostname)) {return origLookup.call(dns, hostname, options, callback);}// 1) Try system DNS firstorigLookup.call(dns, hostname, options, (err, address, family) => {if (!err && address) {return callback(null, address, family);}// 2) System DNS failed with ENOTFOUND or EAI_AGAIN β fall back to DoHif (err && (err.code === "ENOTFOUND" || err.code === "EAI_AGAIN")) {dohResolve(hostname, (dohErr, ip) => {if (dohErr || !ip) {return callback(err); // Return original error}if (options.all) {return callback(null, [{ address: ip, family: 4 }]);}callback(null, ip, 4);});} else {// Other DNS errors β pass throughcallback(err, address, family);}});};
123456789101112131415161718192021222324252627// Lightweight health endpoint on port 7861// OpenClaw runs on 7860, this runs alongside it// Returns 200 OK for keep-alive pings and external monitoringconst http = require('http');const PORT = process.env.HEALTH_PORT || 7861;const startTime = Date.now();const server = http.createServer((req, res) => {if (req.url === '/health' || req.url === '/') {const uptime = Math.floor((Date.now() - startTime) / 1000);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({status: 'ok',uptime: uptime,uptimeHuman: `${Math.floor(uptime / 3600)}h ${Math.floor((uptime % 3600) / 60)}m`,timestamp: new Date().toISOString()}));} else {res.writeHead(404);res.end();}});server.listen(PORT, '0.0.0.0', () => {console.log(`π₯ Health server listening on port ${PORT}`);});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475// Single public entrypoint for HF Spaces: local dashboard + reverse proxy to OpenClaw.const http = require("http");const fs = require("fs");const net = require("net");const PORT = 7861;const GATEWAY_PORT = 7860;const GATEWAY_HOST = "127.0.0.1";const startTime = Date.now();const LLM_MODEL = process.env.LLM_MODEL || "Not Set";const TELEGRAM_ENABLED = !!process.env.TELEGRAM_BOT_TOKEN;function getPathname(url) {try {return new URL(url, "http://localhost").pathname;} catch {return "/";}}function isDashboardRoute(pathname) {return pathname === "/dashboard" || pathname === "/dashboard/";}function isLocalRoute(pathname) {return (pathname === "/health" ||pathname === "/status" ||isDashboardRoute(pathname));}function appendForwarded(existingValue, nextValue) {const cleanNext = nextValue || "";if (!existingValue) return cleanNext;if (Array.isArray(existingValue))return `${existingValue.join(", ")}, ${cleanNext}`;return `${existingValue}, ${cleanNext}`;}function buildProxyHeaders(headers, remoteAddress) {return {...headers,host: headers.host || `${GATEWAY_HOST}:${GATEWAY_PORT}`,"x-forwarded-for": appendForwarded(headers["x-forwarded-for"],remoteAddress,),"x-forwarded-host": headers["x-forwarded-host"] || headers.host || "","x-forwarded-proto": headers["x-forwarded-proto"] || "https",};}function readSyncStatus() {try {if (fs.existsSync("/tmp/sync-status.json")) {return JSON.parse(fs.readFileSync("/tmp/sync-status.json", "utf8"));}} catch {}return { status: "unknown", message: "No sync data yet" };}function renderDashboard() {return `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>HuggingClaw Dashboard</title><link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600&display=swap" rel="stylesheet"><style>:root {--bg: #0f172a;--card-bg: rgba(30, 41, 59, 0.7);--accent: linear-gradient(135deg, #3b82f6, #8b5cf6);--text: #f8fafc;--text-dim: #94a3b8;--success: #10b981;--error: #ef4444;--warning: #f59e0b;}* { box-sizing: border-box; margin: 0; padding: 0; }body {font-family: 'Outfit', sans-serif;background-color: var(--bg);color: var(--text);display: flex;justify-content: center;align-items: center;min-height: 100vh;overflow: hidden;background-image:radial-gradient(at 0% 0%, rgba(59, 130, 246, 0.15) 0px, transparent 50%),radial-gradient(at 100% 0%, rgba(139, 92, 246, 0.15) 0px, transparent 50%);}.dashboard {width: 90%;max-width: 600px;background: var(--card-bg);backdrop-filter: blur(12px);border: 1px solid rgba(255, 255, 255, 0.1);border-radius: 24px;padding: 40px;box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);animation: fadeIn 0.8s ease-out;}@keyframes fadeIn {from { opacity: 0; transform: translateY(20px); }to { opacity: 1; transform: translateY(0); }}header {text-align: center;margin-bottom: 40px;}h1 {font-size: 2.5rem;margin-bottom: 8px;background: var(--accent);-webkit-background-clip: text;-webkit-text-fill-color: transparent;font-weight: 600;}.subtitle {color: var(--text-dim);font-size: 0.9rem;letter-spacing: 1px;text-transform: uppercase;}.stats-grid {display: grid;grid-template-columns: repeat(2, 1fr);gap: 20px;margin-bottom: 30px;}.stat-card {background: rgba(255, 255, 255, 0.03);border: 1px solid rgba(255, 255, 255, 0.05);padding: 20px;border-radius: 16px;transition: transform 0.3s ease, border-color 0.3s ease;}.stat-card:hover {transform: translateY(-5px);border-color: rgba(59, 130, 246, 0.3);}.stat-label {color: var(--text-dim);font-size: 0.75rem;text-transform: uppercase;margin-bottom: 8px;display: block;}.stat-value {font-size: 1.1rem;font-weight: 600;word-break: break-all;}.stat-btn {grid-column: span 2;background: var(--accent);color: #fff;padding: 16px;border-radius: 16px;text-align: center;text-decoration: none;font-weight: 600;margin-top: 10px;transition: transform 0.3s ease, box-shadow 0.3s ease;box-shadow: 0 10px 20px -5px rgba(59, 130, 246, 0.4);}.stat-btn:hover {transform: scale(1.02);box-shadow: 0 15px 30px -5px rgba(59, 130, 246, 0.6);}.status-badge {display: inline-flex;align-items: center;gap: 6px;padding: 4px 12px;border-radius: 20px;font-size: 0.8rem;font-weight: 600;}.status-online { background: rgba(16, 185, 129, 0.1); color: var(--success); }.status-offline { background: rgba(239, 68, 68, 0.1); color: var(--error); }.status-syncing { background: rgba(59, 130, 246, 0.1); color: #3b82f6; }.pulse {width: 8px;height: 8px;border-radius: 50%;background: currentColor;box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);animation: pulse 2s infinite;}@keyframes pulse {0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }70% { transform: scale(1); box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); }100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }}.footer {text-align: center;color: var(--text-dim);font-size: 0.8rem;margin-top: 20px;}.sync-info {background: rgba(255, 255, 255, 0.02);padding: 15px;border-radius: 12px;font-size: 0.85rem;color: var(--text-dim);margin-top: 10px;}#sync-msg { color: var(--text); display: block; margin-top: 4px; }</style></head><body><div class="dashboard"><header><h1>π¦ HuggingClaw</h1><p class="subtitle">Space Dashboard</p></header><div class="stats-grid"><div class="stat-card"><span class="stat-label">Model</span><span class="stat-value" id="model-id">Loading...</span></div><div class="stat-card"><span class="stat-label">Uptime</span><span class="stat-value" id="uptime">Loading...</span></div><div class="stat-card"><span class="stat-label">WhatsApp</span><span id="wa-status">Loading...</span></div><div class="stat-card"><span class="stat-label">Telegram</span><span id="tg-status">Loading...</span></div><a href="/" class="stat-btn">Open Control UI</a></div><div class="stat-card" style="width: 100%;"><span class="stat-label">Workspace Sync Status</span><div id="sync-badge-container"></div><div class="sync-info">Last Sync Activity: <span id="sync-time">Never</span><span id="sync-msg">Initializing synchronization...</span></div></div><div class="footer">Live updates every 10s</div></div><script>async function updateStats() {try {const res = await fetch('/status');const data = await res.json();document.getElementById('model-id').textContent = data.model;document.getElementById('uptime').textContent = data.uptime;document.getElementById('wa-status').innerHTML = data.whatsapp? '<div class="status-badge status-online"><div class="pulse"></div>Active</div>': '<div class="status-badge status-offline">Disabled</div>';document.getElementById('tg-status').innerHTML = data.telegram? '<div class="status-badge status-online"><div class="pulse"></div>Active</div>': '<div class="status-badge status-offline">Disabled</div>';const syncData = data.sync;let badgeClass = 'status-offline';let pulseHtml = '';if (syncData.status === 'success') {badgeClass = 'status-online';pulseHtml = '<div class="pulse"></div>';} else if (syncData.status === 'syncing') {badgeClass = 'status-syncing';pulseHtml = '<div class="pulse" style="background:#3b82f6"></div>';}document.getElementById('sync-badge-container').innerHTML ='<div class="status-badge ' + badgeClass + '">' + pulseHtml + syncData.status.toUpperCase() + '</div>';document.getElementById('sync-time').textContent = syncData.timestamp || 'Never';document.getElementById('sync-msg').textContent = syncData.message || 'Waiting for first sync...';} catch (e) {console.error("Failed to fetch status", e);}}updateStats();setInterval(updateStats, 10000);</script></body></html>`;}function proxyHttp(req, res) {const proxyReq = http.request({hostname: GATEWAY_HOST,port: GATEWAY_PORT,method: req.method,path: req.url,headers: buildProxyHeaders(req.headers, req.socket.remoteAddress),},(proxyRes) => {res.writeHead(proxyRes.statusCode || 502, proxyRes.headers);proxyRes.pipe(res);},);proxyReq.on("error", (error) => {res.writeHead(502, { "Content-Type": "application/json" });res.end(JSON.stringify({status: "error",message: "Gateway unavailable",detail: error.message,}),);});req.pipe(proxyReq);}function serializeUpgradeHeaders(req, remoteAddress) {const forwardedHeaders = [];for (let i = 0; i < req.rawHeaders.length; i += 2) {const name = req.rawHeaders[i];const value = req.rawHeaders[i + 1];const lower = name.toLowerCase();if (lower === "x-forwarded-for" ||lower === "x-forwarded-host" ||lower === "x-forwarded-proto") {continue;}forwardedHeaders.push(`${name}: ${value}`);}forwardedHeaders.push(`X-Forwarded-For: ${appendForwarded(req.headers["x-forwarded-for"], remoteAddress)}`,);forwardedHeaders.push(`X-Forwarded-Host: ${req.headers["x-forwarded-host"] || req.headers.host || ""}`,);forwardedHeaders.push(`X-Forwarded-Proto: ${req.headers["x-forwarded-proto"] || "https"}`,);return forwardedHeaders;}function proxyUpgrade(req, socket, head) {const proxySocket = net.connect(GATEWAY_PORT, GATEWAY_HOST);proxySocket.on("connect", () => {const requestLines = [`${req.method} ${req.url} HTTP/${req.httpVersion}`,...serializeUpgradeHeaders(req, req.socket.remoteAddress),"","",];proxySocket.write(requestLines.join("\r\n"));if (head && head.length > 0) {proxySocket.write(head);}socket.pipe(proxySocket).pipe(socket);});proxySocket.on("error", () => {if (socket.writable) {socket.write("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n");}socket.destroy();});socket.on("error", () => {proxySocket.destroy();});}const server = http.createServer((req, res) => {const pathname = getPathname(req.url || "/");const uptime = Math.floor((Date.now() - startTime) / 1000);const uptimeHuman = `${Math.floor(uptime / 3600)}h ${Math.floor((uptime % 3600) / 60)}m`;if (pathname === "/health") {res.writeHead(200, { "Content-Type": "application/json" });res.end(JSON.stringify({status: "ok",uptime,uptimeHuman,timestamp: new Date().toISOString(),}),);return;}if (pathname === "/status") {res.writeHead(200, { "Content-Type": "application/json" });res.end(JSON.stringify({model: LLM_MODEL,whatsapp: true,telegram: TELEGRAM_ENABLED,sync: readSyncStatus(),uptime: uptimeHuman,}),);return;}if (isDashboardRoute(pathname)) {res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });res.end(renderDashboard());return;}proxyHttp(req, res);});server.on("upgrade", (req, socket, head) => {const pathname = getPathname(req.url || "/");if (isLocalRoute(pathname)) {socket.destroy();return;}proxyUpgrade(req, socket, head);});server.listen(PORT, "0.0.0.0", () => {console.log(`Health server listening on port ${PORT}; proxying gateway traffic to ${GATEWAY_HOST}:${GATEWAY_PORT}`,);});
123456789101112131415161718192021222324252627282930313233343536373839404142434445/** * iframe-fix.cjs β Node.js preload script * * Intercepts OpenClaw's HTTP server to: * 1. Allow iframe embedding (strip X-Frame-Options, fix CSP) */'use strict';
const http = require('http');
console.log('[iframe-fix] Initialized: Allowing iframe embedding for *.hf.space and huggingface.co');
const origEmit = http.Server.prototype.emit;
http.Server.prototype.emit = function (event, ...args) { if (event === 'request') { const [, res] = args;
// Only intercept on the main OpenClaw server (port 7860) const serverPort = this.address && this.address() && this.address().port; if (serverPort && serverPort !== 7860) { return origEmit.apply(this, [event, ...args]); }
// Fix iframe embedding β must be applied BEFORE any early returns const origWriteHead = res.writeHead; res.writeHead = function (statusCode, ...whArgs) { if (res.getHeader) { // Strip X-Frame-Options so it can load in a Hugging Face Space iframe res.removeHeader('x-frame-options'); // Update Content-Security-Policy if it contains frame-ancestors 'none' const csp = res.getHeader('content-security-policy'); if (csp && typeof csp === 'string') { res.setHeader('content-security-policy', csp.replace(/frame-ancestors\s+'none'/i, "frame-ancestors 'self' https://huggingface.co https://*.hf.space")); } } return origWriteHead.apply(this, [statusCode, ...whArgs]); }; }
return origEmit.apply(this, [event, ...args]);};17 unmodified lines181920212223242517 unmodified linesexit 0fi# Ping the Space URL β any HTTP response (even 404) counts as activityPING_URL="https://${SPACE_HOST}"echo "π Keep-alive started: pinging ${PING_URL} every ${INTERVAL}s"17 unmodified lines181920212223242517 unmodified linesexit 0fi# Ping the health endpoint so we keep the Space warm without touching the gatewayPING_URL="https://${SPACE_HOST}/health"echo "π Keep-alive started: pinging ${PING_URL} every ${INTERVAL}s"
233 unmodified lines2342352362372382392402412422432442452462472482492502512522532547 unmodified lines2622632642652662672 unmodified lines27027127227327427527627727821 unmodified lines300301302303304305306307308309310311312313314315233 unmodified linesfifi# Write configecho "$CONFIG_JSON" > "/home/node/.openclaw/openclaw.json"chmod 600 /home/node/.openclaw/openclaw.json# ββ Startup Summary ββecho ""echo " ββββββββββββββββββββββββββββββββββββββββββββ"echo " β π Configuration Summary β"echo " ββββββββββββββββββββββββββββββββββββββββββββ€"printf " β %-40s β\n" "Model: $LLM_MODEL"if [ -n "$TELEGRAM_BOT_TOKEN" ]; thenprintf " β %-40s β\n" "Telegram: β enabled"elseprintf " β %-40s β\n" "Telegram: β not configured"fiif [ -n "$HF_USERNAME" ] && [ -n "$HF_TOKEN" ]; thenprintf " β %-40s β\n" "Backup: β ${HF_USERNAME}/${BACKUP_DATASET:-huggingclaw-backup}"else7 unmodified linesif [ -n "$SPACE_HOST" ]; thenprintf " β %-40s β\n" "Keep-alive: β every ${KEEP_ALIVE_INTERVAL:-300}s"printf " β %-40s β\n" "Control UI: https://${SPACE_HOST}"elseprintf " β %-40s β\n" "Keep-alive: βΈοΈ local mode"fi2 unmodified linesSYNC_STATUS="β every ${SYNC_INTERVAL:-600}s"fiprintf " β %-40s β\n" "Auto-sync: $SYNC_STATUS"echo " ββββββββββββββββββββββββββββββββββββββββββββ"echo ""# ββ Trap SIGTERM for graceful shutdown ββgraceful_shutdown() {echo ""21 unmodified linestrap graceful_shutdown SIGTERM SIGINT# ββ Start background services ββnode /home/node/app/health-server.js &/home/node/app/keep-alive.sh &python3 /home/node/app/workspace-sync.py &# ββ Launch gateway ββecho "π Launching OpenClaw gateway on port 7860..."echo ""# Set model via environment for the gatewayexport LLM_MODEL="$LLM_MODEL"233 unmodified lines2342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632647 unmodified lines2722732742752762772782 unmodified lines28128228328428528628728828929029129229329429529629729829930021 unmodified lines322323324325326327328329330331332333334335336337338339340341342343344345346347233 unmodified linesfifiCONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.plugins.entries.whatsapp = {"enabled": true}')CONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.channels.whatsapp = {"dmPolicy": "pairing"}')# Write configecho "$CONFIG_JSON" > "/home/node/.openclaw/openclaw.json"chmod 600 /home/node/.openclaw/openclaw.json# ββ Enable Iframe Fix (Security: No Token Redirect) ββ# This Node.js preload script strips X-Frame-Options to allow HF Space embeddingexport NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require /home/node/app/iframe-fix.cjs"# ββ Startup Summary ββecho ""echo " ββββββββββββββββββββββββββββββββββββββββββββ"echo " β π Configuration Summary β"echo " ββββββββββββββββββββββββββββββββββββββββββββ€"printf " β %-40s β\n" "OpenClaw: $OPENCLAW_VERSION"printf " β %-40s β\n" "Model: $LLM_MODEL"if [ -n "$TELEGRAM_BOT_TOKEN" ]; thenprintf " β %-40s β\n" "Telegram: β enabled"elseprintf " β %-40s β\n" "Telegram: β not configured"fiprintf " β %-40s β\n" "WhatsApp: β enabled"if [ -n "$HF_USERNAME" ] && [ -n "$HF_TOKEN" ]; thenprintf " β %-40s β\n" "Backup: β ${HF_USERNAME}/${BACKUP_DATASET:-huggingclaw-backup}"else7 unmodified linesif [ -n "$SPACE_HOST" ]; thenprintf " β %-40s β\n" "Keep-alive: β every ${KEEP_ALIVE_INTERVAL:-300}s"printf " β %-40s β\n" "Control UI: https://${SPACE_HOST}"printf " β %-40s β\n" "Dashboard: https://${SPACE_HOST}/dashboard"elseprintf " β %-40s β\n" "Keep-alive: βΈοΈ local mode"fi2 unmodified linesSYNC_STATUS="β every ${SYNC_INTERVAL:-600}s"fiprintf " β %-40s β\n" "Auto-sync: $SYNC_STATUS"if [ -n "$WEBHOOK_URL" ]; thenprintf " β %-40s β\n" "Webhooks: β enabled"fiecho " ββββββββββββββββββββββββββββββββββββββββββββ"echo ""# ββ Trigger Webhook on Restart ββif [ -n "$WEBHOOK_URL" ]; thenecho "π Sending restart webhook..."curl -s -X POST "$WEBHOOK_URL" \-H "Content-Type: application/json" \-d '{"event":"restart", "status":"success", "message":"HuggingClaw gateway has started/restarted.", "model": "'"$LLM_MODEL"'"}' >/dev/null 2>&1 &fi# ββ Trap SIGTERM for graceful shutdown ββgraceful_shutdown() {echo ""21 unmodified linestrap graceful_shutdown SIGTERM SIGINT# ββ Start background services ββexport LLM_MODEL="$LLM_MODEL"# 10. Start Health Server & Dashboardnode /home/node/app/health-server.js &HEALTH_PID=$!# 11. Start HF keep-alive/home/node/app/keep-alive.sh &KEEP_ALIVE_PID=$!# 12. Start WhatsApp Guardian (Automates pairing)node /home/node/app/wa-guardian.js &GUARDIAN_PID=$!echo "π‘οΈ WhatsApp Guardian started (PID: $GUARDIAN_PID)"# 13. Start Workspace Syncpython3 -u /home/node/app/workspace-sync.py &# ββ Launch gateway ββecho "π Launching OpenClaw gateway on port 7860..."echo ""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126/** * HuggingClaw WhatsApp Guardian * * Automates the WhatsApp pairing process on HuggingFace Spaces. * Handles the "515 Restart" by monitoring the channel status and * re-applying the configuration after a successful scan. */"use strict";
const { WebSocket } = require('/home/node/.openclaw/openclaw-app/node_modules/ws');const { randomUUID } = require('node:crypto');
const GATEWAY_URL = "ws://127.0.0.1:7860";const GATEWAY_TOKEN = process.env.GATEWAY_TOKEN || "huggingclaw";const CHECK_INTERVAL = 5000;const WAIT_TIMEOUT = 120000;
let isWaiting = false;let hasShownWaitMessage = false;
async function createConnection() { return new Promise((resolve, reject) => { const ws = new WebSocket(GATEWAY_URL); let resolved = false;
ws.on("message", (data) => { const msg = JSON.parse(data.toString());
if (msg.type === "event" && msg.event === "connect.challenge") { ws.send(JSON.stringify({ type: "req", id: randomUUID(), method: "connect", params: { auth: { token: GATEWAY_TOKEN }, client: { id: "wa-guardian", platform: "linux", mode: "backend", version: "1.0.0" }, scopes: ["operator.admin", "operator.pairing", "operator.read", "operator.write"] } })); return; }
if (!resolved && msg.type === "res" && msg.ok) { resolved = true; resolve(ws); } });
ws.on("error", (e) => { if (!resolved) reject(e); }); setTimeout(() => { if (!resolved) { ws.close(); reject(new Error("Timeout")); } }, 10000); });}
async function callRpc(ws, method, params) { return new Promise((resolve, reject) => { const id = randomUUID(); const handler = (data) => { const msg = JSON.parse(data.toString()); if (msg.id === id) { ws.removeListener("message", handler); resolve(msg); } }; ws.on("message", handler); ws.send(JSON.stringify({ type: "req", id, method, params })); setTimeout(() => { ws.removeListener("message", handler); reject(new Error("RPC Timeout")); }, WAIT_TIMEOUT + 5000); });}
async function checkStatus() { if (isWaiting) return;
let ws; try { ws = await createConnection();
// Check if WhatsApp channel exists and its status const statusRes = await callRpc(ws, "channels.status", {}); const channels = (statusRes.payload || statusRes.result)?.channels || {}; const wa = channels.whatsapp;
if (!wa) { ws.close(); return; }
// If connected, we are good if (wa.connected) { ws.close(); return; }
// If "Ready to pair", we wait for the scan isWaiting = true; if (!hasShownWaitMessage) { console.log("\n[guardian] π± WhatsApp pairing in progress. Please scan the QR code in the Control UI."); hasShownWaitMessage = true; }
console.log("[guardian] Waiting for pairing completion..."); const waitRes = await callRpc(ws, "web.login.wait", { timeoutMs: WAIT_TIMEOUT }); const result = waitRes.payload || waitRes.result;
if (result && (result.connected || (result.message && result.message.includes("515")))) { console.log("[guardian] β
Pairing completed! Saving session and restarting gateway..."); hasShownWaitMessage = false; // Auto-reapply config to finalize pairing const getRes = await callRpc(ws, "config.get", {}); if (getRes.ok) { await callRpc(ws, "config.apply", { raw: getRes.payload.raw, baseHash: getRes.payload.hash }); console.log("[guardian] Configuration re-applied."); } }
} catch (e) { // Normal timeout or gateway starting up } finally { isWaiting = false; if (ws) ws.close(); }}
console.log("[guardian] βοΈ WhatsApp Guardian active. Monitoring pairing status...");setInterval(checkStatus, CHECK_INTERVAL);setTimeout(checkStatus, 10000);18 unmodified lines19202122232417 unmodified lines42434445464780 unmodified lines12812913013113213313413513613713813914014114214314414514614714818 unmodified linesHF_TOKEN = os.environ.get("HF_TOKEN", "")HF_USERNAME = os.environ.get("HF_USERNAME", "")BACKUP_DATASET = os.environ.get("BACKUP_DATASET_NAME", "huggingclaw-backup")running = True17 unmodified linesexcept Exception:return Falsedef sync_with_hf_hub():"""Sync workspace using huggingface_hub library."""80 unmodified linescontinuets = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())if use_hf_hub:if sync_with_hf_hub():print(f"π Workspace sync (hf_hub): pushed changes ({ts})")else:# Fallback to gitif sync_with_git():print(f"π Workspace sync (git fallback): pushed changes ({ts})")else:print(f"π Workspace sync: failed ({ts}), will retry")else:if sync_with_git():print(f"π Workspace sync (git): pushed changes ({ts})")else:print(f"π Workspace sync: push failed ({ts}), will retry")if __name__ == "__main__":18 unmodified lines1920212223242517 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980 unmodified lines16016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019118 unmodified linesHF_TOKEN = os.environ.get("HF_TOKEN", "")HF_USERNAME = os.environ.get("HF_USERNAME", "")BACKUP_DATASET = os.environ.get("BACKUP_DATASET_NAME", "huggingclaw-backup")WEBHOOK_URL = os.environ.get("WEBHOOK_URL", "")running = True17 unmodified linesexcept Exception:return Falsedef write_sync_status(status, message=""):"""Write sync status to file for the health server dashboard."""try:import jsondata = {"status": status,"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),"message": message}with open("/tmp/sync-status.json", "w") as f:json.dump(data, f)except Exception as e:print(f" β οΈ Could not write sync status: {e}")def trigger_webhook(event, status, message):"""Trigger webhook notification."""if not WEBHOOK_URL:returntry:import urllib.requestimport jsondata = json.dumps({"event": event,"status": status,"message": message,"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}).encode('utf-8')req = urllib.request.Request(WEBHOOK_URL, data=data, headers={'Content-Type': 'application/json'})urllib.request.urlopen(req, timeout=10)except Exception as e:print(f" β οΈ Webhook delivery failed: {e}")def sync_with_hf_hub():"""Sync workspace using huggingface_hub library."""80 unmodified linescontinuets = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())write_sync_status("syncing", f"Starting sync at {ts}")if use_hf_hub:if sync_with_hf_hub():print(f"π Workspace sync (hf_hub): pushed changes ({ts})")write_sync_status("success", "Successfully pushed to HF Hub")else:# Fallback to gitif sync_with_git():print(f"π Workspace sync (git fallback): pushed changes ({ts})")write_sync_status("success", "Successfully pushed via git fallback")else:msg = f"Workspace sync: failed ({ts}), will retry"print(f"π {msg}")write_sync_status("error", msg)trigger_webhook("sync", "error", msg)else:if sync_with_git():print(f"π Workspace sync (git): pushed changes ({ts})")write_sync_status("success", "Successfully pushed via git")else:msg = f"Workspace sync: push failed ({ts}), will retry"print(f"π {msg}")write_sync_status("error", msg)trigger_webhook("sync", "error", msg)if __name__ == "__main__":
.env.example+3-7
Dockerfile+8-3
README.md+81-51
dns-fix.js+102-13
health-server.js+467-19
iframe-fix.cjsAdded+45
keep-alive.sh+2-2
start.sh+35-3
wa-guardian.jsAdded+126
workspace-sync.py+45-2