Merge pull request #106 from anurag008w/edit
Browse filesEnhance startup robustness, Jupyter security, and browser reliability
Files changed (11)
- .env.example+2-9
- Dockerfile+3
- README.md+8-16
- env-builder.html+2-1
- env-builder.js+57-67
- health-server.js+5-3
- iframe-fix.cjs+3-2
- jupyter-devdata-sync.py+1
- multi-provider-key-rotator.cjs+25-1
- start.sh+171-20
- wa-guardian.js+20-10
247 unmodified lines24824925025125225325425532 unmodified lines288289290291292293294295296297298299300301247 unmodified linesGATEWAY_TOKEN=your_gateway_token_here# [OPTIONAL] JupyterLab terminal token for /terminal/# Defaults to "huggingface" if unset. Set a strong token for private deployments.JUPYTER_TOKEN=huggingface# (Optional) Password auth — simpler alternative to token for casual users# If set, users can log in with this password instead of the token32 unmodified lines# Default: huggingclaw-backupBACKUP_DATASET_NAME=huggingclaw-backup# Git commit identity for workspace syncsWORKSPACE_GIT_USER=openclaw@example.comWORKSPACE_GIT_NAME=OpenClaw Bot# ── OPTIONAL: Background Services ──# Keep-alive ping interval (seconds). Default: 300. Set 0 to disable.KEEP_ALIVE_INTERVAL=300# Workspace auto-sync interval (seconds). Default: 180.SYNC_INTERVAL=180247 unmodified lines24824925025125225325425532 unmodified lines288289290291292293294247 unmodified linesGATEWAY_TOKEN=your_gateway_token_here# [OPTIONAL] JupyterLab terminal token for /terminal/# Set a strong token for private deployments. Must NOT be "huggingface".JUPYTER_TOKEN=run: openssl rand -hex 32# (Optional) Password auth — simpler alternative to token for casual users# If set, users can log in with this password instead of the token32 unmodified lines# Default: huggingclaw-backupBACKUP_DATASET_NAME=huggingclaw-backup# ── OPTIONAL: Background Services ──# Workspace auto-sync interval (seconds). Default: 180.SYNC_INTERVAL=180
20 unmodified lines21222324252627282920 unmodified linesRUN apt-get update && apt-get install -y \git \sudo \ca-certificates \jq \curl \python3 \python3-pip \chromium \20 unmodified lines21222324252627282930313220 unmodified linesRUN apt-get update && apt-get install -y \git \sudo \file \ca-certificates \jq \curl \dbus \dbus-x11 \python3 \python3-pip \chromium \
19 unmodified lines2021222324252630 unmodified lines5758596061626314 unmodified lines7879808182838419 unmodified lines104105106107108109110255 unmodified lines36636736836937037137237337437537637737837938038138238338438538615 unmodified lines40240340440540640740819 unmodified lines- name: GATEWAY_TOKENdescription: "Strong token to secure your OpenClaw Control UI (generate: openssl rand -hex 32)."- name: JUPYTER_TOKENdescription: "Optional strong token for the JupyterLab terminal at /terminal/ (defaults to huggingface)."- name: CLOUDFLARE_WORKERS_TOKENdescription: "Cloudflare API token — auto-creates a Worker proxy and KeepAlive monitor."- name: TELEGRAM_ALLOWED_USERS30 unmodified lines- [💻 Local Development](#-local-development)- [🔗 CLI Access](#-cli-access)- [💻 JupyterLab Terminal](#-jupyterlab-terminal)- [🔍 Merge Comparison](#-merge-comparison)- [🏗️ Architecture](#-architecture)- [💓 Staying Alive](#-staying-alive)- [🐛 Troubleshooting](#-troubleshooting)14 unmodified lines- 📊 **Visual Dashboard:** Beautiful Web UI to monitor uptime, sync status, and active models.- 🔔 **Webhooks:** Get notified on restarts or backup failures via standard webhooks.- 🔐 **Flexible Auth:** Secure the Control UI with either a gateway token or password.- 💻 **Optional Dev Terminal:** JupyterLab is available at `/terminal/` only when `DEV_MODE=true` (disabled by default).- 🏠 **100% HF-Native:** Runs entirely on HuggingFace’s free infrastructure (2 vCPU, 16GB RAM).## 🎥 Video Tutorial19 unmodified lines> [!TIP]> HuggingClaw is completely flexible! You only need these three secrets to get started. You can set other secrets later.Optional: set `DEV_MODE=true` (Variable) to enable JupyterLab support and install Jupyter dependencies at build time. You can also set `JUPYTER_TOKEN` as a Secret to replace the default terminal token (`huggingface`). If you want to pin a specific OpenClaw release instead of `latest`, add `OPENCLAW_VERSION` under **Variables** in your Space settings. For Docker Spaces, HF passes Variables as build args during image build, so these should be Variables, not Secrets (except tokens).### Step 3: Deploy & Run255 unmodified lines| :--- | :--- | :--- | :--- || `/` | HuggingClaw dashboard | `7861` | Public HF Spaces entrypoint || `/app/` | OpenClaw Control UI | `7860` | Mounted behind the local reverse proxy || `/terminal/` | JupyterLab terminal (DEV_MODE only) | `8888` | Available only when `DEV_MODE=true`; token login uses `JUPYTER_TOKEN` (default `huggingface`) |When enabled, the terminal notebook root is `/home/node`, so you can inspect HuggingClaw files, logs, workspace state, and runtime scripts from the browser.> [!IMPORTANT]> For real deployments, set a strong `JUPYTER_TOKEN` secret. The `huggingface` default exists only to match the duplicateable Hugging Face JupyterLab template.## 🔍 Merge ComparisonThis repository is a merge of two sources:- `anurag162008/HuggingClaw`: OpenClaw gateway, dashboard, Cloudflare proxy/keep-alive, Telegram/WhatsApp helpers, backup sync, key rotation, docs, and security metadata.- Hugging Face `SpacesExamples/jupyterlab` template: JupyterLab Docker behavior, token login UX, Hugging Face-branded login template, pinned Jupyter packages, and Git LFS defaults for large model/data artifacts.The main merge-specific change is the single-port router: HF Spaces exposes `7861`, while the router keeps OpenClaw at `/app/` and JupyterLab at `/terminal/` without leaking internal redirects such as `http://127.0.0.1:8888/...`.## 🏗️ Architecture15 unmodified lines2. Resolve backup namespace and restore workspace from HF Dataset.3. Generate `openclaw.json` configuration.4. Launch background tasks (auto-sync, channel helpers).5. Start the local dashboard/reverse proxy and OpenClaw gateway (JupyterLab starts only when `DEV_MODE=true`).</details>19 unmodified lines2021222324252630 unmodified lines57585960616214 unmodified lines7778798081828319 unmodified lines103104105106107108109110111255 unmodified lines36736836937037137237337437537637737815 unmodified lines39439539639739839940019 unmodified lines- name: GATEWAY_TOKENdescription: "Strong token to secure your OpenClaw Control UI (generate: openssl rand -hex 32)."- name: JUPYTER_TOKENdescription: "Optional token for the JupyterLab terminal at /terminal/. Defaults to GATEWAY_TOKEN when set — no extra secret needed."- name: CLOUDFLARE_WORKERS_TOKENdescription: "Cloudflare API token — auto-creates a Worker proxy and KeepAlive monitor."- name: TELEGRAM_ALLOWED_USERS30 unmodified lines- [💻 Local Development](#-local-development)- [🔗 CLI Access](#-cli-access)- [💻 JupyterLab Terminal](#-jupyterlab-terminal)- [🏗️ Architecture](#-architecture)- [💓 Staying Alive](#-staying-alive)- [🐛 Troubleshooting](#-troubleshooting)14 unmodified lines- 📊 **Visual Dashboard:** Beautiful Web UI to monitor uptime, sync status, and active models.- 🔔 **Webhooks:** Get notified on restarts or backup failures via standard webhooks.- 🔐 **Flexible Auth:** Secure the Control UI with either a gateway token or password.- 💻 **Terminal Out of the Box:** JupyterLab is available at `/terminal/` automatically when `GATEWAY_TOKEN` is set — no extra config needed. `GATEWAY_TOKEN` is reused as the terminal auth token. Set `DEV_MODE=false` explicitly to opt out.- 🏠 **100% HF-Native:** Runs entirely on HuggingFace’s free infrastructure (2 vCPU, 16GB RAM).## 🎥 Video Tutorial19 unmodified lines> [!TIP]> HuggingClaw is completely flexible! You only need these three secrets to get started. You can set other secrets later.**Terminal auto-enables when `GATEWAY_TOKEN` is set** — no extra secrets needed. `GATEWAY_TOKEN` is reused as `JUPYTER_TOKEN`, so the terminal is protected by the same credential as the Control UI. To set a different token, add `JUPYTER_TOKEN` as a Secret. To disable the terminal entirely, set `DEV_MODE=false` as a Variable.If you want to pin a specific OpenClaw release instead of `latest`, add `OPENCLAW_VERSION` under **Variables** in your Space settings. For Docker Spaces, HF passes Variables as build args during image build, so these should be Variables, not Secrets (except tokens).### Step 3: Deploy & Run255 unmodified lines| :--- | :--- | :--- | :--- || `/` | HuggingClaw dashboard | `7861` | Public HF Spaces entrypoint || `/app/` | OpenClaw Control UI | `7860` | Mounted behind the local reverse proxy || `/terminal/` | JupyterLab terminal | `8888` | Auto-enabled when `GATEWAY_TOKEN` is set; uses `GATEWAY_TOKEN` as auth token unless `JUPYTER_TOKEN` is set separately. Set `DEV_MODE=false` to disable. |When enabled, the terminal notebook root is `/home/node`, so you can inspect HuggingClaw files, logs, workspace state, and runtime scripts from the browser.> [!IMPORTANT]> No extra secret needed — `GATEWAY_TOKEN` is automatically reused as `JUPYTER_TOKEN`. Set a separate `JUPYTER_TOKEN` secret only if you want a different terminal credential.## 🏗️ Architecture15 unmodified lines2. Resolve backup namespace and restore workspace from HF Dataset.3. Generate `openclaw.json` configuration.4. Launch background tasks (auto-sync, channel helpers).5. Start the local dashboard/reverse proxy and OpenClaw gateway (JupyterLab starts when `GATEWAY_TOKEN` is set, `DEV_MODE=true`, or `HUGGINGCLAW_JUPYTER_ENABLED=true`).</details>
907 unmodified lines908909910911912913914907 unmodified lines<span class="pblock-title">📦 Bundle Output</span></div><div class="pblock-body"><textarea id="bundleOut" placeholder="Your encoded bundle will appear here…" readonly spellcheck="false"></textarea><input type="text" id="envLineOut" placeholder="HUGGINGCLAW_ENV_BUNDLE=…" readonly spellcheck="false"><div class="row-btns"><button id="copyBundle" class="btn btn-amber">⎘ Bundle</button>907 unmodified lines908909910911912913914915907 unmodified lines<span class="pblock-title">📦 Bundle Output</span></div><div class="pblock-body"><button id="generateBundle" class="btn btn-amber" style="width:100%;font-size:12.5px;"># Generate Bundle</button><textarea id="bundleOut" placeholder="Click # Generate to build your bundle…" readonly spellcheck="false"></textarea><input type="text" id="envLineOut" placeholder="HUGGINGCLAW_ENV_BUNDLE=…" readonly spellcheck="false"><div class="row-btns"><button id="copyBundle" class="btn btn-amber">⎘ Bundle</button>
457 unmodified lines45845946046146246346446546646714 unmodified lines482483484485486487354 unmodified lines842843844845846847848849850851852853854855856857858859860861862863102 unmodified lines9669679689699709719729739749759769779789799809819829839849859869879889891133 unmodified lines21232124212521262127212821295 unmodified lines213521362137213821392140214171 unmodified lines2213221422152216221722182219222022212222222322242225222682 unmodified lines230923102311231223132314231582 unmodified lines239823992400240124022403240424052406240724082409241018 unmodified lines242924302431243224332434243527 unmodified lines246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725183 unmodified lines252225232524252525262527457 unmodified lines"g": "Core","icon": "⚡","k": "OPENCLAW_VERSION","lbl": "Pin OpenClaw version","type": "text","ph": "latest","tag": "optional"},{"g": "Plugins",14 unmodified lines"common": 1,"tag": "build"},{"g": "Startup","icon": "⚡",354 unmodified lines"g": "Core","icon": "⚡","k": "JUPYTER_TOKEN","lbl": "Jupyter access token","type": "password","ph": "huggingface","common": 1,"tag": "credential"},{"g": "Core","icon": "⚡","k": "KEEP_ALIVE_INTERVAL","lbl": "Keep-alive ping interval (seconds)","type": "number","ph": "300","common": 1,"tag": "advanced"},{"g": "Core","icon": "⚡",102 unmodified lines"ph": "/home/node","tag": "advanced"},{"g": "Backup","icon": "💾","k": "WORKSPACE_GIT_USER","lbl": "Workspace git author email","type": "text","ph": "openclaw@example.com","tag": "optional"},{"g": "Backup","icon": "💾","k": "WORKSPACE_GIT_NAME","lbl": "Workspace git author name","type": "text","ph": "OpenClaw Bot","tag": "optional"},{"g": "Provider Keys","icon": "🔑",1133 unmodified linesreturn control;}function cardHTML(f) {const TAG_META = {critical: { cls: 'badge-critical', lbl: 'critical' },credential: { cls: 'badge-credential', lbl: 'credential' },5 unmodified linesconst tm = TAG_META[f.tag] || TAG_META.optional;const badge = `<span class="badge ${tm.cls}">${tm.lbl}</span>`;return `<div class="env-card" data-row data-group="${esc(f.g)}" data-search="${esc((f.g + ' ' + f.k + ' ' + (f.lbl || '') + ' ' + (f.tag || '')).toLowerCase())}"><div class="card-top"><input type="checkbox" class="card-check" data-check="${esc(f.k)}" ${f.common ? 'data-common="1"' : ''}><div class="card-info">71 unmodified linesreturn obj;}function refresh() {const obj = collect();const keys = Object.keys(obj).sort();const bundle = keys.length ? encodeBundle(Object.fromEntries(keys.map(k => [k, obj[k]]))) : '';$('bundleOut').value = bundle;$('envLineOut').value = bundle ? `HUGGINGCLAW_ENV_BUNDLE=${bundle}` : '';const s = $('summary');if (keys.length) {s.innerHTML = `<strong>${keys.length}</strong> variable${keys.length > 1 ? 's' : ''} selected<div class="sum-keys">${keys.map(k => `<span class="sum-key">${esc(k)}</span>`).join('')}</div>`;82 unmodified linesaddCustomRow(key, val, true);}}markSelected(); filter(); refresh();}function autoCheck(key) {82 unmodified linesconst chk = document.querySelector(`[data-check="${CSS.escape(key)}"]`);if (chk) {chk.checked = on;markSelected();}refresh();}function bindFieldEvents() {document.querySelectorAll('[data-check]').forEach(el => el.addEventListener('change', () => { markSelected(); refresh(); }));document.querySelectorAll('[data-key]').forEach(el => el.addEventListener('input', refresh));document.querySelectorAll('[data-toggle]').forEach(btn => btn.addEventListener('click', () => toggleField(btn.dataset.toggle)));document.querySelectorAll('[data-pick-for]').forEach(sel => sel.addEventListener('change', () => handlePickerChange(sel)));18 unmodified lines<span class="sec-count">${items.length}</span><div class="sec-line"></div></div><div class="cards">${items.map(cardHTML).join('')}</div>`;wrap.appendChild(sec);});bindFieldEvents();27 unmodified lines$('search').oninput = filter;$('selectCommon').onclick = () => {document.querySelectorAll('[data-common="1"]').forEach(c => c.checked = true);markSelected();refresh();};$('selectVisible').onclick = () => {document.querySelectorAll('.sec:not(.sec-hidden) [data-row]:not(.hidden) [data-check]').forEach(c => c.checked = true);markSelected();refresh();};$('clearAll').onclick = () => {clearForm();markSelected();filter();refresh();};$('applyImport').onclick = () => {try {applyObj(parseEnv($('importText').value), true);showToast('Imported ✓');} catch (e) {showToast('Import failed');alert(e.message);}};// Auto-import: paste karo aur turant parse + apply ho jaata hai$('importText').addEventListener('paste', () => {setTimeout(() => {try {const val = $('importText').value.trim();if (!val) return;applyObj(parseEnv(val), true);showToast('Auto-imported ✓');} catch (e) {showToast('Import failed');}}, 0);});// Live typing: jaise jaise type karo env format mein, bundle banta jaata hai$('importText').addEventListener('input', () => {const val = $('importText').value.trim();if (!val) return;// Sirf agar valid env/bundle format lag raha ho tabhi auto-applyconst looksLikeEnv = val.includes('=') || val.startsWith('{') || /^[A-Za-z0-9_\-]{20,}$/.test(val);if (looksLikeEnv) {try {applyObj(parseEnv(val), true);} catch (e) { /* silent — user abhi type kar raha hai */ }}});$('addCustom').onclick = () => addCustomRow();$('applyBundle').onclick = () => {try {3 unmodified linesshowToast('Invalid bundle');}};$('copyBundle').onclick = () => copyText($('bundleOut').value);$('copyEnvLine').onclick = () => copyText($('envLineOut').value);$('copyJson').onclick = () => copyText(JSON.stringify(collect(), null, 2));457 unmodified lines45845946046146246346446546646714 unmodified lines482483484485486487488489490491492493494495496354 unmodified lines851852853854855856857858859860861862102 unmodified lines9659669679689699701133 unmodified lines21042105210621072108210921105 unmodified lines211621172118211921202121212271 unmodified lines2194219521962197219821992200220122022203220422052206220722082209221082 unmodified lines229322942295229622972298229982 unmodified lines238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241518 unmodified lines243424352436243724382439244027 unmodified lines24682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625073 unmodified lines2511251225132514251525162517457 unmodified lines"g": "Core","icon": "⚡","k": "OPENCLAW_VERSION","lbl": "Pin OpenClaw version (build-time; rebuild required)","type": "text","ph": "latest","tag": "build"},{"g": "Plugins",14 unmodified lines"common": 1,"tag": "build"},{"g": "Startup","icon": "🩺","k": "AUTO_DOCTOR","lbl": "Auto-fix config on boot (openclaw doctor --fix)","type": "toggle","ph": "false","tag": "advanced"},{"g": "Startup","icon": "⚡",354 unmodified lines"g": "Core","icon": "⚡","k": "JUPYTER_TOKEN","lbl": "Jupyter access token (Must NOT be 'huggingface'. Run: openssl rand -hex 32)","type": "password","ph": "change_this_to_a_strong_token","common": 1,"tag": "credential"},{"g": "Core","icon": "⚡",102 unmodified lines"ph": "/home/node","tag": "advanced"},{"g": "Provider Keys","icon": "🔑",1133 unmodified linesreturn control;}function cardHTML(f, origIdx = 0) {const TAG_META = {critical: { cls: 'badge-critical', lbl: 'critical' },credential: { cls: 'badge-credential', lbl: 'credential' },5 unmodified linesconst tm = TAG_META[f.tag] || TAG_META.optional;const badge = `<span class="badge ${tm.cls}">${tm.lbl}</span>`;return `<div class="env-card" data-row data-orig-idx="${origIdx}" data-group="${esc(f.g)}" data-search="${esc((f.g + ' ' + f.k + ' ' + (f.lbl || '') + ' ' + (f.tag || '')).toLowerCase())}"><div class="card-top"><input type="checkbox" class="card-check" data-check="${esc(f.k)}" ${f.common ? 'data-common="1"' : ''}><div class="card-info">71 unmodified linesreturn obj;}function generateBundle() {const obj = collect();const keys = Object.keys(obj).sort();const bundle = keys.length ? encodeBundle(Object.fromEntries(keys.map(k => [k, obj[k]]))) : '';$('bundleOut').value = bundle;$('envLineOut').value = bundle ? `HUGGINGCLAW_ENV_BUNDLE=${bundle}` : '';}function refresh() {const obj = collect();const keys = Object.keys(obj).sort();const s = $('summary');if (keys.length) {s.innerHTML = `<strong>${keys.length}</strong> variable${keys.length > 1 ? 's' : ''} selected<div class="sum-keys">${keys.map(k => `<span class="sum-key">${esc(k)}</span>`).join('')}</div>`;82 unmodified linesaddCustomRow(key, val, true);}}sortAllSections(); markSelected(); filter(); refresh();}function autoCheck(key) {82 unmodified linesconst chk = document.querySelector(`[data-check="${CSS.escape(key)}"]`);if (chk) {chk.checked = on;sortSection(inp.closest('[data-row]'));markSelected();}refresh();}function sortSection(cardEl) {const cards = cardEl && cardEl.closest('.cards');if (!cards) return;const all = [...cards.querySelectorAll('[data-row]')];const checked = all.filter(c => c.querySelector('[data-check]')?.checked);const rest = all.filter(c => !c.querySelector('[data-check]')?.checked);rest.sort((a, b) => Number(a.dataset.origIdx) - Number(b.dataset.origIdx));[...checked, ...rest].forEach(c => cards.appendChild(c));}function sortAllSections() {document.querySelectorAll('.cards').forEach(cards => {const all = [...cards.querySelectorAll('[data-row]')];const checked = all.filter(c => c.querySelector('[data-check]')?.checked);const rest = all.filter(c => !c.querySelector('[data-check]')?.checked);rest.sort((a, b) => Number(a.dataset.origIdx) - Number(b.dataset.origIdx));[...checked, ...rest].forEach(c => cards.appendChild(c));});}function bindFieldEvents() {document.querySelectorAll('[data-check]').forEach(el => el.addEventListener('change', () => { sortSection(el.closest('[data-row]')); markSelected(); refresh(); }));document.querySelectorAll('[data-key]').forEach(el => el.addEventListener('input', refresh));document.querySelectorAll('[data-toggle]').forEach(btn => btn.addEventListener('click', () => toggleField(btn.dataset.toggle)));document.querySelectorAll('[data-pick-for]').forEach(sel => sel.addEventListener('change', () => handlePickerChange(sel)));18 unmodified lines<span class="sec-count">${items.length}</span><div class="sec-line"></div></div><div class="cards">${items.map((f, i) => cardHTML(f, i)).join('')}</div>`;wrap.appendChild(sec);});bindFieldEvents();27 unmodified lines$('search').oninput = filter;$('selectCommon').onclick = () => {document.querySelectorAll('[data-common="1"]').forEach(c => c.checked = true);sortAllSections();markSelected();refresh();};$('selectVisible').onclick = () => {document.querySelectorAll('.sec:not(.sec-hidden) [data-row]:not(.hidden) [data-check]').forEach(c => c.checked = true);sortAllSections();markSelected();refresh();};$('clearAll').onclick = () => {clearForm();sortAllSections();markSelected();filter();refresh();};$('applyImport').onclick = () => {try {const parsed = parseEnv($('importText').value);const count = Object.keys(parsed).length;if (!count) {showToast('No valid env keys found');return;}applyObj(parsed, true);showToast(`Imported ${count} key${count > 1 ? 's' : ''} ✓`);} catch (e) {showToast('Import failed');alert(e.message);}};// Import is explicit via the Import & Apply button to avoid surprising UI resets.$('addCustom').onclick = () => addCustomRow();$('applyBundle').onclick = () => {try {3 unmodified linesshowToast('Invalid bundle');}};$('generateBundle').onclick = () => generateBundle();$('copyBundle').onclick = () => copyText($('bundleOut').value);$('copyEnvLine').onclick = () => copyText($('envLineOut').value);$('copyJson').onclick = () => copyText(JSON.stringify(collect(), null, 2));
19 unmodified lines20212223242526272843 unmodified lines72737475767778556 unmodified lines63563663763863964064119 unmodified linesconst JUPYTER_PORT = Number.parseInt(process.env.JUPYTER_PORT || "8888", 10);const JUPYTER_HOST = "127.0.0.1";const JUPYTER_BASE = normalizeBase(process.env.JUPYTER_BASE, "/terminal");const DEV_MODE_ENABLED = isTrue(process.env.DEV_MODE);const JUPYTER_ENABLED = /^(true|1|yes|on)$/i.test(process.env.HUGGINGCLAW_JUPYTER_ENABLED || (DEV_MODE_ENABLED ? "true" : "false"));const startTime = Date.now();const LLM_MODEL = process.env.LLM_MODEL || "Not Set";43 unmodified linesSPACE_IS_PRIVATE = false;_privacyDetectionDone = true;console.log("[health-server] Space privacy: public (SPACE_PRIVACY env var override)");privacyDetectionReady.then ? void 0 : null;_privacyDetectionResolve && _privacyDetectionResolve();} else if (_spacPrivacyEnv === "private") {// User explicitly set SPACE_PRIVACY=private — skip API call entirely556 unmodified linesif (pathname === JUPYTER_BASE || pathname.startsWith(JUPYTER_BASE + "/")) {if (!JUPYTER_ENABLED) {res.writeHead(404, { "Content-Type": "application/json" });return res.end(JSON.stringify({ status: "disabled", message: "JupyterLab terminal is disabled. Set DEV_MODE=true to enable /terminal/." }));}if (isDirectHfSpaceRequest) {res.writeHead(200, { "Content-Type": "text/html" });19 unmodified lines20212223242526272829303143 unmodified lines757677787980556 unmodified lines63763863964064164264319 unmodified linesconst JUPYTER_PORT = Number.parseInt(process.env.JUPYTER_PORT || "8888", 10);const JUPYTER_HOST = "127.0.0.1";const JUPYTER_BASE = normalizeBase(process.env.JUPYTER_BASE, "/terminal");const GATEWAY_TOKEN = (process.env.GATEWAY_TOKEN || "").trim();const DEV_MODE_ENABLED = isTrue(process.env.DEV_MODE);// Auto-enable Jupyter when DEV_MODE=true, HUGGINGCLAW_JUPYTER_ENABLED=true, or GATEWAY_TOKEN is set.// GATEWAY_TOKEN doubles as JUPYTER_TOKEN in start.sh — no extra secret needed.const JUPYTER_ENABLED = /^(true|1|yes|on)$/i.test(process.env.HUGGINGCLAW_JUPYTER_ENABLED || (DEV_MODE_ENABLED ? "true" : GATEWAY_TOKEN ? "true" : "false"));const startTime = Date.now();const LLM_MODEL = process.env.LLM_MODEL || "Not Set";43 unmodified linesSPACE_IS_PRIVATE = false;_privacyDetectionDone = true;console.log("[health-server] Space privacy: public (SPACE_PRIVACY env var override)");_privacyDetectionResolve && _privacyDetectionResolve();} else if (_spacPrivacyEnv === "private") {// User explicitly set SPACE_PRIVACY=private — skip API call entirely556 unmodified linesif (pathname === JUPYTER_BASE || pathname.startsWith(JUPYTER_BASE + "/")) {if (!JUPYTER_ENABLED) {res.writeHead(404, { "Content-Type": "application/json" });return res.end(JSON.stringify({ status: "disabled", message: "JupyterLab terminal is disabled. Set GATEWAY_TOKEN or DEV_MODE=true to enable /terminal/ (or set HUGGINGCLAW_JUPYTER_ENABLED=true)." }));}if (isDirectHfSpaceRequest) {res.writeHead(200, { "Content-Type": "text/html" });
18 unmodified lines19202122232425262718 unmodified linesif (event === "request") {const [, res] = args;// Only intercept on the main OpenClaw server (port 7860)const serverPort = this.address && this.address() && this.address().port;if (serverPort && serverPort !== 7860) {return origEmit.apply(this, [event, ...args]);}18 unmodified lines1920212223242526272818 unmodified linesif (event === "request") {const [, res] = args;// Only intercept on the main OpenClaw server (respects GATEWAY_PORT env var)const expectedPort = Number(process.env.GATEWAY_PORT || 7860);const serverPort = this.address && this.address() && this.address().port;if (serverPort && serverPort !== expectedPort) {return origEmit.apply(this, [event, ...args]);}
173 unmodified lines174175176177178179173 unmodified linesreturn Falsedef restore_once(api, rid: str):from huggingface_hub.errors import RepositoryNotFoundErrortmp = Path(tempfile.mkdtemp(prefix="devdata-restore-"))try:173 unmodified lines174175176177178179180173 unmodified linesreturn Falsedef restore_once(api, rid: str):from huggingface_hub import snapshot_downloadfrom huggingface_hub.errors import RepositoryNotFoundErrortmp = Path(tempfile.mkdtemp(prefix="devdata-restore-"))try:
191 unmodified lines192193194195196197122 unmodified lines320321322323324325326191 unmodified linesenvPlural: 'MODELSTUDIO_API_KEYS',envSingular:'MODELSTUDIO_API_KEY',},];122 unmodified lines// Gemini: key URL query param mein jaata hai, Bearer nahiconst url = new URL(typeof input === 'string' ? input : input.url);url.searchParams.set('key', key);input = typeof input === 'string' ? url.toString() : new Request(url.toString(), input);} else {const headers = init.headers || (input && input.headers) || undefined;const patchedHeaders = setAuthHeader(headers, key);191 unmodified lines192193194195196197198199200201202203122 unmodified lines326327328329330331332333334335336337338339340341342343344345346347348349350191 unmodified linesenvPlural: 'MODELSTUDIO_API_KEYS',envSingular:'MODELSTUDIO_API_KEY',},{name: 'synthetic',hostname: /(?:^|\.)synthetic\.local$/i,envPlural: 'SYNTHETIC_API_KEYS',envSingular: 'SYNTHETIC_API_KEY',},];122 unmodified lines// Gemini: key URL query param mein jaata hai, Bearer nahiconst url = new URL(typeof input === 'string' ? input : input.url);url.searchParams.set('key', key);if (typeof input === 'string') {input = url.toString();} else {// Do NOT pass the Request object as init — that clones (consumes) the body stream.// Instead patch only the URL via init object; fetch spec merges headers from Request.init = {method: input.method,headers: input.headers,body: input.body,mode: input.mode,credentials: input.credentials,cache: input.cache,redirect: input.redirect,referrer: input.referrer,integrity: input.integrity,...init,};input = url.toString();}} else {const headers = init.headers || (input && input.headers) || undefined;const patchedHeaders = setAuthHeader(headers, key);
41 unmodified lines42434445464742 unmodified lines9091929394953 unmodified lines99100101102103104215 unmodified lines32032132232332432532626 unmodified lines3533543553563573583593606 unmodified lines367368369370371372373132 unmodified lines50650750850951051151251351451551651745 unmodified lines563564565566567568569570571572573574575104 unmodified lines6806816826836846858 unmodified lines69469569669769869970070170212 unmodified lines71571671771871972037 unmodified lines75875976076176276376452 unmodified lines81781881982082182282382482582682782882983083183283383483583628 unmodified lines865866867868869870567 unmodified lines1438143914401441144214431444111 unmodified lines15561557155815591560156119 unmodified lines15811582158315841585158615871588158915906 unmodified lines15971598159916001601160216031604160516061607160816098 unmodified lines1618161916201621162216231624162516261627162816291630163141 unmodified linescontinueif str(key) in {"HUGGINGCLAW_ENV_BUNDLE", "ENV_BUNDLE"}:continueif os.environ.get(str(key), ""):continueif value is None or isinstance(value, (dict, list)):42 unmodified linesif hc_is_true "$DEV_MODE_NORMALIZED"; thenDEV_MODE_ENABLED=truefiSYNC_INTERVAL="$(trim_var "${SYNC_INTERVAL:-180}")"DEVDATA_DATASET_NAME="$(trim_var "${DEVDATA_DATASET_NAME:-huggingclaw-devdata}")"DEVDATA_SYNC_INTERVAL="$(trim_var "${DEVDATA_SYNC_INTERVAL:-180}")"3 unmodified linesif ! hc_is_true "$DEVDATA_NORMALIZED"; thenDEVDATA_ENABLED=falsefiif [ -n "${SPACE_HOST:-}" ]; thenOPENCLAW_CONSOLE_LOG_LEVEL="${OPENCLAW_CONSOLE_LOG_LEVEL:-warn}"OPENCLAW_FILE_LOG_LEVEL="${OPENCLAW_FILE_LOG_LEVEL:-info}"215 unmodified lines{"gateway": {"mode": "local","port": 7860,"bind": "lan","auth": {"token": ""26 unmodified lines--arg fileLevel "$OPENCLAW_FILE_LOG_LEVEL" \--arg consoleLevel "$OPENCLAW_CONSOLE_LOG_LEVEL" \--arg consoleStyle "$OPENCLAW_CONSOLE_LOG_STYLE" \'.gateway.auth.token = $token| .agents.defaults.model = $model| .logging.level = $fileLevel| .logging.consoleLevel = $consoleLevel| .logging.consoleStyle = $consoleStyle' <<<"$CONFIG_JSON")6 unmodified linesCUSTOM_API_KEY="${CUSTOM_API_KEY:-$LLM_API_KEY}"CUSTOM_API_TYPE="${CUSTOM_API_TYPE:-openai-completions}"CUSTOM_CONTEXT_WINDOW="${CUSTOM_CONTEXT_WINDOW:-128000}"CUSTOM_MAX_TOKENS="${CUSTOM_MAX_TOKENS:-500}"if [ -n "$CUSTOM_PROVIDER_NAME" ] || [ -n "$CUSTOM_BASE_URL" ] || [ -n "$CUSTOM_MODEL_ID" ]; thenCUSTOM_PROVIDER_NORMALIZED=$(printf '%s' "$CUSTOM_PROVIDER_NAME" | tr '[:upper:]' '[:lower:]')132 unmodified lines# Browser configuration (managed local Chromium in HF/Docker)BROWSER_EXECUTABLE_PATH=""for candidate in /usr/bin/chromium /usr/bin/chromium-browser /snap/bin/chromium; doif [ -x "$candidate" ]; thenBROWSER_EXECUTABLE_PATH="$candidate"breakfidoneBROWSER_SHOULD_ENABLE=falseif [ "$BROWSER_PLUGIN_MODE" = "enabled" ] && [ -n "$BROWSER_EXECUTABLE_PATH" ] && [ -x "$BROWSER_EXECUTABLE_PATH" ]; then45 unmodified linesif [ "$BROWSER_SHOULD_ENABLE" = "true" ]; thenCONFIG_JSON=$(jq \--arg execPath "$BROWSER_EXECUTABLE_PATH" \'.browser = {"enabled": true,"defaultProfile": "openclaw","headless": true,"noSandbox": true,"executablePath": $execPath}| .agents.defaults.sandbox.browser.allowHostControl = true' <<<"$CONFIG_JSON")fi104 unmodified linesif [ "$WHATSAPP_ENABLED_NORMALIZED" = "true" ]; thenWHATSAPP_CONFIG_ENABLED=truefiif [ -f "$EXISTING_CONFIG" ]; thenecho "Restored config found — patching required fields and runtime channel/plugin toggles..."PATCHED=$(jq \8 unmodified lines--argjson consoleStyleConfigured "$OPENCLAW_CONSOLE_LOG_STYLE_CONFIGURED" \--argjson whatsappConfigured "$WHATSAPP_ENABLED_CONFIGURED" \--argjson whatsappEnabled "$WHATSAPP_CONFIG_ENABLED" \'(.channels.whatsapp // {}) as $existingWhatsapp| .gateway.auth.token = $token| .agents.defaults.model = $model| if $fileLogConfigured then .logging.level = $fileLevel else . end| if $consoleLogConfigured then .logging.consoleLevel = $consoleLevel else . end| if $consoleStyleConfigured then .logging.consoleStyle = $consoleStyle else . end12 unmodified lines| del(.channels.whatsapp)else.end' \"$EXISTING_CONFIG" 2>/dev/null)37 unmodified linesif [ -n "${CLOUDFLARE_PROXY_URL:-}" ]; thenecho "Proxy : ${CLOUDFLARE_PROXY_URL}"fiRUNTIME_JUPYTER_ENABLED="$DEV_MODE_ENABLED"# Add user bin to PATH for jupyter-lab (installed in Dockerfile when DEV_MODE=true)export PATH="$HOME/.local/bin:$PATH"52 unmodified lines}trap graceful_shutdown SIGTERM SIGINTwarmup_browser() {[ "$BROWSER_SHOULD_ENABLE" = "true" ] || return 0(sleep 5local attemptfor attempt in 1 2 3 4 5; doif openclaw browser --browser-profile openclaw start >/dev/null 2>&1; thenopenclaw browser --browser-profile openclaw open about:blank >/dev/null 2>&1 || trueecho "Managed browser ready."return 0fisleep 2doneecho "Warning: managed browser warm-up did not complete; first browser action may need a retry."28 unmodified linesreturn 0fi# Security guard: refuse to start JupyterLab with the insecure default token.# JupyterLab exposes a full shell — a weak token is equivalent to no auth.if [ -z "${JUPYTER_TOKEN:-}" ] || [ "${JUPYTER_TOKEN}" = "huggingface" ]; then567 unmodified linesfi# ── Fix config before running startup commands ──openclaw doctor --fix || true# ── Arbitrary startup commands from HF Variables/Secrets ──# Recommended: use one variable, HUGGINGCLAW_RUN, as a full bash script. If the111 unmodified linesecho "WhatsApp Guardian started (PID: $GUARDIAN_PID)"}while true; do# Check health-server process - restart if died unexpectedlyif [ -n "${HEALTH_PID:-}" ] && ! kill -0 "$HEALTH_PID" 2>/dev/null; then19 unmodified linesfifiopenclaw doctor --fix || trueecho "Launching OpenClaw gateway on port 7860..."GATEWAY_ARGS=(gateway run --port 7860 --bind lan)if [ "${GATEWAY_VERBOSE:-0}" = "1" ]; thenGATEWAY_ARGS+=(--verbose)echo "Gateway verbose logging enabled (GATEWAY_VERBOSE=1)"6 unmodified linesstdbuf -oL -eL openclaw "${GATEWAY_ARGS[@]}" 2>&1 | tee -a /home/node/.openclaw/gateway.log &GATEWAY_PID=$!# Poll for the gateway to start listening on 7860. OpenClaw can take 20-30s# on cold start (plugin install + auto-restore). Bail out early if the# pipeline died.GATEWAY_READY_TIMEOUT="${GATEWAY_READY_TIMEOUT:-90}"ready=falsefor ((i=0; i<GATEWAY_READY_TIMEOUT; i++)); doif (echo > /dev/tcp/127.0.0.1/7860) 2>/dev/null; thenready=truebreakfi8 unmodified linesecho "Gateway failed to start. Last 30 lines of log:"echo "────────────────────────────────────────────"tail -30 /home/node/.openclaw/gateway.logecho "Gateway failed — JupyterLab and env-builder still running. Retrying in 10s..."sleep 10continuefi# 11. Start WhatsApp Guardian after the gateway is accepting connectionsstart_guardian_once# 11.5 Warm up the managed browser so first browser actions have a live tabwarmup_browser41 unmodified lines42434445464748495042 unmodified lines939495969798991001011021031043 unmodified lines108109110111112113114115116215 unmodified lines33233333433533633733826 unmodified lines3653663673683693703713723733746 unmodified lines381382383384385386387132 unmodified lines52052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359445 unmodified lines640641642643644645646647648649650651652653654655656657658659660661662663664665666667104 unmodified lines7727737747757767777787797807818 unmodified lines79079179279379479579679779879980012 unmodified lines81381481581681781881982082182282382482537 unmodified lines86386486586686786886987087187287387487552 unmodified lines92892993093193293393493593693793893994094194294394494594694794894995095128 unmodified lines980981982983984985986987988989990991992567 unmodified lines156015611562156315641565156615671568111 unmodified lines168016811682168316841685168616871688168916901691169216931694169519 unmodified lines1715171617171718171917201721172217231724172517266 unmodified lines17331734173517361737173817391740174117421743174417458 unmodified lines1754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178241 unmodified linescontinueif str(key) in {"HUGGINGCLAW_ENV_BUNDLE", "ENV_BUNDLE"}:continueif str(key) == "OPENCLAW_VERSION":print("Warning: OPENCLAW_VERSION from env bundle is ignored (build-time only; set HF Variable and rebuild).", file=sys.stderr)continueif os.environ.get(str(key), ""):continueif value is None or isinstance(value, (dict, list)):42 unmodified linesif hc_is_true "$DEV_MODE_NORMALIZED"; thenDEV_MODE_ENABLED=truefi# Auto-enable DEV_MODE when GATEWAY_TOKEN is set and DEV_MODE was not explicitly configured.# GATEWAY_TOKEN doubles as JUPYTER_TOKEN (see start_jupyter_once) — no extra secret required.if [ "$DEV_MODE_ENABLED" != "true" ] && [ -z "${DEV_MODE:-}" ] && [ -n "${GATEWAY_TOKEN:-}" ]; thenDEV_MODE_ENABLED=trueecho "GATEWAY_TOKEN set and DEV_MODE not explicitly configured — auto-enabling terminal (set DEV_MODE=false to opt out)"fiSYNC_INTERVAL="$(trim_var "${SYNC_INTERVAL:-180}")"DEVDATA_DATASET_NAME="$(trim_var "${DEVDATA_DATASET_NAME:-huggingclaw-devdata}")"DEVDATA_SYNC_INTERVAL="$(trim_var "${DEVDATA_SYNC_INTERVAL:-180}")"3 unmodified linesif ! hc_is_true "$DEVDATA_NORMALIZED"; thenDEVDATA_ENABLED=falsefi# On HF Spaces, browser is disabled by default (no display server).# To enable: set BROWSER_PLUGIN_MODE=enabled as an HF Space secret.# WARNING: requires at least CPU Upgrade tier (2 vCPU / 16GB RAM).if [ -n "${SPACE_HOST:-}" ]; thenOPENCLAW_CONSOLE_LOG_LEVEL="${OPENCLAW_CONSOLE_LOG_LEVEL:-warn}"OPENCLAW_FILE_LOG_LEVEL="${OPENCLAW_FILE_LOG_LEVEL:-info}"215 unmodified lines{"gateway": {"mode": "local","port": "${GATEWAY_PORT}","bind": "lan","auth": {"token": ""26 unmodified lines--arg fileLevel "$OPENCLAW_FILE_LOG_LEVEL" \--arg consoleLevel "$OPENCLAW_CONSOLE_LOG_LEVEL" \--arg consoleStyle "$OPENCLAW_CONSOLE_LOG_STYLE" \--arg port "$GATEWAY_PORT" \'.gateway.auth.token = $token| .agents.defaults.model = $model| .gateway.port = ($port | tonumber)| .logging.level = $fileLevel| .logging.consoleLevel = $consoleLevel| .logging.consoleStyle = $consoleStyle' <<<"$CONFIG_JSON")6 unmodified linesCUSTOM_API_KEY="${CUSTOM_API_KEY:-$LLM_API_KEY}"CUSTOM_API_TYPE="${CUSTOM_API_TYPE:-openai-completions}"CUSTOM_CONTEXT_WINDOW="${CUSTOM_CONTEXT_WINDOW:-128000}"CUSTOM_MAX_TOKENS="${CUSTOM_MAX_TOKENS:-8192}"if [ -n "$CUSTOM_PROVIDER_NAME" ] || [ -n "$CUSTOM_BASE_URL" ] || [ -n "$CUSTOM_MODEL_ID" ]; thenCUSTOM_PROVIDER_NORMALIZED=$(printf '%s' "$CUSTOM_PROVIDER_NAME" | tr '[:upper:]' '[:lower:]')132 unmodified lines# Browser configuration (managed local Chromium in HF/Docker)BROWSER_EXECUTABLE_PATH=""BROWSER_WRAPPER_PATH=""HAS_FILE_CMD=falseif command -v file >/dev/null 2>&1; thenHAS_FILE_CMD=truefiensure_chromium_for_browser_plugin() {# Enforce Chromium availability when browser plugin is explicitly enabled.[ "$BROWSER_PLUGIN_MODE" = "enabled" ] || return 0for candidate in /usr/lib/chromium/chromium /usr/bin/chromium /usr/bin/chromium-browser; do[ -x "$candidate" ] && return 0doneif [ "$HAS_FILE_CMD" != "true" ]; thenecho "BROWSER_PLUGIN_MODE=enabled and 'file' command is missing; attempting runtime install..."if _hc_apt_install file; thenHAS_FILE_CMD=trueecho "'file' command installed via apt-get."elseecho "Warning: could not install 'file'; continuing with executable-path fallback checks."fifiecho "BROWSER_PLUGIN_MODE=enabled but Chromium is missing; attempting runtime install..."if _hc_apt_install chromium; thenecho "Chromium installed via apt-get."return 0fiif _hc_apt_install chromium-browser; thenecho "Chromium browser package installed via apt-get."return 0fiecho "ERROR: Browser plugin is enabled, but Chromium install failed. Disable browser plugin or rebuild image with Chromium preinstalled." >&2return 1}ensure_chromium_for_browser_plugin || HC_STARTUP_FAILURES=$((HC_STARTUP_FAILURES + 1))# On Debian/Ubuntu, /usr/bin/chromium is often a shell wrapper while the real# ELF binary lives under /usr/lib/chromium/*. Prefer a real ELF binary, then# fall back to wrapper launchers (Playwright/OpenClaw can execute those too).for candidate in \/usr/lib/chromium/chromium \/usr/lib/chromium-browser/chromium-browser \/usr/bin/chromium \/usr/bin/chromium-browser \/snap/bin/chromium; doif [ -x "$candidate" ]; thenif [ "$HAS_FILE_CMD" = "true" ]; thenif file "$candidate" 2>/dev/null | grep -q "ELF"; thenBROWSER_EXECUTABLE_PATH="$candidate"breakfielse# Minimal images may not ship `file`; accept the first executable path.BROWSER_EXECUTABLE_PATH="$candidate"breakfiif [ -z "$BROWSER_WRAPPER_PATH" ]; thenBROWSER_WRAPPER_PATH="$candidate"fifidoneif [ -z "$BROWSER_EXECUTABLE_PATH" ] && [ -n "$BROWSER_WRAPPER_PATH" ]; thenBROWSER_EXECUTABLE_PATH="$BROWSER_WRAPPER_PATH"echo "No ELF Chromium binary found; using launcher wrapper at $BROWSER_EXECUTABLE_PATH"elif [ -n "$BROWSER_EXECUTABLE_PATH" ] && [ "$HAS_FILE_CMD" != "true" ]; thenecho "Detected Chromium executable at $BROWSER_EXECUTABLE_PATH (ELF probe skipped: 'file' command not installed)"fiif [ -z "$BROWSER_EXECUTABLE_PATH" ]; thenecho "Warning: Chromium executable not found. Browser plugin will be disabled."fiBROWSER_SHOULD_ENABLE=falseif [ "$BROWSER_PLUGIN_MODE" = "enabled" ] && [ -n "$BROWSER_EXECUTABLE_PATH" ] && [ -x "$BROWSER_EXECUTABLE_PATH" ]; then45 unmodified linesif [ "$BROWSER_SHOULD_ENABLE" = "true" ]; thenCONFIG_JSON=$(jq \'.browser = {"enabled": true,"defaultProfile": "openclaw","headless": true,"noSandbox": true,"extraArgs": ["--headless=new","--no-sandbox","--disable-setuid-sandbox","--no-zygote","--disable-dev-shm-usage","--disable-gpu","--remote-debugging-address=127.0.0.1","--disable-features=UseDBus,MediaRouter","--password-store=basic","--no-first-run","--disable-background-networking","--disable-sync","--disable-translate","--disable-notifications","--disable-speech-api"]}| .agents.defaults.sandbox.browser.allowHostControl = true' <<<"$CONFIG_JSON")fi104 unmodified linesif [ "$WHATSAPP_ENABLED_NORMALIZED" = "true" ]; thenWHATSAPP_CONFIG_ENABLED=truefiTELEGRAM_CONFIG_ENABLED=falseif [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; thenTELEGRAM_CONFIG_ENABLED=truefiif [ -f "$EXISTING_CONFIG" ]; thenecho "Restored config found — patching required fields and runtime channel/plugin toggles..."PATCHED=$(jq \8 unmodified lines--argjson consoleStyleConfigured "$OPENCLAW_CONSOLE_LOG_STYLE_CONFIGURED" \--argjson whatsappConfigured "$WHATSAPP_ENABLED_CONFIGURED" \--argjson whatsappEnabled "$WHATSAPP_CONFIG_ENABLED" \--argjson telegramConfigured "$TELEGRAM_CONFIG_ENABLED" \'(.channels.whatsapp // {}) as $existingWhatsapp| .gateway.auth.token = $token| .agents.defaults.model = $model| .gateway.port = ($desired.gateway.port // .gateway.port)| if $fileLogConfigured then .logging.level = $fileLevel else . end| if $consoleLogConfigured then .logging.consoleLevel = $consoleLevel else . end| if $consoleStyleConfigured then .logging.consoleStyle = $consoleStyle else . end12 unmodified lines| del(.channels.whatsapp)else.end| if $telegramConfigured then.channels.telegram = (($desired.channels.telegram // {}) * (.channels.telegram // {}))| .channels.telegram.botToken = $desired.channels.telegram.botTokenelsedel(.channels.telegram)| .plugins.entries.telegram.enabled = falseend' \"$EXISTING_CONFIG" 2>/dev/null)37 unmodified linesif [ -n "${CLOUDFLARE_PROXY_URL:-}" ]; thenecho "Proxy : ${CLOUDFLARE_PROXY_URL}"fi# HUGGINGCLAW_JUPYTER_ENABLED env var se override allow karo# (env-builder "Enable Jupyter terminal" toggle yahi set karta hai)if hc_is_true "${HUGGINGCLAW_JUPYTER_ENABLED:-false}"; thenRUNTIME_JUPYTER_ENABLED=trueelseRUNTIME_JUPYTER_ENABLED="$DEV_MODE_ENABLED"fi# Add user bin to PATH for jupyter-lab (installed in Dockerfile when DEV_MODE=true)export PATH="$HOME/.local/bin:$PATH"52 unmodified lines}trap graceful_shutdown SIGTERM SIGINTBROWSER_WARMED_UP=falsewarmup_browser() {[ "$BROWSER_SHOULD_ENABLE" = "true" ] || return 0# Only warm up once — gateway restarts should not re-spawn new warmup jobs.[ "$BROWSER_WARMED_UP" = "false" ] || return 0BROWSER_WARMED_UP=true(sleep 8local attemptfor attempt in 1 2 3 4 5 6; doif openclaw browser --browser-profile openclaw start >/dev/null 2>&1; thenopenclaw browser --browser-profile openclaw open about:blank >/dev/null 2>&1 || trueecho "Managed browser ready."return 0fisleep 5doneecho "Warning: managed browser warm-up did not complete; first browser action may need a retry."28 unmodified linesreturn 0fi# GATEWAY_TOKEN fallback: if JUPYTER_TOKEN is unset or still the insecure default,# reuse GATEWAY_TOKEN. Both protect the same Space, so the credential is equivalent.if { [ -z "${JUPYTER_TOKEN:-}" ] || [ "${JUPYTER_TOKEN}" = "huggingface" ]; } && [ -n "${GATEWAY_TOKEN:-}" ]; thenJUPYTER_TOKEN="$GATEWAY_TOKEN"echo "JUPYTER_TOKEN not set — using GATEWAY_TOKEN as terminal auth token"fi# Security guard: refuse to start JupyterLab with the insecure default token.# JupyterLab exposes a full shell — a weak token is equivalent to no auth.if [ -z "${JUPYTER_TOKEN:-}" ] || [ "${JUPYTER_TOKEN}" = "huggingface" ]; then567 unmodified linesfi# ── Fix config before running startup commands ──if [ "${AUTO_DOCTOR:-false}" = "true" ]; thenopenclaw doctor --fix || truefi# ── Arbitrary startup commands from HF Variables/Secrets ──# Recommended: use one variable, HUGGINGCLAW_RUN, as a full bash script. If the111 unmodified linesecho "WhatsApp Guardian started (PID: $GUARDIAN_PID)"}# ── Start D-Bus session (once, before gateway loop) ──if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; thenif command -v dbus-launch >/dev/null 2>&1; theneval "$(dbus-launch --sh-syntax 2>/dev/null)" || trueexport DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-disabled:}"elseexport DBUS_SESSION_BUS_ADDRESS="disabled:"fifiwhile true; do# Check health-server process - restart if died unexpectedlyif [ -n "${HEALTH_PID:-}" ] && ! kill -0 "$HEALTH_PID" 2>/dev/null; then19 unmodified linesfifiif [ "${AUTO_DOCTOR:-false}" = "true" ]; thenopenclaw doctor --fix || truefiecho "Launching OpenClaw gateway on port ${GATEWAY_PORT}..."GATEWAY_ARGS=(gateway run --port "${GATEWAY_PORT}" --bind lan)if [ "${GATEWAY_VERBOSE:-0}" = "1" ]; thenGATEWAY_ARGS+=(--verbose)echo "Gateway verbose logging enabled (GATEWAY_VERBOSE=1)"6 unmodified linesstdbuf -oL -eL openclaw "${GATEWAY_ARGS[@]}" 2>&1 | tee -a /home/node/.openclaw/gateway.log &GATEWAY_PID=$!# Poll for the gateway to start listening on ${GATEWAY_PORT}. OpenClaw can take 20-30s# on cold start (plugin install + auto-restore). Bail out early if the# pipeline died.GATEWAY_READY_TIMEOUT="${GATEWAY_READY_TIMEOUT:-90}"ready=falsefor ((i=0; i<GATEWAY_READY_TIMEOUT; i++)); doif (echo > /dev/tcp/127.0.0.1/${GATEWAY_PORT}) 2>/dev/null; thenready=truebreakfi8 unmodified linesecho "Gateway failed to start. Last 30 lines of log:"echo "────────────────────────────────────────────"tail -30 /home/node/.openclaw/gateway.logif [ "$DEV_MODE_ENABLED" = "true" ]; thenecho "Gateway failed — DEV_MODE active, retrying in 10s..."sleep 10continueelseecho "Gateway failed — exiting."exit 1fifi# 11. Start WhatsApp Guardian after the gateway is accepting connectionsstart_guardian_once# ── Silence D-Bus errors for headless Chromium ──if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; thenif command -v dbus-launch >/dev/null 2>&1; theneval "$(dbus-launch --sh-syntax 2>/dev/null)" || trueexport DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-disabled:}"elseexport DBUS_SESSION_BUS_ADDRESS="disabled:"fifi# 11.5 Warm up the managed browser so first browser actions have a live tabwarmup_browser
16 unmodified lines17181920212223101 unmodified lines12512612712812913013116 unmodified lines14814915015115215315433 unmodified lines1881891901911921931947 unmodified lines20220320420520620720820921021121221321421521621721821922016 unmodified lines}const { randomUUID } = require('node:crypto');const GATEWAY_URL = "ws://127.0.0.1:7860";const GATEWAY_TOKEN = process.env.GATEWAY_TOKEN || "huggingclaw";const WHATSAPP_ENABLED = /^true$/i.test(process.env.WHATSAPP_ENABLED || "");const CHECK_INTERVAL = 30000;101 unmodified lines});}async function callRpc(ws, method, params) {return new Promise((resolve, reject) => {const id = randomUUID();const handler = (data) => {16 unmodified linesreject(sendErr);return;}setTimeout(() => { ws.removeListener("message", handler); reject(new Error("RPC Timeout")); }, WAIT_TIMEOUT + 5000);});}33 unmodified lines}console.log("[guardian] Waiting for pairing completion...");const waitRes = await callRpc(ws, "web.login.wait", { timeoutMs: WAIT_TIMEOUT });const result = waitRes.payload || waitRes.result;const message = result?.message || "";const linkedAfter515 = !result?.connected && message.includes("515");7 unmodified lineslastConnectedAt = Date.now();writeStatus({ configured: true, connected: true, pairing: false });if (linkedAfter515) {console.log("[guardian] 515 after scan: credentials saved, reloading config to start WhatsApp...");} else {console.log("[guardian] Pairing completed! Reloading config...");}const getRes = await callRpc(ws, "config.get", {});if (getRes.payload?.raw && getRes.payload?.hash) {await callRpc(ws, "config.apply", { raw: getRes.payload.raw, baseHash: getRes.payload.hash });console.log("[guardian] Configuration re-applied.");}shouldStop = true;setTimeout(() => process.exit(0), 1000);} else if (!message.includes("No active") && !message.includes("Still waiting")) {console.log(`[guardian] Wait result: ${message}`);16 unmodified lines1718192021222324101 unmodified lines12612712812913013113213316 unmodified lines15015115215315415515633 unmodified lines1901911921931941951967 unmodified lines20420520620720820921021121221321421521621721821922022122222322422522622722822923016 unmodified lines}const { randomUUID } = require('node:crypto');const GATEWAY_PORT = Number.parseInt(process.env.GATEWAY_PORT || "7860", 10);const GATEWAY_URL = `ws://127.0.0.1:${GATEWAY_PORT}`;const GATEWAY_TOKEN = process.env.GATEWAY_TOKEN || "huggingclaw";const WHATSAPP_ENABLED = /^true$/i.test(process.env.WHATSAPP_ENABLED || "");const CHECK_INTERVAL = 30000;101 unmodified lines});}async function callRpc(ws, method, params, timeoutMs) {const ms = timeoutMs !== undefined ? timeoutMs : 10000; // default 10s for normal callsreturn new Promise((resolve, reject) => {const id = randomUUID();const handler = (data) => {16 unmodified linesreject(sendErr);return;}setTimeout(() => { ws.removeListener("message", handler); reject(new Error("RPC Timeout")); }, ms);});}33 unmodified lines}console.log("[guardian] Waiting for pairing completion...");const waitRes = await callRpc(ws, "web.login.wait", { timeoutMs: WAIT_TIMEOUT }, WAIT_TIMEOUT + 5000);const result = waitRes.payload || waitRes.result;const message = result?.message || "";const linkedAfter515 = !result?.connected && message.includes("515");7 unmodified lineslastConnectedAt = Date.now();writeStatus({ configured: true, connected: true, pairing: false });// Set shouldStop BEFORE config.apply — gateway restart during apply must not// leave guardian running (it would then incorrectly wipe valid credentials).shouldStop = true;if (linkedAfter515) {console.log("[guardian] 515 after scan: credentials saved, reloading config to start WhatsApp...");} else {console.log("[guardian] Pairing completed! Reloading config...");}try {const getRes = await callRpc(ws, "config.get", {});if (getRes.payload?.raw && getRes.payload?.hash) {await callRpc(ws, "config.apply", { raw: getRes.payload.raw, baseHash: getRes.payload.hash });console.log("[guardian] Configuration re-applied.");}} catch (applyErr) {// Gateway restarted during config.apply — that is expected and fine.// shouldStop is already true so we will not retry or attempt logout.console.log(`[guardian] Config re-apply interrupted (gateway restarting): ${applyErr.message}`);}setTimeout(() => process.exit(0), 1000);} else if (!message.includes("No active") && !message.includes("Still waiting")) {console.log(`[guardian] Wait result: ${message}`);
.env.example+2-9
Dockerfile+3
README.md+8-16
env-builder.html+2-1
env-builder.js+57-67
health-server.js+5-3
iframe-fix.cjs+3-2
jupyter-devdata-sync.py+1
multi-provider-key-rotator.cjs+25-1
start.sh+171-20
wa-guardian.js+20-10