openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
136 lines (135 loc) • 6.15 kB
JavaScript
import { c as hasErrnoCode } from "./paths-0xDagtub.mjs";
import { p as isRecord } from "./utils-BclMknzT.mjs";
import { W as resolveGlobalSingleton, n as isPathInside } from "./path-guards-quCEQx1i.mjs";
import { X as truncateUtf16Safe, v as resolveIdentityPathViaExistingAncestorSync } from "./redact-BRF0hr6G.mjs";
import { t as createSubsystemLogger } from "./subsystem-CeOCPr4l.mjs";
import { t as formatErrorMessage } from "./errors-hqLS1E8Y.mjs";
import path from "node:path";
import fsPromises from "node:fs/promises";
import os from "node:os";
//#region src/infra/non-fatal-cleanup.ts
/** Run cleanup and swallow failures after invoking the optional error hook. */
async function runBestEffortCleanup(e) {
try {
return await e.cleanup();
} catch (t) {
try {
e.onError?.(t);
} catch {}
return;
}
}
//#endregion
//#region src/infra/temp-artifact-cleanup.ts
const log = createSubsystemLogger("infra:temp-artifacts");
const retainedRuntimes = resolveGlobalSingleton(Symbol.for("openclaw.retainedUpdateRuntimes"), () => /* @__PURE__ */ new Set());
/** Registration lasts through worker settlement, including failed update reporting. */
function registerRetainedUpdateRuntime(e) {
retainedRuntimes.add(e);
return () => void retainedRuntimes.delete(e);
}
function reportRetainedUpdateRuntime(e, t) {
const n = `Runtime retained at ${e}: ${t}`;
try {
log.warn(n);
} catch {}
return n;
}
/** Placement and discovery share the climb outside the enclosing module owner. */
function resolveRetainedUpdateRuntimeParents(e, t = []) {
const n = e.split(path.sep);
const r = n.indexOf("node_modules");
const i = [n.slice(0, r >= 0 ? r + 1 : n.length).join(path.sep), ...t];
let a = path.dirname(e);
const o = [a];
while (i.some((e) => isPathInside(e, a))) {
const e = path.dirname(a);
if (e === a) break;
a = e;
o.push(a);
}
return o;
}
async function isRetainedRuntimeMarker(e) {
if (await fsPromises.realpath(e).catch(() => void 0) !== e) return false;
const t = JSON.parse(await fsPromises.readFile(e, "utf8"));
return isRecord(t) && t.name === "openclaw";
}
async function recognizesRetainedRuntime(e, t) {
const n = path.parse(t).root;
const r = path.join(e, "tree", Buffer.from(n).toString("hex"));
const i = path.join(r, path.relative(n, t));
if (await isRetainedRuntimeMarker(path.join(i, "package.json"))) return true;
const a = path.dirname(i);
const o = path.dirname(a);
const s = path.dirname(o);
if (path.basename(i) !== "openclaw" || path.basename(a) !== "node_modules" || !path.basename(o).startsWith("openclaw@") || path.basename(s) !== ".pnpm" || await fsPromises.realpath(s).catch(() => void 0) !== s) return false;
let c = 0;
for await (const e of await fsPromises.opendir(s)) {
if (++c > 4096) throw new Error("retained pnpm version inventory exceeds the bounded lookup; inspect it before manual cleanup");
if (e.isDirectory() && e.name.startsWith("openclaw@") && await isRetainedRuntimeMarker(path.join(s, e.name, "node_modules/openclaw/package.json"))) return true;
}
return false;
}
/** Marked updater projections are disposable; live owners and maintenance fence reclamation. */
async function maintainRetainedUpdateRuntimes(e) {
const t = [];
const n = e.packageRoots.map(resolveIdentityPathViaExistingAncestorSync);
const r = new Set([
os.tmpdir(),
...e.temporaryDirectories ?? [],
...n.flatMap((e) => resolveRetainedUpdateRuntimeParents(e))
].map(resolveIdentityPathViaExistingAncestorSync));
for (const i of r) try {
for (const r of await fsPromises.readdir(i, { withFileTypes: true })) {
if (!/^openclaw-update-runtime-[A-Za-z0-9]{6}$/u.test(r.name)) continue;
const a = path.join(i, r.name);
try {
const r = await fsPromises.lstat(a);
if (!r.isDirectory() || process.getuid && r.uid !== process.getuid()) throw new Error("directory ownership is unknown; inspect it before manual cleanup");
if (retainedRuntimes.has(a)) throw new Error("the creating update still owns this runtime");
let i = false;
for (const e of n) if (await recognizesRetainedRuntime(a, e)) {
i = true;
break;
}
if (!i) throw new Error("no recognized runtime marker; inspect it before manual cleanup");
if (!e.repair) {
t.push(`Runtime retained at ${a}: run \`openclaw doctor --fix\` after its workers stop`);
continue;
}
const { inspectOtherOpenClawProcesses: o } = await import("./openclaw-process-census-CRsXDEnV.mjs");
const s = await fsPromises.lstat(a);
if (s.dev !== r.dev || s.ino !== r.ino || s.ctimeMs !== r.ctimeMs || retainedRuntimes.has(a)) throw new Error("directory identity or custody changed");
e.assertCurrent();
const c = o(a);
if ("error" in c) throw new Error(c.error);
for (const e of c.warnings ?? []) if (!t.includes(e)) t.push(e);
if (c.pids.length) throw new Error(`other OpenClaw processes are still running (PIDs: ${c.pids.join(", ")}); let these holders finish, then rerun openclaw doctor --fix`);
e.assertResourcesSettled?.(a);
e.assertCurrent();
let l;
await removeTemporaryArtifacts(a, "Updater runtime", (e) => {
l = `cleanup failed: ${formatErrorMessage(e)}`;
});
t.push(l ? reportRetainedUpdateRuntime(a, l) : `Removed abandoned updater runtime: ${a}`);
} catch (e) {
if (!hasErrnoCode(e, "ENOENT")) t.push(reportRetainedUpdateRuntime(a, formatErrorMessage(e)));
}
}
} catch (e) {
if (!hasErrnoCode(e, "ENOENT")) t.push(`Cannot inspect updater runtimes in ${i}: ${formatErrorMessage(e)}`);
}
return t;
}
function removeTemporaryArtifacts(e, t, n = (n) => log.warn(truncateUtf16Safe(formatErrorMessage(`${t} cleanup failed; files may remain in ${e}. After the worker or session stops, check permissions and remove the retained directory: ${formatErrorMessage(n)}`), 1024))) {
return runBestEffortCleanup({
cleanup: () => fsPromises.rm(e, {
recursive: true,
force: true
}),
onError: n
});
}
//#endregion
export { resolveRetainedUpdateRuntimeParents as a, reportRetainedUpdateRuntime as i, registerRetainedUpdateRuntime as n, removeTemporaryArtifacts as r, maintainRetainedUpdateRuntimes as t };