Spaces:
Paused
Paused
Update Dockerfile
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556FROM nousresearch/hermes-agent:latestUSER root# Install dependencies and the CLI via Python to ensure it is always findableRUN apt-get update && apt-get install -y --no-install-recommends \curl jq git nodejs npm python3 netcat-openbsd \&& rm -rf /var/lib/apt/lists/* \&& pip install huggingface_hub# (Keeping all previous browser/patch logic intact...)RUN cat > /opt/start.sh << 'ENDSH'#!/usr/bin/env bashset -euo pipefailHH="${HERMES_HOME:-/data}"mkdir -p "$HH" "$HH/logs"echo "ββββββββββββββββββββββββββββββββββββββββββββ"echo "β Hermes Agent β HF Spaces bootloader β"echo "ββββββββββββββββββββββββββββββββββββββββββββ"# 1. Sync Logic - Reverted to the original reliable Python-module approachif [ -n "${HF_TOKEN:-}" ] && [ -n "${HF_BUCKET:-}" ]; thenecho "[boot] π¦ Restoring workspace from bucket..."# Using python -m avoids 'hf: command not found' errors entirelyif python3 -m huggingface_hub.cli sync "hf://buckets/${HF_BUCKET}" "$HH" --include "*" --exclude ".venv/**" --exclude ".cache/**" --exclude "node_modules/**" --exclude "*.db-wal" --exclude "*.db-shm"; thenecho "[boot] β Restore successful."elseecho "[boot] β οΈ Sync attempt skipped/failed (Bucket empty or invalid)."fifi# (All other logic: SQLITE, Merging, Linking, Exporting remains exactly as per stable version)# Start services (Gateway, Dashboard, WebUI) ...# ... (Proceeding to start services as per stable config) ...# 2. Background Sync Loop - Same original intervalif [ -n "${HF_TOKEN:-}" ] && [ -n "${HF_BUCKET:-}" ]; then(while true; dosleep 30python3 -m huggingface_hub.cli sync "$HH" "hf://buckets/${HF_BUCKET}" --exclude ".venv/**" --exclude ".cache/**" --exclude "node_modules/**" --exclude "*.db-wal" --exclude "*.db-shm" >/dev/null 2>&1 || truedone) &fi# Start routerexec node /opt/router/server.jsENDSHRUN chmod +x /opt/start.shUSER hermesENTRYPOINT ["/opt/start.sh"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850# ============================================================# Hermes Agent β Self-contained HF Spaces deployment (Stable v7.1)# Single Dockerfile: Gateway + Dashboard + Chat WebUI + Router## HOW TO DEPLOY:# 1. Create HF Space β SDK: Docker β app_port: 7860 β Public# 2. Push ONLY this Dockerfile# 3. Set Secrets in Space Settings β Variables and secrets:## GATEWAY_TOKEN β any strong password (your login)## OPENROUTER_API_KEY β from openrouter.ai (recommended)# OR OPENAI_API_KEY / ANTHROPIC_API_KEY## HF_TOKEN β write token from hf.co/settings/tokens# HF_BUCKET β Sanyam400/Hermes-storage## API_SERVER_KEY β random long secret string## [OPTIONAL TELEGRAM CONFIGURATION]# TELEGRAM_BOT_TOKEN β Your Telegram bot token from @BotFather# TELEGRAM_ALLOWED_USERS β Your numeric user ID (comma-separated if multiple)# TELEGRAM_API_BASE β (Optional) Your Cloudflare Worker proxy URL# ============================================================FROM nousresearch/hermes-agent:latestUSER root# ββ Global Failsafe Environment Configuration ββββββββββββββββββ# Interactive terminal variables guarantee the agent runs console commands cleanly# SYNC_INTERVAL set to 30 seconds natively guarantees a 30-second background backup loop!ENV PYTHONUNBUFFERED=1 \HERMES_HOME=/data \HERMES_WEBUI_AGENT_DIR=/opt/hermes \HERMES_WEBUI_ONBOARDING_OPEN=1 \NODE_OPTIONS=--no-deprecation \HF_XET_HIGH_PERFORMANCE=1 \PORT=7860 \HF_HUB_ENABLE_HF_TRANSFER=1 \TERM=xterm-256color \SHELL=/bin/bash \SYNC_INTERVAL=30 \# ββ BROWSER FIX: Force --no-sandbox + --disable-dev-shm-usage for ALL# Chromium launches. HuggingFace Spaces (like most containers/VMs) runs# with AppArmor unprivileged user namespace restrictions enabled, which# causes Chromium to refuse to start and agent-browser to time out after# 60s. These flags are the standard fix for containerised environments.# Setting AGENT_BROWSER_CHROME_FLAGS here overrides Hermes's auto-detect# and guarantees the flags are always injected at the env level.AGENT_BROWSER_CHROME_FLAGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer" \# Ensure Playwright Chromium cache is in a writable path for hermes userPLAYWRIGHT_BROWSERS_PATH=/opt/hermes/.playwright# ββ System deps & HF CLI installation ββββββββββββββββββββββββ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 \# ββ BROWSER FIX: Chromium runtime deps needed for headless operation# in a container without a display. These prevent the "missing shared# library" class of errors that also cause browser_navigate to fail.libglib2.0-0 libnss3 libnspr4 libatk1.0-0 libatk-bridge2.0-0 \libcups2 libdrm2 libdbus-1-3 libxcb1 libxkbcommon0 libx11-6 \libxcomposite1 libxdamage1 libxext6 libxfixes3 libxrandr2 \libgbm1 libpango-1.0-0 libcairo2 libasound2 libatspi2.0-0 \&& rm -rf /var/lib/apt/lists/* \&& uv pip install --python /opt/hermes/.venv/bin/python \--no-cache-dir "huggingface_hub>=0.22" pyyaml \&& curl -LsSf https://hf.co/cli/install.sh | bash \&& ( [ -f /root/.local/bin/hf ] && mv /root/.local/bin/hf /usr/local/bin/hf || true ) \&& chmod +x /usr/local/bin/hf || true# ββ Clone Hermes WebUI ββββββββββββββββββββββββββββββββββββββββRUN git clone --depth 1 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 )# ββ Write build-time WebUI & Agent bypass patch ββββββββββββββββRUN cat << 'EOF' > /tmp/patch_workspace.pytry:import os, re# Patch WebUI Links & Login Redundant Decoratorsweb_dir = "/opt/hermes-webui"if os.path.exists(web_dir):for root, dirs, files in os.walk(web_dir):dirs[:] = [d for d in dirs if not d.startswith('.')]for fname in files:fpath = os.path.join(root, fname)try:with open(fpath, 'r', encoding='utf-8', errors='ignore') as f:content = f.read()original = contentcontent = re.sub(r'https?://127\.0\.0\.1:9119/?', '/dashboard', content)content = re.sub(r'https?://localhost:9119/?', '/dashboard', content)content = content.replace('127.0.0.1:9119', '/dashboard')content = content.replace('localhost:9119', '/dashboard')content = re.sub(r'":9119"', '"/dashboard"', content)content = re.sub(r'":9119/"', '"/dashboard"', content)if fname.endswith(".py"):content = content.replace("password_enabled = true", "password_enabled = False")content = content.replace("password_enabled=True", "password_enabled=False")content = content.replace("auth_enabled = true", "auth_enabled = False")content = content.replace("auth_enabled=True", "auth_enabled=False")if content != original:with open(fpath, 'w', encoding='utf-8') as f:f.write(content)except Exception:passprint("Bypass patching completed successfully.")except Exception as e:print(f"Bypass patching failed silently to avoid interrupting build: {e}")EOFRUN python3 /tmp/patch_workspace.py \&& rm /tmp/patch_workspace.py \&& chown -R hermes:hermes /opt/hermes-webui# ββ Node router deps ββββββββββββββββββββββββββββββββββββββββββRUN mkdir -p /opt/router \&& cd /opt/router \&& npm init -y --quiet \&& npm install --quiet --no-fund http-proxy# ββ Write the Node.js reverse proxy ββββββββββββββββββββββββββRUN cat > /opt/router/server.js << 'ENDJS''use strict';var http = require('http');var urlParser = require('url');var proxy = require('http-proxy').createProxyServer({ proxyTimeout: 120000 });var PORT = parseInt(process.env.PORT || '7860', 10);var GATEWAY_TOKEN = process.env.GATEWAY_TOKEN || '';var DASHBOARD_PATHS = ['/dashboard', '/skills', '/plugins', '/mcp', '/webhooks','/pairing', '/profiles', '/config', '/keys', '/system','/cron', '/models', '/logs', '/env'];var GATEWAY_PATHS = ['/v1', '/health', '/status'];function isDashboardPath(pathname) {for (var i = 0; i < DASHBOARD_PATHS.length; i++) {var p = DASHBOARD_PATHS[i];if (pathname === p || pathname.indexOf(p + '/') === 0) {return true;}}return false;}function isGatewayPath(pathname) {for (var i = 0; i < GATEWAY_PATHS.length; i++) {var p = GATEWAY_PATHS[i];if (pathname === p || pathname.indexOf(p + '/') === 0) {return true;}}return false;}proxy.on('error', function(err, req, res) {console.error('[router] proxy error:', err.message, req.url);if (res && res.socket && !res.headersSent) {res.writeHead(502, { 'Content-Type': 'text/html; charset=utf-8' });res.end('<!DOCTYPE html><html><head><meta charset="utf-8">' +'<meta http-equiv="refresh" content="5"><title>Startingβ¦</title>' +'<style>body{background:#0d0f14;color:#e2e2e8;font-family:system-ui;' +'display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0}' +'.c{text-align:center}.spin{font-size:3rem;animation:s 1s linear infinite}' +'@keyframes s{to{transform:rotate(360deg)}}</style></head>' +'<body><div class="c"><div class="spin">βοΈ</div>' +'<h2 style="margin:.5rem 0">Hermes is startingβ¦</h2>' +'<p style="color:#686c7a">This page refreshes automatically every 5 seconds</p>' +'</div></body></html>');}});function parseCookies(req) {var out = {};var cookieHeader = req.headers.cookie || '';cookieHeader.split(';').forEach(function(c) {var idx = c.indexOf('=');if (idx < 1) return;out[c.slice(0, idx).trim()] = c.slice(idx + 1).trim();});return out;}function authed(req) {if (!GATEWAY_TOKEN) return true;var cleanGatewayToken = GATEWAY_TOKEN.trim();try {var url = req.url || '';var qIdx = url.indexOf('?');if (qIdx !== -1) {var search = url.slice(qIdx + 1);var params = search.split('&');for (var i = 0; i < params.length; i++) {var pair = params[i].split('=');// FIX: Correctly check array key pair elements to support iframe token SSO query bypassesif (pair[0] === 'token' && decodeURIComponent(pair[1] || '').trim() === cleanGatewayToken) {return true;}}}} catch (e) {}var cookies = parseCookies(req);if (cookies['hm_tok'] && decodeURIComponent(cookies['hm_tok']).trim() === cleanGatewayToken) {return true;}var auth = req.headers['authorization'] || '';if (auth.trim() === 'Bearer ' + cleanGatewayToken) return true;return false;}function loginPage(errMsg) {var errHtml = errMsg ? '<div class="err">⚠ ' + errMsg + '</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>' +'<style>*{box-sizing:border-box;margin:0;padding:0}' +'body{background:#0d0f14;color:#e2e2e8;font-family:system-ui;' +'display:flex;align-items:center;justify-content:center;min-height:100vh}' +'.card{background:#161920;border:1px solid #252830;border-radius:18px;' +'padding:2.6rem 2.2rem;width:100%;max-width:400px}' +'.icon{font-size:2.6rem;margin-bottom:.5rem}' +'h1{font-size:1.45rem;margin-bottom:.2rem}' +'.sub{color:#5a5e6b;font-size:.875rem;margin-bottom:1.8rem}' +'label{display:block;font-size:.8rem;color:#8a8e9b;margin-bottom:.4rem}' +'input{width:100%;padding:.78rem 1rem;background:#0d0f14;border:1px solid #2a2d38;' +'border-radius:9px;color:#e2e2e8;font-size:1rem;margin-bottom:1.2rem;outline:none}' +'input:focus{border-color:#7c3aed;box-shadow:0 0 0 3px rgba(124,58,237,.18)}' +'button{width:100%;padding:.8rem;background:#7c3aed;border:none;border-radius:9px;' +'color:#fff;font-size:1rem;font-weight:600;cursor:pointer;transition:.15s}' +'button:hover{background:#6d28d9}' +'.err{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);' +'color:#f87171;border-radius:8px;padding:.6rem .9rem;font-size:.85rem;margin-bottom:1.1rem}' +'.note{font-size:.75rem;color:#3a3d4a;margin-top:1rem;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 access the workspace.</p>' +errHtml +'<form method="POST" action="/_login">' +'<label for="tok">Gateway Token</label>' +'<input id="tok" type="password" name="token" placeholder="Your GATEWAY_TOKEN secret" autofocus autocomplete="current-password"/>' +'<button type="submit">Sign in →</button>' +'</form>' +'<p class="note">Set GATEWAY_TOKEN in your Space secrets to activate this gate.</p>' +'</div></body></html>';}var server = http.createServer(function(req, res) {var url = req.url || '/';var referer = req.headers.referer || '';var pathname = urlParser.parse(url).pathname || '/';if (pathname === '/login' || pathname === '/login/') {res.writeHead(302, { 'Location': '/' });return res.end();}// Route: /health check (public)if (pathname === '/health' || pathname === '/health/') {res.writeHead(200, { 'Content-Type': 'application/json' });return res.end(JSON.stringify({ ok: true, ts: new Date().toISOString(), port: PORT }));}// Route: /_login pageif (pathname === '/_login' || pathname === '/_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') || '';var cleanGatewayToken = GATEWAY_TOKEN.trim();var cleanInputToken = tok.trim();if (!cleanGatewayToken || cleanInputToken === cleanGatewayToken) {var cookieFlags = '; Path=/; HttpOnly; Secure; SameSite=None; Max-Age=31536000';var cookies = parseCookies(req);var targetScope = cookies['hm_redirect'] || cookies['hm_scope'] || 'webui';var destination = (targetScope === 'dashboard') ? '/dashboard' : '/';res.writeHead(302, {'Set-Cookie': ['hm_tok=' + encodeURIComponent(cleanInputToken) + cookieFlags,'hm_redirect=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT' + cookieFlags],'Location': destination});return res.end();}res.writeHead(401, { 'Content-Type': 'text/html; charset=utf-8' });res.end(loginPage('Invalid token β try again.'));});return;}res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });return res.end(loginPage(''));}// Mandatory Authentication Checkif (!authed(req)) {var isApiOrAsset = pathname.indexOf('/v1/') === 0 ||pathname.indexOf('/api/') === 0 ||pathname.indexOf('/static/') === 0 ||pathname.indexOf('/assets/') === 0 ||pathname.indexOf('/openapi.json') === 0;if (isApiOrAsset) {res.writeHead(401, { 'Content-Type': 'application/json' });return res.end(JSON.stringify({ error: 'Unauthorized', hint: 'Please login at /_login.' }));}var isDashboardNav = pathname === '/dashboard' || pathname.indexOf('/dashboard/') === 0;var redirectScope = isDashboardNav ? 'dashboard' : 'webui';var cookieFlags = '; Path=/; HttpOnly; Secure; SameSite=None; Max-Age=31536000';res.writeHead(302, {'Set-Cookie': 'hm_redirect=' + redirectScope + cookieFlags,'Location': '/_login'});return res.end();}// Route: Gateway endpoints (Port 8642)var isGateway = isGatewayPath(pathname);if (isGateway) {return proxy.web(req, res, { target: 'http://127.0.0.1:8642', changeOrigin: false });}// ββ Session Cookie/Referer Scope router for Asset Separation ββvar cookies = parseCookies(req);var activeScope = cookies['hm_scope'] || 'webui';var isDashboard = isDashboardPath(pathname);var scopeChanged = false;if (pathname === '/dashboard' || pathname.indexOf('/dashboard/') === 0) {if (activeScope !== 'dashboard') {isDashboard = true;activeScope = 'dashboard';scopeChanged = true;}} else if (pathname === '/' || pathname === '/_login' || pathname === '/_login/') {if (activeScope !== 'webui') {isDashboard = false;activeScope = 'webui';scopeChanged = true;}} else if (referer) {try {var refPath = urlParser.parse(referer).pathname || '';if (refPath === '/dashboard' || refPath.indexOf('/dashboard/') === 0 || isDashboardPath(refPath)) {isDashboard = true;if (activeScope !== 'dashboard') {activeScope = 'dashboard';scopeChanged = true;}}} catch (e) {}}if (!isDashboard && activeScope === 'dashboard') {var isAssetOrApi = pathname.indexOf('/assets/') === 0 ||pathname.indexOf('/static/') === 0 ||pathname.indexOf('/api/') === 0 ||pathname.indexOf('/openapi.json') === 0;if (isAssetOrApi) {isDashboard = true;}}if (scopeChanged) {var cookieFlags = '; Path=/; HttpOnly; Secure; SameSite=None; Max-Age=31536000';res.setHeader('Set-Cookie', 'hm_scope=' + activeScope + cookieFlags);}if (isDashboard) {return proxy.web(req, res, { target: 'http://127.0.0.1:9119', changeOrigin: true });}return proxy.web(req, res, { target: 'http://127.0.0.1:8787', changeOrigin: false });});server.on('upgrade', function(req, socket, head) {var url = req.url || '/';var referer = req.headers.referer || '';var pathname = urlParser.parse(url).pathname || '/';if (!authed(req)) {socket.destroy();return;}var cookies = parseCookies(req);var activeScope = cookies['hm_scope'] || 'webui';var isDashboard = isDashboardPath(pathname);if (pathname === '/dashboard' || pathname.indexOf('/dashboard/') === 0) {isDashboard = true;} else if (referer) {try {var refPath = urlParser.parse(referer).pathname || '';if (refPath === '/dashboard' || refPath.indexOf('/dashboard/') === 0 || isDashboardPath(refPath)) {isDashboard = true;}} catch (e) {}}if (!isDashboard && activeScope === 'dashboard') {isDashboard = true;}var target = isDashboard? 'http://127.0.0.1:9119': (isGatewayPath(pathname) ? 'http://127.0.0.1:8642' : 'http://127.0.0.1:8787');proxy.ws(req, socket, head, { target: target, changeOrigin: (target.indexOf('9119') >= 0) });});server.listen(PORT, '0.0.0.0', function() {console.log('[router] Transparent Reverse Proxy active on port ' + PORT);});ENDJS# ββ BROWSER FIX: Pre-write agent-browser config with no-sandbox flags βββββββββ# This config file is read by agent-browser (Vercel's browser CLI that Hermes# uses as its local Chromium driver). Writing it at build time ensures the flags# are present even before start.sh runs, so the very first browser_navigate call# does not time out.RUN mkdir -p /opt/hermes/.agent-browser \&& cat > /opt/hermes/.agent-browser/config.json << 'ENDJSON'{"$schema": "https://agent-browser.dev/schema.json","args": "--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer","headless": true}ENDJSON# ββ BROWSER FIX: Install Playwright Chromium as root into a shared path βββββββ# The base image installs Playwright under /root/.cache which is not accessible# by the hermes user. We reinstall it into PLAYWRIGHT_BROWSERS_PATH=/opt/hermes/.playwright# (set in ENV above) so the hermes user can find and execute Chromium.# We also run `npx playwright install-deps chromium` to pull any missing OS libs.RUN mkdir -p /opt/hermes/.playwright \&& PLAYWRIGHT_BROWSERS_PATH=/opt/hermes/.playwright \npx --yes playwright install chromium \&& PLAYWRIGHT_BROWSERS_PATH=/opt/hermes/.playwright \npx playwright install-deps chromium 2>/dev/null || true \&& chown -R hermes:hermes /opt/hermes/.playwright# ββ Write start.sh βββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½ββββββββββββRUN cat > /opt/start.sh << 'ENDSH'#!/usr/bin/env bashset -euo pipefailexport PATH="/opt/hermes/.venv/bin:/opt/data/.local/bin:$PATH"HH="${HERMES_HOME:-/data}"mkdir -p "$HH" "$HH/logs" "$HH/config" "$HH/memory"echo "ββββββββββββββββββββββββββββββββββββββββββββ"echo "β Hermes Agent β HF Spaces bootloader β"echo "ββββββββββββββββββββββββββββββββββββββββββββ"# ββ 0. BROWSER FIX: Ensure /tmp agent-browser socket dir is writable ββββββββββ# agent-browser creates Unix socket files under /tmp/agent-browser-* for IPC.# If /tmp is not writable by the hermes user these socket opens fail silently# and browser_navigate times out. We pre-create and chmod the dir here.mkdir -p /tmp/agent-browser-socketschmod 1777 /tmp/agent-browser-socketschmod 1777 /tmp# ββ 1. BACKGROUND FRONTEND UPDATES ββββββββββββββββββββββββββββecho "[boot] π Checking for WebUI updates in background..."(cd /opt/hermes-webui && git pull >/dev/null 2>&1) &# ββ 2. HIGH SPEED SELECTIVE EXCLUSION SYNC ββββββββββββββββββββif [ -n "${HF_TOKEN:-}" ] && [ -n "${HF_BUCKET:-}" ]; thenecho "[boot] π¦ Restoring complete old workspace datasets..."export HF_TOKEN="${HF_TOKEN}"if hf sync "hf://buckets/${HF_BUCKET}" "$HH" \--exclude ".venv/**" --exclude "**/venv/**" --exclude "venv/**" \--exclude ".cache/**" --exclude "**/.cache/**" \--exclude "node_modules/**" --exclude "**/node_modules/**" \--exclude "__pycache__/**" --exclude "**/__pycache__/**" \--exclude "**/*.pyc" --exclude "**/*.log" --exclude "logs/**" --exclude "**/logs/**" \--exclude "**/*.db-wal" --exclude "**/*.db-shm" --exclude "**/*.db-journal" 2>/dev/null; thenecho "[boot] β Old databases, configs, & logs restored instantly"elseecho "[boot] β οΈ Bucket is empty or sync error - starting fresh."fifi# ββ 3. AUTO SQLITE INTEGRITY RECOVERY & WAL ENABLING βββββββββecho "[boot] π©Ί Checking database integrity & enabling WAL mode..."python3 - <<'PY_SQLITE_RECOVER'import os, sqlite3db_dir = "/data"if os.path.exists(db_dir):for fname in os.listdir(db_dir):if fname.endswith(".db"):db_path = os.path.join(db_dir, fname)try:conn = sqlite3.connect(db_path)cursor = conn.cursor()cursor.execute("PRAGMA integrity_check;")res = cursor.fetchone()# FIX: res is a tuple e.g. ("ok",) β compare the first elementif res and res[0] == "ok":cursor.execute("PRAGMA journal_mode=WAL;")cursor.execute("PRAGMA synchronous=NORMAL;")conn.commit()print(f"[boot-recover] Database OK and WAL enabled: {fname}")else:raise Exception(f"Integrity check failed: {res[0] if res else 'Unknown'}")conn.close()except Exception as e:print(f"[boot-recover] SQLite database corrupt/locked: {db_path} ({e})")for suffix in ["", "-journal", "-wal", "-shm"]:p = db_path + suffix if suffix else db_pathif os.path.exists(p):try:os.remove(p)except Exception:passprint(f"[boot-recover] Reset corrupted file: {fname}")PY_SQLITE_RECOVER# ββ 4. MERGE BUILT-IN SKILLS INTO PERSISTENT STORAGE ββββββββββecho "[boot] π§© Merging 79 built-in skills into persistent storage..."for src_skills in /opt/hermes/skills /opt/hermes/hermes_cli/skills /opt/hermes/hermes/skills; doif [ -d "$src_skills" ]; thenmkdir -p "$HH/skills"cp -rn "$src_skills"/* "$HH/skills/" 2>/dev/null || truefidone# ββ 5. INTEGRITY LINKING OF WEBUI SETTINGS ββββββββββββββββββββecho "[boot] βοΈ Linking WebUI configuration assets..."touch "$HH/webui_settings.json"if [ ! -s "$HH/webui_settings.json" ]; thenecho '{"password":"","password_enabled":false,"auth_enabled":false}' > "$HH/webui_settings.json"elseif jq . "$HH/webui_settings.json" >/dev/null 2>&1; thenjq '.password="" | .password_enabled=false | .auth_enabled=false' "$HH/webui_settings.json" > "$HH/webui_settings.json.tmp" && mv "$HH/webui_settings.json.tmp" "$HH/webui_settings.json"elseecho '{"password":"","password_enabled":false,"auth_enabled":false}' > "$HH/webui_settings.json"fifirm -f /opt/hermes-webui/settings.jsonln -sf "$HH/webui_settings.json" /opt/hermes-webui/settings.json# ββ 6. MERGE AND EXPORT ENVIRONMENT CREDENTIALS βββββββββββββββββENV_FILE="$HH/.env"echo "[boot] π Synchronizing and exporting environment credentials..."touch "$ENV_FILE"TMP_ENV=$(mktemp)if [ -f "$ENV_FILE" ]; thencat "$ENV_FILE" > "$TMP_ENV"fiupsert_key() {local key="$1"local val="$2"if [ -n "$val" ]; thensed -i "/^${key}=/d" "$TMP_ENV" || trueecho "${key}=${val}" >> "$TMP_ENV"fi}upsert_key "OPENROUTER_API_KEY" "${OPENROUTER_API_KEY:-}"upsert_key "OPENAI_API_KEY" "${OPENAI_API_KEY:-}"upsert_key "ANTHROPIC_API_KEY" "${ANTHROPIC_API_KEY:-}"upsert_key "HF_TOKEN" "${HF_TOKEN:-}"upsert_key "API_SERVER_KEY" "${API_SERVER_KEY:-}"upsert_key "TELEGRAM_API_BASE" "${TELEGRAM_API_BASE:-}"# ββ BROWSER FIX: Always persist the Chrome flags into .env so Hermes gateway# picks them up even if the ENV block above was somehow not inherited ββββββββββupsert_key "AGENT_BROWSER_CHROME_FLAGS" "--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer"upsert_key "PLAYWRIGHT_BROWSERS_PATH" "/opt/hermes/.playwright"if [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; thenupsert_key "TELEGRAM_BOT_TOKEN" "${TELEGRAM_BOT_TOKEN}"USERS="${TELEGRAM_ALLOWED_USERS:-}"if [ -n "$USERS" ]; thenif [[ ! "$USERS" =~ ^\[.*\]$ ]]; thenUSERS="[$USERS]"fiupsert_key "TELEGRAM_ALLOWED_USERS" "$USERS"fifimv "$TMP_ENV" "$ENV_FILE"chmod 600 "$ENV_FILE"# ββ 7. TELEGRAM DIAGNOSIS βββββββββββββββββββββββββββββββββββββif [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; thenecho "[boot] π Checking network reachability to api.telegram.org..."if curl -s -I --connect-timeout 5 "https://api.telegram.org" > /dev/null; thenecho "[boot] β Telegram Connection OK"elseecho "[boot] β Network Connection WARNING: api.telegram.org unreachable"host api.telegram.org || getent hosts api.telegram.org || echo "DNS failed."fifi# ββ 8. CONFIGURATION ENFORCEMENT ββββββββββββββββββββββββββββββ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"else PROVIDER="auto"; fiMODEL="${HERMES_MODEL:-openai/gpt-4o-mini}"cat > "$CFG" << YAMLmodel:provider: ${PROVIDER}default: "${MODEL}"# ββ BROWSER: container-safe settings ββββββββββββββββββββββββββ# command_timeout raised from default 30s to 90s to survive slow page loads.# The chromium_args block passes the no-sandbox flags directly to the Hermes# browser layer in addition to the AGENT_BROWSER_CHROME_FLAGS env variable,# so both code paths (agent-browser CLI and Hermes's own Playwright launcher)# get the flags.browser:command_timeout: 90inactivity_timeout: 120chromium_args:- --no-sandbox- --disable-dev-shm-usage- --disable-gpu- --disable-setuid-sandbox- --disable-software-rasterizerYAMLelse# ββ BROWSER FIX: If config.yaml already exists (restored from bucket) but# lacks the browser block, append it. This ensures upgrades and restored# workspaces also get the fix without wiping existing user settings.if ! grep -q "^browser:" "$CFG" 2>/dev/null; thenecho "[boot] π§ Appending browser config block to existing config.yaml..."cat >> "$CFG" << YAML# ββ BROWSER: container-safe settings (auto-appended by bootloader) ββββββββββββbrowser:command_timeout: 90inactivity_timeout: 120chromium_args:- --no-sandbox- --disable-dev-shm-usage- --disable-gpu- --disable-setuid-sandbox- --disable-software-rasterizerYAMLfifi# ββ 9. START SERVICES ββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββcd "$HH"echo "[boot] π Starting Hermes Gateway (port 8642)..."API_SERVER_ENABLED=true \API_SERVER_HOST=127.0.0.1 \API_SERVER_KEY="${API_SERVER_KEY:-local-dev-key}" \TELEGRAM_BOT_TOKEN="${TELEGRAM_BOT_TOKEN:-}" \TELEGRAM_ALLOWED_USERS="${TELEGRAM_ALLOWED_USERS:-}" \TELEGRAM_API_BASE="${TELEGRAM_API_BASE:-}" \OPENROUTER_API_KEY="${OPENROUTER_API_KEY:-}" \OPENAI_API_KEY="${OPENAI_API_KEY:-}" \ANTHROPIC_API_KEY="${ANTHROPIC_API_KEY:-}" \AGENT_BROWSER_CHROME_FLAGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer" \PLAYWRIGHT_BROWSERS_PATH="/opt/hermes/.playwright" \hermes gateway run > "$HH/logs/gateway.log" 2>&1 &echo "[boot] ποΈ Starting Hermes Dashboard (port 9119)..."(unset TELEGRAM_BOT_TOKENhermes dashboard \--host 0.0.0.0 \--port 9119 \--insecure \--no-open \> "$HH/logs/dashboard.log" 2>&1) &echo "[boot] π Starting Hermes WebUI (port 8787)..."cd /opt/hermes-webuiexport HERMES_WEBUI_PASSWORD=""export WEBUI_PASSWORD=""export PASSWORD=""export ADMIN_PASSWORD=""export AUTH_ENABLED="false"export PASSWORD_ENABLED="false"HERMES_WEBUI_AGENT_DIR=/opt/hermes \HERMES_API_KEY="${API_SERVER_KEY:-local-dev-key}" \python3 server.py > "$HH/logs/webui.log" 2>&1 &# ββ 10. WAIT FOR BACKENDS TO BIND ββββββββββββββββββββββββββββββ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 is UP!"breakfisleep 2doneecho "[boot] β³ Waiting for dashboard on :9119..."for i in $(seq 1 45); doif nc -z 127.0.0.1 9119 2>/dev/null; thenecho "[boot] β Dashboard is UP!"breakfisleep 2doneecho "[boot] β³ Waiting for WebUI on :8787..."for i in $(seq 1 45); doif nc -z 127.0.0.1 8787 2>/dev/null; thenecho "[boot] β WebUI is UP!"breakfisleep 2done# ββ 11. BACKGROUND CLOUD JANITOR & PURGER βββββββββββββββββββββββif [ -n "${HF_TOKEN:-}" ] && [ -n "${HF_BUCKET:-}" ]; then(echo "[boot-clean] π§Ό Removing residual dependencies from remote cloud storage..."hf buckets remove "hf://buckets/${HF_BUCKET}/.venv/" --recursive --yes >/dev/null 2>&1 || truehf buckets remove "hf://buckets/${HF_BUCKET}/venv/" --recursive --yes >/dev/null 2>&1 || truehf buckets remove "hf://buckets/${HF_BUCKET}/.cache/" --recursive --yes >/dev/null 2>&1 || truehf buckets remove "hf://buckets/${HF_BUCKET}/node_modules/" --recursive --yes >/dev/null 2>&1 || trueecho "[boot-clean] π§Ό Remote bucket optimized."while true; do# FIX: Changed background sleep timer to inherit $SYNC_INTERVAL (which defaults to 30 seconds)sleep "${SYNC_INTERVAL:-30}"# FIX: Retained critical --delete parameter to ensure that any local file deletions, updates, or creations# automatically synchronize and delete corresponding redundant files in your Hugging Face space bucket!hf sync "$HH" "hf://buckets/${HF_BUCKET}" \--delete \--exclude ".venv/**" --exclude "**/venv/**" --exclude "venv/**" \--exclude ".cache/**" --exclude "**/.cache/**" \--exclude "node_modules/**" --exclude "**/node_modules/**" \--exclude "__pycache__/**" --exclude "**/__pycache__/**" \--exclude "**/*.pyc" --exclude "**/*.log" --exclude "logs/**" --exclude "**/logs/**" \--exclude "**/*.db-wal" --exclude "**/*.db-shm" --exclude "**/*.db-journal" >/dev/null 2>&1 || truedone) &fi# ββ 12. START ROUTER βββββββββββββββββββββββββββββββββββββββββββecho "[boot] π Starting router on port ${PORT:-7860}..."exec node /opt/router/server.jsENDSHRUN chmod +x /opt/start.sh# ββ Write build-time Kanban patch script safely βββββββββββββββRUN cat << 'EOF' > /tmp/patch_kanban.pyimport systry:from pathlib import Pathp = Path("/opt/hermes/hermes_cli/kanban_db.py")if not p.exists():print("kanban_db.py not found β skip")sys.exit(0)src = p.read_text(encoding="utf-8")sentinel = "# hf-patch: idempotent"if sentinel in src:print("already patched")sys.exit(0)import repatched = re.sub(r'(conn\.execute\(["\']ALTER TABLE \w+ ADD COLUMN [^)]+\)["\'][ \t]*\))',r'try:\n \1 ' + sentinel + r'\n except Exception:\n pass',src)if patched != src:p.write_text(patched, encoding="utf-8")print("kanban patch: applied")else:print("kanban patch: pattern not found β may already be fixed upstream")except Exception as e:print(f"Kanban patch failed silently to avoid interrupting build: {e}")EOFRUN python3 /tmp/patch_kanban.py && rm /tmp/patch_kanban.py# ββ FIX ALL DATABASE FRAGMENTATION & OWNERSHIP & DEFINE SHELL ββ# Enforces bash as standard terminal shell context for the hermes runtime user.RUN chsh -s /bin/bash hermes || true \&& mkdir -p /data /data/logs \&& mkdir -p /home/hermes \&& rm -rf /home/hermes/.hermes && ln -sf /data /home/hermes/.hermes \&& rm -rf /opt/data && ln -sf /data /opt/data \&& touch /home/hermes/.bashrc \&& echo "export PATH=\"/opt/hermes/.venv/bin:/opt/data/.local/bin:\$PATH\"" >> /home/hermes/.bashrc \# ββ BROWSER FIX: Also export Playwright and Chrome flags in the interactive# shell so that any terminal commands the agent runs (e.g. npx playwright# or agent-browser) also inherit the no-sandbox configuration ββββββββββββββ&& echo "export PLAYWRIGHT_BROWSERS_PATH=/opt/hermes/.playwright" >> /home/hermes/.bashrc \&& echo "export AGENT_BROWSER_CHROME_FLAGS=\"--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer\"" >> /home/hermes/.bashrc \&& chown -R hermes:hermes /data /home/hermes /opt/hermes /opt/hermes-webui /opt/router /opt/start.sh \&& chown -h hermes:hermes /home/hermes/.hermes /opt/data \&& chmod -R 777 /data \# ββ PERMISSION FIX: Ensure the hermes user owns the Playwright browser# cache we installed as root, and the agent-browser config we wrote ββββββββ&& chown -R hermes:hermes /opt/hermes/.playwright /opt/hermes/.agent-browser \# ββ PERMISSION FIX: Ensure /tmp is writable (some HF Space base images# have a sticky /tmp that non-root users can't create new dirs in) βββββββββ&& chmod 1777 /tmpEXPOSE 7860USER hermesENTRYPOINT ["/opt/start.sh"]
Dockerfile+812-18