File size: 21,834 Bytes
0a6ef8b
 
b82c4fb
0a6ef8b
a076318
5f2322c
0a6ef8b
 
 
 
 
0bdba65
 
0a6ef8b
c43cba6
b82c4fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a6ef8b
 
 
 
 
565c32b
0a6ef8b
 
565c32b
0a6ef8b
 
 
 
b82c4fb
565c32b
b82c4fb
0a6ef8b
 
 
565c32b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a6ef8b
 
 
 
 
 
b82c4fb
 
 
 
 
 
b99bd87
b82c4fb
 
 
5292fde
b82c4fb
 
 
 
565c32b
b99bd87
 
 
 
0a6ef8b
b82c4fb
0a6ef8b
 
b82c4fb
0a6ef8b
 
 
31c844f
0a6ef8b
 
 
16ce1a2
0a6ef8b
 
 
 
565c32b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31c844f
565c32b
 
 
 
 
 
 
 
 
 
 
31c844f
565c32b
 
 
 
 
 
 
a076318
c43cba6
d2c6d08
 
 
a076318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2c6d08
a076318
 
 
d2c6d08
a076318
d2c6d08
a076318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2c6d08
a076318
 
 
 
 
d2c6d08
a076318
 
 
 
 
 
 
 
 
 
cf4ab94
a076318
d2c6d08
a076318
 
 
 
 
 
 
 
 
d2c6d08
a076318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b0719e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7cbdbf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b0719e
 
7cbdbf3
a076318
 
 
 
 
 
c4c4082
a076318
c4c4082
a076318
 
 
 
 
 
 
b9f9187
 
7cbdbf3
a076318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293f819
a076318
 
 
c43cba6
a076318
 
 
 
 
 
 
5f2322c
 
 
 
 
 
 
 
 
 
 
 
 
a076318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
577598b
293f819
7cbdbf3
4b0719e
a076318
 
 
 
 
5f2322c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2c6d08
5f2322c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2c6d08
5f2322c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a6ef8b
 
 
a076318
 
5f2322c
 
 
 
 
 
 
 
 
 
 
 
565c32b
 
0a6ef8b
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
import os
import sys
import json
import tarfile
import re
import argparse
from huggingface_hub import HfApi, hf_hub_download

api = HfApi()
repo_id = os.getenv("HF_DATASET")
token = os.getenv("HF_TOKEN")
# 备份产物写 /tmp:容器 cwd(/app) 归 root,运行用户写不进去会导致备份静默失败
FILENAME = "/tmp/latest_backup.tar.gz"

OPENCLAW_DIR = os.getenv("OPENCLAW_DIR") or os.path.join(os.path.expanduser("~"), ".openclaw")

def get_workspace_path():
    config_path = os.path.join(OPENCLAW_DIR, "openclaw.json")
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            config = json.load(f)
        workspace = config.get("agents", {}).get("defaults", {}).get("workspace", "")
        if workspace and os.path.exists(workspace):
            return workspace
    except (FileNotFoundError, json.JSONDecodeError):
        pass
    
    default_workspace = os.path.join(OPENCLAW_DIR, "workspace")
    if os.path.exists(default_workspace):
        return default_workspace
    
    return None

def restore():
    try:
        if not repo_id or not token:
            print("Skip Restore: HF_DATASET or HF_TOKEN not set")
            return

        print(f"Downloading {FILENAME} from {repo_id}...")
        path = hf_hub_download(repo_id=repo_id, filename=FILENAME, repo_type="dataset", token=token)

        with tarfile.open(path, "r:gz") as tar:
            for member in tar.getmembers():
                if member.name == "openclaw.json" or member.name.endswith("/openclaw.json"):
                    continue
                tar.extract(member, path=OPENCLAW_DIR)

        print(f"Success: Restored from {FILENAME}")
    except Exception as e:
        print(f"Restore Note: No existing backup found or error: {e}")

    # Also restore lightweight metadata (cron jobs) from meta/ prefix
    try:
        meta_files = api.list_repo_files(repo_id=repo_id, repo_type="dataset", token=token)
        meta_files = [f for f in meta_files if f.startswith("meta/")]
        if meta_files:
            import shutil
            for mf in meta_files:
                local = os.path.join(OPENCLAW_DIR, mf[len("meta/"):])
                os.makedirs(os.path.dirname(local), exist_ok=True)
                dl = hf_hub_download(
                    repo_id=repo_id, filename=mf, repo_type="dataset", token=token
                )
                shutil.copy2(dl, local)
            print(f"Restored {len(meta_files)} metadata file(s) (cron jobs, credentials)")
    except Exception as e:
        print(f"Metadata restore note: {e}")

def backup():
    try:
        if not repo_id or not token:
            print("Skip Backup: HF_DATASET or HF_TOKEN not set")
            return

        workspace = get_workspace_path()

        paths_to_backup = [
            ("credentials", os.path.join(OPENCLAW_DIR, "credentials")),
            ("cron", os.path.join(OPENCLAW_DIR, "cron")),
            ("agents/main/agent", os.path.join(OPENCLAW_DIR, "agents", "main", "agent")),
            ("skills", os.path.join(OPENCLAW_DIR, "skills")),
        ]

        if workspace:
            persona_files = ["SOUL.md", "AGENTS.md", "IDENTITY.md", "USER.md", "TOOLS.md", "MEMORY.md", "HEARTBEAT.md"]
            for fname in persona_files:
                fpath = os.path.join(workspace, fname)
                if os.path.exists(fpath):
                    paths_to_backup.append((f"workspace/{fname}", fpath))

            workspace_skills = os.path.join(workspace, "skills")
            if os.path.exists(workspace_skills):
                paths_to_backup.append(("workspace/skills", workspace_skills))

        with tarfile.open(FILENAME, "w:gz") as tar:
            for arcname, p in paths_to_backup:
                if os.path.exists(p):
                    tar.add(p, arcname=arcname)

        api.upload_file(
            path_or_fileobj=FILENAME,
            path_in_repo=FILENAME,
            repo_id=repo_id,
            repo_type="dataset",
            token=token
        )
        os.remove(FILENAME)
        print(f"Backup {FILENAME} Success (Overwritten).")
    except Exception as e:
        print(f"Backup Error: {e}")

def sync_metadata():
    """Lightweight sync for small critical metadata (cron jobs, credentials).
    Runs frequently (e.g. every 10-15 min) without full tar overhead."""
    try:
        if not repo_id or not token:
            return
        meta_paths = [
            ("cron", os.path.join(OPENCLAW_DIR, "cron")),
            ("credentials", os.path.join(OPENCLAW_DIR, "credentials")),
        ]
        # Upload each small directory as individual files under meta/ prefix
        for arcname, p in meta_paths:
            if not os.path.exists(p):
                continue
            if os.path.isfile(p):
                api.upload_file(
                    path_or_fileobj=p,
                    path_in_repo=f"meta/{arcname}",
                    repo_id=repo_id,
                    repo_type="dataset",
                    token=token,
                )
            elif os.path.isdir(p):
                for root, dirs, files in os.walk(p):
                    for fname in files:
                        fpath = os.path.join(root, fname)
                        rel = os.path.relpath(fpath, OPENCLAW_DIR)
                        api.upload_file(
                            path_or_fileobj=fpath,
                            path_in_repo=f"meta/{rel}",
                            repo_id=repo_id,
                            repo_type="dataset",
                            token=token,
                        )
        print("Metadata sync OK (cron, credentials)")
    except Exception as e:
        print(f"Metadata sync error: {e}")

def generate_config():
    """从环境变量读取配置,生成 ${OPENCLAW_DIR}/openclaw.json"""
    def parse_list(s):
        return [x.strip() for x in (s or "").split(",") if x.strip()]

    def clean_base(url):
        if not url:
            return ""
        u = url.strip()
        u = re.sub(r"/chat/completions/?$", "", u)
        u = re.sub(r"/v1/?$", "/v1", u)
        return u

    def provider_slugs():
        raw = os.environ.get("PROVIDERS", "").strip()
        if raw:
            return [s.strip().lower() for s in raw.split(",") if s.strip()]
        if os.environ.get("OPENAI_API_BASE") or os.environ.get("MODELS") or os.environ.get("OPENAI_API_KEY"):
            return [os.environ.get("PROVIDER_NAME", "default").strip().lower() or "default"]
        return []

    def load_provider(slug):
        key = slug.upper()
        base = clean_base(os.environ.get(f"{key}_OPENAI_API_BASE", ""))
        models = parse_list(os.environ.get(f"{key}_MODELS", ""))
        api_key = os.environ.get(f"{key}_API_KEY", "")
        if slug == os.environ.get("PROVIDER_NAME", "default").strip().lower():
            base = base or clean_base(os.environ.get("OPENAI_API_BASE", ""))
            models = models or parse_list(os.environ.get("MODELS", ""))
            api_key = api_key or os.environ.get("OPENAI_API_KEY", "")
        return base, models, api_key

    enabled = os.environ.get("QQ_BOT_ENABLED_PY") == "True"
    app_id = os.environ.get("QQ_APP_ID", "")
    secret = os.environ.get("QQ_CLIENT_SECRET", "")
    model = os.environ.get("MODEL", "").strip()
    fallbacks_raw = os.environ.get("MODEL_FALLBACKS", "")
    port = int(os.environ.get("PORT", "7860"))
    gw_token = os.environ.get("OPENCLAW_GATEWAY_PASSWORD", "")

    id_to_slugs = {}
    providers = {}
    agent_models = {}
    failed_providers = []

    for slug in provider_slugs():
        base, model_ids, api_key = load_provider(slug)
        missing = []
        if not api_key:
            missing.append(f"{slug.upper()}_API_KEY")
        if not base:
            missing.append(f"{slug.upper()}_OPENAI_API_BASE")
        if not model_ids:
            missing.append(f"{slug.upper()}_MODELS")
        if missing:
            print(f"WARN: Provider '{slug}' SKIPPED — missing: {', '.join(missing)}")
            failed_providers.append(slug)
            continue

        providers[slug] = {
            "baseUrl": base,
            "apiKey": api_key,
            "api": "openai-completions",
            "models": [{"id": mid, "name": mid} for mid in model_ids],
        }
        for mid in model_ids:
            ref = f"{slug}/{mid}"
            agent_models[ref] = {"alias": mid}
            id_to_slugs.setdefault(mid, []).append(slug)

    def resolve_ref(item):
        item = item.strip()
        if not item:
            return item
        if "/" in item:
            return item
        slugs = id_to_slugs.get(item, [])
        if len(slugs) == 1:
            return f"{slugs[0]}/{item}"
        if len(slugs) > 1:
            print(f"WARN: model id '{item}' exists on multiple providers {slugs}; use provider/model_id")
        return item

    def resolve_primary():
        if model:
            return resolve_ref(model)
        for slug in provider_slugs():
            if slug in providers:
                mids = providers[slug]["models"]
                if mids:
                    return f"{slug}/{mids[0]['id']}"
        return None

    def resolve_fallbacks(primary):
        out = []
        for item in parse_list(fallbacks_raw):
            ref = resolve_ref(item)
            if ref and ref != primary and ref not in out:
                out.append(ref)
        return out

    primary = resolve_primary()
    fallbacks = resolve_fallbacks(primary) if primary else []

    agents_defaults = {}
    if agent_models:
        agents_defaults["models"] = agent_models
    if primary:
        agents_defaults["model"] = {"primary": primary, "fallbacks": fallbacks}

    # 鉴权策略(2026.9.6,auth.mode 支持 none/token/password/trusted-proxy):
    # - 设了 OPENCLAW_GATEWAY_PASSWORD -> password 模式:浏览器弹密码框,输对即进。
    #   设备配对由 start-openclaw.sh 的自动批准循环兜底,无需手动确认。
    # - 没设密码 -> none 模式(开放),但仍自动批准设备,不弹配对框。
    #   (trusted-proxy 模式已不再需要:它依赖反向代理送身份头,HF 不送 x-forwarded-user,
    #    借 x-forwarded-proto 的写法一旦 HF 改头就会让整个 UI 打不开,不如用自动批准循环稳妥。)
    # 可用 GATEWAY_AUTH_MODE 强制覆盖为 none|token|password。
    auth_mode = (os.environ.get("GATEWAY_AUTH_MODE") or "").strip().lower()
    if not auth_mode:
        auth_mode = "password" if gw_token else "none"

    if auth_mode == "password":
        auth_cfg = {"mode": "password", "password": gw_token}
    elif auth_mode == "token":
        auth_cfg = {"mode": "token", "token": gw_token}
    elif auth_mode == "trusted-proxy":
        # 仅高级用户手动开启;需要 HF_IDENTITY_HEADER 指向代理确实会送的 header
        identity_header = (
            os.environ.get("HF_IDENTITY_HEADER", "x-forwarded-proto").strip()
            or "x-forwarded-proto"
        )
        auth_cfg = {
            "mode": "trusted-proxy",
            "trustedProxy": {
                "userHeader": identity_header,
                "allowUsers": [],
                "deviceAutoApprove": {
                    "enabled": True,
                    "scopes": [
                        "operator.read",
                        "operator.write",
                        "operator.approvals",
                        "operator.questions",
                    ],
                },
            },
        }
        if gw_token:
            auth_cfg["password"] = gw_token
    else:  # none
        auth_cfg = {"mode": "none"}

    cfg = {
        "update": {"checkOnStart": True, "auto": {"enabled": True}},
        "models": {"mode": "merge", "providers": providers},
        "agents": {"defaults": agents_defaults},
        "commands": {"restart": True},
        "plugins": {
            "allow": (["openclaw-qqbot", "workboard"] if enabled else ["workboard"]),
            "entries": {
                "openclaw-qqbot": {"enabled": enabled},
                "workboard": {"enabled": True},
            },
        },
        "gateway": {
            "mode": "local",
            "bind": "lan",
            "port": port,
            "trustedProxies": ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"],
            "allowRealIpFallback": True,
            "auth": auth_cfg,
            "controlUi": {
                "enabled": True,
                "allowInsecureAuth": True,
                "dangerouslyAllowHostHeaderOriginFallback": True,
            },
        },
        "channels": {
            "qqbot": {
                "enabled": enabled,
                "appId": app_id,
                "clientSecret": secret,
                "dmPolicy": "open",
                "groupPolicy": "open",
                "requireMention": True,
                "markdownSupport": True,
                "c2cMarkdownDeliveryMode": "proactive-all",
            },
        },
    }

    config_path = os.path.join(OPENCLAW_DIR, "openclaw.json")
    old_cfg = None
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            old_cfg = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        pass

    # Preserve runtime-only providers (not from env vars) across restarts
    env_slugs = set(provider_slugs())
    if old_cfg and "models" in old_cfg and "providers" in old_cfg["models"]:
        for slug, p in old_cfg["models"]["providers"].items():
            if slug not in providers and slug not in env_slugs:
                providers[slug] = p
                for mid_obj in p.get("models", []):
                    mid = mid_obj["id"]
                    ref = f"{slug}/{mid}"
                    agent_models[ref] = {"alias": mid}
                    id_to_slugs.setdefault(mid, []).append(slug)
                print(f"Preserved runtime provider: {slug}")

    if old_cfg and "cron" in old_cfg:
        cfg["cron"] = old_cfg["cron"]
        print(f"Merged existing cron config from previous {config_path}")

    with open(config_path, "w", encoding="utf-8") as f:
        cfg.setdefault("session", {}).update({
            "dmScope": "per-channel-peer",
            "maintenance": {
                "mode": "enforce",
                "pruneAfter": "1d",
                "maxEntries": 200,
            },
        })
        json.dump(cfg, f, indent=2, ensure_ascii=False)

    total_models = sum(len(p["models"]) for p in providers.values())
    print(
        f"Wrote {config_path} (qqbot={enabled}, "
        f"primary={primary or 'unset'}, "
        f"providers={','.join(providers.keys()) or 'none'}, models={total_models}, "
        f"auth={auth_cfg.get('mode')}, pairing=auto-approved-by-loop)"
    )
    if not providers:
        print("WARN: no provider configured — set PROVIDERS and per-provider Variables/Secrets")


def _load_config():
    config_path = os.path.join(OPENCLAW_DIR, "openclaw.json")
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading config: {e}")
        return None

def _save_config(cfg):
    config_path = os.path.join(OPENCLAW_DIR, "openclaw.json")
    with open(config_path, "w", encoding="utf-8") as f:
        json.dump(cfg, f, indent=2, ensure_ascii=False)

def _mask_key(key):
    if not key or len(key) < 12:
        return "***"
    return f"{key[:4]}...{key[-4:]}"

def list_providers():
    cfg = _load_config()
    if not cfg:
        return
    providers = cfg.get("models", {}).get("providers", {})
    if not providers:
        print("No providers configured.")
        return
    model_cfg = cfg.get("agents", {}).get("defaults", {}).get("model", {})
    primary = (model_cfg.get("primary") or "") if isinstance(model_cfg, dict) else ""
    fallbacks = (model_cfg.get("fallbacks") or []) if isinstance(model_cfg, dict) else []
    print(f"{'Slug':<16} {'Base URL':<45} {'Models':<30} {'API Key'}")
    print("-" * 110)
    for slug, p in providers.items():
        marker = " [PRIMARY]" if primary.startswith(f"{slug}/") else ""
        for fb in fallbacks:
            if fb.startswith(f"{slug}/"):
                marker += " [FALLBACK]"
        models_str = ", ".join(m["id"] for m in p.get("models", []))
        print(f"{slug:<16} {p.get('baseUrl', ''):<45} {models_str:<30} {_mask_key(p.get('apiKey', ''))}{marker}")
    print(f"\nPrimary: {primary or '<unset>'}")
    print(f"Fallbacks: {', '.join(fallbacks) if fallbacks else '<none>'}")

def update_provider(args):
    cfg = _load_config()
    if not cfg:
        return
    if "models" not in cfg:
        cfg["models"] = {}
    if "providers" not in cfg["models"]:
        cfg["models"]["providers"] = {}

    providers = cfg["models"]["providers"]
    action = args.action
    slug = args.slug.lower()

    if action == "add":
        if slug in providers:
            print(f"Error: Provider '{slug}' already exists. Use --action update to modify.")
            return
        if not args.base_url or not args.models or not args.api_key:
            print("Error: --base-url, --models, and --api-key are required for add.")
            return
        models_list = [{"id": m.strip(), "name": m.strip()} for m in args.models.split(",") if m.strip()]
        providers[slug] = {
            "baseUrl": args.base_url,
            "apiKey": args.api_key,
            "api": "openai-completions",
            "models": models_list,
        }
        _save_config(cfg)
        print(f"Provider '{slug}' added: base={args.base_url}, models={[m['id'] for m in models_list]}, key={_mask_key(args.api_key)}")
        print("Config saved. Changes take effect immediately (hot-reload).")

    elif action == "remove":
        if slug not in providers:
            print(f"Error: Provider '{slug}' not found.")
            return
        model_cfg = cfg.get("agents", {}).get("defaults", {}).get("model", {})
        primary = (model_cfg.get("primary") or "") if isinstance(model_cfg, dict) else ""
        fallbacks = (model_cfg.get("fallbacks") or []) if isinstance(model_cfg, dict) else []
        if primary.startswith(f"{slug}/"):
            print(f"Error: Provider '{slug}' is the current PRIMARY model ({primary}). Change primary first.")
            return
        any_fb = [fb for fb in fallbacks if fb.startswith(f"{slug}/")]
        if any_fb:
            print(f"Error: Provider '{slug}' has fallback refs: {any_fb}. Remove from fallbacks first.")
            return
        del providers[slug]
        _save_config(cfg)
        print(f"Provider '{slug}' removed.")
        print("Config saved. Changes take effect immediately (hot-reload).")

    elif action == "update":
        if slug not in providers:
            print(f"Error: Provider '{slug}' not found. Use --action add to create it.")
            return
        p = providers[slug]
        if args.base_url:
            p["baseUrl"] = args.base_url
        if args.models:
            p["models"] = [{"id": m.strip(), "name": m.strip()} for m in args.models.split(",") if m.strip()]
        if args.api_key:
            p["apiKey"] = args.api_key
        _save_config(cfg)
        print(f"Provider '{slug}' updated:")
        print(f"  baseUrl: {p.get('baseUrl', '<unchanged>')}")
        print(f"  models:   {[m['id'] for m in p.get('models', [])]}")
        print(f"  apiKey:  {_mask_key(p.get('apiKey', '<unchanged>'))}")
        print("Config saved. Changes take effect immediately (hot-reload).")

    elif action == "set-primary":
        if slug not in providers:
            print(f"Error: Provider '{slug}' not found.")
            return
        if not args.model:
            mids = providers[slug].get("models", [])
            if not mids:
                print(f"Error: Provider '{slug}' has no models. Cannot set as primary.")
                return
            ref = f"{slug}/{mids[0]['id']}"
            print(f"No --model specified, using first model: {ref}")
        else:
            ref = f"{slug}/{args.model}"
        if "agents" not in cfg:
            cfg["agents"] = {}
        if "defaults" not in cfg["agents"]:
            cfg["agents"]["defaults"] = {}
        if "model" not in cfg["agents"]["defaults"]:
            cfg["agents"]["defaults"]["model"] = {"primary": ref, "fallbacks": []}
        else:
            cfg["agents"]["defaults"]["model"]["primary"] = ref
        _save_config(cfg)
        print(f"Primary model set to: {ref}")
        print("Config saved. Changes take effect immediately (hot-reload).")

    else:
        print(f"Unknown action: {action}. Use: add | remove | update | set-primary")


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "backup":
        backup()
    elif len(sys.argv) > 1 and sys.argv[1] == "generate_config":
        generate_config()
    elif len(sys.argv) > 1 and sys.argv[1] == "update_provider":
        parser = argparse.ArgumentParser(description="Runtime provider management")
        parser.add_argument("--action", required=True, choices=["add", "remove", "update", "set-primary"])
        parser.add_argument("--slug", required=True, help="Provider slug name")
        parser.add_argument("--base-url", default="", help="API base URL")
        parser.add_argument("--models", default="", help="Comma-separated model IDs")
        parser.add_argument("--api-key", default="", help="API key")
        parser.add_argument("--model", default="", help="Model ID (for set-primary)")
        args = parser.parse_args(sys.argv[2:])
        update_provider(args)
    elif len(sys.argv) > 1 and sys.argv[1] == "list_providers":
        list_providers()
    elif len(sys.argv) > 1 and sys.argv[1] == "sync_metadata":
        sync_metadata()
    else:
        restore()