F4bC0d3 commited on
Commit ·
5f92103
0
Parent(s):
Initial release: HuggingMes + Hermes WebUI integration
Browse filesFiles changed (11)
- .dockerignoreAdded+14
- .env.exampleAdded+38
- .gitignoreAdded+11
- DockerfileAdded+111
- LICENSEAdded+36
- README.mdAdded+202
- cloudflare-keepalive-setup.pyAdded+225
- cloudflare-proxy-setup.pyAdded+203
- health-server.jsAdded+928
- hermes-sync.pyAdded+337
- start.shAdded+428
1234567891011121314.git.gitignore.dockerignore.env.env.*!.env.example.kiro.venvvenv__pycache__*.pyc*.pyo*.lognode_modules1234567891011121314151617181920212223242526272829303132333435363738# ── Required ──────────────────────────────────────────────────────────GATEWAY_TOKEN=change-me-to-a-strong-random-stringLLM_API_KEY=your-llm-provider-api-keyLLM_MODEL=openrouter/anthropic/claude-sonnet-4
# Examples for other providers:# LLM_MODEL=openai/gpt-4o# LLM_MODEL=anthropic/claude-sonnet-4-6# LLM_MODEL=google/gemini-2.5-flash# LLM_MODEL=deepseek/deepseek-chat# LLM_MODEL=huggingface/Qwen/Qwen3-235B-A22B-Thinking-2507
# ── HF Dataset persistence (recommended) ──────────────────────────────# Write-scope token: https://huggingface.co/settings/tokens# HF_TOKEN=hf_xxx# BACKUP_DATASET_NAME=huggingmes-backup# SYNC_INTERVAL=600
# ── Optional: Cloudflare proxy + keep-alive ───────────────────────────# CLOUDFLARE_WORKERS_TOKEN=cf_xxx# CLOUDFLARE_ACCOUNT_ID=# CLOUDFLARE_KEEPALIVE_CRON=*/10 * * * *
# ── Optional: Telegram bridge ─────────────────────────────────────────# TELEGRAM_BOT_TOKEN=123456:ABC# TELEGRAM_ALLOWED_USERS=11111111,22222222# TELEGRAM_MODE=webhook
# ── Optional: swap the landing page to the HuggingMes status page ─────# PRIMARY_UI=dashboard
# ── Optional: custom OpenAI-compatible endpoint ───────────────────────# CUSTOM_BASE_URL=http://localhost:11434/v1# CUSTOM_MODEL_CONTEXT_LENGTH=131072# CUSTOM_MODEL_MAX_TOKENS=8192
# ── Reproducibility: pin the Hermes Agent base image ──────────────────# HERMES_AGENT_VERSION=latest1234567891011.env.env.*!.env.example__pycache__/*.pyc*.pyo.venv/.cache/*.log*.pid*.tmp123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111# HuggingMes + Hermes WebUI — merged deployment for Hugging Face Spaces# Base: NousResearch Hermes Agent (ships Hermes CLI, gateway, dashboard, Python venv)
ARG HERMES_AGENT_VERSION=latestFROM nousresearch/hermes-agent:${HERMES_AGENT_VERSION}
ARG WEBUI_REF=master
USER root
# System deps (mirrors HuggingMes) + git/nodejs for WebUI checkout + routerRUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ curl \ jq \ git \ python3 \ nodejs \ npm \ chromium \ libnss3 \ libatk1.0-0 \ libatk-bridge2.0-0 \ libdrm2 \ libgbm1 \ libxcomposite1 \ libxdamage1 \ libxrandr2 \ libxkbcommon0 \ libx11-6 \ libxext6 \ libxfixes3 \ libasound2 \ fonts-dejavu-core \ fonts-liberation \ fonts-noto-color-emoji \ && rm -rf /var/lib/apt/lists/* \ && uv pip install --python /opt/hermes/.venv/bin/python --no-cache-dir \ huggingface_hub hf_transfer pyyaml
# Clone nesquena/hermes-webui (install deps into the agent venv so imports resolve)RUN git clone --depth 1 --branch ${WEBUI_REF} \ https://github.com/nesquena/hermes-webui.git /opt/hermes-webui \ && ( [ -f /opt/hermes-webui/requirements.txt ] \ && /opt/hermes/.venv/bin/pip install --no-cache-dir -r /opt/hermes-webui/requirements.txt \ || true ) \ && chown -R hermes:hermes /opt/hermes-webui
# HuggingMes-style integration scripts (vendored from somratpro/HuggingMes)COPY --chown=hermes:hermes start.sh /opt/huggingmes/start.shCOPY --chown=hermes:hermes health-server.js /opt/huggingmes/health-server.jsCOPY --chown=hermes:hermes hermes-sync.py /opt/huggingmes/hermes-sync.pyCOPY --chown=hermes:hermes cloudflare-proxy-setup.py /opt/huggingmes/cloudflare-proxy-setup.pyCOPY --chown=hermes:hermes cloudflare-keepalive-setup.py /opt/huggingmes/cloudflare-keepalive-setup.py
RUN chmod +x \ /opt/huggingmes/start.sh \ /opt/huggingmes/hermes-sync.py \ /opt/huggingmes/cloudflare-proxy-setup.py \ /opt/huggingmes/cloudflare-keepalive-setup.py
# Idempotent kanban migration patch (same workaround HuggingMes ships)RUN python3 - <<'PY'from pathlib import Pathimport sysp = Path("/opt/hermes/hermes_cli/kanban_db.py")if not p.exists(): sys.exit(0)src = p.read_text(encoding="utf-8")sentinel = "# huggingmes-webui: idempotent-alter"if sentinel in src: sys.exit(0)old = ( ' conn.execute(\n' ' "ALTER TABLE tasks ADD COLUMN consecutive_failures "\n' ' "INTEGER NOT NULL DEFAULT 0"\n' ' )')new = ( f' try: {sentinel}\n' ' conn.execute(\n' ' "ALTER TABLE tasks ADD COLUMN consecutive_failures "\n' ' "INTEGER NOT NULL DEFAULT 0"\n' ' )\n' ' except Exception:\n' ' pass')if old in src: p.write_text(src.replace(old, new), encoding="utf-8") print("kanban patch: applied")PY
# Keep hermes CLI on PATH for all shell types (login/interactive/non-interactive)RUN echo 'export PATH="/opt/hermes/.venv/bin:/opt/data/.local/bin:$PATH"' \ > /etc/profile.d/hermes-venv.sh
ENV HERMES_HOME=/opt/data \ HUGGINGMES_APP_DIR=/opt/huggingmes \ HERMES_WEBUI_REPO=/opt/hermes-webui \ HERMES_AGENT_VERSION=${HERMES_AGENT_VERSION} \ PYTHONUNBUFFERED=1 \ HF_HUB_ENABLE_HF_TRANSFER=1 \ PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
EXPOSE 7861
HEALTHCHECK --interval=30s --timeout=5s --start-period=120s \ CMD curl -fsS http://localhost:7861/health || exit 1
USER hermesCMD ["/opt/huggingmes/start.sh"]123456789101112131415161718192021222324252627282930313233343536MIT License
Copyright (c) 2026 F4bC0d3
This project is a deployment recipe that combines three upstream open sourceprojects: - Hermes Agent by Nous Research (MIT) — https://github.com/NousResearch/hermes-agent - Hermes WebUI by Nicolas Esquerre (MIT) — https://github.com/nesquena/hermes-webui - HuggingMes by somratpro (MIT) — https://github.com/somratpro/HuggingMes
The integration layer (Dockerfile, health-server.js routing additions forHermes WebUI, start.sh launch sequence for the WebUI subprocess, README) isreleased under the MIT License below. The vendored files(hermes-sync.py, cloudflare-proxy-setup.py, cloudflare-keepalive-setup.py,plus large parts of start.sh and health-server.js) remain under theiroriginal MIT licenses from the upstream HuggingMes project.
---
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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202---title: HuggingMes Hermes WebUIemoji: ??colorFrom: bluecolorTo: indigosdk: dockerapp_port: 7861pinned: truelicense: mit---# 🪽 HuggingMes + Hermes WebUI
> A merged Hugging Face Space that runs [Hermes Agent](https://github.com/NousResearch/hermes-agent) with [Hermes WebUI](https://github.com/nesquena/hermes-webui) as the primary chat interface. Your own self-hosted AI agent, on free HF Space hardware.
**This project is not original work.** It's a deployment recipe that combines three excellent existing projects into a single Space:
- **[Hermes Agent](https://github.com/NousResearch/hermes-agent)** by **[Nous Research](https://nousresearch.com)** — the actual AI agent (memory, tools, scheduling, multi-provider LLM support). All the intelligence comes from here.- **[Hermes WebUI](https://github.com/nesquena/hermes-webui)** by **[@nesquena](https://github.com/nesquena)** — the three-panel browser UI (sessions, chat, workspace files) with SSE streaming, slash commands, profiles, themes, voice input, file browser, and 100+ other features. Used as the primary chat surface.- **[HuggingMes](https://github.com/somratpro/HuggingMes)** by **[@somratpro](https://github.com/somratpro)** — the HF Space wrapper: Docker image, gateway auth, HF Dataset persistence, Cloudflare proxy/keep-alive, Telegram bridge.
This repo just glues them together so both UIs share one port, one auth token, and one persistence layer on a single HF Space. Full credit goes to the upstream maintainers.
---
## Try it in 30 seconds
I keep a live demo at [huggingface.co/spaces/f4b404/hermes](https://huggingface.co/spaces/f4b404/hermes). Click **Duplicate this Space** at the top right to fork it into your own account.
After duplicating, you only need to set 3 secrets to get running. See the next section.
## Setting up your own Space
### 1. Duplicate the Space
Go to [huggingface.co/spaces/f4b404/hermes](https://huggingface.co/spaces/f4b404/hermes) → click the **⋮** menu (top-right corner) → **Duplicate this Space**. Name it whatever you want, pick CPU basic free hardware, decide public/private. HF copies all files automatically.
If you'd rather start from this repo, create a new Space with **SDK = Docker** at [huggingface.co/new-space](https://huggingface.co/new-space) and upload everything in this repo to its `main` branch.
### 2. Add secrets (Settings → Variables and secrets)
**Required** (the Space will not start without these):
| Secret | What it is | Example || --- | --- | --- || `GATEWAY_TOKEN` | Your password — gates the WebUI login and the `/v1/*` API. Pick anything strong. | A 32-char random string (`openssl rand -base64 32`) || `LLM_API_KEY` | API key for whichever LLM provider you want to use | `sk-or-v1-...` for OpenRouter, `sk-...` for OpenAI, etc. || `LLM_MODEL` | HuggingMes-style model identifier | `openrouter/anthropic/claude-sonnet-4`, `openai/gpt-4o`, `google/gemini-2.5-flash`, `huggingface/Qwen/Qwen3-235B-A22B-Thinking-2507`, etc. |
**Recommended**:
| Secret | Why | How to get || --- | --- | --- || `HF_TOKEN` | Persists your sessions, profiles, skills, cron jobs, memory, and workspace files across Space restarts by syncing to a private HF Dataset every 10 min. **Without this, restarts wipe everything.** | [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) → New token → **Write** scope || `BACKUP_DATASET_NAME` | If you run multiple instances of this Space (or any other HuggingMes-derived project), set a unique name here so they don't overwrite each other's backups. | e.g. `my-hermes-backup` |
**Optional advanced features**:
| Secret | What it does || --- | --- || `CLOUDFLARE_WORKERS_TOKEN` | Auto-provisions two Cloudflare Workers: one as an outbound proxy (needed for Telegram, sometimes for blocked LLM providers) and one as a cron keep-alive worker that pings `/health` every 10 min so the Space doesn't sleep on free tier || `CLOUDFLARE_ACCOUNT_ID` | Explicit Cloudflare account ID if you have multiple || `TELEGRAM_BOT_TOKEN` | Enables the Telegram bridge so you can chat with Hermes from Telegram || `TELEGRAM_ALLOWED_USERS` | Comma-separated numeric Telegram user IDs allowed to use the bot || `PRIMARY_UI` | Set to `dashboard` to make `/` show the HuggingMes status page instead of the chat UI. Default is `webui`. || `SYNC_INTERVAL` | Backup cadence in seconds (default 600, range 60–86400) || `HERMES_AGENT_VERSION` | Pin the upstream Hermes Agent base image to a specific tag for reproducibility (default `latest`) |
### 3. Restart and open
Settings → **Restart this Space** (or **Factory reboot** if you changed the Dockerfile). Wait ~5–8 minutes for the first build. Watch the **Logs** tab — when you see this, you're ready:
```HuggingMes + Hermes WebUI router listening on 0.0.0.0:7861```
Open the Space URL (`https://<you>-<name>.hf.space`) in a **new tab** (the embedded HF iframe sometimes blocks the login cookie). You'll see a login page → enter your `GATEWAY_TOKEN` → the chat UI loads.
> **Tip**: bookmark the direct `*.hf.space` URL rather than the HF page — much smoother on mobile and avoids iframe quirks.
## What you can do once it's running
| URL | What's there || --- | --- || `/` | **Hermes WebUI** — three-panel chat with sessions, file browser, slash commands, profiles, themes, voice input, mermaid diagrams, syntax highlighting, tool cards, and everything else hermes-webui ships || `/hm` | HuggingMes status dashboard — gateway/WebUI/backup/Telegram/keepalive tiles || `/hm/app/` | Hermes's built-in dashboard — manage providers, profiles, cron jobs || `/v1/*` | OpenAI-compatible API — point any OpenAI SDK at it with `GATEWAY_TOKEN` as the API key || `/health` | JSON health probe — no auth, used by HF Spaces and the Cloudflare keepalive worker || `/telegram` | Telegram bot webhook (only if `TELEGRAM_BOT_TOKEN` is set) |
### Using the API from code
```bashcurl https://<you>-<name>.hf.space/v1/chat/completions \ -H "Authorization: Bearer $GATEWAY_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "model": "hermes", "messages": [{"role": "user", "content": "hello"}] }'```
```pythonfrom openai import OpenAIclient = OpenAI( base_url="https://<you>-<name>.hf.space/v1", api_key="<your GATEWAY_TOKEN>",)resp = client.chat.completions.create( model="hermes", messages=[{"role": "user", "content": "hello"}],)```
### Adding MCP servers
Open `/hm/app/config` (the Hermes config editor) and add an `mcp` block. No SSH needed:
```yamlmcp: servers: fetch: command: uvx args: ["mcp-server-fetch"] filesystem: command: npx args: ["-y", "@modelcontextprotocol/server-filesystem", "/opt/data/workspace"]```
`uvx` and `npx` are both pre-installed in the image.
## Persistence and how it works
When `HF_TOKEN` is set:
- **On boot**, the Space downloads the latest snapshot from your private HF Dataset (default name `huggingmes-backup`) and restores it into `/opt/data/`.- **Every `SYNC_INTERVAL` seconds** (default 600), it detects state changes and uploads a new snapshot.- **On graceful shutdown** (SIGTERM), it does one final sync before exit.
What gets backed up: chat sessions, agent memory, workspace files, profiles, skills, cron jobs, Hermes config. The dataset is private to your HF account.
## Architecture
Single port (7861) Node.js router fronts four backends:
```HF Space port 7861 │ ▼ health-server.js (router + auth + status page) │ ├─► / → Hermes WebUI (127.0.0.1:8787) ├─► /hm → HuggingMes status (in-process) ├─► /hm/app/* → Hermes dashboard (127.0.0.1:9119) [SPA-rewritten] ├─► /v1/* → Hermes gateway API (127.0.0.1:8642) [bearer auth] ├─► /telegram → Telegram webhook (127.0.0.1:8765) └─► /health, /status → in-process JSON```
`start.sh` boots Hermes Agent's gateway + dashboard + WebUI as subprocesses, then the router on top. `hermes-sync.py` runs the periodic HF Dataset upload loop. Cloudflare and Telegram setup runs once at boot if their respective secrets are set.
## Local testing
```bashgit clone https://github.com/F4bC0d3/huggingmes-hermes-webui.gitcd huggingmes-hermes-webuicp .env.example .env# edit .env with real GATEWAY_TOKEN, LLM_API_KEY, LLM_MODELdocker build -t huggingmes-hermes-webui .docker run --rm -p 7861:7861 --env-file .env huggingmes-hermes-webui# open http://localhost:7861```
## Troubleshooting
| Symptom | Cause / Fix || --- | --- || Build fails on `nousresearch/hermes-agent:latest` | Set `HERMES_AGENT_VERSION` to a specific tag and restart || Container Running but `/` returns 502 | Hermes WebUI didn't bind. Check Logs tab for `webui.log` output — usually missing/wrong `LLM_API_KEY` || `/v1/*` returns 401 | Need `Authorization: Bearer <GATEWAY_TOKEN>` header || `/api/status` 404s in logs | Cosmetic — old browser tab polling. Ignored. || Login loops on `/login` | Browser embedded in HF iframe blocks cookies. Open the Space in a new tab. || `Dashboard pages blank or 404 on refresh` | Should be fixed by the SPA rewriter in health-server.js. Hard-refresh and unregister service worker if cached: DevTools → Application → Service Workers → Unregister || Space sleeps after a few hours | Free tier limitation. Add `CLOUDFLARE_WORKERS_TOKEN` to provision a keep-alive cron worker || Telegram bot doesn't respond | HF Spaces blocks `api.telegram.org` egress. Add `CLOUDFLARE_WORKERS_TOKEN` to auto-provision an outbound proxy || Two Spaces overwriting each other's backup | Set different `BACKUP_DATASET_NAME` on each |
## Want a native Android app?
I have a companion Android wrapper at **[F4bC0d3/hermes-mobile](https://github.com/F4bC0d3/hermes-mobile)** — same auth flow, sessions drawer, ChatGPT/Claude-style top bar, all hermes-webui features inside. Just point it at your Space URL.
## Credits
- **[Nous Research](https://nousresearch.com)** for **[Hermes Agent](https://github.com/NousResearch/hermes-agent)** — the agent runtime, the persistent memory system, the multi-provider LLM routing, the cron and skills systems. None of this exists without their work.- **[@nesquena](https://github.com/nesquena)** for **[Hermes WebUI](https://github.com/nesquena/hermes-webui)** — the chat interface you actually see and use. Three-panel layout, SSE streaming, slash commands, profile management, theme system, mobile responsive design — all theirs.- **[@somratpro](https://github.com/somratpro)** for **[HuggingMes](https://github.com/somratpro/HuggingMes)** — the HF Space packaging, the HF Dataset backup engine (`hermes-sync.py`), the Cloudflare proxy and keepalive setup, the Telegram integration, and the gateway auth wrapper. This repo is largely a fork of HuggingMes with WebUI added as the primary surface.
This repo's only contribution is the integration layer: a Node.js router that fronts both UIs on a single HF Space port, unified auth where one `GATEWAY_TOKEN` gates everything, and minor tweaks to `start.sh` to launch hermes-webui alongside the existing HuggingMes processes. If you find this useful, star the upstream projects, not this one.
## License
MIT — same as both upstream projects.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225#!/usr/bin/env python3from __future__ import annotations
"""Create or reuse a Cloudflare Worker for Space keep-awake.
Vendored verbatim from github.com/somratpro/HuggingMes."""
import jsonimport osimport reimport sysimport timeimport urllib.requestimport urllib.errorfrom pathlib import Path
API_BASE = "https://api.cloudflare.com/client/v4"KEEPALIVE_STATUS_FILE = Path("/tmp/huggingmes-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}, ) try: with urllib.request.urlopen(req, timeout=30) as response: payload = json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as e: try: error_body = json.loads(e.read().decode("utf-8")) errors = error_body.get("errors") or [{"message": "Unknown error"}] error_msg = errors[0].get("message", "Unknown error") if errors else "Unknown error" except Exception: error_msg = f"HTTP {e.code}: {e.reason}" raise RuntimeError(f"Cloudflare API {e.code}: {error_msg}") 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 "huggingmes-keepalive")[: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 "huggingmes-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": "HuggingMes 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())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203#!/usr/bin/env python3from __future__ import annotations
"""Create or reuse Cloudflare Workers for Telegram proxy and Space keep-awake.
Vendored verbatim from github.com/somratpro/HuggingMes."""
import jsonimport osimport reimport secretsimport sysimport timeimport urllib.requestfrom pathlib import Path
API_BASE = "https://api.cloudflare.com/client/v4"ENV_FILE = Path("/tmp/huggingmes-cloudflare-proxy.env")DEFAULT_ALLOWED = [ "api.telegram.org", "discord.com", "discordapp.com", "gateway.discord.gg", "status.discord.com", "slack.com", "api.slack.com", "web.whatsapp.com", "graph.facebook.com", "graph.instagram.com", "api.openai.com", "googleapis.com", "google.com", "googleusercontent.com", "gstatic.com",]
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 "huggingmes-proxy")[:63].rstrip("-")
def derive_worker_name() -> str: explicit = os.environ.get("CLOUDFLARE_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', '')}-proxy") return "huggingmes-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));}});
const PROXY_SHARED_SECRET = {json.dumps(secret_value)};const ALLOW_PROXY_ALL = {"true" if allow_proxy_all else "false"};const ALLOWED_TARGETS = {json.dumps(allowed_targets)};
function isAllowedHost(hostname) {{ const normalized = String(hostname || "").trim().toLowerCase(); if (!normalized) return false; if (ALLOW_PROXY_ALL) return true; return ALLOWED_TARGETS.some((domain) => normalized === domain || normalized.endsWith(`.${{domain}}`));}}
async function handleRequest(request) {{ const url = new URL(request.url); const queryTarget = url.searchParams.get("proxy_target"); const targetHost = request.headers.get("x-target-host") || queryTarget;
if (PROXY_SHARED_SECRET) {{ const providedSecret = request.headers.get("x-proxy-key") || url.searchParams.get("proxy_key") || ""; const telegramStylePath = url.pathname.startsWith("/bot") || url.pathname.startsWith("/file/bot"); if (providedSecret !== PROXY_SHARED_SECRET && !(telegramStylePath && !targetHost)) {{ return new Response("Unauthorized: Invalid proxy key", {{ status: 401 }}); }} }}
let targetBase = ""; if (targetHost) {{ if (!isAllowedHost(targetHost)) {{ return new Response(`Forbidden: Host ${{targetHost}} is not allowed.`, {{ status: 403 }}); }} targetBase = `https://${{targetHost}}`; }} else if (url.pathname.startsWith("/bot") || url.pathname.startsWith("/file/bot")) {{ targetBase = "https://api.telegram.org"; }} else {{ return new Response("Invalid request: No target host provided.", {{ status: 400 }}); }}
const cleanSearch = new URLSearchParams(url.search); cleanSearch.delete("proxy_target"); cleanSearch.delete("proxy_key"); const searchStr = cleanSearch.toString(); const targetUrl = targetBase + url.pathname + (searchStr ? `?${{searchStr}}` : "");
const headers = new Headers(request.headers); for (const header of ["cf-connecting-ip", "cf-ray", "cf-visitor", "host", "x-real-ip", "x-target-host", "x-proxy-key"]) {{ headers.delete(header); }}
try {{ return await fetch(new Request(targetUrl, {{ method: request.method, headers, body: request.body, redirect: "follow", }})); }} catch (error) {{ return new Response(`Proxy Error: ${{error.message}}`, {{ status: 502 }}); }}}}"""
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', encoding="utf-8", ) ENV_FILE.chmod(0o600)
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 main() -> int: existing_url = os.environ.get("CLOUDFLARE_PROXY_URL", "").strip() existing_secret = os.environ.get("CLOUDFLARE_PROXY_SECRET", "").strip() api_token = os.environ.get("CLOUDFLARE_WORKERS_TOKEN", "").strip()
if existing_url: write_env(existing_url, existing_secret)
if not api_token: return 0
try: 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)
return 0 except Exception as exc: print(f"Cloudflare proxy setup failed: {exc}", file=sys.stderr) return 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928"use strict";
/** * HuggingMes + Hermes WebUI — single-port router on HF Space port 7861. * * Routes: * /login -> HuggingMes login (password = GATEWAY_TOKEN) * /health /status -> JSON health (unauthenticated — for HF probes + keepalive) * /hm /hm/* -> HuggingMes status page + app (auth-gated) * /dashboard -> redirect to /hm * /v1 /v1/* -> Hermes gateway (bearer auth; HTML => login redirect) * /telegram /telegram/*-> Telegram webhook (unauthenticated; Telegram needs to reach it) * everything else -> Hermes WebUI (nesquena/hermes-webui) as the primary UI * WebUI handles its own login at /login-... no, wait: WebUI * also exposes /login. We keep HuggingMes' login at /login * so the shared GATEWAY_TOKEN gates both. * * Based on github.com/somratpro/HuggingMes with added WebUI routing as the * primary UI. */
const http = require("http");const fs = require("fs");const net = require("net");const crypto = require("crypto");
const PORT = Number(process.env.PORT || 7861);const GATEWAY_PORT = Number(process.env.API_SERVER_PORT || 8642);const DASHBOARD_PORT = Number(process.env.DASHBOARD_PORT || 9119);const TELEGRAM_WEBHOOK_PORT = Number(process.env.TELEGRAM_WEBHOOK_PORT || 8765);const WEBUI_PORT = Number(process.env.HERMES_WEBUI_PORT || 8787);const GATEWAY_HOST = "127.0.0.1";const startTime = Date.now();const API_SERVER_KEY = process.env.API_SERVER_KEY || "";const HM_PREFIX = "/hm";const LOGIN_PATH = "/hm/login";const SESSION_COOKIE = "huggingmes_session";const PRIMARY_UI = (process.env.PRIMARY_UI || "webui").toLowerCase();
const SYNC_STATUS_FILE = "/tmp/huggingmes-sync-status.json";const CLOUDFLARE_KEEPALIVE_STATUS_FILE = "/tmp/huggingmes-cloudflare-keepalive-status.json";
/* ── Port probing + auth ──────────────────────────────────────────── */
function canConnect(port, host = GATEWAY_HOST, timeoutMs = 600) { return new Promise((resolve) => { const socket = net.createConnection({ port, host }); const done = (ok) => { socket.removeAllListeners(); socket.destroy(); resolve(ok); }; socket.setTimeout(timeoutMs); socket.once("connect", () => done(true)); socket.once("timeout", () => done(false)); socket.once("error", () => done(false)); });}
function readJson(path, fallback = null) { try { if (fs.existsSync(path)) return JSON.parse(fs.readFileSync(path, "utf8")); } catch {} return fallback;}
function timingSafeEqualString(left, right) { if (!left || !right) return false; const a = Buffer.from(left); const b = Buffer.from(right); if (a.length !== b.length) return false; return crypto.timingSafeEqual(a, b);}
function expectedSessionValue() { if (!API_SERVER_KEY) return ""; return crypto .createHmac("sha256", API_SERVER_KEY) .update("huggingmes-session-v1") .digest("hex");}
function parseCookies(req) { const header = req.headers.cookie || ""; const cookies = {}; for (const item of header.split(";")) { const sep = item.indexOf("="); if (sep < 0) continue; const name = item.slice(0, sep).trim(); const value = item.slice(sep + 1).trim(); if (!name) continue; try { cookies[name] = decodeURIComponent(value); } catch { cookies[name] = value; } } return cookies;}
function isHttpsRequest(req) { return req.headers["x-forwarded-proto"] === "https";}
function buildSessionCookie(req) { const secure = isHttpsRequest(req) ? "; Secure" : ""; return `${SESSION_COOKIE}=${encodeURIComponent(expectedSessionValue())}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400${secure}`;}
function getBearerToken(req) { const value = req.headers.authorization || ""; const match = /^Bearer\s+(.+)$/i.exec(value); return match ? match[1] : "";}
function isAuthorized(req) { if (!API_SERVER_KEY) return true; return ( timingSafeEqualString(getBearerToken(req), API_SERVER_KEY) || timingSafeEqualString( parseCookies(req)[SESSION_COOKIE], expectedSessionValue(), ) );}
function sanitizeNext(value, fallback = "/") { if (!value || typeof value !== "string") return fallback; if (!value.startsWith("/") || value.startsWith("//")) return fallback; return value;}
function loginUrl(nextPath) { return `${LOGIN_PATH}?next=${encodeURIComponent(sanitizeNext(nextPath))}`;}
function wantsHtml(req) { const accept = String(req.headers.accept || ""); return accept.includes("text/html");}
function escapeHtml(value) { return String(value) .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """);}
function readRequestBody(req, limit = 64 * 1024) { return new Promise((resolve, reject) => { let body = ""; req.on("data", (chunk) => { body += chunk; if (body.length > limit) { reject(new Error("Request body is too large.")); req.destroy(); } }); req.on("end", () => resolve(body)); req.on("error", reject); });}
/* ── Login page ───────────────────────────────────────────────────── */
function renderLoginPage(nextPath, errorMessage = "") { const safeNext = sanitizeNext(nextPath, "/"); const errorHtml = errorMessage ? `<div class="error">${escapeHtml(errorMessage)}</div>` : ""; return `<!doctype html><html lang="en"><head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>HuggingMes + Hermes WebUI — Login</title> <style> :root { color-scheme: dark; --bg:#10141f; --panel:#171d2b; --line:#293246; --text:#f4f7fb; --muted:#9aa7bd; --bad:#ef4444; --accent:#38bdf8; } * { box-sizing:border-box; } body { margin:0; min-height:100vh; display:grid; place-items:center; font-family:Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background:var(--bg); color:var(--text); padding:20px; } main { width:min(440px, 100%); border:1px solid var(--line); background:var(--panel); border-radius:8px; padding:28px; } h1 { margin:0 0 8px; font-size:1.55rem; } p { margin:0 0 22px; color:var(--muted); line-height:1.5; } label { display:block; color:var(--muted); font-size:.82rem; margin-bottom:8px; } input { width:100%; min-height:46px; border:1px solid var(--line); border-radius:7px; background:#0b0f18; color:var(--text); padding:0 12px; font:inherit; } button { width:100%; min-height:44px; margin-top:16px; border:0; border-radius:7px; color:#07111f; background:var(--accent); font:inherit; font-weight:750; cursor:pointer; } .error { border:1px solid rgba(239,68,68,.4); background:rgba(239,68,68,.1); color:#fecaca; border-radius:7px; padding:10px 12px; margin-bottom:16px; } </style></head><body> <main> <h1>HuggingMes Admin</h1> <p>Enter the <code>GATEWAY_TOKEN</code> from your Space secrets to access the status dashboard.<br>For the Hermes chat UI, go to <a href="/" style="color:var(--accent)">/</a>.</p> ${errorHtml} <form method="post" action="${LOGIN_PATH}"> <input type="hidden" name="next" value="${escapeHtml(safeNext)}" /> <label for="token">GATEWAY_TOKEN</label> <input id="token" name="token" type="password" autocomplete="current-password" autofocus required /> <button type="submit">Continue</button> </form> </main></body></html>`;}
async function handleLogin(req, res, parsed) { const nextPath = sanitizeNext(parsed.searchParams.get("next") || "/", "/");
if (!API_SERVER_KEY) { redirect(res, nextPath); return; }
if (req.method === "GET") { res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", }); res.end(renderLoginPage(nextPath)); return; }
if (req.method !== "POST") { res.writeHead(405, { allow: "GET, POST" }); res.end("Method not allowed"); return; }
try { const body = await readRequestBody(req); const params = new URLSearchParams(body); const submittedToken = params.get("token") || ""; const submittedNext = sanitizeNext(params.get("next") || nextPath, "/");
if (!timingSafeEqualString(submittedToken, API_SERVER_KEY)) { res.writeHead(401, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", }); res.end( renderLoginPage( submittedNext, "That token did not match GATEWAY_TOKEN.", ), ); return; }
res.writeHead(302, { location: submittedNext, "set-cookie": buildSessionCookie(req), "cache-control": "no-store", }); res.end(); } catch (error) { res.writeHead(400, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", }); res.end(error.message || "Invalid login request."); }}
function requireAuth(req, res) { if (isAuthorized(req)) return true; const parsed = new URL(req.url, "http://localhost"); redirect(res, loginUrl(`${parsed.pathname}${parsed.search}`)); return false;}
/* ── Upstream proxy ────────────────────────────────────────────────── */
function proxyRequest( req, res, targetPort, rewritePath = (path) => path, headerOverrides = {},) { const parsed = new URL(req.url, "http://localhost"); const targetPath = rewritePath(parsed.pathname) + parsed.search; const headers = { ...req.headers, ...headerOverrides, host: `${GATEWAY_HOST}:${targetPort}`, "x-forwarded-host": req.headers.host || "", "x-forwarded-proto": req.headers["x-forwarded-proto"] || "https", };
const proxy = http.request( { hostname: GATEWAY_HOST, port: targetPort, method: req.method, path: targetPath, headers, }, (upstream) => { res.writeHead(upstream.statusCode || 502, upstream.headers); upstream.pipe(res); }, );
proxy.on("error", (error) => { res.writeHead(502, { "content-type": "application/json" }); res.end(JSON.stringify({ error: "proxy_error", message: error.message })); });
req.pipe(proxy);}
function redirect(res, location, statusCode = 302) { res.writeHead(statusCode, { location }); res.end();}
/* ── Dashboard SPA proxy with HTML rewriting ────────────────────────── * * The Hermes dashboard is a Vite React app built for root-path deployment. * Its HTML hardcodes window.__HERMES_BASE_PATH__="" and absolute src/href * paths like /assets/index-XXX.js. Under /hm/app, React's router wouldn't * know its basename and client-side routes (/config, /sessions, etc.) 404 * on refresh. * * This proxy: * - serves the dashboard's index.html for any non-asset /hm/app/* path * (SPA fallback, so /config, /profiles etc. work on direct load) * - rewrites the returned HTML so React router uses /hm/app as its * basename and absolute asset paths get prefixed with /hm/app */function proxyDashboard(req, res) { const parsed = new URL(req.url, "http://localhost"); const inner = parsed.pathname.replace(`${HM_PREFIX}/app`, "") || "/";
const isAssetLike = inner.startsWith("/assets/") || inner.startsWith("/api/") || inner.startsWith("/dashboard-plugins/") || inner.startsWith("/ds-assets/") || /\.[a-z0-9]{1,6}$/i.test(inner);
// SPA routes → serve index.html; everything else → forward as-is. const targetPath = (isAssetLike || inner === "/" ? inner : "/") + parsed.search;
const headers = { ...req.headers, host: `${GATEWAY_HOST}:${DASHBOARD_PORT}`, "x-forwarded-host": req.headers.host || "", "x-forwarded-proto": req.headers["x-forwarded-proto"] || "https", // Disable upstream compression so we can rewrite text responses. "accept-encoding": "identity", };
const upstream = http.request( { hostname: GATEWAY_HOST, port: DASHBOARD_PORT, method: req.method, path: targetPath, headers, }, (upRes) => { const contentType = String(upRes.headers["content-type"] || ""); const shouldRewrite = contentType.includes("text/html") || contentType.includes("application/xhtml");
if (!shouldRewrite) { res.writeHead(upRes.statusCode || 502, upRes.headers); upRes.pipe(res); return; }
const chunks = []; upRes.on("data", (chunk) => chunks.push(chunk)); upRes.on("end", () => { let body = Buffer.concat(chunks).toString("utf8");
// Tell the React router its basename. body = body.replace( /window\.__HERMES_BASE_PATH__\s*=\s*"[^"]*"/g, `window.__HERMES_BASE_PATH__="${HM_PREFIX}/app"`, );
// Prefix absolute asset URLs so they stay under /hm/app. const prefix = `${HM_PREFIX}/app`; body = body.replace( /\b(src|href)="\/(?!\/|http)([^"]*)"/g, (match, attr, rest) => { if ( ("/" + rest).startsWith(prefix + "/") || "/" + rest === prefix ) { return match; } return `${attr}="${prefix}/${rest}"`; }, );
const buf = Buffer.from(body, "utf8"); const outHeaders = { ...upRes.headers }; delete outHeaders["content-length"]; delete outHeaders["transfer-encoding"]; delete outHeaders["content-encoding"]; outHeaders["content-length"] = String(buf.length);
res.writeHead(upRes.statusCode || 502, outHeaders); res.end(buf); }); upRes.on("error", () => { try { res.writeHead(502); res.end(); } catch {} }); }, );
upstream.on("error", (error) => { res.writeHead(502, { "content-type": "application/json" }); res.end(JSON.stringify({ error: "proxy_error", message: error.message })); });
req.pipe(upstream);}
/* ── Status JSON + HuggingMes status page ─────────────────────────── */
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`;}
async function statusPayload() { const gateway = await canConnect(GATEWAY_PORT); const dashboard = await canConnect(DASHBOARD_PORT); const webui = await canConnect(WEBUI_PORT); const telegramWebhook = !!process.env.TELEGRAM_WEBHOOK_URL && (await canConnect(TELEGRAM_WEBHOOK_PORT)); const sync = readJson( SYNC_STATUS_FILE, process.env.HF_TOKEN ? { status: "configured", message: "Backup enabled; waiting for first sync." } : { status: "disabled", message: "HF_TOKEN is not configured." }, );
return { ok: gateway && webui, uptime: formatUptime(Date.now() - startTime), startedAt: new Date(startTime).toISOString(), gateway, dashboard, webui, authConfigured: !!API_SERVER_KEY, primaryUi: PRIMARY_UI, ports: { public: PORT, gateway: GATEWAY_PORT, dashboard: DASHBOARD_PORT, webui: WEBUI_PORT, telegramWebhook: TELEGRAM_WEBHOOK_PORT, }, telegram: { configured: !!process.env.TELEGRAM_BOT_TOKEN, webhook: !!process.env.TELEGRAM_WEBHOOK_URL, webhookUrl: process.env.TELEGRAM_WEBHOOK_URL || "", webhookListening: telegramWebhook, proxy: process.env.CLOUDFLARE_PROXY_URL || "", }, model: 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), };}
function toneBadge(label, tone = "neutral") { return `<span class="badge ${tone}">${escapeHtml(label)}</span>`;}
function valueOrUnset(value, fallback = "Not set") { return value ? escapeHtml(value) : `<span class="muted">${escapeHtml(fallback)}</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 renderStatusPage(data) { const 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" : "Polling"}${data.telegram.proxy ? " via CF proxy" : ""}` : "Not configured"; const backupDetail = data.backup?.message ? escapeHtml(data.backup.message) : "No status yet"; const keepAliveDetail = keepaliveConfigured ? `Pinging <code>${escapeHtml(data.keepalive.targetUrl || "/health")}</code>` : keepaliveStatus === "error" && data.keepalive?.message ? escapeHtml(data.keepalive.message) : process.env.CLOUDFLARE_WORKERS_TOKEN ? "Worker pending or failed" : "Not configured";
const tiles = [ renderTile({ title: "WebUI", value: toneBadge(data.webui ? "Online" : "Offline", data.webui ? "ok" : "off"), detail: data.webui ? `Port ${data.ports.webui}` : "Unreachable", tone: data.webui ? "ok" : "off", }), renderTile({ title: "Gateway", value: toneBadge(data.gateway ? "Online" : "Offline", data.gateway ? "ok" : "off"), detail: data.gateway ? `API on port ${data.ports.gateway}` : "Unreachable", tone: data.gateway ? "ok" : "off", meta: data.authConfigured ? "Protected" : "Unprotected", }), renderTile({ title: "Model", value: `<code>${valueOrUnset(data.model)}</code>`, detail: `Provider: ${valueOrUnset(data.provider || "auto")}`, tone: data.model ? "ok" : "warn", }), renderTile({ title: "Runtime", value: escapeHtml(data.uptime), detail: `Port ${data.ports.public}`, tone: "neutral", }), renderTile({ title: "Telegram", value: toneBadge(data.telegram.configured ? "Configured" : "Disabled", telegramTone), detail: telegramDetail, tone: telegramTone, }), renderTile({ title: "Backup", value: toneBadge(syncStatus.toUpperCase(), syncTone), detail: backupDetail, tone: syncTone, meta: data.backup?.timestamp ? `<span class="local-time" data-iso="${data.backup.timestamp}"></span>` : "", }), 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>HuggingMes + Hermes WebUI</title> <style> :root { color-scheme: dark; --bg:#08080f; --panel:#12111b; --line:#26243a; --text:#f6f4ff; --muted:#7f7a9e; --soft:#b8b3d7; --good:#22c55e; --warn:#f5c542; --bad:#fb7185; --accent:#6557df; } * { 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; } .subtitle { margin-top:12px; color:var(--muted); font-size:.72rem; text-transform:uppercase; letter-spacing:.14em; font-weight:800; } .row { display:flex; gap:10px; margin:24px 0 20px; flex-wrap:wrap; } .hero-action { flex:1 1 200px; min-height:46px; display:flex; align-items:center; justify-content:center; border-radius:8px; background:#ffffff; color:#000000; text-decoration:none; font-weight:850; font-size:.98rem; } .hero-action.secondary { background:#232234; color:var(--text); border:1px solid var(--line); } .hero-action:hover { opacity:.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; 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); } footer { color:var(--muted); text-align:center; font-size:.74rem; margin-top:18px; } @media (max-width: 700px) { .overview { grid-template-columns:1fr; } } </style></head><body> <main> <header> <h1>HuggingMes + Hermes WebUI</h1> <div class="subtitle">Self-hosted Hermes Agent on HF Spaces</div> </header> <div class="row"> <a class="hero-action" href="/" target="_blank" rel="noopener">Open Hermes WebUI -></a> <a class="hero-action secondary" href="${HM_PREFIX}/app/" target="_blank" rel="noopener">Open Hermes Dashboard</a> </div> <section class="overview"> ${tiles} </section> <footer>Built on <a href="https://github.com/somratpro/HuggingMes" style="color:var(--accent)">HuggingMes</a> + <a href="https://github.com/nesquena/hermes-webui" style="color:var(--accent)">Hermes WebUI</a></footer> </main> <script> document.querySelectorAll('.local-time').forEach(el => { const date = new Date(el.getAttribute('data-iso')); if (!isNaN(date)) el.textContent = 'At ' + date.toLocaleTimeString(); }); </script></body></html>`;}
/* ── Server ───────────────────────────────────────────────────────── */
const server = http.createServer(async (req, res) => { const parsed = new URL(req.url, "http://localhost"); const path = parsed.pathname;
// 1. /hm/login — HuggingMes admin login (cookie-based, gates /hm/*). // hermes-webui handles its own /login at the catch-all below. if (path === LOGIN_PATH) { await handleLogin(req, res, parsed); return; }
// 2. /health — unauthenticated; HF Spaces probes + Cloudflare keepalive. if (path === "/health") { const data = await statusPayload(); res.writeHead(data.ok ? 200 : 503, { "content-type": "application/json" }); res.end( JSON.stringify({ ok: data.ok, gateway: data.gateway, webui: data.webui, uptime: data.uptime, }), ); return; }
// 3. /status — unauthenticated JSON status dump. if (path === "/status" || path === "/api/status") { const data = await statusPayload(); res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify(data, null, 2)); return; }
// 4. /telegram — webhook endpoint; no auth (Telegram can't do our cookie). if (path === "/telegram" || path.startsWith("/telegram/")) { proxyRequest(req, res, TELEGRAM_WEBHOOK_PORT); return; }
// 5. /v1/* — Hermes gateway OpenAI-compatible API. if (path === "/v1" || path.startsWith("/v1/")) { if (!isAuthorized(req)) { if (wantsHtml(req)) { redirect(res, loginUrl(`${path}${parsed.search}`)); return; } res.writeHead(401, { "content-type": "application/json", "cache-control": "no-store", }); res.end( JSON.stringify({ error: "unauthorized", message: "Use Authorization: Bearer <GATEWAY_TOKEN>.", }), ); return; } const upstreamHeaders = getBearerToken(req) || !API_SERVER_KEY ? {} : { authorization: `Bearer ${API_SERVER_KEY}` }; proxyRequest(req, res, GATEWAY_PORT, (p) => p, upstreamHeaders); return; }
// 6. /hm — HuggingMes status page. if (path === HM_PREFIX || path === `${HM_PREFIX}/`) { if (!requireAuth(req, res)) return; const data = await statusPayload(); res.writeHead(200, { "content-type": "text/html; charset=utf-8" }); res.end(renderStatusPage(data)); return; }
// /hm/app/* -> Hermes dashboard (SPA with HTML rewriting for base path) if (path === `${HM_PREFIX}/app` || path.startsWith(`${HM_PREFIX}/app/`)) { if (!requireAuth(req, res)) return; proxyDashboard(req, res); return; }
// /hm/status -> JSON if (path === `${HM_PREFIX}/status`) { if (!requireAuth(req, res)) return; const data = await statusPayload(); res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify(data, null, 2)); return; }
// Legacy /dashboard -> /hm if (path === "/dashboard" || path === "/dashboard/") { redirect(res, `${HM_PREFIX}${parsed.search}`); return; }
// Root-path dashboard routes (config, env, providers, etc.) that users // type or bookmark without the /hm/app prefix. Redirect them there. const dashboardRootRoutes = new Set([ "/config", "/env", "/models", "/providers", "/profiles", "/sessions", "/skills", "/cron", "/analytics", "/logs", "/plugins", "/chat", "/docs", ]); if (dashboardRootRoutes.has(path) || [...dashboardRootRoutes].some((r) => path.startsWith(r + "/"))) { redirect(res, `${HM_PREFIX}/app${path}${parsed.search}`); return; }
// 6b. Root-path requests whose Referer came from /hm/app/* must go to // the dashboard, not WebUI. This covers: // - Absolute assets (/assets/*, /ds-assets/*, /dashboard-plugins/*) // - API calls (/api/*) when dashboard code uses absolute paths // - Favicon (/favicon.ico) // - WebSocket upgrades from dashboard pages // - File downloads (any extensioned path referenced by dashboard) // Both the Hermes dashboard AND hermes-webui use /api/* internally, // so the Referer is the only reliable way to disambiguate. const refererPath = (() => { const ref = String(req.headers.referer || ""); if (!ref) return ""; try { return new URL(ref).pathname; } catch { return ""; } })(); const refererIsDashboard = refererPath.startsWith(`${HM_PREFIX}/app`);
if (refererIsDashboard) { // Anything with a Referer from the dashboard goes to the dashboard, // *except* requests that explicitly start with /webui (escape hatch). if (!path.startsWith("/webui")) { if (!requireAuth(req, res)) return; // Assets must NOT get the SPA fallback; pass them through as-is. const parsed2 = new URL(req.url, "http://localhost"); const looksLikeAsset = path.startsWith("/assets/") || path.startsWith("/ds-assets/") || path.startsWith("/dashboard-plugins/") || path.startsWith("/api/") || path === "/favicon.ico" || /\.[a-z0-9]{1,6}$/i.test(path); if (looksLikeAsset) { proxyRequest(req, res, DASHBOARD_PORT); } else { // Unlikely: a dashboard-referrer request for a non-asset, non-/hm // path. Treat as a dashboard sub-route. proxyDashboard(req, res); } return; } }
// 6c. /api/* routes — these are WebUI API calls when Referer isn't the // dashboard. Fall through to the catch-all below.
// 7. Anything else -> Hermes WebUI (primary UI) OR HuggingMes status page. // WebUI handles its own auth internally via HERMES_WEBUI_PASSWORD. if (PRIMARY_UI === "dashboard" && path === "/") { if (!requireAuth(req, res)) return; const data = await statusPayload(); res.writeHead(200, { "content-type": "text/html; charset=utf-8" }); res.end(renderStatusPage(data)); return; }
// Catch-all -> WebUI. Don't gate at the router level: WebUI has its own // password login. GATEWAY_TOKEN *is* the WebUI password (start.sh sets // HERMES_WEBUI_PASSWORD=$GATEWAY_TOKEN). proxyRequest(req, res, WEBUI_PORT);});
server.listen(PORT, "0.0.0.0", () => { console.log(`HuggingMes + Hermes WebUI router listening on 0.0.0.0:${PORT}`);});
/* ── WebSocket upgrade handling ───────────────────────────────────── * * Both the Hermes dashboard and hermes-webui can open WebSocket * connections for live updates. Route the upgrade to the correct * upstream based on path prefix + referer, same as HTTP requests. */server.on("upgrade", (req, clientSocket, head) => { const parsed = new URL(req.url, "http://localhost"); const path = parsed.pathname;
let targetPort = WEBUI_PORT; let targetPath = req.url;
const refererPath = (() => { const ref = String(req.headers.referer || ""); if (!ref) return ""; try { return new URL(ref).pathname; } catch { return ""; } })(); const refererIsDashboard = refererPath.startsWith(`${HM_PREFIX}/app`);
if (path === "/v1" || path.startsWith("/v1/")) { targetPort = GATEWAY_PORT; } else if (path === `${HM_PREFIX}/app` || path.startsWith(`${HM_PREFIX}/app/`)) { targetPort = DASHBOARD_PORT; targetPath = path.replace(`${HM_PREFIX}/app`, "") || "/"; if (parsed.search) targetPath += parsed.search; } else if (refererIsDashboard && !path.startsWith("/webui")) { targetPort = DASHBOARD_PORT; } else if (path.startsWith("/webui/") || path === "/webui") { targetPort = WEBUI_PORT; targetPath = path.replace(/^\/webui/, "") || "/"; if (parsed.search) targetPath += parsed.search; }
const upstream = net.createConnection(targetPort, GATEWAY_HOST, () => { // Forward the HTTP upgrade handshake verbatim const headerLines = [ `${req.method} ${targetPath} HTTP/1.1`, ]; for (const [name, value] of Object.entries(req.headers)) { if (Array.isArray(value)) { for (const v of value) headerLines.push(`${name}: ${v}`); } else { headerLines.push(`${name}: ${value}`); } } headerLines.push("", ""); upstream.write(headerLines.join("\r\n")); if (head && head.length) upstream.write(head); upstream.pipe(clientSocket); clientSocket.pipe(upstream); });
upstream.on("error", () => { try { clientSocket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n"); } catch {} }); clientSocket.on("error", () => { try { upstream.destroy(); } catch {} });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337#!/usr/bin/env python3"""HuggingMes Hermes state backup via Hugging Face Datasets.
Vendored verbatim from github.com/somratpro/HuggingMes.Backs up HERMES_HOME (which includes /opt/data/webui — the hermes-webui state dir)so sessions, profiles, skills, cron, memory, and workspace all survive restarts."""
import hashlibimport jsonimport loggingimport osimport shutilimport signalimport randomimport socketimport sysimport tempfileimport threadingimport timefrom pathlib import Path
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")os.environ.setdefault("HF_HUB_VERBOSITY", "error")os.environ.setdefault("HF_HUB_DOWNLOAD_TIMEOUT", "300")os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
from huggingface_hub import HfApi, snapshot_download, upload_folderfrom huggingface_hub.errors import HfHubHTTPError, RepositoryNotFoundError
logging.getLogger("huggingface_hub").setLevel(logging.ERROR)
HERMES_HOME = Path(os.environ.get("HERMES_HOME", "/opt/data"))STATUS_FILE = Path("/tmp/huggingmes-sync-status.json")STATE_FILE = HERMES_HOME / ".huggingmes-sync-state.json"INTERVAL = int(os.environ.get("SYNC_INTERVAL", "600"))INITIAL_DELAY = int(os.environ.get("SYNC_START_DELAY", "10"))HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()HF_USERNAME = os.environ.get("HF_USERNAME", "").strip()SPACE_AUTHOR_NAME = os.environ.get("SPACE_AUTHOR_NAME", "").strip()BACKUP_DATASET_NAME = os.environ.get("BACKUP_DATASET_NAME", "huggingmes-backup").strip()INCLUDE_ENV = os.environ.get("SYNC_INCLUDE_ENV", "").strip().lower() in {"1", "true", "yes"}MAX_FILE_SIZE_BYTES = int(os.environ.get("SYNC_MAX_FILE_BYTES", str(50 * 1024 * 1024)))
EXCLUDED_DIRS = { ".cache", ".git", ".npm", ".venv", "__pycache__", "node_modules", "venv",}EXCLUDED_TOP_LEVEL = {"logs", STATE_FILE.name}if not INCLUDE_ENV: EXCLUDED_TOP_LEVEL.add(".env")
HF_API = HfApi(token=HF_TOKEN) if HF_TOKEN else NoneSTOP_EVENT = threading.Event()_REPO_ID_CACHE: str | None = None
def write_status(status: str, message: str, fingerprint: str | None = None, marker: tuple[int, int, int] | None = None) -> None: timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) payload = {"status": status, "message": message, "timestamp": timestamp}
tmp_path = STATUS_FILE.with_suffix(".tmp") try: tmp_path.write_text(json.dumps(payload), encoding="utf-8") tmp_path.replace(STATUS_FILE) except OSError: pass
if fingerprint or marker: state = {} if STATE_FILE.exists(): try: state = json.loads(STATE_FILE.read_text(encoding="utf-8")) except Exception: pass if fingerprint: state["last_fingerprint"] = fingerprint if marker: state["last_marker"] = list(marker) state["last_sync"] = timestamp try: STATE_FILE.write_text(json.dumps(state), encoding="utf-8") except OSError: pass
def resolve_backup_repo() -> str: global _REPO_ID_CACHE if _REPO_ID_CACHE: return _REPO_ID_CACHE
namespace = HF_USERNAME or SPACE_AUTHOR_NAME if not namespace and HF_API is not None: whoami = HF_API.whoami() namespace = whoami.get("name") or whoami.get("user") or ""
namespace = str(namespace).strip() if not namespace: raise RuntimeError("Could not determine HF username. Set HF_USERNAME or use an account HF_TOKEN.")
_REPO_ID_CACHE = f"{namespace}/{BACKUP_DATASET_NAME}" return _REPO_ID_CACHE
def ensure_repo_exists() -> str: repo_id = resolve_backup_repo() try: HF_API.repo_info(repo_id=repo_id, repo_type="dataset") except RepositoryNotFoundError: HF_API.create_repo(repo_id=repo_id, repo_type="dataset", private=True) return repo_id
def should_exclude(rel_posix: str, path: Path) -> bool: parts = Path(rel_posix).parts if not parts: return False if parts[0] in EXCLUDED_TOP_LEVEL: return True if any(part in EXCLUDED_DIRS for part in parts): return True if path.is_file(): name_lower = path.name.lower() if name_lower.endswith((".db-shm", ".db-wal", ".db-journal")): return True try: return path.stat().st_size > MAX_FILE_SIZE_BYTES except OSError: return True return False
def metadata_marker(root: Path) -> tuple[int, int, int]: if not root.exists(): return (0, 0, 0) file_count = 0 total_size = 0 newest_mtime = 0 for path in root.rglob("*"): if not path.is_file(): continue rel = path.relative_to(root).as_posix() if should_exclude(rel, path): continue try: stat = path.stat() except OSError: continue file_count += 1 total_size += int(stat.st_size) newest_mtime = max(newest_mtime, int(stat.st_mtime_ns)) return (file_count, total_size, newest_mtime)
def fingerprint_dir(root: Path) -> str: hasher = hashlib.sha256() if not root.exists(): return hasher.hexdigest() for path in sorted(p for p in root.rglob("*") if p.is_file()): rel = path.relative_to(root).as_posix() if should_exclude(rel, path): continue hasher.update(rel.encode("utf-8")) with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): hasher.update(chunk) return hasher.hexdigest()
def create_snapshot_dir(source_root: Path) -> Path: staging_root = Path(tempfile.mkdtemp(prefix="huggingmes-sync-")) for path in sorted(source_root.rglob("*")): rel = path.relative_to(source_root) rel_posix = rel.as_posix() if should_exclude(rel_posix, path): continue target = staging_root / rel if path.is_dir(): target.mkdir(parents=True, exist_ok=True) continue target.parent.mkdir(parents=True, exist_ok=True) try: shutil.copy2(path, target) except OSError: continue return staging_root
def restore() -> bool: if not HF_TOKEN: write_status("disabled", "HF_TOKEN is not configured.") return False
repo_id = resolve_backup_repo() write_status("restoring", f"Restoring Hermes state from {repo_id}") try: with tempfile.TemporaryDirectory() as tmpdir: snapshot_download(repo_id=repo_id, repo_type="dataset", token=HF_TOKEN, local_dir=tmpdir) tmp_path = Path(tmpdir) if not any(tmp_path.iterdir()): write_status("fresh", "Backup dataset is empty. Starting fresh.") return True
HERMES_HOME.mkdir(parents=True, exist_ok=True) for child in tmp_path.iterdir(): if should_exclude(child.name, child): continue target = HERMES_HOME / child.name if target.is_dir(): shutil.rmtree(target, ignore_errors=True) elif target.exists(): target.unlink() if child.is_dir(): shutil.copytree(child, target) else: shutil.copy2(child, target)
write_status("restored", f"Restored Hermes state from {repo_id}") return True except RepositoryNotFoundError: write_status("fresh", f"Backup dataset {repo_id} does not exist yet.") return True except HfHubHTTPError as exc: if exc.response is not None and exc.response.status_code == 404: write_status("fresh", f"Backup dataset {repo_id} does not exist yet.") return True write_status("error", f"Restore failed: {exc}") print(f"Restore failed: {exc}", file=sys.stderr) return False except Exception as exc: write_status("error", f"Restore failed: {exc}") print(f"Restore failed: {exc}", file=sys.stderr) return False
def sync_once(last_fingerprint: str | None = None, last_marker: tuple[int, int, int] | None = None): if last_fingerprint is None and last_marker is None: if STATE_FILE.exists(): try: state = json.loads(STATE_FILE.read_text(encoding="utf-8")) last_fingerprint = state.get("last_fingerprint") m = state.get("last_marker") if m and len(m) == 3: last_marker = tuple(m) except Exception: pass
repo_id = ensure_repo_exists() current_marker = metadata_marker(HERMES_HOME) if last_marker is not None and current_marker == last_marker: write_status("synced", "No Hermes state changes detected (marker match).") return (last_fingerprint or "", current_marker)
current_fingerprint = fingerprint_dir(HERMES_HOME) if last_fingerprint is not None and current_fingerprint == last_fingerprint: write_status("synced", "No Hermes state changes detected (fingerprint match).") return (last_fingerprint, current_marker)
hostname = socket.gethostname() write_status("syncing", f"Uploading Hermes state to {repo_id} from {hostname}") snapshot_dir = create_snapshot_dir(HERMES_HOME) try: upload_folder( folder_path=str(snapshot_dir), repo_id=repo_id, repo_type="dataset", token=HF_TOKEN, commit_message=f"HuggingMes sync [{hostname}] {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}", ignore_patterns=[".git/*", ".git"], ) finally: shutil.rmtree(snapshot_dir, ignore_errors=True)
write_status("success", f"Uploaded Hermes state to {repo_id}", fingerprint=current_fingerprint, marker=current_marker) return (current_fingerprint, current_marker)
def handle_signal(_sig, _frame) -> None: STOP_EVENT.set()
def loop() -> int: signal.signal(signal.SIGTERM, handle_signal) signal.signal(signal.SIGINT, handle_signal) try: repo_id = resolve_backup_repo() write_status("configured", f"Backup loop active for {repo_id} with {INTERVAL}s interval.") except Exception as exc: write_status("error", str(exc)) print(f"Hermes sync error: {exc}") return 1
last_fingerprint = fingerprint_dir(HERMES_HOME) last_marker = metadata_marker(HERMES_HOME) time.sleep(INITIAL_DELAY) print(f"Hermes state sync started: every {INTERVAL}s -> {repo_id}")
while not STOP_EVENT.is_set(): try: last_fingerprint, last_marker = sync_once(last_fingerprint, last_marker) except Exception as exc: write_status("error", f"Sync failed: {exc}") print(f"Hermes sync failed: {exc}") jitter = random.uniform(0.9, 1.1) if STOP_EVENT.wait(INTERVAL * jitter): break return 0
def main() -> int: HERMES_HOME.mkdir(parents=True, exist_ok=True) if len(sys.argv) < 2: return loop() command = sys.argv[1] if command == "restore": return 0 if restore() else 1 if command == "sync-once": try: sync_once() return 0 except Exception as exc: write_status("error", f"Shutdown sync failed: {exc}") print(f"Hermes sync: shutdown sync failed: {exc}") return 1 if command == "loop": return loop() print(f"Unknown command: {command}", file=sys.stderr) return 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428#!/bin/bashset -euo pipefail
umask 0077
# ══════════════════════════════════════════════════════════════════════# HuggingMes + Hermes WebUI — integrated Hermes Agent stack for HF Spaces# Based on github.com/somratpro/HuggingMes, with Hermes WebUI# (github.com/nesquena/hermes-webui) as the primary UI.# ══════════════════════════════════════════════════════════════════════
APP_DIR="${HUGGINGMES_APP_DIR:-/opt/huggingmes}"WEBUI_REPO="${HERMES_WEBUI_REPO:-/opt/hermes-webui}"HERMES_HOME="${HERMES_HOME:-/opt/data}"
PUBLIC_PORT="${PORT:-7861}"GATEWAY_API_PORT="${API_SERVER_PORT:-8642}"DASHBOARD_PORT="${DASHBOARD_PORT:-9119}"TELEGRAM_WEBHOOK_PORT="${TELEGRAM_WEBHOOK_PORT:-8765}"WEBUI_PORT="${HERMES_WEBUI_PORT:-8787}"
SYNC_INTERVAL="${SYNC_INTERVAL:-600}"BACKUP_DATASET="${BACKUP_DATASET_NAME:-huggingmes-backup}"CF_PROXY_ENV_FILE="/tmp/huggingmes-cloudflare-proxy.env"
export HERMES_HOMEexport API_SERVER_ENABLED="${API_SERVER_ENABLED:-true}"export API_SERVER_HOST="${API_SERVER_HOST:-127.0.0.1}"export API_SERVER_PORT="$GATEWAY_API_PORT"export GATEWAY_HEALTH_URL="${GATEWAY_HEALTH_URL:-http://127.0.0.1:${GATEWAY_API_PORT}}"export TELEGRAM_WEBHOOK_PORTexport HERMES_WEBUI_PORT="$WEBUI_PORT"
echo ""echo " ╔══════════════════════════════════════════╗"echo " ║ 🪽 HuggingMes + Hermes WebUI Gateway ║"echo " ╚══════════════════════════════════════════╝"echo ""
# ── Unified auth: GATEWAY_TOKEN drives everything ─────────────────────if [ -z "${API_SERVER_KEY:-}" ]; then if [ -n "${GATEWAY_TOKEN:-}" ]; then export API_SERVER_KEY="$GATEWAY_TOKEN" else API_SERVER_KEY="$(python3 - <<'PY'import secretsprint(secrets.token_urlsafe(32))PY)" export API_SERVER_KEY echo "GATEWAY_TOKEN not set - generated an ephemeral token for this boot." fifi
# Same token becomes Hermes WebUI's login password (unified auth).if [ -n "${GATEWAY_TOKEN:-}" ]; then export HERMES_WEBUI_PASSWORD="${HERMES_WEBUI_PASSWORD:-$GATEWAY_TOKEN}"fi
# ── Setup state dirs ──────────────────────────────────────────────────mkdir -p "$HERMES_HOME"/{cron,sessions,logs,hooks,memories,skills,skins,plans,workspace,home,plugins,webui}
# Expose hermes CLI to login shellsmkdir -p "$HERMES_HOME/.local/bin"ln -sfn /opt/hermes/.venv/bin/hermes "$HERMES_HOME/.local/bin/hermes"
# Redirect Hermes plugin dir into volumeif [ ! -L "${HOME}/.hermes/plugins" ]; then mkdir -p "${HOME}/.hermes" rm -rf "${HOME}/.hermes/plugins" ln -sfn "$HERMES_HOME/plugins" "${HOME}/.hermes/plugins"fi
# ── Restore state from HF Dataset ─────────────────────────────────────if [ -n "${HF_TOKEN:-}" ]; then echo "Restoring Hermes state from HF Dataset..." python3 "$APP_DIR/hermes-sync.py" restore || trueelse echo "HF_TOKEN not set - dataset persistence is disabled."fi
# ── Cloudflare proxy (optional) ───────────────────────────────────────CLOUDFLARE_WORKERS_TOKEN="${CLOUDFLARE_WORKERS_TOKEN:-${CLOUDFLARE_API_TOKEN:-}}"export CLOUDFLARE_WORKERS_TOKENif [ -n "${CLOUDFLARE_WORKERS_TOKEN:-}" ] || [ -n "${CLOUDFLARE_PROXY_URL:-}" ]; then export CLOUDFLARE_PROXY_DEBUG="${CLOUDFLARE_PROXY_DEBUG:-false}" echo "Preparing Cloudflare Telegram proxy..." python3 "$APP_DIR/cloudflare-proxy-setup.py" || true if [ -f "$CF_PROXY_ENV_FILE" ]; then . "$CF_PROXY_ENV_FILE" fifi
if [ -n "${CLOUDFLARE_WORKERS_TOKEN:-}" ]; then echo "Preparing Cloudflare Keepalive worker..." python3 "$APP_DIR/cloudflare-keepalive-setup.py" || truefi
# ── Telegram env normalisation (aliases + webhook URL + secret) ───────if [ -n "${TELEGRAM_USER_IDS:-}" ] && [ -z "${TELEGRAM_ALLOWED_USERS:-}" ]; then export TELEGRAM_ALLOWED_USERS="$TELEGRAM_USER_IDS"elif [ -n "${TELEGRAM_USER_ID:-}" ] && [ -z "${TELEGRAM_ALLOWED_USERS:-}" ]; then export TELEGRAM_ALLOWED_USERS="$TELEGRAM_USER_ID"fi
if [ -n "${TELEGRAM_BOT_TOKEN:-}" ] && [ -n "${SPACE_HOST:-}" ] && [ -z "${TELEGRAM_WEBHOOK_URL:-}" ]; then if [ "${TELEGRAM_MODE:-webhook}" != "polling" ]; then export TELEGRAM_WEBHOOK_URL="https://${SPACE_HOST}/telegram" fifi
if [ -n "${TELEGRAM_WEBHOOK_URL:-}" ] && [ -z "${TELEGRAM_WEBHOOK_SECRET:-}" ]; then SECRET_FILE="$HERMES_HOME/.huggingmes-telegram-webhook-secret" if [ -f "$SECRET_FILE" ]; then TELEGRAM_WEBHOOK_SECRET="$(cat "$SECRET_FILE")" else TELEGRAM_WEBHOOK_SECRET="$(python3 - <<'PY'import secretsprint(secrets.token_hex(32))PY)" printf '%s' "$TELEGRAM_WEBHOOK_SECRET" > "$SECRET_FILE" chmod 600 "$SECRET_FILE" fi export TELEGRAM_WEBHOOK_SECRETfi
# ── Provider-prefix mapping (HuggingMes convention) ───────────────────MODEL_INPUT="${HERMES_MODEL:-${LLM_MODEL:-}}"MODEL_FOR_CONFIG="$MODEL_INPUT"PROVIDER_FOR_CONFIG="${HERMES_INFERENCE_PROVIDER:-auto}"LLM_API_KEY="${LLM_API_KEY:-}"
if [ -n "$MODEL_INPUT" ]; then MODEL_PREFIX="${MODEL_INPUT%%/*}"else MODEL_PREFIX=""fi
case "$MODEL_PREFIX" in openrouter) [ -n "$LLM_API_KEY" ] && export OPENROUTER_API_KEY="${OPENROUTER_API_KEY:-$LLM_API_KEY}" [ "$PROVIDER_FOR_CONFIG" = "auto" ] && PROVIDER_FOR_CONFIG="openrouter" MODEL_FOR_CONFIG="${MODEL_INPUT#openrouter/}" ;; huggingface|hf) [ -n "$LLM_API_KEY" ] && export HF_TOKEN="${HF_TOKEN:-$LLM_API_KEY}" [ "$PROVIDER_FOR_CONFIG" = "auto" ] && PROVIDER_FOR_CONFIG="huggingface" MODEL_FOR_CONFIG="${MODEL_INPUT#huggingface/}" ;; vercel-ai-gateway|ai-gateway) [ -n "$LLM_API_KEY" ] && export AI_GATEWAY_API_KEY="${AI_GATEWAY_API_KEY:-$LLM_API_KEY}" [ "$PROVIDER_FOR_CONFIG" = "auto" ] && PROVIDER_FOR_CONFIG="ai-gateway" MODEL_FOR_CONFIG="${MODEL_INPUT#*/}" ;; anthropic) [ -n "$LLM_API_KEY" ] && export ANTHROPIC_API_KEY="${ANTHROPIC_API_KEY:-$LLM_API_KEY}" ;; openai|openai-codex) [ -n "$LLM_API_KEY" ] && export OPENAI_API_KEY="${OPENAI_API_KEY:-$LLM_API_KEY}" ;; google|gemini) [ -n "$LLM_API_KEY" ] && export GOOGLE_API_KEY="${GOOGLE_API_KEY:-$LLM_API_KEY}" GEMINI_API_KEY="${GEMINI_API_KEY:-$LLM_API_KEY}" PROVIDER_FOR_CONFIG="gemini" MODEL_FOR_CONFIG="${MODEL_INPUT#*/}" ;; deepseek) [ -n "$LLM_API_KEY" ] && export DEEPSEEK_API_KEY="${DEEPSEEK_API_KEY:-$LLM_API_KEY}" ;; kimi-coding|moonshot) [ -n "$LLM_API_KEY" ] && export KIMI_API_KEY="${KIMI_API_KEY:-$LLM_API_KEY}" ;; kimi-coding-cn|moonshot-cn|kimi-cn) [ -n "$LLM_API_KEY" ] && export KIMI_CN_API_KEY="${KIMI_CN_API_KEY:-$LLM_API_KEY}" ;; minimax) [ -n "$LLM_API_KEY" ] && export MINIMAX_API_KEY="${MINIMAX_API_KEY:-$LLM_API_KEY}" ;; minimax-cn) [ -n "$LLM_API_KEY" ] && export MINIMAX_CN_API_KEY="${MINIMAX_CN_API_KEY:-$LLM_API_KEY}" ;; xiaomi) [ -n "$LLM_API_KEY" ] && export XIAOMI_API_KEY="${XIAOMI_API_KEY:-$LLM_API_KEY}" ;; zai|z-ai|z.ai|glm) [ -n "$LLM_API_KEY" ] && export GLM_API_KEY="${GLM_API_KEY:-$LLM_API_KEY}" ;; arcee|arcee-ai|arceeai) [ -n "$LLM_API_KEY" ] && export ARCEEAI_API_KEY="${ARCEEAI_API_KEY:-$LLM_API_KEY}" ;; gmi|gmi-cloud|gmicloud) [ -n "$LLM_API_KEY" ] && export GMI_API_KEY="${GMI_API_KEY:-$LLM_API_KEY}" ;; alibaba|alibaba-coding-plan|alibaba_coding) [ -n "$LLM_API_KEY" ] && export DASHSCOPE_API_KEY="${DASHSCOPE_API_KEY:-$LLM_API_KEY}" ;; tencent-tokenhub|tencent|tokenhub|tencentmaas) [ -n "$LLM_API_KEY" ] && export TOKENHUB_API_KEY="${TOKENHUB_API_KEY:-$LLM_API_KEY}" ;; nvidia) [ -n "$LLM_API_KEY" ] && export NVIDIA_API_KEY="${NVIDIA_API_KEY:-$LLM_API_KEY}" ;; xai|grok) [ -n "$LLM_API_KEY" ] && export XAI_API_KEY="${XAI_API_KEY:-$LLM_API_KEY}" ;; kilocode) [ -n "$LLM_API_KEY" ] && export KILOCODE_API_KEY="${KILOCODE_API_KEY:-$LLM_API_KEY}" ;; opencode-zen) [ -n "$LLM_API_KEY" ] && export OPENCODE_ZEN_API_KEY="${OPENCODE_ZEN_API_KEY:-$LLM_API_KEY}" ;; opencode-go) [ -n "$LLM_API_KEY" ] && export OPENCODE_GO_API_KEY="${OPENCODE_GO_API_KEY:-$LLM_API_KEY}" ;;esac
if [ -n "${CUSTOM_BASE_URL:-}" ]; then PROVIDER_FOR_CONFIG="${CUSTOM_PROVIDER:-custom}" [ -n "$LLM_API_KEY" ] && export OPENAI_API_KEY="${OPENAI_API_KEY:-$LLM_API_KEY}"fi
export MODEL_FOR_CONFIG PROVIDER_FOR_CONFIGexport CUSTOM_BASE_URL="${CUSTOM_BASE_URL:-}"export CUSTOM_API_KEY="${CUSTOM_API_KEY:-${LLM_API_KEY:-}}"export CUSTOM_MODEL_CONTEXT_LENGTH="${CUSTOM_MODEL_CONTEXT_LENGTH:-131072}"export CUSTOM_MODEL_MAX_TOKENS="${CUSTOM_MODEL_MAX_TOKENS:-8192}"export TELEGRAM_BASE_URL="${TELEGRAM_BASE_URL:-}"export TELEGRAM_BASE_FILE_URL="${TELEGRAM_BASE_FILE_URL:-}"
if [ -n "${CLOUDFLARE_PROXY_URL:-}" ] && [ -z "$TELEGRAM_BASE_URL" ]; then CLOUDFLARE_PROXY_URL="${CLOUDFLARE_PROXY_URL%/}" export TELEGRAM_BASE_URL="${CLOUDFLARE_PROXY_URL}/bot" export TELEGRAM_BASE_FILE_URL="${CLOUDFLARE_PROXY_URL}/file/bot"fi
# ── Build Hermes config.yaml ──────────────────────────────────────────python3 - <<'PY'import osfrom pathlib import Pathimport yaml
home = Path(os.environ["HERMES_HOME"])path = home / "config.yaml"try: config = yaml.safe_load(path.read_text(encoding="utf-8")) or {}except FileNotFoundError: config = {}
model_name = os.environ.get("MODEL_FOR_CONFIG", "").strip()provider_name = os.environ.get("PROVIDER_FOR_CONFIG", "").strip()
if model_name: model = config.setdefault("model", {}) model["default"] = model_name if provider_name and provider_name != "auto": model["provider"] = provider_name else: model.pop("provider", None)else: model = config.get("model", {}) print("No LLM_MODEL/HERMES_MODEL set; leaving Hermes model config unchanged.")
custom_base = os.environ.get("CUSTOM_BASE_URL", "").strip()if custom_base and model_name: model.setdefault("base_url", custom_base.rstrip("/")) if os.environ.get("CUSTOM_API_KEY"): model.setdefault("api_key", os.environ["CUSTOM_API_KEY"]) try: model.setdefault("context_length", int(os.environ.get("CUSTOM_MODEL_CONTEXT_LENGTH", "131072"))) model.setdefault("max_tokens", int(os.environ.get("CUSTOM_MODEL_MAX_TOKENS", "8192"))) except ValueError: pass
config.setdefault("terminal", {}).setdefault("cwd", os.environ.get("MESSAGING_CWD", str(home / "workspace")))config.setdefault("compression", {}).setdefault("enabled", True)config.setdefault("display", {}).setdefault("background_process_notifications", os.environ.get("HERMES_BACKGROUND_NOTIFICATIONS", "result"))config.setdefault("security", {}).setdefault("redact_secrets", True)
platforms = config.setdefault("platforms", {})
if os.environ.get("TELEGRAM_BOT_TOKEN"): telegram = platforms.setdefault("telegram", {}) telegram.setdefault("enabled", True) extra = telegram.setdefault("extra", {}) if os.environ.get("TELEGRAM_BASE_URL"): extra.setdefault("base_url", os.environ["TELEGRAM_BASE_URL"]) extra.setdefault("base_file_url", os.environ.get("TELEGRAM_BASE_FILE_URL") or os.environ["TELEGRAM_BASE_URL"]) if os.environ.get("TELEGRAM_ALLOWED_USERS"): config.setdefault("telegram", {}).setdefault("allow_from", [ item.strip() for item in os.environ["TELEGRAM_ALLOWED_USERS"].split(",") if item.strip() ])
path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")path.chmod(0o600)PY
# ── Startup summary ───────────────────────────────────────────────────echo ""echo "Primary UI : ${PRIMARY_UI:-webui}"echo "Model : ${MODEL_FOR_CONFIG:-unset}"echo "Provider : ${PROVIDER_FOR_CONFIG:-unset}"if [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; then echo "Telegram : enabled"else echo "Telegram : not configured"fiif [ -n "${HF_TOKEN:-}" ]; then echo "Backup : ${BACKUP_DATASET} (every ${SYNC_INTERVAL:-600}s)"else echo "Backup : disabled"fiif [ -n "${CLOUDFLARE_PROXY_URL:-}" ]; then echo "CF Proxy : ${CLOUDFLARE_PROXY_URL}"fiecho "Router : 0.0.0.0:${PUBLIC_PORT}"echo "WebUI : 127.0.0.1:${WEBUI_PORT}"echo "Gateway : 127.0.0.1:${GATEWAY_API_PORT}"echo "Dashboard : 127.0.0.1:${DASHBOARD_PORT}"echo ""
# ── Graceful shutdown ─────────────────────────────────────────────────graceful_shutdown() { echo "Shutting down..." if [ -n "${HF_TOKEN:-}" ]; then python3 "$APP_DIR/hermes-sync.py" sync-once || echo "Warning: shutdown sync failed." fi kill $(jobs -p) 2>/dev/null || true exit 0}trap graceful_shutdown SIGTERM SIGINT
# ── Start the public-facing router (port 7861) ────────────────────────node "$APP_DIR/health-server.js" &HEALTH_PID=$!
if [ -n "${WEBHOOK_URL:-}" ]; then python3 - <<'PY' >/dev/null 2>&1 &import json, os, urllib.requestbody = json.dumps({ "event": "restart", "status": "success", "message": "HuggingMes + Hermes WebUI has started.", "model": os.environ.get("MODEL_FOR_CONFIG", ""),}).encode()req = urllib.request.Request(os.environ["WEBHOOK_URL"], data=body, method="POST", headers={"Content-Type": "application/json"})urllib.request.urlopen(req, timeout=10).read()PYfi
# ── Launch Hermes dashboard (private; proxied via /hm/app) ────────────echo "Launching Hermes dashboard on 127.0.0.1:${DASHBOARD_PORT}..."(hermes dashboard --host 127.0.0.1 --insecure 2>&1 | tee -a "$HERMES_HOME/logs/dashboard.log") &DASHBOARD_PID=$!
# ── Launch Hermes gateway ─────────────────────────────────────────────echo "Launching Hermes gateway..."(hermes gateway run 2>&1 | tee -a "$HERMES_HOME/logs/gateway.log") &GATEWAY_PID=$!
GATEWAY_READY_TIMEOUT="${GATEWAY_READY_TIMEOUT:-120}"ready=falsefor ((i=0; i<GATEWAY_READY_TIMEOUT; i++)); do if (echo > "/dev/tcp/127.0.0.1/${GATEWAY_API_PORT}") 2>/dev/null; then ready=true break fi if ! kill -0 "$GATEWAY_PID" 2>/dev/null; then break fi sleep 1done
if [ "$ready" != "true" ]; then echo "" echo "Hermes gateway failed to expose the API health port. Last 40 log lines:" echo "----------------------------------------" tail -40 "$HERMES_HOME/logs/gateway.log" || true exit 1fi
# ── Launch Hermes WebUI (nesquena/hermes-webui) ───────────────────────# Points WebUI at the already-running Hermes agent venv and persists state# under $HERMES_HOME/webui so hermes-sync.py backs it up.export HERMES_WEBUI_AGENT_DIR="/opt/hermes"export HERMES_WEBUI_PYTHON="/opt/hermes/.venv/bin/python"export HERMES_WEBUI_HOST="127.0.0.1"export HERMES_WEBUI_PORTexport HERMES_WEBUI_STATE_DIR="${HERMES_WEBUI_STATE_DIR:-$HERMES_HOME/webui}"export HERMES_WEBUI_DEFAULT_WORKSPACE="${HERMES_WEBUI_DEFAULT_WORKSPACE:-$HERMES_HOME/workspace}"export HERMES_WEBUI_AUTO_INSTALL="0"mkdir -p "$HERMES_WEBUI_STATE_DIR"
echo "Launching Hermes WebUI on 127.0.0.1:${WEBUI_PORT}..."(cd "$WEBUI_REPO" && \ "$HERMES_WEBUI_PYTHON" "$WEBUI_REPO/server.py" 2>&1 | \ tee -a "$HERMES_HOME/logs/webui.log") &WEBUI_PID=$!
# Wait for WebUI to bind its port (non-fatal on timeout — router handles it)WEBUI_READY_TIMEOUT="${WEBUI_READY_TIMEOUT:-60}"for ((i=0; i<WEBUI_READY_TIMEOUT; i++)); do if (echo > "/dev/tcp/127.0.0.1/${WEBUI_PORT}") 2>/dev/null; then echo "Hermes WebUI is up." break fi if ! kill -0 "$WEBUI_PID" 2>/dev/null; then echo "Warning: Hermes WebUI exited during startup. Last 20 log lines:" tail -20 "$HERMES_HOME/logs/webui.log" || true break fi sleep 1done
# ── Periodic backup loop ──────────────────────────────────────────────if [ -n "${HF_TOKEN:-}" ]; then python3 -u "$APP_DIR/hermes-sync.py" loop &fi
# ── Wait on the gateway (primary supervision target) ──────────────────wait "$GATEWAY_PID"
if [ -n "${HF_TOKEN:-}" ]; then echo "Gateway exited - syncing state before shutdown..." python3 "$APP_DIR/hermes-sync.py" sync-once || echo "Warning: final sync failed."fi.dockerignoreAdded+14
.env.exampleAdded+38
.gitignoreAdded+11
DockerfileAdded+111
LICENSEAdded+36
README.mdAdded+202
cloudflare-keepalive-setup.pyAdded+225
cloudflare-proxy-setup.pyAdded+203
health-server.jsAdded+928
hermes-sync.pyAdded+337
start.shAdded+428