openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
407 lines (406 loc) • 15 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as FsSafeError, w as root } from "./fs-safe-BbWvmdVn.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { n as resolvePreferredOpenClawTmpDir } from "./tmp-openclaw-dir-Bf0oU1Cn.mjs";
import { r as resolveOpenClawPackageRootSync } from "./openclaw-root-C-ayo09z.mjs";
import { t as VERSION } from "./version-GlxUMdxI.mjs";
import { c as sha256File } from "./directory-durability-DlnWwNmv.mjs";
import { n as createLazyPromise } from "./lazy-promise-DiCvjz9w.mjs";
import { t as resolveNpmJsonEntries } from "./npm-json-output-D7OoAvKM.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 { t as runTasksWithConcurrency } from "./run-with-concurrency-B34GDKXE.mjs";
import { t as DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS } from "./worker-bundle-limits-Bj1ih83T.mjs";
import { n as WORKER_BUNDLE_CHUNK_PATH_PATTERN, o as compareWorkerBundlePaths, r as WORKER_BUNDLE_ENTRY_PATH, s as hashWorkerBundleManifest, t as WORKER_BUNDLE_ARTIFACT_PATHS } from "./worker-bundle-hash-BmNqrh0H.mjs";
import { o as create, r as extract } from "./esm-C2faEQS9.mjs";
import { n as readWorkerBundleArchiveManifest } from "./worker-bundle-archive-B6evR7Ir.mjs";
import { t as prepareNodeArtifactInWorker } from "./node-bootstrap-artifact-worker-BR0nDaYP.mjs";
import { createReadStream } from "node:fs";
import path from "node:path";
import { createHash, randomUUID } from "node:crypto";
import fs$1 from "node:fs/promises";
//#region src/gateway/worker-environments/bundle.ts
const OPENCLAW_NPM_REGISTRY = "https://registry.npmjs.org/";
const NPM_RELEASE_PROOF_TIMEOUT_MS = 6e4;
const NPM_SHA512_INTEGRITY_PATTERN = /^sha512-[A-Za-z0-9+/]{86}==$/u;
const BUNDLE_TARBALL_NAME_PATTERN = /^([a-f0-9]{64})\.tgz$/u;
const BUNDLE_STAGING_NAME_PATTERN = /^\.staging-[A-Za-z0-9_-]+$/u;
const BUNDLE_TEMP_NAME_PATTERN = /^[a-f0-9]{64}\.tgz\.[0-9]+\.[0-9a-f-]{36}\.tmp$/u;
const PACKAGED_BUNDLE_NAME_PATTERN = /^([a-f0-9]{64})\.tar\.gz$/u;
const PACKAGED_BUNDLE_DIRECTORY = "dist/worker-artifacts";
function normalizeProtocolFeatures(e) {
const t = e.map((e) => e.trim());
if (t.some((e) => e.length === 0)) throw new Error("Worker protocol features must be non-empty strings");
return [...new Set(t)].toSorted(compareWorkerBundlePaths);
}
function resolveBundleCacheDir(e) {
return e ? path.resolve(e) : path.join(resolveStateDir(), "cache", "worker-bundles");
}
function resolvePackageRoot(e) {
if (e) return path.resolve(e);
const t = resolveOpenClawPackageRootSync({
moduleUrl: import.meta.url,
argv1: process.argv[1],
cwd: process.cwd()
});
if (!t) throw new Error("Unable to locate the running OpenClaw package root for worker bundling");
return t;
}
async function isReleasedPackageInstall(e) {
const t = new Set(await fs$1.readdir(e));
return !t.has(".git") && !t.has("pnpm-lock.yaml") && !t.has("bun.lock") && !t.has("bun.lockb");
}
function parseNpmPackageIdentity(e) {
if (!isRecord(e)) return;
const t = normalizeOptionalString(e.name);
const n = normalizeOptionalString(e.version);
const r = normalizeOptionalString(e.integrity) ?? normalizeOptionalString(e["dist.integrity"]);
const i = normalizeOptionalString(e.filename);
return t && n && r ? {
name: t,
version: n,
integrity: r,
filename: i
} : void 0;
}
async function runNpmProofCommand(e) {
try {
const t = await runCommandWithTimeout(e.argv, {
cwd: e.cwd,
timeoutMs: NPM_RELEASE_PROOF_TIMEOUT_MS,
env: {
COREPACK_ENABLE_DOWNLOAD_PROMPT: "0",
NPM_CONFIG_IGNORE_SCRIPTS: "true"
}
});
if (t.code !== 0 || t.stdoutTruncatedBytes) throw new Error(e.failureMessage);
return JSON.parse(t.stdout.trim());
} catch {
throw new Error(e.failureMessage);
}
}
async function hashNpmTarballIntegrity(e) {
const t = createHash("sha512");
for await (const n of createReadStream(e)) t.update(n);
return `sha512-${t.digest("base64")}`;
}
async function verifyPublishedNpmRelease(e) {
const t = await fs$1.mkdtemp(path.join(resolvePreferredOpenClawTmpDir(), "openclaw-worker-npm-proof-"));
try {
const n = parseNpmPackageIdentity(resolveNpmJsonEntries(await runNpmProofCommand({
argv: [
"npm",
"view",
`openclaw@${e.version}`,
"name",
"version",
"dist.integrity",
"--json",
`--registry=${OPENCLAW_NPM_REGISTRY}`
],
cwd: t,
failureMessage: `OpenClaw ${e.version} is not published; use the worker bundle install`
}))[0]);
if (n?.name !== "openclaw" || n.version !== e.version || !NPM_SHA512_INTEGRITY_PATTERN.test(n.integrity)) throw new Error(`Cannot verify exact public npm release openclaw@${e.version}; use the worker bundle install`);
const r = await runNpmProofCommand({
argv: [
"npm",
"pack",
`openclaw@${e.version}`,
"--pack-destination",
t,
"--ignore-scripts",
"--json",
`--registry=${OPENCLAW_NPM_REGISTRY}`
],
cwd: t,
failureMessage: "Unable to verify the installed OpenClaw package; use the worker bundle install"
});
const i = parseNpmPackageIdentity(resolveNpmJsonEntries(r)[0]);
if (!i?.filename || path.basename(i.filename) !== i.filename) throw new Error("npm pack returned incomplete worker package metadata");
const a = path.join(t, i.filename);
let o;
try {
o = await hashNpmTarballIntegrity(a);
} catch {
throw new Error("Unable to verify the installed OpenClaw package; use the worker bundle install");
}
if (i.name !== n.name || i.version !== n.version || i.integrity !== n.integrity || o !== n.integrity) throw new Error(`Installed OpenClaw ${e.version} does not match the published package; use the worker bundle install`);
const s = path.join(t, "package");
await fs$1.mkdir(s);
await extract({
cwd: s,
file: a,
preservePaths: false,
strict: true,
strip: 1
});
if ((await prepareNodeArtifactInWorker("bundle", {
packageRoot: s,
cacheDir: path.join(t, "bundle-cache"),
openclawVersion: e.version,
protocolFeatures: []
})).bundleHash !== e.bundleHash) throw new Error(`Published OpenClaw ${e.version} does not match the prepared worker bundle; use the worker bundle install`);
return n.integrity;
} finally {
await fs$1.rm(t, {
recursive: true,
force: true
});
}
}
async function isCachedTarball(e) {
try {
const t = await fs$1.lstat(e);
if (t.isSymbolicLink() || !t.isFile()) throw new Error(`Unsafe worker bundle cache path: ${e}`);
return true;
} catch (e) {
if (e.code === "ENOENT") return false;
throw e;
}
}
async function cachedTarballMatches(e, t) {
if (!await isCachedTarball(e)) return false;
try {
return hashWorkerBundleManifest(await readWorkerBundleArchiveManifest(e, DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS)) === hashWorkerBundleManifest(t);
} catch {
return false;
}
}
async function writeTarball(e) {
const t = `${e.tarballPath}.${process.pid}.${randomUUID()}.tmp`;
try {
await create({
cwd: e.stagingRoot,
file: t,
gzip: true,
noDirRecurse: true,
noMtime: true,
portable: true,
strict: true,
onWriteEntry: ({ stat: e }) => {
if (e) e.mode = e.mode & -512 | 448;
}
}, e.entries.map((e) => e.path));
try {
await fs$1.rename(t, e.tarballPath);
} catch (n) {
if (n.code !== "EEXIST") throw n;
if (!await cachedTarballMatches(e.tarballPath, e.entries)) {
await fs$1.rm(e.tarballPath, { force: true });
try {
await fs$1.rename(t, e.tarballPath);
} catch (t) {
if (t.code !== "EEXIST" || !await cachedTarballMatches(e.tarballPath, e.entries)) throw t;
}
}
}
} finally {
await fs$1.rm(t, { force: true });
}
}
async function pruneWorkerBundleCache(e) {
let t;
try {
t = await fs$1.readdir(e.cacheDir, { withFileTypes: true });
} catch (t) {
if (t.code !== "ENOENT") e.onError?.(t);
return;
}
const n = t.map(({ name: e }) => ({
name: e,
bundleHash: BUNDLE_TARBALL_NAME_PATTERN.exec(e)?.[1],
staging: BUNDLE_STAGING_NAME_PATTERN.test(e)
})).filter(({ name: t, bundleHash: n, staging: r }) => n !== void 0 && n !== e.currentBundleHash || r || BUNDLE_TEMP_NAME_PATTERN.test(t));
if (n.length === 0) return;
const r = new Set([e.currentBundleHash, ...await e.readRetainedBundleHashes()].filter((e) => /^[a-f0-9]{64}$/u.test(e)));
for (const t of n.toSorted((e, t) => compareWorkerBundlePaths(e.name, t.name))) {
if (t.bundleHash !== void 0 && r.has(t.bundleHash)) continue;
const n = path.join(e.cacheDir, t.name);
try {
const e = await fs$1.lstat(n);
if (e.isSymbolicLink()) continue;
if (t.staging ? !e.isDirectory() : !e.isFile()) continue;
await fs$1.rm(n, {
recursive: t.staging,
force: true
});
} catch (t) {
if (t.code !== "ENOENT") e.onError?.(t);
}
}
}
async function prepareWorkerBundle(e) {
const { packageRoot: t, cacheDir: n, openclawVersion: r, protocolFeatures: i } = e;
const a = await resolvePackagedWorkerBundle({
packageRoot: t,
openclawVersion: r,
protocolFeatures: i
});
if (a) return a;
await fs$1.mkdir(n, { recursive: true });
const o = await fs$1.mkdtemp(path.join(n, ".staging-"));
try {
try {
var s = _usingCtx();
const [e, a] = await Promise.all([root(t, { maxBytes: Infinity }), fs$1.readdir(path.join(t, "dist/worker"))]).catch((e) => {
throw new Error(`OpenClaw worker deploy artifact is missing; build the running package at ${t}`, { cause: e });
});
const c = a.filter((e) => WORKER_BUNDLE_CHUNK_PATH_PATTERN.test(e));
const { results: l, hasError: u, firstError: d } = await runTasksWithConcurrency({
tasks: [...WORKER_BUNDLE_ARTIFACT_PATHS, ...c].map((n) => async () => {
const r = `dist/worker/${n}`;
const { buffer: i } = await e.read(r, {
symlinks: "reject",
hardlinks: "allow"
}).catch((e) => {
if (e instanceof FsSafeError && e.category === "policy") throw new Error(`Unsafe worker deploy artifact: ${r}`, { cause: e });
throw new Error(`OpenClaw worker deploy artifact is missing; build the running package at ${t}`, { cause: e });
});
await fs$1.writeFile(path.join(o, n), i, {
flag: "wx",
mode: 448
});
return {
path: n,
mode: 448,
size: i.byteLength,
sha256: createHash("sha256").update(i).digest("hex")
};
}),
limit: 16,
errorMode: "stop"
});
if (u) throw d;
const f = l.toSorted((e, t) => compareWorkerBundlePaths(e.path, t.path));
const p = hashWorkerBundleManifest(f);
const m = path.join(n, `${p}.tgz`);
if (!await cachedTarballMatches(m, f)) await writeTarball({
stagingRoot: o,
entries: f,
tarballPath: m
});
const h = s.a(await fs$1.open(m, "r"));
return {
install: "bundle",
bundleHash: p,
openclawVersion: r,
protocolFeatures: i,
tarballBytes: (await fs$1.stat(m)).size,
tarballSha256: (await sha256File(h)).digest,
tarballPath: m
};
} catch (e) {
s.e = e;
} finally {
await s.d();
}
} finally {
await fs$1.rm(o, {
recursive: true,
force: true
});
}
}
async function resolvePackagedWorkerBundle(e) {
try {
var t = _usingCtx();
try {
await fs$1.access(path.join(e.packageRoot, "dist/worker", WORKER_BUNDLE_ENTRY_PATH));
return null;
} catch (e) {
if (!isRecord(e) || e.code !== "ENOENT") throw e;
}
const n = path.join(e.packageRoot, PACKAGED_BUNDLE_DIRECTORY);
let r;
try {
r = await fs$1.readdir(n, { withFileTypes: true });
} catch (e) {
if (isRecord(e) && e.code === "ENOENT") return null;
throw e;
}
if (r.length !== 1 || !r[0].isFile()) throw new Error("Packaged worker bundle must contain exactly one regular archive");
const i = PACKAGED_BUNDLE_NAME_PATTERN.exec(r[0].name);
if (!i) throw new Error("Packaged worker bundle archive name is invalid");
const a = path.join(n, r[0].name);
const o = await readWorkerBundleArchiveManifest(a, DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS);
const s = new Set(o.map((e) => e.path));
const c = new Set(WORKER_BUNDLE_ARTIFACT_PATHS);
if (WORKER_BUNDLE_ARTIFACT_PATHS.some((e) => !s.has(e)) || o.some((e) => !c.has(e.path) && !WORKER_BUNDLE_CHUNK_PATH_PATTERN.test(e.path))) throw new Error("Packaged worker bundle archive does not match the worker artifact contract");
const l = hashWorkerBundleManifest(o);
if (l !== i[1]) throw new Error("Packaged worker bundle archive name does not match its manifest hash");
const u = t.a(await fs$1.open(a, "r"));
return {
install: "bundle",
bundleHash: l,
openclawVersion: e.openclawVersion,
protocolFeatures: e.protocolFeatures,
tarballBytes: (await u.stat()).size,
tarballSha256: (await sha256File(u)).digest,
tarballPath: a
};
} catch (e) {
t.e = e;
} finally {
await t.d();
}
}
/** Creates a process-lifecycle bundle producer that scans the running build at most once. */
function createWorkerBundleProducer(e = {}) {
let t;
let n = Promise.resolve();
return {
prepare: createLazyPromise(async () => {
const n = (e.openclawVersion ?? VERSION).trim();
if (!n) throw new Error("Worker bundle requires a non-empty OpenClaw version");
t = await prepareNodeArtifactInWorker("bundle", {
packageRoot: resolvePackageRoot(e.packageRoot),
cacheDir: resolveBundleCacheDir(e.cacheDir),
openclawVersion: n,
protocolFeatures: normalizeProtocolFeatures(e.protocolFeatures ?? [])
});
return t;
}),
async prune(r) {
const i = t;
if (!i) return;
const a = n.then(async () => {
await pruneWorkerBundleCache({
cacheDir: resolveBundleCacheDir(e.cacheDir),
currentBundleHash: i.bundleHash,
readRetainedBundleHashes: r,
onError: e.onCacheCleanupError
});
});
n = a.catch(() => void 0);
await a;
}
};
}
/**
* Selects the exact npm package only after the public tarball's canonical worker manifest proves
* parity with the running gateway bundle.
*/
async function resolveWorkerNpmInstallationArtifact(e) {
const t = e.bundle.openclawVersion.trim();
if (!isExactSemverVersion(t)) throw new Error(`Worker npm install requires the exact published gateway version; expected ${t}`);
if (!await isReleasedPackageInstall(resolvePackageRoot(e.packageRoot))) throw new Error("Worker npm install requires the gateway to run from a packaged release install");
const n = await (e.verifyRelease ?? verifyPublishedNpmRelease)({
bundleHash: e.bundle.bundleHash,
version: t
});
return {
install: "npm",
bundleHash: e.bundle.bundleHash,
openclawVersion: t,
packageIntegrity: n,
protocolFeatures: e.bundle.protocolFeatures,
packageSpec: `openclaw@${t}`
};
}
//#endregion
export { prepareWorkerBundle as n, resolveWorkerNpmInstallationArtifact as r, createWorkerBundleProducer as t };