Spaces:
Paused
Paused
feat: implement DNS-over-HTTPS fallback for network requests and add a web dashboard to the health server.
Browse filesFiles changed (6)
- .env.example+8-1
- README.md+83-46
- dns-fix.js+102-13
- health-server.js+285-10
- start.sh+23-2
- workspace-sync.py+45-2
131 unmodified lines1321331341351361371383 unmodified lines14214314414514614713 unmodified lines161162163164165166131 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_here3 unmodified lines# Multiple user IDs (comma-separated for team access)# TELEGRAM_USER_IDS=123456789,987654321,555555555# ββ OPTIONAL: Workspace Backup to HF Dataset ββHF_USERNAME=your_hf_usernameHF_TOKEN=hf_your_token_here13 unmodified lines# Workspace auto-sync interval (seconds). Default: 600.SYNC_INTERVAL=600# ββ OPTIONAL: Advanced ββ# Pin OpenClaw version. Default: latestOPENCLAW_VERSION=latest131 unmodified lines1321331341351361371383 unmodified lines14214314414514614714814915013 unmodified lines164165166167168169170171172173131 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_here3 unmodified lines# Multiple user IDs (comma-separated for team access)# TELEGRAM_USER_IDS=123456789,987654321,555555555# WhatsApp integration (pairing mode via CLI)# WHATSAPP_ENABLED=true# ββ OPTIONAL: Workspace Backup to HF Dataset ββHF_USERNAME=your_hf_usernameHF_TOKEN=hf_your_token_here13 unmodified lines# Workspace auto-sync interval (seconds). Default: 600.SYNC_INTERVAL=600# ββ OPTIONAL: Webhooks ββ# URL to send HTTP POST requests on startup and backup errors# WEBHOOK_URL=https://your-webhook-endpoint.com/webhook# ββ OPTIONAL: Advanced ββ# Pin OpenClaw version. Default: latestOPENCLAW_VERSION=latest
14 unmodified lines151617181920211 unmodified line2324252627282912 unmodified lines4243444546474837 unmodified lines8687888990913 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616714 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).37 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 Key14 unmodified lines151617181920211 unmodified line2324252627282930313212 unmodified lines45464748495051525337 unmodified lines9192939495969798991001011021031041051061071081091101111121133 unmodified lines11711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320414 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).37 unmodified linesAfter restarting, the bot should appear online on Telegram.## π¬ WhatsApp Setup *(Optional)*To use WhatsApp:1. Add the secret `WHATSAPP_ENABLED` and set it to `true`.2. Once the Space restarts, use the OpenClaw CLI to link your account:```bashnpm install -g openclaw@latestopenclaw channels login --gateway https://YOUR_SPACE_URL.hf.space --channel whatsapp```3. Scan the QR code with your phone (WhatsApp β Linked Devices).> [!NOTE]> HuggingClaw uses dynamic DNS-over-HTTPS probing to ensure reliability on HuggingFace Spaces.## πΎ 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 beautiful web dashboard. Access it by visiting your Space's URL on port 7861 or the internal health endpoint:- **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 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 || `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` | 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 Key
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}`);});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302// Lightweight health server and dashboard on port 7861const http = require('http');const fs = require('fs');const path = require('path');const PORT = process.env.HEALTH_PORT || 7861;const startTime = Date.now();const LLM_MODEL = process.env.LLM_MODEL || 'Not Set';const WHATSAPP_ENABLED = process.env.WHATSAPP_ENABLED === 'true' || process.env.WHATSAPP_ENABLED === '1';const TELEGRAM_ENABLED = !!process.env.TELEGRAM_BOT_TOKEN;const server = http.createServer((req, res) => {const uptime = Math.floor((Date.now() - startTime) / 1000);const uptimeHuman = `${Math.floor(uptime / 3600)}h ${Math.floor((uptime % 3600) / 60)}m`;if (req.url === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({status: 'ok',uptime: uptime,uptimeHuman: uptimeHuman,timestamp: new Date().toISOString()}));return;}if (req.url === '/status') {let syncStatus = { status: 'unknown', message: 'No sync data yet' };try {if (fs.existsSync('/tmp/sync-status.json')) {syncStatus = JSON.parse(fs.readFileSync('/tmp/sync-status.json', 'utf8'));}} catch (e) {}res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({model: LLM_MODEL,whatsapp: WHATSAPP_ENABLED,telegram: TELEGRAM_ENABLED,sync: syncStatus,uptime: uptimeHuman}));return;}if (req.url === '/') {res.writeHead(200, { 'Content-Type': 'text/html' });res.end(`<!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;}.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 Control Panel</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></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>';} else if (syncData.status === 'error') {badgeClass = 'status-offline';}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>`);return;}res.writeHead(404);res.end();});server.listen(PORT, '0.0.0.0', () => {console.log(`π₯ Health server & Dashboard listening on port ${PORT}`);});
233 unmodified lines2342352362372382399 unmodified lines24925025125225325415 unmodified lines27027127227327427527627727821 unmodified lines3003013023033043052 unmodified lines308309310311312313314315233 unmodified linesfifi# Write configecho "$CONFIG_JSON" > "/home/node/.openclaw/openclaw.json"chmod 600 /home/node/.openclaw/openclaw.json9 unmodified lineselseprintf " β %-40s β\n" "Telegram: β not configured"fiif [ -n "$HF_USERNAME" ] && [ -n "$HF_TOKEN" ]; thenprintf " β %-40s β\n" "Backup: β ${HF_USERNAME}/${BACKUP_DATASET:-huggingclaw-backup}"else15 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 &2 unmodified lines# ββ Launch gateway ββecho "π Launching OpenClaw gateway on port 7860..."echo ""# Set model via environment for the gatewayexport LLM_MODEL="$LLM_MODEL"233 unmodified lines2342352362372382392402412422432442459 unmodified lines25525625725825926026126226326426515 unmodified lines28128228328428528628728828929029129229329429529629729829930021 unmodified lines3223233243253263273282 unmodified lines331332333334335336233 unmodified linesfifiif [ "$WHATSAPP_ENABLED" = "true" ] || [ "$WHATSAPP_ENABLED" = "1" ]; thenCONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.plugins.entries.whatsapp = {"enabled": true}')CONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.channels.whatsapp = {"dmPolicy": "pairing"}')fi# Write configecho "$CONFIG_JSON" > "/home/node/.openclaw/openclaw.json"chmod 600 /home/node/.openclaw/openclaw.json9 unmodified lineselseprintf " β %-40s β\n" "Telegram: β not configured"fiif [ "$WHATSAPP_ENABLED" = "true" ] || [ "$WHATSAPP_ENABLED" = "1" ]; thenprintf " β %-40s β\n" "WhatsApp: β enabled"elseprintf " β %-40s β\n" "WhatsApp: β not configured"fiif [ -n "$HF_USERNAME" ] && [ -n "$HF_TOKEN" ]; thenprintf " β %-40s β\n" "Backup: β ${HF_USERNAME}/${BACKUP_DATASET:-huggingclaw-backup}"else15 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"node /home/node/app/health-server.js &/home/node/app/keep-alive.sh &2 unmodified lines# ββ Launch gateway ββecho "π Launching OpenClaw gateway on port 7860..."echo ""
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+8-1
README.md+83-46
dns-fix.js+102-13
health-server.js+285-10
start.sh+23-2
workspace-sync.py+45-2