File size: 9,319 Bytes
988607c 4fcaec0 988607c 229d644 988607c 229d644 988607c b52caf4 988607c b52caf4 229d644 988607c 229d644 988607c 4fcaec0 988607c 8455100 159235c 988607c 7eb8e6d 2902034 7eb8e6d 2902034 7eb8e6d 2902034 7eb8e6d 988607c 159235c 2902034 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | #!/bin/bash
set -e
echo "🤖 MoltBot AI - Starting..."
# ============================================
# 从环境变量生成 OpenClaw 配置
# ============================================
FEISHU_APP_ID="${FEISHU_APP_ID:-}"
FEISHU_APP_SECRET="${FEISHU_APP_SECRET:-}"
API_BASE_URL="${API_BASE_URL:-https://asem12345-cliproxyapi.hf.space/v1}"
API_KEY="${API_KEY:-}"
MODEL_NAME="${MODEL_NAME:-gemini-3-flash}"
BRAVE_API_KEY="${BRAVE_API_KEY:-}"
if [ -z "$FEISHU_APP_ID" ] || [ -z "$FEISHU_APP_SECRET" ]; then
echo "❌ 错误: 请设置 FEISHU_APP_ID 和 FEISHU_APP_SECRET 环境变量"
echo " 在 HF Space Settings → Secrets 中添加"
exit 1
fi
echo "📝 生成 OpenClaw 配置..."
# 生成 provider ID:从 URL 提取域名部分,加 custom- 前缀
# 例如 https://asem12345-cliproxyapi.hf.space/v1 → custom-asem12345-cliproxyapi-hf-space
PROVIDER_ID="custom-$(echo "$API_BASE_URL" | sed 's|https\?://||' | sed 's|/.*||' | sed 's|[^a-zA-Z0-9]|-|g' | sed 's|-*$||')"
OPENCLAW_DIR="$HOME/.openclaw"
# 创建必要目录
mkdir -p "$OPENCLAW_DIR/agents/main/sessions"
mkdir -p "$OPENCLAW_DIR/workspace"
chmod 700 "$OPENCLAW_DIR" 2>/dev/null || true
# 先写一个最小配置让 doctor 能跑
cat > "$OPENCLAW_DIR/openclaw.json" << JSONEOF
{
"gateway": {
"port": 18789,
"bind": "loopback",
"mode": "local"
},
"channels": {
"feishu": {
"enabled": false
}
}
}
JSONEOF
echo "✅ 最小配置已生成"
echo " 飞书 App ID: ${FEISHU_APP_ID}"
# ============================================
# 运行 doctor --fix(自动安装飞书插件等)
# ============================================
echo "🔧 运行 doctor --fix..."
openclaw doctor --fix || true
# 强力删除飞书插件,防止自动启用
rm -rf /root/.openclaw/extensions/feishu-openclaw
# ============================================
# doctor 完成后,写入完整配置(包含自定义模型)
# doctor 有时会覆盖我们的配置,所以放在 doctor 之后
# ============================================
echo "📝 写入完整配置..."
# 用 python 合并配置(保留 doctor 添加的字段如 meta, wizard, plugins 等)
python3 << PYEOF
import json, os
config_path = os.path.expanduser("~/.openclaw/openclaw.json")
# 读取 doctor 生成的配置
try:
with open(config_path) as f:
config = json.load(f)
except:
config = {}
# 设置 gateway
config.setdefault("gateway", {})
config["gateway"]["port"] = 18789
config["gateway"]["bind"] = "loopback"
config["gateway"]["mode"] = "local"
# 设置自定义 provider
config.setdefault("models", {})
config["models"]["mode"] = "merge"
config["models"].setdefault("providers", {})
config["models"]["providers"]["${PROVIDER_ID}"] = {
"baseUrl": "${API_BASE_URL}",
"apiKey": "${API_KEY}",
"api": "openai-completions",
"models": [
{
"id": "${MODEL_NAME}",
"name": "${MODEL_NAME} (Custom Provider)",
"reasoning": False,
"input": ["text"],
"cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
"contextWindow": 131072,
"maxTokens": 8192
}
]
}
# 设置 agent defaults
config.setdefault("agents", {}).setdefault("defaults", {})
config["agents"]["defaults"]["model"] = {
"primary": "${PROVIDER_ID}/${MODEL_NAME}"
}
# 配置 imageModel(Gemini 原生支持多模态,复用主模型)
config["agents"]["defaults"]["imageModel"] = {
"primary": "${PROVIDER_ID}/${MODEL_NAME}"
}
config["agents"]["defaults"].setdefault("models", {})
config["agents"]["defaults"]["models"]["${PROVIDER_ID}/${MODEL_NAME}"] = {}
config["agents"]["defaults"].setdefault("workspace", os.path.expanduser("~/.openclaw/workspace"))
config["agents"]["defaults"].setdefault("compaction", {"mode": "safeguard"})
config["agents"]["defaults"].setdefault("maxConcurrent", 4)
# 配置 memory(记忆功能)
config["agents"]["defaults"]["memorySearch"] = {
"enabled": True,
"provider": "local"
}
print(f"✅ 图片分析(imageModel)已启用")
print(f"✅ 记忆功能(memory)已启用")
# 删除飞书 channel 配置 (防止 OpenClaw 自动启用)
config.setdefault("channels", {})
if "feishu" in config["channels"]:
del config["channels"]["feishu"]
# 配置 Brave Search(上网搜索)
brave_key = os.environ.get("BRAVE_API_KEY", "${BRAVE_API_KEY}")
if brave_key:
config.setdefault("tools", {}).setdefault("web", {})
config["tools"]["web"]["search"] = {
"enabled": True,
"provider": "brave",
"maxResults": 10
}
print(f"✅ Brave Search 已启用")
with open(config_path, "w") as f:
json.dump(config, f, indent=2)
print(f"✅ 完整配置已写入 {config_path}")
print(f" 模型: ${PROVIDER_ID}/${MODEL_NAME}")
# 同时写入 agent 级别的 models.json(防止 fallback 到 anthropic)
agent_dir = os.path.expanduser("~/.openclaw/agents/main/agent")
os.makedirs(agent_dir, exist_ok=True)
agent_models = {
"providers": {
"github-copilot": {
"baseUrl": "https://api.individual.githubcopilot.com",
"models": []
},
"${PROVIDER_ID}": {
"baseUrl": "${API_BASE_URL}",
"apiKey": "${API_KEY}",
"api": "openai-completions",
"models": [
{
"id": "${MODEL_NAME}",
"name": "${MODEL_NAME} (Custom Provider)",
"reasoning": False,
"input": ["text"],
"cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
"contextWindow": 131072,
"maxTokens": 8192
}
]
}
}
}
models_path = os.path.join(agent_dir, "models.json")
with open(models_path, "w") as f:
json.dump(agent_models, f, indent=2)
# 确保 auth-profiles.json 存在(OpenClaw 查找的是这个文件)
auth_path = os.path.join(agent_dir, "auth-profiles.json")
with open(auth_path, "w") as f:
json.dump({}, f)
# 也写一份 auth.json 以防万一
auth2_path = os.path.join(agent_dir, "auth.json")
if not os.path.exists(auth2_path):
with open(auth2_path, "w") as f:
json.dump({}, f)
print(f"✅ Agent 配置已写入 {agent_dir}")
# 递归扫描所有 json 文件,替换 anthropic 引用
import glob
replaced = []
provider_id = "${PROVIDER_ID}"
model_id = "${MODEL_NAME}"
full_model = f"{provider_id}/{model_id}"
for fpath in glob.glob(os.path.expanduser("~/.openclaw/**/*.json"), recursive=True):
try:
with open(fpath) as f:
content = f.read()
if "anthropic" in content:
original = content
# 替换 model references
content = content.replace('"anthropic/claude-sonnet-4-20250514"', f'"{full_model}"')
content = content.replace('"anthropic/claude-3-5-sonnet"', f'"{full_model}"')
content = content.replace('"anthropic/claude-3-5-haiku"', f'"{full_model}"')
content = content.replace('"anthropic/claude-3-haiku"', f'"{full_model}"')
# 通用 anthropic provider 引用
content = content.replace('"anthropic"', f'"{provider_id}"')
if content != original:
with open(fpath, "w") as f:
f.write(content)
replaced.append(fpath)
except:
pass
if replaced:
print(f"⚠️ 替换了 {len(replaced)} 个文件中的 anthropic 引用:")
for r in replaced:
print(f" - {r}")
else:
print("✅ 未发现 anthropic 引用")
# 打印调试信息
print("\n🔍 调试 - openclaw.json:")
try:
with open(config_path) as f:
print(f.read()[:2000])
except:
print(" 无法读取")
print("\n🔍 调试 - agent 目录内容:")
for fpath in glob.glob(os.path.join(agent_dir, "*")):
print(f" {fpath}")
try:
with open(fpath) as f:
c = f.read()[:500]
print(f" {c}")
except:
pass
PYEOF
# 注意: 不再使用 image_proxy 和 sed patch(会破坏 WebSocket 连接)
# 图片处理完全由 image_daemon.py 负责
# ============================================
# 启动 OpenClaw Gateway(后台)
# ============================================
echo "🚀 启动 OpenClaw Gateway..."
openclaw gateway --force &
GATEWAY_PID=$!
echo " Gateway PID: $GATEWAY_PID"
# 等待网关启动
sleep 5
# ============================================
# 启动图片预处理守护进程(后台,带自动重启守护)
# ============================================
echo "🖼️ 启动图片预处理守护进程(带自动重启)..."
(
RESTART_COUNT=0
while true; do
RESTART_COUNT=$((RESTART_COUNT + 1))
echo "[image_daemon_guard] 🚀 启动 image_daemon (第 ${RESTART_COUNT} 次)"
python3 /app/image_daemon.py
EXIT_CODE=$?
echo "[image_daemon_guard] ⚠️ image_daemon 退出 (code=${EXIT_CODE}), 3 秒后重启..."
sleep 3
done
) &
IMAGE_DAEMON_PID=$!
echo " Image Daemon Guard PID: $IMAGE_DAEMON_PID"
# ============================================
# 启动状态监控网页(前台,端口 7860)
# ============================================
echo "📊 启动状态监控网页 (端口 7860)..."
exec python3 /app/status_page.py
|