UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

10,962 lines • 443 kB
import { c as hasErrnoCode, d as isMissingPathError, h as extractErrorCode, l as ignoreMissingPath, o as resolveIsNixMode } from "./paths-0xDagtub.mjs";
import { a as sanitizeForLog, d as asOptionalRecord, h as omitUndefinedFields, l as asNullableRecord, p as isRecord, r as resolveConfigDir, u as asOptionalObjectRecord } from "./utils-BclMknzT.mjs";
import { B as normalizeOptionalString, C as asPositiveInteger, I as hasNonEmptyString, L as normalizeLowercaseStringOrEmpty, P as resolvePositiveTimerTimeoutMs, S as asPositiveFiniteNumber, T as asSafeIntegerInRange, U as resolveGlobalSet, W as resolveGlobalSingleton, a as resolveStateDir, b as asNonNegativeFiniteNumber, i as normalizeWindowsPathPreservingCase, m as tryProcessCwd, n as isPathInside$2, p as resolveUserPath, r as normalizeWindowsPathForComparison$1, t as isNotFoundPathError, y as asFiniteNumber, z as normalizeOptionalLowercaseString } from "./path-guards-quCEQx1i.mjs";
import { A as safeParseJson, S as cloneConfigWithResolutionFacts, T as getConfigResolutionFacts, b as isDeeplyFrozenPlainData, c as withExistingOpenClawStateDatabaseArtifactPreservingReadOnly, d as listAgentIds, k as stableStringify, l as withExistingOpenClawStateDatabaseReadOnly, o as executeExistingOpenClawStateRead, s as getActiveOpenClawStateDatabaseReadSnapshot, u as resolveAgentWorkspaceDir, v as runtimeConfigPublication, y as freezeJsonSnapshot } from "./openclaw-state-db-kPhNg45U.mjs";
import { n as isSqliteLockError } from "./sqlite-error-diagnostics-DXQCgyiD.mjs";
import { l as resolveCompatibilityHostVersion } from "./sqlite-user-version-D-rYjp-A.mjs";
import { B as resolveSecretRefProviderSourceMismatch, C as matchRootFileOpenFailure, E as readFileDescriptorBoundedSync$1, F as ENV_SECRET_REF_ID_RE, G as parseJsonWithJson5Fallback, I as SINGLE_VALUE_FILE_REF_ID, L as isBuiltInDefaultSecretProviderRef, R as isValidSecretProviderAlias, V as secretRefKey, W as parseConfigPathArrayIndex, Z as expectDefined, b as resolveRootPathSync, c as PLUGIN_ORIGIN_PRIORITIES, l as groupPluginRecords, q as isBlockedObjectKey$1, r as redactSensitiveText, s as registerSecretValueForRedaction, w as openRootFileSync, y as resolvePathViaExistingAncestorSync$1, z as normalizeAndGroupSecretRefs } from "./redact-BRF0hr6G.mjs";
import { A as acquireSqliteStagingToken, L as isArtifactPreservingStateRead, k as SQLITE_STAGING_TOKEN_FILES } from "./sqlite-snapshot-staging-owner-D6iplEEs.mjs";
import { a as normalizeSortedUniqueTrimmedStringList, c as normalizeUniqueSingleOrTrimmedStringList, d as normalizeUniqueTrimmedStringList, f as sortUniqueStrings, i as normalizeOptionalTrimmedStringList, n as filterStringEntries, o as normalizeStringEntries, p as uniqueStrings, r as normalizeArrayBackedTrimmedStringList, s as normalizeTrimmedStringList, t as containsAsciiControlCharacter } from "./string-normalization-BMFMScZY.mjs";
import { t as createSubsystemLogger } from "./subsystem-CeOCPr4l.mjs";
import { n as formatErrorMessageWithCode, t as formatErrorMessage } from "./errors-hqLS1E8Y.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-G5_kmB_7.mjs";
import { i as runInDetachedAsyncContext, n as getPluginExecutionFrame } from "./plugin-instance-invocation-DLc0_aJ8.mjs";
import { a as getPluginCacheRoot, c as getScopedPluginCaches, i as getPluginCacheRetirementSignal, l as invalidatePluginCacheMetadata, n as bindPluginCacheRoot, o as getProcessPluginCache, r as getPluginCache, s as getScopedPluginCache, t as resolveOpenClawPackageRootSync } from "./openclaw-root-l-fyeuXJ.mjs";
import { a as registerListener, i as notifyListeners } from "./sql-connection-VmV9pnJI.mjs";
import { c as normalizeDatabasePath } from "./sqlite-worker-identity-CiWdPbPl.mjs";
import { o as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-5PCLNGIM.mjs";
import { S as getNodeSqliteKysely, b as executeSqliteQuerySync, i as tableExists, x as executeSqliteQueryTakeFirstSync } from "./openclaw-state-db-schema-helpers-Bn-sHIhd.mjs";
import { n as isTruthyEnvValue } from "./env-C62NiKTo.mjs";
import { u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D4bxhyEQ.mjs";
import { _ as publishSqliteDatabaseAdmission, o as getSqliteDatabaseAdmission } from "./sqlite-database-admission-DMm34jqt.mjs";
import { t as isEmbeddedStandaloneModule } from "./cli-invocation-CSfpG5sl.mjs";
import { t as runCommandWithTimeout } from "./exec-CUD-gZWW.mjs";
import { n as compareValidSemver } from "./semver-DUtldgR6.mjs";
import { t as sha256Hex } from "./node-crypto-CWAQhBWK.mjs";
import { c as resolvePluginSourceCapturesDirectory, o as isLegacyPluginSourceCaptureName, s as resolvePluginSourceCaptureFallbackPrefix } from "./gateway-process-argv-DB5Y-Mad.mjs";
import { g as registerOpenClawStateDatabaseLifecycleListener, h as registerOpenClawStateDatabaseAsyncResource, mt as decodeMountInfoPath, xt as compareOpenClawVersions } from "./openclaw-state-db-cache-D7C7Hg5y.mjs";
import { t as resolveRuntimeArgs } from "./runtime-worker-url-BEfqe_m6.mjs";
import { f as getOrCreatePromise } from "./worker-task-pool-DBu8jMlX.mjs";
import { n as ok, t as err } from "./result-CV1-31DB.mjs";
import { n as readSecureFile, t as FsSafeError } from "./fs-safe-CQCGsM4r.mjs";
import { _ as MANIFEST_KEY, h as resolveOfficialExternalPluginId, o as getOfficialExternalPluginCatalogManifest } from "./official-external-plugin-catalog-source-CkTuOl59.mjs";
import { a as resolveOfficialExternalPluginLegacyIds, c as BUNDLED_OFFICIAL_EXTERNAL_PLUGIN_CATALOG_ENTRIES, i as resolveOfficialExternalPluginInstall, n as getOfficialExternalPluginCatalogEntryForPackage, o as isPrereleaseResolutionAllowed, s as parseRegistryNpmSpec, t as getOfficialExternalPluginCatalogEntry } from "./official-external-plugin-catalog-Bv-7q5p5.mjs";
import { d as object, f as record, h as union, i as boolean, l as never, m as string, o as discriminatedUnion, p as strictObject, r as array, s as literal, t as _enum, u as number } from "./schemas-DA6xYxQu.mjs";
import { a as SecretStoreValidationError, i as SECRET_STORE_VALUE_MAX_BYTES } from "./openclaw-state-worker-error-Blekn2XA.mjs";
import "./openclaw-state-worker-store-CpJWs6Nu.mjs";
import { t as captureOpenClawStateReadWorkerContext } from "./openclaw-state-worker-context-GPo8ZZmA.mjs";
import "./temp-artifact-cleanup-BGWtaR_8.mjs";
import { createRequire } from "node:module";
import { AsyncLocalStorage } from "node:async_hooks";
import fsSync, { lstatSync, realpathSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import crypto, { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
import { formatPosixMode, readRegularFileSync, safePathSegmentHashed } from "@openclaw/fs-safe/advanced";
import { isPathInside, safeRealpathSync as safeRealpathSync$1, safeStatSync } from "@openclaw/fs-safe/path";
import fsPromises from "node:fs/promises";
import os, { tmpdir } from "node:os";
import { isMainThread } from "node:worker_threads";
import { Buffer as Buffer$1 } from "node:buffer";
import { prerelease, satisfies, valid } from "semver";
import { tryReadJsonSync, tryReadJsonSync as tryReadJsonSync$1 } from "@openclaw/fs-safe/json";
import "commander";
import "@openclaw/fs-safe/atomic";
import pMap from "p-map";
import { inspectPathPermissions, safeStat } from "@openclaw/fs-safe/permissions";
//#region src/infra/test-runtime-env.ts
/** Detects Vitest/test execution from the env shape used by local and worker processes. */
function isVitestRuntimeEnv(e = process.env) {
	const t = e.VITEST;
	return t === "true" || t === "1" || e.VITEST_POOL_ID !== void 0 || e.VITEST_WORKER_ID !== void 0 || e.NODE_ENV === "test";
}
//#endregion
//#region src/plugins/path-safety.ts
/** Plugin-local re-export of shared path safety helpers for plugin install/runtime code. */
function canProbeWindowsPhysicalAlias(e, t) {
	const n = /^(?:[\\/]{2}[?.][\\/])?[A-Za-z]:[\\/]/.exec(t)?.[0];
	if (n) return isPathInside(n, t);
	const r = normalizeWindowsPathPreservingCase(e);
	const i = isPathInside(e, r) && isPathInside(r, e) ? path.win32.parse(r).root || r : e;
	return isPathInside(i, t);
}
/** Resolves matching physical spellings when Windows presents one tree through different aliases. */
function resolvePhysicalPathInsideRootSync(e, t) {
	if (process.platform !== "win32") return;
	try {
		if (!canProbeWindowsPhysicalAlias(e, t) && !canProbeWindowsPhysicalAlias(fsSync.realpathSync(e), t)) return;
		const n = fsSync.statSync(e, { bigint: true });
		if (!n.isDirectory() || n.ino === 0n) return;
		let r = path.resolve(t);
		while (true) {
			const e = fsSync.statSync(r, { bigint: true });
			if (e.dev === n.dev && e.ino === n.ino) {
				const e = fsSync.realpathSync(r);
				return {
					rootPath: e,
					targetPath: path.resolve(e, path.relative(r, t)),
					rootIdentity: Object.freeze({
						dev: n.dev,
						ino: n.ino
					})
				};
			}
			const i = path.dirname(r);
			if (i === r) return;
			r = i;
		}
	} catch {
		return;
	}
}
function isPathInside$1(e, t) {
	return isPathInside(e, t) || resolvePhysicalPathInsideRootSync(e, t) !== void 0;
}
function createIdentityBoundRootFileFs(e, t) {
	const lstatSync = ((...n) => {
		const r = Reflect.apply(fsSync.lstatSync, fsSync, n);
		if (n[0] === e) {
			const n = typeof r.ino === "bigint" ? r : fsSync.lstatSync(e, { bigint: true });
			if (!r.isDirectory() || n.dev !== t.dev || n.ino !== t.ino) throw new FsSafeError("path-mismatch", "plugin root identity changed during alias reconciliation");
		}
		return r;
	});
	return {
		closeSync: fsSync.closeSync,
		constants: fsSync.constants,
		fstatSync: fsSync.fstatSync,
		lstatSync,
		openSync: fsSync.openSync,
		readFileSync: fsSync.readFileSync,
		realpathSync: fsSync.realpathSync
	};
}
/** Opens a plugin artifact after reconciling Windows root aliases. */
function openPluginRootFileSync(e) {
	const t = e.rootRealPath ?? e.rootPath;
	const n = isPathInside(t, e.filePath) ? void 0 : resolvePhysicalPathInsideRootSync(t, e.filePath);
	return openRootFileSync({
		absolutePath: n?.targetPath ?? e.filePath,
		rootPath: n?.rootPath ?? e.rootPath,
		rootRealPath: n?.rootPath ?? e.rootRealPath,
		boundaryLabel: e.boundaryLabel ?? "plugin root",
		rejectHardlinks: e.rejectHardlinks,
		maxBytes: e.maxBytes,
		skipLexicalRootCheck: n ? true : void 0,
		ioFs: n ? createIdentityBoundRootFileFs(n.rootPath, n.rootIdentity) : void 0
	});
}
//#endregion
//#region src/plugins/plugin-cache-files.ts
const DEFAULT_PLUGIN_METADATA_MAX_BYTES = 16777216;
var CachedFileType = class {
	constructor(e) {
		this.mode = e;
	}
	isFile() {
		return (this.mode & fsSync.constants.S_IFMT) === fsSync.constants.S_IFREG;
	}
	isDirectory() {
		return (this.mode & fsSync.constants.S_IFMT) === fsSync.constants.S_IFDIR;
	}
	isSymbolicLink() {
		return (this.mode & fsSync.constants.S_IFMT) === fsSync.constants.S_IFLNK;
	}
};
var CachedStat = class extends CachedFileType {
	constructor(e) {
		super(e.mode);
		this.uid = e.uid;
		this.nlink = e.nlink;
		this.dev = e.dev;
		this.ino = e.ino;
		this.size = e.size;
		this.mtimeMs = e.mtimeMs;
	}
};
var CachedDirectoryEntry = class extends CachedFileType {
	constructor(e) {
		super(e.isFile() ? fsSync.constants.S_IFREG : e.isDirectory() ? fsSync.constants.S_IFDIR : e.isSymbolicLink() ? fsSync.constants.S_IFLNK : 0);
		this.name = e.name;
	}
};
function capturedPluginFile(e, t, n, r) {
	return {
		ok: true,
		path: e,
		rootRealPath: t,
		contents: n,
		hash: crypto.createHash("sha256").update(n).digest("hex"),
		signature: {
			size: r.size,
			mtimeMs: r.mtimeMs,
			ctimeMs: r.ctimeMs
		}
	};
}
function entryKey(e, t) {
	return JSON.stringify([path.normalize(e), t]);
}
function enforceFileSize(e, t, n = "validation", r) {
	if (e.ok && t !== void 0 && Math.max(e.signature.size, e.contents.length) > t) return {
		ok: false,
		failure: {
			ok: false,
			reason: n,
			error: new FsSafeError("too-large", `File exceeds ${t} bytes: ${r ?? e.path}`)
		}
	};
	return e;
}
function pathFacts(e) {
	const t = path.resolve(e);
	const n = getPluginCacheRoot(path.dirname(t));
	const r = path.basename(t);
	let i = n.paths.get(r);
	if (!i) {
		i = {};
		n.paths.set(r, i);
	}
	return i;
}
function pluginCacheExistsSync(e) {
	const t = pathFacts(e);
	return t.exists ??= fsSync.existsSync(e);
}
function resolveRealpath(e) {
	if (path.resolve(e) === e) {
		if (pathFacts(e).nativeRealpath === e) return e;
		if (process.platform !== "win32") {
			const t = path.dirname(e);
			const n = pluginCacheLstatSync(e);
			if (t !== e && n && !n.isSymbolicLink()) {
				const n = pluginCacheRealpathSync(t);
				if (n) return path.join(n, path.basename(e));
			}
		} else if (pluginCacheRealpathSync(e, true) === e) return e;
	}
	return fsSync.realpathSync(e);
}
function pluginCacheRealpathSync(e, t = false) {
	const n = pathFacts(e);
	const r = t ? "nativeRealpath" : "realpath";
	if (n[r] === void 0) try {
		n[r] = t ? fsSync.realpathSync.native(e) : resolveRealpath(e);
		pathFacts(n[r])[r] = n[r];
	} catch {
		n[r] = null;
	}
	return n[r];
}
/** A trusted owner that changes permissions replaces its own observed stat. */
function refreshPluginCacheStat(e) {
	pathFacts(e).stat = void 0;
	return pluginCacheStatSync(e);
}
function pluginCacheStatSync(e, t = false) {
	const n = pathFacts(e);
	if (n.stat === void 0) {
		n.statError = void 0;
		try {
			n.stat = new CachedStat(fsSync.statSync(e));
			n.exists = true;
		} catch (e) {
			materializeErrorStack(e);
			n.statError = e;
			n.stat = null;
		}
	}
	if (n.stat === null && t) throw n.statError;
	return n.stat;
}
/** Final symlink checks must retain lstat facts separately from followed target stats. */
function pluginCacheLstatSync(e) {
	const t = pathFacts(e);
	if (t.lstat === void 0) try {
		t.lstat = new CachedStat(fsSync.lstatSync(e));
	} catch {
		t.lstat = null;
	}
	return t.lstat;
}
function readPluginCacheDirectory(e) {
	const t = getPluginCacheRoot(e);
	if (!t.directory) try {
		t.directory = {
			ok: true,
			entries: fsSync.readdirSync(e, { withFileTypes: true }).map((e) => new CachedDirectoryEntry(e))
		};
	} catch (e) {
		materializeErrorStack(e);
		t.directory = {
			ok: false,
			error: e
		};
	}
	if (!t.directory.ok) throw t.directory.error;
	return t.directory.entries;
}
/** Discovery validation is immutable metadata; actual imports validate their own file identity. */
function checkPluginCacheEntry(e) {
	let t = getPluginCacheRoot(e.rootDir);
	const n = entryKey(e.relativePath, e.rejectHardlinks);
	const r = t.checkedEntries.get(n);
	if (r) return r;
	const i = path.resolve(e.rootDir, e.relativePath);
	let a;
	if (!pluginCacheExistsSync(i)) try {
		const n = resolveRootPathSync({
			absolutePath: i,
			rootPath: e.rootDir,
			rootCanonicalPath: e.rootRealPath,
			boundaryLabel: "plugin package directory"
		});
		t = bindPluginCacheRoot(e.rootDir, n.rootCanonicalPath);
		a = {
			ok: true,
			path: n.canonicalPath,
			rootRealPath: n.rootCanonicalPath,
			exists: false
		};
	} catch (e) {
		a = {
			ok: false,
			reason: "validation",
			error: e
		};
	}
	else {
		const n = openPluginRootFileSync({
			filePath: i,
			rootPath: e.rootDir,
			rootRealPath: e.rootRealPath,
			boundaryLabel: "plugin package directory",
			rejectHardlinks: e.rejectHardlinks
		});
		if (!n.ok) a = n;
		else {
			fsSync.closeSync(n.fd);
			t = bindPluginCacheRoot(e.rootDir, n.rootRealPath);
			Object.assign(pathFacts(n.path), {
				exists: true,
				stat: new CachedStat(n.stat)
			});
			if (process.platform !== "win32") pathFacts(n.path).nativeRealpath = n.path;
			a = {
				ok: true,
				path: n.path,
				rootRealPath: n.rootRealPath,
				exists: true
			};
		}
	}
	if (!a.ok) materializeErrorStack(a.error);
	t.checkedEntries.set(n, a);
	return a;
}
/** Reads metadata once under its original boundary policy, including absence and invalid files. */
function readPluginCacheFile(e) {
	let t = getPluginCacheRoot(e.rootDir);
	const n = e.maxBytes === null ? void 0 : e.maxBytes ?? DEFAULT_PLUGIN_METADATA_MAX_BYTES;
	const r = entryKey(e.relativePath, e.rejectHardlinks);
	let i = t.files.get(r) ?? t.files.get(JSON.stringify([r, n]));
	if (!i && !e.rejectHardlinks) {
		const n = t.files.get(entryKey(e.relativePath, true));
		i = n?.ok ? n : void 0;
	}
	if (i) return enforceFileSize(i, n);
	const a = path.resolve(e.rootDir);
	const o = path.resolve(a, e.relativePath);
	const s = t.checkedEntries.get(r);
	if (pathFacts(o).exists === false || s && (!s.ok || !s.exists)) {
		const e = {
			ok: false,
			failure: s && !s.ok ? s : {
				ok: false,
				reason: "path"
			}
		};
		t.files.set(r, e);
		return e;
	}
	const c = e.rootRealPath ?? pluginCacheRealpathSync(a) ?? a;
	const l = getPluginCacheRoot(c).files.get(r);
	if (l?.ok) {
		bindPluginCacheRoot(a, c);
		return enforceFileSize(l, n);
	}
	const u = path.resolve(c, e.relativePath);
	const d = openPluginRootFileSync({
		filePath: u,
		rootRealPath: c,
		rootPath: c,
		boundaryLabel: "plugin root",
		rejectHardlinks: e.rejectHardlinks,
		maxBytes: n
	});
	let f;
	if (!d.ok) {
		f = {
			ok: false,
			failure: d
		};
		if (d.reason === "path" && d.error && typeof d.error === "object" && "code" in d.error && d.error.code === "ENOENT") {
			pathFacts(o).exists = false;
			pathFacts(u).exists = false;
		}
	} else {
		t = bindPluginCacheRoot(a, d.rootRealPath);
		try {
			const e = n === void 0 ? fsSync.readFileSync(d.fd) : readFileDescriptorBoundedSync$1(d.fd, n);
			f = capturedPluginFile(d.path, d.rootRealPath, e, d.stat);
			Object.assign(pathFacts(u), {
				exists: true,
				stat: new CachedStat(d.stat)
			});
			t.checkedEntries.set(r, {
				ok: true,
				path: d.path,
				rootRealPath: d.rootRealPath,
				exists: true
			});
		} catch (e) {
			f = {
				ok: false,
				failure: {
					ok: false,
					reason: "io",
					error: e
				},
				failurePhase: "read"
			};
		} finally {
			fsSync.closeSync(d.fd);
		}
	}
	if (!f.ok) materializeErrorStack(f.failure.error);
	t.files.set(f.ok ? r : JSON.stringify([r, n]), f);
	return f;
}
/** Catalog files retain the regular-file policy, which rejects final symlinks but allows hardlinks. */
function readPluginCacheRegularFile(e) {
	const t = path.resolve(e.filePath);
	const n = path.dirname(t);
	const r = pluginCacheRealpathSync(n) ?? n;
	const i = bindPluginCacheRoot(n, r);
	const a = path.basename(t);
	const o = JSON.stringify(["regular", a]);
	const s = JSON.stringify([
		"regular",
		a,
		e.maxBytes
	]);
	let c = i.files.get(o) ?? i.files.get(s);
	if (!c && pathFacts(t).exists === false) {
		c = {
			ok: false,
			failure: {
				ok: false,
				reason: "path"
			}
		};
		i.files.set(o, c);
	}
	if (!c) try {
		const { buffer: n, stat: s } = readRegularFileSync({
			filePath: t,
			maxBytes: e.maxBytes
		});
		c = capturedPluginFile(path.join(r, a), r, n, s);
		Object.assign(pathFacts(t), {
			exists: true,
			stat: new CachedStat(s)
		});
		i.files.set(o, c);
	} catch (e) {
		materializeErrorStack(e);
		c = {
			ok: false,
			failure: {
				ok: false,
				reason: "io",
				error: e
			}
		};
		i.files.set(e instanceof FsSafeError && e.code === "too-large" ? s : o, c);
		if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") pathFacts(t).exists = false;
	}
	return enforceFileSize(c, e.maxBytes, "io", t);
}
function readPluginCacheJsonFile(e, t = {}) {
	const n = readPluginCacheRegularFile({
		filePath: e,
		...t
	});
	return n.ok ? parsePluginCacheJson(n) : {
		ok: false,
		error: n.failure.error
	};
}
function parsePluginCacheJson(e, t = {}) {
	const n = t.json5 ? "json5" : "json";
	if (!e[n]) try {
		const r = e.contents.toString("utf8");
		e[n] = {
			ok: true,
			value: t.json5 ? parseJsonWithJson5Fallback(r) : JSON.parse(r)
		};
	} catch (t) {
		materializeErrorStack(t);
		e[n] = {
			ok: false,
			error: t
		};
	}
	return e[n];
}
//#endregion
//#region src/plugins/package-entrypoints.ts
const PUBLIC_SURFACE_SOURCE_EXTENSIONS = [
	".ts",
	".mts",
	".js",
	".mjs",
	".cts",
	".cjs"
];
/** True when a package entrypoint needs built JavaScript candidates. */
function isTypeScriptPackageEntry(e) {
	return [
		".ts",
		".tsx",
		".mts",
		".cts"
	].includes(path.extname(e).toLowerCase());
}
/** Lists built runtime entry candidates for a TypeScript package entrypoint. */
function listBuiltRuntimeEntryCandidates(e) {
	if (!isTypeScriptPackageEntry(e)) return [];
	const t = e.replace(/\\/g, "/");
	const n = t.replace(/\.[^.]+$/u, "");
	const r = n.replace(/^\.\//u, "");
	const i = r.startsWith("src/") ? `./dist/${r.slice(4)}` : `./dist/${r}`;
	const a = path.extname(t).toLowerCase();
	const o = a === ".mts" ? [
		".mjs",
		".js",
		".cjs"
	] : a === ".cts" ? [
		".cjs",
		".js",
		".mjs"
	] : [
		".js",
		".mjs",
		".cjs"
	];
	return [
		i,
		...r.startsWith("src/") ? [`./dist/${r}`] : [],
		n
	].flatMap((e) => o.map((t) => `${e}${t}`));
}
//#endregion
//#region src/plugins/manifest-control-ui.ts
/** Package authoring metadata names source; the runtime manifest names only built assets. */
function controlUiSource(e) {
	const t = isRecord(e.openclaw) ? e.openclaw.controlUi : void 0;
	if (t === void 0) return;
	if (typeof t !== "string" || !t.trim()) throw new Error("package.json openclaw.controlUi must name a browser source entrypoint.");
	return t;
}
function normalizeManifestControlUi(e, t = []) {
	if (e === void 0) return ok(void 0);
	if (!isRecord(e) || Object.keys(e).some((e) => ![
		"entry",
		"styles",
		"activation",
		"settingsViews"
	].includes(e))) return err("controlUi contains an unknown field");
	if (e.activation !== void 0 && e.activation !== "settings-only") return err("controlUi.activation must be settings-only when specified");
	const n = new Set(Array.isArray(t) ? t : []);
	const r = [];
	const i = /* @__PURE__ */ new Set();
	if (e.settingsViews !== void 0) {
		if (!Array.isArray(e.settingsViews) || e.settingsViews.length === 0 || e.settingsViews.length > 2 + n.size) return err("controlUi.settingsViews must declare unique Settings placements");
		for (const t of e.settingsViews) {
			if (!isRecord(t)) return err("invalid Control UI Settings placement");
			let e;
			if (Object.keys(t).length === 2 && t.section === "memory" && (t.panel === "overview" || t.panel === "memories")) e = {
				section: "memory",
				panel: t.panel
			};
			else if (Object.keys(t).length === 3 && t.section === "channels" && t.panel === "detail" && typeof t.channelId === "string" && /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(t.channelId) && n.has(t.channelId)) e = {
				section: "channels",
				panel: "detail",
				channelId: t.channelId
			};
			else return err("Control UI Settings placement must name Memory or an owned channel detail");
			const a = JSON.stringify(e);
			if (i.has(a)) return err("controlUi.settingsViews must declare unique Settings placements");
			i.add(a);
			r.push(e);
		}
	}
	if (e.activation === "settings-only" && !e.settingsViews) return err("settings-only Control UI requires a Settings placement");
	const a = typeof e.entry === "string" ? e.entry.replace(/^\.\//u, "") : "";
	if (a.length > 512 || !/^dist\/(?:[\w-][\w.-]*\/)+[\w-][\w.-]*\.m?js$/u.test(a)) return err("controlUi.entry must be a JavaScript file in a dedicated dist subdirectory");
	if (e.styles !== void 0 && (!Array.isArray(e.styles) || e.styles.length > 16)) return err("controlUi.styles must be an array of at most 16 stylesheets");
	const o = a.slice(0, a.lastIndexOf("/") + 1);
	const s = [];
	for (const t of e.styles ?? []) {
		const e = typeof t === "string" ? t.replace(/^\.\//u, "") : "";
		if (e.length > 512 || !e.startsWith(o) || !/^(?:[\w-][\w.-]*\/)+[\w-][\w.-]*\.css$/u.test(e)) return err("controlUi.styles must contain CSS files under the entry's asset directory");
		if (!s.includes(e)) s.push(e);
	}
	return ok({
		entry: a,
		...s.length > 0 ? { styles: s } : {},
		...e.activation === "settings-only" ? { activation: e.activation } : {},
		...r.length > 0 ? { settingsViews: r } : {}
	});
}
//#endregion
//#region src/plugins/package-manifest.ts
const DEFAULT_PLUGIN_ENTRY_CANDIDATES = [
	"index.ts",
	"index.js",
	"index.mjs",
	"index.cjs"
];
function getPackageManifestMetadata(e) {
	return e?.[MANIFEST_KEY];
}
function resolvePackageExtensionEntries(e) {
	const t = e?.[MANIFEST_KEY];
	if (t === void 0 || t === null) return {
		status: "missing",
		entries: []
	};
	if (!isRecord(t)) return {
		status: "invalid",
		entries: [],
		error: "package.json openclaw must be an object"
	};
	const n = t.extensions;
	if (n === void 0 || n === null) return {
		status: "missing",
		entries: []
	};
	if (!Array.isArray(n)) return {
		status: "invalid",
		entries: [],
		error: "package.json openclaw.extensions must be an array"
	};
	const r = [];
	for (const [e, t] of n.entries()) {
		const n = normalizeOptionalString(t);
		if (!n) return {
			status: "invalid",
			entries: [],
			error: `package.json openclaw.extensions[${e}] must be a non-empty string`
		};
		r.push(n);
	}
	if (r.length === 0) return {
		status: "empty",
		entries: []
	};
	return {
		status: "ok",
		entries: r
	};
}
//#endregion
//#region src/plugins/plugin-runtime-artifact-selection.ts
/** Selects built plugin artifacts without importing active runtime state. */
/** Canonical packaged runtime replaces staging-only dist-runtime artifacts. */
function resolveCanonicalDistRuntimeSource(e) {
	const t = `${path.sep}dist-runtime${path.sep}extensions${path.sep}`;
	const n = e.indexOf(t);
	if (n === -1) return e;
	const r = `${e.slice(0, n)}${path.sep}dist${path.sep}extensions${path.sep}${e.slice(n + t.length)}`;
	return pluginCacheExistsSync(r) ? r : e;
}
/** Finalize once at execution; discovery and identity retain the selected artifact. */
function resolvePluginRuntimeExecutionArtifact(e) {
	const t = resolveCanonicalDistRuntimeSource(e.source);
	const n = resolveCanonicalDistRuntimeSource(e.rootDir);
	return {
		source: t,
		rootDir: n !== e.rootDir && !isPathInside$2(pluginCacheRealpathSync(n) ?? n, pluginCacheRealpathSync(t) ?? t) ? e.rootDir : n
	};
}
/** Selects from lifecycle-owned package facts without pinning a runtime registry. */
function resolvePluginRuntimeArtifactSelection(e) {
	const { source: t, rootDir: n } = resolvePluginRuntimeExecutionArtifact({
		source: pluginCacheRealpathSync(e.source) ?? path.resolve(e.source),
		rootDir: pluginCacheRealpathSync(e.rootDir) ?? path.resolve(e.rootDir)
	});
	const r = getPluginCacheRoot(n).runtimeArtifacts;
	const i = JSON.stringify([
		e.source,
		e.entryKind,
		e.origin,
		e.preferBuiltPluginArtifacts,
		e.sourcePreferred,
		e.packageManifest?.build?.bundledDist
	]);
	let a = r.get(i);
	if (!a) {
		a = resolvePluginRuntimeExecutionArtifact(resolvePreferredBuiltRuntimeArtifact({
			...e,
			source: t,
			rootDir: n
		}));
		r.set(i, a);
	}
	return a;
}
/** Built hosts default only checkout plugins to compiled execution, not installed packages. */
function resolvePluginRuntimeArtifactPreference(e) {
	if (e !== void 0) return e ? "all" : "source";
	return /\.[cm]?js$/.test(new URL(import.meta.url).pathname) ? "bundled" : "source";
}
function resolveBundledArtifactRelativePath(e, t) {
	const n = readPluginCacheFile({
		rootDir: e,
		relativePath: "package.json",
		rejectHardlinks: false
	});
	const r = n.ok ? parsePluginCacheJson(n) : void 0;
	const i = r?.ok && isRecord(r.value) ? getPackageManifestMetadata(r.value) : void 0;
	const a = [...i?.runtimeExtensions?.length ? i.runtimeExtensions : i?.extensions ?? [], i?.runtimeSetupEntry ?? i?.setupEntry].filter((e) => typeof e === "string");
	const o = t.replace(/\.[^.]+$/u, "");
	const s = a.find((e) => path.normalize(e).replace(/\.[^.]+$/u, "") === o);
	if (s) return /\.[cm]?js$/.test(s) ? s : null;
	const c = new Set(a.map((e) => path.extname(e)));
	const l = c.size === 1 ? [...c][0] : void 0;
	if (!l || ![
		".js",
		".mjs",
		".cjs"
	].includes(l) || a.some((e) => path.normalize(e).startsWith(`dist${path.sep}`))) return null;
	return t.replace(/\.[^.]+$/u, l);
}
function resolvePackageLocalDistRuntimeArtifact(e) {
	const t = path.relative(e.rootDir, e.source);
	if (!isTypeScriptPackageEntry(t) || t === "" || t.startsWith("..") || path.isAbsolute(t)) return null;
	for (const n of listBuiltRuntimeEntryCandidates(t)) {
		if (e.origin === "bundled" && !n.startsWith("./dist/")) continue;
		const t = path.resolve(e.rootDir, n);
		if (pluginCacheExistsSync(t)) return pluginCacheRealpathSync(t) ?? path.resolve(t);
	}
	return null;
}
function resolvePreferredBundledRootArtifactFromCanonicalPaths(e) {
	const { rootDir: t, source: n } = e;
	const r = e.packageManifest?.build?.bundledDist === false;
	const i = path.dirname(t);
	if (path.basename(i) !== "extensions") return {
		source: n,
		rootDir: t
	};
	const a = path.dirname(i);
	if (path.basename(a) === "dist" || path.basename(a) === "dist-runtime") return {
		source: n,
		rootDir: t
	};
	const o = path.relative(t, n);
	if (o === "" || o.startsWith("..") || path.isAbsolute(o)) return {
		source: n,
		rootDir: t
	};
	for (const e of r ? ["dist"] : ["dist-runtime", "dist"]) {
		const n = path.join(a, e, "extensions", path.basename(t));
		const r = resolveBundledArtifactRelativePath(n, o);
		if (!r) continue;
		const i = path.join(n, r);
		if (pluginCacheExistsSync(i)) return {
			source: pluginCacheRealpathSync(i) ?? path.resolve(i),
			rootDir: pluginCacheRealpathSync(n) ?? path.resolve(n)
		};
	}
	return {
		source: n,
		rootDir: t
	};
}
/** Applies source, package-local, and root-build preference without runtime memo state. */
function resolvePreferredBuiltRuntimeArtifact(e) {
	const { rootDir: t, source: n } = e;
	if (!e.preferBuiltPluginArtifacts || e.sourcePreferred) return {
		source: n,
		rootDir: t
	};
	if (e.origin !== "bundled") {
		const r = resolvePackageLocalDistRuntimeArtifact({
			...e,
			source: n,
			rootDir: t
		});
		return r ? {
			source: r,
			rootDir: t
		} : {
			source: n,
			rootDir: t
		};
	}
	const r = e.packageManifest?.build?.bundledDist === false ? null : resolvePackageLocalDistRuntimeArtifact({
		...e,
		source: n,
		rootDir: t
	});
	if (r) return {
		source: r,
		rootDir: t
	};
	return resolvePreferredBundledRootArtifactFromCanonicalPaths({
		source: n,
		rootDir: t,
		packageManifest: e.packageManifest
	});
}
//#endregion
//#region src/plugins/bundled-dir.ts
/** Resolves the bundled plugin directory for source checkouts, dist builds, and tests. */
const DISABLED_BUNDLED_PLUGINS_DIR = path.join(os.tmpdir(), "openclaw-empty-bundled-plugins");
const TEST_TRUST_BUNDLED_PLUGINS_DIR_ENV = "OPENCLAW_TEST_TRUST_BUNDLED_PLUGINS_DIR";
/** Returns true when env disables bundled plugin discovery. */
function areBundledPluginsDisabled(e = process.env) {
	const t = normalizeOptionalLowercaseString(e.OPENCLAW_DISABLE_BUNDLED_PLUGINS);
	return t === "1" || t === "true";
}
function resolveDisabledBundledPluginsDir() {
	if (!pluginCacheExistsSync(DISABLED_BUNDLED_PLUGINS_DIR)) {
		fsSync.mkdirSync(DISABLED_BUNDLED_PLUGINS_DIR, { recursive: true });
		refreshPluginCacheStat(DISABLED_BUNDLED_PLUGINS_DIR);
	}
	return DISABLED_BUNDLED_PLUGINS_DIR;
}
function isSourceCheckoutRoot(e) {
	return pluginCacheExistsSync(path.join(e, "pnpm-workspace.yaml")) && pluginCacheExistsSync(path.join(e, "src")) && pluginCacheExistsSync(path.join(e, "extensions"));
}
function shouldTrustTestBundledPluginsDirOverride(e) {
	const t = e !== process.env;
	if (!isTruthyEnvValue(e[TEST_TRUST_BUNDLED_PLUGINS_DIR_ENV]) && !(t && isTruthyEnvValue(process.env[TEST_TRUST_BUNDLED_PLUGINS_DIR_ENV]))) return false;
	return isVitestRuntimeEnv(e) || t && isVitestRuntimeEnv(process.env);
}
function hasUsableBundledPluginTree(e) {
	if (!pluginCacheExistsSync(e)) return false;
	try {
		return readPluginCacheDirectory(e).some((t) => {
			if (!t.isDirectory()) return false;
			const n = path.join(e, t.name);
			return pluginCacheExistsSync(path.join(n, "package.json")) || pluginCacheExistsSync(path.join(n, "openclaw.plugin.json"));
		});
	} catch {
		return false;
	}
}
function safeRealpathSync(e) {
	return pluginCacheRealpathSync(e, true);
}
function trustedBundledPluginRootsForPackageRoot(e) {
	const t = [path.join(e, "dist", "extensions"), path.join(e, "dist-runtime", "extensions")];
	if (isSourceCheckoutRoot(e)) t.push(path.join(e, "extensions"));
	return t;
}
function resolvePackageRootsForBundledPlugins(e) {
	const t = resolveOpenClawPackageRootSync({ argv1: process.argv[1] });
	const n = t && e && isPluginInPackageBundledRoots({
		rootDir: e,
		packageRoot: t
	}) ? null : t;
	const r = resolveOpenClawPackageRootSync({ moduleUrl: import.meta.url });
	return uniqueStrings([n, r].filter((e) => Boolean(e)));
}
function resolveSourceCheckoutDependencyDiagnostic(e = process.env) {
	if (areBundledPluginsDisabled(e)) return null;
	for (const e of resolvePackageRootsForBundledPlugins()) {
		if (!isSourceCheckoutRoot(e)) continue;
		const t = path.join(e, "extensions");
		if (!isPluginInPackageBundledRoots({
			rootDir: t,
			packageRoot: e
		}) || !hasUsableBundledPluginTree(t)) continue;
		if (pluginCacheExistsSync(path.join(e, "node_modules", ".pnpm"))) continue;
		return {
			source: e,
			message: "OpenClaw source checkout detected without pnpm workspace dependencies; run `pnpm install` from the repo root so bundled plugins can load package-local dependencies."
		};
	}
	return null;
}
function resolveTrustedExistingOverride(e) {
	const t = safeRealpathSync(e);
	if (!t) return null;
	const n = resolveOpenClawPackageRootSync({ moduleUrl: import.meta.url });
	if (!n || !isPluginInPackageBundledRoots({
		rootDir: t,
		packageRoot: n
	})) return null;
	if (!hasUsableBundledPluginTree(t)) return null;
	return t;
}
/** Checks physical containment in a package's source or compiled plugin trees. */
function isPluginInPackageBundledRoots(e) {
	const t = safeRealpathSync(e.rootDir);
	const n = safeRealpathSync(e.packageRoot);
	if (!t || !n) return false;
	return trustedBundledPluginRootsForPackageRoot(e.packageRoot).map((e) => safeRealpathSync(e)).some((e) => e !== null && isPathInside$2(n, e) && isPathInside$2(e, t));
}
/** Recognizes compiled bundle ownership only; this never confers plugin trust. */
function isForeignBundledPluginRoot(e, t = process.env) {
	const n = safeRealpathSync(e);
	if (!n) return false;
	const r = path.dirname(n);
	const i = path.dirname(r);
	if (path.basename(r) !== "extensions" || !["dist", "dist-runtime"].includes(path.basename(i))) return false;
	const a = path.dirname(i);
	if (resolveOpenClawPackageRootSync({ cwd: a }) !== a || !isPluginInPackageBundledRoots({
		rootDir: n,
		packageRoot: a
	})) return false;
	const o = resolveBundledPluginsDir(t);
	const s = o ? safeRealpathSync(o) : null;
	if (s && isPathInside$2(s, n)) return false;
	const c = resolvePackageRootsForBundledPlugins();
	return c.length > 0 && !c.some((e) => isPluginInPackageBundledRoots({
		rootDir: n,
		packageRoot: e
	}));
}
function resolveBundledDirFromPackageRoot(e, t = "bundled") {
	const n = path.join(e, "dist", "extensions");
	const r = path.join(e, "dist-runtime", "extensions");
	if (isSourceCheckoutRoot(e)) {
		const i = path.join(e, "extensions");
		return (t === "source" ? [i] : [
			n,
			r,
			i
		]).find((t) => isPluginInPackageBundledRoots({
			rootDir: t,
			packageRoot: e
		}) && hasUsableBundledPluginTree(t));
	}
	return pluginCacheExistsSync(n) ? [r, n].find((t) => isPluginInPackageBundledRoots({
		rootDir: t,
		packageRoot: e
	})) : void 0;
}
function resolveBundledPluginsDirUncached(e) {
	if (areBundledPluginsDisabled(e)) return resolveDisabledBundledPluginsDir();
	const t = e.OPENCLAW_BUNDLED_PLUGINS_DIR?.trim();
	let n = null;
	if (t) {
		const r = resolveUserPath(t, e);
		if (pluginCacheExistsSync(r)) {
			if (shouldTrustTestBundledPluginsDirOverride(e)) return path.resolve(r);
			const t = resolveTrustedExistingOverride(r);
			if (t) return t;
			n = r;
		}
	}
	for (const e of resolvePackageRootsForBundledPlugins(n)) {
		const t = resolveBundledDirFromPackageRoot(e, resolvePluginRuntimeArtifactPreference());
		if (t) return t;
	}
	const r = path.dirname(process.execPath);
	const i = path.join(r, "dist", "extensions");
	if (pluginCacheExistsSync(i)) return i;
	const a = path.join(r, "extensions");
	if (pluginCacheExistsSync(a)) return a;
	try {
		let e = path.dirname(fileURLToPath(import.meta.url));
		for (let t = 0; t < 6; t += 1) {
			const t = path.join(e, "extensions");
			if (pluginCacheExistsSync(t)) return t;
			const n = path.dirname(e);
			if (n === e) break;
			e = n;
		}
	} catch {}
}
function resolveBundledPluginsDir(e = process.env) {
	const t = areBundledPluginsDisabled(e);
	const n = t ? void 0 : e.OPENCLAW_BUNDLED_PLUGINS_DIR?.trim();
	const r = n ? resolveUserPath(n, e) : void 0;
	const i = shouldTrustTestBundledPluginsDirOverride(e);
	const a = process.argv[1];
	const o = process.execPath;
	const s = tryProcessCwd();
	const c = getPluginCache().metadata;
	const l = c.bundledPluginsDir;
	if (l && l.moduleUrl === import.meta.url && l.disabled === t && l.resolvedOverride === r && l.trustOverride === i && l.argv1 === a && l.execPath === o && l.cwd === s) return l.value;
	const u = resolveBundledPluginsDirUncached(e);
	c.bundledPluginsDir = {
		moduleUrl: import.meta.url,
		disabled: t,
		resolvedOverride: r,
		trustOverride: i,
		argv1: a,
		execPath: o,
		cwd: s,
		value: u
	};
	return u;
}
//#endregion
//#region src/channels/bundled-channel-catalog-read.ts
const OFFICIAL_CHANNEL_CATALOG_RELATIVE_PATH = path.join("dist", "channel-catalog.json");
function listPackageRoots() {
	return uniqueStrings([resolveOpenClawPackageRootSync({ cwd: process.cwd() }), resolveOpenClawPackageRootSync({ moduleUrl: import.meta.url })].filter((e) => Boolean(e)));
}
function readBundledExtensionCatalogEntriesSync(e) {
	if (!e) return [];
	try {
		return readPluginCacheDirectory(e).filter((e) => e.isDirectory()).flatMap((t) => {
			const n = path.join(e, t.name, "package.json");
			const r = readPluginCacheJsonFile(n);
			return r.ok && isRecord(r.value) ? [r.value] : [];
		});
	} catch {
		return [];
	}
}
function readOfficialCatalogFileSync() {
	const e = BUNDLED_OFFICIAL_EXTERNAL_PLUGIN_CATALOG_ENTRIES.filter((e) => typeof e === "object" && e !== null);
	for (const t of listPackageRoots()) {
		const n = path.join(t, OFFICIAL_CHANNEL_CATALOG_RELATIVE_PATH);
		const r = readPluginCacheJsonFile(n);
		if (r.ok && isRecord(r.value)) {
			const t = Array.isArray(r.value.entries) ? r.value.entries.filter((e) => isRecord(e)) : [];
			return [...e, ...t];
		}
	}
	return e;
}
function toBundledChannelEntry(e) {
	const t = e.openclaw?.channel;
	const n = normalizeOptionalLowercaseString(t?.id);
	if (!n || !t) return null;
	return {
		id: n,
		channel: t,
		aliases: Array.isArray(t.aliases) ? t.aliases.map((e) => normalizeOptionalLowercaseString(e)).filter((e) => Boolean(e)) : [],
		order: typeof t.order === "number" && Number.isFinite(t.order) ? t.order : Number.MAX_SAFE_INTEGER
	};
}
function listBundledChannelCatalogEntries() {
	const e = resolveBundledPluginsDir();
	const t = getPluginCache().metadata.bundledChannelCatalogs;
	const n = JSON.stringify([process.cwd(), e]);
	const r = t.get(n);
	if (r) return r;
	const i = /* @__PURE__ */ new Map();
	for (const t of readBundledExtensionCatalogEntriesSync(e)) {
		const e = toBundledChannelEntry(t);
		if (e) i.set(e.id, e);
	}
	for (const e of readOfficialCatalogFileSync()) {
		const t = toBundledChannelEntry(e);
		if (t) i.set(t.id, i.get(t.id) ?? t);
	}
	const a = Array.from(i.values()).toSorted((e, t) => e.order - t.order || e.id.localeCompare(t.id));
	t.set(n, a);
	return a;
}
//#endregion
//#region src/channels/bundled-channel-ids.generated.ts
const GENERATED_BUNDLED_CHANNEL_IDS = [
	{
		channelId: "a2a",
		order: 75,
		label: "A2A"
	},
	{
		channelId: "buzz",
		order: 56,
		label: "Buzz"
	},
	{
		channelId: "clickclack",
		order: 85,
		label: "ClickClack"
	},
	{
		channelId: "discord",
		label: "Discord"
	},
	{
		channelId: "feishu",
		aliases: ["lark"],
		order: 35,
		label: "Feishu"
	},
	{
		channelId: "googlechat",
		aliases: ["gchat", "google-chat"],
		order: 55,
		label: "Google Chat"
	},
	{
		channelId: "imessage",
		aliases: ["imsg"],
		label: "iMessage"
	},
	{
		channelId: "irc",
		aliases: ["internet-relay-chat"],
		label: "IRC"
	},
	{
		channelId: "line",
		order: 75,
		label: "LINE"
	},
	{
		channelId: "matrix",
		order: 70,
		label: "Matrix"
	},
	{
		channelId: "mattermost",
		order: 65,
		label: "Mattermost"
	},
	{
		channelId: "msteams",
		aliases: ["teams"],
		order: 60,
		label: "Microsoft Teams"
	},
	{
		channelId: "nextcloud-talk",
		aliases: ["nc", "nc-talk"],
		order: 65,
		label: "Nextcloud Talk"
	},
	{
		channelId: "nostr",
		order: 55,
		label: "Nostr"
	},
	{
		channelId: "qa-channel",
		order: 999,
		configurable: false,
		label: "QA Channel"
	},
	{
		channelId: "raft",
		order: 72,
		label: "Raft"
	},
	{
		channelId: "reef",
		label: "Reef"
	},
	{
		channelId: "signal",
		label: "Signal"
	},
	{
		channelId: "slack",
		label: "Slack"
	},
	{
		channelId: "sms",
		order: 88,
		label: "SMS"
	},
	{
		channelId: "synology-chat",
		order: 90,
		label: "Synology Chat"
	},
	{
		channelId: "telegram",
		label: "Telegram"
	},
	{
		channelId: "tlon",
		order: 90,
		label: "Tlon"
	},
	{
		channelId: "twitch",
		aliases: ["twitch-chat"],
		label: "Twitch"
	},
	{
		channelId: "whatsapp",
		label: "WhatsApp"
	},
	{
		channelId: "x",
		order: 85,
		label: "X (Twitter)"
	},
	{
		channelId: "zalo",
		aliases: ["zl"],
		order: 80,
		label: "Zalo"
	},
	{
		channelId: "zalouser",
		aliases: ["zlu"],
		order: 85,
		label: "Zalo Personal"
	}
];
//#endregion
//#region src/channels/ids.ts
const BUNDLED_CHAT_CHANNEL_ENTRIES = GENERATED_BUNDLED_CHANNEL_IDS.filter((e) => e.configurable !== false).map((e) => ({
	id: normalizeOptionalLowercaseString(e.channelId) ?? e.channelId,
	aliases: e.aliases ?? [],
	label: e.label?.trim() || void 0,
	order: e.order ?? Number.MAX_SAFE_INTEGER
})).toSorted((e, t) => e.order - t.order || e.id.localeCompare(t.id, "en", { sensitivity: "base" }));
const CHAT_CHANNEL_ID_SET = new Set(BUNDLED_CHAT_CHANNEL_ENTRIES.map((e) => e.id));
/**
* Stable built-in channel order derived from generated bundled channel metadata.
*/
const CHAT_CHANNEL_ORDER = Object.freeze(BUNDLED_CHAT_CHANNEL_ENTRIES.map((e) => e.id));
const CHAT_CHANNEL_ALIASES = Object.fromEntries(BUNDLED_CHAT_CHANNEL_ENTRIES.flatMap((e) => e.aliases.map((t) => [t, e.id])));
function normalizeRuntimeBundledChatChannelId(e) {
	return listBundledChannelCatalogEntries().find((t) => t.id === e || t.aliases.includes(e))?.id ?? null;
}
function normalizeChatChannelId(e) {
	const t = normalizeOptionalLowercaseString(e);
	if (!t) return null;
	const n = CHAT_CHANNEL_ALIASES[t] ?? t;
	return CHAT_CHANNEL_ID_SET.has(n) ? n : normalizeRuntimeBundledChatChannelId(t);
}
//#endregion
//#region src/plugins/default-enablement.ts
/** True when a plugin should be enabled by default for a platform. */
function isPluginEnabledByDefaultForPlatform(e, t = process.platform) {
	if (e.enabledByDefault === true) return true;
	return e.enabledByDefaultOnPlatforms?.includes(t) === true;
}
//#endregion
//#region src/plugins/plugin-policy-id.ts
/**
* Canonicalizes a plugin id for comparison against `plugins.allow`, `plugins.deny`, and
* `plugins.entries`, which are lowercase-normalized when config is normalized. A manifest declares
* its id in whatever case its author chose, so policy must compare this derived key rather than the
* declared id. The declared id itself stays untouched: the loader matches it against the plugin's
* runtime export id, and rewriting it would break plugins whose export matches a mixed-case manifest.
*/
function normalizePluginPolicyId(e) {
	return normalizeOptionalLowercaseString(e) ?? "";
}
//#endregion
//#region src/plugins/slots.ts
/** Applies mutually exclusive plugin slot selection for memory and context-engine plugins. */
const DEFAULT_SLOT_BY_KEY = {
	memory: "memory-core",
	contextEngine: "legacy"
};
const PLUGIN_SLOT_KEYS = Object.keys(DEFAULT_SLOT_BY_KEY);
/** Returns the implicit plugin id that owns a slot before config overrides it. */
function defaultSlotIdForKey(e) {
	return DEFAULT_SLOT_BY_KEY[e];
}
/** Raw `plugins.slots[key]`: `none` turns the slot off, blank leaves it unset. */
function normalizeSlotValue(e) {
	const t = normalizeOptionalString(e);
	if (!t) return;
	if (normalizeOptionalLowercaseString(t) === "none") return null;
	return t;
}
function resolveSlotSelection(e, t) {
	const n = normalizeSlotValue(t);
	if (n === void 0) return {
		kind: "default",
		pluginId: defaultSlotIdForKey(e)
	};
	return n === null ? { kind: "off" } : {
		kind: "pinned",
		pluginId: n
	};
}
//#endregion
//#region src/plugins/config-normalization-shared.ts
/** Default plugin id normalizer for already-canonical ids. */
const identityNormalizePluginId = (e) => e.trim();
function normalizePluginConfigList(e, t) {
	return filterStringEntries(e).map((e) => t(e)).filter(Boolean);
}
function normalizeHookTimeoutMs(e) {
	return asSafeIntegerInRange(e, {
		min: 1,
		max: 6e5
	});
}
function normalizeHookTimeouts(e) {
	if (!isRecord(e)) return;
	const t = {};
	for (const [n, r] of Object.entries(e)) {
		const e = normalizeHookTimeoutMs(r);
		if (e !== void 0) t[n] = e;
	}
	return Object.keys(t).length > 0 ? t : void 0;
}
function normalizePluginHooks(e) {
	if (!isRecord(e)) return;
	const t = {};
	for (const n of ["allowPromptInjection", "allowConversationAccess"]) if (typeof e[n] === "boolean") t[n] = e[n];
	const n = normalizeHookTimeoutMs(e.timeoutMs);
	const r = normalizeHookTimeouts(e.timeouts);
	if (n !== void 0) t.timeoutMs = n;
	if (r !== void 0) t.timeouts = r;
	return Object.keys(t).length > 0 ? t : void 0;
}
function normalizePluginModelConfig(e, t) {
	if (!isRecord(e)) return;
	const n = {};
	if (typeof e.allowModelOverride === "boolean") n.allowModelOverride = e.allowModelOverride;
	for (const [r, i] of [["allowedModels", "hasAllowedModelsConfig"], ["allowedCompletionModels", "hasAllowedCompletionModelsConfig"]]) {
		if (r === "allowedCompletionModels" && t !== "llm") continue;
		const a = normalizeArrayBackedTrimmedStringList(e[r]);
		if (a) {
			n[i] = true;
			if (a.length > 0) n[r] = a;
		}
	}
	if (t === "llm") {
		for (const t of ["allowAuthProfileOverride", "allowAgentIdOverride"]) if (typeof e[t] === "boolean") n[t] = e[t];
	}
	return Object.keys(n).length > 0 ? n : void 0;
}
function normalizePluginEntries(e, t) {
	if (!isRecord(e)) return {};
	const n = {};
	for (const [r, i] of Object.entries(e)) {
		const e = t(r);
		if (!e) continue;
		if (!isRecord(i)) {
			n[e] = {};
			continue;
		}
		const a = i;
		n[e] = {
			...n[e],
			enabled: typeof a.enabled === "boolean" ? a.enabled : n[e]?.enabled,
			hooks: normalizePluginHooks(a.hooks) ?? n[e]?.hooks,
			subagent: normalizePluginModelConfig(a.subagent, "subagent") ?? n[e]?.subagent,
			llm: normalizePluginModelConfig(a.llm, "llm") ?? n[e]?.llm,
			config: "config" in a ? a.config : n[e]?.config
		};
	}
	return n;
}
/** Normalizes plugin config while allowing callers to resolve aliases first. */
function normalizePluginsConfigWithResolverCore(e, t = identityNormalizePluginId) {
	const n = resolveSlotSelection("memory", e?.slots?.memory);
	const resolvePolicyId = (e) => normalizePluginPolicyId(t(e));
	return {
		enabled: e?.enabled ?? true,
		allow: normalizePluginConfigList(e?.allow, resolvePolicyId),
		deny: normalizePluginConfigList(e?.deny, resolvePolicyId),
		loadPaths: normalizePluginConfigList(e?.load?.paths, identityNormalizePluginId),
		slots: {
			memory: n.kind === "off" ? null : n.pluginId,
			contextEngine: normalizeSlotValue(e?.slots?.contextEngine)
		},
		entries: normalizePluginEntries(e?.entries, resolvePolicyId)
	};
}
/**
* Enables an owner for any enabled channel; disables it only when all channels are off.
* Unspecified channels leave the plugin's own activation policy in control.
*/
function resolveChannelConfigEnablement(e, t, n) {
	const r = e?.channels;
	if (!r || n?.length === 0) return;
	const i = (n?.length ? n.map((e) => normalizeChatChannelId(e) ?? e) : [normalizeChatChannelId(t)]).map((e) => {
		const t = e ? r[e] : void 0;
		return isRecord(t) ? t.enabled : void 0;
	});
	if (i.includes(true)) return true;
	return i.every((e) => e === false) ? false : void 0;
}
//#endregion
//#region src/plugins/config-activation-shared.ts
function resolvePluginActivationStateShared(e) {
	const t = e.activationSource ?? {
		plugins: e.config,
		rootConfig: e.rootConfig
	};
	const n = normalizePluginPolicyId(e.id);
	let r;
	if (t.plugins.entries[n]?.enabled === true) r = "enabled in config";
	else if (e.origin === "bundled" && resolveChannelConfigEnablement(t.rootConfig, e.id, e.channelIds) === true) r = "channel enabled in config";
	else if (t.plugins.slots.memory === e.id) r = "selected memory slot";
	else if (t.plugins.contextEngineOwnerId !== void 0 ? t.plugins.contextEngineOwnerId === n : t.plugins.slots.contextEngine === e.id) r = "selected context engine slot";
	else if (e.origin !== "bundled" && t.plugins.allow.includes(n)) r = "selected in allowlist";
	const decision = (e, t = {}) => ({
		enabled: e !== "disabled",
		activated: e !== "disabled",
		explicitlyEnabled: r !== void 0,
		source: e,
		reason: void 0,
		...t
	});
	if (!e.config.enabled) return decision("disabled", { reason: "plugins disabled" });
	const i = normalizePluginPolicyId(e.id);
	if (e.config.deny.includes(i)) return decision("disabled", { reason: "blocked by denylist" });
	const a = e.config.entries[i];
	if (a?.enabled === false) return decision("disabled", { reason: "disabled in config" });
	if (resolveChannelConfigEnablement(t.rootConfig ?? e.rootConfig, e.id, e.channelIds) === false) return decision("disabled", { reason: "channel disabled in config" });
	const o = e.config.allow.includes(i);
	if (e.origin === "workspace" && !o && a?.enabled !== true && r !== "selected context engine slot") return decision("disabled", { reason: "workspace plugin (disabled by default)" });
	if (e.config.slots.memory === e.id) return decision("explicit", {
		explicitlyEnabled: true,
		reason: "selected memory slot"
	});
	if (e.config.contextEngineOwnerId !== void 0 ? e.config.contextEngineOwnerId === i : e.config.slots.contextEngine === e.id) return decision("explicit", {
		explicitlyEnabled: true,
		reason: "selected context engine slot"
	});
	if (e.allowBundledChannelExplicitBypassesAllowlist === true && r === "channel enabled in config") return decision("explicit", {
		explicitlyEnabled: true,
		reason: r
	});
	if (e.config.allow.length > 0 && !o) return decision("disabled", { reason: "not in allowlist" });
	if (r) return decision("explicit", {
		explicitlyEnabled: true,
		reason: r
	});
	const s = e.autoEnabledReason || (a?.enabled === true ? "enabled by effective config" : void 0) || (e.origin === "bundled" && resolveChannelConfigEnablement(e.rootConfig, e.id, e.channelIds) === true ? "channel configured" : void 0);
	if (e.origin === "bundled" && e.enabledByDefault === true && (!s || t.plugins.allow.length === 0 || t.plugins.allow.includes(i))) return decision("default", {
		explicitlyEnabled: false,
		reason: "bundled default enablement"
	});
	if (s) return decision("auto", {
		explicitlyEnabled: false,
		reason: s
	});
	if (e.origin === "bundled") return decision("disabled", {
		explicitlyEnabled: false,
		reason: "bundled (disabled by default)"
	});
	return decision("default");
}
//#endregion
//#region src/plugins/config-state.ts
const BUILT_IN_PLUGIN_ALIAS_LOOKUP = /* @__PURE__ */ new Map([
	["google-gemini-cli", "google"],
	["minimax-portal", "minimax"],
	["minimax-portal-auth", "minimax"]
]);
/** Normalizes user/config plugin ids into the canonical lowercase key form. */
function normalizePluginId(e) {
	const t = normalizePluginPolicyId(e);
	return BUILT_IN_PLUGIN_ALIAS_LOOKUP.get(t) ?? t;
}
/** Builds caller-owned policy without exposing the host's prepared objects. */
const createNormalizedPluginsConfig = (e) => normalizePluginsConfigWithResolverCore(e, normalizePluginId);
const normalizePluginsConfig = (e) => {
	if (preparedRuntimePluginsConfig && preparedRuntimePluginsConfig.source === e) return preparedRuntimePluginsConfig.value;
	const t = e ?? EMPTY_PLUGINS_CONFIG;
	if (!isDeeplyFrozenPlainData(t)) return createNormalizedPluginsConfig(t);
	let n = frozenPluginsConfigs.get(t);
	if (!n) {
		n = createSharedNormalizedPluginsConfig(t);
		frozenPluginsConfigs.set(t, n);
	}
	return n;
};
let preparedRuntimePluginsConfig;
const EMPTY_PLUGINS_CONFIG = Object.freeze({});
const frozenPluginsConfigs = /* @__PURE__ */ new WeakMap();
function createSharedNormalizedPluginsConfig(e) {
	const t = createNormalizedPluginsConfig(e);
	for (const e of Object.values(t.entries)) {
		Object.freeze(e.hooks?.timeouts);
		Object.freeze(e.hooks);
		Object.freeze(e.subagent?.allowedModels);
		Object.freeze(e.subagent);
		Object.freeze(e.llm?.allowedModels);
		Object.freeze(e.llm?.allowedCompletionModels);
		Object.freeze(e.llm);
		Object.freeze(e);
	}
	Object.freeze(t.entries);
	for (const e of [
		t.allow,
		t.deny,
		t.loadPaths,
		t.slots
	]) Object.freeze(e);
	return Object.freeze(t);
}
function resolveEffectivePluginActivationState(e) {
	return resolvePluginActivationStateShared({
		...e,
		config: e.config ?? normalizePluginsConfig(e.rootConfig?.plugins),
		allowBundledChannelExplicitBypassesAllowlist: true
	});
}
//#endregion
//#region src/config/runtime-config-capture-state.ts
const captures = /* @__PURE__ */ new WeakMap();
const immutableCaptures = /* @__PURE__ */ new WeakMap();
function getRuntimeConfigCapture(e) {
	return e ? captures.get(e) : void 0;
}
/** Freeze a selected runtime/source pair before its publication owner yields. */
function captureRuntimeConfigWithSource(e, t, n = e === runtimeConfigPublication.current?.config) {
	const r = e === t && isDeeplyFrozenPlainData(e);
	const i = r ? immutableCaptures.get(e) : void 0;
	if (i && getConfigResolutionFacts(i) === getConfigResolutionFacts(e) && getRuntimeConfigCapture(i)?.runtimeOwned === n) return i;
	const clone = (e) => freezeJsonSnapshot(cloneConfigWithResolutionFacts(e));
	const a = clone(e);
	const o = t === e ? a : clone(t);
	captures.set(a, {
		source: o,
		origin: e,
		runtimeOwned: n
	});
	if (o !== a) captures.set(o, {
		source: o,
		origin: t,
		runtimeOwned: t === runtimeConfigPublication.current?.config
	});
	if (r) immutableCaptures.set(e, a);
	return a;
}
//#endregion
//#region src/secrets/resolve-errors.ts
/** Error for failures that affect an entire configured secret provider. */
var SecretProviderResolutionError = class extends Error {
	constructor(e) {
		super(e.message, e.cause !== void 0 ? { cause: e.cause } : void 0);
		this.scope = "provider";
		this.name = "SecretProviderResolutionError";
		this.code = e.code;
		this.source = e.source;
		this.provider = e.provider;
	}
};
/** Error for failures limited to one SecretRef id under a provider. */
var SecretRefResolutionError = class extends Error {
	constructor(e) {
		super(e.message, e.cause !== void 0 ? { cause: e.cause } : void 0);
		this.scope = "ref";
		this.name = "SecretRefResolutionError";
		this.code = e.code;
		this.source = e.source;
		this.provider = e.provider;
		this.refId = e.refId;
	}
};
function isSecretResolutionError(e) {
	return e instanceof SecretProviderResolutionError || e instanceof SecretRefResolutionError;
}
/** Sanitized provider detail suitable for operator-facing diagnostics. */
function describeSecretResolutionOperatorDiagnostic(e) {
	if (e instanceof SecretRefResolutionError && e.code === "SECRET_REF_REDACTED_VALUE") return `Secret reference "${e.source}:${e.provider}:${e.refId}" resolves to a redaction placeholder`;
	if (e instanceof SecretProviderResolutionError && e.code === "SECRET_PROVIDER_PATH_SECURITY_UNVERIFIABLE") return "Windows path security could not be verified";
}
/** Sanitized recovery action suitable for operator-facing diagnostics. */
function describeSecretResolutionOperatorRecovery(e) {
	if (e instanceof SecretRefResolutionError && e.code === "SECRET_REF_REDACTED_VALUE") return "Run openclaw doctor --fix to repair a store-backed Gateway token; supply a real credential for other secrets, then restart the Gateway and reconnect or re-pair clients";
	if (!(e instanceof SecretProviderResolutionError) || e.code !== "SECRET_PROVIDER_PATH_SECURITY_UNVERIFIABLE") return;
	return e.source === "exec" ? "Restore Windows path security verification, or use an existing provider command whose owner and ACLs OpenClaw can verify" : "Restore Windows path security verification, or use an existing secret file whose owner and ACLs OpenClaw can verify";
}
function providerResolutionError(e) {
	return new SecretProviderResolutionError({
		...e,
		code: e.code ?? "SECRET_PROVIDER_UNAVAILABLE"
	});
}
function refResolutionError(e) {
	return new SecretRefResolutionError(e);
}
//#endregion
//#region src/config/redact-sentinel.ts
/** Display markers are never credential material. Match whole values, not substrings. */
const REDACTED_SENTINEL = "__OPENCLAW_REDACTED__";
const REDACTED_SECRET_VALUES = /* @__PURE__ */ new Set([
	REDACTED_SENTINEL,
	"REDACTED",
	"xoxb-REDACTED",
	"xapp-REDACTED",
	"***",
	"[redacted]",
	"[REDACTED]",
	"<redacted>",
	"[REDACTED_PRIVATE_KEY]",
	"[REDACTED CREDENTIAL]"
]);
function isRedactedSecretValue(e) {
	return typeof e === "string" && REDACTED_SECRET_VALUES.has(e.trim());
}
//#endregion
//#region packages/model-catalog-core/src/provider-id.ts
function normalizeProviderId(e) {
	return normalizeLowercaseStringOrEmpty(e);
}
//#endregion
//#region src/agents/workspace-dirs.ts
function listAgentWorkspaceDirs(e, t = process.env) {
	return [...new Set(listAgentIds(e).map((n) => resolveAgentWorkspaceDir(e, n, t)))];
}
//#endregion
//#region src/plugins/candidate-install-owner.ts
function createPluginInstallOwnerMetadata(e, t) {
	const n = Symbol.for(e);
	function read(e) {
		return e[n];
	}
	return {
		record: (e, r, i = false) => {
			if (r || i) Object.defineProperty(e, n, {
				configurable: t,
				enumerable: true,
				value: i ? { ambiguous: true } : { installOwner: r }
			});
			return e;
		},
		resolve: (e) => read(e)?.installOwner,
		isAmbiguous: (e) => read(e)?.ambiguous === true
	};
}
const { record: recordPluginCandidateInstallOwner, resolve: resolvePluginCandidateInstallOwner, isAmbiguous: isPluginCandidateInstallOwnerAmbiguous } = createPluginInstallOwnerMetadata("openclaw.pluginCandidateInstallOwner", true);
/** Editable installs have no reusable identity; npm replacement records invalidate installed code. */
function resolveImmutableInstallIdentity(e, t, n) {
	const r = t ? n[t] : void 0;
	if (e !== "global" || r?.source !== "npm" || !r.integrity) return;
	return JSON.stringify([
		t,
		r.installPath ?? "",
		r.resolvedSpec ?? r.spec ?? "",
		r.integrity,
		r.installedAt ?? ""
	]);
}
//#endregion
//#region packages/model-catalog-core/src/provider-model-id-normalization.ts
let currentManifestModelIdNormalizationPolicies;
/** Replace the process-local manifest normalization policy snapshot. */
function setCurrentManifestModelIdNormalizationPolicies(e) {
	currentManifestModelIdNormalizationPolicies = e;
}
//#endregion
//#region src/plugins/current-plugin-metadata-state.ts
/** Owns config identity reuse for the current immutable metadata snapshot. */
const currentPluginMetadataConfigIdentityCache = {
	add(e) {
		getProcessPluginCache().metadata.current.configIdentities.add(e);
	},
	clear() {
		getProcessPluginCache().metadata.current.configIdentities = /* @__PURE__ */ new WeakSet();
	},
	has(e) {
		return getProcessPluginCache().metadata.current.configIdentities.has(e);
	}
};
/** Stores the process-current plugin metadata snapshot and compatible config fingerprints. */
function setCurrentPluginMetadataSnapshotState(e, t, n, r, i = "operation", a, o = false, s) {
	const c = getProcessPluginCache().metadata.current;
	c.snapshot = e;
	c.owner = i;
	c.configFingerprint = e ? t : void 0;
	c.agentWorkspaceFingerprint = e ? s : void 0;
	c.envFingerprint = e ? a : void 0;
	c.defaultDiscoveryCompatible = Boolean(e && o);
	c.compatibleConfigFingerprints = e ? n : void 0;
	setCurrentManifestModelIdNormalizationPolicies(e ? r : void 0);
}
/** Reads the boot inventory without importing discovery into lightweight consumers. */
function getGatewayPluginMetadataSnapshot() {
	const e = getPluginCache();
	if (e.kind === "process" && e.metadata.current.owner === "gateway") return e.metadata.current.snapshot;
}
/** Captures the current snapshot and the policies eligible for process-wide publication. */
function getCurrentPluginMetadataSnapshotState() {
	const e = getProcessPluginCache().metadata.current;
	return {
		snapshot: e.snapshot,
		owner: e.owner,
		configFingerprint: e.configFingerprint,
		agentWorkspaceFingerprint: e.agentWorkspaceFingerprint,
		envFingerprint: e.envFingerprint,
		defaultDiscoveryCompatible: e.defaultDiscoveryCompatible,
		compatibleConfigFingerprints: e.compatibleConfigFingerprints
	};
}
//#endregion
//#region src/plugins/installed-plugin-index-install-owner.ts
function resolveInstalledPluginIndexInstallOwner(e) {
	const t = e;
	return t.installOwnerAmbiguous ? void 0 : t.installOwner || void 0;
}
//#endregion
//#region src/agents/auth-profiles/persisted-rows-receipt.ts
const rowsReceipt = {
	name: "auth-profiles.rows",
	read: (e) => isRecord(e) ? e : void 0
};
function publishAuthProfileRowsChanged(e) {
	publishSqliteDatabaseAdmission(e, rowsReceipt, {});
}
//#endregion
//#region src/state/config-machine-state-row.ts
const catalogReceipt = {
	name: "model-catalog.remote",
	read: (e) => isRecord(e) ? e : void 0
};
const ttsPathAdmission = {
	name: "state.tts-prefs-path",
	read(e) {
		if (!isRecord(e)) return;
		const t = e.row;
		if (t === void 0) return { row: void 0 };
		if (isRecord(t) && typeof t.value_json === "string" && typeof t.updated_at_ms === "number") return { row: {
			value_json: t.value_json,
			updated_at_ms: t.updated_at_ms
		} };
	}
};
/** Named row owners publish only the facts covered by this mutation. */
function publishConfigMachineStateRow(e, t, n) {
	if (t === "tts.prefsPath") publishSqliteDatabaseAdmission(e, ttsPathAdmission, { row: n });
	else if (t === "authProfiles.store" || t === "authProfiles.state") publishAuthProfileRowsChanged(e);
	else if (t === "modelCatalog.remote.v3" || t === "modelCatalog.remote.v2" || t === "modelCatalog.remote") publishSqliteDatabaseAdmission(e, catalogReceipt, {});
}
function normalizeConfigMachineStateKey(e) {
	const t = e.trim();
	if (!t) throw new Error("config machine state key must not be empty");
	return t;
}
function readConfigMachineStateRowInDatabase(e, t) {
	const n = normalizeConfigMachineStateKey(t);
	const r = n === "tts.prefsPath" ? getSqliteDatabaseAdmission(e, ttsPathAdmission) : void 0;
	if (r) return r.row;
	if (!tableExists(e, "config_machine_state")) return;
	const i = getNodeSqliteKysely(e);
	const a = executeSqliteQueryTakeFirstSync(e, i.selectFrom("config_machine_state").select(["value_json", "updated_at_ms"]).where("state_key", "=", n));
	if (isMainThread && n === "tts.prefsPath") publishConfigMachineStateRow(e, n, a);
	return a;
}
//#endregion
//#region src/state/config-machine-state.ts
function readConfigMachineState(e, t = {}, n = {}) {
	const read = ({ db: t }) => {
		const n = readConfigMachineStateRowInDatabase(t, e);
		return n ? JSON.parse(n.value_json) : void 0;
	};
	return n.artifactPreservingReadOnly ? withExistingOpenClawStateDatabaseArtifactPreservingReadOnly(read, t) : withExistingOpenClawStateDatabaseReadOnly(read, t);
}
//#endregion
//#region src/plugins/install-root-context.ts
const pluginInstallRootContext = resolveGlobalSingleton(Symbol.for("openclaw.pluginInstallRootContext"), () => new AsyncLocalStorage());
/** Resolve the ordinary operator-owned plugin roots before a run redirects state. */
function resolvePluginInstallRoots(e = process.env, t = os.homedir) {
	const n = resolveConfigDir(e, t);
	return Object.freeze({
		extensionsDir: path.join(n, "extensions"),
		gitDir: path.join(n, "git"),
		npmDir: path.join(n, "npm"),
		stateDir: resolveStateDir(e, t)
	});
}
/** Return run-pinned install roots, or resolve the caller's ordinary roots. */
function resolveActivePluginInstallRoots(e = process.env, t = os.homedir) {
	return pluginInstallRootContext.getStore() ?? resolvePluginInstallRoots(e, t);
}
/** Artifact paths do not need the state directory's legacy-location filesystem probes. */
function resolveActivePluginInstallDir(e, t = process.env, n = os.homedir) {
	const r = pluginInstallRootContext.getStore();
	return r ? r[`${e}Dir`] : path.join(resolveConfigDir(t, n), e);
}
/** Return whether the current run pinned operator-owned plugin install roots. */
function hasActivePluginInstallRoots() {
	return pluginInstallRootContext.getStore() !== void 0;
}
//#endregion
//#region src/plugins/plugin-metadata-snapshot-readers.ts
const readerLifetime = resolveGlobalSingleton(Symbol.for("openclaw.pluginMetadataSnapshotReaderCustody"), () => ({ owners: 0 }));
const readerKeys = [
	"adoptCurrentPluginMetadataSnapshotIfAbsent",
	"getCurrentPluginMetadataSnapshot",
	"resolvePluginMetadataSnapshot",
	"loadPluginMetadataSnapshot",
	"listOpenClawPluginManifestMetadata",
	"listKnownProviderAuthEnvVarNamesCore"
];
const snapshotReaderSlot = resolveGlobalSingleton(Symbol.for("openclaw.pluginMetadataSnapshotReaders"), () => ({}), (e) => {
	if (!readerLifetime.owners) for (const t of readerKeys) delete e[t];
}, "close-only");
/** Called at module evaluation; a retained Gateway keeps its registered readers. */
function registerPluginMetadataSnapshotReaders(e) {
	Object.assign(snapshotReaderSlot, e);
}
//#endregion
//#region src/plugins/plugin-source-capture-context.ts
function getPluginSourceCaptureStorage() {
	return getPluginExecutionFrame()?.sourceCaptureStorage;
}
function resolvePluginSourceCaptureStorage(e, t) {
	const n = e === void 0 ? getPluginSourceCaptureStorage() : void 0;
	return Object.freeze({
		stateDir: path.resolve(e ?? n?.stateDir ?? resolveStateDir()),
		placement: t ?? n?.placement ?? "state"
	});
}
/** Executable CLI ownership follows profile selection to each acquired capture root. */
const pluginSourceCaptureMaintenance = resolveGlobalSingleton(Symbol.for("openclaw.pluginSourceCaptureMaintenance"), () => new AsyncLocalStorage());
const pluginSourceCaptureDirectory = new AsyncLocalStorage();
/** Preparation borrows its existing capture domain; host-local recovery owns its own domain. */
const pluginRecoveryCapture = new AsyncLocalStorage();
//#endregion
//#region src/plugins/plugin-source-capture-native-loads.ts
/** The process-wide capture owner installs this observer once. */
const observedNativeLoadPaths = /* @__PURE__ */ new Set();
const nativeLoadObservers = /* @__PURE__ */ new Set();
function recordPluginNativeLoad(e) {
	observedNativeLoadPaths.add(process.platform === "win32" ? normalizeWindowsPathPreservingCase(e) : e);
}
function observePluginNativeLoads() {
	const e = process.dlopen.bind(process);
	process.dlopen = (...t) => {
		try {
			const e = fsSync.realpathSync.native(t[1]);
			recordPluginNativeLoad(e);
			for (const t of nativeLoadObservers) t(e);
		} catch {}
		return e(...t);
	};
	return observedNativeLoadPaths;
}
function createPluginNativeCaptureCustody(e) {
	const t = observePluginNativeLoads();
	const n = /* @__PURE__ */ new Map();
	const r = /* @__PURE__ */ new Set();
	const i = /* @__PURE__ */ new Set();
	/** Reclamation owns an existing native token until its captured payload is gone. */
	async function reclaimInstance(t, i, a) {
		const o = path.join(t, SQLITE_STAGING_TOKEN_FILES[0]);
		const s = SQLITE_STAGING_TOKEN_FILES.map((e) => fsSync.lstatSync(path.join(t, e), { throwIfNoEntry: false }));
		const c = s[0];
		const l = path.join(t, "captures");
		const u = fsSync.lstatSync(l, { throwIfNoEntry: false });
		if (process.getuid && i.uid !== process.getuid() || !c || s.some((e) => e && (!e.isFile() || e.nlink !== 1 || process.getuid && e.uid !== process.getuid())) || u && !u.isDirectory()) return;
		const unchanged = () => {
			const e = fsSync.lstatSync(t);
			const n = fsSync.lstatSync(o);
			return e.dev === i.dev && e.ino === i.ino && e.isDirectory() && n.isFile() && n.nlink === 1 && n.dev === c.dev && n.ino === c.ino;
		};
		const d = acquireSqliteStagingToken(t, "reclaim");
		let f = false;
		const p = [];
		e.add(t);
		try {
			if (!unchanged()) return;
			const e = path.join(t, "native");
			const i = fsSync.lstatSync(e, { throwIfNoEntry: false });
			await a?.assertCurrent();
			if (!unchanged()) return;
			await fsPromises.rm(l, {
				recursive: true,
				force: true
			});
			let o = Boolean(i);
			if (i?.isDirectory() && a) {
				for (const t of await fsPromises.readdir(e, { withFileTypes: true })) {
					const i = path.join(e, t.name);
					if (!t.isDirectory()) continue;
					await a.assertCurrent();
					if (!unchanged()) return;
					const contained = (e) => e.startsWith(i + path.sep);
					if ([...a.retainedPaths].some(contained) || [...n.keys()].some(contained)) continue;
					r.add(i);
					try {
						await fsPromises.rm(i, {
							recursive: true,
							force: true
						});
						a.removed.push(i);
					} finally {
						r.delete(i);
					}
				}
				o = (await fsPromises.readdir(e)).length > 0;
			}
			await a?.assertCurrent();
			if (!unchanged()) return;
			d(true);
			f = true;
			if (!o) {
				await a?.assertCurrent();
				if (unchanged()) await fsPromises.rm(t, {
					recursive: true,
					force: true
				});
			}
		} catch (e) {
			p.push(e);
		} finally {
			try {
				if (!f) d();
			} catch (e) {
				p.push(e);
			} finally {
				e.delete(t);
			}
			throwSqliteLifecycleErrors(p, "Plugin source reclamation and cleanup failed");
		}
	}
	return {
		reclaimInstance,
		/** Independent inventories and loaded modules can retain the same native namespace. */
		isPluginSourceCaptureRetained(r) {
			return [...e, ...i].some((e) => isPathInside$2(e, r) || isPathInside$2(r, e)) || [...n.keys(), ...t].some((e) => isPathInside$2(r, e));
		},
		/** Physical module lifetime outlives registration and CommonJS cache eviction. */
		retainLoadedPluginSourceCapture(n) {
			if (![...t].some((e) => isPathInside$2(n, e))) return false;
			const r = [...e].find((e) => isPathInside$2(e, n)) ?? n;
			if (![...i].some((e) => isPathInside$2(e, r) || isPathInside$2(r, e))) process.emitWarning(`Plugin source capture cleanup: retained-by-loaded-module: ${r}; cleanup deferred until the next startup`);
			i.add(r);
			return true;
		},
		/** Warm generations retain superseded snapshots until their local cache retires. */
		retainPluginNativeCapturePath(e) {
			const t = path.resolve(e);
			if ([...r].some((e) => t.startsWith(e + path.sep))) throw new Error("Plugin native capture is being reclaimed");
			n.set(t, (n.get(t) ?? 0) + 1);
			let i = false;
			return () => {
				if (i) return;
				i = true;
				const e = n.get(t);
				if (e === 1) n.delete(t);
				else n.set(t, e - 1);
			};
		}
	};
}
//#endregion
//#region src/plugins/plugin-source-capture-directory.ts
const CAPTURE_GRACE_MS = 36e5;
const { instances, ownedRoots, reclaimInstance, isPluginSourceCaptureRetained, retainLoadedPluginSourceCapture, retainPluginNativeCapturePath, sweeps } = resolveGlobalSingleton(Symbol.for("openclaw.pluginSourceCaptureInstances"), () => {
	const e = /* @__PURE__ */ new Set();
	const t = createPluginNativeCaptureCustody(e);
	process.once("exit", () => {
		for (const [e, t] of instances) retireInstanceForExit(e, t);
	});
	return {
		instances: /* @__PURE__ */ new Map(),
		ownedRoots: e,
		...t,
		sweeps: /* @__PURE__ */ new Map()
	};
});
/** Explicit exits cannot await generation disposal. These native leases belong
* only to this exiting process; worker overrides remain with their parent. */
function retireInstanceForExit(e, t) {
	try {
		const n = retireInstance(e, t);
		if (n) removeInstanceSync(n, t.pendingNative);
	} catch (e) {
		process.stderr.write(`Plugin source capture exit cleanup failed: ${String(e)}\n`);
	}
}
function retireInstance(e, t) {
	if (t.root && retainLoadedPluginSourceCapture(t.root)) {
		t.references.clear();
		scheduleCaptureCleanup(e, t);
		return;
	}
	t.closing = true;
	let n = t.root;
	try {
		t.token?.(true);
	} catch (e) {
		ignoreMissingPath(e);
		t.token?.();
		n = void 0;
	}
	if (t.root) ownedRoots.delete(t.root);
	t.references.clear();
	if (instances.get(e) === t) instances.delete(e);
	t.releaseSignalExit?.();
	scheduleCaptureCleanup(e, t);
	return n;
}
function warn(e) {
	process.emitWarning(`Plugin source capture cleanup: ${String(e)}`);
}
function removeInstanceSync(e, t = []) {
	if (retainLoadedPluginSourceCapture(e)) return;
	fsSync.rmSync(path.join(e, "captures"), {
		recursive: true,
		force: true
	});
	for (const e of t) fsSync.rmSync(e, {
		recursive: true,
		force: true
	});
	const n = path.join(e, "native");
	if (!fsSync.existsSync(n) || fsSync.readdirSync(n).length === 0) fsSync.rmSync(e, {
		recursive: true,
		force: true
	});
}
async function reclaimInstances(e, t, n = false, r, i) {
	let a;
	try {
		a = await fsPromises.readdir(e, { withFileTypes: true });
	} catch (e) {
		ignoreMissingPath(e);
		return;
	}
	if (a.length === 0) return;
	const o = Date.now() - CAPTURE_GRACE_MS;
	const lstatIfPresent = (e) => fsPromises.lstat(e).catch(ignoreMissingPath);
	for (const s of a) {
		if (!s.isDirectory() || n && !isLegacyPluginSourceCaptureName(s.name) || i && !s.name.startsWith(i)) continue;
		const a = path.join(e, s.name);
		try {
			const e = await fsPromises.lstat(a);
			const t = n ? Math.max(e.mtimeMs, e.ctimeMs, e.birthtimeMs) : e.mtimeMs;
			if (!e.isDirectory() || t > o && !r?.startup) continue;
			const s = await fsPromises.realpath(a);
			if (ownedRoots.has(s) || retainLoadedPluginSourceCapture(s)) continue;
			const c = path.join(s, SQLITE_STAGING_TOKEN_FILES[0]);
			const l = await lstatIfPresent(path.join(s, "native"));
			const u = await lstatIfPresent(c);
			if (n && u) continue;
			if (!u) {
				if (i || t > o) continue;
				if (l) continue;
				await r?.assertCurrent();
				const n = fsSync.lstatSync(s);
				if (n.isDirectory() && n.dev === e.dev && n.ino === e.ino && n.uid === e.uid && (!process.getuid || n.uid === process.getuid())) await fsPromises.rm(s, {
					recursive: true,
					force: true
				});
				continue;
			}
			await reclaimInstance(s, e, r);
		} catch (e) {
			if (!hasErrnoCode(e, "ENOENT") && !isSqliteLockError(e)) t(e);
		}
	}
}
/** Coalesce active scans and report one summary per sweep. */
function sweepPluginSourceCaptureDirectories(e) {
	const t = path.resolve(resolvePluginSourceCapturesDirectory(e));
	let n = sweeps.get(t);
	if (!n) {
		let r = 0;
		let i;
		const recordFailure = (e) => {
			if (r++ === 0) i = e;
		};
		n = reclaimInstances(t, recordFailure).catch(recordFailure).then(() => reclaimInstances(tmpdir(), recordFailure, false, void 0, resolvePluginSourceCaptureFallbackPrefix(e))).catch(recordFailure).then(async () => {
			const t = /* @__PURE__ */ new Set();
			for (const n of [path.join(e, "tmp"), tmpdir()]) try {
				const e = await fsPromises.realpath(n);
				if (!t.has(e)) {
					t.add(e);
					await reclaimInstances(e, recordFailure, true);
				}
			} catch (e) {
				if (!hasErrnoCode(e, "ENOENT")) recordFailure(e);
			}
		}).then(() => {
			if (r === 0) return;
			warn(`${r} cleanup failure(s) in ${t}; will retry. First: ${formatErrorMessage(i)}`);
		}).finally(() => sweeps.delete(t));
		sweeps.set(t, n);
	}
	return n;
}
function scheduleCaptureCleanup(e, t) {
	const n = [...t.references].findLast((e) => e.scheduler && !e.scheduler.signal.aborted)?.scheduler ?? void 0;
	if (t.scheduler === n) return;
	t.scheduler = n;
	t.cleanupScope?.beginClose();
	t.cleanupScope = void 0;
	if (!n || t.storage.placement === "temporary") return;
	const r = n.scope();
	t.cleanupScope = r;
	r.signal.addEventListener("abort", () => scheduleCaptureCleanup(e, t), { once: true });
	runInDetachedAsyncContext(() => r.schedule({
		id: `plugin-source-captures:${e}`,
		delayMs: CAPTURE_GRACE_MS,
		everyMs: CAPTURE_GRACE_MS,
		run: () => sweepPluginSourceCaptureDirectories(t.storage.stateDir)
	}));
}
//#endregion
//#region src/plugins/runtime-close-error.ts
const PluginRuntimeCloseRetainedError = resolveGlobalSingleton(Symbol.for("openclaw.pluginRuntimeCloseRetainedError"), () => class RetainedRuntimeError extends Error {
	constructor(e) {
		super("Plugin runtime still owns resources; inspect cleanup failures before retrying Gateway close.", { cause: e });
		this.name = "PluginRuntimeCloseRetainedError";
	}
});
/** The resource owner finished cleanup and returned callback failures for observation. */
const PluginRuntimeCloseCompletedError = resolveGlobalSingleton(Symbol.for("openclaw.pluginRuntimeCloseCompletedError"), () => class CompletedRuntimeError extends AggregateError {});
//#endregion
//#region src/plugins/plugin-metadata-lifecycle.ts
const pluginMetadataProcessMemoClears = /* @__PURE__ */ new Map();
const gatewayMetadata = resolveGlobalSingleton(Symbol.for("openclaw.gatewayPluginMetadataOwner"), () => ({}));
/** Registers a metadata clear hook with the lifetime of its facts. */
function registerPluginMetadataProcessMemoLifecycleClear(e, t = { owner: "process" }) {
	pluginMetadataProcessMemoClears.set(e, t.owner);
}
//#endregion
//#region src/plugins/bundled-discovery-state.ts
function parseBundledDiscoveryMode(e) {
	return e === "compat" || e === "allowlist" ? e : void 0;
}
function resolveBundledDiscoveryOptions(e) {
	return e.path || e.database || !hasActivePluginInstallRoots() ? e : {
		...e,
		env: {
			...e.env ?? process.env,
			OPENCLAW_STATE_DIR: resolveActivePluginInstallRoots(e.env).stateDir
		}
	};
}
function readBundledDiscoveryMode(e = {}, t = {}) {
	const n = resolveBundledDiscoveryOptions(e);
	return parseBundledDiscoveryMode(readConfigMachineState("plugins.bundledDiscovery", n, t));
}
const discoveryState = resolveGlobalSingleton(Symbol.for("openclaw.bundledDiscoveryMode"), () => ({ snapshotModes: /* @__PURE__ */ new WeakMap() }));
registerPluginMetadataProcessMemoLifecycleClear(() => {
	clearBundledDiscoveryModeMemo();
});
function resolveBundledDiscoveryMemoKey(e) {
	const t = hasActivePluginInstallRoots() ? {
		...e,
		OPENCLAW_STATE_DIR: resolveActivePluginInstallRoots(e).stateDir
	} : e;
	return resolveOpenClawStateSqlitePath(t);
}
/**
* Callers loading a registry with an explicit env pass it so the mode comes
* from that env's state root; omitting it reads the process root. Pinned
* install roots win over both, matching readBundledDiscoveryMode.
*/
function readBundledDiscoveryModeMemoized(e = process.env, t = {}, n) {
	const r = e === process.env ? {} : { env: e };
	const i = t.artifactPreservingReadOnly || isArtifactPreservingStateRead() ? getActiveOpenClawStateDatabaseReadSnapshot(resolveBundledDiscoveryOptions(r)) : void 0;
	if (i || t.artifactPreservingReadOnly) {
		const e = i && discoveryState.snapshotModes.get(i);
		if (e) return e.value;
		const n = readBundledDiscoveryMode(r, t);
		if (i) discoveryState.snapshotModes.set(i, { value: n });
		return n;
	}
	const a = resolveBundledDiscoveryMemoKey(e);
	if (discoveryState.memoized?.key !== a) {
		const t = getPluginCache();
		const r = t.preparedBundledDiscoveryModes.get(a);
		if (r && "value" in r) {
			getPluginCacheRetirementSignal(t).throwIfAborted();
			discoveryState.memoized = {
				key: a,
				value: r.value.value
			};
		} else discoveryState.memoized = {
			key: a,
			value: n ? parseBundledDiscoveryMode(n(a)) : readBundledDiscoveryMode(e === process.env ? {} : { env: e })
		};
	}
	return discoveryState.memoized.value;
}
/**
* Clears the memo after a machine-state write so same-process readers observe
* the new mode. Without this, doctor's migration could cache the pre-migration
* absent mode and rebuild plugin indexes against stale strict-gate decisions.
*/
function clearBundledDiscoveryModeMemo() {
	discoveryState.memoized = void 0;
	discoveryState.snapshotModes = /* @__PURE__ */ new WeakMap();
	for (const e of /* @__PURE__ */ new Set([getPluginCache(), getProcessPluginCache()])) e.preparedBundledDiscoveryModes.clear();
}
//#endregion
//#region src/plugins/compat/activation-hint-records.ts
const ACTIVATION_HINT_METADATA = {
	status: "active",
	owner: "plugin-execution",
	docsPath: "/plugins/manifest",
	diagnostics: ["activation plan compat reason"]
};
const ACTIVATION_HINT_COMPAT_RECORDS = [
	{
		code: "activation-agent-harness-hint",
		...ACTIVATION_HINT_METADATA,
		replacement: "top-level `cliBackends[]` for CLI aliases and future `agentRuntime` ownership metadata",
		surfaces: ["activation.onAgentHarnesses", "activation planner"]
	},
	{
		code: "activation-provider-hint",
		...ACTIVATION_HINT_METADATA,
		replacement: "`providers[]` manifest ownership",
		surfaces: ["activation.onProviders", "activation planner"]
	},
	{
		code: "activation-channel-hint",
		...ACTIVATION_HINT_METADATA,
		replacement: "`channels[]` manifest ownership",
		surfaces: ["activation.onChannels", "activation planner"]
	},
	{
		code: "activation-command-hint",
		...ACTIVATION_HINT_METADATA,
		replacement: "`commandAliases` or command contribution metadata",
		surfaces: ["activation.onCommands", "activation planner"]
	},
	{
		code: "activation-route-hint",
		...ACTIVATION_HINT_METADATA,
		replacement: "HTTP route contribution metadata",
		surfaces: ["activation.onRoutes", "activation planner"]
	},
	{
		code: "activation-config-path-hint",
		...ACTIVATION_HINT_METADATA,
		replacement: "manifest contribution ownership for root config surfaces",
		surfaces: ["activation.onConfigPaths", "startup plugin selection"]
	},
	{
		code: "activation-capability-hint",
		...ACTIVATION_HINT_METADATA,
		replacement: "manifest contribution ownership",
		surfaces: ["activation.onCapabilities", "activation planner"]
	}
];
//#endregion
//#region src/plugins/compat/agent-harness-records.ts
const AGENT_HARNESS_TOOL_CONSTRUCTION_COMPAT_RECORD = {
	code: "agent-harness-sync-tool-construction",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-04",
	warningStarts: "2026-10-04",
	removeAfter: "2026-12-31",
	replacement: "Await hostCapabilities.createToolSurfaceAsync, createOpenClawCodingToolsAsync, or createAgentHarnessToolSurfaceRuntimeAsync with the existing arguments. Released synchronous factories retain their array results and completion timing through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
	docsPath: "/plugins/sdk-migration/compatibility-policy#harness-tool-construction",
	surfaces: [
		"AgentHarnessHostCapabilities.createToolSurface",
		"openclaw/plugin-sdk/agent-harness.createOpenClawCodingTools",
		"openclaw/plugin-sdk/agent-harness-tool-runtime.createAgentHarnessToolSurfaceRuntime"
	],
	diagnostics: ["TypeScript @deprecated annotations and migration documentation; bounded capability-family warnings on legacy preparation"]
};
const AGENT_HARNESS_COMPAT_RECORDS = [
	AGENT_HARNESS_TOOL_CONSTRUCTION_COMPAT_RECORD,
	{
		code: "plugin-unused-registration-capabilities",
		status: "removed",
		owner: "sdk",
		removeAfter: "2026-10-18",
		replacement: "Use directly loadable media references, provider/backend-owned textTransforms, or externally managed AgentsAPI self_hosted environments. There is no replacement global overlay or controller registrar; migrate controller-owned sessions on the previous host first.",
		docsPath: "/plugins/sdk-migration/removed-surfaces#hosted-media-global-transforms-and-executor-controllers",
		surfaces: [
			"OpenClawPluginApi.registerHostedMediaResolver",
			"OpenClawPluginApi.registerTextTransforms",
			"OpenClawPluginApi.registerAgentExecutorController"
		],
		diagnostics: ["TypeScript reports removed API members; saved controller state and configuration require migration"]
	},
	{
		code: "codex-app-server-standalone-extension-runner",
		status: "active",
		owner: "agent-runtime",
		replacement: "Register transforms with api.registerAgentToolResultMiddleware and contracts.agentToolResultMiddleware. Retain the standalone runner and its types until supported published Codex packages no longer import it; @openclaw/codex@2026.10.4 still calls the default empty runner.",
		docsPath: "/plugins/sdk-migration/removed-surfaces#codex-app-server-extension-factories",
		surfaces: [
			"openclaw/plugin-sdk/agent-harness.createCodexAppServerToolResultExtensionRunner",
			"openclaw/plugin-sdk/agent-harness-runtime.createCodexAppServerToolResultExtensionRunner",
			"openclaw/plugin-sdk/agent-harness-runtime.CodexAppServerExtensionContext",
			"openclaw/plugin-sdk/agent-harness-runtime.CodexAppServerExtensionFactory",
			"openclaw/plugin-sdk/agent-harness-runtime.CodexAppServerExtensionRuntime",
			"openclaw/plugin-sdk/agent-harness-runtime.CodexAppServerToolResultEvent",
			"openclaw/plugin-sdk/agent-harness-runtime.CodexAppServerToolResultHandlerResult"
		],
		diagnostics: ["plugin SDK compatibility registry and migration guide"]
	},
	{
		code: "agent-harness-tool-argument-redaction",
		status: "removed",
		owner: "agent-runtime",
		removeAfter: "2026-10-10",
		replacement: "None; pass tool arguments unchanged. Secret masking belongs in diagnostics.",
		docsPath: "/plugins/sdk-migration/removed-surfaces#tool-argument-redaction",
		surfaces: ["openclaw/plugin-sdk/agent-harness-runtime.sanitizeToolArgs"],
		diagnostics: ["plugin SDK shipped-surface guard and migration guide"]
	},
	{
		code: "agent-harness-sdk-alias",
		status: "deprecated",
		owner: "agent-runtime",
		deprecated: "2026-04-25",
		warningStarts: "2026-04-25",
		replacement: "none yet; retain until a harness subpath ships and external migration is proven",
		docsPath: "/plugins/sdk-agent-harness",
		surfaces: ["openclaw/plugin-sdk/agent-harness", "openclaw/plugin-sdk/agent-harness-runtime"],
		diagnostics: ["plugin SDK compatibility warning"]
	}
];
//#endregion
//#region src/plugins/compat/agent-list-runtime-projection-records.ts
const AGENT_LIST_RUNTIME_PROJECTION_COMPAT_RECORDS = [{
	code: "agent-list-runtime-projection",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-02",
	warningStarts: "2026-10-02",
	removeAfter: "2027-01-02",
	replacement: "Canonical `cfg.agents.entries`, or `listAgentIds` / `resolveAgentConfig` from `openclaw/plugin-sdk/agent-runtime`",
	docsPath: "/plugins/sdk-migration/how-to-migrate#agent-roster-config",
	surfaces: ["non-enumerable runtime OpenClawConfig.agents.list projection"],
	diagnostics: ["plugin compatibility registry and migration documentation; no runtime warnings"]
}];
//#endregion
//#region src/plugins/compat/assistant-text-phase-terminal-hint-record.ts
const ASSISTANT_TEXT_PHASE_TERMINAL_HINT_COMPAT_RECORD = {
	code: "assistant-text-phase-terminal-hint",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-11",
	warningStarts: "2026-10-11",
	removalGate: "stable-deprecation-period",
	replacement: "Omit textPhaseRequiresTerminal; unphased text is never retroactively classified.",
	docsPath: "/concepts/streaming#text-phases-and-final-replies",
	surfaces: ["AssistantMessage.openclawDelivery.textPhaseRequiresTerminal"],
	diagnostics: ["TypeScript @deprecated annotation; no runtime warning for the ignored field"]
};
//#endregion
//#region src/plugins/compat/async-sqlite-preparation-records.ts
const PREPARATION = {
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-13",
	warningStarts: "2026-10-13",
	removeAfter: "2026-12-31",
	diagnostics: ["TypeScript @deprecated annotations and actionable once-per-plugin-and-capability-family warnings per process on legacy use"]
};
const ASYNC_SQLITE_PREPARATION_COMPAT_RECORDS = [
	{
		...PREPARATION,
		code: "provider-model-capabilities-sync-read",
		replacement: "Await loadOpenRouterModelCapabilities(modelId), then read getLoadedOpenRouterModelCapabilities(modelId). The synchronous getter remains compatible through 2026-12-31; removal ships in the first January 2027 stable release.",
		docsPath: "/plugins/sdk-migration/sqlite-async",
		surfaces: ["openclaw/plugin-sdk/provider-stream.getOpenRouterModelCapabilities", "openclaw/plugin-sdk/provider-stream-family.getOpenRouterModelCapabilities"]
	},
	{
		...PREPARATION,
		code: "session-store-sync-readers",
		replacement: "Await getSessionEntryAsync, getConversationSessionAsync, readAmbientTranscriptWatermarkAsync, and loadTranscriptEvents. Synchronous readers retain their results during the stable deprecation period. Current entry lookup is not a substitute for historical transcript-key resolution.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-session-and-transcript-readers",
		surfaces: [
			"openclaw/plugin-sdk/session-store-runtime.getSessionEntry",
			"openclaw/plugin-sdk/session-store-runtime.getConversationSession",
			"openclaw/plugin-sdk/session-store-runtime.readAmbientTranscriptWatermark",
			"openclaw/plugin-sdk/session-store-runtime.loadTranscriptEventsSync",
			"api.runtime.agent.session.getSessionEntry",
			"api.runtime.agent.session.getConversationSession"
		]
	},
	{
		...PREPARATION,
		code: "transcript-session-key-sync-resolution",
		replacement: "Await resolveTranscriptSessionKeyBySessionIdAsync from session-store-runtime. It preserves exact historical session-window resolution, including session IDs no longer selected by the current entry.",
		docsPath: "/plugins/sdk-migration/async-transcript-and-tts",
		surfaces: ["openclaw/plugin-sdk/session-store-runtime.resolveTranscriptSessionKeyBySessionId"]
	},
	{
		...PREPARATION,
		code: "pending-input-sync-completion",
		replacement: "Await SessionPendingInputReceipt.completeAsync or UserTurnTranscriptRecorder.completeProcessingAsync before publishing completion. Await waitForPendingInputSettlement when supplied before releasing session admission. Bundled plugins target the current host and use the async companions directly; do not retry async failures synchronously.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-session-transcript-persistence",
		surfaces: ["SessionPendingInputReceipt.complete", "UserTurnTranscriptRecorder.completeProcessing"]
	},
	{
		...PREPARATION,
		code: "session-catalog-sync-preparation",
		replacement: "Await readSessionTranscriptCatalogTitleAsync, prepareSessionCatalogSourceActorProjector, and prepareSessionCatalogGitHubLinker from session-transcript-runtime. Project the prepared facts synchronously and retain current disclosure authority at publication.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#prepare-session-catalog-identities",
		surfaces: [
			"openclaw/plugin-sdk/session-transcript-runtime.readSessionTranscriptCatalogTitle",
			"openclaw/plugin-sdk/session-transcript-runtime.createSessionCatalogSourceActorProjector",
			"openclaw/plugin-sdk/session-transcript-runtime.createSessionCatalogGitHubLinker"
		]
	},
	{
		...PREPARATION,
		code: "channel-policy-sync-preparation",
		replacement: "Await resolveCommandAuthorizationAsync, resolveStoredModelOverrideAsync, resolveCommandArgMenuAsync, inspectConversationBindingAsync, and loadExecApprovalsReadOnlyAsync. Prepared results never replace live authorization at command execution or external side effects.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#migrate-inspection-authorization-and-approval-factories",
		surfaces: [
			"openclaw/plugin-sdk/command-auth-native.resolveCommandAuthorization",
			"openclaw/plugin-sdk/command-auth-native.resolveStoredModelOverride",
			"openclaw/plugin-sdk/command-auth-native.resolveCommandArgMenu",
			"openclaw/plugin-sdk/conversation-binding-inspection-runtime.inspectConversationBinding",
			"openclaw/plugin-sdk/exec-approvals-runtime.loadExecApprovals"
		]
	},
	{
		...PREPARATION,
		code: "approval-routing-sync-preparation",
		replacement: "Use the Async-suffixed approval factories and resolvers, then await their returned eligibility and routing callbacks. Reuse resolveApprovalRequestSessionDeliveryAsync facts for one route decision. Factories remain synchronous; Async names describe their awaited callbacks. Keep live approval and delivery authority at the effect boundary.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#migrate-inspection-authorization-and-approval-factories",
		surfaces: [
			"openclaw/plugin-sdk/approval-delivery-runtime.createApproverRestrictedNativeApprovalCapability",
			"openclaw/plugin-sdk/approval-handler-runtime.createChannelApprovalNativeRuntimeAdapter",
			"openclaw/plugin-sdk/approval-handler-adapter-runtime.createLazyChannelApprovalNativeRuntimeAdapter",
			"openclaw/plugin-sdk/approval-delivery-runtime.createApproverRestrictedNativeApprovalCapabilityFromForwardingRoutes",
			"openclaw/plugin-sdk/approval-native-runtime.createNativeApprovalChannelRouteGates",
			"openclaw/plugin-sdk/approval-native-runtime.createChannelNativeOriginTargetResolver",
			"openclaw/plugin-sdk/approval-client-runtime.createChannelExecApprovalProfile",
			"openclaw/plugin-sdk/approval-native-runtime.createChannelApproverDmTargetResolver",
			"openclaw/plugin-sdk/approval-native-runtime.createNativeApprovalForwardingFallbackSuppressor",
			"openclaw/plugin-sdk/approval-runtime.resolveExecApprovalSessionTarget",
			"openclaw/plugin-sdk/approval-runtime.resolveApprovalRequestSessionTarget",
			"openclaw/plugin-sdk/approval-runtime.resolveApprovalRequestOriginTarget",
			"openclaw/plugin-sdk/approval-native-runtime.resolveApprovalRequestAccountId",
			"openclaw/plugin-sdk/approval-native-runtime.resolveApprovalRequestChannelAccountId",
			"openclaw/plugin-sdk/approval-runtime.doesApprovalRequestMatchChannelAccount",
			"openclaw/plugin-sdk/approval-native-runtime.doesApprovalRequestSelectChannelAccount"
		]
	},
	{
		...PREPARATION,
		code: "debug-proxy-sync-capture",
		replacement: "Acquire acquireDebugProxyCaptureStoreAsync, await store operations, and await lease.release in finally. Use createDebugProxyCaptureReaderAsync and await reads. Use initializeDebugProxyCaptureAsync, captureHttpExchangeAsync, captureWsEventAsync, and finalizeDebugProxyCaptureAsync, including the context captureWsEventAsync companion. Do not fire and forget persistence or fall back after an async failure.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-debug-proxy-capture",
		surfaces: [
			"openclaw/plugin-sdk/proxy-capture.DebugProxyCaptureReader",
			"openclaw/plugin-sdk/proxy-capture.DebugProxyCaptureStore",
			"openclaw/plugin-sdk/proxy-capture.getDebugProxyCaptureStore",
			"openclaw/plugin-sdk/proxy-capture.acquireDebugProxyCaptureStore",
			"openclaw/plugin-sdk/proxy-capture.closeDebugProxyCaptureStore",
			"openclaw/plugin-sdk/proxy-capture.createDebugProxyCaptureReader",
			"openclaw/plugin-sdk/proxy-capture.initializeDebugProxyCapture",
			"openclaw/plugin-sdk/proxy-capture.captureHttpExchange",
			"openclaw/plugin-sdk/proxy-capture.captureWsEvent",
			"openclaw/plugin-sdk/proxy-capture.finalizeDebugProxyCapture",
			"DebugProxyCaptureContext.captureWsEvent"
		]
	}
];
//#endregion
//#region src/plugins/compat/auth-async-record.ts
const AUTH_ASYNC_COMPAT_RECORD = {
	code: "auth-profile-sync-operations",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-11",
	warningStarts: "2026-10-11",
	removeAfter: "2026-12-31",
	replacement: "Await the Async-suffixed auth-store, snapshot-publication, AuthStorage, profile-upsert, provider-availability, profile-metadata, model-auth, model-header, provider-selection, and TTS methods. For secret-read preparation, use loadAuthProfileStoreForRuntimeAsync from agent-runtime with readOnly: true and allowKeychainPrompt: false. Replace saveAuthProfileStore with the owner-backed updateAuthProfileStoreWithLock from provider-auth. Public database-path displays retire after 2026-12-31 with no public async path replacement; display provider/profile identifiers instead. Bundled callers use AuthStorage.resolvePathForDisplayAsync from the private agent-sessions surface for exact selected paths. Use resolveProviderAuthProfileMetadataAsync from provider-auth-runtime for profile metadata. Implement isConfiguredAsync for media, speech, and realtime providers, and resolveConfigAsync for realtime voice providers. For internal realtime hooks, implement isBrowserSessionConfiguredAsync, isGatewayRelayConfiguredAsync, and resolveBrowserSessionCapabilitiesAsync. Released synchronous methods retain their signatures, immediate results, and completion timing through 2026-12-31; removal ships in the first January 2027 stable release.",
	docsPath: "/plugins/sdk-migration/how-to-migrate#await-auth-profile-and-provider-availability-operations",
	surfaces: [
		"openclaw/plugin-sdk/provider-auth ensureAuthProfileStore",
		"openclaw/plugin-sdk/provider-auth ensureAuthProfileStoreForLocalUpdate",
		"openclaw/plugin-sdk/provider-auth upsertAuthProfile",
		"openclaw/plugin-sdk/provider-auth upsertApiKeyProfile",
		"openclaw/plugin-sdk/provider-auth-api-key upsertApiKeyProfile",
		"openclaw/plugin-sdk/provider-auth isProviderApiKeyConfigured",
		"openclaw/plugin-sdk/provider-auth isProviderAuthProfileConfigured",
		"openclaw/plugin-sdk/provider-auth listUsableProviderAuthProfileIds",
		"openclaw/plugin-sdk/provider-auth-runtime resolveProviderAuthProfileMetadata",
		"openclaw/plugin-sdk/agent-runtime ensureAuthProfileStore",
		"openclaw/plugin-sdk/agent-runtime loadAuthProfileStoreWithoutExternalProfiles",
		"openclaw/plugin-sdk/agent-runtime loadAuthProfileStoreForRuntime",
		"openclaw/plugin-sdk/agent-runtime replaceRuntimeAuthProfileStoreSnapshots",
		"openclaw/plugin-sdk/agent-runtime loadAuthProfileStoreForSecretsRuntime",
		"openclaw/plugin-sdk/agent-runtime saveAuthProfileStore",
		"openclaw/plugin-sdk/agent-runtime resolveAuthStorePathForDisplay",
		"openclaw/plugin-sdk/agent-runtime findPersistedAuthProfileCredential",
		"openclaw/plugin-sdk/agent-runtime resolvePersistedAuthProfileOwnerAgentDir",
		"openclaw/plugin-sdk/agent-sessions ModelRegistry.create",
		"openclaw/plugin-sdk/agent-sessions ModelRegistry.refresh",
		"openclaw/plugin-sdk/agent-sessions ModelRegistry.unregisterProvider",
		"openclaw/plugin-sdk/agent-sessions AuthStorage.forAgent",
		"openclaw/plugin-sdk/agent-sessions AuthStorage.create",
		"openclaw/plugin-sdk/agent-sessions AuthStorage.reload",
		"openclaw/plugin-sdk/agent-sessions AuthStorage.set",
		"openclaw/plugin-sdk/agent-sessions AuthStorage.remove",
		"openclaw/plugin-sdk/agent-sessions AuthStorage.logout",
		"openclaw/plugin-sdk/agent-harness-runtime resolveModelAuthMode",
		"openclaw/plugin-sdk/models-provider-runtime formatModelsAvailableHeader",
		"openclaw/plugin-sdk/image-generation-core resolveCapabilityModelCandidates",
		"openclaw/plugin-sdk/provider-selection-runtime resolveConfiguredCapabilityProvider",
		"openclaw/plugin-sdk/realtime-voice resolveConfiguredRealtimeVoiceProvider",
		"openclaw/plugin-sdk/tts-runtime getTtsProvider",
		"openclaw/plugin-sdk/tts-runtime isTtsProviderConfigured",
		"openclaw/plugin-sdk/tts-runtime resolveExplicitTtsOverrides",
		"openclaw/plugin-sdk/agent-runtime getTtsProvider",
		"PluginRuntime.modelAuth.ensureAuthProfileStore",
		"PluginRuntime.modelAuth.isProviderApiKeyConfigured",
		"PluginRuntime.agent.resolveCliBackendDispatchEligibility",
		"ImageGenerationProvider.isConfigured",
		"MusicGenerationProvider.isConfigured",
		"VideoGenerationProvider.isConfigured",
		"SpeechProviderPlugin.isConfigured",
		"RealtimeTranscriptionProviderPlugin.isConfigured",
		"RealtimeVoiceProviderPlugin.isConfigured",
		"RealtimeVoiceProviderPlugin.resolveConfig",
		"InternalRealtimeVoiceProviderApi.isBrowserSessionConfigured",
		"InternalRealtimeVoiceProviderApi.isGatewayRelayConfigured",
		"InternalRealtimeVoiceProviderApi.resolveBrowserSessionCapabilities"
	],
	diagnostics: ["TypeScript @deprecated annotations and migration documentation", "Synchronous auth storage entrypoints warn once per plugin and capability family on use"]
};
//#endregion
//#region src/plugins/compat/binding-persistence-records.ts
const BINDING_PERSISTENCE_COMPAT_RECORDS = [
	{
		code: "conversation-binding-sync-persistence",
		status: "deprecated",
		owner: "sdk",
		deprecated: "2026-10-09",
		warningStarts: "2026-10-09",
		removeAfter: "2026-12-31",
		replacement: "Use createAccountScopedConversationBindingManagerV2, iMessage createIMessageConversationBindingManagerV2, registerSessionBindingAdapterV2, and awaited service list/resolve/touch methods. V2 adapters supply a coherent inspection snapshot with its current-source assertion. Legacy synchronous operations preserve completion and expiry semantics through 2026-12-31; removal ships in the first January 2027 stable release.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-plugin-state-and-conversation-bindings",
		surfaces: [
			"openclaw/plugin-sdk/thread-bindings-runtime.createAccountScopedConversationBindingManager",
			"@openclaw/imessage api.createIMessageConversationBindingManager",
			"AccountScopedConversationBindingManager.getByConversationId",
			"AccountScopedConversationBindingManager.listBySessionKey",
			"AccountScopedConversationBindingManager.bindConversation",
			"AccountScopedConversationBindingManager.touchConversation",
			"AccountScopedConversationBindingManager.unbindConversation",
			"AccountScopedConversationBindingManager.unbindBySessionKey",
			"SessionBindingAdapter.listBySession",
			"SessionBindingAdapter.inspectByConversation",
			"openclaw/plugin-sdk/conversation-runtime.registerSessionBindingAdapter",
			"SessionBindingService.listBySession",
			"SessionBindingService.resolveByConversation",
			"SessionBindingService.touch",
			"openclaw/plugin-sdk/session-binding-runtime.inspectSessionBindingByConversation",
			"openclaw/plugin-sdk/conversation-runtime.resolveRuntimeConversationBindingRoute"
		],
		diagnostics: ["TypeScript @deprecated annotations and one shared runtime warning per plugin and capability family on legacy use"]
	},
	{
		code: "native-session-binding-sync-persistence",
		status: "deprecated",
		owner: "sdk",
		deprecated: "2026-10-09",
		warningStarts: "2026-10-09",
		removeAfter: "2026-12-31",
		replacement: "Use createNativeSessionBindingLifecycleV2 and resolvePreparedNativeSessionBinding with the worker-backed binding store, and release the prepared capture after terminal cleanup. Implement AgentHarness.resolveSessionRuntimeOwnershipAsync for preparation. Released synchronous authority factories remain deprecated compatibility adapters.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-plugin-state-and-conversation-bindings",
		surfaces: [
			"openclaw/plugin-sdk/agent-harness-session-runtime.createNativeSessionBindingLifecycle",
			"openclaw/plugin-sdk/agent-harness-session-runtime.NativeSessionBindingStateStore",
			"openclaw/plugin-sdk/agent-harness-session-runtime.resolveNativeSessionBindingWithAuthority",
			"AgentHarness.resolveSessionRuntimeOwnership"
		],
		diagnostics: ["TypeScript @deprecated annotations and the shared per-plugin capability-family warning budget"]
	},
	{
		code: "approval-event-sync-publication",
		status: "deprecated",
		owner: "sdk",
		deprecated: "2026-10-10",
		warningStarts: "2026-10-10",
		removeAfter: "2026-12-31",
		replacement: "Await approvalEvents.publishRequestedAsync. The legacy publisher retains synchronous delivery counts for synchronous subscribers and refuses async eligibility before delivery; removed in the first January 2027 stable release after the final compatibility day, 2026-12-31.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-gateway-approval-publication",
		surfaces: ["GatewayRequestHandlerOptions.context.approvalEvents.publishRequested"],
		diagnostics: ["TypeScript @deprecated annotation and the shared capability-family warning"]
	}
];
//#endregion
//#region src/plugins/compat/channel-pairing-record.ts
const CHANNEL_PAIRING_COMPAT_RECORD = {
	code: "channel-pairing-sync-allowlist",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-03",
	warningStarts: "2026-10-03",
	removeAfter: "2026-12-31",
	replacement: "Await readChannelAllowFromStore from channel-pairing. The released synchronous reader retains its signature and native behavior through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
	docsPath: "/plugins/sdk-migration/compatibility-policy#channel-pairing-allowlists",
	surfaces: ["openclaw/plugin-sdk/channel-pairing.readChannelAllowFromStoreSync"],
	diagnostics: ["TypeScript @deprecated annotation and migration documentation; bounded capability-family warnings on legacy preparation"]
};
//#endregion
//#region src/plugins/compat/channel-prepared-tool-policy-record.ts
const CHANNEL_PREPARED_TOOL_POLICY_COMPAT_RECORD = {
	code: "channel-prepared-tool-policy",
	status: "deprecated",
	owner: "channel",
	deprecated: "2026-10-12",
	warningStarts: "2026-10-12",
	removalGate: "stable-deprecation-period",
	replacement: "Resolve current configuration through security.resolveDirectToolPolicy or groups.resolveToolPolicy using authenticated requester and conversation facts. The legacy snapshot remains execution-local to the original external request, including its queued turn; it is never requester provenance for new delegation.",
	docsPath: "/plugins/sdk-migration/compatibility-policy#channel-prepared-tool-policy",
	surfaces: ["BuildChannelInboundEventContextParams.access.toolPolicy", "MsgContext.ConversationToolPolicy"],
	diagnostics: ["DEP_CHANNEL_PREPARED_TOOL_POLICY warns once on legacy policy use"]
};
//#endregion
//#region src/plugins/compat/cron-store-path-record.ts
const CRON_STORE_PATH_COMPAT_RECORD = {
	code: "cron-store-sync-path",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-11",
	warningStarts: "2026-10-11",
	removeAfter: "2026-12-31",
	replacement: "Await resolveCronStorePathAsync(storePath) from openclaw/plugin-sdk/cron-store-runtime. The synchronous resolveCronStorePath(storePath) retains its existing return value through 2026-12-31; removal ships in the first January 2027 stable release.",
	docsPath: "/plugins/sdk-migration/compatibility-policy#cron-store-path-resolution",
	surfaces: ["openclaw/plugin-sdk/cron-store-runtime resolveCronStorePath"],
	diagnostics: ["Bounded DEP_PLUGIN_SDK warning for synchronous cron path resolution"]
};
//#endregion
//#region src/plugins/compat/deprecation-marking.ts
const MARKING_DATE = "2026-07-25";
const DEPRECATION_MARKING = {
	status: "removal-pending",
	introduced: MARKING_DATE,
	deprecated: MARKING_DATE,
	warningStarts: MARKING_DATE,
	removeAfter: "2026-10-01"
};
/** The elapsed window does not replace each family's required reader-migration proof. */
const DEPRECATION_MARKING_COMPAT_RECORDS = [
	{
		code: "plugin-sdk-channel-setup-input-fields",
		...DEPRECATION_MARKING,
		owner: "channel",
		replacement: "plugin-local setup input intersections that declare each owning channel field; retain each field until a new published-plugin artifact sweep finds no reader",
		docsPath: "/plugins/sdk-migration#published-channel-setup-compatibility",
		surfaces: [
			"ChannelSetupInput.privateKey",
			"ChannelSetupInput.secret",
			"ChannelSetupInput.botToken",
			"ChannelSetupInput.appToken",
			"ChannelSetupInput.signingSecret",
			"ChannelSetupInput.mode",
			"ChannelSetupInput.cliPath",
			"ChannelSetupInput.authDir",
			"ChannelSetupInput.httpUrl",
			"ChannelSetupInput.httpPort",
			"ChannelSetupInput.webhookPath",
			"ChannelSetupInput.webhookUrl",
			"ChannelSetupInput.userId",
			"ChannelSetupInput.accessToken",
			"ChannelSetupInput.password",
			"ChannelSetupInput.deviceName",
			"ChannelSetupInput.url",
			"ChannelSetupInput.baseUrl",
			"ChannelSetupInput.code",
			"ChannelSetupInput.groupChannels",
			"ChannelSetupInput.dmAllowlist",
			"ChannelSetupInput.autoDiscoverChannels"
		],
		diagnostics: ["TypeScript @deprecated annotations on the reader-backed ChannelSetupInput compatibility tier", "published-plugin artifact reader sweep required before field removal"]
	},
	{
		code: "plugin-sdk-broad-runtime-barrels",
		...DEPRECATION_MARKING,
		owner: "sdk",
		replacement: "focused plugin SDK subpaths for each runtime capability; retain until bundled and published plugins no longer import any of the seven broad barrels",
		docsPath: "/plugins/sdk-migration#compatibility-policy",
		surfaces: [
			"openclaw/plugin-sdk/agent-runtime",
			"openclaw/plugin-sdk/agent-runtime loadModelCatalog params.useCache",
			"openclaw/plugin-sdk/agent-runtime loadModelCatalog params.cacheOnly",
			"openclaw/plugin-sdk/agent-runtime loadModelCatalog params.metadataSnapshot",
			"openclaw/plugin-sdk/agent-runtime loadModelCatalog",
			"openclaw/plugin-sdk/cli-runtime",
			"openclaw/plugin-sdk/conversation-runtime",
			"openclaw/plugin-sdk/hook-runtime",
			"openclaw/plugin-sdk/media-runtime",
			"openclaw/plugin-sdk/media-runtime buildAgentMediaPayload",
			"openclaw/plugin-sdk/plugin-runtime",
			"openclaw/plugin-sdk/security-runtime"
		],
		diagnostics: ["TypeScript @deprecated annotations on broad plugin SDK barrels", "plugin boundary report compatibility inventory"]
	},
	{
		code: "plugin-sdk-provider-owned-helper-shims",
		...DEPRECATION_MARKING,
		owner: "provider",
		replacement: "provider-local auth, model, replay, OAuth, and stream helper APIs; retain until every helper is migrated in official providers and absent from published plugins",
		docsPath: "/plugins/sdk-migration#compatibility-policy",
		surfaces: [
			"openclaw/plugin-sdk/provider-stream MOONSHOT_THINKING_STREAM_HOOKS",
			"openclaw/plugin-sdk/provider-stream-shared defaultToolStreamExtraParams",
			"openclaw/plugin-sdk/provider-stream-shared stripTrailingAnthropicAssistantPrefillWhenThinking",
			"openclaw/plugin-sdk/provider-stream-shared createAnthropicThinkingPrefillPayloadWrapper",
			"openclaw/plugin-sdk/provider-stream-shared OpenAICompatibleThinkingLevel",
			"openclaw/plugin-sdk/provider-stream-shared isOpenAICompatibleThinkingEnabled",
			"openclaw/plugin-sdk/provider-stream-shared DeepSeekV4ThinkingLevel",
			"openclaw/plugin-sdk/provider-stream-shared DeepSeekV4ReasoningEffort",
			"openclaw/plugin-sdk/provider-stream-shared createDeepSeekV4OpenAICompatibleThinkingWrapper",
			"openclaw/plugin-sdk/provider-stream-shared createThinkingOnlyFinalTextWrapper",
			"openclaw/plugin-sdk/provider-stream-shared createGoogleThinkingPayloadWrapper",
			"openclaw/plugin-sdk/provider-stream-shared createGoogleThinkingStreamWrapper",
			"openclaw/plugin-sdk/provider-model-shared isProxyReasoningUnsupportedModelHint",
			"openclaw/plugin-sdk/provider-model-shared NATIVE_ANTHROPIC_REPLAY_HOOKS",
			"openclaw/plugin-sdk/provider-model-shared PASSTHROUGH_GEMINI_REPLAY_HOOKS",
			"openclaw/plugin-sdk/provider-auth toFormUrlEncoded",
			"openclaw/plugin-sdk/provider-auth generatePkceVerifierChallenge",
			"openclaw/plugin-sdk/provider-oauth-runtime OAuthProvider",
			"openclaw/plugin-sdk/provider-oauth-runtime OAuthProviderInfo"
		],
		diagnostics: ["TypeScript @deprecated annotations naming provider-local replacements", "plugin boundary report compatibility inventory"]
	},
	{
		code: "message-presentation-legacy-bridges",
		...DEPRECATION_MARKING,
		owner: "channel",
		replacement: "MessagePresentation values and channel presentation renderers; retain until reply producers and official channel packages no longer emit or read legacy interactive replies",
		docsPath: "/plugins/sdk-migration#compatibility-policy",
		surfaces: [
			"InteractiveReplyButton.value",
			"InteractiveReplyButton.url",
			"InteractiveReplyButton.webApp",
			"InteractiveReplyButton.web_app",
			"InteractiveReplyOption.value",
			"InteractiveReplyButton",
			"InteractiveReplyOption",
			"InteractiveReplyBlock",
			"InteractiveReply",
			"normalizeInteractiveReply",
			"hasInteractiveReplyBlocks",
			"presentationToInteractiveReply",
			"presentationToInteractiveControlsReply",
			"interactiveReplyToPresentation",
			"resolveInteractiveTextFallback",
			"src/auto-reply ReplyPayload.interactive",
			"openclaw/plugin-sdk/reply-payload ReplyPayload.interactive",
			"reduceInteractiveReply",
			"@openclaw/discord buildDiscordInteractiveComponents",
			"@openclaw/slack buildSlackInteractiveBlocks"
		],
		diagnostics: ["TypeScript @deprecated annotations naming MessagePresentation replacements", "plugin boundary report compatibility inventory"]
	},
	{
		code: "plugin-sdk-focused-compat-aliases",
		...DEPRECATION_MARKING,
		owner: "sdk",
		replacement: "the focused replacement named by each TypeScript @deprecated annotation; retain until every enumerated alias has zero bundled and published readers",
		docsPath: "/plugins/sdk-migration#compatibility-policy",
		surfaces: [
			"openclaw/plugin-sdk/acp-runtime __testing",
			"openclaw/plugin-sdk/channel-inbound BuildChannelTurnContextParams",
			"openclaw/plugin-sdk/channel-inbound BuiltChannelTurnContext",
			"openclaw/plugin-sdk/channel-inbound buildChannelTurnContext",
			"openclaw/plugin-sdk/channel-inbound finalizeChannelInboundContext",
			"openclaw/plugin-sdk/channel-inbound filterChannelTurnSupplementalContext",
			"openclaw/plugin-sdk/channel-send-result ChannelSendRawResult",
			"openclaw/plugin-sdk/keyed-async-queue KeyedAsyncQueue.getTailMapForTesting",
			"openclaw/plugin-sdk/persistent-dedupe PersistentDedupeLegacyPathOptions.lockOptions",
			"openclaw/plugin-sdk/retry-runtime createTelegramRetryRunner",
			"openclaw/plugin-sdk/ssrf-policy SsrfPolicyOptions.allowPrivateNetwork",
			"openclaw/plugin-sdk/ssrf-policy ssrfPolicyFromAllowPrivateNetwork",
			"openclaw/plugin-sdk/tts-runtime TtsSynthesisStreamResult",
			"openclaw/plugin-sdk/tts-runtime TtsRuntimeFacade._test"
		],
		diagnostics: ["TypeScript @deprecated annotations naming focused replacements", "plugin boundary report compatibility inventory"]
	},
	{
		code: "agent-harness-terminal-result-aliases",
		...DEPRECATION_MARKING,
		owner: "agent-runtime",
		replacement: "AgentHarnessAttemptResult.terminal and AgentHarnessDeliveryDefaults.visibleReplies; retain until harness migration verifies that legacy terminal fields and sourceVisibleReplies are unread",
		docsPath: "/plugins/sdk-agent-harness",
		surfaces: [
			"AgentHarnessAttemptResult.aborted",
			"AgentHarnessAttemptResult.externalAbort",
			"AgentHarnessAttemptResult.timedOut",
			"AgentHarnessAttemptResult.idleTimedOut",
			"AgentHarnessAttemptResult.timedOutDuringCompaction",
			"AgentHarnessAttemptResult.timedOutDuringToolExecution",
			"AgentHarnessAttemptResult.timedOutByRunBudget",
			"AgentHarnessAttemptResult.promptError",
			"AgentHarnessAttemptResult.promptErrorSource",
			"AgentHarnessDeliveryDefaults.sourceVisibleReplies"
		],
		diagnostics: ["TypeScript @deprecated annotations on agent harness result and delivery defaults", "plugin boundary report compatibility inventory"]
	},
	{
		code: "official-plugin-export-aliases",
		...DEPRECATION_MARKING,
		owner: "channel",
		replacement: "MessagePresentation renderers and host-owned timeout/runtime behavior; retain until minimum supported official plugin packages no longer import these aliases",
		docsPath: "/plugins/compatibility#current-compatibility-areas",
		surfaces: [
			"@openclaw/discord buildDiscordInteractiveComponents",
			"@openclaw/discord normalizeDiscordListenerTimeoutMs",
			"@openclaw/discord normalizeDiscordInboundWorkerTimeoutMs",
			"@openclaw/discord isAbortError",
			"@openclaw/discord runDiscordTaskWithTimeout",
			"@openclaw/slack buildSlackInteractiveBlocks"
		],
		diagnostics: ["TypeScript @deprecated annotations on published official-plugin exports", "plugin boundary report compatibility inventory"]
	},
	{
		code: "memory-host-compatibility-aliases",
		...DEPRECATION_MARKING,
		owner: "sdk",
		replacement: "canonical memory cache/FTS tables; retain until supported memory integrations are verified to use canonical tables without overrides and legacy table data remains preserved",
		docsPath: "/plugins/sdk-migration#compatibility-policy",
		surfaces: ["@openclaw/memory-host-sdk ensureMemoryIndexSchema.embeddingCacheTable", "@openclaw/memory-host-sdk ensureMemoryIndexSchema.ftsTable"],
		diagnostics: ["TypeScript @deprecated annotations on memory-host SDK compatibility fields", "plugin boundary report memory-host SDK summary"],
		tests: ["packages/memory-host-sdk/src/host/memory-schema.test.ts", "src/plugins/compat/registry.test.ts"],
		releaseNote: "Memory-host table overrides remain available until supported artifact usage and legacy data preservation are verified."
	},
	{
		code: "plugin-runtime-api-unused-flat-aliases",
		...DEPRECATION_MARKING,
		status: "removed",
		owner: "plugin-execution",
		replacement: "api.agent.events.emitAgentEvent, api.runContext methods, api.session.controls.registerSessionAction, and api.session.workflow attachment and scheduling methods",
		docsPath: "/plugins/sdk-overview/host-hooks",
		surfaces: [
			"OpenClawPluginApi.emitAgentEvent",
			"OpenClawPluginApi.setRunContext",
			"OpenClawPluginApi.getRunContext",
			"OpenClawPluginApi.clearRunContext",
			"OpenClawPluginApi.registerSessionAction",
			"OpenClawPluginApi.sendSessionAttachment",
			"OpenClawPluginApi.scheduleSessionTurn",
			"OpenClawPluginApi.unscheduleSessionTurnsByTag"
		],
		diagnostics: ["TypeScript reports removed flat members; use the grouped API namespaces"]
	},
	{
		code: "plugin-runtime-api-compat-aliases",
		...DEPRECATION_MARKING,
		owner: "plugin-execution",
		replacement: "the namespaced plugin API and focused runtime methods named per surface; retain until all enumerated flat API and runtime aliases have no readers",
		docsPath: "/plugins/sdk-migration#compatibility-policy",
		surfaces: [
			"OpenClawPluginApi.registerSessionExtension",
			"OpenClawPluginApi.enqueueNextTurnInjection",
			"OpenClawPluginApi.registerControlUiDescriptor",
			"OpenClawPluginApi.registerRuntimeLifecycle",
			"OpenClawPluginApi.registerAgentEventSubscription",
			"OpenClawPluginApi.registerSessionSchedulerJob",
			"PluginHookContext.senderExternalId",
			"PluginAttachmentChannelHints.telegram",
			"PluginAttachmentChannelHints.slack",
			"AgentPromptSurfaceKind pi_main",
			"PluginRuntime.channel.reply.createReplyDispatcherWithTyping",
			"PluginRuntime.channel.reply.resolveHumanDelayConfig",
			"PluginRuntime.channel.reply.dispatchReplyFromConfig",
			"PluginRuntime.channel.reply.finalizeInboundContext",
			"PluginRuntime.channel.media.fetchRemoteMedia",
			"PluginRuntime.channel.session.resolveStorePath",
			"PluginRuntime.channel.session.recordInboundSession",
			"PluginRuntime.channel.inbound.runPreparedReply",
			"PluginRuntime.channel.turn"
		],
		diagnostics: ["TypeScript @deprecated annotations on plugin API and runtime aliases", "plugin boundary report compatibility inventory"]
	},
	{
		code: "plugin-provider-manifest-compat-aliases",
		...DEPRECATION_MARKING,
		owner: "provider",
		replacement: "manifest-owned plugin kind/setup metadata and model catalog registration; retain until providers no longer publish runtime kind or legacy catalog hooks",
		docsPath: "/plugins/sdk-migration#compatibility-policy",
		surfaces: [
			"DefinePluginEntryOptions.kind",
			"SingleProviderPluginOptions.kind",
			"OpenClawPluginDefinition.kind",
			"PluginPackageChannel.cliAddOptions",
			"ProviderPlugin.catalog",
			"ProviderPlugin.staticCatalog",
			"ProviderPlugin.suppressBuiltInModel",
			"ProviderPlugin.augmentModelCatalog",
			"ProviderBuiltInModelSuppressionContext"
		],
		diagnostics: ["TypeScript @deprecated annotations on plugin manifest and provider catalog aliases", "plugin boundary report compatibility inventory"]
	}
];
//#endregion
//#region src/plugins/compat/media-legacy-projection.ts
/** Named compatibility contract for the shipped parallel media projection. */
const MEDIA_LEGACY_PROJECTION_COMPAT_RECORD = {
	code: "media-legacy-projection",
	status: "removal-pending",
	owner: "sdk",
	deprecated: "2026-07-24",
	warningStarts: "2026-07-24",
	removeAfter: "2026-10-01",
	replacement: "ordered `MsgContext.media` / `InboundMediaFacts[]`; typed hook `media` and `originalMedia`; `Attachment*` template variables; and `openclaw/plugin-sdk/media-local-roots`; retain until a clean published-plugin artifact sweep verifies that the legacy media surfaces have no readers",
	docsPath: "/plugins/sdk-migration#media-legacy-projection",
	surfaces: [
		"MsgContext MediaPath/MediaUrl/MediaType and plural/staging fields",
		"openclaw/plugin-sdk/agent-media-payload",
		"ChannelInboundMediaPayload and buildChannelInboundMediaPayload",
		"MediaPayload and buildMediaPayload",
		"message hook mediaPath/mediaUrl/mediaType and plural/original metadata aliases",
		"MediaPath/MediaUrl/MediaType/MediaDir template variables"
	],
	diagnostics: [
		"TypeScript @deprecated annotations naming the facts-first replacement",
		"plugin boundary report compatibility inventory with the approved removeAfter date",
		"SDK, hook, and media template migration documentation"
	]
};
//#endregion
//#region src/plugins/compat/memory-session-records.ts
const MEMORY_SESSION_COMPAT_RECORDS = [
	{
		code: "memory-manager-sync-status",
		status: "deprecated",
		owner: "sdk",
		deprecated: "2026-10-13",
		warningStarts: "2026-10-16",
		removeAfter: "2026-12-31",
		replacement: "Implement and await MemorySearchManager.statusAsync. Consumers of legacy manager types can await readMemorySearchManagerStatus, which retains the synchronous fallback through 2026-12-31. Remove the status member and fallback in the first January 2027 stable release.",
		docsPath: "/plugins/sdk-migration/sqlite-async",
		surfaces: ["MemorySearchManager.status", "MemoryIndexManager.status"],
		diagnostics: ["TypeScript @deprecated annotations and a runtime warning once per plugin and method from the built-in MemoryIndexManager"]
	},
	{
		code: "memory-session-sync-inventory",
		status: "deprecated",
		owner: "sdk",
		deprecated: "2026-10-01",
		warningStarts: "2026-10-01",
		removeAfter: "2026-12-31",
		replacement: "Await loadArchivedSessionsAsync and resolveMemorySessionTargetsAsync from memory-core-host-engine-sessions. Synchronous readers retain their existing signatures and results through 2026-12-31.",
		docsPath: "/plugins/sdk-migration/compatibility-policy#memory-session-inventory-readers",
		surfaces: ["openclaw/plugin-sdk/memory-core-host-engine-sessions.loadArchivedSessions", "openclaw/plugin-sdk/memory-core-host-engine-sessions.resolveMemorySessionTargets"],
		diagnostics: ["TypeScript @deprecated annotations, migration documentation, and a runtime warning once per plugin and family"]
	},
	{
		code: "memory-session-sync-metadata",
		status: "deprecated",
		owner: "sdk",
		deprecated: "2026-10-11",
		warningStarts: "2026-10-11",
		removeAfter: "2026-12-31",
		replacement: "Await loadMemorySessionMetadataAsync and loadMemorySessionMetadataBatchAsync from memory-core-host-engine-sessions. Bundled ingestion uses the history worker; the synchronous metadata reader retains its signature through 2026-12-31.",
		docsPath: "/plugins/sdk-migration/compatibility-policy#memory-session-inventory-readers",
		surfaces: ["openclaw/plugin-sdk/memory-core-host-engine-sessions.loadMemorySessionMetadata"],
		diagnostics: ["TypeScript @deprecated annotations, migration documentation, and one shared DEP_PLUGIN_SDK warning per plugin and memory-session family on main-thread legacy use"]
	}
];
//#endregion
//#region src/plugins/compat/native-exec-approval-record.ts
const NATIVE_EXEC_APPROVAL_COMPAT_RECORD = {
	code: "native-approval-commit-guard",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-09",
	warningStarts: "2026-10-09",
	removalGate: "stable-deprecation-period",
	replacement: "Use host-bound api.runtime.gateway.request approval methods. Released opaque approval commit guards run at the worker precommit boundary; they cannot read uncommitted transaction state. Final effect-time authority checks remain synchronous and current.",
	docsPath: "/plugins/sdk-migration/how-to-migrate#use-worker-owned-approval-requests",
	surfaces: ["GatewayRequestHandlerOptions.sessionMutationCommitGuard for approval methods"],
	diagnostics: ["Shared per-plugin capability-family warning on legacy callback use"]
};
//#endregion
//#region src/plugins/compat/plugin-sdk-private-runtime-export-record.ts
/**
* JavaScript-only SDK facades are not typed contracts, but published plugins link these names;
* the contract test asserts each surface stays exported from its packaged subpath.
*/
const PLUGIN_SDK_PRIVATE_RUNTIME_EXPORT_COMPAT_RECORD = {
	code: "plugin-sdk-private-runtime-shipped-exports",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-15",
	warningStarts: "2026-10-15",
	removeAfter: "2027-01-15",
	replacement: "Import the helper from a typed public SDK subpath that exports it, or keep a plugin-local copy; these JavaScript-only runtime facades are not a typed third-party contract",
	docsPath: "/plugins/sdk-migration/compatibility-policy#private-runtime-facade-exports",
	surfaces: [
		"openclaw/plugin-sdk/acp-runtime.getAcpRuntimeBackend",
		"openclaw/plugin-sdk/approval-reaction-runtime.readApprovalReactionDeliveryMetadata",
		"openclaw/plugin-sdk/fetch-runtime.hasEnvHttpProxyConfigured",
		"openclaw/plugin-sdk/image-generation-core.resolveAgentModelPrimaryValue",
		"openclaw/plugin-sdk/image-generation-core.resolveApiKeyForProvider",
		"openclaw/plugin-sdk/memory-core-host-engine-embeddings.fetchRemoteEmbeddingVectors",
		"openclaw/plugin-sdk/memory-core-host-engine-embeddings.listMemoryEmbeddingProviders",
		"openclaw/plugin-sdk/memory-core-host-engine-storage.chunkMarkdown",
		"openclaw/plugin-sdk/memory-core-host-engine-storage.ensureDir",
		"openclaw/plugin-sdk/memory-core-host-runtime-files.listMemoryFiles",
		"openclaw/plugin-sdk/memory-core-host-runtime-files.normalizeExtraMemoryPaths",
		"openclaw/plugin-sdk/poll-runtime.resolvePollMaxSelections",
		"openclaw/plugin-sdk/provider-stream.createOpenRouterSystemCacheWrapper",
		"openclaw/plugin-sdk/provider-stream.resolveMoonshotThinkingType",
		"openclaw/plugin-sdk/provider-web-fetch.enablePluginInConfig",
		"openclaw/plugin-sdk/provider-web-fetch.jsonResult",
		"openclaw/plugin-sdk/provider-web-fetch.withTrustedWebToolsEndpoint",
		"openclaw/plugin-sdk/provider-web-fetch.wrapExternalContent",
		"openclaw/plugin-sdk/provider-web-fetch.wrapWebContent",
		"openclaw/plugin-sdk/provider-web-search.DEFAULT_TIMEOUT_SECONDS",
		"openclaw/plugin-sdk/provider-web-search.markdownToText",
		"openclaw/plugin-sdk/provider-web-search.setScopedCredentialValue",
		"openclaw/plugin-sdk/provider-web-search.setTopLevelCredentialValue",
		"openclaw/plugin-sdk/retry-runtime.createRateLimitRetryRunner",
		"openclaw/plugin-sdk/speech.readResponseTextLimited",
		"openclaw/plugin-sdk/speech.truncateErrorDetail",
		"openclaw/plugin-sdk/thread-bindings-runtime.resolveThreadBindingConversationIdFromBindingId",
		"openclaw/plugin-sdk/thread-bindings-runtime.resolveThreadBindingFarewellText",
		"openclaw/plugin-sdk/thread-bindings-runtime.resolveThreadBindingLifecycle"
	],
	diagnostics: ["TypeScript @deprecated annotations and the private runtime shipped-export contract test"]
};
//#endregion
//#region src/plugins/compat/plugin-sdk-removed-export-records.ts
const CHANNEL_CLEANUP_REMOVAL = { removeAfter: "2026-10-04" };
const REMOVED_EXPORT_SEEDS = [
	{
		code: "plugin-sdk-allowlist-resolution-entry-mapper",
		...CHANNEL_CLEANUP_REMOVAL,
		owner: "channel",
		subpath: "allow-from",
		names: ["mapBasicAllowlistResolutionEntries"],
		replacement: "None; project BasicAllowlistResolutionEntry fields in the consuming plugin."
	},
	{
		code: "plugin-sdk-computer-use-validator-compiler",
		...CHANNEL_CLEANUP_REMOVAL,
		owner: "sdk",
		subpath: "computer-use",
		names: ["compileComputerUseValidator"],
		replacement: "Use Compile(schema).Check from `typebox/compile` with the schemas exported by `openclaw/plugin-sdk/computer-use`."
	},
	{
		code: "plugin-sdk-stoppable-passive-monitor",
		...CHANNEL_CLEANUP_REMOVAL,
		owner: "channel",
		subpath: "extension-shared",
		names: ["runStoppablePassiveMonitor"],
		replacement: "Use `openclaw/plugin-sdk/channel-outbound.runPassiveAccountLifecycle` with stop: (monitor) => monitor.stop()."
	},
	{
		code: "plugin-sdk-advertised-lan-host",
		...CHANNEL_CLEANUP_REMOVAL,
		owner: "sdk",
		subpath: "gateway-runtime",
		names: ["resolveAdvertisedLanHost"],
		replacement: "None; advertised LAN host discovery is host-owned and has no public SDK replacement."
	},
	{
		code: "plugin-sdk-json-file-fallback-reader",
		...CHANNEL_CLEANUP_REMOVAL,
		owner: "sdk",
		subpath: "json-store",
		names: ["readJsonFileWithFallback"],
		replacement: "None; plugins that read JSON artifacts must own parsing, fallback, and file-existence handling."
	},
	{
		code: "plugin-sdk-secret-input-mode-normalizer",
		...CHANNEL_CLEANUP_REMOVAL,
		owner: "provider",
		subpath: "provider-auth",
		names: ["normalizeSecretInputModeInput"],
		replacement: "None; validate plugin-owned input as the exported SecretInputMode values plaintext or ref."
	},
	{
		code: "plugin-sdk-persistent-dedupe-legacy-json-migration",
		removeAfter: "2026-10-04",
		owner: "sdk",
		subpath: "persistent-dedupe",
		names: [
			"PersistentDedupeLegacyJsonMigrationOptions",
			"PersistentDedupeLegacyJsonMigrationResult",
			"listPersistentDedupeLegacyJsonFileEntries",
			"migratePersistentDedupeLegacyJsonFile"
		],
		replacement: "None; the legacy JSON migration was retired. Runtime dedupe continues through the SQLite-backed persistent-dedupe APIs."
	},
	{
		code: "plugin-sdk-provider-auth-copilot-helpers",
		removeAfter: "2026-10-01",
		owner: "provider",
		subpath: "provider-auth",
		names: [
			"CachedCopilotToken",
			"DEFAULT_COPILOT_API_BASE_URL",
			"deriveCopilotApiBaseUrlFromToken",
			"resolveCopilotApiToken"
		],
		replacement: "Provider-local auth APIs for GitHub Copilot; none in the public SDK. Third-party plugins must own their provider-specific token exchange and caching."
	}
];
function buildRemovedExportRecord(e) {
	return {
		code: e.code,
		status: "removed",
		owner: e.owner,
		removeAfter: e.removeAfter,
		replacement: e.replacement,
		docsPath: "/plugins/sdk-migration/removed-surfaces#retroactively-recorded-shipped-exports",
		surfaces: e.names.map((t) => `openclaw/plugin-sdk/${e.subpath}.${t}`),
		diagnostics: ["plugin SDK shipped-surface guard and migration guide"]
	};
}
const PLUGIN_SDK_REMOVED_EXPORT_RECORDS = [
	...REMOVED_EXPORT_SEEDS.map(buildRemovedExportRecord),
	{
		code: "plugin-sdk-heartbeat-reply-runtime",
		status: "removed",
		owner: "agent-runtime",
		removeAfter: "2026-10-03",
		replacement: "Use ordinary Automations and the producer-owned terminal reply contract from openclaw/plugin-sdk/agent-harness-runtime; heartbeat-specific prompt and reply normalization no longer applies.",
		docsPath: "/plugins/sdk-migration/removed-surfaces#heartbeat-executor-and-wake-helpers",
		surfaces: [
			"openclaw/plugin-sdk/reply-runtime.HEARTBEAT_PROMPT",
			"openclaw/plugin-sdk/reply-runtime.DEFAULT_HEARTBEAT_ACK_MAX_CHARS",
			"openclaw/plugin-sdk/reply-runtime.resolveHeartbeatPromptCore",
			"openclaw/plugin-sdk/reply-runtime.stripHeartbeatToken",
			"openclaw/plugin-sdk/reply-runtime.resolveHeartbeatReplyPayload",
			"openclaw/plugin-sdk/reply-runtime.HEARTBEAT_TOKEN"
		],
		diagnostics: ["plugin SDK shipped-surface guard and migration guide"]
	},
	{
		code: "plugin-sdk-heartbeat-agent-harness-runtime",
		status: "removed",
		owner: "agent-runtime",
		removeAfter: "2026-10-03",
		replacement: "Use ordinary reply text and the standard silent reply convention; the heartbeat response SDK helpers are no longer exported.",
		docsPath: "/plugins/sdk-migration/removed-surfaces#heartbeat-executor-and-wake-helpers",
		surfaces: [
			"openclaw/plugin-sdk/agent-harness-runtime.HeartbeatToolResponse",
			"openclaw/plugin-sdk/agent-harness-runtime.HEARTBEAT_RESPONSE_TOOL_NAME",
			"openclaw/plugin-sdk/agent-harness-runtime.normalizeHeartbeatToolResponse"
		],
		diagnostics: ["plugin SDK shipped-surface guard and migration guide"]
	},
	{
		code: "plugin-sdk-reply-silence-parsers",
		status: "removed",
		owner: "agent-runtime",
		removeAfter: "2026-10-12",
		replacement: "Delivery plugins forward prepared text without parsing it. Harness producers use prepareAgentRunTerminalReply from openclaw/plugin-sdk/agent-harness-runtime once and publish its terminalReply. Import SILENT_REPLY_TOKEN from openclaw/plugin-sdk/reply-runtime instead of reply-chunking.",
		docsPath: "/plugins/sdk-migration/removed-surfaces#reply-silence-parsing",
		surfaces: [
			"openclaw/plugin-sdk/reply-chunking.isSilentReplyText",
			"openclaw/plugin-sdk/reply-chunking.isSilentReplyPayloadText",
			"openclaw/plugin-sdk/reply-chunking.SILENT_REPLY_TOKEN"
		],
		diagnostics: ["plugin SDK shipped-surface guard and migration guide"]
	}
];
//#endregion
//#region src/plugins/compat/plugin-sdk-subpath-records.ts
const PLUGIN_SDK_SUBPATH_SEEDS = [
	{
		code: "plugin-sdk-channel-streaming-subpath",
		subpath: "channel-streaming",
		status: "removed",
		owner: "channel",
		replacement: "`openclaw/plugin-sdk/channel-outbound`"
	},
	{
		code: "plugin-sdk-config-runtime-subpath",
		subpath: "config-runtime",
		status: "removed",
		removeAfter: "2026-09-30",
		owner: "config",
		replacement: "`api.pluginConfig`, `openclaw/plugin-sdk/config-mutation`, `openclaw/plugin-sdk/runtime-config-snapshot`, and `openclaw/plugin-sdk/config-contracts`"
	},
	{
		code: "plugin-sdk-inbound-reply-dispatch-subpath",
		subpath: "inbound-reply-dispatch",
		owner: "channel",
		removalGate: "stable-deprecation-period",
		replacement: "`openclaw/plugin-sdk/channel-inbound` and `openclaw/plugin-sdk/channel-outbound`"
	},
	{
		code: "plugin-sdk-channel-reply-pipeline-subpath",
		subpath: "channel-reply-pipeline",
		status: "removed",
		removeAfter: "2026-09-30",
		owner: "channel",
		replacement: "`openclaw/plugin-sdk/channel-outbound`"
	},
	{
		code: "plugin-sdk-infra-runtime-subpath",
		subpath: "infra-runtime",
		status: "removed",
		removeAfter: "2026-09-30",
		owner: "sdk",
		replacement: "focused typed subpaths including `openclaw/plugin-sdk/system-event-runtime`, `openclaw/plugin-sdk/error-runtime`, `openclaw/plugin-sdk/approval-runtime`, and `openclaw/plugin-sdk/ssrf-runtime`; use injected runtime APIs for host operations without a public subpath"
	},
	{
		code: "plugin-sdk-text-runtime-subpath",
		subpath: "text-runtime",
		status: "removed",
		owner: "sdk",
		replacement: "`openclaw/plugin-sdk/logging-core`, `openclaw/plugin-sdk/text-chunking`, `openclaw/plugin-sdk/text-utility-runtime`, and `openclaw/plugin-sdk/string-coerce-runtime`"
	},
	{
		code: "plugin-sdk-channel-secret-runtime-subpath",
		subpath: "channel-secret-runtime",
		status: "removed",
		owner: "channel",
		replacement: "`openclaw/plugin-sdk/channel-secret-basic-runtime` and `openclaw/plugin-sdk/channel-secret-tts-runtime`"
	},
	{
		code: "plugin-sdk-agent-config-primitives-subpath",
		subpath: "agent-config-primitives",
		status: "removed",
		owner: "config",
		replacement: "`openclaw/plugin-sdk/channel-config-schema`"
	},
	{
		code: "plugin-sdk-matrix-subpath",
		subpath: "matrix",
		status: "removed",
		owner: "channel",
		replacement: "`openclaw/plugin-sdk/run-command`"
	},
	{
		code: "plugin-sdk-channel-logging-subpath",
		subpath: "channel-logging",
		status: "removed",
		owner: "channel",
		replacement: "`openclaw/plugin-sdk/channel-inbound` and `openclaw/plugin-sdk/channel-outbound`"
	},
	{
		code: "plugin-sdk-channel-lifecycle-subpath",
		subpath: "channel-lifecycle",
		status: "removed",
		removeAfter: "2026-09-30",
		owner: "channel",
		replacement: "`openclaw/plugin-sdk/channel-outbound`"
	},
	{
		code: "plugin-sdk-channel-message-subpath",
		subpath: "channel-message",
		status: "removed",
		removeAfter: "2026-09-30",
		owner: "channel",
		replacement: "`openclaw/plugin-sdk/channel-outbound` and `openclaw/plugin-sdk/channel-inbound`"
	},
	{
		code: "plugin-sdk-command-auth-subpath",
		subpath: "command-auth",
		status: "removed",
		removeAfter: "2026-10-01",
		owner: "sdk",
		replacement: "`openclaw/plugin-sdk/channel-ingress-runtime` for sender authorization; matching named exports from `openclaw/plugin-sdk/command-auth-native`, `openclaw/plugin-sdk/command-status`, `openclaw/plugin-sdk/models-provider-runtime`, and `openclaw/plugin-sdk/channel-inbound`; adapt legacy authorization types to the ingress contract"
	},
	{
		code: "plugin-sdk-discord-subpath",
		subpath: "discord",
		status: "removed",
		removeAfter: "2026-10-01",
		owner: "channel",
		replacement: "matching named exports from `openclaw/plugin-sdk/channel-contract`, `openclaw/plugin-sdk/channel-core`, `openclaw/plugin-sdk/channel-plugin-common`, `openclaw/plugin-sdk/channel-status`, or `openclaw/plugin-sdk/config-contracts`; external plugins use generic channel contracts and the injected runtime for channel-owned behavior"
	},
	{
		code: "plugin-sdk-telegram-account-subpath",
		subpath: "telegram-account",
		status: "removed",
		removeAfter: "2026-10-01",
		owner: "channel",
		replacement: "generic channel contracts and injected runtime helpers for external plugins; the Telegram plugin's `api.ts` for repository consumers"
	},
	{
		code: "plugin-sdk-group-access-subpath",
		subpath: "group-access",
		status: "removed",
		owner: "channel",
		replacement: "`openclaw/plugin-sdk/channel-ingress-runtime`"
	},
	{
		code: "plugin-sdk-zod-subpath",
		subpath: "zod",
		status: "removed",
		owner: "sdk",
		replacement: "the direct `zod` package import"
	}
];
function buildPluginSdkSubpathRecord(e) {
	const t = {
		code: e.code,
		owner: e.owner,
		replacement: e.replacement,
		docsPath: "/plugins/sdk-migration",
		surfaces: [`openclaw/plugin-sdk/${e.subpath}`]
	};
	if ("status" in e && e.status === "removed") return {
		...t,
		status: e.status,
		removeAfter: "removeAfter" in e ? e.removeAfter : void 0,
		diagnostics: ["plugin SDK compatibility registry and migration guide"]
	};
	return {
		...t,
		status: "status" in e ? e.status : "deprecated",
		deprecated: "2026-07-06",
		warningStarts: "2026-07-06",
		removalGate: "removalGate" in e ? e.removalGate : void 0,
		diagnostics: ["repository deprecated API usage guard for core and bundled plugins; no external runtime import warning"]
	};
}
const PLUGIN_SDK_SUBPATH_RECORDS = PLUGIN_SDK_SUBPATH_SEEDS.map(buildPluginSdkSubpathRecord);
const BUNDLED_ONLY_PUBLIC_PLUGIN_SDK_SUBPATH_SEEDS = [
	{
		subpath: "media-understanding",
		status: "removal-pending",
		removeAfter: "2026-09-30",
		replacement: "`api.registerMediaUnderstandingProvider(...)` with provider-owned request helpers and types from `openclaw/plugin-sdk/plugin-entry`; retain the public subpath through the 2026-09-30 window while official plugin consumers migrate",
		docsPath: "/plugins/architecture"
	},
	{
		subpath: "memory-host-core",
		status: "removal-pending",
		removeAfter: "2026-09-30",
		replacement: "host-prepared memory prompts via `openclaw/plugin-sdk/core` and memory capability registration through the injected plugin API; retain the facade through the 2026-09-30 window and until a focused public-artifact read seam exists",
		docsPath: "/plugins/architecture-internals#context-engine-plugins"
	},
	{
		subpath: "plugin-config-runtime",
		status: "removal-pending",
		removeAfter: "2026-12-01",
		replacement: "`api.pluginConfig`, runtime tool context config, and focused `config-contracts`, `runtime-config-snapshot`, or `config-mutation` subpaths; retain the public subpath through the 2026-12-01 window while official plugin consumers migrate",
		docsPath: "/plugins/sdk-runtime"
	},
	{
		subpath: "tool-plugin",
		status: "deprecated",
		replacement: "retain the public subpath until plugin authoring has a nonexecuting static metadata replacement for `defineToolPlugin`; `getToolPluginMetadata` currently reads metadata only from an already-executed entry",
		docsPath: "/plugins/tool-plugins"
	}
];
function buildPublicSdkSubpathRecord({ subpath: e, ...t }) {
	return {
		code: `plugin-sdk-${e}-public-demotion`,
		owner: "sdk",
		deprecated: "2026-07-15",
		warningStarts: "2026-07-15",
		...t,
		surfaces: [`openclaw/plugin-sdk/${e}`],
		diagnostics: ["registry-backed public SDK demotion window; no external runtime import warning"]
	};
}
const BUNDLED_ONLY_PUBLIC_PLUGIN_SDK_SUBPATH_RECORDS = BUNDLED_ONLY_PUBLIC_PLUGIN_SDK_SUBPATH_SEEDS.map(buildPublicSdkSubpathRecord);
//#endregion
//#region src/plugins/compat/progress-receipt-handoff-record.ts
const PROGRESS_RECEIPT_HANDOFF_COMPAT_RECORD = {
	code: "reply-dispatch-progress-receipt-handoff",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-06",
	warningStarts: "2026-10-06",
	removalGate: "stable-deprecation-period",
	replacement: "Adapt editable progress cards through ReplyDispatchRuntimeInfo.adoptProgressDraft. The released receipt-based adoptProgressContinuation type is retained until an announced later ordinary stable release and explicit maintainer approval; the host never offers it, so adapters keep ordinary waiting-reply delivery.",
	docsPath: "/plugins/sdk-migration/compatibility-policy#progress-card-handoff",
	surfaces: ["openclaw/plugin-sdk/reply-runtime.ReplyDispatchRuntimeInfo.adoptProgressContinuation"],
	diagnostics: ["TypeScript @deprecated annotation and migration documentation; no runtime warnings"]
};
//#endregion
//#region src/plugins/compat/reply-tool-authority-record.ts
const REPLY_TOOL_AUTHORITY_COMPAT_RECORD = {
	code: "reply-tool-authority-sync-preparation",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-04",
	warningStarts: "2026-10-04",
	removeAfter: "2026-12-31",
	replacement: "Await the Async reply-operation, fingerprint, and V2 queue companions. Question dispatchers await authority.assertCurrentAsync after transport preparation and assert current authority immediately before I/O. Released synchronous contracts remain through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
	docsPath: "/plugins/sdk-migration/how-to-migrate#await-reply-tool-authority",
	surfaces: [
		"EmbeddedRunAttemptParams.replyOperation",
		"EmbeddedRunAttemptParamsV2.replyOperation",
		"AgentHarnessAttemptParams.replyOperation",
		"AgentHarnessAttemptParamsV2.replyOperation",
		"ReplyToolAuthoritySnapshot.fingerprint and project",
		"ReplyBackendMessageInjectionV2.queueMessage, claimPendingUserInputAnswer, and cancelPendingUserInput",
		"AgentQuestionDispatcher.authority.assertCurrent"
	],
	diagnostics: ["TypeScript @deprecated annotations and bounded warnings on legacy preparation or injection fallbacks; supported prepared projections and live effect assertions remain silent"]
};
//#endregion
//#region src/plugins/compat/transcript-stats-record.ts
const TRANSCRIPT_STATS_COMPAT_RECORD = {
	code: "session-transcript-sync-statistics",
	status: "deprecated",
	owner: "sdk",
	removeAfter: "2026-12-31",
	deprecated: "2026-10-11",
	warningStarts: "2026-10-11",
	replacement: "Await readTranscriptStatsAsync from session-store-runtime, or readTranscriptStatsBatchReadOnlyAsync and statSessionEntry from memory-core-host-engine-sessions. Batch reads preserve input order, duplicate IDs, and null results for unavailable stores through the existing history worker. Worker-local kernels and supplied statistics may retain direct synchronous reads; legacy main-thread SDK calls remain compatible through 2026-12-31.",
	docsPath: "/plugins/sdk-migration/how-to-migrate#await-transcript-statistics",
	surfaces: [
		"openclaw/plugin-sdk/session-store-runtime.readTranscriptStatsSync",
		"openclaw/plugin-sdk/memory-core-host-engine-sessions.readTranscriptStatsBatchReadOnlySync",
		"openclaw/plugin-sdk/memory-core-host-engine-sessions.statSessionEntrySync"
	],
	diagnostics: ["TypeScript @deprecated annotations and one shared DEP_PLUGIN_SDK warning per plugin and session-store family on main-thread legacy use; worker-local reads do not warn"]
};
//#endregion
//#region src/plugins/compat/session-persistence-records.ts
const DEPRECATED_SESSION_COMPAT = {
	status: "deprecated",
	owner: "sdk",
	removeAfter: "2026-12-31",
	diagnostics: ["TypeScript @deprecated annotations and migration documentation; bounded capability-family warnings on legacy preparation"]
};
const SESSION_PERSISTENCE_COMPAT_RECORDS = [
	REPLY_TOOL_AUTHORITY_COMPAT_RECORD,
	TRANSCRIPT_STATS_COMPAT_RECORD,
	{
		code: "session-store-sync-listing",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-11",
		warningStarts: "2026-10-11",
		replacement: "Await listSessionEntriesAsync with an explicit agentId for read-only metadata; use getSessionEntryAsync for complete entries. Retain final deletion and disclosure authority at the effect boundary. The synchronous listing remains compatible through 2026-12-31.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-session-metadata-listings",
		surfaces: ["openclaw/plugin-sdk/session-store-runtime.listSessionEntries", "api.runtime.agent.session.listSessionEntries"],
		diagnostics: ["TypeScript @deprecated annotations and one shared DEP_PLUGIN_SDK warning per plugin and session-store family per process on legacy use"]
	},
	{
		code: "github-publication-native-callbacks",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-09",
		warningStarts: "2026-10-09",
		replacement: "Use requestForSessionV2 and requestForClaimV2 with the host-provided GitHubPublicationRequesterV2, and requestPersonalForSessionV2 and confirmPersonalV2 with PersonalGitHubSessionActionV2. Await deferClaimPreparationAsync, deferOrphanedRequestsAsync, listUnreportedResultsAsync, markReportedAsync, readAsync, and personalStatusAsync. Legacy publication methods retain their signatures but fail at invocation. On githubOAuthService, await cancelAuthorizationAsync and retireProfileAsync; on its personal service, await cancelAuthorizationAsync and disconnectAsync. These OAuth compatibility methods retain synchronous completion. Deprecated signatures will be removed in the first January 2027 stable release after the final compatibility day, 2026-12-31.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-github-publication-operations",
		surfaces: [
			"GatewayRequestHandlerOptions.context.githubPublicationService.requestForSession",
			"GatewayRequestHandlerOptions.context.githubPublicationService.requestForClaim",
			"GatewayRequestHandlerOptions.context.githubPublicationService.requestPersonalForSession",
			"GatewayRequestHandlerOptions.context.githubPublicationService.confirmPersonal",
			"GatewayRequestHandlerOptions.context.githubPublicationService.deferClaimPreparation",
			"GatewayRequestHandlerOptions.context.githubPublicationService.deferOrphanedRequests",
			"GatewayRequestHandlerOptions.context.githubPublicationService.listUnreportedResults",
			"GatewayRequestHandlerOptions.context.githubPublicationService.markReported",
			"GatewayRequestHandlerOptions.context.githubPublicationService.personalStatus",
			"GatewayRequestHandlerOptions.context.githubOAuthService.cancelAuthorization",
			"GatewayRequestHandlerOptions.context.githubOAuthService.retireProfile",
			"GatewayRequestHandlerOptions.context.githubOAuthService.personal.cancelAuthorization",
			"GatewayRequestHandlerOptions.context.githubOAuthService.personal.disconnect",
			"GitHubPublicationRequester",
			"GitHubPublicationRequesterPolicy",
			"PersonalGitHubSessionAction",
			"getPluginRuntimeGatewayRequestScope().context.githubPublicationService",
			"getPluginRuntimeGatewayRequestScope().context.githubOAuthService.personal"
		],
		diagnostics: ["TypeScript @deprecated annotations naming the V2 or Async replacement; one shared runtime DEP_PLUGIN_SDK warning per plugin and github-publication family per process, including bounded unscoped SDK use"]
	},
	{
		code: "session-store-opaque-mutations",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-09",
		warningStarts: "2026-10-09",
		replacement: "Use prepareSessionEntryPatch for host preparation followed by an exact-snapshot conditional commit, applySessionEntryPatch for data-only patches, and updateLastRouteWithAuthority for guarded route updates. Legacy opaque transaction guards retain their ordering and will be removed in the first January 2027 stable release after the final compatibility day, 2026-12-31.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#prepare-session-entry-changes",
		surfaces: [
			"openclaw/plugin-sdk/session-store-runtime.patchSessionEntry",
			"openclaw/plugin-sdk/session-store-runtime.updateSessionStoreEntry",
			"openclaw/plugin-sdk/session-store-runtime.updateLastRoute.assertCommitAllowed",
			"api.runtime.agent.session.patchSessionEntry",
			"api.runtime.agent.session.updateSessionStoreEntry",
			"api.runtime.channel.session.updateLastRoute.assertCommitAllowed"
		],
		diagnostics: ["TypeScript @deprecated annotations and one shared DEP_PLUGIN_SDK warning per plugin and session-store family per process on legacy use"]
	},
	{
		code: "codex-transcript-sync-validation",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-06",
		warningStarts: "2026-10-06",
		replacement: "Await readCodexSessionContextProjection for retained worker projection and final validation. Keep the released synchronous validators through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major. readCodexSessionContext remains a supported synchronous worker reader with its released three-argument generic result contract.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-session-transcript-persistence",
		surfaces: ["openclaw/plugin-sdk/codex-session-transcript-runtime.validateCodexSessionTranscriptReadAdmission", "openclaw/plugin-sdk/codex-session-transcript-runtime.validateCodexSessionTranscriptContextVersion"]
	},
	{
		code: "deprecated-session-store-beta5-api",
		status: "removed",
		removeAfter: "2026-09-30",
		owner: "sdk",
		deprecated: "2026-07-12",
		warningStarts: "2026-07-12",
		replacement: "Use `getSessionEntryAsync(...)` and `listSessionEntriesAsync(...)` for reads; `prepareSessionEntryPatch(...)`, `applySessionEntryPatch(...)`, `upsertSessionEntry(...)`, and `deleteSessionEntry(...)` for row mutations; and session identity with `session-transcript-runtime` for active transcripts. The supported-plugin cutoff excludes v2026.7.1-beta.5 and other packages importing the retired bridge.",
		docsPath: "/plugins/sdk-migration/removed-surfaces#removed-session-and-transcript-file-apis",
		surfaces: [
			"openclaw/plugin-sdk/session-store-runtime loadSessionStore",
			"openclaw/plugin-sdk/session-store-runtime updateSessionStore",
			"openclaw/plugin-sdk/session-store-runtime resolveSessionFilePath",
			"openclaw/plugin-sdk/session-store-runtime resolveSessionStoreEntry",
			"openclaw/plugin-sdk/session-store-runtime LoadSessionStoreOptions",
			"openclaw/plugin-sdk/session-store-runtime UpdateSessionStoreOptions",
			"openclaw package root loadSessionStore",
			"openclaw package root saveSessionStore"
		],
		diagnostics: ["plugin compatibility registry and migration guide"]
	},
	{
		code: "transcript-lock-sync-message-preparation",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-05",
		warningStarts: "2026-10-08",
		replacement: "Use withSessionTranscriptWrite (or withCodexSessionTranscriptMirrorWrite) with preparation.prepareMessage and preparation.source. Legacy lock and opaque callback forms retain durable transaction ordering through 2026-12-31; incognito targets reject them with migration guidance.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-locked-transcript-preparation",
		surfaces: [
			"SessionTranscriptWriteLockContext.appendMessage.prepareMessageAfterIdempotencyCheck",
			"CodexSessionTranscriptMirrorWriteLockContext.appendMessageWithMessageSequence.prepareMessageAfterIdempotencyCheck",
			"SessionTranscriptWriteLockContext.appendMessage.beforeFreshMessageCommit",
			"CodexSessionTranscriptMirrorWriteLockContext.appendMessageWithMessageSequence.beforeFreshMessageCommit",
			"openclaw/plugin-sdk/session-transcript-runtime.withSessionTranscriptWriteLock",
			"openclaw/plugin-sdk/codex-session-transcript-runtime.withCodexSessionTranscriptMirrorWriteLock"
		],
		diagnostics: ["TypeScript @deprecated annotations; one runtime warning per plugin for legacy transcript callbacks/locks; incognito targets receive an actionable replacement error"]
	},
	{
		code: "session-upstream-links-sync-persistence",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-05",
		warningStarts: "2026-10-05",
		replacement: "Await upsertSessionUpstreamLinkAsync and deleteSessionUpstreamLinkAsync from session-catalog. Official harnesses await the native initializer's linkAsync method. Retain the synchronous signatures and completion timing shipped in v2026.9.8 through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-session-upstream-links",
		surfaces: [
			"openclaw/plugin-sdk/session-catalog.upsertSessionUpstreamLink",
			"openclaw/plugin-sdk/session-catalog.deleteSessionUpstreamLink",
			"openclaw/plugin-sdk/agent-harness-session-runtime.createNativeSessionInitializationOwner().prepare().link"
		],
		diagnostics: ["TypeScript @deprecated annotations and one shared DEP_SESSION_PERSISTENCE warning per plugin and upstream-link capability family; unscoped consumers share one SDK-level warning"]
	},
	{
		code: "session-observer-progress-sync-reads",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-04",
		warningStarts: "2026-10-04",
		replacement: "Await sessionObserver.handleEventAsync, getCompanionSnapshotAsync, and disposeAsync. Use reply_dispatch shouldSendToolSummariesAsync/shouldSendFullToolDetailsAsync and onVerboseProgressVisibilityAsync. Retain synchronous contracts through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-session-observer-and-progress-visibility",
		surfaces: [
			"GatewayRequestHandlerOptions.context.sessionObserver.handleEvent",
			"GatewayRequestHandlerOptions.context.sessionObserver.getCompanionSnapshot",
			"GatewayRequestHandlerOptions.context.sessionObserver.dispose",
			"PluginHookReplyDispatchEvent.shouldSendToolSummaries",
			"PluginHookReplyDispatchEvent.shouldSendFullToolDetails",
			"GetReplyOptions.onVerboseProgressVisibility",
			"tryDispatchAcpReplyHook boolean-only event inputs"
		]
	},
	{
		code: "channel-inbound-sync-envelope-timestamps",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-05",
		warningStarts: "2026-10-05",
		replacement: "Await readSessionUpdatedAtAsync, createChannelInboundEnvelopeBuilderAsync, or resolveInboundSessionEnvelopeContextAsync at each message's formatting boundary. Resolve routes through resolveAgentRoute and use dispatchInboundDirectDm. Retain the synchronous signatures and callback timing shipped in 2026.9.8 through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-migration/compatibility-policy#inbound-envelope-timestamps",
		surfaces: [
			"openclaw/plugin-sdk/session-store-runtime.readSessionUpdatedAt",
			"api.runtime.channel.session.readSessionUpdatedAt",
			"openclaw/plugin-sdk/channel-inbound.createChannelInboundEnvelopeBuilder",
			"openclaw/plugin-sdk/channel-inbound.resolveChannelInboundRouteEnvelope",
			"openclaw/plugin-sdk/channel-inbound.resolveInboundSessionEnvelopeContext",
			"openclaw/plugin-sdk/channel-inbound.dispatchInboundDirectDmWithRuntime",
			"openclaw/plugin-sdk/inbound-envelope.createInboundEnvelopeBuilder",
			"openclaw/plugin-sdk/inbound-envelope.resolveInboundRouteEnvelopeBuilder",
			"openclaw/plugin-sdk/inbound-envelope.resolveInboundRouteEnvelopeBuilderWithRuntime"
		]
	},
	{
		code: "reply-run-start-unprepared-transcript",
		...DEPRECATED_SESSION_COMPAT,
		owner: "agent-runtime",
		deprecated: "2026-10-04",
		warningStarts: "2026-10-04",
		replacement: "Use onPreparedAgentRunStart with a required transcriptStart field, forwarding the complete notification and synchronous return value. Bundled runtimes prepare the facts asynchronously; retain the released onAgentRunStart callback and omitted-facts synchronous read through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-migration/compatibility-policy#reply-run-start-transcript-facts",
		surfaces: ["openclaw/plugin-sdk/reply-runtime.GetReplyOptions.onAgentRunStart", "PluginHookReplyDispatchContext.onAgentRunStart"],
		diagnostics: ["TypeScript @deprecated annotation and one runtime DEP_SESSION_PERSISTENCE warning per plugin and callback family per process"]
	},
	{
		code: "session-manager-sync-context-read",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-04",
		warningStarts: "2026-10-04",
		replacement: "Await SessionManager.readSessionContextAsync for full-fidelity context consumption. The synchronous reader retains its shipped result through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-session-transcript-persistence",
		surfaces: ["SessionManager.readSessionContext"],
		diagnostics: ["TypeScript @deprecated annotation and one runtime DEP_SESSION_PERSISTENCE warning per plugin and capability family per process"]
	},
	{
		code: "session-reset-freshness-sync-read",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-05",
		warningStarts: "2026-10-05",
		replacement: "Await runtime.channel.session.resolveEntryResetFreshnessAsync. The released synchronous resolveEntryResetFreshness method retains its parameters and result through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-migration#session-reset-freshness",
		surfaces: ["api.runtime.channel.session.resolveEntryResetFreshness"],
		diagnostics: ["TypeScript @deprecated annotation and migration documentation; bounded capability-family warnings on legacy preparation"]
	},
	{
		code: "agent-end-sync-side-effects",
		...DEPRECATED_SESSION_COMPAT,
		owner: "agent-runtime",
		deprecated: "2026-10-04",
		warningStarts: "2026-10-04",
		replacement: "Await runAgentEndSideEffectsAsync before releasing the turn lease. The released runAgentEndSideEffects helper retains its synchronous void result and scheduling behavior through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-agent-harness/attempt-runtime#agent-end-side-effects",
		surfaces: ["openclaw/plugin-sdk/agent-harness-runtime.runAgentEndSideEffects"],
		diagnostics: ["TypeScript @deprecated annotation and migration documentation; bounded capability-family warnings on legacy preparation"]
	},
	{
		code: "native-session-generation-sync-authority",
		...DEPRECATED_SESSION_COMPAT,
		owner: "agent-runtime",
		deprecated: "2026-10-03",
		warningStarts: "2026-10-03",
		replacement: "Await retainNativeSessionGenerationAuthority, resolvePreparedNativeSessionBinding, and reclaimNativeSessionGenerationWithAuthority. Release prepared captures after terminal cleanup. Released synchronous capture and two-argument mutation callbacks remain deprecated while published official harness readers migrate.",
		docsPath: "/plugins/sdk-migration/compatibility-policy#native-session-generation-authority",
		surfaces: [
			"openclaw/plugin-sdk/agent-harness-session-runtime.captureNativeSessionGenerationAuthority",
			"openclaw/plugin-sdk/agent-harness-session-runtime.resolveNativeSessionBinding",
			"openclaw/plugin-sdk/agent-harness-session-runtime.reclaimNativeSessionGeneration",
			"openclaw/plugin-sdk/agent-harness-session-runtime.NativeSessionGenerationOperations"
		]
	},
	{
		code: "native-session-deletion-unbound-callbacks",
		...DEPRECATED_SESSION_COMPAT,
		owner: "agent-runtime",
		deprecated: "2026-10-11",
		warningStarts: "2026-10-11",
		replacement: "Pass participants from createNativeSessionBindingLifecycleV2.withDeletion for reversible stored bindings or createNativeSessionCommitFinalizer for commit-only cleanup. Factory-produced participants and the existing harness hooks remain supported; direct unbound callbacks retain synchronous commit and rollback through 2026-12-31.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#replace-unbound-native-session-deletion-callbacks",
		surfaces: [
			"AgentHarnessSessionDeletionMutation unbound commit/rollback callbacks",
			"AgentHarness.withSessionDeletion unbound mutation argument",
			"AgentHarness.withSessionContextReset unbound mutation argument"
		],
		diagnostics: ["TypeScript contract documentation and one shared DEP_SESSION_PERSISTENCE warning per plugin and native-session-deletion family per process, emitted only for unbound callbacks"]
	},
	{
		code: "session-manager-sync-persistence",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-01",
		warningStarts: "2026-10-01",
		replacement: "Await the matching Async-suffixed SessionManager method, including the returned rewrite commit. For resolveCurrentTurnEntryId with includeOmittedCustomMessages, await openAsync and traverse the complete view without that option. Shipped synchronous adapters remain compatible during their deprecation period and will be removed in the first January 2027 stable release after the final compatibility day, 2026-12-31.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-session-transcript-persistence",
		surfaces: [
			"SessionManager.appendMessage",
			"SessionManager.appendMessageWithTranscriptAnchor",
			"SessionManager.appendCompaction",
			"SessionManager.appendResetBoundary",
			"SessionManager.appendCustomEntry",
			"SessionManager.appendSessionInfo",
			"SessionManager.appendCustomMessageEntry",
			"SessionManager.appendLeafControl",
			"SessionManager.appendLabelChange",
			"SessionManager.branch",
			"SessionManager.branchWithSummary",
			"SessionManager.removeTrailingEntries",
			"SessionManager.persist",
			"SessionManager.prepareTranscriptRewrite",
			"SessionManager.appendMessageToTranscript",
			"SessionManager.open",
			"SessionManager.openBounded",
			"SessionManager.openDetachedBounded",
			"SessionManager.openModelContext",
			"SessionManager.setSessionTarget",
			"SessionManager.reloadPersistedTranscript",
			"SessionManager.resolveCurrentTurnEntryId.includeOmittedCustomMessages"
		],
		diagnostics: ["TypeScript @deprecated annotations naming awaited twins", "one runtime DEP_SESSION_PERSISTENCE warning per plugin and capability family per process"]
	},
	{
		code: "extension-session-sync-persistence",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-01",
		warningStarts: "2026-10-01",
		replacement: "Await ExtensionAPI.appendEntryAsync, setSessionNameAsync, and setLabelAsync, and AgentSession.setSessionNameAsync. Existing synchronous third-party methods retain their void return contract through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-extension-session-changes",
		surfaces: [
			"ExtensionAPI.appendEntry",
			"ExtensionAPI.setSessionName",
			"ExtensionAPI.setLabel",
			"AgentSession.setSessionName"
		],
		diagnostics: ["TypeScript @deprecated annotations, migration guide, and shared once-per-plugin-and-family DEP_SESSION_PERSISTENCE warning"]
	},
	{
		code: "provider-replay-sync-persistence",
		...DEPRECATED_SESSION_COMPAT,
		owner: "provider",
		deprecated: "2026-10-01",
		warningStarts: "2026-10-01",
		replacement: "Use ProviderPlugin.sanitizeReplayHistoryAsync with ProviderSanitizeReplayHistoryContextV2 and await ProviderReplaySessionStateV2.appendCustomEntryAsync; use sanitizeGoogleGeminiReplayHistoryAsync for the shared Gemini implementation. Retain legacy third-party contexts and hooks through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-provider-replay-metadata",
		surfaces: [
			"ProviderPlugin.sanitizeReplayHistory",
			"ProviderReplaySessionState.appendCustomEntry",
			"openclaw/plugin-sdk/provider-model-shared.sanitizeGoogleGeminiReplayHistory",
			"ProviderSanitizeReplayHistoryContext",
			"ProviderReplaySessionState"
		],
		diagnostics: ["TypeScript @deprecated annotations, versioned migration guide, and shared once-per-plugin-and-family DEP_SESSION_PERSISTENCE warning"]
	},
	{
		code: "agent-execution-preparation-released-signature",
		status: "active",
		owner: "sdk",
		replacement: "Keep the execution input shapes shipped in v2026.9.9 and v2026.10.1-beta.1 by openOpenClawAgentSqliteWorkerStore, including the beta capturePreparedGenerationClaim method for parameter-derived types. Private native-adoption capabilities are not plugin requirements. The released two-argument prepare contract remains supported without migration or deprecation; host admission reuses the native owner’s published schema facts.",
		docsPath: "/plugins/sdk-migration/compatibility-policy#agent-execution-preparation-compatibility",
		surfaces: ["openclaw/plugin-sdk/sqlite-runtime.openOpenClawAgentSqliteWorkerStore publicationSource.execution", "openclaw/plugin-sdk/sqlite-runtime.openOpenClawAgentSqliteWorkerStore publicationSource.execution.prepare"],
		diagnostics: ["SDK type assertions and compatibility documentation; no runtime warnings"]
	},
	{
		code: "acp-session-sync-read",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-11",
		warningStarts: "2026-10-11",
		replacement: "Await readAcpSessionEntryAsync. Bundled consumers use the existing worker-backed reader; the released synchronous reader keeps its result contract through 2026-12-31; removal ships in the first January 2027 stable release.",
		docsPath: "/plugins/sdk-migration/compatibility-policy#acp-metadata-binding-compatibility",
		surfaces: ["openclaw/plugin-sdk/acp-runtime.readAcpSessionEntry", "AcpSessionManager.resolveSession"],
		diagnostics: ["TypeScript @deprecated annotation and one shared DEP_PLUGIN_SDK warning per plugin and ACP-session family per process on legacy use"]
	},
	{
		code: "acp-session-metadata-released-signatures",
		status: "active",
		owner: "sdk",
		replacement: "Keep the released one-argument ACP reader and manager read/write injection signatures. Internal actor bindings are not plugin arguments; actor activation must preserve these callable contracts. The APIs remain supported and are not deprecated.",
		docsPath: "/plugins/sdk-migration/compatibility-policy#acp-metadata-binding-compatibility",
		surfaces: [
			"openclaw/plugin-sdk/acp-runtime.readAcpSessionEntryAsync",
			"AcpSessionManagerDeps.loadSessionEntryAsync",
			"AcpSessionManagerDeps.upsertSessionMeta"
		],
		diagnostics: ["SDK type assertions and compatibility documentation; no runtime warnings"]
	},
	{
		code: "memory-session-released-signatures",
		status: "active",
		owner: "sdk",
		replacement: "Keep the released Memory entry, corpus, and reset-recall reader signatures. Internal actor sources are not plugin arguments; actor activation must preserve the existing Promise results and synchronous message observers. These APIs remain supported and are not deprecated.",
		docsPath: "/plugins/sdk-migration/compatibility-policy#memory-session-binding-compatibility",
		surfaces: [
			"openclaw/plugin-sdk/memory-core-host-engine-sessions.buildSessionEntry",
			"openclaw/plugin-sdk/memory-core-host-engine-sessions.listSessionTranscriptCorpusEntriesForAgent",
			"openclaw/plugin-sdk/memory-core-host-engine-sessions.readSessionResetRecallCutoff"
		],
		diagnostics: ["SDK type assertions and compatibility documentation; no runtime warnings"]
	},
	{
		code: "transcript-strict-sync-message-preparation",
		...DEPRECATED_SESSION_COMPAT,
		deprecated: "2026-10-05",
		warningStarts: "2026-10-08",
		replacement: "Use preparation.prepareMessage and preparation.source with appendSessionTranscriptMessageByIdentityStrict or appendSessionTranscriptMessageByIdentity. Legacy opaque callbacks retain durable transaction ordering through 2026-12-31; incognito targets reject them with migration guidance.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-strict-transcript-message-preparation",
		surfaces: [
			"appendSessionTranscriptMessageByIdentityStrict.prepareMessageAfterIdempotencyCheck",
			"appendSessionTranscriptMessageByIdentityStrict.beforeFreshMessageCommit",
			"appendSessionTranscriptMessageByIdentity.prepareMessageAfterIdempotencyCheck",
			"appendSessionTranscriptMessageByIdentity.beforeFreshMessageCommit"
		],
		diagnostics: ["TypeScript @deprecated annotations; one runtime warning per plugin shared with legacy transcript locks; incognito targets receive an actionable replacement error"]
	}
];
//#endregion
//#region src/plugins/compat/session-transcript-view-record.ts
const SESSION_TRANSCRIPT_VIEW_COMPAT_RECORD = {
	code: "session-transcript-sync-view",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-11",
	warningStarts: "2026-10-11",
	removeAfter: "2026-12-31",
	replacement: "Await loadCombinedSessionStoreForGatewayAsync from openclaw/plugin-sdk/session-transcript-hit. The synchronous export retains its complete, non-incognito view through 2026-12-31; removal ships in the first January 2027 stable release.",
	docsPath: "/plugins/sdk-migration/compatibility-policy#session-transcript-search-views",
	surfaces: ["openclaw/plugin-sdk/session-transcript-hit loadCombinedSessionStoreForGateway"],
	diagnostics: ["Bounded DEP_PLUGIN_SDK warning for synchronous session transcript views"]
};
//#endregion
//#region src/plugins/compat/sqlite-runtime-records.ts
const SQLITE_RUNTIME_COMPAT_RECORDS = [{
	code: "sqlite-runtime-native-access",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-09",
	warningStarts: "2026-10-09",
	removeAfter: "2026-12-31",
	replacement: "Use openOpenClawAgentSqliteWorkerStoreV2 with required live authority and serializable domain commands. Worker backends use sqlite-worker-runtime primitives; explicit readOnly inspection and offline Doctor maintenance retain their native contracts. Native callbacks are not serialized or moved by adding await. Released calls retain their signatures and synchronous transaction ordering through the deprecation period and are removed in the first January 2027 stable release after the final compatibility day, 2026-12-31.",
	docsPath: "/plugins/sdk-migration/how-to-migrate#replace-native-sqlite-runtime-writes",
	surfaces: [
		"openclaw/plugin-sdk/sqlite-runtime.openNodeSqliteDatabase writable handles",
		"openclaw/plugin-sdk/sqlite-runtime.openOpenClawAgentSqliteWorkerStore publicationSource.DatabaseSync",
		"openclaw/plugin-sdk/sqlite-runtime.openOpenClawAgentDatabase",
		"openclaw/plugin-sdk/sqlite-runtime.borrowOpenClawAgentDatabase",
		"openclaw/plugin-sdk/sqlite-runtime.withOpenClawAgentDatabaseAsync",
		"openclaw/plugin-sdk/sqlite-runtime.withOpenClawAgentDatabaseWrite",
		"openclaw/plugin-sdk/sqlite-runtime.runOpenClawAgentWriteAdmission",
		"openclaw/plugin-sdk/sqlite-runtime.runSqliteImmediateTransaction",
		"openclaw/plugin-sdk/sqlite-runtime.runSqliteImmediateTransactionSync",
		"openclaw/plugin-sdk/sqlite-runtime.executeSqliteQuerySync",
		"openclaw/plugin-sdk/sqlite-runtime.executeSqliteQueryTakeFirstSync",
		"openclaw/plugin-sdk/sqlite-runtime.iterateSqliteQuerySync",
		"openclaw/plugin-sdk/sqlite-runtime.prepareSqliteQuerySync",
		"openclaw/plugin-sdk/sqlite-runtime.getNodeSqliteKysely"
	],
	diagnostics: ["TypeScript @deprecated annotations and one shared warning per plugin identity and capability family on actual legacy use; unscoped consumers share a bounded SDK warning"]
}];
//#endregion
//#region src/plugins/compat/web-search-provider-list-record.ts
const WEB_SEARCH_PROVIDER_LIST_COMPAT_RECORD = {
	code: "web-search-sync-provider-list",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-11",
	warningStarts: "2026-10-11",
	removeAfter: "2026-12-31",
	replacement: "Await runtime.webSearch.listProvidersAsync(params). The synchronous listProviders(params) retains its return shape through 2026-12-31; removal ships in the first January 2027 stable release.",
	docsPath: "/plugins/sdk-migration/compatibility-policy#web-search-provider-lists",
	surfaces: ["PluginRuntime.webSearch.listProviders"],
	diagnostics: ["Bounded DEP_PLUGIN_SDK warning for synchronous web-search provider lists"]
};
//#endregion
//#region src/plugins/compat/workspace-mutation-guard.ts
const WORKSPACE_MUTATION_GUARD_COMPAT_RECORD = {
	code: "workspace-mutation-guard-callback",
	status: "deprecated",
	owner: "sdk",
	deprecated: "2026-10-02",
	warningStarts: "2026-10-02",
	removeAfter: "2026-12-31",
	replacement: "Await database preparation before ensureAgentWorkspace and use SQL-free guard.assertHost for live authority. Internal recovery predicates run on the worker transaction connection.",
	docsPath: "/plugins/sdk-migration/how-to-migrate#workspace-mutation-guards",
	surfaces: ["api.runtime.agent.ensureAgentWorkspace.beforePersistentApply"],
	diagnostics: ["@deprecated JSDoc and one DEP_WORKSPACE_MUTATION_GUARD warning per process", "Warning explains before-dispatch timing and deprecated but allowed synchronous OpenClaw DB access"]
};
//#endregion
//#region src/plugins/compat/registry-records.ts
function defineCompatRecords(e) {
	return e;
}
function sdkCompatRecord(e, t) {
	return {
		code: e,
		status: "deprecated",
		owner: "sdk",
		...t
	};
}
const PLUGIN_COMPAT_RECORDS = defineCompatRecords([
	...PLUGIN_SDK_REMOVED_EXPORT_RECORDS,
	...AGENT_HARNESS_COMPAT_RECORDS,
	AUTH_ASYNC_COMPAT_RECORD,
	...ASYNC_SQLITE_PREPARATION_COMPAT_RECORDS,
	...BINDING_PERSISTENCE_COMPAT_RECORDS,
	CHANNEL_PAIRING_COMPAT_RECORD,
	CRON_STORE_PATH_COMPAT_RECORD,
	sdkCompatRecord("mention-inbox-sync-persistence", {
		deprecated: "2026-10-03",
		warningStarts: "2026-10-03",
		removalGate: "stable-deprecation-period",
		replacement: "Await mentionInbox.listAsync(client, publish), mentionInbox.dismissAsync(client, ids, publish), mentionInbox.recordCommittedInputAsync(input), and mentionInbox.invalidateAsync(sessionKey). Publish list/dismiss responses synchronously inside the supplied callback. Deprecated synchronous signatures remain until an announced later ordinary stable release; list/dismiss return UNAVAILABLE, invalidate throws migration guidance, and recordCommittedInput queues the worker operation after commit.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-mention-inbox-operations",
		surfaces: [
			"GatewayRequestHandlerOptions.context.mentionInbox.list",
			"GatewayRequestHandlerOptions.context.mentionInbox.dismiss",
			"GatewayRequestHandlerOptions.context.mentionInbox.recordCommittedInput",
			"GatewayRequestHandlerOptions.context.mentionInbox.invalidate",
			"getPluginRuntimeGatewayRequestScope().context.mentionInbox"
		],
		diagnostics: ["TypeScript @deprecated annotations, explicit migration-directed rejection, and one DEP_SESSION_PERSISTENCE warning per plugin and capability family per process; unscoped callers share one SDK-level family warning"]
	}),
	sdkCompatRecord("model-account-connect-sync-persistence", {
		deprecated: "2026-10-03",
		warningStarts: "2026-10-03",
		removeAfter: "2026-12-31",
		replacement: "Await modelAccountConnectService.listLinksAsync, linkAsync, unlinkAsync, listAsync, selectAsync, statusAsync, and cancelAsync with the existing arguments. Retain synchronous methods and their completion timing for shipped third-party contracts through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-personal-model-account-operations",
		surfaces: [
			"GatewayRequestHandlerOptions.context.modelAccountConnectService.listLinks",
			"GatewayRequestHandlerOptions.context.modelAccountConnectService.link",
			"GatewayRequestHandlerOptions.context.modelAccountConnectService.unlink",
			"GatewayRequestHandlerOptions.context.modelAccountConnectService.list",
			"GatewayRequestHandlerOptions.context.modelAccountConnectService.select",
			"GatewayRequestHandlerOptions.context.modelAccountConnectService.status",
			"GatewayRequestHandlerOptions.context.modelAccountConnectService.cancel",
			"getPluginRuntimeGatewayRequestScope().context.modelAccountConnectService"
		],
		diagnostics: ["TypeScript @deprecated annotations and one DEP_SESSION_PERSISTENCE warning per plugin and capability family per process; unscoped callers share one SDK-level family warning"]
	}),
	WORKSPACE_MUTATION_GUARD_COMPAT_RECORD,
	...SESSION_PERSISTENCE_COMPAT_RECORDS,
	sdkCompatRecord("skill-command-discovery-sync", {
		deprecated: "2026-10-11",
		warningStarts: "2026-10-11",
		removeAfter: "2026-12-31",
		replacement: "Await prepareSkillCommandsForAgents or prepareSkillCommandsForWorkspace. Synchronous list methods retain their array results through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#await-skill-command-discovery",
		surfaces: [
			"openclaw/plugin-sdk/skill-commands-runtime.listSkillCommandsForAgents",
			"openclaw/plugin-sdk/skill-commands-runtime.listSkillCommandsForWorkspace",
			"openclaw/plugin-sdk/command-auth-native.listSkillCommandsForAgents"
		],
		diagnostics: ["TypeScript @deprecated annotations and one runtime warning per plugin and capability family"]
	}),
	...SQLITE_RUNTIME_COMPAT_RECORDS,
	NATIVE_EXEC_APPROVAL_COMPAT_RECORD,
	sdkCompatRecord("tts-preferences-sync-resolution", {
		deprecated: "2026-10-03",
		warningStarts: "2026-10-03",
		removeAfter: "2026-12-31",
		replacement: "Await resolveTtsPrefsPathAsync(config) for the machine-owned path. For prompt hints, await the public api.runtime.tts.buildSystemPromptHintAsync method. Bundled plugins can also await private prepareTtsPreferences and pass preparedTtsPreferences to the supported synchronous hint overload. The unprepared synchronous hint and preference-path calls remain compatible through 2026-12-31; removal ships in the first January 2027 stable release.",
		docsPath: "/plugins/sdk-migration/async-transcript-and-tts",
		surfaces: [
			"openclaw/plugin-sdk/agent-runtime resolveTtsPrefsPath",
			"openclaw/plugin-sdk/tts-runtime resolveTtsPrefsPath",
			"openclaw/plugin-sdk/tts-runtime buildTtsSystemPromptHint"
		],
		diagnostics: ["Bounded DEP_PLUGIN_SDK warning for legacy path resolution and unprepared synchronous hint calls; prepared hints remain silent"]
	}),
	...AGENT_LIST_RUNTIME_PROJECTION_COMPAT_RECORDS,
	sdkCompatRecord("watched-sessions-sync-harness-context", {
		deprecated: "2026-10-03",
		warningStarts: "2026-10-03",
		removeAfter: "2026-12-31",
		replacement: "Await prepareWatchedSessionsHarnessContext with an assertCurrent callback bound to the current host capability. The released buildWatchedSessionsHarnessContext retains its synchronous string-or-undefined result through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-migration/compatibility-policy#watched-session-harness-context",
		surfaces: ["openclaw/plugin-sdk/agent-harness-runtime.buildWatchedSessionsHarnessContext"],
		diagnostics: ["TypeScript @deprecated annotation and migration documentation; bounded capability-family warnings on legacy preparation"]
	}),
	WEB_SEARCH_PROVIDER_LIST_COMPAT_RECORD,
	PROGRESS_RECEIPT_HANDOFF_COMPAT_RECORD,
	{
		code: "runtime-config-sync-load",
		status: "deprecated",
		owner: "config",
		deprecated: "2026-10-11",
		warningStarts: "2026-10-11",
		removeAfter: "2026-12-31",
		replacement: "Use readRuntimeConfig for the already prepared runtime snapshot. At a cold preparation boundary, await captureRuntimeConfigAsyncReader()() first or use its returned config. The released getRuntimeConfig keeps its synchronous cold-load behavior through 2026-12-31; removal ships in the first January 2027 stable release.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#read-prepared-runtime-config",
		surfaces: ["openclaw/plugin-sdk/runtime-config-snapshot.getRuntimeConfig", "openclaw/plugin-sdk/memory-core-host-runtime-core.getRuntimeConfig"],
		diagnostics: ["TypeScript @deprecated annotation and one DEP_SESSION_PERSISTENCE warning per plugin and runtime-config family per process on legacy use"]
	},
	ASSISTANT_TEXT_PHASE_TERMINAL_HINT_COMPAT_RECORD,
	SESSION_TRANSCRIPT_VIEW_COMPAT_RECORD,
	PLUGIN_SDK_PRIVATE_RUNTIME_EXPORT_COMPAT_RECORD,
	CHANNEL_PREPARED_TOOL_POLICY_COMPAT_RECORD,
	sdkCompatRecord("plugin-sdk-session-header-link", {
		deprecated: "2026-10-12",
		warningStarts: "2026-10-12",
		removeAfter: "2027-01-12",
		replacement: "Register a plugin-owned `session-header` accessory that renders its own content; the host no longer supplies session conversation-link metadata",
		docsPath: "/plugins/sdk-migration/compatibility-policy#session-header-link-helper",
		surfaces: ["openclaw/plugin-sdk/control-ui.createSessionHeaderLink"],
		diagnostics: ["TypeScript @deprecated annotation and shipped Plugin SDK surface check"]
	}),
	sdkCompatRecord("gateway-placement-sync-results", {
		deprecated: "2026-10-02",
		warningStarts: "2026-10-02",
		removalGate: "stable-deprecation-period",
		replacement: "Await getManyAsync, retireSessionPlacementAsync, listPendingWorkspaceResultsAsync, getWorkspaceResultReconcilingSessionIdsAsync, getAdmittedDeviceSessionCountsAsync, and deferOrphanedRequestsAsync on the Gateway context. For placement standing-grant preparation, await resolveBindingAsync, retainAsync, and validateAsync. Placement get/getMany read committed in-process receipts only; cold reads require getAsync/getManyAsync. Synchronous placement inventories and writes retain their deprecated signatures but fail with migration guidance; use listAsync, listForReconcileAsync, clearLocalTurnClaimsAfterRestartAsync, retireSessionPlacementAsync, and the result-reader replacements. Other listed surfaces follow their owner-specific migration contracts.",
		docsPath: "/plugins/sdk-migration/compatibility-policy#gateway-placement-and-publication-readers",
		surfaces: [
			"GatewayRequestHandlerOptions.context.workerSessionPlacementService.getMany",
			"GatewayRequestHandlerOptions.context.workerSessionPlacementService.retireSessionPlacement",
			"GatewayRequestHandlerOptions.context.workerSessionPlacementService.clearLocalTurnClaimsAfterRestart",
			"GatewayRequestHandlerOptions.context.workerPlacementDispatchService.getAdmittedDeviceSessionCounts",
			"GatewayRequestHandlerOptions.context.placementStandingGrants.resolveBinding",
			"GatewayRequestHandlerOptions.context.placementStandingGrants.retain",
			"GatewayRequestHandlerOptions.context.placementStandingGrants.validate",
			"GatewayRequestHandlerOptions.context.workerSessionPlacementService.listPendingWorkspaceResults",
			"GatewayRequestHandlerOptions.context.workerSessionPlacementService.getWorkspaceResultReconcilingSessionIds",
			"GatewayRequestHandlerOptions.context.githubPublicationService.deferOrphanedRequests",
			"getPluginRuntimeGatewayRequestScope().context"
		],
		diagnostics: ["TypeScript @deprecated annotations and migration documentation; placement reads, retirement, and restart clearing warn once per plugin and capability family on legacy use, while GitHub orphan deferral shares the github-publication family warning"]
	}),
	...MEMORY_SESSION_COMPAT_RECORDS,
	{
		code: "channel-webhook-listener-config-inputs",
		status: "deprecated",
		owner: "config",
		deprecated: "2026-09-26",
		warningStarts: "2026-09-26",
		removalGate: "stable-deprecation-period",
		replacement: "Use legacyWebhook for canonical listener config. Doctor migrates stored webhookPort/webhookHost and webhook.port inputs; deprecated optional TypeScript properties preserve config producer source compatibility until an approved ordinary stable removal.",
		docsPath: "/gateway/doctor/config-migrations#channel-webhook-listeners",
		surfaces: [
			"TelegramAccountConfig.webhookPort",
			"TelegramAccountConfig.webhookHost",
			"FeishuConfig.webhookPort",
			"FeishuConfig.webhookHost",
			"FeishuAccountConfig.webhookPort",
			"FeishuAccountConfig.webhookHost",
			"MSTeamsWebhookConfig.port",
			"NextcloudTalkAccountConfig.webhookPort",
			"NextcloudTalkAccountConfig.webhookHost"
		],
		diagnostics: ["TypeScript @deprecated annotations and plugin-owned Doctor migration"]
	},
	{
		code: "conversation-binding-sync-mutations",
		status: "deprecated",
		owner: "channel",
		deprecated: "2026-09-20",
		warningStarts: "2026-09-20",
		removeAfter: "2026-12-31",
		replacement: "Await getSessionBindingService().bind, unbind, inspectByConversationAsync, resolveByConversationAsync, touchAsync, resolveRuntimeConversationBindingRouteAsync, and the Async-suffixed thread-binding lifecycle setters. Bundled current-conversation mutations and session listings use the existing worker owner. Project prepared inspection facts with inspectRuntimeConversationBindingRoute. Legacy external adapters retain their synchronous projection contract.",
		docsPath: "/plugins/sdk-runtime/channel#awaited-conversation-binding-mutations",
		surfaces: [
			"SessionBindingService.touch",
			"SessionBindingService.resolveByConversation",
			"SessionBindingAdapter.touch",
			"SessionBindingAdapter.resolveByConversation",
			"resolveRuntimeConversationBindingRoute",
			"ChannelConversationBindingSupport.setIdleTimeoutBySessionKey",
			"ChannelConversationBindingSupport.setMaxAgeBySessionKey",
			"api.runtime.channel.threadBindings.setIdleTimeoutBySessionKey",
			"api.runtime.channel.threadBindings.setMaxAgeBySessionKey",
			"@openclaw/discord.setThreadBindingIdleTimeoutBySessionKey",
			"@openclaw/discord.setThreadBindingMaxAgeBySessionKey",
			"@openclaw/telegram.setTelegramThreadBindingIdleTimeoutBySessionKey",
			"@openclaw/telegram.setTelegramThreadBindingMaxAgeBySessionKey",
			"@openclaw/matrix.setMatrixThreadBindingIdleTimeoutBySessionKey",
			"@openclaw/matrix.setMatrixThreadBindingMaxAgeBySessionKey"
		],
		diagnostics: ["TypeScript @deprecated annotations and bounded capability-family warnings on legacy binding calls"]
	},
	...PLUGIN_SDK_SUBPATH_RECORDS,
	...BUNDLED_ONLY_PUBLIC_PLUGIN_SDK_SUBPATH_RECORDS,
	...DEPRECATION_MARKING_COMPAT_RECORDS,
	MEDIA_LEGACY_PROJECTION_COMPAT_RECORD,
	sdkCompatRecord("node-workspace-sync-acquisition", {
		deprecated: "2026-09-15",
		warningStarts: "2026-09-15",
		removeAfter: "2026-12-31",
		replacement: "Await context.acquireManagedWorkspaceAsync(request) and release the returned lease in finally. Retain synchronous acquisition for supported external plugins through 2026-12-31; removal ships in the first January 2027 stable release.",
		docsPath: "/plugins/sdk-migration/how-to-migrate#managed-node-workspace-acquisition",
		surfaces: ["OpenClawPluginNodeHostCommandContext.acquireManagedWorkspace"],
		diagnostics: ["TypeScript @deprecated annotation and bounded capability-family warning on legacy workspace acquisition"]
	}),
	sdkCompatRecord("plugin-state-sync-keyed-store", {
		deprecated: "2026-09-11",
		warningStarts: "2026-09-11",
		removeAfter: "2026-12-31",
		replacement: "Use api.runtime.state.openKeyedStoreV2 or createPluginStateKeyedStoreV2, await data-only operations, and replace update/deleteIf closures with observe/compareAndApply. Synchronous methods retain commit-before-return through 2026-12-31; removal ships in the first January 2027 stable release without an SDK major.",
		docsPath: "/plugins/sdk-runtime/state-and-system#synchronous-keyed-store-migration",
		surfaces: [
			"api.runtime.state.openSyncKeyedStore",
			"PluginStateSyncKeyedStore",
			"createPluginStateSyncKeyedStore",
			"PluginStateSyncKeyedStore.register",
			"PluginStateSyncKeyedStore.registerIfAbsent",
			"PluginStateSyncKeyedStore.update",
			"PluginStateSyncKeyedStore.deleteIf",
			"PluginStateSyncKeyedStore.lookup",
			"PluginStateSyncKeyedStore.lookupMany",
			"PluginStateSyncKeyedStore.consume",
			"PluginStateSyncKeyedStore.delete",
			"PluginStateSyncKeyedStore.entries",
			"PluginStateSyncKeyedStore.count",
			"PluginStateSyncKeyedStore.clear",
			"PluginStateKeyedStore.update",
			"PluginStateKeyedStore.deleteIf"
		],
		diagnostics: ["TypeScript @deprecated annotations and state-store migration documentation", "plugin compatibility inventory; legacy writer migrations use the shared once-per-plugin-and-capability-family warning policy"]
	}),
	sdkCompatRecord("memory-read-result-statusless-success", {
		deprecated: "2026-08-19",
		warningStarts: "2026-08-19",
		removalGate: "stable-deprecation-period",
		replacement: "`MemoryReadResult` with explicit `status: \"ok\" | \"not_found\"`",
		docsPath: "/plugins/sdk-migration#memory-read-missing-results",
		surfaces: ["statusless external memory manager read results"],
		diagnostics: ["host memory-manager acquisition adapter"]
	}),
	sdkCompatRecord("context-engine-legacy-host-param-default", {
		status: "removed",
		replacement: "`ContextEngineInfo.acceptedHostParams` for restricted projection; omitted declarations receive full host params",
		docsPath: "/concepts/context-engine#the-contextengine-interface",
		surfaces: ["ContextEngineInfo.acceptedHostParams and undeclared-engine default projection"],
		diagnostics: ["plugin compatibility registry and context engine guide"]
	}),
	sdkCompatRecord("removed-global-api-provider-publication", {
		status: "removed",
		replacement: "provider plugins via `api.registerProvider(...)`; host/runtime code registers against its lifecycle-owned `ApiRegistry`",
		docsPath: "/plugins/sdk-migration#process-global-api-provider-publication",
		surfaces: ["openclaw/plugin-sdk/llm registerApiProvider", "openclaw/plugin-sdk/llm unregisterApiProviders"],
		diagnostics: ["plugin SDK compatibility registry and migration guide"]
	}),
	sdkCompatRecord("legacy-deactivate-hook-alias", {
		status: "removed",
		replacement: "`gateway_stop` hook",
		docsPath: "/plugins/sdk-migration#deactivate-hook-alias",
		surfaces: ["api.on(\"deactivate\", ...)", "plugin typed hook registration"],
		diagnostics: ["plugin compatibility registry and migration guide"]
	}),
	sdkCompatRecord("legacy-subagent-spawning-hook", {
		status: "removed",
		replacement: "`subagent_spawned` for post-launch observation; core session-binding adapters for thread routing",
		docsPath: "/plugins/hooks#upcoming-deprecations",
		surfaces: [
			"api.on(\"subagent_spawning\", ...)",
			"PluginHookSubagentSpawningEvent",
			"PluginHookSubagentSpawningResult",
			"SubagentLifecycleHookRunner.runSubagentSpawning"
		],
		diagnostics: ["plugin compatibility registry and migration guide"]
	}),
	sdkCompatRecord("removed-skill-proposal-hooks", {
		status: "removed",
		removeAfter: "2026-10-07",
		docsPath: "/plugins/sdk-migration/removed-surfaces#skill-workshop-proposal-hooks",
		surfaces: [
			"api.on(\"skill_proposal_evaluate\", ...)",
			"api.on(\"skill_proposal_changed\", ...)",
			"openclaw/plugin-sdk/plugin-entry.PluginHookSkillProposalEvaluateEvent",
			"openclaw/plugin-sdk/plugin-entry.PluginHookSkillProposalEvaluateResult",
			"openclaw/plugin-sdk/plugin-entry.PluginHookSkillProposalEvaluationOutcome",
			"openclaw/plugin-sdk/plugin-entry.PluginHookSkillProposalChangedEvent",
			"openclaw/plugin-sdk/plugin-entry.PluginHookSkillProposalKind",
			"openclaw/plugin-sdk/plugin-entry.PluginHookSkillEvaluationFinding",
			"openclaw/plugin-sdk/plugin-entry.PluginHookSkillBundleFile",
			"openclaw/plugin-sdk/plugin-entry.PluginHookSkillBundleSnapshot",
			"PluginHookSkillChangedEvent.proposal"
		],
		diagnostics: ["plugin compatibility registry and migration guide"]
	}),
	sdkCompatRecord("hook-only-plugin-shape", {
		status: "active",
		replacement: "explicit capability registration",
		docsPath: "/plugins/sdk-migration",
		surfaces: [
			"plugin shape inspection",
			"plugins inspect",
			"status diagnostics"
		],
		diagnostics: ["plugin compatibility notice"]
	}),
	sdkCompatRecord("deprecated-memory-embedding-provider-api", {
		status: "removed",
		replacement: "`api.registerEmbeddingProvider(...)` and `contracts.embeddingProviders`",
		docsPath: "/plugins/sdk-migration#memory-embedding-provider-api",
		surfaces: [
			"api.registerMemoryEmbeddingProvider(...)",
			"contracts.memoryEmbeddingProviders",
			"openclaw/plugin-sdk/memory-core-host-engine-embeddings registerMemoryEmbeddingProvider",
			"plugin compatibility registry and migration guide"
		],
		diagnostics: ["plugin compatibility registry and migration guide"]
	}),
	sdkCompatRecord("plugin-sdk-session-agent-resolution-aliases", {
		deprecated: "2026-08-29",
		warningStarts: "2026-08-29",
		removeAfter: "2026-11-29",
		replacement: "`resolveSessionAgentIdsStrict` and `resolveSessionAgentIdStrict` with an explicit agent, agent-scoped session key, prepared fallback, or persisted owner",
		docsPath: "/plugins/compatibility#session-agent-resolution-aliases",
		surfaces: [
			"openclaw/plugin-sdk/agent-scope-runtime resolveSessionAgentIds and resolveSessionAgentId",
			"openclaw/plugin-sdk/agent-runtime session-agent resolver aliases",
			"openclaw/plugin-sdk/agent-harness-runtime session-agent resolver aliases",
			"openclaw/plugin-sdk/memory-core-host-runtime-core session-agent resolver alias",
			"openclaw/plugin-sdk/memory-host-core session-agent resolver alias"
		],
		diagnostics: ["TypeScript deprecated SDK alias annotations", "plugin compatibility registry"]
	}),
	sdkCompatRecord("agent-harness-credential-prompt-string-argument", {
		deprecated: "2026-09-09",
		warningStarts: "2026-09-09",
		removeAfter: "2026-11-30",
		replacement: "options object `{ controlToolsAvailable }`",
		docsPath: "/plugins/sdk-migration/removed-surfaces#credential-prompt-builder",
		surfaces: ["openclaw/plugin-sdk/agent-harness-runtime buildCredentialSafetyPrompt string argument"],
		diagnostics: ["JSDoc parameter deprecation", "plugin compatibility registry"]
	}),
	sdkCompatRecord("removed-session-transcript-file-api", {
		status: "removed",
		replacement: "session identity (`sessionKey`/`sessionId`), `SessionTranscriptUpdate.target`, and Gateway/runtime session helpers",
		docsPath: "/plugins/sdk-migration#removed-session-and-transcript-file-apis",
		surfaces: [
			"saveSessionStore",
			"resolveSessionTranscriptPathInDir",
			"resolveAndPersistSessionFile",
			"readLatestAssistantTextFromSessionTranscript",
			"SessionTranscriptUpdate.sessionFile",
			"sessionFiles",
			"transcriptPath",
			"sessionFile",
			"plugins inspect compatibility notices"
		],
		diagnostics: ["plugin compatibility notice"]
	}),
	{
		code: "hook.before_tool_call.terminal-block-approval",
		status: "active",
		owner: "agent-runtime",
		docsPath: "/plugins/hooks",
		surfaces: ["before_tool_call block result", "before_tool_call approval result"],
		diagnostics: ["hook runner contract check"]
	},
	{
		code: "hook.llm-observer.privacy-payload",
		status: "active",
		owner: "agent-runtime",
		docsPath: "/plugins/hooks",
		surfaces: [
			"llm_input",
			"llm_output",
			"agent_end",
			"allowConversationAccess"
		],
		diagnostics: ["conversation access hook contract check"]
	},
	{
		code: "api.capture.runtime-registrars",
		status: "active",
		owner: "plugin-execution",
		docsPath: "/plugins/architecture-internals",
		surfaces: [
			"createCapturedPluginRegistration",
			"capturePluginRegistration",
			"OpenClawPluginApi"
		],
		diagnostics: ["runtime registration capture contract check"]
	},
	{
		code: "channel.runtime.envelope-config-metadata",
		status: "active",
		owner: "channel",
		docsPath: "/plugins/sdk-channel-plugins",
		surfaces: [
			"api.registerChannel",
			"channel setup metadata",
			"channel message envelope"
		],
		diagnostics: ["channel runtime contract check"]
	},
	{
		code: "whatsapp-web-inbound-flat-message-aliases",
		status: "removed",
		owner: "channel",
		replacement: "WhatsApp `WebInboundCallbackMessage` nested contexts: `event`, `payload`, `quote`, `group`, and `platform`",
		docsPath: "/plugins/compatibility",
		surfaces: [
			"@openclaw/whatsapp WebInboundMessage flat fields",
			"WhatsApp monitorWebInbox onMessage callback",
			"WhatsApp monitorWebChannel listenerFactory injected messages"
		],
		diagnostics: ["plugin compatibility registry and compatibility guide"]
	},
	{
		code: "whatsapp-web-inbound-admission-top-level-fields",
		status: "removed",
		owner: "channel",
		replacement: "WhatsApp `WebInboundMessage.admission` fields: `conversation.id`, `accountId`, `ingress.decision`, and `conversation.kind`",
		docsPath: "/plugins/compatibility",
		surfaces: [
			"@openclaw/whatsapp WebInboundMessage top-level admission fields",
			"WhatsApp monitorWebInbox onMessage callback",
			"WhatsApp monitorWebChannel listenerFactory injected messages"
		],
		diagnostics: ["plugin compatibility registry and compatibility guide"]
	},
	sdkCompatRecord("sdk-untrusted-context-identifier-aliases", {
		status: "removal-pending",
		deprecated: "2026-07-22",
		warningStarts: "2026-07-22",
		removeAfter: "2026-09-08",
		replacement: "`MsgContext.ChannelPromptContext`, `MsgContext.ChannelStructuredContext`, `ChannelStructuredContextEntry`, `SupplementalContextFacts.channelStructuredContext`, and `buildChannelMetadata`; retain the aliases until migration of published plugin readers is verified and explicit breaking-release approval is granted",
		docsPath: "/plugins/compatibility",
		surfaces: [
			"openclaw/plugin-sdk reply-runtime MsgContext.UntrustedContext and UntrustedStructuredContext",
			"openclaw/plugin-sdk reply-runtime UntrustedStructuredContextEntry",
			"openclaw/plugin-sdk channel-inbound SupplementalContextFacts.untrustedContext",
			"openclaw/plugin-sdk security-runtime buildUntrustedChannelMetadata"
		],
		diagnostics: ["TypeScript deprecated SDK alias annotations"]
	}),
	sdkCompatRecord("channel-explicit-target-parser", {
		status: "removed",
		replacement: "`messaging.targetResolver` for target normalization and `messaging.resolveOutboundSessionRoute` for session/thread identity",
		docsPath: "/plugins/sdk-migration",
		surfaces: [
			"ChannelMessagingAdapter.parseExplicitTarget",
			"openclaw/plugin-sdk/channel-route ChannelRouteExplicitTarget",
			"openclaw/plugin-sdk/channel-route ChannelRouteExplicitTargetParser",
			"openclaw/plugin-sdk/channel-route resolveChannelRouteTargetWithParser"
		],
		diagnostics: ["plugin SDK compatibility warning"]
	}),
	sdkCompatRecord("channel-messaging-targets-subpath", {
		status: "removed",
		replacement: "`openclaw/plugin-sdk/channel-targets`",
		docsPath: "/plugins/sdk-migration",
		surfaces: ["openclaw/plugin-sdk/messaging-targets"],
		diagnostics: ["plugin SDK compatibility warning"]
	}),
	{
		code: "bundled-plugin-allowlist",
		status: "active",
		owner: "config",
		replacement: "manifest-owned plugin enablement and scoped load plans",
		docsPath: "/plugins/architecture",
		surfaces: [
			"plugins.allow",
			"bundled provider startup",
			"plugins status"
		],
		diagnostics: ["plugin status report"]
	},
	{
		code: "bundled-plugin-enablement",
		status: "active",
		owner: "config",
		replacement: "manifest-owned plugin defaults and scoped load plans",
		docsPath: "/plugins/architecture",
		surfaces: [
			"plugins.entries",
			"bundled provider startup",
			"plugins status"
		],
		diagnostics: ["plugin status report"]
	},
	...ACTIVATION_HINT_COMPAT_RECORDS,
	{
		code: "embedded-pi-agent-sdk-aliases",
		status: "removed",
		owner: "agent-runtime",
		replacement: "`runEmbeddedAgent` and `EmbeddedAgent*` SDK/runtime names",
		docsPath: "/plugins/sdk-runtime",
		surfaces: [
			"api.runtime.agent.runEmbeddedPiAgent",
			"openclaw/extension-api runEmbeddedPiAgent",
			"openclaw/plugin-sdk/agent-harness-runtime EmbeddedPi* aliases"
		],
		diagnostics: ["plugin SDK compatibility registry"]
	},
	{
		code: "plugin-sdk-shipped-channel-setup-exports",
		status: "deprecated",
		owner: "channel",
		deprecated: "2026-07-23",
		warningStarts: "2026-07-23",
		replacement: "retain until supported published packages migrate to plugin-owned config schemas plus generic `openclaw/plugin-sdk/channel-config-schema` and `openclaw/plugin-sdk/setup-runtime` primitives",
		docsPath: "/plugins/sdk-migration#published-channel-setup-compatibility",
		surfaces: [
			"openclaw/plugin-sdk/bundled-channel-config-schema SlackConfigSchema",
			"openclaw/plugin-sdk/bundled-channel-config-schema DiscordConfigSchema",
			"openclaw/plugin-sdk/bundled-channel-config-schema SignalConfigSchema",
			"openclaw/plugin-sdk/bundled-channel-config-schema MSTeamsConfigSchema",
			"openclaw/plugin-sdk/setup-runtime createLegacyCompatChannelDmPolicy",
			"openclaw/plugin-sdk/setup-runtime promptLegacyChannelAllowFromForAccount"
		],
		diagnostics: ["repository deprecated API usage guard for core and bundled plugins; no external runtime import warning"]
	},
	{
		code: "generated-bundled-channel-config-fallback",
		status: "active",
		owner: "channel",
		replacement: "manifest registry `channelConfigs` metadata",
		docsPath: "/plugins/manifest",
		surfaces: ["generated bundled channel config metadata", "channel config validation"],
		diagnostics: ["channel config metadata fallback"]
	},
	{
		code: "setup-runtime-fallback",
		status: "active",
		owner: "setup",
		replacement: "`setup.requiresRuntime: false` with complete setup descriptors",
		docsPath: "/plugins/manifest/setup-and-auth#setup-reference",
		surfaces: ["setup-api runtime fallback", "setup.requiresRuntime omitted"],
		diagnostics: ["setup registry runtime diagnostic"]
	}
]);
//#endregion
//#region src/plugins/installed-plugin-index-hash.ts
/** Hashes JSON-serializable data with SHA-256. */
function hashJson(e) {
	return sha256Hex(JSON.stringify(e));
}
/** Hashes JSON-like data independently of object property insertion order. */
function hashStableJson(e) {
	return sha256Hex(stableStringify(e));
}
//#endregion
//#region src/plugins/installed-plugin-index-policy.ts
/** Hashes config policy inputs that can change installed plugin activation. */
function resolveInstalledPluginIndexPolicyHash(e, t, n = {}) {
	const r = normalizePluginsConfig(e?.plugins);
	const i = {};
	const a = e?.channels;
	if (a && typeof a === "object" && !Array.isArray(a)) {
		for (const [e, t] of Object.entries(a)) if (t && typeof t === "object" && !Array.isArray(t)) {
			const n = t.enabled;
			if (typeof n === "boolean") i[e] = n;
		}
	}
	return hashJson({
		plugins: {
			enabled: r.enabled,
			allow: r.allow,
			deny: r.deny,
			bundledDiscovery: readBundledDiscoveryModeMemoized(t, n) ?? null,
			slots: r.slots,
			entries: Object.fromEntries(Object.entries(r.entries).flatMap(([e, t]) => typeof t.enabled === "boolean" ? [[e, t.enabled]] : []).sort(([e], [t]) => e.localeCompare(t)))
		},
		channels: Object.fromEntries(Object.entries(i).sort(([e], [t]) => e.localeCompare(t)))
	});
}
//#endregion
//#region src/plugins/bundled-load-path-aliases.ts
const PACKAGED_BUNDLED_ROOTS = [path.join("dist", "extensions"), path.join("dist-runtime", "extensions")];
/** Normalizes bundled lookup paths without preserving trailing separators. */
function normalizeBundledLookupPath(e) {
	const t = path.normalize(e);
	const n = path.parse(t).root;
	let r = t;
	while (r.length > n.length && (r.endsWith(path.sep) || r.endsWith("/"))) r = r.slice(0, -1);
	return r;
}
function findBundledRoot(e, t = PACKAGED_BUNDLED_ROOTS) {
	const n = normalizeBundledLookupPath(e);
	for (const e of t) {
		const t = `${path.sep}${e}`;
		const r = n.lastIndexOf(t);
		if (r === -1) continue;
		const i = r + t.length;
		if (n.length !== i && n[i] !== path.sep) continue;
		return {
			packageRoot: n.slice(0, r),
			bundledRoot: n.slice(0, i),
			bundledLeaf: n.slice(i + path.sep.length)
		};
	}
	return null;
}
/** Builds the legacy extensions root for a packaged bundled plugin root. */
function buildLegacyBundledRootPath(e) {
	const t = findBundledRoot(e);
	return t ? path.join(t.packageRoot, "extensions") : null;
}
//#endregion
//#region src/plugins/bundled-source-overlays.ts
/** Parses Linux mountinfo content into absolute mount points. */
function parseLinuxMountInfoMountPoints(e) {
	const t = /* @__PURE__ */ new Set();
	for (const n of e.split(/\r?\n/u)) {
		const e = n.trim();
		if (!e) continue;
		const r = e.split(" ")[4];
		if (!r) continue;
		t.add(path.resolve(decodeMountInfoPath(r)));
	}
	return t;
}
function readLinuxMountPoints() {
	const e = getPluginCache().metadata;
	if (!e.discoveryMountPoints) try {
		e.discoveryMountPoints = parseLinuxMountInfoMountPoints(fsSync.readFileSync("/proc/self/mountinfo", "utf8"));
	} catch {
		e.discoveryMountPoints = /* @__PURE__ */ new Set();
	}
	return e.discoveryMountPoints;
}
function isFilesystemMountPoint(e) {
	const t = pluginCacheStatSync(e);
	const n = pluginCacheStatSync(path.dirname(e));
	return Boolean(t && n && (t.dev !== n.dev || t.ino === n.ino));
}
function sourceOverlaysDisabled(e) {
	const t = normalizeOptionalLowercaseString(e.OPENCLAW_DISABLE_BUNDLED_SOURCE_OVERLAYS);
	return t === "1" || t === "true";
}
/** True when a path appears to be a mounted bundled source overlay. */
function isBundledSourceOverlayPath(e) {
	const t = path.resolve(e.sourcePath);
	return (e.mountPoints ?? readLinuxMountPoints()).has(t) || isFilesystemMountPoint(t);
}
/** Lists source overlay directories that shadow packaged bundled plugin dirs. */
function listBundledSourceOverlayDirs(e) {
	if (sourceOverlaysDisabled(e.env ?? process.env) || !e.bundledRoot) return [];
	const t = buildLegacyBundledRootPath(e.bundledRoot);
	if (!t || !pluginCacheExistsSync(t)) return [];
	let n;
	try {
		n = readPluginCacheDirectory(t);
	} catch {
		return [];
	}
	const r = readLinuxMountPoints();
	const i = isBundledSourceOverlayPath({
		sourcePath: t,
		mountPoints: r
	});
	const a = [];
	for (const o of n) {
		if (!o.isDirectory()) continue;
		const n = path.join(t, o.name);
		const s = path.join(e.bundledRoot, o.name);
		if (!pluginCacheExistsSync(s)) continue;
		if (!i && !isBundledSourceOverlayPath({
			sourcePath: n,
			mountPoints: r
		})) continue;
		a.push(n);
	}
	return a.toSorted((e, t) => e.localeCompare(t));
}
//#endregion
//#region packages/llm-core/src/model-data.ts
const MODEL_DATA_APIS = [
	"openai-completions",
	"openai-responses",
	"openai-chatgpt-responses",
	"anthropic-messages",
	"google-generative-ai",
	"google-interactions",
	"google-vertex",
	"github-copilot",
	"bedrock-converse-stream",
	"ollama",
	"pi-messages",
	"azure-openai-responses"
];
const MODEL_DATA_THINKING_FORMATS = [
	"openai",
	"openrouter",
	"deepseek",
	"together",
	"qwen",
	"qwen-chat-template",
	"zai"
];
const MODEL_DATA_THINKING_LEVELS = [
	"off",
	"minimal",
	"low",
	"medium",
	"high",
	"xhigh",
	"max"
];
//#endregion
//#region packages/model-catalog-core/src/model-catalog-types.ts
const MODEL_CATALOG_APIS = [...MODEL_DATA_APIS];
const MODEL_CATALOG_THINKING_FORMATS = [...MODEL_DATA_THINKING_FORMATS];
function isModelCatalogThinkingFormat(e) {
	return MODEL_CATALOG_THINKING_FORMATS.includes(e);
}
const MODEL_FAMILY_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
const MODEL_FAMILY_MAX_LENGTH = 64;
/**
* Canonical model family: the developer lineage a catalog declares for a model, such as
* `anthropic`. Callers pass only provider or catalog metadata, never a model id or name.
*/
function normalizeModelFamily(e) {
	if (typeof e !== "string") return;
	const t = e.trim().toLowerCase();
	return t.length <= MODEL_FAMILY_MAX_LENGTH && MODEL_FAMILY_PATTERN.test(t) ? t : void 0;
}
const MODEL_CATALOG_INPUTS$1 = [
	"text",
	"image",
	"video",
	"document"
];
const MODEL_CATALOG_THINKING_LEVELS = [...MODEL_DATA_THINKING_LEVELS];
const MODEL_CATALOG_STATUSES$1 = [
	"available",
	"preview",
	"deprecated",
	"disabled"
];
//#endregion
//#region packages/model-catalog-core/src/model-inference-capabilities.ts
const positiveInteger = number().int().positive().max(Number.MAX_SAFE_INTEGER);
const questionType = _enum([
	"boolean",
	"choice",
	"score",
	"sort",
	"tags",
	"box"
]);
const questionTypes = array(questionType).min(1).max(6).refine((e) => new Set(e).size === e.length);
const probabilitySemantics = _enum([
	"boolean",
	"categorical",
	"independent",
	"provider-defined",
	"none"
]);
const question = object({
	/** Meaning of the supplied numbers, not a claim of calibrated accuracy. */
	probabilities: probabilitySemantics,
	/** The selected answer may be absent even when probabilities are present. */
	abstention: boolean(),
	minOptions: positiveInteger.optional(),
	maxOptions: positiveInteger.optional(),
	maxImageOptions: positiveInteger.optional(),
	requiresCriteria: boolean().optional()
}).refine((e) => e.minOptions === void 0 || e.maxOptions === void 0 || e.minOptions <= e.maxOptions);
const questions = object({
	boolean: question.optional(),
	choice: question.optional(),
	score: question.optional(),
	sort: question.optional(),
	tags: question.optional(),
	box: question.optional()
}).refine((e) => Object.values(e).some(Boolean));
const reasoningMode = _enum([
	"auto",
	"off",
	"on"
]);
const reasoning = object({
	modes: array(reasoningMode).min(1).max(3).refine((e) => new Set(e).size === e.length),
	default: reasoningMode.optional(),
	questionTypes: questionTypes.optional(),
	/** Execution metadata is different from generated reasoning text. */
	metadata: boolean().optional()
}).refine((e) => e.default === void 0 || e.modes.includes(e.default));
const billingSource = _enum([
	"provider-docs",
	"provider-catalog",
	"configured"
]);
const billing = discriminatedUnion("unit", [object({
	unit: literal("tokens"),
	source: billingSource,
	/** Omitted rates are unknown; explicit zero is a published free token bucket. */
	usdPerMillion: object({
		input: number().nonnegative().finite().optional(),
		output: number().nonnegative().finite().optional()
	}).optional()
}), object({
	unit: _enum(["decision-units", "requests"]),
	source: billingSource,
	usdPerMillion: never().optional()
})]);
/** Provider-declared facts for one physical route; never execution or grounding authority. */
const ModelInferenceCapabilitiesSchema = object({
	/** Explicit declarations never infer chat support from text encoding or structured output. */
	chat: boolean(),
	decision: object({
		/** Provider-owned wire adapter identifier, not an endpoint or credential identity. */
		protocol: string().max(64).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/),
		input: array(_enum(["text", "image"])).min(1).max(2).refine((e) => new Set(e).size === e.length),
		/** Absent means undeclared kinds/semantics, not an invented support claim. */
		questions: questions.optional(),
		confidence: _enum(["provider-specific", "none"]).optional(),
		reasoning: reasoning.optional(),
		/** Support only. A request still needs explicit shared policy for extra egress/billing. */
		grounding: object({
			webSearch: boolean(),
			questionTypes: questionTypes.optional()
		}).optional(),
		limits: object({
			maxQuestions: positiveInteger.optional(),
			maxRequestTokens: positiveInteger.optional(),
			maxStateAndQuestionTokens: positiveInteger.optional(),
			maxInputTokens: positiveInteger.optional(),
			inputTokenScope: _enum(["encoded-question", "state-plus-each-criterion"]).optional(),
			image: object({
				maxBytes: positiveInteger,
				mimeTypes: array(_enum([
					"image/png",
					"image/jpeg",
					"image/webp"
				])).min(1).max(3),
				remoteUrls: boolean()
			}).optional()
		}).optional(),
		billing: billing.optional()
	}).refine((e) => {
		const supported = (t) => e.questions === void 0 || e.questions[t] !== void 0;
		return (e.reasoning?.questionTypes?.every(supported) ?? true) && (e.grounding?.questionTypes?.every(supported) ?? true) && (e.limits?.image === void 0 || e.input.includes("image"));
	}).optional()
});
//#endregion
//#region packages/model-catalog-core/src/model-catalog-normalize.ts
const MODEL_CATALOG_INPUTS = new Set(MODEL_CATALOG_INPUTS$1);
const MODEL_CATALOG_DISCOVERY_MODES = /* @__PURE__ */ new Set([
	"static",
	"refreshable",
	"runtime"
]);
const MODEL_CATALOG_STATUSES = new Set(MODEL_CATALOG_STATUSES$1);
const MODEL_CATALOG_API_SET = new Set(MODEL_CATALOG_APIS);
/** Reject object keys that can mutate prototypes when copied into records. */
function isBlockedObjectKey(e) {
	return e === "__proto__" || e === "prototype" || e === "constructor";
}
function normalizeStringMap(e) {
	return normalizeCatalogRecords(e, (e, t) => {
		const n = normalizeOptionalString(t) ?? "";
		return e && !isBlockedObjectKey(e) && n ? n : void 0;
	}, (e) => normalizeOptionalString(e) ?? "");
}
function normalizeCatalogFields(e, t, n = {}) {
	for (const r of e) {
		const e = t(r);
		if (e !== void 0) n[r] = e;
	}
	return n;
}
function normalizeModelCatalogApi(e) {
	const t = normalizeOptionalString(e) ?? "";
	return MODEL_CATALOG_API_SET.has(t) ? t : void 0;
}
function normalizeModelCatalogContextWindows(e) {
	if (!Array.isArray(e)) return;
	const t = /* @__PURE__ */ new Set();
	const n = e.slice(0, 16).flatMap((e) => {
		if (!isRecord(e)) return [];
		const n = normalizeOptionalString(e.id) ?? "";
		const r = normalizeOptionalString(e.label) ?? "";
		const i = asPositiveInteger(e.contextWindow);
		if (!n || !r || i === void 0 || t.has(n)) return [];
		t.add(n);
		return [{
			id: n,
			label: r,
			contextWindow: i
		}];
	});
	return n.length > 0 ? n.toSorted((e, t) => e.contextWindow - t.contextWindow || e.id.localeCompare(t.id)) : void 0;
}
function normalizeModelCatalogTieredCost(e) {
	if (!Array.isArray(e)) return;
	const t = [];
	for (const n of e) {
		if (!isRecord(n) || !Array.isArray(n.range)) continue;
		const e = asNonNegativeFiniteNumber(n.input);
		const r = asNonNegativeFiniteNumber(n.output);
		const i = asNonNegativeFiniteNumber(n.cacheRead);
		const a = asNonNegativeFiniteNumber(n.cacheWrite);
		if (e === void 0 || r === void 0 || i === void 0 || a === void 0 || n.range.length < 1 || n.range.length > 2) continue;
		const o = n.range.map((e) => asNonNegativeFiniteNumber(e));
		if (o.some((e) => e === void 0)) continue;
		t.push({
			input: e,
			output: r,
			cacheRead: i,
			cacheWrite: a,
			range: o.length === 1 ? [o[0]] : [o[0], o[1]]
		});
	}
	return t.length > 0 ? t : void 0;
}
function normalizeModelCatalogCost(e) {
	if (!isRecord(e)) return;
	const t = normalizeCatalogFields([
		"input",
		"output",
		"cacheRead",
		"cacheWrite"
	], (t) => asNonNegativeFiniteNumber(e[t]));
	const n = normalizeModelCatalogTieredCost(e.tieredPricing);
	if (n) t.tieredPricing = n;
	return Object.keys(t).length > 0 ? t : void 0;
}
function normalizeOpenRouterPrice(e) {
	if (!isRecord(e)) return;
	const t = normalizeCatalogFields([
		"prompt",
		"completion",
		"image",
		"audio",
		"request"
	], (t) => {
		const n = e[t];
		return normalizeOptionalString(n) ?? asFiniteNumber(n);
	});
	return Object.keys(t).length > 0 ? t : void 0;
}
function normalizeOpenRouterMetricPreference(e) {
	const t = asFiniteNumber(e);
	if (t !== void 0) return t;
	if (!isRecord(e)) return;
	const n = normalizeCatalogFields([
		"p50",
		"p75",
		"p90",
		"p99"
	], (t) => asFiniteNumber(e[t]));
	return Object.keys(n).length > 0 ? n : void 0;
}
function normalizeOpenRouterSort(e) {
	const t = normalizeOptionalString(e);
	if (t) return t;
	if (!isRecord(e)) return;
	const n = normalizeOptionalString(e.by);
	const r = e.partition === null ? null : normalizeOptionalString(e.partition) ?? void 0;
	const i = {
		...n ? { by: n } : {},
		...r !== void 0 ? { partition: r } : {}
	};
	return Object.keys(i).length > 0 ? i : void 0;
}
function normalizeOpenRouterRouting(e) {
	if (!isRecord(e)) return;
	const t = {
		...typeof e.allow_fallbacks === "boolean" ? { allow_fallbacks: e.allow_fallbacks } : {},
		...typeof e.require_parameters === "boolean" ? { require_parameters: e.require_parameters } : {},
		...e.data_collection === "deny" || e.data_collection === "allow" ? { data_collection: e.data_collection } : {},
		...typeof e.zdr === "boolean" ? { zdr: e.zdr } : {},
		...typeof e.enforce_distillable_text === "boolean" ? { enforce_distillable_text: e.enforce_distillable_text } : {}
	};
	normalizeCatalogFields([
		"order",
		"only",
		"ignore",
		"quantizations"
	], (t) => normalizeOptionalTrimmedStringList(e[t]), t);
	const n = normalizeOpenRouterSort(e.sort);
	if (n) t.sort = n;
	const r = normalizeOpenRouterPrice(e.max_price);
	if (r) t.max_price = r;
	for (const n of ["preferred_min_throughput", "preferred_max_latency"]) {
		const r = normalizeOpenRouterMetricPreference(e[n]);
		if (r !== void 0) t[n] = r;
	}
	return Object.keys(t).length > 0 ? t : void 0;
}
function normalizeVercelGatewayRouting(e) {
	if (!isRecord(e)) return;
	const t = normalizeCatalogFields(["only", "order"], (t) => normalizeOptionalTrimmedStringList(e[t]));
	return Object.keys(t).length > 0 ? t : void 0;
}
function normalizeModelCatalogCompat(e) {
	if (!isRecord(e)) return;
	const t = {};
	for (const n of [
		"supportsStore",
		"supportsPromptCacheKey",
		"supportsDeveloperRole",
		"supportsReasoningEffort",
		"supportsTemperature",
		"supportsInstructions",
		"supportsUsageInStreaming",
		"supportsTools",
		"supportsStrictMode",
		"supportsJsonSchemaResponseFormat",
		"requiresStringContent",
		"strictMessageKeys",
		"requiresToolResultName",
		"requiresAssistantAfterToolResult",
		"requiresThinkingAsText",
		"requiresReasoningContentOnAssistantMessages",
		"zaiToolStream",
		"sendSessionAffinityHeaders",
		"sendSessionIdHeader",
		"supportsEagerToolInputStreaming",
		"supportsLongCacheRetention",
		"supportsResponsesContinuation",
		"requiresOpenAiAnthropicToolPayload"
	]) if (typeof e[n] === "boolean") t[n] = e[n];
	normalizeCatalogFields(["toolSchemaProfile", "toolCallArgumentsEncoding"], (t) => normalizeOptionalString(e[t]), t);
	for (const n of [
		"visibleReasoningDetailTypes",
		"supportedReasoningEfforts",
		"unsupportedToolSchemaKeywords"
	]) {
		const r = normalizeTrimmedStringList(e[n]);
		if (r.length > 0 || n === "supportedReasoningEfforts" && Array.isArray(e[n])) t[n] = r;
	}
	if (isRecord(e.reasoningEffortMap)) {
		const n = Object.fromEntries(Object.entries(e.reasoningEffortMap).flatMap(([e, t]) => {
			const n = e.trim();
			const r = typeof t === "string" ? t.trim() : "";
			return n && r ? [[n, r]] : [];
		}));
		if (Object.keys(n).length > 0) t.reasoningEffortMap = n;
	}
	const n = normalizeOptionalString(e.codeMode) ?? "";
	if (n === "preferred" || n === "capable") t.codeMode = n;
	const r = normalizeOptionalString(e.maxTokensField) ?? "";
	if (r === "max_completion_tokens" || r === "max_tokens") t.maxTokensField = r;
	const i = normalizeOptionalString(e.thinkingFormat) ?? "";
	if (isModelCatalogThinkingFormat(i)) t.thinkingFormat = i;
	if (e.cacheControlFormat === "anthropic") t.cacheControlFormat = "anthropic";
	const a = normalizeOpenRouterRouting(e.openRouterRouting);
	if (a) t.openRouterRouting = a;
	const o = normalizeVercelGatewayRouting(e.vercelGatewayRouting);
	if (o) t.vercelGatewayRouting = o;
	return Object.keys(t).length > 0 ? t : void 0;
}
function normalizeModelCatalogMediaInput(e) {
	if (!isRecord(e) || !isRecord(e.image)) return;
	const t = {};
	for (const n of [
		"maxBytes",
		"maxPixels",
		"maxSidePx",
		"preferredSidePx"
	]) {
		const r = asPositiveInteger(e.image[n]);
		if (r !== void 0) t[n] = r;
	}
	const n = normalizeOptionalString(e.image.tokenMode) ?? "";
	if (n === "tile" || n === "detail" || n === "provider") t.tokenMode = n;
	return Object.keys(t).length > 0 ? { image: t } : void 0;
}
function normalizeModelCatalogModel(e) {
	if (!isRecord(e)) return;
	const t = normalizeOptionalString(e.id) ?? "";
	if (!t) return;
	const n = e.inference === void 0 ? void 0 : ModelInferenceCapabilitiesSchema.safeParse(e.inference);
	if (n && !n.success) return;
	const r = normalizeOptionalString(e.name) ?? "";
	const i = normalizeModelCatalogApi(e.api);
	const a = normalizeOptionalString(e.baseUrl) ?? "";
	const o = normalizeStringMap(e.headers);
	const s = normalizeTrimmedStringList(e.input).filter((e) => MODEL_CATALOG_INPUTS.has(e));
	const c = s.length > 0 ? s : void 0;
	const l = typeof e.reasoning === "boolean" ? e.reasoning : void 0;
	const u = asPositiveFiniteNumber(e.contextWindow);
	const d = normalizeModelCatalogContextWindows(e.contextWindows);
	const f = normalizeOptionalString(e.contextWindowDefault);
	const p = f && d?.some((e) => e.id === f) ? {
		contextWindows: d,
		contextWindowDefault: f
	} : {};
	const m = asPositiveInteger(e.contextTokens);
	const h = asPositiveInteger(e.parameterCount);
	const g = normalizeModelFamily(e.family);
	const _ = asPositiveFiniteNumber(e.maxTokens);
	const v = e.thinkingLevelMap;
	const y = isRecord(v) ? normalizeCatalogFields(MODEL_CATALOG_THINKING_LEVELS, (e) => {
		const t = v[e];
		return t === null ? null : normalizeOptionalString(t);
	}) : void 0;
	const b = y && Object.keys(y).length > 0 ? y : void 0;
	const x = normalizeModelCatalogCost(e.cost);
	const S = normalizeModelCatalogCompat(e.compat);
	const C = normalizeModelCatalogMediaInput(e.mediaInput);
	const w = normalizeOptionalString(e.status) ?? "";
	const T = MODEL_CATALOG_STATUSES.has(w) ? w : void 0;
	const E = normalizeOptionalString(e.statusReason) ?? "";
	const D = normalizeTrimmedStringList(e.replaces);
	const O = normalizeOptionalString(e.replacedBy) ?? "";
	const k = normalizeTrimmedStringList(e.tags);
	return {
		id: t,
		...r ? { name: r } : {},
		...n?.success ? { inference: n.data } : {},
		...i ? { api: i } : {},
		...a ? { baseUrl: a } : {},
		...o ? { headers: o } : {},
		...c ? { input: c } : {},
		...l !== void 0 ? { reasoning: l } : {},
		...u !== void 0 ? { contextWindow: u } : {},
		...p,
		...m !== void 0 ? { contextTokens: m } : {},
		...h !== void 0 ? { parameterCount: h } : {},
		...g ? { family: g } : {},
		..._ !== void 0 ? { maxTokens: _ } : {},
		...b ? { thinkingLevelMap: b } : {},
		...x ? { cost: x } : {},
		...S ? { compat: S } : {},
		...C ? { mediaInput: C } : {},
		...T ? { status: T } : {},
		...E ? { statusReason: E } : {},
		...D.length > 0 ? { replaces: D } : {},
		...O ? { replacedBy: O } : {},
		...k.length > 0 ? { tags: k } : {}
	};
}
function normalizeModelCatalogProvider(e) {
	if (!isRecord(e)) return;
	if (e.authScope !== void 0 && e.authScope !== "agent" && e.authScope !== "plugin") throw new Error("Invalid model catalog credential ownership metadata");
	const t = e.authScope;
	const n = Array.isArray(e.models) ? e.models.map((e) => normalizeModelCatalogModel(e)).filter((e) => Boolean(e)) : [];
	if (n.length === 0 && t === void 0) return;
	const r = normalizeOptionalString(e.baseUrl) ?? "";
	const i = normalizeModelCatalogApi(e.api);
	const a = normalizeStringMap(e.headers);
	const o = normalizeOptionalString(e.defaultModel) ?? "";
	const s = normalizeOptionalString(e.defaultUtilityModel) ?? "";
	const c = normalizeCatalogRecords(e.defaultUtilityModels, (e, t) => {
		const n = normalizeOptionalString(t) ?? "";
		return e && !isBlockedObjectKey(e) && n ? n : void 0;
	}, (e) => normalizeOptionalString(e)?.toLowerCase() ?? "");
	const l = normalizeModelFamily(e.family);
	return {
		...t ? { authScope: t } : {},
		...r ? { baseUrl: r } : {},
		...i ? { api: i } : {},
		...a ? { headers: a } : {},
		...l ? { family: l } : {},
		...o ? { defaultModel: o } : {},
		...s ? { defaultUtilityModel: s } : {},
		...c ? { defaultUtilityModels: c } : {},
		models: n
	};
}
function normalizeCatalogRecords(e, t, n = normalizeProviderId) {
	if (!isRecord(e)) return;
	const r = {};
	for (const [i, a] of Object.entries(e)) {
		const e = n(i);
		const o = t(e, a);
		if (o !== void 0) r[e] = o;
	}
	return Object.keys(r).length > 0 ? r : void 0;
}
function normalizeModelCatalogSuppressions(e) {
	if (!Array.isArray(e)) return;
	const t = [];
	for (const n of e) {
		if (!isRecord(n)) continue;
		const e = normalizeProviderId(normalizeOptionalString(n.provider) ?? "");
		const r = normalizeOptionalString(n.model) ?? "";
		if (!e || !r) continue;
		const i = normalizeOptionalString(n.reason) ?? "";
		const a = isRecord(n.retirement) ? normalizeOptionalString(n.retirement.replacedBy) : void 0;
		const o = isRecord(n.retirement) && (n.retirement.replacedBy === void 0 || a) ? a ? { replacedBy: a } : {} : void 0;
		const s = isRecord(n.when) ? n.when : void 0;
		const c = normalizeTrimmedStringList(s?.baseUrlHosts).map((e) => e.toLowerCase());
		const l = normalizeTrimmedStringList(s?.providerConfigApiIn).map((e) => e.toLowerCase());
		const u = c.length > 0 || l.length > 0 ? {
			...c.length > 0 ? { baseUrlHosts: c } : {},
			...l.length > 0 ? { providerConfigApiIn: l } : {}
		} : void 0;
		if (o && n.when !== void 0 && (!s || !u || s.baseUrlHosts !== void 0 && c.length === 0 || s.providerConfigApiIn !== void 0 && l.length === 0)) continue;
		t.push({
			provider: e,
			model: r,
			...i ? { reason: i } : {},
			...o ? { retirement: o } : {},
			...u ? { when: u } : {}
		});
	}
	return t.length > 0 ? t : void 0;
}
/** Normalize a raw model catalog object for the set of providers owned by a plugin/manifest. */
function normalizeModelCatalog(e, t) {
	if (!isRecord(e)) return;
	const n = new Set([...t.ownedProviders].map(normalizeProviderId).filter(Boolean));
	const r = Object.fromEntries(Object.entries(normalizeStringMap(e.modelsDev) ?? {}).flatMap(([e, t]) => {
		const r = normalizeProviderId(e);
		return n.has(r) && !isBlockedObjectKey(r) ? [[r, t]] : [];
	}));
	const i = normalizeCatalogRecords(e.providers, (e, t) => e && n.has(e) ? normalizeModelCatalogProvider(t) : void 0);
	const a = normalizeCatalogRecords(e.aliases, (e, t) => {
		if (!e || !isRecord(t)) return;
		const r = normalizeProviderId(normalizeOptionalString(t.provider) ?? "");
		if (!r || !n.has(r)) return;
		const i = normalizeModelCatalogApi(t.api);
		const a = normalizeOptionalString(t.baseUrl) ?? "";
		return {
			provider: r,
			...i ? { api: i } : {},
			...a ? { baseUrl: a } : {}
		};
	});
	const o = normalizeModelCatalogSuppressions(e.suppressions);
	const s = normalizeCatalogRecords(e.discovery, (e, t) => {
		const r = normalizeOptionalString(t) ?? "";
		return e && n.has(e) && MODEL_CATALOG_DISCOVERY_MODES.has(r) ? r : void 0;
	});
	const c = e.runtimeAugment === true;
	const l = [...new Set(normalizeTrimmedStringList(e.configuredEndpointDiscovery).map(normalizeProviderId).filter((e) => s?.[e] === "runtime"))];
	const u = {
		...Object.keys(r).length > 0 ? { modelsDev: r } : {},
		...i ? { providers: i } : {},
		...a ? { aliases: a } : {},
		...o ? { suppressions: o } : {},
		...s ? { discovery: s } : {},
		...l.length > 0 ? { configuredEndpointDiscovery: l } : {},
		...c ? { runtimeAugment: c } : {}
	};
	return Object.keys(u).length > 0 ? u : void 0;
}
//#endregion
//#region packages/gateway-protocol/src/plugin-ui-capabilities.ts
/** Static UI contribution kinds, in canonical presentation order. */
const PLUGIN_UI_CAPABILITIES = [
	"page",
	"navigation",
	"panel",
	"action",
	"accessory",
	"widget",
	"inline",
	"replacement",
	"link-reader"
];
/** Omission is unspecified; an empty declaration explicitly advertises no UI. */
function validatePluginUiCapabilities(e) {
	if (e === void 0) return { ok: true };
	if (!Array.isArray(e)) return {
		ok: false,
		error: "must be an array"
	};
	for (const t of e) if (!PLUGIN_UI_CAPABILITIES.some((e) => e === t)) return {
		ok: false,
		error: `contains unknown UI capability ${JSON.stringify(t)}`
	};
	return {
		ok: true,
		capabilities: PLUGIN_UI_CAPABILITIES.filter((t) => e.includes(t))
	};
}
//#endregion
//#region packages/plugin-package-contract/src/categories.ts
/** Active browse taxonomy, ordered with the core configuration surfaces first. */
const PLUGIN_CATEGORY_SLUGS = [
	"channels",
	"models",
	"agent-runtimes",
	"memory",
	"context",
	"voice",
	"web",
	"computer-use",
	"media",
	"security",
	"integrations",
	"developer-tools",
	"infrastructure",
	"documents-files",
	"inbox-collaboration",
	"productivity",
	"scheduling",
	"finance-payments",
	"sales-marketing",
	"data-analytics",
	"agent-orchestration",
	"research",
	"other"
];
/** Published declarations remain readable while authors adopt the active taxonomy. */
const LEGACY_PLUGIN_CATEGORY_SLUGS = [
	"tools",
	"runtime",
	"gateway"
];
const ACCEPTED_PLUGIN_CATEGORY_SLUGS = [...PLUGIN_CATEGORY_SLUGS, ...LEGACY_PLUGIN_CATEGORY_SLUGS];
/** Validate optional ordered package-owned plugin categories. */
function validatePluginCategories(e) {
	if (e === void 0) return { ok: true };
	if (!Array.isArray(e)) return {
		ok: false,
		error: "must be an array"
	};
	if (e.length < 1 || e.length > 3) return {
		ok: false,
		error: "must contain between 1 and 3 entries"
	};
	const t = [];
	for (const n of e) {
		const e = ACCEPTED_PLUGIN_CATEGORY_SLUGS.find((e) => e === n);
		if (!e) return {
			ok: false,
			error: `contains unknown category ${JSON.stringify(n)}`
		};
		if (t.includes(e)) return {
			ok: false,
			error: "must not contain duplicates"
		};
		t.push(e);
	}
	return {
		ok: true,
		categories: t
	};
}
//#endregion
//#region src/shared/dedupe-by-key.ts
function indexFirstByKey(e, t) {
	const n = /* @__PURE__ */ new Map();
	for (const r of e) {
		const e = t(r);
		if (!n.has(e)) n.set(e, r);
	}
	return n;
}
function dedupeByKey(e, t) {
	return [...indexFirstByKey(e, t).values()];
}
//#endregion
//#region src/cli/program/command-descriptor-utils.ts
const SAFE_COMMAND_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
/** Normalize and validate a command descriptor name for safe Commander registration. */
function normalizeCommandDescriptorName(e) {
	const t = e.trim();
	return SAFE_COMMAND_NAME_PATTERN.test(t) ? t : null;
}
/** Strip unsafe terminal content from descriptor descriptions. */
function sanitizeCommandDescriptorDescription(e) {
	return sanitizeForLog(e).trim();
}
//#endregion
//#region src/plugins/manifest-contract-keys.ts
const PLUGIN_MANIFEST_CONTRACT_KEYS = [
	"codeModeExecutors",
	"agentToolResultMiddleware",
	"trustedToolPolicies",
	"externalAuthProviders",
	"decisionProviders",
	"embeddingProviders",
	"speechProviders",
	"realtimeTranscriptionProviders",
	"realtimeVoiceProviders",
	"mediaUnderstandingProviders",
	"transcriptSourceProviders",
	"documentExtractors",
	"imageGenerationProviders",
	"videoGenerationProviders",
	"musicGenerationProviders",
	"webContentExtractors",
	"webFetchProviders",
	"webSearchProviders",
	"workerProviders",
	"workerProfileSuggestions",
	"storageProviders",
	"usageProviders",
	"migrationProviders",
	"gatewayMethodDispatch",
	"commandRuntimeCapabilities",
	"sessionScheduledTurns",
	"subagentProfiles",
	"tools"
];
/** Static transcript setup metadata; runtime registration does not gate configuration. */
const TRANSCRIPT_SOURCE_LOCATOR_FIELDS = [
	"accountId",
	"guildId",
	"channelId",
	"meetingUrl"
];
//#endregion
//#region src/plugins/manifest-capability-normalizers.ts
function normalizeProviderAssistantVisibility(e) {
	return e === "visible" || e === "manual-only" || e === "detected-only" ? e : void 0;
}
function isPluginManifestOnboardingScope(e) {
	return e === "text-inference" || e === "image-generation" || e === "music-generation";
}
function normalizeDecisionCapabilities(e) {
	if (!isRecord(e) || !Array.isArray(e.questionTypes) || e.questionTypes.length === 0 || e.questionTypes.length > 3 || !e.questionTypes.every((e) => e === "boolean" || e === "choice" || e === "score")) return;
	const t = { questionTypes: [...new Set(e.questionTypes)] };
	for (const n of [
		"maxQuestions",
		"maxChoiceAlternatives",
		"maxScoreLevels",
		"maxInputTokens"
	]) {
		const r = e[n];
		if (typeof r === "number" && Number.isSafeInteger(r) && r > 0) t[n] = r;
	}
	if (e.inputTokenScope === "encoded-question" || e.inputTokenScope === "state-plus-each-criterion") t.inputTokenScope = e.inputTokenScope;
	if (typeof e.requiresBooleanCriteria === "boolean") t.requiresBooleanCriteria = e.requiresBooleanCriteria;
	if (e.confidence === "provider-specific" || e.confidence === "none") t.confidence = e.confidence;
	return t;
}
/** Normalize provider-owned model descriptors without importing provider code. */
function normalizeManifestDecisionModels(e, t) {
	const n = /* @__PURE__ */ new Set();
	return normalizeManifestObjectList(e, (e) => {
		const r = normalizeOptionalString(e.provider);
		const i = normalizeOptionalString(e.id);
		const a = normalizeOptionalString(e.name);
		if (!r || !i || !a || !t?.includes(r)) return;
		const o = `${r}/${i}`;
		if (n.has(o)) return;
		const s = normalizeDecisionCapabilities(e.capabilities);
		n.add(o);
		return {
			provider: r,
			id: i,
			name: a,
			...s ? { capabilities: s } : {}
		};
	});
}
function normalizeManifestProviderEndpoints(e) {
	return normalizeManifestObjectList(e, (e) => {
		const t = normalizeOptionalString(e.endpointClass);
		if (!t) return;
		const n = normalizeOptionalTrimmedStringList(e.hosts)?.map((e) => e.toLowerCase());
		const r = normalizeOptionalTrimmedStringList(e.hostSuffixes)?.map((e) => e.toLowerCase());
		const i = normalizeOptionalTrimmedStringList(e.baseUrls);
		if (!n && !r && !i) return;
		return omitUndefinedFields({
			endpointClass: t,
			hosts: n,
			hostSuffixes: r,
			baseUrls: i,
			googleVertexRegion: normalizeOptionalString(e.googleVertexRegion),
			googleVertexRegionHostSuffix: normalizeOptionalString(e.googleVertexRegionHostSuffix)?.toLowerCase()
		});
	});
}
/** Endpoint restrictions constrain a provider alias without changing stored credential identity. */
function normalizeManifestProviderAuthAliases(e) {
	return normalizeManifestRecord(e, (e) => {
		if (typeof e === "string") return normalizeOptionalString(e);
		if (isRecord(e)) {
			const t = normalizeOptionalString(e.provider);
			const n = normalizeTrimmedStringList(e.baseUrls);
			if (t && n.length > 0) return {
				provider: t,
				baseUrls: n
			};
		}
	});
}
function isPluginToolProfile(e) {
	return e === "minimal" || e === "coding" || e === "messaging" || e === "full";
}
function normalizeStringListRecord(e) {
	return normalizeManifestRecord(e, normalizeOptionalTrimmedStringList);
}
function normalizeManifestStringRecord(e) {
	return normalizeManifestRecord(e, normalizeOptionalString);
}
function normalizeManifestMcpServers(e) {
	return normalizeNamedMetadataRecord(e, (e) => ({ ...e }));
}
function normalizeManifestRecord(e, t) {
	if (!isRecord(e)) return;
	const n = Object.create(null);
	for (const [r, i] of Object.entries(e)) {
		const e = normalizeOptionalString(r) ?? "";
		const a = !e || isBlockedObjectKey$1(e) ? void 0 : t(i, e);
		if (a) n[e] = a;
	}
	return Object.keys(n).length > 0 ? n : void 0;
}
function normalizeNamedMetadataRecord(e, t) {
	return normalizeManifestRecord(e, (e, n) => isRecord(e) ? t(e, n) : void 0);
}
function normalizeManifestObjectList(e, t) {
	if (!Array.isArray(e)) return;
	const n = [];
	for (const r of e) {
		const e = isRecord(r) ? t(r) : void 0;
		if (e !== void 0) n.push(e);
	}
	return n.length > 0 ? n : void 0;
}
function normalizeManifestTranscriptSources(e, t = []) {
	return normalizeNamedMetadataRecord(e, (e, n) => {
		if (!t.includes(n)) return;
		const r = normalizeOptionalString(e.name);
		const i = e.autoStart;
		const a = isRecord(i) && Object.entries(i).every(([e, t]) => TRANSCRIPT_SOURCE_LOCATOR_FIELDS.some((t) => t === e) && (t === "optional" || t === "required")) ? Object.fromEntries(Object.entries(i)) : void 0;
		return r || a ? {
			...r ? { name: r } : {},
			...a ? { autoStart: a } : {}
		} : void 0;
	});
}
function isMediaUnderstandingCapability(e) {
	return e === "image" || e === "audio" || e === "video";
}
function normalizeMediaUnderstandingRecord(e, t) {
	if (!isRecord(e)) return;
	const n = {};
	for (const [r, i] of Object.entries(e)) {
		if (!isMediaUnderstandingCapability(r)) continue;
		const e = t(i);
		if (e !== void 0) n[r] = e;
	}
	return Object.keys(n).length > 0 ? n : void 0;
}
function normalizeMediaUnderstandingCapabilities(e) {
	const t = normalizeTrimmedStringList(e).filter(isMediaUnderstandingCapability);
	return t.length > 0 ? t : void 0;
}
function normalizeMediaUnderstandingNativeDocumentInputs(e) {
	const t = normalizeTrimmedStringList(e).filter((e) => e === "pdf");
	return t.length > 0 ? t : void 0;
}
function normalizeMediaUnderstandingDocumentModels(e) {
	if (!isRecord(e)) return;
	const t = e.pdf;
	if (!isRecord(t)) return;
	const n = optionalManifestFields({
		textExtraction: normalizeOptionalString(t.textExtraction),
		image: t.image === false ? false : normalizeOptionalString(t.image)
	});
	return n ? { pdf: n } : void 0;
}
function normalizeMediaUnderstandingProviderMetadata(e) {
	return normalizeNamedMetadataRecord(e, (e) => optionalManifestFields({
		capabilities: normalizeMediaUnderstandingCapabilities(e.capabilities),
		defaultModels: normalizeMediaUnderstandingRecord(e.defaultModels, normalizeOptionalString),
		autoPriority: normalizeMediaUnderstandingRecord(e.autoPriority, (e) => typeof e === "number" && Number.isFinite(e) ? e : void 0),
		nativeDocumentInputs: normalizeMediaUnderstandingNativeDocumentInputs(e.nativeDocumentInputs),
		documentModels: normalizeMediaUnderstandingDocumentModels(e.documentModels)
	}));
}
function normalizeProviderBaseUrlGuard(e) {
	if (!isRecord(e)) return;
	const t = normalizeOptionalString(e.provider);
	const n = normalizeTrimmedStringList(e.allowedBaseUrls);
	if (!t || n.length === 0) return;
	const r = normalizeOptionalString(e.defaultBaseUrl);
	return {
		provider: t,
		...r ? { defaultBaseUrl: r } : {},
		allowedBaseUrls: n
	};
}
function normalizeCapabilityProviderModeConfigSignal(e) {
	if (!isRecord(e)) return;
	return optionalManifestFields({
		path: normalizeOptionalString(e.path),
		default: normalizeOptionalString(e.default),
		allowed: normalizeOptionalTrimmedStringList(e.allowed),
		disallowed: normalizeOptionalTrimmedStringList(e.disallowed)
	});
}
function normalizeCapabilityProviderMetadataEntry(e) {
	return optionalManifestFields({
		aliases: normalizeOptionalTrimmedStringList(e.aliases),
		authProviders: normalizeOptionalTrimmedStringList(e.authProviders),
		authSignals: normalizeManifestObjectList(e.authSignals, (e) => {
			const t = normalizeOptionalString(e.provider);
			if (!t) return;
			return omitUndefinedFields({
				provider: t,
				providerBaseUrl: normalizeProviderBaseUrlGuard(e.providerBaseUrl)
			});
		}),
		configSignals: normalizeManifestObjectList(e.configSignals, (e) => {
			const t = normalizeOptionalString(e.rootPath);
			if (!t) return;
			const n = normalizeOptionalTrimmedStringList(e.required);
			const r = normalizeOptionalTrimmedStringList(e.requiredAny);
			const i = normalizeCapabilityProviderModeConfigSignal(e.mode);
			return n || r || i ? omitUndefinedFields({
				rootPath: t,
				overlayPath: normalizeOptionalString(e.overlayPath),
				overlayMapPath: normalizeOptionalString(e.overlayMapPath),
				required: n,
				requiredAny: r,
				mode: i
			}) : void 0;
		}),
		referenceAudioInputs: e.referenceAudioInputs === true ? true : void 0
	});
}
function normalizeCapabilityProviderMetadata(e) {
	return normalizeNamedMetadataRecord(e, normalizeCapabilityProviderMetadataEntry);
}
function normalizePluginToolMetadata(e) {
	return normalizeNamedMetadataRecord(e, (e) => {
		const t = normalizeCapabilityProviderMetadataEntry(e);
		const n = normalizeTrimmedStringList(e.profiles).filter(isPluginToolProfile);
		const r = {
			...t,
			...e.optional === true ? { optional: true } : {},
			...n.length > 0 ? { profiles: n } : {},
			...e.replaySafe === true ? { replaySafe: true } : {},
			...e.sideEffecting === true ? { sideEffecting: true } : {}
		};
		return Object.keys(r).length > 0 ? r : void 0;
	});
}
function normalizeManifestCatalog(e) {
	if (!isRecord(e)) return;
	return optionalManifestFields({
		featured: typeof e.featured === "boolean" ? e.featured : void 0,
		order: typeof e.order === "number" && Number.isFinite(e.order) ? e.order : void 0
	});
}
function normalizeManifestContracts(e) {
	if (!isRecord(e)) return;
	const t = {};
	for (const n of PLUGIN_MANIFEST_CONTRACT_KEYS) {
		const r = normalizeTrimmedStringList(e[n]);
		if (r.length > 0) t[n] = r;
	}
	return Object.keys(t).length > 0 ? t : void 0;
}
function isManifestConfigLiteral(e) {
	return e === null || typeof e === "string" || typeof e === "number" || typeof e === "boolean";
}
function normalizeManifestConfigContracts(e) {
	if (!isRecord(e)) return;
	const t = normalizeTrimmedStringList(e.compatibilityMigrationPaths);
	const n = normalizeTrimmedStringList(e.compatibilityRuntimePaths);
	const r = isRecord(e.secretInputs) ? e.secretInputs : void 0;
	const i = normalizeManifestObjectList(e.dangerousFlags, (e) => {
		const t = normalizeOptionalString(e.path) ?? "";
		return t && isManifestConfigLiteral(e.equals) ? {
			path: t,
			equals: e.equals
		} : void 0;
	});
	const a = r ? normalizeManifestObjectList(r.paths, (e) => {
		const t = normalizeOptionalString(e.path) ?? "";
		if (!t) return;
		const n = e.expected === "string" ? e.expected : void 0;
		const r = e.ownerKind === "capability" || e.ownerKind === "route" ? e.ownerKind : void 0;
		return {
			path: t,
			...n ? { expected: n } : {},
			...r ? { ownerKind: r } : {}
		};
	}) : void 0;
	const o = a ? {
		...typeof r?.bundledDefaultEnabled === "boolean" ? { bundledDefaultEnabled: r.bundledDefaultEnabled } : {},
		paths: a
	} : void 0;
	const s = {
		...t.length > 0 ? { compatibilityMigrationPaths: t } : {},
		...n.length > 0 ? { compatibilityRuntimePaths: n } : {},
		...i ? { dangerousFlags: i } : {},
		...o ? { secretInputs: o } : {}
	};
	return Object.keys(s).length > 0 ? s : void 0;
}
/** Only fresh field projections belong here; never mutate the authored manifest. */
function optionalManifestFields(e) {
	omitUndefinedFields(e);
	return Object.keys(e).length > 0 ? e : void 0;
}
//#endregion
//#region src/plugins/manifest-platforms.ts
const MANIFEST_PLATFORMS = /* @__PURE__ */ new Set([
	"aix",
	"android",
	"darwin",
	"freebsd",
	"haiku",
	"linux",
	"openbsd",
	"sunos",
	"win32",
	"cygwin",
	"netbsd"
]);
function normalizeManifestPlatforms(e) {
	return normalizeTrimmedStringList(e).filter((e) => MANIFEST_PLATFORMS.has(e));
}
//#endregion
//#region src/plugins/setup-presentation-url.ts
function normalizeSetupPresentationHttpsUrl(e) {
	const t = normalizeOptionalString(e);
	const n = t ? URL.parse(t) : null;
	if (!n) return;
	const r = n.toString();
	return n.protocol === "https:" && n.hostname && !n.username && !n.password && r.length <= 2048 ? r : void 0;
}
//#endregion
//#region src/plugins/manifest-setup-normalizers.ts
function normalizeManifestActivation(e) {
	if (!isRecord(e)) return;
	const t = {};
	if (typeof e.onStartup === "boolean") t.onStartup = e.onStartup;
	for (const n of [
		"onProviders",
		"onAgentHarnesses",
		"onCommands",
		"onChannels",
		"onRoutes",
		"onConfigPaths"
	]) {
		const r = normalizeTrimmedStringList(e[n]);
		if (r.length > 0) t[n] = r;
	}
	const n = normalizeTrimmedStringList(e.onCapabilities).filter((e) => e === "provider" || e === "channel" || e === "tool" || e === "hook");
	if (n.length > 0) t.onCapabilities = n;
	return Object.keys(t).length > 0 ? t : void 0;
}
function normalizeChannelAccountKeyPolicies(e, t) {
	if (!isRecord(e)) return;
	const n = Object.create(null);
	for (const r of t) {
		if (isBlockedObjectKey$1(r) || !Object.hasOwn(e, r)) continue;
		const t = e[r];
		const i = isRecord(t) ? normalizeOptionalString(t.canonicalAliasesRequireOwnField) : void 0;
		if (i && !isBlockedObjectKey$1(i)) n[r] = { canonicalAliasesRequireOwnField: i };
	}
	return Object.keys(n).length ? n : void 0;
}
function normalizeManifestCliCommands(e) {
	if (!Array.isArray(e)) return;
	const t = /* @__PURE__ */ new Set();
	return normalizeManifestObjectList(e, (e) => {
		if (typeof e.name !== "string" || typeof e.description !== "string") return;
		const n = normalizeCommandDescriptorName(e.name);
		const r = sanitizeCommandDescriptorDescription(e.description);
		if (!n || !r || typeof e.hasSubcommands !== "boolean" || t.has(n)) return;
		t.add(n);
		return {
			name: n,
			description: r,
			hasSubcommands: e.hasSubcommands
		};
	}) ?? [];
}
function normalizeManifestSetup(e) {
	if (!isRecord(e)) return;
	const t = isRecord(e.nativeSessionCatalog) ? omitUndefinedFields({
		label: normalizeOptionalString(e.nativeSessionCatalog.label) ?? "",
		legacyDefaultEnabled: e.nativeSessionCatalog.legacyDefaultEnabled === true ? true : void 0,
		nodeCommands: normalizeOptionalTrimmedStringList(e.nativeSessionCatalog.nodeCommands),
		description: normalizeOptionalString(e.nativeSessionCatalog.description)
	}) : void 0;
	return optionalManifestFields({
		providers: normalizeManifestObjectList(e.providers, (e) => {
			const t = normalizeOptionalString(e.id) ?? "";
			if (!t) return;
			return omitUndefinedFields({
				id: t,
				authMethods: normalizeOptionalTrimmedStringList(e.authMethods),
				envVars: normalizeOptionalTrimmedStringList(e.envVars),
				authEvidence: normalizeManifestObjectList(e.authEvidence, (e) => {
					if (e.type !== "local-file-with-env") return;
					const t = normalizeOptionalString(e.credentialMarker);
					if (!t) return;
					const n = normalizeOptionalString(e.fileEnvVar);
					const r = normalizeOptionalTrimmedStringList(e.fallbackPaths);
					if (!n && !r) return;
					return omitUndefinedFields({
						type: "local-file-with-env",
						fileEnvVar: n,
						fallbackPaths: r,
						requiresAnyEnv: normalizeOptionalTrimmedStringList(e.requiresAnyEnv),
						requiresAllEnv: normalizeOptionalTrimmedStringList(e.requiresAllEnv),
						credentialMarker: t,
						source: normalizeOptionalString(e.source)
					});
				})
			});
		}),
		cliBackends: normalizeOptionalTrimmedStringList(e.cliBackends),
		configMigrations: normalizeOptionalTrimmedStringList(e.configMigrations),
		nativeSessionCatalog: t?.label ? t : void 0,
		requiresRuntime: typeof e.requiresRuntime === "boolean" ? e.requiresRuntime : void 0
	});
}
function normalizeManifestQaRunners(e) {
	return normalizeManifestObjectList(e, (e) => {
		const t = normalizeOptionalString(e.commandName) ?? "";
		if (!t) return;
		return omitUndefinedFields({
			commandName: t,
			description: normalizeOptionalString(e.description)
		});
	});
}
function normalizeDashboardCapabilityBase(e, t, n) {
	if (!isRecord(e)) return `${t}[${n}] must be an object`;
	const r = normalizeOptionalString(e.id);
	const i = normalizeOptionalString(e.method);
	const a = normalizeOptionalString(e.description);
	if (!r || !/^[a-z0-9][a-z0-9._-]*$/u.test(r)) return `${t}[${n}].id must be a lowercase capability id`;
	if (!i) return `${t}[${n}].method must be a non-empty string`;
	if (!a) return `${t}[${n}].description must be a non-empty string`;
	return {
		id: r,
		method: i,
		description: a
	};
}
function normalizeManifestDashboard(e) {
	if (e === void 0) return { ok: true };
	if (!isRecord(e)) return {
		ok: false,
		error: "dashboard must be an object"
	};
	const t = [];
	for (const n of ["dataBindings", "actionVerbs"]) {
		const r = e[n];
		if (r !== void 0 && !Array.isArray(r)) return {
			ok: false,
			error: `dashboard.${n} must be an array`
		};
		t.push({
			field: n,
			entries: r ?? []
		});
	}
	const n = {};
	for (const e of t) {
		const { field: t } = e;
		const r = [];
		for (const [n, i] of e.entries.entries()) {
			const e = normalizeDashboardCapabilityBase(i, `dashboard.${t}`, n);
			if (typeof e === "string") return {
				ok: false,
				error: e
			};
			const a = t === "actionVerbs" && isRecord(i) ? i.paramShape : void 0;
			if (a !== void 0 && !isRecord(a)) return {
				ok: false,
				error: `dashboard.actionVerbs[${n}].paramShape must be a JSON Schema object`
			};
			r.push({
				...e,
				...a ? { paramShape: a } : {}
			});
		}
		if (r.length > 0) n[t] = r;
	}
	return Object.keys(n).length > 0 ? {
		ok: true,
		dashboard: n
	} : { ok: true };
}
function normalizeProviderChannelLogin(e) {
	if (!isRecord(e) || Object.keys(e).some((e) => e !== "aliases")) return;
	if (e.aliases !== void 0 && (!Array.isArray(e.aliases) || e.aliases.some((e) => typeof e !== "string" || !e.trim()))) return;
	const t = normalizeUniqueTrimmedStringList(e.aliases);
	return t.length > 0 ? { aliases: t } : {};
}
function normalizeProviderAuthChoices(e) {
	return normalizeManifestObjectList(e, (e) => {
		const t = normalizeOptionalString(e.provider) ?? "";
		const n = normalizeOptionalString(e.method) ?? "";
		const r = normalizeOptionalString(e.choiceId) ?? "";
		if (!t || !n || !r) return;
		const i = normalizeTrimmedStringList(e.onboardingScopes).filter(isPluginManifestOnboardingScope);
		return omitUndefinedFields({
			provider: t,
			method: n,
			choiceId: r,
			modelTarget: e.modelTarget === "utility" ? "utility" : void 0,
			platforms: e.platforms !== void 0 ? normalizeManifestPlatforms(e.platforms) : void 0,
			choiceLabel: normalizeOptionalString(e.choiceLabel),
			choiceHint: normalizeOptionalString(e.choiceHint),
			icon: normalizeSetupPresentationHttpsUrl(e.icon),
			website: normalizeSetupPresentationHttpsUrl(e.website),
			docsUrl: normalizeSetupPresentationHttpsUrl(e.docsUrl),
			assistantPriority: typeof e.assistantPriority === "number" && Number.isFinite(e.assistantPriority) ? e.assistantPriority : void 0,
			assistantVisibility: normalizeProviderAssistantVisibility(e.assistantVisibility),
			deprecatedChoiceIds: normalizeOptionalTrimmedStringList(e.deprecatedChoiceIds),
			groupId: normalizeOptionalString(e.groupId),
			groupLabel: normalizeOptionalString(e.groupLabel),
			groupHint: normalizeOptionalString(e.groupHint),
			onboardingFeatured: e.onboardingFeatured === true ? true : void 0,
			appGuidedDiscovery: e.appGuidedDiscovery === true ? true : void 0,
			optionKey: normalizeOptionalString(e.optionKey),
			cliFlag: normalizeOptionalString(e.cliFlag),
			cliOption: normalizeOptionalString(e.cliOption),
			cliDescription: normalizeOptionalString(e.cliDescription),
			appGuidedSecret: e.appGuidedSecret === true ? true : void 0,
			personalAccount: e.personalAccount === true ? true : void 0,
			appGuidedActionLabel: normalizeOptionalString(e.appGuidedActionLabel),
			appGuidedAuth: e.appGuidedAuth === "oauth" || e.appGuidedAuth === "device-code" ? e.appGuidedAuth : void 0,
			credentialOnly: e.credentialOnly === true ? true : void 0,
			channelLogin: normalizeProviderChannelLogin(e.channelLogin),
			onboardingScopes: i.length > 0 ? i : void 0
		});
	});
}
function normalizeConfigUiHints(e) {
	if (!isRecord(e)) return;
	const t = Object.create(null);
	for (const [n, r] of Object.entries(e)) {
		if (!isRecord(r)) continue;
		const e = { ...r };
		if ("presentation" in e && e.presentation !== "phone-number") delete e.presentation;
		if ("multiline" in e && typeof e.multiline !== "boolean") delete e.multiline;
		t[n] = e;
	}
	return Object.keys(t).length > 0 ? t : void 0;
}
function normalizeChannelConfigs(e) {
	return normalizeNamedMetadataRecord(e, (e) => {
		const t = isRecord(e.schema) ? e.schema : null;
		if (!t) return;
		return omitUndefinedFields({
			schema: t,
			uiHints: normalizeConfigUiHints(e.uiHints),
			runtime: isRecord(e.runtime) && typeof e.runtime.safeParse === "function" ? e.runtime : void 0,
			label: normalizeOptionalString(e.label),
			description: normalizeOptionalString(e.description),
			preferOver: normalizeOptionalTrimmedStringList(e.preferOver),
			commands: normalizeManifestChannelCommandDefaults(e.commands)
		});
	});
}
function normalizeManifestChannelCommandDefaults(e) {
	if (!isRecord(e)) return;
	const t = {};
	for (const n of ["nativeCommandsAutoEnabled", "nativeSkillsAutoEnabled"]) if (typeof e[n] === "boolean") t[n] = e[n];
	return Object.keys(t).length > 0 ? t : void 0;
}
//#endregion
//#region src/plugins/control-ui-build-manifest.ts
/** Browser builds replace only their declaration; authored capabilities remain authoritative. */
function loadPluginControlUiDeclaration(e) {
	const t = "dist/openclaw.plugin.json";
	if (!pluginCacheLstatSync(path.join(e.rootDir, t)) || !pluginCacheLstatSync(path.join(e.rootDir, "package.json"))) return normalizeManifestControlUi(e.controlUi, e.channels);
	const n = readPluginCacheFile({
		...e,
		relativePath: "package.json"
	});
	if (!n.ok) return err("generated Control UI package metadata could not be safely read");
	const r = parsePluginCacheJson(n);
	if (!r.ok || !isRecord(r.value)) return err("generated Control UI package metadata must be an object");
	try {
		if (!controlUiSource(r.value)) return normalizeManifestControlUi(e.controlUi, e.channels);
	} catch (e) {
		return err(String(e));
	}
	const i = readPluginCacheFile({
		rootDir: e.rootDir,
		relativePath: t,
		rejectHardlinks: e.rejectHardlinks,
		rootRealPath: e.rootRealPath,
		maxBytes: 262144
	});
	if (!i.ok) return err("generated Control UI manifest could not be safely read");
	const a = parsePluginCacheJson(i);
	if (!a.ok || !isRecord(a.value) || a.value.controlUi === void 0) return err("generated Control UI manifest must contain controlUi");
	return normalizeManifestControlUi(a.value.controlUi, e.channels);
}
//#endregion
//#region src/plugins/doctor-session-route-state-owner-types.ts
function coerceDoctorSessionRouteStateOwners(e) {
	if (!Array.isArray(e)) return [];
	return e.flatMap((e) => {
		const t = asOptionalObjectRecord(e);
		if (typeof t?.id !== "string" || typeof t.label !== "string") return [];
		const n = t.id.trim();
		const r = t.label.trim();
		if (!n || !r) return [];
		const i = {
			id: n,
			label: r,
			providerIds: normalizeTrimmedStringList(t.providerIds),
			runtimeIds: normalizeTrimmedStringList(t.runtimeIds),
			cliSessionKeys: normalizeTrimmedStringList(t.cliSessionKeys),
			authProfilePrefixes: normalizeTrimmedStringList(t.authProfilePrefixes)
		};
		return [
			"providerIds",
			"runtimeIds",
			"cliSessionKeys",
			"authProfilePrefixes"
		].every((e) => t[e] === void 0 || i[e].length > 0) ? [i] : [];
	});
}
//#endregion
//#region src/plugins/manifest-command-aliases.ts
/** Normalizes manifest-declared CLI command aliases. */
/** Normalizes manifest command alias records, omitting invalid entries. */
function normalizeManifestCommandAliases(e) {
	if (!Array.isArray(e)) return;
	const t = [];
	for (const n of e) {
		const e = typeof n === "string" ? { name: n } : n;
		if (!isRecord(e)) continue;
		const r = normalizeOptionalString(e.name) ?? "";
		if (!r) continue;
		const i = e.kind === "runtime-slash" ? e.kind : void 0;
		const a = normalizeOptionalString(e.cliCommand) ?? "";
		t.push({
			name: r,
			...i ? { kind: i } : {},
			...a ? { cliCommand: a } : {}
		});
	}
	return t.length > 0 ? t : void 0;
}
//#endregion
//#region src/plugins/manifest-config-groups.ts
/** Invalid presentation metadata leaves the plugin's complete flat settings form available. */
function normalizeConfigGroups(e, t) {
	if (!Array.isArray(e) || e.length === 0 || !isRecord(t.properties)) return;
	const n = /* @__PURE__ */ new Set();
	const r = /* @__PURE__ */ new Set();
	const i = [];
	for (const a of e) {
		if (!isRecord(a)) return;
		const e = typeof a.id === "string" ? a.id.trim() : "";
		const o = typeof a.title === "string" ? a.title.trim() : "";
		if (!e || !o || n.has(e) || a.order !== void 0 && !Number.isInteger(a.order) || !Array.isArray(a.properties) || a.properties.length === 0) return;
		const s = [];
		for (const e of a.properties) {
			if (typeof e !== "string" || !e || !Object.hasOwn(t.properties, e) || r.has(e)) return;
			r.add(e);
			s.push(e);
		}
		n.add(e);
		i.push({
			id: e,
			title: o,
			...typeof a.order === "number" ? { order: a.order } : {},
			properties: s
		});
	}
	return i;
}
//#endregion
//#region packages/model-catalog-core/src/model-catalog-pricing.ts
const OPENROUTER_MODELS_URL = "https://openrouter.ai/api/v1/models";
const MODELS_DEV_CATALOG_URL = "https://models.opencode.ai/api.json";
const LITELLM_PRICING_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
const MODEL_PRICING_SOURCES = [
	{
		id: "openCode",
		label: "OpenCode",
		url: MODELS_DEV_CATALOG_URL,
		authoritative: true
	},
	{
		id: "venice",
		label: "Venice",
		url: "https://api.venice.ai/api/v1/models",
		authoritative: true
	},
	{
		id: "chutes",
		label: "Chutes",
		url: "https://llm.chutes.ai/v1/models",
		authoritative: true
	},
	{
		id: "cerebras",
		label: "Cerebras",
		url: "https://api.cerebras.ai/public/v1/models",
		authoritative: true
	},
	{
		id: "deepinfra",
		label: "DeepInfra",
		url: "https://api.deepinfra.com/models/list",
		authoritative: true
	},
	{
		id: "modelsDev",
		label: "models.dev",
		url: MODELS_DEV_CATALOG_URL,
		authoritative: false
	},
	{
		id: "openRouter",
		label: "OpenRouter",
		url: OPENROUTER_MODELS_URL,
		authoritative: false
	},
	{
		id: "liteLLM",
		label: "LiteLLM",
		url: LITELLM_PRICING_URL,
		authoritative: false
	}
];
/** Normalize source policy without deciding which plugin owns the provider. */
function normalizeModelPricingProvider(e) {
	const t = asOptionalRecord(e);
	if (!t) return;
	const n = normalizeProviderId(normalizeOptionalString(t.priceAs) ?? "");
	const r = {
		...typeof t.external === "boolean" ? { external: t.external } : {},
		...n ? { priceAs: n } : {}
	};
	for (const { id: e } of MODEL_PRICING_SOURCES) {
		const n = t[e];
		if (n === false) {
			r[e] = false;
			continue;
		}
		const i = asOptionalRecord(n);
		const a = normalizeProviderId(normalizeOptionalString(i?.provider) ?? "");
		const o = normalizeTrimmedStringList(i?.modelIdTransforms).filter((e) => e === "version-dots");
		const s = {
			...a ? { provider: a } : {},
			...i?.passthroughProviderModel === true ? { passthroughProviderModel: true } : {},
			...o.length > 0 ? { modelIdTransforms: o } : {}
		};
		if (Object.keys(s).length > 0) r[e] = s;
	}
	return Object.keys(r).length > 0 ? r : void 0;
}
//#endregion
//#region src/plugins/plugin-provider-request-policy.ts
/** Manifest parsing and prepared metadata use the same provider request policy. */
function normalizeManifestProviderRequestProvider(e) {
	if (!isRecord(e)) return;
	const t = normalizeOptionalString(e.family);
	const n = normalizeOptionalString(e.compatibilityFamily) === "moonshot" ? "moonshot" : void 0;
	const r = isRecord(e.openAICompletions) ? e.openAICompletions.supportsStreamingUsage : void 0;
	const i = typeof r === "boolean" ? { supportsStreamingUsage: r } : void 0;
	const a = {
		...t ? { family: t } : {},
		...n ? { compatibilityFamily: n } : {},
		...isRecord(e.modelParamsSchema) ? { modelParamsSchema: e.modelParamsSchema } : {},
		...i ? { openAICompletions: i } : {}
	};
	return Object.keys(a).length > 0 ? a : void 0;
}
//#endregion
//#region src/plugins/manifest-model-provider-normalizers.ts
const MAX_SECRET_PROVIDER_EXEC_ARGS = 128;
const MAX_SECRET_PROVIDER_EXEC_ARG_BYTES = 1024;
const MAX_SECRET_PROVIDER_EXEC_TIMEOUT_MS = 12e4;
const MAX_SECRET_PROVIDER_EXEC_OUTPUT_BYTES = 20971520;
const MAX_SECRET_PROVIDER_EXEC_PASS_ENV = 128;
const SECRET_PROVIDER_NODE_COMMAND_PLACEHOLDER = "${node}";
function normalizeManifestModelSupport(e) {
	if (!isRecord(e)) return;
	return optionalManifestFields({
		modelPrefixes: normalizeOptionalTrimmedStringList(e.modelPrefixes),
		modelPatterns: normalizeOptionalTrimmedStringList(e.modelPatterns)
	});
}
function normalizeOwnedProviderMap(e, t, n) {
	if (!isRecord(e) || !isRecord(e.providers)) return;
	const r = new Set([...t].map((e) => normalizeProviderId(e)).filter(Boolean));
	const i = {};
	for (const [t, a] of Object.entries(e.providers)) {
		const e = normalizeProviderId(t);
		const o = e && r.has(e) ? n(a) : null;
		if (e && o) i[e] = o;
	}
	return Object.keys(i).length > 0 ? i : void 0;
}
function normalizeManifestModelPricing(e, t) {
	const n = normalizeOwnedProviderMap(e, t.ownedProviders, normalizeModelPricingProvider);
	return n ? { providers: n } : void 0;
}
function normalizeManifestModelIdPrefixRules(e) {
	return normalizeManifestObjectList(e, (e) => {
		const t = normalizeOptionalString(e.modelPrefix);
		const n = normalizeOptionalString(e.prefix);
		return t && n ? {
			modelPrefix: t,
			prefix: n
		} : void 0;
	});
}
function normalizeManifestModelIdNormalizationProvider(e) {
	if (!isRecord(e)) return;
	const t = {};
	if (isRecord(e.aliases)) for (const [n, r] of Object.entries(e.aliases)) {
		const e = normalizeProviderId(n);
		const i = normalizeOptionalString(r);
		if (e && i) t[e] = i;
	}
	return optionalManifestFields({
		aliases: Object.keys(t).length > 0 ? t : void 0,
		stripPrefixes: normalizeOptionalTrimmedStringList(e.stripPrefixes),
		prefixWhenBare: normalizeOptionalString(e.prefixWhenBare),
		prefixWhenBareAfterAliasStartsWith: normalizeManifestModelIdPrefixRules(e.prefixWhenBareAfterAliasStartsWith)
	});
}
function normalizeManifestModelIdNormalization(e, t) {
	const n = normalizeOwnedProviderMap(e, t.ownedProviders, normalizeManifestModelIdNormalizationProvider);
	return n ? { providers: n } : void 0;
}
function normalizeManifestProviderRequest(e, t) {
	const n = normalizeOwnedProviderMap(e, t.ownedProviders, normalizeManifestProviderRequestProvider);
	return n ? { providers: n } : void 0;
}
function normalizeManifestPositiveInteger(e, t) {
	return asSafeIntegerInRange(e, {
		min: 1,
		max: t
	});
}
function normalizeManifestSecretProviderIntegrations(e) {
	return normalizeNamedMetadataRecord(e, (e) => {
		const t = normalizeOptionalString(e.command);
		if (e.source !== "exec" || t !== SECRET_PROVIDER_NODE_COMMAND_PLACEHOLDER) return;
		const n = [];
		if (Array.isArray(e.args)) for (const t of e.args) {
			if (typeof t !== "string" || t.length > MAX_SECRET_PROVIDER_EXEC_ARG_BYTES) continue;
			n.push(t);
			if (n.length >= MAX_SECRET_PROVIDER_EXEC_ARGS) break;
		}
		const r = normalizeTrimmedStringList(e.passEnv).filter((e) => ENV_SECRET_REF_ID_RE.test(e)).slice(0, MAX_SECRET_PROVIDER_EXEC_PASS_ENV);
		return omitUndefinedFields({
			providerAlias: normalizeOptionalString(e.providerAlias),
			displayName: normalizeOptionalString(e.displayName),
			description: normalizeOptionalString(e.description),
			source: "exec",
			command: t,
			args: n.length > 0 ? n : void 0,
			timeoutMs: normalizeManifestPositiveInteger(e.timeoutMs, MAX_SECRET_PROVIDER_EXEC_TIMEOUT_MS),
			noOutputTimeoutMs: normalizeManifestPositiveInteger(e.noOutputTimeoutMs, MAX_SECRET_PROVIDER_EXEC_TIMEOUT_MS),
			maxOutputBytes: normalizeManifestPositiveInteger(e.maxOutputBytes, MAX_SECRET_PROVIDER_EXEC_OUTPUT_BYTES),
			jsonOnly: typeof e.jsonOnly === "boolean" ? e.jsonOnly : void 0,
			env: normalizeManifestStringRecord(e.env),
			passEnv: r.length > 0 ? r : void 0
		});
	});
}
//#endregion
//#region packages/gateway-protocol/src/theme-ids.ts
/** Lightweight theme identifiers used while browser preferences boot. */
const BUILTIN_THEME_IDS = [
	"claw",
	"knot",
	"dash",
	"absolutely",
	"tide",
	"beacon",
	"phosphor",
	"crt",
	"manuscript",
	"rose",
	"miami"
];
const THEME_LOCAL_ID_PATTERN = new RegExp(`^[a-z0-9][a-z0-9_-]{0,63}$`);
function isBuiltinThemeId(e) {
	return BUILTIN_THEME_IDS.some((t) => t === e);
}
function isThemeId(e) {
	if (isBuiltinThemeId(e)) return true;
	if (typeof e !== "string" || e.length > 256) return false;
	const t = e.lastIndexOf("/");
	const n = e.slice(0, t);
	return t > 0 && !n.startsWith("user/") && /^@?[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)*$/i.test(n) && THEME_LOCAL_ID_PATTERN.test(e.slice(t + 1));
}
//#endregion
//#region packages/gateway-protocol/src/theme.ts
const THEME_COLOR_KEYS = [
	"background",
	"foreground",
	"card",
	"card-foreground",
	"popover",
	"popover-foreground",
	"primary",
	"primary-foreground",
	"secondary",
	"secondary-foreground",
	"muted",
	"muted-foreground",
	"accent",
	"accent-foreground",
	"destructive",
	"destructive-foreground",
	"border",
	"input",
	"ring"
];
const THEME_FONT_KEYS = ["font-sans", "font-mono"];
const THEME_MASCOT_VALUES = ["claw", "none"];
const THEME_BRAND_ICON_IDS = ["claw", "mark"];
const THEME_WORKING_INDICATOR_VALUES = [
	"claw",
	"dots",
	"brand",
	"none"
];
const THEME_BRAND_NAME_MAX_LENGTH = 80;
const THEME_CRITTER_IDS = ["penguin", "fedora"];
const THEME_AVATAR_HAT_IDS = [
	"fedora",
	"crown",
	"santa",
	"party",
	"pumpkin"
];
const THEME_ARTWORK_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,31}$/;
const THEME_WORKING_PHRASES_MAX = 24;
const THEME_WORKING_PHRASE_MAX_LENGTH = 24;
const MAX_THEME_DEFINITION_BYTES = 4096;
const THEME_NAME_MAX_LENGTH = 80;
const THEME_DESCRIPTION_MAX_LENGTH = 320;
const THEME_TOKEN_MAX_LENGTH = 120;
const BUILTIN_THEMES = [
	{
		id: "claw",
		name: "Claw",
		description: "Signature coral red and teal on charcoal or pale surfaces, with Instrument Sans throughout. A balanced everyday workspace."
	},
	{
		id: "knot",
		name: "Knot",
		description: "Crimson accents on true black or clean white, with Geist typography. Sharp, minimal, and high contrast."
	},
	{
		id: "dash",
		name: "Dash",
		description: "Toasted caramel on deep cocoa or warm cream, with DM Sans controls and Fraunces serif chat. Warm and bookish."
	},
	{
		id: "absolutely",
		name: "Absolutely",
		description: "Terracotta clay on warm graphite or soft cream, with Space Grotesk controls and Lora serif chat. Quiet editorial character."
	},
	{
		id: "tide",
		name: "Tide",
		description: "Steel cyan on cool slate or pale blue-gray, with IBM Plex Sans throughout. Calm, technical, and understated."
	},
	{
		id: "beacon",
		name: "Beacon",
		description: "High-visibility amber on black or white, bold focus rings, and Atkinson Hyperlegible typography. Designed for maximum readability."
	},
	{
		id: "phosphor",
		name: "Phosphor",
		mascot: "none",
		brandIcon: "mark",
		workingIndicator: "dots",
		lobsterdex: false,
		description: "Luminous green on green-tinted black or pale green, with JetBrains Mono throughout. A classic green terminal atmosphere."
	},
	{
		id: "crt",
		name: "CRT",
		mascot: "none",
		brandIcon: "mark",
		workingIndicator: "dots",
		lobsterdex: false,
		description: "White phosphor and amber on tube black, with a light counterpart, JetBrains Mono, and nearly square corners. A retro computer console."
	},
	{
		id: "manuscript",
		name: "Manuscript",
		description: "Lapis blue and gold on aged paper, with a dark reading-room variant and Lora serif throughout. A quiet illuminated manuscript."
	},
	{
		id: "rose",
		name: "Rosé",
		description: "Dried rose and gold on deep plum-gray or soft rose-tinted cream, with DM Sans. Gentle, muted, and warm."
	},
	{
		id: "miami",
		name: "Miami",
		description: "Hot magenta and cyan on violet-black or pale lavender, with Space Grotesk. Bright neon energy and a synthwave character."
	}
].map((e) => Object.assign(e, {
	source: "builtin",
	modes: ["light", "dark"]
}));
function requireRecord(e, t) {
	if (!e || typeof e !== "object" || Array.isArray(e)) throw new Error(`${t} must be an object`);
	return e;
}
function requireKeys(e, t, n) {
	const r = Object.keys(e).find((e) => !t.includes(e));
	if (r) throw new Error(`${n} has unsupported field ${r}`);
}
function requireText(e, t, n) {
	if (typeof e !== "string" || !e.trim() || e.trim().length > n || Array.from(e).some((e) => e.charCodeAt(0) < 32 || e.charCodeAt(0) === 127)) throw new Error(`${t} must be nonempty text of at most ${n} characters`);
	return e.trim();
}
function requireChoice(e, t, n) {
	const r = t.find((t) => t === e);
	if (!r) throw new Error(`${n} must be one of ${t.join(", ")}`);
	return r;
}
const NUMBER = "[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:e[+-]?\\d+)?";
const COMPONENT = `${NUMBER}%?`;
const HUE = `${NUMBER}(?:deg|grad|rad|turn)?`;
const LEGACY_COLOR_FUNCTION = new RegExp(`^(?:(?:rgb|rgba)\\( *(?:${NUMBER} *, *${NUMBER} *, *${NUMBER}|${NUMBER}% *, *${NUMBER}% *, *${NUMBER}%)|(?:hsl|hsla)\\( *${HUE} *, *${NUMBER}% *, *${NUMBER}%)(?: *, *${COMPONENT})? *\\)$`, "i");
const COLOR_FUNCTION = new RegExp(`^(?:(?:rgb|rgba|oklab|lab)\\( *${COMPONENT} +${COMPONENT} +${COMPONENT}|(?:hsl|hsla)\\( *${HUE} +${COMPONENT} +${COMPONENT}|(?:oklch|lch)\\( *${COMPONENT} +${COMPONENT} +${HUE})(?: */ *${COMPONENT})? *\\)$`, "i");
const COLOR_SPACE_FUNCTION = new RegExp(`^color\\( *(?:srgb|srgb-linear|display-p3|a98-rgb|prophoto-rgb|rec2020|xyz|xyz-d50|xyz-d65) +${COMPONENT} +${COMPONENT} +${COMPONENT}(?: */ *${COMPONENT})? *\\)$`, "i");
const FONT_IDENTIFIER = "(?:--[a-z0-9_-]*|-?[a-z_][a-z0-9_-]*)";
const FONT_FAMILY = `(?:"[a-z0-9 ,'._-]*"|'[a-z0-9 ,"._-]*'|${FONT_IDENTIFIER}(?: +${FONT_IDENTIFIER})*)`;
const FONT_FAMILY_LIST = new RegExp(`^${FONT_FAMILY}(?: *, *${FONT_FAMILY})*$`, "i");
const CSS_WIDE_KEYWORDS = /* @__PURE__ */ new Set([
	"inherit",
	"initial",
	"unset",
	"revert",
	"revert-layer"
]);
const GENERIC_FONT_FAMILIES = /* @__PURE__ */ new Set([
	"serif",
	"sans-serif",
	"monospace",
	"cursive",
	"fantasy",
	"system-ui",
	"ui-serif",
	"ui-sans-serif",
	"ui-monospace",
	"ui-rounded",
	"emoji",
	"math",
	"fangsong",
	"-webkit-body"
]);
function isFontFamilyList(e) {
	if (!FONT_FAMILY_LIST.test(e)) return false;
	return e.replace(/"[^"]*"|'[^']*'/g, "").split(",").every((e) => {
		const t = e.trim().toLowerCase().split(/ +/);
		return t.every((e) => !CSS_WIDE_KEYWORDS.has(e) && e !== "default" && (t.length === 1 || !GENERIC_FONT_FAMILIES.has(e)));
	});
}
function requireColor(e, t) {
	const n = requireText(e, t, 120);
	if (!/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(n) && !/^(?:transparent|black|white)$/i.test(n) && !LEGACY_COLOR_FUNCTION.test(n) && !COLOR_FUNCTION.test(n) && !COLOR_SPACE_FUNCTION.test(n)) throw new Error(`${t} must be a hex, rgb, hsl, lab, lch, oklab, oklch, or color() color`);
	return n;
}
function normalizePalette(e, t) {
	const n = requireRecord(e, `theme.${t}`);
	requireKeys(n, [...THEME_COLOR_KEYS, ...THEME_FONT_KEYS], `theme.${t}`);
	const r = THEME_COLOR_KEYS.map((e) => [e, requireColor(n[e], `theme.${t}.${e}`)]);
	const i = Object.fromEntries(r);
	for (const e of THEME_FONT_KEYS) {
		if (n[e] === void 0) continue;
		const r = requireText(n[e], `theme.${t}.${e}`, 120);
		if (!isFontFamilyList(r)) throw new Error(`theme.${t}.${e} must contain only font family names`);
		i[e] = r;
	}
	return i;
}
/** Rejects executable CSS and incomplete palettes before they reach storage or a stylesheet. */
function normalizeThemeDefinition(e, t) {
	const n = requireRecord(e, "theme");
	requireKeys(n, [
		"name",
		"description",
		"mascot",
		"brandName",
		"brandIcon",
		"workingIndicator",
		"lobsterdex",
		"communityLinks",
		"workingPhrases",
		"critters",
		"avatarHat",
		"light",
		"dark"
	], "theme");
	const r = {
		name: requireText(n.name, "theme.name", 80),
		description: requireText(n.description, "theme.description", 320),
		...n.light !== void 0 ? { light: normalizePalette(n.light, "light") } : {},
		...n.dark !== void 0 ? { dark: normalizePalette(n.dark, "dark") } : {}
	};
	if (n.mascot !== void 0) r.mascot = requireChoice(n.mascot, THEME_MASCOT_VALUES, "theme.mascot");
	if (n.brandName !== void 0) {
		const e = requireText(n.brandName, "theme.brandName", 80);
		if (/[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/u.test(e)) throw new Error("theme.brandName must contain only printable characters");
		r.brandName = e;
	}
	if (n.brandIcon !== void 0) r.brandIcon = requireChoice(n.brandIcon, [...THEME_BRAND_ICON_IDS, ...t?.iconIds ?? []], "theme.brandIcon");
	if (n.workingIndicator !== void 0) r.workingIndicator = requireChoice(n.workingIndicator, THEME_WORKING_INDICATOR_VALUES, "theme.workingIndicator");
	for (const e of ["lobsterdex", "communityLinks"]) if (n[e] !== void 0) {
		if (typeof n[e] !== "boolean") throw new Error(`theme.${e} must be a boolean`);
		r[e] = n[e];
	}
	if (n.workingPhrases !== void 0) {
		if (!Array.isArray(n.workingPhrases) || n.workingPhrases.length > 24) throw new Error(`theme.workingPhrases must be an array of at most ${24} entries`);
		const e = Array.from(n.workingPhrases, (e, t) => requireText(e, `theme.workingPhrases[${t}]`, 24));
		if (new Set(e).size !== e.length) throw new Error("theme.workingPhrases must not contain duplicate entries after trimming");
		r.workingPhrases = e;
	}
	if (n.critters !== void 0) {
		if (!Array.isArray(n.critters) || n.critters.length > 8) throw new Error("theme.critters must be an array of at most 8 entries");
		const e = [...THEME_CRITTER_IDS, ...t?.critterIds ?? []];
		const i = Array.from(n.critters, (t, n) => requireChoice(t, e, `theme.critters[${n}]`));
		if (new Set(i).size !== i.length) throw new Error("theme.critters must not contain duplicate entries");
		r.critters = i;
	}
	if (n.avatarHat !== void 0) r.avatarHat = requireChoice(n.avatarHat, [...THEME_AVATAR_HAT_IDS, ...t?.hatIds ?? []], "theme.avatarHat");
	if (!r.light && !r.dark) throw new Error("theme must provide at least one light or dark palette");
	if (new TextEncoder().encode(JSON.stringify(r)).length > 4096) throw new Error(`theme definition exceeds ${MAX_THEME_DEFINITION_BYTES} bytes`);
	return r;
}
//#endregion
//#region src/plugins/manifest-themes.ts
const MAX_PLUGIN_THEMES = 32;
const MAX_THEME_ARTWORK_ENTRIES = 8;
function objectProperties(e) {
	return e.type === "ObjectExpression" ? e.properties.filter((e) => e.type === "Property") : [];
}
function propertyName(e) {
	return e.key.type === "Identifier" ? e.key.name : e.key.type === "Literal" ? String(e.key.value) : "";
}
function validateArtworkDuplicates(e) {
	const { parseExpressionAt: t } = createRequire(import.meta.url)("acorn");
	const n = t(`(${e}\n)`, 0, { ecmaVersion: "latest" });
	for (const e of objectProperties(n)) {
		if (propertyName(e) !== "themes" || e.value.type !== "ArrayExpression") continue;
		for (const t of e.value.elements) {
			if (!t || t.type !== "ObjectExpression") continue;
			for (const e of objectProperties(t)) {
				const t = propertyName(e);
				if (t !== "icons" && t !== "hats" && t !== "critters" && t !== "backgrounds") continue;
				const n = /* @__PURE__ */ new Set();
				for (const r of objectProperties(e.value)) {
					const e = propertyName(r);
					if (n.has(e)) throw new Error(`themes.${t} has duplicate artwork ID ${e}`);
					n.add(e);
				}
			}
		}
	}
}
function normalizeArtworkEntries(e, t, n, r) {
	if (e === void 0) return;
	if (!isRecord(e)) throw new Error(`${t} must be a map with at most ${MAX_THEME_ARTWORK_ENTRIES} entries`);
	const i = Object.entries(e);
	if (i.length > MAX_THEME_ARTWORK_ENTRIES) throw new Error(`${t} must be a map with at most ${MAX_THEME_ARTWORK_ENTRIES} entries`);
	for (const [e] of i) if (!THEME_ARTWORK_ID_PATTERN.test(e) || n.includes(e)) throw new Error(`${t}.${e} must use a safe local ID outside the built-in catalog`);
	return Object.fromEntries(i.map(([e, n]) => [e, r(n, `${t}.${e}`)]));
}
function normalizeArtworkPath(e, t) {
	const n = typeof e === "string" ? e.replace(/^\.\//, "") : "";
	if (!/^(?:[a-z0-9_-][a-z0-9._-]*\/)*[a-z0-9_-][a-z0-9._-]*\.svg$/i.test(n)) throw new Error(`${t} must be an SVG file inside the plugin root`);
	return n;
}
function normalizeBackgrounds(e, t) {
	if (e === void 0) return;
	const n = isRecord(e) ? Object.entries(e) : [];
	if (!n.length || n.some(([e]) => e !== "light" && e !== "dark")) throw new Error(`${t} must map light and/or dark to an image`);
	return Object.fromEntries(n.map(([e, n]) => {
		const r = typeof n === "string" ? n.replace(/^\.\//, "") : "";
		if (!/^(?:[a-z0-9_-][a-z0-9._-]*\/)*[a-z0-9_-][a-z0-9._-]*\.(?:png|jpe?g|webp)$/i.test(r)) throw new Error(`${t}.${e} must be a PNG, JPEG, or WebP file inside the plugin root`);
		return [e, r];
	}));
}
function normalizeCritter(e, t) {
	if (!isRecord(e)) throw new Error(`${t} must be an object with an SVG source`);
	const { source: n, title: r, crossMs: i } = e;
	if (Object.keys(e).some((e) => ![
		"source",
		"title",
		"crossMs"
	].includes(e))) throw new Error(`${t} has unsupported fields`);
	if (r !== void 0 && (typeof r !== "string" || r.length > 60 || /[\p{Cc}\p{Cf}\p{Cs}]/u.test(r))) throw new Error(`${t}.title must be at most 60 printable characters`);
	if (i !== void 0 && (typeof i !== "number" || !Number.isInteger(i) || i < 5e3 || i > 9e4)) throw new Error(`${t}.crossMs must be an integer from 5000 to 90000`);
	return omitUndefinedFields({
		source: normalizeArtworkPath(n, `${t}.source`),
		title: r,
		crossMs: i
	});
}
function normalizeManifestThemes(e, t, n) {
	if (e === void 0) return { ok: true };
	if (!Array.isArray(e) || e.length > MAX_PLUGIN_THEMES) return {
		ok: false,
		error: `themes must be an array with at most ${MAX_PLUGIN_THEMES} entries`
	};
	if (e.length && (t === "user" || !isThemeId(`${t}/x`))) return {
		ok: false,
		error: "themes require a portable plugin ID outside the reserved user namespace"
	};
	const r = [];
	const i = /* @__PURE__ */ new Set();
	for (const [t, n] of e.entries()) {
		if (!isRecord(n)) return {
			ok: false,
			error: `themes[${t}] must be an object`
		};
		const { id: e, name: a, description: o, source: s, icons: c, hats: l, critters: u, backgrounds: d } = n;
		if (Object.keys(n).some((e) => ![
			"id",
			"name",
			"description",
			"source",
			"icons",
			"hats",
			"critters",
			"backgrounds"
		].includes(e)) || typeof e !== "string" || !THEME_LOCAL_ID_PATTERN.test(e) || i.has(e) || typeof a !== "string" || !a.trim() || a.trim().length > 80 || typeof o !== "string" || !o.trim() || o.trim().length > 320 || containsAsciiControlCharacter(a + o) || typeof s !== "string") return {
			ok: false,
			error: `themes[${t}] requires a unique safe id, name, description, and JSON source`
		};
		const f = s.replace(/^\.\//, "");
		if (!/^(?:[a-z0-9_-][a-z0-9._-]*\/)*[a-z0-9_-][a-z0-9._-]*\.json$/i.test(f)) return {
			ok: false,
			error: `themes[${t}].source must be a JSON file inside the plugin root`
		};
		try {
			r.push({
				id: e,
				name: a.trim(),
				description: o.trim(),
				source: f,
				...omitUndefinedFields({
					icons: normalizeArtworkEntries(c, `themes[${t}].icons`, THEME_BRAND_ICON_IDS, normalizeArtworkPath),
					hats: normalizeArtworkEntries(l, `themes[${t}].hats`, THEME_AVATAR_HAT_IDS, normalizeArtworkPath),
					critters: normalizeArtworkEntries(u, `themes[${t}].critters`, THEME_CRITTER_IDS, normalizeCritter),
					backgrounds: normalizeBackgrounds(d, `themes[${t}].backgrounds`)
				})
			});
		} catch (e) {
			return {
				ok: false,
				error: e instanceof Error ? e.message : "invalid theme artwork"
			};
		}
		i.add(e);
	}
	if (n && r.some((e) => e.icons || e.hats || e.critters || e.backgrounds)) try {
		validateArtworkDuplicates(n);
	} catch (e) {
		return {
			ok: false,
			error: e instanceof Error ? e.message : "invalid theme artwork"
		};
	}
	return {
		ok: true,
		themes: r
	};
}
//#endregion
//#region src/plugins/manifest.ts
/** Loads and normalizes OpenClaw plugin manifests, including contracts and config schemas. */
/** Canonical plugin manifest filename inside plugin roots. */
const PLUGIN_MANIFEST_FILENAME = "openclaw.plugin.json";
const MAX_PLUGIN_MANIFEST_BYTES = 262144;
const CORE_RESERVED_PLUGIN_IDS = /* @__PURE__ */ new Set(["node-mcp"]);
const VALID_PLUGIN_KINDS = /* @__PURE__ */ new Set(["memory", "context-engine"]);
function isCoreReservedPluginId(e) {
	return CORE_RESERVED_PLUGIN_IDS.has(normalizePluginPolicyId(e));
}
function parsePluginKind(e) {
	const t = typeof e === "string" ? [e] : Array.isArray(e) ? e : [];
	const n = [];
	for (const e of t) {
		if (typeof e !== "string" || !VALID_PLUGIN_KINDS.has(e)) continue;
		const t = e;
		if (!n.includes(t)) n.push(t);
	}
	return n.length === 0 ? void 0 : n.length === 1 ? n[0] : n;
}
function parseDoctorStateMigrationDescriptors(e) {
	if (typeof e === "boolean") return e;
	if (!Array.isArray(e)) return;
	const t = /* @__PURE__ */ new Set();
	return e.flatMap((e) => {
		if (!isRecord(e)) return [];
		const n = normalizeOptionalString(e.id);
		if (!n || t.has(n)) return [];
		t.add(n);
		return [{
			id: n,
			...e.doctorOnly === true ? { doctorOnly: true } : {},
			...e.phase === "after-session-repair" ? { phase: "after-session-repair" } : {}
		}];
	});
}
function parseManifestBackupResources(e) {
	if (e === void 0) return { ok: true };
	if (!Array.isArray(e)) return {
		ok: false,
		error: "backupResources must be an array"
	};
	const t = /* @__PURE__ */ new Map();
	for (const [n, r] of e.entries()) {
		if (!isRecord(r) || Object.keys(r).some((e) => ![
			"disposition",
			"scope",
			"relativePath",
			"databaseFamily"
		].includes(e)) || !("disposition" in r) || !("scope" in r) || !("relativePath" in r)) return {
			ok: false,
			error: `backupResources[${n}] requires disposition, scope, relativePath, and optional databaseFamily`
		};
		const { disposition: e, scope: i, relativePath: a, databaseFamily: o } = r;
		if (e !== "include" && e !== "regenerable") return {
			ok: false,
			error: `backupResources[${n}].disposition is invalid`
		};
		if (i !== "state" && i !== "agent") return {
			ok: false,
			error: `backupResources[${n}].scope is invalid`
		};
		if (o !== void 0 && (e !== "include" || i !== "state" || o !== "state")) return {
			ok: false,
			error: `backupResources[${n}].databaseFamily is invalid`
		};
		if (typeof a !== "string" || !a || a.includes("\\") || a.includes("\0") || path.posix.isAbsolute(a) || path.win32.isAbsolute(a) || /^[A-Za-z][A-Za-z\d+.-]*:/.test(a) || a.split("/").some((e) => !e || e === "." || e === "..")) return {
			ok: false,
			error: `backupResources[${n}].relativePath must be a strict relative POSIX path`
		};
		const s = {
			disposition: e,
			scope: i,
			relativePath: a,
			...o !== void 0 ? { databaseFamily: o } : {}
		};
		t.set(`${i}\0${a}\0${e}\0${o ?? ""}`, s);
	}
	return {
		ok: true,
		resources: [...t.entries()].toSorted(([e], [t]) => e < t ? -1 : e > t ? 1 : 0).map(([, e]) => e)
	};
}
function loadPluginManifest(e, t = true, n) {
	const r = readPluginCacheFile({
		rootDir: e,
		relativePath: PLUGIN_MANIFEST_FILENAME,
		...n !== void 0 ? { rootRealPath: n } : {},
		maxBytes: MAX_PLUGIN_MANIFEST_BYTES,
		rejectHardlinks: t
	});
	const i = r.ok ? r.path : path.join(e, PLUGIN_MANIFEST_FILENAME);
	if (!r.ok) return matchRootFileOpenFailure(r.failure, {
		path: () => ({
			ok: false,
			error: `plugin manifest not found: ${i}`,
			manifestPath: i
		}),
		fallback: (e) => ({
			ok: false,
			error: `unsafe plugin manifest path: ${i} (${e.reason})`,
			manifestPath: i
		})
	});
	if (r.manifest) return r.manifest;
	const cacheResult = (e) => {
		return r.manifest = e;
	};
	const fail = (e) => cacheResult({
		ok: false,
		error: e,
		manifestPath: i
	});
	const a = parsePluginCacheJson(r, { json5: true });
	if (!a.ok) return fail(`failed to parse plugin manifest: ${String(a.error)}`);
	const o = a.value;
	if (!isRecord(o)) return fail("plugin manifest must be an object");
	const s = normalizeOptionalString(o.id) ?? "";
	if (!s) return fail("plugin manifest requires id");
	if (isCoreReservedPluginId(s)) return fail(`plugin manifest id "${s}" is reserved by OpenClaw core`);
	const c = isRecord(o.configSchema) ? o.configSchema : null;
	if (!c) return fail("plugin manifest requires configSchema");
	const l = parseManifestBackupResources(o.backupResources);
	if (!l.ok) return cacheResult({
		ok: false,
		error: `invalid plugin manifest backupResources: ${l.error}`,
		manifestPath: i,
		diagnosticCode: "backup-resource-declaration-invalid"
	});
	const u = validatePluginCategories(o.categories);
	if (!u.ok) return fail(`invalid plugin manifest categories: ${u.error}`);
	const d = parsePluginKind(o.kind);
	let f;
	if (o.contextEngineIds !== void 0) {
		if (!(Array.isArray(d) ? d : [d]).includes("context-engine") || !Array.isArray(o.contextEngineIds) || o.contextEngineIds.length === 0 || o.contextEngineIds.some((e) => typeof e !== "string" || !e.trim() || ["legacy", "none"].includes(e.trim().toLowerCase()))) return cacheResult({
			ok: false,
			error: "contextEngineIds requires context-engine kind and a nonempty array of nonreserved engine IDs",
			manifestPath: i
		});
		f = [...new Set(normalizeTrimmedStringList(o.contextEngineIds))];
	}
	const p = normalizeTrimmedStringList(o.requiresPlugins);
	const m = normalizeManifestPlatforms(o.enabledByDefaultOnPlatforms);
	const h = normalizeTrimmedStringList(o.legacyPluginIds);
	const g = normalizeTrimmedStringList(o.autoEnableWhenConfiguredProviders);
	const _ = normalizeTrimmedStringList(o.providers);
	const v = normalizeTrimmedStringList(o.channels);
	const y = normalizeManifestContracts(o.contracts);
	const b = normalizeTrimmedStringList(o.cliBackends);
	const x = isRecord(o.doctorContract) ? o.doctorContract : void 0;
	const S = normalizeManifestCliCommands(o.cliCommands);
	let C;
	if (x?.recoveryCli !== void 0) {
		if (!Array.isArray(x.recoveryCli)) return fail("doctorContract.recoveryCli must be an array of command paths");
		C = [];
		const e = /* @__PURE__ */ new Set();
		for (const t of x.recoveryCli) {
			if (!Array.isArray(t) || t.length === 0 || !t.every((e) => typeof e === "string" && normalizeCommandDescriptorName(e) === e) || !S?.some(({ name: e }) => e === t[0])) return fail("doctorContract.recoveryCli paths must use plain command names beneath a declared cliCommands root");
			const n = t.join(" ");
			if (!e.has(n)) {
				e.add(n);
				C.push(t);
			}
		}
	}
	const w = parseDoctorStateMigrationDescriptors(x?.stateMigrations);
	const T = x ? {
		...Object.fromEntries([
			"configRepair",
			"resolveSessionStoreAgentIds",
			"sessionRouteStateOwners"
		].flatMap((e) => typeof x[e] === "boolean" ? [[e, x[e]]] : [])),
		...w !== void 0 ? { stateMigrations: w } : {},
		...C !== void 0 ? { recoveryCli: C } : {}
	} : void 0;
	/** The documented V1 manifest is an input adapter, not a second catalog. */
	const normalizeManifestModelCatalog = () => {
		const e = /* @__PURE__ */ new Set([
			..._,
			...b,
			...y?.decisionProviders ?? []
		]);
		const t = normalizeModelCatalog(o.modelCatalog, { ownedProviders: e });
		const n = normalizeManifestDecisionModels(o.decisionModels, y?.decisionProviders);
		if (!n?.length) return t;
		const r = /* @__PURE__ */ new Map();
		if (isRecord(o.modelCatalog) && isRecord(o.modelCatalog.providers)) for (const [e, t] of Object.entries(o.modelCatalog.providers)) {
			if (!isRecord(t) || !Array.isArray(t.models)) continue;
			const n = normalizeProviderId(e);
			const i = r.get(n) ?? /* @__PURE__ */ new Set();
			for (const e of t.models) {
				const t = isRecord(e) ? normalizeOptionalString(e.id) : void 0;
				if (t) i.add(t);
			}
			r.set(n, i);
		}
		const i = { ...t?.providers };
		for (const e of n) {
			const t = normalizeProviderId(e.provider);
			if (!t || isBlockedObjectKey$1(t)) continue;
			const n = i[t];
			if (r.get(t)?.has(e.id)) continue;
			const a = e.capabilities;
			const o = {};
			for (const e of a?.questionTypes ?? []) o[e] = {
				probabilities: e === "boolean" ? "boolean" : "provider-defined",
				abstention: false,
				...e === "boolean" && a?.requiresBooleanCriteria !== void 0 ? { requiresCriteria: a.requiresBooleanCriteria } : {},
				...e === "choice" && a?.maxChoiceAlternatives !== void 0 ? { maxOptions: a.maxChoiceAlternatives } : {},
				...e === "score" && a?.maxScoreLevels !== void 0 ? { maxOptions: a.maxScoreLevels } : {}
			};
			const s = {
				id: e.id,
				name: e.name,
				inference: {
					chat: false,
					decision: {
						protocol: "decision-v1",
						input: ["text"],
						...a ? {
							questions: o,
							...a.confidence ? { confidence: a.confidence } : {},
							limits: {
								...a.maxQuestions !== void 0 ? { maxQuestions: a.maxQuestions } : {},
								...a.maxInputTokens !== void 0 ? { maxInputTokens: a.maxInputTokens } : {},
								...a.inputTokenScope ? { inputTokenScope: a.inputTokenScope } : {}
							}
						} : {}
					}
				}
			};
			i[t] = {
				...n,
				models: [...n?.models ?? [], s]
			};
		}
		return normalizeModelCatalog({
			...t,
			providers: i
		}, { ownedProviders: e });
	};
	let E;
	try {
		E = normalizeManifestModelCatalog();
	} catch {
		return cacheResult({
			ok: false,
			error: "invalid plugin manifest modelCatalog ownership metadata",
			manifestPath: i
		});
	}
	const D = {
		id: s,
		configSchema: c,
		..."categories" in u ? { categories: u.categories } : {},
		...l.resources !== void 0 ? { backupResources: l.resources } : {},
		...p.length > 0 ? { requiresPlugins: p } : {},
		...o.enabledByDefault === true ? { enabledByDefault: true } : {},
		...m.length > 0 ? { enabledByDefaultOnPlatforms: m } : {},
		...h.length > 0 ? { legacyPluginIds: h } : {},
		...g.length > 0 ? { autoEnableWhenConfiguredProviders: g } : {},
		kind: d,
		...f ? { contextEngineIds: f } : {},
		...isRecord(o.reload) && o.reload.turnHandover === true ? { reload: { turnHandover: true } } : {},
		channels: v,
		channelAccountKeyPolicies: normalizeChannelAccountKeyPolicies(o.channelAccountKeyPolicies, v),
		providers: _,
		...o.managesOwnAvailability === true ? { managesOwnAvailability: true } : {},
		providerCatalogEntry: normalizeOptionalString(o.providerCatalogEntry),
		capabilityCatalogEntry: o.capabilityCatalogEntry === void 0 ? void 0 : normalizeOptionalString(o.capabilityCatalogEntry) ?? "",
		modelSupport: normalizeManifestModelSupport(o.modelSupport),
		modelCatalog: E,
		modelPricing: normalizeManifestModelPricing(o.modelPricing, { ownedProviders: /* @__PURE__ */ new Set([..._, ...b]) }),
		modelIdNormalization: normalizeManifestModelIdNormalization(o.modelIdNormalization, { ownedProviders: new Set(_) }),
		providerEndpoints: normalizeManifestProviderEndpoints(o.providerEndpoints),
		providerRequest: normalizeManifestProviderRequest(o.providerRequest, { ownedProviders: new Set(_) }),
		secretProviderIntegrations: normalizeManifestSecretProviderIntegrations(o.secretProviderIntegrations),
		cliBackends: b,
		syntheticAuthRefs: normalizeTrimmedStringList(o.syntheticAuthRefs),
		nonSecretAuthMarkers: normalizeTrimmedStringList(o.nonSecretAuthMarkers),
		commandAliases: normalizeManifestCommandAliases(o.commandAliases),
		cliCommands: S,
		providerUsageAuthEnvVars: normalizeStringListRecord(o.providerUsageAuthEnvVars),
		providerAuthAliases: normalizeManifestProviderAuthAliases(o.providerAuthAliases),
		providerAuthChoices: normalizeProviderAuthChoices(o.providerAuthChoices),
		activation: normalizeManifestActivation(o.activation),
		setup: normalizeManifestSetup(o.setup),
		doctorContract: T,
		doctorHealthChecks: o.doctorHealthChecks === true ? true : void 0,
		sessionRouteStateOwners: o.sessionRouteStateOwners === void 0 ? void 0 : coerceDoctorSessionRouteStateOwners(o.sessionRouteStateOwners),
		qaRunners: normalizeManifestQaRunners(o.qaRunners)
	};
	const O = normalizeManifestDashboard(o.dashboard);
	if (!O.ok) return fail(`invalid plugin manifest dashboard: ${O.error}`);
	const k = validatePluginUiCapabilities(o.uiCapabilities);
	const A = loadPluginControlUiDeclaration({
		rootDir: e,
		controlUi: o.controlUi,
		channels: v,
		rejectHardlinks: t,
		rootRealPath: n
	});
	if (!A.ok) return fail(`invalid plugin manifest controlUi: ${A.error}`);
	const j = normalizeManifestThemes(o.themes, s, r.contents.toString("utf8"));
	if (!j.ok) return fail(`invalid plugin manifest themes: ${j.error}`);
	return cacheResult({
		ok: true,
		...!k.ok ? { warnings: [`ignoring invalid plugin manifest uiCapabilities: ${k.error}`] } : {},
		manifest: {
			...D,
			dashboard: O.dashboard,
			controlUi: A.value,
			...k.ok && k.capabilities !== void 0 ? { uiCapabilities: k.capabilities } : {},
			themes: j.themes,
			mcpServers: normalizeManifestMcpServers(o.mcpServers),
			skills: normalizeTrimmedStringList(o.skills),
			name: normalizeOptionalString(o.name),
			description: normalizeOptionalString(o.description),
			catalog: normalizeManifestCatalog(o.catalog),
			version: normalizeOptionalString(o.version),
			uiHints: normalizeConfigUiHints(o.uiHints),
			configGroups: normalizeConfigGroups(o.configGroups, c),
			contracts: y,
			decisionModels: normalizeManifestDecisionModels(o.decisionModels, y?.decisionProviders),
			transcriptSources: normalizeManifestTranscriptSources(o.transcriptSources, y?.transcriptSourceProviders),
			mediaUnderstandingProviderMetadata: normalizeMediaUnderstandingProviderMetadata(o.mediaUnderstandingProviderMetadata),
			imageGenerationProviderMetadata: normalizeCapabilityProviderMetadata(o.imageGenerationProviderMetadata),
			videoGenerationProviderMetadata: normalizeCapabilityProviderMetadata(o.videoGenerationProviderMetadata),
			musicGenerationProviderMetadata: normalizeCapabilityProviderMetadata(o.musicGenerationProviderMetadata),
			toolMetadata: normalizePluginToolMetadata(o.toolMetadata),
			configContracts: normalizeManifestConfigContracts(o.configContracts),
			channelConfigs: normalizeChannelConfigs(o.channelConfigs)
		},
		manifestPath: i
	});
}
//#endregion
//#region src/plugins/bundle-manifest.ts
/** Reads Agent/Codex/Claude/Cursor bundle manifests into OpenClaw plugin manifest metadata. */
/** Relative manifest path for Codex-style plugin bundles. */
const CODEX_BUNDLE_MANIFEST_RELATIVE_PATH = ".codex-plugin/plugin.json";
const CLAUDE_BUNDLE_MANIFEST_RELATIVE_PATH = ".claude-plugin/plugin.json";
const CURSOR_BUNDLE_MANIFEST_RELATIVE_PATH = ".cursor-plugin/plugin.json";
const AGENT_BUNDLE_MANIFEST_RELATIVE_PATH = "plugin.json";
const BUNDLE_MANIFEST_PATHS = {
	agent: AGENT_BUNDLE_MANIFEST_RELATIVE_PATH,
	claude: CLAUDE_BUNDLE_MANIFEST_RELATIVE_PATH,
	codex: CODEX_BUNDLE_MANIFEST_RELATIVE_PATH,
	cursor: CURSOR_BUNDLE_MANIFEST_RELATIVE_PATH
};
const AGENT_BUNDLE_EXTENSION_NAMESPACE = "ai.openclaw";
const AGENT_BUNDLE_MANIFEST_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json";
const MAX_AGENT_BUNDLE_MANIFEST_BYTES = 262144;
const log$1 = createSubsystemLogger("plugins/bundle-manifest");
function mergeBundlePathLists(...e) {
	return [...new Set(e.flat())];
}
function hasInlineCapabilityValue(e) {
	if (typeof e === "string") return e.trim().length > 0;
	if (Array.isArray(e)) return e.length > 0;
	if (isRecord(e)) return Object.keys(e).length > 0;
	return e === true;
}
function slugifyPluginId(e, t) {
	const n = path.basename(t);
	return (normalizeLowercaseStringOrEmpty(e) || normalizeLowercaseStringOrEmpty(n)).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "bundle-plugin";
}
function loadBundleManifestFile(e) {
	const t = path.join(e.rootDir, e.manifestRelativePath);
	const n = readPluginCacheFile({
		rootDir: e.rootDir,
		rootRealPath: e.rootRealPath,
		relativePath: e.manifestRelativePath,
		rejectHardlinks: e.rejectHardlinks,
		maxBytes: MAX_AGENT_BUNDLE_MANIFEST_BYTES
	});
	if (!n.ok) return matchRootFileOpenFailure(n.failure, {
		path: () => {
			if (e.allowMissing) return {
				ok: true,
				raw: {},
				manifestPath: t
			};
			return {
				ok: false,
				error: `plugin manifest not found: ${t}`,
				manifestPath: t
			};
		},
		fallback: (e) => ({
			ok: false,
			error: `unsafe plugin manifest path: ${t} (${e.reason})`,
			manifestPath: t
		})
	});
	const r = parsePluginCacheJson(n, { json5: !e.strictJson });
	if (!r.ok) return {
		ok: false,
		error: `failed to parse plugin manifest: ${formatErrorMessage(r.error)}`,
		manifestPath: t
	};
	if (!isRecord(r.value)) return {
		ok: false,
		error: "plugin manifest must be an object",
		manifestPath: t
	};
	return {
		ok: true,
		raw: r.value,
		manifestPath: t
	};
}
function resolveCodexComponentDirs(e, t, n) {
	const r = normalizeUniqueSingleOrTrimmedStringList(e[n]);
	if (r.length > 0) return r;
	return pluginCacheExistsSync(path.join(t, n)) ? [n] : [];
}
function resolveBundleComponentPaths(e, t, n) {
	const r = normalizeUniqueSingleOrTrimmedStringList(e);
	return mergeBundlePathLists(n.filter((e) => pluginCacheExistsSync(path.join(t, e))), r);
}
function resolveCursorComponents(e, t) {
	const n = resolveBundleComponentPaths(e.commands, t, [".cursor/commands"]);
	const r = mergeBundlePathLists(resolveBundleComponentPaths(e.skills, t, ["skills"]), n);
	const i = resolveBundleComponentPaths(e.subagents ?? e.agents, t, [".cursor/agents"]);
	const a = [
		...r.length > 0 ? ["skills"] : [],
		...n.length > 0 ? ["commands"] : [],
		...i.length > 0 ? ["agents"] : []
	];
	for (const [n, r] of [
		["hooks", ".cursor/hooks.json"],
		["rules", ".cursor/rules"],
		["mcpServers", ".mcp.json"]
	]) if (hasInlineCapabilityValue(e[n]) || pluginCacheExistsSync(path.join(t, r))) a.push(n);
	return {
		skills: r,
		capabilities: a
	};
}
function resolveAgentActivation(e, t) {
	if (e.extensions === void 0) return;
	if (!isRecord(e.extensions)) {
		log$1.warn(`ignoring Agent Plugins extensions in ${t}: expected an object`);
		return;
	}
	const n = e.extensions[AGENT_BUNDLE_EXTENSION_NAMESPACE];
	if (n === void 0) return;
	if (!isRecord(n)) {
		log$1.warn(`ignoring Agent Plugins ${AGENT_BUNDLE_EXTENSION_NAMESPACE} extension in ${t}: expected an object`);
		return;
	}
	return normalizeManifestActivation(n.activation);
}
function loadBundleManifest(e) {
	const t = e.rejectHardlinks ?? true;
	const n = e.bundleFormat === "codex" || e.bundleFormat === "cursor" || e.bundleFormat === "agent" ? BUNDLE_MANIFEST_PATHS[e.bundleFormat] : CLAUDE_BUNDLE_MANIFEST_RELATIVE_PATH;
	const r = loadBundleManifestFile({
		rootDir: e.rootDir,
		...e.rootRealPath !== void 0 ? { rootRealPath: e.rootRealPath } : {},
		manifestRelativePath: n,
		rejectHardlinks: t,
		allowMissing: e.bundleFormat === "claude",
		strictJson: e.bundleFormat === "agent"
	});
	if (!r.ok) return r;
	const i = r.raw;
	const a = isRecord(i.interface) ? i.interface : void 0;
	const o = normalizeOptionalString(i.name);
	const s = normalizeOptionalString(i.description) ?? normalizeOptionalString(i.shortDescription) ?? normalizeOptionalString(a?.shortDescription);
	const c = normalizeOptionalString(i.version);
	const l = {
		id: slugifyPluginId(o, e.rootDir),
		name: o,
		description: s,
		version: c,
		skills: [],
		settingsFiles: [],
		hooks: [],
		bundleFormat: e.bundleFormat,
		activation: void 0,
		capabilities: []
	};
	if (e.bundleFormat === "agent") {
		if (i.$schema !== AGENT_BUNDLE_MANIFEST_SCHEMA) return {
			ok: false,
			error: `root plugin.json is not an Agent Plugins manifest; expected $schema ${AGENT_BUNDLE_MANIFEST_SCHEMA}`,
			manifestPath: r.manifestPath
		};
		if (!o) return {
			ok: false,
			error: "agent plugin manifest name must be a non-empty string",
			manifestPath: r.manifestPath
		};
		l.skills = pluginCacheStatSync(path.join(e.rootDir, "skills"))?.isDirectory() ? ["skills"] : [];
		l.activation = resolveAgentActivation(i, r.manifestPath);
		l.capabilities = [...l.skills.length > 0 ? ["skills"] : [], ...pluginCacheExistsSync(path.join(e.rootDir, "mcp.json")) ? ["mcpServers"] : []];
	} else {
		l.activation = normalizeManifestActivation(i.activation);
		if (e.bundleFormat === "codex") {
			l.skills = resolveCodexComponentDirs(i, e.rootDir, "skills");
			l.hooks = resolveCodexComponentDirs(i, e.rootDir, "hooks");
			l.capabilities = [...l.skills.length > 0 ? ["skills"] : [], ...l.hooks.length > 0 ? ["hooks"] : []];
			for (const [t, n] of [["mcpServers", ".mcp.json"], ["apps", ".app.json"]]) if (hasInlineCapabilityValue(i[t]) || pluginCacheExistsSync(path.join(e.rootDir, n))) l.capabilities.push(t);
		} else if (e.bundleFormat === "cursor") Object.assign(l, resolveCursorComponents(i, e.rootDir));
		else Object.assign(l, resolveClaudeComponents(i, e.rootDir));
	}
	const u = isRecord(i.extensions) ? i.extensions : void 0;
	const d = isRecord(u?.["com.openai"]) ? u["com.openai"] : void 0;
	const f = normalizeOptionalString(d?.onboardingSkill);
	if (f) {
		const t = path.normalize(f);
		if (!path.isAbsolute(t) && t !== ".." && !t.startsWith(`..${path.sep}`) && path.basename(t) === "SKILL.md" && l.skills.some((n) => {
			const r = path.relative(path.resolve(e.rootDir, n), path.resolve(e.rootDir, t));
			return r !== ".." && !r.startsWith(`..${path.sep}`) && !path.isAbsolute(r);
		})) l.onboardingSkill = t;
	}
	return {
		ok: true,
		manifest: l,
		manifestPath: r.manifestPath
	};
}
function resolveClaudeComponents(e, t) {
	const n = resolveBundleComponentPaths(e.skills, t, ["skills"]);
	const r = resolveBundleComponentPaths(e.commands, t, ["commands"]);
	const i = resolveBundleComponentPaths(e.agents, t, ["agents"]);
	const a = resolveBundleComponentPaths(e.outputStyles, t, ["output-styles"]);
	const o = mergeBundlePathLists(n, r, i, a);
	const s = pluginCacheExistsSync(path.join(t, "settings.json")) ? ["settings.json"] : [];
	const c = resolveBundleComponentPaths(e.hooks, t, ["hooks/hooks.json"]);
	return {
		skills: o,
		settingsFiles: s,
		hooks: c,
		capabilities: [
			...o.length > 0 ? ["skills"] : [],
			...r.length > 0 ? ["commands"] : [],
			...i.length > 0 ? ["agents"] : [],
			...hasInlineCapabilityValue(e.hooks) || c.length > 0 ? ["hooks"] : [],
			...hasInlineCapabilityValue(e.mcpServers) || resolveBundleComponentPaths(e.mcpServers, t, [".mcp.json"]).length > 0 ? ["mcpServers"] : [],
			...hasInlineCapabilityValue(e.lspServers) || resolveBundleComponentPaths(e.lspServers, t, [".lsp.json"]).length > 0 ? ["lspServers"] : [],
			...hasInlineCapabilityValue(e.outputStyles) || a.length > 0 ? ["outputStyles"] : [],
			...s.length > 0 ? ["settings"] : []
		]
	};
}
function detectBundleManifestFormat(e) {
	if (pluginCacheExistsSync(path.join(e, CODEX_BUNDLE_MANIFEST_RELATIVE_PATH))) return "codex";
	if (pluginCacheExistsSync(path.join(e, CURSOR_BUNDLE_MANIFEST_RELATIVE_PATH))) return "cursor";
	if (pluginCacheExistsSync(path.join(e, ".claude-plugin/plugin.json"))) return "claude";
	if (pluginCacheExistsSync(path.join(e, "openclaw.plugin.json"))) return null;
	if (pluginCacheExistsSync(path.join(e, AGENT_BUNDLE_MANIFEST_RELATIVE_PATH))) {
		const t = loadBundleManifestFile({
			rootDir: e,
			manifestRelativePath: AGENT_BUNDLE_MANIFEST_RELATIVE_PATH,
			rejectHardlinks: false,
			strictJson: true
		});
		if (t.ok && t.raw.$schema === AGENT_BUNDLE_MANIFEST_SCHEMA) return "agent";
	}
	if (DEFAULT_PLUGIN_ENTRY_CANDIDATES.some((t) => pluginCacheExistsSync(path.join(e, t)))) return null;
	if ([
		path.join(e, "skills"),
		path.join(e, "commands"),
		path.join(e, "agents"),
		path.join(e, "hooks", "hooks.json"),
		path.join(e, ".mcp.json"),
		path.join(e, ".lsp.json"),
		path.join(e, "settings.json")
	].some((e) => pluginCacheExistsSync(e))) return "claude";
	return null;
}
//#endregion
//#region src/plugins/package-compat.ts
function normalizePartialComparableVersion(e) {
	const t = e.trim();
	return /^[vV]?[0-9]+\.[0-9]+$/.test(t) ? {
		version: `${t}.0`,
		isPartial: true
	} : {
		version: t,
		isPartial: false
	};
}
function normalizePluginApiVersionForComparator(e, t) {
	const n = OPENCLAW_NUMERIC_CORRECTION_PATTERN.exec(e.trim())?.[1];
	if (n) return n;
	return prerelease(normalizePartialComparableVersion(t).version) ? e : OPENCLAW_RELEASE_SUFFIX_PATTERN.exec(e.trim())?.[1] ?? e;
}
function satisfiesComparator(e, t) {
	const n = t.trim();
	if (!n) return true;
	const r = /^(>=|<=|>|<|=|\^|~)?\s*(.+)$/.exec(n);
	if (!r) return false;
	const i = r[1] ?? "";
	const a = r[2]?.trim();
	if (!a || /^[<>=^~]/.test(a)) return false;
	const o = normalizePluginApiVersionForComparator(e, a);
	const s = normalizePartialComparableVersion(a);
	const c = s.isPartial && !i ? `>=${s.version}` : `${i}${s.version}`;
	return satisfies(o, c, { includePrerelease: true });
}
function satisfiesSemverRange(e, t) {
	if (t.includes("||")) return false;
	const n = normalizeStringEntries(t.trim().split(/\s+/));
	if (n.length === 0) return false;
	return n.every((t) => satisfiesComparator(e, t));
}
const OPENCLAW_RELEASE_SUFFIX_PATTERN = /^[vV]?(\d{4}\.[1-9]\d?\.[1-9]\d*)(?:-\d+|-(?:alpha|beta|rc)\.\d+)$/i;
const OPENCLAW_NUMERIC_CORRECTION_PATTERN = /^[vV]?(\d{4}\.[1-9]\d?\.[1-9]\d*)-\d+$/;
/** Resolves the plugin API compatibility range declared by package metadata. */
function resolvePackagePluginApiRange(e) {
	if (!isRecord(e) || !("compat" in e)) return { ok: true };
	const t = e.compat;
	if (t === void 0 || t === null) return { ok: true };
	if (!isRecord(t)) return {
		ok: false,
		error: "package.json openclaw.compat must be an object"
	};
	if (!("pluginApi" in t)) return { ok: true };
	const n = t.pluginApi;
	if (typeof n !== "string") return {
		ok: false,
		error: "package.json openclaw.compat.pluginApi must be a string"
	};
	const r = n.trim();
	if (!r) return {
		ok: false,
		error: "package.json openclaw.compat.pluginApi must not be empty"
	};
	return {
		ok: true,
		range: r
	};
}
/** Checks whether a host plugin API version satisfies a package plugin API range. */
function satisfiesPluginApiRange(e, t) {
	if (!t) return true;
	return satisfiesSemverRange(e, t);
}
//#endregion
//#region src/plugins/runtime-degraded-state.ts
/** Boot-stable quarantine state for configured plugins whose payload failed verification. */
const PLUGIN_AVAILABILITY_POLICY = {
	state: "configured-unavailable",
	severity: "warning",
	repairCommand: "openclaw doctor --fix"
};
//#endregion
//#region src/plugins/discovery-availability.ts
const CONFIGURED_PLUGIN_PATH_UNAVAILABLE = "configured-plugin-path-unavailable";
const CONFIGURED_PLUGIN_PATH_INSPECTION_FAILED = "configured-plugin-path-inspection-failed";
function shouldSkipIncompatiblePackagePluginApi(e) {
	if (e.origin === "bundled") return false;
	const t = resolvePackagePluginApiRange(e.packageManifest);
	if (!t.ok) {
		e.diagnostics.push({
			level: "warn",
			configDisposition: "preserve",
			source: path.join(e.packageDir, "package.json"),
			message: `invalid package plugin API metadata: ${t.error}; skipping discovery (check package.json openclaw.compat.pluginApi)`,
			pluginId: e.pluginId
		});
		return true;
	}
	const n = t.range;
	if (!n) return false;
	const r = resolveCompatibilityHostVersion(e.env);
	if (satisfiesPluginApiRange(r, n)) return false;
	e.diagnostics.push({
		level: "warn",
		configDisposition: "preserve",
		source: path.join(e.packageDir, "package.json"),
		message: `plugin requires plugin API ${n}, but this host is ${r}; skipping discovery (check "openclaw --version", OPENCLAW_COMPATIBILITY_HOST_VERSION, or run "openclaw doctor")`,
		pluginId: e.pluginId
	});
	return true;
}
function pluginPathFailureDiagnostic(e, t, n) {
	if (t === "config" && !isMissingPathError(n)) {
		const t = extractErrorCode(n) ?? "UNKNOWN";
		const r = `${t === "EACCES" || t === "EPERM" ? `Fix permissions on ${e}` : t === "ELOOP" ? `Fix the symbolic link loop at ${e}` : `Resolve the filesystem inspection error on ${e}`}, then run \`${PLUGIN_AVAILABILITY_POLICY.repairCommand}\`.`;
		return {
			level: "warn",
			code: CONFIGURED_PLUGIN_PATH_INSPECTION_FAILED,
			configDisposition: "preserve",
			errorCode: t,
			source: e,
			fixHint: r,
			message: `Configured plugin load path inspection failed: ${e} (${formatErrorMessageWithCode(n)}). Uninspected plugin configuration is preserved. ${r}`
		};
	}
	return t === "config" ? {
		level: "warn",
		code: CONFIGURED_PLUGIN_PATH_UNAVAILABLE,
		configDisposition: "preserve",
		source: e,
		message: `Configured plugin load path is unavailable: ${e}. Uninspected plugin configuration is preserved. Restore access to the path, then run \`${PLUGIN_AVAILABILITY_POLICY.repairCommand}\`.`
	} : {
		level: "error",
		source: e,
		message: `plugin path not found: ${e}`
	};
}
function inspectPluginLoadPath(e, t, n) {
	try {
		const r = pluginCacheStatSync(e, t === "config");
		if (!r && !pluginCacheExistsSync(e)) n.push(pluginPathFailureDiagnostic(e, t, void 0));
		if (t === "config" && r) {
			if (r.isDirectory()) readPluginCacheDirectory(e);
			else if (!r.isFile()) throw Object.assign(/* @__PURE__ */ new Error("Plugin load path is not a regular file or directory"), { code: "ERR_INVALID_FILE_TYPE" });
		}
		return r;
	} catch (r) {
		n.push(pluginPathFailureDiagnostic(e, t, r));
		return null;
	}
}
//#endregion
//#region src/plugins/hardlink-policy.ts
/** Enforces plugin root hardlink policy with bundled and immutable Nix-store exceptions. */
const NIX_STORE_ROOT = "/nix/store";
/** Returns true when a plugin root resolves inside the immutable Nix store. */
function isNixStorePluginRoot(e) {
	const t = pluginCacheRealpathSync(e) ?? path.resolve(e);
	return t === NIX_STORE_ROOT || t.startsWith(`${NIX_STORE_ROOT}/`);
}
/** Decides whether plugin file hardlinks should fail boundary validation for one root. */
function shouldRejectHardlinkedPluginFiles(e) {
	if (e.origin === "bundled") return false;
	if (resolveIsNixMode(e.env) && isNixStorePluginRoot(e.rootDir)) return false;
	return true;
}
//#endregion
//#region src/plugins/discovery-required-plugins.ts
function addMissingRequiredPluginDiagnostics(e, t) {
	const n = new Set(e.candidates.map((e) => normalizePluginPolicyId(e.idHint)));
	const r = /* @__PURE__ */ new Set();
	let i;
	for (const a of e.candidates) for (const o of a.requiredPluginIds ?? []) {
		const s = normalizePluginPolicyId(o);
		if (n.has(s)) continue;
		if (!i) {
			i = /* @__PURE__ */ new Set();
			for (const n of e.candidates) {
				if (n.origin !== "config" || n.packageDir) continue;
				const e = shouldRejectHardlinkedPluginFiles({
					origin: n.origin,
					rootDir: n.rootDir,
					env: t.env
				});
				const r = loadPluginManifest(n.rootDir, e);
				if (r.ok) i.add(normalizePluginPolicyId(r.manifest.id));
			}
		}
		if (i.has(s)) continue;
		const c = `${normalizePluginPolicyId(a.idHint)}\0${s}`;
		if (r.has(c)) continue;
		r.add(c);
		e.diagnostics.push({
			level: "warn",
			pluginId: a.idHint,
			source: a.requiredPluginSource ?? a.source,
			message: `plugin "${a.idHint}" requires plugin "${o}"; install "${o}" to use it`
		});
	}
}
//#endregion
//#region src/plugins/package-entry-resolution.ts
function reportPackageEntryDiagnostic(e, t, n) {
	e.diagnostics.push({
		level: t,
		...e.pluginIdHint ? { pluginId: e.pluginIdHint } : {},
		message: n,
		source: e.sourceLabel
	});
	return null;
}
function resolvePackageRuntimeExtensionEntries(e) {
	const t = getPackageManifestMetadata(e.manifest ?? void 0)?.runtimeExtensions;
	const n = [];
	if (!Array.isArray(t)) return {
		ok: true,
		runtimeExtensions: n
	};
	for (const [e, r] of t.entries()) {
		const t = normalizeOptionalString(r);
		if (!t) return {
			ok: false,
			error: `package.json openclaw.runtimeExtensions[${e}] must be a non-empty string`
		};
		n.push(t);
	}
	if (n.length > 0 && n.length !== e.extensions.length) return {
		ok: false,
		error: `package.json openclaw.runtimeExtensions length (${n.length}) must match openclaw.extensions length (${e.extensions.length})`
	};
	return {
		ok: true,
		runtimeExtensions: n
	};
}
function missingCompiledRuntimeEntryMessage(e) {
	const t = e.context === "install" ? "package install" : "installed plugin package";
	const n = e.context === "install" ? "retry installation after the publisher ships compiled JavaScript" : "update or reinstall the plugin after the publisher ships compiled JavaScript, or disable/uninstall the plugin until then";
	return `${t} requires compiled runtime output for TypeScript entry ${e.entry}: expected ${e.candidates.join(", ")}. This is a plugin packaging issue, not a local config problem; ${n}. TypeScript source fallback is only supported for source checkouts and local development paths.`;
}
function resolvePackageEntrySource(e) {
	const t = path.resolve(e.packageDir, e.entryPath);
	const n = e.rejectHardlinks ?? true;
	const r = [t];
	if (!n) {
		const e = t.replace(/\.[^.]+$/u, ".js");
		if (e !== t) r.push(e);
	}
	const i = r.find((e) => pluginCacheExistsSync(e)) ?? t;
	const a = checkPluginCacheEntry({
		rootDir: e.packageDir,
		relativePath: path.relative(e.packageDir, i),
		rootRealPath: e.packageRootRealPath,
		rejectHardlinks: n
	});
	if (!a.ok) return matchRootFileOpenFailure(a, {
		path: () => null,
		io: () => reportPackageEntryDiagnostic(e, "warn", `extension entry unreadable (I/O error): ${e.entryPath}`),
		fallback: () => reportPackageEntryDiagnostic(e, "error", `extension entry escapes package directory: ${e.entryPath}`)
	});
	return a.exists ? a.path : null;
}
function resolveSafePackageEntry(e) {
	const t = path.resolve(e.packageDir, e.entryPath);
	if (pluginCacheExistsSync(t)) {
		const n = resolvePackageEntrySource(e);
		if (!n) return null;
		return {
			relativePath: path.relative(e.packageDir, t).replace(/\\/g, "/"),
			existingSource: n
		};
	}
	if (!checkPluginCacheEntry({
		rootDir: e.packageDir,
		relativePath: e.entryPath,
		rootRealPath: e.packageRootRealPath,
		rejectHardlinks: e.rejectHardlinks ?? true
	}).ok) return reportPackageEntryDiagnostic(e, "error", `extension entry escapes package directory: ${e.entryPath}`);
	return { relativePath: path.relative(e.packageDir, t).replace(/\\/g, "/") };
}
function resolvePackageRuntimeEntrySource(e) {
	const t = resolveSafePackageEntry(e);
	if (!t) return null;
	if (e.runtimeEntryPath) {
		const t = resolvePackageEntrySource({
			...e,
			entryPath: e.runtimeEntryPath
		});
		if (t) return t;
		return reportPackageEntryDiagnostic(e, "error", `${e.runtimeEntryLabel ?? "runtime entry"} not found: ${e.runtimeEntryPath}`);
	}
	if (e.origin === "config" || e.origin === "global") {
		const n = listBuiltRuntimeEntryCandidates(t.relativePath);
		for (const t of n) {
			if (!pluginCacheExistsSync(path.resolve(e.packageDir, t))) continue;
			return resolvePackageEntrySource({
				...e,
				entryPath: t
			});
		}
		if ((e.requireBuiltRuntimeEntry ?? e.origin === "global") && isTypeScriptPackageEntry(t.relativePath)) return reportPackageEntryDiagnostic(e, "warn", missingCompiledRuntimeEntryMessage({
			context: "installed",
			entry: t.relativePath,
			candidates: n
		}));
	}
	if (t.existingSource) return t.existingSource;
	if (e.rejectHardlinks === false) {
		const t = resolvePackageEntrySource(e);
		if (t) return t;
	}
	return reportPackageEntryDiagnostic(e, "error", `${e.sourceEntryLabel ?? "extension entry"} not found: ${t.relativePath}`);
}
/** Resolves the runtime setup source for a plugin package manifest. */
function resolvePackageSetupSource(e) {
	const t = getPackageManifestMetadata(e.manifest ?? void 0);
	const n = normalizeOptionalString(t?.setupEntry);
	if (!n) return null;
	return resolvePackageRuntimeEntrySource({
		...e,
		entryPath: n,
		sourceEntryLabel: "setup entry",
		runtimeEntryPath: normalizeOptionalString(t?.runtimeSetupEntry),
		runtimeEntryLabel: "runtime setup entry",
		pluginIdHint: e.pluginIdHint ?? normalizeOptionalString(t?.plugin?.id) ?? normalizeOptionalString(t?.channel?.id)
	});
}
/** Keeps declarations paired with their runtime sources when earlier entries cannot resolve. */
function resolvePackageRuntimeExtensions(e) {
	const t = resolvePackageRuntimeExtensionEntries(e);
	if (!t.ok) {
		reportPackageEntryDiagnostic(e, "error", t.error);
		return [];
	}
	return e.extensions.flatMap((n, r) => {
		const i = resolvePackageRuntimeEntrySource({
			...e,
			entryPath: n,
			sourceEntryLabel: "extension entry",
			runtimeEntryPath: t.runtimeExtensions[r],
			runtimeEntryLabel: "runtime extension entry"
		});
		return i ? [{
			entryPath: n,
			source: i
		}] : [];
	});
}
//#endregion
//#region src/plugins/plugin-lifecycle-trace.ts
/** Checks the opt-in plugin lifecycle tracing environment flag. */
function isPluginLifecycleTraceEnabled() {
	const e = process.env.OPENCLAW_PLUGIN_LIFECYCLE_TRACE?.trim().toLowerCase();
	return e === "1" || e === "true" || e === "yes";
}
function emitPluginLifecycleTrace(e) {
	const t = Number(process.hrtime.bigint() - e.start) / 1e6;
	const n = Object.entries(e.details ?? {}).filter((e) => e[1] !== void 0).map(([e, t]) => `${e}=${typeof t === "string" ? JSON.stringify(t) : t}`).join(" ");
	const r = n ? ` ${n}` : "";
	console.error(`[plugins:lifecycle] phase=${JSON.stringify(e.phase)} ms=${t.toFixed(2)} status=${e.status}${r}`);
}
/** Traces a synchronous plugin lifecycle phase when tracing is enabled. */
function tracePluginLifecyclePhase(e, t, n) {
	if (!isPluginLifecycleTraceEnabled()) return t();
	const r = process.hrtime.bigint();
	let i = "error";
	try {
		const e = t();
		i = "ok";
		return e;
	} finally {
		emitPluginLifecycleTrace({
			phase: e,
			start: r,
			status: i,
			details: n
		});
	}
}
//#endregion
//#region src/plugins/dev-source-root.ts
/** Env var that points bundled-plugin lookup at an OpenClaw source checkout. */
const OPENCLAW_DEV_SOURCE_ROOT_ENV = "OPENCLAW_DEV_SOURCE_ROOT";
/** Packaging records this only for same-commit plugins in a non-release image. */
function readStagedOfficialPluginIds(e) {
	const t = readPluginCacheJsonFile(path.join(e, "dist", "build-info.json"));
	if (!t.ok || !isRecord(t.value)) return [];
	const { commit: n, stagedOfficialPlugins: r } = t.value;
	return typeof n === "string" && /^[0-9a-f]{40}$/.test(n) && isRecord(r) && r.commit === n && Array.isArray(r.pluginIds) ? r.pluginIds : [];
}
function readPackageName(e) {
	try {
		const t = JSON.parse(fsSync.readFileSync(e, "utf-8"));
		return typeof t.name === "string" ? t.name : null;
	} catch {
		return null;
	}
}
/** Resolves and validates the configured OpenClaw development source root. */
function resolveOpenClawDevSourceRoot(e = process.env) {
	const t = e[OPENCLAW_DEV_SOURCE_ROOT_ENV]?.trim();
	if (!t) return null;
	const n = resolveUserPath(t, e);
	const r = getPluginCache().sdk.devSourceRoots;
	if (r.has(n)) return r.get(n) ?? null;
	const i = pluginCacheRealpathSync(n);
	const a = i && readPackageName(path.join(i, "package.json")) === "openclaw" && pluginCacheExistsSync(path.join(i, "src")) && pluginCacheExistsSync(path.join(i, "extensions")) ? i : null;
	r.set(n, a);
	return a;
}
/** Source builds own their bundled SDK consumers even without an explicit development selector. */
function resolveBundledPluginSourceRoot(e = process.env) {
	const t = resolveOpenClawDevSourceRoot(e);
	if (t) return t;
	const n = resolveOpenClawPackageRootSync({ moduleUrl: import.meta.url });
	return n && (isSourceCheckoutRoot(n) || readStagedOfficialPluginIds(n).length > 0) ? n : null;
}
/** Prioritizes already-bundled candidates; the selector itself never grants provenance. */
function isBundledPluginInsideDevSourceRoot(e) {
	const t = resolveBundledPluginSourceRoot(e.env);
	if (!t) return false;
	if (!isPluginInPackageBundledRoots({
		packageRoot: t,
		rootDir: resolveUserPath(e.rootDir, e.env)
	})) return false;
	if (resolveOpenClawDevSourceRoot(e.env)) return true;
	const n = pluginCacheRealpathSync(t);
	const r = pluginCacheRealpathSync(resolveUserPath(e.rootDir, e.env));
	if (!isSourceCheckoutRoot(t)) return Boolean(n && r && readStagedOfficialPluginIds(n).includes(path.basename(r)) && path.dirname(r) === path.join(n, "dist", "extensions"));
	return Boolean(n && r && ["dist", "dist-runtime"].some((e) => isPathInside$2(path.join(n, e, "extensions"), r)));
}
//#endregion
//#region src/plugins/install-paths.ts
/** Validates a plugin id for install path safety. */
function validatePluginId(e) {
	const t = e.trim();
	if (!t) return "invalid plugin name: missing";
	if (t.includes("\\")) return "invalid plugin name: path separators not allowed";
	const n = t.split("/");
	if (n.some((e) => !e)) return "invalid plugin name: malformed scope";
	if (n.some((e) => e === "." || e === "..")) return "invalid plugin name: reserved path segment";
	if (n.length === 1) {
		if (t.startsWith("@")) return "invalid plugin name: scoped ids must use @scope/name format";
		return null;
	}
	if (n.length !== 2) return "invalid plugin name: path separators not allowed";
	if (!n[0]?.startsWith("@") || n[0].length < 2) return "invalid plugin name: scoped ids must use @scope/name format";
	return null;
}
/** Resolves the default directory for path-installed plugin extensions. */
function resolveDefaultPluginExtensionsDir(e = process.env, t) {
	return resolveActivePluginInstallDir("extensions", e, t);
}
/** Resolves the default directory for managed npm plugin installs. */
function resolveDefaultPluginNpmDir(e = process.env, t) {
	return resolveActivePluginInstallDir("npm", e, t);
}
/** Encodes an npm package name into a managed npm project directory name. */
function encodePluginNpmProjectDirName(e) {
	const t = e.trim();
	if (!t) throw new Error("invalid npm package name: missing");
	return safePathSegmentHashed(t);
}
/** Resolves the directory containing managed npm plugin projects. */
function resolvePluginNpmProjectsDir(e) {
	const t = e ? resolveUserPath(e) : resolveDefaultPluginNpmDir();
	return path.join(t, "projects");
}
/** Resolves the managed npm project directory for a package name. */
function resolvePluginNpmProjectDir(e) {
	return path.join(resolvePluginNpmProjectsDir(e.npmDir), encodePluginNpmProjectDirName(e.packageName));
}
const PLUGIN_NPM_GENERATION_PROJECT_SEPARATOR = "__openclaw-generation__";
const PLUGIN_NPM_GENERATION_KEY_HASH_CHARS = 16;
const PLUGIN_NPM_GENERATION_KEY_DIR_NAME_PATTERN = new RegExp(`^g-[a-f0-9]{${PLUGIN_NPM_GENERATION_KEY_HASH_CHARS}}$`, "u");
/** Resolves the managed npm artifact-generation project directory prefix for a package. */
function resolvePluginNpmGenerationProjectDirPrefix(e) {
	return `${encodePluginNpmProjectDirName(e)}${PLUGIN_NPM_GENERATION_PROJECT_SEPARATOR}`;
}
/** Checks that a managed path preserves its npm-root-relative real path. */
function isPluginNpmManagedPath(e) {
	const t = path.resolve(e.npmDir ?? resolveDefaultPluginNpmDir());
	const n = path.resolve(e.managedPath);
	try {
		return lstatSync(t).isDirectory() && path.relative(t, n) === path.relative(realpathSync(t), e.allowMissing ? resolvePathViaExistingAncestorSync$1(n) : realpathSync(n));
	} catch {
		return false;
	}
}
/** Checks whether a project directory has the exact managed shape owned by a package. */
function isPluginNpmProjectDir(e) {
	const t = path.resolve(e.npmDir ?? resolveDefaultPluginNpmDir());
	const n = path.resolve(e.projectDir);
	if (path.dirname(n) !== path.resolve(resolvePluginNpmProjectsDir(t))) return false;
	if (!isPluginNpmManagedPath({
		managedPath: n,
		npmDir: t
	})) return false;
	if (!isPluginNpmManagedPath({
		managedPath: path.join(n, "node_modules", ...e.packageName.split("/")),
		npmDir: t,
		allowMissing: true
	})) return false;
	if (n === path.resolve(resolvePluginNpmProjectDir(e))) return true;
	const r = path.basename(n);
	const i = resolvePluginNpmGenerationProjectDirPrefix(e.packageName);
	return r.startsWith(i) && PLUGIN_NPM_GENERATION_KEY_DIR_NAME_PATTERN.test(r.slice(i.length));
}
//#endregion
//#region src/plugins/roots.ts
function resolvePluginSourceRoots(e) {
	const t = e.env ?? process.env;
	const n = e.workspaceDir ? resolveUserPath(e.workspaceDir, t) : void 0;
	return {
		stock: resolveBundledPluginsDir(t),
		global: resolveDefaultPluginExtensionsDir(t),
		workspace: n ? path.join(n, ".openclaw", "extensions") : void 0
	};
}
function resolvePluginCacheInputs(e) {
	const t = e.env ?? process.env;
	return {
		roots: resolvePluginSourceRoots({
			workspaceDir: e.workspaceDir,
			env: t
		}),
		loadPaths: normalizeStringEntries((e.loadPaths ?? []).filter((e) => typeof e === "string")).map((e) => resolveUserPath(e, t)),
		devSourceRoot: resolveOpenClawDevSourceRoot(t)
	};
}
//#endregion
//#region src/infra/json-files.ts
function tryReadJsonObjectSync(e) {
	return asNullableRecord(tryReadJsonSync(e));
}
//#endregion
//#region src/plugins/status-dependencies-core.ts
function normalizeDependencyMap(e) {
	if (!e || typeof e !== "object" || Array.isArray(e)) return {};
	const t = {};
	for (const [n, r] of Object.entries(e)) {
		const e = n.trim();
		if (!e || typeof r !== "string" || !r.trim()) continue;
		t[e] = r.trim();
	}
	return t;
}
/** Normalizes raw package dependency maps into sorted plugin dependency specs. */
function normalizePluginDependencySpecs(e) {
	const t = normalizeDependencyMap(e.dependencies);
	const n = normalizeDependencyMap(e.optionalDependencies);
	for (const e of Object.keys(n)) delete t[e];
	return {
		dependencies: t,
		optionalDependencies: n
	};
}
//#endregion
//#region src/plugins/discovery.ts
/** Discovers plugin candidates from bundled, workspace, global, package, and bundle roots. */
const SCANNED_DIRECTORY_IGNORE_NAMES = /* @__PURE__ */ new Set([
	".git",
	".hg",
	".svn",
	".turbo",
	".yarn",
	".yarn-cache",
	"build",
	"coverage",
	"dist",
	"node_modules"
]);
function currentUid() {
	if (process.platform === "win32" || typeof process.getuid !== "function") return null;
	return process.getuid();
}
function checkSourceEscapesRoot(e) {
	const t = pluginCacheRealpathSync(e.source);
	const n = pluginCacheRealpathSync(e.rootDir);
	if (!t || !n) return null;
	if (isPathInside$1(n, t)) return null;
	return {
		source: e.source,
		message: `blocked plugin candidate: source escapes plugin root (${e.source} -> ${t}; root=${n})`
	};
}
function checkPathStatAndPermissions(e) {
	if (process.platform === "win32") return null;
	const t = [e.rootDir, e.source];
	const n = /* @__PURE__ */ new Set();
	for (const r of t) {
		const t = path.resolve(r);
		if (n.has(t)) continue;
		n.add(t);
		let i = pluginCacheStatSync(r);
		if (!i) return {
			source: r,
			message: `blocked plugin candidate: cannot stat path (${r})`
		};
		let a = i.mode & 511;
		if ((a & 2) !== 0 && e.origin === "bundled") try {
			fsSync.chmodSync(r, a & -19);
			const e = refreshPluginCacheStat(r);
			if (!e) return {
				source: r,
				message: `blocked plugin candidate: cannot stat path (${r})`
			};
			i = e;
			a = e.mode & 511;
		} catch {}
		if ((a & 2) !== 0) return {
			source: r,
			message: `blocked plugin candidate: world-writable path (${r}, mode=${formatPosixMode(a)})`
		};
		if (e.origin !== "bundled" && e.uid !== null && typeof i.uid === "number" && i.uid !== e.uid && i.uid !== 0) return {
			source: r,
			message: `blocked plugin candidate: suspicious ownership (${r}, uid=${i.uid}, expected uid=${e.uid} or root)`
		};
	}
	return null;
}
function isExtensionFile(e) {
	const t = path.extname(e);
	if (!PUBLIC_SURFACE_SOURCE_EXTENSIONS.some((e) => e === t)) return false;
	if (/\.d\.[cm]?ts$/.test(e)) return false;
	return !normalizeLowercaseStringOrEmpty(path.basename(e)).includes(".test.");
}
function shouldIgnoreScannedDirectory(e) {
	const t = normalizeLowercaseStringOrEmpty(e);
	return !t || SCANNED_DIRECTORY_IGNORE_NAMES.has(t) || t.endsWith(".bak") || t.includes(".backup-") || t.includes(".disabled");
}
function resolvesToSameDirectory(e, t) {
	if (!e || !t) return false;
	const n = pluginCacheRealpathSync(e);
	const r = pluginCacheRealpathSync(t);
	if (n && r) return n === r;
	return path.resolve(e) === path.resolve(t);
}
function mergeCandidateInstallOwner(e, t, n) {
	const r = resolvePluginCandidateInstallOwner(e);
	const i = r && t && r !== t;
	if (isPluginCandidateInstallOwnerAmbiguous(e) || n || i) recordPluginCandidateInstallOwner(e, void 0, true);
	else if (t) recordPluginCandidateInstallOwner(e, t);
}
function prepareInstalledPluginPaths(e, t, n) {
	const r = /* @__PURE__ */ new Map();
	const i = /* @__PURE__ */ new Set();
	const a = /* @__PURE__ */ new Set();
	const resolveRecordPath = (e) => typeof e === "string" && e.trim() ? resolveUserPath(e, t) : void 0;
	for (const [t, o] of Object.entries(e ?? {})) {
		const e = resolveRecordPath(o.installPath);
		const s = resolveRecordPath(o.sourcePath);
		for (const t of [e, s]) if (t && pluginCacheExistsSync(t)) {
			const e = resolveManagedPluginDirKey(t);
			if (e) a.add(e);
		}
		const c = e ?? s;
		if (!c || !pluginCacheExistsSync(c)) continue;
		const l = pluginCacheRealpathSync(c) ?? path.resolve(c);
		const u = !(o.source === "path" && e && s && resolvesToSameDirectory(e, s));
		const d = r.get(l);
		if (d) {
			d.requireBuiltRuntimeEntry ||= u;
			if (d.installOwner !== t) {
				delete d.installOwner;
				d.installOwnerAmbiguous = true;
				n.push({
					level: "error",
					source: c,
					message: "multiple plugin install records claim the same package path; refresh or reinstall the package before using managed lifecycle actions"
				});
			}
		} else {
			r.set(l, {
				path: c,
				requireBuiltRuntimeEntry: u,
				installOwner: t
			});
			const e = resolveManagedPluginDirKey(c);
			if (e) i.add(e);
		}
	}
	return {
		installedPaths: [...r.values()],
		installedPluginDirKeys: i,
		managedPluginDirs: a
	};
}
function resolveManagedPluginDirKey(e) {
	const t = pluginCacheStatSync(e);
	if (!t) return null;
	const n = t.isFile() ? path.dirname(e) : e;
	return pluginCacheRealpathSync(n) ?? path.resolve(n);
}
function isManagedPluginDir(e) {
	if (!e.managedPluginDirs || e.managedPluginDirs.size === 0) return false;
	const t = e.realpath ?? pluginCacheRealpathSync(e.dir) ?? path.resolve(e.dir);
	return e.managedPluginDirs.has(t);
}
function readPackageManifest(e, t = true, n) {
	const r = readPluginCacheFile({
		rootDir: e,
		...n !== void 0 ? { rootRealPath: n } : {},
		relativePath: "package.json",
		rejectHardlinks: t
	});
	if (!r.ok) return null;
	const i = parsePluginCacheJson(r);
	return i.ok && isRecord(i.value) ? i.value : null;
}
function derivePackagePluginIdHint(e) {
	const t = normalizeOptionalString(e);
	if (!t) return;
	const n = t.slice(t.lastIndexOf("/") + 1);
	for (const e of ["-provider", "-plugin"]) if (n.endsWith(e) && n.length > e.length) return n.slice(0, -e.length);
	return normalizeOptionalString(n);
}
function resolvePluginPackageEntries(e) {
	const t = groupPluginRecords(resolvePackageRuntimeExtensions(e), (t) => {
		const n = t.source;
		const r = e.manifestId;
		const i = e.manifest?.name;
		const a = path.basename(e.packageDir);
		const o = e.extensions.length > 1;
		const s = path.basename(n, path.extname(n));
		const c = normalizeOptionalString(r) ?? derivePackagePluginIdHint(i) ?? a;
		return o ? `${c}/${s}` : c;
	});
	const n = [];
	for (const [r, i] of t) {
		if (e.extensions.length > 1 && i.length > 1) {
			e.diagnostics.push({
				level: "error",
				pluginId: r,
				source: e.sourceLabel,
				message: `plugin package entries collide on derived id "${r}" (${i.map((t) => path.relative(e.packageDir, t.source)).join(", ")}); rename the entry files to unique basenames`
			});
			continue;
		}
		for (const e of i) n.push({
			...e,
			idHint: r
		});
	}
	return n;
}
function isSourceCheckoutExtensionsDir(e) {
	const t = path.dirname(e);
	return pluginCacheExistsSync(path.join(t, ".git")) && pluginCacheExistsSync(path.join(t, "pnpm-workspace.yaml")) && pluginCacheExistsSync(path.join(t, "src")) && hasUsableBundledPluginTree(e);
}
function resolveBundledSourceCheckoutExtensionsDir(e) {
	if (!e) return;
	const t = buildLegacyBundledRootPath(e);
	if (!t || !isPluginInPackageBundledRoots({
		rootDir: t,
		packageRoot: path.dirname(t)
	}) || !isSourceCheckoutExtensionsDir(t)) return;
	return t;
}
function isHostBundledPluginRoot(e, t) {
	const n = resolveBundledPluginsDir(t);
	const r = pluginCacheRealpathSync(e) ?? path.resolve(e);
	return [n, resolveBundledSourceCheckoutExtensionsDir(n)].some((e) => e && isPathInside$1(pluginCacheRealpathSync(e) ?? path.resolve(e), r));
}
function readChildDirectoryNames(e) {
	if (!e || !pluginCacheExistsSync(e)) return /* @__PURE__ */ new Set();
	try {
		return new Set(sortUniqueStrings(readPluginCacheDirectory(e).filter((e) => e.isDirectory()).map((e) => e.name)));
	} catch {
		return /* @__PURE__ */ new Set();
	}
}
function readBundledDistOptOutDirectoryNames(e) {
	const t = /* @__PURE__ */ new Set();
	if (!e) return t;
	for (const n of readChildDirectoryNames(e)) if (getPackageManifestMetadata(readPackageManifest(path.join(e, n), false) ?? void 0)?.build?.bundledDist === false) t.add(n);
	return t;
}
function createPluginScanner(e) {
	const t = {
		candidates: [],
		diagnostics: []
	};
	const { candidates: n, diagnostics: r } = t;
	const i = /* @__PURE__ */ new Map();
	function addCandidate(e) {
		const t = path.resolve(e.source);
		if (i.has(t)) {
			const n = i.get(t);
			if (n) mergeCandidateInstallOwner(n, e.installOwner, e.installOwnerAmbiguous === true);
			return;
		}
		const a = pluginCacheRealpathSync(e.rootDir) ?? path.resolve(e.rootDir);
		const o = checkSourceEscapesRoot({
			source: t,
			rootDir: a
		}) ?? checkPathStatAndPermissions({
			source: t,
			rootDir: a,
			origin: e.origin,
			uid: currentUid()
		});
		if (o) {
			r.push({
				level: "warn",
				...e.idHint ? { pluginId: e.idHint } : {},
				...o
			});
			i.set(t, void 0);
			return;
		}
		const s = e.manifest ?? null;
		const c = getPackageManifestMetadata(s ?? void 0);
		const l = normalizePluginDependencySpecs({
			dependencies: s?.dependencies,
			optionalDependencies: s?.optionalDependencies
		});
		const u = {
			idHint: e.idHint,
			...e.effectivePluginId ? { effectivePluginId: e.effectivePluginId } : {},
			...e.diagnosticIdHint && e.diagnosticIdHint !== e.idHint ? { diagnosticIdHint: e.diagnosticIdHint } : {},
			source: t,
			setupSource: e.setupSource,
			rootDir: a,
			origin: e.origin,
			format: e.format ?? "openclaw",
			bundleFormat: e.bundleFormat,
			workspaceDir: e.workspaceDir,
			packageName: normalizeOptionalString(s?.name),
			packageVersion: normalizeOptionalString(s?.version),
			packageDescription: normalizeOptionalString(s?.description),
			packageDir: e.packageDir,
			packageManifest: c,
			packageDependencies: l.dependencies,
			packageOptionalDependencies: l.optionalDependencies,
			rawPackageManifest: s ?? void 0,
			bundledManifestId: e.bundledManifestId,
			bundledManifestPath: e.bundledManifestPath,
			...e.requiredPluginIds && e.requiredPluginIds.length > 0 ? { requiredPluginIds: e.requiredPluginIds } : {},
			...e.requiredPluginSource ? { requiredPluginSource: e.requiredPluginSource } : {}
		};
		recordPluginCandidateInstallOwner(u, e.installOwner, e.installOwnerAmbiguous === true);
		n.push(u);
		i.set(t, u);
	}
	function discoverPluginDirectory(t) {
		const { dir: n, rootRealPath: i } = t;
		const a = t.requireBuiltRuntimeEntry ?? isManagedPluginDir({
			dir: n,
			realpath: i,
			managedPluginDirs: t.managedPluginDirs
		});
		const o = shouldRejectHardlinkedPluginFiles({
			origin: t.origin,
			rootDir: n,
			env: e
		});
		const s = readPackageManifest(n, o, i);
		const c = getPackageManifestMetadata(s ?? void 0);
		const l = loadPluginManifest(n, o, i);
		const u = l.ok ? l : void 0;
		const d = u?.manifest.id;
		const f = normalizeOptionalString(d) ?? normalizeOptionalString(c?.plugin?.id) ?? normalizeOptionalString(c?.channel?.id) ?? derivePackagePluginIdHint(s?.name) ?? path.basename(n);
		if (shouldSkipIncompatiblePackagePluginApi({
			origin: t.origin,
			packageManifest: c,
			pluginId: f,
			packageDir: n,
			env: e,
			diagnostics: r
		})) return true;
		const p = resolvePackageExtensionEntries(s ?? void 0);
		if (p.status === "invalid" || p.status === "empty") {
			r.push({
				level: "error",
				source: n,
				message: p.status === "invalid" ? p.error : "package.json openclaw.extensions is empty",
				...f ? { pluginId: f } : {}
			});
			return true;
		}
		const m = p.status === "ok" ? p.entries : [];
		const h = {
			packageDir: n,
			...i !== void 0 ? { packageRootRealPath: i } : {},
			manifest: s,
			pluginIdHint: f,
			origin: t.origin,
			requireBuiltRuntimeEntry: a,
			sourceLabel: n,
			diagnostics: r,
			rejectHardlinks: o
		};
		const g = resolvePackageSetupSource(h);
		const addPackageCandidate = (e, r, i) => {
			addCandidate({
				idHint: r,
				...i ? { effectivePluginId: i } : {},
				diagnosticIdHint: f,
				source: e,
				...g ? { setupSource: g } : {},
				rootDir: n,
				origin: t.origin,
				workspaceDir: t.workspaceDir,
				...t.installOwner ? { installOwner: t.installOwner } : {},
				...t.installOwnerAmbiguous ? { installOwnerAmbiguous: true } : {},
				manifest: s,
				packageDir: n,
				requiredPluginIds: u?.manifest.requiresPlugins,
				requiredPluginSource: u?.manifestPath
			});
		};
		if (m.length > 0) {
			const e = resolvePluginPackageEntries({
				...h,
				extensions: m,
				manifestId: d ?? normalizeOptionalString(c?.plugin?.id)
			});
			for (const t of e) addPackageCandidate(t.source, t.idHint, m.length > 1 ? t.idHint : void 0);
			return true;
		}
		const _ = detectBundleManifestFormat(n);
		if (_) {
			const e = loadBundleManifest({
				rootDir: n,
				...i !== void 0 ? { rootRealPath: i } : {},
				bundleFormat: _,
				rejectHardlinks: o
			});
			if (!e.ok) r.push({
				level: "error",
				message: e.error,
				source: e.manifestPath
			});
			else {
				addCandidate({
					idHint: e.manifest.id,
					source: n,
					rootDir: n,
					origin: t.origin,
					format: "bundle",
					bundleFormat: _,
					workspaceDir: t.workspaceDir,
					...t.installOwner ? { installOwner: t.installOwner } : {},
					...t.installOwnerAmbiguous ? { installOwnerAmbiguous: true } : {},
					manifest: s,
					packageDir: n,
					bundledManifestId: e.manifest.id,
					bundledManifestPath: e.manifestPath
				});
				return true;
			}
		}
		const v = [...DEFAULT_PLUGIN_ENTRY_CANDIDATES].map((e) => path.join(n, e)).find((e) => pluginCacheExistsSync(e));
		if (v && isExtensionFile(v)) {
			addPackageCandidate(v, d ?? path.basename(n));
			return true;
		}
		return false;
	}
	function discoverInDirectory(e) {
		if (!pluginCacheExistsSync(e.dir)) return;
		let t;
		try {
			t = readPluginCacheDirectory(e.dir).toSorted((e, t) => e.name < t.name ? -1 : e.name > t.name ? 1 : 0);
		} catch (t) {
			r.push(e.origin === "config" ? pluginPathFailureDiagnostic(e.dir, e.origin, t) : {
				level: "warn",
				message: `failed to read extensions dir: ${e.dir} (${String(t)})`,
				source: e.dir
			});
			return;
		}
		for (const n of t) {
			const t = path.join(e.dir, n.name);
			const i = n.isSymbolicLink() ? pluginCacheStatSync(t) : n;
			const a = i?.isFile() ? "file" : i?.isDirectory() ? "directory" : null;
			if (a === "file") {
				if (!(e.scanFiles ?? e.origin === "bundled") || !isExtensionFile(t)) continue;
				addCandidate({
					idHint: path.basename(n.name, path.extname(n.name)),
					source: t,
					rootDir: path.dirname(t),
					origin: e.origin,
					workspaceDir: e.workspaceDir,
					...e.installOwner ? { installOwner: e.installOwner } : {},
					...e.installOwnerAmbiguous ? { installOwnerAmbiguous: true } : {}
				});
				continue;
			}
			if (a !== "directory") continue;
			if (e.skipDirectories?.has(n.name)) continue;
			if (shouldIgnoreScannedDirectory(n.name)) continue;
			const o = pluginCacheRealpathSync(t) ?? void 0;
			const s = o ?? path.resolve(t);
			if (e.origin === "bundled" && !isPathInside$1(pluginCacheRealpathSync(e.dir) ?? path.resolve(e.dir), s)) {
				r.push({
					level: "error",
					source: t,
					message: `blocked plugin candidate: package directory escapes bundled root (${t})`
				});
				continue;
			}
			if (e.skipRootDirKeys?.has(s)) continue;
			discoverPluginDirectory({
				...e,
				dir: t,
				rootRealPath: o
			});
		}
	}
	function discoverFromPath(t) {
		const n = resolveUserPath(t.rawPath, e);
		const i = inspectPluginLoadPath(n, t.origin, r);
		if (!i) return;
		const a = (t.origin === "config" || t.origin === "global") && isHostBundledPluginRoot(i.isFile() ? path.dirname(n) : n, e) ? "bundled" : t.origin;
		if (i.isFile()) {
			if (!isExtensionFile(n)) {
				r.push({
					level: "error",
					message: `plugin path is not a supported file: ${n}`,
					source: n
				});
				return;
			}
			addCandidate({
				idHint: path.basename(n, path.extname(n)),
				source: n,
				rootDir: path.dirname(n),
				origin: a,
				workspaceDir: t.workspaceDir,
				...t.installOwner ? { installOwner: t.installOwner } : {},
				...t.installOwnerAmbiguous ? { installOwnerAmbiguous: true } : {}
			});
			return;
		}
		if (i.isDirectory()) {
			if (discoverPluginDirectory({
				...t,
				origin: a,
				dir: n,
				rootRealPath: pluginCacheRealpathSync(n) ?? void 0
			})) return;
			discoverInDirectory({
				dir: n,
				origin: a,
				workspaceDir: t.workspaceDir,
				...t.scanFiles !== void 0 || t.origin === "config" ? { scanFiles: t.scanFiles ?? true } : {},
				...t.requireBuiltRuntimeEntry !== void 0 ? { requireBuiltRuntimeEntry: t.requireBuiltRuntimeEntry } : {},
				...t.managedPluginDirs ? { managedPluginDirs: t.managedPluginDirs } : {},
				...t.skipRootDirKeys ? { skipRootDirKeys: t.skipRootDirKeys } : {}
			});
		}
	}
	function discoverConfiguredPaths(e, t) {
		const r = n.length;
		for (const n of e) if (typeof n === "string" && n.trim()) discoverFromPath({
			rawPath: n.trim(),
			origin: "config",
			workspaceDir: t
		});
		for (const e of n.slice(r)) e.configSelected = true;
	}
	function finish() {
		const e = /* @__PURE__ */ new Map();
		const i = /* @__PURE__ */ new Set();
		const a = [];
		for (const t of n) {
			const n = pluginCacheRealpathSync(t.source) ?? path.resolve(t.source);
			const r = e.get(n);
			if (r) {
				const i = t.origin === "bundled" ? t : r;
				const a = i === t ? r : t;
				if (a.origin === "config" || a.configSelected) i.configSelected = true;
				if (a.sourcePreferred) i.sourcePreferred = true;
				mergeCandidateInstallOwner(i, resolvePluginCandidateInstallOwner(a), isPluginCandidateInstallOwnerAmbiguous(a));
				e.set(n, i);
				continue;
			}
			e.set(n, t);
		}
		for (const e of r) {
			const t = [
				e.level,
				e.pluginId ?? "",
				e.source ?? "",
				e.message
			].join("\0");
			if (i.has(t)) continue;
			i.add(t);
			a.push(e);
		}
		t.candidates = [...e.values()];
		t.diagnostics = a;
		return t;
	}
	return {
		result: t,
		discoverConfiguredPaths,
		discoverFromPath,
		discoverInDirectory,
		finish
	};
}
function discoveryPolicy(e, t) {
	return {
		ownershipUid: currentUid(),
		compatibilityHostVersion: resolveCompatibilityHostVersion(e),
		bundledRoot: t ?? resolveBundledPluginsDir(e) ?? "",
		nix: resolveIsNixMode(e),
		sourceOverlaysDisabled: e.OPENCLAW_DISABLE_BUNDLED_SOURCE_OVERLAYS ?? "",
		home: e.OPENCLAW_HOME ?? "",
		userHome: e.HOME ?? "",
		userProfile: e.USERPROFILE ?? "",
		cwd: process.cwd()
	};
}
function discoverSharedPluginRoots(e) {
	const { roots: t, env: n } = e;
	const r = getPluginCache().metadata.sharedDiscovery;
	const i = hashStableJson({
		roots: t,
		installRecords: Object.entries(e.installRecords ?? {}),
		rootScope: e.rootScope ?? "all",
		policy: discoveryPolicy(n, t.stock)
	});
	const a = r.get(i);
	if (a) return a;
	const o = createPluginScanner(n);
	const { result: s, discoverInDirectory: c } = o;
	const l = /* @__PURE__ */ new Set();
	const discoverWorkspacePath = (e) => {
		const t = s.candidates.length;
		o.discoverFromPath(e);
		for (const e of s.candidates.slice(t)) l.add(e);
	};
	tracePluginLifecyclePhase("discovery scan", () => {
		for (const e of listBundledSourceOverlayDirs({
			bundledRoot: t.stock,
			env: n
		})) {
			const t = s.candidates.length;
			discoverWorkspacePath({
				rawPath: e,
				origin: "bundled"
			});
			for (const e of s.candidates.slice(t)) e.sourcePreferred = true;
			s.diagnostics.push({
				level: "warn",
				source: e,
				message: "using bind-mounted bundled plugin source overlay; this source overrides the packaged dist bundle for the same plugin id"
			});
		}
		const r = resolveSourceCheckoutDependencyDiagnostic(n);
		if (r) s.diagnostics.push({
			level: "warn",
			source: r.source,
			message: r.message
		});
		const i = resolveBundledSourceCheckoutExtensionsDir(t.stock);
		const a = readBundledDistOptOutDirectoryNames(i);
		if (i) for (const e of a) discoverWorkspacePath({
			rawPath: path.join(i, e),
			origin: "bundled"
		});
		if (t.stock) c({
			dir: t.stock,
			origin: "bundled",
			skipDirectories: a
		});
		const o = resolvesToSameDirectory(i, t.stock);
		if (i && !o) c({
			dir: i,
			origin: "bundled",
			skipDirectories: readChildDirectoryNames(t.stock)
		});
		if (e.rootScope !== "bundled") {
			const { installedPaths: r, installedPluginDirKeys: i, managedPluginDirs: a } = prepareInstalledPluginPaths(e.installRecords, n, s.diagnostics);
			for (const e of r) discoverWorkspacePath({
				rawPath: e.path,
				origin: "global",
				...e.installOwner ? { installOwner: e.installOwner } : {},
				...e.installOwnerAmbiguous ? { installOwnerAmbiguous: true } : {},
				requireBuiltRuntimeEntry: e.requireBuiltRuntimeEntry,
				managedPluginDirs: a,
				scanFiles: true
			});
			c({
				dir: t.global,
				origin: "global",
				managedPluginDirs: a,
				skipRootDirKeys: i
			});
		}
	}, { scope: "shared" });
	const u = {
		candidates: s.candidates.map((e) => ({
			candidate: e,
			usesWorkspace: l.has(e)
		})),
		diagnostics: s.diagnostics
	};
	r.set(i, u);
	return u;
}
function discoverOpenClawPlugins(e) {
	const t = e.env ?? process.env;
	const n = normalizeOptionalString(e.workspaceDir);
	const r = n ? resolveUserPath(n, t) : void 0;
	const i = resolvePluginSourceRoots({
		workspaceDir: r,
		env: t
	});
	const a = e.bundledRoot ? {
		...i,
		stock: path.resolve(e.bundledRoot)
	} : i;
	const o = getPluginCache().metadata.discovery;
	const s = hashStableJson({
		phase: "all",
		roots: a,
		workspaceDir: n,
		loadPaths: e.extraPaths ?? [],
		installRecords: Object.entries(e.installRecords ?? {}),
		rootScope: e.rootScope ?? "all",
		policy: discoveryPolicy(t, a.stock)
	});
	const c = o.get(s);
	if (c) return c;
	const l = createPluginScanner(t);
	const { result: u, discoverInDirectory: d } = l;
	if (e.rootScope !== "bundled") tracePluginLifecyclePhase("discovery scan", () => {
		l.discoverConfiguredPaths(e.extraPaths ?? [], n);
		const t = resolvesToSameDirectory(r, a.stock) || resolvesToSameDirectory(a.workspace, a.global);
		if (a.workspace && r && !t) d({
			dir: a.workspace,
			origin: "workspace",
			workspaceDir: r
		});
	}, {
		scope: "scoped",
		extraPathCount: e.extraPaths?.length ?? 0
	});
	const f = discoverSharedPluginRoots({
		roots: {
			stock: a.stock,
			global: a.global
		},
		installRecords: e.installRecords,
		env: t,
		rootScope: e.rootScope
	});
	for (const { candidate: e, usesWorkspace: t } of f.candidates) u.candidates.push({
		...e,
		...t ? { workspaceDir: n } : {}
	});
	u.diagnostics.push(...f.diagnostics);
	l.finish();
	addMissingRequiredPluginDiagnostics(u, { env: t });
	o.set(s, u);
	return u;
}
//#endregion
//#region src/plugins/installed-plugin-index-facts.ts
/** Package facts share the existing generation; mutable management inputs stay uncached. */
function getInstalledPluginIndexFacts(e) {
	const t = getPluginCache().metadata.indexFacts;
	const n = t.get(e);
	if (n) return n;
	if (!isDeeplyFrozenPlainData(e)) return;
	const r = {};
	t.set(e, r);
	return r;
}
//#endregion
//#region src/plugins/bundled-provider-compat.ts
const BUNDLED_PROVIDER_COMPAT_CONTRACT_KEYS = [
	"speechProviders",
	"externalAuthProviders",
	"embeddingProviders",
	"mediaUnderstandingProviders",
	"transcriptSourceProviders",
	"realtimeVoiceProviders",
	"realtimeTranscriptionProviders",
	"imageGenerationProviders",
	"videoGenerationProviders",
	"musicGenerationProviders",
	"webFetchProviders",
	"webSearchProviders",
	"workerProviders",
	"storageProviders",
	"usageProviders",
	"migrationProviders"
];
const BUNDLED_PROVIDER_COMPAT_CONTRACTS = new Set(BUNDLED_PROVIDER_COMPAT_CONTRACT_KEYS);
//#endregion
//#region src/config/zod-schema.installs.ts
const InstallSourceSchema = union([
	literal("npm"),
	literal("archive"),
	literal("path"),
	literal("clawhub"),
	literal("git")
]);
const InstallRecordShape = {
	source: InstallSourceSchema,
	spec: string().optional(),
	sourcePath: string().optional(),
	installPath: string().optional(),
	version: string().optional(),
	resolvedName: string().optional(),
	resolvedVersion: string().optional(),
	resolvedSpec: string().optional(),
	integrity: string().optional(),
	shasum: string().optional(),
	resolvedAt: string().optional(),
	installedAt: string().optional(),
	clawhubUrl: string().optional(),
	clawhubPackage: string().optional(),
	clawhubFamily: union([literal("code-plugin"), literal("bundle-plugin")]).optional(),
	clawhubChannel: union([
		literal("official"),
		literal("community"),
		literal("private")
	]).optional(),
	clawhubTrustDisposition: union([
		literal("clean"),
		literal("review-recommended"),
		literal("review-required"),
		literal("blocked")
	]).optional(),
	clawhubTrustScanStatus: string().optional(),
	clawhubTrustModerationState: string().optional(),
	clawhubTrustReasons: array(string()).optional(),
	clawhubTrustPending: boolean().optional(),
	clawhubTrustStale: boolean().optional(),
	clawhubTrustCheckedAt: string().optional(),
	clawhubTrustAcknowledgedAt: string().optional(),
	artifactKind: union([literal("legacy-zip"), literal("npm-pack")]).optional(),
	artifactFormat: union([literal("zip"), literal("tgz")]).optional(),
	npmIntegrity: string().optional(),
	npmShasum: string().optional(),
	npmTarballName: string().optional(),
	clawpackSha256: string().optional(),
	clawpackSpecVersion: number().int().nonnegative().optional(),
	clawpackManifestSha256: string().optional(),
	clawpackSize: number().int().nonnegative().optional(),
	gitUrl: string().optional(),
	gitRef: string().optional(),
	gitCommit: string().optional()
};
object(InstallRecordShape);
const StrictPluginInstallRecordSchema = object({
	...InstallRecordShape,
	source: union([InstallSourceSchema, literal("marketplace")]),
	/** Retained package child-plugin engine ownership for uninstall without runtime files. */
	contextEngineIdsByPlugin: record(string().min(1), array(string().min(1))).optional(),
	marketplaceName: string().optional(),
	marketplaceSource: string().optional(),
	marketplacePlugin: string().optional(),
	acceptedSurface: strictObject({
		channels: array(string().min(1)),
		providers: array(string().min(1)),
		tools: array(string().min(1)),
		contracts: array(string().min(1)),
		hooks: array(string().min(1)),
		mcpServers: array(string().min(1)),
		cliCommands: array(string().min(1)),
		cliBackends: array(string().min(1)),
		skills: array(string().min(1)),
		dangerousConfigFlags: array(string().min(1))
	}).optional(),
	acceptedSurfaceHash: string().optional(),
	acceptedSurfaceAt: string().optional(),
	acceptedSurfaceIntegrity: string().optional()
});
//#endregion
//#region src/config/plugin-install-record-map.ts
const PluginInstallRecordSchema = StrictPluginInstallRecordSchema.passthrough();
const NORMALIZED_STRING_FIELDS = [
	"spec",
	"sourcePath",
	"installPath",
	"version",
	"resolvedName",
	"resolvedVersion",
	"resolvedSpec",
	"integrity",
	"shasum",
	"resolvedAt",
	"installedAt",
	"clawhubUrl",
	"clawhubPackage",
	"clawhubTrustScanStatus",
	"clawhubTrustModerationState",
	"clawhubTrustCheckedAt",
	"clawhubTrustAcknowledgedAt",
	"npmIntegrity",
	"npmShasum",
	"npmTarballName",
	"clawpackSha256",
	"clawpackManifestSha256",
	"gitUrl",
	"gitRef",
	"gitCommit",
	"marketplaceName",
	"marketplaceSource",
	"marketplacePlugin",
	"acceptedSurfaceHash",
	"acceptedSurfaceAt",
	"acceptedSurfaceIntegrity"
];
function createPluginInstallRecordMap() {
	return Object.create(null);
}
function setPluginInstallRecordMapEntry(e, t, n) {
	Object.defineProperty(e, t, {
		configurable: true,
		enumerable: true,
		value: n,
		writable: true
	});
}
function getPluginInstallRecordMapEntry(e, t) {
	return e && Object.hasOwn(e, t) ? e[t] : void 0;
}
function copyPluginInstallRecordMap(e) {
	const t = createPluginInstallRecordMap();
	for (const [n, r] of Object.entries(e ?? {})) setPluginInstallRecordMapEntry(t, n, r);
	return t;
}
function parsePluginInstallRecord(e) {
	const t = PluginInstallRecordSchema.safeParse(e);
	if (!t.success) return null;
	const n = t.data;
	for (const e of NORMALIZED_STRING_FIELDS) {
		const t = n[e];
		if (t === void 0) continue;
		const r = t.trim();
		if (r) n[e] = r;
		else delete n[e];
	}
	if (n.clawhubTrustReasons) {
		const e = n.clawhubTrustReasons.map((e) => e.trim()).filter(Boolean);
		if (e.length > 0) n.clawhubTrustReasons = e;
		else delete n.clawhubTrustReasons;
	}
	return n;
}
function parsePluginInstallRecordMap(e) {
	if (!isRecord(e)) return null;
	const t = createPluginInstallRecordMap();
	for (const [n, r] of Object.entries(e)) {
		const e = parsePluginInstallRecord(r);
		if (!e) return null;
		setPluginInstallRecordMapEntry(t, n, e);
	}
	return t;
}
function inspectPluginInstallRecordMap(e) {
	if (e === void 0) return { status: "missing" };
	const t = parsePluginInstallRecordMap(e);
	return t ? {
		status: "valid",
		records: t
	} : { status: "invalid" };
}
//#endregion
//#region src/plugins/doctor-contract-artifact.ts
/** Resolves the Doctor artifact shared by loading, index hashing, and freshness. */
const CONTRACT_API_EXTENSIONS = [
	".js",
	".mjs",
	".cjs",
	".ts",
	".mts",
	".cts"
];
const CURRENT_MODULE_PATH = fileURLToPath(import.meta.url);
const RUNNING_FROM_BUILT_ARTIFACT = CURRENT_MODULE_PATH.includes(`${path.sep}dist${path.sep}`) || CURRENT_MODULE_PATH.includes(`${path.sep}dist-runtime${path.sep}`);
const ORDERED_EXTENSIONS = RUNNING_FROM_BUILT_ARTIFACT ? CONTRACT_API_EXTENSIONS : [...CONTRACT_API_EXTENSIONS.slice(3), ...CONTRACT_API_EXTENSIONS.slice(0, 3)];
const ARTIFACT_CANDIDATES = ["doctor-contract-api", "contract-api"].map((e) => {
	const t = ORDERED_EXTENSIONS.map((t) => `${e}${t}`);
	return {
		rootPaths: t,
		paths: t.flatMap((e) => [e, path.join("dist", e)])
	};
});
//#endregion
//#region src/infra/clawhub-spec.ts
/** Parses explicit `clawhub:<name>[@version]` package specs for ClawHub installs. */
function parseClawHubPluginSpec(e) {
	const t = e.trim();
	if (!t.toLowerCase().startsWith("clawhub:")) return null;
	const n = t.slice(8).trim();
	if (!n) return null;
	const r = n.lastIndexOf("@");
	if (r <= 0) return { name: n };
	if (r >= n.length - 1) return null;
	const i = n.slice(0, r).trim();
	const a = n.slice(r + 1).trim();
	if (!i || !a) return null;
	return {
		name: i,
		version: a
	};
}
//#endregion
//#region src/plugins/manifest-install-owner.ts
const { record: recordPluginManifestInstallOwner, resolve: resolvePluginManifestInstallOwner, isAmbiguous: isPluginManifestInstallOwnerAmbiguous } = createPluginInstallOwnerMetadata("openclaw.pluginManifestInstallOwner", false);
//#endregion
//#region src/plugins/plugin-metadata-state.kernel.ts
const INSTALLED_PLUGIN_INDEX_STATE_KEY = "plugins.installedIndex";
function readPluginMetadataStateRowsInDatabase(e, t) {
	if (!tableExists(e, "config_machine_state")) return [];
	return executeSqliteQuerySync(e, getNodeSqliteKysely(e).selectFrom("config_machine_state").select(["state_key", "value_json"]).where("state_key", "in", t)).rows;
}
//#endregion
//#region src/plugins/installed-plugin-index-row.ts
/** Shared inspection commands use the same existing-only, artifact-preserving reader. */
function readPluginMetadataStateRowSync(e, t, n = false) {
	const r = readPluginMetadataStateRowsSync([e === "installed-index" ? INSTALLED_PLUGIN_INDEX_STATE_KEY : "plugins.bundledDiscovery"], t, n)[0];
	return r ? { value_json: r.value_json } : void 0;
}
/** Acquire related metadata facts from the same prepared database bytes. */
function readPluginMetadataStateRowsSync(e, t, n = false) {
	const read = ({ db: t }) => readPluginMetadataStateRowsInDatabase(t, e);
	return (n ? withExistingOpenClawStateDatabaseArtifactPreservingReadOnly(read, t) : withExistingOpenClawStateDatabaseReadOnly(read, t)) ?? [];
}
//#endregion
//#region src/plugins/installed-plugin-index-store-path.ts
const LEGACY_INSTALLED_PLUGIN_INDEX_STORE_PATH = path.join("plugins", "installs.json");
function resolveStoreEnv(e) {
	const t = e.env ?? process.env;
	if (e.stateDir) return {
		...t,
		OPENCLAW_STATE_DIR: e.stateDir
	};
	if (hasActivePluginInstallRoots()) return {
		...t,
		OPENCLAW_STATE_DIR: resolveActivePluginInstallRoots(t).stateDir
	};
	return t;
}
/** Resolves the canonical SQLite-backed installed plugin index path. */
function resolveInstalledPluginIndexStorePath(e = {}) {
	if (e.filePath) return e.filePath;
	return resolveOpenClawStateSqlitePath(resolveStoreEnv(e));
}
/** Resolves state database options for the installed plugin index store. */
function resolveInstalledPluginIndexStateDatabaseOptions(e = {}) {
	if (e.filePath) return {
		...e.env ? { env: e.env } : {},
		path: e.filePath
	};
	return { env: resolveStoreEnv(e) };
}
//#endregion
//#region src/plugins/installed-plugin-index-record-state.ts
/** Read failures must escape before either projection can authorize recovery or rebuilding. */
function readPersistedInstalledPluginIndexRowSync(e) {
	if (e.filePath?.endsWith(".json")) return;
	return readPluginMetadataStateRowSync("installed-index", resolveInstalledPluginIndexStateDatabaseOptions(e), e.artifactPreservingReadOnly);
}
/** Share the SQLite row while validating install records independently from index metadata. */
function getPersistedInstalledPluginIndexCacheEntry(e, t = () => readPersistedInstalledPluginIndexRowSync(e)) {
	const n = getPluginCache().persistedInstalledIndex;
	const r = path.resolve(resolveInstalledPluginIndexStorePath(e));
	const i = n.get(r);
	if (i && "value" in i) return i.value;
	const a = t();
	const o = { state: a ? {
		status: "present",
		value: safeParseJson(a.value_json)
	} : { status: "missing" } };
	n.set(r, { value: o });
	return o;
}
function inspectPersistedInstalledPluginIndexInstallRecords(e) {
	if (!e.records) {
		const t = e.state;
		const n = (t.status === "present" ? t.value : void 0)?.index?.installRecords;
		e.records = t.status === "missing" ? { status: "missing" } : n === void 0 ? { status: "invalid" } : inspectPluginInstallRecordMap(n);
	}
	return e.records;
}
function inspectPersistedInstalledPluginIndexInstallRecordsSync(e = {}) {
	return inspectPersistedInstalledPluginIndexInstallRecords(getPersistedInstalledPluginIndexCacheEntry(e));
}
//#endregion
//#region src/plugins/npm-project-roots.ts
function sortPaths(e) {
	return e.toSorted((e, t) => e.localeCompare(t));
}
/** Lists directory candidates; each consumer establishes its own package ownership. */
function listPluginNpmProjectCandidatesSync(e) {
	const t = resolvePluginNpmProjectsDir(e);
	try {
		return sortPaths(fsSync.readdirSync(t, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => path.join(t, e.name)));
	} catch (e) {
		if (isNotFoundPathError(e)) return [];
		throw e;
	}
}
/** Lists admitted projects with the manifest that established their managed ownership. */
function listManagedPluginNpmProjectsSync(e) {
	return listPluginNpmProjectCandidatesSync(e).flatMap((t) => {
		const n = tryReadJsonSync$1(path.join(t, "package.json"));
		if (!isRecord(n) || !isRecord(n.dependencies)) return [];
		return Object.keys(n.dependencies).some((n) => validatePluginId(n) === null && isPluginNpmProjectDir({
			packageName: n,
			projectDir: t,
			npmDir: e
		})) ? [{
			projectRoot: t,
			manifest: n
		}] : [];
	});
}
//#endregion
//#region src/plugins/managed-npm-retention.ts
const RETAINED_MANAGED_NPM_INSTALL_MARKER_DIR = ".openclaw-retained-npm-installs";
function resolveRetainedManagedNpmInstallPackageInfo(e) {
	const t = path.resolve(e);
	const n = path.basename(t);
	const r = path.dirname(t);
	const i = path.basename(r);
	const a = i.startsWith("@");
	const o = a ? path.dirname(r) : r;
	if (path.basename(o) !== "node_modules") return null;
	const s = a ? `${i}/${n}` : n;
	if (!n || n === "." || !s.trim()) return null;
	const c = path.dirname(o);
	return {
		packageName: s,
		projectRoot: c,
		markerPath: path.join(c, RETAINED_MANAGED_NPM_INSTALL_MARKER_DIR, `${safePathSegmentHashed(s)}.json`)
	};
}
function hasRetainedManagedNpmInstallMarker(e) {
	const t = resolveRetainedManagedNpmInstallPackageInfo(e);
	return t ? fsSync.existsSync(t.markerPath) : false;
}
//#endregion
//#region src/plugins/installed-plugin-index-record-reader.ts
/** Reads installed-index records back into manifest registry records. */
function readStringRecord(e) {
	if (!isRecord(e)) return {};
	const t = {};
	for (const [n, r] of Object.entries(e).toSorted(([e], [t]) => e.localeCompare(t))) {
		if (isBlockedObjectKey$1(n)) continue;
		if (typeof r === "string" && r.trim()) t[n] = r.trim();
	}
	return t;
}
function hasPackagePluginMetadata(e) {
	const t = e.openclaw;
	if (!isRecord(t)) return false;
	const n = t.extensions;
	return Array.isArray(n) && n.some((e) => typeof e === "string");
}
function readManifestPluginId(e) {
	const t = tryReadJsonObjectSync(path.join(e, "openclaw.plugin.json"));
	return (typeof t?.id === "string" ? t.id.trim() : "") || void 0;
}
function resolveRecoveredManagedNpmRoot(e = {}) {
	return path.resolve(e.stateDir ? path.join(e.stateDir, "npm") : resolveDefaultPluginNpmDir(e.env));
}
function resolveRecoveredManagedNpmPluginId(e) {
	const { packageManifest: t } = e;
	if (!t || !hasPackagePluginMetadata(t)) return;
	const n = typeof t.name === "string" && t.name.trim() ? t.name.trim() : e.packageName;
	const r = readManifestPluginId(e.packageDir) ?? n;
	return validatePluginId(r) ? void 0 : r;
}
function readManagedNpmInstallTimestampMs(e) {
	const t = e.sharedLegacyRoot ? [e.packageDir] : [path.join(e.projectRoot, "package.json"), e.projectRoot];
	for (const e of t) try {
		return fsSync.statSync(e).mtimeMs;
	} catch {}
	return 0;
}
function buildRecoveredManagedNpmInstallCandidatesForRoot(e) {
	const t = readStringRecord(e.rootManifest?.dependencies);
	const n = [];
	for (const [r, i] of Object.entries(t)) {
		const t = path.join(e.projectRoot, "node_modules", ...r.split("/"));
		if (!safeStatSync(t)?.isDirectory()) continue;
		if (hasRetainedManagedNpmInstallMarker(t)) continue;
		const a = tryReadJsonObjectSync(path.join(t, "package.json"));
		const o = resolveRecoveredManagedNpmPluginId({
			packageName: r,
			packageDir: t,
			packageManifest: a
		});
		if (!o) continue;
		const s = typeof a?.version === "string" && a.version.trim() ? a.version.trim() : void 0;
		n.push({
			pluginId: o,
			installTimestampMs: readManagedNpmInstallTimestampMs({
				packageDir: t,
				projectRoot: e.projectRoot,
				sharedLegacyRoot: e.sharedLegacyRoot
			}),
			installRecord: {
				source: "npm",
				spec: `${r}@${i}`,
				installPath: t,
				...s ? {
					version: s,
					resolvedName: r,
					resolvedVersion: s
				} : {},
				...s ? { resolvedSpec: `${r}@${s}` } : {}
			}
		});
	}
	return n;
}
/** Lists recoverable managed npm installs without assigning active precedence. */
function listRecoveredManagedNpmInstallCandidates(e = {}) {
	const t = resolveRecoveredManagedNpmRoot(e);
	return [...buildRecoveredManagedNpmInstallCandidatesForRoot({
		projectRoot: t,
		rootManifest: tryReadJsonObjectSync(path.join(t, "package.json")),
		sharedLegacyRoot: true
	}), ...listManagedPluginNpmProjectsSync(t).flatMap(({ projectRoot: e, manifest: t }) => buildRecoveredManagedNpmInstallCandidatesForRoot({
		projectRoot: e,
		rootManifest: t,
		sharedLegacyRoot: false
	}))];
}
function recordsShareInstallPath(e, t) {
	if (!e?.installPath || !t.installPath) return false;
	return normalizeInstallPathForComparison(e.installPath) === normalizeInstallPathForComparison(t.installPath);
}
function normalizeInstallPathForComparison(e) {
	const t = path.resolve(e);
	return process.platform === "win32" ? normalizeWindowsPathForComparison$1(t) : t;
}
function pickMostRecentRecoveredManagedNpmCandidate(e) {
	return e.toSorted((e, t) => {
		const n = t.installTimestampMs - e.installTimestampMs;
		if (n !== 0) return n;
		return (t.installRecord.installPath ?? "").localeCompare(e.installRecord.installPath ?? "");
	})[0];
}
function emitManagedNpmRecoveryFallbackWarning(e) {
	process.emitWarning(`Managed npm recovery found ${e.candidates.length} installs for plugin "${e.pluginId}" without an authoritative active path; selected the most recently installed candidate. Run \`openclaw doctor --fix\` to persist and retire stale generations.`, {
		code: "OPENCLAW_PLUGIN_INSTALL_RECOVERY_FALLBACK",
		type: "OpenClawPluginRecoveryWarning",
		detail: JSON.stringify({
			pluginId: e.pluginId,
			selectedInstallPath: e.selected.installRecord.installPath,
			candidates: e.candidates.map((e) => ({
				installPath: e.installRecord.installPath,
				installTimestampMs: e.installTimestampMs
			}))
		})
	});
}
function buildRecoveredManagedNpmInstallRecords(e, t = {}) {
	const n = resolveRecoveredManagedNpmRoot(t);
	const r = createPluginInstallRecordMap();
	const i = groupPluginRecords(listRecoveredManagedNpmInstallCandidates(t), (e) => e.pluginId);
	for (const [t, a] of i) {
		const i = getPluginInstallRecordMapEntry(e ?? void 0, t);
		const o = a.find((e) => recordsShareInstallPath(i, e.installRecord));
		const s = o ?? pickMostRecentRecoveredManagedNpmCandidate(a);
		setPluginInstallRecordMapEntry(r, t, s.installRecord);
		const c = isUnavailableManagedNpmInstallRecord({
			npmRoot: n,
			persisted: i,
			recovered: s.installRecord
		});
		if (!o && a.length > 1 && (!i || c)) emitManagedNpmRecoveryFallbackWarning({
			pluginId: t,
			selected: s,
			candidates: a
		});
	}
	return r;
}
function readInstallRecordVersion(e) {
	return e?.resolvedVersion ?? e?.version;
}
function isUnavailableManagedNpmInstallRecord(e) {
	const t = e.persisted?.installPath;
	if (e.persisted?.source !== "npm" || !t) return false;
	try {
		if (fsSync.statSync(t).isDirectory()) return false;
	} catch (e) {
		if (!isNotFoundPathError(e)) return false;
	}
	const n = resolveRetainedManagedNpmInstallPackageInfo(t);
	if (!n || n.packageName !== e.recovered.resolvedName) return false;
	const r = normalizeInstallPathForComparison(e.npmRoot);
	return normalizeInstallPathForComparison(n.projectRoot) === r || normalizeInstallPathForComparison(path.dirname(n.projectRoot)) === normalizeInstallPathForComparison(resolvePluginNpmProjectsDir(e.npmRoot));
}
function mergeRecoveredManagedNpmMetadata(e, t, n = {}) {
	const r = {
		...e,
		...t
	};
	if (n.preservePersistedSpec) {
		const n = e.spec ? parseRegistryNpmSpec(e.spec) : null;
		const i = n !== null && isPrereleaseResolutionAllowed({
			spec: n,
			resolvedVersion: t.resolvedVersion
		}) && (n.selectorKind !== "exact-version" || n.selector !== void 0 && t.resolvedVersion !== void 0 && compareValidSemver(n.selector, t.resolvedVersion) === 0);
		if (n?.name === t.resolvedName && i) r.spec = e.spec;
	}
	delete r.integrity;
	delete r.shasum;
	delete r.resolvedAt;
	delete r.installedAt;
	return r;
}
function mergeRecoveredManagedNpmRecord(e) {
	if (e.persisted && isUnavailableManagedNpmInstallRecord(e)) return mergeRecoveredManagedNpmMetadata(e.persisted, e.recovered, { preservePersistedSpec: true });
	const t = readInstallRecordVersion(e.persisted);
	const n = readInstallRecordVersion(e.recovered);
	if (e.persisted?.source === "npm" && recordsShareInstallPath(e.persisted, e.recovered) && n && t !== n) return mergeRecoveredManagedNpmMetadata(e.persisted, e.recovered);
	return e.persisted ?? e.recovered;
}
/** Merges persisted records with managed npm installs recovered from the current root. */
function mergeRecoveredManagedNpmInstallRecords(e, t) {
	const n = resolveRecoveredManagedNpmRoot(t);
	const r = buildRecoveredManagedNpmInstallRecords(e, t);
	const i = copyPluginInstallRecordMap(e ?? void 0);
	for (const [e, t] of Object.entries(r)) setPluginInstallRecordMapEntry(i, e, mergeRecoveredManagedNpmRecord({
		npmRoot: n,
		persisted: getPluginInstallRecordMapEntry(i, e),
		recovered: t
	}));
	return i;
}
function requireLoadablePluginInstallRecordState(e) {
	if (e.status === "invalid") throw new Error("Persisted plugin install records are invalid. Run openclaw doctor to inspect and repair plugin installation state.");
	return e.status === "valid" ? e.records : null;
}
function resolveInstallRecordsCacheKey(e) {
	return [path.resolve(resolveInstalledPluginIndexStorePath(e)), resolveRecoveredManagedNpmRoot(e)].join("\0");
}
/** Synchronously loads installed plugin records, recovering managed npm installs and caching them. */
function loadInstalledPluginIndexInstallRecordsSync(e = {}) {
	const t = resolveInstallRecordsCacheKey(e);
	const n = getPluginCache().installRecords;
	const r = n.get(t);
	if (r) return copyPluginInstallRecordMap(r);
	const i = mergeRecoveredManagedNpmInstallRecords(requireLoadablePluginInstallRecordState(inspectPersistedInstalledPluginIndexInstallRecordsSync(e)), e);
	n.set(t, i);
	return copyPluginInstallRecordMap(i);
}
//#endregion
//#region src/plugins/official-external-install-records.ts
function resolveNpmSpecPackageName(e) {
	return e ? parseRegistryNpmSpec(e)?.name : void 0;
}
function resolveClawHubSpecPackageName(e) {
	return e ? parseClawHubPluginSpec(e)?.name : void 0;
}
function resolveExactNpmPackageName(e) {
	const t = resolveNpmSpecPackageName(e);
	return t && e.trim() === t ? t : void 0;
}
function resolveRecordedPackageNames(e) {
	const t = e.flatMap(([e, t]) => e === void 0 ? [] : [t(e)]);
	return t.every((e) => Boolean(e)) ? t : void 0;
}
function resolveUnanimousRecordedNpmPackageName(e) {
	if (e.source !== "npm") return;
	const t = resolveRecordedPackageNames([
		[e.spec, resolveNpmSpecPackageName],
		[e.resolvedName, resolveExactNpmPackageName],
		[e.resolvedSpec, resolveNpmSpecPackageName]
	]);
	return t && new Set(t).size === 1 ? t[0] : void 0;
}
function hasTrustedOfficialNpmProvenance(e) {
	return e.source === "npm" && e.artifactKind === void 0 && e.sourcePath === void 0;
}
function resolveRecordedClawHubPackageNames(e) {
	return resolveRecordedPackageNames([
		[e.clawhubPackage, resolveExactNpmPackageName],
		[e.spec, resolveClawHubSpecPackageName],
		[e.resolvedSpec, (e) => resolveClawHubSpecPackageName(e) ?? resolveNpmSpecPackageName(e)],
		[e.resolvedName, resolveExactNpmPackageName]
	]);
}
function isOfficialClawHubInstallRecord(e) {
	if (e.source !== "clawhub" || e.clawhubChannel !== "official") return false;
	return (e.clawhubUrl ?? "").trim().replace(/\/+$/, "") === "https://clawhub.ai";
}
/** Resolves one package identity from a current trusted official ClawHub install record. */
function resolveTrustedOfficialClawHubPackageName(e) {
	if (!isOfficialClawHubInstallRecord(e)) return;
	const t = resolveRecordedClawHubPackageNames(e);
	return t && new Set(t).size === 1 ? t[0] : void 0;
}
/** Valid registry provenance does not grant official plugin authority. */
function isThirdPartyNpmInstallRecord(e, t, n) {
	return Boolean(t && !getOfficialExternalPluginCatalogEntry(e) && !getOfficialExternalPluginCatalogEntryForPackage(t) && hasTrustedOfficialNpmProvenance(n) && resolveUnanimousRecordedNpmPackageName(n) === t && (n.clawhubPackage === void 0 || resolveExactNpmPackageName(n.clawhubPackage) === t));
}
/** Binds official trust to the actual package and consistent recorded source identity. */
function isTrustedOfficialPluginInstallRecord(e) {
	const t = e.packageName?.trim();
	const n = t ? getOfficialExternalPluginCatalogEntryForPackage(t) : void 0;
	if (!n || resolveOfficialExternalPluginId(n) !== e.pluginId && !resolveOfficialExternalPluginLegacyIds(n).includes(e.pluginId)) return false;
	const r = resolveOfficialExternalPluginInstall(n);
	const i = e.record;
	if (i.source === "npm") return hasTrustedOfficialNpmProvenance(i) && resolveNpmSpecPackageName(r?.npmSpec) === t && resolveUnanimousRecordedNpmPackageName(i) === t && (i.clawhubPackage === void 0 || resolveExactNpmPackageName(i.clawhubPackage) === t);
	return Boolean(r?.clawhubSpec || r?.npmSpec) && (i.clawhubPackage !== void 0 || i.spec !== void 0) && resolveTrustedOfficialClawHubPackageName(i) === t;
}
//#endregion
//#region src/plugins/installed-plugin-record-match.ts
function resolveCandidateInstallOwner(e) {
	if (isPluginCandidateInstallOwnerAmbiguous(e.candidate)) return;
	const t = resolvePluginCandidateInstallOwner(e.candidate);
	return t && Object.hasOwn(e.installRecords, t) ? t : void 0;
}
function matchesInstalledPluginRecord(e) {
	if (e.candidate.origin !== "global" && e.candidate.origin !== "config") return false;
	const t = resolveCandidateInstallOwner(e);
	const n = t ? e.installRecords[t] : void 0;
	if (!n) return false;
	const r = [
		e.candidate.rootDir,
		e.candidate.packageDir,
		e.candidate.source,
		e.candidate.setupSource
	].filter((e) => typeof e === "string" && e.trim().length > 0).map((t) => {
		const n = resolveUserPath(t, e.env);
		return pluginCacheRealpathSync(n) ?? n;
	});
	const i = (e.installPathOnly ? [n.installPath] : [n.installPath, n.sourcePath]).filter((e) => typeof e === "string" && e.trim().length > 0).map((t) => {
		const n = resolveUserPath(t, e.env);
		return pluginCacheRealpathSync(n) ?? n;
	});
	if (r.length === 0 || i.length === 0) return false;
	return i.some((e) => r.some((t) => t === e || isPathInside$1(e, t) || isPathInside$1(t, e)));
}
function resolvePluginTrust(e) {
	const t = resolveCandidateInstallOwner(e);
	const n = t ? e.installRecords[t] : void 0;
	const r = e.candidate.origin;
	let i;
	if (r === "bundled") i = "bundled";
	else if (isPluginCandidateInstallOwnerAmbiguous(e.candidate)) i = "owner-ambiguous";
	else if (r === "workspace" || n?.source === "path" || n?.source === "npm" && (n.artifactKind !== void 0 || n.sourcePath !== void 0)) i = "origin-path";
	else if (!n || !t) i = "record-missing";
	else if (!matchesInstalledPluginRecord({
		...e,
		installPathOnly: true
	})) i = "install-path-mismatch";
	else if (isTrustedOfficialPluginInstallRecord({
		pluginId: t,
		packageName: e.candidate.packageName,
		record: n
	})) i = "trusted-official";
	else if (n.source === "npm" && n.spec === void 0 && n.resolvedName === void 0 && n.resolvedSpec === void 0 || n.source === "clawhub" && n.clawhubUrl === void 0 && n.clawhubChannel === void 0) i = "provenance-missing";
	else if (isThirdPartyNpmInstallRecord(t, e.candidate.packageName, n)) i = "third-party-npm";
	else i = "provenance-invalid";
	return {
		reason: i,
		registryPath: e.registryPath,
		origin: r,
		installSource: n?.source,
		installSpec: n?.spec === void 0 ? void 0 : redactSensitiveText(n.spec, { mode: "tools" })
	};
}
//#endregion
//#region packages/media-core/src/inline-image-data-url.ts
const HEIC_BRANDS = /* @__PURE__ */ new Set([
	"heic",
	"heix",
	"hevc",
	"hevx",
	"heis",
	"heim",
	"hevm",
	"hevs"
]);
const HEIF_BRANDS = /* @__PURE__ */ new Set(["mif1", "msf1"]);
/** Sniffs supported inline image formats from decoded bytes. */
function sniffInlineImageMime(e) {
	if (e.length >= 8 && e.readBigUInt64BE(0) === 9894494448401390090n) return "image/png";
	if (e.length >= 3 && e.readUIntBE(0, 3) === 16767231) return "image/jpeg";
	if (e.length >= 12 && e.toString("ascii", 0, 4) === "RIFF" && e.toString("ascii", 8, 12) === "WEBP") return "image/webp";
	if (e.length >= 6 && /^GIF8[79]a$/.test(e.toString("ascii", 0, 6))) return "image/gif";
	if (e.length >= 2 && e.readUInt16BE(0) === 16973) return "image/bmp";
	if (e.length < 12 || e.subarray(4, 8).toString("ascii") !== "ftyp") return;
	const t = [e.subarray(8, 12).toString("ascii")];
	for (let n = 16; n + 4 <= e.length; n += 4) t.push(e.subarray(n, n + 4).toString("ascii"));
	if (t.some((e) => HEIC_BRANDS.has(e))) return "image/heic";
	if (t.some((e) => HEIF_BRANDS.has(e))) return "image/heif";
}
//#endregion
//#region packages/gateway-protocol/src/svg-image.ts
const SVG_PROLOGUE_WHITESPACE_RE = /\s*/y;
function skipSvgPrologueWhitespace(e, t) {
	SVG_PROLOGUE_WHITESPACE_RE.lastIndex = t;
	SVG_PROLOGUE_WHITESPACE_RE.exec(e);
	return SVG_PROLOGUE_WHITESPACE_RE.lastIndex;
}
function startsWithToken(e, t, n) {
	return e.slice(t, t + n.length).toLowerCase() === n;
}
/**
* Recognizes an SVG root element after an optional XML declaration and comments.
*
* An index scan rather than a regex on purpose: the equivalent
* `(?:<!--[\s\S]*?-->\s*)*<svg` backtracks exponentially on comment-like bytes that
* never reach a root element, and these bytes arrive from remote icon and
* link-favicon responses on the Gateway's single event loop, so one crafted
* response would stall every session. A comment ends at its first `-->`, so text
* between a closed comment and the root element is rejected, not absorbed.
*/
function startsWithSvgRootElement(e) {
	let t = skipSvgPrologueWhitespace(e, 0);
	if (startsWithToken(e, t, "<?xml")) {
		const n = e.indexOf(">", t);
		if (n < 0) return false;
		t = skipSvgPrologueWhitespace(e, n + 1);
	}
	while (startsWithToken(e, t, "<!--")) {
		const n = e.indexOf("-->", t + 4);
		if (n < 0) return false;
		t = skipSvgPrologueWhitespace(e, n + 3);
	}
	if (!startsWithToken(e, t, "<svg")) return false;
	const n = e[t + 4];
	return n === ">" || n === "/" && e[t + 5] === ">" || n !== void 0 && /\s/u.test(n);
}
/**
* SVG images stay self-contained: no script, document expansion, embedded
* documents, or outbound fetches can reach the browser through an image route.
*/
function isSelfContainedSvg(e) {
	return !e.includes("\0") && !/<!doctype|<!entity/iu.test(e) && !/<\s*(?:script|foreignObject|image|use|iframe)\b/iu.test(e) && !/\b(?:href|xlink:href|src)\s*=/iu.test(e) && startsWithSvgRootElement(e);
}
//#endregion
//#region src/plugins/portable-icon-paths.ts
/** Package-local artwork contracts shared by discovery and package builders. */
const PORTABLE_PLUGIN_ICON_PATH = "assets/icon.png";
const PLUGIN_ACTIVITY_ICON_PATH = "assets/activity.svg";
const PLUGIN_TOOL_ACTIVITY_ICON_DIR = "assets/activity";
const PLUGIN_ACTIVITY_ICON_MAX_BYTES = 32768;
/** Theme backgrounds stay within the authenticated image route's 512 KiB response cap. */
const PLUGIN_THEME_BACKGROUND_MAX_BYTES = 524288;
function isPluginActivityToolName(e) {
	return /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/u.test(e);
}
//#endregion
//#region src/plugins/manifest-theme-definitions.ts
const BACKGROUND_MIME_TYPES = /* @__PURE__ */ new Set([
	"image/png",
	"image/jpeg",
	"image/webp"
]);
/** Capture palettes and artwork so a published generation never reads changed files. */
function loadManifestThemeDefinitions(e) {
	if (!e.themes?.length) return;
	return e.themes.flatMap((t) => {
		try {
			if (e.pluginId === "user" || !isThemeId(`${e.pluginId}/${t.id}`)) throw new Error("qualified theme ID must be portable, outside user/, and at most 256 characters");
			const n = readPluginCacheFile({
				rootDir: e.rootDir,
				relativePath: t.source,
				rejectHardlinks: e.rejectHardlinks,
				maxBytes: MAX_THEME_DEFINITION_BYTES * 4
			});
			if (!n.ok) throw new Error("source must be a readable JSON file inside the plugin root");
			const r = normalizeThemeDefinition(JSON.parse(n.contents.toString("utf8")), {
				iconIds: Object.keys(t.icons ?? {}),
				hatIds: Object.keys(t.hats ?? {}),
				critterIds: Object.keys(t.critters ?? {})
			});
			if (r.name !== t.name || r.description !== t.description) throw new Error("name and description must match the manifest declaration");
			const readSvg = (t) => {
				const n = readPluginCacheFile({
					rootDir: e.rootDir,
					relativePath: t,
					rejectHardlinks: e.rejectHardlinks,
					maxBytes: PLUGIN_ACTIVITY_ICON_MAX_BYTES
				});
				if (!n.ok) throw new Error(`artwork ${t} must be a readable SVG inside the plugin root, at most ${PLUGIN_ACTIVITY_ICON_MAX_BYTES} bytes`);
				const r = n.contents.toString("utf8");
				if (!isSelfContainedSvg(r)) throw new Error(`artwork ${t} must be a self-contained SVG`);
				return r;
			};
			const readBackground = (t) => {
				const n = readPluginCacheFile({
					rootDir: e.rootDir,
					relativePath: t,
					rejectHardlinks: e.rejectHardlinks,
					maxBytes: PLUGIN_THEME_BACKGROUND_MAX_BYTES
				});
				if (!n.ok || !BACKGROUND_MIME_TYPES.has(sniffInlineImageMime(n.contents) ?? "")) throw new Error(`background ${t} must be a readable PNG, JPEG, or WebP inside the plugin root, at most ${PLUGIN_THEME_BACKGROUND_MAX_BYTES} bytes`);
				return n.contents.toString("base64");
			};
			const i = {
				...t.icons ? { icons: Object.fromEntries(Object.entries(t.icons).map(([e, t]) => [e, { svg: readSvg(t) }])) } : {},
				...t.hats ? { hats: Object.fromEntries(Object.entries(t.hats).map(([e, t]) => [e, { svg: readSvg(t) }])) } : {},
				...t.critters ? { critters: Object.fromEntries(Object.entries(t.critters).map(([e, { source: t, ...n }]) => [e, {
					svg: readSvg(t),
					...n
				}])) } : {},
				...t.backgrounds ? { backgrounds: Object.fromEntries(Object.entries(t.backgrounds).map(([e, t]) => [e, { base64: readBackground(t) }])) } : {}
			};
			return [{
				id: t.id,
				definition: r,
				...t.icons || t.hats || t.critters || t.backgrounds ? { artwork: i } : {}
			}];
		} catch (n) {
			e.diagnostics.push({
				level: "warn",
				pluginId: e.pluginId,
				message: `theme ${t.id} is unavailable: ${n instanceof Error ? n.message : "invalid definition"}`
			});
			return [];
		}
	});
}
//#endregion
//#region src/plugins/manifest-record.ts
function resolvePluginSourcePath(e) {
	if (pluginCacheExistsSync(e)) return e;
	if (e.endsWith(".ts")) {
		const t = e.slice(0, -3) + ".js";
		if (pluginCacheExistsSync(t)) return t;
	}
	return e;
}
function isPluginRootPath(e) {
	const t = path.resolve(e.targetPath);
	const n = path.resolve(e.rootPath);
	if (!isPathInside$1(n, t)) return false;
	const r = pluginCacheRealpathSync(t);
	if (!r) return e.targetMustExist !== true;
	if (!isPathInside$1(e.rootRealPath, r)) return false;
	if (e.rejectHardlinks === true) {
		const e = pluginCacheStatSync(t);
		if (!e || e.nlink > 1) return false;
	}
	return true;
}
function resolvePortablePluginIcons(e) {
	let t;
	const resolveIcon = (n) => {
		const r = path.resolve(e.rootDir, n);
		const i = pluginCacheLstatSync(r);
		if (!i?.isFile() || e.rejectHardlinks && i.nlink > 1) return;
		if (!t) {
			const n = path.resolve(e.rootDir);
			t = {
				path: n,
				realPath: pluginCacheRealpathSync(n) ?? n
			};
		}
		return isPluginRootPath({
			rootPath: t.path,
			targetPath: r,
			rootRealPath: t.realPath,
			rejectHardlinks: e.rejectHardlinks,
			targetMustExist: true
		}) ? r : void 0;
	};
	const n = resolveIcon(PORTABLE_PLUGIN_ICON_PATH);
	const r = resolveIcon(PLUGIN_ACTIVITY_ICON_PATH);
	const i = path.resolve(e.rootDir, PLUGIN_TOOL_ACTIVITY_ICON_DIR);
	if (!isPluginRootPath({
		rootPath: e.rootDir,
		rootRealPath: e.rootDir === t?.path ? t.realPath : pluginCacheRealpathSync(e.rootDir) ?? e.rootDir,
		targetPath: i,
		targetMustExist: true
	})) return {
		iconPath: n,
		activityIconPath: r
	};
	let a;
	try {
		a = readPluginCacheDirectory(i);
	} catch {
		return {
			iconPath: n,
			activityIconPath: r
		};
	}
	if (a.length > 128) return {
		iconPath: n,
		activityIconPath: r
	};
	const o = [];
	for (const e of a.map((e) => e.name).toSorted()) {
		const t = e.endsWith(".svg") ? e.slice(0, -4) : "";
		if (!isPluginActivityToolName(t)) continue;
		const n = resolveIcon(`${PLUGIN_TOOL_ACTIVITY_ICON_DIR}/${e}`);
		if (n) o.push([t, n]);
	}
	return {
		iconPath: n,
		activityIconPath: r,
		...o.length ? { toolActivityIconPaths: Object.fromEntries(o) } : {}
	};
}
function mergePackageChannelMetaIntoChannelConfigs(e) {
	const t = e.packageChannel?.id?.trim();
	if (!t || isBlockedObjectKey$1(t) || !e.channelConfigs || !Object.hasOwn(e.channelConfigs, t)) return e.channelConfigs;
	const n = e.channelConfigs[t];
	if (!n) return e.channelConfigs;
	const r = n.label ?? normalizeOptionalString(e.packageChannel?.label) ?? "";
	const i = n.description ?? normalizeOptionalString(e.packageChannel?.blurb) ?? "";
	const a = n.preferOver ?? normalizeOptionalTrimmedStringList(e.packageChannel?.preferOver);
	const o = n.commands ?? normalizeManifestChannelCommandDefaults(e.packageChannel?.commands);
	const s = Object.create(null);
	for (const [t, n] of Object.entries(e.channelConfigs)) if (!isBlockedObjectKey$1(t)) s[t] = n;
	s[t] = {
		...n,
		...r ? { label: r } : {},
		...i ? { description: i } : {},
		...a?.length ? { preferOver: a } : {},
		...o ? { commands: o } : {}
	};
	return s;
}
function mergeManifestContracts(e, t) {
	if (!t) return e;
	const n = {};
	for (const r of PLUGIN_MANIFEST_CONTRACT_KEYS) {
		const i = normalizeUniqueTrimmedStringList([...e?.[r] ?? [], ...t[r] ?? []]);
		if (i.length > 0) n[r] = i;
	}
	return Object.keys(n).length > 0 ? n : void 0;
}
function mergeCatalogChannelConfigs(e) {
	if (!e.catalogChannelConfigs) return e.manifestChannelConfigs;
	const t = Object.create(null);
	for (const [n, r] of Object.entries(e.catalogChannelConfigs)) if (!isBlockedObjectKey$1(n)) t[n] = r;
	for (const [n, r] of Object.entries(e.manifestChannelConfigs ?? {})) if (!isBlockedObjectKey$1(n)) {
		const e = t[n];
		if (!e) {
			t[n] = r;
			continue;
		}
		const i = {
			...e,
			...r,
			schema: r.schema ?? e.schema
		};
		if (e.uiHints || r.uiHints) i.uiHints = {
			...e.uiHints,
			...r.uiHints
		};
		for (const t of [
			"runtime",
			"label",
			"description",
			"preferOver",
			"commands"
		]) {
			const n = r[t] ?? e[t];
			if (n) Object.assign(i, { [t]: n });
		}
		t[n] = i;
	}
	return Object.keys(t).length > 0 ? t : void 0;
}
function buildPluginManifestRecord(e) {
	const t = e.candidate.effectivePluginId ?? e.manifest.id;
	const resolveCatalogEntry = (n) => {
		const r = e.manifest[n];
		if (r === void 0) return;
		const i = e.candidate.rootDir;
		const a = e.manifestPath;
		const o = e.rejectHardlinks;
		const s = e.diagnostics;
		const pushDiagnostic = () => {
			s.push({
				level: "warn",
				pluginId: sanitizeForLog(t),
				source: sanitizeForLog(a),
				message: `plugin manifest ${n} must resolve inside the plugin root; ignoring entry`
			});
		};
		if (!r || path.isAbsolute(r)) {
			pushDiagnostic();
			return;
		}
		const c = path.resolve(i);
		const l = pluginCacheRealpathSync(c) ?? c;
		const u = path.resolve(c, r);
		if (!isPluginRootPath({
			rootPath: c,
			targetPath: u,
			rootRealPath: l,
			rejectHardlinks: o,
			targetMustExist: pluginCacheExistsSync(u)
		})) {
			pushDiagnostic();
			return;
		}
		const d = resolvePluginSourcePath(u);
		if (!isPluginRootPath({
			rootPath: c,
			targetPath: d,
			rootRealPath: l,
			rejectHardlinks: o,
			targetMustExist: pluginCacheExistsSync(d)
		})) {
			pushDiagnostic();
			return;
		}
		return d;
	};
	const n = e.candidate.origin === "bundled" && e.bundledChannelConfigCollector ? e.bundledChannelConfigCollector({
		pluginDir: e.candidate.packageDir ?? e.candidate.rootDir,
		manifest: e.manifest,
		packageManifest: e.candidate.packageManifest
	}) : e.manifest.channelConfigs;
	const r = e.candidate.origin !== "bundled" ? getOfficialExternalPluginCatalogManifest(getOfficialExternalPluginCatalogEntryForPackage(e.candidate.packageName) ?? {}) : void 0;
	const i = mergePackageChannelMetaIntoChannelConfigs({
		channelConfigs: mergeCatalogChannelConfigs({
			manifestChannelConfigs: n,
			catalogChannelConfigs: r?.channelConfigs
		}),
		packageChannel: e.candidate.packageManifest?.channel
	});
	const a = normalizeManifestChannelCommandDefaults(e.candidate.packageManifest?.channel?.commands);
	return {
		id: t,
		categories: e.manifest.categories,
		backupResources: e.manifest.backupResources,
		doctorContract: e.manifest.doctorContract,
		doctorHealthChecks: e.manifest.doctorHealthChecks,
		sessionRouteStateOwners: e.manifest.sessionRouteStateOwners,
		name: normalizeOptionalString(e.manifest.name) ?? e.candidate.packageName,
		description: normalizeOptionalString(e.manifest.description) ?? e.candidate.packageDescription,
		catalog: normalizeManifestCatalog({
			featured: e.manifest.catalog?.featured ?? r?.catalog?.featured,
			order: e.manifest.catalog?.order ?? r?.catalog?.order
		}),
		...resolvePortablePluginIcons({
			rootDir: e.candidate.rootDir,
			rejectHardlinks: e.rejectHardlinks
		}),
		version: normalizeOptionalString(e.manifest.version) ?? e.candidate.packageVersion,
		packageName: e.candidate.packageName,
		packageVersion: e.candidate.packageVersion,
		packageDescription: e.candidate.packageDescription,
		enabledByDefault: e.manifest.enabledByDefault === true ? true : void 0,
		enabledByDefaultOnPlatforms: e.manifest.enabledByDefaultOnPlatforms,
		autoEnableWhenConfiguredProviders: e.manifest.autoEnableWhenConfiguredProviders,
		legacyPluginIds: e.manifest.legacyPluginIds,
		format: e.candidate.format ?? "openclaw",
		bundleFormat: e.candidate.bundleFormat,
		kind: e.manifest.kind,
		contextEngineIds: e.manifest.contextEngineIds,
		reload: e.manifest.reload,
		channels: e.manifest.channels ?? [],
		channelAccountKeyPolicies: e.manifest.channelAccountKeyPolicies,
		providers: e.manifest.providers ?? [],
		managesOwnAvailability: e.manifest.managesOwnAvailability,
		providerDiscoverySource: resolveCatalogEntry("providerCatalogEntry"),
		capabilityCatalogSource: e.manifest.capabilityCatalogEntry === void 0 ? void 0 : resolveCatalogEntry("capabilityCatalogEntry") ?? null,
		modelSupport: e.manifest.modelSupport,
		modelCatalog: e.manifest.modelCatalog,
		modelPricing: e.manifest.modelPricing,
		modelIdNormalization: e.manifest.modelIdNormalization,
		providerEndpoints: e.manifest.providerEndpoints,
		providerRequest: e.manifest.providerRequest,
		secretProviderIntegrations: e.manifest.secretProviderIntegrations,
		cliBackends: e.manifest.cliBackends ?? [],
		syntheticAuthRefs: e.manifest.syntheticAuthRefs ?? [],
		nonSecretAuthMarkers: e.manifest.nonSecretAuthMarkers ?? [],
		commandAliases: e.manifest.commandAliases,
		cliCommands: e.manifest.cliCommands,
		providerUsageAuthEnvVars: e.manifest.providerUsageAuthEnvVars,
		providerAuthAliases: e.manifest.providerAuthAliases,
		providerAuthChoices: e.manifest.providerAuthChoices,
		activation: e.manifest.activation,
		setup: e.manifest.setup,
		packageManifest: e.candidate.packageManifest,
		packageDependencies: e.candidate.packageDependencies,
		packageOptionalDependencies: e.candidate.packageOptionalDependencies,
		packageChannel: e.candidate.packageManifest?.channel,
		packageInstall: e.candidate.packageManifest?.install,
		trustedOfficialInstall: e.trust.reason === "trusted-official" ? true : void 0,
		trust: e.trust,
		qaRunners: e.manifest.qaRunners,
		dashboard: e.manifest.dashboard,
		controlUi: e.manifest.controlUi,
		uiCapabilities: e.manifest.uiCapabilities,
		themes: e.manifest.themes,
		themeDefinitions: loadManifestThemeDefinitions({
			pluginId: t,
			rootDir: e.candidate.rootDir,
			themes: e.manifest.themes,
			rejectHardlinks: e.rejectHardlinks,
			diagnostics: e.diagnostics
		}),
		mcpServers: e.manifest.mcpServers,
		skills: e.manifest.skills ?? [],
		settingsFiles: [],
		hooks: [],
		origin: e.candidate.origin,
		workspaceDir: e.candidate.workspaceDir,
		rootDir: e.candidate.rootDir,
		source: e.candidate.source,
		setupSource: e.candidate.setupSource,
		manifestPath: e.manifestPath,
		schemaCacheKey: e.schemaCacheKey,
		configSchema: e.configSchema,
		configUiHints: e.manifest.uiHints,
		configGroups: e.manifest.configGroups,
		contracts: mergeManifestContracts(e.manifest.contracts, r?.contracts),
		transcriptSources: e.manifest.transcriptSources,
		decisionModels: e.manifest.decisionModels,
		mediaUnderstandingProviderMetadata: e.manifest.mediaUnderstandingProviderMetadata,
		imageGenerationProviderMetadata: e.manifest.imageGenerationProviderMetadata,
		videoGenerationProviderMetadata: e.manifest.videoGenerationProviderMetadata,
		musicGenerationProviderMetadata: e.manifest.musicGenerationProviderMetadata,
		toolMetadata: e.manifest.toolMetadata,
		configContracts: e.manifest.configContracts,
		channelConfigs: i,
		...e.candidate.packageManifest?.channel?.id ? { channelCatalogMeta: {
			id: e.candidate.packageManifest.channel.id,
			...typeof e.candidate.packageManifest.channel.label === "string" ? { label: e.candidate.packageManifest.channel.label } : {},
			...typeof e.candidate.packageManifest.channel.blurb === "string" ? { blurb: e.candidate.packageManifest.channel.blurb } : {},
			...e.candidate.packageManifest.channel.preferOver ? { preferOver: e.candidate.packageManifest.channel.preferOver } : {},
			...a ? { commands: a } : {}
		} } : {}
	};
}
function buildBundleManifestRecord(e) {
	return {
		id: e.manifest.id,
		name: normalizeOptionalString(e.manifest.name) ?? e.candidate.idHint,
		description: normalizeOptionalString(e.manifest.description),
		...resolvePortablePluginIcons({
			rootDir: e.candidate.rootDir,
			rejectHardlinks: e.rejectHardlinks
		}),
		version: normalizeOptionalString(e.manifest.version),
		packageName: e.candidate.packageName,
		packageVersion: e.candidate.packageVersion,
		packageDescription: e.candidate.packageDescription,
		packageManifest: e.candidate.packageManifest,
		packageDependencies: e.candidate.packageDependencies,
		packageOptionalDependencies: e.candidate.packageOptionalDependencies,
		packageChannel: e.candidate.packageManifest?.channel,
		packageInstall: e.candidate.packageManifest?.install,
		format: "bundle",
		bundleFormat: e.candidate.bundleFormat,
		bundleCapabilities: e.manifest.capabilities,
		...e.manifest.onboardingSkill ? { onboardingSkill: e.manifest.onboardingSkill } : {},
		activation: e.manifest.activation,
		channels: [],
		providers: [],
		cliBackends: [],
		syntheticAuthRefs: [],
		nonSecretAuthMarkers: [],
		skills: e.manifest.skills ?? [],
		settingsFiles: e.manifest.settingsFiles ?? [],
		hooks: e.manifest.hooks ?? [],
		origin: e.candidate.origin,
		workspaceDir: e.candidate.workspaceDir,
		rootDir: e.candidate.rootDir,
		source: e.candidate.source,
		manifestPath: e.manifestPath,
		schemaCacheKey: void 0,
		configSchema: void 0,
		configUiHints: void 0,
		configContracts: void 0,
		channelConfigs: void 0
	};
}
//#endregion
//#region src/plugins/min-host-version.ts
/** Validation message for plugin minHostVersion manifest fields. */
const MIN_HOST_VERSION_FORMAT = "openclaw.install.minHostVersion must use a semver floor in the form \">=x.y.z[-prerelease][+build]\"";
const SEMVER_LABEL_RE = String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?`;
const MIN_HOST_VERSION_RE = new RegExp(`^>=(${SEMVER_LABEL_RE})$`);
const LEGACY_MIN_HOST_VERSION_RE = new RegExp(`^(${SEMVER_LABEL_RE})$`);
/** Parses a plugin minHostVersion manifest field. */
function parseMinHostVersionRequirement(e, t = {}) {
	const n = normalizeOptionalString(e);
	if (!n) return null;
	const r = n.match(MIN_HOST_VERSION_RE) ?? (t.allowLegacyBareSemver ? n.match(LEGACY_MIN_HOST_VERSION_RE) : null);
	if (!r) return null;
	const i = r[1] ?? "";
	if (!valid(i)) return null;
	return {
		raw: n,
		minimumLabel: i
	};
}
/** Checks whether the current host satisfies a plugin minHostVersion requirement. */
function checkMinHostVersion(e) {
	if (e.minHostVersion === void 0) return {
		ok: true,
		requirement: null
	};
	const t = parseMinHostVersionRequirement(e.minHostVersion, { allowLegacyBareSemver: e.allowLegacyBareSemver });
	if (!t) return {
		ok: false,
		kind: "invalid",
		error: MIN_HOST_VERSION_FORMAT
	};
	const n = normalizeOptionalString(e.currentVersion) || "unknown";
	const r = compareOpenClawVersions(n, t.minimumLabel);
	if (r === null) return {
		ok: false,
		kind: "unknown_host_version",
		requirement: t
	};
	if (r < 0) return {
		ok: false,
		kind: "incompatible",
		requirement: t,
		currentVersion: n
	};
	return {
		ok: true,
		requirement: t
	};
}
//#endregion
//#region src/plugins/manifest-registry-build.ts
function rejectCaseFoldedIdCollisions(e, t) {
	const n = /* @__PURE__ */ new Set();
	for (const [r, i] of groupPluginRecords(e, (e) => normalizePluginPolicyId(e.id))) {
		const e = [...new Set(i.map((e) => e.id))].toSorted();
		if (e.length < 2) continue;
		const a = `plugin ids ${e.map((e) => JSON.stringify(e)).join(", ")} collide as normalized id ${JSON.stringify(r)}; refusing all colliding plugins`;
		for (const e of i) {
			n.add(e);
			t.push({
				level: "error",
				pluginId: e.id,
				source: e.source,
				message: a
			});
		}
	}
	return e.filter((e) => !n.has(e));
}
function pushNonBundledChannelConfigDescriptorDiagnostic(e) {
	if (e.record.origin === "bundled" || e.record.format === "bundle") return;
	const t = normalizePluginPolicyId(e.record.id);
	const n = e.normalized?.entries[t];
	if (e.normalized?.enabled === false || n?.enabled === false || e.normalized?.deny.includes(t) || e.normalized?.allow.length && !e.normalized.allow.includes(t)) return;
	const r = e.record.channels.map((e) => e.trim()).filter((e) => e.length > 0);
	if (r.length === 0) return;
	const i = e.record.channelConfigs ?? {};
	const a = r.filter((e) => !Object.hasOwn(i, e));
	if (a.length === 0) return;
	const o = a.map(sanitizeForLog);
	e.diagnostics.push({
		level: "warn",
		pluginId: sanitizeForLog(e.record.id),
		source: sanitizeForLog(e.record.manifestPath),
		message: `channel plugin manifest declares ${o.join(", ")} without channelConfigs metadata; add openclaw.plugin.json#channelConfigs so config schema and setup surfaces work before runtime loads. Channels without channelConfigs still appear in channel listings, but setup UI may be limited.`
	});
}
function dedupePluginDiagnostics(e, t) {
	return dedupeByKey(e, (e) => JSON.stringify([
		e.level,
		e.pluginId ?? "",
		e.message,
		e.level === "error" || t.has(e) ? e.source ?? "" : ""
	]));
}
function isStaleForeignBundledPin(e) {
	return isForeignBundledPluginRoot(e.candidate.rootDir, e.env) && !isBundledPluginInsideDevSourceRoot({
		rootDir: e.candidate.rootDir,
		env: e.env
	});
}
function resolveDuplicatePrecedenceRank(e) {
	if (e.candidate.origin === "config" || e.candidate.configSelected) return 0;
	if (e.candidate.origin === "bundled" && isBundledPluginInsideDevSourceRoot({
		rootDir: e.candidate.rootDir,
		env: e.env
	})) return 1;
	if (e.candidate.origin === "global" && !isStaleForeignBundledPin({
		candidate: e.candidate,
		env: e.env
	}) && matchesInstalledPluginRecord(e)) return 2;
	if (e.candidate.origin === "bundled") return 3;
	if (e.candidate.origin === "workspace") return 4;
	return 5;
}
function isSameGlobalPackageDuplicate(e, t) {
	if (e.origin !== "global" || t.origin !== "global") return false;
	const n = normalizeOptionalString(e.packageName);
	const r = normalizeOptionalString(t.packageName);
	if (!n || n !== r) return false;
	const i = normalizeOptionalString(e.packageVersion);
	const a = normalizeOptionalString(t.packageVersion);
	return Boolean(i && a && i === a);
}
function buildPluginManifestRegistry(e) {
	const t = e.config ?? {};
	const n = normalizePluginsConfigWithResolverCore(t.plugins);
	const r = e.env ?? process.env;
	const i = e.registryPath ?? resolveInstalledPluginIndexStorePath({ env: r });
	const { getInstallRecords: a } = e;
	const o = e.candidates ? {
		candidates: e.candidates,
		diagnostics: e.diagnostics ?? []
	} : e.discovery ?? discoverOpenClawPlugins({
		workspaceDir: e.workspaceDir,
		extraPaths: n.loadPaths,
		env: r,
		installRecords: a()
	});
	const s = new Set(o.diagnostics);
	const c = [...s];
	const l = o.candidates.toSorted((e, t) => Number(t.origin === "config" || t.configSelected === true) - Number(e.origin === "config" || e.configSelected === true));
	const u = /* @__PURE__ */ new Map();
	const d = /* @__PURE__ */ new Map();
	const f = /* @__PURE__ */ new Set();
	const p = resolveCompatibilityHostVersion(r);
	const m = new Set(n.loadPaths.map((e) => resolveUserPath(e, r)).filter((e) => pluginCacheStatSync(e)?.isFile() === true).map((e) => path.resolve(e)));
	for (const t of l) {
		const n = shouldRejectHardlinkedPluginFiles({
			origin: t.origin,
			rootDir: t.rootDir,
			env: r
		});
		const o = (t.format ?? "openclaw") === "bundle";
		const s = t.origin === "config" && m.has(path.resolve(t.source)) && !pluginCacheExistsSync(path.join(t.rootDir, "openclaw.plugin.json"));
		if (s && isCoreReservedPluginId(t.idHint)) {
			c.push({
				level: "error",
				pluginId: t.idHint,
				source: t.source,
				message: `plugin manifest id "${t.idHint}" is reserved by OpenClaw core`
			});
			continue;
		}
		const l = t.origin === "bundled" && t.bundledManifest && t.bundledManifestPath ? {
			ok: true,
			manifest: t.bundledManifest,
			manifestPath: t.bundledManifestPath
		} : o && t.bundleFormat ? loadBundleManifest({
			rootDir: t.rootDir,
			bundleFormat: t.bundleFormat,
			rejectHardlinks: n
		}) : s ? {
			ok: true,
			manifest: {
				id: t.idHint,
				configSchema: {
					type: "object",
					additionalProperties: false
				},
				activation: { onStartup: true }
			},
			manifestPath: t.source
		} : loadPluginManifest(t.rootDir, n);
		if (!l.ok) {
			c.push({
				level: "error",
				pluginId: t.diagnosticIdHint ?? t.idHint,
				message: l.error,
				source: l.manifestPath,
				..."diagnosticCode" in l && l.diagnosticCode ? { code: l.diagnosticCode } : {}
			});
			continue;
		}
		if ("warnings" in l && l.warnings) d.set(l.manifestPath, l.warnings);
		const h = l.manifest;
		const g = t.effectivePluginId ?? h.id;
		if (t.origin !== "bundled") {
			const e = path.join(t.packageDir ?? t.rootDir, "package.json");
			const n = t.origin === "global" && matchesInstalledPluginRecord({
				candidate: t,
				env: r,
				installRecords: a()
			});
			const i = checkMinHostVersion({
				currentVersion: p,
				minHostVersion: t.packageManifest?.install?.minHostVersion,
				allowLegacyBareSemver: n
			});
			if (!i.ok) {
				c.push({
					level: i.kind === "invalid" ? "error" : "warn",
					pluginId: g,
					source: e,
					message: i.kind === "invalid" ? `plugin manifest invalid | ${i.error}` : i.kind === "unknown_host_version" ? `plugin requires OpenClaw >=${i.requirement.minimumLabel}, but this host version could not be determined; skipping load` : `plugin requires OpenClaw >=${i.requirement.minimumLabel}, but this host is ${i.currentVersion}; skipping load`
				});
				continue;
			}
			const o = resolvePackagePluginApiRange(t.packageManifest);
			if (!o.ok) {
				c.push({
					level: "error",
					pluginId: g,
					source: e,
					message: `plugin manifest invalid | ${o.error}`
				});
				continue;
			}
			const s = o.range;
			if (s && !satisfiesPluginApiRange(p, s)) {
				c.push({
					level: "warn",
					configDisposition: "preserve",
					pluginId: g,
					source: e,
					message: `plugin requires plugin API ${s}, but this host is ${p}; skipping load (check "openclaw --version", OPENCLAW_COMPATIBILITY_HOST_VERSION, or run "openclaw doctor")`
				});
				continue;
			}
		}
		const _ = "configSchema" in h ? h.configSchema : void 0;
		const v = (() => {
			if (!_ || s) return;
			const e = readPluginCacheFile({
				rootDir: t.rootDir,
				relativePath: path.relative(t.rootDir, l.manifestPath),
				rejectHardlinks: n,
				maxBytes: 262144
			});
			return e.ok ? `${l.manifestPath}:${e.hash}` : l.manifestPath;
		})();
		const y = o ? buildBundleManifestRecord({
			manifest: h,
			candidate: t,
			manifestPath: l.manifestPath,
			rejectHardlinks: n
		}) : buildPluginManifestRecord({
			manifest: h,
			candidate: t,
			manifestPath: l.manifestPath,
			diagnostics: c,
			rejectHardlinks: n,
			schemaCacheKey: v,
			configSchema: _,
			trust: resolvePluginTrust({
				registryPath: i,
				candidate: t,
				env: r,
				installRecords: a()
			}),
			...e.bundledChannelConfigCollector ? { bundledChannelConfigCollector: e.bundledChannelConfigCollector } : {}
		});
		if (t.sourcePreferred || t.origin === "bundled" && t.configSelected) y.sourcePreferred = true;
		recordPluginManifestInstallOwner(y, resolvePluginCandidateInstallOwner(t), isPluginCandidateInstallOwnerAmbiguous(t));
		const b = u.get(g);
		if (b) {
			const e = b.candidate.rootDir === t.rootDir;
			if ((() => {
				if (e) return true;
				const n = pluginCacheRealpathSync(b.candidate.rootDir);
				const r = pluginCacheRealpathSync(t.rootDir);
				return Boolean(n && r && n === r);
			})()) {
				if (y.sourcePreferred || b.record.sourcePreferred) {
					y.sourcePreferred = true;
					b.record.sourcePreferred = true;
				}
				if (PLUGIN_ORIGIN_PRIORITIES[t.origin]?.explicit < PLUGIN_ORIGIN_PRIORITIES[b.candidate.origin]?.explicit) u.set(g, {
					candidate: t,
					record: y
				});
				continue;
			}
			const n = resolveDuplicatePrecedenceRank({
				candidate: t,
				env: r,
				installRecords: a()
			});
			const i = resolveDuplicatePrecedenceRank({
				candidate: b.candidate,
				env: r,
				installRecords: a()
			});
			const o = n < i;
			const s = o ? t : b.candidate;
			const l = o ? b.candidate : t;
			if (o) u.set(g, {
				candidate: t,
				record: y
			});
			const d = b.candidate;
			const p = a();
			if ([[t, d], [d, t]].some(([e, t]) => matchesInstalledPluginRecord({
				candidate: e,
				env: r,
				installRecords: p
			}) && !isStaleForeignBundledPin({
				candidate: e,
				env: r
			}) && t.origin === "bundled" && !isBundledPluginInsideDevSourceRoot({
				rootDir: t.rootDir,
				env: r
			}))) continue;
			if (isSameGlobalPackageDuplicate(t, b.candidate)) continue;
			const m = s.origin === "bundled" && isStaleForeignBundledPin({
				candidate: l,
				env: r
			}) && matchesInstalledPluginRecord({
				candidate: l,
				env: r,
				installRecords: a()
			});
			const h = !m && Math.min(n, i) === 0 && n !== i;
			if (h) {
				if (f.has(g)) continue;
				f.add(g);
			}
			c.push({
				level: h ? "info" : "warn",
				...h ? { code: "explicit-config-plugin-selection" } : {},
				pluginId: g,
				source: l.source,
				message: m ? `stale plugin install record: "${g}" is pinned to ${l.rootDir}, which belongs to a different OpenClaw installation. This installation's bundled plugin is being used instead. No uninstall is needed to use the bundled plugin. Uninstalling, even with \`--keep-files\`, removes plugin configuration; re-enabling does not restore it.` : h ? `duplicate plugin id resolved by explicit config-selected plugin; ${l.origin} plugin will be overridden by config plugin (${s.source})` : `duplicate plugin id detected; ${l.origin} plugin will be overridden by ${s.origin} plugin (${s.source}); ignored plugin source: ${l.source}`
			});
			continue;
		}
		u.set(g, {
			candidate: t,
			record: y
		});
	}
	const h = rejectCaseFoldedIdCollisions([...u.values()].map(({ record: e }) => e), c);
	for (const e of h) {
		for (const t of d.get(e.manifestPath) ?? []) c.push({
			level: "warn",
			pluginId: sanitizeForLog(e.id),
			source: sanitizeForLog(e.manifestPath),
			message: sanitizeForLog(t)
		});
		pushNonBundledChannelConfigDescriptorDiagnostic({
			record: e,
			diagnostics: c,
			normalized: n
		});
	}
	return {
		plugins: h,
		diagnostics: dedupePluginDiagnostics(c, s)
	};
}
//#endregion
//#region src/plugins/manifest-registry.ts
function loadPluginManifestRegistryCore(e = {}) {
	if (!e.candidates && !e.discovery && !e.installRecords) {
		const e = getGatewayPluginMetadataSnapshot();
		if (e) return e.manifestRegistry;
	}
	const t = e.env ?? process.env;
	let n = e.installRecords;
	return buildPluginManifestRegistry({
		...e,
		env: t,
		getInstallRecords: () => n ??= loadInstalledPluginIndexInstallRecordsSync({ env: t })
	});
}
//#endregion
//#region src/plugins/plugin-metadata-env.ts
const PLUGIN_METADATA_ENV_KEYS = [
	"ANDROID_DATA",
	"APPDATA",
	"HOME",
	"OPENCLAW_BUNDLED_PLUGINS_DIR",
	"OPENCLAW_COMPATIBILITY_HOST_VERSION",
	"OPENCLAW_CONFIG_PATH",
	"OPENCLAW_DEV_SOURCE_ROOT",
	"OPENCLAW_DISABLE_BUNDLED_PLUGINS",
	"OPENCLAW_DISABLE_BUNDLED_SOURCE_OVERLAYS",
	"OPENCLAW_HOME",
	"OPENCLAW_NIX_MODE",
	"OPENCLAW_STATE_DIR",
	"PREFIX",
	"USERPROFILE",
	"XDG_CONFIG_HOME"
];
/** Compares discovery namespaces without resolving or probing filesystem roots. */
function resolvePluginMetadataEnvFingerprint(e = process.env) {
	return hashJson({
		env: Object.fromEntries(PLUGIN_METADATA_ENV_KEYS.flatMap((t) => {
			const n = e[t];
			return n === void 0 ? [] : [[t, n]];
		})),
		installRoots: hasActivePluginInstallRoots() ? resolveActivePluginInstallRoots() : void 0,
		trustBundledPluginsDirOverride: shouldTrustTestBundledPluginsDirOverride(e),
		cwd: tryProcessCwd()
	});
}
//#endregion
//#region src/plugins/manifest-registry-installed.ts
function resolveInstalledManifestRegistryIndexFingerprint(e) {
	const t = getInstalledPluginIndexFacts(e);
	const n = t?.fingerprint;
	if (n) return n;
	const r = hashStableJson({
		version: e.version,
		hostContractVersion: e.hostContractVersion,
		compatRegistryVersion: e.compatRegistryVersion,
		migrationVersion: e.migrationVersion,
		policyHash: e.policyHash,
		installRecords: e.installRecords,
		diagnostics: e.diagnostics,
		plugins: e.plugins.map(({ doctorContractFile: e, sourceAdmissions: t, packageBuild: n, ...r }) => ({
			...r,
			...n?.bundledDist === void 0 ? {} : { packageBuild: { bundledDist: n.bundledDist } }
		}))
	});
	if (t) t.fingerprint = r;
	return r;
}
//#endregion
//#region src/plugins/plugin-control-plane-context.ts
function resolvePluginDiscoveryContext(e = {}) {
	const t = e.config?.plugins?.load?.paths;
	return resolvePluginCacheInputs({
		env: e.env ?? process.env,
		workspaceDir: e.workspaceDir,
		loadPaths: e.loadPaths ?? (Array.isArray(t) ? t : void 0)
	});
}
/** Resolves a stable fingerprint for plugin control-plane activation state. */
function resolvePluginControlPlaneFingerprint(e = {}) {
	const t = e.inventoryFingerprint ?? (e.index ? resolveInstalledManifestRegistryIndexFingerprint(e.index) : void 0);
	return hashJson({
		discovery: resolvePluginDiscoveryContext(e),
		policyFingerprint: e.policyHash ?? resolveInstalledPluginIndexPolicyHash(e.config, e.env),
		...t ? { inventoryFingerprint: t } : {},
		...e.activationFingerprint ? { activationFingerprint: e.activationFingerprint } : {}
	});
}
//#endregion
//#region src/plugins/plugin-native-admission-state.ts
const admissions = /* @__PURE__ */ new WeakMap();
/** Publication bounds reusable code to the installed entries and configured workspaces. */
function publishInspectionNativeEsmPolicy(e, t) {
	const n = e.inspectionNativeEsmPolicy ??= {
		...t,
		viewKeys: /* @__PURE__ */ new Set([resolveAdmissionViewKey(false), resolveAdmissionViewKey(true)])
	};
	for (const t of admissions.get(e)?.values() ?? []) if (n.viewKeys.has(t.viewKey)) t.inspectionNativeEsm ??= { ...n };
}
function resolveAdmissionViewKey(e = isArtifactPreservingStateRead(), t = resolvePluginSourceCaptureStorage(), n = resolveActivePluginInstallRoots().stateDir) {
	return JSON.stringify([
		e ? "readonly" : "writable",
		resolvePluginMetadataEnvFingerprint(),
		t.stateDir,
		t.placement,
		n
	]);
}
//#endregion
//#region src/plugins/plugin-scope.ts
/** Normalizes plugin id scope input into a sorted unique string list. */
function normalizePluginIdScope(e) {
	return e === void 0 ? void 0 : normalizeSortedUniqueTrimmedStringList(e);
}
/** Serializes plugin scope for cache keys. */
function serializePluginIdScope(e) {
	return e === void 0 ? "__unscoped__" : JSON.stringify(e);
}
//#endregion
//#region src/plugins/current-plugin-metadata-snapshot.ts
function prepareInspectionNativeEsmPolicy(e, t, n) {
	const r = /* @__PURE__ */ new Map();
	const i = new Map(e.manifestRegistry.plugins.map((e) => [`${e.rootDir}\0${e.id}`, e]));
	for (const t of e.index.plugins) {
		const n = resolveImmutableInstallIdentity(t.origin, resolveInstalledPluginIndexInstallOwner(t), e.index.installRecords);
		const a = i.get(`${t.rootDir}\0${t.pluginId}`);
		if (!n || !a) continue;
		for (const e of ["runtime", "setup"]) {
			const t = e === "runtime" ? a.source : a.setupSource;
			if (!t) continue;
			for (const i of [false, true]) {
				const o = resolvePluginRuntimeExecutionArtifact(resolvePluginRuntimeArtifactSelection({
					...a,
					source: t,
					entryKind: e,
					preferBuiltPluginArtifacts: i
				}));
				const s = safeRealpathSync$1(o.source);
				if (s) r.set(s, n);
			}
		}
	}
	return {
		workspaces: new Set(t),
		sources: r,
		devSourceRoot: resolvePluginDiscoveryContext({
			config: n.config,
			env: n.env,
			workspaceDir: n.workspaceDir ?? e.workspaceDir
		}).devSourceRoot
	};
}
function prepareConfigCompatibility(e, t, n) {
	const r = t.compatibleConfigs?.map((e) => resolveInstalledPluginIndexPolicyHash(e, t.env));
	const i = t.compatibleConfigs?.map((e, t) => n(e, r?.[t]));
	const a = [...t.compatibleConfigs ?? []];
	if (t.config) {
		const n = resolveInstalledPluginIndexPolicyHash(t.config, t.env);
		if (n === e.policyHash || r?.includes(n)) a.push(t.config);
	}
	return {
		compatibleConfigFingerprints: i,
		configIdentities: a
	};
}
function prepareCurrentPluginMetadataSnapshotPublication(e, t, n = "operation") {
	const fingerprint = (n, r) => resolvePluginControlPlaneFingerprint({
		config: n,
		env: t.env,
		index: e.index,
		policyHash: r,
		workspaceDir: t.workspaceDir ?? e.workspaceDir
	});
	const { compatibleConfigFingerprints: r, configIdentities: i } = prepareConfigCompatibility(e, t, fingerprint);
	const a = fingerprint(t.config, e.policyHash);
	const o = fingerprint({}, e.policyHash);
	const s = a === o || e.configFingerprint === o || Boolean(r?.includes(o));
	const c = resolvePluginMetadataEnvFingerprint(t.env);
	const l = n === "gateway" && t.config ? listAgentWorkspaceDirs(t.config, t.env) : void 0;
	const u = l && JSON.stringify(l);
	const d = l && prepareInspectionNativeEsmPolicy(e, l, t);
	return () => {
		if (getCurrentPluginMetadataSnapshotState().owner === "gateway" && n !== "gateway") throw new Error("Gateway plugin metadata can only be replaced after shutdown");
		currentPluginMetadataConfigIdentityCache.clear();
		setCurrentPluginMetadataSnapshotState(e, a, r, n === "gateway" || s ? e.owners.modelIdNormalizationPolicies : void 0, n, c, s, u);
		if (d) publishInspectionNativeEsmPolicy(getProcessPluginCache(), d);
		for (const e of i) currentPluginMetadataConfigIdentityCache.add(e);
	};
}
/** Publishes a prepared CLI snapshot without displacing a lifecycle owner. */
function adoptCurrentPluginMetadataSnapshotIfAbsent(e, t = {}) {
	if (getScopedPluginCache()?.kind === "operation" || getCurrentPluginMetadataSnapshotState().snapshot !== void 0) return;
	prepareCurrentPluginMetadataSnapshotPublication(e, t)();
}
/** Explicit installation refreshes the command before its next metadata phase. */
function clearCurrentPluginMetadataOperation() {
	const e = new Set(getScopedPluginCaches());
	const t = /* @__PURE__ */ new Set();
	for (let n = getPluginExecutionFrame()?.metadataScope; n; n = n.parent) if (n.immutableRuntimeGeneration) t.add(n.cache);
	else e.add(n.cache);
	for (const n of e) if (n.kind === "operation" && !t.has(n)) invalidatePluginCacheMetadata(n);
}
function isScopedSnapshotInCurrentCache(e) {
	if (!e.immutableRuntimeGeneration && e.metadata !== e.cache.metadata) return false;
	const t = getScopedPluginCache();
	return t?.kind !== "operation" || e.cache === t;
}
const NEEDS_PREPARED_POLICY = Symbol("needs-prepared-policy");
function resolveCompatiblePluginMetadataSnapshot(e, t, n = {}) {
	const r = e.snapshot;
	if (!r) return;
	if (e.immutableRuntimeGeneration) return r;
	const i = t.env ?? process.env;
	if (e.envFingerprint !== resolvePluginMetadataEnvFingerprint(i)) return;
	const a = normalizePluginIdScope(t.pluginIds ?? t.pluginIdScope?.resolve({ index: r.index }));
	const o = normalizePluginIdScope(r.pluginIds);
	if (a !== void 0 && serializePluginIdScope(o) !== serializePluginIdScope(a)) return;
	if (o !== void 0 && a === void 0 && t.allowScopedSnapshot !== true) return;
	const s = t.workspaceDir ?? (t.allowWorkspaceScopedSnapshot === true || n.scopedOwnerContext === true ? r.workspaceDir : void 0);
	if (r.workspaceDir !== void 0 && s === void 0) return;
	if (s !== void 0 && (r.workspaceDir ?? "") !== (s ?? "")) return;
	const c = Boolean(t.config && e.hasConfigIdentity?.(t.config));
	if (c && t.requireDefaultDiscoveryContext !== true) return r;
	if (t.config && !c && t.allowSynchronousPolicyRead === false) return NEEDS_PREPARED_POLICY;
	const l = t.config && !c ? resolveInstalledPluginIndexPolicyHash(t.config, t.env) : void 0;
	if (t.config && !c) {
		const n = resolvePluginControlPlaneFingerprint({
			config: t.config,
			env: i,
			index: r.index,
			policyHash: l,
			workspaceDir: s
		});
		if (!(e.configFingerprint === n || r.configFingerprint === n || Boolean(e.compatibleConfigFingerprints?.includes(n)))) return;
	}
	if (t.requireDefaultDiscoveryContext === true && n.scopedOwnerContext !== true && e.defaultDiscoveryCompatible !== true) return;
	return r;
}
function getCurrentPluginMetadataSnapshot(e = {}) {
	for (let t = getPluginExecutionFrame()?.metadataScope; t; t = t.parent) {
		if (!isScopedSnapshotInCurrentCache(t)) continue;
		const n = resolveCompatiblePluginMetadataSnapshot(t, e, { scopedOwnerContext: true });
		if (n === NEEDS_PREPARED_POLICY) return;
		if (n) return n;
	}
	const t = getScopedPluginCache();
	if (t && t !== getProcessPluginCache()) return;
	const n = getCurrentPluginMetadataSnapshotState();
	const r = resolveCompatiblePluginMetadataSnapshot({
		...n,
		hasConfigIdentity: (e) => currentPluginMetadataConfigIdentityCache.has(e),
		immutableRuntimeGeneration: n.owner === "gateway"
	}, e);
	return r === NEEDS_PREPARED_POLICY ? void 0 : r;
}
registerPluginMetadataSnapshotReaders({
	adoptCurrentPluginMetadataSnapshotIfAbsent,
	getCurrentPluginMetadataSnapshot
});
registerPluginMetadataProcessMemoLifecycleClear(clearCurrentPluginMetadataOperation, { owner: "operation" });
//#endregion
//#region src/utils/run-with-concurrency.ts
/** Runs async tasks with bounded concurrency while preserving result indexes. */
async function runTasksWithConcurrency(e) {
	const { tasks: t, limit: n, onTaskError: r, throwOnError: i = false } = e;
	const a = e.errorMode ?? "continue";
	if (t.length === 0) return {
		results: [],
		firstError: void 0,
		hasError: false
	};
	const o = Number.isFinite(n) ? Math.max(1, Math.min(Math.floor(n), t.length)) : t.length;
	const s = Array.from({ length: t.length });
	let c = void 0;
	let l = false;
	return new Promise((e, n) => {
		const runOne = async (e, t) => {
			if (a === "stop" && l) return;
			try {
				s[t] = await e();
			} catch (e) {
				if (!l) {
					c = e;
					l = true;
				}
				let a = e;
				try {
					r?.(e, t);
				} catch (e) {
					a = e;
				}
				if (i) n(a);
			}
		};
		const u = AsyncLocalStorage.bind((e, t) => Promise.resolve().then(() => runOne(e, t)));
		pMap(t.slice(), u, { concurrency: o }).then(() => e({
			results: s,
			firstError: c,
			hasError: l
		}), n);
	});
}
//#endregion
//#region src/secrets/exec-provider-path-validation.ts
/** Checks the same command-path trust boundary before validation, writes, and execution. */
async function assertSecureExecCommandPath(e) {
	const t = resolveUserPath(e.command);
	if (!t) throw new Error(`${e.label} must be an absolute path.`);
	const n = await safeStat(t);
	if (!n.ok) throw new Error(`${e.label} is not readable: ${t}`);
	if (n.isDir) throw new Error(`${e.label} must be a file: ${t}`);
	if (n.isSymlink) throw new Error(`${e.label} must not be a symlink: ${t}`);
	if (e.trustedDirs && e.trustedDirs.length > 0) {
		if (!e.trustedDirs.map((e) => resolveUserPath(e)).some((e) => isPathInside(e, t))) throw new Error(`${e.label} is outside trustedDirs: ${t}`);
	}
	const r = await inspectPathPermissions(t);
	if (!r.ok) throw new Error(`${e.label} permissions could not be verified: ${t}`);
	if (r.worldWritable || r.groupWritable) throw new Error(`${e.label} permissions are too open: ${t}`);
	if (process.platform === "win32" && r.source === "unknown") throw new FsSafeError("permission-unverified", `${e.label} ACL verification unavailable on Windows for ${t}. Move the command to a path whose ACLs OpenClaw can verify; there is no provider-level bypass.`);
	if (process.platform !== "win32" && typeof process.getuid === "function" && n.uid != null) {
		const r = process.getuid();
		if (n.uid !== r) throw new Error(`${e.label} must be owned by the current user (uid=${r}): ${t}`);
	}
	return t;
}
//#endregion
//#region src/secrets/json-pointer.ts
/** JSON Pointer token helpers for file-backed secret refs. */
/**
* Reads a value from a JSON-like document using an absolute JSON Pointer.
* Missing segments throw by default; `onMissing: "undefined"` is for optional probes.
*/
function readJsonPointer(e, t, n = {}) {
	const r = n.onMissing ?? "throw";
	const fail = (e) => {
		if (r === "throw") throw new Error(e);
	};
	if (!t.startsWith("/")) return fail("File-backed secret ids must be absolute JSON pointers (for example: \"/providers/openai/apiKey\").");
	let i = e;
	for (const e of t.slice(1).split("/")) {
		const t = e.replace(/~1/g, "/").replace(/~0/g, "~");
		if (Array.isArray(i)) {
			const e = parseConfigPathArrayIndex(t);
			if (e === void 0 || e >= i.length) return fail(`JSON pointer segment "${t}" is out of bounds.`);
			i = i[e];
			continue;
		}
		if (!isRecord(i) || !Object.hasOwn(i, t)) return fail(`JSON pointer segment "${t}" does not exist.`);
		i = i[t];
	}
	return i;
}
//#endregion
//#region src/plugins/manifest-owner-policy.ts
/** Resolves whether a manifest owner plugin is effectively activated. */
function isActivatedManifestOwner(e) {
	return resolveEffectivePluginActivationState({
		id: e.plugin.id,
		origin: e.plugin.origin,
		channelIds: e.plugin.channels,
		config: e.normalizedConfig,
		rootConfig: e.rootConfig,
		enabledByDefault: isPluginEnabledByDefaultForPlatform(e.plugin)
	}).activated;
}
//#endregion
//#region src/secrets/provider-integrations.ts
/** Materializes trusted plugin secret-provider integrations into exec provider configs. */
const NODE_COMMAND_PLACEHOLDER = "${node}";
function resolvePluginRelativePath(e, t) {
	const n = path.resolve(t, e);
	return isPathInside$2(t, n) ? n : void 0;
}
function resolveArg(e, t) {
	if (!e.startsWith("./") && !e.startsWith("../")) return e;
	return resolvePluginRelativePath(e, t);
}
function isSecurePosixPathStat(e) {
	if (process.platform === "win32") return true;
	if ((e.mode & 2) !== 0) return false;
	if (typeof process.getuid !== "function" || typeof e.uid !== "number") return true;
	const t = process.getuid();
	return e.uid === t || e.uid === 0;
}
function resolveNodeEntrypointArg(e) {
	const t = e.args[0];
	if (!t?.startsWith("./")) return;
	const n = resolvePluginRelativePath(t, e.pluginRoot);
	if (!n) return;
	if (isEmbeddedStandaloneModule(n)) return n;
	try {
		const t = openRootFileSync({
			absolutePath: n,
			rootPath: e.pluginRoot,
			boundaryLabel: "plugin root",
			rejectHardlinks: e.rejectHardlinks,
			symlinks: process.platform === "win32" ? "follow-parents-within-root" : "reject"
		});
		if (!t.ok) return;
		try {
			if (!isSecurePosixPathStat(t.stat)) return;
			if (process.platform !== "win32") for (let e = path.dirname(t.path);; e = path.dirname(e)) {
				const n = fsSync.lstatSync(e);
				if (!n.isDirectory() || !isSecurePosixPathStat(n)) return;
				if (e === t.rootRealPath) break;
			}
			return t.path;
		} finally {
			fsSync.closeSync(t.fd);
		}
	} catch {
		return;
	}
}
function materializeExecProviderConfig(e, t, n) {
	const r = t.rootDir;
	if (e.command !== NODE_COMMAND_PLACEHOLDER || !e.args) return;
	const i = shouldRejectHardlinkedPluginFiles({
		origin: t.origin,
		rootDir: r,
		env: n
	});
	const a = resolveNodeEntrypointArg({
		args: e.args,
		pluginRoot: r,
		rejectHardlinks: i
	});
	if (!a) return;
	const o = e.args.slice(1).map((e) => resolveArg(e, r)).filter((e) => e !== void 0);
	if (o.length !== e.args.length - 1) return;
	return {
		source: "exec",
		command: process.execPath,
		args: [
			...resolveRuntimeArgs(),
			a,
			...o
		],
		...e.timeoutMs !== void 0 ? { timeoutMs: e.timeoutMs } : {},
		...e.noOutputTimeoutMs !== void 0 ? { noOutputTimeoutMs: e.noOutputTimeoutMs } : {},
		...e.maxOutputBytes !== void 0 ? { maxOutputBytes: e.maxOutputBytes } : {},
		...e.jsonOnly === false ? { jsonOnly: false } : {},
		...e.env ? { env: e.env } : {},
		...e.passEnv ? { passEnv: e.passEnv } : {},
		trustedDirs: [.../* @__PURE__ */ new Set([path.dirname(process.execPath), r])]
	};
}
function canExposeSecretProviderIntegrations(e) {
	if (e.record.origin !== "bundled" && e.record.origin !== "global") return false;
	return isActivatedManifestOwner({
		plugin: e.record,
		normalizedConfig: e.normalizedConfig,
		rootConfig: e.config
	});
}
function isPluginIntegrationSecretProviderConfig(e) {
	return typeof e === "object" && e !== null && "source" in e && e.source === "exec" && "pluginIntegration" in e && typeof e.pluginIntegration === "object" && e.pluginIntegration !== null && "pluginId" in e.pluginIntegration && typeof e.pluginIntegration.pluginId === "string" && e.pluginIntegration.pluginId.trim().length > 0 && "integrationId" in e.pluginIntegration && typeof e.pluginIntegration.integrationId === "string" && e.pluginIntegration.integrationId.trim().length > 0;
}
/** Materializes an active trusted plugin secret-provider integration into an exec provider. */
function resolveSecretProviderIntegrationConfig(e) {
	const t = e.config ?? {};
	const n = normalizePluginsConfig(t.plugins);
	const r = e.env ?? process.env;
	const { pluginId: i, integrationId: a } = e.providerConfig.pluginIntegration;
	if (!isValidSecretProviderAlias(e.providerAlias)) return {
		ok: false,
		reason: `provider alias "${e.providerAlias}" is invalid`
	};
	const o = e.manifestRegistry.plugins.find((e) => e.id === i);
	if (!o) return {
		ok: false,
		reason: `plugin "${i}" is not installed`
	};
	if (!canExposeSecretProviderIntegrations({
		record: o,
		normalizedConfig: n,
		config: t
	})) return {
		ok: false,
		reason: `plugin "${i}" is not active or is not from a trusted install origin`
	};
	const s = o.secretProviderIntegrations?.[a];
	if (!s) return {
		ok: false,
		reason: `plugin "${o.id}" does not declare secret provider integration "${a}"`
	};
	const c = materializeExecProviderConfig(s, o, r);
	if (!c) return {
		ok: false,
		reason: `plugin "${o.id}" integration "${a}" could not be materialized`
	};
	return {
		ok: true,
		providerConfig: c
	};
}
//#endregion
//#region src/secrets/sentinel.ts
const SECRET_SENTINEL_SOURCE = "oc-sent-v2\\.[A-Za-z0-9_-]+\\.end";
const SECRET_SENTINEL_MAX_LENGTH = 11 + Math.ceil(262288 / 3) + 4;
const SECRET_SENTINEL_PATTERN = new RegExp(SECRET_SENTINEL_SOURCE, "g");
const secretSentinelKeys = resolveGlobalSingleton(Symbol.for("openclaw.secretSentinel.keys"), () => ({ keys: randomBytes(64) })).keys;
const secretSentinelCipherKey = secretSentinelKeys.subarray(0, 32);
const secretSentinelNonceKey = secretSentinelKeys.subarray(32);
//#endregion
//#region src/secrets/store/secret-store-github-names.ts
const HIDDEN_GITHUB_STORE_NAME_PATTERN = /^github-(setup|device|oauth)-[a-f0-9]{32}$/u;
function classifyHiddenGitHubStoreName(e) {
	const t = HIDDEN_GITHUB_STORE_NAME_PATTERN.exec(e)?.[1];
	return t === "setup" || t === "device" || t === "oauth" ? t : void 0;
}
//#endregion
//#region src/secrets/store/secret-store-changes.ts
const listeners = resolveGlobalSet(Symbol.for("openclaw.secretStoreChanges"), "close-and-restart");
function subscribeSecretStoreChanges(e) {
	return registerListener(listeners, e);
}
function publishSecretStoreChange(e, t) {
	notifyListeners(listeners, {
		databasePath: normalizeDatabasePath(e),
		githubOAuth: t === void 0 || t.some((e) => {
			const t = classifyHiddenGitHubStoreName(e);
			return t === "device" || t === "oauth";
		})
	});
}
//#endregion
//#region src/secrets/store/secret-store-validation.ts
function assertSecretStoreEnvName(e) {
	if (!ENV_SECRET_REF_ID_RE.test(e)) throw new SecretStoreValidationError("SECRET_STORE_INVALID_NAME", `Secret store name must match ${String(ENV_SECRET_REF_ID_RE)}.`);
}
//#endregion
//#region src/secrets/store/secret-store.ts
const log = createSubsystemLogger("secrets/store");
async function readSecretStoreValue(e) {
	try {
		const t = e.name;
		assertSecretStoreEnvName(t);
		const n = e.context ?? captureOpenClawStateReadWorkerContext(e.database);
		const r = (await executeExistingOpenClawStateRead({
			path: n.admission.databasePath,
			env: n.environment
		}, {
			type: "secrets.value",
			input: { name: t }
		}, {
			context: n,
			preferIndependentWarmRead: true
		}))?.row;
		if (r?.kind === "secret") registerSecretValueForRedaction(r.value);
		n.admission.assertCurrent();
		e.assertCurrent?.();
		if (!r) return err({
			code: "SECRET_STORE_NOT_FOUND",
			message: `Secret store entry "${t}" was not found.`
		});
		return ok(r.value);
	} catch (e) {
		if (e instanceof SecretStoreValidationError) return err({
			code: "SECRET_STORE_INVALID_NAME",
			message: e.message
		});
		return err({
			code: "SECRET_STORE_UNAVAILABLE",
			message: "Secret store database is unavailable.",
			cause: e
		});
	}
}
const expiryObservations = /* @__PURE__ */ new Map();
subscribeSecretStoreChanges(({ databasePath: e }) => {
	const t = expiryObservations.get(e);
	if (t) t.dirty = true;
});
registerOpenClawStateDatabaseAsyncResource({ async close() {
	const e = [...expiryObservations.keys()];
	expiryObservations.clear();
	for (const t of e) publishSecretStoreChange(t);
} });
registerOpenClawStateDatabaseLifecycleListener((e) => {
	if (e.kind !== "opened") {
		const t = expiryObservations.get(e.path);
		if (t) {
			t.dirty = true;
			expiryObservations.delete(e.path);
		}
	}
});
//#endregion
//#region src/secrets/resolve-store.ts
const STORE_SECRET_REF_BATCH_MAX_BYTES = 512 * SECRET_STORE_VALUE_MAX_BYTES;
async function resolveStoreRefs(e) {
	const t = captureOpenClawStateReadWorkerContext(e.database);
	const n = /* @__PURE__ */ new Map();
	let r = 0;
	for (const i of e.refs) {
		const a = await readSecretStoreValue({
			scope: { kind: "team" },
			name: i.id,
			context: t
		});
		t.admission.assertCurrent();
		if (!a.ok) {
			if (a.error.code === "SECRET_STORE_NOT_FOUND" || a.error.code === "SECRET_STORE_INVALID_NAME") {
				e.onRefError(refResolutionError({
					code: a.error.code === "SECRET_STORE_NOT_FOUND" ? "SECRET_REF_NOT_FOUND" : "SECRET_REF_INVALID",
					source: "store",
					provider: e.providerName,
					refId: i.id,
					message: a.error.message
				}));
				continue;
			}
			throw providerResolutionError({
				code: "SECRET_PROVIDER_UNAVAILABLE",
				source: "store",
				provider: e.providerName,
				message: a.error.message,
				cause: a.error.cause
			});
		}
		r += Buffer.byteLength(a.value, "utf8");
		if (r > STORE_SECRET_REF_BATCH_MAX_BYTES) throw providerResolutionError({
			code: "SECRET_PROVIDER_INVALID",
			source: "store",
			provider: e.providerName,
			message: `Store provider "${e.providerName}" exceeded its ${STORE_SECRET_REF_BATCH_MAX_BYTES}-byte batch limit.`
		});
		n.set(i.id, a.value);
	}
	return n;
}
//#endregion
//#region src/secrets/shared.ts
/**
* Normalizes numeric config to a positive integer, falling back when the input is not finite.
*/
function normalizePositiveInt(e, t) {
	if (typeof e === "number" && Number.isFinite(e)) return Math.max(1, Math.floor(e));
	return Math.max(1, Math.floor(t));
}
//#endregion
//#region src/secrets/resolve.ts
/** Resolves SecretRef values from env, file, exec, and store secret providers. */
const DEFAULT_PROVIDER_CONCURRENCY = 4;
const DEFAULT_MAX_REFS_PER_PROVIDER = 512;
const DEFAULT_MAX_BATCH_BYTES = 262144;
const DEFAULT_FILE_MAX_BYTES = 1048576;
const DEFAULT_FILE_TIMEOUT_MS = 5e3;
const DEFAULT_EXEC_TIMEOUT_MS = 5e3;
const DEFAULT_EXEC_MAX_OUTPUT_BYTES = 1048576;
const SAFE_EXEC_ERROR_CODES = /* @__PURE__ */ new Set(["AMBIGUOUS_DUPLICATE_KEY", "NOT_FOUND"]);
function resolveConfiguredProvider(e) {
	const { ref: t, config: n } = e;
	const r = n.secrets?.providers?.[t.provider];
	if (isBuiltInDefaultSecretProviderRef(n, t)) {
		if (t.source === "env" || t.source === "store") return { source: t.source };
	}
	if (!r) throw providerResolutionError({
		code: "SECRET_PROVIDER_NOT_CONFIGURED",
		source: t.source,
		provider: t.provider,
		message: `Secret provider "${t.provider}" is not configured (ref: ${t.source}:${t.provider}:${t.id}).`
	});
	const i = resolveSecretRefProviderSourceMismatch(n, t);
	if (i) throw providerResolutionError({
		code: "SECRET_PROVIDER_INVALID",
		source: t.source,
		provider: t.provider,
		message: `Secret provider "${t.provider}" has source "${i}" but ref requests "${t.source}".`
	});
	if (isPluginIntegrationSecretProviderConfig(r)) {
		const i = e.manifestRegistry ?? getCurrentPluginMetadataSnapshot({
			config: n,
			env: e.env,
			allowWorkspaceScopedSnapshot: true
		})?.manifestRegistry ?? loadPluginManifestRegistryCore({
			config: n,
			env: e.env
		});
		const a = resolveSecretProviderIntegrationConfig({
			manifestRegistry: i,
			providerAlias: t.provider,
			providerConfig: r,
			config: n,
			env: e.env
		});
		if (!a.ok) throw providerResolutionError({
			source: t.source,
			provider: t.provider,
			message: `Secret provider "${t.provider}" plugin integration is unavailable: ${a.reason}.`
		});
		return a.providerConfig;
	}
	return r;
}
async function resolveProviderRefs({ refs: e, source: t, providerName: n, onRefError: r, providerConfig: i, options: a }) {
	try {
		if (i.source === "env") {
			const t = a.env ?? process.env;
			const o = /* @__PURE__ */ new Map();
			const s = i.allowlist ? new Set(i.allowlist) : null;
			for (const i of e) {
				if (s && !s.has(i.id)) {
					r(refResolutionError({
						code: "SECRET_REF_POLICY_DENIED",
						source: "env",
						provider: n,
						refId: i.id,
						message: `Environment variable "${i.id}" is not allowlisted in secrets.providers.${n}.allowlist.`
					}));
					continue;
				}
				const e = t[i.id];
				if (!hasNonEmptyString(e)) {
					r(refResolutionError({
						code: "SECRET_REF_NOT_FOUND",
						source: "env",
						provider: n,
						refId: i.id,
						message: `Environment variable "${i.id}" is missing or empty.`
					}));
					continue;
				}
				o.set(i.id, e);
			}
			return o;
		}
		if (i.source === "file") {
			const t = a.cache;
			const read = async () => {
				const e = resolveUserPath(i.path);
				const t = resolvePositiveTimerTimeoutMs(i.timeoutMs, DEFAULT_FILE_TIMEOUT_MS);
				const r = normalizePositiveInt(i.maxBytes, DEFAULT_FILE_MAX_BYTES);
				try {
					const { buffer: a } = await readSecureFile({
						filePath: e,
						label: `secrets.providers.${n}.path`,
						io: {
							maxBytes: r,
							timeoutMs: t
						},
						permissions: { allowInsecure: false }
					});
					const o = a.toString("utf8").replace(/^\uFEFF/, "");
					if (i.mode === "singleValue") return o.replace(/\r?\n$/, "");
					const s = JSON.parse(o);
					if (!isRecord(s)) throw new Error(`File provider "${n}" payload is not a JSON object.`);
					return s;
				} catch (e) {
					if (e instanceof FsSafeError && e.code === "timeout") throw new Error(`File provider "${n}" timed out after ${t}ms.`, { cause: e });
					throw e;
				}
			};
			let o;
			if (!t) o = await read();
			else {
				t.filePayloadByProvider ??= /* @__PURE__ */ new Map();
				o = await getOrCreatePromise(t.filePayloadByProvider, n, read);
			}
			const s = i.mode ?? "json";
			const c = /* @__PURE__ */ new Map();
			if (s === "singleValue") {
				for (const t of e) {
					if (t.id !== "value") {
						r(refResolutionError({
							code: "SECRET_REF_INVALID",
							source: "file",
							provider: n,
							refId: t.id,
							message: `singleValue file provider "${n}" expects ref id "${SINGLE_VALUE_FILE_REF_ID}".`
						}));
						continue;
					}
					c.set(t.id, o);
				}
				return c;
			}
			for (const t of e) try {
				c.set(t.id, readJsonPointer(o, t.id, { onMissing: "throw" }));
			} catch (e) {
				r(refResolutionError({
					code: "SECRET_REF_NOT_FOUND",
					source: "file",
					provider: n,
					refId: t.id,
					message: formatErrorMessage(e),
					cause: e
				}));
			}
			return c;
		}
		if (i.source === "store") return await resolveStoreRefs({
			refs: e,
			providerName: n,
			onRefError: r,
			database: { env: a.env ?? process.env }
		});
		if (i.source === "exec") {
			if (isPluginIntegrationSecretProviderConfig(i)) throw providerResolutionError({
				source: t,
				provider: n,
				message: `Secret provider "${n}" plugin integration was not materialized before exec resolution.`
			});
			const o = a.env ?? process.env;
			const s = uniqueStrings(e.map((e) => e.id));
			const c = await assertSecureExecCommandPath({
				command: i.command,
				label: `secrets.providers.${n}.command`,
				trustedDirs: i.trustedDirs
			});
			const l = JSON.stringify({
				protocolVersion: 1,
				provider: n,
				ids: s
			});
			if (Buffer.byteLength(l, "utf8") > DEFAULT_MAX_BATCH_BYTES) throw providerResolutionError({
				code: "SECRET_PROVIDER_INVALID",
				source: "exec",
				provider: n,
				message: `Exec provider "${n}" request exceeded maxBatchBytes (${DEFAULT_MAX_BATCH_BYTES}).`
			});
			const u = {};
			for (const e of i.passEnv ?? []) {
				const t = o[e];
				if (t !== void 0) u[e] = t;
			}
			for (const [e, t] of Object.entries(i.env ?? {})) u[e] = t;
			const d = resolvePositiveTimerTimeoutMs(i.timeoutMs, DEFAULT_EXEC_TIMEOUT_MS);
			const f = resolvePositiveTimerTimeoutMs(i.noOutputTimeoutMs, d);
			const p = normalizePositiveInt(i.maxOutputBytes, DEFAULT_EXEC_MAX_OUTPUT_BYTES);
			const m = i.jsonOnly ?? true;
			const h = await runCommandWithTimeout([c, ...i.args ?? []], {
				baseEnv: {},
				cwd: path.dirname(c),
				env: u,
				input: l,
				killProcessTree: true,
				maxCombinedOutputBytes: p,
				maxOutputBytes: p,
				noOutputTimeoutMs: f,
				outputCapture: "head",
				terminateOnOutputLimit: true,
				timeoutMs: d
			});
			let g;
			if (h.termination === "timeout") g = `Exec provider "${n}" timed out after ${d}ms.`;
			else if (h.termination === "no-output-timeout") g = `Exec provider "${n}" produced no output for ${f}ms.`;
			else if (h.outputLimitExceeded) g = `Exec provider output exceeded maxOutputBytes (${p}).`;
			else if (h.code !== 0) g = `Exec provider "${n}" exited with code ${String(h.code)}.`;
			if (g !== void 0) throw providerResolutionError({
				source: "exec",
				provider: n,
				message: g
			});
			function invalidResponse(e) {
				throw providerResolutionError({
					source: "exec",
					provider: n,
					message: `Exec provider "${n}" ${e}`
				});
			}
			const _ = h.stdout.trim();
			if (!_) invalidResponse("returned empty stdout.");
			let v;
			try {
				v = JSON.parse(_);
			} catch {
				if (!m && s.length === 1) return /* @__PURE__ */ new Map([[expectDefined(s[0], "ids entry at 0"), _]]);
				invalidResponse("returned invalid JSON.");
			}
			if (!isRecord(v)) {
				if (!m && s.length === 1 && typeof v === "string") return /* @__PURE__ */ new Map([[expectDefined(s[0], "ids entry at 0"), v]]);
				invalidResponse("response must be an object.");
			}
			if (v.protocolVersion !== 1) invalidResponse("protocolVersion must be 1.");
			const y = v.values;
			if (!isRecord(y)) invalidResponse("response missing \"values\".");
			const b = isRecord(v.errors) ? v.errors : null;
			const x = {};
			for (const e of s) {
				if (b && Object.hasOwn(b, e)) {
					const t = b[e];
					const i = isRecord(t) && typeof t.code === "string" ? t.code : null;
					const a = i && SAFE_EXEC_ERROR_CODES.has(i) ? i : null;
					r(refResolutionError({
						code: a === "NOT_FOUND" ? "SECRET_REF_NOT_FOUND" : "SECRET_REF_PROVIDER_ERROR",
						source: "exec",
						provider: n,
						refId: e,
						message: `Exec provider "${n}" failed for id "${e}"${a ? ` (${a})` : ""}.`
					}));
					continue;
				}
				if (!Object.hasOwn(y, e)) {
					r(refResolutionError({
						code: "SECRET_REF_NOT_FOUND",
						source: "exec",
						provider: n,
						refId: e,
						message: `Exec provider "${n}" response missing id "${e}".`
					}));
					continue;
				}
				x[e] = y[e];
			}
			return new Map(Object.entries(x));
		}
		throw providerResolutionError({
			source: t,
			provider: n,
			message: `Unsupported secret provider source "${String(i.source)}".`
		});
	} catch (e) {
		if (isSecretResolutionError(e)) throw e;
		const r = process.platform === "win32" && (t === "file" || t === "exec") && e instanceof FsSafeError && e.code === "permission-unverified";
		throw providerResolutionError({
			...r ? { code: "SECRET_PROVIDER_PATH_SECURITY_UNVERIFIABLE" } : {},
			source: t,
			provider: n,
			message: formatErrorMessage(e),
			cause: e
		});
	}
}
async function resolveSecretRefProviderGroups(e) {
	const t = normalizeAndGroupSecretRefs(e.refs);
	const n = /* @__PURE__ */ new Map();
	const { options: r, errorMode: i } = e;
	const a = t.map((e) => async () => {
		const t = /* @__PURE__ */ new Map();
		const onRefError = (e) => {
			if (i === "stop") throw e;
			t.set(e.refId, e);
		};
		if (e.refs.length > DEFAULT_MAX_REFS_PER_PROVIDER) throw providerResolutionError({
			code: "SECRET_PROVIDER_INVALID",
			source: e.source,
			provider: e.providerName,
			message: `Secret provider "${e.providerName}" exceeded maxRefsPerProvider (${DEFAULT_MAX_REFS_PER_PROVIDER}).`
		});
		const n = resolveConfiguredProvider({
			ref: expectDefined(e.refs[0], "refs entry at 0"),
			config: r.config,
			env: r.env ?? process.env,
			manifestRegistry: r.manifestRegistry
		});
		const a = await resolveProviderRefs({
			refs: e.refs,
			source: e.source,
			providerName: e.providerName,
			providerConfig: n,
			options: r,
			onRefError
		});
		for (const n of e.refs) {
			if (t.has(n.id)) continue;
			if (!a.has(n.id)) {
				onRefError(refResolutionError({
					code: "SECRET_REF_PROVIDER_CONTRACT",
					source: e.source,
					provider: e.providerName,
					refId: n.id,
					message: `Secret provider "${e.providerName}" did not return id "${n.id}".`
				}));
				continue;
			}
			if (isRedactedSecretValue(a.get(n.id))) onRefError(refResolutionError({
				code: "SECRET_REF_REDACTED_VALUE",
				source: e.source,
				provider: e.providerName,
				refId: n.id,
				message: `Secret reference "${e.source}:${e.providerName}:${n.id}" resolves to a redaction placeholder. Run openclaw doctor --fix to repair a store-backed Gateway token; supply a real credential for other secrets.`
			}));
		}
		return {
			group: e,
			values: a,
			refFailures: t
		};
	});
	const o = await runTasksWithConcurrency({
		tasks: a,
		limit: DEFAULT_PROVIDER_CONCURRENCY,
		errorMode: e.errorMode,
		onTaskError: (e, t) => {
			n.set(t, e);
		}
	});
	const s = /* @__PURE__ */ new Map();
	const c = [];
	for (const e of o.results) {
		if (!e) continue;
		for (const t of e.group.refs) {
			const n = e.refFailures.get(t.id);
			if (n) c.push({
				group: e.group,
				error: n
			});
			else s.set(secretRefKey(t), e.values.get(t.id));
		}
	}
	for (const [e, r] of t.entries()) if (n.has(e)) c.push({
		group: r,
		error: n.get(e)
	});
	return {
		resolved: s,
		failures: c,
		hasError: o.hasError,
		firstError: o.firstError
	};
}
/** Resolves a batch of SecretRefs, grouped by provider for bounded provider concurrency. */
async function resolveSecretRefValues(e, t) {
	const n = await resolveSecretRefProviderGroups({
		refs: e,
		options: t,
		errorMode: "stop"
	});
	if (n.hasError) throw n.firstError;
	return n.resolved;
}
/** Resolves one SecretRef, using the optional shared runtime cache. */
async function resolveSecretRefValue(e, t) {
	const n = t.cache;
	const r = secretRefKey(e);
	const resolve = async () => {
		const n = await resolveSecretRefValues([e], t);
		if (!n.has(r)) throw refResolutionError({
			code: "SECRET_REF_PROVIDER_CONTRACT",
			source: e.source,
			provider: e.provider,
			refId: e.id,
			message: `Secret reference "${r}" resolved to no value.`
		});
		return n.get(r);
	};
	if (!n) return await resolve();
	n.resolvedByRefKey ??= /* @__PURE__ */ new Map();
	return await getOrCreatePromise(n.resolvedByRefKey, r, resolve);
}
/** Resolves one SecretRef and requires a non-empty string result. */
async function resolveSecretRefString(e, t) {
	const n = await resolveSecretRefValue(e, t);
	if (!hasNonEmptyString(n)) throw new Error(`Secret reference "${e.source}:${e.provider}:${e.id}" resolved to a non-string or empty value.`);
	return n;
}
//#endregion
export { describeSecretResolutionOperatorRecovery as a, isVitestRuntimeEnv as c, describeSecretResolutionOperatorDiagnostic as i, resolveSecretRefValue as n, isSecretResolutionError as o, resolveSecretRefValues as r, captureRuntimeConfigWithSource as s, resolveSecretRefString as t };