Spaces:
Sleeping
Sleeping
Somrat Sorkar commited on
Commit Β·
5365372
1
Parent(s): 0bfb89f
v1.1.0: Pre-built Docker image, huggingface_hub sync, password auth, trusted proxies
Browse filesFiles changed (6)
- .env.example+13
- CHANGELOG.md+16
- Dockerfile+21-7
- README.md+21-9
- start.sh+31-1
- workspace-sync.pyAdded+149
127 unmodified lines12812913013113213330 unmodified lines164165166167168169127 unmodified lines# Generate: openssl rand -hex 32GATEWAY_TOKEN=your_gateway_token_here# ββ OPTIONAL: Telegram Integration ββ# Get bot token from: https://t.me/BotFatherTELEGRAM_BOT_TOKEN=your_bot_token_here30 unmodified lines# Health endpoint port. Default: 7861HEALTH_PORT=7861# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# QUICK START: Only 3 secrets required!# 1. LLM_API_KEY β From your LLM provider127 unmodified lines12812913013113213313413513613730 unmodified lines168169170171172173174175176177178179180181182127 unmodified lines# Generate: openssl rand -hex 32GATEWAY_TOKEN=your_gateway_token_here# (Optional) Password auth β simpler alternative to token for casual users# 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_here30 unmodified lines# Health endpoint port. Default: 7861HEALTH_PORT=7861# Trusted proxies (comma-separated IPs)# Fixes "Proxy headers detected from untrusted address" behind reverse proxies# Only set if you see pairing/auth errors. Find IPs in Space logs (remote=x.x.x.x)# TRUSTED_PROXIES=10.20.31.87,10.20.26.157# Allowed origins for Control UI (comma-separated URLs)# Locks down the web UI to only these origins# ALLOWED_ORIGINS=https://your-space.hf.space# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# QUICK START: Only 3 secrets required!# 1. LLM_API_KEY β From your LLM provider
1 unmodified line2345671 unmodified lineAll notable changes to this project will be documented in this file.## [1.0.0] - 2026-03-30### π Initial Release1 unmodified line2345678910111213141516171819202122231 unmodified lineAll notable changes to this project will be documented in this file.## [1.1.0] - 2026-03-31### Added- **Pre-built Docker image** β uses `ghcr.io/openclaw/openclaw:latest` multi-stage build for much faster builds (minutes instead of 30+)- **Python huggingface_hub sync** β `workspace-sync.py` uses the `huggingface_hub` library for more reliable HF Dataset sync (handles auth, LFS, retries). Falls back to git-based sync automatically- **Password auth** β `OPENCLAW_PASSWORD` for simpler login (optional alternative to token)- **Trusted proxies** β `TRUSTED_PROXIES` env var fixes "Proxy headers detected from untrusted address" errors on HF Spaces- **Allowed origins** β `ALLOWED_ORIGINS` env var to lock down Control UI access- **40+ LLM providers** β Added support for OpenCode, OpenRouter, DeepSeek, Qwen, Z.ai, Moonshot, Mistral, xAI, NVIDIA, Volcengine, BytePlus, Cohere, Groq, HuggingFace Inference, and more- **OpenCode Zen/Go** β support for OpenCode's tested model service### Changed- Provider detection now uses `case` statement (cleaner, faster) with correct OpenClaw provider IDs- Model IDs now sourced from OpenClaw docs (not OpenRouter) for accuracy- Google API key env var corrected to `GEMINI_API_KEY`## [1.0.0] - 2026-03-30### π Initial Release
123456789101112131415161718192021222324252627282930FROM node:22-slim# Version pinning (default: latest)ARG OPENCLAW_VERSION=latest# Install git, ca-certificates, jq, and curlRUN apt-get update && apt-get install -y \git \ca-certificates \jq \curl \--no-install-recommends && \rm -rf /var/lib/apt/lists/*# Reuse existing node user (UID 1000)RUN mkdir -p /home/node/app /home/node/.openclaw && \chown -R 1000:1000 /home/node# Install OpenClaw (version configurable via build arg)RUN npm install -g openclaw@${OPENCLAW_VERSION}# Copy 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.sh /home/node/app/workspace-sync.shRUN chmod +x /home/node/app/start.sh /home/node/app/keep-alive.sh /home/node/app/workspace-sync.shUSER node1234567891011121314151617181920212223242526272829303132333435363738394041424344# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# π¦ HuggingClaw β OpenClaw Gateway for HuggingFace Spaces# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 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 \git \ca-certificates \jq \curl \python3 \python3-pip \--no-install-recommends && \pip3 install --no-cache-dir --break-system-packages huggingface_hub && \rm -rf /var/lib/apt/lists/*# Reuse existing node user (UID 1000)RUN mkdir -p /home/node/app /home/node/.openclaw && \chown -R 1000:1000 /home/node# Copy pre-built OpenClaw (skips npm install entirely β much faster!)COPY --from=openclaw --chown=1000:1000 /app /home/node/.openclaw/openclaw-app# 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.sh /home/node/app/workspace-sync.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.sh /home/node/app/workspace-sync.shUSER node
22 unmodified lines232425262728293031323334353670 unmodified lines107108109110111112186 unmodified lines29930030130230330430530649 unmodified lines35635735835936036136236336436536636736836920 unmodified lines39039139239339439539622 unmodified lines### β¨ Features- **Zero-config** β just add 3 secrets and deploy- **Any LLM provider** β Claude, GPT-4, Gemini, etc.- **Built-in keep-alive** β self-pings to prevent HF sleep (no external cron needed)- **Auto-sync workspace** β commits + pushes changes every 10 min- **Auto-create backup** β creates the HF Dataset for you if it doesn't exist- **Graceful shutdown** β saves workspace before container dies- **Multi-user Telegram** β supports comma-separated user IDs for teams- **Health endpoint** β `/health` for monitoring- **Version pinning** β lock OpenClaw to a specific version- **100% HF-native** β runs entirely on HuggingFace infrastructure---70 unmodified lines| `KEEP_ALIVE_INTERVAL` | `300` (5 min) | Self-ping interval. `0` = disable || `SYNC_INTERVAL` | `600` (10 min) | Auto-sync interval |#### Advanced| Variable | Default | Purpose |186 unmodified lines1. **Auto-creates** the dataset if it doesn't exist2. **Restores** workspace on every startup3. **Auto-syncs** changes every 10 minutes (configurable)4. **Saves** on shutdown (graceful SIGTERM handling)Custom dataset name: `BACKUP_DATASET_NAME=my-custom-backup`49 unmodified lines```HuggingClaw/βββ Dockerfile # Runtime: Node.js + OpenClaw + curl + jqβββ start.sh # Config generator + validation + orchestratorβββ keep-alive.sh # Self-ping to prevent HF sleepβββ workspace-sync.sh # Periodic workspace commit + pushβββ health-server.js # Health endpoint (/health)βββ dns-fix.js # DNS override for HF network restrictionsβββ .env.example # Complete configuration referenceβββ .gitignore # Keeps secrets out of version controlβββ README.md # You are here```20 unmodified lines**Space sleeping** β Check logs for `π Keep-alive started`. If missing, `SPACE_HOST` might not be set**Control UI blocked** β The Space URL is auto-allowlisted. Check logs for origin errors**Version issues** β Pin with `OPENCLAW_VERSION=2026.3.24` in secrets22 unmodified lines23242526272829303132333435363770 unmodified lines108109110111112113114115116117118119120121186 unmodified lines30830931031131231331431531649 unmodified lines36636736836937037137237337437537637737837920 unmodified lines40040140240340440540640740822 unmodified lines### β¨ Features- **Zero-config** β just add 3 secrets and deploy- **Any LLM provider** β Claude, GPT-4, Gemini, DeepSeek, Qwen, Grok, and [40+ more](#-llm-provider-setup)- **Fast builds** β uses pre-built OpenClaw Docker image (minutes, not 30+)- **Smart workspace sync** β uses `huggingface_hub` Python library (more reliable than git for HF)- **Built-in keep-alive** β self-pings to prevent HF sleep (no external cron needed)- **Auto-create backup** β creates the HF Dataset for you if it doesn't exist- **Graceful shutdown** β saves workspace before container dies- **Multi-user Telegram** β supports comma-separated user IDs for teams- **Health endpoint** β `/health` for monitoring- **Password or token auth** β choose what works for you- **100% HF-native** β runs entirely on HuggingFace infrastructure---70 unmodified lines| `KEEP_ALIVE_INTERVAL` | `300` (5 min) | Self-ping interval. `0` = disable || `SYNC_INTERVAL` | `600` (10 min) | Auto-sync interval |#### Security (Optional)| Variable | Default | Purpose ||----------|---------|---------|| `OPENCLAW_PASSWORD` | β | Password auth (simpler alternative to token) || `TRUSTED_PROXIES` | β | Comma-separated proxy IPs (fixes auth issues behind reverse proxies) || `ALLOWED_ORIGINS` | β | Comma-separated URLs to lock down Control UI |#### Advanced| Variable | Default | Purpose |186 unmodified lines1. **Auto-creates** the dataset if it doesn't exist2. **Restores** workspace on every startup3. **Smart sync** β uses `huggingface_hub` Python library (handles auth, LFS, retries automatically; falls back to git if unavailable)4. **Auto-syncs** changes every 10 minutes (configurable via `SYNC_INTERVAL`)5. **Saves** on shutdown (graceful SIGTERM handling)Custom dataset name: `BACKUP_DATASET_NAME=my-custom-backup`49 unmodified lines```HuggingClaw/βββ Dockerfile # Multi-stage build with pre-built OpenClaw imageβββ start.sh # Config generator + validation + orchestratorβββ keep-alive.sh # Self-ping to prevent HF sleepβββ workspace-sync.py # Smart sync via huggingface_hub (with git fallback)βββ workspace-sync.sh # Legacy git-based sync (fallback)βββ health-server.js # Health endpoint (/health)βββ dns-fix.js # DNS override for HF network restrictionsβββ .env.example # Complete configuration referenceβββ README.md # You are here```20 unmodified lines**Space sleeping** β Check logs for `π Keep-alive started`. If missing, `SPACE_HOST` might not be set**"Proxy headers detected" or auth errors** β Set `TRUSTED_PROXIES` with the IPs from your Space logs (`remote=x.x.x.x`)**Control UI blocked** β Set `ALLOWED_ORIGINS=https://your-space.hf.space` or check logs for origin errors**Version issues** β Pin with `OPENCLAW_VERSION=2026.3.24` in secrets
198 unmodified lines19920020120220320428 unmodified lines23323423523623723837 unmodified lines276277278279280281282198 unmodified lines# Disable device auth (pairing) for headless Docker β token-only authCONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".gateway.controlUi.dangerouslyDisableDeviceAuth = true")# Telegram (supports multiple user IDs, comma-separated)if [ -n "$TELEGRAM_BOT_TOKEN" ]; thenCONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.plugins.entries.telegram = {"enabled": true}')28 unmodified lineselseprintf " β %-40s β\n" "Backup: β not configured"fiif [ -n "$SPACE_HOST" ]; thenprintf " β %-40s β\n" "Keep-alive: β every ${KEEP_ALIVE_INTERVAL:-300}s"printf " β %-40s β\n" "Control UI: https://${SPACE_HOST}"37 unmodified lines# ββ Start background services ββnode /home/node/app/health-server.js &/home/node/app/keep-alive.sh &/home/node/app/workspace-sync.sh &# ββ Launch gateway ββecho "π Launching OpenClaw gateway on port 7860..."198 unmodified lines19920020120220320420520620720820921021121221321421521621721821922022122222328 unmodified lines25225325425525625725825926026126237 unmodified lines300301302303304305306307308309310311312198 unmodified lines# Disable device auth (pairing) for headless Docker β token-only authCONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".gateway.controlUi.dangerouslyDisableDeviceAuth = true")# Password auth (optional β simpler alternative to token for casual users)if [ -n "$OPENCLAW_PASSWORD" ]; thenCONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".gateway.auth.mode = \"password\" | .gateway.auth.password = \"$OPENCLAW_PASSWORD\"")fi# Trusted proxies (optional β fixes "Proxy headers detected from untrusted address" on HF Spaces)# Set TRUSTED_PROXIES as comma-separated IPs, e.g. "10.20.31.87,10.20.26.157"if [ -n "$TRUSTED_PROXIES" ]; thenPROXIES_JSON=$(echo "$TRUSTED_PROXIES" | tr ',' '\n' | sed 's/^ *//;s/ *$//' | jq -R . | jq -s .)CONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".gateway.trustedProxies = $PROXIES_JSON")fi# Allowed origins (optional β lock down Control UI to specific URLs)# Set ALLOWED_ORIGINS as comma-separated URLs, e.g. "https://your-space.hf.space"if [ -n "$ALLOWED_ORIGINS" ]; thenORIGINS_JSON=$(echo "$ALLOWED_ORIGINS" | tr ',' '\n' | sed 's/^ *//;s/ *$//' | jq -R . | jq -s .)CONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".gateway.controlUi.allowedOrigins = $ORIGINS_JSON")fi# Telegram (supports multiple user IDs, comma-separated)if [ -n "$TELEGRAM_BOT_TOKEN" ]; thenCONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.plugins.entries.telegram = {"enabled": true}')28 unmodified lineselseprintf " β %-40s β\n" "Backup: β not configured"fiif [ -n "$OPENCLAW_PASSWORD" ]; thenprintf " β %-40s β\n" "Auth: π password"elseprintf " β %-40s β\n" "Auth: π token"fiif [ -n "$SPACE_HOST" ]; thenprintf " β %-40s β\n" "Keep-alive: β every ${KEEP_ALIVE_INTERVAL:-300}s"printf " β %-40s β\n" "Control UI: https://${SPACE_HOST}"37 unmodified lines# ββ Start background services ββnode /home/node/app/health-server.js &/home/node/app/keep-alive.sh &# Use Python huggingface_hub sync if available, fallback to git-based syncif python3 -c "import huggingface_hub" 2>/dev/null; thenpython3 /home/node/app/workspace-sync.py &else/home/node/app/workspace-sync.sh &fi# ββ Launch gateway ββecho "π Launching OpenClaw gateway on port 7860..."
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149#!/usr/bin/env python3"""HuggingClaw Workspace Sync β HuggingFace Hub based backupUses huggingface_hub Python library instead of git for more reliableHF Dataset operations (handles auth, LFS, retries automatically).
Falls back to git-based sync if HF_USERNAME or HF_TOKEN are not set."""
import osimport sysimport timeimport signalimport subprocessfrom pathlib import Path
WORKSPACE = Path("/home/node/.openclaw/workspace")INTERVAL = int(os.environ.get("SYNC_INTERVAL", "600"))HF_TOKEN = os.environ.get("HF_TOKEN", "")HF_USERNAME = os.environ.get("HF_USERNAME", "")BACKUP_DATASET = os.environ.get("BACKUP_DATASET_NAME", "huggingclaw-backup")
running = True
def signal_handler(sig, frame): global running running = False
signal.signal(signal.SIGTERM, signal_handler)signal.signal(signal.SIGINT, signal_handler)
def has_changes(): """Check if workspace has uncommitted changes (git-based check).""" try: subprocess.run(["git", "add", "-A"], cwd=WORKSPACE, capture_output=True) result = subprocess.run( ["git", "diff", "--cached", "--quiet"], cwd=WORKSPACE, capture_output=True ) return result.returncode != 0 except Exception: return False
def sync_with_hf_hub(): """Sync workspace using huggingface_hub library.""" try: from huggingface_hub import HfApi, upload_folder
api = HfApi(token=HF_TOKEN) repo_id = f"{HF_USERNAME}/{BACKUP_DATASET}"
# Ensure dataset exists try: api.repo_info(repo_id=repo_id, repo_type="dataset") except Exception: print(f" π Creating dataset {repo_id}...") try: api.create_repo(repo_id=repo_id, repo_type="dataset", private=True) print(f" β
Dataset created: {repo_id}") except Exception as e: print(f" β οΈ Could not create dataset: {e}") return False
# Upload workspace upload_folder( folder_path=str(WORKSPACE), repo_id=repo_id, repo_type="dataset", token=HF_TOKEN, commit_message=f"Auto-sync {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}", ignore_patterns=[".git/*", ".git"], ) return True
except ImportError: print(" β οΈ huggingface_hub not installed, falling back to git") return False except Exception as e: print(f" β οΈ HF Hub sync failed: {e}") return False
def sync_with_git(): """Fallback: sync workspace using git.""" try: ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) subprocess.run(["git", "add", "-A"], cwd=WORKSPACE, capture_output=True) subprocess.run( ["git", "commit", "-m", f"Auto-sync {ts}"], cwd=WORKSPACE, capture_output=True ) result = subprocess.run( ["git", "push", "origin", "main"], cwd=WORKSPACE, capture_output=True ) return result.returncode == 0 except Exception: return False
def main(): # Wait for workspace to initialize time.sleep(30)
if not WORKSPACE.exists(): print("π Workspace sync: workspace not found, exiting.") return
use_hf_hub = bool(HF_TOKEN and HF_USERNAME)
if use_hf_hub: print(f"π Workspace sync started (huggingface_hub): every {INTERVAL}s β {HF_USERNAME}/{BACKUP_DATASET}") else: git_dir = WORKSPACE / ".git" if not git_dir.exists(): print("π Workspace sync: no git repo and no HF credentials, skipping.") return print(f"π Workspace sync started (git): every {INTERVAL}s")
while running: time.sleep(INTERVAL) if not running: break
if not has_changes(): continue
ts = 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 git if 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__": main().env.example+13
CHANGELOG.md+16
Dockerfile+21-7
README.md+21-9
start.sh+31-1
workspace-sync.pyAdded+149