Somrat Sorkar commited on
Commit
18ecb3d
Β·
unverified Β·
2 Parent(s): 8f6996cb835b9d

Merge pull request #21 from anurag008w/main

Browse files

Enhance Jupyter security, environment builder UX, and browser reliability

.env.example CHANGED
@@ -131,12 +131,29 @@ LLM_MODEL=anthropic/claude-sonnet-4-5
131
  # Keys are rotated round-robin on every request β€” useful when you
132
  # have multiple accounts or want to spread rate-limit quota.
133
  #
 
 
 
 
 
 
 
134
  # Pattern: <PROVIDER>_API_KEYS=key1,key2,key3
135
  # Fallback order: plural pool β†’ singular key β†’ LLM_API_KEY (optional)
136
  # Set false only if you want to disable global LLM_API_KEY fallback
137
  # across providers.
138
  LLM_API_KEY_FALLBACK_ENABLED=true
139
  #
 
 
 
 
 
 
 
 
 
 
140
  # Uncomment and fill in only the providers you use:
141
  #
142
  # ANTHROPIC_API_KEYS=sk-ant-key1,sk-ant-key2,sk-ant-key3
@@ -147,7 +164,8 @@ LLM_API_KEY_FALLBACK_ENABLED=true
147
  # KILOCODE_API_KEYS=key1,key2
148
  # OPENCODE_API_KEYS=key1,key2
149
  # ZAI_API_KEYS=key1,key2
150
- # MOONSHOT_API_KEYS=key1,key2
 
151
  # MINIMAX_API_KEYS=key1,key2
152
  # XIAOMI_API_KEYS=key1,key2
153
  # VOLCANO_ENGINE_API_KEYS=key1,key2
@@ -248,8 +266,8 @@ LLM_API_KEY_FALLBACK_ENABLED=true
248
  GATEWAY_TOKEN=your_gateway_token_here
249
 
250
  # [OPTIONAL] JupyterLab terminal token for /terminal/
251
- # Defaults to "huggingface" if unset. Set a strong token for private deployments.
252
- JUPYTER_TOKEN=huggingface
253
 
254
  # (Optional) Password auth β€” simpler alternative to token for casual users
255
  # If set, users can log in with this password instead of the token
@@ -288,14 +306,7 @@ HF_TOKEN=hf_your_token_here
288
  # Default: huggingclaw-backup
289
  BACKUP_DATASET_NAME=huggingclaw-backup
290
 
291
- # Git commit identity for workspace syncs
292
- WORKSPACE_GIT_USER=openclaw@example.com
293
- WORKSPACE_GIT_NAME=OpenClaw Bot
294
-
295
  # ── OPTIONAL: Background Services ──
296
- # Keep-alive ping interval (seconds). Default: 300. Set 0 to disable.
297
- KEEP_ALIVE_INTERVAL=300
298
-
299
  # Workspace auto-sync interval (seconds). Default: 180.
300
  SYNC_INTERVAL=180
301
 
@@ -305,6 +316,9 @@ OPENCLAW_CONFIG_WATCH_INTERVAL=1
305
  # Wait for openclaw.json to stay valid and unchanged before syncing. Default: 3.
306
  OPENCLAW_CONFIG_SETTLE_SECONDS=3
307
 
 
 
 
308
  # Webhooks: Standard POST notifications for lifecycle events
309
  # WEBHOOK_URL=https://your-webhook-endpoint.com/log
310
 
 
131
  # Keys are rotated round-robin on every request β€” useful when you
132
  # have multiple accounts or want to spread rate-limit quota.
133
  #
134
+ # Smart backoff: when a key gets a 429/402 response, it is temporarily
135
+ # suspended so other keys handle traffic.
136
+ # Strike 1 β†’ suspended for KEY_BLACKLIST_COOLDOWN_MS (default 60 s)
137
+ # Strike 2 β†’ suspended for KEY_BLACKLIST_COOLDOWN_MS Γ— 4 (default 4 min)
138
+ # Strike 3 β†’ suspended for 24 h (quota likely exhausted β€” skipped all day)
139
+ # A successful response resets the strike counter for that key.
140
+ #
141
  # Pattern: <PROVIDER>_API_KEYS=key1,key2,key3
142
  # Fallback order: plural pool β†’ singular key β†’ LLM_API_KEY (optional)
143
  # Set false only if you want to disable global LLM_API_KEY fallback
144
  # across providers.
145
  LLM_API_KEY_FALLBACK_ENABLED=true
146
  #
147
+ # Base backoff duration (ms) after the first 429 on a key (default: 60 s).
148
+ # Increases exponentially on repeated failures.
149
+ # KEY_BLACKLIST_COOLDOWN_MS=60000
150
+ #
151
+ # Number of consecutive 429/quota errors before a key is suspended for 24 h.
152
+ # KEY_MAX_STRIKES=3
153
+ #
154
+ # Note: KIMI_API_KEYS and MOONSHOT_API_KEYS share the same API endpoint
155
+ # (api.moonshot.cn) and are combined into one rotation pool automatically.
156
+ #
157
  # Uncomment and fill in only the providers you use:
158
  #
159
  # ANTHROPIC_API_KEYS=sk-ant-key1,sk-ant-key2,sk-ant-key3
 
164
  # KILOCODE_API_KEYS=key1,key2
165
  # OPENCODE_API_KEYS=key1,key2
166
  # ZAI_API_KEYS=key1,key2
167
+ # MOONSHOT_API_KEYS=key1,key2 # combines with KIMI_API_KEYS
168
+ # KIMI_API_KEYS=key1,key2 # combines with MOONSHOT_API_KEYS
169
  # MINIMAX_API_KEYS=key1,key2
170
  # XIAOMI_API_KEYS=key1,key2
171
  # VOLCANO_ENGINE_API_KEYS=key1,key2
 
266
  GATEWAY_TOKEN=your_gateway_token_here
267
 
268
  # [OPTIONAL] JupyterLab terminal token for /terminal/
269
+ # Set a strong token for private deployments. Must NOT be "huggingface".
270
+ JUPYTER_TOKEN=run: openssl rand -hex 32
271
 
272
  # (Optional) Password auth β€” simpler alternative to token for casual users
273
  # If set, users can log in with this password instead of the token
 
306
  # Default: huggingclaw-backup
307
  BACKUP_DATASET_NAME=huggingclaw-backup
308
 
 
 
 
 
309
  # ── OPTIONAL: Background Services ──
 
 
 
310
  # Workspace auto-sync interval (seconds). Default: 180.
311
  SYNC_INTERVAL=180
312
 
 
316
  # Wait for openclaw.json to stay valid and unchanged before syncing. Default: 3.
317
  OPENCLAW_CONFIG_SETTLE_SECONDS=3
318
 
319
+ # Minimum gap between sessions-triggered immediate syncs (seconds). Default: 30.
320
+ SESSIONS_MIN_SYNC_GAP=30
321
+
322
  # Webhooks: Standard POST notifications for lifecycle events
323
  # WEBHOOK_URL=https://your-webhook-endpoint.com/log
324
 
Dockerfile CHANGED
@@ -23,9 +23,12 @@ ARG DEV_MODE=false
23
  RUN apt-get update && apt-get install -y --no-install-recommends \
24
  git \
25
  sudo \
 
26
  ca-certificates \
27
  jq \
28
  curl \
 
 
29
  python3 \
30
  python3-pip \
31
  chromium \
@@ -107,6 +110,7 @@ RUN chmod +x /home/node/app/start.sh \
107
  /home/node/app/cloudflare-proxy-setup.py \
108
  /home/node/app/cloudflare-keepalive-setup.py \
109
  /home/node/app/openclaw-sync.py \
 
110
  /home/node/app/multi-provider-key-rotator.cjs
111
 
112
  USER node
 
23
  RUN apt-get update && apt-get install -y --no-install-recommends \
24
  git \
25
  sudo \
26
+ file \
27
  ca-certificates \
28
  jq \
29
  curl \
30
+ dbus \
31
+ dbus-x11 \
32
  python3 \
33
  python3-pip \
34
  chromium \
 
110
  /home/node/app/cloudflare-proxy-setup.py \
111
  /home/node/app/cloudflare-keepalive-setup.py \
112
  /home/node/app/openclaw-sync.py \
113
+ /home/node/app/jupyter-devdata-sync.py \
114
  /home/node/app/multi-provider-key-rotator.cjs
115
 
116
  USER node
README.md CHANGED
@@ -57,7 +57,6 @@ secrets:
57
  - [πŸ’» Local Development](#-local-development)
58
  - [πŸ”— CLI Access](#-cli-access)
59
  - [πŸ’» JupyterLab Terminal](#-jupyterlab-terminal)
60
- - [πŸ” Merge Comparison](#-merge-comparison)
61
  - [πŸ—οΈ Architecture](#-architecture)
62
  - [πŸ’“ Staying Alive](#-staying-alive)
63
  - [πŸ› Troubleshooting](#-troubleshooting)
@@ -178,6 +177,7 @@ HuggingClaw automatically syncs your workspace (chats, settings, sessions) to a
178
  | `SYNC_INTERVAL` | `180` | Full backup frequency in seconds |
179
  | `OPENCLAW_CONFIG_WATCH_INTERVAL` | `1` | How often to check `openclaw.json` for immediate settings sync |
180
  | `OPENCLAW_CONFIG_SETTLE_SECONDS` | `3` | How long `openclaw.json` must stay valid and unchanged before syncing |
 
181
 
182
  ## πŸ“¦ Ephemeral Package Re-install *(Optional)*
183
 
@@ -242,7 +242,7 @@ Configure password access and network restrictions:
242
 
243
  | Variable | Default | Description |
244
  | :--- | :--- | :--- |
245
- | `OPENCLAW_PASSWORD` | β€” | Enable simple password auth instead of token |
246
  | `TRUSTED_PROXIES` | β€” | Comma-separated IPs of HF proxies |
247
  | `ALLOWED_ORIGINS` | β€” | Comma-separated allowed origins for Control UI |
248
  | `CLOUDFLARE_KEEPALIVE_ENABLED` | `true` | Set to `false` to disable the automatic Cloudflare KeepAlive worker |
@@ -371,20 +371,11 @@ The merged Space includes the Hugging Face JupyterLab template behavior inside t
371
  | `/app/` | OpenClaw Control UI | `7860` | Mounted behind the local reverse proxy |
372
  | `/terminal/` | JupyterLab terminal | `8888` | Auto-enabled when `GATEWAY_TOKEN` is set; uses `GATEWAY_TOKEN` as auth token unless `JUPYTER_TOKEN` is set separately. Set `DEV_MODE=false` to disable. |
373
 
374
- When enabled, the terminal notebook root is `/home/node`, so you can inspect HuggingClaw files, logs, workspace state, and runtime scripts from the browser.
375
 
376
  > [!IMPORTANT]
377
  > No extra secret needed β€” `GATEWAY_TOKEN` is automatically reused as `JUPYTER_TOKEN`. Set a separate `JUPYTER_TOKEN` secret only if you want a different terminal credential.
378
 
379
- ## πŸ” Merge Comparison
380
-
381
- This repository is a merge of two sources:
382
-
383
- - `anurag162008/HuggingClaw`: OpenClaw gateway, dashboard, Cloudflare proxy/keep-alive, Telegram/WhatsApp helpers, backup sync, key rotation, docs, and security metadata.
384
- - Hugging Face `SpacesExamples/jupyterlab` template: JupyterLab Docker behavior, token login UX, Hugging Face-branded login template, pinned Jupyter packages, and Git LFS defaults for large model/data artifacts.
385
-
386
- The main merge-specific change is the single-port router: HF Spaces exposes `7861`, while the router keeps OpenClaw at `/app/` and JupyterLab at `/terminal/` without leaking internal redirects such as `http://127.0.0.1:8888/...`.
387
-
388
  ## πŸ—οΈ Architecture
389
 
390
  HuggingClaw uses a multi-layered approach to ensure stability and persistence on Hugging Face's ephemeral infrastructure.
 
57
  - [πŸ’» Local Development](#-local-development)
58
  - [πŸ”— CLI Access](#-cli-access)
59
  - [πŸ’» JupyterLab Terminal](#-jupyterlab-terminal)
 
60
  - [πŸ—οΈ Architecture](#-architecture)
61
  - [πŸ’“ Staying Alive](#-staying-alive)
62
  - [πŸ› Troubleshooting](#-troubleshooting)
 
177
  | `SYNC_INTERVAL` | `180` | Full backup frequency in seconds |
178
  | `OPENCLAW_CONFIG_WATCH_INTERVAL` | `1` | How often to check `openclaw.json` for immediate settings sync |
179
  | `OPENCLAW_CONFIG_SETTLE_SECONDS` | `3` | How long `openclaw.json` must stay valid and unchanged before syncing |
180
+ | `SESSIONS_MIN_SYNC_GAP` | `30` | Minimum seconds between session-triggered immediate syncs |
181
 
182
  ## πŸ“¦ Ephemeral Package Re-install *(Optional)*
183
 
 
242
 
243
  | Variable | Default | Description |
244
  | :--- | :--- | :--- |
245
+ | `OPENCLAW_PASSWORD` | β€” | Enable simple password auth instead of token (applies only when `GATEWAY_TOKEN` is empty) |
246
  | `TRUSTED_PROXIES` | β€” | Comma-separated IPs of HF proxies |
247
  | `ALLOWED_ORIGINS` | β€” | Comma-separated allowed origins for Control UI |
248
  | `CLOUDFLARE_KEEPALIVE_ENABLED` | `true` | Set to `false` to disable the automatic Cloudflare KeepAlive worker |
 
371
  | `/app/` | OpenClaw Control UI | `7860` | Mounted behind the local reverse proxy |
372
  | `/terminal/` | JupyterLab terminal | `8888` | Auto-enabled when `GATEWAY_TOKEN` is set; uses `GATEWAY_TOKEN` as auth token unless `JUPYTER_TOKEN` is set separately. Set `DEV_MODE=false` to disable. |
373
 
374
+ When enabled, the terminal notebook root defaults to `/home/node` (stable + writable by default). To browse a broader tree, set `JUPYTER_ROOT_DIR=/home`. Handy shortcuts are also created: `HuggingClaw`, `HuggingClaw-Workspace`, and `OpenClaw-Home`.
375
 
376
  > [!IMPORTANT]
377
  > No extra secret needed β€” `GATEWAY_TOKEN` is automatically reused as `JUPYTER_TOKEN`. Set a separate `JUPYTER_TOKEN` secret only if you want a different terminal credential.
378
 
 
 
 
 
 
 
 
 
 
379
  ## πŸ—οΈ Architecture
380
 
381
  HuggingClaw uses a multi-layered approach to ensure stability and persistence on Hugging Face's ephemeral infrastructure.
cloudflare-proxy-setup.py CHANGED
@@ -12,7 +12,8 @@ from pathlib import Path
12
  API_BASE = "https://api.cloudflare.com/client/v4"
13
  ENV_FILE = Path("/tmp/huggingclaw-cloudflare-proxy.env")
14
  DEFAULT_ALLOWED = [
15
- # Messaging
 
16
  "api.telegram.org",
17
  "discord.com",
18
  "discordapp.com",
@@ -32,8 +33,6 @@ DEFAULT_ALLOWED = [
32
  # Video
33
  "youtube.com",
34
  "www.youtube.com",
35
- # AI APIs
36
- "api.openai.com",
37
  # Email HTTP APIs (SMTP ports are blocked; use these instead)
38
  "api.resend.com",
39
  "api.sendgrid.com",
@@ -43,6 +42,11 @@ DEFAULT_ALLOWED = [
43
  "google.com",
44
  "googleusercontent.com",
45
  "gstatic.com",
 
 
 
 
 
46
  ]
47
 
48
 
 
12
  API_BASE = "https://api.cloudflare.com/client/v4"
13
  ENV_FILE = Path("/tmp/huggingclaw-cloudflare-proxy.env")
14
  DEFAULT_ALLOWED = [
15
+ # Messaging & social platforms β€” primary use-case for the Cloudflare proxy
16
+ # on HF Spaces (geo-restrictions on Telegram, Discord, WhatsApp, etc.).
17
  "api.telegram.org",
18
  "discord.com",
19
  "discordapp.com",
 
33
  # Video
34
  "youtube.com",
35
  "www.youtube.com",
 
 
36
  # Email HTTP APIs (SMTP ports are blocked; use these instead)
37
  "api.resend.com",
38
  "api.sendgrid.com",
 
42
  "google.com",
43
  "googleusercontent.com",
44
  "gstatic.com",
45
+ # NOTE: AI-provider domains (api.openai.com, api.anthropic.com, etc.) are
46
+ # intentionally NOT included here. Proxying AI calls routes API keys through
47
+ # the Cloudflare Worker without an explicit opt-in. Users who need AI API
48
+ # calls proxied (e.g. geo-restricted regions) can add specific domains via
49
+ # the CLOUDFLARE_PROXY_DOMAINS environment variable.
50
  ]
51
 
52
 
cloudflare-proxy.js CHANGED
@@ -24,6 +24,8 @@ if (
24
  const DEBUG = process.env.CLOUDFLARE_PROXY_DEBUG === "true";
25
  const PROXY_SHARED_SECRET = (process.env.CLOUDFLARE_PROXY_SECRET || "").trim();
26
  const DEFAULT_PROXY_DOMAINS = [
 
 
27
  "api.telegram.org", "discord.com", "discordapp.com",
28
  "gateway.discord.gg", "status.discord.com", "web.whatsapp.com",
29
  "graph.facebook.com", "graph.instagram.com",
@@ -31,10 +33,15 @@ const DEFAULT_PROXY_DOMAINS = [
31
  "api.linkedin.com", "www.linkedin.com",
32
  "open.tiktokapis.com", "oauth.reddit.com",
33
  "youtube.com", "www.youtube.com",
34
- "api.openai.com",
35
- "integrate.api.nvidia.com", "api.nvidia.com",
36
  "api.resend.com", "api.sendgrid.com", "api.mailgun.net",
 
37
  "googleapis.com", "google.com", "googleusercontent.com", "gstatic.com",
 
 
 
 
 
38
  ];
39
  const PROXY_DOMAINS_RAW = (process.env.CLOUDFLARE_PROXY_DOMAINS || "").trim();
40
  const PROXY_ALL = PROXY_DOMAINS_RAW === "*";
 
24
  const DEBUG = process.env.CLOUDFLARE_PROXY_DEBUG === "true";
25
  const PROXY_SHARED_SECRET = (process.env.CLOUDFLARE_PROXY_SECRET || "").trim();
26
  const DEFAULT_PROXY_DOMAINS = [
27
+ // Messaging & social platforms β€” these are the primary use-case for the
28
+ // Cloudflare proxy on HF Spaces (geo-restrictions on Telegram, Discord, WA).
29
  "api.telegram.org", "discord.com", "discordapp.com",
30
  "gateway.discord.gg", "status.discord.com", "web.whatsapp.com",
31
  "graph.facebook.com", "graph.instagram.com",
 
33
  "api.linkedin.com", "www.linkedin.com",
34
  "open.tiktokapis.com", "oauth.reddit.com",
35
  "youtube.com", "www.youtube.com",
36
+ // Email delivery
 
37
  "api.resend.com", "api.sendgrid.com", "api.mailgun.net",
38
+ // Google services
39
  "googleapis.com", "google.com", "googleusercontent.com", "gstatic.com",
40
+ // NOTE: AI-provider domains (api.openai.com, api.anthropic.com, etc.) are
41
+ // intentionally NOT included here. Proxying AI calls routes your API keys
42
+ // through the Cloudflare Worker without an explicit opt-in. Users who need
43
+ // AI API calls proxied (e.g. geo-restricted regions) can add specific
44
+ // domains via the CLOUDFLARE_PROXY_DOMAINS environment variable.
45
  ];
46
  const PROXY_DOMAINS_RAW = (process.env.CLOUDFLARE_PROXY_DOMAINS || "").trim();
47
  const PROXY_ALL = PROXY_DOMAINS_RAW === "*";
env-builder.html CHANGED
@@ -37,16 +37,16 @@
37
  --panel-w: 340px;
38
  }
39
 
40
- html { scroll-behavior: smooth; }
41
 
42
  body {
43
  font-family: var(--sans);
44
  background: var(--bg);
45
  color: var(--text);
46
- min-height: 100vh;
 
47
  display: flex;
48
  flex-direction: column;
49
- overflow-x: hidden;
50
  }
51
 
52
  /* ── Topbar ── */
@@ -130,6 +130,7 @@ body {
130
  background: var(--bg2);
131
  display: flex;
132
  flex-direction: column;
 
133
  overflow: hidden;
134
  }
135
 
@@ -330,6 +331,15 @@ body {
330
  letter-spacing: 1.2px;
331
  color: var(--text3);
332
  }
 
 
 
 
 
 
 
 
 
333
 
334
  .sec-line {
335
  flex: 1;
@@ -339,8 +349,8 @@ body {
339
 
340
  .cards {
341
  display: grid;
342
- grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
343
- gap: 10px;
344
  }
345
 
346
  /* ── ENV Card ── */
@@ -360,6 +370,22 @@ body {
360
  background: linear-gradient(135deg, var(--bg2) 80%, rgba(245,166,35,.04));
361
  }
362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
  .card-top {
364
  display: flex;
365
  align-items: flex-start;
@@ -407,16 +433,46 @@ body {
407
  border-radius: 20px;
408
  }
409
 
410
- .badge-s {
411
- background: rgba(240,95,95,.12);
412
- color: var(--red);
413
- border: 1px solid rgba(240,95,95,.25);
 
414
  }
415
 
416
- .badge-f {
417
- background: rgba(61,214,140,.1);
418
- color: var(--green);
419
- border: 1px solid rgba(61,214,140,.2);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  }
421
 
422
  /* ── Card inputs ── */
@@ -522,6 +578,7 @@ body {
522
  .panel-scroll {
523
  flex: 1;
524
  overflow-y: auto;
 
525
  padding: 16px;
526
  display: flex;
527
  flex-direction: column;
@@ -679,6 +736,10 @@ body {
679
  ::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 4px; }
680
 
681
  /* ── Responsive ── */
 
 
 
 
682
  @media (max-width: 900px) {
683
  :root { --panel-w: 280px; --sidebar-w: 180px; }
684
  }
@@ -692,6 +753,57 @@ body {
692
  .sidebar-wrap { display: none; }
693
  .topbar-divider, .topbar-title { display: none; }
694
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
695
  </style>
696
  </head>
697
 
@@ -729,6 +841,7 @@ body {
729
 
730
  <!-- toolbar -->
731
  <div class="toolbar">
 
732
  <div class="search-wrap">
733
  <span class="search-icon">βŒ•</span>
734
  <input id="search" type="text" placeholder="Search variables…" autocomplete="off" spellcheck="false">
@@ -736,6 +849,7 @@ body {
736
 
737
  <div class="tb-sep"></div>
738
 
 
739
  <button id="selectCommon" class="btn">β˜… Common</button>
740
  <button id="selectVisible" class="btn">β˜‘ Visible</button>
741
  <button id="clearAll" class="btn btn-ghost">βœ• Clear</button>
@@ -746,6 +860,29 @@ body {
746
 
747
  <!-- sections -->
748
  <div class="sections-scroll">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
749
  <div id="sections"></div>
750
 
751
  <!-- Custom Env section -->
@@ -764,7 +901,6 @@ body {
764
  <aside class="right-panel">
765
  <div class="panel-scroll">
766
 
767
- <!-- Summary -->
768
  <div class="pblock">
769
  <div class="pblock-head">
770
  <span class="pblock-title">πŸ“Š Summary</span>
@@ -780,7 +916,8 @@ body {
780
  <span class="pblock-title">πŸ“¦ Bundle Output</span>
781
  </div>
782
  <div class="pblock-body">
783
- <textarea id="bundleOut" placeholder="Your encoded bundle will appear here…" readonly spellcheck="false"></textarea>
 
784
  <input type="text" id="envLineOut" placeholder="HUGGINGCLAW_ENV_BUNDLE=…" readonly spellcheck="false">
785
  <div class="row-btns">
786
  <button id="copyBundle" class="btn btn-amber">⎘ Bundle</button>
 
37
  --panel-w: 340px;
38
  }
39
 
40
+ html { scroll-behavior: smooth; height: 100%; }
41
 
42
  body {
43
  font-family: var(--sans);
44
  background: var(--bg);
45
  color: var(--text);
46
+ height: 100vh;
47
+ overflow: hidden;
48
  display: flex;
49
  flex-direction: column;
 
50
  }
51
 
52
  /* ── Topbar ── */
 
130
  background: var(--bg2);
131
  display: flex;
132
  flex-direction: column;
133
+ min-height: 0;
134
  overflow: hidden;
135
  }
136
 
 
331
  letter-spacing: 1.2px;
332
  color: var(--text3);
333
  }
334
+ .sec-count {
335
+ font-family: var(--mono);
336
+ font-size: 10px;
337
+ color: var(--text3);
338
+ background: var(--bg3);
339
+ border: 1px solid var(--border);
340
+ border-radius: 10px;
341
+ padding: 1px 7px;
342
+ }
343
 
344
  .sec-line {
345
  flex: 1;
 
349
 
350
  .cards {
351
  display: grid;
352
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
353
+ gap: 9px;
354
  }
355
 
356
  /* ── ENV Card ── */
 
370
  background: linear-gradient(135deg, var(--bg2) 80%, rgba(245,166,35,.04));
371
  }
372
 
373
+ /* Critical cards get a red left-border accent */
374
+ .env-card:has(.badge-critical) {
375
+ border-left: 3px solid rgba(240,80,80,.4);
376
+ }
377
+ .env-card:has(.badge-critical):hover {
378
+ border-left-color: rgba(240,80,80,.7);
379
+ }
380
+ .env-card:has(.badge-critical).selected {
381
+ border-left-color: #f05f5f;
382
+ }
383
+
384
+ /* Credential cards get an amber left-border accent */
385
+ .env-card:has(.badge-credential) {
386
+ border-left: 3px solid rgba(220,140,60,.3);
387
+ }
388
+
389
  .card-top {
390
  display: flex;
391
  align-items: flex-start;
 
433
  border-radius: 20px;
434
  }
435
 
436
+ /* critical β€” space breaks without this */
437
+ .badge-critical {
438
+ background: rgba(240,80,80,.14);
439
+ color: #f05f5f;
440
+ border: 1px solid rgba(240,80,80,.3);
441
  }
442
 
443
+ /* credential β€” sensitive key / token */
444
+ .badge-credential {
445
+ background: rgba(220,140,60,.13);
446
+ color: #e09040;
447
+ border: 1px solid rgba(220,140,60,.28);
448
+ }
449
+
450
+ /* feature β€” enables an optional feature */
451
+ .badge-feature {
452
+ background: rgba(70,140,250,.12);
453
+ color: #5a9eff;
454
+ border: 1px solid rgba(70,140,250,.25);
455
+ }
456
+
457
+ /* optional β€” safe to change freely */
458
+ .badge-optional {
459
+ background: rgba(61,214,140,.10);
460
+ color: #3dd68c;
461
+ border: 1px solid rgba(61,214,140,.22);
462
+ }
463
+
464
+ /* advanced β€” power-user, risky if wrong */
465
+ .badge-advanced {
466
+ background: rgba(160,100,230,.12);
467
+ color: #b07ae0;
468
+ border: 1px solid rgba(160,100,230,.25);
469
+ }
470
+
471
+ /* build-time β€” needs HF Space rebuild */
472
+ .badge-build {
473
+ background: rgba(240,185,60,.12);
474
+ color: #e0b030;
475
+ border: 1px solid rgba(240,185,60,.28);
476
  }
477
 
478
  /* ── Card inputs ── */
 
578
  .panel-scroll {
579
  flex: 1;
580
  overflow-y: auto;
581
+ min-height: 0;
582
  padding: 16px;
583
  display: flex;
584
  flex-direction: column;
 
736
  ::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 4px; }
737
 
738
  /* ── Responsive ── */
739
+
740
+ @media (max-width: 1100px) {
741
+ .toolbar-hint { display: none; }
742
+ }
743
  @media (max-width: 900px) {
744
  :root { --panel-w: 280px; --sidebar-w: 180px; }
745
  }
 
753
  .sidebar-wrap { display: none; }
754
  .topbar-divider, .topbar-title { display: none; }
755
  }
756
+
757
+ /* ── Tag Legend (collapsible) ── */
758
+ .tag-legend {
759
+ margin-bottom: 14px;
760
+ background: var(--bg2);
761
+ border: 1px solid var(--border);
762
+ border-radius: var(--r);
763
+ overflow: hidden;
764
+ }
765
+ .legend-summary {
766
+ display: flex;
767
+ align-items: center;
768
+ gap: 10px;
769
+ padding: 7px 12px;
770
+ cursor: pointer;
771
+ list-style: none;
772
+ user-select: none;
773
+ outline: none;
774
+ }
775
+ .legend-summary::-webkit-details-marker { display: none; }
776
+ .legend-chips { display: flex; gap: 5px; flex-wrap: wrap; flex: 1; }
777
+ .legend-hint {
778
+ font-size: 10px;
779
+ color: var(--text3);
780
+ white-space: nowrap;
781
+ flex-shrink: 0;
782
+ }
783
+ .tag-legend[open] .legend-hint { opacity: 0; }
784
+ .toolbar-hint { color: var(--muted); font-size: 12px; margin-right: 10px; white-space: nowrap; }
785
+ .legend-body {
786
+ padding: 8px 12px 10px;
787
+ border-top: 1px solid var(--border);
788
+ display: flex;
789
+ flex-direction: column;
790
+ gap: 6px;
791
+ }
792
+ .legend-row {
793
+ display: flex;
794
+ align-items: center;
795
+ gap: 10px;
796
+ font-size: 11px;
797
+ color: var(--text2);
798
+ }
799
+ .legend-row .badge { flex-shrink: 0; width: 74px; text-align: center; }
800
+ .legend-tip {
801
+ font-size: 9.5px;
802
+ color: var(--text3);
803
+ margin-top: 4px;
804
+ padding-top: 6px;
805
+ border-top: 1px solid var(--border);
806
+ }
807
  </style>
808
  </head>
809
 
 
841
 
842
  <!-- toolbar -->
843
  <div class="toolbar">
844
+ <div class="toolbar-hint">Tip: Start with <strong>⚑ Required</strong>, then fill keys and click <strong># Generate Bundle</strong>.</div>
845
  <div class="search-wrap">
846
  <span class="search-icon">βŒ•</span>
847
  <input id="search" type="text" placeholder="Search variables…" autocomplete="off" spellcheck="false">
 
849
 
850
  <div class="tb-sep"></div>
851
 
852
+ <button id="selectRequired" class="btn" title="Select all critical variables first">⚑ Required</button>
853
  <button id="selectCommon" class="btn">β˜… Common</button>
854
  <button id="selectVisible" class="btn">β˜‘ Visible</button>
855
  <button id="clearAll" class="btn btn-ghost">βœ• Clear</button>
 
860
 
861
  <!-- sections -->
862
  <div class="sections-scroll">
863
+ <!-- Tag Legend (compact collapsible) -->
864
+ <details class="tag-legend" id="tagLegend">
865
+ <summary class="legend-summary">
866
+ <span class="legend-chips">
867
+ <span class="badge badge-critical">critical</span>
868
+ <span class="badge badge-credential">credential</span>
869
+ <span class="badge badge-feature">feature</span>
870
+ <span class="badge badge-optional">optional</span>
871
+ <span class="badge badge-advanced">advanced</span>
872
+ <span class="badge badge-build">build-time</span>
873
+ </span>
874
+ <span class="legend-hint">what do these mean?</span>
875
+ </summary>
876
+ <div class="legend-body">
877
+ <div class="legend-row"><span class="badge badge-critical">critical</span><span>Space won't work without this</span></div>
878
+ <div class="legend-row"><span class="badge badge-credential">credential</span><span>Sensitive key or token β€” never share</span></div>
879
+ <div class="legend-row"><span class="badge badge-feature">feature</span><span>Enables a specific optional feature</span></div>
880
+ <div class="legend-row"><span class="badge badge-optional">optional</span><span>Safe to change β€” nothing breaks</span></div>
881
+ <div class="legend-row"><span class="badge badge-advanced">advanced</span><span>Power-user setting β€” wrong value causes issues</span></div>
882
+ <div class="legend-row"><span class="badge badge-build">build-time</span><span>Needs HF Space rebuild to fully take effect</span></div>
883
+ <div class="legend-tip">πŸ’‘ Type a tag name in search to filter by it</div>
884
+ </div>
885
+ </details>
886
  <div id="sections"></div>
887
 
888
  <!-- Custom Env section -->
 
901
  <aside class="right-panel">
902
  <div class="panel-scroll">
903
 
 
904
  <div class="pblock">
905
  <div class="pblock-head">
906
  <span class="pblock-title">πŸ“Š Summary</span>
 
916
  <span class="pblock-title">πŸ“¦ Bundle Output</span>
917
  </div>
918
  <div class="pblock-body">
919
+ <button id="generateBundle" class="btn btn-amber" style="width:100%;font-size:12.5px;"># Generate Bundle</button>
920
+ <textarea id="bundleOut" placeholder="Click # Generate to build your bundle…" readonly spellcheck="false"></textarea>
921
  <input type="text" id="envLineOut" placeholder="HUGGINGCLAW_ENV_BUNDLE=…" readonly spellcheck="false">
922
  <div class="row-btns">
923
  <button id="copyBundle" class="btn btn-amber">⎘ Bundle</button>
env-builder.js CHANGED
@@ -54,25 +54,25 @@ const MODEL_CATALOGS = {
54
  "Groq": [
55
  "groq/compound",
56
  "groq/compound-mini",
57
- "llama-3.1-8b-instant",
58
- "llama-3.1-70b-versatile",
59
- "llama-3.3-70b-versatile",
60
  "meta-llama/llama-4-scout-17b-16e-instruct",
61
  "openai/gpt-oss-20b",
62
  "openai/gpt-oss-120b",
63
  "qwen/qwen3-32b",
64
- "mixtral-8x7b-32768"
65
  ],
66
  "Mistral": [
67
- "mistral-large-latest",
68
- "mistral-large-2",
69
- "mistral-medium-3.5",
70
- "mistral-small-latest",
71
- "mistral-small-3.2",
72
- "devstral-2",
73
- "ocr-3-premier",
74
- "voxtral-mini-transcribe-realtime",
75
- "codestral-latest"
76
  ],
77
  "Cohere": [
78
  "command-a",
@@ -280,25 +280,25 @@ const MODEL_CATALOGS = {
280
  "GROQ_MODELS": [
281
  "groq/compound",
282
  "groq/compound-mini",
283
- "llama-3.1-8b-instant",
284
- "llama-3.1-70b-versatile",
285
- "llama-3.3-70b-versatile",
286
  "openai/gpt-oss-20b",
287
  "openai/gpt-oss-120b",
288
  "meta-llama/llama-4-scout-17b-16e-instruct",
289
  "qwen/qwen3-32b",
290
- "mixtral-8x7b-32768"
291
  ],
292
  "MISTRAL_MODELS": [
293
- "mistral-large-latest",
294
- "mistral-large-2",
295
- "mistral-medium-3.5",
296
- "mistral-small-latest",
297
- "mistral-small-3.2",
298
- "devstral-2",
299
- "ocr-3-premier",
300
- "voxtral-mini-transcribe-realtime",
301
- "codestral-latest"
302
  ],
303
  "XAI_MODELS": [
304
  "grok-4.3",
@@ -416,200 +416,247 @@ const MODEL_CATALOGS = {
416
  };
417
 
418
  const FIELDS = [
419
- {
420
  "g": "Core",
421
  "icon": "⚑",
422
  "k": "LLM_MODEL",
423
  "lbl": "Default model ID",
424
- "type": "model",
425
- "options_key": "LLM_MODEL",
426
  "ph": "choose a provider model",
427
- "common": 1
 
428
  },
429
- {
430
  "g": "Core",
431
  "icon": "⚑",
432
  "k": "LLM_API_KEY",
433
  "lbl": "Primary provider API key",
434
  "type": "password",
435
- "secret": 1,
436
  "ph": "sk-...",
437
- "common": 1
 
438
  },
439
- {
440
  "g": "Core",
441
  "icon": "⚑",
442
  "k": "GATEWAY_TOKEN",
443
  "lbl": "Control UI gateway token",
444
  "type": "password",
445
- "secret": 1,
446
- "common": 1
447
  },
448
- {
449
  "g": "Core",
450
  "icon": "⚑",
451
  "k": "OPENCLAW_PASSWORD",
452
  "lbl": "Optional password auth",
453
  "type": "password",
454
- "secret": 1
455
  },
456
- {
457
  "g": "Core",
458
  "icon": "⚑",
459
  "k": "OPENCLAW_VERSION",
460
- "lbl": "Pin OpenClaw version",
461
  "type": "text",
462
- "ph": "latest"
 
463
  },
464
- {
465
- "g": "Core",
466
  "icon": "⚑",
467
  "k": "LLM_API_KEY_FALLBACK_ENABLED",
468
  "lbl": "Allow global LLM_API_KEY fallback",
469
  "type": "toggle",
470
- "ph": "true"
 
471
  },
472
- {
473
- "g": "Core",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474
  "icon": "⚑",
475
  "k": "DEV_MODE",
476
  "lbl": "Enable dev mode",
477
  "type": "toggle",
478
  "ph": "false",
479
- "common": 1
 
 
 
 
 
 
 
 
 
 
480
  },
481
- {
482
- "g": "Core",
483
  "icon": "⚑",
484
  "k": "HUGGINGCLAW_JUPYTER_ENABLED",
485
  "lbl": "Enable Jupyter terminal",
486
  "type": "toggle",
487
  "ph": "false",
488
- "common": 1
 
489
  },
490
- {
491
- "g": "Core",
492
  "icon": "⚑",
493
  "k": "DEVDATA",
494
  "lbl": "DevData switch",
495
  "type": "toggle",
496
  "ph": "on",
497
- "common": 1
 
498
  },
499
- {
500
- "g": "Core",
501
  "icon": "⚑",
502
  "k": "DEVDATA_DATASET_NAME",
503
  "lbl": "DevData dataset name",
504
  "type": "text",
505
  "ph": "huggingclaw-devdata",
506
- "common": 1
 
507
  },
508
- {
509
- "g": "Core",
510
  "icon": "⚑",
511
  "k": "DEVDATA_SYNC_INTERVAL",
512
  "lbl": "DevData sync interval (seconds)",
513
  "type": "number",
514
- "ph": "180"
 
515
  },
516
- {
517
- "g": "Core",
518
  "icon": "⚑",
519
  "k": "WHATSAPP_ENABLED",
520
  "lbl": "Enable WhatsApp pairing",
521
  "type": "toggle",
522
  "ph": "false",
523
- "common": 1
 
524
  },
525
- {
526
- "g": "Core",
527
  "icon": "⚑",
528
  "k": "HUGGINGCLAW_CAPTURE_DISABLE",
529
  "lbl": "Disable capture wrapper",
530
  "type": "toggle",
531
- "ph": "false"
 
532
  },
533
- {
534
- "g": "Core",
535
  "icon": "⚑",
536
  "k": "HUGGINGCLAW_STARTUP_STRICT",
537
  "lbl": "Stop on startup failure",
538
  "type": "toggle",
539
- "ph": "false"
 
540
  },
541
- {
542
- "g": "Core",
543
  "icon": "⚑",
544
  "k": "HUGGINGCLAW_RUN",
545
  "lbl": "Startup command (one-liner)",
546
- "type": "textarea"
 
547
  },
548
- {
549
- "g": "Core",
550
  "icon": "⚑",
551
  "k": "HUGGINGCLAW_STARTUP_COMMANDS",
552
  "lbl": "Multiline startup commands",
553
- "type": "textarea"
 
554
  },
555
- {
556
- "g": "Core",
557
  "icon": "⚑",
558
  "k": "HUGGINGCLAW_STARTUP_SCRIPT",
559
  "lbl": "Startup shell script",
560
- "type": "textarea"
 
561
  },
562
- {
563
- "g": "Core",
564
  "icon": "⚑",
565
  "k": "HUGGINGCLAW_STARTUP_SCRIPT_B64",
566
  "lbl": "Startup script (base64)",
567
- "type": "textarea"
 
568
  },
569
- {
570
- "g": "Core",
571
  "icon": "⚑",
572
  "k": "HUGGINGCLAW_APT_PACKAGES",
573
  "lbl": "APT packages to install",
574
- "type": "textarea"
 
575
  },
576
- {
577
- "g": "Core",
578
  "icon": "⚑",
579
  "k": "HUGGINGCLAW_PIP_PACKAGES",
580
  "lbl": "Pip packages to install",
581
- "type": "textarea"
 
582
  },
583
- {
584
- "g": "Core",
585
  "icon": "⚑",
586
  "k": "HUGGINGCLAW_NPM_PACKAGES",
587
  "lbl": "NPM packages to install",
588
- "type": "textarea"
 
589
  },
590
- {
591
- "g": "Core",
592
  "icon": "⚑",
593
  "k": "HUGGINGCLAW_OPENCLAW_PLUGINS",
594
  "lbl": "OpenClaw plugins to load",
595
- "type": "textarea"
 
596
  },
597
- {
598
- "g": "Core",
599
  "icon": "⚑",
600
  "k": "ALLOWED_ORIGINS",
601
  "lbl": "Allowed CORS origins",
602
- "type": "textarea"
 
603
  },
604
- {
605
- "g": "Core",
606
  "icon": "⚑",
607
  "k": "TRUSTED_PROXIES",
608
  "lbl": "Trusted proxy CIDRs",
609
- "type": "textarea"
 
610
  },
611
- {
612
- "g": "Core",
613
  "icon": "⚑",
614
  "k": "WEBHOOK_URL",
615
  "lbl": "Webhook URL",
@@ -622,34 +669,38 @@ const FIELDS = [
622
  "k": "GATEWAY_MAX_RESTARTS",
623
  "lbl": "Gateway max restarts",
624
  "type": "number",
625
- "ph": "10"
 
626
  },
627
- {
628
- "g": "Core",
629
  "icon": "⚑",
630
  "k": "GATEWAY_READY_TIMEOUT",
631
  "lbl": "Gateway ready timeout",
632
  "type": "number",
633
- "ph": "90"
 
634
  },
635
- {
636
- "g": "Core",
637
  "icon": "⚑",
638
  "k": "GATEWAY_RESTART_DELAY",
639
  "lbl": "Gateway restart delay",
640
  "type": "number",
641
- "ph": "5"
 
642
  },
643
- {
644
- "g": "Core",
645
  "icon": "⚑",
646
  "k": "GATEWAY_VERBOSE",
647
  "lbl": "Verbose gateway logs",
648
  "type": "toggle",
649
- "ph": "false"
 
650
  },
651
- {
652
- "g": "Core",
653
  "icon": "⚑",
654
  "k": "OPENCLAW_CONSOLE_LOG_LEVEL",
655
  "lbl": "Console log level",
@@ -660,10 +711,11 @@ const FIELDS = [
660
  "warn",
661
  "error"
662
  ],
663
- "ph": "info"
 
664
  },
665
- {
666
- "g": "Core",
667
  "icon": "⚑",
668
  "k": "OPENCLAW_FILE_LOG_LEVEL",
669
  "lbl": "File log level",
@@ -674,10 +726,11 @@ const FIELDS = [
674
  "warn",
675
  "error"
676
  ],
677
- "ph": "info"
 
678
  },
679
- {
680
- "g": "Core",
681
  "icon": "⚑",
682
  "k": "OPENCLAW_CONSOLE_LOG_STYLE",
683
  "lbl": "Console log style",
@@ -687,10 +740,11 @@ const FIELDS = [
687
  "json",
688
  "compact"
689
  ],
690
- "ph": "pretty"
 
691
  },
692
- {
693
- "g": "Core",
694
  "icon": "⚑",
695
  "k": "BROWSER_PLUGIN_MODE",
696
  "lbl": "Browser plugin mode",
@@ -700,10 +754,11 @@ const FIELDS = [
700
  "enabled",
701
  "disabled"
702
  ],
703
- "ph": "auto"
 
704
  },
705
- {
706
- "g": "Core",
707
  "icon": "⚑",
708
  "k": "ACP_PLUGIN_MODE",
709
  "lbl": "ACP plugin mode",
@@ -713,98 +768,106 @@ const FIELDS = [
713
  "enabled",
714
  "disabled"
715
  ],
716
- "ph": "auto"
 
717
  },
718
- {
719
- "g": "Core",
720
  "icon": "⚑",
721
  "k": "CLOUDFLARE_PROXY_DEBUG",
722
  "lbl": "Cloudflare proxy debug",
723
  "type": "toggle",
724
- "ph": "false"
 
725
  },
726
- {
727
- "g": "Core",
728
  "icon": "⚑",
729
  "k": "CLOUDFLARE_KEEPALIVE_ENABLED",
730
  "lbl": "Enable keep-awake worker",
731
  "type": "toggle",
732
- "ph": "true"
 
733
  },
734
- {
735
- "g": "Core",
736
  "icon": "⚑",
737
  "k": "CLOUDFLARE_PROXY_URL",
738
  "lbl": "Proxy worker URL",
739
  "type": "text",
740
  "ph": "https://your-proxy.workers.dev",
741
- "common": 1
 
742
  },
743
- {
744
- "g": "Core",
745
  "icon": "⚑",
746
  "k": "CLOUDFLARE_PROXY_SECRET",
747
  "lbl": "Proxy shared secret",
748
  "type": "password",
749
- "secret": 1
750
  },
751
- {
752
- "g": "Core",
753
  "icon": "⚑",
754
  "k": "CLOUDFLARE_PROXY_DOMAINS",
755
  "lbl": "Extra domains to proxy",
756
  "type": "textarea",
757
- "ph": "api.sendgrid.com,slack.com"
 
758
  },
759
- {
760
- "g": "Core",
761
  "icon": "⚑",
762
  "k": "CLOUDFLARE_WORKERS_TOKEN",
763
  "lbl": "Workers API token",
764
  "type": "password",
765
- "secret": 1,
766
- "common": 1
767
  },
768
- {
769
  "g": "Core",
770
  "icon": "⚑",
771
  "k": "HF_USERNAME",
772
  "lbl": "Hugging Face username",
773
  "type": "text",
774
- "common": 1
 
775
  },
776
- {
777
  "g": "Core",
778
  "icon": "⚑",
779
  "k": "HF_TOKEN",
780
  "lbl": "HF write token",
781
  "type": "password",
782
- "secret": 1,
783
- "common": 1
784
  },
785
- {
786
  "g": "Core",
787
  "icon": "⚑",
788
  "k": "BACKUP_DATASET_NAME",
789
  "lbl": "Backup dataset name",
790
  "type": "text",
791
  "ph": "huggingclaw-backup",
792
- "common": 1
 
793
  },
794
- {
795
  "g": "Core",
796
  "icon": "⚑",
797
  "k": "SYNC_INTERVAL",
798
  "lbl": "Sync interval (seconds)",
799
  "type": "number",
800
  "ph": "180",
801
- "common": 1
 
802
  },
803
- {
804
  "g": "Core",
805
  "icon": "⚑",
806
  "k": "JUPYTER_TOKEN",
807
- "lbl": "Jupyter access token",
808
  "type": "password",
809
  "secret": 1,
810
  "ph": "huggingface",
@@ -816,95 +879,116 @@ const FIELDS = [
816
  "k": "OPENCLAW_DISABLE_BONJOUR",
817
  "lbl": "Disable Bonjour/mDNS discovery",
818
  "type": "toggle",
819
- "ph": "false"
 
820
  },
821
- {
822
  "g": "Core",
823
  "icon": "⚑",
824
  "k": "OPENCLAW_RUNTIME_VERSION",
825
  "lbl": "Pin runtime version",
826
  "type": "text",
827
- "ph": "latest"
 
828
  },
829
- {
830
  "g": "Core",
831
  "icon": "⚑",
832
  "k": "OPENCLAW_DISPLAY_VERSION",
833
  "lbl": "Display version label",
834
  "type": "text",
835
- "ph": ""
 
836
  },
837
- {
838
  "g": "Integrations",
839
  "icon": "πŸ”Œ",
840
  "k": "CLOUDFLARE_ACCOUNT_ID",
841
  "lbl": "Cloudflare account ID",
842
  "type": "text",
843
- "ph": "account-id"
 
844
  },
845
- {
846
  "g": "Integrations",
847
  "icon": "πŸ”Œ",
848
  "k": "CLOUDFLARE_WORKER_NAME",
849
  "lbl": "Outbound proxy worker name",
850
  "type": "text",
851
- "ph": "huggingclaw-proxy"
 
852
  },
853
- {
854
  "g": "Integrations",
855
  "icon": "πŸ”Œ",
856
  "k": "CLOUDFLARE_KEEPALIVE_URL",
857
  "lbl": "Keepalive worker URL",
858
  "type": "text",
859
- "ph": "https://your-worker.workers.dev"
 
860
  },
861
- {
862
  "g": "Integrations",
863
  "icon": "πŸ”Œ",
864
  "k": "CLOUDFLARE_KEEPALIVE_WORKER_NAME",
865
  "lbl": "Keepalive worker name",
866
  "type": "text",
867
- "ph": "huggingclaw-keepalive"
 
868
  },
869
- {
870
  "g": "Integrations",
871
  "icon": "πŸ”Œ",
872
  "k": "CLOUDFLARE_KEEPALIVE_CRON",
873
  "lbl": "Keepalive cron schedule",
874
  "type": "text",
875
- "ph": "*/5 * * * *"
 
876
  },
877
- {
878
  "g": "Integrations",
879
  "icon": "πŸ”Œ",
880
  "k": "TELEGRAM_API_ROOT",
881
  "lbl": "Telegram API root override",
882
  "type": "text",
883
- "ph": "https://api.telegram.org"
 
884
  },
885
- {
886
  "g": "Runtime",
887
  "icon": "βš™οΈ",
888
  "k": "OPENCLAW_CONFIG_WATCH_INTERVAL",
889
  "lbl": "Config watch interval (seconds)",
890
  "type": "number",
891
- "ph": "1"
 
892
  },
893
- {
894
  "g": "Runtime",
895
  "icon": "βš™οΈ",
896
  "k": "OPENCLAW_CONFIG_SETTLE_SECONDS",
897
  "lbl": "Config settle window (seconds)",
898
  "type": "number",
899
- "ph": "3"
 
900
  },
901
- {
 
 
 
 
 
 
 
 
 
902
  "g": "Runtime",
903
  "icon": "βš™οΈ",
904
  "k": "JUPYTER_ROOT_DIR",
905
  "lbl": "Jupyter root directory",
906
  "type": "text",
907
- "ph": "/home/node"
 
908
  },
909
  {
910
  "g": "Provider Keys",
@@ -912,663 +996,711 @@ const FIELDS = [
912
  "k": "ANTHROPIC_API_KEY",
913
  "lbl": "Anthropic (Claude)",
914
  "type": "password",
915
- "secret": 1,
916
- "common": 0
917
  },
918
- {
919
  "g": "Provider Keys",
920
  "icon": "πŸ”‘",
921
  "k": "OPENAI_API_KEY",
922
  "lbl": "OpenAI (GPT)",
923
  "type": "password",
924
- "secret": 1,
925
- "common": 0
926
  },
927
- {
928
  "g": "Provider Keys",
929
  "icon": "πŸ”‘",
930
  "k": "GEMINI_API_KEY",
931
  "lbl": "Google Gemini",
932
  "type": "password",
933
- "secret": 1,
934
- "common": 0
935
  },
936
- {
937
  "g": "Provider Keys",
938
  "icon": "πŸ”‘",
939
  "k": "DEEPSEEK_API_KEY",
940
  "lbl": "DeepSeek",
941
  "type": "password",
942
- "secret": 1,
943
- "common": 0
944
  },
945
- {
946
  "g": "Provider Keys",
947
  "icon": "πŸ”‘",
948
  "k": "OPENROUTER_API_KEY",
949
  "lbl": "OpenRouter",
950
  "type": "password",
951
- "secret": 1,
952
- "common": 1
953
  },
954
- {
955
  "g": "Provider Keys",
956
  "icon": "πŸ”‘",
957
  "k": "OPENCODE_API_KEY",
958
  "lbl": "OpenCode",
959
  "type": "password",
960
- "secret": 1,
961
- "common": 0
962
  },
963
- {
964
  "g": "Provider Keys",
965
  "icon": "πŸ”‘",
966
  "k": "KILOCODE_API_KEY",
967
  "lbl": "KiloCode",
968
  "type": "password",
969
- "secret": 1,
970
- "common": 0
971
  },
972
- {
973
  "g": "Provider Keys",
974
  "icon": "πŸ”‘",
975
  "k": "ZAI_API_KEY",
976
  "lbl": "Z.ai / GLM",
977
  "type": "password",
978
- "secret": 1,
979
- "common": 0
980
  },
981
- {
982
  "g": "Provider Keys",
983
  "icon": "πŸ”‘",
984
  "k": "MOONSHOT_API_KEY",
985
  "lbl": "Moonshot / Kimi",
986
  "type": "password",
987
- "secret": 1,
988
- "common": 0
989
  },
990
- {
991
  "g": "Provider Keys",
992
  "icon": "πŸ”‘",
993
  "k": "MINIMAX_API_KEY",
994
  "lbl": "MiniMax",
995
  "type": "password",
996
- "secret": 1,
997
- "common": 0
998
  },
999
- {
1000
  "g": "Provider Keys",
1001
  "icon": "πŸ”‘",
1002
  "k": "XIAOMI_API_KEY",
1003
  "lbl": "Xiaomi / MiMo",
1004
  "type": "password",
1005
- "secret": 1,
1006
- "common": 0
1007
  },
1008
- {
1009
  "g": "Provider Keys",
1010
  "icon": "πŸ”‘",
1011
  "k": "VOLCANO_ENGINE_API_KEY",
1012
  "lbl": "Volcengine / Doubao",
1013
  "type": "password",
1014
- "secret": 1,
1015
- "common": 0
1016
  },
1017
- {
1018
  "g": "Provider Keys",
1019
  "icon": "πŸ”‘",
1020
  "k": "BYTEPLUS_API_KEY",
1021
  "lbl": "BytePlus",
1022
  "type": "password",
1023
- "secret": 1,
1024
- "common": 0
1025
  },
1026
- {
1027
  "g": "Provider Keys",
1028
  "icon": "πŸ”‘",
1029
  "k": "MISTRAL_API_KEY",
1030
  "lbl": "Mistral",
1031
  "type": "password",
1032
- "secret": 1,
1033
- "common": 0
1034
  },
1035
- {
1036
  "g": "Provider Keys",
1037
  "icon": "πŸ”‘",
1038
  "k": "XAI_API_KEY",
1039
  "lbl": "xAI (Grok)",
1040
  "type": "password",
1041
- "secret": 1,
1042
- "common": 0
1043
  },
1044
- {
1045
  "g": "Provider Keys",
1046
  "icon": "πŸ”‘",
1047
  "k": "NVIDIA_API_KEY",
1048
  "lbl": "NVIDIA",
1049
  "type": "password",
1050
- "secret": 1,
1051
- "common": 0
1052
  },
1053
- {
1054
  "g": "Provider Keys",
1055
  "icon": "πŸ”‘",
1056
  "k": "GROQ_API_KEY",
1057
  "lbl": "Groq",
1058
  "type": "password",
1059
- "secret": 1,
1060
- "common": 0
1061
  },
1062
- {
1063
  "g": "Provider Keys",
1064
  "icon": "πŸ”‘",
1065
  "k": "COHERE_API_KEY",
1066
  "lbl": "Cohere",
1067
  "type": "password",
1068
- "secret": 1,
1069
- "common": 0
1070
  },
1071
- {
1072
  "g": "Provider Keys",
1073
  "icon": "πŸ”‘",
1074
  "k": "TOGETHER_API_KEY",
1075
  "lbl": "Together AI",
1076
  "type": "password",
1077
- "secret": 1,
1078
- "common": 0
1079
  },
1080
- {
1081
  "g": "Provider Keys",
1082
  "icon": "πŸ”‘",
1083
  "k": "CEREBRAS_API_KEY",
1084
  "lbl": "Cerebras",
1085
  "type": "password",
1086
- "secret": 1,
1087
- "common": 0
1088
  },
1089
- {
1090
  "g": "Provider Keys",
1091
  "icon": "πŸ”‘",
1092
  "k": "QIANFAN_API_KEY",
1093
  "lbl": "Qianfan",
1094
  "type": "password",
1095
- "secret": 1,
1096
- "common": 0
1097
  },
1098
- {
1099
  "g": "Provider Keys",
1100
  "icon": "πŸ”‘",
1101
  "k": "MODELSTUDIO_API_KEY",
1102
  "lbl": "ModelStudio",
1103
  "type": "password",
1104
- "secret": 1,
1105
- "common": 0
1106
  },
1107
- {
1108
  "g": "Provider Keys",
1109
  "icon": "πŸ”‘",
1110
  "k": "KIMI_API_KEY",
1111
  "lbl": "Kimi",
1112
  "type": "password",
1113
- "secret": 1,
1114
- "common": 0
1115
  },
1116
- {
1117
  "g": "Provider Keys",
1118
  "icon": "πŸ”‘",
1119
  "k": "HUGGINGFACE_HUB_TOKEN",
1120
  "lbl": "Hugging Face token",
1121
  "type": "password",
1122
- "secret": 1,
1123
- "common": 0
1124
  },
1125
- {
1126
  "g": "Provider Keys",
1127
  "icon": "πŸ”‘",
1128
  "k": "COPILOT_GITHUB_TOKEN",
1129
  "lbl": "GitHub Copilot",
1130
  "type": "password",
1131
- "secret": 1,
1132
- "common": 0
1133
  },
1134
- {
1135
  "g": "Provider Keys",
1136
  "icon": "πŸ”‘",
1137
  "k": "VENICE_API_KEY",
1138
  "lbl": "Venice",
1139
  "type": "password",
1140
- "secret": 1,
1141
- "common": 0
1142
  },
1143
- {
1144
  "g": "Provider Keys",
1145
  "icon": "πŸ”‘",
1146
  "k": "SYNTHETIC_API_KEY",
1147
  "lbl": "Synthetic",
1148
  "type": "password",
1149
- "secret": 1,
1150
- "common": 0
1151
  },
1152
- {
1153
  "g": "Provider Keys",
1154
  "icon": "πŸ”‘",
1155
  "k": "AI_GATEWAY_API_KEY",
1156
  "lbl": "AI Gateway",
1157
  "type": "password",
1158
- "secret": 1,
1159
- "common": 0
1160
  },
1161
- {
1162
  "g": "Rotation Pools",
1163
  "icon": "πŸ”„",
1164
  "k": "ANTHROPIC_API_KEYS",
1165
  "lbl": "Anthropic pool (comma-sep)",
1166
- "type": "text"
 
1167
  },
1168
- {
1169
  "g": "Rotation Pools",
1170
  "icon": "πŸ”„",
1171
  "k": "OPENAI_API_KEYS",
1172
  "lbl": "OpenAI pool",
1173
- "type": "text"
 
1174
  },
1175
- {
1176
  "g": "Rotation Pools",
1177
  "icon": "πŸ”„",
1178
  "k": "GEMINI_API_KEYS",
1179
  "lbl": "Gemini pool",
1180
- "type": "text"
 
1181
  },
1182
- {
1183
  "g": "Rotation Pools",
1184
  "icon": "πŸ”„",
1185
  "k": "DEEPSEEK_API_KEYS",
1186
  "lbl": "DeepSeek pool",
1187
- "type": "text"
 
1188
  },
1189
- {
1190
  "g": "Rotation Pools",
1191
  "icon": "πŸ”„",
1192
  "k": "OPENROUTER_API_KEYS",
1193
  "lbl": "OpenRouter pool",
1194
- "type": "text"
 
1195
  },
1196
- {
1197
  "g": "Rotation Pools",
1198
  "icon": "πŸ”„",
1199
  "k": "OPENCODE_API_KEYS",
1200
  "lbl": "OpenCode pool",
1201
- "type": "text"
 
1202
  },
1203
- {
1204
  "g": "Rotation Pools",
1205
  "icon": "πŸ”„",
1206
  "k": "KILOCODE_API_KEYS",
1207
  "lbl": "KiloCode pool",
1208
- "type": "text"
 
1209
  },
1210
- {
1211
  "g": "Rotation Pools",
1212
  "icon": "πŸ”„",
1213
  "k": "ZAI_API_KEYS",
1214
  "lbl": "Z.ai / GLM pool",
1215
- "type": "text"
 
1216
  },
1217
- {
1218
  "g": "Rotation Pools",
1219
  "icon": "πŸ”„",
1220
  "k": "MOONSHOT_API_KEYS",
1221
- "lbl": "Moonshot / Kimi pool",
1222
- "type": "text"
 
1223
  },
1224
- {
1225
  "g": "Rotation Pools",
1226
  "icon": "πŸ”„",
1227
  "k": "MINIMAX_API_KEYS",
1228
  "lbl": "MiniMax pool",
1229
- "type": "text"
 
1230
  },
1231
- {
1232
  "g": "Rotation Pools",
1233
  "icon": "πŸ”„",
1234
  "k": "XIAOMI_API_KEYS",
1235
  "lbl": "Xiaomi pool",
1236
- "type": "text"
 
1237
  },
1238
- {
1239
  "g": "Rotation Pools",
1240
  "icon": "πŸ”„",
1241
  "k": "VOLCANO_ENGINE_API_KEYS",
1242
  "lbl": "Volcano Engine pool",
1243
- "type": "text"
 
1244
  },
1245
- {
1246
  "g": "Rotation Pools",
1247
  "icon": "πŸ”„",
1248
  "k": "BYTEPLUS_API_KEYS",
1249
  "lbl": "BytePlus pool",
1250
- "type": "text"
 
1251
  },
1252
- {
1253
  "g": "Rotation Pools",
1254
  "icon": "πŸ”„",
1255
  "k": "MISTRAL_API_KEYS",
1256
  "lbl": "Mistral pool",
1257
- "type": "text"
 
1258
  },
1259
- {
1260
  "g": "Rotation Pools",
1261
  "icon": "πŸ”„",
1262
  "k": "XAI_API_KEYS",
1263
  "lbl": "xAI pool",
1264
- "type": "text"
 
1265
  },
1266
- {
1267
  "g": "Rotation Pools",
1268
  "icon": "πŸ”„",
1269
  "k": "NVIDIA_API_KEYS",
1270
  "lbl": "NVIDIA pool",
1271
- "type": "text"
 
1272
  },
1273
- {
1274
  "g": "Rotation Pools",
1275
  "icon": "πŸ”„",
1276
  "k": "GROQ_API_KEYS",
1277
  "lbl": "Groq pool",
1278
- "type": "text"
 
1279
  },
1280
- {
1281
  "g": "Rotation Pools",
1282
  "icon": "πŸ”„",
1283
  "k": "COHERE_API_KEYS",
1284
  "lbl": "Cohere pool",
1285
- "type": "text"
 
1286
  },
1287
- {
1288
  "g": "Rotation Pools",
1289
  "icon": "πŸ”„",
1290
  "k": "TOGETHER_API_KEYS",
1291
  "lbl": "Together pool",
1292
- "type": "text"
 
1293
  },
1294
- {
1295
  "g": "Rotation Pools",
1296
  "icon": "πŸ”„",
1297
  "k": "CEREBRAS_API_KEYS",
1298
  "lbl": "Cerebras pool",
1299
- "type": "text"
 
1300
  },
1301
- {
1302
  "g": "Rotation Pools",
1303
  "icon": "πŸ”„",
1304
  "k": "HUGGINGFACE_HUB_TOKENS",
1305
  "lbl": "HF token pool",
1306
  "type": "text"
1307
  },
1308
- {
1309
  "g": "Model Lists",
1310
  "icon": "πŸ“‹",
1311
  "k": "OPENAI_MODELS",
1312
  "lbl": "Visible OpenAI models",
1313
  "type": "model_list",
1314
  "options_key": "OPENAI_MODELS",
1315
- "ph": "Select models to build a comma list"
 
1316
  },
1317
- {
1318
  "g": "Model Lists",
1319
  "icon": "πŸ“‹",
1320
  "k": "ANTHROPIC_MODELS",
1321
  "lbl": "Visible Anthropic models",
1322
  "type": "model_list",
1323
  "options_key": "ANTHROPIC_MODELS",
1324
- "ph": "Select models to build a comma list"
 
1325
  },
1326
- {
1327
  "g": "Model Lists",
1328
  "icon": "πŸ“‹",
1329
  "k": "GEMINI_MODELS",
1330
  "lbl": "Visible Gemini models",
1331
  "type": "model_list",
1332
  "options_key": "GEMINI_MODELS",
1333
- "ph": "Select models to build a comma list"
 
1334
  },
1335
- {
1336
  "g": "Model Lists",
1337
  "icon": "πŸ“‹",
1338
  "k": "DEEPSEEK_MODELS",
1339
  "lbl": "Visible DeepSeek models",
1340
  "type": "model_list",
1341
  "options_key": "DEEPSEEK_MODELS",
1342
- "ph": "Select models to build a comma list"
 
1343
  },
1344
- {
1345
  "g": "Model Lists",
1346
  "icon": "πŸ“‹",
1347
  "k": "OPENROUTER_MODELS",
1348
  "lbl": "Visible OpenRouter models",
1349
  "type": "model_list",
1350
  "options_key": "OPENROUTER_MODELS",
1351
- "ph": "Select models to build a comma list"
 
1352
  },
1353
- {
1354
  "g": "Model Lists",
1355
  "icon": "πŸ“‹",
1356
  "k": "GROQ_MODELS",
1357
  "lbl": "Visible Groq models",
1358
  "type": "model_list",
1359
  "options_key": "GROQ_MODELS",
1360
- "ph": "Select models to build a comma list"
 
1361
  },
1362
- {
1363
  "g": "Model Lists",
1364
  "icon": "πŸ“‹",
1365
  "k": "MISTRAL_MODELS",
1366
  "lbl": "Visible Mistral models",
1367
  "type": "model_list",
1368
  "options_key": "MISTRAL_MODELS",
1369
- "ph": "Select models to build a comma list"
 
1370
  },
1371
- {
1372
  "g": "Model Lists",
1373
  "icon": "πŸ“‹",
1374
  "k": "XAI_MODELS",
1375
  "lbl": "Visible xAI models",
1376
  "type": "model_list",
1377
  "options_key": "XAI_MODELS",
1378
- "ph": "Select models to build a comma list"
 
1379
  },
1380
- {
1381
  "g": "Model Lists",
1382
  "icon": "πŸ“‹",
1383
  "k": "COHERE_MODELS",
1384
  "lbl": "Visible Cohere models",
1385
  "type": "model_list",
1386
  "options_key": "COHERE_MODELS",
1387
- "ph": "Select models to build a comma list"
 
1388
  },
1389
- {
1390
  "g": "Model Lists",
1391
  "icon": "πŸ“‹",
1392
  "k": "TOGETHER_MODELS",
1393
  "lbl": "Visible Together models",
1394
  "type": "model_list",
1395
  "options_key": "TOGETHER_MODELS",
1396
- "ph": "Select models to build a comma list"
 
1397
  },
1398
- {
1399
  "g": "Model Lists",
1400
  "icon": "πŸ“‹",
1401
  "k": "CEREBRAS_MODELS",
1402
  "lbl": "Visible Cerebras models",
1403
  "type": "model_list",
1404
  "options_key": "CEREBRAS_MODELS",
1405
- "ph": "Select models to build a comma list"
 
1406
  },
1407
- {
1408
  "g": "Model Lists",
1409
  "icon": "πŸ“‹",
1410
  "k": "NVIDIA_MODELS",
1411
  "lbl": "Visible NVIDIA models",
1412
  "type": "model_list",
1413
  "options_key": "NVIDIA_MODELS",
1414
- "ph": "Select models to build a comma list"
 
1415
  },
1416
- {
1417
  "g": "Model Lists",
1418
  "icon": "πŸ“‹",
1419
  "k": "KILOCODE_MODELS",
1420
  "lbl": "Visible KiloCode models",
1421
  "type": "model_list",
1422
  "options_key": "KILOCODE_MODELS",
1423
- "ph": "Select models to build a comma list"
 
1424
  },
1425
- {
1426
  "g": "Model Lists",
1427
  "icon": "πŸ“‹",
1428
  "k": "OPENCODE_MODELS",
1429
  "lbl": "Visible OpenCode models",
1430
  "type": "model_list",
1431
  "options_key": "OPENCODE_MODELS",
1432
- "ph": "Select models to build a comma list"
 
1433
  },
1434
- {
1435
  "g": "Model Lists",
1436
  "icon": "πŸ“‹",
1437
  "k": "ZAI_MODELS",
1438
  "lbl": "Visible Z.ai / GLM models",
1439
  "type": "model_list",
1440
  "options_key": "ZAI_MODELS",
1441
- "ph": "Select models to build a comma list"
 
1442
  },
1443
- {
1444
  "g": "Model Lists",
1445
  "icon": "πŸ“‹",
1446
  "k": "MOONSHOT_MODELS",
1447
  "lbl": "Visible Moonshot / Kimi models",
1448
  "type": "model_list",
1449
  "options_key": "MOONSHOT_MODELS",
1450
- "ph": "Select models to build a comma list"
 
1451
  },
1452
- {
1453
  "g": "Model Lists",
1454
  "icon": "πŸ“‹",
1455
  "k": "MINIMAX_MODELS",
1456
  "lbl": "Visible MiniMax models",
1457
  "type": "model_list",
1458
  "options_key": "MINIMAX_MODELS",
1459
- "ph": "Select models to build a comma list"
 
1460
  },
1461
- {
1462
  "g": "Model Lists",
1463
  "icon": "πŸ“‹",
1464
  "k": "XIAOMI_MODELS",
1465
  "lbl": "Visible Xiaomi models",
1466
  "type": "model_list",
1467
  "options_key": "XIAOMI_MODELS",
1468
- "ph": "Select models to build a comma list"
 
1469
  },
1470
- {
1471
  "g": "Model Lists",
1472
  "icon": "πŸ“‹",
1473
  "k": "VOLCANO_ENGINE_MODELS",
1474
  "lbl": "Visible Volcano Engine models",
1475
  "type": "model_list",
1476
  "options_key": "VOLCANO_ENGINE_MODELS",
1477
- "ph": "Select models to build a comma list"
 
1478
  },
1479
- {
1480
  "g": "Model Lists",
1481
  "icon": "πŸ“‹",
1482
  "k": "BYTEPLUS_MODELS",
1483
  "lbl": "Visible BytePlus models",
1484
  "type": "model_list",
1485
  "options_key": "BYTEPLUS_MODELS",
1486
- "ph": "Select models to build a comma list"
 
1487
  },
1488
- {
1489
  "g": "Model Lists",
1490
  "icon": "πŸ“‹",
1491
  "k": "QIANFAN_MODELS",
1492
  "lbl": "Visible Qianfan models",
1493
  "type": "model_list",
1494
  "options_key": "QIANFAN_MODELS",
1495
- "ph": "Select models to build a comma list"
 
1496
  },
1497
- {
1498
  "g": "Model Lists",
1499
  "icon": "πŸ“‹",
1500
  "k": "MODELSTUDIO_MODELS",
1501
  "lbl": "Visible ModelStudio models",
1502
  "type": "model_list",
1503
  "options_key": "MODELSTUDIO_MODELS",
1504
- "ph": "Select models to build a comma list"
 
1505
  },
1506
- {
1507
  "g": "Model Lists",
1508
  "icon": "πŸ“‹",
1509
  "k": "KIMI_MODELS",
1510
  "lbl": "Visible Kimi models",
1511
  "type": "model_list",
1512
  "options_key": "KIMI_MODELS",
1513
- "ph": "Select models to build a comma list"
 
1514
  },
1515
- {
1516
  "g": "Model Lists",
1517
  "icon": "πŸ“‹",
1518
  "k": "HUGGINGFACE_MODELS",
1519
  "lbl": "Visible Hugging Face models",
1520
  "type": "model_list",
1521
  "options_key": "HUGGINGFACE_MODELS",
1522
- "ph": "Select models to build a comma list"
 
1523
  },
1524
- {
1525
  "g": "Model Lists",
1526
  "icon": "πŸ“‹",
1527
  "k": "GITHUB_COPILOT_MODELS",
1528
  "lbl": "Visible GitHub Copilot models",
1529
  "type": "model_list",
1530
  "options_key": "GITHUB_COPILOT_MODELS",
1531
- "ph": "Select models to build a comma list"
 
1532
  },
1533
- {
1534
  "g": "Custom Provider",
1535
  "icon": "πŸ”Œ",
1536
  "k": "CUSTOM_PROVIDER_NAME",
1537
  "lbl": "Provider display name",
1538
- "type": "text"
 
1539
  },
1540
- {
1541
  "g": "Custom Provider",
1542
  "icon": "πŸ”Œ",
1543
  "k": "CUSTOM_BASE_URL",
1544
  "lbl": "OpenAI-compatible base URL",
1545
- "type": "text"
 
1546
  },
1547
- {
1548
  "g": "Custom Provider",
1549
  "icon": "πŸ”Œ",
1550
  "k": "CUSTOM_MODEL_ID",
1551
  "lbl": "Model ID",
1552
- "type": "model",
1553
- "options_key": "LLM_MODEL",
1554
- "ph": "custom model id"
1555
  },
1556
- {
1557
  "g": "Custom Provider",
1558
  "icon": "πŸ”Œ",
1559
  "k": "CUSTOM_MODEL_NAME",
1560
  "lbl": "Friendly model name",
1561
- "type": "text"
 
1562
  },
1563
- {
1564
  "g": "Custom Provider",
1565
  "icon": "πŸ”Œ",
1566
  "k": "CUSTOM_API_KEY",
1567
  "lbl": "Provider API key",
1568
  "type": "password",
1569
- "secret": 1
1570
  },
1571
- {
1572
  "g": "Custom Provider",
1573
  "icon": "πŸ”Œ",
1574
  "k": "CUSTOM_API_TYPE",
@@ -1581,104 +1713,200 @@ const FIELDS = [
1581
  "gemini",
1582
  "openrouter"
1583
  ],
1584
- "ph": "openai-completions"
 
1585
  },
1586
- {
1587
  "g": "Custom Provider",
1588
  "icon": "πŸ”Œ",
1589
  "k": "CUSTOM_CONTEXT_WINDOW",
1590
  "lbl": "Context window",
1591
  "type": "number",
1592
- "ph": "128000"
 
1593
  },
1594
- {
1595
  "g": "Custom Provider",
1596
  "icon": "πŸ”Œ",
1597
  "k": "CUSTOM_MAX_TOKENS",
1598
  "lbl": "Max output tokens",
1599
  "type": "number",
1600
- "ph": "500"
 
1601
  },
1602
- {
1603
  "g": "Telegram",
1604
  "icon": "✈️",
1605
  "k": "TELEGRAM_BOT_TOKEN",
1606
  "lbl": "Bot token from BotFather",
1607
  "type": "password",
1608
- "secret": 1,
1609
- "common": 1
1610
  },
1611
- {
1612
  "g": "Telegram",
1613
  "icon": "✈️",
1614
  "k": "TELEGRAM_ALLOWED_USERS",
1615
  "lbl": "Allowed user IDs (comma)",
1616
  "type": "text",
1617
  "ph": "123456789,987654321",
1618
- "common": 1
 
1619
  },
1620
- {
 
 
 
 
 
 
 
 
1621
  "g": "Deployment",
1622
  "icon": "🧭",
1623
  "k": "APP_BASE",
1624
  "lbl": "Public app base path",
1625
  "type": "text",
1626
- "ph": "/app"
 
1627
  },
1628
- {
1629
  "g": "Deployment",
1630
  "icon": "🧭",
1631
  "k": "SPACE_AUTHOR_NAME",
1632
  "lbl": "HF Space author name",
1633
- "type": "text"
 
1634
  },
1635
- {
1636
  "g": "Deployment",
1637
  "icon": "🧭",
1638
  "k": "SPACE_HOST",
1639
  "lbl": "HF Space host domain",
1640
- "type": "text"
 
1641
  },
1642
- {
1643
  "g": "Deployment",
1644
  "icon": "🧭",
1645
  "k": "PORT",
1646
  "lbl": "Public dashboard port",
1647
  "type": "number",
1648
- "ph": "7861"
 
1649
  },
1650
- {
1651
  "g": "Deployment",
1652
  "icon": "🧭",
1653
  "k": "GATEWAY_PORT",
1654
  "lbl": "OpenClaw internal port",
1655
  "type": "number",
1656
- "ph": "7860"
 
1657
  },
1658
- {
1659
  "g": "Deployment",
1660
  "icon": "🧭",
1661
  "k": "JUPYTER_PORT",
1662
  "lbl": "Jupyter internal port",
1663
  "type": "number",
1664
- "ph": "8888"
 
1665
  },
1666
- {
1667
  "g": "Deployment",
1668
  "icon": "🧭",
1669
  "k": "JUPYTER_BASE",
1670
  "lbl": "Jupyter public base path",
1671
  "type": "text",
1672
- "ph": "/terminal"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1673
  }
1674
- ];
1675
 
1676
  const ICONS = {
1677
- All:'🏠', Core:'⚑', Deployment:'🧭', 'Provider Keys':'πŸ”‘', 'Rotation Pools':'πŸ”„',
1678
- 'Model Lists':'πŸ“‹', 'Custom Provider':'πŸ”Œ', Telegram:'✈️', WhatsApp:'πŸ’¬',
1679
- Cloudflare:'☁️', Backup:'πŸ’Ύ', DevData:'πŸ§ͺ', Runtime:'βš™οΈ', 'Custom Env':'πŸ”§'
 
 
1680
  };
1681
-
1682
  const $ = id => document.getElementById(id);
1683
  const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({
1684
  '&': '&amp;',
@@ -1815,6 +2043,7 @@ function defaultValueFor(field) {
1815
  }
1816
 
1817
  function valueControlHTML(field) {
 
1818
  const key = esc(field.k);
1819
  const placeholder = esc(field.ph || field.lbl || '');
1820
  const isSecret = !!field.secret;
@@ -1854,15 +2083,21 @@ function valueControlHTML(field) {
1854
  ${control}
1855
  </div>`;
1856
 
1857
- return control;
1858
  }
1859
 
1860
- function cardHTML(f) {
1861
- const badge = f.secret
1862
- ? '<span class="badge badge-s">secret</span>'
1863
- : '<span class="badge badge-f">safe</span>';
 
 
 
 
 
 
 
1864
 
1865
- return `<div class="env-card" data-row data-group="${esc(f.g)}" data-search="${esc((f.g + ' ' + f.k + ' ' + (f.lbl || '')).toLowerCase())}">
1866
  <div class="card-top">
1867
  <input type="checkbox" class="card-check" data-check="${esc(f.k)}" ${f.common ? 'data-common="1"' : ''}>
1868
  <div class="card-info">
@@ -1940,14 +2175,17 @@ function collect() {
1940
  return obj;
1941
  }
1942
 
1943
- function refresh() {
1944
  const obj = collect();
1945
  const keys = Object.keys(obj).sort();
1946
  const bundle = keys.length ? encodeBundle(Object.fromEntries(keys.map(k => [k, obj[k]]))) : '';
1947
-
1948
  $('bundleOut').value = bundle;
1949
  $('envLineOut').value = bundle ? `HUGGINGCLAW_ENV_BUNDLE=${bundle}` : '';
 
1950
 
 
 
 
1951
  const s = $('summary');
1952
  if (keys.length) {
1953
  s.innerHTML = `<strong>${keys.length}</strong> variable${keys.length > 1 ? 's' : ''} selected<div class="sum-keys">${keys.map(k => `<span class="sum-key">${esc(k)}</span>`).join('')}</div>`;
@@ -2036,7 +2274,7 @@ function applyObj(obj, replace = false) {
2036
  addCustomRow(key, val, true);
2037
  }
2038
  }
2039
- markSelected(); filter(); refresh();
2040
  }
2041
 
2042
  function autoCheck(key) {
@@ -2125,13 +2363,34 @@ function toggleField(key) {
2125
  const chk = document.querySelector(`[data-check="${CSS.escape(key)}"]`);
2126
  if (chk) {
2127
  chk.checked = on;
 
2128
  markSelected();
2129
  }
2130
  refresh();
2131
  }
2132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2133
  function bindFieldEvents() {
2134
- document.querySelectorAll('[data-check]').forEach(el => el.addEventListener('change', () => { markSelected(); refresh(); }));
2135
  document.querySelectorAll('[data-key]').forEach(el => el.addEventListener('input', refresh));
2136
  document.querySelectorAll('[data-toggle]').forEach(btn => btn.addEventListener('click', () => toggleField(btn.dataset.toggle)));
2137
  document.querySelectorAll('[data-pick-for]').forEach(sel => sel.addEventListener('change', () => handlePickerChange(sel)));
@@ -2141,22 +2400,31 @@ function bindFieldEvents() {
2141
 
2142
  function renderSections() {
2143
  const grouped = {};
2144
- FIELDS.forEach(f => { (grouped[f.g] ||= []).push(f); });
 
 
 
2145
 
2146
  const wrap = $('sections');
 
2147
  wrap.innerHTML = '';
2148
  Object.entries(grouped).forEach(([grp, items]) => {
2149
- const sec = document.createElement('div');
2150
- sec.className = 'sec';
2151
- sec.dataset.section = grp;
2152
- sec.innerHTML = `
2153
- <div class="sec-header">
2154
- <span class="sec-icon">${ICONS[grp] || 'πŸ“'}</span>
2155
- <span class="sec-title">${esc(grp)}</span>
2156
- <div class="sec-line"></div>
2157
- </div>
2158
- <div class="cards">${items.map(cardHTML).join('')}</div>`;
2159
- wrap.appendChild(sec);
 
 
 
 
 
2160
  });
2161
  bindFieldEvents();
2162
  }
@@ -2179,66 +2447,62 @@ function copyText(text) {
2179
  }
2180
 
2181
  // ── Init ──
2182
- renderSidebar();
2183
- renderSections();
2184
- addCustomRow();
2185
- filter();
2186
- refresh();
 
 
 
 
 
 
2187
 
2188
  // ── Events ──
2189
  $('search').oninput = filter;
 
 
 
 
 
 
2190
  $('selectCommon').onclick = () => {
2191
  document.querySelectorAll('[data-common="1"]').forEach(c => c.checked = true);
 
2192
  markSelected();
2193
  refresh();
2194
  };
2195
  $('selectVisible').onclick = () => {
2196
  document.querySelectorAll('.sec:not(.sec-hidden) [data-row]:not(.hidden) [data-check]').forEach(c => c.checked = true);
 
2197
  markSelected();
2198
  refresh();
2199
  };
2200
  $('clearAll').onclick = () => {
2201
  clearForm();
 
2202
  markSelected();
2203
  filter();
2204
  refresh();
2205
  };
2206
  $('applyImport').onclick = () => {
2207
  try {
2208
- applyObj(parseEnv($('importText').value), true);
2209
- showToast('Imported βœ“');
 
 
 
 
 
 
2210
  } catch (e) {
2211
  showToast('Import failed');
2212
  alert(e.message);
2213
  }
2214
  };
2215
 
2216
- // Auto-import: paste karo aur turant parse + apply ho jaata hai
2217
- $('importText').addEventListener('paste', () => {
2218
- setTimeout(() => {
2219
- try {
2220
- const val = $('importText').value.trim();
2221
- if (!val) return;
2222
- applyObj(parseEnv(val), true);
2223
- showToast('Auto-imported βœ“');
2224
- } catch (e) {
2225
- showToast('Import failed');
2226
- }
2227
- }, 0);
2228
- });
2229
-
2230
- // Live typing: jaise jaise type karo env format mein, bundle banta jaata hai
2231
- $('importText').addEventListener('input', () => {
2232
- const val = $('importText').value.trim();
2233
- if (!val) return;
2234
- // Sirf agar valid env/bundle format lag raha ho tabhi auto-apply
2235
- const looksLikeEnv = val.includes('=') || val.startsWith('{') || /^[A-Za-z0-9_\-]{20,}$/.test(val);
2236
- if (looksLikeEnv) {
2237
- try {
2238
- applyObj(parseEnv(val), true);
2239
- } catch (e) { /* silent β€” user abhi type kar raha hai */ }
2240
- }
2241
- });
2242
  $('addCustom').onclick = () => addCustomRow();
2243
  $('applyBundle').onclick = () => {
2244
  try {
@@ -2248,6 +2512,7 @@ $('applyBundle').onclick = () => {
2248
  showToast('Invalid bundle');
2249
  }
2250
  };
 
2251
  $('copyBundle').onclick = () => copyText($('bundleOut').value);
2252
  $('copyEnvLine').onclick = () => copyText($('envLineOut').value);
2253
  $('copyJson').onclick = () => copyText(JSON.stringify(collect(), null, 2));
 
54
  "Groq": [
55
  "groq/compound",
56
  "groq/compound-mini",
57
+ "groq/llama-3.1-8b-instant",
58
+ "groq/llama-3.1-70b-versatile",
59
+ "groq/llama-3.3-70b-versatile",
60
  "meta-llama/llama-4-scout-17b-16e-instruct",
61
  "openai/gpt-oss-20b",
62
  "openai/gpt-oss-120b",
63
  "qwen/qwen3-32b",
64
+ "groq/mixtral-8x7b-32768"
65
  ],
66
  "Mistral": [
67
+ "mistral/mistral-large-latest",
68
+ "mistral/mistral-large-2",
69
+ "mistral/mistral-medium-3.5",
70
+ "mistral/mistral-small-latest",
71
+ "mistral/mistral-small-3.2",
72
+ "mistral/devstral-2",
73
+ "mistral/ocr-3-premier",
74
+ "mistral/voxtral-mini-transcribe-realtime",
75
+ "mistral/codestral-latest"
76
  ],
77
  "Cohere": [
78
  "command-a",
 
280
  "GROQ_MODELS": [
281
  "groq/compound",
282
  "groq/compound-mini",
283
+ "groq/llama-3.1-8b-instant",
284
+ "groq/llama-3.1-70b-versatile",
285
+ "groq/llama-3.3-70b-versatile",
286
  "openai/gpt-oss-20b",
287
  "openai/gpt-oss-120b",
288
  "meta-llama/llama-4-scout-17b-16e-instruct",
289
  "qwen/qwen3-32b",
290
+ "groq/mixtral-8x7b-32768"
291
  ],
292
  "MISTRAL_MODELS": [
293
+ "mistral/mistral-large-latest",
294
+ "mistral/mistral-large-2",
295
+ "mistral/mistral-medium-3.5",
296
+ "mistral/mistral-small-latest",
297
+ "mistral/mistral-small-3.2",
298
+ "mistral/devstral-2",
299
+ "mistral/ocr-3-premier",
300
+ "mistral/voxtral-mini-transcribe-realtime",
301
+ "mistral/codestral-latest"
302
  ],
303
  "XAI_MODELS": [
304
  "grok-4.3",
 
416
  };
417
 
418
  const FIELDS = [
419
+ {
420
  "g": "Core",
421
  "icon": "⚑",
422
  "k": "LLM_MODEL",
423
  "lbl": "Default model ID",
424
+ "type": "text",
 
425
  "ph": "choose a provider model",
426
+ "common": 1,
427
+ "tag": "critical"
428
  },
429
+ {
430
  "g": "Core",
431
  "icon": "⚑",
432
  "k": "LLM_API_KEY",
433
  "lbl": "Primary provider API key",
434
  "type": "password",
 
435
  "ph": "sk-...",
436
+ "common": 1,
437
+ "tag": "credential"
438
  },
439
+ {
440
  "g": "Core",
441
  "icon": "⚑",
442
  "k": "GATEWAY_TOKEN",
443
  "lbl": "Control UI gateway token",
444
  "type": "password",
445
+ "common": 1,
446
+ "tag": "critical"
447
  },
448
+ {
449
  "g": "Core",
450
  "icon": "⚑",
451
  "k": "OPENCLAW_PASSWORD",
452
  "lbl": "Optional password auth",
453
  "type": "password",
454
+ "tag": "credential"
455
  },
456
+ {
457
  "g": "Core",
458
  "icon": "⚑",
459
  "k": "OPENCLAW_VERSION",
460
+ "lbl": "Pin OpenClaw version (build-time; rebuild required)",
461
  "type": "text",
462
+ "ph": "latest",
463
+ "tag": "build"
464
  },
465
+ {
466
+ "g": "Plugins",
467
  "icon": "⚑",
468
  "k": "LLM_API_KEY_FALLBACK_ENABLED",
469
  "lbl": "Allow global LLM_API_KEY fallback",
470
  "type": "toggle",
471
+ "ph": "true",
472
+ "tag": "advanced"
473
  },
474
+ {
475
+ "g": "Plugins",
476
+ "icon": "πŸ”„",
477
+ "k": "KEY_BLACKLIST_COOLDOWN_MS",
478
+ "lbl": "Key rotation base backoff (ms) β€” time a key is skipped after first 429/rate-limit (doubles on repeated failures; 24h after max strikes)",
479
+ "type": "text",
480
+ "ph": "60000",
481
+ "tag": "advanced"
482
+ },
483
+ {
484
+ "g": "Plugins",
485
+ "icon": "πŸ”„",
486
+ "k": "KEY_MAX_STRIKES",
487
+ "lbl": "Key rotation max strikes β€” consecutive 429/quota errors before a key is suspended for 24h",
488
+ "type": "text",
489
+ "ph": "3",
490
+ "tag": "advanced"
491
+ },
492
+ {
493
+ "g": "Startup",
494
  "icon": "⚑",
495
  "k": "DEV_MODE",
496
  "lbl": "Enable dev mode",
497
  "type": "toggle",
498
  "ph": "false",
499
+ "common": 1,
500
+ "tag": "build"
501
+ },
502
+ {
503
+ "g": "Startup",
504
+ "icon": "🩺",
505
+ "k": "AUTO_DOCTOR",
506
+ "lbl": "Auto-fix config on boot (openclaw doctor --fix)",
507
+ "type": "toggle",
508
+ "ph": "false",
509
+ "tag": "advanced"
510
  },
511
+ {
512
+ "g": "Startup",
513
  "icon": "⚑",
514
  "k": "HUGGINGCLAW_JUPYTER_ENABLED",
515
  "lbl": "Enable Jupyter terminal",
516
  "type": "toggle",
517
  "ph": "false",
518
+ "common": 1,
519
+ "tag": "feature"
520
  },
521
+ {
522
+ "g": "DevData",
523
  "icon": "⚑",
524
  "k": "DEVDATA",
525
  "lbl": "DevData switch",
526
  "type": "toggle",
527
  "ph": "on",
528
+ "common": 1,
529
+ "tag": "feature"
530
  },
531
+ {
532
+ "g": "DevData",
533
  "icon": "⚑",
534
  "k": "DEVDATA_DATASET_NAME",
535
  "lbl": "DevData dataset name",
536
  "type": "text",
537
  "ph": "huggingclaw-devdata",
538
+ "common": 1,
539
+ "tag": "feature"
540
  },
541
+ {
542
+ "g": "DevData",
543
  "icon": "⚑",
544
  "k": "DEVDATA_SYNC_INTERVAL",
545
  "lbl": "DevData sync interval (seconds)",
546
  "type": "number",
547
+ "ph": "180",
548
+ "tag": "advanced"
549
  },
550
+ {
551
+ "g": "WhatsApp",
552
  "icon": "⚑",
553
  "k": "WHATSAPP_ENABLED",
554
  "lbl": "Enable WhatsApp pairing",
555
  "type": "toggle",
556
  "ph": "false",
557
+ "common": 1,
558
+ "tag": "feature"
559
  },
560
+ {
561
+ "g": "Startup",
562
  "icon": "⚑",
563
  "k": "HUGGINGCLAW_CAPTURE_DISABLE",
564
  "lbl": "Disable capture wrapper",
565
  "type": "toggle",
566
+ "ph": "false",
567
+ "tag": "advanced"
568
  },
569
+ {
570
+ "g": "Startup",
571
  "icon": "⚑",
572
  "k": "HUGGINGCLAW_STARTUP_STRICT",
573
  "lbl": "Stop on startup failure",
574
  "type": "toggle",
575
+ "ph": "false",
576
+ "tag": "advanced"
577
  },
578
+ {
579
+ "g": "Startup",
580
  "icon": "⚑",
581
  "k": "HUGGINGCLAW_RUN",
582
  "lbl": "Startup command (one-liner)",
583
+ "type": "textarea",
584
+ "tag": "optional"
585
  },
586
+ {
587
+ "g": "Startup",
588
  "icon": "⚑",
589
  "k": "HUGGINGCLAW_STARTUP_COMMANDS",
590
  "lbl": "Multiline startup commands",
591
+ "type": "textarea",
592
+ "tag": "optional"
593
  },
594
+ {
595
+ "g": "Startup",
596
  "icon": "⚑",
597
  "k": "HUGGINGCLAW_STARTUP_SCRIPT",
598
  "lbl": "Startup shell script",
599
+ "type": "textarea",
600
+ "tag": "optional"
601
  },
602
+ {
603
+ "g": "Startup",
604
  "icon": "⚑",
605
  "k": "HUGGINGCLAW_STARTUP_SCRIPT_B64",
606
  "lbl": "Startup script (base64)",
607
+ "type": "textarea",
608
+ "tag": "optional"
609
  },
610
+ {
611
+ "g": "Startup",
612
  "icon": "⚑",
613
  "k": "HUGGINGCLAW_APT_PACKAGES",
614
  "lbl": "APT packages to install",
615
+ "type": "textarea",
616
+ "tag": "optional"
617
  },
618
+ {
619
+ "g": "Startup",
620
  "icon": "⚑",
621
  "k": "HUGGINGCLAW_PIP_PACKAGES",
622
  "lbl": "Pip packages to install",
623
+ "type": "textarea",
624
+ "tag": "optional"
625
  },
626
+ {
627
+ "g": "Startup",
628
  "icon": "⚑",
629
  "k": "HUGGINGCLAW_NPM_PACKAGES",
630
  "lbl": "NPM packages to install",
631
+ "type": "textarea",
632
+ "tag": "optional"
633
  },
634
+ {
635
+ "g": "Startup",
636
  "icon": "⚑",
637
  "k": "HUGGINGCLAW_OPENCLAW_PLUGINS",
638
  "lbl": "OpenClaw plugins to load",
639
+ "type": "textarea",
640
+ "tag": "optional"
641
  },
642
+ {
643
+ "g": "Network",
644
  "icon": "⚑",
645
  "k": "ALLOWED_ORIGINS",
646
  "lbl": "Allowed CORS origins",
647
+ "type": "textarea",
648
+ "tag": "advanced"
649
  },
650
+ {
651
+ "g": "Network",
652
  "icon": "⚑",
653
  "k": "TRUSTED_PROXIES",
654
  "lbl": "Trusted proxy CIDRs",
655
+ "type": "textarea",
656
+ "tag": "advanced"
657
  },
658
+ {
659
+ "g": "Network",
660
  "icon": "⚑",
661
  "k": "WEBHOOK_URL",
662
  "lbl": "Webhook URL",
 
669
  "k": "GATEWAY_MAX_RESTARTS",
670
  "lbl": "Gateway max restarts",
671
  "type": "number",
672
+ "ph": "10",
673
+ "tag": "advanced"
674
  },
675
+ {
676
+ "g": "Gateway",
677
  "icon": "⚑",
678
  "k": "GATEWAY_READY_TIMEOUT",
679
  "lbl": "Gateway ready timeout",
680
  "type": "number",
681
+ "ph": "90",
682
+ "tag": "advanced"
683
  },
684
+ {
685
+ "g": "Gateway",
686
  "icon": "⚑",
687
  "k": "GATEWAY_RESTART_DELAY",
688
  "lbl": "Gateway restart delay",
689
  "type": "number",
690
+ "ph": "5",
691
+ "tag": "advanced"
692
  },
693
+ {
694
+ "g": "Gateway",
695
  "icon": "⚑",
696
  "k": "GATEWAY_VERBOSE",
697
  "lbl": "Verbose gateway logs",
698
  "type": "toggle",
699
+ "ph": "false",
700
+ "tag": "advanced"
701
  },
702
+ {
703
+ "g": "Logging",
704
  "icon": "⚑",
705
  "k": "OPENCLAW_CONSOLE_LOG_LEVEL",
706
  "lbl": "Console log level",
 
711
  "warn",
712
  "error"
713
  ],
714
+ "ph": "info",
715
+ "tag": "optional"
716
  },
717
+ {
718
+ "g": "Logging",
719
  "icon": "⚑",
720
  "k": "OPENCLAW_FILE_LOG_LEVEL",
721
  "lbl": "File log level",
 
726
  "warn",
727
  "error"
728
  ],
729
+ "ph": "info",
730
+ "tag": "optional"
731
  },
732
+ {
733
+ "g": "Logging",
734
  "icon": "⚑",
735
  "k": "OPENCLAW_CONSOLE_LOG_STYLE",
736
  "lbl": "Console log style",
 
740
  "json",
741
  "compact"
742
  ],
743
+ "ph": "pretty",
744
+ "tag": "optional"
745
  },
746
+ {
747
+ "g": "Plugins",
748
  "icon": "⚑",
749
  "k": "BROWSER_PLUGIN_MODE",
750
  "lbl": "Browser plugin mode",
 
754
  "enabled",
755
  "disabled"
756
  ],
757
+ "ph": "auto",
758
+ "tag": "feature"
759
  },
760
+ {
761
+ "g": "Plugins",
762
  "icon": "⚑",
763
  "k": "ACP_PLUGIN_MODE",
764
  "lbl": "ACP plugin mode",
 
768
  "enabled",
769
  "disabled"
770
  ],
771
+ "ph": "auto",
772
+ "tag": "feature"
773
  },
774
+ {
775
+ "g": "Cloudflare",
776
  "icon": "⚑",
777
  "k": "CLOUDFLARE_PROXY_DEBUG",
778
  "lbl": "Cloudflare proxy debug",
779
  "type": "toggle",
780
+ "ph": "false",
781
+ "tag": "advanced"
782
  },
783
+ {
784
+ "g": "Cloudflare",
785
  "icon": "⚑",
786
  "k": "CLOUDFLARE_KEEPALIVE_ENABLED",
787
  "lbl": "Enable keep-awake worker",
788
  "type": "toggle",
789
+ "ph": "true",
790
+ "tag": "feature"
791
  },
792
+ {
793
+ "g": "Cloudflare",
794
  "icon": "⚑",
795
  "k": "CLOUDFLARE_PROXY_URL",
796
  "lbl": "Proxy worker URL",
797
  "type": "text",
798
  "ph": "https://your-proxy.workers.dev",
799
+ "common": 1,
800
+ "tag": "feature"
801
  },
802
+ {
803
+ "g": "Cloudflare",
804
  "icon": "⚑",
805
  "k": "CLOUDFLARE_PROXY_SECRET",
806
  "lbl": "Proxy shared secret",
807
  "type": "password",
808
+ "tag": "credential"
809
  },
810
+ {
811
+ "g": "Cloudflare",
812
  "icon": "⚑",
813
  "k": "CLOUDFLARE_PROXY_DOMAINS",
814
  "lbl": "Extra domains to proxy",
815
  "type": "textarea",
816
+ "ph": "api.sendgrid.com,slack.com",
817
+ "tag": "advanced"
818
  },
819
+ {
820
+ "g": "Cloudflare",
821
  "icon": "⚑",
822
  "k": "CLOUDFLARE_WORKERS_TOKEN",
823
  "lbl": "Workers API token",
824
  "type": "password",
825
+ "common": 1,
826
+ "tag": "credential"
827
  },
828
+ {
829
  "g": "Core",
830
  "icon": "⚑",
831
  "k": "HF_USERNAME",
832
  "lbl": "Hugging Face username",
833
  "type": "text",
834
+ "common": 1,
835
+ "tag": "optional"
836
  },
837
+ {
838
  "g": "Core",
839
  "icon": "⚑",
840
  "k": "HF_TOKEN",
841
  "lbl": "HF write token",
842
  "type": "password",
843
+ "common": 1,
844
+ "tag": "credential"
845
  },
846
+ {
847
  "g": "Core",
848
  "icon": "⚑",
849
  "k": "BACKUP_DATASET_NAME",
850
  "lbl": "Backup dataset name",
851
  "type": "text",
852
  "ph": "huggingclaw-backup",
853
+ "common": 1,
854
+ "tag": "optional"
855
  },
856
+ {
857
  "g": "Core",
858
  "icon": "⚑",
859
  "k": "SYNC_INTERVAL",
860
  "lbl": "Sync interval (seconds)",
861
  "type": "number",
862
  "ph": "180",
863
+ "common": 1,
864
+ "tag": "advanced"
865
  },
866
+ {
867
  "g": "Core",
868
  "icon": "⚑",
869
  "k": "JUPYTER_TOKEN",
870
+ "lbl": "Jupyter access token (Must NOT be 'huggingface'. Run: openssl rand -hex 32)",
871
  "type": "password",
872
  "secret": 1,
873
  "ph": "huggingface",
 
879
  "k": "OPENCLAW_DISABLE_BONJOUR",
880
  "lbl": "Disable Bonjour/mDNS discovery",
881
  "type": "toggle",
882
+ "ph": "false",
883
+ "tag": "advanced"
884
  },
885
+ {
886
  "g": "Core",
887
  "icon": "⚑",
888
  "k": "OPENCLAW_RUNTIME_VERSION",
889
  "lbl": "Pin runtime version",
890
  "type": "text",
891
+ "ph": "latest",
892
+ "tag": "advanced"
893
  },
894
+ {
895
  "g": "Core",
896
  "icon": "⚑",
897
  "k": "OPENCLAW_DISPLAY_VERSION",
898
  "lbl": "Display version label",
899
  "type": "text",
900
+ "ph": "",
901
+ "tag": "optional"
902
  },
903
+ {
904
  "g": "Integrations",
905
  "icon": "πŸ”Œ",
906
  "k": "CLOUDFLARE_ACCOUNT_ID",
907
  "lbl": "Cloudflare account ID",
908
  "type": "text",
909
+ "ph": "account-id",
910
+ "tag": "feature"
911
  },
912
+ {
913
  "g": "Integrations",
914
  "icon": "πŸ”Œ",
915
  "k": "CLOUDFLARE_WORKER_NAME",
916
  "lbl": "Outbound proxy worker name",
917
  "type": "text",
918
+ "ph": "huggingclaw-proxy",
919
+ "tag": "feature"
920
  },
921
+ {
922
  "g": "Integrations",
923
  "icon": "πŸ”Œ",
924
  "k": "CLOUDFLARE_KEEPALIVE_URL",
925
  "lbl": "Keepalive worker URL",
926
  "type": "text",
927
+ "ph": "https://your-worker.workers.dev",
928
+ "tag": "feature"
929
  },
930
+ {
931
  "g": "Integrations",
932
  "icon": "πŸ”Œ",
933
  "k": "CLOUDFLARE_KEEPALIVE_WORKER_NAME",
934
  "lbl": "Keepalive worker name",
935
  "type": "text",
936
+ "ph": "huggingclaw-keepalive",
937
+ "tag": "feature"
938
  },
939
+ {
940
  "g": "Integrations",
941
  "icon": "πŸ”Œ",
942
  "k": "CLOUDFLARE_KEEPALIVE_CRON",
943
  "lbl": "Keepalive cron schedule",
944
  "type": "text",
945
+ "ph": "*/5 * * * *",
946
+ "tag": "advanced"
947
  },
948
+ {
949
  "g": "Integrations",
950
  "icon": "πŸ”Œ",
951
  "k": "TELEGRAM_API_ROOT",
952
  "lbl": "Telegram API root override",
953
  "type": "text",
954
+ "ph": "https://api.telegram.org",
955
+ "tag": "advanced"
956
  },
957
+ {
958
  "g": "Runtime",
959
  "icon": "βš™οΈ",
960
  "k": "OPENCLAW_CONFIG_WATCH_INTERVAL",
961
  "lbl": "Config watch interval (seconds)",
962
  "type": "number",
963
+ "ph": "1",
964
+ "tag": "advanced"
965
  },
966
+ {
967
  "g": "Runtime",
968
  "icon": "βš™οΈ",
969
  "k": "OPENCLAW_CONFIG_SETTLE_SECONDS",
970
  "lbl": "Config settle window (seconds)",
971
  "type": "number",
972
+ "ph": "3",
973
+ "tag": "advanced"
974
  },
975
+ {
976
+ "g": "Runtime",
977
+ "icon": "βš™οΈ",
978
+ "k": "SESSIONS_MIN_SYNC_GAP",
979
+ "lbl": "Sessions min sync gap (seconds)",
980
+ "type": "number",
981
+ "ph": "30",
982
+ "tag": "advanced"
983
+ },
984
+ {
985
  "g": "Runtime",
986
  "icon": "βš™οΈ",
987
  "k": "JUPYTER_ROOT_DIR",
988
  "lbl": "Jupyter root directory",
989
  "type": "text",
990
+ "ph": "/home/node",
991
+ "tag": "advanced"
992
  },
993
  {
994
  "g": "Provider Keys",
 
996
  "k": "ANTHROPIC_API_KEY",
997
  "lbl": "Anthropic (Claude)",
998
  "type": "password",
999
+ "common": 0,
1000
+ "tag": "credential"
1001
  },
1002
+ {
1003
  "g": "Provider Keys",
1004
  "icon": "πŸ”‘",
1005
  "k": "OPENAI_API_KEY",
1006
  "lbl": "OpenAI (GPT)",
1007
  "type": "password",
1008
+ "common": 0,
1009
+ "tag": "credential"
1010
  },
1011
+ {
1012
  "g": "Provider Keys",
1013
  "icon": "πŸ”‘",
1014
  "k": "GEMINI_API_KEY",
1015
  "lbl": "Google Gemini",
1016
  "type": "password",
1017
+ "common": 0,
1018
+ "tag": "credential"
1019
  },
1020
+ {
1021
  "g": "Provider Keys",
1022
  "icon": "πŸ”‘",
1023
  "k": "DEEPSEEK_API_KEY",
1024
  "lbl": "DeepSeek",
1025
  "type": "password",
1026
+ "common": 0,
1027
+ "tag": "credential"
1028
  },
1029
+ {
1030
  "g": "Provider Keys",
1031
  "icon": "πŸ”‘",
1032
  "k": "OPENROUTER_API_KEY",
1033
  "lbl": "OpenRouter",
1034
  "type": "password",
1035
+ "common": 1,
1036
+ "tag": "credential"
1037
  },
1038
+ {
1039
  "g": "Provider Keys",
1040
  "icon": "πŸ”‘",
1041
  "k": "OPENCODE_API_KEY",
1042
  "lbl": "OpenCode",
1043
  "type": "password",
1044
+ "common": 0,
1045
+ "tag": "credential"
1046
  },
1047
+ {
1048
  "g": "Provider Keys",
1049
  "icon": "πŸ”‘",
1050
  "k": "KILOCODE_API_KEY",
1051
  "lbl": "KiloCode",
1052
  "type": "password",
1053
+ "common": 0,
1054
+ "tag": "credential"
1055
  },
1056
+ {
1057
  "g": "Provider Keys",
1058
  "icon": "πŸ”‘",
1059
  "k": "ZAI_API_KEY",
1060
  "lbl": "Z.ai / GLM",
1061
  "type": "password",
1062
+ "common": 0,
1063
+ "tag": "credential"
1064
  },
1065
+ {
1066
  "g": "Provider Keys",
1067
  "icon": "πŸ”‘",
1068
  "k": "MOONSHOT_API_KEY",
1069
  "lbl": "Moonshot / Kimi",
1070
  "type": "password",
1071
+ "common": 0,
1072
+ "tag": "credential"
1073
  },
1074
+ {
1075
  "g": "Provider Keys",
1076
  "icon": "πŸ”‘",
1077
  "k": "MINIMAX_API_KEY",
1078
  "lbl": "MiniMax",
1079
  "type": "password",
1080
+ "common": 0,
1081
+ "tag": "credential"
1082
  },
1083
+ {
1084
  "g": "Provider Keys",
1085
  "icon": "πŸ”‘",
1086
  "k": "XIAOMI_API_KEY",
1087
  "lbl": "Xiaomi / MiMo",
1088
  "type": "password",
1089
+ "common": 0,
1090
+ "tag": "credential"
1091
  },
1092
+ {
1093
  "g": "Provider Keys",
1094
  "icon": "πŸ”‘",
1095
  "k": "VOLCANO_ENGINE_API_KEY",
1096
  "lbl": "Volcengine / Doubao",
1097
  "type": "password",
1098
+ "common": 0,
1099
+ "tag": "credential"
1100
  },
1101
+ {
1102
  "g": "Provider Keys",
1103
  "icon": "πŸ”‘",
1104
  "k": "BYTEPLUS_API_KEY",
1105
  "lbl": "BytePlus",
1106
  "type": "password",
1107
+ "common": 0,
1108
+ "tag": "credential"
1109
  },
1110
+ {
1111
  "g": "Provider Keys",
1112
  "icon": "πŸ”‘",
1113
  "k": "MISTRAL_API_KEY",
1114
  "lbl": "Mistral",
1115
  "type": "password",
1116
+ "common": 0,
1117
+ "tag": "credential"
1118
  },
1119
+ {
1120
  "g": "Provider Keys",
1121
  "icon": "πŸ”‘",
1122
  "k": "XAI_API_KEY",
1123
  "lbl": "xAI (Grok)",
1124
  "type": "password",
1125
+ "common": 0,
1126
+ "tag": "credential"
1127
  },
1128
+ {
1129
  "g": "Provider Keys",
1130
  "icon": "πŸ”‘",
1131
  "k": "NVIDIA_API_KEY",
1132
  "lbl": "NVIDIA",
1133
  "type": "password",
1134
+ "common": 0,
1135
+ "tag": "credential"
1136
  },
1137
+ {
1138
  "g": "Provider Keys",
1139
  "icon": "πŸ”‘",
1140
  "k": "GROQ_API_KEY",
1141
  "lbl": "Groq",
1142
  "type": "password",
1143
+ "common": 0,
1144
+ "tag": "credential"
1145
  },
1146
+ {
1147
  "g": "Provider Keys",
1148
  "icon": "πŸ”‘",
1149
  "k": "COHERE_API_KEY",
1150
  "lbl": "Cohere",
1151
  "type": "password",
1152
+ "common": 0,
1153
+ "tag": "credential"
1154
  },
1155
+ {
1156
  "g": "Provider Keys",
1157
  "icon": "πŸ”‘",
1158
  "k": "TOGETHER_API_KEY",
1159
  "lbl": "Together AI",
1160
  "type": "password",
1161
+ "common": 0,
1162
+ "tag": "credential"
1163
  },
1164
+ {
1165
  "g": "Provider Keys",
1166
  "icon": "πŸ”‘",
1167
  "k": "CEREBRAS_API_KEY",
1168
  "lbl": "Cerebras",
1169
  "type": "password",
1170
+ "common": 0,
1171
+ "tag": "credential"
1172
  },
1173
+ {
1174
  "g": "Provider Keys",
1175
  "icon": "πŸ”‘",
1176
  "k": "QIANFAN_API_KEY",
1177
  "lbl": "Qianfan",
1178
  "type": "password",
1179
+ "common": 0,
1180
+ "tag": "credential"
1181
  },
1182
+ {
1183
  "g": "Provider Keys",
1184
  "icon": "πŸ”‘",
1185
  "k": "MODELSTUDIO_API_KEY",
1186
  "lbl": "ModelStudio",
1187
  "type": "password",
1188
+ "common": 0,
1189
+ "tag": "credential"
1190
  },
1191
+ {
1192
  "g": "Provider Keys",
1193
  "icon": "πŸ”‘",
1194
  "k": "KIMI_API_KEY",
1195
  "lbl": "Kimi",
1196
  "type": "password",
1197
+ "common": 0,
1198
+ "tag": "credential"
1199
  },
1200
+ {
1201
  "g": "Provider Keys",
1202
  "icon": "πŸ”‘",
1203
  "k": "HUGGINGFACE_HUB_TOKEN",
1204
  "lbl": "Hugging Face token",
1205
  "type": "password",
1206
+ "common": 0,
1207
+ "tag": "credential"
1208
  },
1209
+ {
1210
  "g": "Provider Keys",
1211
  "icon": "πŸ”‘",
1212
  "k": "COPILOT_GITHUB_TOKEN",
1213
  "lbl": "GitHub Copilot",
1214
  "type": "password",
1215
+ "common": 0,
1216
+ "tag": "credential"
1217
  },
1218
+ {
1219
  "g": "Provider Keys",
1220
  "icon": "πŸ”‘",
1221
  "k": "VENICE_API_KEY",
1222
  "lbl": "Venice",
1223
  "type": "password",
1224
+ "common": 0,
1225
+ "tag": "credential"
1226
  },
1227
+ {
1228
  "g": "Provider Keys",
1229
  "icon": "πŸ”‘",
1230
  "k": "SYNTHETIC_API_KEY",
1231
  "lbl": "Synthetic",
1232
  "type": "password",
1233
+ "common": 0,
1234
+ "tag": "credential"
1235
  },
1236
+ {
1237
  "g": "Provider Keys",
1238
  "icon": "πŸ”‘",
1239
  "k": "AI_GATEWAY_API_KEY",
1240
  "lbl": "AI Gateway",
1241
  "type": "password",
1242
+ "common": 0,
1243
+ "tag": "credential"
1244
  },
1245
+ {
1246
  "g": "Rotation Pools",
1247
  "icon": "πŸ”„",
1248
  "k": "ANTHROPIC_API_KEYS",
1249
  "lbl": "Anthropic pool (comma-sep)",
1250
+ "type": "text",
1251
+ "tag": "advanced"
1252
  },
1253
+ {
1254
  "g": "Rotation Pools",
1255
  "icon": "πŸ”„",
1256
  "k": "OPENAI_API_KEYS",
1257
  "lbl": "OpenAI pool",
1258
+ "type": "text",
1259
+ "tag": "advanced"
1260
  },
1261
+ {
1262
  "g": "Rotation Pools",
1263
  "icon": "πŸ”„",
1264
  "k": "GEMINI_API_KEYS",
1265
  "lbl": "Gemini pool",
1266
+ "type": "text",
1267
+ "tag": "advanced"
1268
  },
1269
+ {
1270
  "g": "Rotation Pools",
1271
  "icon": "πŸ”„",
1272
  "k": "DEEPSEEK_API_KEYS",
1273
  "lbl": "DeepSeek pool",
1274
+ "type": "text",
1275
+ "tag": "advanced"
1276
  },
1277
+ {
1278
  "g": "Rotation Pools",
1279
  "icon": "πŸ”„",
1280
  "k": "OPENROUTER_API_KEYS",
1281
  "lbl": "OpenRouter pool",
1282
+ "type": "text",
1283
+ "tag": "advanced"
1284
  },
1285
+ {
1286
  "g": "Rotation Pools",
1287
  "icon": "πŸ”„",
1288
  "k": "OPENCODE_API_KEYS",
1289
  "lbl": "OpenCode pool",
1290
+ "type": "text",
1291
+ "tag": "advanced"
1292
  },
1293
+ {
1294
  "g": "Rotation Pools",
1295
  "icon": "πŸ”„",
1296
  "k": "KILOCODE_API_KEYS",
1297
  "lbl": "KiloCode pool",
1298
+ "type": "text",
1299
+ "tag": "advanced"
1300
  },
1301
+ {
1302
  "g": "Rotation Pools",
1303
  "icon": "πŸ”„",
1304
  "k": "ZAI_API_KEYS",
1305
  "lbl": "Z.ai / GLM pool",
1306
+ "type": "text",
1307
+ "tag": "advanced"
1308
  },
1309
+ {
1310
  "g": "Rotation Pools",
1311
  "icon": "πŸ”„",
1312
  "k": "MOONSHOT_API_KEYS",
1313
+ "lbl": "Moonshot pool (merged with KIMI_API_KEYS into one rotation pool)",
1314
+ "type": "text",
1315
+ "tag": "advanced"
1316
  },
1317
+ {
1318
  "g": "Rotation Pools",
1319
  "icon": "πŸ”„",
1320
  "k": "MINIMAX_API_KEYS",
1321
  "lbl": "MiniMax pool",
1322
+ "type": "text",
1323
+ "tag": "advanced"
1324
  },
1325
+ {
1326
  "g": "Rotation Pools",
1327
  "icon": "πŸ”„",
1328
  "k": "XIAOMI_API_KEYS",
1329
  "lbl": "Xiaomi pool",
1330
+ "type": "text",
1331
+ "tag": "advanced"
1332
  },
1333
+ {
1334
  "g": "Rotation Pools",
1335
  "icon": "πŸ”„",
1336
  "k": "VOLCANO_ENGINE_API_KEYS",
1337
  "lbl": "Volcano Engine pool",
1338
+ "type": "text",
1339
+ "tag": "advanced"
1340
  },
1341
+ {
1342
  "g": "Rotation Pools",
1343
  "icon": "πŸ”„",
1344
  "k": "BYTEPLUS_API_KEYS",
1345
  "lbl": "BytePlus pool",
1346
+ "type": "text",
1347
+ "tag": "advanced"
1348
  },
1349
+ {
1350
  "g": "Rotation Pools",
1351
  "icon": "πŸ”„",
1352
  "k": "MISTRAL_API_KEYS",
1353
  "lbl": "Mistral pool",
1354
+ "type": "text",
1355
+ "tag": "advanced"
1356
  },
1357
+ {
1358
  "g": "Rotation Pools",
1359
  "icon": "πŸ”„",
1360
  "k": "XAI_API_KEYS",
1361
  "lbl": "xAI pool",
1362
+ "type": "text",
1363
+ "tag": "advanced"
1364
  },
1365
+ {
1366
  "g": "Rotation Pools",
1367
  "icon": "πŸ”„",
1368
  "k": "NVIDIA_API_KEYS",
1369
  "lbl": "NVIDIA pool",
1370
+ "type": "text",
1371
+ "tag": "advanced"
1372
  },
1373
+ {
1374
  "g": "Rotation Pools",
1375
  "icon": "πŸ”„",
1376
  "k": "GROQ_API_KEYS",
1377
  "lbl": "Groq pool",
1378
+ "type": "text",
1379
+ "tag": "advanced"
1380
  },
1381
+ {
1382
  "g": "Rotation Pools",
1383
  "icon": "πŸ”„",
1384
  "k": "COHERE_API_KEYS",
1385
  "lbl": "Cohere pool",
1386
+ "type": "text",
1387
+ "tag": "advanced"
1388
  },
1389
+ {
1390
  "g": "Rotation Pools",
1391
  "icon": "πŸ”„",
1392
  "k": "TOGETHER_API_KEYS",
1393
  "lbl": "Together pool",
1394
+ "type": "text",
1395
+ "tag": "advanced"
1396
  },
1397
+ {
1398
  "g": "Rotation Pools",
1399
  "icon": "πŸ”„",
1400
  "k": "CEREBRAS_API_KEYS",
1401
  "lbl": "Cerebras pool",
1402
+ "type": "text",
1403
+ "tag": "advanced"
1404
  },
1405
+ {
1406
  "g": "Rotation Pools",
1407
  "icon": "πŸ”„",
1408
  "k": "HUGGINGFACE_HUB_TOKENS",
1409
  "lbl": "HF token pool",
1410
  "type": "text"
1411
  },
1412
+ {
1413
  "g": "Model Lists",
1414
  "icon": "πŸ“‹",
1415
  "k": "OPENAI_MODELS",
1416
  "lbl": "Visible OpenAI models",
1417
  "type": "model_list",
1418
  "options_key": "OPENAI_MODELS",
1419
+ "ph": "Select models to build a comma list",
1420
+ "tag": "optional"
1421
  },
1422
+ {
1423
  "g": "Model Lists",
1424
  "icon": "πŸ“‹",
1425
  "k": "ANTHROPIC_MODELS",
1426
  "lbl": "Visible Anthropic models",
1427
  "type": "model_list",
1428
  "options_key": "ANTHROPIC_MODELS",
1429
+ "ph": "Select models to build a comma list",
1430
+ "tag": "optional"
1431
  },
1432
+ {
1433
  "g": "Model Lists",
1434
  "icon": "πŸ“‹",
1435
  "k": "GEMINI_MODELS",
1436
  "lbl": "Visible Gemini models",
1437
  "type": "model_list",
1438
  "options_key": "GEMINI_MODELS",
1439
+ "ph": "Select models to build a comma list",
1440
+ "tag": "optional"
1441
  },
1442
+ {
1443
  "g": "Model Lists",
1444
  "icon": "πŸ“‹",
1445
  "k": "DEEPSEEK_MODELS",
1446
  "lbl": "Visible DeepSeek models",
1447
  "type": "model_list",
1448
  "options_key": "DEEPSEEK_MODELS",
1449
+ "ph": "Select models to build a comma list",
1450
+ "tag": "optional"
1451
  },
1452
+ {
1453
  "g": "Model Lists",
1454
  "icon": "πŸ“‹",
1455
  "k": "OPENROUTER_MODELS",
1456
  "lbl": "Visible OpenRouter models",
1457
  "type": "model_list",
1458
  "options_key": "OPENROUTER_MODELS",
1459
+ "ph": "Select models to build a comma list",
1460
+ "tag": "optional"
1461
  },
1462
+ {
1463
  "g": "Model Lists",
1464
  "icon": "πŸ“‹",
1465
  "k": "GROQ_MODELS",
1466
  "lbl": "Visible Groq models",
1467
  "type": "model_list",
1468
  "options_key": "GROQ_MODELS",
1469
+ "ph": "Select models to build a comma list",
1470
+ "tag": "optional"
1471
  },
1472
+ {
1473
  "g": "Model Lists",
1474
  "icon": "πŸ“‹",
1475
  "k": "MISTRAL_MODELS",
1476
  "lbl": "Visible Mistral models",
1477
  "type": "model_list",
1478
  "options_key": "MISTRAL_MODELS",
1479
+ "ph": "Select models to build a comma list",
1480
+ "tag": "optional"
1481
  },
1482
+ {
1483
  "g": "Model Lists",
1484
  "icon": "πŸ“‹",
1485
  "k": "XAI_MODELS",
1486
  "lbl": "Visible xAI models",
1487
  "type": "model_list",
1488
  "options_key": "XAI_MODELS",
1489
+ "ph": "Select models to build a comma list",
1490
+ "tag": "optional"
1491
  },
1492
+ {
1493
  "g": "Model Lists",
1494
  "icon": "πŸ“‹",
1495
  "k": "COHERE_MODELS",
1496
  "lbl": "Visible Cohere models",
1497
  "type": "model_list",
1498
  "options_key": "COHERE_MODELS",
1499
+ "ph": "Select models to build a comma list",
1500
+ "tag": "optional"
1501
  },
1502
+ {
1503
  "g": "Model Lists",
1504
  "icon": "πŸ“‹",
1505
  "k": "TOGETHER_MODELS",
1506
  "lbl": "Visible Together models",
1507
  "type": "model_list",
1508
  "options_key": "TOGETHER_MODELS",
1509
+ "ph": "Select models to build a comma list",
1510
+ "tag": "optional"
1511
  },
1512
+ {
1513
  "g": "Model Lists",
1514
  "icon": "πŸ“‹",
1515
  "k": "CEREBRAS_MODELS",
1516
  "lbl": "Visible Cerebras models",
1517
  "type": "model_list",
1518
  "options_key": "CEREBRAS_MODELS",
1519
+ "ph": "Select models to build a comma list",
1520
+ "tag": "optional"
1521
  },
1522
+ {
1523
  "g": "Model Lists",
1524
  "icon": "πŸ“‹",
1525
  "k": "NVIDIA_MODELS",
1526
  "lbl": "Visible NVIDIA models",
1527
  "type": "model_list",
1528
  "options_key": "NVIDIA_MODELS",
1529
+ "ph": "Select models to build a comma list",
1530
+ "tag": "optional"
1531
  },
1532
+ {
1533
  "g": "Model Lists",
1534
  "icon": "πŸ“‹",
1535
  "k": "KILOCODE_MODELS",
1536
  "lbl": "Visible KiloCode models",
1537
  "type": "model_list",
1538
  "options_key": "KILOCODE_MODELS",
1539
+ "ph": "Select models to build a comma list",
1540
+ "tag": "optional"
1541
  },
1542
+ {
1543
  "g": "Model Lists",
1544
  "icon": "πŸ“‹",
1545
  "k": "OPENCODE_MODELS",
1546
  "lbl": "Visible OpenCode models",
1547
  "type": "model_list",
1548
  "options_key": "OPENCODE_MODELS",
1549
+ "ph": "Select models to build a comma list",
1550
+ "tag": "optional"
1551
  },
1552
+ {
1553
  "g": "Model Lists",
1554
  "icon": "πŸ“‹",
1555
  "k": "ZAI_MODELS",
1556
  "lbl": "Visible Z.ai / GLM models",
1557
  "type": "model_list",
1558
  "options_key": "ZAI_MODELS",
1559
+ "ph": "Select models to build a comma list",
1560
+ "tag": "optional"
1561
  },
1562
+ {
1563
  "g": "Model Lists",
1564
  "icon": "πŸ“‹",
1565
  "k": "MOONSHOT_MODELS",
1566
  "lbl": "Visible Moonshot / Kimi models",
1567
  "type": "model_list",
1568
  "options_key": "MOONSHOT_MODELS",
1569
+ "ph": "Select models to build a comma list",
1570
+ "tag": "optional"
1571
  },
1572
+ {
1573
  "g": "Model Lists",
1574
  "icon": "πŸ“‹",
1575
  "k": "MINIMAX_MODELS",
1576
  "lbl": "Visible MiniMax models",
1577
  "type": "model_list",
1578
  "options_key": "MINIMAX_MODELS",
1579
+ "ph": "Select models to build a comma list",
1580
+ "tag": "optional"
1581
  },
1582
+ {
1583
  "g": "Model Lists",
1584
  "icon": "πŸ“‹",
1585
  "k": "XIAOMI_MODELS",
1586
  "lbl": "Visible Xiaomi models",
1587
  "type": "model_list",
1588
  "options_key": "XIAOMI_MODELS",
1589
+ "ph": "Select models to build a comma list",
1590
+ "tag": "optional"
1591
  },
1592
+ {
1593
  "g": "Model Lists",
1594
  "icon": "πŸ“‹",
1595
  "k": "VOLCANO_ENGINE_MODELS",
1596
  "lbl": "Visible Volcano Engine models",
1597
  "type": "model_list",
1598
  "options_key": "VOLCANO_ENGINE_MODELS",
1599
+ "ph": "Select models to build a comma list",
1600
+ "tag": "optional"
1601
  },
1602
+ {
1603
  "g": "Model Lists",
1604
  "icon": "πŸ“‹",
1605
  "k": "BYTEPLUS_MODELS",
1606
  "lbl": "Visible BytePlus models",
1607
  "type": "model_list",
1608
  "options_key": "BYTEPLUS_MODELS",
1609
+ "ph": "Select models to build a comma list",
1610
+ "tag": "optional"
1611
  },
1612
+ {
1613
  "g": "Model Lists",
1614
  "icon": "πŸ“‹",
1615
  "k": "QIANFAN_MODELS",
1616
  "lbl": "Visible Qianfan models",
1617
  "type": "model_list",
1618
  "options_key": "QIANFAN_MODELS",
1619
+ "ph": "Select models to build a comma list",
1620
+ "tag": "optional"
1621
  },
1622
+ {
1623
  "g": "Model Lists",
1624
  "icon": "πŸ“‹",
1625
  "k": "MODELSTUDIO_MODELS",
1626
  "lbl": "Visible ModelStudio models",
1627
  "type": "model_list",
1628
  "options_key": "MODELSTUDIO_MODELS",
1629
+ "ph": "Select models to build a comma list",
1630
+ "tag": "optional"
1631
  },
1632
+ {
1633
  "g": "Model Lists",
1634
  "icon": "πŸ“‹",
1635
  "k": "KIMI_MODELS",
1636
  "lbl": "Visible Kimi models",
1637
  "type": "model_list",
1638
  "options_key": "KIMI_MODELS",
1639
+ "ph": "Select models to build a comma list",
1640
+ "tag": "optional"
1641
  },
1642
+ {
1643
  "g": "Model Lists",
1644
  "icon": "πŸ“‹",
1645
  "k": "HUGGINGFACE_MODELS",
1646
  "lbl": "Visible Hugging Face models",
1647
  "type": "model_list",
1648
  "options_key": "HUGGINGFACE_MODELS",
1649
+ "ph": "Select models to build a comma list",
1650
+ "tag": "optional"
1651
  },
1652
+ {
1653
  "g": "Model Lists",
1654
  "icon": "πŸ“‹",
1655
  "k": "GITHUB_COPILOT_MODELS",
1656
  "lbl": "Visible GitHub Copilot models",
1657
  "type": "model_list",
1658
  "options_key": "GITHUB_COPILOT_MODELS",
1659
+ "ph": "Select models to build a comma list",
1660
+ "tag": "optional"
1661
  },
1662
+ {
1663
  "g": "Custom Provider",
1664
  "icon": "πŸ”Œ",
1665
  "k": "CUSTOM_PROVIDER_NAME",
1666
  "lbl": "Provider display name",
1667
+ "type": "text",
1668
+ "tag": "feature"
1669
  },
1670
+ {
1671
  "g": "Custom Provider",
1672
  "icon": "πŸ”Œ",
1673
  "k": "CUSTOM_BASE_URL",
1674
  "lbl": "OpenAI-compatible base URL",
1675
+ "type": "text",
1676
+ "tag": "feature"
1677
  },
1678
+ {
1679
  "g": "Custom Provider",
1680
  "icon": "πŸ”Œ",
1681
  "k": "CUSTOM_MODEL_ID",
1682
  "lbl": "Model ID",
1683
+ "type": "text",
1684
+ "ph": "custom model id",
1685
+ "tag": "feature"
1686
  },
1687
+ {
1688
  "g": "Custom Provider",
1689
  "icon": "πŸ”Œ",
1690
  "k": "CUSTOM_MODEL_NAME",
1691
  "lbl": "Friendly model name",
1692
+ "type": "text",
1693
+ "tag": "feature"
1694
  },
1695
+ {
1696
  "g": "Custom Provider",
1697
  "icon": "πŸ”Œ",
1698
  "k": "CUSTOM_API_KEY",
1699
  "lbl": "Provider API key",
1700
  "type": "password",
1701
+ "tag": "credential"
1702
  },
1703
+ {
1704
  "g": "Custom Provider",
1705
  "icon": "πŸ”Œ",
1706
  "k": "CUSTOM_API_TYPE",
 
1713
  "gemini",
1714
  "openrouter"
1715
  ],
1716
+ "ph": "openai-completions",
1717
+ "tag": "feature"
1718
  },
1719
+ {
1720
  "g": "Custom Provider",
1721
  "icon": "πŸ”Œ",
1722
  "k": "CUSTOM_CONTEXT_WINDOW",
1723
  "lbl": "Context window",
1724
  "type": "number",
1725
+ "ph": "128000",
1726
+ "tag": "advanced"
1727
  },
1728
+ {
1729
  "g": "Custom Provider",
1730
  "icon": "πŸ”Œ",
1731
  "k": "CUSTOM_MAX_TOKENS",
1732
  "lbl": "Max output tokens",
1733
  "type": "number",
1734
+ "ph": "8192",
1735
+ "tag": "advanced"
1736
  },
1737
+ {
1738
  "g": "Telegram",
1739
  "icon": "✈️",
1740
  "k": "TELEGRAM_BOT_TOKEN",
1741
  "lbl": "Bot token from BotFather",
1742
  "type": "password",
1743
+ "common": 1,
1744
+ "tag": "credential"
1745
  },
1746
+ {
1747
  "g": "Telegram",
1748
  "icon": "✈️",
1749
  "k": "TELEGRAM_ALLOWED_USERS",
1750
  "lbl": "Allowed user IDs (comma)",
1751
  "type": "text",
1752
  "ph": "123456789,987654321",
1753
+ "common": 1,
1754
+ "tag": "critical"
1755
  },
1756
+ {
1757
+ "g": "Telegram",
1758
+ "icon": "✈️",
1759
+ "k": "TELEGRAM_USER_IDS",
1760
+ "lbl": "Telegram user IDs (comma)",
1761
+ "type": "text",
1762
+ "tag": "optional"
1763
+ },
1764
+ {
1765
  "g": "Deployment",
1766
  "icon": "🧭",
1767
  "k": "APP_BASE",
1768
  "lbl": "Public app base path",
1769
  "type": "text",
1770
+ "ph": "/app",
1771
+ "tag": "advanced"
1772
  },
1773
+ {
1774
  "g": "Deployment",
1775
  "icon": "🧭",
1776
  "k": "SPACE_AUTHOR_NAME",
1777
  "lbl": "HF Space author name",
1778
+ "type": "text",
1779
+ "tag": "optional"
1780
  },
1781
+ {
1782
  "g": "Deployment",
1783
  "icon": "🧭",
1784
  "k": "SPACE_HOST",
1785
  "lbl": "HF Space host domain",
1786
+ "type": "text",
1787
+ "tag": "optional"
1788
  },
1789
+ {
1790
  "g": "Deployment",
1791
  "icon": "🧭",
1792
  "k": "PORT",
1793
  "lbl": "Public dashboard port",
1794
  "type": "number",
1795
+ "ph": "7861",
1796
+ "tag": "advanced"
1797
  },
1798
+ {
1799
  "g": "Deployment",
1800
  "icon": "🧭",
1801
  "k": "GATEWAY_PORT",
1802
  "lbl": "OpenClaw internal port",
1803
  "type": "number",
1804
+ "ph": "7860",
1805
+ "tag": "advanced"
1806
  },
1807
+ {
1808
  "g": "Deployment",
1809
  "icon": "🧭",
1810
  "k": "JUPYTER_PORT",
1811
  "lbl": "Jupyter internal port",
1812
  "type": "number",
1813
+ "ph": "8888",
1814
+ "tag": "advanced"
1815
  },
1816
+ {
1817
  "g": "Deployment",
1818
  "icon": "🧭",
1819
  "k": "JUPYTER_BASE",
1820
  "lbl": "Jupyter public base path",
1821
  "type": "text",
1822
+ "ph": "/terminal",
1823
+ "tag": "advanced"
1824
+ },
1825
+ {
1826
+ "g": "Rotation Pools",
1827
+ "icon": "πŸ”„",
1828
+ "k": "AI_GATEWAY_API_KEYS",
1829
+ "lbl": "AI Gateway pool (comma-sep)",
1830
+ "type": "text",
1831
+ "tag": "advanced"
1832
+ },
1833
+ {
1834
+ "g": "Rotation Pools",
1835
+ "icon": "πŸ”„",
1836
+ "k": "COPILOT_GITHUB_TOKENS",
1837
+ "lbl": "GitHub Copilot token pool",
1838
+ "type": "text",
1839
+ "tag": "advanced"
1840
+ },
1841
+ {
1842
+ "g": "Rotation Pools",
1843
+ "icon": "πŸ”„",
1844
+ "k": "KIMI_API_KEYS",
1845
+ "lbl": "Kimi pool (merged with MOONSHOT_API_KEYS into one rotation pool)",
1846
+ "type": "text",
1847
+ "tag": "advanced"
1848
+ },
1849
+ {
1850
+ "g": "Rotation Pools",
1851
+ "icon": "πŸ”„",
1852
+ "k": "MODELSTUDIO_API_KEYS",
1853
+ "lbl": "ModelStudio pool",
1854
+ "type": "text",
1855
+ "tag": "advanced"
1856
+ },
1857
+ {
1858
+ "g": "Rotation Pools",
1859
+ "icon": "πŸ”„",
1860
+ "k": "QIANFAN_API_KEYS",
1861
+ "lbl": "Qianfan pool",
1862
+ "type": "text",
1863
+ "tag": "advanced"
1864
+ },
1865
+ {
1866
+ "g": "Rotation Pools",
1867
+ "icon": "πŸ”„",
1868
+ "k": "SYNTHETIC_API_KEYS",
1869
+ "lbl": "Synthetic pool",
1870
+ "type": "text",
1871
+ "tag": "advanced"
1872
+ },
1873
+ {
1874
+ "g": "Rotation Pools",
1875
+ "icon": "πŸ”„",
1876
+ "k": "VENICE_API_KEYS",
1877
+ "lbl": "Venice pool",
1878
+ "type": "text",
1879
+ "tag": "advanced"
1880
+ },
1881
+ {
1882
+ "g": "Model Lists",
1883
+ "icon": "πŸ“‹",
1884
+ "k": "VENICE_MODELS",
1885
+ "lbl": "Visible Venice models",
1886
+ "type": "model_list",
1887
+ "options_key": "VENICE_MODELS",
1888
+ "ph": "Select models to build a comma list",
1889
+ "tag": "optional"
1890
+ },
1891
+ {
1892
+ "g": "Model Lists",
1893
+ "icon": "πŸ“‹",
1894
+ "k": "SYNTHETIC_MODELS",
1895
+ "lbl": "Visible Synthetic models",
1896
+ "type": "model_list",
1897
+ "options_key": "SYNTHETIC_MODELS",
1898
+ "ph": "Select models to build a comma list",
1899
+ "tag": "optional"
1900
  }
1901
+ ]
1902
 
1903
  const ICONS = {
1904
+ All:'🏠', Core:'⚑', Startup:'πŸš€', DevData:'πŸ§ͺ', WhatsApp:'πŸ’¬',
1905
+ Cloudflare:'☁️', Gateway:'πŸ”€', Logging:'πŸ“', Network:'🌐', Plugins:'πŸ”Œ',
1906
+ Deployment:'🧭', 'Provider Keys':'πŸ”‘', 'Rotation Pools':'πŸ”„',
1907
+ 'Model Lists':'πŸ“‹', 'Custom Provider':'🧩', Telegram:'✈️',
1908
+ Backup:'πŸ’Ύ', Runtime:'βš™οΈ', Integrations:'πŸ”—', 'Custom Env':'πŸ”§'
1909
  };
 
1910
  const $ = id => document.getElementById(id);
1911
  const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({
1912
  '&': '&amp;',
 
2043
  }
2044
 
2045
  function valueControlHTML(field) {
2046
+ if (!field || !field.k) return '<span style="color:red">Invalid field</span>';
2047
  const key = esc(field.k);
2048
  const placeholder = esc(field.ph || field.lbl || '');
2049
  const isSecret = !!field.secret;
 
2083
  ${control}
2084
  </div>`;
2085
 
 
2086
  }
2087
 
2088
+ function cardHTML(f, origIdx = 0) {
2089
+ const TAG_META = {
2090
+ critical: { cls: 'badge-critical', lbl: 'critical' },
2091
+ credential: { cls: 'badge-credential', lbl: 'credential' },
2092
+ feature: { cls: 'badge-feature', lbl: 'feature' },
2093
+ optional: { cls: 'badge-optional', lbl: 'optional' },
2094
+ advanced: { cls: 'badge-advanced', lbl: 'advanced' },
2095
+ build: { cls: 'badge-build', lbl: 'build-time' },
2096
+ };
2097
+ const tm = TAG_META[f.tag] || TAG_META.optional;
2098
+ const badge = `<span class="badge ${tm.cls}">${tm.lbl}</span>`;
2099
 
2100
+ return `<div class="env-card" data-row data-orig-idx="${origIdx}" data-group="${esc(f.g)}" data-search="${esc((f.g + ' ' + f.k + ' ' + (f.lbl || '') + ' ' + (f.tag || '')).toLowerCase())}" data-tag="${esc(f.tag || 'optional')}">
2101
  <div class="card-top">
2102
  <input type="checkbox" class="card-check" data-check="${esc(f.k)}" ${f.common ? 'data-common="1"' : ''}>
2103
  <div class="card-info">
 
2175
  return obj;
2176
  }
2177
 
2178
+ function generateBundle() {
2179
  const obj = collect();
2180
  const keys = Object.keys(obj).sort();
2181
  const bundle = keys.length ? encodeBundle(Object.fromEntries(keys.map(k => [k, obj[k]]))) : '';
 
2182
  $('bundleOut').value = bundle;
2183
  $('envLineOut').value = bundle ? `HUGGINGCLAW_ENV_BUNDLE=${bundle}` : '';
2184
+ }
2185
 
2186
+ function refresh() {
2187
+ const obj = collect();
2188
+ const keys = Object.keys(obj).sort();
2189
  const s = $('summary');
2190
  if (keys.length) {
2191
  s.innerHTML = `<strong>${keys.length}</strong> variable${keys.length > 1 ? 's' : ''} selected<div class="sum-keys">${keys.map(k => `<span class="sum-key">${esc(k)}</span>`).join('')}</div>`;
 
2274
  addCustomRow(key, val, true);
2275
  }
2276
  }
2277
+ sortAllSections(); markSelected(); filter(); refresh();
2278
  }
2279
 
2280
  function autoCheck(key) {
 
2363
  const chk = document.querySelector(`[data-check="${CSS.escape(key)}"]`);
2364
  if (chk) {
2365
  chk.checked = on;
2366
+ sortSection(inp.closest('[data-row]'));
2367
  markSelected();
2368
  }
2369
  refresh();
2370
  }
2371
 
2372
+ function sortSection(cardEl) {
2373
+ const cards = cardEl && cardEl.closest('.cards');
2374
+ if (!cards) return;
2375
+ const all = [...cards.querySelectorAll('[data-row]')];
2376
+ const checked = all.filter(c => c.querySelector('[data-check]')?.checked);
2377
+ const rest = all.filter(c => !c.querySelector('[data-check]')?.checked);
2378
+ rest.sort((a, b) => Number(a.dataset.origIdx) - Number(b.dataset.origIdx));
2379
+ [...checked, ...rest].forEach(c => cards.appendChild(c));
2380
+ }
2381
+
2382
+ function sortAllSections() {
2383
+ document.querySelectorAll('.cards').forEach(cards => {
2384
+ const all = [...cards.querySelectorAll('[data-row]')];
2385
+ const checked = all.filter(c => c.querySelector('[data-check]')?.checked);
2386
+ const rest = all.filter(c => !c.querySelector('[data-check]')?.checked);
2387
+ rest.sort((a, b) => Number(a.dataset.origIdx) - Number(b.dataset.origIdx));
2388
+ [...checked, ...rest].forEach(c => cards.appendChild(c));
2389
+ });
2390
+ }
2391
+
2392
  function bindFieldEvents() {
2393
+ document.querySelectorAll('[data-check]').forEach(el => el.addEventListener('change', () => { sortSection(el.closest('[data-row]')); markSelected(); refresh(); }));
2394
  document.querySelectorAll('[data-key]').forEach(el => el.addEventListener('input', refresh));
2395
  document.querySelectorAll('[data-toggle]').forEach(btn => btn.addEventListener('click', () => toggleField(btn.dataset.toggle)));
2396
  document.querySelectorAll('[data-pick-for]').forEach(sel => sel.addEventListener('change', () => handlePickerChange(sel)));
 
2400
 
2401
  function renderSections() {
2402
  const grouped = {};
2403
+ FIELDS.forEach(f => {
2404
+ if (!f || !f.g || !f.k) return;
2405
+ (grouped[f.g] ||= []).push(f);
2406
+ });
2407
 
2408
  const wrap = $('sections');
2409
+ if (!wrap) return;
2410
  wrap.innerHTML = '';
2411
  Object.entries(grouped).forEach(([grp, items]) => {
2412
+ try {
2413
+ const sec = document.createElement('div');
2414
+ sec.className = 'sec';
2415
+ sec.dataset.section = grp;
2416
+ sec.innerHTML = `
2417
+ <div class="sec-header">
2418
+ <span class="sec-icon">${ICONS[grp] || 'πŸ“'}</span>
2419
+ <span class="sec-title">${esc(grp)}</span>
2420
+ <span class="sec-count">${items.length}</span>
2421
+ <div class="sec-line"></div>
2422
+ </div>
2423
+ <div class="cards">${items.map((f, i) => { try { return cardHTML(f, i); } catch(e) { console.error('cardHTML error for field', f.k, e); return ''; } }).join('')}</div>`;
2424
+ wrap.appendChild(sec);
2425
+ } catch(e) {
2426
+ console.error('renderSections error for group', grp, e);
2427
+ }
2428
  });
2429
  bindFieldEvents();
2430
  }
 
2447
  }
2448
 
2449
  // ── Init ──
2450
+ try {
2451
+ renderSidebar();
2452
+ renderSections();
2453
+ addCustomRow();
2454
+ filter();
2455
+ refresh();
2456
+ } catch(e) {
2457
+ console.error('HuggingClaw ENV Builder init error:', e);
2458
+ const wrap = document.getElementById('sections');
2459
+ if (wrap) wrap.innerHTML = '<div style="color:red;padding:20px">ENV Builder failed to load. Open browser console for details. Error: ' + e.message + '</div>';
2460
+ }
2461
 
2462
  // ── Events ──
2463
  $('search').oninput = filter;
2464
+ $('selectRequired').onclick = () => {
2465
+ document.querySelectorAll('[data-row][data-tag="critical"] [data-check]').forEach(c => c.checked = true);
2466
+ sortAllSections();
2467
+ markSelected();
2468
+ refresh();
2469
+ };
2470
  $('selectCommon').onclick = () => {
2471
  document.querySelectorAll('[data-common="1"]').forEach(c => c.checked = true);
2472
+ sortAllSections();
2473
  markSelected();
2474
  refresh();
2475
  };
2476
  $('selectVisible').onclick = () => {
2477
  document.querySelectorAll('.sec:not(.sec-hidden) [data-row]:not(.hidden) [data-check]').forEach(c => c.checked = true);
2478
+ sortAllSections();
2479
  markSelected();
2480
  refresh();
2481
  };
2482
  $('clearAll').onclick = () => {
2483
  clearForm();
2484
+ sortAllSections();
2485
  markSelected();
2486
  filter();
2487
  refresh();
2488
  };
2489
  $('applyImport').onclick = () => {
2490
  try {
2491
+ const parsed = parseEnv($('importText').value);
2492
+ const count = Object.keys(parsed).length;
2493
+ if (!count) {
2494
+ showToast('No valid env keys found');
2495
+ return;
2496
+ }
2497
+ applyObj(parsed, true);
2498
+ showToast(`Imported ${count} key${count > 1 ? 's' : ''} βœ“`);
2499
  } catch (e) {
2500
  showToast('Import failed');
2501
  alert(e.message);
2502
  }
2503
  };
2504
 
2505
+ // Import is explicit via the Import & Apply button to avoid surprising UI resets.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2506
  $('addCustom').onclick = () => addCustomRow();
2507
  $('applyBundle').onclick = () => {
2508
  try {
 
2512
  showToast('Invalid bundle');
2513
  }
2514
  };
2515
+ $('generateBundle').onclick = () => generateBundle();
2516
  $('copyBundle').onclick = () => copyText($('bundleOut').value);
2517
  $('copyEnvLine').onclick = () => copyText($('envLineOut').value);
2518
  $('copyJson').onclick = () => copyText(JSON.stringify(collect(), null, 2));
health-server.js CHANGED
@@ -25,10 +25,15 @@ const GATEWAY_TOKEN = (process.env.GATEWAY_TOKEN || "").trim();
25
  const SESSION_COOKIE = "hc_session";
26
  const LOGIN_PATH = "/login";
27
  const DEV_MODE_ENABLED = isTrue(process.env.DEV_MODE);
28
- // Default true. Only false when DEV_MODE=false or HUGGINGCLAW_JUPYTER_ENABLED=false is explicitly set.
 
 
29
  const JUPYTER_ENABLED =
30
- !/^(false|0|no|off)$/i.test(String(process.env.DEV_MODE || "").trim()) &&
31
- !/^(false|0|no|off)$/i.test(String(process.env.HUGGINGCLAW_JUPYTER_ENABLED || "").trim());
 
 
 
32
  const startTime = Date.now();
33
  const LLM_MODEL = process.env.LLM_MODEL || "Not Set";
34
  const LLM_PROVIDER = LLM_MODEL.includes("/") ? LLM_MODEL.split("/")[0] : "";
@@ -60,50 +65,134 @@ function deriveHfSpaceUrl() {
60
  return "";
61
  }
62
  const HF_SPACE_URL = deriveHfSpaceUrl();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
- // Auto-detect space privacy via HF API at startup.
65
- // Caches result so every request doesn't hit the API.
66
- let SPACE_IS_PRIVATE = false;
67
  async function detectSpacePrivacy() {
68
- if (!SPACE_ID) return;
69
- try {
70
- const token = (process.env.HF_TOKEN || "").trim();
71
- const reqOptions = {
72
- hostname: "huggingface.co",
73
- path: `/api/spaces/${SPACE_ID}`,
74
- method: "GET",
75
- headers: Object.assign(
76
- { "User-Agent": "HuggingClaw/health-server" },
77
- token ? { Authorization: `Bearer ${token}` } : {}
78
- ),
79
- };
80
- await new Promise((resolve) => {
81
- const r = https.request(reqOptions, (res) => {
82
- let body = "";
83
- res.on("data", (chunk) => { body += chunk; });
84
- res.on("end", () => {
85
- try {
86
- if (res.statusCode === 200) {
87
- const data = JSON.parse(body);
88
- SPACE_IS_PRIVATE = data.private === true;
89
- } else if (res.statusCode === 404 && !token) {
90
- // 404 with no token usually means private space
91
- SPACE_IS_PRIVATE = true;
92
- }
93
- } catch {}
94
- resolve();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  });
 
 
 
96
  });
97
- r.on("error", resolve);
98
- r.setTimeout(5000, () => { r.destroy(); resolve(); });
99
- r.end();
100
- });
101
- console.log(`[health-server] Space privacy detected: ${SPACE_IS_PRIVATE ? "private" : "public"}`);
102
- } catch {
103
- // Network error β€” default to false (safe)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  }
 
 
 
 
 
 
 
 
 
 
105
  }
106
- detectSpacePrivacy();
107
  const CLOUDFLARE_KEEPALIVE_STATUS_FILE =
108
  "/tmp/huggingclaw-cloudflare-keepalive-status.json";
109
 
@@ -349,15 +438,63 @@ function renderDashboard(data) {
349
  <a class="hero-action env" data-space-link="env-builder" href="/env-builder">βš™οΈ Env Builder β†’</a>
350
  </div>
351
  <section class="overview">${tilesHtml}</section>
352
- <footer>Built by <a href="https://github.com/somratpro" target="_blank" rel="noopener noreferrer" style="color:inherit;text-decoration:none">@somratpro</a>${JUPYTER_ENABLED ? " Β· Terminal by JupyterLab" : ""}</footer>
353
  </main>
354
  <script>
355
  document.querySelectorAll('.local-time').forEach(el=>{const d=new Date(el.getAttribute('data-iso'));if(!isNaN(d))el.textContent='At '+d.toLocaleTimeString()});
356
  const inEmbeddedApp = (() => { try { return window.top !== window.self; } catch { return true; } })();
357
  const isDirectHfSpaceHost = /\.hf\.space$/i.test(window.location.hostname);
358
  const HF_SPACE_URL = ${JSON.stringify(HF_SPACE_URL)};
359
- const SPACE_IS_PRIVATE = ${JSON.stringify(SPACE_IS_PRIVATE)};
360
- // ── Private Space Guard ──
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  // Direct .hf.space access outside the HF App iframe has no valid session cookie
362
  // for private spaces β€” HF CDN returns 404 before the request reaches the container.
363
  // Redirect users to huggingface.co/spaces/... which authenticates them properly.
@@ -368,18 +505,6 @@ function renderDashboard(data) {
368
  document.body.appendChild(notice);
369
  setTimeout(() => { window.location.replace(HF_SPACE_URL); }, 300);
370
  }
371
- // If inside the HF App iframe, force new-tab navigation so users can break out
372
- // to the standalone Space host. Also keep direct .hf.space behavior opening new tabs.
373
- const openInNewTab = inEmbeddedApp || isDirectHfSpaceHost;
374
- document.querySelectorAll('a[data-space-link]').forEach((a) => {
375
- if (openInNewTab) {
376
- a.setAttribute('target', '_blank');
377
- a.setAttribute('rel', 'noopener noreferrer');
378
- } else {
379
- a.removeAttribute('target');
380
- a.removeAttribute('rel');
381
- }
382
- });
383
  </script>
384
  </body></html>`;
385
  }
@@ -388,7 +513,6 @@ function renderPrivateRedirect(targetUrl) {
388
  const safeUrl = escapeHtml(targetUrl);
389
  return `<!doctype html><html lang="en"><head>
390
  <meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/>
391
- <meta http-equiv="refresh" content="3;url=${safeUrl}"/>
392
  <title>HuggingClaw β€” Private Space</title>
393
  <style>
394
  :root{color-scheme:dark}
@@ -411,8 +535,13 @@ function renderPrivateRedirect(targetUrl) {
411
  <div class="sub">Redirecting in 3 seconds&hellip;</div>
412
  </div>
413
  <script>
414
- // Immediate redirect if JS available β€” don't wait for meta refresh
415
- setTimeout(() => { window.location.replace(${JSON.stringify(targetUrl)}); }, 100);
 
 
 
 
 
416
  </script>
417
  </body></html>`;
418
  }
@@ -513,6 +642,15 @@ function proxyHTTP(req, res, targetHost, targetPort, options = {}) {
513
  const server = http.createServer(async (req, res) => {
514
  const { pathname } = parseRequestUrl(req.url);
515
 
 
 
 
 
 
 
 
 
 
516
  if (pathname === "/health") {
517
  const gatewayReady = await probePort(GATEWAY_HOST, GATEWAY_PORT, "/health");
518
  res.writeHead(gatewayReady ? 200 : 503, { "Content-Type": "application/json" });
@@ -545,11 +683,45 @@ const server = http.createServer(async (req, res) => {
545
  // and WebSocket upgrades pass through untouched.
546
  // /health and /status are always exempt so uptime monitors keep working.
547
  const isHtmlRequest = (req.headers.accept || "").includes("text/html");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
548
  const isDirectHfSpaceRequest = SPACE_IS_PRIVATE &&
 
549
  HF_SPACE_URL &&
550
  isHtmlRequest &&
551
  typeof req.headers.host === "string" &&
552
- req.headers.host.endsWith(".hf.space");
 
 
553
 
554
  if (pathname === LOGIN_PATH) {
555
  if (isAuthorized(req)) {
@@ -587,7 +759,7 @@ const server = http.createServer(async (req, res) => {
587
 
588
  if (pathname === "/env-builder" || pathname === "/env-builder/") {
589
  if (isDirectHfSpaceRequest) {
590
- res.writeHead(200, { "Content-Type": "text/html" });
591
  return res.end(renderPrivateRedirect(HF_SPACE_URL));
592
  }
593
  if (!requireAuth(req, res)) return;
@@ -599,7 +771,7 @@ const server = http.createServer(async (req, res) => {
599
  if (!requireAuth(req, res)) return;
600
  try {
601
  const js = fs.readFileSync(require("path").join(__dirname, "env-builder.js"), "utf8");
602
- res.writeHead(200, { "Content-Type": "application/javascript" });
603
  return res.end(js);
604
  } catch (exc) {
605
  res.writeHead(404, { "Content-Type": "text/plain" });
@@ -608,6 +780,7 @@ const server = http.createServer(async (req, res) => {
608
  }
609
 
610
  if (pathname === "/" || pathname === "/dashboard") {
 
611
  if (isDirectHfSpaceRequest) {
612
  res.writeHead(200, { "Content-Type": "text/html" });
613
  return res.end(renderPrivateRedirect(HF_SPACE_URL));
 
25
  const SESSION_COOKIE = "hc_session";
26
  const LOGIN_PATH = "/login";
27
  const DEV_MODE_ENABLED = isTrue(process.env.DEV_MODE);
28
+ // Explicit HUGGINGCLAW_JUPYTER_ENABLED=true enables Jupyter.
29
+ // Otherwise DEV_MODE=true enables it unless HUGGINGCLAW_JUPYTER_ENABLED is explicitly false.
30
+ // HUGGINGCLAW_JUPYTER_ENABLED=true is the explicit user override and always wins.
31
  const JUPYTER_ENABLED =
32
+ /^(true|1|yes|on)$/i.test(String(process.env.HUGGINGCLAW_JUPYTER_ENABLED || "").trim()) ||
33
+ (
34
+ isTrue(process.env.DEV_MODE) &&
35
+ !/^(false|0|no|off)$/i.test(String(process.env.HUGGINGCLAW_JUPYTER_ENABLED || "").trim())
36
+ );
37
  const startTime = Date.now();
38
  const LLM_MODEL = process.env.LLM_MODEL || "Not Set";
39
  const LLM_PROVIDER = LLM_MODEL.includes("/") ? LLM_MODEL.split("/")[0] : "";
 
65
  return "";
66
  }
67
  const HF_SPACE_URL = deriveHfSpaceUrl();
68
+ const _privacyWaitRaw = Number(process.env.PRIVACY_DETECTION_WAIT_MS || "1500");
69
+ const PRIVACY_DETECTION_WAIT_MS = Number.isFinite(_privacyWaitRaw)
70
+ ? Math.max(0, Math.floor(_privacyWaitRaw))
71
+ : 1500;
72
+
73
+ // ── Privacy Detection ──
74
+ // Priority order:
75
+ // 1. SPACE_PRIVACY env var ("public" / "private") β€” explicit user override, most reliable
76
+ // 2. HF API call to huggingface.co β€” auto-detect
77
+ // 3. Fail-secure default: treat as private if SPACE_ID is set
78
+
79
+ // 1. Check explicit env var override first
80
+ const _spacPrivacyEnv = (process.env.SPACE_PRIVACY || "").trim().toLowerCase();
81
+ let SPACE_IS_PRIVATE;
82
+ let _privacyDetectionDone = false;
83
+ let _privacyDetectionResolve;
84
+ const privacyDetectionReady = new Promise((res) => { _privacyDetectionResolve = res; });
85
+
86
+ if (_spacPrivacyEnv === "public") {
87
+ // User explicitly set SPACE_PRIVACY=public β€” skip API call entirely
88
+ SPACE_IS_PRIVATE = false;
89
+ _privacyDetectionDone = true;
90
+ console.log("[health-server] Space privacy: public (SPACE_PRIVACY env var override)");
91
+ _privacyDetectionResolve && _privacyDetectionResolve();
92
+ } else if (_spacPrivacyEnv === "private") {
93
+ // User explicitly set SPACE_PRIVACY=private β€” skip API call entirely
94
+ SPACE_IS_PRIVATE = true;
95
+ _privacyDetectionDone = true;
96
+ console.log("[health-server] Space privacy: private (SPACE_PRIVACY env var override)");
97
+ _privacyDetectionResolve && _privacyDetectionResolve();
98
+ } else {
99
+ // 2. Auto-detect via HF API (with fail-secure default)
100
+ // Default to private if SPACE_ID is set β€” gets corrected by API call below.
101
+ SPACE_IS_PRIVATE = !!SPACE_ID;
102
+ }
103
 
 
 
 
104
  async function detectSpacePrivacy() {
105
+ // Skip if already resolved via env var
106
+ if (_spacPrivacyEnv === "public" || _spacPrivacyEnv === "private") return;
107
+ // Skip if not running on HF Spaces
108
+ if (!SPACE_ID) {
109
+ SPACE_IS_PRIVATE = false;
110
+ _privacyDetectionDone = true;
111
+ _privacyDetectionResolve();
112
+ return;
113
+ }
114
+
115
+ const token = (process.env.HF_TOKEN || process.env.HUGGINGFACE_HUB_TOKEN || "").trim();
116
+ const reqOptions = {
117
+ hostname: "huggingface.co",
118
+ path: `/api/spaces/${SPACE_ID}`,
119
+ method: "GET",
120
+ headers: Object.assign(
121
+ { "User-Agent": "HuggingClaw/health-server" },
122
+ token ? { Authorization: `Bearer ${token}` } : {}
123
+ ),
124
+ };
125
+
126
+ // Retry up to 5 times with increasing delay β€” covers transient failures at boot
127
+ const MAX_ATTEMPTS = 5;
128
+ let detected = false;
129
+
130
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
131
+ try {
132
+ const result = await new Promise((resolve) => {
133
+ const r = https.request(reqOptions, (apiRes) => {
134
+ let body = "";
135
+ apiRes.on("data", (chunk) => { body += chunk; });
136
+ apiRes.on("end", () => {
137
+ try {
138
+ if (apiRes.statusCode === 200) {
139
+ const data = JSON.parse(body);
140
+ // API confirmed privacy status
141
+ SPACE_IS_PRIVATE = data.private === true;
142
+ resolve({ ok: true, status: apiRes.statusCode });
143
+ } else if (apiRes.statusCode === 401 || apiRes.statusCode === 403) {
144
+ // 401/403 on /api/spaces means the space IS private and our token
145
+ // is missing or wrong. Mark as private.
146
+ SPACE_IS_PRIVATE = true;
147
+ resolve({ ok: true, status: apiRes.statusCode, forcedPrivate: true });
148
+ } else if (apiRes.statusCode === 404) {
149
+ // Space not found β€” shouldn't happen but treat as non-blocking; default stays.
150
+ resolve({ ok: false, status: apiRes.statusCode });
151
+ } else {
152
+ // Other non-200 β€” transient; retry
153
+ resolve({ ok: false, status: apiRes.statusCode });
154
+ }
155
+ } catch { resolve({ ok: false, status: apiRes.statusCode }); }
156
+ });
157
  });
158
+ r.on("error", (err) => resolve({ ok: false, error: err.message }));
159
+ r.setTimeout(8000, () => { r.destroy(); resolve({ ok: false, error: "timeout" }); });
160
+ r.end();
161
  });
162
+
163
+ console.log(`[health-server] Privacy detection attempt ${attempt}/${MAX_ATTEMPTS}: status=${result.status || "network-error"} ok=${result.ok}`);
164
+
165
+ if (result.ok) { detected = true; break; }
166
+ } catch (err) {
167
+ console.warn(`[health-server] Privacy detection attempt ${attempt} threw: ${err.message}`);
168
+ }
169
+
170
+ const delay = Math.min(2000 * attempt, 10000); // 2s, 4s, 6s, 8s, 10s
171
+ if (attempt < MAX_ATTEMPTS) {
172
+ await new Promise((r) => setTimeout(r, delay));
173
+ }
174
+ }
175
+
176
+ if (!detected) {
177
+ console.warn(
178
+ `[health-server] Privacy detection failed after ${MAX_ATTEMPTS} attempts β€” ` +
179
+ `defaulting to ${SPACE_IS_PRIVATE ? "private" : "public"}. ` +
180
+ `TIP: Set SPACE_PRIVACY=public (or private) in your Space secrets to skip API detection.`
181
+ );
182
+ } else {
183
+ console.log(`[health-server] Space privacy detected via HF API: ${SPACE_IS_PRIVATE ? "private" : "public"}`);
184
  }
185
+
186
+ _privacyDetectionDone = true;
187
+ _privacyDetectionResolve();
188
+ }
189
+
190
+ // Only run API detection if env var override not used
191
+ if (_spacPrivacyEnv !== "public" && _spacPrivacyEnv !== "private") {
192
+ detectSpacePrivacy();
193
+ // Re-check every 5 minutes so runtime public↔private changes are picked up
194
+ setInterval(detectSpacePrivacy, 5 * 60 * 1000);
195
  }
 
196
  const CLOUDFLARE_KEEPALIVE_STATUS_FILE =
197
  "/tmp/huggingclaw-cloudflare-keepalive-status.json";
198
 
 
438
  <a class="hero-action env" data-space-link="env-builder" href="/env-builder">βš™οΈ Env Builder β†’</a>
439
  </div>
440
  <section class="overview">${tilesHtml}</section>
441
+ <footer>Built by <a href="https://github.com/somratpro" target="_blank" rel="noopener noreferrer" style="color:inherit;text-decoration:none">@somratpro</a>${JUPYTER_ENABLED ? " Β· Terminal by JupyterLab" : ""}<br>Env Builder &amp; JupyterLab integration by<br><a href="https://github.com/anurag008w" target="_blank" rel="noopener noreferrer" style="color:inherit;text-decoration:none">@anurag</a></footer>
442
  </main>
443
  <script>
444
  document.querySelectorAll('.local-time').forEach(el=>{const d=new Date(el.getAttribute('data-iso'));if(!isNaN(d))el.textContent='At '+d.toLocaleTimeString()});
445
  const inEmbeddedApp = (() => { try { return window.top !== window.self; } catch { return true; } })();
446
  const isDirectHfSpaceHost = /\.hf\.space$/i.test(window.location.hostname);
447
  const HF_SPACE_URL = ${JSON.stringify(HF_SPACE_URL)};
448
+ // Server-side detected value (may be stale if page was cached β€” see /api/is-private)
449
+ let SPACE_IS_PRIVATE = ${JSON.stringify(SPACE_IS_PRIVATE)};
450
+
451
+ function applyLinkTargets() {
452
+ // Keep hero buttons in-frame for private spaces; open new tab for public spaces
453
+ // accessed via the HF iframe or directly at .hf.space.
454
+ const openInNewTab = !SPACE_IS_PRIVATE && (inEmbeddedApp || isDirectHfSpaceHost);
455
+ document.querySelectorAll('a[data-space-link]').forEach((a) => {
456
+ if (openInNewTab) {
457
+ a.setAttribute('target', '_blank');
458
+ a.setAttribute('rel', 'noopener noreferrer');
459
+ } else {
460
+ a.removeAttribute('target');
461
+ a.removeAttribute('rel');
462
+ }
463
+ });
464
+ }
465
+
466
+ applyLinkTargets();
467
+
468
+ // Always re-fetch the live privacy status from the server to handle:
469
+ // 1. Startup race condition where server rendered before API detection finished
470
+ // 2. Any mismatch between client-rendered value and actual server-side state
471
+ // 3. Public spaces where the fail-secure default (private) needs correcting
472
+ // Also retries after 4s in case the first fetch raced with a server-side retry.
473
+ function syncPrivacy() {
474
+ return fetch('/api/is-private', { cache: 'no-store' })
475
+ .then(r => r.json())
476
+ .then(d => {
477
+ if (d.isPrivate !== SPACE_IS_PRIVATE) {
478
+ SPACE_IS_PRIVATE = d.isPrivate;
479
+ applyLinkTargets(); // re-run: adds or removes target="_blank" on buttons
480
+ }
481
+ return d.isPrivate;
482
+ })
483
+ .catch(() => SPACE_IS_PRIVATE);
484
+ }
485
+
486
+ if (isDirectHfSpaceHost) {
487
+ // Immediate check on page load
488
+ syncPrivacy().then(isPrivate => {
489
+ // If space appears private after first check, re-verify after server retries
490
+ // complete (server retries up to 3Γ—5s = ~15s). This catches the edge case
491
+ // where a PUBLIC space returned private due to a transient API failure.
492
+ if (isPrivate) {
493
+ setTimeout(syncPrivacy, 8000);
494
+ setTimeout(syncPrivacy, 16000);
495
+ }
496
+ });
497
+ }
498
  // Direct .hf.space access outside the HF App iframe has no valid session cookie
499
  // for private spaces β€” HF CDN returns 404 before the request reaches the container.
500
  // Redirect users to huggingface.co/spaces/... which authenticates them properly.
 
505
  document.body.appendChild(notice);
506
  setTimeout(() => { window.location.replace(HF_SPACE_URL); }, 300);
507
  }
 
 
 
 
 
 
 
 
 
 
 
 
508
  </script>
509
  </body></html>`;
510
  }
 
513
  const safeUrl = escapeHtml(targetUrl);
514
  return `<!doctype html><html lang="en"><head>
515
  <meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/>
 
516
  <title>HuggingClaw β€” Private Space</title>
517
  <style>
518
  :root{color-scheme:dark}
 
535
  <div class="sub">Redirecting in 3 seconds&hellip;</div>
536
  </div>
537
  <script>
538
+ // Only auto-redirect when NOT inside an iframe (e.g. HF App tab embeds this
539
+ // page in an iframe; navigating that iframe to huggingface.co is blocked by
540
+ // X-Frame-Options and causes "refused to connect" in the browser).
541
+ const _inFrame = (() => { try { return window.top !== window.self; } catch { return true; } })();
542
+ if (!_inFrame) {
543
+ setTimeout(() => { window.location.replace(${JSON.stringify(targetUrl)}); }, 100);
544
+ }
545
  </script>
546
  </body></html>`;
547
  }
 
642
  const server = http.createServer(async (req, res) => {
643
  const { pathname } = parseRequestUrl(req.url);
644
 
645
+ // Lightweight endpoint for client-side fallback detection.
646
+ // Called by the dashboard JS if it suspects the server-rendered SPACE_IS_PRIVATE
647
+ // value was stale (race condition at startup). No auth required β€” it's not sensitive.
648
+ if (pathname === "/api/is-private") {
649
+ if (!_privacyDetectionDone) await privacyDetectionReady;
650
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
651
+ return res.end(JSON.stringify({ isPrivate: SPACE_IS_PRIVATE }));
652
+ }
653
+
654
  if (pathname === "/health") {
655
  const gatewayReady = await probePort(GATEWAY_HOST, GATEWAY_PORT, "/health");
656
  res.writeHead(gatewayReady ? 200 : 503, { "Content-Type": "application/json" });
 
683
  // and WebSocket upgrades pass through untouched.
684
  // /health and /status are always exempt so uptime monitors keep working.
685
  const isHtmlRequest = (req.headers.accept || "").includes("text/html");
686
+
687
+ // RACE CONDITION FIX: Wait for privacy detection to finish BEFORE computing
688
+ // isDirectHfSpaceRequest. Previously this const was computed immediately with
689
+ // the fail-secure default (SPACE_IS_PRIVATE=true), causing private redirects
690
+ // even when the space is actually public or the owner is accessing via HF App.
691
+ // After the very first HTML request, _privacyDetectionDone=true so no delay.
692
+ let privacyWaitTimedOut = false;
693
+ if (isHtmlRequest && !_privacyDetectionDone) {
694
+ const waitResult = await Promise.race([
695
+ privacyDetectionReady.then(() => "detected"),
696
+ new Promise((resolve) => setTimeout(() => resolve("timeout"), PRIVACY_DETECTION_WAIT_MS)),
697
+ ]);
698
+ privacyWaitTimedOut = waitResult == "timeout";
699
+ }
700
+
701
+ // In-app navigation (clicking links within the HF iframe) sends a Referer
702
+ // from the same .hf.space origin β€” don't redirect those, only redirect
703
+ // fresh direct browser access that has no same-origin referer.
704
+ const referer = req.headers.referer || req.headers.referrer || "";
705
+ const isSameOriginNav = !!(referer && typeof req.headers.host === "string" &&
706
+ referer.startsWith(`https://${req.headers.host}`));
707
+ // When HF App embeds the space in an iframe, the initial request has
708
+ // Referer: https://huggingface.co/spaces/... (NOT .hf.space).
709
+ // HF handles authentication itself β€” if the user is not logged in, HF
710
+ // redirects them before the iframe ever loads. So a huggingface.co referer
711
+ // means the user is already authenticated; skip the private redirect.
712
+ const isFromHFApp = !!(referer && (
713
+ referer.startsWith("https://huggingface.co") ||
714
+ referer.startsWith("https://hf.co")
715
+ ));
716
+ // NOTE: computed AFTER detection is awaited above β€” always uses real value.
717
  const isDirectHfSpaceRequest = SPACE_IS_PRIVATE &&
718
+ !privacyWaitTimedOut &&
719
  HF_SPACE_URL &&
720
  isHtmlRequest &&
721
  typeof req.headers.host === "string" &&
722
+ req.headers.host.endsWith(".hf.space") &&
723
+ !isSameOriginNav &&
724
+ !isFromHFApp;
725
 
726
  if (pathname === LOGIN_PATH) {
727
  if (isAuthorized(req)) {
 
759
 
760
  if (pathname === "/env-builder" || pathname === "/env-builder/") {
761
  if (isDirectHfSpaceRequest) {
762
+ res.writeHead(200, { "Content-Type": "text/html", "Cache-Control": "no-store" });
763
  return res.end(renderPrivateRedirect(HF_SPACE_URL));
764
  }
765
  if (!requireAuth(req, res)) return;
 
771
  if (!requireAuth(req, res)) return;
772
  try {
773
  const js = fs.readFileSync(require("path").join(__dirname, "env-builder.js"), "utf8");
774
+ res.writeHead(200, { "Content-Type": "application/javascript", "Cache-Control": "no-store" });
775
  return res.end(js);
776
  } catch (exc) {
777
  res.writeHead(404, { "Content-Type": "text/plain" });
 
780
  }
781
 
782
  if (pathname === "/" || pathname === "/dashboard") {
783
+ // Detection already awaited above (in the isHtmlRequest guard) β€” no extra wait needed.
784
  if (isDirectHfSpaceRequest) {
785
  res.writeHead(200, { "Content-Type": "text/html" });
786
  return res.end(renderPrivateRedirect(HF_SPACE_URL));
iframe-fix.cjs CHANGED
@@ -19,9 +19,10 @@ http.Server.prototype.emit = function (event, ...args) {
19
  if (event === "request") {
20
  const [, res] = args;
21
 
22
- // Only intercept on the main OpenClaw server (port 7860)
 
23
  const serverPort = this.address && this.address() && this.address().port;
24
- if (serverPort && serverPort !== 7860) {
25
  return origEmit.apply(this, [event, ...args]);
26
  }
27
 
 
19
  if (event === "request") {
20
  const [, res] = args;
21
 
22
+ // Only intercept on the main OpenClaw server (respects GATEWAY_PORT env var)
23
+ const expectedPort = Number(process.env.GATEWAY_PORT || 7860);
24
  const serverPort = this.address && this.address() && this.address().port;
25
+ if (serverPort && serverPort !== expectedPort) {
26
  return origEmit.apply(this, [event, ...args]);
27
  }
28
 
jupyter-devdata-sync.py CHANGED
@@ -61,7 +61,11 @@ EXCLUDE = {
61
 
62
 
63
  def enabled():
64
- dev = is_true(os.environ.get("DEV_MODE", ""))
 
 
 
 
65
  separate_dataset = DATASET_NAME != BACKUP_DATASET_NAME
66
  if ENABLE and dev and HF_TOKEN and not separate_dataset:
67
  print("DevData sync disabled: DEVDATA_DATASET_NAME must be separate from BACKUP_DATASET_NAME.")
@@ -97,22 +101,41 @@ import fnmatch as _fnmatch
97
  SECRET_FILENAME_PATTERNS = {
98
  ".env", # dotenv files β€” almost always contain API keys
99
  ".env.*", # .env.local, .env.production, etc.
100
- "*secret*", # any file/dir whose name contains "secret"
101
- "*secrets*",
102
- "*_secret*",
103
- "*-secret*",
104
- "*key*", # private keys, API key files
105
- "*_key*",
106
- "*-key*",
107
- "*token*", # token files
108
- "*_token*",
109
- "*-token*",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  "*.pem", # TLS/SSH private keys
111
  "*.key", # generic key files
112
  "*.p12", # PKCS#12 bundles
113
  "*.pfx",
114
- "credentials", # common credential file names
115
- "credentials.*",
116
  ".netrc", # stores plaintext passwords
117
  ".htpasswd",
118
  }
@@ -174,6 +197,7 @@ def is_jupyter_running(port: int = 8888) -> bool:
174
  return False
175
 
176
  def restore_once(api, rid: str):
 
177
  from huggingface_hub.errors import RepositoryNotFoundError
178
  tmp = Path(tempfile.mkdtemp(prefix="devdata-restore-"))
179
  try:
 
61
 
62
 
63
  def enabled():
64
+ jupyter_override = os.environ.get("HUGGINGCLAW_JUPYTER_ENABLED", "")
65
+ if jupyter_override.strip():
66
+ dev = is_true(jupyter_override)
67
+ else:
68
+ dev = is_true(os.environ.get("DEV_MODE", ""))
69
  separate_dataset = DATASET_NAME != BACKUP_DATASET_NAME
70
  if ENABLE and dev and HF_TOKEN and not separate_dataset:
71
  print("DevData sync disabled: DEVDATA_DATASET_NAME must be separate from BACKUP_DATASET_NAME.")
 
101
  SECRET_FILENAME_PATTERNS = {
102
  ".env", # dotenv files β€” almost always contain API keys
103
  ".env.*", # .env.local, .env.production, etc.
104
+ "id_rsa",
105
+ "id_dsa",
106
+ "id_ecdsa",
107
+ "id_ed25519",
108
+ "authorized_keys",
109
+ "known_hosts",
110
+ "secret",
111
+ "secrets",
112
+ "secret.*",
113
+ "*.secret",
114
+ "*_secret",
115
+ "*_secret.*",
116
+ "*-secret",
117
+ "*-secret.*",
118
+ "token",
119
+ "token.*",
120
+ "*.token",
121
+ "*_token",
122
+ "*_token.*",
123
+ "*-token",
124
+ "*-token.*",
125
+ "api_token",
126
+ "access_token",
127
+ "refresh_token",
128
+ "credentials", # common credential file names
129
+ "credentials.*",
130
+ "auth.json",
131
+ "auth.yaml",
132
+ "auth.yml",
133
+ "auth.toml",
134
+ "auth.ini",
135
  "*.pem", # TLS/SSH private keys
136
  "*.key", # generic key files
137
  "*.p12", # PKCS#12 bundles
138
  "*.pfx",
 
 
139
  ".netrc", # stores plaintext passwords
140
  ".htpasswd",
141
  }
 
197
  return False
198
 
199
  def restore_once(api, rid: str):
200
+ from huggingface_hub import snapshot_download
201
  from huggingface_hub.errors import RepositoryNotFoundError
202
  tmp = Path(tempfile.mkdtemp(prefix="devdata-restore-"))
203
  try:
multi-provider-key-rotator.cjs CHANGED
@@ -3,266 +3,248 @@
3
  /**
4
  * Multi-provider API key rotator for OpenClaw/HuggingClaw
5
  * --------------------------------------------------------
6
- * Works exactly like nvidia-key-rotator.cjs but covers every
7
- * provider that HuggingClaw supports.
 
 
 
8
  *
9
- * For each provider you can supply a comma-separated pool:
10
- * ANTHROPIC_API_KEYS=key1,key2,key3
11
- * Falls back to the singular env var, and optionally to LLM_API_KEY.
12
- *
13
- * Keys are rotated round-robin per provider independently.
14
- *
15
- * Patches globalThis.fetch + node:http + node:https so that
16
- * virtually every caller is covered without code changes.
17
  */
18
 
19
  const http = require('node:http');
20
  const https = require('node:https');
21
 
22
- // This file is preloaded through NODE_OPTIONS, so it also runs inside npm and
23
- // OpenClaw helper subprocesses that may emit machine-readable JSON on stdout.
24
- // Keep rotator diagnostics on stderr to avoid corrupting those stdout streams.
25
- const log = (...args) => console.error(...args);
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  // ─── Provider definitions ────────────────────────────────────────────────────
28
- //
29
- // hostname – regex tested against the request hostname (case-insensitive)
30
- // envPlural – env var that holds a comma-separated key pool (preferred)
31
- // envSingular – env var that holds a single key (fallback)
32
- //
33
- // LLM_API_KEY fallback can be controlled via:
34
- // LLM_API_KEY_FALLBACK_ENABLED=true|false
35
- // Default is enabled for backwards compatibility.
36
- //
37
- const PROVIDERS = [
38
- {
39
- name: 'anthropic',
40
- hostname: /(?:^|\.)api\.anthropic\.com$/i,
41
- envPlural: 'ANTHROPIC_API_KEYS',
42
- envSingular:'ANTHROPIC_API_KEY',
43
- },
44
- {
45
- name: 'openai',
46
- hostname: /(?:^|\.)api\.openai\.com$/i,
47
- envPlural: 'OPENAI_API_KEYS',
48
- envSingular:'OPENAI_API_KEY',
49
- },
50
- {
51
- name: 'gemini',
52
- // Gemini uses generativelanguage API; also covers aiplatform
53
- hostname: /(?:^|\.)(?:generativelanguage\.googleapis\.com|aiplatform\.googleapis\.com)$/i,
54
- envPlural: 'GEMINI_API_KEYS',
55
- envSingular:'GEMINI_API_KEY',
56
- queryParam: true,
57
- },
58
- {
59
- name: 'deepseek',
60
- hostname: /(?:^|\.)api\.deepseek\.com$/i,
61
- envPlural: 'DEEPSEEK_API_KEYS',
62
- envSingular:'DEEPSEEK_API_KEY',
63
- },
64
- {
65
- name: 'openrouter',
66
- hostname: /(?:^|\.)openrouter\.ai$/i,
67
- envPlural: 'OPENROUTER_API_KEYS',
68
- envSingular:'OPENROUTER_API_KEY',
69
- },
70
- {
71
- name: 'kilocode',
72
- hostname: /(?:^|\.)kilocode\.ai$/i,
73
- envPlural: 'KILOCODE_API_KEYS',
74
- envSingular:'KILOCODE_API_KEY',
75
- },
76
- {
77
- name: 'opencode',
78
- hostname: /(?:^|\.)opencode\.ai$/i,
79
- envPlural: 'OPENCODE_API_KEYS',
80
- envSingular:'OPENCODE_API_KEY',
81
- },
82
- {
83
- name: 'zai',
84
- // Z.ai / GLM β€” both domains normalised to "zai" in OpenClaw
85
- hostname: /(?:^|\.)(?:z\.ai|open\.bigmodel\.cn)$/i,
86
- envPlural: 'ZAI_API_KEYS',
87
- envSingular:'ZAI_API_KEY',
88
- },
89
- {
90
- name: 'moonshot',
91
- hostname: /(?:^|\.)api\.moonshot\.cn$/i,
92
- envPlural: 'MOONSHOT_API_KEYS',
93
- envSingular:'MOONSHOT_API_KEY',
94
- },
95
- {
96
- name: 'minimax',
97
- hostname: /(?:^|\.)api\.minimax\.chat$/i,
98
- envPlural: 'MINIMAX_API_KEYS',
99
- envSingular:'MINIMAX_API_KEY',
100
- },
101
- {
102
- name: 'xiaomi',
103
- // MiMo β€” update hostname if Xiaomi publishes an official domain
104
- hostname: /(?:^|\.)api\.xiaomi\.com$/i,
105
- envPlural: 'XIAOMI_API_KEYS',
106
- envSingular:'XIAOMI_API_KEY',
107
- },
108
- {
109
- name: 'volcengine',
110
- // Volcengine / Doubao
111
- hostname: /(?:^|\.)(?:ark\.cn-beijing\.volces\.com|volcengineapi\.com)$/i,
112
- envPlural: 'VOLCANO_ENGINE_API_KEYS',
113
- envSingular:'VOLCANO_ENGINE_API_KEY',
114
- },
115
- {
116
- name: 'byteplus',
117
- hostname: /(?:^|\.)maas-api\.ml-platform-cn-beijing\.byteplus\.com$/i,
118
- envPlural: 'BYTEPLUS_API_KEYS',
119
- envSingular:'BYTEPLUS_API_KEY',
120
- },
121
- {
122
- name: 'mistral',
123
- hostname: /(?:^|\.)api\.mistral\.ai$/i,
124
- envPlural: 'MISTRAL_API_KEYS',
125
- envSingular:'MISTRAL_API_KEY',
126
- },
127
- {
128
- name: 'xai',
129
- hostname: /(?:^|\.)api\.x\.ai$/i,
130
- envPlural: 'XAI_API_KEYS',
131
- envSingular:'XAI_API_KEY',
132
- },
133
- {
134
- name: 'nvidia',
135
- hostname: /(?:^|\.)(?:integrate\.api\.nvidia\.com|api\.nvidia\.com)$/i,
136
- envPlural: 'NVIDIA_API_KEYS',
137
- envSingular:'NVIDIA_API_KEY',
138
- },
139
- {
140
- name: 'groq',
141
- hostname: /(?:^|\.)api\.groq\.com$/i,
142
- envPlural: 'GROQ_API_KEYS',
143
- envSingular:'GROQ_API_KEY',
144
- },
145
- {
146
- name: 'cohere',
147
- hostname: /(?:^|\.)api\.cohere\.(?:ai|com)$/i,
148
- envPlural: 'COHERE_API_KEYS',
149
- envSingular:'COHERE_API_KEY',
150
- },
151
- {
152
- name: 'together',
153
- hostname: /(?:^|\.)api\.together\.(?:xyz|ai)$/i,
154
- envPlural: 'TOGETHER_API_KEYS',
155
- envSingular:'TOGETHER_API_KEY',
156
- },
157
- {
158
- name: 'cerebras',
159
- hostname: /(?:^|\.)api\.cerebras\.ai$/i,
160
- envPlural: 'CEREBRAS_API_KEYS',
161
- envSingular:'CEREBRAS_API_KEY',
162
- },
163
- {
164
- name: 'huggingface',
165
- hostname: /(?:^|\.)(?:api-inference\.huggingface\.co|router\.huggingface\.co|huggingface\.co)$/i,
166
- envPlural: 'HUGGINGFACE_HUB_TOKENS', // plural variant
167
- envSingular:'HUGGINGFACE_HUB_TOKEN',
168
- },
169
- {
170
- name: 'venice',
171
- hostname: /(?:^|\.)api\.venice\.ai$/i,
172
- envPlural: 'VENICE_API_KEYS',
173
- envSingular:'VENICE_API_KEY',
174
- },
175
- {
176
- name: 'github-copilot',
177
- hostname: /(?:^|\.)api\.githubcopilot\.com$/i,
178
- envPlural: 'COPILOT_GITHUB_TOKENS',
179
- envSingular:'COPILOT_GITHUB_TOKEN',
180
- },
181
- {
182
- name: 'qianfan',
183
- // Baidu Qianfan / ERNIE
184
- hostname: /(?:^|\.)(?:aip|qianfan)\.baidubce\.com$/i,
185
- envPlural: 'QIANFAN_API_KEYS',
186
- envSingular:'QIANFAN_API_KEY',
187
- },
188
- {
189
- name: 'modelstudio',
190
- // Aliyun DashScope / Qwen (both qwen/* and modelstudio/* prefixes)
191
- hostname: /(?:^|\.)dashscope\.aliyuncs\.com$/i,
192
- envPlural: 'MODELSTUDIO_API_KEYS',
193
- envSingular:'MODELSTUDIO_API_KEY',
194
- },
195
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  ];
197
 
198
  // ─── Key loading ─────────────────────────────────────────────────────────────
199
 
200
  function normalizeKeys(...inputs) {
201
- const seen = new Set();
202
- const out = [];
203
- for (const input of inputs) {
204
- for (const k of String(input || '').split(',').map(s => s.trim()).filter(Boolean)) {
205
  if (!seen.has(k)) { seen.add(k); out.push(k); }
206
- }
207
- }
208
  return out;
209
  }
210
 
211
- // Build per-provider key pools + rotation indices
 
 
 
 
212
  const providerState = PROVIDERS.map(p => {
213
- const llmFallbackRaw = String(process.env.LLM_API_KEY_FALLBACK_ENABLED || '').trim().toLowerCase();
214
- const llmFallbackEnabled = !/^(0|false|no|off)$/.test(llmFallbackRaw);
 
 
 
 
 
 
215
  const dedicatedKeys = normalizeKeys(
216
  process.env[p.envPlural] || '',
217
  process.env[p.envSingular] || '',
 
218
  );
219
  const hasDedicated = dedicatedKeys.length > 0;
220
  const keys = hasDedicated
221
  ? dedicatedKeys
222
- : (
223
- llmFallbackEnabled
224
- ? normalizeKeys(process.env.LLM_API_KEY || '')
225
- : []
226
- );
227
 
228
- if (hasDedicated) {
229
  log(`[key-rotator] ${p.name}: ${keys.length} key${keys.length === 1 ? '' : 's'}`);
230
- } else if (!keys.length) {
231
- console.warn(`[key-rotator] No keys for provider "${p.name}"`);
232
- }
233
 
234
- return { ...p, keys, idx: 0 };
 
 
 
 
 
 
235
  });
236
 
237
- // Summarise providers that fall back to LLM_API_KEY
238
  const fallbackCount = providerState.filter(p => {
239
- const dedicated = normalizeKeys(
240
- process.env[p.envPlural] || '',
241
- process.env[p.envSingular] || '',
242
- );
243
- return dedicated.length === 0 && p.keys.length > 0;
244
  }).length;
245
- if (fallbackCount > 0) {
246
  log(`[key-rotator] ${fallbackCount} provider(s) using LLM_API_KEY fallback`);
247
- } else if (process.env.LLM_API_KEY && /^(0|false|no|off)$/i.test(String(process.env.LLM_API_KEY_FALLBACK_ENABLED || ''))) {
248
- log('[key-rotator] LLM_API_KEY fallback disabled (set LLM_API_KEY_FALLBACK_ENABLED=true to re-enable)');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  }
250
 
251
- // ─── Runtime helpers ─────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
 
253
  function resolveHostname(urlLike) {
254
  try {
255
  const u =
256
- typeof urlLike === 'string' ? new URL(urlLike)
257
- : urlLike instanceof URL ? urlLike
258
- : urlLike && typeof urlLike.url === 'string' ? new URL(urlLike.url)
259
- : urlLike && typeof urlLike.href === 'string' ? new URL(urlLike.href)
260
- : urlLike && typeof urlLike.hostname === 'string' ? urlLike
261
  : null;
262
  return u ? u.hostname : null;
263
- } catch {
264
- return null;
265
- }
266
  }
267
 
268
  function matchProvider(hostname) {
@@ -270,126 +252,135 @@ function matchProvider(hostname) {
270
  return providerState.find(p => p.hostname.test(hostname)) || null;
271
  }
272
 
273
- function nextKey(provider) {
274
- if (!provider || !provider.keys.length) return null;
275
- const key = provider.keys[provider.idx % provider.keys.length];
276
- provider.idx = (provider.idx + 1) % provider.keys.length;
277
- return key;
278
- }
279
-
280
  function setAuthHeader(headers, key) {
281
  if (!key) return headers;
282
- const authValue = `Bearer ${key}`;
283
-
284
  if (typeof Headers !== 'undefined' && headers instanceof Headers) {
285
- headers.set('authorization', authValue);
286
- return headers;
287
  }
288
  if (Array.isArray(headers)) {
289
- const out = headers.filter(([k]) => String(k).toLowerCase() !== 'authorization');
290
- out.push(['authorization', authValue]);
291
- return out;
292
  }
293
- if (headers && typeof headers === 'object') {
294
- return { ...headers, authorization: authValue };
 
 
 
 
 
 
 
 
295
  }
296
- return { authorization: authValue };
297
  }
298
 
299
  // ─── Patch globalThis.fetch ───────────────────────────────────────────────────
300
 
301
  function patchFetch() {
302
  if (typeof globalThis.fetch !== 'function') return;
303
-
304
- const originalFetch = globalThis.fetch.bind(globalThis);
305
 
306
  globalThis.fetch = async function patchedFetch(input, init = {}) {
307
- try {
308
- const urlLike =
309
- typeof input === 'string' || input instanceof URL
310
- ? input
311
- : input && typeof input.url === 'string' ? input.url : null;
312
 
313
- const hostname = resolveHostname(urlLike);
314
- const provider = matchProvider(hostname);
 
 
 
315
 
316
- if (provider) {
317
  const key = nextKey(provider);
318
  if (key) {
 
319
  if (provider.queryParam) {
320
- // Gemini: key URL query param mein jaata hai, Bearer nahi
321
  const url = new URL(typeof input === 'string' ? input : input.url);
322
  url.searchParams.set('key', key);
323
- input = typeof input === 'string' ? url.toString() : new Request(url.toString(), input);
 
 
 
 
 
 
 
 
324
  } else {
325
- const headers = init.headers || (input && input.headers) || undefined;
326
- const patchedHeaders = setAuthHeader(headers, key);
327
- init = { ...init, headers: patchedHeaders };
328
- // NOTE: new Request(input, {headers}) yahan nahi karte β€” Request clone karna
329
- // body stream ko disturb kar deta hai β†’ UND_ERR_INVALID_ARG on POST requests.
330
- // init.headers fetch spec ke mutabiq Request ke headers ko override kar deta hai.
331
  }
332
  }
333
  }
334
- } catch (err) {
335
- console.warn('[key-rotator] fetch patch error:', err?.message || err);
336
- }
337
 
338
- return originalFetch(input, init);
 
 
 
 
 
339
  };
340
  }
341
 
342
  // ─── Patch node:http / node:https ────────────────────────────────────────────
343
 
344
  function patchHttpModule(mod) {
345
- const originalRequest = mod.request;
346
 
347
  mod.request = function patchedRequest(...args) {
 
 
348
  try {
349
  const options = args[0];
350
- const hostname = resolveHostname(options);
351
- const provider = matchProvider(hostname);
352
 
353
  if (provider) {
354
  const key = nextKey(provider);
355
  if (key) {
 
356
  if (provider.queryParam) {
357
- // Gemini: ?key= query param use karo
358
- const u = new URL(String(typeof options === 'string' || options instanceof URL ? options : `https://${options.hostname}${options.path || '/'}`));
 
 
 
359
  u.searchParams.set('key', key);
360
  args[0] = typeof options === 'object' && !(options instanceof URL)
361
- ? { ...options, path: `${u.pathname}${u.search}` }
362
  : u.toString();
363
  } else if (typeof options === 'string' || options instanceof URL) {
364
- // Convert string/URL to options object and inject auth header.
365
- // Also preserve any extra options passed as args[1] (3-arg form of http.request).
366
  const u = new URL(String(options));
367
- const extraOpts = (args[1] && typeof args[1] === 'object' && typeof args[1].on !== 'function') ? args[1] : {};
368
- args[0] = {
369
- protocol: u.protocol,
370
- hostname: u.hostname,
371
- port: u.port,
372
- path: `${u.pathname}${u.search}`,
373
- ...extraOpts,
374
- headers: setAuthHeader(extraOpts.headers, key),
375
- };
376
  } else if (options && typeof options === 'object') {
377
- args[0] = { ...options, headers: setAuthHeader(options.headers, key) };
378
  }
379
  }
380
  }
381
- } catch (err) {
382
- console.warn('[key-rotator] http patch error:', err?.message || err);
383
- }
384
 
385
- return originalRequest.apply(mod, args);
 
 
 
 
 
 
 
 
 
 
 
386
  };
387
  }
388
 
389
- // ─── Apply patches ────────────────────────────────────────────────────────────
390
 
391
  patchFetch();
392
  patchHttpModule(http);
393
  patchHttpModule(https);
394
 
395
- log('[key-rotator] loaded β€” all providers active');
 
3
  /**
4
  * Multi-provider API key rotator for OpenClaw/HuggingClaw
5
  * --------------------------------------------------------
6
+ * - Round-robin rotation per provider
7
+ * - 429/402 β†’ exponential backoff blacklist per key
8
+ * - After MAX_STRIKES consecutive failures β†’ permanent session blacklist
9
+ * - Successful response β†’ strikes reset
10
+ * - 10+ keys handled correctly (idx tracks only active keys, no drift)
11
  *
12
+ * Env vars:
13
+ * KEY_BLACKLIST_COOLDOWN_MS base backoff ms (default 60 000)
14
+ * KEY_MAX_STRIKES failures before perm (default 3)
15
+ * LLM_API_KEY_FALLBACK_ENABLED true/false (default true)
 
 
 
 
16
  */
17
 
18
  const http = require('node:http');
19
  const https = require('node:https');
20
 
21
+ const log = (...a) => console.error(...a);
22
+ const warn = (...a) => console.warn(...a);
23
+
24
+ // ─── Config ──────────────────────────────────────────────────────────────────
25
+
26
+ const BASE_COOLDOWN_MS = Math.max(
27
+ 1000,
28
+ parseInt(process.env.KEY_BLACKLIST_COOLDOWN_MS || '', 10) || 60_000,
29
+ );
30
+ const MAX_STRIKES = Math.max(
31
+ 1,
32
+ parseInt(process.env.KEY_MAX_STRIKES || '', 10) || 3,
33
+ );
34
+ // Permanently blacklisted keys retry after this long (default 24 h).
35
+ // "Permanent" just means very long β€” avoids truly forever loops on app restart.
36
+ const PERM_BLACKLIST_MS = 24 * 60 * 60 * 1000;
37
 
38
  // ─── Provider definitions ────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ const PROVIDERS = [
41
+ { name:'anthropic', hostname:/(?:^|\.)api\.anthropic\.com$/i, envPlural:'ANTHROPIC_API_KEYS', envSingular:'ANTHROPIC_API_KEY' },
42
+ { name:'openai', hostname:/(?:^|\.)api\.openai\.com$/i, envPlural:'OPENAI_API_KEYS', envSingular:'OPENAI_API_KEY' },
43
+ { name:'gemini', hostname:/(?:^|\.)(?:generativelanguage\.googleapis\.com|aiplatform\.googleapis\.com)$/i,
44
+ envPlural:'GEMINI_API_KEYS', envSingular:'GEMINI_API_KEY', queryParam:true },
45
+ { name:'deepseek', hostname:/(?:^|\.)api\.deepseek\.com$/i, envPlural:'DEEPSEEK_API_KEYS', envSingular:'DEEPSEEK_API_KEY' },
46
+ { name:'openrouter', hostname:/(?:^|\.)openrouter\.ai$/i, envPlural:'OPENROUTER_API_KEYS', envSingular:'OPENROUTER_API_KEY' },
47
+ { name:'kilocode', hostname:/(?:^|\.)kilocode\.ai$/i, envPlural:'KILOCODE_API_KEYS', envSingular:'KILOCODE_API_KEY' },
48
+ { name:'opencode', hostname:/(?:^|\.)opencode\.ai$/i, envPlural:'OPENCODE_API_KEYS', envSingular:'OPENCODE_API_KEY' },
49
+ { name:'zai', hostname:/(?:^|\.)(?:z\.ai|open\.bigmodel\.cn)$/i, envPlural:'ZAI_API_KEYS', envSingular:'ZAI_API_KEY' },
50
+ // FIX: kimi-coding aur moonshot ek hi hostname share karte hain (api.moonshot.cn).
51
+ // Purani file mein dono alag entries thi β€” find() hamesha kimi-coding pick karta tha,
52
+ // MOONSHOT_API_KEYS kabhi use nahi hoti. Ab merged entry: dono pools combine honge.
53
+ { name:'kimi-moonshot',hostname:/(?:^|\.)api\.moonshot\.cn$/i, envPlural:'KIMI_API_KEYS', envSingular:'KIMI_API_KEY',
54
+ _extraPlural:'MOONSHOT_API_KEYS', _extraSingular:'MOONSHOT_API_KEY' },
55
+ { name:'minimax', hostname:/(?:^|\.)api\.minimax\.chat$/i, envPlural:'MINIMAX_API_KEYS', envSingular:'MINIMAX_API_KEY' },
56
+ { name:'xiaomi', hostname:/(?:^|\.)api\.xiaomi\.com$/i, envPlural:'XIAOMI_API_KEYS', envSingular:'XIAOMI_API_KEY' },
57
+ { name:'volcengine', hostname:/(?:^|\.)(?:ark\.cn-beijing\.volces\.com|volcengineapi\.com)$/i,
58
+ envPlural:'VOLCANO_ENGINE_API_KEYS', envSingular:'VOLCANO_ENGINE_API_KEY' },
59
+ { name:'byteplus', hostname:/(?:^|\.)maas-api\.ml-platform-cn-beijing\.byteplus\.com$/i,
60
+ envPlural:'BYTEPLUS_API_KEYS', envSingular:'BYTEPLUS_API_KEY' },
61
+ { name:'mistral', hostname:/(?:^|\.)api\.mistral\.ai$/i, envPlural:'MISTRAL_API_KEYS', envSingular:'MISTRAL_API_KEY' },
62
+ { name:'xai', hostname:/(?:^|\.)api\.x\.ai$/i, envPlural:'XAI_API_KEYS', envSingular:'XAI_API_KEY' },
63
+ { name:'nvidia', hostname:/(?:^|\.)(?:integrate\.api\.nvidia\.com|api\.nvidia\.com)$/i,
64
+ envPlural:'NVIDIA_API_KEYS', envSingular:'NVIDIA_API_KEY' },
65
+ { name:'groq', hostname:/(?:^|\.)api\.groq\.com$/i, envPlural:'GROQ_API_KEYS', envSingular:'GROQ_API_KEY' },
66
+ { name:'cohere', hostname:/(?:^|\.)api\.cohere\.(?:ai|com)$/i, envPlural:'COHERE_API_KEYS', envSingular:'COHERE_API_KEY' },
67
+ { name:'together', hostname:/(?:^|\.)api\.together\.(?:xyz|ai)$/i, envPlural:'TOGETHER_API_KEYS', envSingular:'TOGETHER_API_KEY' },
68
+ { name:'cerebras', hostname:/(?:^|\.)api\.cerebras\.ai$/i, envPlural:'CEREBRAS_API_KEYS', envSingular:'CEREBRAS_API_KEY' },
69
+ { name:'huggingface', hostname:/(?:^|\.)(?:api-inference\.huggingface\.co|router\.huggingface\.co|huggingface\.co)$/i,
70
+ envPlural:'HUGGINGFACE_HUB_TOKENS', envSingular:'HUGGINGFACE_HUB_TOKEN' },
71
+ { name:'venice', hostname:/(?:^|\.)api\.venice\.ai$/i, envPlural:'VENICE_API_KEYS', envSingular:'VENICE_API_KEY' },
72
+ { name:'github-copilot',hostname:/(?:^|\.)api\.githubcopilot\.com$/i, envPlural:'COPILOT_GITHUB_TOKENS', envSingular:'COPILOT_GITHUB_TOKEN' },
73
+ { name:'qianfan', hostname:/(?:^|\.)(?:aip|qianfan)\.baidubce\.com$/i, envPlural:'QIANFAN_API_KEYS', envSingular:'QIANFAN_API_KEY' },
74
+ { name:'modelstudio', hostname:/(?:^|\.)dashscope\.aliyuncs\.com$/i, envPlural:'MODELSTUDIO_API_KEYS', envSingular:'MODELSTUDIO_API_KEY' },
75
+ { name:'synthetic', hostname:/(?:^|\.)synthetic\.local$/i, envPlural:'SYNTHETIC_API_KEYS', envSingular:'SYNTHETIC_API_KEY' },
76
  ];
77
 
78
  // ─── Key loading ─────────────────────────────────────────────────────────────
79
 
80
  function normalizeKeys(...inputs) {
81
+ const seen = new Set(), out = [];
82
+ for (const input of inputs)
83
+ for (const k of String(input || '').split(',').map(s => s.trim()).filter(Boolean))
 
84
  if (!seen.has(k)) { seen.add(k); out.push(k); }
 
 
85
  return out;
86
  }
87
 
88
+ // Per-key state: { strikes, blacklistedUntil }
89
+ // strikes – consecutive 429/402 count; resets on success
90
+ // blacklistedUntil – epoch ms; 0 = active
91
+ function makeKeyState() { return { strikes: 0, blacklistedUntil: 0 }; }
92
+
93
  const providerState = PROVIDERS.map(p => {
94
+ const llmFallbackEnabled = !/^(0|false|no|off)$/.test(
95
+ String(process.env.LLM_API_KEY_FALLBACK_ENABLED || '').trim().toLowerCase(),
96
+ );
97
+
98
+ const extraKeys = (p._extraPlural || p._extraSingular)
99
+ ? normalizeKeys(process.env[p._extraPlural || ''] || '', process.env[p._extraSingular || ''] || '')
100
+ : [];
101
+
102
  const dedicatedKeys = normalizeKeys(
103
  process.env[p.envPlural] || '',
104
  process.env[p.envSingular] || '',
105
+ ...extraKeys,
106
  );
107
  const hasDedicated = dedicatedKeys.length > 0;
108
  const keys = hasDedicated
109
  ? dedicatedKeys
110
+ : (llmFallbackEnabled ? normalizeKeys(process.env.LLM_API_KEY || '') : []);
 
 
 
 
111
 
112
+ if (hasDedicated)
113
  log(`[key-rotator] ${p.name}: ${keys.length} key${keys.length === 1 ? '' : 's'}`);
114
+ else if (!keys.length)
115
+ warn(`[key-rotator] No keys for provider "${p.name}"`);
 
116
 
117
+ // keyState: Map<keyString, {strikes, blacklistedUntil}>
118
+ const keyState = new Map(keys.map(k => [k, makeKeyState()]));
119
+
120
+ // FIX: idx tracks position in the ACTIVE (non-permanently-removed) pool.
121
+ // We never remove keys from the array β€” we just skip blacklisted ones.
122
+ // idx advances only when a key is ACTUALLY picked (no drift for skipped keys).
123
+ return { ...p, keys, keyState, idx: 0 };
124
  });
125
 
126
+ // LLM_API_KEY fallback summary
127
  const fallbackCount = providerState.filter(p => {
128
+ const ded = normalizeKeys(process.env[p.envPlural] || '', process.env[p.envSingular] || '');
129
+ return ded.length === 0 && p.keys.length > 0;
 
 
 
130
  }).length;
131
+ if (fallbackCount > 0)
132
  log(`[key-rotator] ${fallbackCount} provider(s) using LLM_API_KEY fallback`);
133
+
134
+ // ─── Per-key state helpers ────────────────────────────────────────────────────
135
+
136
+ /**
137
+ * Is this key currently sitting out?
138
+ * Also auto-clears expired blacklists so the key re-enters the pool silently.
139
+ */
140
+ function isActive(p, key) {
141
+ const ks = p.keyState.get(key);
142
+ if (!ks) return true; // unknown key β†’ treat as active
143
+ if (ks.blacklistedUntil === 0) return true; // not blacklisted
144
+ if (Date.now() >= ks.blacklistedUntil) {
145
+ ks.blacklistedUntil = 0; // expired β†’ back in pool
146
+ log(`[key-rotator] ${p.name}: ...${key.slice(-6)} back in pool`);
147
+ return true;
148
+ }
149
+ return false;
150
  }
151
 
152
+ /**
153
+ * Called when a key gets a 429/402 response.
154
+ *
155
+ * Strike logic:
156
+ * strike 1 β†’ BASE_COOLDOWN_MS (e.g. 60 s β€” probably rate-limit)
157
+ * strike 2 β†’ BASE_COOLDOWN_MS Γ— 4 (240 s)
158
+ * strike 3 β†’ PERM_BLACKLIST_MS (24 h β€” treat as quota exhausted, skip all day)
159
+ *
160
+ * A successful response resets strikes so a key that was temporarily
161
+ * rate-limited and recovered is treated as fresh again.
162
+ */
163
+ function recordFailure(p, key) {
164
+ let ks = p.keyState.get(key);
165
+ if (!ks) { ks = makeKeyState(); p.keyState.set(key, ks); }
166
+
167
+ ks.strikes = Math.min(ks.strikes + 1, MAX_STRIKES);
168
+
169
+ let cooldown;
170
+ if (ks.strikes >= MAX_STRIKES) {
171
+ cooldown = PERM_BLACKLIST_MS;
172
+ warn(`[key-rotator] ${p.name}: ...${key.slice(-6)} reached ${MAX_STRIKES} strikes β€” suspended for 24 h (quota likely exhausted)`);
173
+ } else {
174
+ // Exponential: 1Γ— β†’ 4Γ— (strikes 1 and 2)
175
+ cooldown = BASE_COOLDOWN_MS * Math.pow(4, ks.strikes - 1);
176
+ const secs = Math.round(cooldown / 1000);
177
+ log(`[key-rotator] ${p.name}: ...${key.slice(-6)} strike ${ks.strikes}/${MAX_STRIKES} β€” backoff ${secs}s`);
178
+ }
179
+
180
+ ks.blacklistedUntil = Date.now() + cooldown;
181
+ }
182
+
183
+ /**
184
+ * Called on any 2xx/3xx response β€” resets the key's strike counter.
185
+ */
186
+ function recordSuccess(p, key) {
187
+ const ks = p.keyState.get(key);
188
+ if (ks && ks.strikes > 0) {
189
+ ks.strikes = 0;
190
+ log(`[key-rotator] ${p.name}: ...${key.slice(-6)} recovered β€” strikes reset`);
191
+ }
192
+ }
193
+
194
+ // ─── Round-robin selection ────────────────────────────────────────────────────
195
+
196
+ /**
197
+ * Pick the next active key using round-robin.
198
+ *
199
+ * FIX (idx drift): idx advances by 1 per CALL, not per skip.
200
+ * We scan up to `total` positions from the current idx to find an active key.
201
+ * The found key's position becomes the new baseline for the next call.
202
+ *
203
+ * Example with 10 keys where k3–k7 are blacklisted:
204
+ * call 1: start=0 β†’ picks k0, next start=1
205
+ * call 2: start=1 β†’ picks k1, next start=2
206
+ * call 3: start=2 β†’ scans k2β†’active, picks k2, next start=3
207
+ * call 4: start=3 β†’ scans k3(skip)…k7(skip)β†’k8 active, picks k8, next start=9
208
+ * call 5: start=9 β†’ picks k9, next start=0
209
+ * Every active key gets equal share; blacklisted keys are cleanly skipped.
210
+ */
211
+ function nextKey(p) {
212
+ if (!p || !p.keys.length) return null;
213
+
214
+ const total = p.keys.length;
215
+
216
+ for (let offset = 0; offset < total; offset++) {
217
+ const i = (p.idx + offset) % total;
218
+ const key = p.keys[i];
219
+ if (isActive(p, key)) {
220
+ p.idx = (i + 1) % total; // next call starts AFTER the key we just picked
221
+ return key;
222
+ }
223
+ }
224
+
225
+ // All keys are sitting out β€” pick the one closest to recovering
226
+ warn(`[key-rotator] ${p.name}: all ${total} key(s) suspended β€” using soonest-recovering key`);
227
+ let best = p.keys[0], bestExpiry = Infinity;
228
+ for (const k of p.keys) {
229
+ const exp = p.keyState.get(k)?.blacklistedUntil ?? 0;
230
+ if (exp < bestExpiry) { best = k; bestExpiry = exp; }
231
+ }
232
+ return best;
233
+ }
234
+
235
+ // ─── Auth header injection ────────────────────────────────────────────────────
236
 
237
  function resolveHostname(urlLike) {
238
  try {
239
  const u =
240
+ typeof urlLike === 'string' ? new URL(urlLike)
241
+ : urlLike instanceof URL ? urlLike
242
+ : urlLike && typeof urlLike.url === 'string' ? new URL(urlLike.url)
243
+ : urlLike && typeof urlLike.href === 'string' ? new URL(urlLike.href)
244
+ : urlLike && typeof urlLike.hostname === 'string' ? urlLike
245
  : null;
246
  return u ? u.hostname : null;
247
+ } catch { return null; }
 
 
248
  }
249
 
250
  function matchProvider(hostname) {
 
252
  return providerState.find(p => p.hostname.test(hostname)) || null;
253
  }
254
 
 
 
 
 
 
 
 
255
  function setAuthHeader(headers, key) {
256
  if (!key) return headers;
257
+ const val = `Bearer ${key}`;
 
258
  if (typeof Headers !== 'undefined' && headers instanceof Headers) {
259
+ headers.set('authorization', val); return headers;
 
260
  }
261
  if (Array.isArray(headers)) {
262
+ return [...headers.filter(([k]) => String(k).toLowerCase() !== 'authorization'), ['authorization', val]];
 
 
263
  }
264
+ if (headers && typeof headers === 'object') return { ...headers, authorization: val };
265
+ return { authorization: val };
266
+ }
267
+
268
+ function handleStatus(p, key, status) {
269
+ if (!p || !key) return;
270
+ if (status === 429 || status === 402) {
271
+ recordFailure(p, key);
272
+ } else if (status >= 200 && status < 400) {
273
+ recordSuccess(p, key);
274
  }
 
275
  }
276
 
277
  // ─── Patch globalThis.fetch ───────────────────────────────────────────────────
278
 
279
  function patchFetch() {
280
  if (typeof globalThis.fetch !== 'function') return;
281
+ const orig = globalThis.fetch.bind(globalThis);
 
282
 
283
  globalThis.fetch = async function patchedFetch(input, init = {}) {
284
+ let usedKey = null, usedProvider = null;
 
 
 
 
285
 
286
+ try {
287
+ const urlLike = typeof input === 'string' || input instanceof URL
288
+ ? input
289
+ : (input && typeof input.url === 'string' ? input.url : null);
290
+ const provider = matchProvider(resolveHostname(urlLike));
291
 
292
+ if (provider) {
293
  const key = nextKey(provider);
294
  if (key) {
295
+ usedKey = key; usedProvider = provider;
296
  if (provider.queryParam) {
 
297
  const url = new URL(typeof input === 'string' ? input : input.url);
298
  url.searchParams.set('key', key);
299
+ if (typeof input === 'string') {
300
+ input = url.toString();
301
+ } else {
302
+ init = { method:input.method, headers:input.headers, body:input.body,
303
+ mode:input.mode, credentials:input.credentials, cache:input.cache,
304
+ redirect:input.redirect, referrer:input.referrer,
305
+ integrity:input.integrity, ...init };
306
+ input = url.toString();
307
+ }
308
  } else {
309
+ init = { ...init, headers: setAuthHeader(init.headers || (input && input.headers) || undefined, key) };
 
 
 
 
 
310
  }
311
  }
312
  }
313
+ } catch (err) { warn('[key-rotator] fetch patch error:', err?.message || err); }
 
 
314
 
315
+ let response;
316
+ try { response = await orig(input, init); }
317
+ catch (err) { throw err; }
318
+
319
+ try { handleStatus(usedProvider, usedKey, response.status); } catch (_) {}
320
+ return response;
321
  };
322
  }
323
 
324
  // ─── Patch node:http / node:https ────────────────────────────────────────────
325
 
326
  function patchHttpModule(mod) {
327
+ const orig = mod.request;
328
 
329
  mod.request = function patchedRequest(...args) {
330
+ let usedKey = null, usedProvider = null;
331
+
332
  try {
333
  const options = args[0];
334
+ const provider = matchProvider(resolveHostname(options));
 
335
 
336
  if (provider) {
337
  const key = nextKey(provider);
338
  if (key) {
339
+ usedKey = key; usedProvider = provider;
340
  if (provider.queryParam) {
341
+ const u = new URL(String(
342
+ typeof options === 'string' || options instanceof URL
343
+ ? options
344
+ : `https://${options.hostname}${options.path || '/'}`
345
+ ));
346
  u.searchParams.set('key', key);
347
  args[0] = typeof options === 'object' && !(options instanceof URL)
348
+ ? { ...options, path:`${u.pathname}${u.search}` }
349
  : u.toString();
350
  } else if (typeof options === 'string' || options instanceof URL) {
 
 
351
  const u = new URL(String(options));
352
+ const extra = (args[1] && typeof args[1] === 'object' && typeof args[1].on !== 'function') ? args[1] : {};
353
+ args[0] = { protocol:u.protocol, hostname:u.hostname, port:u.port,
354
+ path:`${u.pathname}${u.search}`, ...extra,
355
+ headers:setAuthHeader(extra.headers, key) };
 
 
 
 
 
356
  } else if (options && typeof options === 'object') {
357
+ args[0] = { ...options, headers:setAuthHeader(options.headers, key) };
358
  }
359
  }
360
  }
361
+ } catch (err) { warn('[key-rotator] http patch error:', err?.message || err); }
362
+
363
+ const req = orig.apply(mod, args);
364
 
365
+ // Intercept response to track 429/success
366
+ if (usedProvider && usedKey) {
367
+ const _emit = req.emit.bind(req);
368
+ req.emit = function (event, ...rest) {
369
+ if (event === 'response') {
370
+ const res = rest[0];
371
+ try { handleStatus(usedProvider, usedKey, res?.statusCode); } catch (_) {}
372
+ }
373
+ return _emit(event, ...rest);
374
+ };
375
+ }
376
+ return req;
377
  };
378
  }
379
 
380
+ // ─── Boot ─────────────────────────────────────────────────────────────────────
381
 
382
  patchFetch();
383
  patchHttpModule(http);
384
  patchHttpModule(https);
385
 
386
+ log(`[key-rotator] loaded β€” cooldown base:${BASE_COOLDOWN_MS/1000}s max-strikes:${MAX_STRIKES} perm-suspend:24h`);
openclaw-sync.py CHANGED
@@ -50,6 +50,7 @@ CONFIG_SETTLE_SECONDS = max(
50
  0.0,
51
  float(os.environ.get("OPENCLAW_CONFIG_SETTLE_SECONDS", "3")),
52
  )
 
53
  HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
54
  HF_USERNAME = os.environ.get("HF_USERNAME", "").strip()
55
  SPACE_AUTHOR_NAME = os.environ.get("SPACE_AUTHOR_NAME", "").strip()
@@ -75,12 +76,14 @@ EXCLUDED_STATE_NAMES = {
75
  "browser",
76
  "npm",
77
  }
 
78
  WHATSAPP_CREDS_DIR = OPENCLAW_HOME / "credentials" / "whatsapp" / "default"
79
  WHATSAPP_BACKUP_DIR = STATE_DIR / "credentials" / "whatsapp" / "default"
80
  RESET_MARKER = WORKSPACE / ".reset_credentials"
81
  HF_API = HfApi(token=HF_TOKEN) if HF_TOKEN else None
82
  STOP_EVENT = threading.Event()
83
  _REPO_ID_CACHE: str | None = None
 
84
  WorkspaceMarker: TypeAlias = tuple[int, int, int, str]
85
 
86
 
@@ -108,6 +111,35 @@ def count_files(path: Path) -> int:
108
  return sum(1 for child in path.rglob("*") if child.is_file())
109
 
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  def snapshot_state_into_workspace() -> None:
112
  try:
113
  STATE_DIR.mkdir(parents=True, exist_ok=True)
@@ -117,18 +149,47 @@ def snapshot_state_into_workspace() -> None:
117
  staging_dir = STATE_DIR / ".openclaw-staging"
118
  if staging_dir.exists():
119
  shutil.rmtree(staging_dir, ignore_errors=True)
120
- staging_dir.mkdir(parents=True, exist_ok=True)
 
 
 
121
 
 
 
122
  for source_path in OPENCLAW_HOME.iterdir():
123
  if source_path.name in EXCLUDED_STATE_NAMES:
124
  continue
125
 
126
  backup_path = staging_dir / source_path.name
127
- if source_path.is_dir():
128
- shutil.copytree(source_path, backup_path)
129
- elif source_path.is_file():
130
- shutil.copy2(source_path, backup_path)
131
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  # Atomically swap staging β†’ real backup dir
133
  if OPENCLAW_STATE_BACKUP_DIR.exists():
134
  shutil.rmtree(OPENCLAW_STATE_BACKUP_DIR, ignore_errors=True)
@@ -525,6 +586,86 @@ def is_valid_json_file(path: Path) -> bool:
525
  return False
526
 
527
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
528
  def wait_for_config_settle(config_marker: tuple[int, int, int]) -> tuple[str, tuple[int, int, int]]:
529
  stable_since = time.monotonic()
530
  current_marker = config_marker
@@ -547,14 +688,32 @@ def wait_for_config_settle(config_marker: tuple[int, int, int]) -> tuple[str, tu
547
  return ("stopped", current_marker)
548
 
549
 
550
- def wait_for_sync_trigger(config_marker: tuple[int, int, int]) -> tuple[str, tuple[int, int, int]]:
 
 
 
551
  deadline = time.monotonic() + max(0, INTERVAL)
 
 
 
 
 
552
 
553
  while not STOP_EVENT.is_set():
554
  current_config_marker = file_marker(OPENCLAW_CONFIG_FILE)
555
  if current_config_marker != config_marker:
556
  return wait_for_config_settle(current_config_marker)
557
 
 
 
 
 
 
 
 
 
 
 
558
  remaining = deadline - time.monotonic()
559
  if remaining <= 0:
560
  return ("interval", current_config_marker)
@@ -610,11 +769,16 @@ def loop() -> int:
610
  print("Initial workspace fingerprint captured.")
611
 
612
  config_marker = file_marker(OPENCLAW_CONFIG_FILE)
 
 
 
613
 
614
  while not STOP_EVENT.is_set():
615
  try:
616
  sync_started_config_marker = file_marker(OPENCLAW_CONFIG_FILE)
617
  last_fingerprint, last_marker = sync_once(last_fingerprint, last_marker)
 
 
618
  config_marker = file_marker(OPENCLAW_CONFIG_FILE)
619
 
620
  if config_marker != sync_started_config_marker:
@@ -627,12 +791,19 @@ def loop() -> int:
627
  write_status("error", f"Sync failed: {exc}")
628
  print(f"Workspace sync failed: {exc}")
629
  config_marker = file_marker(OPENCLAW_CONFIG_FILE)
 
630
 
631
- trigger, config_marker = wait_for_sync_trigger(config_marker)
 
 
 
632
  if trigger == "stopped":
633
  break
634
  if trigger == "settled":
635
  print("OpenClaw config changed and settled; syncing immediately.")
 
 
 
636
 
637
  return 0
638
 
 
50
  0.0,
51
  float(os.environ.get("OPENCLAW_CONFIG_SETTLE_SECONDS", "3")),
52
  )
53
+ SESSIONS_MIN_SYNC_GAP = int(os.environ.get("SESSIONS_MIN_SYNC_GAP", "30"))
54
  HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
55
  HF_USERNAME = os.environ.get("HF_USERNAME", "").strip()
56
  SPACE_AUTHOR_NAME = os.environ.get("SPACE_AUTHOR_NAME", "").strip()
 
76
  "browser",
77
  "npm",
78
  }
79
+ SESSIONS_ROOT = OPENCLAW_HOME / "agents"
80
  WHATSAPP_CREDS_DIR = OPENCLAW_HOME / "credentials" / "whatsapp" / "default"
81
  WHATSAPP_BACKUP_DIR = STATE_DIR / "credentials" / "whatsapp" / "default"
82
  RESET_MARKER = WORKSPACE / ".reset_credentials"
83
  HF_API = HfApi(token=HF_TOKEN) if HF_TOKEN else None
84
  STOP_EVENT = threading.Event()
85
  _REPO_ID_CACHE: str | None = None
86
+ _SESSIONS_FILE_DIGEST_CACHE: dict[str, tuple[int, int, int, str]] = {}
87
  WorkspaceMarker: TypeAlias = tuple[int, int, int, str]
88
 
89
 
 
111
  return sum(1 for child in path.rglob("*") if child.is_file())
112
 
113
 
114
+ def copy_state_entry_with_retry(source_path: Path, backup_path: Path, attempts: int = 3) -> None:
115
+ """Copy one top-level .openclaw entry with short retries for hot files/dirs."""
116
+ last_exc: Exception | None = None
117
+ for attempt in range(1, attempts + 1):
118
+ try:
119
+ if backup_path.exists():
120
+ if backup_path.is_dir():
121
+ shutil.rmtree(backup_path, ignore_errors=True)
122
+ else:
123
+ backup_path.unlink(missing_ok=True)
124
+ if source_path.is_dir():
125
+ shutil.copytree(source_path, backup_path)
126
+ return
127
+ if source_path.is_file():
128
+ shutil.copy2(source_path, backup_path)
129
+ return
130
+ return
131
+ except Exception as exc:
132
+ last_exc = exc
133
+ if attempt < attempts:
134
+ time.sleep(0.2 * attempt)
135
+ if backup_path.exists():
136
+ if backup_path.is_dir():
137
+ shutil.rmtree(backup_path, ignore_errors=True)
138
+ else:
139
+ backup_path.unlink(missing_ok=True)
140
+ continue
141
+ raise last_exc
142
+
143
  def snapshot_state_into_workspace() -> None:
144
  try:
145
  STATE_DIR.mkdir(parents=True, exist_ok=True)
 
149
  staging_dir = STATE_DIR / ".openclaw-staging"
150
  if staging_dir.exists():
151
  shutil.rmtree(staging_dir, ignore_errors=True)
152
+ if OPENCLAW_STATE_BACKUP_DIR.exists():
153
+ shutil.copytree(OPENCLAW_STATE_BACKUP_DIR, staging_dir)
154
+ else:
155
+ staging_dir.mkdir(parents=True, exist_ok=True)
156
 
157
+ skipped_entries: list[tuple[str, Exception]] = []
158
+ copied_entry_names: set[str] = set()
159
  for source_path in OPENCLAW_HOME.iterdir():
160
  if source_path.name in EXCLUDED_STATE_NAMES:
161
  continue
162
 
163
  backup_path = staging_dir / source_path.name
164
+ try:
165
+ copy_state_entry_with_retry(source_path, backup_path)
166
+ copied_entry_names.add(source_path.name)
167
+ except Exception as entry_exc:
168
+ skipped_entries.append((source_path.name, entry_exc))
169
+
170
+ # If staging was seeded from a previous backup, remove entries that no
171
+ # longer exist in OPENCLAW_HOME so the backup remains a true mirror of
172
+ # current state (except entries intentionally excluded from sync).
173
+ for staged_path in list(staging_dir.iterdir()):
174
+ if staged_path.name in EXCLUDED_STATE_NAMES:
175
+ continue
176
+ if staged_path.name in copied_entry_names:
177
+ continue
178
+ if staged_path.exists():
179
+ if staged_path.is_dir():
180
+ shutil.rmtree(staged_path, ignore_errors=True)
181
+ else:
182
+ staged_path.unlink(missing_ok=True)
183
+
184
+ # If any top-level state entries could not be copied, keep the last
185
+ # known-good version for only those entries (staging was seeded from
186
+ # previous backup). This preserves forward progress for the rest.
187
+ if skipped_entries:
188
+ for name, entry_exc in skipped_entries:
189
+ print(f"Warning: keeping previous state entry {name}: {entry_exc}")
190
+ print(
191
+ "Warning: OpenClaw state snapshot had copy failures; updated remaining state entries."
192
+ )
193
  # Atomically swap staging β†’ real backup dir
194
  if OPENCLAW_STATE_BACKUP_DIR.exists():
195
  shutil.rmtree(OPENCLAW_STATE_BACKUP_DIR, ignore_errors=True)
 
586
  return False
587
 
588
 
589
+ def sessions_marker() -> tuple[int, int, int, str]:
590
+ """Return a lightweight marker for all agent session directories.
591
+
592
+ OpenClaw can use agent profiles beyond "main". Watch every
593
+ */sessions path under .openclaw/agents so session changes always trigger
594
+ syncs regardless of profile name.
595
+ """
596
+ if not SESSIONS_ROOT.exists():
597
+ return (0, 0, 0, "")
598
+
599
+ file_count = 0
600
+ total_size = 0
601
+ newest_mtime = 0
602
+ metadata_hasher = hashlib.sha256()
603
+
604
+ global _SESSIONS_FILE_DIGEST_CACHE
605
+ next_cache: dict[str, tuple[int, int, int, str]] = {}
606
+
607
+ for profile_dir in sorted(SESSIONS_ROOT.iterdir()):
608
+ if not profile_dir.is_dir():
609
+ continue
610
+ sessions_dir = profile_dir / "sessions"
611
+ if not sessions_dir.exists():
612
+ continue
613
+ # Use content fingerprinting for sessions so we detect changes even
614
+ # when file size + mtime metadata appear unchanged across quick writes.
615
+ # (Some tooling can rewrite files in-place with preserved timestamps.)
616
+ marker = metadata_marker(sessions_dir)
617
+ digest = hashlib.sha256()
618
+ for path in sorted(p for p in sessions_dir.rglob("*") if p.is_file()):
619
+ rel = path.relative_to(sessions_dir).as_posix()
620
+ try:
621
+ stat = path.stat()
622
+ except OSError:
623
+ continue
624
+ size = int(stat.st_size)
625
+ mtime_ns = int(stat.st_mtime_ns)
626
+ ctime_ns = int(stat.st_ctime_ns)
627
+ cache_key = f"{profile_dir.name}\0{rel}"
628
+ digest.update(rel.encode("utf-8"))
629
+ digest.update(b"\0")
630
+ digest.update(str(size).encode("ascii"))
631
+ digest.update(b"\0")
632
+ digest.update(str(mtime_ns).encode("ascii"))
633
+ digest.update(b"\0")
634
+ digest.update(str(ctime_ns).encode("ascii"))
635
+ digest.update(b"\0")
636
+ cached = _SESSIONS_FILE_DIGEST_CACHE.get(cache_key)
637
+ if (
638
+ cached is not None
639
+ and cached[0] == size
640
+ and cached[1] == mtime_ns
641
+ and cached[2] == ctime_ns
642
+ ):
643
+ file_digest = cached[3]
644
+ else:
645
+ file_hasher = hashlib.sha256()
646
+ try:
647
+ with path.open("rb") as handle:
648
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
649
+ file_hasher.update(chunk)
650
+ except (FileNotFoundError, IsADirectoryError, NotADirectoryError):
651
+ continue
652
+ file_digest = file_hasher.hexdigest()
653
+ next_cache[cache_key] = (size, mtime_ns, ctime_ns, file_digest)
654
+ digest.update(file_digest.encode("ascii"))
655
+ digest.update(b"\0")
656
+
657
+ file_count += marker[0]
658
+ total_size += marker[1]
659
+ newest_mtime = max(newest_mtime, marker[2])
660
+ metadata_hasher.update(profile_dir.name.encode("utf-8"))
661
+ metadata_hasher.update(b"\0")
662
+ metadata_hasher.update(digest.hexdigest().encode("ascii"))
663
+ metadata_hasher.update(b"\0")
664
+
665
+ _SESSIONS_FILE_DIGEST_CACHE = next_cache
666
+ return (file_count, total_size, newest_mtime, metadata_hasher.hexdigest())
667
+
668
+
669
  def wait_for_config_settle(config_marker: tuple[int, int, int]) -> tuple[str, tuple[int, int, int]]:
670
  stable_since = time.monotonic()
671
  current_marker = config_marker
 
688
  return ("stopped", current_marker)
689
 
690
 
691
+ def wait_for_sync_trigger(
692
+ config_marker: tuple[int, int, int],
693
+ last_sessions_sync_time: float = 0.0,
694
+ ) -> tuple[str, tuple[int, int, int]]:
695
  deadline = time.monotonic() + max(0, INTERVAL)
696
+ # BUG FIX: also watch sessions directory so new/updated sessions
697
+ # trigger an immediate sync instead of waiting the full interval.
698
+ # Without this, sessions created between 180-second intervals were
699
+ # lost when the container restarted (e.g. HF Space going to sleep).
700
+ last_sessions_marker = sessions_marker()
701
 
702
  while not STOP_EVENT.is_set():
703
  current_config_marker = file_marker(OPENCLAW_CONFIG_FILE)
704
  if current_config_marker != config_marker:
705
  return wait_for_config_settle(current_config_marker)
706
 
707
+ sessions_gap_elapsed = (
708
+ time.monotonic() - last_sessions_sync_time >= SESSIONS_MIN_SYNC_GAP
709
+ )
710
+ if sessions_gap_elapsed:
711
+ # Sessions changed -> trigger sync immediately (no settle needed;
712
+ # session files are written atomically by OpenClaw).
713
+ current_sessions_marker = sessions_marker()
714
+ if current_sessions_marker != last_sessions_marker:
715
+ return ("sessions", current_config_marker)
716
+
717
  remaining = deadline - time.monotonic()
718
  if remaining <= 0:
719
  return ("interval", current_config_marker)
 
769
  print("Initial workspace fingerprint captured.")
770
 
771
  config_marker = file_marker(OPENCLAW_CONFIG_FILE)
772
+ last_sessions_sync_time = 0.0
773
+
774
+ sync_trigger = "startup"
775
 
776
  while not STOP_EVENT.is_set():
777
  try:
778
  sync_started_config_marker = file_marker(OPENCLAW_CONFIG_FILE)
779
  last_fingerprint, last_marker = sync_once(last_fingerprint, last_marker)
780
+ if sync_trigger == "sessions":
781
+ last_sessions_sync_time = time.monotonic()
782
  config_marker = file_marker(OPENCLAW_CONFIG_FILE)
783
 
784
  if config_marker != sync_started_config_marker:
 
791
  write_status("error", f"Sync failed: {exc}")
792
  print(f"Workspace sync failed: {exc}")
793
  config_marker = file_marker(OPENCLAW_CONFIG_FILE)
794
+ STOP_EVENT.wait(min(30, SESSIONS_MIN_SYNC_GAP))
795
 
796
+ trigger, config_marker = wait_for_sync_trigger(
797
+ config_marker,
798
+ last_sessions_sync_time=last_sessions_sync_time,
799
+ )
800
  if trigger == "stopped":
801
  break
802
  if trigger == "settled":
803
  print("OpenClaw config changed and settled; syncing immediately.")
804
+ if trigger == "sessions":
805
+ print("Session files changed; syncing immediately.")
806
+ sync_trigger = trigger
807
 
808
  return 0
809
 
start.sh CHANGED
@@ -42,6 +42,9 @@ try:
42
  continue
43
  if str(key) in {"HUGGINGCLAW_ENV_BUNDLE", "ENV_BUNDLE"}:
44
  continue
 
 
 
45
  if os.environ.get(str(key), ""):
46
  continue
47
  if value is None or isinstance(value, (dict, list)):
@@ -96,6 +99,11 @@ if [ "$DEV_MODE_ENABLED" != "true" ] && [ -z "${DEV_MODE:-}" ] && [ -n "${GATEWA
96
  DEV_MODE_ENABLED=true
97
  : # auto-enable is silent; set DEV_MODE=false to opt out
98
  fi
 
 
 
 
 
99
  SYNC_INTERVAL="$(trim_var "${SYNC_INTERVAL:-180}")"
100
  DEVDATA_DATASET_NAME="$(trim_var "${DEVDATA_DATASET_NAME:-huggingclaw-devdata}")"
101
  DEVDATA_SYNC_INTERVAL="$(trim_var "${DEVDATA_SYNC_INTERVAL:-180}")"
@@ -105,6 +113,9 @@ DEVDATA_ENABLED=true
105
  if ! hc_is_true "$DEVDATA_NORMALIZED"; then
106
  DEVDATA_ENABLED=false
107
  fi
 
 
 
108
  if [ -n "${SPACE_HOST:-}" ]; then
109
  OPENCLAW_CONSOLE_LOG_LEVEL="${OPENCLAW_CONSOLE_LOG_LEVEL:-warn}"
110
  OPENCLAW_FILE_LOG_LEVEL="${OPENCLAW_FILE_LOG_LEVEL:-info}"
@@ -197,7 +208,7 @@ case "$LLM_PROVIDER" in
197
  byteplus|byteplus-plan) export BYTEPLUS_API_KEY="$LLM_API_KEY" ;;
198
  qianfan) export QIANFAN_API_KEY="$LLM_API_KEY" ;;
199
  # ── Western Providers ──
200
- mistral|mistralai) export MISTRAL_API_KEY="$LLM_API_KEY" ;;
201
  xai|x-ai) export XAI_API_KEY="$LLM_API_KEY" ;;
202
  nvidia) export NVIDIA_API_KEY="$LLM_API_KEY" ;;
203
  cohere) export COHERE_API_KEY="$LLM_API_KEY" ;;
@@ -208,8 +219,18 @@ case "$LLM_PROVIDER" in
208
  venice) export VENICE_API_KEY="$LLM_API_KEY" ;;
209
  synthetic) export SYNTHETIC_API_KEY="$LLM_API_KEY" ;;
210
  github-copilot) export COPILOT_GITHUB_TOKEN="$LLM_API_KEY" ;;
 
 
 
 
 
 
 
 
 
211
  # ── Fallback: Anthropic (default) ──
212
  *)
 
213
  export ANTHROPIC_API_KEY="$LLM_API_KEY"
214
  ;;
215
  esac
@@ -234,7 +255,6 @@ promote_first_pool_key() {
234
  promote_first_pool_key "ANTHROPIC_API_KEY" "ANTHROPIC_API_KEYS"
235
  promote_first_pool_key "OPENAI_API_KEY" "OPENAI_API_KEYS"
236
  promote_first_pool_key "GEMINI_API_KEY" "GEMINI_API_KEYS"
237
- promote_first_pool_key "GEMINI_API_KEY" "GOOGLE_API_KEYS"
238
  promote_first_pool_key "DEEPSEEK_API_KEY" "DEEPSEEK_API_KEYS"
239
  promote_first_pool_key "OPENROUTER_API_KEY" "OPENROUTER_API_KEYS"
240
  promote_first_pool_key "KILOCODE_API_KEY" "KILOCODE_API_KEYS"
@@ -268,11 +288,6 @@ if [ -z "${MOONSHOT_API_KEY:-}" ] && [ -n "${KIMI_API_KEY:-}" ]; then
268
  fi
269
  promote_first_pool_key "HUGGINGFACE_HUB_TOKEN" "HUGGINGFACE_HUB_TOKENS"
270
 
271
- # Compatibility aliases for Google provider secrets some users already have.
272
- if [ -z "${GEMINI_API_KEY:-}" ] && [ -n "${GOOGLE_API_KEY:-}" ]; then
273
- export GEMINI_API_KEY="$GOOGLE_API_KEY"
274
- fi
275
-
276
  # ── Setup directories ──
277
  mkdir -p /home/node/.openclaw/agents/main/sessions
278
  mkdir -p /home/node/.openclaw/credentials
@@ -307,7 +322,7 @@ else
307
  echo "HF_TOKEN not set β€” running without dataset persistence."
308
  fi
309
 
310
- CLOUDFLARE_WORKERS_TOKEN="${CLOUDFLARE_WORKERS_TOKEN:-${CLOUDFLARE_API_TOKEN:-}}"
311
  export CLOUDFLARE_WORKERS_TOKEN
312
  CF_PROXY_ENV_FILE="/tmp/huggingclaw-cloudflare-proxy.env"
313
  if [ -n "${CLOUDFLARE_WORKERS_TOKEN:-}" ] || [ -n "${CLOUDFLARE_PROXY_URL:-}" ]; then
@@ -326,7 +341,7 @@ CONFIG_JSON=$(cat <<'CONFIGEOF'
326
  {
327
  "gateway": {
328
  "mode": "local",
329
- "port": 7860,
330
  "bind": "lan",
331
  "auth": {
332
  "token": ""
@@ -359,8 +374,10 @@ CONFIG_JSON=$(jq \
359
  --arg fileLevel "$OPENCLAW_FILE_LOG_LEVEL" \
360
  --arg consoleLevel "$OPENCLAW_CONSOLE_LOG_LEVEL" \
361
  --arg consoleStyle "$OPENCLAW_CONSOLE_LOG_STYLE" \
 
362
  '.gateway.auth.token = $token
363
  | .agents.defaults.model = $model
 
364
  | .logging.level = $fileLevel
365
  | .logging.consoleLevel = $consoleLevel
366
  | .logging.consoleStyle = $consoleStyle' <<<"$CONFIG_JSON")
@@ -373,7 +390,7 @@ CUSTOM_MODEL_NAME="${CUSTOM_MODEL_NAME:-$CUSTOM_MODEL_ID}"
373
  CUSTOM_API_KEY="${CUSTOM_API_KEY:-$LLM_API_KEY}"
374
  CUSTOM_API_TYPE="${CUSTOM_API_TYPE:-openai-completions}"
375
  CUSTOM_CONTEXT_WINDOW="${CUSTOM_CONTEXT_WINDOW:-128000}"
376
- CUSTOM_MAX_TOKENS="${CUSTOM_MAX_TOKENS:-500}"
377
 
378
  if [ -n "$CUSTOM_PROVIDER_NAME" ] || [ -n "$CUSTOM_BASE_URL" ] || [ -n "$CUSTOM_MODEL_ID" ]; then
379
  CUSTOM_PROVIDER_NORMALIZED=$(printf '%s' "$CUSTOM_PROVIDER_NAME" | tr '[:upper:]' '[:lower:]')
@@ -464,8 +481,10 @@ inject_provider_models_from_env() {
464
  CONFIG_JSON=$(jq \
465
  --arg provider "$provider" \
466
  --argjson models "$models_json" \
467
- '.models.mode = "merge"
468
- | .models.providers[$provider] = ((.models.providers[$provider] // {}) + {models: $models})' <<<"$CONFIG_JSON")
 
 
469
  }
470
 
471
  # Built-in provider model envs (optional)
@@ -510,12 +529,76 @@ inject_provider_models_from_env "github-copilot" "GITHUB_COPILOT_MODELS" "COPILO
510
 
511
  # Browser configuration (managed local Chromium in HF/Docker)
512
  BROWSER_EXECUTABLE_PATH=""
513
- for candidate in /usr/bin/chromium /usr/bin/chromium-browser /snap/bin/chromium; do
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
514
  if [ -x "$candidate" ]; then
515
- BROWSER_EXECUTABLE_PATH="$candidate"
516
- break
 
 
 
 
 
 
 
 
 
 
 
517
  fi
518
  done
 
 
 
 
 
 
 
 
 
519
 
520
  BROWSER_SHOULD_ENABLE=false
521
  if [ "$BROWSER_PLUGIN_MODE" = "enabled" ] && [ -n "$BROWSER_EXECUTABLE_PATH" ] && [ -x "$BROWSER_EXECUTABLE_PATH" ]; then
@@ -567,13 +650,28 @@ CONFIG_JSON=$(jq \
567
 
568
  if [ "$BROWSER_SHOULD_ENABLE" = "true" ]; then
569
  CONFIG_JSON=$(jq \
570
- --arg execPath "$BROWSER_EXECUTABLE_PATH" \
571
  '.browser = {
572
  "enabled": true,
573
  "defaultProfile": "openclaw",
574
  "headless": true,
575
  "noSandbox": true,
576
- "executablePath": $execPath
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
577
  }
578
  | .agents.defaults.sandbox.browser.allowHostControl = true' <<<"$CONFIG_JSON")
579
  fi
@@ -588,7 +686,7 @@ CONFIG_JSON=$(jq \
588
  | (if $spaceHost != "" then
589
  .gateway.controlUi.allowedOrigins = ["https://" + $spaceHost]
590
  else . end)
591
- | (if $password != "" then
592
  .gateway.auth.mode = "password" | .gateway.auth.password = $password
593
  else . end)' <<<"$CONFIG_JSON")
594
 
@@ -684,6 +782,10 @@ WHATSAPP_CONFIG_ENABLED=false
684
  if [ "$WHATSAPP_ENABLED_NORMALIZED" = "true" ]; then
685
  WHATSAPP_CONFIG_ENABLED=true
686
  fi
 
 
 
 
687
  if [ -f "$EXISTING_CONFIG" ]; then
688
  echo "Restored config found β€” patching required fields and runtime channel/plugin toggles..."
689
  PATCHED=$(jq \
@@ -698,9 +800,11 @@ if [ -f "$EXISTING_CONFIG" ]; then
698
  --argjson consoleStyleConfigured "$OPENCLAW_CONSOLE_LOG_STYLE_CONFIGURED" \
699
  --argjson whatsappConfigured "$WHATSAPP_ENABLED_CONFIGURED" \
700
  --argjson whatsappEnabled "$WHATSAPP_CONFIG_ENABLED" \
 
701
  '(.channels.whatsapp // {}) as $existingWhatsapp
702
  | .gateway.auth.token = $token
703
  | .agents.defaults.model = $model
 
704
  | if $fileLogConfigured then .logging.level = $fileLevel else . end
705
  | if $consoleLogConfigured then .logging.consoleLevel = $consoleLevel else . end
706
  | if $consoleStyleConfigured then .logging.consoleStyle = $consoleStyle else . end
@@ -719,6 +823,13 @@ if [ -f "$EXISTING_CONFIG" ]; then
719
  | del(.channels.whatsapp)
720
  else
721
  .
 
 
 
 
 
 
 
722
  end' \
723
  "$EXISTING_CONFIG" 2>/dev/null)
724
 
@@ -762,7 +873,13 @@ fi
762
  if [ -n "${CLOUDFLARE_PROXY_URL:-}" ]; then
763
  echo "Proxy : ${CLOUDFLARE_PROXY_URL}"
764
  fi
765
- RUNTIME_JUPYTER_ENABLED="$DEV_MODE_ENABLED"
 
 
 
 
 
 
766
  # Add user bin to PATH for jupyter-lab (installed in Dockerfile when DEV_MODE=true)
767
  export PATH="$HOME/.local/bin:$PATH"
768
 
@@ -807,6 +924,17 @@ graceful_shutdown() {
807
  echo "Shutting down..."
808
  if [ -f "/home/node/app/openclaw-sync.py" ] && [ -n "${HF_TOKEN:-}" ]; then
809
  echo "Saving state before exit..."
 
 
 
 
 
 
 
 
 
 
 
810
  timeout 8s python3 /home/node/app/openclaw-sync.py sync-once-settled || \
811
  echo "Warning: could not complete settled shutdown sync"
812
  sleep 1
@@ -820,20 +948,24 @@ graceful_shutdown() {
820
  }
821
  trap graceful_shutdown SIGTERM SIGINT
822
 
 
823
  warmup_browser() {
824
  [ "$BROWSER_SHOULD_ENABLE" = "true" ] || return 0
 
 
 
825
 
826
  (
827
- sleep 5
828
 
829
  local attempt
830
- for attempt in 1 2 3 4 5; do
831
  if openclaw browser --browser-profile openclaw start >/dev/null 2>&1; then
832
  openclaw browser --browser-profile openclaw open about:blank >/dev/null 2>&1 || true
833
  echo "Managed browser ready."
834
  return 0
835
  fi
836
- sleep 2
837
  done
838
 
839
  echo "Warning: managed browser warm-up did not complete; first browser action may need a retry."
@@ -843,6 +975,21 @@ warmup_browser() {
843
 
844
  # ── Start background services ──
845
  export LLM_MODEL="$LLM_MODEL"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
846
  # 10. Start Health Server & Dashboard
847
  node /home/node/app/health-server.js &
848
  HEALTH_PID=$!
@@ -885,6 +1032,11 @@ start_jupyter_once() {
885
  ln -sfn /home/node/.openclaw/workspace "$JUPYTER_ROOT_DIR/HuggingClaw-Workspace"
886
  fi
887
  fi
 
 
 
 
 
888
 
889
  # Pre-create runtime directory
890
  mkdir -p "$JUPYTER_ROOT_DIR/.jupyter"
@@ -1248,7 +1400,7 @@ fi
1248
  # Runs user-provided boot commands one by one so failures are visible in logs.
1249
  # By default failures are logged and boot continues; set
1250
  # HUGGINGCLAW_STARTUP_STRICT=true to fail the Space startup on any error.
1251
- HC_STARTUP_FAILURES=0
1252
  HC_STARTUP_STRICT_NORMALIZED=$(printf '%s' "${HUGGINGCLAW_STARTUP_STRICT:-false}" | tr '[:upper:]' '[:lower:]')
1253
  hc_run_startup_command() {
1254
  local source_label="$1"
@@ -1427,6 +1579,11 @@ if [ -n "${HUGGINGCLAW_OPENCLAW_PLUGINS:-}" ]; then
1427
  fi
1428
  fi
1429
 
 
 
 
 
 
1430
  # ── Arbitrary startup commands from HF Variables/Secrets ──
1431
  # Recommended: use one variable, HUGGINGCLAW_RUN, as a full bash script. If the
1432
  # value starts with base64: or b64:, the rest is decoded and run as the script.
@@ -1543,6 +1700,16 @@ start_guardian_once() {
1543
  echo "WhatsApp Guardian started (PID: $GUARDIAN_PID)"
1544
  }
1545
 
 
 
 
 
 
 
 
 
 
 
1546
  while true; do
1547
  # Check health-server process - restart if died unexpectedly
1548
  if [ -n "${HEALTH_PID:-}" ] && ! kill -0 "$HEALTH_PID" 2>/dev/null; then
@@ -1568,9 +1735,12 @@ while true; do
1568
  fi
1569
  fi
1570
 
1571
- echo "Launching OpenClaw gateway on port 7860..."
 
 
 
1572
 
1573
- GATEWAY_ARGS=(gateway run --port 7860 --bind lan)
1574
  if [ "${GATEWAY_VERBOSE:-0}" = "1" ]; then
1575
  GATEWAY_ARGS+=(--verbose)
1576
  echo "Gateway verbose logging enabled (GATEWAY_VERBOSE=1)"
@@ -1583,13 +1753,13 @@ while true; do
1583
  stdbuf -oL -eL openclaw "${GATEWAY_ARGS[@]}" 2>&1 | tee -a /home/node/.openclaw/gateway.log &
1584
  GATEWAY_PID=$!
1585
 
1586
- # Poll for the gateway to start listening on 7860. OpenClaw can take 20-30s
1587
  # on cold start (plugin install + auto-restore). Bail out early if the
1588
  # pipeline died.
1589
  GATEWAY_READY_TIMEOUT="${GATEWAY_READY_TIMEOUT:-90}"
1590
  ready=false
1591
  for ((i=0; i<GATEWAY_READY_TIMEOUT; i++)); do
1592
- if (echo > /dev/tcp/127.0.0.1/7860) 2>/dev/null; then
1593
  ready=true
1594
  break
1595
  fi
@@ -1604,7 +1774,14 @@ while true; do
1604
  echo "Gateway failed to start. Last 30 lines of log:"
1605
  echo "────────────────────────────────────────────"
1606
  tail -30 /home/node/.openclaw/gateway.log
1607
- exit 1
 
 
 
 
 
 
 
1608
  fi
1609
 
1610
  # 11. Start WhatsApp Guardian after the gateway is accepting connections
@@ -1629,7 +1806,8 @@ while true; do
1629
  GATEWAY_RESTART_COUNT=$((GATEWAY_RESTART_COUNT + 1))
1630
  if [ "$GATEWAY_MAX_RESTARTS" != "0" ] && [ "$GATEWAY_RESTART_COUNT" -ge "$GATEWAY_MAX_RESTARTS" ]; then
1631
  echo "Gateway exited with code ${GATEWAY_EXIT_CODE}; restart limit (${GATEWAY_MAX_RESTARTS}) reached."
1632
- exit "$GATEWAY_EXIT_CODE"
 
1633
  fi
1634
 
1635
  echo "Gateway exited with code ${GATEWAY_EXIT_CODE}; restarting in ${GATEWAY_RESTART_DELAY}s..."
 
42
  continue
43
  if str(key) in {"HUGGINGCLAW_ENV_BUNDLE", "ENV_BUNDLE"}:
44
  continue
45
+ if str(key) == "OPENCLAW_VERSION":
46
+ print("Warning: OPENCLAW_VERSION from env bundle is ignored (build-time only; set HF Variable and rebuild).", file=sys.stderr)
47
+ continue
48
  if os.environ.get(str(key), ""):
49
  continue
50
  if value is None or isinstance(value, (dict, list)):
 
99
  DEV_MODE_ENABLED=true
100
  : # auto-enable is silent; set DEV_MODE=false to opt out
101
  fi
102
+ if [ "$DEV_MODE_ENABLED" = "true" ]; then
103
+ export DEV_MODE=true
104
+ else
105
+ export DEV_MODE=false
106
+ fi
107
  SYNC_INTERVAL="$(trim_var "${SYNC_INTERVAL:-180}")"
108
  DEVDATA_DATASET_NAME="$(trim_var "${DEVDATA_DATASET_NAME:-huggingclaw-devdata}")"
109
  DEVDATA_SYNC_INTERVAL="$(trim_var "${DEVDATA_SYNC_INTERVAL:-180}")"
 
113
  if ! hc_is_true "$DEVDATA_NORMALIZED"; then
114
  DEVDATA_ENABLED=false
115
  fi
116
+ # On HF Spaces, browser is disabled by default (no display server).
117
+ # To enable: set BROWSER_PLUGIN_MODE=enabled as an HF Space secret.
118
+ # WARNING: requires at least CPU Upgrade tier (2 vCPU / 16GB RAM).
119
  if [ -n "${SPACE_HOST:-}" ]; then
120
  OPENCLAW_CONSOLE_LOG_LEVEL="${OPENCLAW_CONSOLE_LOG_LEVEL:-warn}"
121
  OPENCLAW_FILE_LOG_LEVEL="${OPENCLAW_FILE_LOG_LEVEL:-info}"
 
208
  byteplus|byteplus-plan) export BYTEPLUS_API_KEY="$LLM_API_KEY" ;;
209
  qianfan) export QIANFAN_API_KEY="$LLM_API_KEY" ;;
210
  # ── Western Providers ──
211
+ mistral) export MISTRAL_API_KEY="$LLM_API_KEY" ;;
212
  xai|x-ai) export XAI_API_KEY="$LLM_API_KEY" ;;
213
  nvidia) export NVIDIA_API_KEY="$LLM_API_KEY" ;;
214
  cohere) export COHERE_API_KEY="$LLM_API_KEY" ;;
 
219
  venice) export VENICE_API_KEY="$LLM_API_KEY" ;;
220
  synthetic) export SYNTHETIC_API_KEY="$LLM_API_KEY" ;;
221
  github-copilot) export COPILOT_GITHUB_TOKEN="$LLM_API_KEY" ;;
222
+ llama-3.*|llama-4.*|mixtral-*|gemma-*)
223
+ export GROQ_API_KEY="$LLM_API_KEY"
224
+ echo "Note: bare Groq model '$LLM_MODEL' detected; mapped LLM_API_KEY β†’ GROQ_API_KEY. Use 'groq/${LLM_MODEL}' prefix to be explicit." ;;
225
+ mistral-*|codestral-*|devstral-*|voxtral-*)
226
+ export MISTRAL_API_KEY="$LLM_API_KEY"
227
+ echo "Note: bare Mistral model '$LLM_MODEL' detected; mapped LLM_API_KEY β†’ MISTRAL_API_KEY. Use 'mistral/${LLM_MODEL}' prefix to be explicit." ;;
228
+ moonshotai|meta-llama|deepseek-ai|MiniMaxAI|minimax-ai|Qwen|zai-org|mistralai|google)
229
+ echo "Warning: LLM_MODEL='$LLM_MODEL' uses sub-provider prefix '$LLM_PROVIDER'. This is a router-namespaced model (Together/OpenRouter). Mapping LLM_API_KEY β†’ TOGETHER_API_KEY. If using OpenRouter, also set OPENROUTER_API_KEY as a separate secret."
230
+ export TOGETHER_API_KEY="${TOGETHER_API_KEY:-$LLM_API_KEY}" ;;
231
  # ── Fallback: Anthropic (default) ──
232
  *)
233
+ echo "Warning: Unknown provider prefix '$LLM_PROVIDER' in LLM_MODEL='$LLM_MODEL'. Defaulting to ANTHROPIC_API_KEY. If using a router-namespaced model (e.g. moonshotai/Kimi-K2.5), set TOGETHER_API_KEY or OPENROUTER_API_KEY as a separate secret."
234
  export ANTHROPIC_API_KEY="$LLM_API_KEY"
235
  ;;
236
  esac
 
255
  promote_first_pool_key "ANTHROPIC_API_KEY" "ANTHROPIC_API_KEYS"
256
  promote_first_pool_key "OPENAI_API_KEY" "OPENAI_API_KEYS"
257
  promote_first_pool_key "GEMINI_API_KEY" "GEMINI_API_KEYS"
 
258
  promote_first_pool_key "DEEPSEEK_API_KEY" "DEEPSEEK_API_KEYS"
259
  promote_first_pool_key "OPENROUTER_API_KEY" "OPENROUTER_API_KEYS"
260
  promote_first_pool_key "KILOCODE_API_KEY" "KILOCODE_API_KEYS"
 
288
  fi
289
  promote_first_pool_key "HUGGINGFACE_HUB_TOKEN" "HUGGINGFACE_HUB_TOKENS"
290
 
 
 
 
 
 
291
  # ── Setup directories ──
292
  mkdir -p /home/node/.openclaw/agents/main/sessions
293
  mkdir -p /home/node/.openclaw/credentials
 
322
  echo "HF_TOKEN not set β€” running without dataset persistence."
323
  fi
324
 
325
+ CLOUDFLARE_WORKERS_TOKEN="${CLOUDFLARE_WORKERS_TOKEN:-}"
326
  export CLOUDFLARE_WORKERS_TOKEN
327
  CF_PROXY_ENV_FILE="/tmp/huggingclaw-cloudflare-proxy.env"
328
  if [ -n "${CLOUDFLARE_WORKERS_TOKEN:-}" ] || [ -n "${CLOUDFLARE_PROXY_URL:-}" ]; then
 
341
  {
342
  "gateway": {
343
  "mode": "local",
344
+ "port": "${GATEWAY_PORT}",
345
  "bind": "lan",
346
  "auth": {
347
  "token": ""
 
374
  --arg fileLevel "$OPENCLAW_FILE_LOG_LEVEL" \
375
  --arg consoleLevel "$OPENCLAW_CONSOLE_LOG_LEVEL" \
376
  --arg consoleStyle "$OPENCLAW_CONSOLE_LOG_STYLE" \
377
+ --arg port "$GATEWAY_PORT" \
378
  '.gateway.auth.token = $token
379
  | .agents.defaults.model = $model
380
+ | .gateway.port = ($port | tonumber)
381
  | .logging.level = $fileLevel
382
  | .logging.consoleLevel = $consoleLevel
383
  | .logging.consoleStyle = $consoleStyle' <<<"$CONFIG_JSON")
 
390
  CUSTOM_API_KEY="${CUSTOM_API_KEY:-$LLM_API_KEY}"
391
  CUSTOM_API_TYPE="${CUSTOM_API_TYPE:-openai-completions}"
392
  CUSTOM_CONTEXT_WINDOW="${CUSTOM_CONTEXT_WINDOW:-128000}"
393
+ CUSTOM_MAX_TOKENS="${CUSTOM_MAX_TOKENS:-8192}"
394
 
395
  if [ -n "$CUSTOM_PROVIDER_NAME" ] || [ -n "$CUSTOM_BASE_URL" ] || [ -n "$CUSTOM_MODEL_ID" ]; then
396
  CUSTOM_PROVIDER_NORMALIZED=$(printf '%s' "$CUSTOM_PROVIDER_NAME" | tr '[:upper:]' '[:lower:]')
 
481
  CONFIG_JSON=$(jq \
482
  --arg provider "$provider" \
483
  --argjson models "$models_json" \
484
+ 'if .models.providers[$provider] then
485
+ .models.mode = "merge"
486
+ | .models.providers[$provider].models = $models
487
+ else . end' <<<"$CONFIG_JSON")
488
  }
489
 
490
  # Built-in provider model envs (optional)
 
529
 
530
  # Browser configuration (managed local Chromium in HF/Docker)
531
  BROWSER_EXECUTABLE_PATH=""
532
+ BROWSER_WRAPPER_PATH=""
533
+ HAS_FILE_CMD=false
534
+ if command -v file >/dev/null 2>&1; then
535
+ HAS_FILE_CMD=true
536
+ fi
537
+
538
+ ensure_chromium_for_browser_plugin() {
539
+ # Enforce Chromium availability when browser plugin is explicitly enabled.
540
+ [ "$BROWSER_PLUGIN_MODE" = "enabled" ] || return 0
541
+ for candidate in /usr/lib/chromium/chromium /usr/bin/chromium /usr/bin/chromium-browser; do
542
+ [ -x "$candidate" ] && return 0
543
+ done
544
+ if [ "$HAS_FILE_CMD" != "true" ]; then
545
+ echo "BROWSER_PLUGIN_MODE=enabled and 'file' command is missing; attempting runtime install..."
546
+ if _hc_apt_install file; then
547
+ HAS_FILE_CMD=true
548
+ echo "'file' command installed via apt-get."
549
+ else
550
+ echo "Warning: could not install 'file'; continuing with executable-path fallback checks."
551
+ fi
552
+ fi
553
+ echo "BROWSER_PLUGIN_MODE=enabled but Chromium is missing; attempting runtime install..."
554
+ if _hc_apt_install chromium; then
555
+ echo "Chromium installed via apt-get."
556
+ return 0
557
+ fi
558
+ if _hc_apt_install chromium-browser; then
559
+ echo "Chromium browser package installed via apt-get."
560
+ return 0
561
+ fi
562
+ echo "ERROR: Browser plugin is enabled, but Chromium install failed. Disable browser plugin or rebuild image with Chromium preinstalled." >&2
563
+ return 1
564
+ }
565
+ HC_STARTUP_FAILURES=0
566
+ ensure_chromium_for_browser_plugin || HC_STARTUP_FAILURES=$((HC_STARTUP_FAILURES + 1))
567
+
568
+ # On Debian/Ubuntu, /usr/bin/chromium is often a shell wrapper while the real
569
+ # ELF binary lives under /usr/lib/chromium/*. Prefer a real ELF binary, then
570
+ # fall back to wrapper launchers (Playwright/OpenClaw can execute those too).
571
+ for candidate in \
572
+ /usr/lib/chromium/chromium \
573
+ /usr/lib/chromium-browser/chromium-browser \
574
+ /usr/bin/chromium \
575
+ /usr/bin/chromium-browser \
576
+ /snap/bin/chromium; do
577
  if [ -x "$candidate" ]; then
578
+ if [ "$HAS_FILE_CMD" = "true" ]; then
579
+ if file "$candidate" 2>/dev/null | grep -q "ELF"; then
580
+ BROWSER_EXECUTABLE_PATH="$candidate"
581
+ break
582
+ fi
583
+ else
584
+ # Minimal images may not ship `file`; accept the first executable path.
585
+ BROWSER_EXECUTABLE_PATH="$candidate"
586
+ break
587
+ fi
588
+ if [ -z "$BROWSER_WRAPPER_PATH" ]; then
589
+ BROWSER_WRAPPER_PATH="$candidate"
590
+ fi
591
  fi
592
  done
593
+ if [ -z "$BROWSER_EXECUTABLE_PATH" ] && [ -n "$BROWSER_WRAPPER_PATH" ]; then
594
+ BROWSER_EXECUTABLE_PATH="$BROWSER_WRAPPER_PATH"
595
+ echo "No ELF Chromium binary found; using launcher wrapper at $BROWSER_EXECUTABLE_PATH"
596
+ elif [ -n "$BROWSER_EXECUTABLE_PATH" ] && [ "$HAS_FILE_CMD" != "true" ]; then
597
+ echo "Detected Chromium executable at $BROWSER_EXECUTABLE_PATH (ELF probe skipped: 'file' command not installed)"
598
+ fi
599
+ if [ -z "$BROWSER_EXECUTABLE_PATH" ]; then
600
+ echo "Warning: Chromium executable not found. Browser plugin will be disabled."
601
+ fi
602
 
603
  BROWSER_SHOULD_ENABLE=false
604
  if [ "$BROWSER_PLUGIN_MODE" = "enabled" ] && [ -n "$BROWSER_EXECUTABLE_PATH" ] && [ -x "$BROWSER_EXECUTABLE_PATH" ]; then
 
650
 
651
  if [ "$BROWSER_SHOULD_ENABLE" = "true" ]; then
652
  CONFIG_JSON=$(jq \
 
653
  '.browser = {
654
  "enabled": true,
655
  "defaultProfile": "openclaw",
656
  "headless": true,
657
  "noSandbox": true,
658
+ "extraArgs": [
659
+ "--headless=new",
660
+ "--no-sandbox",
661
+ "--disable-setuid-sandbox",
662
+ "--no-zygote",
663
+ "--disable-dev-shm-usage",
664
+ "--disable-gpu",
665
+ "--remote-debugging-address=127.0.0.1",
666
+ "--disable-features=UseDBus,MediaRouter",
667
+ "--password-store=basic",
668
+ "--no-first-run",
669
+ "--disable-background-networking",
670
+ "--disable-sync",
671
+ "--disable-translate",
672
+ "--disable-notifications",
673
+ "--disable-speech-api"
674
+ ]
675
  }
676
  | .agents.defaults.sandbox.browser.allowHostControl = true' <<<"$CONFIG_JSON")
677
  fi
 
686
  | (if $spaceHost != "" then
687
  .gateway.controlUi.allowedOrigins = ["https://" + $spaceHost]
688
  else . end)
689
+ | (if ($password != "" and (.gateway.auth.token // "") == "") then
690
  .gateway.auth.mode = "password" | .gateway.auth.password = $password
691
  else . end)' <<<"$CONFIG_JSON")
692
 
 
782
  if [ "$WHATSAPP_ENABLED_NORMALIZED" = "true" ]; then
783
  WHATSAPP_CONFIG_ENABLED=true
784
  fi
785
+ TELEGRAM_CONFIG_ENABLED=false
786
+ if [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; then
787
+ TELEGRAM_CONFIG_ENABLED=true
788
+ fi
789
  if [ -f "$EXISTING_CONFIG" ]; then
790
  echo "Restored config found β€” patching required fields and runtime channel/plugin toggles..."
791
  PATCHED=$(jq \
 
800
  --argjson consoleStyleConfigured "$OPENCLAW_CONSOLE_LOG_STYLE_CONFIGURED" \
801
  --argjson whatsappConfigured "$WHATSAPP_ENABLED_CONFIGURED" \
802
  --argjson whatsappEnabled "$WHATSAPP_CONFIG_ENABLED" \
803
+ --argjson telegramConfigured "$TELEGRAM_CONFIG_ENABLED" \
804
  '(.channels.whatsapp // {}) as $existingWhatsapp
805
  | .gateway.auth.token = $token
806
  | .agents.defaults.model = $model
807
+ | .gateway.port = ($desired.gateway.port // .gateway.port)
808
  | if $fileLogConfigured then .logging.level = $fileLevel else . end
809
  | if $consoleLogConfigured then .logging.consoleLevel = $consoleLevel else . end
810
  | if $consoleStyleConfigured then .logging.consoleStyle = $consoleStyle else . end
 
823
  | del(.channels.whatsapp)
824
  else
825
  .
826
+ end
827
+ | if $telegramConfigured then
828
+ .channels.telegram = (($desired.channels.telegram // {}) * (.channels.telegram // {}))
829
+ | .channels.telegram.botToken = $desired.channels.telegram.botToken
830
+ else
831
+ del(.channels.telegram)
832
+ | .plugins.entries.telegram.enabled = false
833
  end' \
834
  "$EXISTING_CONFIG" 2>/dev/null)
835
 
 
873
  if [ -n "${CLOUDFLARE_PROXY_URL:-}" ]; then
874
  echo "Proxy : ${CLOUDFLARE_PROXY_URL}"
875
  fi
876
+ # HUGGINGCLAW_JUPYTER_ENABLED env var se override allow karo
877
+ # (env-builder "Enable Jupyter terminal" toggle yahi set karta hai)
878
+ if hc_is_true "${HUGGINGCLAW_JUPYTER_ENABLED:-false}"; then
879
+ RUNTIME_JUPYTER_ENABLED=true
880
+ else
881
+ RUNTIME_JUPYTER_ENABLED="$DEV_MODE_ENABLED"
882
+ fi
883
  # Add user bin to PATH for jupyter-lab (installed in Dockerfile when DEV_MODE=true)
884
  export PATH="$HOME/.local/bin:$PATH"
885
 
 
924
  echo "Shutting down..."
925
  if [ -f "/home/node/app/openclaw-sync.py" ] && [ -n "${HF_TOKEN:-}" ]; then
926
  echo "Saving state before exit..."
927
+ # BUG FIX: kill the background sync loop *before* running the shutdown
928
+ # syncs. The loop holds the sync lock while uploading; if it is
929
+ # mid-upload when sync-once-settled runs, the 8-second timeout fires
930
+ # before the lock is released and the settled-sync is silently skipped.
931
+ # Killing the loop first releases the lock immediately (fcntl.flock is
932
+ # released on process exit) so sync-once-settled can acquire it cleanly.
933
+ if [ -n "${SYNC_LOOP_PID:-}" ]; then
934
+ kill "$SYNC_LOOP_PID" 2>/dev/null || true
935
+ # Give Python a moment to flush and release the lock file.
936
+ sleep 0.5
937
+ fi
938
  timeout 8s python3 /home/node/app/openclaw-sync.py sync-once-settled || \
939
  echo "Warning: could not complete settled shutdown sync"
940
  sleep 1
 
948
  }
949
  trap graceful_shutdown SIGTERM SIGINT
950
 
951
+ BROWSER_WARMED_UP=false
952
  warmup_browser() {
953
  [ "$BROWSER_SHOULD_ENABLE" = "true" ] || return 0
954
+ # Only warm up once β€” gateway restarts should not re-spawn new warmup jobs.
955
+ [ "$BROWSER_WARMED_UP" = "false" ] || return 0
956
+ BROWSER_WARMED_UP=true
957
 
958
  (
959
+ sleep 8
960
 
961
  local attempt
962
+ for attempt in 1 2 3 4 5 6; do
963
  if openclaw browser --browser-profile openclaw start >/dev/null 2>&1; then
964
  openclaw browser --browser-profile openclaw open about:blank >/dev/null 2>&1 || true
965
  echo "Managed browser ready."
966
  return 0
967
  fi
968
+ sleep 5
969
  done
970
 
971
  echo "Warning: managed browser warm-up did not complete; first browser action may need a retry."
 
975
 
976
  # ── Start background services ──
977
  export LLM_MODEL="$LLM_MODEL"
978
+
979
+ # ── Ensure key-rotator uses the correct HF token for huggingface.co calls ──
980
+ # NODE_OPTIONS preloads multi-provider-key-rotator.cjs into health-server.js.
981
+ # The rotator patches https.request and injects HUGGINGFACE_HUB_TOKEN (or
982
+ # falls back to LLM_API_KEY) for any call to huggingface.co β€” including the
983
+ # privacy-detection API call in detectSpacePrivacy(). If HUGGINGFACE_HUB_TOKEN
984
+ # is not set (user's LLM provider is not HuggingFace), the rotator falls back
985
+ # to LLM_API_KEY, which is the AI-provider key, NOT the HF owner token.
986
+ # This causes a 401 on /api/spaces/${SPACE_ID} β†’ privacy detection always
987
+ # fails β†’ SPACE_IS_PRIVATE stays true β†’ public-space links never open in a
988
+ # new tab.
989
+ # Fix: seed HUGGINGFACE_HUB_TOKEN from HF_TOKEN when not already set.
990
+ # HF Spaces auto-injects HF_TOKEN as the space owner's token, so this is safe.
991
+ export HUGGINGFACE_HUB_TOKEN="${HUGGINGFACE_HUB_TOKEN:-${HF_TOKEN:-}}"
992
+
993
  # 10. Start Health Server & Dashboard
994
  node /home/node/app/health-server.js &
995
  HEALTH_PID=$!
 
1032
  ln -sfn /home/node/.openclaw/workspace "$JUPYTER_ROOT_DIR/HuggingClaw-Workspace"
1033
  fi
1034
  fi
1035
+ if [ "$JUPYTER_ROOT_DIR" != "/home/node/.openclaw" ]; then
1036
+ if [ -L "$JUPYTER_ROOT_DIR/OpenClaw-Home" ] || [ ! -e "$JUPYTER_ROOT_DIR/OpenClaw-Home" ]; then
1037
+ ln -sfn /home/node/.openclaw "$JUPYTER_ROOT_DIR/OpenClaw-Home"
1038
+ fi
1039
+ fi
1040
 
1041
  # Pre-create runtime directory
1042
  mkdir -p "$JUPYTER_ROOT_DIR/.jupyter"
 
1400
  # Runs user-provided boot commands one by one so failures are visible in logs.
1401
  # By default failures are logged and boot continues; set
1402
  # HUGGINGCLAW_STARTUP_STRICT=true to fail the Space startup on any error.
1403
+ # HC_STARTUP_FAILURES initialized earlier (before Chromium ensure check)
1404
  HC_STARTUP_STRICT_NORMALIZED=$(printf '%s' "${HUGGINGCLAW_STARTUP_STRICT:-false}" | tr '[:upper:]' '[:lower:]')
1405
  hc_run_startup_command() {
1406
  local source_label="$1"
 
1579
  fi
1580
  fi
1581
 
1582
+ # ── Fix config before running startup commands ──
1583
+ if [ "${AUTO_DOCTOR:-false}" = "true" ]; then
1584
+ openclaw doctor --fix || true
1585
+ fi
1586
+
1587
  # ── Arbitrary startup commands from HF Variables/Secrets ──
1588
  # Recommended: use one variable, HUGGINGCLAW_RUN, as a full bash script. If the
1589
  # value starts with base64: or b64:, the rest is decoded and run as the script.
 
1700
  echo "WhatsApp Guardian started (PID: $GUARDIAN_PID)"
1701
  }
1702
 
1703
+ # ── Start D-Bus session (once, before gateway loop) ──
1704
+ if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then
1705
+ if command -v dbus-launch >/dev/null 2>&1; then
1706
+ eval "$(dbus-launch --sh-syntax 2>/dev/null)" || true
1707
+ export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-disabled:}"
1708
+ else
1709
+ export DBUS_SESSION_BUS_ADDRESS="disabled:"
1710
+ fi
1711
+ fi
1712
+
1713
  while true; do
1714
  # Check health-server process - restart if died unexpectedly
1715
  if [ -n "${HEALTH_PID:-}" ] && ! kill -0 "$HEALTH_PID" 2>/dev/null; then
 
1735
  fi
1736
  fi
1737
 
1738
+ if [ "${AUTO_DOCTOR:-false}" = "true" ]; then
1739
+ openclaw doctor --fix || true
1740
+ fi
1741
+ echo "Launching OpenClaw gateway on port ${GATEWAY_PORT}..."
1742
 
1743
+ GATEWAY_ARGS=(gateway run --port "${GATEWAY_PORT}" --bind lan)
1744
  if [ "${GATEWAY_VERBOSE:-0}" = "1" ]; then
1745
  GATEWAY_ARGS+=(--verbose)
1746
  echo "Gateway verbose logging enabled (GATEWAY_VERBOSE=1)"
 
1753
  stdbuf -oL -eL openclaw "${GATEWAY_ARGS[@]}" 2>&1 | tee -a /home/node/.openclaw/gateway.log &
1754
  GATEWAY_PID=$!
1755
 
1756
+ # Poll for the gateway to start listening on ${GATEWAY_PORT}. OpenClaw can take 20-30s
1757
  # on cold start (plugin install + auto-restore). Bail out early if the
1758
  # pipeline died.
1759
  GATEWAY_READY_TIMEOUT="${GATEWAY_READY_TIMEOUT:-90}"
1760
  ready=false
1761
  for ((i=0; i<GATEWAY_READY_TIMEOUT; i++)); do
1762
+ if (echo > /dev/tcp/127.0.0.1/${GATEWAY_PORT}) 2>/dev/null; then
1763
  ready=true
1764
  break
1765
  fi
 
1774
  echo "Gateway failed to start. Last 30 lines of log:"
1775
  echo "────────────────────────────────────────────"
1776
  tail -30 /home/node/.openclaw/gateway.log
1777
+ if [ "$DEV_MODE_ENABLED" = "true" ]; then
1778
+ echo "Gateway failed β€” DEV_MODE active, retrying in 10s..."
1779
+ sleep 10
1780
+ continue
1781
+ else
1782
+ echo "Gateway failed β€” exiting."
1783
+ exit 1
1784
+ fi
1785
  fi
1786
 
1787
  # 11. Start WhatsApp Guardian after the gateway is accepting connections
 
1806
  GATEWAY_RESTART_COUNT=$((GATEWAY_RESTART_COUNT + 1))
1807
  if [ "$GATEWAY_MAX_RESTARTS" != "0" ] && [ "$GATEWAY_RESTART_COUNT" -ge "$GATEWAY_MAX_RESTARTS" ]; then
1808
  echo "Gateway exited with code ${GATEWAY_EXIT_CODE}; restart limit (${GATEWAY_MAX_RESTARTS}) reached."
1809
+ echo "Gateway stopped β€” JupyterLab and env-builder still running."
1810
+ break
1811
  fi
1812
 
1813
  echo "Gateway exited with code ${GATEWAY_EXIT_CODE}; restarting in ${GATEWAY_RESTART_DELAY}s..."
wa-guardian.js CHANGED
@@ -17,7 +17,8 @@ try {
17
  }
18
  const { randomUUID } = require('node:crypto');
19
 
20
- const GATEWAY_URL = "ws://127.0.0.1:7860";
 
21
  const GATEWAY_TOKEN = process.env.GATEWAY_TOKEN || "huggingclaw";
22
  const WHATSAPP_ENABLED = /^true$/i.test(process.env.WHATSAPP_ENABLED || "");
23
  const CHECK_INTERVAL = 30000;
@@ -91,7 +92,7 @@ async function createConnection() {
91
  method: "connect",
92
  params: {
93
  minProtocol: 3,
94
- maxProtocol: 3,
95
  client: {
96
  id: "gateway-client",
97
  version: "1.0.0",
@@ -125,7 +126,8 @@ async function createConnection() {
125
  });
126
  }
127
 
128
- async function callRpc(ws, method, params) {
 
129
  return new Promise((resolve, reject) => {
130
  const id = randomUUID();
131
  const handler = (data) => {
@@ -148,7 +150,7 @@ async function callRpc(ws, method, params) {
148
  reject(sendErr);
149
  return;
150
  }
151
- setTimeout(() => { ws.removeListener("message", handler); reject(new Error("RPC Timeout")); }, WAIT_TIMEOUT + 5000);
152
  });
153
  }
154
 
@@ -188,7 +190,7 @@ async function checkStatus() {
188
  }
189
 
190
  console.log("[guardian] Waiting for pairing completion...");
191
- const waitRes = await callRpc(ws, "web.login.wait", { timeoutMs: WAIT_TIMEOUT });
192
  const result = waitRes.payload || waitRes.result;
193
  const message = result?.message || "";
194
  const linkedAfter515 = !result?.connected && message.includes("515");
@@ -202,19 +204,27 @@ async function checkStatus() {
202
  lastConnectedAt = Date.now();
203
  writeStatus({ configured: true, connected: true, pairing: false });
204
 
 
 
 
 
205
  if (linkedAfter515) {
206
  console.log("[guardian] 515 after scan: credentials saved, reloading config to start WhatsApp...");
207
  } else {
208
  console.log("[guardian] Pairing completed! Reloading config...");
209
  }
210
 
211
- const getRes = await callRpc(ws, "config.get", {});
212
- if (getRes.payload?.raw && getRes.payload?.hash) {
213
- await callRpc(ws, "config.apply", { raw: getRes.payload.raw, baseHash: getRes.payload.hash });
214
- console.log("[guardian] Configuration re-applied.");
 
 
 
 
 
 
215
  }
216
-
217
- shouldStop = true;
218
  setTimeout(() => process.exit(0), 1000);
219
  } else if (!message.includes("No active") && !message.includes("Still waiting")) {
220
  console.log(`[guardian] Wait result: ${message}`);
 
17
  }
18
  const { randomUUID } = require('node:crypto');
19
 
20
+ const GATEWAY_PORT = Number.parseInt(process.env.GATEWAY_PORT || "7860", 10);
21
+ const GATEWAY_URL = `ws://127.0.0.1:${GATEWAY_PORT}`;
22
  const GATEWAY_TOKEN = process.env.GATEWAY_TOKEN || "huggingclaw";
23
  const WHATSAPP_ENABLED = /^true$/i.test(process.env.WHATSAPP_ENABLED || "");
24
  const CHECK_INTERVAL = 30000;
 
92
  method: "connect",
93
  params: {
94
  minProtocol: 3,
95
+ maxProtocol: 4,
96
  client: {
97
  id: "gateway-client",
98
  version: "1.0.0",
 
126
  });
127
  }
128
 
129
+ async function callRpc(ws, method, params, timeoutMs) {
130
+ const ms = timeoutMs !== undefined ? timeoutMs : 10000; // default 10s for normal calls
131
  return new Promise((resolve, reject) => {
132
  const id = randomUUID();
133
  const handler = (data) => {
 
150
  reject(sendErr);
151
  return;
152
  }
153
+ setTimeout(() => { ws.removeListener("message", handler); reject(new Error("RPC Timeout")); }, ms);
154
  });
155
  }
156
 
 
190
  }
191
 
192
  console.log("[guardian] Waiting for pairing completion...");
193
+ const waitRes = await callRpc(ws, "web.login.wait", { timeoutMs: WAIT_TIMEOUT }, WAIT_TIMEOUT + 5000);
194
  const result = waitRes.payload || waitRes.result;
195
  const message = result?.message || "";
196
  const linkedAfter515 = !result?.connected && message.includes("515");
 
204
  lastConnectedAt = Date.now();
205
  writeStatus({ configured: true, connected: true, pairing: false });
206
 
207
+ // Set shouldStop BEFORE config.apply β€” gateway restart during apply must not
208
+ // leave guardian running (it would then incorrectly wipe valid credentials).
209
+ shouldStop = true;
210
+
211
  if (linkedAfter515) {
212
  console.log("[guardian] 515 after scan: credentials saved, reloading config to start WhatsApp...");
213
  } else {
214
  console.log("[guardian] Pairing completed! Reloading config...");
215
  }
216
 
217
+ try {
218
+ const getRes = await callRpc(ws, "config.get", {});
219
+ if (getRes.payload?.raw && getRes.payload?.hash) {
220
+ await callRpc(ws, "config.apply", { raw: getRes.payload.raw, baseHash: getRes.payload.hash });
221
+ console.log("[guardian] Configuration re-applied.");
222
+ }
223
+ } catch (applyErr) {
224
+ // Gateway restarted during config.apply β€” that is expected and fine.
225
+ // shouldStop is already true so we will not retry or attempt logout.
226
+ console.log(`[guardian] Config re-apply interrupted (gateway restarting): ${applyErr.message}`);
227
  }
 
 
228
  setTimeout(() => process.exit(0), 1000);
229
  } else if (!message.includes("No active") && !message.includes("Still waiting")) {
230
  console.log(`[guardian] Wait result: ${message}`);