8900 commited on
Commit
0263c73
Β·
verified Β·
1 Parent(s): 6af251e

Update setup-hf-config.mjs

Browse files
Files changed (1) hide show
  1. setup-hf-config.mjs +104 -79
setup-hf-config.mjs CHANGED
@@ -4,8 +4,20 @@ import https from "node:https";
4
 
5
  // ============================================================
6
  // OpenClaw HF Spaces - Production Config Writer
7
- // Called ONCE per container lifetime by entrypoint.sh.
8
- // Always writes fresh config from env vars on first boot.
 
 
 
 
 
 
 
 
 
 
 
 
9
  // ============================================================
10
 
11
  var HOME = process.env.OPENCLAW_HOME || process.env.HOME || "/home/user";
@@ -20,27 +32,20 @@ function parseList(val) {
20
  if (!val || !val.trim()) return [];
21
  return val.split(",").map(function(s) { return s.trim(); }).filter(Boolean);
22
  }
23
-
24
- function envStr(key) {
25
- return (process.env[key] || "").trim();
26
- }
27
 
28
  // –– auth –––––––––––––––––––––––––
29
-
30
  var gatewayToken = envStr("OPENCLAW_GATEWAY_TOKEN");
31
  var gatewayPassword = envStr("OPENCLAW_GATEWAY_PASSWORD");
32
-
33
  if (!gatewayToken && !gatewayPassword) {
34
  console.error("[setup] FATAL: set OPENCLAW_GATEWAY_TOKEN or OPENCLAW_GATEWAY_PASSWORD");
35
  process.exit(0);
36
  }
37
 
38
  // –– model ———————————————––
39
-
40
  var defaultModel = envStr("OPENCLAW_HF_DEFAULT_MODEL") || "google/gemini-2.0-flash";
41
 
42
  // –– provider keys —————————————–
43
-
44
  var EXCLUDE_PREFIXES = [
45
  "OPENCLAW_", "SPACE_", "SYSTEM_", "HF_",
46
  "NODE_", "PATH", "HOME", "USER", "PWD", "LANG", "LC_",
@@ -50,7 +55,6 @@ var INCLUDE_SUFFIXES = [
50
  "_API_KEY", "_SECRET_KEY", "_ACCESS_TOKEN",
51
  "_BOT_TOKEN", "_AUTH_TOKEN", "_APP_KEY"
52
  ];
53
-
54
  function isProviderKey(k) {
55
  var i;
56
  for (i = 0; i < EXCLUDE_PREFIXES.length; i++) {
@@ -62,61 +66,26 @@ if (k.length > s.length && k.indexOf(s) === k.length - s.length) return true;
62
  }
63
  return false;
64
  }
65
-
66
  var providerKeys = Object.keys(process.env).filter(function(k) {
67
  return isProviderKey(k) && (process.env[k] || "").trim();
68
  }).sort();
69
 
70
- console.log("[setup] Detected provider keys (" + providerKeys.length + "):");
71
- providerKeys.forEach(function(k) { console.log(" + " + k); });
72
 
73
  // –– trusted proxies β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
74
-
75
  var envProxies = parseList(envStr("OPENCLAW_GATEWAY_TRUSTED_PROXIES"));
76
  var trustedProxies = envProxies.length > 0 ? envProxies : [
77
- "10.0.0.0/8",
78
- "172.16.0.0/12",
79
- "192.168.0.0/16",
80
  "10.16.0.0/12", "10.20.0.0/12",
81
  "10.16.4.123", "10.16.7.92", "10.16.18.232",
82
  "10.16.34.155", "10.16.43.133", "10.16.1.206",
83
  "10.16.37.110", "10.16.43.246",
84
  "10.20.1.9", "10.20.1.222",
85
  "10.20.26.157", "10.20.31.87",
86
- "10.20.0.1", "172.17.0.1",
87
- "127.0.0.1"
88
  ];
89
 
90
- // –– build config β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
91
-
92
- var config = {
93
- gateway: {
94
- auth: gatewayToken
95
- ? { mode: "token", token: gatewayToken }
96
- : { mode: "password", password: gatewayPassword },
97
- controlUi: {
98
- allowInsecureAuth: true,
99
- allowedOrigins: ["*"],
100
- dangerouslyDisableDeviceAuth: true,
101
- dangerouslyAllowHostHeaderOriginFallback: true
102
- },
103
- trustedProxies: trustedProxies
104
- },
105
- agents: {
106
- defaults: {
107
- model: defaultModel,
108
- workspace: WORKSPACE
109
- }
110
- },
111
- env: { vars: {} }
112
- };
113
-
114
- providerKeys.forEach(function(pk) {
115
- config.env.vars[pk] = (process.env[pk] || "").trim();
116
- });
117
-
118
- // –– Telegram –––––––––––––––––––––––
119
-
120
  function tgRequest(token, method, body) {
121
  return new Promise(function(resolve) {
122
  var data = JSON.stringify(body || {});
@@ -142,64 +111,120 @@ req.end();
142
  });
143
  }
144
 
145
- async function setupTelegram() {
146
- var token = envStr("TELEGRAM_BOT_TOKEN");
147
- if (!token) {
148
- console.log("[setup] Telegram: disabled (no TELEGRAM_BOT_TOKEN)");
149
  return;
150
  }
151
-
152
- if (SPACE_HOST) {
153
- var webhookUrl = "https://" + SPACE_HOST + "/tg-webhook";
154
  var r = await tgRequest(token, "setWebhook", {
155
- url: webhookUrl,
156
- drop_pending_updates: true,
157
- max_connections: 10
158
  });
159
  if (r && r.ok) {
160
- console.log("[setup] Telegram: webhook registered -> " + webhookUrl);
161
  } else {
162
- console.log("[setup] Telegram: auto-registration failed");
163
- console.log("[setup] Open this URL in your browser once:");
164
  console.log(" https://api.telegram.org/bot" + token +
165
- "/setWebhook?url=" + webhookUrl + "&drop_pending_updates=true");
166
  }
167
- } else {
168
- console.log("[setup] Telegram: set SPACE_HOST for auto webhook");
169
  }
170
 
171
- config.channels = {
172
- telegram: {
173
- enabled: true,
174
- accounts: {
175
- main: { botToken: token, apiRoot: "https://api.telegram.org" }
176
- }
177
  }
178
- };
179
- console.log("[setup] Telegram: configured");
 
 
 
 
 
180
  }
181
 
182
  // –– main –––––––––––––––––––––––––
183
-
184
  (async function() {
185
  fs.mkdirSync(STATE_DIR, { recursive: true });
186
  fs.mkdirSync(WORKSPACE, { recursive: true });
187
  fs.mkdirSync(path.join(WORKSPACE, "memory"), { recursive: true });
188
 
189
- await setupTelegram();
 
190
 
 
191
  if (fs.existsSync(CONFIG_PATH)) {
192
- fs.copyFileSync(CONFIG_PATH, CONFIG_PATH + ".bak");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  }
194
- fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
195
 
 
196
  console.log("[setup] Done.");
197
  console.log("[setup] auth = " + (gatewayToken ? "token" : "password"));
198
  console.log("[setup] model = " + defaultModel);
199
  console.log("[setup] workspace = " + WORKSPACE);
200
  console.log("[setup] proxies = " + trustedProxies.length);
201
  console.log("[setup] env.vars = " + providerKeys.length);
202
- console.log("[setup] config = " + CONFIG_PATH);
203
  })().catch(function(e) {
204
  console.error("[setup] Fatal: " + e.message);
205
  process.exit(0);
 
4
 
5
  // ============================================================
6
  // OpenClaw HF Spaces - Production Config Writer
7
+ //
8
+ // KEY BEHAVIOR:
9
+ // If openclaw.json exists and is valid -> PATCH only (preserve user settings)
10
+ // If openclaw.json missing -> write fresh template
11
+ //
12
+ // What gets patched every run:
13
+ // gateway.auth (from env OPENCLAW_GATEWAY_TOKEN)
14
+ // env.vars (all provider API keys)
15
+ // channels.telegram (from env TELEGRAM_BOT_TOKEN)
16
+ // agents.defaults.workspace (ensure correct path)
17
+ // gateway.trustedProxies (ensure not empty)
18
+ //
19
+ // What is NEVER touched when patching:
20
+ // All user settings from Control UI (model choices, agent config, etc.)
21
  // ============================================================
22
 
23
  var HOME = process.env.OPENCLAW_HOME || process.env.HOME || "/home/user";
 
32
  if (!val || !val.trim()) return [];
33
  return val.split(",").map(function(s) { return s.trim(); }).filter(Boolean);
34
  }
35
+ function envStr(key) { return (process.env[key] || "").trim(); }
 
 
 
36
 
37
  // –– auth –––––––––––––––––––––––––
 
38
  var gatewayToken = envStr("OPENCLAW_GATEWAY_TOKEN");
39
  var gatewayPassword = envStr("OPENCLAW_GATEWAY_PASSWORD");
 
40
  if (!gatewayToken && !gatewayPassword) {
41
  console.error("[setup] FATAL: set OPENCLAW_GATEWAY_TOKEN or OPENCLAW_GATEWAY_PASSWORD");
42
  process.exit(0);
43
  }
44
 
45
  // –– model ———————————————––
 
46
  var defaultModel = envStr("OPENCLAW_HF_DEFAULT_MODEL") || "google/gemini-2.0-flash";
47
 
48
  // –– provider keys —————————————–
 
49
  var EXCLUDE_PREFIXES = [
50
  "OPENCLAW_", "SPACE_", "SYSTEM_", "HF_",
51
  "NODE_", "PATH", "HOME", "USER", "PWD", "LANG", "LC_",
 
55
  "_API_KEY", "_SECRET_KEY", "_ACCESS_TOKEN",
56
  "_BOT_TOKEN", "_AUTH_TOKEN", "_APP_KEY"
57
  ];
 
58
  function isProviderKey(k) {
59
  var i;
60
  for (i = 0; i < EXCLUDE_PREFIXES.length; i++) {
 
66
  }
67
  return false;
68
  }
 
69
  var providerKeys = Object.keys(process.env).filter(function(k) {
70
  return isProviderKey(k) && (process.env[k] || "").trim();
71
  }).sort();
72
 
73
+ console.log("[setup] Provider keys (" + providerKeys.length + "): " + providerKeys.join(", "));
 
74
 
75
  // –– trusted proxies β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
 
76
  var envProxies = parseList(envStr("OPENCLAW_GATEWAY_TRUSTED_PROXIES"));
77
  var trustedProxies = envProxies.length > 0 ? envProxies : [
78
+ "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16",
 
 
79
  "10.16.0.0/12", "10.20.0.0/12",
80
  "10.16.4.123", "10.16.7.92", "10.16.18.232",
81
  "10.16.34.155", "10.16.43.133", "10.16.1.206",
82
  "10.16.37.110", "10.16.43.246",
83
  "10.20.1.9", "10.20.1.222",
84
  "10.20.26.157", "10.20.31.87",
85
+ "10.20.0.1", "172.17.0.1", "127.0.0.1"
 
86
  ];
87
 
88
+ // –– Telegram helpers –––––––––––––––––––
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  function tgRequest(token, method, body) {
90
  return new Promise(function(resolve) {
91
  var data = JSON.stringify(body || {});
 
111
  });
112
  }
113
 
114
+ async function setupWebhook(token) {
115
+ if (!SPACE_HOST) {
116
+ console.log("[setup] Telegram: set SPACE_HOST for auto webhook");
 
117
  return;
118
  }
119
+ var url = "https://" + SPACE_HOST + "/tg-webhook";
 
 
120
  var r = await tgRequest(token, "setWebhook", {
121
+ url: url, drop_pending_updates: true, max_connections: 10
 
 
122
  });
123
  if (r && r.ok) {
124
+ console.log("[setup] Telegram: webhook registered -> " + url);
125
  } else {
126
+ console.log("[setup] Telegram: webhook failed (HF outbound blocked). Open in browser:");
 
127
  console.log(" https://api.telegram.org/bot" + token +
128
+ "/setWebhook?url=" + url + "&drop_pending_updates=true");
129
  }
 
 
130
  }
131
 
132
+ function buildAuth() {
133
+ return gatewayToken
134
+ ? { mode: "token", token: gatewayToken }
135
+ : { mode: "password", password: gatewayPassword };
 
 
136
  }
137
+
138
+ function buildEnvVars() {
139
+ var vars = {};
140
+ providerKeys.forEach(function(pk) {
141
+ vars[pk] = (process.env[pk] || "").trim();
142
+ });
143
+ return vars;
144
  }
145
 
146
  // –– main –––––––––––––––––––––––––
 
147
  (async function() {
148
  fs.mkdirSync(STATE_DIR, { recursive: true });
149
  fs.mkdirSync(WORKSPACE, { recursive: true });
150
  fs.mkdirSync(path.join(WORKSPACE, "memory"), { recursive: true });
151
 
152
+ var token = envStr("TELEGRAM_BOT_TOKEN");
153
+ if (token) await setupWebhook(token);
154
 
155
+ // –– PATCH MODE: existing valid config found ––––
156
  if (fs.existsSync(CONFIG_PATH)) {
157
+ var raw = fs.readFileSync(CONFIG_PATH, "utf-8").trim();
158
+ var parsed = null;
159
+ try { parsed = JSON.parse(raw); } catch (e) { /* invalid, fall through to fresh write */ }
160
+
161
+ if (parsed) {
162
+ // Patch only env-derived fields, preserve everything else
163
+ parsed.gateway = parsed.gateway || {};
164
+ parsed.gateway.auth = buildAuth();
165
+ if (!parsed.gateway.trustedProxies || parsed.gateway.trustedProxies.length < 5) {
166
+ parsed.gateway.trustedProxies = trustedProxies;
167
+ }
168
+ parsed.agents = parsed.agents || {};
169
+ parsed.agents.defaults = parsed.agents.defaults || {};
170
+ parsed.agents.defaults.workspace = WORKSPACE;
171
+ parsed.env = parsed.env || {};
172
+ parsed.env.vars = buildEnvVars();
173
+
174
+ if (token) {
175
+ parsed.channels = {
176
+ telegram: {
177
+ enabled: true,
178
+ accounts: { main: { botToken: token, apiRoot: "https://api.telegram.org" } }
179
+ }
180
+ };
181
+ }
182
+
183
+ fs.copyFileSync(CONFIG_PATH, CONFIG_PATH + ".bak");
184
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(parsed, null, 2), "utf-8");
185
+ console.log("[setup] Patched existing config (user settings preserved)");
186
+ console.log("[setup] workspace = " + WORKSPACE);
187
+ console.log("[setup] env.vars = " + providerKeys.length);
188
+ return;
189
+ }
190
+ }
191
+
192
+ // –– FRESH MODE: no config or invalid config ––––
193
+ console.log("[setup] No valid config found - writing fresh template");
194
+
195
+ var config = {
196
+ gateway: {
197
+ auth: buildAuth(),
198
+ controlUi: {
199
+ allowInsecureAuth: true,
200
+ allowedOrigins: ["*"],
201
+ dangerouslyDisableDeviceAuth: true,
202
+ dangerouslyAllowHostHeaderOriginFallback: true
203
+ },
204
+ trustedProxies: trustedProxies
205
+ },
206
+ agents: {
207
+ defaults: { model: defaultModel, workspace: WORKSPACE }
208
+ },
209
+ env: { vars: buildEnvVars() }
210
+ };
211
+
212
+ if (token) {
213
+ config.channels = {
214
+ telegram: {
215
+ enabled: true,
216
+ accounts: { main: { botToken: token, apiRoot: "https://api.telegram.org" } }
217
+ }
218
+ };
219
  }
 
220
 
221
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
222
  console.log("[setup] Done.");
223
  console.log("[setup] auth = " + (gatewayToken ? "token" : "password"));
224
  console.log("[setup] model = " + defaultModel);
225
  console.log("[setup] workspace = " + WORKSPACE);
226
  console.log("[setup] proxies = " + trustedProxies.length);
227
  console.log("[setup] env.vars = " + providerKeys.length);
 
228
  })().catch(function(e) {
229
  console.error("[setup] Fatal: " + e.message);
230
  process.exit(0);