-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart-moltbot.sh
More file actions
308 lines (272 loc) · 11.8 KB
/
start-moltbot.sh
File metadata and controls
308 lines (272 loc) · 11.8 KB
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
#!/bin/bash
# Startup script for Moltbot in Cloudflare Sandbox
# This script:
# 1. Restores config from R2 backup if available
# 2. Configures moltbot from environment variables
# 3. Starts a background sync to backup config to R2
# 4. Starts the gateway
set -e
# Check if clawdbot gateway is already running - bail early if so
# Note: CLI is still named "clawdbot" until upstream renames it
if pgrep -f "clawdbot gateway" > /dev/null 2>&1; then
echo "Moltbot gateway is already running, exiting."
exit 0
fi
# Paths (clawdbot paths are used internally - upstream hasn't renamed yet)
CONFIG_DIR="/root/.clawdbot"
CONFIG_FILE="$CONFIG_DIR/clawdbot.json"
TEMPLATE_DIR="/root/.clawdbot-templates"
TEMPLATE_FILE="$TEMPLATE_DIR/moltbot.json.template"
BACKUP_DIR="/data/moltbot"
echo "Config directory: $CONFIG_DIR"
echo "Backup directory: $BACKUP_DIR"
# Create config directory
mkdir -p "$CONFIG_DIR"
# ============================================================
# RESTORE FROM R2 BACKUP
# ============================================================
# Check if R2 backup exists by looking for clawdbot.json
# The BACKUP_DIR may exist but be empty if R2 was just mounted
# Note: backup structure is $BACKUP_DIR/clawdbot/ and $BACKUP_DIR/skills/
# Helper function to check if R2 backup is newer than local
should_restore_from_r2() {
local R2_SYNC_FILE="$BACKUP_DIR/.last-sync"
local LOCAL_SYNC_FILE="$CONFIG_DIR/.last-sync"
# If no R2 sync timestamp, don't restore
if [ ! -f "$R2_SYNC_FILE" ]; then
echo "No R2 sync timestamp found, skipping restore"
return 1
fi
# If no local sync timestamp, restore from R2
if [ ! -f "$LOCAL_SYNC_FILE" ]; then
echo "No local sync timestamp, will restore from R2"
return 0
fi
# Compare timestamps
R2_TIME=$(cat "$R2_SYNC_FILE" 2>/dev/null)
LOCAL_TIME=$(cat "$LOCAL_SYNC_FILE" 2>/dev/null)
echo "R2 last sync: $R2_TIME"
echo "Local last sync: $LOCAL_TIME"
# Convert to epoch seconds for comparison
R2_EPOCH=$(date -d "$R2_TIME" +%s 2>/dev/null || echo "0")
LOCAL_EPOCH=$(date -d "$LOCAL_TIME" +%s 2>/dev/null || echo "0")
if [ "$R2_EPOCH" -gt "$LOCAL_EPOCH" ]; then
echo "R2 backup is newer, will restore"
return 0
else
echo "Local data is newer or same, skipping restore"
return 1
fi
}
if [ -f "$BACKUP_DIR/clawdbot/clawdbot.json" ]; then
if should_restore_from_r2; then
echo "Restoring from R2 backup at $BACKUP_DIR/clawdbot..."
cp -a "$BACKUP_DIR/clawdbot/." "$CONFIG_DIR/"
# Copy the sync timestamp to local so we know what version we have
cp -f "$BACKUP_DIR/.last-sync" "$CONFIG_DIR/.last-sync" 2>/dev/null || true
echo "Restored config from R2 backup"
fi
elif [ -f "$BACKUP_DIR/clawdbot.json" ]; then
# Legacy backup format (flat structure)
if should_restore_from_r2; then
echo "Restoring from legacy R2 backup at $BACKUP_DIR..."
cp -a "$BACKUP_DIR/." "$CONFIG_DIR/"
cp -f "$BACKUP_DIR/.last-sync" "$CONFIG_DIR/.last-sync" 2>/dev/null || true
echo "Restored config from legacy R2 backup"
fi
elif [ -d "$BACKUP_DIR" ]; then
echo "R2 mounted at $BACKUP_DIR but no backup data found yet"
else
echo "R2 not mounted, starting fresh"
fi
# Restore skills from R2 backup if available (only if R2 is newer)
SKILLS_DIR="/root/clawd/skills"
if [ -d "$BACKUP_DIR/skills" ] && [ "$(ls -A $BACKUP_DIR/skills 2>/dev/null)" ]; then
if should_restore_from_r2; then
echo "Restoring skills from $BACKUP_DIR/skills..."
mkdir -p "$SKILLS_DIR"
cp -a "$BACKUP_DIR/skills/." "$SKILLS_DIR/"
echo "Restored skills from R2 backup"
fi
fi
# If config file still doesn't exist, create from template
if [ ! -f "$CONFIG_FILE" ]; then
echo "No existing config found, initializing from template..."
if [ -f "$TEMPLATE_FILE" ]; then
cp "$TEMPLATE_FILE" "$CONFIG_FILE"
else
# Create minimal config if template doesn't exist
cat > "$CONFIG_FILE" << 'EOFCONFIG'
{
"agents": {
"defaults": {
"workspace": "/root/clawd"
}
},
"gateway": {
"port": 18789,
"mode": "local"
}
}
EOFCONFIG
fi
else
echo "Using existing config"
fi
# ============================================================
# UPDATE CONFIG FROM ENVIRONMENT VARIABLES
# ============================================================
node << EOFNODE
const fs = require('fs');
const configPath = '/root/.clawdbot/clawdbot.json';
console.log('Updating config at:', configPath);
let config = {};
try {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
} catch (e) {
console.log('Starting with empty config');
}
// Ensure nested objects exist
config.agents = config.agents || {};
config.agents.defaults = config.agents.defaults || {};
config.agents.defaults.model = config.agents.defaults.model || {};
config.gateway = config.gateway || {};
config.channels = config.channels || {};
// Clean up any broken anthropic provider config from previous runs
// (older versions didn't include required 'name' field)
if (config.models?.providers?.anthropic?.models) {
const hasInvalidModels = config.models.providers.anthropic.models.some(m => !m.name);
if (hasInvalidModels) {
console.log('Removing broken anthropic provider config (missing model names)');
delete config.models.providers.anthropic;
}
}
// Gateway configuration
config.gateway.port = 18789;
config.gateway.mode = 'local';
config.gateway.trustedProxies = ['10.1.0.0'];
// Set gateway token if provided
if (process.env.CLAWDBOT_GATEWAY_TOKEN) {
config.gateway.auth = config.gateway.auth || {};
config.gateway.auth.token = process.env.CLAWDBOT_GATEWAY_TOKEN;
}
// Allow insecure auth for dev mode
if (process.env.CLAWDBOT_DEV_MODE === 'true') {
config.gateway.controlUi = config.gateway.controlUi || {};
config.gateway.controlUi.allowInsecureAuth = true;
}
// Telegram configuration
if (process.env.TELEGRAM_BOT_TOKEN) {
config.channels.telegram = config.channels.telegram || {};
config.channels.telegram.botToken = process.env.TELEGRAM_BOT_TOKEN;
config.channels.telegram.enabled = true;
const telegramDmPolicy = process.env.TELEGRAM_DM_POLICY || 'pairing';
config.channels.telegram.dmPolicy = telegramDmPolicy;
if (process.env.TELEGRAM_DM_ALLOW_FROM) {
// Explicit allowlist: "123,456,789" → ['123', '456', '789']
config.channels.telegram.allowFrom = process.env.TELEGRAM_DM_ALLOW_FROM.split(',');
} else if (telegramDmPolicy === 'open') {
// "open" policy requires allowFrom: ["*"]
config.channels.telegram.allowFrom = ['*'];
}
}
// Discord configuration
// Note: Discord uses nested dm.policy, not flat dmPolicy like Telegram
// See: https://github.com/moltbot/moltbot/blob/v2026.1.24-1/src/config/zod-schema.providers-core.ts#L147-L155
if (process.env.DISCORD_BOT_TOKEN) {
config.channels.discord = config.channels.discord || {};
config.channels.discord.token = process.env.DISCORD_BOT_TOKEN;
config.channels.discord.enabled = true;
const discordDmPolicy = process.env.DISCORD_DM_POLICY || 'pairing';
config.channels.discord.dm = config.channels.discord.dm || {};
config.channels.discord.dm.policy = discordDmPolicy;
// "open" policy requires allowFrom: ["*"]
if (discordDmPolicy === 'open') {
config.channels.discord.dm.allowFrom = ['*'];
}
}
// Slack configuration
if (process.env.SLACK_BOT_TOKEN && process.env.SLACK_APP_TOKEN) {
config.channels.slack = config.channels.slack || {};
config.channels.slack.botToken = process.env.SLACK_BOT_TOKEN;
config.channels.slack.appToken = process.env.SLACK_APP_TOKEN;
config.channels.slack.enabled = true;
}
// Base URL override (e.g., for Cloudflare AI Gateway)
// Usage: Set AI_GATEWAY_BASE_URL or ANTHROPIC_BASE_URL to your endpoint like:
// https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/anthropic
// https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai
const baseUrl = (process.env.AI_GATEWAY_BASE_URL || process.env.ANTHROPIC_BASE_URL || '').replace(/\/+$/, '');
const isOpenAI = baseUrl.endsWith('/openai');
if (isOpenAI) {
// Create custom openai provider config with baseUrl override
// Omit apiKey so moltbot falls back to OPENAI_API_KEY env var
console.log('Configuring OpenAI provider with base URL:', baseUrl);
config.models = config.models || {};
config.models.providers = config.models.providers || {};
config.models.providers.openai = {
baseUrl: baseUrl,
api: 'openai-responses',
models: [
{ id: 'gpt-5.2', name: 'GPT-5.2', contextWindow: 200000 },
{ id: 'gpt-5', name: 'GPT-5', contextWindow: 200000 },
{ id: 'gpt-4.5-preview', name: 'GPT-4.5 Preview', contextWindow: 128000 },
]
};
// Add models to the allowlist so they appear in /models
config.agents.defaults.models = config.agents.defaults.models || {};
config.agents.defaults.models['openai/gpt-5.2'] = { alias: 'GPT-5.2' };
config.agents.defaults.models['openai/gpt-5'] = { alias: 'GPT-5' };
config.agents.defaults.models['openai/gpt-4.5-preview'] = { alias: 'GPT-4.5' };
config.agents.defaults.model.primary = 'openai/gpt-5.2';
} else if (baseUrl) {
console.log('Configuring Anthropic provider with base URL:', baseUrl);
config.models = config.models || {};
config.models.providers = config.models.providers || {};
const providerConfig = {
baseUrl: baseUrl,
api: 'anthropic-messages',
models: [
{ id: 'claude-opus-4-5-20251101', name: 'Claude Opus 4.5', contextWindow: 200000 },
{ id: 'claude-sonnet-4-5-20250929', name: 'Claude Sonnet 4.5', contextWindow: 200000 },
{ id: 'claude-haiku-4-5-20251001', name: 'Claude Haiku 4.5', contextWindow: 200000 },
]
};
// Include API key in provider config if set (required when using custom baseUrl)
if (process.env.ANTHROPIC_API_KEY) {
providerConfig.apiKey = process.env.ANTHROPIC_API_KEY;
}
config.models.providers.anthropic = providerConfig;
// Add models to the allowlist so they appear in /models
config.agents.defaults.models = config.agents.defaults.models || {};
config.agents.defaults.models['anthropic/claude-opus-4-5-20251101'] = { alias: 'Opus 4.5' };
config.agents.defaults.models['anthropic/claude-sonnet-4-5-20250929'] = { alias: 'Sonnet 4.5' };
config.agents.defaults.models['anthropic/claude-haiku-4-5-20251001'] = { alias: 'Haiku 4.5' };
config.agents.defaults.model.primary = 'anthropic/claude-opus-4-5-20251101';
} else {
// Default to Anthropic without custom base URL (uses built-in pi-ai catalog)
config.agents.defaults.model.primary = 'anthropic/claude-opus-4-5';
}
// Write updated config
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
console.log('Configuration updated successfully');
console.log('Config:', JSON.stringify(config, null, 2));
EOFNODE
# ============================================================
# START GATEWAY
# ============================================================
# Note: R2 backup sync is handled by the Worker's cron trigger
echo "Starting Moltbot Gateway..."
echo "Gateway will be available on port 18789"
# Clean up stale lock files
rm -f /tmp/clawdbot-gateway.lock 2>/dev/null || true
rm -f "$CONFIG_DIR/gateway.lock" 2>/dev/null || true
BIND_MODE="lan"
echo "Dev mode: ${CLAWDBOT_DEV_MODE:-false}, Bind mode: $BIND_MODE"
if [ -n "$CLAWDBOT_GATEWAY_TOKEN" ]; then
echo "Starting gateway with token auth..."
exec clawdbot gateway --port 18789 --verbose --allow-unconfigured --bind "$BIND_MODE" --token "$CLAWDBOT_GATEWAY_TOKEN"
else
echo "Starting gateway with device pairing (no token)..."
exec clawdbot gateway --port 18789 --verbose --allow-unconfigured --bind "$BIND_MODE"
fi