UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

213 lines (212 loc) • 7.95 kB
import * as module from "node:module"; import { readFileSync, statSync } from "node:fs"; import { fileURLToPath } from "node:url"; import path from "node:path"; import { createHash } from "node:crypto"; import fs$1 from "node:fs/promises"; import os from "node:os"; import { isMainThread } from "node:worker_threads"; //#region node-compile-cache.mjs if (isMainThread && process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED === "gateway") { delete process.env.NODE_DISABLE_COMPILE_CACHE; delete process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED; } const MAX_BYTES = 536870912; const MAX_AGE_MS = 6048e5; const MAINTENANCE_INTERVAL_MS = 36e5; const MAX_FILES = 4096; const MAX_VISITS = 16384; const MAINTENANCE_BUDGET_MS = 3e4; const BUILD_MARKER_RE = /^(?:[a-f0-9]{16}|\d+-\d+|no-package-json|build-[A-Za-z0-9._-]+)$/; const sanitize = (e) => { const t = e.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, ""); return t && t !== "." && t !== ".." ? t : "unknown"; }; function isCurrentCompileCache(e, t) { const n = module.getCompileCacheDir?.(); const r = path.resolve(e); return n && (path.resolve(n) === r || t.NODE_COMPILE_CACHE && path.resolve(t.NODE_COMPILE_CACHE) === r && path.dirname(path.resolve(n)) === r); } function resolveOpenClawCompileCacheRespawnEnv({ directory: e, env: t = process.env, foregroundGateway: n = false }) { if (process.permission || t.NODE_DISABLE_COMPILE_CACHE !== void 0 || t.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED === "1" && !n || !e || !module.getCompileCacheDir?.()) return; if (n && isMainThread) return { ...t, NODE_COMPILE_CACHE: e, NODE_DISABLE_COMPILE_CACHE: "1", OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED: "gateway" }; if (isCurrentCompileCache(e, t)) return; return { ...t, NODE_COMPILE_CACHE: e, OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED: "1" }; } function enableOpenClawCompileCache({ directory: e, env: t = process.env, foregroundGateway: n = false }) { if (!e || t.NODE_DISABLE_COMPILE_CACHE !== void 0) return; const r = globalThis[Symbol.for("openclaw.nodeCompileCacheBase")] ??= {}; if (n && isMainThread) { r.baseDirectory ??= path.resolve(e); maintainOpenClawCompileCache(e); return; } try { const n = module.enableCompileCache(e); if (n.status === module.constants.compileCacheStatus.ENABLED || n.status === module.constants.compileCacheStatus.ALREADY_ENABLED && isCurrentCompileCache(e, t)) { r.baseDirectory ??= path.resolve(e); maintainOpenClawCompileCache(e); return; } if (n.status === module.constants.compileCacheStatus.ALREADY_ENABLED) return; } catch {} if (!r.unavailableReported) { r.unavailableReported = true; process.stderr.write("[openclaw] Compile cache unavailable; continuing without it.\n"); } } function scheduleOpenClawCompileCacheFlush() { if (!module.getCompileCacheDir?.()) return; const e = globalThis[Symbol.for("openclaw.nodeCompileCacheBase")] ??= {}; if (e.flush) return; e.flush = setImmediate(() => { e.flush = void 0; try { module.flushCompileCache(); } catch {} }); e.flush.unref(); } function resolveOpenClawCompileCacheDirectory({ installRoot: e, env: t = process.env, foregroundGateway: n = false, prewarm: r = false }) { if (t.NODE_DISABLE_COMPILE_CACHE !== void 0) return; if (!r && !n && t.NODE_COMPILE_CACHE === void 0) return; const i = path.join(e, "package.json"); let a = "unknown"; let o = "no-package-json"; try { const e = JSON.parse(readFileSync(i, "utf8")); a = typeof e.version === "string" ? sanitize(e.version) : a; const t = statSync(i); o = `${Math.trunc(t.mtimeMs)}-${t.size}`; } catch {} try { const t = JSON.parse(readFileSync(path.join(e, "dist", "build-info.json"), "utf8")); if (typeof t.buildId === "string" && t.buildId.trim()) o = createHash("sha256").update(t.buildId).digest("hex").slice(0, 16); } catch {} let s = path.resolve(t.NODE_COMPILE_CACHE || path.join(os.tmpdir(), "node-compile-cache")); while (path.basename(path.dirname(path.dirname(s))) === "openclaw" && BUILD_MARKER_RE.test(path.basename(s))) s = path.dirname(path.dirname(path.dirname(s))); return resolveSafeNodeCompileCacheDirectory(path.join(s, "openclaw", a, o)); } function resolveSafeNodeCompileCacheDirectory(e) { if (process.platform === "win32" && path.resolve(e).length > 200) { process.stderr.write("[openclaw] Compile cache disabled: Windows cache path exceeds 200 characters.\n"); return; } return e; } async function maintainOpenClawCompileCache(e) { if (process.permission) return; const t = globalThis[Symbol.for("openclaw.nodeCompileCacheBase")] ??= {}; const n = t.maintenance ??= /* @__PURE__ */ new Set(); if (n.has(e)) return; n.add(e); try { const t = await fs$1.lstat(path.dirname(path.dirname(e))).catch(() => void 0); if (t && Date.now() - t.mtimeMs < MAINTENANCE_INTERVAL_MS) return; const { spawn: n } = await import("node:child_process"); const r = n(process.execPath, [ fileURLToPath(import.meta.url), "--maintain", e ], { detached: true, stdio: "ignore", windowsHide: true, env: { ...Object.fromEntries(Object.entries(process.env).filter(([e]) => !/^(NODE_OPTIONS|BUN_OPTIONS)$/i.test(e))), NODE_DISABLE_COMPILE_CACHE: "1", OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED: "1" } }); r.on("error", () => {}); r.unref(); } catch {} } async function maintain(e) { const t = path.dirname(path.dirname(e)); const n = path.basename(path.dirname(e)); if (path.basename(t) !== "openclaw" || sanitize(n) !== n || !BUILD_MARKER_RE.test(path.basename(e))) return; const r = Date.now(); const i = await fs$1.lstat(t).catch(() => void 0); for (const n of [ t, path.dirname(e), e ]) { const e = n === t ? i : await fs$1.lstat(n).catch(() => void 0); if (e && !e.isDirectory()) return; } if (i && r - i.mtimeMs < MAINTENANCE_INTERVAL_MS) return; await fs$1.mkdir(t, { recursive: true }); const a = `${t}.maintenance`; const o = await fs$1.lstat(a).catch(() => void 0); if (o && r - o.mtimeMs > 3e5) await fs$1.rmdir(a).catch(() => {}); if (!await fs$1.mkdir(a).then(() => true, () => false)) return; const s = []; let c = 0; let l = 0; let u = false; async function prune() { s.sort((e, t) => t.mtimeMs - e.mtimeMs); while (s.length) { if (Date.now() - r > MAINTENANCE_BUDGET_MS) return false; const e = s[s.length - 1]; if (c <= MAX_BYTES && s.length <= MAX_FILES && r - e.mtimeMs <= MAX_AGE_MS) break; await fs$1.unlink(e.file).catch((e) => { if (e.code !== "ENOENT") throw e; }); c -= e.size; s.pop(); } return true; } async function visit(e) { for await (const t of await fs$1.opendir(e)) { if (++l > MAX_VISITS || Date.now() - r > MAINTENANCE_BUDGET_MS) return false; const n = path.join(e, t.name); if (t.isDirectory()) { if (!await visit(n)) return false; } else if (t.isFile()) { const e = await fs$1.lstat(n).catch((e) => { if (e.code !== "ENOENT") throw e; }); if (!e) continue; c += e.size; s.push({ file: n, size: e.size, mtimeMs: e.mtimeMs }); if (s.length % 256 === 0 && !await prune()) return false; } } return true; } try { if (r - (await fs$1.lstat(t)).mtimeMs < MAINTENANCE_INTERVAL_MS) { u = true; return; } const e = await visit(t); if (await prune() && e) { const e = /* @__PURE__ */ new Date(); await fs$1.utimes(t, e, e); u = true; } } finally { if (!u) await fs$1.utimes(t, i?.atime ?? /* @__PURE__ */ new Date(0), i?.mtime ?? /* @__PURE__ */ new Date(0)).catch(() => {}); await fs$1.rmdir(a); } } if (process.argv[2] === "--maintain" && process.argv[1] === fileURLToPath(import.meta.url) && process.argv[3]) maintain(process.argv[3]).catch(() => {}); //#endregion export { scheduleOpenClawCompileCacheFlush as a, resolveSafeNodeCompileCacheDirectory as i, resolveOpenClawCompileCacheDirectory as n, resolveOpenClawCompileCacheRespawnEnv as r, enableOpenClawCompileCache as t };