import { c as normalizeOptionalString } from "./string-coerce-Bje8XVt9.js";
import { n as resolveOpenClawPackageRootSync } from "./openclaw-root-OulwLQAX.js";
import { t as createLazyImportLoader } from "./lazy-promise-AiZRy56y.js";
import { A as isPrereleaseResolutionAllowed, D as compareOpenClawReleaseVersions, M as parseRegistryNpmSpec, O as formatPrereleaseResolutionError, S as resolvePackageExtensionEntries, c as validatePackageExtensionEntriesForInstall, j as isPrereleaseSemverVersion, k as isExactSemverVersion } from "./discovery-w2P25hlM.js";
import { c as matchesExpectedPluginId, d as resolveDefaultPluginNpmDir, h as packageNameMatchesId, l as resolveDefaultPluginExtensionsDir, m as validatePluginId, p as safePluginInstallFileName, s as encodePluginInstallDirName } from "./channel-catalog-registry-D2drDK4i.js";
import { p as resolveUserPath } from "./utils-Ba75iQOz.js";
import { r as runCommandWithTimeout } from "./exec-BN4Fyfp2.js";
import { i as resolveNpmSpecMetadata } from "./install-source-utils-CEkXWmbY.js";
import { i as parseComparableSemver, t as compareComparableSemver } from "./semver-compare-Br1P04sn.js";
import { n as createSafeNpmInstallEnv, t as createSafeNpmInstallArgs } from "./safe-package-install-vpWfjqSj.js";
import { t as resolveNpmIntegrityDriftWithDefaultMessage } from "./npm-integrity-C2ThH8l3.js";
import path from "node:path";
import fs from "node:fs/promises";
//#region src/infra/npm-managed-root.ts
function isRecord(value) {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}
function readOptionalString(value) {
	return typeof value === "string" && value.trim() ? value.trim() : void 0;
}
function readDependencyRecord(value) {
	if (!isRecord(value)) return {};
	const dependencies = {};
	for (const [key, raw] of Object.entries(value)) if (typeof raw === "string") dependencies[key] = raw;
	return dependencies;
}
async function readManagedNpmRootManifest(filePath) {
	try {
		const parsed = JSON.parse(await fs.readFile(filePath, "utf8"));
		return isRecord(parsed) ? { ...parsed } : {};
	} catch (err) {
		if (err.code === "ENOENT") return {};
		throw err;
	}
}
function resolveManagedNpmRootDependencySpec(params) {
	return params.resolution.version ?? params.parsedSpec.selector ?? "latest";
}
async function upsertManagedNpmRootDependency(params) {
	await fs.mkdir(params.npmRoot, { recursive: true });
	const manifestPath = path.join(params.npmRoot, "package.json");
	const manifest = await readManagedNpmRootManifest(manifestPath);
	const dependencies = readDependencyRecord(manifest.dependencies);
	const next = {
		...manifest,
		private: true,
		dependencies: {
			...dependencies,
			[params.packageName]: params.dependencySpec
		}
	};
	await fs.writeFile(manifestPath, `${JSON.stringify(next, null, 2)}\n`, "utf8");
}
async function readManagedNpmRootInstalledDependency(params) {
	const lockPath = path.join(params.npmRoot, "package-lock.json");
	const parsed = JSON.parse(await fs.readFile(lockPath, "utf8"));
	if (!isRecord(parsed) || !isRecord(parsed.packages)) return null;
	const entry = parsed.packages[`node_modules/${params.packageName}`];
	if (!isRecord(entry)) return null;
	return {
		version: readOptionalString(entry.version),
		integrity: readOptionalString(entry.integrity),
		resolved: readOptionalString(entry.resolved)
	};
}
async function removeManagedNpmRootDependency(params) {
	const manifestPath = path.join(params.npmRoot, "package.json");
	const manifest = await readManagedNpmRootManifest(manifestPath);
	const dependencies = readDependencyRecord(manifest.dependencies);
	if (!(params.packageName in dependencies)) return;
	const { [params.packageName]: _removed, ...nextDependencies } = dependencies;
	const next = {
		...manifest,
		private: true,
		dependencies: nextDependencies
	};
	await fs.writeFile(manifestPath, `${JSON.stringify(next, null, 2)}\n`, "utf8");
}
//#endregion
//#region src/plugins/plugin-peer-link.ts
/**
* Symlink the host openclaw package for plugins that declare it as a peer.
* Plugin package managers still own third-party dependencies; this only wires
* the host SDK package into the plugin-local Node graph.
*/
async function linkOpenClawPeerDependencies(params) {
	const peers = Object.keys(params.peerDependencies).filter((name) => name === "openclaw");
	if (peers.length === 0) return;
	const hostRoot = resolveOpenClawPackageRootSync({
		argv1: process.argv[1],
		moduleUrl: import.meta.url,
		cwd: process.cwd()
	});
	if (!hostRoot) {
		params.logger.warn?.("Could not locate openclaw package root to symlink peerDependencies; plugin may fail to resolve openclaw at runtime.");
		return;
	}
	const nodeModulesDir = path.join(params.installedDir, "node_modules");
	await fs.mkdir(nodeModulesDir, { recursive: true });
	for (const peerName of peers) {
		const linkPath = path.join(nodeModulesDir, peerName);
		try {
			await fs.rm(linkPath, {
				recursive: true,
				force: true
			});
			await fs.symlink(hostRoot, linkPath, "junction");
			params.logger.info?.(`Linked peerDependency "${peerName}" -> ${hostRoot}`);
		} catch (err) {
			params.logger.warn?.(`Failed to symlink peerDependency "${peerName}": ${String(err)}`);
		}
	}
}
//#endregion
//#region src/plugins/install.ts
const pluginInstallRuntimeLoader = createLazyImportLoader(() => import("./install.runtime.js"));
async function loadPluginInstallRuntime() {
	return await pluginInstallRuntimeLoader.load();
}
const MISSING_EXTENSIONS_ERROR = "package.json missing openclaw.extensions; update the plugin package to include openclaw.extensions (for example [\"./dist/index.js\"]). See https://docs.openclaw.ai/help/troubleshooting#plugin-install-fails-with-missing-openclaw-extensions";
const PLUGIN_ARCHIVE_ROOT_MARKERS = [
	"package.json",
	"openclaw.plugin.json",
	".codex-plugin/plugin.json",
	".claude-plugin/plugin.json",
	".cursor-plugin/plugin.json"
];
const PLUGIN_INSTALL_ERROR_CODE = {
	INVALID_NPM_SPEC: "invalid_npm_spec",
	INVALID_MIN_HOST_VERSION: "invalid_min_host_version",
	UNKNOWN_HOST_VERSION: "unknown_host_version",
	INCOMPATIBLE_HOST_VERSION: "incompatible_host_version",
	MISSING_OPENCLAW_EXTENSIONS: "missing_openclaw_extensions",
	MISSING_PLUGIN_MANIFEST: "missing_plugin_manifest",
	EMPTY_OPENCLAW_EXTENSIONS: "empty_openclaw_extensions",
	INVALID_OPENCLAW_EXTENSIONS: "invalid_openclaw_extensions",
	NPM_PACKAGE_NOT_FOUND: "npm_package_not_found",
	PLUGIN_ID_MISMATCH: "plugin_id_mismatch",
	SECURITY_SCAN_BLOCKED: "security_scan_blocked",
	SECURITY_SCAN_FAILED: "security_scan_failed"
};
const defaultLogger = {};
function ensureOpenClawExtensions(params) {
	const resolved = resolvePackageExtensionEntries(params.manifest);
	if (resolved.status === "missing") return {
		ok: false,
		error: MISSING_EXTENSIONS_ERROR,
		code: PLUGIN_INSTALL_ERROR_CODE.MISSING_OPENCLAW_EXTENSIONS
	};
	if (resolved.status === "empty") return {
		ok: false,
		error: "package.json openclaw.extensions is empty",
		code: PLUGIN_INSTALL_ERROR_CODE.EMPTY_OPENCLAW_EXTENSIONS
	};
	return {
		ok: true,
		entries: resolved.entries
	};
}
function isNpmPackageNotFoundMessage(error) {
	const normalized = error.trim();
	if (normalized.startsWith("Package not found on npm:")) return true;
	return /E404|404 not found|not in this registry/i.test(normalized);
}
function compareNpmSemver(a, b) {
	const releaseCmp = compareOpenClawReleaseVersions(a, b);
	if (releaseCmp !== null) return releaseCmp;
	return compareComparableSemver(parseComparableSemver(a), parseComparableSemver(b)) ?? 0;
}
async function resolveTrustedOfficialPrereleaseResolution(params) {
	if (!params.spec.name.startsWith("@openclaw/")) return null;
	const versions = await runCommandWithTimeout([
		"npm",
		"view",
		params.spec.name,
		"versions",
		"--json"
	], {
		timeoutMs: Math.max(params.timeoutMs, 6e4),
		env: {
			COREPACK_ENABLE_DOWNLOAD_PROMPT: "0",
			NPM_CONFIG_IGNORE_SCRIPTS: "true"
		}
	});
	if (versions.code !== 0) return null;
	let parsed;
	try {
		parsed = JSON.parse(versions.stdout.trim());
	} catch {
		return null;
	}
	const semverVersions = (Array.isArray(parsed) ? parsed : [parsed]).filter((value) => typeof value === "string" && isExactSemverVersion(value));
	const stableVersion = semverVersions.filter((value) => !isPrereleaseSemverVersion(value)).toSorted(compareNpmSemver).at(-1);
	if (!stableVersion) {
		const prereleaseVersion = semverVersions.filter(isPrereleaseSemverVersion).toSorted(compareNpmSemver).at(-1);
		if (prereleaseVersion && semverVersions.every(isPrereleaseSemverVersion)) {
			if (prereleaseVersion !== params.resolvedPrereleaseVersion) {
				const prereleaseSpec = `${params.spec.name}@${prereleaseVersion}`;
				const metadataResult = await resolveNpmSpecMetadata({
					spec: prereleaseSpec,
					timeoutMs: params.timeoutMs
				});
				if (!metadataResult.ok) return null;
				params.logger.warn?.(`Resolved ${params.spec.raw} to prerelease version ${params.resolvedPrereleaseVersion}; using newest prerelease ${prereleaseSpec} because this trusted official OpenClaw package has no stable npm versions yet.`);
				return {
					kind: "prerelease-only",
					resolution: metadataResult.metadata
				};
			}
			params.logger.warn?.(`Resolved ${params.spec.raw} to prerelease version ${params.resolvedPrereleaseVersion}; allowing it because this trusted official OpenClaw package has no stable npm versions yet.`);
			return { kind: "allow-prerelease-only" };
		}
		return null;
	}
	const stableSpec = `${params.spec.name}@${stableVersion}`;
	const metadataResult = await resolveNpmSpecMetadata({
		spec: stableSpec,
		timeoutMs: params.timeoutMs
	});
	if (!metadataResult.ok) return null;
	params.logger.warn?.(`Resolved ${params.spec.raw} to prerelease version ${params.resolvedPrereleaseVersion}; falling back to stable ${stableSpec} for this trusted official OpenClaw install.`);
	return {
		kind: "stable",
		resolution: metadataResult.metadata
	};
}
function buildFileInstallResult(pluginId, targetFile) {
	return {
		ok: true,
		pluginId,
		targetDir: targetFile,
		manifestName: void 0,
		version: void 0,
		extensions: [path.basename(targetFile)]
	};
}
function buildDirectoryInstallResult(params) {
	return {
		ok: true,
		pluginId: params.pluginId,
		targetDir: params.targetDir,
		manifestName: params.manifestName,
		version: params.version,
		extensions: params.extensions
	};
}
function hasPackageRuntimeDependencies(manifest) {
	return Object.keys(manifest.dependencies ?? {}).length > 0 || Object.keys(manifest.optionalDependencies ?? {}).length > 0;
}
function buildBlockedInstallResult(params) {
	return {
		ok: false,
		error: params.blocked.reason,
		...params.blocked.code === "security_scan_failed" ? { code: PLUGIN_INSTALL_ERROR_CODE.SECURITY_SCAN_FAILED } : params.blocked.code === "security_scan_blocked" ? { code: PLUGIN_INSTALL_ERROR_CODE.SECURITY_SCAN_BLOCKED } : {}
	};
}
async function rollbackManagedNpmPluginInstall(params) {
	try {
		await runCommandWithTimeout([
			"npm",
			"uninstall",
			"--loglevel=error",
			"--ignore-scripts",
			"--no-audit",
			"--no-fund",
			"--prefix",
			".",
			params.packageName
		], {
			cwd: params.npmRoot,
			timeoutMs: Math.max(params.timeoutMs, 3e5),
			env: createSafeNpmInstallEnv(process.env, {
				packageLock: true,
				quiet: true
			})
		});
	} catch (error) {
		params.logger.warn?.(`Failed to run npm uninstall rollback for ${params.packageName}: ${String(error)}`);
	}
	try {
		await fs.rm(params.targetDir, {
			recursive: true,
			force: true
		});
	} catch (error) {
		params.logger.warn?.(`Failed to remove failed plugin install directory ${params.targetDir}: ${String(error)}`);
	}
	try {
		await removeManagedNpmRootDependency({
			npmRoot: params.npmRoot,
			packageName: params.packageName
		});
	} catch (error) {
		params.logger.warn?.(`Failed to remove managed npm dependency ${params.packageName}: ${String(error)}`);
	}
}
function resolveInstalledNpmResolutionMismatch(params) {
	if (!params.installed) return `npm install did not record package-lock metadata for ${params.packageName}`;
	if (params.expected.version && params.installed.version !== params.expected.version) return `npm install resolved ${params.packageName} to version ${params.installed.version ?? "unknown"}, expected ${params.expected.version}`;
	if (params.expected.integrity && params.installed.integrity !== params.expected.integrity) return `npm install resolved ${params.packageName} with integrity ${params.installed.integrity ?? "unknown"}, expected ${params.expected.integrity}`;
	return null;
}
function pickPackageInstallCommonParams(params) {
	return {
		dangerouslyForceUnsafeInstall: params.dangerouslyForceUnsafeInstall,
		trustedSourceLinkedOfficialInstall: params.trustedSourceLinkedOfficialInstall,
		extensionsDir: params.extensionsDir,
		npmDir: params.npmDir,
		timeoutMs: params.timeoutMs,
		logger: params.logger,
		mode: params.mode,
		dryRun: params.dryRun,
		expectedPluginId: params.expectedPluginId,
		requirePluginManifest: params.requirePluginManifest,
		installPolicyRequest: params.installPolicyRequest
	};
}
function pickFileInstallCommonParams(params) {
	return {
		dangerouslyForceUnsafeInstall: params.dangerouslyForceUnsafeInstall,
		extensionsDir: params.extensionsDir,
		logger: params.logger,
		mode: params.mode,
		dryRun: params.dryRun,
		installPolicyRequest: params.installPolicyRequest
	};
}
async function ensureInstallTargetAvailableForMode(params) {
	return await params.runtime.ensureInstallTargetAvailable({
		mode: params.mode,
		targetDir: params.targetPath,
		alreadyExistsError: `plugin already exists: ${params.targetPath} (delete it first)`
	});
}
async function resolvePreparedDirectoryInstallTarget(params) {
	const targetDirResult = await resolvePluginInstallTarget({
		runtime: params.runtime,
		pluginId: params.pluginId,
		extensionsDir: params.extensionsDir,
		nameEncoder: params.nameEncoder
	});
	if (!targetDirResult.ok) return targetDirResult;
	return {
		ok: true,
		target: {
			targetPath: targetDirResult.targetDir,
			effectiveMode: await resolveEffectiveInstallMode({
				runtime: params.runtime,
				requestedMode: params.requestedMode,
				targetPath: targetDirResult.targetDir
			})
		}
	};
}
async function runInstallSourceScan(params) {
	try {
		const scanResult = await params.scan();
		if (scanResult?.blocked) return buildBlockedInstallResult({ blocked: scanResult.blocked });
		return null;
	} catch (err) {
		return {
			ok: false,
			error: `${params.subject} installation blocked: code safety scan failed (${String(err)}). Run "openclaw security audit --deep" for details.`,
			code: PLUGIN_INSTALL_ERROR_CODE.SECURITY_SCAN_FAILED
		};
	}
}
async function installPluginDirectoryIntoExtensions(params) {
	const runtime = await loadPluginInstallRuntime();
	let targetDir = params.targetDir;
	if (!targetDir) {
		const targetDirResult = await resolvePluginInstallTarget({
			runtime,
			pluginId: params.pluginId,
			extensionsDir: params.extensionsDir,
			nameEncoder: params.nameEncoder
		});
		if (!targetDirResult.ok) return {
			ok: false,
			error: targetDirResult.error
		};
		targetDir = targetDirResult.targetDir;
	}
	const availability = await ensureInstallTargetAvailableForMode({
		runtime,
		targetPath: targetDir,
		mode: params.mode
	});
	if (!availability.ok) return availability;
	if (params.dryRun) return buildDirectoryInstallResult({
		pluginId: params.pluginId,
		targetDir,
		manifestName: params.manifestName,
		version: params.version,
		extensions: params.extensions
	});
	const installRes = await runtime.installPackageDir({
		sourceDir: params.sourceDir,
		targetDir,
		mode: params.mode,
		timeoutMs: params.timeoutMs,
		logger: params.logger,
		copyErrorPrefix: params.copyErrorPrefix,
		hasDeps: params.hasDeps,
		depsLogMessage: params.depsLogMessage,
		afterCopy: params.afterCopy,
		afterInstall: async (installedDir) => {
			const postInstallResult = await params.afterInstall?.(installedDir);
			if (!postInstallResult) return { ok: true };
			return {
				ok: false,
				error: postInstallResult.error,
				...postInstallResult.code ? { code: postInstallResult.code } : {}
			};
		}
	});
	if (!installRes.ok) return {
		ok: false,
		error: installRes.error,
		...installRes.code ? { code: installRes.code } : {}
	};
	return buildDirectoryInstallResult({
		pluginId: params.pluginId,
		targetDir,
		manifestName: params.manifestName,
		version: params.version,
		extensions: params.extensions
	});
}
async function resolvePluginInstallTarget(params) {
	const extensionsDir = params.extensionsDir ? resolveUserPath(params.extensionsDir) : resolveDefaultPluginExtensionsDir();
	return await params.runtime.resolveCanonicalInstallTarget({
		baseDir: extensionsDir,
		id: params.pluginId,
		invalidNameMessage: "invalid plugin name: path traversal detected",
		boundaryLabel: "extensions directory",
		nameEncoder: params.nameEncoder
	});
}
async function resolveEffectiveInstallMode(params) {
	if (params.requestedMode !== "update") return "install";
	return await params.runtime.fileExists(params.targetPath) ? "update" : "install";
}
async function installBundleFromSourceDir(params) {
	const runtime = await loadPluginInstallRuntime();
	const bundleFormat = runtime.detectBundleManifestFormat(params.sourceDir);
	if (!bundleFormat) return null;
	const { logger, timeoutMs, mode, dryRun } = runtime.resolveTimedInstallModeOptions(params, defaultLogger);
	const manifestRes = runtime.loadBundleManifest({
		rootDir: params.sourceDir,
		bundleFormat,
		rejectHardlinks: true
	});
	if (!manifestRes.ok) return {
		ok: false,
		error: manifestRes.error
	};
	const pluginId = manifestRes.manifest.id;
	const pluginIdError = validatePluginId(pluginId);
	if (pluginIdError) return {
		ok: false,
		error: pluginIdError
	};
	if (params.expectedPluginId && params.expectedPluginId !== pluginId) return {
		ok: false,
		error: `plugin id mismatch: expected ${params.expectedPluginId}, got ${pluginId}`,
		code: PLUGIN_INSTALL_ERROR_CODE.PLUGIN_ID_MISMATCH
	};
	const targetResult = await resolvePreparedDirectoryInstallTarget({
		runtime,
		pluginId,
		extensionsDir: params.extensionsDir,
		requestedMode: mode
	});
	if (!targetResult.ok) return {
		ok: false,
		error: targetResult.error
	};
	const scanResult = await runInstallSourceScan({
		subject: `Bundle "${pluginId}"`,
		scan: async () => await runtime.scanBundleInstallSource({
			dangerouslyForceUnsafeInstall: params.dangerouslyForceUnsafeInstall,
			sourceDir: params.sourceDir,
			pluginId,
			logger,
			requestKind: params.installPolicyRequest?.kind,
			requestedSpecifier: params.installPolicyRequest?.requestedSpecifier,
			mode: targetResult.target.effectiveMode,
			version: manifestRes.manifest.version
		})
	});
	if (scanResult) return scanResult;
	return await installPluginDirectoryIntoExtensions({
		sourceDir: params.sourceDir,
		pluginId,
		manifestName: manifestRes.manifest.name,
		version: manifestRes.manifest.version,
		extensions: [],
		targetDir: targetResult.target.targetPath,
		extensionsDir: params.extensionsDir,
		logger,
		timeoutMs,
		mode: targetResult.target.effectiveMode,
		dryRun,
		copyErrorPrefix: "failed to copy plugin bundle",
		hasDeps: false,
		depsLogMessage: ""
	});
}
async function installPluginFromSourceDir(params) {
	if (await detectNativePackageInstallSource(params.sourceDir)) return await installPluginFromPackageDir({
		packageDir: params.sourceDir,
		...pickPackageInstallCommonParams(params)
	});
	const bundleResult = await installBundleFromSourceDir({
		sourceDir: params.sourceDir,
		...pickPackageInstallCommonParams(params)
	});
	if (bundleResult) return bundleResult;
	return await installPluginFromPackageDir({
		packageDir: params.sourceDir,
		...pickPackageInstallCommonParams(params)
	});
}
async function detectNativePackageInstallSource(packageDir) {
	const runtime = await loadPluginInstallRuntime();
	const manifestPath = path.join(packageDir, "package.json");
	if (!await runtime.fileExists(manifestPath)) return false;
	try {
		return ensureOpenClawExtensions({ manifest: await runtime.readJsonFile(manifestPath) }).ok;
	} catch {
		return false;
	}
}
async function validatePackagePluginInstallSource(params) {
	const manifestPath = path.join(params.packageDir, "package.json");
	if (!await params.runtime.fileExists(manifestPath)) return {
		ok: false,
		error: "extracted package missing package.json"
	};
	let manifest;
	try {
		manifest = await params.runtime.readJsonFile(manifestPath);
	} catch (err) {
		return {
			ok: false,
			error: `invalid package.json: ${String(err)}`
		};
	}
	const extensionsResult = ensureOpenClawExtensions({ manifest });
	if (!extensionsResult.ok) return {
		ok: false,
		error: extensionsResult.error,
		code: extensionsResult.code
	};
	const extensions = extensionsResult.entries;
	const pkgName = normalizeOptionalString(manifest.name) ?? "";
	const npmPluginId = pkgName || "plugin";
	const ocManifestResult = params.runtime.loadPluginManifest(params.packageDir);
	if (!ocManifestResult.ok && params.requirePluginManifest) return {
		ok: false,
		error: `package missing valid openclaw.plugin.json: ${ocManifestResult.error}`,
		code: PLUGIN_INSTALL_ERROR_CODE.MISSING_PLUGIN_MANIFEST
	};
	const manifestPluginId = ocManifestResult.ok && ocManifestResult.manifest.id ? ocManifestResult.manifest.id.trim() : void 0;
	const pluginId = manifestPluginId ?? npmPluginId;
	const pluginIdError = validatePluginId(pluginId);
	if (pluginIdError) return {
		ok: false,
		error: pluginIdError
	};
	if (!matchesExpectedPluginId({
		expectedPluginId: params.expectedPluginId,
		pluginId,
		manifestPluginId,
		npmPluginId
	})) return {
		ok: false,
		error: `plugin id mismatch: expected ${params.expectedPluginId}, got ${pluginId}`,
		code: PLUGIN_INSTALL_ERROR_CODE.PLUGIN_ID_MISMATCH
	};
	if (manifestPluginId && !packageNameMatchesId(npmPluginId, manifestPluginId)) params.logger.info?.(`Plugin manifest id "${manifestPluginId}" differs from npm package name "${npmPluginId}"; using manifest id as the config key.`);
	const packageMetadata = params.runtime.getPackageManifestMetadata(manifest);
	const minHostVersionCheck = params.runtime.checkMinHostVersion({
		currentVersion: params.runtime.resolveCompatibilityHostVersion(),
		minHostVersion: packageMetadata?.install?.minHostVersion
	});
	if (!minHostVersionCheck.ok) {
		if (minHostVersionCheck.kind === "invalid") return {
			ok: false,
			error: `invalid package.json openclaw.install.minHostVersion: ${minHostVersionCheck.error}`,
			code: PLUGIN_INSTALL_ERROR_CODE.INVALID_MIN_HOST_VERSION
		};
		if (minHostVersionCheck.kind === "unknown_host_version") return {
			ok: false,
			error: `plugin "${pluginId}" requires OpenClaw >=${minHostVersionCheck.requirement.minimumLabel}, but this host version could not be determined. Re-run from a released build or set OPENCLAW_VERSION and retry.`,
			code: PLUGIN_INSTALL_ERROR_CODE.UNKNOWN_HOST_VERSION
		};
		return {
			ok: false,
			error: `plugin "${pluginId}" requires OpenClaw >=${minHostVersionCheck.requirement.minimumLabel}, but this host is ${minHostVersionCheck.currentVersion}. Upgrade OpenClaw and retry.`,
			code: PLUGIN_INSTALL_ERROR_CODE.INCOMPATIBLE_HOST_VERSION
		};
	}
	const extensionValidation = await validatePackageExtensionEntriesForInstall({
		packageDir: params.packageDir,
		extensions,
		manifest
	});
	if (!extensionValidation.ok) return {
		ok: false,
		error: extensionValidation.error,
		code: PLUGIN_INSTALL_ERROR_CODE.INVALID_OPENCLAW_EXTENSIONS
	};
	const scanMode = params.resolveEffectiveMode ? await params.resolveEffectiveMode(pluginId) : params.mode;
	const scanResult = await runInstallSourceScan({
		subject: `Plugin "${pluginId}"`,
		scan: async () => await params.runtime.scanPackageInstallSource({
			dangerouslyForceUnsafeInstall: params.dangerouslyForceUnsafeInstall,
			trustedSourceLinkedOfficialInstall: params.trustedSourceLinkedOfficialInstall,
			packageDir: params.packageDir,
			pluginId,
			logger: params.logger,
			extensions,
			requestKind: params.installPolicyRequest?.kind,
			requestedSpecifier: params.installPolicyRequest?.requestedSpecifier,
			mode: scanMode,
			packageName: pkgName || void 0,
			manifestId: manifestPluginId,
			version: typeof manifest.version === "string" ? manifest.version : void 0
		})
	});
	if (scanResult) return scanResult;
	return {
		ok: true,
		plugin: {
			manifest,
			pluginId,
			manifestName: pkgName || void 0,
			version: typeof manifest.version === "string" ? manifest.version : void 0,
			extensions,
			hasRuntimeDependencies: hasPackageRuntimeDependencies(manifest),
			peerDependencies: manifest.peerDependencies ?? {}
		}
	};
}
async function scanAndLinkInstalledPackage(params) {
	const scanResult = await runInstallSourceScan({
		subject: `Plugin "${params.pluginId}"`,
		scan: async () => await params.runtime.scanInstalledPackageDependencyTree({
			allowManagedNpmRootPackagePeerSymlinks: params.dependencyScanRootDir !== void 0 && path.resolve(params.dependencyScanRootDir) !== path.resolve(params.installedDir),
			logger: params.logger,
			packageDir: params.dependencyScanRootDir ?? params.installedDir,
			pluginId: params.pluginId
		})
	});
	if (scanResult) return scanResult;
	await linkOpenClawPeerDependencies({
		installedDir: params.installedDir,
		peerDependencies: params.peerDependencies,
		logger: params.logger
	});
	return null;
}
async function installPluginFromInstalledPackageDir(params) {
	const runtime = await loadPluginInstallRuntime();
	const { logger } = runtime.resolveTimedInstallModeOptions(params, defaultLogger);
	const validated = await validatePackagePluginInstallSource({
		runtime,
		packageDir: params.packageDir,
		expectedPluginId: params.expectedPluginId,
		requirePluginManifest: params.requirePluginManifest,
		dangerouslyForceUnsafeInstall: params.dangerouslyForceUnsafeInstall,
		trustedSourceLinkedOfficialInstall: params.trustedSourceLinkedOfficialInstall,
		installPolicyRequest: params.installPolicyRequest,
		logger,
		mode: params.mode ?? "install"
	});
	if (!validated.ok) return validated;
	const postInstallError = await scanAndLinkInstalledPackage({
		runtime,
		installedDir: params.packageDir,
		dependencyScanRootDir: params.dependencyScanRootDir,
		pluginId: validated.plugin.pluginId,
		peerDependencies: validated.plugin.peerDependencies,
		logger
	});
	if (postInstallError) return postInstallError;
	return buildDirectoryInstallResult({
		pluginId: validated.plugin.pluginId,
		targetDir: params.packageDir,
		manifestName: validated.plugin.manifestName,
		version: validated.plugin.version,
		extensions: validated.plugin.extensions
	});
}
async function installPluginFromPackageDir(params) {
	const runtime = await loadPluginInstallRuntime();
	const { logger, timeoutMs, mode, dryRun } = runtime.resolveTimedInstallModeOptions(params, defaultLogger);
	let preparedTarget;
	const resolvePreparedTargetForPluginId = async (pluginId) => {
		if (!preparedTarget) {
			const targetResult = await resolvePreparedDirectoryInstallTarget({
				runtime,
				pluginId,
				extensionsDir: params.extensionsDir,
				requestedMode: mode,
				nameEncoder: encodePluginInstallDirName
			});
			if (!targetResult.ok) throw new Error(targetResult.error);
			preparedTarget = targetResult.target;
		}
		return preparedTarget;
	};
	const validated = await validatePackagePluginInstallSource({
		runtime,
		packageDir: params.packageDir,
		expectedPluginId: params.expectedPluginId,
		requirePluginManifest: params.requirePluginManifest,
		dangerouslyForceUnsafeInstall: params.dangerouslyForceUnsafeInstall,
		trustedSourceLinkedOfficialInstall: params.trustedSourceLinkedOfficialInstall,
		installPolicyRequest: params.installPolicyRequest,
		logger,
		mode,
		resolveEffectiveMode: async (pluginId) => (await resolvePreparedTargetForPluginId(pluginId)).effectiveMode
	});
	if (!validated.ok) return validated;
	const { plugin } = validated;
	preparedTarget = await resolvePreparedTargetForPluginId(plugin.pluginId);
	const hasBundleManifest = Boolean(runtime.detectBundleManifestFormat(params.packageDir));
	return await installPluginDirectoryIntoExtensions({
		sourceDir: params.packageDir,
		pluginId: plugin.pluginId,
		manifestName: plugin.manifestName,
		version: plugin.version,
		extensions: plugin.extensions,
		targetDir: preparedTarget.targetPath,
		extensionsDir: params.extensionsDir,
		logger,
		timeoutMs,
		mode: preparedTarget.effectiveMode,
		dryRun,
		copyErrorPrefix: "failed to copy plugin",
		hasDeps: plugin.hasRuntimeDependencies && !hasBundleManifest && params.installPolicyRequest?.kind === "plugin-archive",
		depsLogMessage: "Installing plugin dependencies…",
		nameEncoder: encodePluginInstallDirName,
		afterInstall: async (installedDir) => {
			return await scanAndLinkInstalledPackage({
				runtime,
				installedDir,
				pluginId: plugin.pluginId,
				peerDependencies: plugin.peerDependencies,
				logger
			});
		}
	});
}
async function installPluginFromArchive(params) {
	const runtime = await loadPluginInstallRuntime();
	const logger = params.logger ?? defaultLogger;
	const timeoutMs = params.timeoutMs ?? 12e4;
	const mode = params.mode ?? "install";
	const installPolicyRequest = params.installPolicyRequest ?? {
		kind: "plugin-archive",
		requestedSpecifier: params.archivePath
	};
	const archivePathResult = await runtime.resolveArchiveSourcePath(params.archivePath);
	if (!archivePathResult.ok) return archivePathResult;
	const archivePath = archivePathResult.path;
	return await runtime.withExtractedArchiveRoot({
		archivePath,
		tempDirPrefix: "openclaw-plugin-",
		timeoutMs,
		logger,
		rootMarkers: PLUGIN_ARCHIVE_ROOT_MARKERS,
		onExtracted: async (sourceDir) => await installPluginFromSourceDir({
			sourceDir,
			...pickPackageInstallCommonParams({
				dangerouslyForceUnsafeInstall: params.dangerouslyForceUnsafeInstall,
				extensionsDir: params.extensionsDir,
				timeoutMs,
				logger,
				mode,
				dryRun: params.dryRun,
				expectedPluginId: params.expectedPluginId,
				trustedSourceLinkedOfficialInstall: params.trustedSourceLinkedOfficialInstall,
				requirePluginManifest: true,
				installPolicyRequest
			})
		})
	});
}
async function installPluginFromDir(params) {
	const runtime = await loadPluginInstallRuntime();
	const dirPath = resolveUserPath(params.dirPath);
	const installPolicyRequest = params.installPolicyRequest ?? {
		kind: "plugin-dir",
		requestedSpecifier: params.dirPath
	};
	if (!await runtime.fileExists(dirPath)) return {
		ok: false,
		error: `directory not found: ${dirPath}`
	};
	if (!(await fs.stat(dirPath)).isDirectory()) return {
		ok: false,
		error: `not a directory: ${dirPath}`
	};
	return await installPluginFromSourceDir({
		sourceDir: dirPath,
		...pickPackageInstallCommonParams({
			...params,
			installPolicyRequest
		})
	});
}
async function installPluginFromFile(params) {
	const runtime = await loadPluginInstallRuntime();
	const { logger, mode, dryRun } = runtime.resolveInstallModeOptions(params, defaultLogger);
	const filePath = resolveUserPath(params.filePath);
	const installPolicyRequest = params.installPolicyRequest ?? {
		kind: "plugin-file",
		requestedSpecifier: params.filePath
	};
	if (!await runtime.fileExists(filePath)) return {
		ok: false,
		error: `file not found: ${filePath}`
	};
	const extensionsDir = params.extensionsDir ? resolveUserPath(params.extensionsDir) : resolveDefaultPluginExtensionsDir();
	await fs.mkdir(extensionsDir, { recursive: true });
	const pluginId = path.basename(filePath, path.extname(filePath)) || "plugin";
	const pluginIdError = validatePluginId(pluginId);
	if (pluginIdError) return {
		ok: false,
		error: pluginIdError
	};
	const targetFile = path.join(extensionsDir, `${safePluginInstallFileName(pluginId)}${path.extname(filePath)}`);
	const preparedTarget = {
		targetPath: targetFile,
		effectiveMode: await resolveEffectiveInstallMode({
			runtime,
			requestedMode: mode,
			targetPath: targetFile
		})
	};
	const availability = await ensureInstallTargetAvailableForMode({
		runtime,
		targetPath: preparedTarget.targetPath,
		mode: preparedTarget.effectiveMode
	});
	if (!availability.ok) return availability;
	if (dryRun) return buildFileInstallResult(pluginId, preparedTarget.targetPath);
	const scanResult = await runInstallSourceScan({
		subject: `Plugin file "${pluginId}"`,
		scan: async () => await runtime.scanFileInstallSource({
			dangerouslyForceUnsafeInstall: params.dangerouslyForceUnsafeInstall,
			filePath,
			logger,
			mode: preparedTarget.effectiveMode,
			pluginId,
			requestedSpecifier: installPolicyRequest.requestedSpecifier
		})
	});
	if (scanResult) return scanResult;
	logger.info?.(`Installing to ${preparedTarget.targetPath}…`);
	try {
		await (await runtime.root(extensionsDir)).copyIn(path.basename(preparedTarget.targetPath), filePath);
	} catch (err) {
		return {
			ok: false,
			error: String(err)
		};
	}
	return buildFileInstallResult(pluginId, preparedTarget.targetPath);
}
async function installPluginFromNpmSpec(params) {
	const runtime = await loadPluginInstallRuntime();
	const { logger, timeoutMs, mode, dryRun } = runtime.resolveTimedInstallModeOptions(params, defaultLogger);
	const expectedPluginId = params.expectedPluginId;
	const spec = params.spec.trim();
	const specError = runtime.validateRegistryNpmSpec(spec);
	if (specError) return {
		ok: false,
		error: specError,
		code: PLUGIN_INSTALL_ERROR_CODE.INVALID_NPM_SPEC
	};
	const parsedSpec = parseRegistryNpmSpec(spec);
	if (!parsedSpec) return {
		ok: false,
		error: "unsupported npm spec",
		code: PLUGIN_INSTALL_ERROR_CODE.INVALID_NPM_SPEC
	};
	const metadataResult = await resolveNpmSpecMetadata({
		spec,
		timeoutMs
	});
	if (!metadataResult.ok) return {
		ok: false,
		error: metadataResult.error,
		...isNpmPackageNotFoundMessage(metadataResult.error) ? { code: PLUGIN_INSTALL_ERROR_CODE.NPM_PACKAGE_NOT_FOUND } : {}
	};
	const npmResolution = {
		...metadataResult.metadata,
		resolvedAt: (/* @__PURE__ */ new Date()).toISOString()
	};
	if (npmResolution.version && !isPrereleaseResolutionAllowed({
		spec: parsedSpec,
		resolvedVersion: npmResolution.version
	})) {
		const trustedResolution = params.trustedSourceLinkedOfficialInstall ? await resolveTrustedOfficialPrereleaseResolution({
			spec: parsedSpec,
			resolvedPrereleaseVersion: npmResolution.version,
			timeoutMs,
			logger
		}) : null;
		if (trustedResolution?.kind === "stable" || trustedResolution?.kind === "prerelease-only") Object.assign(npmResolution, trustedResolution.resolution, { resolvedAt: npmResolution.resolvedAt });
		else if (trustedResolution?.kind === "allow-prerelease-only") {} else return {
			ok: false,
			error: formatPrereleaseResolutionError({
				spec: parsedSpec,
				resolvedVersion: npmResolution.version
			})
		};
	}
	const driftResult = await resolveNpmIntegrityDriftWithDefaultMessage({
		spec,
		expectedIntegrity: params.expectedIntegrity,
		resolution: npmResolution,
		onIntegrityDrift: params.onIntegrityDrift,
		warn: (message) => logger.warn?.(message)
	});
	if (driftResult.error) return {
		ok: false,
		error: driftResult.error
	};
	const npmRoot = params.npmDir ? resolveUserPath(params.npmDir) : resolveDefaultPluginNpmDir();
	const installRoot = path.join(npmRoot, "node_modules", parsedSpec.name);
	const effectiveMode = await resolveEffectiveInstallMode({
		runtime,
		requestedMode: mode,
		targetPath: installRoot
	});
	const availability = await ensureInstallTargetAvailableForMode({
		runtime,
		targetPath: installRoot,
		mode: effectiveMode
	});
	if (!availability.ok) return availability;
	if (dryRun) return {
		ok: true,
		pluginId: expectedPluginId ?? parsedSpec.name,
		targetDir: installRoot,
		extensions: [],
		npmResolution,
		...driftResult.integrityDrift ? { integrityDrift: driftResult.integrityDrift } : {}
	};
	logger.info?.(`Installing ${spec} into ${npmRoot}…`);
	await upsertManagedNpmRootDependency({
		npmRoot,
		packageName: parsedSpec.name,
		dependencySpec: resolveManagedNpmRootDependencySpec({
			parsedSpec,
			resolution: npmResolution
		})
	});
	const install = await runCommandWithTimeout([
		"npm",
		...createSafeNpmInstallArgs({
			omitDev: true,
			loglevel: "error",
			noAudit: true,
			noFund: true
		}),
		"--prefix",
		"."
	], {
		cwd: npmRoot,
		timeoutMs: Math.max(timeoutMs, 3e5),
		env: createSafeNpmInstallEnv(process.env, {
			packageLock: true,
			quiet: true
		})
	});
	if (install.code !== 0) {
		await removeManagedNpmRootDependency({
			npmRoot,
			packageName: parsedSpec.name
		});
		return {
			ok: false,
			error: `npm install failed: ${install.stderr.trim() || install.stdout.trim()}`
		};
	}
	let installedDependency;
	try {
		installedDependency = await readManagedNpmRootInstalledDependency({
			npmRoot,
			packageName: parsedSpec.name
		});
	} catch (error) {
		await rollbackManagedNpmPluginInstall({
			npmRoot,
			packageName: parsedSpec.name,
			targetDir: installRoot,
			timeoutMs,
			logger
		});
		return {
			ok: false,
			error: `Failed to verify npm install metadata for ${parsedSpec.name}: ${String(error)}`
		};
	}
	const resolutionMismatch = resolveInstalledNpmResolutionMismatch({
		packageName: parsedSpec.name,
		expected: npmResolution,
		installed: installedDependency
	});
	if (resolutionMismatch) {
		await rollbackManagedNpmPluginInstall({
			npmRoot,
			packageName: parsedSpec.name,
			targetDir: installRoot,
			timeoutMs,
			logger
		});
		return {
			ok: false,
			error: resolutionMismatch
		};
	}
	const result = await installPluginFromInstalledPackageDir({
		dangerouslyForceUnsafeInstall: params.dangerouslyForceUnsafeInstall,
		packageDir: installRoot,
		dependencyScanRootDir: npmRoot,
		logger,
		expectedPluginId,
		trustedSourceLinkedOfficialInstall: params.trustedSourceLinkedOfficialInstall,
		mode: effectiveMode,
		installPolicyRequest: {
			kind: "plugin-npm",
			requestedSpecifier: spec
		}
	});
	if (!result.ok) {
		await rollbackManagedNpmPluginInstall({
			npmRoot,
			packageName: parsedSpec.name,
			targetDir: installRoot,
			timeoutMs,
			logger
		});
		return result;
	}
	return {
		...result,
		npmResolution,
		...driftResult.integrityDrift ? { integrityDrift: driftResult.integrityDrift } : {}
	};
}
async function installPluginFromPath(params) {
	const runtime = await loadPluginInstallRuntime();
	const pathResult = await runtime.resolveExistingInstallPath(params.path);
	if (!pathResult.ok) return pathResult;
	const { resolvedPath: resolved, stat } = pathResult;
	const packageInstallOptions = pickPackageInstallCommonParams(params);
	if (stat.isDirectory()) return await installPluginFromDir({
		dirPath: resolved,
		...packageInstallOptions,
		installPolicyRequest: {
			kind: "plugin-dir",
			requestedSpecifier: params.path
		}
	});
	if (runtime.resolveArchiveKind(resolved)) return await installPluginFromArchive({
		archivePath: resolved,
		...packageInstallOptions,
		installPolicyRequest: {
			kind: "plugin-archive",
			requestedSpecifier: params.path
		}
	});
	return await installPluginFromFile({
		filePath: resolved,
		...pickFileInstallCommonParams({
			...params,
			installPolicyRequest: {
				kind: "plugin-file",
				requestedSpecifier: params.path
			}
		})
	});
}
//#endregion
export { installPluginFromPath as a, installPluginFromNpmSpec as i, installPluginFromArchive as n, installPluginFromInstalledPackageDir as r, PLUGIN_INSTALL_ERROR_CODE as t };
