openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
265 lines (264 loc) • 10.3 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { o as asRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { a as lstatIfExists } from "./path-existence-Co7-GyVr.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { i as parsePackageOpenClawSchemaVersions } from "./openclaw-schema-versions-E_10NoI6.mjs";
import { n as AUTO_UPDATE_STEP_TIMEOUT_MS } from "./update-run-timeouts-Byb-PlTk.mjs";
import { i as isExactSemverVersion } from "./npm-registry-spec-HKkAvl6N.mjs";
import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs";
import "./exec-aRIvS9s4.mjs";
import "./http-body-B9w7rzPz.mjs";
import { t as cancelUnreadResponseBody } from "./http-response-body-B-i_0116.mjs";
import { n as buildTimeoutAbortSignal } from "./fetch-timeout-D62KciOm.mjs";
import { a as resolveNpmGlobalPrefixLayoutFromPrefix } from "./update-npm-prefix-CBfxc8-S.mjs";
import { o as UPDATE_NETWORK_TIMEOUT_MS } from "./npm-install-env-DGs2GyHo.mjs";
import { n as fetchRegistryPackageDocument } from "./update-check-package-target-f97Li08r.mjs";
import { n as collectPackageDistContentInventoryErrors } from "./package-dist-inventory-Cx9cBjwG.mjs";
import { S as createGlobalInstallEnv, f as resolveGlobalInstallTarget, r as collectInstalledGlobalPackageErrors } from "./update-global-EYvKtjUB.mjs";
import { a as runStep } from "./update-runner-command-DcZD6XBi.mjs";
import { l as resolveUpdateRegistryTarget } from "./update-check-BfPo_IXH.mjs";
import { c as withInstallWorkspace, i as packNpmSpecToArchive, r as normalizeNpmViewMetadata, s as resolveNpmSpecMetadata } from "./install-source-utils-yGloSiaw.mjs";
import { t as resolveNpmIntegrityDriftWithDefaultMessage } from "./npm-integrity-CW0aDdA3.mjs";
import { t as withUpdateCommandExecutor } from "./update-command-executor-DJ6PbooS.mjs";
import { t as runGlobalPackageUpdateSteps } from "./package-update-steps-N6noh5W3.mjs";
import { n as assertNodeRuntimeUpdateCompatible, r as readNodeRuntimeUpdateManifest, t as assertNodeRuntimeSchemaVersions } from "./auto-update-compatibility-gTRYr_5N.mjs";
import { createWriteStream } from "node:fs";
import path from "node:path";
import { createHash, randomUUID } from "node:crypto";
import fs$1 from "node:fs/promises";
import { pipeline } from "node:stream/promises";
//#region src/node-host/auto-update-install.ts
/** Install only into an immutable private generation; activation belongs to the node launcher. */
async function prepareNodeRuntimeUpdate(e) {
const t = e.targetVersion.trim();
if (!isExactSemverVersion(t) || /[\\/]/u.test(t)) throw new Error("Node auto-update requires an exact published OpenClaw version.");
e.signal?.throwIfAborted();
const n = `openclaw@${t}`;
const r = process.versions.bun && process.platform !== "win32" ? "bun" : "npm";
const i = resolveUpdateRegistryTarget();
const a = r === "bun" ? await (async () => {
try {
const n = await fetchRegistryPackageDocument({
...i,
signal: e.signal,
target: t,
label: "npm package manifest",
operation: "npm-registry-package-manifest",
bodyTimeoutMs: Math.max(1, UPDATE_NETWORK_TIMEOUT_MS)
});
const r = normalizeNpmViewMetadata(n, `${i.packageName}@${t}`);
const a = normalizeOptionalString(asRecord(asRecord(n).dist).tarball);
if (!r?.name || !r.version || !a) throw new Error("Registry returned incomplete package metadata (name, version, or tarball).");
return {
...r,
tarball: a
};
} catch (e) {
throw new Error(`Registry package manifest failed: ${String(e)}`, { cause: e });
}
})() : void 0;
let o = a;
if (!o) {
const t = await resolveNpmSpecMetadata({
spec: n,
signal: e.signal
});
if (!t.ok) throw new Error(t.error);
o = t.metadata;
}
if (o.name !== "openclaw" || o.version !== t || !o.integrity) throw new Error("Node auto-update registry metadata does not identify the requested release and integrity.");
assertNodeRuntimeSchemaVersions(parsePackageOpenClawSchemaVersions({
name: o.name,
version: o.version,
openclaw: o.packageOpenClaw
}));
const s = o.integrity;
const c = createHash("sha256").update(s).digest("hex");
const l = path.resolve(e.stateDir, "node-runtime", "releases", `${t}-${c}`);
const prepareGeneration = async (o) => {
const c = resolveNpmGlobalPrefixLayoutFromPrefix(o);
const l = path.join(c.globalRoot, "openclaw");
const u = {
runtimeRoot: o,
packageRoot: l,
version: t,
integrity: s
};
return await withUpdateCommandExecutor(randomUUID(), async (d) => {
const f = await d.enter(o);
const assertCurrent = () => {
f.assertCurrent();
e.signal?.throwIfAborted();
};
assertCurrent();
if (await lstatIfExists(l, "ENOENT") !== void 0) {
try {
const e = [...await collectInstalledGlobalPackageErrors({
packageRoot: l,
expectedVersion: t
}), ...await collectPackageDistContentInventoryErrors(l)];
if (e.length) throw new Error(e.join("; "));
await readNodeRuntimeUpdateManifest(l);
} catch (e) {
assertCurrent();
return { invalidRuntime: `Preserved invalid node runtime at ${o}: ${formatErrorMessage(e)}` };
}
await assertNodeRuntimeUpdateCompatible({
...e,
packageRoot: l
});
assertCurrent();
return u;
}
return await withInstallWorkspace("openclaw-node-update-", async (o) => {
assertCurrent();
let d;
if (a) {
const { signal: t, cleanup: n, refresh: r } = buildTimeoutAbortSignal({
timeoutMs: Math.max(1, UPDATE_NETWORK_TIMEOUT_MS),
signal: e.signal,
operation: "npm-registry-package-download"
});
let c;
let l;
try {
const e = new URL(a.tarball);
if (e.origin !== new URL(i.registryUrl).origin) throw new Error("Package tarball must share the registry origin.");
if (!/^sha512-[A-Za-z0-9+/]{86}==$/u.test(s)) throw new Error("Package archive requires supported sha512 integrity.");
c = await fetch(e.toString(), {
signal: t,
redirect: "error"
});
if (!c.ok || !c.body) throw new Error(`Package archive download failed: HTTP ${c.status}`);
r();
const n = createHash("sha512");
l = path.join(o, `${randomUUID()}.tgz`);
await pipeline(c.body, async function* (e) {
for await (const t of e) {
n.update(t);
r();
yield t;
}
}, createWriteStream(l, {
flags: "wx",
mode: 384
}), { signal: t });
t?.throwIfAborted();
if (`sha512-${n.digest("base64")}` !== s) throw new Error("Package archive integrity mismatch.");
d = l;
} catch (e) {
if (l) await fs$1.rm(l, { force: true });
throw new Error(`Registry package archive failed: ${String(e)}`, { cause: e });
} finally {
await cancelUnreadResponseBody(c);
n();
}
assertCurrent();
} else {
const r = await packNpmSpecToArchive({
spec: n,
cwd: o,
timeoutMs: AUTO_UPDATE_STEP_TIMEOUT_MS,
signal: e.signal
});
assertCurrent();
if (!r.ok) throw new Error(r.error);
if (r.metadata.name !== "openclaw" || r.metadata.version !== t) throw new Error("Node auto-update archive does not match the requested release.");
const i = await resolveNpmIntegrityDriftWithDefaultMessage({
spec: n,
expectedIntegrity: s,
resolution: r.metadata
});
if (i.error) throw new Error(i.error);
d = r.archivePath;
}
const f = await createGlobalInstallEnv({
...process.env,
OPENCLAW_STATE_DIR: path.join(o, "state"),
OPENCLAW_CONFIG_PATH: path.join(o, "openclaw.json"),
...r === "bun" ? {
BUN_INSTALL_GLOBAL_DIR: path.dirname(c.globalRoot),
BUN_INSTALL_BIN: c.binDir
} : {}
}, { manager: r });
const runCommand = async (t, n) => {
assertCurrent();
const r = await runCommandWithTimeout(t, {
...n,
env: {
...f,
...n.env
},
signal: e.signal,
killProcessTree: true
});
assertCurrent();
return r;
};
const p = await resolveGlobalInstallTarget({
manager: r,
runCommand,
timeoutMs: AUTO_UPDATE_STEP_TIMEOUT_MS,
pkgRoot: l,
honorPackageRoot: true,
packageName: "openclaw",
...r === "bun" ? { env: f } : {}
});
if (p.manager !== r || p.packageRoot !== l || p.globalRoot !== c.globalRoot) throw new Error(`Node auto-update ${r} target escaped its private runtime prefix.`);
assertCurrent();
if (r === "bun") {
await fs$1.mkdir(c.globalRoot, { recursive: true });
await fs$1.mkdir(c.binDir, { recursive: true });
await fs$1.writeFile(path.join(path.dirname(c.globalRoot), "package.json"), "{\"private\":true}\n", { flag: "wx" }).catch((e) => {
if (!hasErrnoCode(e, "EEXIST")) throw e;
});
assertCurrent();
}
const m = await runGlobalPackageUpdateSteps({
installTarget: p,
installSpec: d,
packageName: "openclaw",
runCommand,
runStep: (e) => runStep({
...e,
runCommand,
cwd: e.cwd ?? o,
stepIndex: 0,
totalSteps: 0
}),
timeoutMs: AUTO_UPDATE_STEP_TIMEOUT_MS,
env: f,
installCwd: o,
assertCurrent,
validateCandidate: async (n) => {
if ((await readNodeRuntimeUpdateManifest(n)).version !== t) throw new Error("Node auto-update installed an unexpected package version.");
await assertNodeRuntimeUpdateCompatible({
...e,
packageRoot: n
});
assertCurrent();
return [];
}
});
assertCurrent();
if (m.failedStep || m.activePackageRoot !== l || m.afterVersion !== t) throw new Error(m.failedStep?.stderrTail ?? "Node auto-update private installation could not be verified.");
return u;
});
});
};
const u = await prepareGeneration(l);
if (!("invalidRuntime" in u)) return u;
try {
const e = await prepareGeneration(`${l}-${randomUUID()}`);
if ("invalidRuntime" in e) throw new Error(e.invalidRuntime);
return {
...e,
warnings: [u.invalidRuntime]
};
} catch (e) {
throw new Error(`${u.invalidRuntime}; fresh installation failed: ${formatErrorMessage(e)}`, { cause: e });
}
}
//#endregion
export { prepareNodeRuntimeUpdate };