Spaces:
Paused
Paused
Commit Β·
af9e60e
0
Parent(s):
Initial commit
Browse filesFiles changed (13)
- .env.exampleAdded+185
- CHANGELOG.mdAdded+43
- CODE_OF_CONDUCT.mdAdded+27
- CONTRIBUTING.mdAdded+46
- DockerfileAdded+53
- LICENSEAdded+21
- README.mdAdded+426
- SECURITY.mdAdded+28
- dns-fix.jsAdded+19
- health-server.jsAdded+27
- keep-alive.shAdded+34
- start.shAdded+330
- workspace-sync.pyAdded+149
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# π¦ HuggingClaw β OpenClaw Gateway for HuggingFace Spaces# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Copy this file to .env and fill in your values.# For local development: cp .env.example .env && nano .env
# ββ REQUIRED: Core Configuration ββ# [REQUIRED] LLM provider API key# - Anthropic: sk-ant-v0-...# - OpenAI: sk-...# - Google: AIzaSy...# - OpenRouter: sk-or-v1-... (300+ models via single key)LLM_API_KEY=your_api_key_here
# [REQUIRED] LLM model to use (format: provider/model-name)# Auto-detects provider from prefix β any provider is supported!# Provider IDs from OpenClaw docs: docs.openclaw.ai/concepts/model-providers## ββ Core Providers ββ## Anthropic (ANTHROPIC_API_KEY):# - anthropic/claude-opus-4-6# - anthropic/claude-sonnet-4-6# - anthropic/claude-sonnet-4-5# - anthropic/claude-haiku-4-5## OpenAI (OPENAI_API_KEY):# - openai/gpt-5.4-pro# - openai/gpt-5.4# - openai/gpt-5.4-mini# - openai/gpt-5.4-nano# - openai/gpt-4.1# - openai/gpt-4.1-mini## Google Gemini (GEMINI_API_KEY):# - google/gemini-3.1-pro-preview# - google/gemini-3-flash-preview# - google/gemini-2.5-pro# - google/gemini-2.5-flash## DeepSeek (DEEPSEEK_API_KEY):# - deepseek/deepseek-v3.2# - deepseek/deepseek-r1-0528# - deepseek/deepseek-r1## ββ OpenCode Providers ββ## OpenCode Zen β tested & verified models (OPENCODE_API_KEY):# - opencode/claude-opus-4-6# - opencode/gpt-5.4# Get key from: https://opencode.ai/auth## OpenCode Go β low-cost open models (OPENCODE_API_KEY):# - opencode-go/kimi-k2.5## ββ Gateway/Router Providers ββ## OpenRouter β 300+ models via single API key (OPENROUTER_API_KEY):# - openrouter/anthropic/claude-sonnet-4-6# - openrouter/openai/gpt-5.4# - openrouter/deepseek/deepseek-v3.2# - openrouter/meta-llama/llama-3.3-70b-instruct:free# Get key from: https://openrouter.ai## Kilo Gateway (KILOCODE_API_KEY):# - kilocode/anthropic/claude-opus-4.6## ββ Chinese/Asian Providers ββ## Z.ai / GLM (ZAI_API_KEY) β OpenClaw normalizes z-ai/z.ai β zai:# - zai/glm-5# - zai/glm-5-turbo# - zai/glm-4.7# - zai/glm-4.7-flash## Moonshot / Kimi (MOONSHOT_API_KEY):# - moonshot/kimi-k2.5# - moonshot/kimi-k2-thinking## MiniMax (MINIMAX_API_KEY):# - minimax/minimax-m2.7# - minimax/minimax-m2.5## Xiaomi / MiMo (XIAOMI_API_KEY):# - xiaomi/mimo-v2-pro# - xiaomi/mimo-v2-omni## Volcengine / Doubao (VOLCANO_ENGINE_API_KEY):# - volcengine/doubao-seed-1-8-251228# - volcengine/kimi-k2-5-260127## BytePlus β international (BYTEPLUS_API_KEY):# - byteplus/seed-1-8-251228## ββ Western Providers ββ## Mistral (MISTRAL_API_KEY):# - mistral/mistral-large-latest# - mistral/mistral-small-2603# - mistral/devstral-medium## xAI / Grok (XAI_API_KEY):# - xai/grok-4.20-beta# - xai/grok-4## NVIDIA (NVIDIA_API_KEY):# - nvidia/nemotron-3-super-120b-a12b## Groq (GROQ_API_KEY):# - groq/mixtral-8x7b-32768## Cohere (COHERE_API_KEY):# - cohere/command-a## Together (TOGETHER_API_KEY):# - together/meta-llama/llama-3.3-70b-instruct## Cerebras (CEREBRAS_API_KEY):# - cerebras/zai-glm-4.7## HuggingFace Inference (HUGGINGFACE_HUB_TOKEN):# - huggingface/deepseek-ai/DeepSeek-R1## Or any other OpenClaw-supported provider (format: provider/model-name)LLM_MODEL=anthropic/claude-sonnet-4-5
# [REQUIRED] Gateway authentication token# 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_here
# Single user ID (from https://t.me/userinfobot)TELEGRAM_USER_ID=123456789
# 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_here
# Backup dataset name (auto-created if missing)# Default: huggingclaw-backupBACKUP_DATASET_NAME=huggingclaw-backup
# Git commit identity for workspace syncsWORKSPACE_GIT_USER=openclaw@example.comWORKSPACE_GIT_NAME=OpenClaw Bot
# ββ OPTIONAL: Background Services ββ# Keep-alive ping interval (seconds). Default: 300. Set 0 to disable.KEEP_ALIVE_INTERVAL=300
# 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 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# 2. LLM_MODEL β Pick a model above# 3. GATEWAY_TOKEN β Run: openssl rand -hex 32# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ12345678910111213141516171819202122232425262728293031323334353637383940414243# Changelog
All 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
#### Features- **Any LLM provider** β Anthropic (Claude), OpenAI (GPT-4), Google (Gemini)- **Telegram integration** β connect via @BotFather, supports multiple users- **Built-in keep-alive** β self-pings to prevent HF Spaces 48h sleep- **Auto-sync workspace** β commits + pushes to HF Dataset every 10 min- **Auto-create backup** β creates HF Dataset automatically on first run- **Graceful shutdown** β saves workspace before container stops- **Health endpoint** β `/health` on port 7861 for monitoring- **DNS fix** β bypasses HF Spaces internal DNS restrictions- **Version pinning** β lock OpenClaw to a specific version- **Startup banner** β clean summary of all running services- **Zero-config defaults** β just 2 secrets to get started
#### Architecture- `start.sh` β config generator + validation + orchestrator- `keep-alive.sh` β self-ping background service- `workspace-sync.sh` β periodic workspace backup- `health-server.js` β lightweight health endpoint- `dns-fix.js` β DNS override for HF network restrictions123456789101112131415161718192021222324252627# Code of Conduct
## Our Pledge
We are committed to making participation in this project a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
**Positive behavior includes:**- Using welcoming and inclusive language- Being respectful of differing viewpoints- Gracefully accepting constructive criticism- Focusing on what is best for the community
**Unacceptable behavior includes:**- Trolling, insulting, or derogatory comments- Public or private harassment- Publishing others' private information without permission- Other conduct which could reasonably be considered inappropriate
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting the maintainer. All complaints will be reviewed and investigated.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), version 2.0.12345678910111213141516171819202122232425262728293031323334353637383940414243444546# Contributing to HuggingClaw
Thanks for your interest in contributing! π¦
## How to Contribute
### Bug Reports- Open an issue with a clear description- Include your HF Space logs if possible- Mention which LLM provider you're using
### Feature Requests- Open an issue with the `enhancement` label- Describe the use case β why is this needed?
### Pull Requests1. Fork the repo2. Create a feature branch: `git checkout -b feature/my-feature`3. Make your changes4. Test locally with Docker: `docker build -t huggingclaw . && docker run -p 7860:7860 --env-file .env huggingclaw`5. Commit with a clear message6. Push and open a PR
### Code Style- Shell scripts: use `set -e`, quote variables, comment non-obvious logic- Keep it simple β this project should stay easy to understand- No unnecessary dependencies
### Testing- Test with at least one LLM provider (Anthropic, OpenAI, or Google)- Test with and without Telegram enabled- Test with and without workspace backup enabled- Verify keep-alive and auto-sync work
## Development Setup
```bashcp .env.example .env# Fill in your valuesdocker build -t huggingclaw .docker run -p 7860:7860 --env-file .env huggingclaw```
## Questions?
Open an issue or start a discussion. We're friendly! π€1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# π¦ 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.py /home/node/app/workspace-sync.pyRUN chmod +x /home/node/app/start.sh /home/node/app/keep-alive.sh
USER node
ENV HOME=/home/node \ PATH=/home/node/.local/bin:/usr/local/bin:$PATH \ NODE_OPTIONS="--require /opt/dns-fix.js"
WORKDIR /home/node/app
EXPOSE 7860
CMD ["/home/node/app/start.sh"]123456789101112131415161718192021MIT License
Copyright (c) 2026 Somrat Sorkar (@somratpro)
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426---title: HuggingClawemoji: π¦colorFrom: bluecolorTo: purplesdk: dockerapp_port: 7860pinned: true---
<!-- Badges -->[](https://github.com/somratpro/huggingclaw)[](https://opensource.org/licenses/MIT)[](https://huggingface.co/spaces)[](https://github.com/openclaw/openclaw)
# π¦ HuggingClaw
Run your own **always-on AI assistant** on HuggingFace Spaces β for free.
Works with **any LLM** (Anthropic, OpenAI, Google), connects via **Telegram**, and persists your workspace to **HF Datasets** automatically.
### β¨ 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
---
## π Quick Start
### 1. Duplicate this Space[](https://huggingface.co/spaces/somratpro/HuggingClaw?duplicate=true)
Click the button above β name it β set to **Private**
### 2. Add Required SecretsGo to **Settings β Secrets**:
| Secret | Value ||--------|-------|| `LLM_API_KEY` | Your API key ([Anthropic](https://console.anthropic.com/) / [OpenAI](https://platform.openai.com/) / [Google](https://ai.google.dev/)) || `LLM_MODEL` | Model to use (e.g. `google/gemini-2.5-flash`, `anthropic/claude-sonnet-4-5`, `openai/gpt-4`) || `GATEWAY_TOKEN` | Run `openssl rand -hex 32` to generate |
### 3. DeployThat's it! The Space builds and starts automatically.
### 4. (Optional) Add Telegram| Secret | Value ||--------|-------|| `TELEGRAM_BOT_TOKEN` | From [@BotFather](https://t.me/BotFather) || `TELEGRAM_USER_ID` | Your user ID ([how to find](https://t.me/userinfobot)) |
### 5. (Optional) Enable Workspace Backup| Secret | Value ||--------|-------|| `HF_USERNAME` | Your HuggingFace username || `HF_TOKEN` | [HF token](https://huggingface.co/settings/tokens) with write access |
The backup dataset (`huggingclaw-backup`) is **created automatically** β no manual setup needed.
---
## π All Configuration Options
See **`.env.example`** for the complete reference with examples.
#### Required
| Variable | Purpose ||----------|---------|| `LLM_API_KEY` | LLM provider API key || `LLM_MODEL` | Model to use (e.g. `google/gemini-2.5-flash`, `anthropic/claude-sonnet-4-5`, `openai/gpt-4`) β auto-detects provider from prefix || `GATEWAY_TOKEN` | Gateway auth token |
#### Telegram
| Variable | Purpose ||----------|---------|| `TELEGRAM_BOT_TOKEN` | Bot token from @BotFather || `TELEGRAM_USER_ID` | Single user allowlist || `TELEGRAM_USER_IDS` | Multiple users (comma-separated): `123,456,789` |
#### Workspace Backup
| Variable | Default | Purpose ||----------|---------|---------|| `HF_USERNAME` | β | Your HF username || `HF_TOKEN` | β | HF token (write access) || `BACKUP_DATASET_NAME` | `huggingclaw-backup` | Dataset name (auto-created!) || `WORKSPACE_GIT_USER` | `openclaw@example.com` | Git commit email || `WORKSPACE_GIT_NAME` | `OpenClaw Bot` | Git commit name |
#### Background Services
| Variable | Default | Purpose ||----------|---------|---------|| `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 ||----------|---------|---------|| `OPENCLAW_VERSION` | `latest` | Pin OpenClaw version || `HEALTH_PORT` | `7861` | Health endpoint port |
---
## π€ LLM Provider Setup
Just set `LLM_MODEL` with the correct provider prefix β **any provider is supported**! The provider is auto-detected from the model name. All provider IDs from [OpenClaw docs](https://docs.openclaw.ai/concepts/model-providers).
### Anthropic (Claude)```LLM_API_KEY=sk-ant-v0-...LLM_MODEL=anthropic/claude-sonnet-4-5```Models: `anthropic/claude-opus-4-6` Β· `anthropic/claude-sonnet-4-6` Β· `anthropic/claude-sonnet-4-5` Β· `anthropic/claude-haiku-4-5`
### OpenAI```LLM_API_KEY=sk-...LLM_MODEL=openai/gpt-5.4```Models: `openai/gpt-5.4-pro` Β· `openai/gpt-5.4` Β· `openai/gpt-5.4-mini` Β· `openai/gpt-5.4-nano` Β· `openai/gpt-4.1` Β· `openai/gpt-4.1-mini`
### Google (Gemini)```LLM_API_KEY=AIzaSy...LLM_MODEL=google/gemini-2.5-flash```Models: `google/gemini-3.1-pro-preview` Β· `google/gemini-3-flash-preview` Β· `google/gemini-2.5-pro` Β· `google/gemini-2.5-flash`
### DeepSeek```LLM_API_KEY=sk-...LLM_MODEL=deepseek/deepseek-v3.2```Models: `deepseek/deepseek-v3.2` Β· `deepseek/deepseek-r1-0528` Β· `deepseek/deepseek-r1`Get key from: [DeepSeek Platform](https://platform.deepseek.com)
### OpenCode Zen (tested & verified models)```LLM_API_KEY=your_opencode_api_keyLLM_MODEL=opencode/claude-opus-4-6```Models: `opencode/claude-opus-4-6` Β· `opencode/gpt-5.4`Get key from: [OpenCode.ai](https://opencode.ai/auth)
### OpenCode Go (low-cost open models)```LLM_API_KEY=your_opencode_api_keyLLM_MODEL=opencode-go/kimi-k2.5```Get key from: [OpenCode.ai](https://opencode.ai/auth)
### Z.ai (GLM)```LLM_API_KEY=your_zai_api_keyLLM_MODEL=zai/glm-5```Models: `zai/glm-5` Β· `zai/glm-5-turbo` Β· `zai/glm-4.7` Β· `zai/glm-4.7-flash`Get key from: [Z.ai](https://z.ai) Β· Note: `z-ai/` and `z.ai/` prefixes auto-normalize to `zai/`
### Moonshot (Kimi)```LLM_API_KEY=sk-...LLM_MODEL=moonshot/kimi-k2.5```Models: `moonshot/kimi-k2.5` Β· `moonshot/kimi-k2-thinking`Get key from: [Moonshot API](https://platform.moonshot.cn)
### Mistral```LLM_API_KEY=your_mistral_api_keyLLM_MODEL=mistral/mistral-large-latest```Models: `mistral/mistral-large-latest` Β· `mistral/mistral-small-2603` Β· `mistral/devstral-medium` Β· `mistral/codestral-2508`Get key from: [Mistral Console](https://console.mistral.ai)
### xAI (Grok)```LLM_API_KEY=your_xai_api_keyLLM_MODEL=xai/grok-4.20-beta```Models: `xai/grok-4.20-beta` Β· `xai/grok-4` Β· `xai/grok-4.1-fast`Get key from: [xAI Console](https://console.x.ai)
### MiniMax```LLM_API_KEY=your_minimax_api_keyLLM_MODEL=minimax/minimax-m2.7```Models: `minimax/minimax-m2.7` Β· `minimax/minimax-m2.5`Get key from: [MiniMax Platform](https://platform.minimax.io)
### NVIDIA```LLM_API_KEY=your_nvidia_api_keyLLM_MODEL=nvidia/nemotron-3-super-120b-a12b```Get key from: [NVIDIA API](https://api.nvidia.com)
### Xiaomi (MiMo)```LLM_API_KEY=your_xiaomi_api_keyLLM_MODEL=xiaomi/mimo-v2-pro```Models: `xiaomi/mimo-v2-pro` Β· `xiaomi/mimo-v2-omni`
### Volcengine (Doubao / ByteDance)```LLM_API_KEY=your_volcengine_api_keyLLM_MODEL=volcengine/doubao-seed-1-8-251228```Models: `volcengine/doubao-seed-1-8-251228` Β· `volcengine/kimi-k2-5-260127` Β· `volcengine/glm-4-7-251222`Get key from: [Volcengine](https://www.volcengine.com)
### Groq```LLM_API_KEY=your_groq_api_keyLLM_MODEL=groq/mixtral-8x7b-32768```Get key from: [Groq Console](https://console.groq.com)
### Cohere```LLM_API_KEY=your_cohere_api_keyLLM_MODEL=cohere/command-a```Get key from: [Cohere Dashboard](https://dashboard.cohere.com)
### HuggingFace Inference```LLM_API_KEY=hf_your_tokenLLM_MODEL=huggingface/deepseek-ai/DeepSeek-R1```Get key from: [HuggingFace Tokens](https://huggingface.co/settings/tokens)
### OpenRouter (300+ models via single API key)```LLM_API_KEY=sk-or-v1-...LLM_MODEL=openrouter/anthropic/claude-sonnet-4-6```With OpenRouter, you can access **every model above** with a single API key! Just prefix with `openrouter/`:- `openrouter/anthropic/claude-sonnet-4-6` β Anthropic Claude- `openrouter/openai/gpt-5.4` β OpenAI- `openrouter/deepseek/deepseek-v3.2` β DeepSeek- `openrouter/google/gemini-2.5-flash` β Google Gemini- `openrouter/meta-llama/llama-3.3-70b-instruct:free` β Llama (free!)- `openrouter/moonshotai/kimi-k2.5` β Moonshot Kimi- `openrouter/z-ai/glm-5-turbo` β Z.ai GLM
Get key from: [OpenRouter.ai](https://openrouter.ai) Β· [Full model list](https://openrouter.ai/models)
### Kilo Gateway```LLM_API_KEY=your_kilocode_api_keyLLM_MODEL=kilocode/anthropic/claude-opus-4.6```Get key from: [Kilo.ai](https://kilo.ai)
### Any Other ProviderHuggingClaw supports **any LLM provider** that OpenClaw supports. Just use:```LLM_API_KEY=your_api_keyLLM_MODEL=provider/model-name```The provider prefix is auto-detected and mapped to the appropriate environment variable.
Full provider list: [OpenClaw Model Providers](https://docs.openclaw.ai/concepts/model-providers) Β· [OpenCode Providers](https://opencode.ai/docs/providers)
---
## π± Telegram Setup
1. Message [@BotFather](https://t.me/BotFather) β `/newbot` β copy the token2. Message [@userinfobot](https://t.me/userinfobot) to get your user ID3. Add secrets: `TELEGRAM_BOT_TOKEN` and `TELEGRAM_USER_ID`4. Restart the Space β DM your bot π
**Multiple users?** Use `TELEGRAM_USER_IDS=123,456,789` (comma-separated)
---
## πΎ Workspace Backup
Set `HF_USERNAME` + `HF_TOKEN` and HuggingClaw handles everything:
1. **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`
---
## π How It Stays Alive
HF Spaces sleeps after 48h of no HTTP requests. HuggingClaw prevents this with:
- **Self-ping** β pings its own URL every 5 min (uses HF's `SPACE_HOST` env var)- **Health endpoint** β returns `200 OK` with uptime info- **Zero dependencies** β no external cron, no third-party pinger
Your Space runs forever, powered entirely by HF. π―
---
## π» Local Development
```bashgit clone https://github.com/somratpro/huggingclaw.gitcd huggingclawcp .env.example .envnano .env # fill in your values```
**Docker:**```bashdocker build -t huggingclaw .docker run -p 7860:7860 --env-file .env huggingclaw```
**Without Docker:**```bashnpm install -g openclaw@latestexport $(cat .env | xargs)bash start.sh```
---
## π Connect via CLI
```bashnpm install -g openclaw@latestopenclaw channels login --gateway https://YOUR-SPACE-URL.hf.space# Enter your GATEWAY_TOKEN when prompted```
---
## ποΈ Architecture
```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)βββ 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```
**Startup flow:**1. Validate secrets β fail fast with clear errors2. Validate HF token β warn if expired3. Auto-create backup dataset if missing4. Restore workspace from HF Dataset5. Generate `openclaw.json` config from env vars6. Print startup summary7. Start background services (keep-alive, auto-sync)8. Launch OpenClaw gateway9. On SIGTERM β save workspace β exit cleanly
---
## π Troubleshooting
**Missing secrets** β Check **Settings β Secrets** for `LLM_API_KEY` and `GATEWAY_TOKEN`
**Telegram not working** β Verify bot token is valid, check logs for `π± Enabling Telegram`
**Workspace not restoring** β Check `HF_USERNAME` and `HF_TOKEN` are set, token has write access
**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
---
## π Links
- [OpenClaw Docs](https://docs.openclaw.ai) Β· [OpenClaw GitHub](https://github.com/openclaw/openclaw) Β· [HF Spaces Docs](https://huggingface.co/docs/hub/spaces)
---
## π€ Contributing
Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
## π License
MIT β see [LICENSE](LICENSE) for details.
---
Made with β€οΈ by [@somratpro](https://github.com/somratpro) for the [OpenClaw](https://github.com/openclaw/openclaw) community12345678910111213141516171819202122232425262728# Security Policy
## Reporting a Vulnerability
If you discover a security vulnerability, please report it responsibly:
1. **Do NOT open a public issue**2. Email the maintainer or open a private security advisory on GitHub3. Include steps to reproduce if possible
We'll respond within 48 hours and work on a fix.
## Security Best Practices
When deploying HuggingClaw:
- **Set your Space to Private** β prevents unauthorized access to your gateway- **Use a strong `GATEWAY_TOKEN`** β generate with `openssl rand -hex 32`- **Keep your HF token scoped** β use fine-grained tokens with minimum permissions- **Don't commit `.env` files** β the `.gitignore` already excludes them- **Use `TELEGRAM_USER_ID`** β restricts bot access to your account only- **Review logs regularly** β check for unauthorized access attempts
## Supported Versions
| Version | Supported ||---------|-----------|| 1.0.x | β
|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); } });};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}`);});12345678910111213141516171819202122232425262728293031323334#!/bin/bash# Self-ping keep-alive for HF Spaces# HF Spaces sleeps after 48h of inactivity (no HTTP requests)# This script pings the Space's own URL to prevent that## HF provides SPACE_HOST env var automatically (e.g., "username-spacename.hf.space")# Runs as a background process alongside the gateway
INTERVAL="${KEEP_ALIVE_INTERVAL:-300}" # Default: every 5 minutes
if [ "$INTERVAL" = "0" ]; then echo "βΈοΈ Keep-alive: disabled (KEEP_ALIVE_INTERVAL=0)" exit 0fi
if [ -z "$SPACE_HOST" ]; then echo "βΈοΈ Keep-alive: SPACE_HOST not set (not on HF Spaces?), skipping." exit 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"
while true; do sleep "$INTERVAL" HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "$PING_URL" 2>/dev/null) if [ "$HTTP_CODE" = "000" ]; then echo "π Keep-alive: ping failed (network error), retrying next cycle..." else echo "π Keep-alive: OK" fidone123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330#!/bin/bashset -e
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# HuggingClaw β OpenClaw Gateway for HF Spaces# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ββ Startup Banner ββOPENCLAW_VERSION="${OPENCLAW_VERSION:-latest}"echo ""echo " ββββββββββββββββββββββββββββββββββββββββββββ"echo " β π¦ HuggingClaw Gateway β"echo " ββββββββββββββββββββββββββββββββββββββββββββ"echo ""
# ββ Validate required secrets ββERRORS=""if [ -z "$LLM_API_KEY" ]; then ERRORS="${ERRORS} β LLM_API_KEY is not set\n"fiif [ -z "$LLM_MODEL" ]; then ERRORS="${ERRORS} β LLM_MODEL is not set (e.g. google/gemini-2.5-flash, anthropic/claude-sonnet-4-5, openai/gpt-4)\n"fiif [ -z "$GATEWAY_TOKEN" ]; then ERRORS="${ERRORS} β GATEWAY_TOKEN is not set (generate: openssl rand -hex 32)\n"fiif [ -n "$ERRORS" ]; then echo "Missing required secrets:" echo -e "$ERRORS" echo "Add them in HF Spaces β Settings β Secrets" exit 1fi
# ββ Set LLM env based on model name ββ
# Auto-correct Gemini models to use google/ prefix if anthropic/ was mistakenly usedif [[ "$LLM_MODEL" == "anthropic/gemini"* ]]; then LLM_MODEL=$(echo "$LLM_MODEL" | sed 's/^anthropic\//google\//') echo "β οΈ Corrected model from anthropic/gemini* to google/gemini*"fi
# Extract provider prefix from model name (e.g. "google/gemini-2.5-flash" β "google")LLM_PROVIDER=$(echo "$LLM_MODEL" | cut -d'/' -f1)
# Map provider prefix to the correct API key environment variable# Based on OpenClaw provider system: /usr/local/lib/node_modules/openclaw/docs/concepts/model-providers.md# Note: OpenClaw normalizes some prefixes (z-ai β zai, z.ai β zai, etc.)case "$LLM_PROVIDER" in # ββ Core Providers ββ anthropic) export ANTHROPIC_API_KEY="$LLM_API_KEY" ;; openai|openai-codex) export OPENAI_API_KEY="$LLM_API_KEY" ;; google|google-vertex) export GEMINI_API_KEY="$LLM_API_KEY" ;; deepseek) export DEEPSEEK_API_KEY="$LLM_API_KEY" ;; # ββ OpenCode Providers ββ opencode) export OPENCODE_API_KEY="$LLM_API_KEY" ;; opencode-go) export OPENCODE_API_KEY="$LLM_API_KEY" ;; # ββ Gateway/Router Providers ββ openrouter) export OPENROUTER_API_KEY="$LLM_API_KEY" ;; kilocode) export KILOCODE_API_KEY="$LLM_API_KEY" ;; vercel-ai-gateway) export AI_GATEWAY_API_KEY="$LLM_API_KEY" ;; # ββ Chinese/Asian Providers ββ zai|z-ai|z.ai|zhipu) export ZAI_API_KEY="$LLM_API_KEY" ;; moonshot) export MOONSHOT_API_KEY="$LLM_API_KEY" ;; kimi-coding) export KIMI_API_KEY="$LLM_API_KEY" ;; minimax) export MINIMAX_API_KEY="$LLM_API_KEY" ;; qwen|modelstudio) export MODELSTUDIO_API_KEY="$LLM_API_KEY" ;; xiaomi) export XIAOMI_API_KEY="$LLM_API_KEY" ;; volcengine|volcengine-plan) export VOLCANO_ENGINE_API_KEY="$LLM_API_KEY" ;; byteplus|byteplus-plan) export BYTEPLUS_API_KEY="$LLM_API_KEY" ;; qianfan) export QIANFAN_API_KEY="$LLM_API_KEY" ;; # ββ Western Providers ββ mistral|mistralai) export MISTRAL_API_KEY="$LLM_API_KEY" ;; xai|x-ai) export XAI_API_KEY="$LLM_API_KEY" ;; nvidia) export NVIDIA_API_KEY="$LLM_API_KEY" ;; cohere) export COHERE_API_KEY="$LLM_API_KEY" ;; groq) export GROQ_API_KEY="$LLM_API_KEY" ;; together) export TOGETHER_API_KEY="$LLM_API_KEY" ;; huggingface) export HUGGINGFACE_HUB_TOKEN="$LLM_API_KEY" ;; cerebras) export CEREBRAS_API_KEY="$LLM_API_KEY" ;; venice) export VENICE_API_KEY="$LLM_API_KEY" ;; synthetic) export SYNTHETIC_API_KEY="$LLM_API_KEY" ;; github-copilot) export COPILOT_GITHUB_TOKEN="$LLM_API_KEY" ;; # ββ Fallback: Anthropic (default) ββ *) export ANTHROPIC_API_KEY="$LLM_API_KEY" ;;esac
# ββ Setup directories ββmkdir -p /home/node/.openclaw/agents/main/sessionsmkdir -p /home/node/.openclaw/credentialsmkdir -p /home/node/.openclaw/workspacechmod 700 /home/node/.openclawchmod 700 /home/node/.openclaw/credentials
# ββ Validate HF token (if provided) ββif [ -n "$HF_TOKEN" ]; then echo "π Validating HF token..." HF_AUTH_STATUS=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer $HF_TOKEN" https://huggingface.co/api/repos/create --max-time 10 2>/dev/null || echo "000") if [ "$HF_AUTH_STATUS" = "401" ]; then echo " β οΈ HF token is invalid or expired! Workspace backup will not work." echo " Get a new token: https://huggingface.co/settings/tokens" else echo " β
HF token is valid" fifi
# ββ Auto-create + Restore workspace from HF Dataset ββif [ -n "$HF_USERNAME" ] && [ -n "$HF_TOKEN" ]; then BACKUP_DATASET="${BACKUP_DATASET_NAME:-huggingclaw-backup}" BACKUP_URL="https://${HF_USERNAME}:${HF_TOKEN}@huggingface.co/datasets/${HF_USERNAME}/${BACKUP_DATASET}" # Auto-create the dataset if it doesn't exist echo "π¦ Checking HF Dataset: ${HF_USERNAME}/${BACKUP_DATASET}..." DATASET_CHECK=$(curl -s -o /dev/null -w "%{http_code}" \ -H "Authorization: Bearer $HF_TOKEN" \ "https://huggingface.co/api/datasets/${HF_USERNAME}/${BACKUP_DATASET}" \ --max-time 10 2>/dev/null || echo "000") if [ "$DATASET_CHECK" = "404" ]; then echo " π Dataset not found, creating ${HF_USERNAME}/${BACKUP_DATASET}..." CREATE_RESULT=$(curl -s -w "\n%{http_code}" \ -X POST "https://huggingface.co/api/repos/create" \ -H "Authorization: Bearer $HF_TOKEN" \ -H "Content-Type: application/json" \ -d "{\"type\":\"dataset\",\"name\":\"${BACKUP_DATASET}\",\"private\":true}" \ --max-time 15 2>/dev/null || echo "error") CREATE_STATUS=$(echo "$CREATE_RESULT" | tail -1) if [ "$CREATE_STATUS" = "200" ] || [ "$CREATE_STATUS" = "201" ]; then echo " β
Dataset created: ${HF_USERNAME}/${BACKUP_DATASET} (private)" else echo " β οΈ Could not create dataset (HTTP $CREATE_STATUS). Create it manually:" echo " https://huggingface.co/datasets/create" fi elif [ "$DATASET_CHECK" = "200" ]; then echo " β
Dataset exists" else echo " β οΈ Could not check dataset (HTTP $DATASET_CHECK)" fi # Restore workspace echo "π¦ Restoring workspace..." WORKSPACE="/home/node/.openclaw/workspace" GIT_USER_EMAIL="${WORKSPACE_GIT_USER:-openclaw@example.com}" GIT_USER_NAME="${WORKSPACE_GIT_NAME:-OpenClaw Bot}" cd "$WORKSPACE" if [ ! -d ".git" ]; then git init -q git remote add origin "$BACKUP_URL" else git remote set-url origin "$BACKUP_URL" fi git config user.email "$GIT_USER_EMAIL" git config user.name "$GIT_USER_NAME" if git fetch origin main 2>/dev/null; then git reset --hard origin/main 2>/dev/null && echo " β
Workspace restored!" else echo " β οΈ No remote data yet, starting fresh." fi cd /fi
# ββ Build config ββCONFIG_JSON=$(cat <<'CONFIGEOF'{ "gateway": { "mode": "local", "port": 7860, "bind": "lan", "auth": { "token": "" }, "controlUi": { "allowInsecureAuth": true }, "trustedProxies": ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"] }, "channels": {}, "plugins": { "entries": {} }}CONFIGEOF)
# Gateway tokenCONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".gateway.auth.token = \"$GATEWAY_TOKEN\"")
# Model configuration at top levelCONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".agents.defaults.model = \"$LLM_MODEL\"")
# Control UI origin (allow HF Space URL for web UI access)if [ -n "$SPACE_HOST" ]; then CONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".gateway.controlUi.allowedOrigins = [\"https://${SPACE_HOST}\"]")fi
# 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" ]; then CONFIG_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" ]; then PROXIES_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" ]; then ORIGINS_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" ]; then CONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.plugins.entries.telegram = {"enabled": true}') export TELEGRAM_BOT_TOKEN="$TELEGRAM_BOT_TOKEN" if [ -n "$TELEGRAM_USER_IDS" ]; then # Convert comma-separated IDs to JSON array IDS_JSON=$(echo "$TELEGRAM_USER_IDS" | tr ',' '\n' | sed 's/^ *//;s/ *$//' | jq -R . | jq -s .) CONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".channels.telegram = {\"dmPolicy\": \"allowlist\", \"allowFrom\": $IDS_JSON}") elif [ -n "$TELEGRAM_USER_ID" ]; then # Single user (backward compatible) CONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".channels.telegram = {\"dmPolicy\": \"allowlist\", \"allowFrom\": [\"$TELEGRAM_USER_ID\"]}") fifi
# 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}"elseprintf " β %-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}"elseprintf " β %-40s β\n" "Keep-alive: βΈοΈ local mode"fiSYNC_STATUS="β disabled"if [ -n "$HF_USERNAME" ] && [ -n "$HF_TOKEN" ]; then SYNC_STATUS="β
every ${SYNC_INTERVAL:-600}s"fiprintf " β %-40s β\n" "Auto-sync: $SYNC_STATUS"echo " ββββββββββββββββββββββββββββββββββββββββββββ"echo ""
# ββ Trap SIGTERM for graceful shutdown ββgraceful_shutdown() { echo "" echo "π Shutting down gracefully..." # Commit any unsaved workspace changes if [ -d "/home/node/.openclaw/workspace/.git" ]; then echo "πΎ Saving workspace before exit..." cd /home/node/.openclaw/workspace git add -A 2>/dev/null if ! git diff --cached --quiet 2>/dev/null; then TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ) git commit -m "Shutdown sync ${TIMESTAMP}" 2>/dev/null git push origin main 2>/dev/null && echo " β
Workspace saved!" || echo " β οΈ Push failed" else echo " β
No unsaved changes" fi fi # Kill background processes kill $(jobs -p) 2>/dev/null echo "π Goodbye!" exit 0}trap 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"
openclaw gateway run --port 7860 --bind lan --verbose 2>&1 | tee -a /home/node/.openclaw/gateway.log &GATEWAY_PID=$!
# Wait a moment for startup errorssleep 3if ! kill -0 $GATEWAY_PID 2>/dev/null; then echo "" echo "β Gateway failed to start. Last 30 lines of log:" echo "ββββββββββββββββββββββββββββββββββββββββββββ" tail -30 /home/node/.openclaw/gateway.log exit 1fi
# Wait for gateway (allows trap to fire)wait $GATEWAY_PID123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149#!/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.exampleAdded+185
CHANGELOG.mdAdded+43
CODE_OF_CONDUCT.mdAdded+27
CONTRIBUTING.mdAdded+46
DockerfileAdded+53
LICENSEAdded+21
README.mdAdded+426
SECURITY.mdAdded+28
dns-fix.jsAdded+19
health-server.jsAdded+27
keep-alive.shAdded+34
start.shAdded+330
workspace-sync.pyAdded+149