-
Notifications
You must be signed in to change notification settings - Fork 792
Expand file tree
/
Copy pathpostinstall.cjs
More file actions
330 lines (285 loc) · 13.7 KB
/
postinstall.cjs
File metadata and controls
330 lines (285 loc) · 13.7 KB
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
#!/usr/bin/env node
"use strict";
const { spawnSync } = require("child_process");
const path = require("path");
const fs = require("fs");
const RESET = "\x1b[0m";
const GREEN = "\x1b[32m";
const YELLOW = "\x1b[33m";
const RED = "\x1b[31m";
const CYAN = "\x1b[36m";
const BOLD = "\x1b[1m";
const DIM = "\x1b[2m";
function log(msg) { console.log(` ${CYAN}[memos-local]${RESET} ${msg}`); }
function warn(msg) { console.log(` ${YELLOW}⚠ [memos-local]${RESET} ${msg}`); }
function ok(msg) { console.log(` ${GREEN}✔ [memos-local]${RESET} ${msg}`); }
function fail(msg) { console.log(` ${RED}✖ [memos-local]${RESET} ${msg}`); }
function phase(n, title) {
console.log(`\n${CYAN}${BOLD} ─── Phase ${n}: ${title} ───${RESET}\n`);
}
const pluginDir = path.resolve(__dirname, "..");
console.log(`
${CYAN}${BOLD}┌──────────────────────────────────────────────────┐
│ MemOS Local Memory — postinstall setup │
└──────────────────────────────────────────────────┘${RESET}
`);
log(`Plugin dir: ${DIM}${pluginDir}${RESET}`);
log(`Node: ${process.version} Platform: ${process.platform}-${process.arch}`);
/* ═══════════════════════════════════════════════════════════
* Phase 0: Ensure all dependencies are installed
* ═══════════════════════════════════════════════════════════ */
function ensureDependencies() {
phase(0, "检测核心依赖 / Check core dependencies");
const coreDeps = ["@sinclair/typebox", "uuid", "posthog-node", "@huggingface/transformers"];
const missing = [];
for (const dep of coreDeps) {
try {
require.resolve(dep, { paths: [pluginDir] });
log(` ${dep} ${GREEN}✔${RESET}`);
} catch {
missing.push(dep);
log(` ${dep} ${RED}✖ missing${RESET}`);
}
}
if (missing.length === 0) {
ok("All core dependencies present.");
return;
}
warn(`Missing ${missing.length} dependencies: ${BOLD}${missing.join(", ")}${RESET}`);
log("Running: npm install --omit=dev ...");
const startMs = Date.now();
const result = spawnSync("npm", ["install", "--omit=dev"], {
cwd: pluginDir,
stdio: "pipe",
shell: true,
timeout: 120_000,
});
const elapsed = ((Date.now() - startMs) / 1000).toFixed(1);
const stderr = (result.stderr || "").toString().trim();
if (result.status === 0) {
ok(`Dependencies installed successfully (${elapsed}s).`);
} else {
fail(`npm install exited with code ${result.status} (${elapsed}s).`);
if (stderr) warn(`stderr: ${stderr.slice(0, 300)}`);
warn("Some features may not work. Try running manually:");
warn(` cd ${pluginDir} && npm install --omit=dev`);
}
}
try {
ensureDependencies();
} catch (e) {
warn(`Dependency check error: ${e.message}`);
}
/* ═══════════════════════════════════════════════════════════
* Phase 1: Clean up legacy plugin versions
* ═══════════════════════════════════════════════════════════ */
function cleanupLegacy() {
phase(1, "清理旧版本插件 / Clean up legacy plugins");
const home = process.env.HOME || process.env.USERPROFILE || "";
if (!home) { log("Cannot determine HOME directory, skipping."); return; }
const ocHome = path.join(home, ".openclaw");
if (!fs.existsSync(ocHome)) { log("No ~/.openclaw directory found, skipping."); return; }
const extDir = path.join(ocHome, "extensions");
if (!fs.existsSync(extDir)) { log("No extensions directory found, skipping."); return; }
const legacyDirs = [
path.join(extDir, "memos-lite"),
path.join(extDir, "memos-lite-openclaw-plugin"),
path.join(extDir, "node_modules", "@memtensor", "memos-lite-openclaw-plugin"),
];
let cleaned = 0;
for (const dir of legacyDirs) {
if (fs.existsSync(dir)) {
try {
fs.rmSync(dir, { recursive: true, force: true });
ok(`Removed legacy dir: ${DIM}${dir}${RESET}`);
cleaned++;
} catch (e) {
warn(`Could not remove ${dir}: ${e.message}`);
}
}
}
const cfgPath = path.join(ocHome, "openclaw.json");
if (fs.existsSync(cfgPath)) {
try {
const raw = fs.readFileSync(cfgPath, "utf-8");
const cfg = JSON.parse(raw);
const entries = cfg?.plugins?.entries;
if (entries) {
const oldKeys = ["memos-lite", "memos-lite-openclaw-plugin"];
let cfgChanged = false;
for (const oldKey of oldKeys) {
if (entries[oldKey]) {
const oldEntry = entries[oldKey];
if (!entries["memos-local-openclaw-plugin"]) {
entries["memos-local-openclaw-plugin"] = oldEntry;
log(`Migrated config: ${DIM}${oldKey}${RESET} → ${GREEN}memos-local-openclaw-plugin${RESET}`);
}
delete entries[oldKey];
cfgChanged = true;
ok(`Removed legacy config key: ${DIM}${oldKey}${RESET}`);
}
}
const newEntry = entries["memos-local-openclaw-plugin"];
if (newEntry && typeof newEntry.source === "string") {
const oldSource = newEntry.source;
if (oldSource.includes("memos-lite")) {
newEntry.source = oldSource
.replace(/memos-lite-openclaw-plugin/g, "memos-local-openclaw-plugin")
.replace(/memos-lite/g, "memos-local");
if (newEntry.source !== oldSource) {
log(`Updated source path: ${DIM}${oldSource}${RESET} → ${GREEN}${newEntry.source}${RESET}`);
cfgChanged = true;
}
}
}
if (cfgChanged) {
const backup = cfgPath + ".bak-" + Date.now();
fs.copyFileSync(cfgPath, backup);
fs.writeFileSync(cfgPath, JSON.stringify(cfg, null, 2) + "\n", "utf-8");
ok(`Config updated. Backup: ${DIM}${backup}${RESET}`);
} else {
log("No legacy config entries found.");
}
}
} catch (e) {
warn(`Could not update openclaw.json: ${e.message}`);
}
}
if (cleaned > 0) {
ok(`Legacy cleanup done: ${cleaned} old dir(s) removed.`);
} else {
ok("No legacy plugin directories found. Clean.");
}
}
try {
cleanupLegacy();
} catch (e) {
warn(`Legacy cleanup error: ${e.message}`);
}
/* ═══════════════════════════════════════════════════════════
* Phase 2: Verify better-sqlite3 native module
* ═══════════════════════════════════════════════════════════ */
phase(2, "检查 better-sqlite3 原生模块 / Check native module");
const sqliteModulePath = path.join(pluginDir, "node_modules", "better-sqlite3");
function findSqliteBinding() {
const candidates = [
path.join(sqliteModulePath, "build", "Release", "better_sqlite3.node"),
path.join(sqliteModulePath, "build", "better_sqlite3.node"),
path.join(sqliteModulePath, "build", "Debug", "better_sqlite3.node"),
];
const prebuildDir = path.join(sqliteModulePath, "prebuilds");
if (fs.existsSync(prebuildDir)) {
try {
const platformDir = `${process.platform}-${process.arch}`;
const pbDir = path.join(prebuildDir, platformDir);
if (fs.existsSync(pbDir)) {
const files = fs.readdirSync(pbDir).filter(f => f.endsWith(".node"));
for (const f of files) candidates.push(path.join(pbDir, f));
}
} catch { /* ignore */ }
}
for (const c of candidates) {
if (fs.existsSync(c)) return c;
}
return null;
}
function sqliteBindingsExist() {
const found = findSqliteBinding();
if (found) {
log(`Native binding found: ${DIM}${found}${RESET}`);
return true;
}
return false;
}
/**
* Check whether better-sqlite3 can actually be loaded by the current
* Node.js runtime. A binding file may exist on disk but still fail
* with NODE_MODULE_VERSION mismatch after a Node.js or plugin update.
*/
function sqliteLoadsSuccessfully() {
try {
require(path.join(sqliteModulePath, "lib", "index.js"));
return true;
} catch (e) {
if (e && e.message && e.message.includes("NODE_MODULE_VERSION")) {
warn("ABI version mismatch — native module was built for a different Node.js version.");
return false;
}
// For any other load error fall through to the rebuild path as well.
return false;
}
}
let needsRebuild = false;
if (!sqliteBindingsExist()) {
warn("better-sqlite3 native bindings not found in plugin dir.");
log(`Searched in: ${DIM}${sqliteModulePath}/build/${RESET}`);
needsRebuild = true;
} else if (!sqliteLoadsSuccessfully()) {
log("Native binding file exists but cannot be loaded by current Node.js.");
needsRebuild = true;
} else {
ok("better-sqlite3 is ready.");
console.log(`
${GREEN}${BOLD} ┌──────────────────────────────────────────────────┐
│ ✔ Setup complete! │
│ │
│ Restart gateway: │
│ ${CYAN}openclaw gateway stop && openclaw gateway start${GREEN} │
└──────────────────────────────────────────────────┘${RESET}
`);
process.exit(0);
}
log("Running: npm rebuild better-sqlite3 (may take 30-60s)...");
const startMs = Date.now();
const result = spawnSync("npm", ["rebuild", "better-sqlite3"], {
cwd: pluginDir,
stdio: "pipe",
shell: true,
timeout: 180_000,
});
const elapsed = ((Date.now() - startMs) / 1000).toFixed(1);
const stdout = (result.stdout || "").toString().trim();
const stderr = (result.stderr || "").toString().trim();
if (stdout) log(`rebuild output: ${DIM}${stdout.slice(0, 500)}${RESET}`);
if (stderr) warn(`rebuild stderr: ${DIM}${stderr.slice(0, 500)}${RESET}`);
if (result.status === 0) {
if (sqliteBindingsExist()) {
ok(`better-sqlite3 rebuilt successfully (${elapsed}s).`);
console.log(`
${GREEN}${BOLD} ┌──────────────────────────────────────────────────┐
│ ✔ Setup complete! │
│ │
│ Restart gateway: │
│ ${CYAN}openclaw gateway stop && openclaw gateway start${GREEN} │
└──────────────────────────────────────────────────┘${RESET}
`);
process.exit(0);
} else {
fail(`Rebuild completed but bindings still missing (${elapsed}s).`);
fail(`Looked in: ${sqliteModulePath}/build/`);
}
} else {
fail(`Rebuild failed with exit code ${result.status} (${elapsed}s).`);
}
console.log(`
${YELLOW}${BOLD} ╔══════════════════════════════════════════════════════════════╗
║ ✖ better-sqlite3 native module build failed ║
╠══════════════════════════════════════════════════════════════╣${RESET}
${YELLOW} ║${RESET} ${YELLOW}║${RESET}
${YELLOW} ║${RESET} This plugin requires C/C++ build tools to compile ${YELLOW}║${RESET}
${YELLOW} ║${RESET} the SQLite native module on first install. ${YELLOW}║${RESET}
${YELLOW} ║${RESET} ${YELLOW}║${RESET}
${YELLOW} ║${RESET} ${BOLD}Install build tools:${RESET} ${YELLOW}║${RESET}
${YELLOW} ║${RESET} ${YELLOW}║${RESET}
${YELLOW} ║${RESET} ${CYAN}macOS:${RESET} xcode-select --install ${YELLOW}║${RESET}
${YELLOW} ║${RESET} ${CYAN}Ubuntu:${RESET} sudo apt install build-essential python3 ${YELLOW}║${RESET}
${YELLOW} ║${RESET} ${CYAN}Windows:${RESET} npm install -g windows-build-tools ${YELLOW}║${RESET}
${YELLOW} ║${RESET} ${YELLOW}║${RESET}
${YELLOW} ║${RESET} ${BOLD}Then retry:${RESET} ${YELLOW}║${RESET}
${YELLOW} ║${RESET} ${GREEN}cd ${pluginDir}${RESET}
${YELLOW} ║${RESET} ${GREEN}npm rebuild better-sqlite3${RESET} ${YELLOW}║${RESET}
${YELLOW} ║${RESET} ${GREEN}openclaw gateway stop && openclaw gateway start${RESET} ${YELLOW}║${RESET}
${YELLOW} ║${RESET} ${YELLOW}║${RESET}
${YELLOW}${BOLD} ╚══════════════════════════════════════════════════════════════╝${RESET}
`);
process.exit(0);