Spaces:
Paused
Paused
Add Cloudflare keepalive worker and restyle dashboard
Browse filesFiles changed (4)
- README.md+31-26
- cloudflare-proxy-setup.py+175-35
- health-server.js+66-80
- start.sh+1-1
20 unmodified lines21222324252627282930313233348 unmodified lines434445464748495073 unmodified lines1241251261271281291301311321331341351361374 unmodified lines1421431441451461476 unmodified lines15415515615715815916016116216316416516616716816917017117217317417511 unmodified lines18718818919019119219320 unmodified lines- name: HF_TOKENdescription: "Hugging Face token with write access for private Dataset backup."- name: CLOUDFLARE_WORKERS_TOKENdescription: "Cloudflare API token for automatic Worker proxy setup."- name: UPTIMEROBOT_API_KEYdescription: "UptimeRobot Main API key for automatic keep-awake monitor setup."---# HuggingMessHuggingMess runs [Nous Research Hermes Agent](https://github.com/NousResearch/hermes-agent) as a Hugging Face Docker Space. It follows the same practical shape as HuggingClaw: one public Space port, Telegram gateway support, Cloudflare Worker proxy setup, UptimeRobot keep-awake, and private HF Dataset backup for Hermes state.## Quick Start8 unmodified lines| `TELEGRAM_ALLOWED_USERS` | Recommended | Comma-separated numeric Telegram user IDs || `GATEWAY_TOKEN` | Recommended | Bearer token for `/v1/*` API routes || `HF_TOKEN` | Optional | Enables private Dataset backup named `huggingmess-backup` || `CLOUDFLARE_WORKERS_TOKEN` | Optional | Auto-creates a Worker proxy for Telegram Bot API traffic || `UPTIMEROBOT_API_KEY` | Optional | Auto-creates a monitor for `/health` |## Access Control73 unmodified linesHermes requires numeric Telegram IDs for allowlists. You can use either Hermes-native `TELEGRAM_ALLOWED_USERS` or the HuggingClaw-style aliases `TELEGRAM_USER_ID` / `TELEGRAM_USER_IDS`.## Cloudflare ProxyHugging Face Spaces can be restrictive for outbound bot API traffic. Add `CLOUDFLARE_WORKERS_TOKEN`, and HuggingMess will:1. create a Cloudflare Worker,2. generate a shared proxy secret,3. set Hermes Telegram `base_url` to `https://worker.example.workers.dev/bot`,4. set `base_file_url` to `https://worker.example.workers.dev/file/bot`.Manual mode is also supported:4 unmodified linesThe manual Worker source is included in `cloudflare-worker.js`.## BackupSet `HF_TOKEN` with write access to enable backup. HuggingMess syncs `/opt/data` to a private Dataset named `huggingmess-backup` every 180 seconds by default.6 unmodified linesBy default `.env` is excluded from backups because HF Space secrets are already injected at runtime.## Keep AwakeAdd `UPTIMEROBOT_API_KEY`, and HuggingMess creates or reuses a monitor for:```texthttps://your-space.hf.space/health```Optional UptimeRobot variables:| Variable | Default | Description || :--- | :--- | :--- || `UPTIMEROBOT_MONITOR_NAME` | `HuggingMess <space>` | Friendly monitor name || `UPTIMEROBOT_INTERVAL` | `300` | Monitor interval in seconds || `UPTIMEROBOT_ALERT_CONTACTS` | unset | Dash-separated alert contact IDs |## Local Development```bash11 unmodified lines| Route | Purpose || :--- | :--- || `/` | HuggingMess dashboard || `/health` | Health check for HF and UptimeRobot || `/status` | JSON status || `/app/` | Proxied Hermes dashboard/app || `/v1/*` | Proxied Hermes OpenAI-compatible API routes |20 unmodified lines2122232425262728293031328 unmodified lines4142434445464773 unmodified lines1211221231241251261271281291301311321331341354 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611621631641651661671686 unmodified lines17517617717817918011 unmodified lines19219319419519619719820 unmodified lines- name: HF_TOKENdescription: "Hugging Face token with write access for private Dataset backup."- name: CLOUDFLARE_WORKERS_TOKENdescription: "Cloudflare API token for automatic Telegram proxy and keep-awake Worker setup."---# HuggingMessHuggingMess runs [Nous Research Hermes Agent](https://github.com/NousResearch/hermes-agent) as a Hugging Face Docker Space. It follows the same practical shape as HuggingClaw: one public Space port, Telegram gateway support, Cloudflare Worker proxy setup, Cloudflare cron keep-awake, and private HF Dataset backup for Hermes state.## Quick Start8 unmodified lines| `TELEGRAM_ALLOWED_USERS` | Recommended | Comma-separated numeric Telegram user IDs || `GATEWAY_TOKEN` | Recommended | Bearer token for `/v1/*` API routes || `HF_TOKEN` | Optional | Enables private Dataset backup named `huggingmess-backup` || `CLOUDFLARE_WORKERS_TOKEN` | Optional | Auto-creates Workers for Telegram proxy and `/health` keep-awake |## Access Control73 unmodified linesHermes requires numeric Telegram IDs for allowlists. You can use either Hermes-native `TELEGRAM_ALLOWED_USERS` or the HuggingClaw-style aliases `TELEGRAM_USER_ID` / `TELEGRAM_USER_IDS`.## Cloudflare WorkersHugging Face Spaces can be restrictive for outbound bot API traffic. Add `CLOUDFLARE_WORKERS_TOKEN`, and HuggingMess will:1. create a Telegram proxy Worker,2. generate a shared proxy secret,3. set Hermes Telegram `base_url` to `https://worker.example.workers.dev/bot`,4. set `base_file_url` to `https://worker.example.workers.dev/file/bot`,5. create a second scheduled keep-awake Worker that pings your Space `/health` route.Manual mode is also supported:4 unmodified linesThe manual Worker source is included in `cloudflare-worker.js`.### Keep AwakeWhen `CLOUDFLARE_WORKERS_TOKEN` and `SPACE_HOST` are present, HuggingMess creates a scheduled Worker that pings:```texthttps://your-space.hf.space/health```Default schedule:```text*/10 * * * *```Optional variables:| Variable | Default | Description || :--- | :--- | :--- || `CLOUDFLARE_KEEPALIVE_ENABLED` | `true` | Set `false` to skip keep-awake Worker setup || `CLOUDFLARE_KEEPALIVE_CRON` | `*/10 * * * *` | Cloudflare cron expression || `CLOUDFLARE_KEEPALIVE_URL` | `https://<SPACE_HOST>/health` | URL to ping || `CLOUDFLARE_KEEPALIVE_WORKER_NAME` | derived from `SPACE_HOST` | Custom Worker name |## BackupSet `HF_TOKEN` with write access to enable backup. HuggingMess syncs `/opt/data` to a private Dataset named `huggingmess-backup` every 180 seconds by default.6 unmodified linesBy default `.env` is excluded from backups because HF Space secrets are already injected at runtime.## Local Development```bash11 unmodified lines| Route | Purpose || :--- | :--- || `/` | HuggingMess dashboard || `/health` | Health check for HF and Cloudflare keep-awake || `/status` | JSON status || `/app/` | Proxied Hermes dashboard/app || `/v1/*` | Proxied Hermes OpenAI-compatible API routes |
1234567891011121314151644 unmodified lines61626364656660 unmodified lines1271281291301311322 unmodified lines1351361371381391401 unmodified line142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189#!/usr/bin/env python3"""Create or reuse a Cloudflare Worker that proxies Telegram Bot API calls."""import jsonimport osimport reimport secretsimport sysimport urllib.requestfrom pathlib import PathAPI_BASE = "https://api.cloudflare.com/client/v4"ENV_FILE = Path("/tmp/huggingmess-cloudflare-proxy.env")DEFAULT_ALLOWED = ["api.telegram.org","discord.com",44 unmodified linesreturn "huggingmess-proxy"def render_worker(secret_value: str, allowed_targets: list[str], allow_proxy_all: bool) -> str:return f"""addEventListener("fetch", (event) => {{event.respondWith(handleRequest(event.request));60 unmodified lines"""def write_env(proxy_url: str, proxy_secret: str) -> None:ENV_FILE.write_text(f'export CLOUDFLARE_PROXY_URL="{proxy_url}"\nexport CLOUDFLARE_PROXY_SECRET="{proxy_secret}"\n',2 unmodified linesENV_FILE.chmod(0o600)def main() -> int:existing_url = os.environ.get("CLOUDFLARE_PROXY_URL", "").strip()existing_secret = os.environ.get("CLOUDFLARE_PROXY_SECRET", "").strip()1 unmodified lineif existing_url:write_env(existing_url, existing_secret)return 0if not api_token:return 0try: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.")allowed_raw = os.environ.get("CLOUDFLARE_PROXY_DOMAINS", "").strip()allow_proxy_all = allowed_raw == "*"extra = [] if allow_proxy_all else [v.strip() for v in allowed_raw.split(",") if v.strip()]allowed = list(dict.fromkeys(DEFAULT_ALLOWED + extra))worker_name = derive_worker_name()proxy_secret = existing_secret or secrets.token_urlsafe(24)cf_request("PUT",f"/accounts/{account_id}/workers/scripts/{worker_name}",api_token,body=render_worker(proxy_secret, allowed, allow_proxy_all).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"),)write_env(f"https://{worker_name}.{subdomain}.workers.dev", proxy_secret)return 0except Exception as exc:print(f"Cloudflare proxy setup failed: {exc}", file=sys.stderr)return 1123456789101112131415161718192044 unmodified lines6566676869707172737475767778798060 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012 unmodified lines2042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862871 unmodified line289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329#!/usr/bin/env python3from __future__ import annotations"""Create or reuse Cloudflare Workers for Telegram proxy and Space keep-awake."""import jsonimport osimport reimport secretsimport sysimport timeimport urllib.requestfrom pathlib import PathAPI_BASE = "https://api.cloudflare.com/client/v4"ENV_FILE = Path("/tmp/huggingmess-cloudflare-proxy.env")KEEPALIVE_STATUS_FILE = Path("/tmp/huggingmess-cloudflare-keepalive-status.json")DEFAULT_ALLOWED = ["api.telegram.org","discord.com",44 unmodified linesreturn "huggingmess-proxy"def derive_keepalive_worker_name() -> str:explicit = os.environ.get("CLOUDFLARE_KEEPALIVE_WORKER_NAME", "").strip()if explicit:return slugify(explicit)space_host = os.environ.get("SPACE_HOST", "").strip()if space_host:return slugify(f"{space_host.replace('.hf.space', '')}-keepalive")return "huggingmess-keepalive"def render_worker(secret_value: str, allowed_targets: list[str], allow_proxy_all: bool) -> str:return f"""addEventListener("fetch", (event) => {{event.respondWith(handleRequest(event.request));60 unmodified lines"""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": "HuggingMess 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_env(proxy_url: str, proxy_secret: str) -> None:ENV_FILE.write_text(f'export CLOUDFLARE_PROXY_URL="{proxy_url}"\nexport CLOUDFLARE_PROXY_SECRET="{proxy_secret}"\n',2 unmodified linesENV_FILE.chmod(0o600)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:passdef 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, subdomaindef 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."})returnspace_host = os.environ.get("SPACE_HOST", "").strip()if not space_host:write_keepalive_status({"configured": False, "status": "skipped", "message": "SPACE_HOST is not set."})returncron = 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:existing_url = os.environ.get("CLOUDFLARE_PROXY_URL", "").strip()existing_secret = os.environ.get("CLOUDFLARE_PROXY_SECRET", "").strip()1 unmodified lineif existing_url:write_env(existing_url, existing_secret)if not api_token:return 0try:account_id, subdomain = resolve_account_and_subdomain(api_token)if not existing_url:allowed_raw = os.environ.get("CLOUDFLARE_PROXY_DOMAINS", "").strip()allow_proxy_all = allowed_raw == "*"extra = [] if allow_proxy_all else [v.strip() for v in allowed_raw.split(",") if v.strip()]allowed = list(dict.fromkeys(DEFAULT_ALLOWED + extra))worker_name = derive_worker_name()proxy_secret = existing_secret or secrets.token_urlsafe(24)cf_request("PUT",f"/accounts/{account_id}/workers/scripts/{worker_name}",api_token,body=render_worker(proxy_secret, allowed, allow_proxy_all).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"),)write_env(f"https://{worker_name}.{subdomain}.workers.dev", proxy_secret)setup_keepalive_worker(api_token, account_id, subdomain)return 0except Exception as exc:print(f"Cloudflare proxy setup failed: {exc}", file=sys.stderr)write_keepalive_status({"configured": False, "status": "error", "message": str(exc)})return 1
16 unmodified lines17181920212223290 unmodified lines31431531631731831932025 unmodified lines34634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540611 unmodified lines4184194204214224234244254264274 unmodified lines4324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924 unmodified lines49749849950050150216 unmodified linesconst SESSION_COOKIE = "huggingmess_session";const SYNC_STATUS_FILE = "/tmp/huggingmess-sync-status.json";const UPTIMEROBOT_STATUS_FILE = "/tmp/huggingmess-uptimerobot-status.json";function canConnect(port, host = GATEWAY_HOST, timeoutMs = 600) {return new Promise((resolve) => {290 unmodified linesmodel: process.env.MODEL_FOR_CONFIG || process.env.HERMES_MODEL || process.env.LLM_MODEL || "",provider: process.env.PROVIDER_FOR_CONFIG || process.env.HERMES_INFERENCE_PROVIDER || "auto",backup: sync,uptimerobot: readJson(UPTIMEROBOT_STATUS_FILE, null),};}25 unmodified linesconst syncStatus = String(data.backup?.status || "unknown");const syncTone = ["success", "restored", "synced", "configured"].includes(syncStatus) ? "ok" : syncStatus === "disabled" ? "warn" : "neutral";const telegramTone = data.telegram.configured ? (data.telegram.webhookListening || !data.telegram.webhook ? "ok" : "warn") : "warn";const keepAliveTone = data.uptimerobot?.configured ? "ok" : process.env.UPTIMEROBOT_API_KEY ? "warn" : "neutral";const gatewayDetail = data.gateway? `OpenAI-compatible API is listening on internal port <code>${data.ports.gateway}</code>.`: `Gateway API is not reachable on internal port <code>${data.ports.gateway}</code>.`;const appDetail = data.dashboard? `Hermes dashboard is listening on internal port <code>${data.ports.dashboard}</code>.`: `Hermes dashboard is not reachable on internal port <code>${data.ports.dashboard}</code>.`;const authDetail = data.authConfigured? `Protected by <code>GATEWAY_TOKEN</code> with a token-only login page.`: `No <code>GATEWAY_TOKEN</code> is set; public app routes are unlocked.`;const telegramDetail = data.telegram.configured? `${data.telegram.webhook ? "Webhook mode" : "Polling mode"}${data.telegram.proxy ? ` through Cloudflare proxy` : ""}.`: "Add TELEGRAM_BOT_TOKEN to enable Telegram.";const backupDetail = data.backup?.message ? escapeHtml(data.backup.message) : "No backup status has been written yet.";const backupMeta = data.backup?.timestamp ? `Last update ${escapeHtml(data.backup.timestamp)}` : "";const keepAliveDetail = data.uptimerobot?.configured? `Monitoring <code>${escapeHtml(data.uptimerobot.url || "/health")}</code>.`: process.env.UPTIMEROBOT_API_KEY? "UptimeRobot setup is pending or failed; check Space logs.": "Add UPTIMEROBOT_API_KEY to create a keep-awake monitor.";const tiles = [renderTile({title: "Gateway",value: toneBadge(data.gateway ? "Online" : "Offline", data.gateway ? "ok" : "off"),detail: gatewayDetail,tone: data.gateway ? "ok" : "off",meta: `API routes are protected by <code>GATEWAY_TOKEN</code>.`,}),renderTile({title: "Hermes App",value: toneBadge(data.dashboard ? "Ready" : "Starting", data.dashboard ? "ok" : "warn"),detail: appDetail,tone: data.dashboard ? "ok" : "warn",meta: `<code>/app/</code> opens in a new window.`,}),renderTile({title: "Auth",value: toneBadge(data.authConfigured ? "Token set" : "Unlocked", data.authConfigured ? "ok" : "warn"),detail: authDetail,tone: data.authConfigured ? "ok" : "warn",meta: data.authConfigured ? "Browser visits use the login page; API clients use Bearer auth." : "Set GATEWAY_TOKEN before sharing this Space.",}),renderTile({title: "Runtime",value: escapeHtml(data.uptime),detail: `Public port <code>${data.ports.public}</code>. Started <code>${escapeHtml(data.startedAt)}</code>.`,tone: "neutral",meta: `Health endpoint: <code>/health</code>`,}),renderTile({title: "Model",value: `<code>${valueOrUnset(data.model)}</code>`,detail: `Provider <code>${valueOrUnset(data.provider || "auto")}</code>.`,tone: data.model ? "ok" : "warn",meta: "For Gemini: LLM_MODEL=google/gemini-2.5-flash",}),renderTile({title: "Telegram",11 unmodified lines}),renderTile({title: "Keep Awake",value: toneBadge(data.uptimerobot?.configured ? "Monitor active" : "Not configured", keepAliveTone),detail: keepAliveDetail,tone: keepAliveTone,meta: process.env.UPTIMEROBOT_API_KEY ? "UPTIMEROBOT_API_KEY detected." : "",}),].join("");4 unmodified lines<meta name="viewport" content="width=device-width, initial-scale=1" /><title>HuggingMess</title><style>:root { color-scheme: dark; --bg:#101010; --panel:#171717; --panel2:#1e1e1e; --line:#303030; --text:#f3f4f6; --muted:#a1a1aa; --soft:#d4d4d8; --good:#4ade80; --warn:#fbbf24; --bad:#fb7185; --accent:#67e8f9; }* { 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:14px; }main { width:min(1180px, calc(100% - 32px)); margin:0 auto; padding:24px 0 32px; }header { display:flex; justify-content:space-between; gap:24px; align-items:flex-start; margin-bottom:18px; border-bottom:1px solid var(--line); padding-bottom:18px; }h1 { margin:0; font-size:clamp(2rem, 4vw, 3.2rem); line-height:1; letter-spacing:0; }.subtitle { margin-top:10px; color:var(--muted); max-width:700px; line-height:1.45; font-size:.95rem; }.top-actions { display:flex; flex-wrap:wrap; gap:8px; justify-content:flex-end; min-width:300px; }.overview { display:grid; grid-template-columns:repeat(4, minmax(0, 1fr)); gap:10px; margin-bottom:10px; }.tile { border:1px solid var(--line); background:var(--panel); border-radius:8px; padding:14px; min-height:142px; display:flex; flex-direction:column; gap:10px; }.tile.ok { border-color:rgba(74,222,128,.28); }.tile.warn { border-color:rgba(251,191,36,.28); }.tile.off { border-color:rgba(251,113,133,.32); }.tile-head { display:flex; align-items:center; justify-content:space-between; gap:12px; }.tile-title { color:var(--muted); font-size:.72rem; letter-spacing:.12em; text-transform:uppercase; font-weight:800; }.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.05rem; font-weight:760; overflow-wrap:anywhere; }.tile-detail { color:var(--soft); line-height:1.45; font-size:.86rem; }.tile-meta { color:var(--muted); line-height:1.4; font-size:.78rem; margin-top:auto; overflow-wrap:anywhere; }.panel { border:1px solid var(--line); background:var(--panel2); border-radius:8px; padding:14px; margin-top:10px; }.launch-panel { display:flex; align-items:center; justify-content:space-between; gap:18px; }.panel-title { color:var(--muted); font-size:.72rem; letter-spacing:.12em; text-transform:uppercase; font-weight:800; margin-bottom:7px; }.panel-copy { color:var(--soft); line-height:1.45; font-size:.9rem; margin:0; }code { background:#0d0d0d; border:1px solid var(--line); border-radius:6px; padding:2px 5px; color:var(--text); font-size:.9em; }pre { margin:0; white-space:pre-wrap; overflow-wrap:anywhere; background:#0d0d0d; border:1px solid var(--line); border-radius:7px; padding:10px; color:var(--soft); font-size:.82rem; line-height:1.45; }.row { display:flex; flex-wrap:wrap; gap:8px; align-items:center; }.badge { display:inline-flex; align-items:center; border:1px solid var(--line); border-radius:999px; padding:4px 9px; font-size:.75rem; font-weight:800; line-height:1; }.badge.ok { color:var(--good); border-color:rgba(74,222,128,.36); background:rgba(74,222,128,.08); }.badge.warn { color:var(--warn); border-color:rgba(251,191,36,.34); background:rgba(251,191,36,.08); }.badge.off { color:var(--bad); border-color:rgba(251,113,133,.36); background:rgba(251,113,133,.08); }.badge.neutral { color:var(--soft); }.muted { color:var(--muted); }.button { display:inline-flex; align-items:center; justify-content:center; min-height:34px; padding:0 11px; border-radius:7px; color:#081012; background:var(--accent); text-decoration:none; font-weight:800; font-size:.86rem; }.button.secondary { color:var(--text); background:#242424; border:1px solid var(--line); }.button.subtle { color:var(--soft); background:transparent; border:1px solid var(--line); }@media (max-width: 980px) { .overview { grid-template-columns:repeat(2, minmax(0, 1fr)); } header { display:block; } .top-actions { justify-content:flex-start; margin-top:14px; min-width:0; } }@media (max-width: 760px) { .launch-panel { display:block; } .launch-panel .button { margin-top:12px; width:100%; } }@media (max-width: 620px) { main { width:min(100% - 20px, 1180px); padding-top:16px; } .overview { grid-template-columns:1fr; } h1 { font-size:2rem; } }</style></head><body><main><header><div><h1>HuggingMess</h1><div class="subtitle">Hermes Agent on Hugging Face Spaces: app gateway, OpenAI-compatible API, Telegram webhook, Cloudflare proxy, backup, and keep-awake state in one place.</div></div><div class="top-actions"><a class="button" href="${APP_BASE}/" target="_blank" rel="noopener noreferrer">Open App</a><a class="button secondary" href="/status">Status JSON</a></div></header><section class="overview">${tiles}</section>4 unmodified lines</div><a class="button" href="${APP_BASE}/" target="_blank" rel="noopener noreferrer">Open Hermes Agent</a></section></main></body></html>`;16 unmodified lines17181920212223290 unmodified lines31431531631731831932025 unmodified lines34634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039111 unmodified lines4034044054064074084094104114124 unmodified lines4174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774 unmodified lines48248348448548648748816 unmodified linesconst SESSION_COOKIE = "huggingmess_session";const SYNC_STATUS_FILE = "/tmp/huggingmess-sync-status.json";const CLOUDFLARE_KEEPALIVE_STATUS_FILE = "/tmp/huggingmess-cloudflare-keepalive-status.json";function canConnect(port, host = GATEWAY_HOST, timeoutMs = 600) {return new Promise((resolve) => {290 unmodified linesmodel: process.env.MODEL_FOR_CONFIG || process.env.HERMES_MODEL || process.env.LLM_MODEL || "",provider: process.env.PROVIDER_FOR_CONFIG || process.env.HERMES_INFERENCE_PROVIDER || "auto",backup: sync,keepalive: readJson(CLOUDFLARE_KEEPALIVE_STATUS_FILE, null),};}25 unmodified linesconst syncStatus = String(data.backup?.status || "unknown");const syncTone = ["success", "restored", "synced", "configured"].includes(syncStatus) ? "ok" : syncStatus === "disabled" ? "warn" : "neutral";const telegramTone = data.telegram.configured ? (data.telegram.webhookListening || !data.telegram.webhook ? "ok" : "warn") : "warn";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 telegramDetail = data.telegram.configured? `${data.telegram.webhook ? "Webhook mode" : "Polling mode"}${data.telegram.proxy ? ` through Cloudflare proxy` : ""}.`: "Add TELEGRAM_BOT_TOKEN to enable Telegram.";const backupDetail = data.backup?.message ? escapeHtml(data.backup.message) : "No backup status has been written yet.";const backupMeta = data.backup?.timestamp ? `Last update ${escapeHtml(data.backup.timestamp)}` : "";const keepAliveDetail = keepaliveConfigured? `Worker <code>${escapeHtml(data.keepalive.workerName || "keepalive")}</code> pings <code>${escapeHtml(data.keepalive.targetUrl || "/health")}</code>.`: process.env.CLOUDFLARE_WORKERS_TOKEN? "Cloudflare keep-awake Worker is pending or failed; check Space logs.": "Add CLOUDFLARE_WORKERS_TOKEN to create a scheduled keep-awake Worker.";const serviceOk = data.gateway && data.dashboard;const topCards = [`<div class="mini-card"><span class="mini-label">Service</span>${toneBadge(serviceOk ? "Running" : "Starting", serviceOk ? "ok" : "warn")}</div>`,`<div class="mini-card"><span class="mini-label">Uptime</span><strong>${escapeHtml(data.uptime)}</strong></div>`,`<div class="mini-card"><span class="mini-label">Backup</span>${toneBadge(syncStatus.toUpperCase(), syncTone)}</div>`,].join("");const tiles = [renderTile({title: "Gateway",value: toneBadge(data.gateway ? "Online" : "Offline", data.gateway ? "ok" : "off"),detail: data.gateway ? `OpenAI-compatible API on port <code>${data.ports.gateway}</code>.` : `Gateway API is not reachable on port <code>${data.ports.gateway}</code>.`,tone: data.gateway ? "ok" : "off",meta: data.authConfigured ? `Protected by <code>GATEWAY_TOKEN</code>.` : `Set <code>GATEWAY_TOKEN</code> before sharing.`,}),renderTile({title: "Model",value: `<code>${valueOrUnset(data.model)}</code>`,detail: `Provider <code>${valueOrUnset(data.provider || "auto")}</code>.`,tone: data.model ? "ok" : "warn",meta: "Gemini example: google/gemini-2.5-flash",}),renderTile({title: "Runtime",value: escapeHtml(data.uptime),detail: `Public port <code>${data.ports.public}</code>; health at <code>/health</code>.`,tone: "neutral",meta: `Started <code>${escapeHtml(data.startedAt)}</code>.`,}),renderTile({title: "Telegram",11 unmodified lines}),renderTile({title: "Keep Awake",value: toneBadge(keepaliveConfigured ? "Cloudflare cron" : keepaliveStatus.toUpperCase(), keepAliveTone),detail: keepAliveDetail,tone: keepAliveTone,meta: keepaliveConfigured ? `Schedule <code>${escapeHtml(data.keepalive.cron || "*/10 * * * *")}</code>.` : "",}),].join("");4 unmodified lines<meta name="viewport" content="width=device-width, initial-scale=1" /><title>HuggingMess</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:#6557df; --accent2:#7c6cf2; }* { 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:var(--accent); color:#fff; text-decoration:none; font-weight:850; font-size:.98rem; margin:24px 0 20px; }.hero-action:hover { background:var(--accent2); }.mini-grid { display:grid; grid-template-columns:repeat(3, minmax(0, 1fr)); gap:10px; margin-bottom:18px; }.mini-card { min-height:68px; border:1px solid var(--line); background:var(--panel); border-radius:8px; padding:13px; display:flex; flex-direction:column; justify-content:center; gap:9px; }.mini-label { color:var(--muted); font-size:.66rem; letter-spacing:.16em; text-transform:uppercase; font-weight:850; }.mini-card strong { font-size:1.02rem; }.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; }.panel { border:1px solid var(--line); background:var(--panel2); border-radius:11px; padding:16px; margin-top:18px; }.launch-panel { text-align:center; }.panel-title { color:var(--muted); font-size:.7rem; letter-spacing:.16em; text-transform:uppercase; font-weight:850; margin-bottom:8px; }.panel-copy { color:var(--soft); line-height:1.5; font-size:.86rem; margin:0 auto 14px; max-width:560px; }code { background:#232234; border:1px solid #34324c; border-radius:6px; padding:2px 6px; color:var(--text); font-size:.9em; }pre { margin:0; white-space:pre-wrap; overflow-wrap:anywhere; background:#0d0d0d; border:1px solid var(--line); border-radius:7px; padding:10px; color:var(--soft); font-size:.82rem; line-height:1.45; }.row { display:flex; flex-wrap:wrap; gap:8px; align-items:center; }.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); }.muted { color:var(--muted); }.button { display:inline-flex; align-items:center; justify-content:center; min-height:40px; padding:0 16px; border-radius:8px; color:#fff; background:var(--accent); text-decoration:none; font-weight:850; font-size:.9rem; }.button.secondary { color:var(--text); background:#242424; border:1px solid var(--line); }footer { color:var(--muted); text-align:center; font-size:.74rem; margin-top:18px; }footer .live { color:var(--good); }@media (max-width: 700px) { .mini-grid, .overview { grid-template-columns:1fr; } main { width:min(100% - 22px, 720px); padding-top:28px; } }</style></head><body><main><header><h1>HuggingMess</h1><div class="subtitle">Self-hosted - Hugging Face Spaces - Hermes Agent</div></header><a class="hero-action" href="${APP_BASE}/" target="_blank" rel="noopener noreferrer">Open Hermes Agent -></a><section class="mini-grid">${topCards}</section><section class="overview">${tiles}</section>4 unmodified lines</div><a class="button" href="${APP_BASE}/" target="_blank" rel="noopener noreferrer">Open Hermes Agent</a></section><footer><span class="live">Live</span> status - Health endpoint: <code>/health</code></footer></main></body></html>`;
277 unmodified lines278279280281282283284277 unmodified linesnode "$APP_DIR/health-server.js" &HEALTH_PID=$!if [ -n "${UPTIMEROBOT_API_KEY:-}" ] && [ -n "${SPACE_HOST:-}" ]; thenecho "Setting up UptimeRobot monitor..."bash "$APP_DIR/setup-uptimerobot.sh" "${SPACE_HOST}" || truefi277 unmodified lines278279280281282283284277 unmodified linesnode "$APP_DIR/health-server.js" &HEALTH_PID=$!if [ "${UPTIMEROBOT_ENABLED:-false}" = "true" ] && [ -n "${UPTIMEROBOT_API_KEY:-}" ] && [ -n "${SPACE_HOST:-}" ]; thenecho "Setting up UptimeRobot monitor..."bash "$APP_DIR/setup-uptimerobot.sh" "${SPACE_HOST}" || truefi
README.md+31-26
cloudflare-proxy-setup.py+175-35
health-server.js+66-80
start.sh+1-1