Spaces:
Paused
Paused
Update Dockerfile
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811822 unmodified lines1851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824836 unmodified lines4904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445459 unmodified lines5555565575585595605615625635645655665675685695705715725735745755765775785795805815825835842 unmodified lines58758858959059159259359459559659759859960060160260360421 unmodified lines6266276286296306316326336346355 unmodified lines64164264364464564664712 unmodified lines660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756# ============================================================# Hermes Agent β Ubuntu 22.04 base (Stable v8.0)# Full Ubuntu environment β runs as root β zero permission errors# Single Dockerfile: Gateway + Dashboard + Chat WebUI + Router## WHY UBUNTU BASE:# The previous nousresearch/hermes-agent base image ran as a# non-root "hermes" user, causing: chmod/chown permission denied,# Chromium --no-sandbox still failing, /tmp not writable.# Starting from ubuntu:22.04 and installing everything as root# eliminates ALL of those issues permanently.## 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)# TELEGRAM_API_BASE β (Optional) Cloudflare Worker proxy URL# ============================================================FROM ubuntu:22.04# Prevent apt from asking interactive questions during buildENV DEBIAN_FRONTEND=noninteractiveENV TZ=UTC# ββ Global Environment βββββββββββββββββββββββββββββββββββββββββ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 \HOME=/root \PATH="/root/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \# ββ Playwright: store Chromium in a fixed root-owned path βββββPLAYWRIGHT_BROWSERS_PATH=/opt/playwright \# ββ agent-browser: both official var (AGENT_BROWSER_ARGS) and# Hermes-specific var (AGENT_BROWSER_CHROME_FLAGS) set so that# no-sandbox flags reach Chromium regardless of which code path firesAGENT_BROWSER_ARGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer" \AGENT_BROWSER_CHROME_FLAGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer"# ββ 1. System packages βββββββββββββββββββββββββββββββββββββββββRUN apt-get update && apt-get install -y --no-install-recommends \# Core utilitiesca-certificates curl wget gnupg git jq \tar gzip unzip zip \netcat-openbsd dnsutils iputils-ping \# Shell & system tools the agent uses in terminalbash sudo procps lsof htop \# Python 3python3 python3-pip python3-venv python3-dev \# Node.js deps (we install Node via NodeSource below)build-essential \# SQLitesqlite3 \# Chromium / Playwright runtime deps β full set for headlesslibnss3 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 libglib2.0-0 libx11-xcb1 libxcursor1 \libxi6 libxtst6 fonts-liberation libappindicator3-1 \xdg-utils \&& rm -rf /var/lib/apt/lists/*# ββ 2. Node.js 20 LTS (via NodeSource) ββββββββββββββββββββββββRUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \&& apt-get install -y nodejs \&& rm -rf /var/lib/apt/lists/* \&& node --version && npm --version# ββ 3. Install uv (fast Python package manager) βββββββββββββββRUN curl -LsSf https://astral.sh/uv/install.sh | bash \&& ln -sf /root/.local/bin/uv /usr/local/bin/uv \&& ln -sf /root/.local/bin/uvx /usr/local/bin/uvx# ββ 4. Install Hermes Agent via pip βββββββββββββββββββββββββββ# We install into a venv to keep it isolated and reproducibleRUN python3 -m venv /opt/hermes/.venv \&& /opt/hermes/.venv/bin/pip install --upgrade pip \&& /opt/hermes/.venv/bin/pip install --no-cache-dir \hermes-agent \&& ln -sf /opt/hermes/.venv/bin/hermes /usr/local/bin/hermes# ββ 5. Install HuggingFace CLI (hf) βββββββββββββββββββββββββββRUN curl -LsSf https://hf.co/cli/install.sh | bash \&& ( [ -f /root/.local/bin/hf ] && ln -sf /root/.local/bin/hf /usr/local/bin/hf || true ) \&& hf --version || true# ββ 6. Install huggingface_hub and pyyaml into the venv βββββββRUN /opt/hermes/.venv/bin/pip install --no-cache-dir \"huggingface_hub[hf_xet]>=0.22" pyyaml requests# ββ 7. 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 )# ββ 8. Patch WebUI: remove auth/password gates & fix URLs βββββRUN python3 << 'PYEOF'import os, reweb_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("WebUI patch complete.")PYEOF# ββ 9. Patch Kanban DB (idempotent ALTER TABLE) ββββββββββββββββRUN python3 << 'PYEOF'import sys, refrom pathlib import Pathfor candidate in ["/opt/hermes/.venv/lib/python3.10/site-packages/hermes_cli/kanban_db.py","/opt/hermes/.venv/lib/python3.11/site-packages/hermes_cli/kanban_db.py","/opt/hermes/.venv/lib/python3.12/site-packages/hermes_cli/kanban_db.py",]:p = Path(candidate)if p.exists():src = p.read_text(encoding="utf-8")sentinel = "# hf-patch: idempotent"if sentinel not in src:patched = 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(f"Kanban patch applied: {candidate}")else:print(f"Already patched: {candidate}")breakelse:print("kanban_db.py not found in venv β skipping")PYEOF# ββ 10. Node.js router deps ββββββββββββββββββββββββββββββββββββ2 unmodified lines&& npm init -y --quiet \&& npm install --quiet --no-fund http-proxy# ββ 11. Write the Node.js reverse proxy / auth router βββββββββ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 clean = GATEWAY_TOKEN.trim();try {var url = req.url || '';var qIdx = url.indexOf('?');if (qIdx !== -1) {var params = url.slice(qIdx + 1).split('&');for (var i = 0; i < params.length; i++) {var pair = params[i].split('=');if (pair[0] === 'token' && decodeURIComponent(pair[1] || '').trim() === clean) return true;}}} catch(e) {}var cookies = parseCookies(req);if (cookies['hm_tok'] && decodeURIComponent(cookies['hm_tok']).trim() === clean) return true;var auth = req.headers['authorization'] || '';if (auth.trim() === 'Bearer ' + clean) 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();}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 }));}if (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 clean = GATEWAY_TOKEN.trim();if (!clean || tok.trim() === clean) {var cf = '; Path=/; HttpOnly; Secure; SameSite=None; Max-Age=31536000';var cookies = parseCookies(req);var scope = cookies['hm_redirect'] || cookies['hm_scope'] || 'webui';var dest = (scope === 'dashboard') ? '/dashboard' : '/';res.writeHead(302, {'Set-Cookie': ['hm_tok=' + encodeURIComponent(tok.trim()) + cf,'hm_redirect=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT' + cf],'Location': dest});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(''));}if (!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 cf = '; Path=/; HttpOnly; Secure; SameSite=None; Max-Age=31536000';res.writeHead(302, {'Set-Cookie': 'hm_redirect=' + (isDashboardNav ? 'dashboard' : 'webui') + cf,'Location': '/_login'});return res.end();}if (isGatewayPath(pathname)) {return proxy.web(req, res, { target: 'http://127.0.0.1:8642', changeOrigin: false });}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 isAsset = pathname.indexOf('/assets/') === 0 || pathname.indexOf('/static/') === 0 ||pathname.indexOf('/api/') === 0 || pathname.indexOf('/openapi.json') === 0;if (isAsset) isDashboard = true;}if (scopeChanged) {res.setHeader('Set-Cookie', 'hm_scope=' + activeScope + '; Path=/; HttpOnly; Secure; SameSite=None; Max-Age=31536000');}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 pathname = urlParser.parse(req.url || '/').pathname || '/';var referer = req.headers.referer || '';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 rp = urlParser.parse(referer).pathname || '';if (rp === '/dashboard' || rp.indexOf('/dashboard/') === 0 || isDashboardPath(rp)) 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# ββ 12. Install Playwright Chromium βββββββββββββββββββββββββββ# Running as root β no sandbox needed. PLAYWRIGHT_BROWSERS_PATH is already# set in ENV to /opt/playwright. install-deps ensures all OS libs are present.RUN mkdir -p /opt/playwright \&& npx --yes playwright install chromium \&& npx playwright install-deps chromium 2>/dev/null || true# ββ 13. Write agent-browser config (both locations) βββββββββββ# ~/.agent-browser/config.json = user-level config read by agent-browser CLI# We write to /root/.agent-browser since HOME=/rootRUN mkdir -p /root/.agent-browser \&& cat > /root/.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,"ignoreHttpsErrors": true}ENDJSON# ββ 14. Create data directories ββββββββββββββββββββββββββββββββRUN mkdir -p /data /data/logs /data/config /data/memory \&& chmod -R 777 /data# ββ 15. Write start.sh βββββββββββββββββββββββββββββββββββββββββRUN cat > /opt/start.sh << 'ENDSH'#!/usr/bin/env bash# Running as root inside Ubuntu β no permission issuesset -euo pipefailexport PATH="/opt/hermes/.venv/bin:/root/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"export HOME="/root"export PLAYWRIGHT_BROWSERS_PATH="/opt/playwright"export AGENT_BROWSER_ARGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer"export AGENT_BROWSER_CHROME_FLAGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer"HH="${HERMES_HOME:-/data}"mkdir -p "$HH" "$HH/logs" "$HH/config" "$HH/memory"echo "ββββββββββββββββββββββββββββββββββββββββββββ"echo "β Hermes Agent β Ubuntu 22.04 bootloader β"echo "β Running as: $(whoami) (uid=$(id -u)) β"echo "ββββββββββββββββββββββββββββββββββββββββββββ"# ββ 1. PULL LATEST WEBUI IN BACKGROUND ββββββββββββββββββββββββecho "[boot] π Checking for WebUI updates in background..."(cd /opt/hermes-webui && git pull >/dev/null 2>&1 && echo "[boot] β WebUI updated") &# ββ 2. RESTORE FROM HF BUCKET βββββββββββββββββββββββββββββββββif [ -n "${HF_TOKEN:-}" ] && [ -n "${HF_BUCKET:-}" ]; thenecho "[boot] π¦ Restoring workspace from HF bucket..."export HF_TOKEN="${HF_TOKEN}"6 unmodified lines--exclude "logs/**" --exclude "**/logs/**" --exclude "**/*.log" \--exclude "**/*.db-wal" --exclude "**/*.db-shm" --exclude "**/*.db-journal" \2>/dev/null; thenecho "[boot] β Workspace restored from bucket"elseecho "[boot] β οΈ Bucket empty or first run β starting fresh"fifi# ββ 3. SQLITE INTEGRITY CHECK & WAL MODE ββββββββββββββββββββββecho "[boot] π©Ί Checking SQLite databases..."python3 - <<'PY'import os, sqlite3db_dir = "/data"if os.path.exists(db_dir):for fname in os.listdir(db_dir):if not fname.endswith(".db"):continuedb_path = os.path.join(db_dir, fname)try:conn = sqlite3.connect(db_path)cur = conn.cursor()cur.execute("PRAGMA integrity_check;")res = cur.fetchone()# res is a tuple like ("ok",) β must compare res[0]if res and res[0] == "ok":cur.execute("PRAGMA journal_mode=WAL;")cur.execute("PRAGMA synchronous=NORMAL;")conn.commit()print(f"[boot] β DB OK + WAL enabled: {fname}")else:raise Exception(f"integrity failed: {res}")conn.close()except Exception as e:print(f"[boot] π₯ Corrupt DB, resetting: {fname} ({e})")for sfx in ["", "-journal", "-wal", "-shm"]:p = db_path + sfx if sfx else db_pathtry: os.remove(p)except: passPY# ββ 4. MERGE BUILT-IN SKILLS ββββββββββββββββββββββββββββββββββecho "[boot] π§© Merging built-in skills..."for src in /opt/hermes/skills /opt/hermes/.venv/lib/python3.*/site-packages/hermes_cli/skills; doif [ -d "$src" ]; thenmkdir -p "$HH/skills"cp -rn "$src"/* "$HH/skills/" 2>/dev/null || trueecho "[boot] β Skills merged from: $src"fidone# ββ 5. WEBUI SETTINGS (disable auth) ββββββββββββββββββββββββββecho "[boot] βοΈ Configuring WebUI settings..."touch "$HH/webui_settings.json"if [ ! -s "$HH/webui_settings.json" ]; thenecho '{"password":"","password_enabled":false,"auth_enabled":false}' > "$HH/webui_settings.json"9 unmodified linesrm -f /opt/hermes-webui/settings.jsonln -sf "$HH/webui_settings.json" /opt/hermes-webui/settings.json# ββ 6. SYNC ENV CREDENTIALS TO .env βββββββββββββββββββββββββββENV_FILE="$HH/.env"echo "[boot] π Syncing credentials to .env..."touch "$ENV_FILE"TMP_ENV=$(mktemp)cat "$ENV_FILE" > "$TMP_ENV"upsert_key() {local key="$1" val="$2"[ -n "$val" ] || return 0sed -i "/^${key}=/d" "$TMP_ENV" || trueecho "${key}=${val}" >> "$TMP_ENV"}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:-}"upsert_key "PLAYWRIGHT_BROWSERS_PATH" "/opt/playwright"upsert_key "AGENT_BROWSER_ARGS" "--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer"upsert_key "AGENT_BROWSER_CHROME_FLAGS" "--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer"if [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; thenupsert_key "TELEGRAM_BOT_TOKEN" "${TELEGRAM_BOT_TOKEN}"USERS="${TELEGRAM_ALLOWED_USERS:-}"2 unmodified linesupsert_key "TELEGRAM_ALLOWED_USERS" "$USERS"fifimv "$TMP_ENV" "$ENV_FILE"chmod 600 "$ENV_FILE"# ββ 7. TELEGRAM NETWORK CHECK βββββββββββββββββββββββββββββββββif [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; thenecho "[boot] π Checking Telegram connectivity..."if curl -s -I --connect-timeout 5 "https://api.telegram.org" >/dev/null; thenecho "[boot] β Telegram reachable"elseecho "[boot] β Telegram unreachable"fifi# ββ 8. WRITE config.yaml ββββββββββββββββββββββββββββββββββββββ21 unmodified lines- --disable-software-rasterizerYAMLelse# Append browser block to existing config if missingif ! grep -q "^browser:" "$CFG" 2>/dev/null; thenecho "[boot] π§ Appending browser config to existing config.yaml..."cat >> "$CFG" << YAMLbrowser:command_timeout: 905 unmodified lines- --disable-setuid-sandbox- --disable-software-rasterizerYAMLfifi# ββ 9. START SERVICES βββββββββββββββββββββββββββββββββββββββββ12 unmodified linesPLAYWRIGHT_BROWSERS_PATH="/opt/playwright" \AGENT_BROWSER_ARGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer" \AGENT_BROWSER_CHROME_FLAGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer" \hermes gateway run > "$HH/logs/gateway.log" 2>&1 &echo "[boot] ποΈ Starting Hermes Dashboard (port 9119)..."(unset TELEGRAM_BOT_TOKEN || truehermes 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-webuiHERMES_WEBUI_PASSWORD="" \WEBUI_PASSWORD="" \PASSWORD="" \ADMIN_PASSWORD="" \AUTH_ENABLED="false" \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 ALL BACKENDS βββββββββββββββββββββββββββββββββwait_for_port() {local label="$1" port="$2"echo "[boot] β³ Waiting for ${label} on :${port}..."for i in $(seq 1 45); doif nc -z 127.0.0.1 "$port" 2>/dev/null; thenecho "[boot] β ${label} is UP!"return 0fisleep 2doneecho "[boot] β οΈ ${label} did not start in time β check logs"}wait_for_port "Gateway" 8642wait_for_port "Dashboard" 9119wait_for_port "WebUI" 8787# ββ 11. BACKGROUND CLOUD SYNC (every 30s) βββββββββββββββββββββif [ -n "${HF_TOKEN:-}" ] && [ -n "${HF_BUCKET:-}" ]; then(# One-time: remove any old dependency dirs from bucketecho "[boot-clean] π§Ό Cleaning old deps from bucket..."for dir in .venv venv .cache node_modules; dohf buckets remove "hf://buckets/${HF_BUCKET}/${dir}/" \--recursive --yes >/dev/null 2>&1 || truedoneecho "[boot-clean] β Bucket clean"# Recurring sync loopwhile true; dosleep "${SYNC_INTERVAL:-30}"hf sync "$HH" "hf://buckets/${HF_BUCKET}" \--delete \--exclude ".venv/**" --exclude "**/venv/**" \--exclude ".cache/**" --exclude "**/.cache/**" \--exclude "node_modules/**" --exclude "**/node_modules/**" \--exclude "__pycache__/**" --exclude "**/__pycache__/**" \--exclude "**/*.pyc" \--exclude "logs/**" --exclude "**/logs/**" \--exclude "**/*.log" \--exclude "**/*.db-wal" --exclude "**/*.db-shm" \--exclude "**/*.db-journal" \>/dev/null 2>&1 || truedone) &fi# ββ 12. START ROUTER (this is the foreground/PID1 process) ββββecho "[boot] π Starting router on port ${PORT:-7860}..."exec node /opt/router/server.jsENDSHRUN chmod +x /opt/start.sh# ββ 16. Final permissions ββββββββββββββββββββββββββββββββββββββRUN chmod -R 777 /data \&& chmod -R 755 /opt/hermes \&& chmod -R 755 /opt/hermes-webui \&& chmod -R 755 /opt/playwright \&& chmod -R 755 /root/.agent-browserEXPOSE 7860# Stay as root β HF Spaces will remap to UID 1000 at runtime but the# process still has effectively root-level access to everything we builtUSER rootENTRYPOINT ["/opt/start.sh"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561572 unmodified lines1601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013026 unmodified lines3093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623639 unmodified lines3733743753763773783793803813823833843853863873883893903913923933943953963973982 unmodified lines40140240340440540640740840941041141241341441521 unmodified lines4374384394404414424435 unmodified lines44945045145245345412 unmodified lines467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541# ============================================================# Hermes Agent β Ubuntu 22.04 base (Stable v8.1)# Full Ubuntu root environment β zero permission errors# 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]# TELEGRAM_BOT_TOKEN β from @BotFather# TELEGRAM_ALLOWED_USERS β your numeric user ID# TELEGRAM_API_BASE β Cloudflare Worker proxy URL# ============================================================FROM ubuntu:22.04ENV DEBIAN_FRONTEND=noninteractive \TZ=UTC# ββ Global environment βββββββββββββββββββββββββββββββββββββββββENV PYTHONUNBUFFERED=1 \HOME=/root \HERMES_HOME=/data \HERMES_INSTALL_DIR=/usr/local/lib/hermes-agent \NODE_OPTIONS=--no-deprecation \HF_XET_HIGH_PERFORMANCE=1 \HF_HUB_ENABLE_HF_TRANSFER=1 \PORT=7860 \TERM=xterm-256color \SHELL=/bin/bash \SYNC_INTERVAL=30 \PLAYWRIGHT_BROWSERS_PATH=/opt/playwright \AGENT_BROWSER_ARGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer" \AGENT_BROWSER_CHROME_FLAGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer"# ββ 1. APT packages ββββββββββββββββββββββββββββββββββββββββββββRUN apt-get update && apt-get install -y --no-install-recommends \ca-certificates curl wget gnupg git jq \tar gzip unzip zip \netcat-openbsd dnsutils iputils-ping \bash sudo procps lsof htop \python3 python3-pip python3-venv python3-dev \build-essential sqlite3 \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 libglib2.0-0 libx11-xcb1 libxcursor1 \libxi6 libxtst6 fonts-liberation xdg-utils \&& rm -rf /var/lib/apt/lists/*# ββ 2. Node.js 20 LTS ββββββββββββββββββββββββββββββββββββββββββRUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \&& apt-get install -y nodejs \&& rm -rf /var/lib/apt/lists/*# ββ 3. uv (fast Python package manager) βββββββββββββββββββββββRUN curl -LsSf https://astral.sh/uv/install.sh | bash \&& ln -sf /root/.local/bin/uv /usr/local/bin/uv \&& ln -sf /root/.local/bin/uvx /usr/local/bin/uvx# ββ 4. Install Hermes Agent via official installer βββββββββββββ# --skip-setup β skips interactive wizard (non-interactive Docker build)# --skip-browser β we install Playwright separately into /opt/playwright# so it is in a fixed path not under HERMES_HOME# As root on Linux the installer uses FHS layout:# code β /usr/local/lib/hermes-agent# binaryβ /usr/local/bin/hermes# data β /root/.hermes (we override with HERMES_HOME=/data at runtime)RUN curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh \| bash -s -- --skip-setup --skip-browser# ββ 5. Install HuggingFace CLI βββββββββββββββββββββββββββββββββRUN curl -LsSf https://hf.co/cli/install.sh | bash \&& ln -sf /root/.local/bin/hf /usr/local/bin/hf || true# ββ 6. Install Playwright Chromium into fixed path βββββββββββββRUN mkdir -p /opt/playwright \&& PLAYWRIGHT_BROWSERS_PATH=/opt/playwright \npx --yes playwright install chromium \&& PLAYWRIGHT_BROWSERS_PATH=/opt/playwright \npx playwright install-deps chromium 2>/dev/null || true# ββ 7. Clone Hermes WebUI + install its deps ββββββββββββββββββRUN git clone --depth 1 https://github.com/nesquena/hermes-webui.git /opt/hermes-webui \&& ( [ -f /opt/hermes-webui/requirements.txt ] \&& pip3 install --no-cache-dir -r /opt/hermes-webui/requirements.txt \|| true )# ββ 8. Patch WebUI: strip auth gates, fix internal URLs ββββββββRUN python3 << 'PYEOF'import os, refor root, dirs, files in os.walk("/opt/hermes-webui"):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()orig = 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"):for pair in [("password_enabled = true","password_enabled = False"),("password_enabled=True","password_enabled=False"),("auth_enabled = true","auth_enabled = False"),("auth_enabled=True","auth_enabled=False")]:content = content.replace(*pair)if content != orig:with open(fpath, 'w', encoding='utf-8') as f:f.write(content)except Exception:passprint("WebUI patched.")PYEOF# ββ 9. Patch Kanban DB (idempotent ALTER TABLE) ββββββββββββββββRUN python3 << 'PYEOF'import sys, re, globfrom pathlib import Path# Find kanban_db.py wherever pip installed itcandidates = glob.glob("/usr/local/lib/hermes-agent/.venv/lib/python3.*/site-packages/hermes_cli/kanban_db.py") \+ glob.glob("/usr/local/lib/hermes-agent/hermes_cli/kanban_db.py") \+ glob.glob("/root/.hermes/hermes-agent/hermes_cli/kanban_db.py")for c in candidates:p = Path(c)if not p.exists(): continuesrc = p.read_text(encoding="utf-8")sentinel = "# hf-patch: idempotent"if sentinel in src:print(f"Already patched: {c}"); breakpatched = 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(f"Patched: {c}"); breakelse:print("kanban_db.py not found β skip")PYEOF# ββ 10. Node.js router deps ββββββββββββββββββββββββββββββββββββ2 unmodified lines&& npm init -y --quiet \&& npm install --quiet --no-fund http-proxy# ββ 11. Write the Node.js reverse proxy βββββββββββββββββββββββCOPY --chmod=644 /dev/stdin /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 isDash(p){return DASHBOARD_PATHS.some(function(d){return p===d||p.indexOf(d+'/')===0;});}function isGW(p){return GATEWAY_PATHS.some(function(d){return p===d||p.indexOf(d+'/')===0;});}proxy.on('error',function(e,req,res){if(res&&res.socket&&!res.headersSent){res.writeHead(502,{'Content-Type':'text/html'});res.end('<html><head><meta http-equiv="refresh" content="5"></head><body><h2>Startingβ¦</h2></body></html>');}});function parseCookies(req){var o={};(req.headers.cookie||'').split(';').forEach(function(c){var i=c.indexOf('=');if(i>0)o[c.slice(0,i).trim()]=c.slice(i+1).trim();});return o;}function authed(req){if(!GATEWAY_TOKEN)return true;var t=GATEWAY_TOKEN.trim();try{var q=(req.url||'').split('?')[1]||'';q.split('&').forEach(function(p){var kv=p.split('=');if(kv[0]==='token'&&decodeURIComponent(kv[1]||'').trim()===t)throw 'ok';});}catch(e){if(e==='ok')return true;}var c=parseCookies(req);if(c['hm_tok']&&decodeURIComponent(c['hm_tok']).trim()===t)return true;if((req.headers['authorization']||'').trim()==='Bearer '+t)return true;return false;}function loginPage(err){return'<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Hermes</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}'+'.c{background:#161920;border:1px solid #252830;border-radius:18px;padding:2.6rem 2.2rem;width:100%;max-width:400px}'+'h1{font-size:1.45rem;margin-bottom:.2rem}.s{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}'+'button{width:100%;padding:.8rem;background:#7c3aed;border:none;border-radius:9px;color:#fff;font-size:1rem;font-weight:600;cursor:pointer}'+(err?'.e{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}':'')+'</style></head>'+'<body><div class="c"><h1>🥯 Hermes Agent</h1><p class="s">Enter your gateway token.</p>'+(err?'<div class="e">⚠ '+err+'</div>':'')+'<form method="POST" action="/_login"><label>Gateway Token</label>'+'<input type="password" name="token" autofocus autocomplete="current-password"/>'+'<button type="submit">Sign in →</button></form></div></body></html>';}var server=http.createServer(function(req,res){var url=req.url||'/';var ref=req.headers.referer||'';var pn=urlParser.parse(url).pathname||'/';if(pn==='/login'||pn==='/login/'){res.writeHead(302,{'Location':'/'});return res.end();}if(pn==='/health'||pn==='/health/'){res.writeHead(200,{'Content-Type':'application/json'});return res.end(JSON.stringify({ok:true,ts:new Date().toISOString()}));}if(pn==='/_login'||pn==='/_login/'){if(req.method==='POST'){var b='';req.on('data',function(d){b+=d;});req.on('end',function(){var tok=new URLSearchParams(b).get('token')||'';var t=GATEWAY_TOKEN.trim();if(!t||tok.trim()===t){var cf='; Path=/; HttpOnly; Secure; SameSite=None; Max-Age=31536000';var sc=parseCookies(req);var scope=sc['hm_redirect']||sc['hm_scope']||'webui';res.writeHead(302,{'Set-Cookie':['hm_tok='+encodeURIComponent(tok.trim())+cf,'hm_redirect=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT'+cf],'Location':scope==='dashboard'?'/dashboard':'/'});return res.end();}res.writeHead(401,{'Content-Type':'text/html'});res.end(loginPage('Invalid token.'));});return;}res.writeHead(200,{'Content-Type':'text/html'});return res.end(loginPage(''));}if(!authed(req)){var isApi=pn.indexOf('/v1/')===0||pn.indexOf('/api/')===0||pn.indexOf('/static/')===0||pn.indexOf('/assets/')===0;if(isApi){res.writeHead(401,{'Content-Type':'application/json'});return res.end(JSON.stringify({error:'Unauthorized'}));}var cf='; Path=/; HttpOnly; Secure; SameSite=None; Max-Age=31536000';res.writeHead(302,{'Set-Cookie':'hm_redirect='+(pn==='/dashboard'||pn.indexOf('/dashboard/')===0?'dashboard':'webui')+cf,'Location':'/_login'});return res.end();}if(isGW(pn))return proxy.web(req,res,{target:'http://127.0.0.1:8642',changeOrigin:false});var ck=parseCookies(req);var scope=ck['hm_scope']||'webui';var dash=isDash(pn);var changed=false;if(pn==='/dashboard'||pn.indexOf('/dashboard/')===0){if(scope!=='dashboard'){dash=true;scope='dashboard';changed=true;}}else if(pn==='/'||pn==='/_login'){if(scope!=='webui'){dash=false;scope='webui';changed=true;}}else if(ref){try{var rp=urlParser.parse(ref).pathname||'';if(rp==='/dashboard'||rp.indexOf('/dashboard/')===0||isDash(rp)){dash=true;if(scope!=='dashboard'){scope='dashboard';changed=true;}}}catch(e){}}if(!dash&&scope==='dashboard'){var isA=pn.indexOf('/assets/')===0||pn.indexOf('/static/')===0||pn.indexOf('/api/')===0;if(isA)dash=true;}if(changed)res.setHeader('Set-Cookie','hm_scope='+scope+'; Path=/; HttpOnly; Secure; SameSite=None; Max-Age=31536000');if(dash)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 pn=urlParser.parse(req.url||'/').pathname||'';if(!authed(req)){socket.destroy();return;}var ck=parseCookies(req);var scope=ck['hm_scope']||'webui';var dash=isDash(pn);if(pn==='/dashboard'||pn.indexOf('/dashboard/')===0)dash=true;if(!dash&&scope==='dashboard')dash=true;var t=dash?'http://127.0.0.1:9119':(isGW(pn)?'http://127.0.0.1:8642':'http://127.0.0.1:8787');proxy.ws(req,socket,head,{target:t,changeOrigin:t.indexOf('9119')>=0});});server.listen(PORT,'0.0.0.0',function(){console.log('[router] listening on port '+PORT);});ENDJS# ββ 12. agent-browser config (no-sandbox flags) ββββββββββββββββRUN mkdir -p /root/.agent-browser \&& printf '{\n "$schema":"https://agent-browser.dev/schema.json",\n "args":"--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer",\n "headless":true,\n "ignoreHttpsErrors":true\n}\n' \> /root/.agent-browser/config.json# ββ 13. Data directory βββββββββββββββββββββββββββββββββββββββββRUN mkdir -p /data /data/logs /data/config /data/memory \&& chmod -R 777 /data# ββ 14. Write start.sh βββββββββββββββββββββββββββββββββββββββββRUN cat > /opt/start.sh << 'ENDSH'#!/usr/bin/env bashset -euo pipefail# ββ Hermes installer puts binary + venv here when run as root ββ# Priority: FHS path β fallback legacy pathHERMES_BIN=""for candidate in \/usr/local/bin/hermes \/usr/local/lib/hermes-agent/.venv/bin/hermes \/root/.hermes/hermes-agent/.venv/bin/hermes \/root/.local/bin/hermes; doif [ -x "$candidate" ]; then HERMES_BIN="$candidate"; break; fidone[ -n "$HERMES_BIN" ] || { echo "[boot] FATAL: hermes binary not found"; exit 1; }# Build PATH from every possible venv locationVENV_BIN="$(dirname "$HERMES_BIN")"export PATH="$VENV_BIN:/root/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"export HOME="/root"export HERMES_HOME="${HERMES_HOME:-/data}"export PLAYWRIGHT_BROWSERS_PATH="/opt/playwright"export AGENT_BROWSER_ARGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer"export AGENT_BROWSER_CHROME_FLAGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer"HH="$HERMES_HOME"mkdir -p "$HH" "$HH/logs" "$HH/config" "$HH/memory"echo "ββββββββββββββββββββββββββββββββββββββββββββ"echo "β Hermes Agent β Ubuntu 22.04 bootloader β"printf "β Running as: %-28sβ\n" "$(whoami) (uid=$(id -u))"echo "ββββββββββββββββββββββββββββββββββββββββββββ"echo "[boot] hermes binary: $HERMES_BIN"# ββ 1. PULL LATEST WEBUI ββββββββββββββββββββββββββββββββββββββ(cd /opt/hermes-webui && git pull >/dev/null 2>&1 && echo "[boot] β WebUI updated") &# ββ 2. RESTORE FROM HF BUCKET ββββββββββββββββββββββββββββββββif [ -n "${HF_TOKEN:-}" ] && [ -n "${HF_BUCKET:-}" ]; thenecho "[boot] π¦ Restoring workspace from HF bucket..."export HF_TOKEN="${HF_TOKEN}"6 unmodified lines--exclude "logs/**" --exclude "**/logs/**" --exclude "**/*.log" \--exclude "**/*.db-wal" --exclude "**/*.db-shm" --exclude "**/*.db-journal" \2>/dev/null; thenecho "[boot] β Workspace restored"elseecho "[boot] β οΈ Bucket empty or first run β starting fresh"fifi# ββ 3. SQLITE INTEGRITY + WAL ββββββββββββββββββββββββββββββββpython3 - <<'PY'import os, sqlite3db_dir = os.environ.get("HERMES_HOME", "/data")if os.path.exists(db_dir):for fname in os.listdir(db_dir):if not fname.endswith(".db"): continuedb_path = os.path.join(db_dir, fname)try:conn = sqlite3.connect(db_path)cur = conn.cursor()cur.execute("PRAGMA integrity_check;")res = cur.fetchone()if res and res[0] == "ok":cur.execute("PRAGMA journal_mode=WAL;")cur.execute("PRAGMA synchronous=NORMAL;")conn.commit()print(f"[boot] β DB OK + WAL: {fname}")else:raise Exception(f"integrity: {res}")conn.close()except Exception as e:print(f"[boot] π₯ Resetting corrupt DB: {fname} ({e})")for sfx in ["","-journal","-wal","-shm"]:p = db_path + sfx if sfx else db_pathtry: os.remove(p)except: passPY# ββ 4. MERGE BUILT-IN SKILLS βββββββββββββββββββββββββββββββββfor src in \/usr/local/lib/hermes-agent/hermes_cli/skills \/root/.hermes/hermes-agent/hermes_cli/skills \/usr/local/lib/hermes-agent/.venv/lib/python3.*/site-packages/hermes_cli/skills; dofor d in $src; do[ -d "$d" ] || continuemkdir -p "$HH/skills"cp -rn "$d"/* "$HH/skills/" 2>/dev/null || trueecho "[boot] β Skills from: $d"donedone# ββ 5. WEBUI SETTINGS ββββββββββββββββββββββββββββββββββββββββtouch "$HH/webui_settings.json"if [ ! -s "$HH/webui_settings.json" ]; thenecho '{"password":"","password_enabled":false,"auth_enabled":false}' > "$HH/webui_settings.json"9 unmodified linesrm -f /opt/hermes-webui/settings.jsonln -sf "$HH/webui_settings.json" /opt/hermes-webui/settings.json# ββ 6. SYNC ENV CREDENTIALS ββββββββββββββββββββββββββββββββββENV_FILE="$HH/.env"touch "$ENV_FILE"TMP_ENV=$(mktemp)cat "$ENV_FILE" > "$TMP_ENV"upsert_key() {local key="$1" val="$2"[ -n "$val" ] || return 0sed -i "/^${key}=/d" "$TMP_ENV" || trueecho "${key}=${val}" >> "$TMP_ENV"}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:-}"upsert_key "PLAYWRIGHT_BROWSERS_PATH" "/opt/playwright"upsert_key "AGENT_BROWSER_ARGS" "--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer"upsert_key "AGENT_BROWSER_CHROME_FLAGS" "--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer"if [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; thenupsert_key "TELEGRAM_BOT_TOKEN" "${TELEGRAM_BOT_TOKEN}"USERS="${TELEGRAM_ALLOWED_USERS:-}"2 unmodified linesupsert_key "TELEGRAM_ALLOWED_USERS" "$USERS"fifimv "$TMP_ENV" "$ENV_FILE"chmod 600 "$ENV_FILE"echo "[boot] β Credentials synced to .env"# ββ 7. TELEGRAM CHECK ββββββββββββββββββββββββββββββββββββββββif [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; thencurl -s -I --connect-timeout 5 "https://api.telegram.org" >/dev/null \&& echo "[boot] β Telegram reachable" \|| echo "[boot] β Telegram unreachable"fi# ββ 8. WRITE config.yaml ββββββββββββββββββββββββββββββββββββββ21 unmodified lines- --disable-software-rasterizerYAMLelsegrep -q "^browser:" "$CFG" 2>/dev/null || cat >> "$CFG" << YAMLbrowser:command_timeout: 905 unmodified lines- --disable-setuid-sandbox- --disable-software-rasterizerYAMLfi# ββ 9. START SERVICES βββββββββββββββββββββββββββββββββββββββββ12 unmodified linesPLAYWRIGHT_BROWSERS_PATH="/opt/playwright" \AGENT_BROWSER_ARGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer" \AGENT_BROWSER_CHROME_FLAGS="--no-sandbox,--disable-dev-shm-usage,--disable-gpu,--disable-setuid-sandbox,--disable-software-rasterizer" \"$HERMES_BIN" gateway run > "$HH/logs/gateway.log" 2>&1 &echo "[boot] ποΈ Starting Hermes Dashboard (port 9119)..."(unset TELEGRAM_BOT_TOKEN || true"$HERMES_BIN" 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-webuiHERMES_WEBUI_PASSWORD="" WEBUI_PASSWORD="" PASSWORD="" \ADMIN_PASSWORD="" AUTH_ENABLED="false" PASSWORD_ENABLED="false" \HERMES_WEBUI_AGENT_DIR="$(dirname $(dirname "$HERMES_BIN"))" \HERMES_API_KEY="${API_SERVER_KEY:-local-dev-key}" \python3 server.py > "$HH/logs/webui.log" 2>&1 &# ββ 10. WAIT FOR BACKENDS ββββββββββββββββββββββββββββββββββββwait_port() {local label="$1" port="$2"echo "[boot] β³ Waiting for ${label} on :${port}..."for i in $(seq 1 45); donc -z 127.0.0.1 "$port" 2>/dev/null && echo "[boot] β ${label} UP" && returnsleep 2doneecho "[boot] β οΈ ${label} timeout β check $HH/logs/"}wait_port "Gateway" 8642wait_port "Dashboard" 9119wait_port "WebUI" 8787# ββ 11. BACKGROUND CLOUD SYNC ββββββββββββββββββββββββββββββββif [ -n "${HF_TOKEN:-}" ] && [ -n "${HF_BUCKET:-}" ]; then(for dir in .venv venv .cache node_modules; dohf buckets remove "hf://buckets/${HF_BUCKET}/${dir}/" --recursive --yes >/dev/null 2>&1 || truedoneecho "[boot-clean] β Bucket clean"while true; dosleep "${SYNC_INTERVAL:-30}"hf sync "$HH" "hf://buckets/${HF_BUCKET}" \--delete \--exclude ".venv/**" --exclude "**/venv/**" \--exclude ".cache/**" --exclude "**/.cache/**" \--exclude "node_modules/**" --exclude "**/node_modules/**" \--exclude "__pycache__/**" --exclude "**/__pycache__/**" \--exclude "**/*.pyc" \--exclude "logs/**" --exclude "**/logs/**" --exclude "**/*.log" \--exclude "**/*.db-wal" --exclude "**/*.db-shm" --exclude "**/*.db-journal" \>/dev/null 2>&1 || truedone) &fi# ββ 12. START ROUTER (foreground PID1) βββββββββββββββββββββββecho "[boot] π Starting router on port ${PORT:-7860}..."exec node /opt/router/server.jsENDSHRUN chmod +x /opt/start.sh# ββ 15. Final permissions ββββββββββββββββββββββββββββββββββββββRUN chmod -R 777 /data \&& chmod -R 755 /opt/playwright \&& chmod -R 755 /root/.agent-browser \&& chmod -R 755 /opt/hermes-webui \&& chmod -R 755 /opt/routerEXPOSE 7860USER rootENTRYPOINT ["/opt/start.sh"]
Dockerfile+252-467