UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,287 lines • 52.2 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { O as walkDirectory, w as root } from "./fs-safe-BbWvmdVn.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { c as sha256File } from "./directory-durability-DlnWwNmv.mjs";
import { n as MAX_WORKER_BUNDLE_ARCHIVE_BYTES, t as DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS } from "./worker-bundle-limits-Bj1ih83T.mjs";
import { o as compareWorkerBundlePaths, s as hashWorkerBundleManifest } from "./worker-bundle-hash-BmNqrh0H.mjs";
import { r as PACKAGE_LIFECYCLE_PENDING_RELATIVE_PATH, t as LEGACY_PACKAGE_INSTALL_GUARD_RELATIVE_PATH } from "./package-lifecycle-marker-DhfhzqrA.mjs";
import { r as collectPackageDistInventory, s as PACKAGE_DIST_INVENTORY_RELATIVE_PATH } from "./package-dist-inventory-Cx9cBjwG.mjs";
import { t as isRecord$1 } from "./record-shared-CspPqq9g.mjs";
import { g as ReadEntry, s as Pack, v as Header } from "./esm-C2faEQS9.mjs";
import { n as readWorkerBundleArchiveManifest } from "./worker-bundle-archive-B6evR7Ir.mjs";
import { createRequire } from "node:module";
import fs, { constants, createWriteStream } from "node:fs";
import path, { isAbsolute, join, win32 } from "node:path";
import { createHash } from "node:crypto";
import fs$1 from "node:fs/promises";
import { isDeepStrictEqual } from "node:util";
import { once } from "node:events";
import { satisfies, valid } from "semver";
import { StringDecoder } from "node:string_decoder";
import { finished, pipeline } from "node:stream/promises";
import { Parser } from "acorn";
//#region scripts/lib/package-bundle-dependencies.mts
function listBundleDependencies(e) {
	if (!isRecord$1(e)) return [];
	if (e.bundleDependencies === true || e.bundledDependencies === true) return Object.keys(isRecord$1(e.dependencies) ? e.dependencies : {});
	const t = Array.isArray(e.bundleDependencies) ? e.bundleDependencies : e.bundledDependencies;
	return Array.isArray(t) ? t.filter((e) => typeof e === "string") : [];
}
//#endregion
//#region scripts/lib/package-bundled-mcp.mts
const PATCHED_MCP_NAME = "chrome-devtools-mcp";
const PATCHED_MCP_CLI = "build/src/bin/chrome-devtools-mcp.js";
function mcpFileHashes(e) {
	return /* @__PURE__ */ new Map([
		[PATCHED_MCP_CLI, e.cli],
		["build/src/bin/chrome-devtools-mcp-main.js", e.main],
		["LICENSE", "58d1e17ffe5109a7ae296caafcadfdbe6a7d176f0bc4ab01e12a689b0499d8bd"],
		["build/src/third_party/THIRD_PARTY_NOTICES", e.notices],
		["build/src/TextSnapshot.js", e.snapshot],
		["build/src/McpPage.js", e.page],
		["build/src/third_party/index.js", e.thirdParty],
		["build/src/OPENCLAW_PATCH_NOTICE.md", e.patchNotice]
	]);
}
const MCP_FILE_HASHES = /* @__PURE__ */ new Map([
	["1.8.0", mcpFileHashes({
		cli: "9f380d06e1ac05b257e27e708c0cc4b4ba190e285ed6eb6c8aa50978d98a12c5",
		snapshot: "299833ad0e4cfc171a417afaec41df594e4862fe53a7ada6ba160409f979788b",
		main: "fc383cb3e5db5f18cf1e8c49221212c669825248874ba91c90ba9035e175f5b4",
		notices: "8f10277934fe6888173f41f7cbbd9112d208c8c931bf163db59110f69f119e53",
		page: "b9e791d758e4d28589525e2d427600e24b271d365a5879893a392043a11cf426",
		thirdParty: "a8f5cb1e02405d347117114141b58572f71c083861fb50ab31a27511e3a279bf",
		patchNotice: "8f5a32aaedf4bb6f8ad39f226bd343bf804132c11ebc6c3c19f667669856287c"
	})],
	["1.9.0", mcpFileHashes({
		cli: "9f380d06e1ac05b257e27e708c0cc4b4ba190e285ed6eb6c8aa50978d98a12c5",
		snapshot: "299833ad0e4cfc171a417afaec41df594e4862fe53a7ada6ba160409f979788b",
		main: "5ca0e81196ab6b6e1481629a2dcae7f416b3b38f74555e3138ad5cdbb055e809",
		notices: "975febf536bb1c83c031a7888b90bdf1ffe8dc46000e0698eac364491dca8ac4",
		page: "6d83dbd4d79c913664fbfa428d138b22fe4246612ab4dfcd93e9d8e62d5d6b51",
		thirdParty: "7609bb6c575c7c1152b3f4233ad4b98d97885c62ccff7bd9ee29257ca8ffc83f",
		patchNotice: "0e53a04f337a3760f2f1adab9c20e3b4f07019795f503266c0b68e0f46d55a6c"
	})],
	["1.10.1", mcpFileHashes({
		cli: "9f380d06e1ac05b257e27e708c0cc4b4ba190e285ed6eb6c8aa50978d98a12c5",
		snapshot: "299833ad0e4cfc171a417afaec41df594e4862fe53a7ada6ba160409f979788b",
		main: "10603ea8c2ac9f69a42791100701795018ebfaa522a7c93d783ed583cce5cce4",
		notices: "6ae0ce181dbc9ba4217b6aad679d7503ed3ab56c45e6f3647e9ab753aa97b67b",
		page: "47aa13c6b28cc11e1b0883532edea97cfde7563d78d143035850852d09809975",
		thirdParty: "c988e0684584b75e87ae04b768c4f8ae7064401afe5187ec0d4878b2c6833f12",
		patchNotice: "4bf44b52a80b5860b2160bc83407a5f0dd09f1801c85d0a2b6e4fec26bd7045d"
	})],
	["1.11.0", mcpFileHashes({
		cli: "e8b0290a8fe9a1edc31d595ccc870df926bfaaafe19fb14cd4d8d47bf6194979",
		main: "68bffbf26cf0e8840409079456a7681c03e737cd977935c2e0c424c1b8a0700a",
		snapshot: "5c647c3d0b416bdfc1bcaf1b1136f6a7682db05cf59982e3ab6f17d00d2d17ac",
		notices: "6476ce17667202e92ea191d166050a3ab74f465f2f7a2b6b01dcb4e9477b6a0a",
		page: "4044a30df6292a5d4517f718c32818e9c85f8051c318ec88bef7aa127d883a36",
		thirdParty: "b047499006b0027bd37165fa8197fa6fa5caa9b8c07d938992857659270ec493",
		patchNotice: "41aada055258ec8754581f6cee1e3ed505499be8373969e6267031ebabc00594"
	})]
]);
const REQUIRED_MCP_FILES = [
	"build/src/third_party/devtools-formatter-worker.js",
	"build/src/third_party/devtools-heap-snapshot-worker.js",
	"build/src/third_party/lighthouse-devtools-mcp-bundle.js",
	"build/src/third_party/bundled-packages.json"
];
/** The published MCP bundles contain optional UMD/BiDi imports; exact patches and assets own their artifact contract. */
function collectPatchedMcpArtifactErrors({ declaredVersion: e = "1.11.0", manifest: t, files: n, sha256: r }) {
	const i = typeof e === "string" ? MCP_FILE_HASHES.get(e) : void 0;
	if (typeof e !== "string" || !i) return [`package.json dependencies.${PATCHED_MCP_NAME} must be pinned to a supported patched version`];
	const a = [];
	if (!isRecord$1(t) || t.version !== e || t.type !== "module") a.push(`bundled ${PATCHED_MCP_NAME} must be ESM version ${e}`);
	if (!isRecord$1(t) || !isRecord$1(t.bin) || t.bin["chrome-devtools-mcp"] !== `./${"build/src/bin/chrome-devtools-mcp.js"}`) a.push(`bundled ${PATCHED_MCP_NAME} must expose CLI ${PATCHED_MCP_CLI}`);
	for (const e of [...REQUIRED_MCP_FILES, ...i.keys()]) {
		if (!n.has(e)) {
			a.push(`bundled ${PATCHED_MCP_NAME} is missing required runtime entry ${e}`);
			continue;
		}
		const t = i.get(e);
		if (t && r(e) !== t) a.push(`bundled ${PATCHED_MCP_NAME} has unpatched or changed runtime entry ${e}`);
	}
	if (![...n].some((e) => e.startsWith("build/src/third_party/issue-descriptions/") && e.endsWith(".md"))) a.push(`bundled ${PATCHED_MCP_NAME} is missing third-party issue descriptions`);
	return a;
}
//#endregion
//#region scripts/lib/javascript-statements.mjs
var AppendOnlyScopeNames = class extends Array {
	firstIndices = /* @__PURE__ */ new Map();
	push(...e) {
		const t = this.length;
		const n = super.push(...e);
		for (let n = 0; n < e.length; n += 1) {
			const r = e[n];
			if (!this.firstIndices.has(r)) this.firstIndices.set(r, t + n);
		}
		return n;
	}
	indexOf(e, t = 0) {
		return t === 0 ? this.firstIndices.get(e) ?? -1 : super.indexOf(e, t);
	}
};
const ArtifactParser = Parser.extend((e) => class extends e {
	enterScope(e) {
		super.enterScope(e);
		const t = this.currentScope();
		t.lexical = new AppendOnlyScopeNames();
		t.var = new AppendOnlyScopeNames();
		t.functions = new AppendOnlyScopeNames();
	}
});
/**
* Visit completed statements without retaining the full Program AST.
* @param {string} source
* @param {{ sourceType: "script" | "module", allowHashBang?: boolean, allowReturnOutsideFunction?: boolean }} options
* @param {(statements: import("acorn").Program["body"]) => void} visit
*/
function visitJavaScriptStatements(e, t, n) {
	/** @type {import("acorn").Program} */
	const r = {
		type: "Program",
		start: 0,
		end: 0,
		sourceType: t.sourceType,
		body: []
	};
	const visitCompletedStatements = () => {
		if (r.body.length > 0) n(r.body.splice(0));
	};
	ArtifactParser.parse(e, {
		ecmaVersion: "latest",
		...t,
		program: r,
		onToken: visitCompletedStatements
	});
	visitCompletedStatements();
}
//#endregion
//#region scripts/lib/package-dist-imports.mjs
const JS_FILE_RE = /\.(?:cjs|js|mjs)$/u;
const TS_FILE_RE = /\.(?:cts|ts|mts)$/u;
const require$1 = createRequire(import.meta.url);
/** Strip types for import analysis only; distribution bytes remain unchanged. */
function preparePackageDistJavaScript(e, t) {
	return TS_FILE_RE.test(e) ? require$1("esbuild").transformSync(t, {
		loader: "ts",
		target: "esnext",
		sourcefile: e,
		tsconfigRaw: { compilerOptions: { verbatimModuleSyntax: true } }
	}).code : t;
}
function normalizePackagePath(e) {
	return e.replace(/\\/gu, "/").replace(/^package\//u, "");
}
function stripSpecifierSuffix(e) {
	return e.replace(/[?#].*$/u, "");
}
function hasRuntimeFileExtension(e, t) {
	const n = path.posix.basename(stripSpecifierSuffix(e));
	return /\.(?:cjs|js|mjs|exe)$/u.test(n) || t && TS_FILE_RE.test(n);
}
function literal(e) {
	if (e?.type === "Literal" && typeof e.value === "string") return e.value;
	return e?.type === "TemplateLiteral" && e.expressions.length === 0 ? e.quasis[0].value.cooked : void 0;
}
function packageJsonsFor(e, t) {
	return e.packageJsons ?? new Map(t.filter((t) => e.readText && path.posix.basename(t) === "package.json").map((t) => [t, e.readText(t)]));
}
function sourceTypeFor(e, t) {
	if (/\.(?:cjs|cts)$/u.test(e)) return "script";
	if (/\.(?:mjs|mts)$/u.test(e)) return "module";
	let n = path.posix.dirname(e);
	while (true) {
		const e = t.get(path.posix.join(n, "package.json"));
		if (e !== void 0) {
			const t = JSON.parse(e).type;
			return t === "module" ? "module" : t === "commonjs" ? "script" : void 0;
		}
		if (n === "." || n === "/") return;
		n = path.posix.dirname(n);
	}
}
function resolvesCommonJs(e, t, n) {
	const r = [
		"",
		".js",
		".json",
		".node"
	];
	const loadFile = (e) => r.some((n) => t.has(e + n));
	const loadIndex = (e) => r.slice(1).some((n) => t.has(path.posix.join(e, "index" + n)));
	if (!e.endsWith("/") && loadFile(e)) return true;
	const i = n.get(path.posix.join(e, "package.json"));
	const a = i === void 0 ? void 0 : JSON.parse(i).main;
	if (typeof a === "string" && a) {
		const t = path.posix.join(e, a);
		if (loadFile(t) || loadIndex(t)) return true;
	}
	return loadIndex(e);
}
function appendImportEdges(e, t, n, r, i, a, o) {
	function visit(e) {
		if (a && (e.type === "Identifier" && (e.name === "require" || e.name === "createRequire") || e.type === "Literal" && (e.value === "require" || e.value === "createRequire"))) a();
		if (e.type === "Identifier" || e.type === "Literal" || e.type === "TemplateElement") return;
		let r;
		let s;
		if (e.type === "ImportDeclaration" || e.type === "ExportNamedDeclaration" || e.type === "ExportAllDeclaration" || e.type === "ImportExpression") {
			s = literal(e.source);
			if (e.source?.type === "Literal" && typeof e.source.value === "string") o?.(e.source.value);
		} else if (e.type === "CallExpression" && e.callee.type === "Identifier" && e.callee.name === "require") {
			r = "require";
			s = literal(e.arguments[0]);
		} else if (e.type === "NewExpression" && e.callee.type === "Identifier" && e.callee.name === "URL" && e.arguments.length >= 2) {
			const t = e.arguments[1];
			if (t.type === "MemberExpression" && !t.computed && t.property.type === "Identifier" && t.property.name === "url" && t.object.type === "MetaProperty" && t.object.meta.name === "import" && t.object.property.name === "meta") {
				r = "import-meta-url";
				s = literal(e.arguments[0]);
			}
		}
		if (s?.startsWith(".") && (r !== "import-meta-url" || hasRuntimeFileExtension(s, i))) {
			const e = path.posix.normalize(path.posix.join(path.posix.dirname(t), r === "require" ? s : stripSpecifierSuffix(s)));
			if (!(r === "import-meta-url" && t === "dist/managed-handoff-runtime.mjs" && e === "dist/node_modules/@openclaw/proc-safe/dist/identity.js") && (r !== "import-meta-url" || e.startsWith("dist/"))) n.push({
				importerPath: t,
				importedPath: e,
				...r === "require" ? { kind: r } : {}
			});
		}
		for (const t in e) {
			const n = e[t];
			if (!n || typeof n !== "object") continue;
			if (Array.isArray(n)) {
				for (const e of n) if (e && typeof e.type === "string") visit(e);
			} else if (typeof n.type === "string") visit(n);
		}
	}
	const scan = (t) => visitJavaScriptStatements(e, {
		sourceType: t,
		allowReturnOutsideFunction: true
	}, (e) => {
		for (const t of e) visit(t);
	});
	if (r) {
		scan(r);
		return;
	}
	const s = n.length;
	try {
		scan("script");
	} catch (e) {
		if (!(e instanceof SyntaxError)) throw e;
		n.length = s;
		scan("module");
	}
}
/** Collect missing-file errors for relative imports inside package files. */
function collectPackageDistImportErrors(e) {
	const t = [...new Set(e.files.map(normalizePackagePath))];
	const n = new Set(t);
	const r = [];
	const i = packageJsonsFor(e, t);
	const a = e.imports ?? collectPackageDistImports({
		files: t,
		readText: e.readText,
		packageJsons: i
	});
	for (const { importerPath: e, importedPath: t, kind: o } of a) if (!(o === "require" ? resolvesCommonJs(t, n, i) : n.has(t))) r.push(`${e} imports missing ${t}`);
	return r;
}
/** Collect relative dist import edges from package JavaScript files. */
function collectPackageDistImports(e) {
	const t = e.files.length === 1 ? [normalizePackagePath(e.files[0])] : [...new Set(e.files.map(normalizePackagePath))].toSorted((e, t) => e.localeCompare(t));
	const n = [];
	const r = packageJsonsFor(e, t);
	for (const i of t) {
		if (!JS_FILE_RE.test(i) && !(e.includeTypeScript && TS_FILE_RE.test(i)) || /(?:^|\/)node_modules\//u.test(i)) continue;
		appendImportEdges(preparePackageDistJavaScript(i, e.readText(i)), i, n, sourceTypeFor(i, r), e.includeTypeScript, e.onNodeLoaderReference, e.onStaticImport);
	}
	return n;
}
//#endregion
//#region scripts/lib/package-installed-dependencies.mts
function validateBundledPackageName(e) {
	if (!/^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/u.test(e)) throw new Error(`Invalid bundled dependency name: ${e}`);
}
async function installedPackagePath(e, t) {
	validateBundledPackageName(t);
	const n = createRequire(path.join(e, "package.json")).resolve.paths(t) ?? [];
	for (const e of n) {
		const n = path.join(e, t);
		try {
			await fs$1.access(path.join(n, "package.json"));
			return n;
		} catch (e) {
			if (!isRecord$1(e) || e.code !== "ENOENT") throw e;
		}
	}
}
async function installedPackageDependencies(e, t) {
	const n = isRecord$1(t.dependencies) ? t.dependencies : {};
	const r = isRecord$1(t.optionalDependencies) ? t.optionalDependencies : {};
	const i = isRecord$1(t.peerDependencies) ? t.peerDependencies : {};
	const a = isRecord$1(t.peerDependenciesMeta) ? t.peerDependenciesMeta : {};
	const o = [];
	for (const t of Object.keys({
		...i,
		...n,
		...r
	})) {
		const i = await installedPackagePath(e, t);
		const s = a[t];
		const c = Object.hasOwn(r, t) || !Object.hasOwn(n, t) && isRecord$1(s) && s.optional === true;
		if (!i) {
			if (c) continue;
			throw new Error(`Linked bundle requires dependency-closure staging: ${e} is missing ${t}`);
		}
		o.push({
			name: t,
			path: i,
			root: await fs$1.realpath(i)
		});
	}
	return o;
}
function hasInstalledPackageAncestor(e, t, n) {
	const r = createRequire(path.join(e, "package.json")).resolve.paths(t.name) ?? [];
	for (const e of r) {
		const r = n.get(path.join(e, t.name));
		if (r !== void 0) return r === t.root;
	}
	return false;
}
//#endregion
//#region scripts/package-source-dependencies.mjs
const PRIVATE_WORKSPACE_VERSION = "0.0.0-private";
function dependenciesRecord(e, t) {
	if (e === void 0) return {};
	if (typeof e !== "object" || e === null || Array.isArray(e)) throw new Error(`${t} dependencies must be an object when present`);
	return e;
}
function validateBundledPackageDependencyAlignment({ bundledDependencies: e, bundledPackageLabel: t, rootDependencies: n, rootPackageLabel: r = "root package.json" }) {
	const i = dependenciesRecord(e, t);
	const a = dependenciesRecord(n, r);
	const o = [];
	for (const [e, n] of Object.entries(i)) {
		if (typeof n !== "string") throw new Error(`${t} dependency ${e} must declare a string version`);
		if (n === PRIVATE_WORKSPACE_VERSION) continue;
		const i = a[e];
		if (i !== void 0 && typeof i !== "string") throw new Error(`${r} dependency ${e} must declare a string version`);
		if (i !== n && i !== `workspace:${n}`) throw new Error(`${r} must declare ${e}@${n} to bundle ${t} without duplicate dependencies`);
		o.push([e, n]);
	}
	return o;
}
//#endregion
//#region src/infra/package-plugin-composition.ts
/** Shared dependency ownership for release packages and private node distributions. */
function composePackagePlugins(e, t) {
	const n = structuredClone(e);
	const r = /* @__PURE__ */ new Set();
	for (const { id: e, packageJson: i } of t) {
		for (const e of listBundleDependencies(i)) r.add(e);
		for (const t of ["dependencies", "optionalDependencies"]) {
			const r = i[t] ?? {};
			for (const [t, n] of Object.entries(r)) if (valid(n) !== n) throw new Error(`Selected plugin ${e} requires an exact dependency pin: ${t}@${n}`);
			for (const t of [n.dependencies, n.optionalDependencies]) validateBundledPackageDependencyAlignment({
				bundledDependencies: r,
				bundledPackageLabel: `selected plugin ${e}`,
				rootDependencies: {
					...r,
					...t
				}
			});
			n[t] = {
				...n[t],
				...r
			};
		}
	}
	for (const e of listBundleDependencies(n)) r.add(e);
	if (r.size > 0) {
		n.bundleDependencies = [...r].toSorted();
		delete n.bundledDependencies;
	}
	for (const e of Object.keys(n.dependencies ?? {})) delete n.optionalDependencies?.[e];
	for (const { id: e, packageJson: r } of t) for (const [t, i] of Object.entries(r.peerDependencies ?? {})) {
		const a = t === n.name ? n.version : n.dependencies?.[t] ?? n.optionalDependencies?.[t];
		if (!a && !r.peerDependenciesMeta?.[t]?.optional || a && !satisfies(a, i)) throw new Error(`Selected plugin ${e} requires peer ${t}@${i} in the distribution`);
	}
	const i = new Set(t.map(({ id: e }) => `!dist/extensions/${e}/**`));
	if (n.files) n.files = n.files.filter((e) => !i.has(e));
	return n;
}
//#endregion
//#region src/gateway/worker-environments/node-bootstrap-prebuilt.ts
/** Deployment-owned input; never write or remove this file in the running installation. */
const NODE_BOOTSTRAP_PREBUILT_ARCHIVE = "node-runtime.tgz";
async function copyNodeBootstrapPrebuiltArchive(e, t) {
	if (process.platform === "win32") return;
	const n = path.join(t, NODE_BOOTSTRAP_PREBUILT_ARCHIVE);
	const r = await root(e, {
		symlinks: "reject",
		hardlinks: "allow"
	});
	const i = await root(t);
	try {
		await i.copyIn(NODE_BOOTSTRAP_PREBUILT_ARCHIVE, {
			root: r,
			relativePath: NODE_BOOTSTRAP_PREBUILT_ARCHIVE
		}, {
			maxBytes: MAX_WORKER_BUNDLE_ARCHIVE_BYTES,
			overwrite: false,
			durable: false,
			mode: 384
		});
		return await readWorkerBundleArchiveManifest(n, DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS);
	} catch {
		await fs$1.rm(n, { force: true });
		return;
	}
}
//#endregion
//#region scripts/lib/root-package-bundled-plugin-excludes.mjs
/** Collect bundled plugin directories excluded from the root package artifact. */
function collectRootPackageExcludedExtensionDirs(e = {}) {
	const t = /* @__PURE__ */ new Set();
	let n = e.files;
	if (!n) {
		const r = path.join(e.cwd ?? process.cwd(), "package.json");
		if (!fs.existsSync(r)) return t;
		n = JSON.parse(fs.readFileSync(r, "utf8")).files ?? [];
	}
	for (const e of n) {
		if (typeof e !== "string") continue;
		const n = /^!dist\/extensions\/([^/]+)\/\*\*$/u.exec(e);
		if (n?.[1] && n[1] !== "node_modules") t.add(n[1]);
	}
	return t;
}
//#endregion
//#region src/infra/package-root-imports.ts
const require = createRequire(import.meta.url);
const namespaces = /* @__PURE__ */ new Map([
	["node:module", "module"],
	["module", "module"],
	["node:process", "process"],
	["process", "process"],
	["node:path", "path"],
	["path", "path"],
	["node:fs", "fs"],
	["fs", "fs"],
	["node:fs/promises", "fs-promises"],
	["fs/promises", "fs-promises"]
]);
const members = /* @__PURE__ */ new Map([
	["module", /* @__PURE__ */ new Map([["createRequire", "factory"]])],
	["process", /* @__PURE__ */ new Map([
		["getBuiltinModule", "builtin"],
		["cwd", "cwd"],
		["chdir", "chdir"]
	])],
	["path", /* @__PURE__ */ new Map([["join", "join"], ["resolve", "resolve"]])],
	["fs", /* @__PURE__ */ new Map([["realpathSync", "realpath"], ["promises", "fs-promises"]])],
	["fs-promises", /* @__PURE__ */ new Map([["realpath", "realpath-async"]])]
]);
const ambient = /* @__PURE__ */ new Map([
	["require", "root"],
	["__filename", "location"],
	["process", "process"]
]);
const loaders = /* @__PURE__ */ new Set([
	"root",
	"caller",
	"unlocated"
]);
const snapshotsKinds = /* @__PURE__ */ new Set([
	"caller-path",
	"caller-string",
	"caller",
	"root"
]);
const callerValues = /* @__PURE__ */ new Set([
	"input",
	"caller-path",
	"caller-string"
]);
const pathValues = /* @__PURE__ */ new Set([
	...callerValues,
	"literal",
	"relative"
]);
const readableValues = /* @__PURE__ */ new Set([
	...pathValues,
	"module",
	"process",
	"path",
	"fs",
	"fs-promises",
	"scalar"
]);
const pureCalls = /* @__PURE__ */ new Set([
	"factory",
	"builtin",
	"join",
	"resolve",
	"realpath",
	"realpath-async",
	"cwd"
]);
function union(...e) {
	const t = [...new Set(e.flat())];
	return t.length ? t : ["unknown"];
}
/** Read dependency ownership without resolving or executing the inspected package. */
function collectPackageRootImports(e, t) {
	const { parse: n } = require("@babel/parser");
	const { default: r } = require("@babel/traverse");
	const i = n(e, {
		sourceType: "unambiguous",
		allowUndeclaredExports: true,
		allowReturnOutsideFunction: true,
		createImportExpressions: true
	});
	const a = [];
	const recordImport = (e, n, r = "runtime") => {
		a.push(e);
		if (t) {
			if (n.start == null) throw new Error("Parsed package import is missing its source position");
			t(e, n.start, r);
		}
	};
	const o = /* @__PURE__ */ new Map();
	const s = [];
	const c = [i.program];
	const l = /* @__PURE__ */ new Map();
	const u = [];
	const d = [];
	const f = /* @__PURE__ */ new Map();
	let p = false;
	function symbolAt(e) {
		return o.get(e)?.scope.getBinding(e.name);
	}
	function literal(e) {
		return e?.type === "StringLiteral" ? e.value : void 0;
	}
	function property(e) {
		return e.type === "Identifier" ? e.name : literal(e);
	}
	function memberName(e) {
		return e.computed ? literal(e.property) : property(e.property);
	}
	function register(e, t, n) {
		for (const r of Object.values(e.getBindingIdentifiers())) {
			const i = e.scope.getBinding(r.name);
			if (i) {
				const a = l.get(i) ?? [];
				a.push({
					node: e.node,
					name: r,
					constant: t,
					inputScope: n
				});
				l.set(i, a);
			}
		}
	}
	function recordWrite(e, t) {
		switch (e.type) {
			case "Identifier":
				u.push([e, t]);
				break;
			case "AssignmentPattern":
				recordWrite(e.left);
				break;
			case "ObjectPattern":
				for (const t of e.properties) recordWrite(t.type === "ObjectProperty" ? t.value : t.argument);
				break;
			case "ArrayPattern":
				for (const t of e.elements) if (t) recordWrite(t);
				break;
			case "RestElement": recordWrite(e.argument);
		}
	}
	r(i, {
		enter(e) {
			o.set(e.node, e);
		},
		ImportDeclaration(e) {
			recordImport(e.node.source.value, e.node, "static");
			for (const t of e.get("specifiers")) register(t, true);
		},
		ExportNamedDeclaration(e) {
			if (e.node.source) recordImport(e.node.source.value, e.node, "static");
		},
		ExportAllDeclaration(e) {
			recordImport(e.node.source.value, e.node, "static");
		},
		ImportExpression(e) {
			const t = literal(e.node.source);
			if (t !== void 0) recordImport(t, e.node);
		},
		"CallExpression|OptionalCallExpression"(e) {
			if (e.isCallExpression() || e.isOptionalCallExpression()) s.push(e.node);
		},
		Function(e) {
			c.push(e.node);
			for (const t of e.get("params")) register(t, false, e.node);
		},
		VariableDeclarator(e) {
			register(e, e.parentPath.isVariableDeclaration({ kind: "const" }));
		},
		AssignmentExpression(e) {
			recordWrite(e.node.left, e.node.right);
		},
		"ForOfStatement|ForInStatement"(e) {
			if (e.isForOfStatement() || e.isForInStatement()) {
				if (e.node.left.type !== "VariableDeclaration") recordWrite(e.node.left);
			}
		},
		"MemberExpression|OptionalMemberExpression"(e) {
			if (e.isMemberExpression() || e.isOptionalMemberExpression()) {
				if (memberName(e.node) === "chdir") d.push(e.node);
			}
		}
	});
	const m = /* @__PURE__ */ new Map();
	for (const [e, t] of u) {
		const n = symbolAt(e);
		if (n) m.set(n, [...m.get(n) ?? [], t]);
	}
	function memberOrigins(e, t) {
		return union(e.map((e) => e === "input" ? "input" : t === void 0 ? "unknown" : members.get(e)?.get(t) ?? "unknown"));
	}
	function origins(e, t = /* @__PURE__ */ new Set(), n, r = false) {
		if (e.type === "AwaitExpression") return origins(e.argument, t, n, true);
		if (e.type === "StringLiteral" || e.type === "TemplateLiteral" && e.expressions.length === 0) {
			const t = e.type === "StringLiteral" ? e.value : e.quasis[0]?.value.cooked ?? "";
			return [isAbsolute(t) || win32.isAbsolute(t) || URL.canParse(t) ? "literal" : "relative"];
		}
		if ([
			"NumericLiteral",
			"BooleanLiteral",
			"NullLiteral"
		].includes(e.type)) return ["literal"];
		if (e.type === "ConditionalExpression") return union(origins(e.consequent, new Set(t), n), origins(e.alternate, new Set(t), n));
		if (e.type === "SequenceExpression") {
			const r = e.expressions.at(-1);
			return r ? origins(r, t, n) : ["unknown"];
		}
		if (e.type === "BinaryExpression" || e.type === "LogicalExpression" || e.type === "AssignmentExpression") {
			if (e.operator === "=") return origins(e.right, t, n);
			const r = union(origins(e.left, new Set(t), n), origins(e.right, new Set(t), n));
			if ([
				"||",
				"&&",
				"??",
				"||=",
				"&&=",
				"??="
			].includes(e.operator)) return r;
			if (e.operator === "+" && r.some((e) => callerValues.has(e)) && r.every((e) => pathValues.has(e))) return ["caller-string"];
			return ["scalar"];
		}
		if (e.type === "Identifier") {
			const r = symbolAt(e);
			if (!r) return [ambient.get(e.name) ?? "unknown"];
			const i = f.get(r);
			if (i) return i;
			if (t.has(r)) return ["unknown"];
			t.add(r);
			const a = l.get(r) ?? [];
			const o = n && a.some((e) => e.inputScope === n);
			return union(...a.map((e) => declarationOrigins(e, new Set(t), n)), ...(o ? [] : m.get(r) ?? []).map((e) => e ? origins(e, new Set(t), n) : ["unknown"]));
		}
		if (e.type === "MemberExpression" || e.type === "OptionalMemberExpression") {
			const r = memberName(e);
			if (r === "url" && e.object.type === "MetaProperty" && e.object.meta.name === "import" && e.object.property.name === "meta") return ["location"];
			return memberOrigins(origins(e.object, t, n), r);
		}
		if (e.type === "ImportExpression") return [namespaces.get(literal(e.source) ?? "") ?? "unknown"];
		if (e.type === "CallExpression" || e.type === "OptionalCallExpression") {
			const i = literal(e.arguments[0]);
			const a = i === void 0 ? void 0 : namespaces.get(i);
			const o = origins(e.callee, new Set(t), n);
			const s = o.some((e) => [
				"factory",
				"resolve",
				"realpath",
				"realpath-async",
				"join"
			].includes(e)) ? e.arguments.map((e) => origins(e, new Set(t), n)) : [];
			return union(...o.map((t) => {
				if (t === "factory") return (s[0] ?? ["unknown"]).map((e) => e === "location" ? "root" : callerValues.has(e) ? "caller" : "unlocated");
				if (loaders.has(t) || t === "builtin") return [a ?? "unknown"];
				if (t === "cwd") return [n && !p ? "caller-path" : "scalar"];
				if (t === "realpath-async" && !r) return ["unknown"];
				if (t === "resolve" || (t === "realpath" || t === "realpath-async") && e.arguments.length === 1) {
					const e = t === "resolve" ? s.flat() : s[0] ?? ["unknown"];
					return [!p && e.every((e) => [
						"input",
						"caller-path",
						"caller-string",
						"relative"
					].includes(e)) && (n || e.includes("caller-path")) && (n || !e.includes("caller-string")) ? "caller-path" : "scalar"];
				}
				if (t === "join") {
					const e = s.flat();
					if (e.every((e) => pathValues.has(e)) && e.some((e) => callerValues.has(e))) return [s[0]?.every((e) => e === "caller-path") ? "caller-path" : "caller-string"];
					return ["scalar"];
				}
				return ["unknown"];
			}));
		}
		return ["unknown"];
	}
	function declarationOrigins(e, t, n) {
		const { node: r, name: i } = e;
		if (r.type === "ImportSpecifier" || r.type === "ImportNamespaceSpecifier" || r.type === "ImportDefaultSpecifier") {
			const e = o.get(r)?.parent;
			const t = e?.type === "ImportDeclaration" ? namespaces.get(e.source.value) : void 0;
			return t ? r.type === "ImportSpecifier" ? memberOrigins([t], property(r.imported)) : [t] : ["unknown"];
		}
		if (r.type !== "VariableDeclarator" && !e.inputScope) return ["unknown"];
		const a = r.type === "VariableDeclarator" ? r.id : r;
		const s = r.type === "VariableDeclarator" ? r.init : r.type === "AssignmentPattern" ? r.right : void 0;
		const c = e.inputScope ? union([n === e.inputScope ? "input" : "unknown"], s ? a.type === "AssignmentPattern" && a.left.type !== "Identifier" ? ["unknown"] : origins(s, new Set(t), n) : []) : s ? origins(s, new Set(t), n) : ["unknown"];
		if (a === i || a.type === "AssignmentPattern" && a.left === i) return union(c, !e.inputScope && !e.constant ? ["unknown"] : []);
		const l = [];
		let u = i;
		let d = o.get(u)?.parent;
		let f;
		while (d && u !== a) {
			if (d.type === "AssignmentPattern") l.push(d.left === i ? origins(d.right, new Set(t), n) : ["unknown"]);
			if (d.type === "ObjectProperty" && o.get(d)?.parent === a && (d.value === i || d.value.type === "AssignmentPattern" && d.value.left === i)) f = d.computed ? literal(d.key) : property(d.key);
			u = d;
			d = o.get(u)?.parent;
		}
		return union(e.inputScope ? c : f === void 0 ? ["unknown"] : memberOrigins(c, f), ...l, !e.inputScope && !e.constant ? ["unknown"] : []);
	}
	function pure(e, t) {
		if (e.type === "Identifier") return Boolean(symbolAt(e)) || ambient.has(e.name) || e.name === "undefined";
		if ([
			"StringLiteral",
			"NumericLiteral",
			"BooleanLiteral",
			"NullLiteral"
		].includes(e.type) || e.type === "TemplateLiteral" && e.expressions.length === 0) return true;
		if (e.type === "LogicalExpression") return pure(e.left, t) && pure(e.right, t);
		if (e.type === "ConditionalExpression") return pure(e.test, t) && pure(e.consequent, t) && pure(e.alternate, t);
		if (e.type === "AwaitExpression") {
			const n = e.argument;
			if (n.type === "ImportExpression") return namespaces.has(literal(n.source) ?? "") && pure(n, t);
			if (n.type !== "CallExpression" && n.type !== "OptionalCallExpression") return false;
			return origins(n.callee, /* @__PURE__ */ new Set(), t).every((e) => e === "realpath-async") && pure(n, t);
		}
		if (e.type === "MemberExpression" || e.type === "OptionalMemberExpression") {
			if (origins(e, /* @__PURE__ */ new Set(), t).includes("location")) return true;
			return origins(e.object, /* @__PURE__ */ new Set(), t).every((e) => readableValues.has(e)) && pure(e.object, t) && (!e.computed || literal(e.property) !== void 0);
		}
		if (e.type === "ImportExpression") return !e.options && namespaces.has(literal(e.source) ?? "");
		if (e.type !== "CallExpression" && e.type !== "OptionalCallExpression") return false;
		const n = namespaces.has(literal(e.arguments[0]) ?? "") && e.arguments.length === 1;
		return origins(e.callee, /* @__PURE__ */ new Set(), t).every((t) => pureCalls.has(t) && (t === "join" || t === "resolve" || e.arguments.length === (t === "cwd" ? 0 : 1)) || loaders.has(t) && n) && pure(e.callee, t) && e.arguments.every((e) => pure(e, t));
	}
	p = d.some((e) => origins(e).includes("chdir")) || [...l.values()].some((e) => e.some((e) => declarationOrigins(e, /* @__PURE__ */ new Set()).includes("chdir")));
	for (const e of c.toSorted((e, t) => (e.start ?? 0) - (t.start ?? 0))) {
		const t = e.type === "Program" ? e : e.body;
		if (t.type !== "Program" && t.type !== "BlockStatement") continue;
		if (e.type !== "Program" && e.params.some((e) => e.type !== "Identifier")) continue;
		prefix: for (const n of t.body) {
			const t = n.type === "ExportNamedDeclaration" || n.type === "ExportDefaultDeclaration" ? n.declaration : n;
			if (!t || t.type === "ImportDeclaration" || t.type === "ExportAllDeclaration" || t.type === "FunctionDeclaration" || t.type === "EmptyStatement" || t.type === "ExpressionStatement" && t.expression.type === "StringLiteral") continue;
			if (t.type !== "VariableDeclaration" || t.kind !== "const") break;
			for (const n of t.declarations) {
				if (n.id.type !== "Identifier" || !n.init || !pure(n.init, e)) break prefix;
				const t = origins(n.init, /* @__PURE__ */ new Set(), e);
				if (!t.every((e) => snapshotsKinds.has(e) || [
					"literal",
					"relative",
					...namespaces.values(),
					...pureCalls
				].includes(e))) break prefix;
				const r = symbolAt(n.id);
				if (r && t.every((e) => snapshotsKinds.has(e))) f.set(r, t);
			}
		}
	}
	for (const e of s) {
		const t = literal(e.arguments[0]);
		if (e.arguments.length !== 1 || t === void 0) continue;
		const n = origins(e.callee);
		if (n.includes("root") || e.callee.type === "Identifier" && e.callee.name === "require" && !n.every((e) => e === "caller")) recordImport(t, e);
	}
	return a;
}
//#endregion
//#region src/infra/runtime-dependency-ownership.ts
const RUNTIME_DEPENDENCY_OWNERSHIP_RELATIVE_PATH = "dist/runtime-dependency-ownership.json";
function parseRuntimeDependencyOwnership(e) {
	if (!isRecord(e) || !isRecord(e.chunks)) return null;
	for (const t of Object.values(e.chunks)) if (!isRecord(t) || typeof t.sha256 !== "string" || !/^[a-f0-9]{64}$/u.test(t.sha256) || !Array.isArray(t.extensions) || !t.extensions.every((e) => typeof e === "string" && /^[a-z0-9][a-z0-9-]*$/u.test(e)) || new Set(t.extensions).size !== t.extensions.length) return null;
	return e;
}
function readRuntimeDependencyOwnership(e, t = fs) {
	const n = join(e, RUNTIME_DEPENDENCY_OWNERSHIP_RELATIVE_PATH);
	if (!t.existsSync(n)) return null;
	const r = t.lstatSync(n);
	if (!r.isFile() || r.size > 1048576) throw new Error("ownership artifact must be a regular file no larger than 1048576 bytes");
	const i = parseRuntimeDependencyOwnership(JSON.parse(t.readFileSync(n, "utf8")));
	if (!i) throw new Error("ownership artifact does not match the supported schema");
	return i;
}
//#endregion
//#region src/shared/non-packaged-plugin-dirs.ts
/** Bundled plugins available to source builds but excluded from node and npm distributions. */
const NON_PACKAGED_BUNDLED_PLUGIN_DIRS = /* @__PURE__ */ new Set(["qa-channel", "qa-lab"]);
//#endregion
//#region src/gateway/worker-environments/node-bootstrap-runtime-chunks.ts
async function resolveNodeBootstrapRuntimeChunks(e, t, n, r) {
	const i = readRuntimeDependencyOwnership(e);
	const a = r ?? /* @__PURE__ */ new Set([...NON_PACKAGED_BUNDLED_PLUGIN_DIRS, ...collectRootPackageExcludedExtensionDirs({ files: n })]);
	const o = new Map(t.flatMap((e) => {
		if (!e.startsWith("dist/") || !/\.[cm]?js$/u.test(e) || e.startsWith("dist/extensions/")) return [];
		const t = i?.chunks[e.slice(5)];
		return t?.extensions.every((e) => a.has(e)) ? [[e, t]] : [];
	}));
	const s = /* @__PURE__ */ new Map();
	if (o.size === 0) return {
		files: t,
		sourceFacts: s
	};
	const c = await root(e, {
		hardlinks: "allow",
		symlinks: "reject"
	});
	const l = new Set(t);
	const u = new Set(n);
	const read = async (e) => {
		const { buffer: t } = await c.read(e, {
			hardlinks: "allow",
			symlinks: "reject",
			maxBytes: DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS.maxExpandedBytes
		});
		const n = o.get(e);
		if (n && createHash("sha256").update(t).digest("hex") !== n.sha256) throw new Error(`Runtime dependency ownership does not match ${e}; rebuild the Gateway`);
		return t;
	};
	const d = new Set(t.filter((e) => !o.has(e)));
	for (const t of d) {
		const n = u.has(t) && /\.[cm]?ts$/u.test(t);
		if (!/\.[cm]?js$/u.test(t) && !n) continue;
		const r = (await read(t)).toString("utf8");
		let i = /(?:^|\/)node_modules\//u.test(t);
		const a = [];
		const c = collectPackageDistImports({
			files: [t],
			includeTypeScript: n,
			readText: () => r,
			onNodeLoaderReference: () => {
				i = true;
			},
			onStaticImport: (e) => {
				a.push(e);
			}
		});
		s.set(t, { imports: c });
		const f = new Set(c.map(({ importedPath: e }) => e));
		const p = createRequire(path.join(e, t)).resolve;
		const m = i ? collectPackageRootImports(preparePackageDistJavaScript(t, r)) : a;
		for (const n of m) {
			if (!n.startsWith(".")) continue;
			const r = n.replace(/[?#].*$/u, "");
			const i = path.posix.normalize(path.posix.join(path.posix.dirname(t), r));
			if (l.has(i) && f.has(i)) continue;
			try {
				f.add(path.relative(e, p(r)).split(path.sep).join("/"));
			} catch {}
		}
		for (const e of f) if (o.has(e)) d.add(e);
	}
	for (const e of o.keys()) if (!d.has(e)) await read(e);
	return {
		files: t.filter((e) => d.has(e)),
		sourceFacts: s
	};
}
//#endregion
//#region src/gateway/worker-environments/node-bootstrap-artifact-build.ts
const IGNORED_PLUGIN_DIRECTORIES = /* @__PURE__ */ new Set([
	"node_modules",
	"src",
	"test",
	"tests"
]);
const PLUGIN_DIST_SHARED_CHUNK_PREFIX = "dist/.setup";
const METADATA_KEYS = [
	"name",
	"version",
	"dependencies",
	"optionalDependencies",
	"peerDependencies",
	"peerDependenciesMeta"
];
function bootstrapPath(e) {
	if (!e || e.includes("\\") || e.includes("\0") || e.startsWith("/") || e.split("/").some((e) => !e || e === "." || e === "..")) throw new Error(`Unsafe node distribution path: ${e}`);
	return e;
}
async function readPackageManifest(e) {
	const t = JSON.parse(await fs$1.readFile(path.join(e, "package.json"), "utf8"));
	if (!t.name || valid(t.version) !== t.version) throw new Error("Node distribution requires a named package with an exact version");
	return t;
}
function requireRunningBuild(e, t, n) {
	const r = JSON.parse(t);
	if (!e.runningBuildId || r.buildId !== e.runningBuildId || r.version !== n) throw new Error("Cloud bootstrap requires the running Gateway build; run pnpm build and restart the Gateway before provisioning");
	return e.runningBuildId;
}
async function observeBootstrapModes(e) {
	const t = [];
	for (const n of [420, 493]) {
		const r = path.join(e, `.mode-${n.toString(8)}`);
		const i = await fs$1.open(r, "wx", n);
		try {
			t.push((await i.stat()).mode & 511);
		} finally {
			await i.close();
			await fs$1.rm(r);
		}
	}
	return t;
}
async function collectBootstrapFiles(e, t = false) {
	const included = ({ name: e, relativePath: n }) => t && n.split(path.sep).join("/") === PLUGIN_DIST_SHARED_CHUNK_PREFIX || !e.startsWith(".") && !(t ? IGNORED_PLUGIN_DIRECTORIES.has(e) : n === "node_modules");
	const { entries: n, failedDirs: r, truncated: i } = await walkDirectory(e, {
		maxEntries: DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS.maxEntries,
		symlinks: "include",
		include: included,
		descend: (e) => {
			if (e.depth >= 64) throw new Error(`Node bootstrap ${t ? "plugin" : "dependency"} exceeds its directory depth limit`);
			return included(e);
		}
	});
	if (r.length > 0) throw r[0].error;
	if (i) throw new Error("Node bootstrap distribution exceeds its artifact limits");
	return n.flatMap((e) => {
		if (e.kind === "directory" || (t ? !/\.(?:[cm]?js|json|wasm)$/u.test(e.name) : e.relativePath === "package.json")) return [];
		if (e.kind !== "file") throw new Error(`Unsafe bundled node distribution path: ${e.relativePath}`);
		return [e.relativePath.split(path.sep).join("/")];
	});
}
async function resolvePlugins(e, t) {
	const n = /* @__PURE__ */ new Set();
	return await Promise.all(e.plugins.map(async ({ id: e, root: r }) => {
		if (!/^[a-z0-9][a-z0-9_-]*$/u.test(e) || n.has(e)) throw new Error(`Invalid or duplicate node bootstrap plugin: ${e}`);
		n.add(e);
		const i = await fs$1.realpath(r);
		const a = path.join(t, "extensions", e);
		const o = path.join(t, "dist", "extensions", e);
		const s = i === a ? o : i;
		const c = await readPackageManifest(s);
		if (i === a) {
			const t = await readPackageManifest(a);
			if (METADATA_KEYS.some((e) => !isDeepStrictEqual(c[e], t[e]))) throw new Error(`Built plugin ${e} does not match source metadata; rebuild and restart the Gateway`);
		}
		if (JSON.parse(await fs$1.readFile(path.join(s, "openclaw.plugin.json"), "utf8")).id !== e) throw new Error(`Node bootstrap plugin identity does not match ${e}`);
		const l = c.openclaw?.runtimeExtensions ?? c.openclaw?.extensions;
		if (!l?.length) throw new Error(`Node bootstrap plugin ${e} has no runtime entry`);
		for (const e of l) {
			const t = bootstrapPath(e.replace(/^\.\//u, "").replace(/\.ts$/u, ".js"));
			await fs$1.access(path.join(s, t));
		}
		return {
			id: e,
			root: s,
			installationRoot: i,
			packageJson: c,
			bundled: s === o
		};
	}));
}
async function prepareNodeBootstrapArtifact(e, t, n = true) {
	const r = await fs$1.realpath(e.packageRoot);
	const i = await readPackageManifest(r);
	if (i.name !== "openclaw") throw new Error("Node bootstrap requires the running OpenClaw package root");
	const a = path.join(r, "dist", "build-info.json");
	const o = requireRunningBuild(e, await fs$1.readFile(a, "utf8").catch((e) => {
		throw new Error("Cloud bootstrap requires a built Gateway; run pnpm build and restart the Gateway before provisioning", { cause: e });
	}), i.version);
	const s = await resolvePlugins(e, r);
	const c = composePackagePlugins(i, s);
	const l = await observeBootstrapModes(t);
	const u = {
		label: c.name,
		prefix: "",
		files: [],
		imports: [],
		packageJsons: /* @__PURE__ */ new Map()
	};
	const d = [];
	const f = /* @__PURE__ */ new Map();
	const planEntry = (e, t) => {
		bootstrapPath(e);
		f.set(e, t);
		if (f.size > DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS.maxEntries) throw new Error("Node bootstrap distribution exceeds its artifact limits");
	};
	let p = 0;
	let m = 0;
	const reserveFile = (e) => {
		p += e;
		m += 1;
		if (m > DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS.maxEntries || p > DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS.maxExpandedBytes) throw new Error("Node bootstrap distribution exceeds its artifact limits");
	};
	const addGeneratedFile = (e, t, n = u) => {
		reserveFile(Buffer.byteLength(t));
		planEntry(e, {
			contents: Buffer.from(t),
			scope: n
		});
	};
	const addFiles = (e, t, n = "", r = u) => {
		for (const i of new Set(t)) planEntry(`${n}${i}`, {
			source: {
				root: e,
				relative: i
			},
			scope: r
		});
	};
	const readEntry = async (e, t) => {
		if ("contents" in e) {
			await t([e.contents], e.contents.byteLength, l[0]);
			return;
		}
		const { root: n, relative: r } = e.source;
		const i = path.join(n, r);
		if (await fs$1.realpath(i) !== i) throw new Error(`Node distribution cannot contain symbolic links: ${r}`);
		const a = await fs$1.open(i, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
		try {
			const e = await a.stat();
			if (!e.isFile()) throw new Error(`Invalid node distribution file: ${r}`);
			reserveFile(e.size);
			async function* chunks() {
				let t = e.size;
				while (t >= 0) {
					const e = Buffer.allocUnsafe(Math.min(t + 1, 65536));
					const { bytesRead: n } = await a.read(e, 0, e.length, null);
					if (!n) return;
					t -= n;
					yield e.subarray(0, n);
				}
			}
			await t(chunks(), e.size, l[(e.mode & 73) !== 0 ? 1 : 0]);
			const n = await fs$1.lstat(i);
			if (n.isSymbolicLink() || n.dev !== e.dev || n.ino !== e.ino || await fs$1.realpath(i) !== i) throw new Error(`Node distribution changed while packaging: ${r}`);
		} finally {
			await a.close();
		}
	};
	const h = s.filter((e) => !e.bundled).map(({ id: e }) => `dist/extensions/${e}/`);
	const g = (await collectPackageDistInventory(r, { packageManifest: c })).filter((e) => !e.startsWith("dist/worker/") && !e.startsWith("dist/worker-artifacts/") && !e.startsWith("dist/control-ui/") && !h.some((t) => e.startsWith(t)));
	const _ = (i.files ?? []).filter((e) => (e.startsWith("scripts/") || /\.[cm]?[jt]s$/u.test(e)) && !e.startsWith("!") && !e.includes("*") && !e.endsWith("/"));
	const { files: v, sourceFacts: y } = await resolveNodeBootstrapRuntimeChunks(r, [..._, ...g].filter((e) => e !== LEGACY_PACKAGE_INSTALL_GUARD_RELATIVE_PATH), c.files ?? []);
	if (!v.includes("dist/entry.js") && !v.includes("dist/entry.mjs")) throw new Error("Cloud bootstrap is missing its built CLI entry; run pnpm build and restart the Gateway");
	addFiles(r, v);
	c.scripts = Object.fromEntries(Object.entries(c.scripts ?? {}).filter(([e]) => [
		"preinstall",
		"install",
		"postinstall"
	].includes(e)));
	delete c.devDependencies;
	for (const e of s) {
		if (e.bundled) continue;
		const t = await collectBootstrapFiles(e.root, true);
		addFiles(e.root, t, `dist/extensions/${e.id}/`);
	}
	const addBundledPackage = async (e, t, n, r = false) => {
		const i = r ? await collectPackageDistInventory(e) : await collectBootstrapFiles(e);
		if (i.length === 0) throw new Error(`Bundled node dependency ${t.name} needs its compiled distribution; rebuild the Gateway`);
		const a = {
			label: t.name,
			prefix: n,
			files: [],
			imports: [],
			packageJsons: /* @__PURE__ */ new Map(),
			...t.name === "chrome-devtools-mcp" ? { patchedMcp: {
				manifest: t,
				hashes: /* @__PURE__ */ new Map()
			} } : {}
		};
		d.push(a);
		addFiles(e, i, n, a);
		delete t.devDependencies;
		delete t.scripts;
		addGeneratedFile(`${n}package.json`, `${JSON.stringify(t, null, 2)}\n`, a);
	};
	const addRegistryClosure = async (e, n, r, i) => {
		if (r.split("/").length > 64) throw new Error("Node bootstrap dependency exceeds its directory depth limit");
		await addBundledPackage(e, n, r);
		const a = path.resolve(t, "package", r);
		const o = new Map(i).set(a, e);
		for (const t of await installedPackageDependencies(e, n)) {
			if (hasInstalledPackageAncestor(a, t, o)) continue;
			await addRegistryClosure(t.root, await readPackageManifest(t.root), `${r}node_modules/${t.name}/`, o);
		}
	};
	const b = /* @__PURE__ */ new Set([...listBundleDependencies(i), ...Object.entries(i.dependencies ?? {}).filter(([, e]) => e.startsWith("workspace:")).map(([e]) => e)]);
	const x = /* @__PURE__ */ new Set([...b, ...listBundleDependencies(c)]);
	for (const e of [...x].toSorted()) {
		bootstrapPath(e);
		const t = (b.has(e) ? void 0 : s.find(({ packageJson: t }) => listBundleDependencies(t).includes(e)) ?? s.find(({ packageJson: t }) => Object.hasOwn(t.dependencies ?? {}, e) || Object.hasOwn(t.optionalDependencies ?? {}, e)))?.installationRoot ?? r;
		const n = await installedPackagePath(t, e);
		if (!n) throw new Error(`Bundled node dependency ${e} is missing from ${t}; install its dependencies and rebuild the Gateway`);
		const a = await fs$1.realpath(n);
		const o = await readPackageManifest(a);
		if (o.name !== e) throw new Error(`Bundled node distribution dependency identity does not match ${e}`);
		const l = i.dependencies?.[e]?.startsWith("workspace:") || !a.endsWith(`${path.sep}node_modules${path.sep}${e.split("/").join(path.sep)}`);
		if (l) {
			const t = validateBundledPackageDependencyAlignment({
				bundledDependencies: o.dependencies,
				bundledPackageLabel: `bundled ${e}`,
				rootDependencies: c.dependencies
			});
			for (const [e, n] of t) c.dependencies[e] = n;
			delete o.dependencies;
		}
		const u = `node_modules/${e}/`;
		if (l) await addBundledPackage(a, o, u, true);
		else await addRegistryClosure(a, o, u, /* @__PURE__ */ new Map());
		c.dependencies[e] = o.version;
	}
	c.bundleDependencies = [...x].toSorted();
	delete c.bundledDependencies;
	for (const [e, t] of Object.entries({
		...c.optionalDependencies,
		...c.dependencies
	})) if (valid(t) !== t) throw new Error(`Node distribution requires an exact dependency pin: ${e}@${t}`);
	addGeneratedFile("package.json", `${JSON.stringify(c, null, 2)}\n`);
	const S = [...f.keys()].filter((e) => e.startsWith("dist/")).toSorted();
	addGeneratedFile(PACKAGE_DIST_INVENTORY_RELATIVE_PATH, `${JSON.stringify(S)}\n`);
	addGeneratedFile(PACKAGE_LIFECYCLE_PENDING_RELATIVE_PATH, "pending\n");
	const C = [...f].toSorted(([e], [t]) => Number(path.posix.basename(t) === "package.json") - Number(path.posix.basename(e) === "package.json") || compareWorkerBundlePaths(e, t));
	u.files = C.map(([e]) => e);
	for (const [e, t] of C) if (t.scope !== u) t.scope.files.push(e.slice(t.scope.prefix.length));
	const w = path.join(t, NODE_BOOTSTRAP_PREBUILT_ARCHIVE);
	const T = n ? await copyNodeBootstrapPrebuiltArchive(r, t) : void 0;
	let E = Promise.resolve();
	const D = T ? void 0 : new Pack({
		gzip: true,
		noMtime: true,
		portable: true,
		strict: true,
		onWriteEntry(e) {
			E = finished(e, {
				readable: true,
				writable: false,
				cleanup: true
			});
			E.catch(() => void 0);
		}
	});
	const O = createHash("sha256");
	const k = D ? pipeline(D, async function* (e) {
		for await (const t of e) {
			O.update(t);
			yield t;
		}
	}, createWriteStream(w, { flags: "wx" })) : Promise.resolve();
	const A = new AbortController();
	k.catch((e) => A.abort(e));
	const j = [];
	try {
		for (const [e, t] of C) await readEntry(t, async (n, r, i) => {
			const a = e.slice(t.scope.prefix.length);
			const o = y.get(e);
			const s = path.posix.basename(e) === "package.json";
			const c = t.scope === u && _.includes(e);
			const l = s || !o && !t.scope.patchedMcp && (/\.[cm]?js$/u.test(a) || c && /\.[cm]?ts$/u.test(a)) ? new StringDecoder("utf8") : void 0;
			let d = "";
			const f = D ? new ReadEntry(new Header({
				path: `package/${e}`,
				size: r,
				mode: i,
				type: "File"
			})) : void 0;
			if (f && D) D.add(f);
			const p = createHash("sha256");
			let m = 0;
			for await (const t of n) {
				A.signal.throwIfAborted();
				m += t.byteLength;
				if (m > r) throw new Error(`Node distribution changed while packaging: ${e}`);
				p.update(t);
				if (l) d += l.write(t);
				if (f && !f.write(t)) await once(f, "drain", { signal: A.signal });
			}
			if (m !== r) throw new Error(`Node distribution changed while packaging: ${e}`);
			f?.end();
			d += l?.end() ?? "";
			if (s) {
				u.packageJsons.set(e, d);
				t.scope.packageJsons.set(a, d);
			}
			const h = {
				path: `package/${e}`,
				size: r,
				mode: process.platform === "win32" ? 448 : i,
				sha256: p.digest("hex")
			};
			if (t.scope.patchedMcp) t.scope.patchedMcp.hashes.set(a, h.sha256);
			else t.scope.imports.push(...o?.imports ?? collectPackageDistImports({
				files: [a],
				includeTypeScript: c,
				packageJsons: t.scope.packageJsons,
				readText: () => d
			}));
			j.push(h);
			if (D) await Promise.race([E, k]);
		});
		for (const e of [...d, u]) {
			const t = e.patchedMcp ? collectPatchedMcpArtifactErrors({
				manifest: e.patchedMcp.manifest,
				files: new Set(e.files),
				sha256: (t) => e.patchedMcp?.hashes.get(t)
			}) : collectPackageDistImportErrors(e);
			if (t.length > 0) throw new Error(`Node distribution ${e.label} ${e.patchedMcp ? "has an invalid patched dependency" : "has an incomplete built import closure"}; rebuild and restart the Gateway: ${t.slice(0, 5).join("; ")}`);
		}
		D?.end();
		await k;
	} catch (e) {
		D?.destroy(e instanceof Error ? e : new Error("Node bootstrap archive failed", { cause: e }));
		D?.zip?.destroy();
		await k.catch(() => void 0);
		throw e;
	}
	const M = (await fs$1.stat(w)).size;
	if (M > 536870912) throw new Error("Node bootstrap archive exceeds the transfer limit");
	j.sort((e, t) => compareWorkerBundlePaths(e.path, t.path));
	if (T) {
		if (hashWorkerBundleManifest(j) !== hashWorkerBundleManifest(T)) {
			await fs$1.rm(w);
			return await prepareNodeBootstrapArtifact(e, t, false);
		}
	}
	let N;
	if (D) N = O.digest("hex");
	else try {
		var P = _usingCtx();
		const e = P.a(await fs$1.open(w, "r"));
		N = (await sha256File(e)).digest;
	} catch (e) {
		P.e = e;
	} finally {
		await P.d();
	}
	return {
		tarballPath: w,
		tarballSha256: N,
		tarballBytes: M,
		openclawVersion: c.version,
		buildId: o,
		enabledPluginIds: s.map(({ id: e }) => e).toSorted()
	};
}
//#endregion
export { prepareNodeBootstrapArtifact };