import os import sys import tarfile from datetime import datetime from huggingface_hub import HfApi, hf_hub_download API = HfApi() def env(name: str, default: str = "") -> str: v = os.getenv(name, default).strip() return v HF_TOKEN = env("HF_TOKEN") HF_DATASET = env("HF_DATASET") OPENCLAW_HOME = env("OPENCLAW_HOME", os.path.join(os.path.expanduser("~"), ".openclaw")) BACKUP_PREFIX = "openclaw-backup-" MAX_SCAN = 50 # scan last N files def _enabled() -> bool: return bool(HF_TOKEN and HF_DATASET) def _tar_paths(): # What we persist sessions = os.path.join(OPENCLAW_HOME, "sessions") workspace = os.path.join(OPENCLAW_HOME, "workspace") cfg = os.path.join(OPENCLAW_HOME, "openclaw.json") return [p for p in [sessions, workspace, cfg] if os.path.exists(p)] def restore(): if not _enabled(): print("[sync] restore skipped: HF_TOKEN/HF_DATASET not set") return 0 try: files = API.list_repo_files(repo_id=HF_DATASET, repo_type="dataset", token=HF_TOKEN) backups = sorted([f for f in files if f.startswith(BACKUP_PREFIX) and f.endswith(".tar.gz")], reverse=True) if not backups: print("[sync] no backups found in dataset") return 0 target = backups[0] print(f"[sync] restoring from {target}") local = hf_hub_download( repo_id=HF_DATASET, repo_type="dataset", filename=target, token=HF_TOKEN, ) os.makedirs(OPENCLAW_HOME, exist_ok=True) with tarfile.open(local, "r:gz") as tar: tar.extractall(path=OPENCLAW_HOME) print("[sync] restore ok") return 0 except Exception as e: print(f"[sync] restore error: {e}") return 0 # do not crash startup def backup(): if not _enabled(): print("[sync] backup skipped: HF_TOKEN/HF_DATASET not set") return 0 try: os.makedirs("/tmp", exist_ok=True) name = f"{BACKUP_PREFIX}{datetime.utcnow().strftime('%Y%m%d-%H%M%S')}.tar.gz" out_path = os.path.join("/tmp", name) paths = _tar_paths() if not paths: print("[sync] nothing to backup yet") return 0 # Create tarball with relative paths inside OPENCLAW_HOME with tarfile.open(out_path, "w:gz") as tar: for p in paths: arcname = os.path.relpath(p, OPENCLAW_HOME) tar.add(p, arcname=arcname) API.upload_file( path_or_fileobj=out_path, path_in_repo=name, repo_id=HF_DATASET, repo_type="dataset", token=HF_TOKEN, ) print(f"[sync] backup uploaded: {name}") return 0 except Exception as e: print(f"[sync] backup error: {e}") return 0 if __name__ == "__main__": cmd = sys.argv[1] if len(sys.argv) > 1 else "restore" if cmd == "backup": raise SystemExit(backup()) raise SystemExit(restore())