8900 commited on
Update hf-sync-manager.mjs
Browse files- hf-sync-manager.mjs +69 -131
hf-sync-manager.mjs
CHANGED
|
@@ -2,162 +2,100 @@ import fs from "node:fs";
|
|
| 2 |
import path from "node:path";
|
| 3 |
import { execSync } from "node:child_process";
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
const UPLOAD_INTERVAL = 3 * 60 * 60 * 1000; // 3小时
|
| 13 |
-
|
| 14 |
-
const FILES = ["conversations", "memory", "logs"];
|
| 15 |
-
|
| 16 |
-
// ===================== 内存对象 =====================
|
| 17 |
-
const botMemory = {
|
| 18 |
-
conversations: [],
|
| 19 |
-
memory: [],
|
| 20 |
-
logs: []
|
| 21 |
-
};
|
| 22 |
-
|
| 23 |
-
// ===================== Helper =====================
|
| 24 |
-
function log(msg) { console.log(`[hf-sync] ${msg}`); }
|
| 25 |
-
function repoUrl() { return `https://user:${HF_TOKEN}@huggingface.co/datasets/${DATASET_ID}`; }
|
| 26 |
-
function git(args, cwd) {
|
| 27 |
-
return execSync("git " + args, {
|
| 28 |
-
cwd: cwd || REPO_DIR,
|
| 29 |
-
stdio: "pipe",
|
| 30 |
-
timeout: 120000,
|
| 31 |
-
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }
|
| 32 |
-
}).toString().trim();
|
| 33 |
-
}
|
| 34 |
-
|
| 35 |
-
function ensureRepo() {
|
| 36 |
-
if (fs.existsSync(path.join(REPO_DIR, ".git"))) return;
|
| 37 |
-
execSync("rm -rf " + REPO_DIR, { stdio: "pipe" });
|
| 38 |
-
try { git("clone --depth 1 " + repoUrl() + " " + REPO_DIR, "/tmp"); }
|
| 39 |
-
catch {
|
| 40 |
-
fs.mkdirSync(REPO_DIR, { recursive: true });
|
| 41 |
-
git("init", REPO_DIR);
|
| 42 |
-
git("remote add origin " + repoUrl(), REPO_DIR);
|
| 43 |
-
}
|
| 44 |
-
git("config user.email openclaw@hf.space", REPO_DIR);
|
| 45 |
-
git("config user.name OpenClaw-Memory-Sync", REPO_DIR);
|
| 46 |
-
git("config pull.rebase false", REPO_DIR);
|
| 47 |
-
}
|
| 48 |
-
|
| 49 |
-
function pullLatest() {
|
| 50 |
-
try { git("fetch --quiet origin"); } catch {}
|
| 51 |
-
try { git("pull --quiet --no-rebase origin main"); } catch {}
|
| 52 |
-
}
|
| 53 |
-
|
| 54 |
-
// ===================== JSONL 操作 =====================
|
| 55 |
-
function readJsonl(filePath, targetArray) {
|
| 56 |
-
if (!fs.existsSync(filePath)) return;
|
| 57 |
-
const lines = fs.readFileSync(filePath, "utf-8").split("\n").filter(Boolean);
|
| 58 |
-
lines.forEach(line => { try { targetArray.push(JSON.parse(line)); } catch{} });
|
| 59 |
-
}
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
fs.writeFileSync(filePath, lines, "utf-8");
|
| 64 |
-
}
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
}
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
| 74 |
}
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
}
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
}
|
| 86 |
|
| 87 |
-
function
|
| 88 |
-
|
| 89 |
-
fs.mkdirSync(dir, { recursive: true });
|
| 90 |
-
const fileMap = {};
|
| 91 |
-
FILES.forEach(f => { fileMap[f] = path.join(dir, f + ".jsonl"); });
|
| 92 |
-
return fileMap;
|
| 93 |
-
}
|
| 94 |
|
| 95 |
-
|
| 96 |
-
function
|
| 97 |
-
if (!fs.existsSync(REPO_DIR)) return;
|
| 98 |
-
const repoMemoryDir = path.join(REPO_DIR, "dataset-memory");
|
| 99 |
-
if (!fs.existsSync(repoMemoryDir)) return;
|
| 100 |
-
|
| 101 |
-
// 遍历每个日期文件夹
|
| 102 |
-
const dateDirs = fs.readdirSync(repoMemoryDir).filter(f => fs.statSync(path.join(repoMemoryDir,f)).isDirectory());
|
| 103 |
-
dateDirs.forEach(dateDir => {
|
| 104 |
-
const files = {};
|
| 105 |
-
FILES.forEach(f => { files[f] = path.join(repoMemoryDir, dateDir, f + ".jsonl"); });
|
| 106 |
-
FILES.forEach(f => readJsonl(files[f], botMemory[f]));
|
| 107 |
-
});
|
| 108 |
-
log(`Loaded: conversations=${botMemory.conversations.length}, memory=${botMemory.memory.length}, logs=${botMemory.logs.length}`);
|
| 109 |
-
}
|
| 110 |
|
| 111 |
-
function
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
fs.
|
| 115 |
-
|
|
|
|
| 116 |
}
|
| 117 |
|
| 118 |
-
function
|
| 119 |
-
|
| 120 |
-
git("add -A", REPO_DIR);
|
| 121 |
-
const changed = git("diff --cached --name-only", REPO_DIR);
|
| 122 |
-
if (!changed) return 0;
|
| 123 |
-
const ts = new Date().toISOString().replace("T"," ").substring(0,19);
|
| 124 |
-
git(`commit -m "memory-sync ${ts}"`, REPO_DIR);
|
| 125 |
-
git("push --quiet origin HEAD:main", REPO_DIR);
|
| 126 |
-
return changed.split("\n").filter(Boolean).length;
|
| 127 |
-
} catch(e){ log("Push failed: "+e.message); return 0; }
|
| 128 |
}
|
| 129 |
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
log("Boot restore
|
| 134 |
-
ensureRepo();
|
| 135 |
-
pullLatest();
|
| 136 |
-
loadMemoryFromRepo();
|
| 137 |
}
|
| 138 |
|
| 139 |
-
async function startUploadLoop()
|
| 140 |
while(true){
|
| 141 |
-
await
|
| 142 |
-
try{
|
| 143 |
-
log("Saving memory to repo...");
|
| 144 |
-
saveMemoryToRepo();
|
| 145 |
-
const count = commitAndPush();
|
| 146 |
-
log("Upload done: "+count+" file(s) changed");
|
| 147 |
-
} catch(e){ log("Upload error: "+e.message); }
|
| 148 |
}
|
| 149 |
}
|
| 150 |
|
| 151 |
-
// ===================== Main =====================
|
| 152 |
async function main(){
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
bootRestore();
|
| 155 |
-
log("Memory ready.");
|
| 156 |
|
| 157 |
if(HF_TOKEN && DATASET_ID){
|
| 158 |
-
log(
|
| 159 |
-
startUploadLoop().catch(e=>log("Upload loop error: "+e.message));
|
| 160 |
}
|
|
|
|
|
|
|
| 161 |
}
|
| 162 |
|
| 163 |
-
main().catch(e
|
|
|
|
| 2 |
import path from "node:path";
|
| 3 |
import { execSync } from "node:child_process";
|
| 4 |
|
| 5 |
+
var HOME = process.env.OPENCLAW_HOME || process.env.HOME || "/home/user";
|
| 6 |
+
var OPENCLAW_DIR = path.join(HOME,".openclaw");
|
| 7 |
+
var MEMORY_DIR = path.join(OPENCLAW_DIR,"dataset-memory");
|
| 8 |
+
var HF_TOKEN = (process.env.HF_TOKEN||"").trim();
|
| 9 |
+
var DATASET_ID = (process.env.HF_DATASET_ID||"").trim();
|
| 10 |
+
var REPO_DIR = "/tmp/hf-memory-sync";
|
| 11 |
+
var UPLOAD_INTERVAL = 3*60*60*1000;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
var TRACK_NAMES = ["conversations","memory","logs"];
|
| 14 |
+
var botMemory = { conversations:[], memory:[], logs:[] };
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
function log(msg){ console.log("[hf-sync] "+msg); }
|
| 17 |
+
function repoUrl(){ return "https://user:"+HF_TOKEN+"@huggingface.co/datasets/"+DATASET_ID; }
|
| 18 |
+
function git(args,cwd){ return execSync("git "+args,{ cwd:cwd||REPO_DIR, stdio:"pipe", timeout:120000, env:Object.assign({},process.env,{GIT_TERMINAL_PROMPT:"0"}) }).toString().trim(); }
|
| 19 |
+
function sleep(ms){ return new Promise(resolve=>setTimeout(resolve,ms)); }
|
|
|
|
| 20 |
|
| 21 |
+
function ensureRepo(){
|
| 22 |
+
if(fs.existsSync(path.join(REPO_DIR,".git"))) return;
|
| 23 |
+
execSync("rm -rf "+REPO_DIR,{stdio:"pipe"});
|
| 24 |
+
try{ git("clone --depth 1 "+repoUrl()+" "+REPO_DIR,"/tmp"); } catch(e){ git("init",REPO_DIR); git("remote add origin "+repoUrl(),REPO_DIR); }
|
| 25 |
+
try{ git("config user.email openclaw@hf.space"); git("config user.name OpenClaw-Memory-Sync"); git("config pull.rebase false"); } catch(e){ }
|
| 26 |
}
|
| 27 |
|
| 28 |
+
function pullLatest(){
|
| 29 |
+
try{ git("fetch --quiet origin"); git("pull --quiet --no-rebase origin main"); }
|
| 30 |
+
catch(e){ try{ git("pull --quiet --no-rebase origin master"); } catch(e2){ } }
|
| 31 |
}
|
| 32 |
|
| 33 |
+
function commitAndPush(){
|
| 34 |
+
try{
|
| 35 |
+
git("add -A");
|
| 36 |
+
var changed = git("diff --cached --name-only");
|
| 37 |
+
if(!changed) return 0;
|
| 38 |
+
var ts = new Date().toISOString().replace("T"," ").substring(0,19);
|
| 39 |
+
var count = changed.split("\n").filter(Boolean).length;
|
| 40 |
+
git('commit -m "memory-sync '+ts+'"');
|
| 41 |
+
try{ git("push --quiet origin HEAD:main"); } catch(e){ git("push --quiet origin HEAD:master"); }
|
| 42 |
+
return count;
|
| 43 |
+
}catch(e){ log("Push failed: "+e.message); return 0; }
|
| 44 |
}
|
| 45 |
|
| 46 |
+
function readJsonl(filePath,targetArray){ if(!fs.existsSync(filePath)) return; fs.readFileSync(filePath,"utf-8").split("\n").filter(Boolean).forEach(line=>{ try{ targetArray.push(JSON.parse(line)) }catch(e){} }); }
|
| 47 |
+
function writeJsonl(filePath,dataArray){ fs.writeFileSync(filePath,dataArray.map(x=>JSON.stringify(x)).join("\n"),"utf-8"); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
function todayDir(){ var d=new Date(); return d.getFullYear()+"-"+String(d.getMonth()+1).padStart(2,"0")+"-"+String(d.getDate()).padStart(2,"0"); }
|
| 50 |
+
function getRepoDateDir(dateStr){ var dir=path.join(REPO_DIR,"dataset-memory",dateStr); fs.mkdirSync(dir,{recursive:true}); return dir; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
+
function loadMemoryFromRepo(){
|
| 53 |
+
var repoBase = path.join(REPO_DIR,"dataset-memory");
|
| 54 |
+
if(!fs.existsSync(repoBase)) return;
|
| 55 |
+
var dateDirs = fs.readdirSync(repoBase).filter(f=>fs.statSync(path.join(repoBase,f)).isDirectory());
|
| 56 |
+
dateDirs.forEach(dateDir=>{ TRACK_NAMES.forEach(track=>{ readJsonl(path.join(repoBase,dateDir,track+".jsonl"),botMemory[track]); }); });
|
| 57 |
+
log("Loaded: conversations="+botMemory.conversations.length+" memory="+botMemory.memory.length+" logs="+botMemory.logs.length);
|
| 58 |
}
|
| 59 |
|
| 60 |
+
function saveMemoryToRepo(){
|
| 61 |
+
var dateStr=todayDir(); var destDir=getRepoDateDir(dateStr); TRACK_NAMES.forEach(track=>writeJsonl(path.join(destDir,track+".jsonl"),botMemory[track]));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
}
|
| 63 |
|
| 64 |
+
function bootRestore(){
|
| 65 |
+
if(!HF_TOKEN || !DATASET_ID){ log("HF_TOKEN or HF_DATASET_ID not set, skipping restore"); return; }
|
| 66 |
+
log("Boot restore starting from "+DATASET_ID+"...");
|
| 67 |
+
try{ ensureRepo(); pullLatest(); loadMemoryFromRepo(); log("Boot restore done."); }catch(e){ log("Boot restore failed (non-fatal): "+e.message); }
|
|
|
|
|
|
|
|
|
|
| 68 |
}
|
| 69 |
|
| 70 |
+
async function startUploadLoop(){
|
| 71 |
while(true){
|
| 72 |
+
await sleep(UPLOAD_INTERVAL);
|
| 73 |
+
try{ log("Uploading memory to repo..."); ensureRepo(); pullLatest(); saveMemoryToRepo(); var count=commitAndPush(); log("Upload done: "+count+" file(s) changed"); }catch(e){ log("Upload error: "+e.message); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
}
|
| 75 |
}
|
| 76 |
|
|
|
|
| 77 |
async function main(){
|
| 78 |
+
log("Starting...");
|
| 79 |
+
log("OPENCLAW_DIR : "+OPENCLAW_DIR);
|
| 80 |
+
log("HF_DATASET_ID: "+(DATASET_ID||"NOT SET"));
|
| 81 |
+
log("Upload interval: "+(UPLOAD_INTERVAL/3600000)+"h");
|
| 82 |
+
|
| 83 |
+
fs.mkdirSync(MEMORY_DIR,{recursive:true});
|
| 84 |
+
try{
|
| 85 |
+
execSync("git config --global user.email openclaw@hf.space",{stdio:"pipe"});
|
| 86 |
+
execSync("git config --global user.name OpenClaw-Memory-Sync",{stdio:"pipe"});
|
| 87 |
+
execSync("git config --global http.postBuffer 52428800",{stdio:"pipe"});
|
| 88 |
+
execSync("git config --global pull.rebase false",{stdio:"pipe"});
|
| 89 |
+
}catch(e){}
|
| 90 |
+
|
| 91 |
bootRestore();
|
|
|
|
| 92 |
|
| 93 |
if(HF_TOKEN && DATASET_ID){
|
| 94 |
+
log("Upload loop started (first run in "+(UPLOAD_INTERVAL/3600000)+"h)");
|
| 95 |
+
startUploadLoop().catch(e=>{ log("Upload loop error: "+e.message); });
|
| 96 |
}
|
| 97 |
+
|
| 98 |
+
log("Ready.");
|
| 99 |
}
|
| 100 |
|
| 101 |
+
main().catch(e=>{ console.error("[hf-sync] Fatal: "+e.message); });
|