Spaces:
Paused
Paused
feat: replace UptimeRobot with an automated Cloudflare Worker for Space keep-alive functionality
Browse filesFiles changed (7)
- .env.example+3-3
- Dockerfile+2-2
- README.md+7-8
- cloudflare-keepalive-setup.pyAdded+212
- health-server.js+277-792
- setup-uptimerobot.shDeleted-91
- start.sh+3-3
205 unmodified lines206207208209210211212213214205 unmodified lines# Webhooks: Standard POST notifications for lifecycle events# WEBHOOK_URL=https://your-webhook-endpoint.com/log# UptimeRobot keep-alive: add your Main API key (NOT Read-only or Monitor-specific).# Monitor is created automatically at boot. Status shown on the dashboard.# UPTIMEROBOT_API_KEY=ur_your_api_key_here# Trusted proxies (comma-separated IPs)# Fixes "Proxy headers detected from untrusted address" behind reverse proxies205 unmodified lines206207208209210211212213214205 unmodified lines# Webhooks: Standard POST notifications for lifecycle events# WEBHOOK_URL=https://your-webhook-endpoint.com/log# Cloudflare proxy & keep-alive: add your Cloudflare API token.# A Worker is created automatically at boot for both outbound proxying and keep-alive.# CLOUDFLARE_WORKERS_TOKEN=your_cloudflare_token_here# Trusted proxies (comma-separated IPs)# Fixes "Proxy headers detected from untrusted address" behind reverse proxies
68 unmodified lines697071727374757668 unmodified linesCOPY --chown=1000:1000 iframe-fix.cjs /home/node/app/iframe-fix.cjsCOPY --chown=1000:1000 start.sh /home/node/app/start.shCOPY --chown=1000:1000 wa-guardian.js /home/node/app/wa-guardian.jsCOPY --chown=1000:1000 workspace-sync.py /home/node/app/workspace-sync.pyRUN chmod +x /home/node/app/start.sh /home/node/app/cloudflare-proxy-setup.pyUSER node68 unmodified lines697071727374757668 unmodified linesCOPY --chown=1000:1000 iframe-fix.cjs /home/node/app/iframe-fix.cjsCOPY --chown=1000:1000 start.sh /home/node/app/start.shCOPY --chown=1000:1000 wa-guardian.js /home/node/app/wa-guardian.jsCOPY --chown=1000:1000 cloudflare-keepalive-setup.py /home/node/app/cloudflare-keepalive-setup.pyRUN chmod +x /home/node/app/start.sh /home/node/app/cloudflare-proxy-setup.py /home/node/app/cloudflare-keepalive-setup.pyUSER node
14 unmodified lines15161718192021222332 unmodified lines56575859606162105 unmodified lines16816917017117217317412 unmodified lines187188189190191192193114 unmodified lines3083093103113123133146 unmodified lines32132232332432532632732814 unmodified lines- name: GATEWAY_TOKENdescription: "Strong token to secure your OpenClaw Control UI (generate: openssl rand -hex 32)."- name: CLOUDFLARE_WORKERS_TOKENdescription: "Cloudflare API token β auto-creates a Worker proxy for Telegram, WhatsApp, and Google APIs."- name: UPTIMEROBOT_API_KEYdescription: UptimeRobot API key for automatic monitor setup.---<!-- Badges -->32 unmodified lines- π³ **Fast Builds:** Uses a pre-built OpenClaw Docker image to deploy in minutes.- π **Cloudflare Outbound Proxy:** HuggingClaw can automatically provision a Cloudflare Worker proxy for blocked outbound traffic such as Telegram API requests.- πΎ **Workspace Backup:** Chats, settings, and WhatsApp session state sync to a private HF Dataset via the `huggingface_hub`, preserving data automatically without storing your HF token in a git remote.- β° **External Keep-Alive:** Add `UPTIMEROBOT_API_KEY` as a Space secret and the monitor is created automatically at boot β no manual setup.- π₯ **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.105 unmodified lines## π Staying Alive *(Recommended on Free HF Spaces)*Add your [UptimeRobot](https://uptimerobot.com/) **Main API key** as a Space secret named `UPTIMEROBOT_API_KEY`. HuggingClaw will automatically create a monitor for your Space's `/health` endpoint at boot. The dashboard shows the current status (configured, setting up, or failed).## π Webhooks *(Optional)*12 unmodified lines| `OPENCLAW_PASSWORD` | β | Enable simple password auth instead of token || `TRUSTED_PROXIES` | β | Comma-separated IPs of HF proxies || `ALLOWED_ORIGINS` | β | Comma-separated allowed origins for Control UI || `OPENCLAW_VERSION` | `latest` | Build-time pin for the OpenClaw image tag |## π€ LLM Providers114 unmodified lines- **Missing secrets:** Ensure `LLM_API_KEY`, `LLM_MODEL`, and `GATEWAY_TOKEN` are set in your Space **Settings β Secrets**.- **Telegram bot issues:** Verify your `TELEGRAM_BOT_TOKEN`. Check Space logs for lines like `π± Enabling Telegram`.- **Backup restore failing:** Make sure `HF_TOKEN` is valid and has write access to your HF account dataset. Set `HF_USERNAME` only if auto-detection is not available in your environment.- **Space keeps sleeping:** Add `UPTIMEROBOT_API_KEY` as a Space secret to enable automatic keep-awake monitoring.- **Auth errors / proxy:** If you see reverse-proxy auth errors, add the logged IPs under `TRUSTED_PROXIES` (from logs `remote=x.x.x.x`).- **Control UI says too many failed authentication attempts:** Wait for the retry window to expire, then open the Space in an incognito window or clear site storage for your Space before logging in again with `GATEWAY_TOKEN`.- **WhatsApp lost its session after restart:** Make sure `HF_TOKEN` is configured so the hidden session backup can be restored on boot.6 unmodified lines| Project | What it runs | HF Space | GitHub || :--- | :--- | :--- | :--- || **HuggingClip** | Paperclip β AI agent orchestration platform | [Space](https://huggingface.co/spaces/somratpro/HuggingClip) | [Repo](https://github.com/somratpro/huggingclip) || **Hugging8n** | n8n β workflow & automation platform | [Space](https://huggingface.co/spaces/somratpro/Hugging8n) | [Repo](https://github.com/somratpro/hugging8n) |## π Links14 unmodified lines1516171819202132 unmodified lines54555657585960105 unmodified lines16616716816917017117212 unmodified lines185186187188189190191114 unmodified lines3063073083093103113126 unmodified lines31932032132232332432532632714 unmodified lines- name: GATEWAY_TOKENdescription: "Strong token to secure your OpenClaw Control UI (generate: openssl rand -hex 32)."- name: CLOUDFLARE_WORKERS_TOKENdescription: "Cloudflare API token β auto-creates a Worker proxy and KeepAlive monitor."---<!-- Badges -->32 unmodified lines- π³ **Fast Builds:** Uses a pre-built OpenClaw Docker image to deploy in minutes.- π **Cloudflare Outbound Proxy:** HuggingClaw can automatically provision a Cloudflare Worker proxy for blocked outbound traffic such as Telegram API requests.- πΎ **Workspace Backup:** Chats, settings, and WhatsApp session state sync to a private HF Dataset via the `huggingface_hub`, preserving data automatically without storing your HF token in a git remote.- β° **Easy Keep-Alive:** Uses `CLOUDFLARE_WORKERS_TOKEN` to automatically set up a cron-triggered keep-awake worker at boot.- π₯ **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.105 unmodified lines## π Staying Alive *(Recommended on Free HF Spaces)*Your Space will automatically be kept awake by a background Cloudflare Worker when you configure the `CLOUDFLARE_WORKERS_TOKEN` secret. The worker uses a cron trigger to regularly ping your Space's `/health` endpoint. The dashboard displays the current keep-alive worker status.## π Webhooks *(Optional)*12 unmodified lines| `OPENCLAW_PASSWORD` | β | Enable simple password auth instead of token || `TRUSTED_PROXIES` | β | Comma-separated IPs of HF proxies || `ALLOWED_ORIGINS` | β | Comma-separated allowed origins for Control UI || `CLOUDFLARE_KEEPALIVE_ENABLED` | `true` | Set to `false` to disable the automatic Cloudflare KeepAlive worker |## π€ LLM Providers114 unmodified lines- **Missing secrets:** Ensure `LLM_API_KEY`, `LLM_MODEL`, and `GATEWAY_TOKEN` are set in your Space **Settings β Secrets**.- **Telegram bot issues:** Verify your `TELEGRAM_BOT_TOKEN`. Check Space logs for lines like `π± Enabling Telegram`.- **Backup restore failing:** Make sure `HF_TOKEN` is valid and has write access to your HF account dataset. Set `HF_USERNAME` only if auto-detection is not available in your environment.- **Space keeps sleeping:** Add `CLOUDFLARE_WORKERS_TOKEN` as a Space secret to enable automatic keep-awake monitoring via Cloudflare Workers.- **Auth errors / proxy:** If you see reverse-proxy auth errors, add the logged IPs under `TRUSTED_PROXIES` (from logs `remote=x.x.x.x`).- **Control UI says too many failed authentication attempts:** Wait for the retry window to expire, then open the Space in an incognito window or clear site storage for your Space before logging in again with `GATEWAY_TOKEN`.- **WhatsApp lost its session after restart:** Make sure `HF_TOKEN` is configured so the hidden session backup can be restored on boot.6 unmodified lines| Project | What it runs | HF Space | GitHub || :--- | :--- | :--- | :--- || **HuggingMess** | Hermes β Self-hosted agent gateway | [Space](https://huggingface.co/spaces/somratpro/HuggingMess) | [Repo](https://github.com/somratpro/huggingmess) || **Hugging8n** | n8n β workflow & automation platform | [Space](https://huggingface.co/spaces/somratpro/Hugging8n) | [Repo](https://github.com/somratpro/hugging8n) || **HuggingClip** | Paperclip β AI agent orchestration platform | [Space](https://huggingface.co/spaces/somratpro/HuggingClip) | [Repo](https://github.com/somratpro/huggingclip) |## π Links
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212#!/usr/bin/env python3from __future__ import annotations
"""Create or reuse a Cloudflare Worker for Space keep-awake."""
import jsonimport osimport reimport sysimport timeimport urllib.requestfrom pathlib import Path
API_BASE = "https://api.cloudflare.com/client/v4"KEEPALIVE_STATUS_FILE = Path("/tmp/huggingclaw-cloudflare-keepalive-status.json")
def cf_request(method: str, path: str, token: str, body: bytes | None = None, content_type: str = "application/json"): req = urllib.request.Request( f"{API_BASE}{path}", data=body, method=method, headers={"Authorization": f"Bearer {token}", "Content-Type": content_type}, ) with urllib.request.urlopen(req, timeout=30) as response: payload = json.loads(response.read().decode("utf-8")) if not payload.get("success"): errors = payload.get("errors") or [{"message": "Unknown Cloudflare API error"}] raise RuntimeError(errors[0].get("message", "Unknown Cloudflare API error")) return payload["result"]
def slugify(value: str) -> str: cleaned = re.sub(r"[^a-z0-9-]+", "-", value.lower()).strip("-") cleaned = re.sub(r"-{2,}", "-", cleaned) return (cleaned or "huggingclaw-proxy")[:63].rstrip("-")
def get_space_host() -> str: space_host = os.environ.get("SPACE_HOST", "").strip() if space_host: return space_host author = os.environ.get("SPACE_AUTHOR_NAME", "").strip() repo = os.environ.get("SPACE_REPO_NAME", "").strip() if author and repo: return f"{author}-{repo}.hf.space".lower() return ""
def derive_keepalive_worker_name() -> str: explicit = os.environ.get("CLOUDFLARE_KEEPALIVE_WORKER_NAME", "").strip() if explicit: return slugify(explicit) space_host = get_space_host() if space_host: return slugify(f"{space_host.replace('.hf.space', '')}-keepalive") return "huggingclaw-keepalive"
def render_keepalive_worker(target_url: str) -> str: return f"""addEventListener("fetch", (event) => {{ event.respondWith(handleRequest(event.request));}});
addEventListener("scheduled", (event) => {{ event.waitUntil(ping("cron"));}});
const TARGET_URL = {json.dumps(target_url)};
async function ping(source) {{ const startedAt = new Date().toISOString(); try {{ const response = await fetch(TARGET_URL, {{ method: "GET", headers: {{ "user-agent": "HuggingClaw Cloudflare KeepAlive", "cache-control": "no-cache" }}, cf: {{ cacheTtl: 0, cacheEverything: false }} }}); return {{ ok: response.ok, status: response.status, source, target: TARGET_URL, timestamp: startedAt }}; }} catch (error) {{ return {{ ok: false, status: 0, source, target: TARGET_URL, timestamp: startedAt, error: error.message }}; }}}}
async function handleRequest(request) {{ const url = new URL(request.url); if (url.pathname === "/" || url.pathname === "/health" || url.pathname === "/ping") {{ const result = await ping("manual"); return new Response(JSON.stringify(result, null, 2), {{ status: result.ok ? 200 : 502, headers: {{ "content-type": "application/json; charset=utf-8" }} }}); }} return new Response("Not found", {{ status: 404 }});}}"""
def write_keepalive_status(payload: dict) -> None: payload = { **payload, "timestamp": payload.get("timestamp") or time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), } KEEPALIVE_STATUS_FILE.write_text(json.dumps(payload), encoding="utf-8") try: KEEPALIVE_STATUS_FILE.chmod(0o600) except OSError: pass
def resolve_account_and_subdomain(api_token: str) -> tuple[str, str]: account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip() if not account_id: accounts = cf_request("GET", "/accounts", api_token) if not accounts: raise RuntimeError("No Cloudflare account is available for this token.") account_id = accounts[0]["id"]
subdomain_info = cf_request("GET", f"/accounts/{account_id}/workers/subdomain", api_token) subdomain = (subdomain_info or {}).get("subdomain", "").strip() if not subdomain: raise RuntimeError("Cloudflare Workers subdomain is not configured. Enable workers.dev first.") return account_id, subdomain
def setup_keepalive_worker(api_token: str, account_id: str, subdomain: str) -> None: enabled = os.environ.get("CLOUDFLARE_KEEPALIVE_ENABLED", "true").strip().lower() if enabled in {"0", "false", "no", "off"}: write_keepalive_status({"configured": False, "status": "disabled", "message": "Cloudflare keep-awake is disabled."}) return
space_host = get_space_host() if not space_host: write_keepalive_status({"configured": False, "status": "skipped", "message": "SPACE_HOST could not be determined."}) return
cron = os.environ.get("CLOUDFLARE_KEEPALIVE_CRON", "*/10 * * * *").strip() space_host = space_host.removeprefix("https://").removeprefix("http://").split("/")[0] target_url = os.environ.get("CLOUDFLARE_KEEPALIVE_URL", f"https://{space_host}/health").strip() worker_name = derive_keepalive_worker_name() worker_source = render_keepalive_worker(target_url)
cf_request( "PUT", f"/accounts/{account_id}/workers/scripts/{worker_name}", api_token, body=worker_source.encode("utf-8"), content_type="application/javascript", ) cf_request( "POST", f"/accounts/{account_id}/workers/scripts/{worker_name}/subdomain", api_token, body=json.dumps({"enabled": True, "previews_enabled": True}).encode("utf-8"), ) cf_request( "PUT", f"/accounts/{account_id}/workers/scripts/{worker_name}/schedules", api_token, body=json.dumps([{"cron": cron}]).encode("utf-8"), )
worker_url = f"https://{worker_name}.{subdomain}.workers.dev" write_keepalive_status( { "configured": True, "status": "configured", "workerName": worker_name, "workerUrl": worker_url, "targetUrl": target_url, "cron": cron, "message": f"Cloudflare Worker cron pings {target_url} on {cron}.", } )
def main() -> int: api_token = os.environ.get("CLOUDFLARE_WORKERS_TOKEN", "").strip()
if not api_token: return 0
try: account_id, subdomain = resolve_account_and_subdomain(api_token) setup_keepalive_worker(api_token, account_id, subdomain) return 0 except Exception as exc: print(f"Cloudflare keepalive setup failed: {exc}", file=sys.stderr) write_keepalive_status({"configured": False, "status": "error", "message": str(exc)}) return 1
if __name__ == "__main__": raise SystemExit(main())12 unmodified lines131415161718192021222324253 unmodified lines293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914011 unmodified lines15215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189212 unmodified linesconst WHATSAPP_STATUS_FILE = "/tmp/huggingclaw-wa-status.json";const HF_BACKUP_ENABLED = !!process.env.HF_TOKEN;const SYNC_INTERVAL = process.env.SYNC_INTERVAL || "180";const DASHBOARD_BASE = "/dashboard";const DASHBOARD_STATUS_PATH = `${DASHBOARD_BASE}/status`;const DASHBOARD_HEALTH_PATH = `${DASHBOARD_BASE}/health`;const DASHBOARD_APP_BASE = `${DASHBOARD_BASE}/app`;const APP_BASE = "/app";const UPTIMEROBOT_STATUS_FILE = "/tmp/huggingclaw-uptimerobot-status.json";const UPTIMEROBOT_API_KEY_SET = !!process.env.UPTIMEROBOT_API_KEY;function parseRequestUrl(url) {try {3 unmodified lines}}function isDashboardRoute(pathname) {return (pathname === "/" ||pathname === DASHBOARD_BASE ||pathname === `${DASHBOARD_BASE}/`);}function isDashboardAppRoute(pathname) {return (pathname === DASHBOARD_APP_BASE ||pathname.startsWith(`${DASHBOARD_APP_BASE}/`));}function isAppRoute(pathname) {return pathname === APP_BASE || pathname.startsWith(`${APP_BASE}/`);}function isLocalRoute(pathname) {return (pathname === "/health" ||pathname === "/status" ||pathname === DASHBOARD_HEALTH_PATH ||pathname === DASHBOARD_STATUS_PATH);}function mapAppProxyPath(path) {if (path === DASHBOARD_APP_BASE) return APP_BASE;if (path.startsWith(`${DASHBOARD_APP_BASE}/`)) {return `${APP_BASE}${path.slice(DASHBOARD_APP_BASE.length)}`;}if (path === APP_BASE || path.startsWith(`${APP_BASE}/`)) {return path;}return path;}function sanitizeAppProxySearch(parsedUrl) {const filtered = new URLSearchParams(parsedUrl.searchParams);// HF Space UI sometimes appends its own control params to deep links.filtered.delete("logs");const query = filtered.toString();return query ? `?${query}` : "";}function appendForwarded(existingValue, nextValue) {const cleanNext = nextValue || "";if (!existingValue) return cleanNext;if (Array.isArray(existingValue))return `${existingValue.join(", ")}, ${cleanNext}`;return `${existingValue}, ${cleanNext}`;}function getForwardedClientIp(req) {const forwardedFor = req.headers["x-forwarded-for"];if (Array.isArray(forwardedFor) && forwardedFor.length > 0) {return String(forwardedFor[0]).split(",")[0].trim();}if (typeof forwardedFor === "string" && forwardedFor.trim()) {return forwardedFor.split(",")[0].trim();}return req.socket.remoteAddress || "";}function buildProxyHeaders(headers, remoteAddress) {return {...headers,host: `${GATEWAY_HOST}:${GATEWAY_PORT}`,"x-forwarded-for": remoteAddress || "","x-forwarded-host": headers.host || "","x-forwarded-proto": headers["x-forwarded-proto"] || "https",};}function getRequesterIp(req) {return (getForwardedClientIp(req) ||req.socket.remoteAddress ||"unknown");}function readSyncStatus() {try {if (fs.existsSync("/tmp/sync-status.json")) {return JSON.parse(fs.readFileSync("/tmp/sync-status.json", "utf8"));}} catch {}if (HF_BACKUP_ENABLED) {return {status: "configured",message: `Backup is enabled. Waiting for the next sync window (${SYNC_INTERVAL}s).`,};}return { status: "unknown", message: "No sync data yet" };}function normalizeChannelStatus(channel, configured) {return {configured: configured || !!channel,connected: !!(channel && channel.connected),};}function readGuardianStatus() {if (!WHATSAPP_ENABLED) {return { configured: false, connected: false, pairing: false };11 unmodified linesreturn { configured: true, connected: false, pairing: false };}function getUptimeRobotStatus() {try {if (fs.existsSync(UPTIMEROBOT_STATUS_FILE)) {return JSON.parse(fs.readFileSync(UPTIMEROBOT_STATUS_FILE, "utf8"));}} catch {}return null;}function renderChannelBadge(channel, configuredLabel) {if (channel && channel.connected) {return '<div class="status-badge status-online"><div class="pulse"></div>Active</div>';}if (channel && channel.configured) {return `<div class="status-badge status-syncing">${configuredLabel}</div>`;}return '<div class="status-badge status-offline">Disabled</div>';}function renderSyncBadge(syncData) {let badgeClass = "status-offline";let pulseHtml = "";if (syncData.status === "success" || syncData.status === "configured") {badgeClass = "status-online";pulseHtml = '<div class="pulse"></div>';} else if (syncData.status === "syncing") {badgeClass = "status-syncing";pulseHtml = '<div class="pulse" style="background:#3b82f6"></div>';}return `<div class="status-badge ${badgeClass}">${pulseHtml}${String(syncData.status || "unknown").toUpperCase()}</div>`;}function renderDashboard(initialData) {const controlUiHref = `${APP_BASE}/`;const urStatus = initialData.uptimerobotStatus;let keepAwakeHtml;if (urStatus?.configured) {keepAwakeHtml = `<div class="helper-summary success"><div class="status-badge status-online"><div class="pulse"></div>CONFIGURED</div><span>UptimeRobot monitor active for <code>${urStatus.url || "your /health endpoint"}</code>.</span></div>`;} else if (urStatus?.configured === false) {keepAwakeHtml = `<div class="helper-summary" style="background:rgba(239,68,68,0.08);"><div class="status-badge status-offline">FAILED</div><span>Monitor setup failed. Check Space logs for details.</span></div>`;} else if (UPTIMEROBOT_API_KEY_SET) {keepAwakeHtml = `<div class="helper-summary"><div class="status-badge status-syncing">SETTING UP…</div><span>UptimeRobot monitor is being configured.</span></div>`;} else {keepAwakeHtml = `<div class="helper-summary"><strong>Not configured.</strong> Add <code>UPTIMEROBOT_API_KEY</code> to Space secrets to enable keep-awake monitoring.</div>`;}return `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>HuggingClaw Dashboard</title><link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600&display=swap" rel="stylesheet"><style>:root {--bg: #0f172a;--card-bg: rgba(30, 41, 59, 0.7);--accent: linear-gradient(135deg, #3b82f6, #8b5cf6);--text: #f8fafc;--text-dim: #94a3b8;--success: #10b981;--error: #ef4444;--warning: #f59e0b;}* { box-sizing: border-box; margin: 0; padding: 0; }body {font-family: 'Outfit', sans-serif;background-color: var(--bg);color: var(--text);display: flex;justify-content: center;align-items: flex-start;min-height: 100vh;overflow-x: hidden;overflow-y: auto;padding: 24px 0;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;margin: 24px 0;}@keyframes fadeIn {from { opacity: 0; transform: translateY(20px); }to { opacity: 1; transform: translateY(0); }}header {text-align: center;margin-bottom: 40px;}h1 {font-size: 2.5rem;margin-bottom: 8px;background: var(--accent);-webkit-background-clip: text;-webkit-text-fill-color: transparent;font-weight: 600;}.subtitle {color: var(--text-dim);font-size: 0.9rem;letter-spacing: 1px;text-transform: uppercase;}.stats-grid {display: grid;grid-template-columns: repeat(2, 1fr);gap: 20px;margin-bottom: 30px;}.stat-card {background: rgba(255, 255, 255, 0.03);border: 1px solid rgba(255, 255, 255, 0.05);padding: 20px;border-radius: 16px;transition: transform 0.3s ease, border-color 0.3s ease;}.stat-card:hover {transform: translateY(-5px);border-color: rgba(59, 130, 246, 0.3);}.stat-label {color: var(--text-dim);font-size: 0.75rem;text-transform: uppercase;margin-bottom: 8px;display: block;}.stat-value {font-size: 1.1rem;font-weight: 600;word-break: break-all;}.stat-btn {grid-column: span 2;background: var(--accent);color: #fff;padding: 16px;border-radius: 16px;text-align: center;text-decoration: none;font-weight: 600;margin-top: 10px;transition: transform 0.3s ease, box-shadow 0.3s ease;box-shadow: 0 10px 20px -5px rgba(59, 130, 246, 0.4);}.stat-btn:hover {transform: scale(1.02);box-shadow: 0 15px 30px -5px rgba(59, 130, 246, 0.6);}.status-badge {display: inline-flex;align-items: center;gap: 6px;padding: 4px 12px;border-radius: 20px;font-size: 0.8rem;font-weight: 600;}.status-online { background: rgba(16, 185, 129, 0.1); color: var(--success); }.status-offline { background: rgba(239, 68, 68, 0.1); color: var(--error); }.status-syncing { background: rgba(59, 130, 246, 0.1); color: #3b82f6; }.pulse {width: 8px;height: 8px;border-radius: 50%;background: currentColor;box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);animation: pulse 2s infinite;}@keyframes pulse {0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }70% { transform: scale(1); box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); }100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }}.footer {text-align: center;color: var(--text-dim);font-size: 0.8rem;margin-top: 20px;}.sync-info {background: rgba(255, 255, 255, 0.02);padding: 15px;border-radius: 12px;font-size: 0.85rem;color: var(--text-dim);margin-top: 10px;}#sync-msg { color: var(--text); display: block; margin-top: 4px; }.card-header {display: flex;align-items: center;justify-content: space-between;gap: 12px;margin-bottom: 8px;}.card-header .stat-label {margin-bottom: 0;}.helper-card {width: 100%;margin-top: 20px;}.helper-copy {color: var(--text-dim);font-size: 0.92rem;line-height: 1.6;margin-top: 10px;}.helper-copy strong {color: var(--text);}.helper-row {display: flex;gap: 10px;margin-top: 16px;flex-wrap: wrap;}.helper-input {flex: 1;min-width: 240px;background: rgba(255, 255, 255, 0.04);border: 1px solid rgba(255, 255, 255, 0.08);color: var(--text);border-radius: 12px;padding: 14px 16px;font: inherit;}.helper-input::placeholder {color: var(--text-dim);}.helper-button {background: var(--accent);color: #fff;border: 0;border-radius: 12px;padding: 14px 18px;font: inherit;font-weight: 600;cursor: pointer;min-width: 180px;}.helper-button:disabled {opacity: 0.6;cursor: wait;}.hidden {display: none !important;}.helper-note {margin-top: 10px;font-size: 0.82rem;color: var(--text-dim);}.helper-result {margin-top: 14px;padding: 12px 14px;border-radius: 12px;font-size: 0.9rem;display: none;}.helper-result.ok {display: block;background: rgba(16, 185, 129, 0.1);color: var(--success);}.helper-result.error {display: block;background: rgba(239, 68, 68, 0.1);color: var(--error);}.helper-shell {margin-top: 12px;}.helper-shell.hidden {display: none;}.helper-summary {margin-top: 14px;padding: 12px 14px;border-radius: 12px;background: rgba(255, 255, 255, 0.03);color: var(--text-dim);font-size: 0.9rem;line-height: 1.5;display: flex;align-items: center;gap: 10px;flex-wrap: wrap;}.helper-summary strong { color: var(--text); }.helper-summary code {background: rgba(255,255,255,0.06);padding: 2px 6px;border-radius: 6px;font-size: 0.82rem;color: var(--text);}.helper-summary.success { background: rgba(16, 185, 129, 0.08); }@media (max-width: 700px) {body {padding: 16px 0;}.dashboard {width: calc(100% - 24px);padding: 24px;border-radius: 18px;margin: 12px 0;}header {margin-bottom: 28px;}h1 {font-size: 2rem;}.stats-grid {grid-template-columns: 1fr;gap: 14px;margin-bottom: 20px;}.stat-btn {grid-column: span 1;}.stat-card {padding: 16px;}.card-header {align-items: flex-start;flex-direction: column;}.helper-row {flex-direction: column;}.helper-input,.helper-button {width: 100%;min-width: 0;}}</style></head><body><div class="dashboard"><header><h1>π¦ HuggingClaw</h1><p class="subtitle">Space Dashboard</p></header><div class="stats-grid"><div class="stat-card"><span class="stat-label">Model</span><span class="stat-value" id="model-id">${initialData.model}</span></div><div class="stat-card"><span class="stat-label">Uptime</span><span class="stat-value" id="uptime">${initialData.uptime}</span></div><div class="stat-card"><span class="stat-label">WhatsApp</span><span id="wa-status">${renderChannelBadge(initialData.whatsapp, "Ready to pair")}</span></div><div class="stat-card"><span class="stat-label">Telegram</span><span id="tg-status">${renderChannelBadge(initialData.telegram, "Configured")}</span></div><a href="${controlUiHref}" id="control-ui-link" class="stat-btn" target="_blank" rel="noopener noreferrer">Open Control UI</a></div><div class="stat-card" style="width: 100%;"><div class="card-header"><span class="stat-label">Workspace Sync Status</span><div id="sync-badge-container">${renderSyncBadge(initialData.sync)}</div></div><div class="sync-info">Last Sync Activity: <span id="sync-time">${initialData.sync.timestamp || "Never"}</span><span id="sync-msg">${initialData.sync.message || "Waiting for first sync..."}</span></div></div><div class="stat-card helper-card"><span class="stat-label">Keep Space Awake</span>${keepAwakeHtml}</div><div class="footer">Live updates every 10s</div></div><script>function getDashboardBase() {const pathname = window.location.pathname || '/';if (pathname === '/' || pathname === '') return '';if (pathname === '${DASHBOARD_BASE}' || pathname === '${DASHBOARD_BASE}/') return '${DASHBOARD_BASE}';return pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;}function getCurrentSearch() {return window.location.search || '';}async function updateStats() {try {const res = await fetch(getDashboardBase() + '/status' + getCurrentSearch());const data = await res.json();document.getElementById('model-id').textContent = data.model;document.getElementById('uptime').textContent = data.uptime;function renderChannelStatus(channel, configuredLabel) {if (channel && channel.connected) {return '<div class="status-badge status-online"><div class="pulse"></div>Active</div>';}if (channel && channel.configured) {return '<div class="status-badge status-syncing">' + configuredLabel + '</div>';}return '<div class="status-badge status-offline">Disabled</div>';}document.getElementById('wa-status').innerHTML = renderChannelStatus(data.whatsapp, 'Ready to pair');document.getElementById('tg-status').innerHTML = renderChannelStatus(data.telegram, 'Configured');const syncData = data.sync;let badgeClass = 'status-offline';let pulseHtml = '';if (syncData.status === 'success' || syncData.status === 'configured') {badgeClass = 'status-online';pulseHtml = '<div class="pulse"></div>';} else if (syncData.status === 'syncing') {badgeClass = 'status-syncing';pulseHtml = '<div class="pulse" style="background:#3b82f6"></div>';}document.getElementById('sync-badge-container').innerHTML ='<div class="status-badge ' + badgeClass + '">' + pulseHtml + syncData.status.toUpperCase() + '</div>';document.getElementById('sync-time').textContent = syncData.timestamp || 'Never';document.getElementById('sync-msg').textContent = syncData.message || 'Waiting for first sync...';} catch (e) {console.error("Failed to fetch status", e);}}updateStats();setInterval(updateStats, 10000);document.getElementById('control-ui-link').setAttribute('href', getDashboardBase() + '/app/' + getCurrentSearch());</script></body></html>`;}function proxyHttp(req, res, proxyPath = req.url, proxyPort = GATEWAY_PORT) {const clientIp = getForwardedClientIp(req);let upstreamStarted = false;const proxyReq = http.request({hostname: GATEWAY_HOST,port: proxyPort,method: req.method,path: proxyPath,headers: buildProxyHeaders(req.headers, clientIp),},(proxyRes) => {upstreamStarted = true;res.writeHead(proxyRes.statusCode || 502, proxyRes.headers);proxyRes.pipe(res);},);proxyReq.on("error", (error) => {if (res.headersSent || upstreamStarted) {res.destroy();return;}res.writeHead(502, { "Content-Type": "application/json" });res.end(JSON.stringify({status: "error",message: "Gateway unavailable",detail: error.message,}),);});res.on("close", () => {proxyReq.destroy();});req.pipe(proxyReq);}function serializeUpgradeHeaders(req, clientIp, proxyPort) {const forwardedHeaders = [];for (let i = 0; i < req.rawHeaders.length; i += 2) {const name = req.rawHeaders[i];const value = req.rawHeaders[i + 1];const lower = name.toLowerCase();if (lower === "host" ||lower === "x-forwarded-for" ||lower === "x-forwarded-host" ||lower === "x-forwarded-proto") {continue;}forwardedHeaders.push(`${name}: ${value}`);}forwardedHeaders.push(`Host: ${GATEWAY_HOST}:${proxyPort}`,);forwardedHeaders.push(`X-Forwarded-For: ${clientIp || ""}`,);forwardedHeaders.push(`X-Forwarded-Host: ${req.headers.host || ""}`,);forwardedHeaders.push(`X-Forwarded-Proto: ${req.headers["x-forwarded-proto"] || "https"}`,);return forwardedHeaders;}function proxyUpgrade(req,socket,head,proxyPath = req.url,proxyPort = GATEWAY_PORT,) {const proxySocket = net.connect(proxyPort, GATEWAY_HOST);const clientIp = getForwardedClientIp(req);proxySocket.on("connect", () => {const requestLines = [`${req.method} ${proxyPath} HTTP/${req.httpVersion}`,...serializeUpgradeHeaders(req, clientIp, proxyPort),"","",];proxySocket.write(requestLines.join("\r\n"));if (head && head.length > 0) {proxySocket.write(head);}socket.pipe(proxySocket).pipe(socket);});proxySocket.on("error", () => {if (socket.writable) {socket.write("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n");}socket.destroy();});socket.on("error", () => {proxySocket.destroy();});}const server = http.createServer((req, res) => {const parsedUrl = parseRequestUrl(req.url || "/");const pathname = parsedUrl.pathname;const uptime = Math.floor((Date.now() - startTime) / 1000);const uptimeHuman = `${Math.floor(uptime / 3600)}h ${Math.floor((uptime % 3600) / 60)}m`;if (pathname === "/health" || pathname === DASHBOARD_HEALTH_PATH) {res.writeHead(200, { "Content-Type": "application/json" });res.end(JSON.stringify({status: "ok",uptime,uptimeHuman,timestamp: new Date().toISOString(),}),);return;}if (pathname === "/status" || pathname === DASHBOARD_STATUS_PATH) {void (async () => {const guardianStatus = readGuardianStatus();res.writeHead(200, { "Content-Type": "application/json" });res.end(JSON.stringify({model: LLM_MODEL,whatsapp: {configured: guardianStatus.configured,connected: guardianStatus.connected,pairing: guardianStatus.pairing,},telegram: normalizeChannelStatus(null, TELEGRAM_ENABLED),sync: readSyncStatus(),uptime: uptimeHuman,}),);})();return;}if (isDashboardRoute(pathname)) {const guardianStatus = readGuardianStatus();const initialData = {model: LLM_MODEL,whatsapp: {configured: guardianStatus.configured,connected: guardianStatus.connected,pairing: guardianStatus.pairing,},telegram: normalizeChannelStatus(null, TELEGRAM_ENABLED),sync: readSyncStatus(),uptime: uptimeHuman,uptimerobotStatus: getUptimeRobotStatus(),};res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });res.end(renderDashboard(initialData));return;}if (isDashboardAppRoute(pathname) || isAppRoute(pathname)) {const proxyPath = mapAppProxyPath(pathname) + sanitizeAppProxySearch(parsedUrl);proxyHttp(req, res, proxyPath, GATEWAY_PORT);return;}proxyHttp(req, res);});server.on("upgrade", (req, socket, head) => {const pathname = parseRequestUrl(req.url || "/").pathname;if (isLocalRoute(pathname)) {socket.destroy();return;}if (isDashboardAppRoute(pathname) || isAppRoute(pathname)) {const parsedUrl = parseRequestUrl(req.url || "/");const proxyPath = mapAppProxyPath(pathname) + sanitizeAppProxySearch(parsedUrl);proxyUpgrade(req, socket, head, proxyPath, GATEWAY_PORT);return;}proxyUpgrade(req, socket, head);});server.listen(PORT, "0.0.0.0", () => {console.log(`Health server listening on port ${PORT}; proxying gateway traffic to ${GATEWAY_HOST}:${GATEWAY_PORT}`,);});12 unmodified lines1314151617181920213 unmodified lines25262728293031323334353637383940414243444511 unmodified lines5758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637712 unmodified linesconst WHATSAPP_STATUS_FILE = "/tmp/huggingclaw-wa-status.json";const HF_BACKUP_ENABLED = !!process.env.HF_TOKEN;const SYNC_INTERVAL = process.env.SYNC_INTERVAL || "180";const APP_BASE = "/app";const SYNC_STATUS_FILE = "/tmp/sync-status.json";const CLOUDFLARE_KEEPALIVE_STATUS_FILE = "/tmp/huggingclaw-cloudflare-keepalive-status.json";function parseRequestUrl(url) {try {3 unmodified lines}}function getSyncStatus() {try {if (fs.existsSync(SYNC_STATUS_FILE)) {return JSON.parse(fs.readFileSync(SYNC_STATUS_FILE, "utf8"));}} catch {}if (HF_BACKUP_ENABLED) {return {status: "configured",message: `Backup is enabled. Waiting for sync window (${SYNC_INTERVAL}s).`,};}return { status: "unknown", message: "No sync data yet" };}function readGuardianStatus() {if (!WHATSAPP_ENABLED) {return { configured: false, connected: false, pairing: false };11 unmodified linesreturn { configured: true, connected: false, pairing: false };}function getKeepaliveStatus() {try {if (fs.existsSync(CLOUDFLARE_KEEPALIVE_STATUS_FILE)) {return JSON.parse(fs.readFileSync(CLOUDFLARE_KEEPALIVE_STATUS_FILE, "utf8"));}} catch {}return null;}function probeGatewayHealth(timeoutMs = 1500) {return new Promise((resolve) => {const request = http.get({hostname: GATEWAY_HOST,port: GATEWAY_PORT,path: "/health",timeout: timeoutMs,},(response) => {response.resume();resolve(response.statusCode >= 200 && response.statusCode < 400);},);request.on("timeout", () => {request.destroy();resolve(false);});request.on("error", () => resolve(false));});}function formatUptime(ms) {const total = Math.floor(ms / 1000);const days = Math.floor(total / 86400);const hours = Math.floor((total % 86400) / 3600);const minutes = Math.floor((total % 3600) / 60);if (days) return `${days}d ${hours}h ${minutes}m`;if (hours) return `${hours}h ${minutes}m`;return `${minutes}m`;}function escapeHtml(value) {return String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);}function toneBadge(label, tone = "neutral") {return `<span class="badge ${tone}">${escapeHtml(label)}</span>`;}function renderTile({ title, value, detail = "", tone = "neutral", meta = "" }) {return `<article class="tile ${tone}"><div class="tile-head"><span class="tile-title">${escapeHtml(title)}</span><span class="tile-dot"></span></div><div class="tile-value">${value}</div>${detail ? `<div class="tile-detail">${detail}</div>` : ""}${meta ? `<div class="tile-meta">${meta}</div>` : ""}</article>`;}function renderDashboard(data) {const syncStatus = String(data.sync?.status || "unknown");const syncTone = ["success", "restored", "synced", "configured"].includes(syncStatus)? "ok": syncStatus === "disabled"? "warn": "neutral";const backupDetail = data.sync?.message ? escapeHtml(data.sync.message) : "No status yet";const keepaliveConfigured = data.keepalive?.configured === true;const keepaliveStatus = String(data.keepalive?.status ||(process.env.CLOUDFLARE_WORKERS_TOKEN ? "pending" : "not configured"),);const keepAliveTone = keepaliveConfigured? "ok": process.env.CLOUDFLARE_WORKERS_TOKEN? "warn": "neutral";const keepAliveDetail = keepaliveConfigured? `Pinging <code>${escapeHtml(data.keepalive.targetUrl || "/health")}</code>`: process.env.CLOUDFLARE_WORKERS_TOKEN? "Worker pending or failed": "Not configured";const tiles = [renderTile({title: "Gateway",value: toneBadge(data.gatewayReady ? "Online" : "Offline", data.gatewayReady ? "ok" : "off"),detail: `Internal Port ${GATEWAY_PORT}`,tone: data.gatewayReady ? "ok" : "off",}),renderTile({title: "Model",value: `<code>${escapeHtml(LLM_MODEL)}</code>`,detail: `Primary LLM Configured`,tone: "neutral",}),renderTile({title: "Runtime",value: escapeHtml(data.uptimeHuman),detail: `Public Port ${PORT}`,tone: "neutral",}),renderTile({title: "WhatsApp",value: toneBadge(data.whatsapp.connected ? "Connected" : (data.whatsapp.configured ? "Ready" : "Disabled"), data.whatsapp.connected ? "ok" : (data.whatsapp.configured ? "warn" : "neutral")),detail: data.whatsapp.connected ? "Active Session" : (data.whatsapp.pairing ? "Pairing Requested" : "Channel configured"),tone: data.whatsapp.connected ? "ok" : (data.whatsapp.configured ? "warn" : "neutral"),}),renderTile({title: "Telegram",value: toneBadge(TELEGRAM_ENABLED ? "Enabled" : "Disabled", TELEGRAM_ENABLED ? "ok" : "neutral"),detail: TELEGRAM_ENABLED ? "Bot Channel active" : "Not configured",tone: TELEGRAM_ENABLED ? "ok" : "neutral",}),renderTile({title: "Backup",value: toneBadge(syncStatus.toUpperCase(), syncTone),detail: backupDetail,tone: syncTone,}),renderTile({title: "Keep Awake",value: toneBadge(keepaliveConfigured ? "CF Cron" : keepaliveStatus.toUpperCase(), keepAliveTone),detail: keepAliveDetail,tone: keepAliveTone,}),].join("");return `<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>HuggingClaw</title><style>:root { color-scheme: dark; --bg:#08080f; --panel:#12111b; --panel2:#151421; --line:#26243a; --text:#f6f4ff; --muted:#7f7a9e; --soft:#b8b3d7; --good:#22c55e; --warn:#f5c542; --bad:#fb7185; --accent:#3b82f6; --accent2:#8b5cf6; }* { box-sizing:border-box; }body { margin:0; min-height:100vh; font-family:Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background:var(--bg); color:var(--text); font-size:13px; }main { width:min(720px, calc(100% - 32px)); margin:0 auto; padding:36px 0 44px; }header { text-align:center; margin-bottom:22px; }h1 { margin:0; font-size:1.65rem; line-height:1; letter-spacing:0; }.subtitle { margin-top:12px; color:var(--muted); font-size:.72rem; text-transform:uppercase; letter-spacing:.14em; font-weight:800; }.hero-action { display:flex; width:100%; min-height:46px; align-items:center; justify-content:center; border-radius:8px; background:linear-gradient(135deg, var(--accent), var(--accent2)); color:#ffffff; text-decoration:none; font-weight:850; font-size:.98rem; margin:24px 0 20px; transition: opacity 0.15s ease; }.hero-action:hover { opacity: 0.9; }.overview { display:grid; grid-template-columns:repeat(2, minmax(0, 1fr)); gap:10px; margin-bottom:10px; }.tile { border:1px solid var(--line); background:var(--panel); border-radius:11px; padding:18px; min-height:124px; display:flex; flex-direction:column; gap:10px; position:relative; }.tile.ok { border-color:rgba(34,197,94,.22); }.tile.warn { border-color:rgba(245,197,66,.24); }.tile.off { border-color:rgba(251,113,133,.28); }.tile-head { display:flex; align-items:center; justify-content:space-between; gap:12px; }.tile-title { color:var(--muted); font-size:.67rem; letter-spacing:.18em; text-transform:uppercase; font-weight:850; }.tile-dot { width:7px; height:7px; border-radius:50%; background:var(--line); }.tile.ok .tile-dot { background:var(--good); }.tile.warn .tile-dot { background:var(--warn); }.tile.off .tile-dot { background:var(--bad); }.tile-value { font-size:1.12rem; font-weight:850; overflow-wrap:anywhere; }.tile-detail { color:var(--soft); line-height:1.45; font-size:.83rem; }.tile-meta { color:var(--muted); line-height:1.4; font-size:.75rem; margin-top:auto; overflow-wrap:anywhere; }code { background:#232234; border:1px solid #34324c; border-radius:6px; padding:2px 6px; color:var(--text); font-size:.9em; }.badge { display:inline-flex; align-items:center; width:max-content; border:1px solid var(--line); border-radius:999px; padding:5px 10px; font-size:.72rem; font-weight:850; line-height:1; text-transform:uppercase; }.badge.ok { color:var(--good); border-color:rgba(34,197,94,.34); background:rgba(34,197,94,.11); }.badge.warn { color:var(--warn); border-color:rgba(245,197,66,.34); background:rgba(245,197,66,.11); }.badge.off { color:var(--bad); border-color:rgba(251,113,133,.34); background:rgba(251,113,133,.11); }.badge.neutral { color:var(--soft); }footer { color:var(--muted); text-align:center; font-size:.74rem; margin-top:18px; }footer .live { color:var(--good); }@media (max-width: 700px) { .overview { grid-template-columns:1fr; } main { width:min(100% - 22px, 720px); padding-top:28px; } }</style></head><body><main><header><h1>π¦ HuggingClaw</h1><div class="subtitle">OpenClaw Gateway Dashboard</div></header><a class="hero-action" href="${APP_BASE}/" target="_blank" rel="noopener noreferrer">Open Control UI -></a><section class="overview">${tiles}</section><footer><span class="live">Live</span> status - Health endpoint: <code>/health</code></footer></main></body></html>`;}const server = http.createServer(async (req, res) => {const url = parseRequestUrl(req.url);const pathname = url.pathname;// 1. Dashboard Routesif (pathname === "/health") {const gatewayReady = await probeGatewayHealth();res.writeHead(gatewayReady ? 200 : 503, { "Content-Type": "application/json" });return res.end(JSON.stringify({status: gatewayReady ? "ok" : "degraded",gatewayReady,uptime: formatUptime(Date.now() - startTime),sync: getSyncStatus(),keepalive: getKeepaliveStatus(),}),);}if (pathname === "/status") {const gatewayReady = await probeGatewayHealth();res.writeHead(200, { "Content-Type": "application/json" });return res.end(JSON.stringify({model: LLM_MODEL,uptime: formatUptime(Date.now() - startTime),gatewayReady,sync: getSyncStatus(),whatsapp: readGuardianStatus(),keepalive: getKeepaliveStatus(),}),);}if (pathname === "/" || pathname === "/dashboard") {const gatewayReady = await probeGatewayHealth();res.writeHead(200, { "Content-Type": "text/html" });return res.end(renderDashboard({uptimeHuman: formatUptime(Date.now() - startTime),gatewayReady,sync: getSyncStatus(),whatsapp: readGuardianStatus(),keepalive: getKeepaliveStatus(),}),);}// 2. OpenClaw Proxy Logicconst proxyHeaders = {...req.headers,host: `${GATEWAY_HOST}:${GATEWAY_PORT}`,"x-forwarded-for": req.socket.remoteAddress,"x-forwarded-host": req.headers.host,"x-forwarded-proto": "https",};const proxyReq = http.request({hostname: GATEWAY_HOST,port: GATEWAY_PORT,path: pathname + url.search,method: req.method,headers: proxyHeaders,},(proxyRes) => {res.writeHead(proxyRes.statusCode, proxyRes.headers);proxyRes.pipe(res);proxyRes.on("error", (err) => {console.error("proxyRes error:", err);res.end();});},);req.on("error", (err) => {console.error("req error:", err);proxyReq.destroy();});res.on("error", (err) => {console.error("res error:", err);proxyReq.destroy();});proxyReq.on("error", (err) => {console.error("proxyReq error:", err);if (!res.headersSent) {res.writeHead(503, { "Content-Type": "application/json" });res.end(JSON.stringify({status: "starting",message: "Gateway is initializing... or connection failed",}),);} else {res.end();}});req.pipe(proxyReq);});server.on("upgrade", (req, socket, head) => {const url = parseRequestUrl(req.url);const proxyPath = url.pathname;const proxySocket = net.connect(GATEWAY_PORT, GATEWAY_HOST, () => {proxySocket.write(`${req.method} ${proxyPath}${url.search} HTTP/${req.httpVersion}\r\n`,);for (let i = 0; i < req.rawHeaders.length; i += 2) {proxySocket.write(`${req.rawHeaders[i]}: ${req.rawHeaders[i + 1]}\r\n`);}proxySocket.write("\r\n");if (head && head.length) proxySocket.write(head);proxySocket.pipe(socket).pipe(proxySocket);});proxySocket.on("error", () => socket.destroy());});server.timeout = 0;server.keepAliveTimeout = 65000;server.listen(PORT, "0.0.0.0", () =>console.log(`π¦ HuggingClaw Dashboard on ${PORT} -> Gateway on ${GATEWAY_PORT}`),);
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091#!/bin/bashset -euo pipefail
# Create or update a UptimeRobot monitor for this Hugging Face Space.## Requirements:# - UPTIMEROBOT_API_KEY: Main API key from UptimeRobot# - SPACE_HOST or first CLI arg: your HF Space host, e.g. "user-space.hf.space"## Optional:# - UPTIMEROBOT_MONITOR_NAME: friendly name for the monitor# - UPTIMEROBOT_ALERT_CONTACTS: dash-separated alert contact IDs, e.g. "123456-789012"# - UPTIMEROBOT_INTERVAL: monitoring interval in seconds (default: 300 = 5 min; min: 30)
API_URL="https://api.uptimerobot.com/v2"API_KEY="${UPTIMEROBOT_API_KEY:-}"SPACE_HOST_INPUT="${1:-${SPACE_HOST:-}}"STATUS_FILE="/tmp/huggingclaw-uptimerobot-status.json"
if [ -z "$API_KEY" ]; then echo "Missing UPTIMEROBOT_API_KEY." echo "Use the Main API key from UptimeRobot -> Integrations." echo "Do not use the Read-only API key or a Monitor-specific API key." exit 1fi
if [ -z "$SPACE_HOST_INPUT" ]; then echo "Missing Space host." echo "Usage: UPTIMEROBOT_API_KEY=... ./setup-uptimerobot.sh your-space.hf.space" exit 1fi
SPACE_HOST_CLEAN="${SPACE_HOST_INPUT#https://}"SPACE_HOST_CLEAN="${SPACE_HOST_CLEAN#http://}"SPACE_HOST_CLEAN="${SPACE_HOST_CLEAN%%/*}"
MONITOR_URL="https://${SPACE_HOST_CLEAN}/health"MONITOR_NAME="${UPTIMEROBOT_MONITOR_NAME:-HuggingClaw ${SPACE_HOST_CLEAN}}"INTERVAL="${UPTIMEROBOT_INTERVAL:-300}"
echo "Checking existing UptimeRobot monitors for ${MONITOR_URL}..."MONITORS_RESPONSE=$(curl -sS -X POST "${API_URL}/getMonitors" \ -d "api_key=${API_KEY}" \ -d "format=json" \ -d "logs=0" \ -d "response_times=0" \ -d "response_times_limit=1")
MONITOR_ID=$(printf '%s' "$MONITORS_RESPONSE" | jq -r --arg url "$MONITOR_URL" ' (.monitors // []) | map(select(.url == $url)) | first | .id // empty')
if [ -n "$MONITOR_ID" ]; then printf '{"configured":true,"monitorId":"%s","url":"%s","alreadyExisted":true,"timestamp":"%s"}\n' \ "$MONITOR_ID" "$MONITOR_URL" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$STATUS_FILE" echo "Monitor already exists (id=${MONITOR_ID}) for ${MONITOR_URL}" exit 0fi
echo "Creating new UptimeRobot monitor for ${MONITOR_URL}..."
CURL_ARGS=( -sS -X POST "${API_URL}/newMonitor" -d "api_key=${API_KEY}" -d "format=json" -d "type=1" -d "friendly_name=${MONITOR_NAME}" -d "url=${MONITOR_URL}" -d "interval=${INTERVAL}")
if [ -n "${UPTIMEROBOT_ALERT_CONTACTS:-}" ]; then CURL_ARGS+=(-d "alert_contacts=${UPTIMEROBOT_ALERT_CONTACTS}")fi
CREATE_RESPONSE=$(curl "${CURL_ARGS[@]}")CREATE_STATUS=$(printf '%s' "$CREATE_RESPONSE" | jq -r '.stat // "fail"')
if [ "$CREATE_STATUS" != "ok" ]; then printf '{"configured":false,"error":"creation failed","timestamp":"%s"}\n' \ "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$STATUS_FILE" echo "Failed to create monitor." printf '%s\n' "$CREATE_RESPONSE" exit 1fi
NEW_ID=$(printf '%s' "$CREATE_RESPONSE" | jq -r '.monitor.id // empty')printf '{"configured":true,"monitorId":"%s","url":"%s","timestamp":"%s"}\n' \ "${NEW_ID:-}" "$MONITOR_URL" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$STATUS_FILE"echo "Created UptimeRobot monitor ${NEW_ID:-"(id unavailable)"} for ${MONITOR_URL}"496 unmodified lines497498499500501502503504505496 unmodified linesnode /home/node/app/health-server.js &HEALTH_PID=$!if [ -n "${UPTIMEROBOT_API_KEY:-}" ] && [ -n "${SPACE_HOST:-}" ]; thenecho "Setting up UptimeRobot monitor..."bash /home/node/app/setup-uptimerobot.sh "${SPACE_HOST}" || truefi# ββ Launch gateway ββ496 unmodified lines497498499500501502503504505496 unmodified linesnode /home/node/app/health-server.js &HEALTH_PID=$!if [ -n "${CLOUDFLARE_WORKERS_TOKEN:-}" ]; thenecho "Setting up Cloudflare KeepAlive monitor..."python3 /home/node/app/cloudflare-keepalive-setup.py || truefi# ββ Launch gateway ββ
.env.example+3-3
Dockerfile+2-2
README.md+7-8
cloudflare-keepalive-setup.pyAdded+212
health-server.js+277-792
setup-uptimerobot.shDeleted-91
start.sh+3-3