Spaces:
Paused
Paused
Update Dockerfile
Browse files123456789101112131415161718192021222324252627282 unmodified lines3132333435363738394041424344454647484950516 unmodified lines58596061626364656667686970717 unmodified lines7980818283848586878889901 unmodified line92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452463 unmodified lines2502512522532542552562572582592602612622632642652662672682692702712722732742751 unmodified line27727827928028128228317 unmodified lines3013023033043053063073083093103113125 unmodified lines3183193203213223233243253263273283293303313323333343352 unmodified lines3383393403413423433443456 unmodified lines3523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893909 unmodified lines4004014024034044054064074081 unmodified line4104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744751 unmodified line4774784794804814824834844857 unmodified lines4934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745 unmodified lines5805815825835845855864 unmodified lines5915925935945955965972 unmodified lines6006016026036046056066076086096106111 unmodified line61361461561661761861913 unmodified lines6336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636643 unmodified lines6686696706716726736746756766776786796806816826836846856866876886896906916926936946956964 unmodified lines7017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547553 unmodified lines75976076176276376476576676776876977077177277377477577677713 unmodified lines791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820# ============================================================# Hermes Agent β HF Spaces v8## WHAT'S NEW vs v7:# - Cloudflare Worker auto-deployed at startup (Telegram/Discord/Slack proxy)# - SPACE_HOST auto-detected β no HERMES_SPACE_URL secret needed# - Dashboard wait loop added β no more "starting" page after boot# - WebUI fallback: if port 8787 unavailable, root β dashboard# - /tg, /discord-wh, /slack-wh added as gateway routes# - Telegram webhook auto-set to CF Worker URL after deploy# - Startup optimized: bucket only syncs changed files (delta)## REQUIRED SECRETS:# GATEWAY_TOKEN your login password# OPENROUTER_API_KEY from openrouter.ai (recommended)# OR ANTHROPIC_API_KEY / OPENAI_API_KEY# HF_TOKEN HF write token# HF_BUCKET e.g. Sanyam400/Hermes-storage## FOR CLOUDFLARE WORKER (Telegram/Discord/Slack channels):# CLOUDFLARE_ACCOUNT_ID from dash.cloudflare.com (right sidebar)# CLOUDFLARE_WORKERS_TOKEN CF API token (Workers Scripts:Edit)# CF_WORKER_NAME optional, default: hermes-gateway# TELEGRAM_BOT_TOKEN optional, sets webhook automatically# TELEGRAM_ALLOWED_USERS optional, your numeric Telegram user ID# ============================================================FROM nousresearch/hermes-agent:latest2 unmodified lines# ββ System deps βββββββββββββββββββββββββββββββββββββββββββββββRUN apt-get update && apt-get install -y --no-install-recommends \ca-certificates curl jq git nodejs npm python3 netcat-openbsd \tar gzip unzip dnsutils sudo bash \&& rm -rf /var/lib/apt/lists/*RUN uv pip install --python /opt/hermes/.venv/bin/python \--no-cache-dir "huggingface_hub>=1.5.0" pyyaml# hf CLIRUN curl -LsSf https://hf.co/cli/install.sh | bash \&& ( mv /root/.local/bin/hf /usr/local/bin/hf 2>/dev/null \|| cp "$(find /root -name 'hf' -type f 2>/dev/null | head -1)" \/usr/local/bin/hf 2>/dev/null || true ) \&& chmod +x /usr/local/bin/hf 2>/dev/null || true# Give hermes user full terminal / sudo accessRUN usermod -aG sudo hermes \&& echo "hermes ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers \&& chsh -s /bin/bash hermes6 unmodified lines# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# CLOUDFLARE WORKER SCRIPT# Deployed automatically at startup if CF credentials are set.# Telegram/Discord/Slack β Worker β adds Bearer auth β HF Space# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββRUN cat > /opt/worker.js << 'ENDWORKER'// Hermes Gateway β Cloudflare Worker v8// Proxies Telegram / Discord / Slack webhooks to your HF Space// with Bearer auth injected automatically.// Also pings /health every 20 min via a setInterval workaround.var ROUTES = {'/telegram': '/tg',7 unmodified lines});async function handleRequest(request) {var url = new URL(request.url);var path = url.pathname;var HERMES = (typeof HERMES_URL !== 'undefined' ? HERMES_URL : '').replace(/\/$/, '');var TOKEN = typeof GATEWAY_TOKEN !== 'undefined' ? GATEWAY_TOKEN : '';// ββ Public health ββββββββββββββββββββββββββββββββββββββββif (path === '/health' || path === '/') {return new Response(JSON.stringify({ ok: true, worker: 'hermes-cf-proxy', hermes: HERMES }),1 unmodified line);}// ββ Only accept POST for webhooks ββββββββββββββββββββββββif (request.method !== 'POST') {return new Response('Method Not Allowed', { status: 405 });}// ββ Map path to Hermes endpoint ββββββββββββββββββββββββββvar hermesSuffix = ROUTES[path] || ('/webhooks' + path);var hermesTarget = HERMES + hermesSuffix;var body = await request.arrayBuffer();var ct = request.headers.get('Content-Type') || 'application/json';// ββ Forward with Bearer auth βββββββββββββββββββββββββββββvar resp;try {resp = await fetch(hermesTarget, {method: 'POST',headers: {'Content-Type': ct,'Authorization': 'Bearer ' + TOKEN,'X-CF-Worker': 'hermes-proxy','X-Original-Path': path,},body: body,});} catch(e) {return new Response(JSON.stringify({ error: 'Hermes unreachable', detail: e.message }),{ status: 502, headers: { 'Content-Type': 'application/json' } });}var resText = await resp.text();return new Response(resText, {status: resp.status,headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },});}ENDWORKER# ββ CF Worker deployment helper (Python, uses built-in urllib) βRUN cat > /opt/deploy_worker.py << 'ENDPY'#!/usr/bin/env python3"""Auto-deploys the Cloudflare Worker and sets Telegram webhook.Called from start.sh if CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_WORKERS_TOKEN are set."""import os, sys, json, urllib.request, urllib.parseACCOUNT_ID = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip()CF_TOKEN = os.environ.get("CLOUDFLARE_WORKERS_TOKEN", "").strip()WORKER_NAME = os.environ.get("CF_WORKER_NAME", "hermes-gateway").strip()SPACE_HOST = os.environ.get("SPACE_HOST", "").strip()GATEWAY_TOKEN = os.environ.get("GATEWAY_TOKEN", "").strip()TG_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "").strip()if not ACCOUNT_ID or not CF_TOKEN:print("[worker] CF credentials not set β skipping")sys.exit(0)# Auto-detect Hermes URL from HF SPACE_HOST env varif SPACE_HOST:HERMES_URL = f"https://{SPACE_HOST}"else:HERMES_URL = os.environ.get("HERMES_SPACE_URL", "").strip()if not HERMES_URL:print("[worker] β Cannot determine Hermes URL (SPACE_HOST not set)")sys.exit(1)BASE = f"https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/workers"HEADERS = {"Authorization": f"Bearer {CF_TOKEN}"}def cf_req(method, url, data=None, content_type="application/json"):req = urllib.request.Request(url, method=method,headers={**HEADERS, "Content-Type": content_type},)if data is not None:body = data if isinstance(data, bytes) else json.dumps(data).encode()req.data = bodytry:with urllib.request.urlopen(req, timeout=15) as r:return json.loads(r.read())except urllib.error.HTTPError as e:return json.loads(e.read())# ββ 1. Upload worker script βββββββββββββββββββββββββββββββββββprint(f"[worker] π€ Deploying worker '{WORKER_NAME}' to Cloudflare...")with open("/opt/worker.js", "rb") as f:script = f.read()res = cf_req("PUT", f"{BASE}/scripts/{WORKER_NAME}",data=script, content_type="application/javascript")if not res.get("success"):print(f"[worker] β Upload failed: {res.get('errors')}")sys.exit(1)print(f"[worker] β Script uploaded")# ββ 2. Set worker environment variables βββββββββββββββββββββββprint(f"[worker] π Setting worker secrets...")for key, val in [("HERMES_URL", HERMES_URL), ("GATEWAY_TOKEN", GATEWAY_TOKEN)]:r = cf_req("PUT", f"{BASE}/scripts/{WORKER_NAME}/secrets",data={"name": key, "text": val, "type": "secret_text"})ok = "β " if r.get("success") else "β "print(f"[worker] {ok} Secret {key}: {'set' if r.get('success') else r.get('errors')}")# ββ 3. Get workers.dev subdomain ββββββββββββββββββββββββββββββsub_res = cf_req("GET", f"{BASE}/subdomain")subdomain = sub_res.get("result", {}).get("subdomain", "")if not subdomain:print("[worker] β Could not get workers.dev subdomain")sys.exit(1)WORKER_URL = f"https://{WORKER_NAME}.{subdomain}.workers.dev"print(f"[worker] π Worker URL: {WORKER_URL}")# Save worker URL for other scripts to usewith open("/data/cf_worker_url.txt", "w") as f:f.write(WORKER_URL)# ββ 4. Set Telegram webhook βββββββββββββββββββββββββββββββββββif TG_TOKEN:webhook_url = f"{WORKER_URL}/telegram"print(f"[worker] π€ Setting Telegram webhook β {webhook_url}")tg_req = urllib.request.Request(f"https://api.telegram.org/bot{TG_TOKEN}/setWebhook",method="POST",data=urllib.parse.urlencode({"url": webhook_url}).encode(),headers={"Content-Type": "application/x-www-form-urlencoded"},)try:with urllib.request.urlopen(tg_req, timeout=10) as r:tg_res = json.loads(r.read())if tg_res.get("ok"):print(f"[worker] β Telegram webhook set!")else:print(f"[worker] β Telegram: {tg_res.get('description')}")except Exception as e:print(f"[worker] β Telegram webhook failed: {e}")print(f"[worker] π Done! Worker: {WORKER_URL}")print(f"[worker] Add to Telegram bot: {WORKER_URL}/telegram")print(f"[worker] Add to Discord: {WORKER_URL}/discord")print(f"[worker] Add to Slack: {WORKER_URL}/slack")ENDPY# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# ROUTER# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββRUN cat > /opt/router/server.js << 'ENDJS''use strict';3 unmodified linesvar PORT = parseInt(process.env.PORT || '7860', 10);var GATEWAY_TOKEN = process.env.GATEWAY_TOKEN || '';// Paths that belong to the Hermes dashboard (port 9119)var DASHBOARD_PATHS = ['/dashboard','/skills','/plugins','/mcp','/webhooks','/pairing','/profiles','/config','/keys','/system','/cron','/models','/logs','/env','/sessions','/channels','/documentation','/docs','/api','/openapi.json'];// Paths proxied directly to the gateway REST API (port 8642)var GATEWAY_PATHS = ['/v1','/tg','/discord-wh','/slack-wh','/whatsapp-wh'];// Track whether WebUI (8787) is available β detected at first requestvar webUIAvailable = null;// ββ CRITICAL: split('?')[0] returns a STRING ββββββββββββββββββfunction getPathname(url) {return (url || '/').split('?')[0].split('#')[0] || '/';}function isDashboardPath(p) {for (var i = 0; i < DASHBOARD_PATHS.length; i++) {var d = DASHBOARD_PATHS[i];if (p === d || p.indexOf(d + '/') === 0) return true;1 unmodified linereturn false;}function isGatewayPath(p) {for (var i = 0; i < GATEWAY_PATHS.length; i++) {var g = GATEWAY_PATHS[i];if (p === g || p.indexOf(g + '/') === 0) return true;17 unmodified linesif (c['hm_tok'] && decodeURIComponent(c['hm_tok']) === GATEWAY_TOKEN) return true;var auth = req.headers['authorization'] || '';if (auth === 'Bearer ' + GATEWAY_TOKEN) return true;// CF Worker adds this header β trust itif (req.headers['x-cf-worker'] === 'hermes-proxy') return true;return false;}// ββ 502 / loading page ββββββββββββββββββββββββββββββββββββββββproxy.on('error', function(err, req, res) {if (res && res.socket && !res.headersSent) {res.writeHead(502, { 'Content-Type': 'text/html; charset=utf-8' });5 unmodified lines'display:flex;align-items:center;justify-content:center;min-height:100vh}' +'.c{text-align:center}.spin{font-size:3rem;animation:s 1.2s linear infinite}' +'@keyframes s{to{transform:rotate(360deg)}}' +'h2{margin:.6rem 0 .3rem}p{color:#686c7a;font-size:.9rem}' +'</style></head><body>' +'<div class="c"><div class="spin">βοΈ</div>' +'<h2>Hermes is startingβ¦</h2>' +'<p>Refreshing in 5 s β ' + err.message + '</p>' +'</div></body></html>');}});function loginPage(err) {var e = err ? '<div class="err">β ' + err + '</div>' : '';return '<!DOCTYPE html><html lang="en"><head>' +'<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">' +'<title>Hermes β Sign in</title>' +2 unmodified lines'display:flex;align-items:center;justify-content:center;min-height:100vh}' +'.card{background:#161920;border:1px solid #252830;border-radius:18px;' +'padding:2.5rem 2rem;width:100%;max-width:400px}' +'.icon{font-size:2.5rem;margin-bottom:.4rem}' +'h1{font-size:1.4rem;margin-bottom:.2rem}' +'.sub{color:#5a5e6b;font-size:.875rem;margin-bottom:1.6rem}' +'label{display:block;font-size:.8rem;color:#8a8e9b;margin-bottom:.35rem}' +'input{width:100%;padding:.75rem 1rem;background:#0d0f14;border:1px solid #2a2d38;' +6 unmodified lines'color:#f87171;border-radius:7px;padding:.55rem .9rem;font-size:.85rem;margin-bottom:1rem}' +'.note{font-size:.73rem;color:#3a3d4a;margin-top:.9rem;text-align:center}' +'</style></head><body><div class="card">' +'<div class="icon">πͺ½</div><h1>Hermes Agent</h1>' +'<p class="sub">Enter your gateway token to continue.</p>' + e +'<form method="POST" action="/_login">' +'<label for="t">Gateway Token</label>' +'<input id="t" type="password" name="token" placeholder="Your GATEWAY_TOKEN" autofocus/>' +'<button type="submit">Sign in β</button>' +'</form><p class="note">Set GATEWAY_TOKEN in Space secrets to change this.</p>' +'</div></body></html>';}var server = http.createServer(function(req, res) {var url = req.url || '/';var pn = getPathname(url);// Public: health (no auth)if (pn === '/health' || pn === '/health/') {res.writeHead(200, { 'Content-Type': 'application/json' });return res.end(JSON.stringify({ ok: true, ts: new Date().toISOString() }));}// Login (/_login avoids HF intercepting /login)if (pn === '/_login') {if (req.method === 'POST') {var body = '';req.on('data', function(d) { body += d; });req.on('end', function() {var tok = new URLSearchParams(body).get('token') || '';if (!GATEWAY_TOKEN || tok === GATEWAY_TOKEN) {var secure = req.headers['x-forwarded-proto'] === 'https';res.writeHead(302, {'Set-Cookie': 'hm_tok=' + encodeURIComponent(tok) +'; Path=/; HttpOnly' +(secure ? '; Secure; SameSite=None' : '; SameSite=Lax'),'Location': '/'});return res.end();9 unmodified lines// Auth gateif (!authed(req)) {if (pn.indexOf('/v1/') === 0 || pn.indexOf('/api/') === 0 ||pn.indexOf('/assets/') === 0 || pn.indexOf('/static/') === 0 ||pn.indexOf('/tg') === 0) {res.writeHead(401, { 'Content-Type': 'application/json' });return res.end(JSON.stringify({ error: 'Unauthorized' }));}1 unmodified linereturn res.end();}// Gateway REST API pathsif (isGatewayPath(pn)) {return proxy.web(req, res, { target: 'http://127.0.0.1:8642' });}// Dashboard pathsif (isDashboardPath(pn)) {return proxy.web(req, res, { target: 'http://127.0.0.1:9119', changeOrigin: true });}// Check referer for dashboard sub-requestsvar refPN = getPathname((req.headers.referer || '').replace(/^https?:\/\/[^\/]+/, ''));if (isDashboardPath(refPN)) {return proxy.web(req, res, { target: 'http://127.0.0.1:9119', changeOrigin: true });}// Default: WebUI (8787) with fallback to dashboard (9119)// If WebUI not running, go straight to dashboardif (webUIAvailable === false) {return proxy.web(req, res, { target: 'http://127.0.0.1:9119', changeOrigin: true });}proxy.web(req, res, { target: 'http://127.0.0.1:8787' }, function(err) {// WebUI failed β mark it unavailable and try dashboardif (webUIAvailable !== false) {webUIAvailable = false;console.log('[router] WebUI (:8787) unavailable β routing to dashboard (:9119)');}proxy.web(req, res, { target: 'http://127.0.0.1:9119', changeOrigin: true });});});// WebSocket upgradeserver.on('upgrade', function(req, socket, head) {if (!authed(req)) { socket.destroy(); return; }var pn = getPathname(req.url || '/');var refPN = getPathname((req.headers.referer || '').replace(/^https?:\/\/[^\/]+/, ''));var target = isGatewayPath(pn) ? 'http://127.0.0.1:8642': (isDashboardPath(pn)||isDashboardPath(refPN)) ? 'http://127.0.0.1:9119': (webUIAvailable === false) ? 'http://127.0.0.1:9119': 'http://127.0.0.1:8787';proxy.ws(req, socket, head, { target: target, changeOrigin: target.indexOf('9119') >= 0 });});// Probe WebUI availability on startup (after 15s)setTimeout(function() {http.get('http://127.0.0.1:8787/', function(r) {webUIAvailable = true;r.resume();console.log('[router] WebUI (:8787) is available');}).on('error', function() {webUIAvailable = false;console.log('[router] WebUI (:8787) not running β root / β dashboard (:9119)');});}, 15000);// Keep-alive self-ping every 20 min (prevents HF 48h auto-pause)setInterval(function() {http.get('http://127.0.0.1:' + PORT + '/health', function(r) { r.resume(); }).on('error', function(){});1 unmodified lineserver.listen(PORT, '0.0.0.0', function() {console.log('[router] β Listening on 0.0.0.0:' + PORT);console.log('[router] /v1/* /tg /discord-wh β Gateway (:8642)');console.log('[router] /dashboard /skills etc β Dashboard (:9119)');console.log('[router] / β WebUI (:8787) or Dashboard');});ENDJS7 unmodified linesVENV_PY="/opt/hermes/.venv/bin/python3"HH="${HERMES_HOME:-/data}"mkdir -p "$HH" "$HH/logs"# HF auto-sets SPACE_HOST = "sanyam400-docker.hf.space"HERMES_URL="https://${SPACE_HOST:-localhost}"echo ""echo "ββββββββββββββββββββββββββββββββββββββββββββ"echo "β Hermes Agent v8 β HF Spaces boot β"echo "ββββββββββββββββββββββββββββββββββββββββββββ"echo ""# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 1 β START ROUTER IMMEDIATELY on :7860# Port 7860 must respond fast or HF kills the Space with 503.# Router serves /health + loading page while backends boot.# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββecho "[boot] π Starting router on :${PORT:-7860}..."node /opt/router/server.js &ROUTER_PID=$!sleep 1# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 2 β RESTORE FROM HF BUCKET# ~/.hermes is symlinked to /data β Hermes saves everything there.# sync_bucket only downloads CHANGED files (delta sync = fast).# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif [ -n "${HF_TOKEN:-}" ] && [ -n "${HF_BUCKET:-}" ]; thenecho "[boot] π¦ Restoring from hf://buckets/${HF_BUCKET} (delta sync)..."$VENV_PY - << 'PYEOF' || echo "[boot] β Restore skipped"import os, systry:from huggingface_hub import sync_bucket, create_buckettok = os.environ["HF_TOKEN"]bucket = os.environ["HF_BUCKET"]home = os.environ.get("HERMES_HOME", "/data")create_bucket(bucket, private=True, exist_ok=True, token=tok)# No ignore_patterns β sync_bucket does delta (only changed files)sync_bucket(f"hf://buckets/{bucket}", home, token=tok)print("[boot] β Bucket restore OK")except Exception as e:print(f"[boot] β {e}")sys.exit(1)PYEOFfi# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 3 β SQLITE WAL MODE (prevents corruption after sync)# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ$VENV_PY - << 'PYEOF' 2>/dev/null || trueimport os, sqlite3home = os.environ.get("HERMES_HOME", "/data")if not os.path.isdir(home): exit(0)for f in os.listdir(home):if not f.endswith(".db"): continuep = os.path.join(home, f)try:c = sqlite3.connect(p)ok = c.execute("PRAGMA integrity_check").fetchone()if ok and ok[0] == "ok":c.execute("PRAGMA journal_mode=WAL")c.execute("PRAGMA synchronous=NORMAL")c.commit()print(f"[boot] WAL enabled: {f}")else:raise Exception("integrity check failed")c.close()except Exception as e:print(f"[boot] DB issue ({f}): {e} β resetting")for s in ["","-wal","-shm","-journal"]:try: os.remove(p + (s if s else ""))except: passPYEOF# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 4 β WRITE / MERGE .env (API keys)# Merges Space secrets into /data/.env on every boot.# Existing manually-set keys are preserved.# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββecho "[boot] π Writing .env..."ENV_FILE="$HH/.env"5 unmodified lines[ -z "$v" ] && returnsed -i "/^${k}=/d" "$TMP" 2>/dev/null || trueecho "${k}=${v}" >> "$TMP"echo " β Set ${k} in ${ENV_FILE}"}upsert OPENROUTER_API_KEY "${OPENROUTER_API_KEY:-}"4 unmodified linesupsert API_SERVER_KEY "${API_SERVER_KEY:-}"if [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; thenupsert TELEGRAM_BOT_TOKEN "$TELEGRAM_BOT_TOKEN"TUSERS="${TELEGRAM_ALLOWED_USERS:-}"[[ -n "$TUSERS" && ! "$TUSERS" =~ ^\[.*\]$ ]] && TUSERS="[$TUSERS]"[ -n "$TUSERS" ] && upsert TELEGRAM_ALLOWED_USERS "$TUSERS"2 unmodified linesmv "$TMP" "$ENV_FILE"chmod 600 "$ENV_FILE"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 5 β WRITE config.yaml (correct model format)# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββCFG="$HH/config.yaml"if [ ! -f "$CFG" ]; thenecho "[boot] βοΈ Writing config.yaml..."if [ -n "${OPENROUTER_API_KEY:-}" ]; then PROVIDER="openrouter"elif [ -n "${ANTHROPIC_API_KEY:-}" ]; then PROVIDER="anthropic"elif [ -n "${OPENAI_API_KEY:-}" ]; then PROVIDER="openai"1 unmodified lineelse PROVIDER="auto"; fiMODEL="${HERMES_MODEL:-openai/gpt-4o-mini}"cat > "$CFG" << YAML# Hermes config β auto-written by HF Spaces boot v8model:provider: ${PROVIDER}default: "${MODEL}"13 unmodified linesfi# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 6 β SEED SKILLS# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfor src in /opt/hermes/skills /opt/hermes/hermes_cli/skills /opt/hermes/hermes/skills; doif [ -d "$src" ]; thenmkdir -p "$HH/skills"cp -rn "$src"/* "$HH/skills/" 2>/dev/null || trueecho "[boot] Skills seeded from $src"fidone# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 7 β DEPLOY CLOUDFLARE WORKER (if credentials set)# Deploys worker.js to CF, sets env vars, and sets Telegram webhook.# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif [ -n "${CLOUDFLARE_ACCOUNT_ID:-}" ] && [ -n "${CLOUDFLARE_WORKERS_TOKEN:-}" ]; thenecho "[boot] βοΈ Deploying Cloudflare Worker..."$VENV_PY /opt/deploy_worker.py 2>&1 | tee -a "$HH/logs/cf_workers.log" \&& echo "[boot] β CF Worker deployed" \|| echo "[boot] β CF Worker deploy failed β check $HH/logs/cf_workers.log"elseecho "[boot] βΉ No CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_WORKERS_TOKEN β skipping CF workers"echo "[boot] Add these secrets to enable Telegram proxy + keep-alive cron"fi# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 8 β START HERMES GATEWAY on :8642# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββecho "[boot] π Starting Hermes Gateway on :8642..."API_SERVER_ENABLED=true \3 unmodified linesecho "[boot] Gateway PID: $!"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 9 β WAIT FOR GATEWAY (HTTP health check, max 90 s)# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββecho "[boot] β³ Waiting for gateway on :8642..."for i in $(seq 1 45); doif nc -z 127.0.0.1 8642 2>/dev/null; then# Extra HTTP health checkif curl -sf http://127.0.0.1:8642/health > /dev/null 2>&1 || \curl -sf http://127.0.0.1:8642/ > /dev/null 2>&1; thenecho "[boot] β Gateway HTTP health OK! (${i}Γ2 s)"elseecho "[boot] β Gateway TCP up (${i}Γ2 s)"fibreakfiif [ "$i" -eq 45 ]; thenecho "[boot] β οΈ Gateway timeout β last log:"tail -20 "$HH/logs/gateway.log" 2>/dev/null || truefisleep 2done# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 10 β START HERMES DASHBOARD on :9119# βββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββββecho "[boot] ποΈ Starting Hermes Dashboard on :9119..."hermes dashboard \4 unmodified lines> "$HH/logs/dashboard.log" 2>&1 &echo "[boot] Dashboard PID: $!"# Wait for dashboard to bind (max 40 s) β prevents "starting" pageecho "[boot] β³ Waiting for dashboard on :9119..."for i in $(seq 1 20); doif nc -z 127.0.0.1 9119 2>/dev/null; thenecho "[boot] β Dashboard up! (${i}Γ2 s)"; breakfiif [ "$i" -eq 20 ]; thenecho "[boot] β οΈ Dashboard timeout β check $HH/logs/dashboard.log"tail -10 "$HH/logs/dashboard.log" 2>/dev/null || truefisleep 2done# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 11 β START WEBUI on :8787 (optional, falls back to dashboard)# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif [ -d "/opt/hermes-webui" ] && [ -f "/opt/hermes-webui/server.py" ]; thenecho "[boot] π Starting WebUI on :8787..."cd /opt/hermes-webuiHERMES_WEBUI_AGENT_DIR=/opt/hermes \HERMES_API_KEY="${API_SERVER_KEY:-local-dev-key}" \WEBUI_PORT=8787 PORT=8787 WEBUI_HOST=127.0.0.1 \python3 server.py > "$HH/logs/webui.log" 2>&1 &elseecho "[boot] βΉ No WebUI at /opt/hermes-webui β using Dashboard as chat UI"fi# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 12 β BACKGROUND BUCKET SYNC every 300 s# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif [ -n "${HF_TOKEN:-}" ] && [ -n "${HF_BUCKET:-}" ]; thenecho "[boot] π Bucket sync β every 300 s to hf://buckets/${HF_BUCKET}"(while true; dosleep 300echo "[sync] β¬ Uploading /data β hf://buckets/${HF_BUCKET}..."$VENV_PY - << 'PYEOF' 2>&1 | tail -4 || trueimport os, shutil, globfrom huggingface_hub import sync_bucket, create_buckettok = os.environ["HF_TOKEN"]bucket = os.environ["HF_BUCKET"]home = os.environ.get("HERMES_HOME", "/data")# Remove temp/log dirs before upload so they don't accumulate in bucketfor d in ["logs",".cache","__pycache__"]:p = os.path.join(home, d)if os.path.isdir(p): shutil.rmtree(p, ignore_errors=True)for f in glob.glob(os.path.join(home,"**","*.log"), recursive=True):try: os.remove(f)except: passcreate_bucket(bucket, private=True, exist_ok=True, token=tok)sync_bucket(home, f"hf://buckets/{bucket}", token=tok)print("[sync] β OK")3 unmodified linesfi# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# DONE β show worker URL if available# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββecho ""echo "[boot] π All services started!"echo "[boot] Space URL: https://${SPACE_HOST:-your-space.hf.space}"echo "[boot] Dashboard: https://${SPACE_HOST:-your-space.hf.space}/dashboard"WORKER_URL_FILE="$HH/cf_worker_url.txt"if [ -f "$WORKER_URL_FILE" ]; thenWU=$(cat "$WORKER_URL_FILE")echo "[boot] CF Worker: $WU"echo "[boot] Telegram: $WU/telegram"echo "[boot] Discord: $WU/discord"fiecho ""wait $ROUTER_PID13 unmodified linesr'(conn\.execute\(["\']ALTER TABLE \w+ ADD COLUMN [^)]+\)["\'][ \t]*\))',r'try:\n \1 # hf-idempotent\n except Exception:\n pass', src)if new != src: p.write_text(new); print("kanban patch applied")else: print("pattern not found β OK")PYPATCH# ββ Symlinks + ownership ββββββββββββββββββββββββββββββββββββββ# /home/hermes/.hermes β /data (Hermes CLI home dir)# /opt/data β /data (HERMES_HOME env var target)RUN mkdir -p /data /data/logs /data/skills \&& mkdir -p /home/hermes \&& rm -rf /home/hermes/.hermes && ln -sf /data /home/hermes/.hermes \&& rm -rf /opt/data && ln -sf /data /opt/data \&& chown -R hermes:hermes \/data /home/hermes \/opt/hermes /opt/router /opt/start.sh \/opt/worker.js /opt/deploy_worker.py \&& chown -h hermes:hermes /home/hermes/.hermes /opt/data \&& chmod 750 /dataENV HERMES_HOME=/data \HERMES_WEBUI_AGENT_DIR=/opt/hermes \PYTHONUNBUFFERED=1 \PORT=7860 \HF_HUB_ENABLE_HF_TRANSFER=1 \SHELL=/bin/bashEXPOSE 7860123456789101112131415161718192021222324252627282 unmodified lines3132333435363738394041424344454647484950516 unmodified lines5859606162636465666768697 unmodified lines77787980818283848586871 unmodified line89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042053 unmodified lines2092102112122132142152162172182192202212222232242252262272282292302311 unmodified line23323423523623723823917 unmodified lines2572582592602612622632642652662675 unmodified lines2732742752762772782792802812822832842852862872882892 unmodified lines2922932942952962972986 unmodified lines3053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443459 unmodified lines3553563573583593603613623631 unmodified line3653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994001 unmodified line4024034044054064074084097 unmodified lines4174184194204214224234244254264274284294304314324334344354364374384394404414424434445 unmodified lines4504514524534544554564 unmodified lines4614624634644654664672 unmodified lines4704714724734744754764774781 unmodified line48048148248348448548613 unmodified lines5005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775783 unmodified lines5825835845855865875885895905915925935945955965975985996004 unmodified lines6056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506513 unmodified lines65565665765865966066166266366466566666766866967067113 unmodified lines685686687688689690691692693694695696697698699700701702703704705706707708709710711712713# ============================================================# Hermes Agent β HF Spaces v9 (fast startup)## KEY FIXES vs v8:# 1. HF_XET_HIGH_PERFORMANCE=1 (replaces deprecated HF_HUB_ENABLE_HF_TRANSFER)# 2. Bucket restore is ASYNC β services start in ~15s regardless of bucket size# Config/keys always come from Space secrets (fast), not the bucket.# Sessions/memory restore in background while app is already running.# 3. WebUI removed (nesquena/hermes-webui doesn't exist) β dashboard is the UI# 4. Router simplified: all non-API traffic β Dashboard (:9119)# 5. Bucket backup cleans logs+cache+venv before upload so bucket stays lean## REQUIRED SECRETS:# GATEWAY_TOKEN your login password# OPENROUTER_API_KEY from openrouter.ai β recommended# OR ANTHROPIC_API_KEY / OPENAI_API_KEY# HF_TOKEN HF write token# HF_BUCKET e.g. Sanyam400/Hermes-storage## OPTIONAL β Cloudflare Worker (Telegram/Discord proxy + keep-alive):# CLOUDFLARE_ACCOUNT_ID from dash.cloudflare.com# CLOUDFLARE_WORKERS_TOKEN CF API token (Workers Scripts:Edit)# CF_WORKER_NAME default: hermes-gateway# TELEGRAM_BOT_TOKEN auto-sets webhook to CF Worker# TELEGRAM_ALLOWED_USERS your numeric Telegram user ID# ============================================================FROM nousresearch/hermes-agent:latest2 unmodified lines# ββ System deps βββββββββββββββββββββββββββββββββββββββββββββββRUN apt-get update && apt-get install -y --no-install-recommends \ca-certificates curl jq git nodejs npm python3 \netcat-openbsd tar gzip dnsutils sudo bash \&& rm -rf /var/lib/apt/lists/*RUN uv pip install --python /opt/hermes/.venv/bin/python \--no-cache-dir "huggingface_hub>=1.5.0" pyyaml# hf CLI (bucket sync)RUN curl -LsSf https://hf.co/cli/install.sh | bash \&& ( mv /root/.local/bin/hf /usr/local/bin/hf 2>/dev/null \|| find /root -name 'hf' -type f 2>/dev/null | head -1 \| xargs -I{} cp {} /usr/local/bin/hf 2>/dev/null || true ) \&& chmod +x /usr/local/bin/hf 2>/dev/null || true# Full terminal + sudo access for hermes userRUN usermod -aG sudo hermes \&& echo "hermes ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers \&& chsh -s /bin/bash hermes6 unmodified lines# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# CLOUDFLARE WORKER SCRIPT# Proxies Telegram/Discord/Slack β HF Space with Bearer auth.# Deployed automatically if CF secrets are set.# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββRUN cat > /opt/worker.js << 'ENDWORKER'// Hermes Gateway β Cloudflare Worker v9// Proxies inbound platform webhooks to your HF Space with Bearer auth.var ROUTES = {'/telegram': '/tg',7 unmodified lines});async function handleRequest(request) {var url = new URL(request.url);var path = url.pathname;var HERMES = (typeof HERMES_URL !== 'undefined' ? HERMES_URL : '').replace(/\/$/, '');var TOKEN = (typeof GATEWAY_TOKEN !== 'undefined') ? GATEWAY_TOKEN : '';if (path === '/health' || path === '/') {return new Response(JSON.stringify({ ok: true, worker: 'hermes-cf-proxy', hermes: HERMES }),1 unmodified line);}if (request.method !== 'POST') {return new Response('Method Not Allowed', { status: 405 });}var suffix = ROUTES[path] || ('/webhooks' + path);var target = HERMES + suffix;var body = await request.arrayBuffer();try {var resp = await fetch(target, {method: 'POST',headers: {'Content-Type': request.headers.get('Content-Type') || 'application/json','Authorization': 'Bearer ' + TOKEN,'X-CF-Worker': 'hermes-proxy','X-Original-Path': path,},body: body,});var text = await resp.text();return new Response(text, {status: resp.status,headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },});} catch(e) {return new Response(JSON.stringify({ error: 'Hermes unreachable', detail: e.message }),{ status: 502, headers: { 'Content-Type': 'application/json' } });}}ENDWORKER# ββ CF Worker deploy script βββββββββββββββββββββββββββββββββββRUN cat > /opt/deploy_worker.py << 'ENDPY'#!/usr/bin/env python3"""Auto-deploys Cloudflare Worker and sets Telegram webhook."""import os, sys, json, urllib.request, urllib.parseACCOUNT_ID = os.environ.get("CLOUDFLARE_ACCOUNT_ID","").strip()CF_TOKEN = os.environ.get("CLOUDFLARE_WORKERS_TOKEN","").strip()WORKER_NAME = os.environ.get("CF_WORKER_NAME","hermes-gateway").strip()SPACE_HOST = os.environ.get("SPACE_HOST","").strip()GATEWAY_TOKEN = os.environ.get("GATEWAY_TOKEN","").strip()TG_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN","").strip()if not ACCOUNT_ID or not CF_TOKEN:print("[worker] CF credentials not set β skipping"); sys.exit(0)HERMES_URL = f"https://{SPACE_HOST}" if SPACE_HOST else os.environ.get("HERMES_SPACE_URL","").strip()if not HERMES_URL:print("[worker] β SPACE_HOST not set β cannot determine Hermes URL"); sys.exit(1)BASE = f"https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/workers"HDR = {"Authorization": f"Bearer {CF_TOKEN}"}def req(method, url, data=None, ct="application/json"):r = urllib.request.Request(url, method=method, headers={**HDR,"Content-Type":ct})if data is not None:r.data = data if isinstance(data,bytes) else json.dumps(data).encode()try:with urllib.request.urlopen(r, timeout=20) as res:return json.loads(res.read())except urllib.error.HTTPError as e:return json.loads(e.read())print(f"[worker] π€ Deploying '{WORKER_NAME}'...")with open("/opt/worker.js","rb") as f: script = f.read()res = req("PUT", f"{BASE}/scripts/{WORKER_NAME}", data=script, ct="application/javascript")if not res.get("success"):print(f"[worker] β Upload failed: {res.get('errors')}"); sys.exit(1)print("[worker] β Script uploaded")for key, val in [("HERMES_URL", HERMES_URL), ("GATEWAY_TOKEN", GATEWAY_TOKEN)]:r = req("PUT", f"{BASE}/scripts/{WORKER_NAME}/secrets",data={"name":key,"text":val,"type":"secret_text"})print(f"[worker] {'β ' if r.get('success') else 'β '} Secret {key}")sub = req("GET", f"{BASE}/subdomain").get("result",{}).get("subdomain","")if not sub:print("[worker] β Could not get workers.dev subdomain"); sys.exit(1)WORKER_URL = f"https://{WORKER_NAME}.{sub}.workers.dev"print(f"[worker] π Worker: {WORKER_URL}")os.makedirs(os.environ.get("HERMES_HOME","/data"), exist_ok=True)with open(os.path.join(os.environ.get("HERMES_HOME","/data"),"cf_worker_url.txt"),"w") as f:f.write(WORKER_URL)if TG_TOKEN:print(f"[worker] π€ Setting Telegram webhook β {WORKER_URL}/telegram")try:tg = urllib.request.Request(f"https://api.telegram.org/bot{TG_TOKEN}/setWebhook",method="POST",data=urllib.parse.urlencode({"url":f"{WORKER_URL}/telegram"}).encode(),headers={"Content-Type":"application/x-www-form-urlencoded"},)with urllib.request.urlopen(tg, timeout=10) as r:res = json.loads(r.read())print(f"[worker] {'β Webhook set' if res.get('ok') else 'β '+res.get('description','')}")except Exception as e:print(f"[worker] β {e}")print(f"[worker] Telegram: {WORKER_URL}/telegram")print(f"[worker] Discord: {WORKER_URL}/discord")print(f"[worker] Slack: {WORKER_URL}/slack")ENDPY# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# ROUTER β single entry point on port 7860# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββRUN cat > /opt/router/server.js << 'ENDJS''use strict';3 unmodified linesvar PORT = parseInt(process.env.PORT || '7860', 10);var GATEWAY_TOKEN = process.env.GATEWAY_TOKEN || '';// All known dashboard paths (everything else β dashboard too)var DASHBOARD_PATHS = ['/dashboard','/skills','/plugins','/mcp','/webhooks','/pairing','/profiles','/config','/keys','/system','/cron','/models','/logs','/env','/sessions','/channels','/documentation','/docs','/openapi.json'];// Paths that go directly to the gateway REST APIvar GATEWAY_PATHS = ['/v1','/tg','/discord-wh','/slack-wh','/whatsapp-wh'];// FIX: always use split('?')[0] so pathname is a STRING not an arrayfunction pn(url) {return (url || '/').split('?')[0].split('#')[0] || '/';}function isDashboard(p) {for (var i = 0; i < DASHBOARD_PATHS.length; i++) {var d = DASHBOARD_PATHS[i];if (p === d || p.indexOf(d + '/') === 0) return true;1 unmodified linereturn false;}function isGateway(p) {for (var i = 0; i < GATEWAY_PATHS.length; i++) {var g = GATEWAY_PATHS[i];if (p === g || p.indexOf(g + '/') === 0) return true;17 unmodified linesif (c['hm_tok'] && decodeURIComponent(c['hm_tok']) === GATEWAY_TOKEN) return true;var auth = req.headers['authorization'] || '';if (auth === 'Bearer ' + GATEWAY_TOKEN) return true;// CF Worker requests are pre-authenticatedif (req.headers['x-cf-worker'] === 'hermes-proxy') return true;return false;}proxy.on('error', function(err, req, res) {if (res && res.socket && !res.headersSent) {res.writeHead(502, { 'Content-Type': 'text/html; charset=utf-8' });5 unmodified lines'display:flex;align-items:center;justify-content:center;min-height:100vh}' +'.c{text-align:center}.spin{font-size:3rem;animation:s 1.2s linear infinite}' +'@keyframes s{to{transform:rotate(360deg)}}' +'h2{margin:.6rem 0 .3rem}small{color:#686c7a;font-size:.85rem}' +'</style></head><body>' +'<div class="c"><div class="spin">βοΈ</div>' +'<h2>Hermes is startingβ¦</h2>' +'<small>Refreshing in 5 s</small>' +'</div></body></html>');}});function loginPage(err) {return '<!DOCTYPE html><html lang="en"><head>' +'<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">' +'<title>Hermes β Sign in</title>' +2 unmodified lines'display:flex;align-items:center;justify-content:center;min-height:100vh}' +'.card{background:#161920;border:1px solid #252830;border-radius:18px;' +'padding:2.5rem 2rem;width:100%;max-width:400px}' +'h1{font-size:1.4rem;margin:.4rem 0 .15rem}' +'.sub{color:#5a5e6b;font-size:.875rem;margin-bottom:1.6rem}' +'label{display:block;font-size:.8rem;color:#8a8e9b;margin-bottom:.35rem}' +'input{width:100%;padding:.75rem 1rem;background:#0d0f14;border:1px solid #2a2d38;' +6 unmodified lines'color:#f87171;border-radius:7px;padding:.55rem .9rem;font-size:.85rem;margin-bottom:1rem}' +'.note{font-size:.73rem;color:#3a3d4a;margin-top:.9rem;text-align:center}' +'</style></head><body><div class="card">' +'<div style="font-size:2.5rem;margin-bottom:.3rem">πͺ½</div>' +'<h1>Hermes Agent</h1>' +'<p class="sub">Enter your gateway token to continue.</p>' +(err ? '<div class="err">β ' + err + '</div>' : '') +'<form method="POST" action="/_login">' +'<label for="t">Gateway Token</label>' +'<input id="t" type="password" name="token" placeholder="Your GATEWAY_TOKEN" autofocus/>' +'<button type="submit">Sign in β</button>' +'</form>' +'<p class="note">Set GATEWAY_TOKEN in Space secrets to change this.</p>' +'</div></body></html>';}var server = http.createServer(function(req, res) {var path = pn(req.url);// Public β no authif (path === '/health' || path === '/health/') {res.writeHead(200, { 'Content-Type': 'application/json' });return res.end(JSON.stringify({ ok: true, ts: new Date().toISOString() }));}// Login page (/_login avoids HF intercepting /login)if (path === '/_login') {if (req.method === 'POST') {var body = '';req.on('data', function(d) { body += d; });req.on('end', function() {var tok = new URLSearchParams(body).get('token') || '';if (!GATEWAY_TOKEN || tok === GATEWAY_TOKEN) {var isHttps = req.headers['x-forwarded-proto'] === 'https';res.writeHead(302, {'Set-Cookie': 'hm_tok=' + encodeURIComponent(tok) +'; Path=/; HttpOnly' +(isHttps ? '; Secure; SameSite=None' : '; SameSite=Lax'),'Location': '/'});return res.end();9 unmodified lines// Auth gateif (!authed(req)) {if (path.indexOf('/v1/') === 0 || path.indexOf('/api/') === 0 ||path.indexOf('/assets/') === 0 || path.indexOf('/static/') === 0 ||isGateway(path)) {res.writeHead(401, { 'Content-Type': 'application/json' });return res.end(JSON.stringify({ error: 'Unauthorized' }));}1 unmodified linereturn res.end();}// Gateway APIif (isGateway(path)) {return proxy.web(req, res, { target: 'http://127.0.0.1:8642' });}// Dashboard pathsif (isDashboard(path)) {return proxy.web(req, res, { target: 'http://127.0.0.1:9119', changeOrigin: true });}// Check referer for dashboard sub-requests (assets, API calls made from dashboard pages)var refPath = pn((req.headers.referer || '').replace(/^https?:\/\/[^\/]+/, ''));if (isDashboard(refPath)) {return proxy.web(req, res, { target: 'http://127.0.0.1:9119', changeOrigin: true });}// Default: everything goes to dashboard (no separate WebUI)proxy.web(req, res, { target: 'http://127.0.0.1:9119', changeOrigin: true });});// WebSocketserver.on('upgrade', function(req, socket, head) {if (!authed(req)) { socket.destroy(); return; }var path = pn(req.url || '/');var refPath = pn((req.headers.referer || '').replace(/^https?:\/\/[^\/]+/, ''));var target = isGateway(path) ? 'http://127.0.0.1:8642' : 'http://127.0.0.1:9119';proxy.ws(req, socket, head, { target: target, changeOrigin: target.indexOf('9119') >= 0 });});// Keep-alive: self-ping every 20 min to prevent HF 48h auto-pausesetInterval(function() {http.get('http://127.0.0.1:' + PORT + '/health', function(r) { r.resume(); }).on('error', function(){});1 unmodified lineserver.listen(PORT, '0.0.0.0', function() {console.log('[router] β Listening on 0.0.0.0:' + PORT);console.log('[router] /v1/* /tg /discord-wh β Gateway (:8642)');console.log('[router] everything else β Dashboard (:9119)');});ENDJS7 unmodified linesVENV_PY="/opt/hermes/.venv/bin/python3"HH="${HERMES_HOME:-/data}"mkdir -p "$HH" "$HH/logs"HERMES_URL="https://${SPACE_HOST:-localhost}"echo ""echo "ββββββββββββββββββββββββββββββββββββββββββββ"echo "β Hermes Agent v9 β HF Spaces boot β"echo "ββββββββββββββββββββββββββββββββββββββββββββ"echo ""# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 1 β ROUTER on :7860 (IMMEDIATE)# HF kills the Space with 503 if port 7860 doesn't respond fast.# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββecho "[boot] π Starting router on :${PORT:-7860}..."node /opt/router/server.js &ROUTER_PID=$!sleep 1echo "[boot] Router up β "# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 2 β WRITE CONFIG + KEYS (from Space secrets, not bucket)# Done BEFORE bucket restore so services can start immediately.# Bucket only restores sessions/memory which are not critical for startup.# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββecho "[boot] π Writing .env..."ENV_FILE="$HH/.env"5 unmodified lines[ -z "$v" ] && returnsed -i "/^${k}=/d" "$TMP" 2>/dev/null || trueecho "${k}=${v}" >> "$TMP"echo " β Set ${k}"}upsert OPENROUTER_API_KEY "${OPENROUTER_API_KEY:-}"4 unmodified linesupsert API_SERVER_KEY "${API_SERVER_KEY:-}"if [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; thenupsert TELEGRAM_BOT_TOKEN "$TELEGRAM_BOT_TOKEN"TUSERS="${TELEGRAM_ALLOWED_USERS:-}"[[ -n "$TUSERS" && ! "$TUSERS" =~ ^\[.*\]$ ]] && TUSERS="[$TUSERS]"[ -n "$TUSERS" ] && upsert TELEGRAM_ALLOWED_USERS "$TUSERS"2 unmodified linesmv "$TMP" "$ENV_FILE"chmod 600 "$ENV_FILE"echo "[boot] βοΈ Writing config.yaml..."CFG="$HH/config.yaml"if [ ! -f "$CFG" ]; thenif [ -n "${OPENROUTER_API_KEY:-}" ]; then PROVIDER="openrouter"elif [ -n "${ANTHROPIC_API_KEY:-}" ]; then PROVIDER="anthropic"elif [ -n "${OPENAI_API_KEY:-}" ]; then PROVIDER="openai"1 unmodified lineelse PROVIDER="auto"; fiMODEL="${HERMES_MODEL:-openai/gpt-4o-mini}"cat > "$CFG" << YAML# Hermes config β auto-written by HF Spaces boot v9model:provider: ${PROVIDER}default: "${MODEL}"13 unmodified linesfi# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 3 β BUCKET RESTORE (ASYNC β runs in background)# WHY ASYNC: bucket can have thousands of session/memory files# which would block startup for minutes. Config+keys are already# written from secrets so services start immediately.# Sessions/memory will be available once background restore finishes.# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif [ -n "${HF_TOKEN:-}" ] && [ -n "${HF_BUCKET:-}" ]; thenecho "[boot] π¦ Async restore β hf://buckets/${HF_BUCKET} (background)"($VENV_PY - << 'PYEOF' 2>&1 | grep -v 'FutureWarning\|is not used anymore\|HF_HUB_ENABLE\|warnings.warn\|site-packages' || trueimport os, systry:from huggingface_hub import sync_bucket, create_buckettok = os.environ["HF_TOKEN"]bucket = os.environ["HF_BUCKET"]home = os.environ.get("HERMES_HOME","/data")create_bucket(bucket, private=True, exist_ok=True, token=tok)sync_bucket(f"hf://buckets/{bucket}", home, token=tok)print("[restore] β Bucket restore complete")except Exception as e:print(f"[restore] β {e}")PYEOF) &RESTORE_PID=$!echo "[boot] Restore running in background (PID $RESTORE_PID)"fi# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 4 β SQLITE WAL MODE# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ$VENV_PY - 2>/dev/null << 'PYEOF' || trueimport os, sqlite3home = os.environ.get("HERMES_HOME","/data")if not os.path.isdir(home): exit()for f in os.listdir(home):if not f.endswith(".db"): continuep = os.path.join(home, f)try:c = sqlite3.connect(p)if c.execute("PRAGMA integrity_check").fetchone()[0] == "ok":c.execute("PRAGMA journal_mode=WAL")c.execute("PRAGMA synchronous=NORMAL")c.commit()print(f"[boot] WAL: {f}")c.close()except Exception as e:print(f"[boot] DB reset ({f}): {e}")for s in ["","-wal","-shm","-journal"]:try: os.remove(p+(s if s else ""))except: passPYEOF# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 5 β SEED SKILLS# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfor src in /opt/hermes/skills /opt/hermes/hermes_cli/skills /opt/hermes/hermes/skills; do[ -d "$src" ] && mkdir -p "$HH/skills" && cp -rn "$src"/* "$HH/skills/" 2>/dev/null || truedone[ -d "$HH/skills" ] && echo "[boot] Skills seeded"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 6 β DEPLOY CLOUDFLARE WORKER (if credentials set)# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif [ -n "${CLOUDFLARE_ACCOUNT_ID:-}" ] && [ -n "${CLOUDFLARE_WORKERS_TOKEN:-}" ]; thenecho "[boot] βοΈ Deploying Cloudflare Worker..."$VENV_PY /opt/deploy_worker.py 2>&1 | grep -v 'FutureWarning\|warnings' \| tee -a "$HH/logs/cf_workers.log" || trueelseecho "[boot] βΉ CF secrets not set β Telegram uses long-polling mode"fi# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 7 β START GATEWAY on :8642# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββecho "[boot] π Starting Hermes Gateway on :8642..."API_SERVER_ENABLED=true \3 unmodified linesecho "[boot] Gateway PID: $!"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 8 β WAIT FOR GATEWAY (max 90 s)# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββecho "[boot] β³ Waiting for gateway on :8642..."for i in $(seq 1 45); doif nc -z 127.0.0.1 8642 2>/dev/null; thenecho "[boot] β Gateway up! (${i}Γ2 s)"; breakfi[ "$i" -eq 45 ] && { echo "[boot] β Gateway timeout"; tail -20 "$HH/logs/gateway.log" 2>/dev/null; }sleep 2done# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 9 β START DASHBOARD on :9119# βββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββββecho "[boot] ποΈ Starting Hermes Dashboard on :9119..."hermes dashboard \4 unmodified lines> "$HH/logs/dashboard.log" 2>&1 &echo "[boot] Dashboard PID: $!"# Wait for dashboard to bind (max 40 s) β prevents "starting" flashecho "[boot] β³ Waiting for dashboard on :9119..."for i in $(seq 1 20); doif nc -z 127.0.0.1 9119 2>/dev/null; thenecho "[boot] β Dashboard up! (${i}Γ2 s)"; breakfi[ "$i" -eq 20 ] && { echo "[boot] β Dashboard timeout"; tail -10 "$HH/logs/dashboard.log" 2>/dev/null; }sleep 2done# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STEP 10 β BUCKET SYNC every 300 s (background)# Cleans logs/cache before upload so bucket stays lean.# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif [ -n "${HF_TOKEN:-}" ] && [ -n "${HF_BUCKET:-}" ]; thenecho "[boot] π Bucket sync every 300 s β hf://buckets/${HF_BUCKET}"(while true; dosleep 300echo "[sync] β¬ Uploading /data β hf://buckets/${HF_BUCKET}..."$VENV_PY - << 'PYEOF' 2>&1 | grep -v 'FutureWarning\|is not used anymore\|warnings.warn\|site-packages' | tail -5 || trueimport os, shutil, globfrom huggingface_hub import sync_bucket, create_buckettok = os.environ["HF_TOKEN"]bucket = os.environ["HF_BUCKET"]home = os.environ.get("HERMES_HOME","/data")# Clean junk BEFORE upload so it's also removed from bucket (sync deletes non-local files)for d in ["logs",".cache","__pycache__",".venv","node_modules"]:p = os.path.join(home, d)if os.path.isdir(p): shutil.rmtree(p, ignore_errors=True)for f in glob.glob(os.path.join(home,"**","*.log"), recursive=True):try: os.remove(f)except: passfor f in glob.glob(os.path.join(home,"**","*.pyc"), recursive=True):try: os.remove(f)except: passfor f in glob.glob(os.path.join(home,"**","*.tmp"), recursive=True):try: os.remove(f)except: passcreate_bucket(bucket, private=True, exist_ok=True, token=tok)sync_bucket(home, f"hf://buckets/{bucket}", token=tok)print("[sync] β OK")3 unmodified linesfi# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# DONE# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββecho ""echo "[boot] π All services up!"echo "[boot] Space: https://${SPACE_HOST:-your-space.hf.space}"echo "[boot] Dashboard: https://${SPACE_HOST:-your-space.hf.space}/dashboard"[ -f "$HH/cf_worker_url.txt" ] && {WU=$(cat "$HH/cf_worker_url.txt")echo "[boot] CF Worker: $WU"echo "[boot] Telegram: $WU/telegram"}echo ""wait $ROUTER_PID13 unmodified linesr'(conn\.execute\(["\']ALTER TABLE \w+ ADD COLUMN [^)]+\)["\'][ \t]*\))',r'try:\n \1 # hf-idempotent\n except Exception:\n pass', src)if new != src: p.write_text(new); print("patch applied")else: print("pattern not found β OK")PYPATCH# ββ Symlinks + ownership ββββββββββββββββββββββββββββββββββββββ# /home/hermes/.hermes β /data (Hermes reads ~/.hermes/ for all data)# /opt/data β /data (HERMES_HOME target)RUN mkdir -p /data /data/logs /data/skills \&& mkdir -p /home/hermes \&& rm -rf /home/hermes/.hermes && ln -sf /data /home/hermes/.hermes \&& rm -rf /opt/data && ln -sf /data /opt/data \&& chown -R hermes:hermes \/data /home/hermes /opt/hermes \/opt/router /opt/start.sh /opt/worker.js /opt/deploy_worker.py \&& chown -h hermes:hermes /home/hermes/.hermes /opt/data \&& chmod 750 /data# HF_XET_HIGH_PERFORMANCE replaces deprecated HF_HUB_ENABLE_HF_TRANSFERENV HERMES_HOME=/data \PYTHONUNBUFFERED=1 \PORT=7860 \SHELL=/bin/bash \HF_XET_HIGH_PERFORMANCE=1EXPOSE 7860
Dockerfile+242-349