Spaces:
Sleeping
Sleeping
Update Dockerfile
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121# 核心镜像:Node 22 slim 保证了环境的现代性与轻量化FROM node:22-slim# 1. 安装系统依赖# 包含:git (拉取依赖), openssh-client (解决构建报错), build-essential/g++/make (编译原生模块), python3 (运行同步脚本)RUN apt-get update && apt-get install -y --no-install-recommends \git openssh-client build-essential python3 python3-pip \g++ make ca-certificates \&& rm -rf /var/lib/apt/lists/*# 2. 安装 Hugging Face 命令行工具RUN pip3 install --no-cache-dir huggingface_hub --break-system-packages# 3. 构建环境优化# 修复 Git 证书问题并将所有 SSH 协议重定向为 HTTPSRUN update-ca-certificates && \git config --global http.sslVerify false && \git config --global url."https://github.com/".insteadOf ssh://git@github.com/# 4. 全局安装 OpenClawRUN npm install -g openclaw@latest --unsafe-perm# 5. 设置环境变量ENV PORT=7860 \OPENCLAW_GATEWAY_MODE=local \HOME=/root# 6. 核心同步引擎 (sync.py)# 针对 OpenClaw 新版 MEMORY.md 机制进行了全路径覆盖RUN echo 'import os, sys, tarfile\n\from huggingface_hub import HfApi, hf_hub_download\n\from datetime import datetime, timedelta\n\api = HfApi()\n\repo_id = os.getenv("HF_DATASET")\n\token = os.getenv("HF_TOKEN")\n\\n\def restore():\n\try:\n\print(f"--- [SYNC] 启动恢复流程, 目标仓库: {repo_id} ---")\n\if not repo_id or not token: \n\print("--- [SYNC] 跳过恢复: 未配置 HF_DATASET 或 HF_TOKEN ---")\n\return False\n\files = api.list_repo_files(repo_id=repo_id, repo_type="dataset", token=token)\n\now = datetime.now()\n\for i in range(5):\n\day = (now - timedelta(days=i)).strftime("%Y-%m-%d")\n\name = f"backup_{day}.tar.gz"\n\if name in files:\n\print(f"--- [SYNC] 发现备份文件: {name}, 正在下载... ---")\n\path = hf_hub_download(repo_id=repo_id, filename=name, repo_type="dataset", token=token)\n\with tarfile.open(path, "r:gz") as tar: tar.extractall(path="/root/.openclaw/")\n\print(f"--- [SYNC] 恢复成功! 数据已覆盖至 /root/.openclaw/ ---")\n\return True\n\print("--- [SYNC] 未找到最近 5 天的备份包 ---")\n\except Exception as e: print(f"--- [SYNC] 恢复异常: {e} ---")\n\\n\def backup():\n\try:\n\day = datetime.now().strftime("%Y-%m-%d")\n\name = f"backup_{day}.tar.gz"\n\print(f"--- [SYNC] 正在执行全量备份: {name} ---")\n\with tarfile.open(name, "w:gz") as tar:\n\# 路径说明:sessions(网关历史), workspace(记忆文件), agents(配置), memory(旧版目录)\n\for target in ["sessions", "workspace", "agents", "memory", "openclaw.json"]:\n\full_path = f"/root/.openclaw/{target}"\n\if os.path.exists(full_path):\n\tar.add(full_path, arcname=target)\n\api.upload_file(path_or_fileobj=name, path_in_repo=name, repo_id=repo_id, repo_type="dataset", token=token)\n\print(f"--- [SYNC] 备份上传成功! ---")\n\except Exception as e: print(f"--- [SYNC] 备份失败: {e} ---")\n\\n\if __name__ == "__main__":\n\if len(sys.argv) > 1 and sys.argv[1] == "backup": backup()\n\else: restore()' > /usr/local/bin/sync.py# 7. 容器入口脚本 (start-openclaw)# 负责恢复数据 -> 生成配置 -> 启动网关 -> 定时备份RUN echo "#!/bin/bash\n\set -e\n\mkdir -p /root/.openclaw/sessions\n\mkdir -p /root/.openclaw/workspace\n\\n\# 启动前执行数据恢复\n\python3 /usr/local/bin/sync.py restore\n\\n\# 清理 API Base 地址\n\CLEAN_BASE=\$(echo \"\$OPENAI_API_BASE\" | sed \"s|/chat/completions||g\" | sed \"s|/v1/|/v1|g\" | sed \"s|/v1\$|/v1|g\")\n\\n\# 生成 openclaw.json 配置文件\n\cat > /root/.openclaw/openclaw.json <<EOF\n\{\n\\"models\": {\n\\"providers\": {\n\\"siliconflow\": {\n\\"baseUrl\": \"\$CLEAN_BASE\",\n\\"apiKey\": \"\$OPENAI_API_KEY\",\n\\"api\": \"openai-completions\",\n\\"models\": [{ \"id\": \"\$MODEL\", \"name\": \"DeepSeek\", \"contextWindow\": 128000 }]\n\}\n\}\n\},\n\\"agents\": { \"defaults\": { \"model\": { \"primary\": \"siliconflow/\$MODEL\" } } },\n\\"gateway\": {\n\\"mode\": \"local\", \"bind\": \"lan\", \"port\": \$PORT,\n\\"trustedProxies\": [\"0.0.0.0/0\", \"10.0.0.0/8\", \"172.16.0.0/12\", \"192.168.0.0/16\"],\n\\"auth\": { \"mode\": \"token\", \"token\": \"\$OPENCLAW_GATEWAY_PASSWORD\" },\n\\"controlUi\": { \"allowInsecureAuth\": true }\n\}\n\}\n\EOF\n\\n\# 启动定时备份进程 (每 3 小时执行一次,增强安全性)\n\(while true; do sleep 10800; python3 /usr/local/bin/sync.py backup; done) &\n\\n\# 启动 OpenClaw 网关\n\openclaw doctor --fix\n\exec openclaw gateway run --port \$PORT\n\" > /usr/local/bin/start-openclaw && chmod +x /usr/local/bin/start-openclawEXPOSE 7860CMD ["/usr/local/bin/start-openclaw"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784FROM node:22-slimLABEL description="OpenClaw Multi-Agent for HuggingFace Space"LABEL version="2026.2.26"# 1. System dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \git openssh-client build-essential python3 python3-pip \g++ make ca-certificates curl iputils-ping nano \&& rm -rf /var/lib/apt/lists/*RUN pip3 install --no-cache-dir huggingface_hub --break-system-packages# 2. Network optimizationRUN update-ca-certificates && \git config --global url."https://github.com/".insteadOf ssh://git@github.com/# 3. Install dependencies at build timeRUN npm install -g @larksuiteoapi/node-sdk --unsafe-perm && \npm install -g openclaw@2026.2.26 --unsafe-perm# 4. Copy nano-banana-pro skill from local filesCOPY skills/nano-banana-pro /home/node/.openclaw/skills/nano-banana-proRUN ls -laR /home/node/.openclaw/skills/nano-banana-pro/ && \chmod +x /home/node/.openclaw/skills/nano-banana-pro/scripts/generate_image.py && \chown -R node:node /home/node/.openclaw/skills# Install Python dependencies for nano-banana-pro skillRUN pip3 install --no-cache-dir google-genai pillow --break-system-packages# Install uv for running Python scriptsRUN curl -LsSf https://astral.sh/uv/install.sh | sh && \mv /root/.local/bin/uv /usr/local/bin/uv && \mv /root/.local/bin/uvx /usr/local/bin/uvx 2>/dev/null || true# 5. Environment configurationENV HOME=/home/node# Create directoriesRUN mkdir -p /home/node/.openclaw && \chmod 700 /home/node/.openclaw && \chown -R node:node /home/nodeWORKDIR /home/node# 6. Sync engine for backup/restore from HF DatasetRUN cat << 'PYEOF' > /usr/local/bin/sync.pyimport os, sys, tarfilefrom huggingface_hub import HfApi, hf_hub_downloadfrom datetime import datetime, timedeltaapi = HfApi()repo_id = os.getenv("HF_DATASET")token = os.getenv("HF_TOKEN")base = "/home/node/.openclaw"def restore():try:if not repo_id:return Falsefiles = api.list_repo_files(repo_id=repo_id, repo_type="dataset", token=token)for i in range(5):day = (datetime.now() - timedelta(days=i)).strftime("%Y-%m-%d")name = f"backup_{day}.tar.gz"if name in files:print(f"[SYNC] Found backup: {name}, downloading...")path = hf_hub_download(repo_id=repo_id, filename=name, repo_type="dataset", token=token)os.makedirs(base, exist_ok=True)with tarfile.open(path, "r:gz") as tar:tar.extractall(path=base)print("[SYNC] Restore Success")return Trueexcept Exception as e:print(f"[SYNC] Restore Error: {e}")return Falsedef backup():try:if not repo_id:returnday = datetime.now().strftime("%Y-%m-%d")name = f"backup_{day}.tar.gz"print(f"[SYNC] Starting backup to {name}...")with tarfile.open(f"/tmp/{name}", "w:gz") as tar:# Exclude skills - they should be installed, not backed upfor target in ["sessions", "workspace", "memory", "plugins", "agents"]:full_path = f"{base}/{target}"if os.path.exists(full_path):tar.add(full_path, arcname=target)api.upload_file(path_or_fileobj=f"/tmp/{name}",path_in_repo=name,repo_id=repo_id,repo_type="dataset",token=token)print("[SYNC] Backup Upload Success")except Exception as e:print(f"[SYNC] Backup Error: {e}")if __name__ == "__main__":if len(sys.argv) > 1 and sys.argv[1] == "backup":backup()else:restore()PYEOFRUN chmod +x /usr/local/bin/sync.py# 7. Startup scriptRUN cat << 'STARTEOF' > /usr/local/bin/start-openclaw#!/bin/bashset -e# Image model with fallback (allow external override)export IMAGE_MODEL="${IMAGE_MODEL:-imagen-4.0-generate-001}"BASE="/home/node/.openclaw"echo "=== OpenClaw Multi-Agent Gateway Starting ==="# OpenClaw is installed at build timeOPENCLAW_VERSION=$(openclaw --version 2>/dev/null || echo "unknown")echo "--- OpenClaw Version: ${OPENCLAW_VERSION} ---"# Restore data from HF Datasetecho "--- Restoring Data from HF Dataset ---"python3 /usr/local/bin/sync.py restore || truefind "$BASE" -name "*.lock" -type f -delete 2>/dev/null || true# Clean environment variables (matching HF Space env.txt)CLEAN_DISCORD_TOKEN=$(echo "${DISCORD_TOKEN}" | tr -d '\r\n[:space:]"')RAW_DISCORD_USER=$(echo "${DISCORD_USER_ID}" | tr -d '[:space:]')CLEAN_FEISHU_APP_ID=$(echo "${FEISHU_APP_ID}" | tr -d '\r\n[:space:]"')CLEAN_FEISHU_APP_SECRET=$(echo "${FEISHU_APP_SECRET}" | tr -d '\r\n[:space:]"')# FEISHU_ENCRYPT_KEY is optional - set empty if not providedCLEAN_FEISHU_ENCRYPT_KEY=$(echo "${FEISHU_ENCRYPT_KEY:-}" | tr -d '\r\n[:space:]"')# Proxy settings (optional)export HTTP_PROXY="${HTTP_PROXY:-}"export HTTPS_PROXY="${HTTPS_PROXY:-}"# Create directory structure for multi-agent (preserve existing skills)mkdir -p "$BASE"/{workspace,credentials,canvas,plugins,devices}mkdir -p "$BASE/agents/assistant"mkdir -p "$BASE/agents/coder"mkdir -p "$BASE/agents/designer"# Ensure skills directory exists with correct permissionsmkdir -p "$BASE/skills"mkdir -p "$BASE/workspace-designer/skills"mkdir -p "$BASE/workspace-designer/memory"mkdir -p "$BASE/workspace-designer/output"# Copy skill to designer workspace (copy instead of symlink for security compatibility)rm -rf "$BASE/workspace-designer/skills/nano-banana-pro"cp -r "$BASE/skills/nano-banana-pro" "$BASE/workspace-designer/skills/nano-banana-pro"echo "--- Skill copied to designer workspace ---"# Link designer output to canvas for web accessmkdir -p "$BASE/canvas"rm -f "$BASE/canvas/output"ln -sf "$BASE/workspace-designer/output" "$BASE/canvas/output"echo "--- Designer output linked to canvas ---"# Verify skill is properly copiedif [ -d "$BASE/workspace-designer/skills/nano-banana-pro" ]; thenecho "--- Skill copied to designer workspace: OK ---"elseecho "--- WARNING: Skill not copied to designer workspace ---"fi# Verify nano-banana-pro skill scripts existif [ ! -d "$BASE/skills/nano-banana-pro/scripts" ]; thenecho "[WARNING] nano-banana-pro/scripts not found, image generation may not work"fi# Force cleanup old config to avoid conflictsrm -f "$BASE/openclaw.json"rm -f "$BASE/openclaw.json.bak"rm -f "$BASE/credentials.json"# Note: With auth.mode=none, no device pairing is required# Create agent workspacesfor agent in assistant coder designer; domkdir -p "$BASE/workspace-$agent"mkdir -p "$BASE/agents/$agent/sessions"done# ==========================================# Agent Soul Definitions# ==========================================# Agent 1: Assistant (Team Leader)cat > "$BASE/workspace-assistant/SOUL.md" << 'EOF'# IdentityYou are "Team Leader", the project manager of the AI team.# Team MembersYou have two specialists you can delegate tasks to:1. **coder** - Expert engineer for writing code2. **designer** - Expert artist for generating images using nano-banana-pro skill# How to DelegateUse the sessions_spawn tool to create tasks for specialists:1. For coding tasks, use: sessions_spawn with targetAgent="coder"2. For image generation, use: sessions_spawn with targetAgent="designer"# ExampleUser: "Draw a cat"Action: Use sessions_spawn to create a session for designer with the task.User: "Write a recursive function"Action: Use sessions_spawn to create a session for coder with the task.# Rules- For coding tasks, delegate to coder- For image generation tasks, delegate to designer- For general questions, answer yourself- Always wait for specialist to complete and report backEOF# Assistant AGENTS.md - Operational rulescat > "$BASE/workspace-assistant/AGENTS.md" << 'EOF'# Assistant Agent Rules## Delegation- Use sessions_spawn to delegate tasks to subagents- targetAgent="coder" for coding tasks- targetAgent="designer" for image generation tasks## Critical Safety Rules- **NEVER** attempt to restart, stop, or manage the `openclaw gateway` service.- If a subagent fails to spawn (e.g., pairing error), report the status to the user and ask for authorization if needed.- Do NOT assume port conflicts require a service restart.## Workflow1. Understand user request2. Delegate to specialist (coder/designer)3. **WAIT** for the specialist to complete the task. Do NOT try to message the specialist directly to check progress. Wait for the automated report.4. Report the final result (including images/code) back to the user.EOF# Assistant TOOLS.md - Tool documentationcat > "$BASE/workspace-assistant/TOOLS.md" << 'EOF'# Available Tools## sessions_spawn- Spawn subagent sessions for specialized tasks## sessions_send- Send messages to existing subagent sessions## Other Tools- read, write, edit, exec, message, etc.EOF# Agent 2: Coder (Engineer)cat > "$BASE/workspace-coder/SOUL.md" << 'EOF'# IdentityYou are "Engineer", the technical expert of the team.# SkillsYou specialize in writing clean, efficient code.# Rules- You receive tasks from Team Leader via sessions_send- Deliver working, well-commented code- Report completion back to Team LeaderEOF# Coder AGENTS.md - Operational rulescat > "$BASE/workspace-coder/AGENTS.md" << 'EOF'# Coder Agent Rules## Your TaskWrite code when requested by the Team Leader.## Workflow1. Receive task from Team Leader via sessions_send2. Understand requirements3. Write clean, efficient code4. Test if possible5. Report completionEOF# Coder TOOLS.md - Tool documentationcat > "$BASE/workspace-coder/TOOLS.md" << 'EOF'# Available Tools## Code Tools- write: Write code files- edit: Edit existing code- exec: Run commands## Other Tools- read, message, etc.EOF# Agent 3: Designer (Creator with image generation skill)cat > "$BASE/workspace-designer/SOUL.md" << 'EOF'# IdentityYou are "Creator", the visual artist with nano-banana-pro skill for image generation.# Available SkillsYou have access to the **nano-banana-pro** skill for generating images using Google Gemini.# How to Generate ImagesWhen asked to generate an image:1. Look for the nano-banana-pro skill in your available tools2. Use the skill with a clear prompt describing the image3. The skill will generate and return the image4. **IMPORTANT**: If generation fails, the script will output an error image. Always use the provided output path.# Example prompts- "A cute cat sitting on a windowsill"- "A futuristic city at sunset"- "Abstract art with blue and gold colors"# Rules- Always try to use nano-banana-pro skill for image requests- Provide detailed, creative prompts- Report the result back to the userEOF# Setup external URL for Canvas (HARDCODED for stability)EXTERNAL_URL="https://tianmingyun999-openclaw.hf.space"echo "--- EXTERNAL_URL set to: $EXTERNAL_URL ---"# Designer AGENTS.md - Operational rules (subagent can see this)cat > "$BASE/workspace-designer/AGENTS.md" << EOF# Designer Agent Rules## Your TaskGenerate images using the nano-banana-pro skill when requested.## How to Generate Images (IMPORTANT!)Use exec tool to run the generate_image.py script directly:1. When user requests an image, use exec tool to run:\`\`\`uv run /home/node/.openclaw/skills/nano-banana-pro/scripts/generate_image.py --prompt "your image description" --filename "output/output.png" --resolution 1K\`\`\`2. The image will be generated at /home/node/.openclaw/workspace-designer/output/output.png3. **To send the image to the user**, you MUST follow these 3 steps:a. **Copy to allowed media directory** (for upload):\`\`\`cp /home/node/.openclaw/workspace-designer/output/output.png /tmp/output.png\`\`\`b. **Copy to canvas directory** (for public URL):\`\`\`cp /home/node/.openclaw/workspace-designer/output/output.png /home/node/.openclaw/canvas/output/output.png\`\`\`c. **Send message with BOTH media and URL**:\`\`\`message channel=feishu target=<user_id> message="Here is your image. Link: ${EXTERNAL_URL}/__openclaw__/canvas/output/output.png" media=/tmp/output.png\`\`\`IMPORTANT:- You MUST copy to /tmp/ first (for upload)- You MUST copy to /home/node/.openclaw/canvas/output/ (for URL link)- Use BOTH media parameter AND the URL in the message text- Do NOT use Markdown image links ()## ExampleUser: "Draw a cat"Action:1. Run script (saving to output/output.png).2. Wait for completion.3. Copy to /tmp: cp /home/node/.openclaw/workspace-designer/output/output.png /tmp/output.png4. Copy to canvas: cp /home/node/.openclaw/workspace-designer/output/output.png /home/node/.openclaw/canvas/output/output.png5. Send: message channel=feishu target=<user_id> message="Image generated. Link: ${EXTERNAL_URL}/__openclaw__/canvas/output/output.png" media=/tmp/output.pngEOF# Designer TOOLS.md - Tool documentation (subagent can see this)cat > "$BASE/workspace-designer/TOOLS.md" << 'EOF'# Available Tools## Image GenerationUse exec tool to run the image generation script:```uv run /home/node/.openclaw/skills/nano-banana-pro/scripts/generate_image.py --prompt "描述" --filename "output/output.png" --resolution 1K```## Other Available Tools- read: Read files- write: Write files- edit: Edit files- exec: Execute commands- message: Send messagesEOF# ==========================================# Network Configuration# ==========================================export NODE_OPTIONS="--dns-result-order=ipv4first --no-warnings"export no_proxy="localhost,127.0.0.1,::1,feishu.cn,open.feishu.cn,larksuite.com"# Gateway authentication - required for lan binding# Token must match between config and CLIGATEWAY_TOKEN="openclaw-hf-space-token-2026"export OPENCLAW_GATEWAY_TOKEN="$GATEWAY_TOKEN"# Critical: Set environment for OpenClawexport OPENCLAW_HOME="$BASE"export OPENCLAW_CONFIG_PATH="$BASE/openclaw.json"# Default model fallbackexport MODEL="${MODEL:-gemini-2.0-flash}"# Image generation model for nano-banana-pro skillexport IMAGE_MODEL="${IMAGE_MODEL:-imagen-4.0-generate-001}"# Logging configuration - output to stdout for HF Spaceexport OPENCLAW_LOG_LEVEL="${OPENCLAW_LOG_LEVEL:-info}"export OPENCLAW_CONSOLE_STYLE="pretty"# ==========================================# Generate OpenClaw Configuration# ==========================================echo "--- Generating Configuration ---"cat > "$BASE/openclaw.json" << JSONEOF{"logging": {"level": "debug","consoleLevel": "debug","consoleStyle": "pretty","redactSensitive": "tools"},"session": {"dmScope": "per-channel-peer"},"models": {"providers": {"google": {"baseUrl": "https://generativelanguage.googleapis.com/v1beta","apiKey": "${GEMINI_API_KEY}","models": [{ "id": "${MODEL}", "name": "Primary Model" }]}}},"skills": {"allowBundled": ["gemini", "nano-banana-pro"],"load": {"extraDirs": ["$BASE/skills"]},"entries": {"nano-banana-pro": {"enabled": true,"apiKey": "${GEMINI_API_KEY}","env": {"GEMINI_API_KEY": "${GEMINI_API_KEY}","IMAGE_MODEL": "${IMAGE_MODEL:-imagen-4.0-generate-001}"}}}},"tools": {"agentToAgent": {"enabled": true,"allow": ["assistant", "coder", "designer"]},"allow": ["exec", "read", "write", "edit", "process", "bash", "sessions_spawn", "sessions_send", "sessions_list", "message"],"deny": ["gateway", "cron"],"elevated": {"enabled": true,"allowFrom": {"discord": ["*"],"feishu": ["*"]}}},"agents": {"defaults": {"model": {"primary": "google/${MODEL}"},"elevatedDefault": "on"},"list": [{"id": "assistant","name": "Team Leader","default": true,"workspace": "$BASE/workspace-assistant","agentDir": "$BASE/agents/assistant","identity": {"name": "Team Leader","theme": "project manager","emoji": "🧠"},"groupChat": {"mentionPatterns": ["@assistant", "@Team Leader", "@总指挥"]},"subagents": {"allowAgents": ["coder", "designer"]}},{"id": "coder","name": "Engineer","workspace": "$BASE/workspace-coder","agentDir": "$BASE/agents/coder","identity": {"name": "Engineer","theme": "expert coder","emoji": "💻"},"groupChat": {"mentionPatterns": ["@coder", "@Engineer", "@工程师", "@Coder"]},"subagents": {"allowAgents": ["assistant"]}},{"id": "designer","name": "Creator","workspace": "$BASE/workspace-designer","agentDir": "$BASE/agents/designer","skills": ["nano-banana-pro"],"identity": {"name": "Creator","theme": "visual artist","emoji": "🎨"},"groupChat": {"mentionPatterns": ["@designer", "@Creator", "@创作官", "@Designer"]},"subagents": {"allowAgents": ["assistant"]}}]},"channels": {"feishu": {"enabled": true,"dmPolicy": "open","groupPolicy": "open","allowFrom": ["*"],"accounts": {"main": {"appId": "${CLEAN_FEISHU_APP_ID}","appSecret": "${CLEAN_FEISHU_APP_SECRET}","botName": "OpenClaw AI","encryptKey": "${CLEAN_FEISHU_ENCRYPT_KEY}"}}},"discord": {"enabled": true,"dmPolicy": "open","groupPolicy": "open","allowFrom": ["*"],"replyToMode": "off","accounts": {"default": {"token": "${CLEAN_DISCORD_TOKEN}","dm": { "enabled": true },"guilds": {"*": { "requireMention": false }},"actions": {"reactions": true,"messages": true}}}}},"bindings": [{"agentId": "assistant","match": { "channel": "feishu", "accountId": "main" }},{"agentId": "assistant","match": { "channel": "discord", "accountId": "default" }}],"gateway": {"mode": "local","port": 7860,"bind": "custom","customBindHost": "0.0.0.0","trustedProxies": ["10.0.0.0/8"],"auth": {"mode": "token","token": "openclaw-hf-space-token-2026","rateLimit": {"maxAttempts": 10,"windowMs": 60000,"lockoutMs": 300000,"exemptLoopback": true}},"controlUi": {"enabled": true,"allowInsecureAuth": true,"dangerouslyDisableDeviceAuth": true,"dangerouslyAllowHostHeaderOriginFallback": true},"tools": {"deny": ["gateway"]}}}JSONEOF# ==========================================# Generate Credentials# ==========================================cat > "$BASE/credentials.json" << CREDEOF{"channels": {"feishu": {"accounts": {"main": {"appId": "${CLEAN_FEISHU_APP_ID}","appSecret": "${CLEAN_FEISHU_APP_SECRET}","encryptKey": "${CLEAN_FEISHU_ENCRYPT_KEY}"}}},"discord": {"token": "${CLEAN_DISCORD_TOKEN}"}}}CREDEOF# Set ownershipchown -R node:node /home/node/.openclaw# Create .env file with gateway token for remote accesscat > "$BASE/.env" << ENVEOFOPENCLAW_GATEWAY_TOKEN=${GATEWAY_TOKEN}ENVEOFchown node:node "$BASE/.env"# Initial backuppython3 /usr/local/bin/sync.py backup || true# Start periodic backup (every 3 hours)(while true; do sleep 10800; python3 /usr/local/bin/sync.py backup || true; done) &# ==========================================# Start Gateway# ==========================================cd "$BASE"echo "--- Starting OpenClaw Gateway on port 7860 ---"echo "--- Gateway Bind: custom (0.0.0.0) ---"echo "--- Gateway Auth: token ---"echo "--- controlUi: allowInsecureAuth=true, dangerouslyDisableDeviceAuth=true ---"echo "--- Agent-to-Agent: enabled ---"echo "--- Tools denied: gateway ---"echo "--- Elevated Mode: enabled for all users ---"echo "--- Model: ${MODEL} ---"echo "--- Skills directory: $BASE/skills ---"echo "--- Designer workspace: $BASE/workspace-designer ---"if [ -d "$BASE/skills/nano-banana-pro" ]; thenecho "--- nano-banana-pro skill: installed ---"ls -la "$BASE/skills/nano-banana-pro/"elseecho "--- WARNING: nano-banana-pro skill NOT found ---"fiif [ -d "$BASE/workspace-designer/skills/nano-banana-pro" ]; thenecho "--- Skill copied to designer workspace: OK ---"elseecho "--- WARNING: Skill not copied to designer workspace ---"fi# ==========================================# Dynamic Configuration (Runtime)# ==========================================# Setup external URL for Canvas# Note: SPACE_HOST is not used to avoid config errors. URL is hardcoded.EXTERNAL_URL="https://tianmingyun999-openclaw.hf.space"echo "--- EXTERNAL_URL set to: $EXTERNAL_URL ---"echo "--- Generating Runtime Designer Configuration ---"cat > "$BASE/workspace-designer/AGENTS.md" << AGENTEOF# Designer Agent Rules## Your TaskGenerate images using the nano-banana-pro skill when requested.## Model Information- **Skill**: nano-banana-pro- **Model**: ${IMAGE_MODEL:-imagen-4.0-generate-001}- **Type**: Image Generation Model (Text-to-Image)## Prompting Guide- Use clear, descriptive prompts in English.- Focus on visual elements, style, lighting, and composition.- Avoid conversational filler; be direct.## How to Generate Images (IMPORTANT!)Use exec tool to run the generate_image.py script directly:1. When user requests an image, use exec tool to run:\`\`\`uv run /home/node/.openclaw/skills/nano-banana-pro/scripts/generate_image.py --prompt "your image description" --filename "output/output.png" --resolution 1K\`\`\`2. The image will be generated at /home/node/.openclaw/workspace-designer/output/output.png3. **To send the image to the user**, you MUST follow these 3 steps:a. **Copy to allowed media directory** (for upload):\`\`\`cp /home/node/.openclaw/workspace-designer/output/output.png /tmp/output.png\`\`\`b. **Copy to canvas directory** (for public URL):\`\`\`cp /home/node/.openclaw/workspace-designer/output/output.png /home/node/.openclaw/canvas/output/output.png\`\`\`c. **Send message with BOTH media and URL**:\`\`\`message channel=feishu target=<user_id> message="Here is your image. Link: ${EXTERNAL_URL}/__openclaw__/canvas/output/output.png" media=/tmp/output.png\`\`\`IMPORTANT:- You MUST copy to /tmp/ first (for upload)- You MUST copy to /home/node/.openclaw/canvas/output/ (for URL link)- Use BOTH media parameter AND the URL in the message text- Do NOT use Markdown image links ()## ExampleUser: "Draw a cat"Action:1. Run script (saving to output/output.png).2. Wait for completion.3. Copy to /tmp: cp /home/node/.openclaw/workspace-designer/output/output.png /tmp/output.png4. Copy to canvas: cp /home/node/.openclaw/workspace-designer/output/output.png /home/node/.openclaw/canvas/output/output.png5. Send: message channel=feishu target=<user_id> message="Image generated. Link: ${EXTERNAL_URL}/__openclaw__/canvas/output/output.png" media=/tmp/output.pngAGENTEOF# Verbose mode for detailed loggingVERBOSE_FLAG=""if [ "${OPENCLAW_VERBOSE:-false}" = "true" ]; thenVERBOSE_FLAG="--verbose"echo "--- Verbose mode enabled ---"fi# Kill any existing gateway process on port 7860 to avoid port conflictsecho "--- Checking for existing gateway processes ---"pkill -f "openclaw gateway" 2>/dev/null || truesleep 1# OpenClaw: use custom bind to 0.0.0.0 for HF Space# Version is auto-updated to latest at runtimeexec openclaw gateway run --port 7860 --allow-unconfigured --token "$GATEWAY_TOKEN" ${VERBOSE_FLAG}STARTEOFRUN chmod +x /usr/local/bin/start-openclaw# Final ownershipRUN chown -R node:node /home/node# Switch to non-root userUSER 1000WORKDIR /home/node# HuggingFace Space uses port 7860EXPOSE 7860# Start OpenClawCMD ["/usr/local/bin/start-openclaw"]
Dockerfile+771-108