Spaces:
Sleeping
Sleeping
tao-shen commited on
Commit ·
0d9d280
1
Parent(s): b19d31a
feat: add timing to all stages, fix OPENROUTER_API_KEY crash, async DNS
Browse filesFiles changed (4)
- Dockerfile+56-44
- openclaw.json+1-1
- scripts/entrypoint.sh+23-10
- scripts/sync_hf.py+17
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970# OpenClaw on Hugging Face Spaces — 从源码构建# 文档: https://huggingface.co/docs/hub/spaces-sdks-dockerFROM node:22-bookworm# Force rebuild - upload_folder persistence v9RUN echo "clean-build-v9-upload-folder-$(date +%s)"# 构建依赖(包含 Python3 以便使用 huggingface_hub 做 Dataset 持久化)RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates curl python3 python3-pip \&& rm -rf /var/lib/apt/lists/*RUN pip3 install --no-cache-dir --break-system-packages huggingface_hubRUN corepack enableRUN curl -fsSL https://bun.sh/install | bashENV PATH="/root/.bun/bin:${PATH}"WORKDIR /appRUN git clone --depth 1 https://github.com/openclaw/openclaw.git openclawWORKDIR /app/openclaw# 补丁:仅在实际成功解析消息 body 并即将投递回复时记录 inbound,# 避免解密失败(Bad MAC)的消息被误计为已接收导致 lastInboundAt 有值但无法回复COPY patches /app/patchesRUN if [ -f /app/patches/web-inbound-record-activity-after-body.patch ]; then patch -p1 < /app/patches/web-inbound-record-activity-after-body.patch; fiRUN pnpm install --frozen-lockfileRUN pnpm buildENV OPENCLAW_PREFER_PNPM=1RUN pnpm ui:build# 验证构建产物完整(包含 Telegram 和 WhatsApp 扩展)RUN test -f dist/entry.js && echo "[build-check] dist/entry.js OK" \&& test -f dist/plugin-sdk/index.js && echo "[build-check] dist/plugin-sdk/index.js OK" \&& test -d extensions/telegram && echo "[build-check] extensions/telegram OK" \&& test -d extensions/whatsapp && echo "[build-check] extensions/whatsapp OK" \&& test -d dist/control-ui && echo "[build-check] dist/control-ui OK"# 向 Control UI 注入自动 token 配置(让浏览器自动连接,无需手动输入 token)RUN python3 << 'PYEOF'import pathlibp = pathlib.Path('dist/control-ui/index.html')script = '<script>!function(){var K="openclaw.control.settings.v1";try{var s=JSON.parse(localStorage.getItem(K)||"{}")||{};if(!s.token){s.token="openclaw-space-default";localStorage.setItem(K,JSON.stringify(s))}}catch(e){}}()</script>'h = p.read_text()p.write_text(h.replace('</head>', script + '</head>'))print('[build-check] Token auto-config injected into Control UI')PYEOF# 不修改内部代码,改用外部 WebSocket 监护脚本处理 515 重连ENV NODE_ENV=production# 禁用 bundled 插件发现(改由 global symlink 提供);用空目录替代 /dev/null 避免 ENOTDIR 警告RUN mkdir -p /app/openclaw/empty-bundled-pluginsENV OPENCLAW_BUNDLED_PLUGINS_DIR=/app/openclaw/empty-bundled-pluginsRUN chown -R node:node /app# 创建 ~/.openclaw 目录结构RUN mkdir -p /home/node/.openclaw/workspace /home/node/.openclaw/credentials# Note: openclaw.json is NOT copied here - it will be restored from Dataset by openclaw_sync.py# The new persistence system backs up and restores the entire ~/.openclaw directory# 持久化脚本(完整目录备份) & DNS 修复COPY --chown=node:node scripts /home/node/scriptsCOPY --chown=node:node openclaw.json /home/node/scripts/openclaw.json.defaultRUN chmod +x /home/node/scripts/entrypoint.shRUN chmod +x /home/node/scripts/sync_hf.pyRUN chown -R node:node /home/nodeUSER nodeENV HOME=/home/node12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# OpenClaw on Hugging Face Spaces — 从源码构建(带计时)# 文档: https://huggingface.co/docs/hub/spaces-sdks-dockerFROM node:22-bookwormSHELL ["/bin/bash", "-c"]# ── Step 1: System dependencies ──────────────────────────────────────────────RUN echo "[build][step1] Installing system deps..." && START=$(date +%s) \&& apt-get update && apt-get install -y --no-install-recommends git ca-certificates curl python3 python3-pip \&& rm -rf /var/lib/apt/lists/* \&& echo "[build][step1] System deps: $(($(date +%s) - START))s"# ── Step 2: Python dependencies ──────────────────────────────────────────────RUN echo "[build][step2] Installing huggingface_hub..." && START=$(date +%s) \&& pip3 install --no-cache-dir --break-system-packages huggingface_hub \&& echo "[build][step2] huggingface_hub: $(($(date +%s) - START))s"# ── Step 3: Node tooling ────────────────────────────────────────────────────RUN echo "[build][step3] Enabling corepack + bun..." && START=$(date +%s) \&& corepack enable \&& curl -fsSL https://bun.sh/install | bash \&& echo "[build][step3] Corepack + Bun: $(($(date +%s) - START))s"ENV PATH="/root/.bun/bin:${PATH}"# ── Step 4: Clone OpenClaw ───────────────────────────────────────────────────WORKDIR /appRUN echo "[build][step4] Cloning OpenClaw..." && START=$(date +%s) \&& git clone --depth 1 https://github.com/openclaw/openclaw.git openclaw \&& echo "[build][step4] Git clone: $(($(date +%s) - START))s"WORKDIR /app/openclaw# ── Step 5: Apply patches ───────────────────────────────────────────────────COPY patches /app/patchesRUN echo "[build][step5] Applying patches..." && START=$(date +%s) \&& if [ -f /app/patches/web-inbound-record-activity-after-body.patch ]; then \patch -p1 < /app/patches/web-inbound-record-activity-after-body.patch; \fi \&& echo "[build][step5] Patches: $(($(date +%s) - START))s"# ── Step 6: pnpm install ────────────────────────────────────────────────────RUN echo "[build][step6] pnpm install..." && START=$(date +%s) \&& pnpm install --frozen-lockfile \&& echo "[build][step6] pnpm install: $(($(date +%s) - START))s"# ── Step 7: pnpm build ──────────────────────────────────────────────────────RUN echo "[build][step7] pnpm build..." && START=$(date +%s) \&& pnpm build \&& echo "[build][step7] pnpm build: $(($(date +%s) - START))s"# ── Step 8: pnpm ui:build ───────────────────────────────────────────────────ENV OPENCLAW_PREFER_PNPM=1RUN echo "[build][step8] pnpm ui:build..." && START=$(date +%s) \&& pnpm ui:build \&& echo "[build][step8] pnpm ui:build: $(($(date +%s) - START))s"# ── Step 9: Verify build artifacts ──────────────────────────────────────────RUN echo "[build][step9] Verifying build artifacts..." \&& test -f dist/entry.js && echo " OK dist/entry.js" \&& test -f dist/plugin-sdk/index.js && echo " OK dist/plugin-sdk/index.js" \&& test -d extensions/telegram && echo " OK extensions/telegram" \&& test -d extensions/whatsapp && echo " OK extensions/whatsapp" \&& test -d dist/control-ui && echo " OK dist/control-ui"# ── Step 10: Inject auto-token into Control UI ──────────────────────────────COPY --chown=node:node scripts /home/node/scriptsRUN chmod +x /home/node/scripts/inject-token.sh && bash /home/node/scripts/inject-token.sh# ── Step 11: Final setup ────────────────────────────────────────────────────ENV NODE_ENV=productionRUN mkdir -p /app/openclaw/empty-bundled-pluginsENV OPENCLAW_BUNDLED_PLUGINS_DIR=/app/openclaw/empty-bundled-pluginsRUN chown -R node:node /appRUN mkdir -p /home/node/.openclaw/workspace /home/node/.openclaw/credentialsCOPY --chown=node:node openclaw.json /home/node/scripts/openclaw.json.defaultRUN chmod +x /home/node/scripts/entrypoint.sh \&& chmod +x /home/node/scripts/sync_hf.py \&& chown -R node:node /home/nodeUSER nodeENV HOME=/home/node
21 unmodified lines2223242526272821 unmodified lines"providers": {"openrouter": {"baseUrl": "https://openrouter.ai/api/v1","apiKey": "${OPENROUTER_API_KEY}","api": "openai-completions","models": [{21 unmodified lines2223242526272821 unmodified lines"providers": {"openrouter": {"baseUrl": "https://openrouter.ai/api/v1","apiKey": "__OPENROUTER_API_KEY__","api": "openai-completions","models": [{
1234567891011121314151617181920212223242526272829303132333435363738394041#!/bin/shset -eecho "[entrypoint] OpenClaw HuggingFace Spaces Entrypoint"echo "[entrypoint] ======================================="# DNS pre-resolution for WhatsAppecho "[entrypoint] Resolving WhatsApp domains via DNS-over-HTTPS..."python3 /home/node/scripts/dns-resolve.py /tmp/dns-resolved.json || echo "[entrypoint] DNS pre-resolve had issues (non-fatal)"# Enable Node.js DNS fixexport NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require /home/node/scripts/dns-fix.cjs"# Ensure extensions symlink existsif [ ! -L /home/node/.openclaw/extensions ]; thenrm -rf /home/node/.openclaw/extensions 2>/dev/null || trueln -s /app/openclaw/extensions /home/node/.openclaw/extensionsecho "[entrypoint] Created extensions symlink -> /app/openclaw/extensions"fi# Check for WhatsApp credentialsif [ -d /home/node/.openclaw/credentials/whatsapp ]; thenecho "[entrypoint] Found existing WhatsApp credentials - will use for auto-connect"fi# Build artifacts checkcd /app/openclawecho "[entrypoint] Build artifacts check:"test -f dist/entry.js && echo " OK dist/entry.js" || echo " WARNING: dist/entry.js missing!"test -f dist/plugin-sdk/index.js && echo " OK dist/plugin-sdk/index.js" || echo " WARNING: dist/plugin-sdk/index.js missing!"echo " Extensions: $(ls extensions/ 2>/dev/null | wc -l | tr -d ' ') found"echo " Global extensions link: $(readlink /home/node/.openclaw/extensions 2>/dev/null || echo 'NOT SET')"echo " DNS resolved: $(cat /tmp/dns-resolved.json 2>/dev/null || echo 'file missing')"# Create logs directorymkdir -p /home/node/logstouch /home/node/logs/app.log# Start OpenClaw via sync_hf.pyecho "[entrypoint] Starting OpenClaw via sync_hf.py..."exec python3 -u /home/node/scripts/sync_hf.py123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354#!/bin/shset -eBOOT_START=$(date +%s)echo "[entrypoint] OpenClaw HuggingFace Spaces Entrypoint"echo "[entrypoint] ======================================="# ── DNS pre-resolution (run in BACKGROUND — was 121s blocking) ──────────────echo "[entrypoint] Resolving WhatsApp domains via DNS-over-HTTPS (background)..."DNS_START=$(date +%s)(python3 /home/node/scripts/dns-resolve.py /tmp/dns-resolved.json 2>&1DNS_END=$(date +%s)echo "[TIMER] DNS pre-resolve (background): $((DNS_END - DNS_START))s") &DNS_PID=$!# Enable Node.js DNS fix (will use resolved file when ready)export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require /home/node/scripts/dns-fix.cjs"# ── Extensions symlink ──────────────────────────────────────────────────────SYMLINK_START=$(date +%s)if [ ! -L /home/node/.openclaw/extensions ]; thenrm -rf /home/node/.openclaw/extensions 2>/dev/null || trueln -s /app/openclaw/extensions /home/node/.openclaw/extensionsecho "[entrypoint] Created extensions symlink -> /app/openclaw/extensions"fiecho "[TIMER] Extensions symlink: $(($(date +%s) - SYMLINK_START))s"# ── WhatsApp credentials check ──────────────────────────────────────────────if [ -d /home/node/.openclaw/credentials/whatsapp ]; thenecho "[entrypoint] Found existing WhatsApp credentials - will use for auto-connect"fi# ── Build artifacts check ───────────────────────────────────────────────────cd /app/openclawecho "[entrypoint] Build artifacts check:"test -f dist/entry.js && echo " OK dist/entry.js" || echo " WARNING: dist/entry.js missing!"test -f dist/plugin-sdk/index.js && echo " OK dist/plugin-sdk/index.js" || echo " WARNING: dist/plugin-sdk/index.js missing!"echo " Extensions: $(ls extensions/ 2>/dev/null | wc -l | tr -d ' ') found"echo " Global extensions link: $(readlink /home/node/.openclaw/extensions 2>/dev/null || echo 'NOT SET')"# Create logs directorymkdir -p /home/node/logstouch /home/node/logs/app.logENTRYPOINT_END=$(date +%s)echo "[TIMER] Entrypoint (before sync_hf.py): $((ENTRYPOINT_END - BOOT_START))s"# ── Start OpenClaw via sync_hf.py (don't wait for DNS — it runs in bg) ─────echo "[entrypoint] Starting OpenClaw via sync_hf.py..."echo "[entrypoint] DNS resolution running in background (PID $DNS_PID), app will use it when ready"exec python3 -u /home/node/scripts/sync_hf.py
251 unmodified lines252253254255256257241 unmodified lines4995005015025035045055065075081 unmodified line510511512513514515516251 unmodified linesdefault_src = Path(__file__).parent / "openclaw.json.default"if default_src.exists():shutil.copy2(str(default_src), str(config_path))print("[SYNC] Created openclaw.json from default template")else:with open(config_path, "w") as f:241 unmodified linesdef main():try:sync = OpenClawFullSync()# 1. Restoresync.load_from_repo()# 2. Background syncstop_event = threading.Event()1 unmodified linet.start()# 3. Start applicationprocess = sync.run_openclaw()# Signal handlerdef handle_signal(sig, frame):251 unmodified lines252253254255256257258259260261262263264265241 unmodified lines5075085095105115125135145155165175185195205215221 unmodified line524525526527528529530531532533251 unmodified linesdefault_src = Path(__file__).parent / "openclaw.json.default"if default_src.exists():shutil.copy2(str(default_src), str(config_path))# Replace placeholder with actual env var valuetext = config_path.read_text()if "__OPENROUTER_API_KEY__" in text:if OPENROUTER_API_KEY:text = text.replace("__OPENROUTER_API_KEY__", OPENROUTER_API_KEY)else:text = text.replace("__OPENROUTER_API_KEY__", "")config_path.write_text(text)print("[SYNC] Created openclaw.json from default template")else:with open(config_path, "w") as f:241 unmodified linesdef main():try:t_main_start = time.time()t0 = time.time()sync = OpenClawFullSync()print(f"[TIMER] sync_hf init: {time.time() - t0:.1f}s")# 1. Restoret0 = time.time()sync.load_from_repo()print(f"[TIMER] load_from_repo (restore): {time.time() - t0:.1f}s")# 2. Background syncstop_event = threading.Event()1 unmodified linet.start()# 3. Start applicationt0 = time.time()process = sync.run_openclaw()print(f"[TIMER] run_openclaw launch: {time.time() - t0:.1f}s")print(f"[TIMER] Total startup (init → app launched): {time.time() - t_main_start:.1f}s")# Signal handlerdef handle_signal(sig, frame):
Dockerfile+56-44
openclaw.json+1-1
scripts/entrypoint.sh+23-10
scripts/sync_hf.py+17