UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4,010 lines • 148 kB
import { c as normalizeOptionalLowercaseString, p as normalizeStringifiedOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord, r as asNullableRecord, s as ensureRecord } from "./record-coerce-CVPuDqcc.mjs";
import { b as uniqueStrings, g as normalizeUniqueStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { t as isBlockedObjectKey } from "./prototype-keys-CLGi5xDj.mjs";
import { n as DEFAULT_GATEWAY_PORT } from "./paths-DAcAg5aV.mjs";
import { t as findNormalizedProviderKey } from "./provider-id-b5XGSf9C.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { n as normalizeAccountId, t as DEFAULT_ACCOUNT_ID } from "./account-id-BqKT3GuY.mjs";
import { t as hasAgentRosterProperty } from "./agent-roster-t1ooUdXp.mjs";
import { c as mapLegacyAudioTranscription, i as LEGACY_CONFIG_MIGRATIONS_RUNTIME_ENTRIES, o as createLegacyConfigRule, t as LEGACY_CONFIG_MIGRATION_TOOLS_BY_SENDER } from "./legacy-tools-by-sender-Cj1HdJFy.mjs";
import { a as getRetainedLegacyDefaultAgentId, o as setRetainedLegacyDefaultAgentId } from "./legacy.default-agent-owner-DpmHgK0A.mjs";
import { t as parseLegacyAgentRoster } from "./legacy.roster-BcYJITMZ.mjs";
import { a as visitAgentEntries, i as visitAgentConfigScopes, n as moveLegacyConfigKey, o as visitChannelEntries, r as someAgentEntry, t as deleteRetiredPath } from "./legacy-config-record-shared-D3vIaBh9.mjs";
import { i as normalizeTalkSection, r as normalizeTalkRealtimeConfig } from "./talk-CqEDzucG.mjs";
import { t as normalizeExactAllowedHost } from "./exact-hostname-DgSGIR8G.mjs";
import { t as parseDurationMs } from "./parse-duration-D6UJm52I.mjs";
import { c as resolveExactExecModeFromPolicy } from "./exec-approvals-core-puBAw1bE.mjs";
import { l as mergeAlsoAllowPolicy } from "./tool-policy-BR4v75RA.mjs";
import { L as isKnownCoreToolId, U as resolveCoreToolProfilePolicy } from "./tool-catalog-C1ALpCJD.mjs";
import { i as expandToolGroups, s as normalizeToolList } from "./tool-policy-shared-BHvBopvF.mjs";
import { r as createToolPolicyMatcher, s as isToolAllowedByPolicyName } from "./tool-policy-match-DzwVnbV4.mjs";
import { i as isGatewayNonLoopbackBindMode, o as resolveGatewayPortWithDefault, r as hasConfiguredControlUiAllowedOrigins, t as buildDefaultControlUiAllowedOrigins } from "./gateway-control-ui-origins-jPuz3g3d.mjs";
import { t as DEFAULT_SANDBOX_BROWSER_NETWORK } from "./browser-network-BG6jdrVm.mjs";
import { n as resolveProviderToolPolicy, r as resolveProviderToolPolicyEntry, t as normalizeToolProviderPolicyKey } from "./provider-tool-policy-DNUBF9-2.mjs";
import { n as isKnownCliMcpTypeAlias, t as canonicalizeConfiguredMcpServer } from "./mcp-config-normalize-DxJwGDsa.mjs";
import { i as selectLegacyHeartbeatVisibility } from "./channel-legacy-config-migrate-DVMnZ4Sy.mjs";
import { t as mergeMissing } from "./merge-missing-B2E5LWKD.mjs";
import { t as LEGACY_CONFIG_MIGRATIONS_RUNTIME_MODELS } from "./legacy-config-migrations.runtime.models-DVGtmnPu.mjs";
import { n as normalizeConfiguredMemoryExtraPaths } from "./config-utils-sHBULYOF.mjs";
import "./config-utils-CoN3l5FQ.mjs";
import { c as isToolPolicyPath, n as TASK_SUGGESTION_TOOL_NAME_MIGRATION, o as migrateLegacyToolNamePolicies, r as findLegacyToolNamePaths, s as TOOL_POLICY_ROOTS, t as IMAGE_INSPECTION_TOOL_NAME_MIGRATION } from "./legacy-tool-name-migration-DNYJiu1e.mjs";
import { isDeepStrictEqual } from "node:util";
//#region src/commands/doctor/shared/legacy-config-migrations.audio.ts
function applyLegacyAudioTranscriptionModel(e, t, n) {
	const r = mapLegacyAudioTranscription(t);
	if (!r) {
		n.push("Removed audio.transcription (invalid or empty command).");
		return;
	}
	const i = ensureRecord(e, "tools");
	const a = ensureRecord(i, "media");
	const o = ensureRecord(a, "audio");
	const s = Array.isArray(a.models) ? a.models : [];
	const isAudioCompatible = (e) => {
		const t = asNullableRecord(e);
		return t !== null && (!Array.isArray(t.capabilities) || t.capabilities.includes("audio"));
	};
	if (!(Array.isArray(o.models) && o.models.some(isAudioCompatible) || s.some(isAudioCompatible))) {
		o.enabled = true;
		o.preferredModel = typeof r.command === "string" ? `cli:${r.command}` : void 0;
		a.models = [...s, {
			...r,
			capabilities: ["audio"]
		}];
		n.push("Moved audio.transcription → tools.media.models.");
		return;
	}
	n.push("Removed audio.transcription (tools.media.models already set).");
}
const LEGACY_CONFIG_MIGRATIONS_AUDIO = [{
	id: "audio.transcription-v2",
	legacyRules: [{
		path: ["audio", "transcription"],
		message: "Use a capability-tagged tools.media.models entry instead."
	}],
	apply: (e, t) => {
		const n = asNullableRecord(e.audio);
		if (n?.transcription === void 0) return;
		applyLegacyAudioTranscriptionModel(e, n.transcription, t);
		delete n.transcription;
		if (Object.keys(n).length === 0) delete e.audio;
	}
}];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.channels.ts
function hasLegacyThreadBindingSpawnSplit(e) {
	const t = asNullableRecord(e);
	return Boolean(t && (Object.hasOwn(t, "spawnSubagentSessions") || Object.hasOwn(t, "spawnAcpSessions")));
}
function migrateThreadBindingsSpawnSessionsForPath(e) {
	const t = asNullableRecord(e.owner.threadBindings);
	if (!t || !hasLegacyThreadBindingSpawnSplit(t)) return;
	const n = t.spawnSessions !== void 0;
	const r = t.spawnSubagentSessions;
	const i = t.spawnAcpSessions;
	const a = [r, i].filter((e) => typeof e === "boolean");
	const o = a.length > 0 ? a.every((e) => e) : void 0;
	delete t.spawnSubagentSessions;
	delete t.spawnAcpSessions;
	if (!n && o !== void 0) t.spawnSessions = o;
	if (n) e.changes.push(`Removed deprecated ${e.pathPrefix}.threadBindings.spawnSubagentSessions/spawnAcpSessions (${e.pathPrefix}.threadBindings.spawnSessions already set).`);
	else if (typeof r === "boolean" && typeof i === "boolean" && r !== i) e.changes.push(`Collapsed conflicting ${e.pathPrefix}.threadBindings.spawnSubagentSessions/spawnAcpSessions → ${e.pathPrefix}.threadBindings.spawnSessions (${String(o)}).`);
	else e.changes.push(`Moved ${e.pathPrefix}.threadBindings.spawnSubagentSessions/spawnAcpSessions → ${e.pathPrefix}.threadBindings.spawnSessions (${String(o)}).`);
}
function hasLegacyThreadBindingInAnyChannel(e) {
	let t = false;
	for (const n of Object.keys(asNullableRecord(e) ?? {})) {
		visitChannelEntries({ channels: e }, n, (e) => {
			t ||= hasLegacyThreadBindingSpawnSplit(e.threadBindings);
		});
		if (t) return true;
	}
	return false;
}
const LEGACY_CONFIG_MIGRATIONS_CHANNELS = [{
	id: "thread-bindings.spawn-sessions",
	legacyRules: [{
		path: ["session", "threadBindings"],
		message: "session.threadBindings.spawnSubagentSessions/spawnAcpSessions were replaced by session.threadBindings.spawnSessions. Run \"openclaw doctor --fix\".",
		match: hasLegacyThreadBindingSpawnSplit
	}, {
		path: ["channels"],
		message: "channels.<id>.threadBindings.spawnSubagentSessions/spawnAcpSessions were replaced by channels.<id>.threadBindings.spawnSessions. Run \"openclaw doctor --fix\".",
		match: hasLegacyThreadBindingInAnyChannel
	}],
	apply: (e, t) => {
		const n = asNullableRecord(e.session);
		if (n) migrateThreadBindingsSpawnSessionsForPath({
			owner: n,
			pathPrefix: "session",
			changes: t
		});
		const r = asNullableRecord(e.channels);
		if (!r) return;
		for (const n of Object.keys(r)) visitChannelEntries(e, n, (e, n) => {
			migrateThreadBindingsSpawnSessionsForPath({
				owner: e,
				pathPrefix: n,
				changes: t
			});
		});
	}
}];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.qqbot-account.ts
function hasEnvironmentValue(e) {
	return Boolean(process.env[e]?.trim());
}
function shouldCreateEnvironmentOnlyQQBotConfig(e) {
	const t = asNullableRecord(e.channels);
	return Boolean((e.channels === void 0 || t) && !asNullableRecord(t?.qqbot) && hasEnvironmentValue("QQBOT_APP_ID") && hasEnvironmentValue("QQBOT_CLIENT_SECRET"));
}
function listQQBotConfigEntries(e) {
	const t = structuredClone(e);
	const n = [{
		entry: e,
		path: "channels.qqbot"
	}];
	const r = asNullableRecord(e.accounts);
	if (!r) return n;
	for (const [e, i] of Object.entries(r)) {
		const r = asNullableRecord(i);
		if (r) n.push({
			entry: r,
			path: `channels.qqbot.accounts.${e}`,
			aliasSuffix: e,
			inheritedEntry: e === "default" ? t : void 0
		});
	}
	return n;
}
function migrateDefaultAccount(e, t) {
	const n = asNullableRecord(e.accounts);
	const r = typeof e.defaultAccount === "string" ? e.defaultAccount.trim() : "";
	const i = r.toLowerCase();
	const a = asNullableRecord(n?.default);
	if (r && i !== "default") {
		const o = i;
		const s = asNullableRecord(n?.[o]);
		if (!s) {
			delete e.defaultAccount;
			t.push(`Removed invalid channels.qqbot.defaultAccount=${r}; the bundled plugin already fell back to its normal account selection order.`);
			return;
		}
		if (e.appId || hasEnvironmentValue("QQBOT_APP_ID") || a) return;
		const c = { [o]: s };
		for (const [e, t] of Object.entries(n ?? {})) if (e !== o && !isBlockedObjectKey(e)) c[e] = t;
		if (Object.keys(c)[0] !== o) return;
		e.accounts = c;
		delete e.defaultAccount;
		t.push(`Moved channels.qqbot.accounts.${o} to the first account position and removed defaultAccount so Tencent QQBot 2.0 preserves the selected named default.`);
		return;
	}
	if (!n || !a) {
		if (Object.hasOwn(e, "defaultAccount")) {
			delete e.defaultAccount;
			t.push("Removed channels.qqbot.defaultAccount=default because Tencent QQBot 2.0 selects the root account directly.");
		}
		return;
	}
	for (const [t, n] of Object.entries(a)) if (t !== "accounts" && !isBlockedObjectKey(t)) e[t] = n;
	delete n.default;
	if (Object.keys(n).length === 0) delete e.accounts;
	delete e.defaultAccount;
	t.push("Moved channels.qqbot.accounts.default overrides to channels.qqbot for Tencent QQBot 2.0 default-account resolution.");
}
function normalizeProviderAliasSegment(e) {
	return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "account";
}
function isMatchingFileProvider(e, t) {
	const n = asNullableRecord(e);
	return Boolean(n && n.source === "file" && n.path === t && n.mode === "singleValue");
}
function allocateFileProviderAlias(e) {
	let t = e.raw;
	for (const e of ["secrets", "providers"]) {
		let n = asNullableRecord(t[e]);
		if (!n) {
			if (t[e] !== void 0) return;
			n = {};
			t[e] = n;
		}
		t = n;
	}
	const n = `qqbot${e.aliasSuffix ? `-${normalizeProviderAliasSegment(e.aliasSuffix)}` : ""}-client-secret`.slice(0, 60).replace(/-+$/g, "");
	for (let r = 1; r <= 999; r += 1) {
		const i = r === 1 ? n : `${n.slice(0, 60 - String(r).length)}-${r}`;
		const a = t[i];
		if (a === void 0) {
			t[i] = {
				source: "file",
				path: e.filePath,
				mode: "singleValue"
			};
			return i;
		}
		if (isMatchingFileProvider(a, e.filePath)) return i;
	}
}
function migrateClientSecretFile(e) {
	if (!Object.hasOwn(e.entry, "clientSecretFile")) return;
	if (e.entry.clientSecret !== void 0) {
		delete e.entry.clientSecretFile;
		e.changes.push(`Removed ${e.path}.clientSecretFile (${e.path}.clientSecret already set).`);
		return;
	}
	const t = typeof e.entry.clientSecretFile === "string" ? e.entry.clientSecretFile.trim() : "";
	if (!t) {
		e.entry.enabled = false;
		delete e.entry.clientSecretFile;
		e.changes.push(`Removed invalid ${e.path}.clientSecretFile and disabled this QQBot account.`);
		return;
	}
	const n = allocateFileProviderAlias({
		raw: e.raw,
		filePath: t,
		aliasSuffix: e.aliasSuffix
	});
	if (!n) {
		e.entry.enabled = false;
		e.changes.push(`Disabled ${e.path} because its clientSecretFile could not be migrated while secrets.providers has an incompatible shape.`);
		return;
	}
	e.entry.clientSecret = {
		source: "file",
		provider: n,
		id: "value"
	};
	delete e.entry.clientSecretFile;
	e.changes.push(`Moved ${e.path}.clientSecretFile → ${e.path}.clientSecret using file provider ${n}.`);
}
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.qqbot.ts
const APPROVALS_DISABLED_SENTINEL = "openclaw:approval-disabled";
function hasQQBotEntryMatching(e, t) {
	const n = asNullableRecord(e);
	return Boolean(n && listQQBotConfigEntries(n).some(({ entry: e, inheritedEntry: n }) => t(e, n)));
}
function qqbotEntryRule(e, t) {
	return {
		path: ["channels", "qqbot"],
		message: e,
		match: (e) => hasQQBotEntryMatching(e, t)
	};
}
function normalizeIds(e) {
	return normalizeUniqueStringEntries(Array.isArray(e) ? e.filter((e) => typeof e === "string" || typeof e === "number") : []);
}
function normalizeLegacyAllowFrom(e) {
	return uniqueStrings(normalizeIds(e).map((e) => {
		const t = e.replace(/^qqbot:/i, "");
		if (t === "*" || t === APPROVALS_DISABLED_SENTINEL) return t;
		return t.toUpperCase();
	}));
}
function resolveLegacyQQBotCommandsAllowFrom(e) {
	const t = asNullableRecord(e.commands);
	const n = asNullableRecord(t?.allowFrom);
	if (!n) return;
	if (Array.isArray(n.qqbot)) return normalizeLegacyAllowFrom(n.qqbot);
	return Array.isArray(n["*"]) ? normalizeLegacyAllowFrom(n["*"]) : void 0;
}
function hasConfiguredFilter(e) {
	return Array.isArray(e) ? e.length > 0 : e !== void 0;
}
function migrateExecApprovals(e) {
	const t = Object.hasOwn(e.entry, "execApprovals");
	const n = t || e.inheritedEntry?.execApprovals !== void 0;
	const r = t || Object.hasOwn(e.entry, "allowFrom") || Object.hasOwn(e.entry, "dmPolicy");
	if (e.inheritedEntry && !r) return;
	const i = asNullableRecord(t ? e.entry.execApprovals : e.inheritedEntry?.execApprovals);
	const a = Object.hasOwn(e.entry, "allowFrom") ? e.entry.allowFrom : e.inheritedEntry?.allowFrom;
	const o = Object.hasOwn(e.entry, "dmPolicy") ? e.entry.dmPolicy : e.inheritedEntry?.dmPolicy;
	const s = normalizeLegacyAllowFrom(a);
	const c = normalizeLegacyAllowFrom(i?.approvers);
	const l = s.length === 0 || s.includes("*");
	const u = o === "open" || o === void 0 && l || o === "allowlist" && s.includes("*");
	if (!n) {
		if (e.commandsAllowFrom !== void 0) {
			const t = e.commandsAllowFrom.filter((e) => e !== "*");
			const n = new Set(s.filter((e) => e !== "*"));
			const r = s.length > 0 && !s.includes("*") ? t.filter((e) => n.has(e)) : t;
			const i = r.length > 0 ? r : [APPROVALS_DISABLED_SENTINEL];
			const a = u && o !== "open";
			if (s.length === i.length && s.every((e, t) => e === i[t]) && !a) return;
			e.entry.allowFrom = i;
			if (a) e.entry.dmPolicy = "open";
			e.changes.push(`Secured ${e.path}.allowFrom for Tencent QQBot 2.0 native approvals using the previous commands.allowFrom operator list${r.length > 0 ? " intersected with restrictive chat access" : "; no safely representable operator remained, so approvals were locked"}.`);
			return;
		}
		if (!l) return;
		const t = s.filter((e) => e !== "*");
		e.entry.allowFrom = t.length > 0 ? t : [APPROVALS_DISABLED_SENTINEL];
		if (u) e.entry.dmPolicy = "open";
		e.changes.push(`Secured ${e.path}.allowFrom for Tencent QQBot 2.0 native approvals; wildcard/empty approval access was replaced with ${t.length > 0 ? "the existing explicit IDs" : "a non-matching marker"} while preserving open DM access separately.`);
		return;
	}
	const d = !i || i.enabled === false || hasConfiguredFilter(i.agentFilter) || hasConfiguredFilter(i.sessionFilter) || i.target !== void 0;
	let f;
	let p;
	if (d || c.includes("*")) {
		f = [APPROVALS_DISABLED_SENTINEL];
		p = "the Tencent 2.0 plugin cannot represent the previous approval policy, so native approval actions were locked";
	} else if (c.length > 0) {
		const e = new Set(s.filter((e) => e !== "*"));
		f = o === "allowlist" && s.length === 0 ? [] : s.length > 0 && !s.includes("*") ? c.filter((t) => e.has(t)) : c;
		if (f.length === 0) {
			f = [APPROVALS_DISABLED_SENTINEL];
			p = "the approval and chat allowlists did not overlap, so native approval actions were locked";
		} else p = "approval access was intersected with the existing chat allowlist";
	} else if (s.length > 0 && !s.includes("*")) {
		f = s;
		p = "the existing restrictive chat allowlist remains the approval allowlist";
	} else {
		f = [APPROVALS_DISABLED_SENTINEL];
		p = "the previous same-chat or wildcard policy has no safe Tencent 2.0 representation, so native approval actions were locked";
	}
	if (u && !f.includes("*")) e.entry.dmPolicy = "open";
	e.entry.allowFrom = f;
	delete e.entry.execApprovals;
	e.changes.push(`Moved ${e.path}.execApprovals → ${e.path}.allowFrom; ${p}. Review chat access before re-enabling broader approval access.`);
}
function migrateAllowFrom(e) {
	const t = normalizeIds(e.entry.allowFrom);
	const n = normalizeLegacyAllowFrom(e.entry.allowFrom);
	if (t.every((e, t) => e === n[t])) return;
	e.entry.allowFrom = n;
	e.changes.push(`Normalized ${e.path}.allowFrom QQBot-prefixed IDs for Tencent QQBot 2.0.`);
}
function hasLegacyStreamingTransport(e) {
	const t = asNullableRecord(e.streaming);
	return Boolean(t && (Object.hasOwn(t, "nativeTransport") || Object.hasOwn(t, "c2cStreamApi")));
}
function migrateStreamingTransport(e) {
	const t = asNullableRecord(e.entry.streaming);
	if (!t || !hasLegacyStreamingTransport(e.entry)) return;
	const n = typeof t.nativeTransport === "boolean" ? t.nativeTransport : typeof t.c2cStreamApi === "boolean" ? t.c2cStreamApi : void 0;
	delete t.nativeTransport;
	delete t.c2cStreamApi;
	if (n !== void 0) t.mode = n ? "partial" : "off";
	e.changes.push(`Removed unsupported ${e.path}.streaming native transport keys for Tencent QQBot 2.0${n === void 0 ? "" : ` and set mode=${String(t.mode)}`}.`);
}
function mapTencentToolPolicy(e) {
	const t = asNullableRecord(e);
	const n = Array.isArray(t?.allow) ? t.allow.map(String) : void 0;
	const r = Array.isArray(t?.deny) ? t.deny.map(String) : void 0;
	const i = !n || n.length === 0 || n.includes("*");
	if (i && (!r || r.length === 0)) return "full";
	if (r?.length === 1 && r[0] === "*") return "none";
	if (i && r?.length === 3 && [
		"exec",
		"read",
		"write"
	].every((e) => r.includes(e))) return "restricted";
	return "none";
}
function mostRestrictiveTencentToolPolicy(e, t) {
	const n = {
		none: 0,
		restricted: 1,
		full: 2
	};
	const r = e === "full" || e === "restricted" || e === "none" ? e : "none";
	return n[r] <= n[t] ? r : t;
}
function migrateGroupTools(e) {
	const t = asNullableRecord(e.entry.groups);
	if (!t) return;
	for (const [n, r] of Object.entries(t)) {
		const t = asNullableRecord(r);
		if (!t || !Object.hasOwn(t, "tools") && !Object.hasOwn(t, "toolsBySender")) continue;
		const i = `${e.path}.groups.${n}`;
		const a = Object.hasOwn(t, "toolsBySender") ? "none" : mapTencentToolPolicy(t.tools);
		t.toolPolicy = t.toolPolicy === void 0 ? a : mostRestrictiveTencentToolPolicy(t.toolPolicy, a);
		e.changes.push(`Moved ${i}.tools policy → ${i}.toolPolicy=${String(t.toolPolicy)} for Tencent QQBot 2.0, preserving the most restrictive configured policy.`);
		delete t.tools;
		if (Object.hasOwn(t, "toolsBySender")) {
			delete t.toolsBySender;
			e.changes.push(`Removed ${i}.toolsBySender; Tencent QQBot 2.0 cannot represent sender-specific tool policy, so the group policy was not broadened.`);
		}
	}
}
function someQQBotGroup(e, t) {
	return Object.values(asNullableRecord(e?.groups) ?? {}).some((e) => {
		const n = asNullableRecord(e);
		return Boolean(n && t(n));
	});
}
function migrateGroupCommandLevels(e) {
	const t = asNullableRecord(e.entry.groups);
	if (!t) {
		if (someQQBotGroup(e.inheritedEntry, (e) => Object.hasOwn(e, "commandLevel") && e.commandLevel !== "all") && e.entry.groupPolicy !== void 0 && e.entry.groupPolicy !== "disabled") {
			e.entry.groupPolicy = "disabled";
			e.changes.push(`Set ${e.path}.groupPolicy=disabled because this default account overrides the root lock while inheriting a safety/strict group command policy that Tencent QQBot 2.0 cannot represent.`);
		}
		return;
	}
	let n = false;
	for (const [r, i] of Object.entries(t)) {
		const t = asNullableRecord(i);
		if (!t || !Object.hasOwn(t, "commandLevel")) continue;
		const a = t.commandLevel;
		if (a !== "all") n = true;
		delete t.commandLevel;
		e.changes.push(`Removed unsupported ${e.path}.groups.${r}.commandLevel=${String(a)} for Tencent QQBot 2.0.`);
	}
	if (!n) return;
	e.entry.groupPolicy = "disabled";
	e.changes.push(`Set ${e.path}.groupPolicy=disabled because Tencent QQBot 2.0 cannot represent a previous safety/strict group command policy. Review the account before re-enabling group access.`);
}
const LEGACY_CONFIG_MIGRATIONS_QQBOT = [{
	id: "qqbot.tencent-2.0-compatibility",
	legacyRules: [
		{
			path: [],
			message: "Environment-only QQBot credentials need a safe Tencent QQBot 2.0 config shell. Run \"openclaw doctor --fix\".",
			match: (e, t) => shouldCreateEnvironmentOnlyQQBotConfig(t)
		},
		{
			path: ["channels", "qqbot"],
			message: "QQBot defaultAccount/accounts.default must migrate to Tencent QQBot 2.0 account selection. Run \"openclaw doctor --fix\".",
			match: (e) => {
				const t = asNullableRecord(e);
				return Boolean(t && (Object.hasOwn(t, "defaultAccount") || asNullableRecord(asNullableRecord(t.accounts)?.default)));
			}
		},
		qqbotEntryRule("QQBot clientSecretFile must migrate to a file-backed SecretRef for Tencent QQBot 2.0. Run \"openclaw doctor --fix\".", (e) => Object.hasOwn(e, "clientSecretFile")),
		qqbotEntryRule("QQBot wildcard/empty allowFrom must be separated from Tencent QQBot 2.0 native approval access. Run \"openclaw doctor --fix\".", (e, t) => {
			if (Object.hasOwn(e, "execApprovals")) return false;
			const n = normalizeLegacyAllowFrom(Object.hasOwn(e, "allowFrom") ? e.allowFrom : t?.allowFrom);
			return n.length === 0 || n.includes("*");
		}),
		{
			path: ["channels", "qqbot"],
			message: "QQBot chat allowFrom must be reconciled with the previous commands.allowFrom approval operators for Tencent QQBot 2.0. Run \"openclaw doctor --fix\".",
			match: (e, t) => {
				const n = resolveLegacyQQBotCommandsAllowFrom(t);
				if (n === void 0) return false;
				const r = new Set(n.filter((e) => e !== "*"));
				return hasQQBotEntryMatching(e, (e, t) => {
					if (Object.hasOwn(e, "execApprovals") || !Object.hasOwn(e, "allowFrom") && t?.execApprovals !== void 0) return false;
					return normalizeLegacyAllowFrom(Object.hasOwn(e, "allowFrom") ? e.allowFrom : t?.allowFrom).filter((e) => e !== "*" && e !== APPROVALS_DISABLED_SENTINEL).some((e) => !r.has(e));
				});
			}
		},
		qqbotEntryRule("QQBot groups.*.commandLevel must migrate before Tencent QQBot 2.0 can safely handle group commands. Run \"openclaw doctor --fix\".", (e) => someQQBotGroup(e, (e) => Object.hasOwn(e, "commandLevel"))),
		qqbotEntryRule("QQBot streaming.nativeTransport/c2cStreamApi must migrate to Tencent QQBot 2.0 streaming.mode. Run \"openclaw doctor --fix\".", hasLegacyStreamingTransport),
		qqbotEntryRule("QQBot allowFrom IDs must migrate to Tencent QQBot 2.0 uppercase OpenIDs. Run \"openclaw doctor --fix\".", (e) => {
			const t = normalizeIds(e.allowFrom);
			const n = normalizeLegacyAllowFrom(e.allowFrom);
			return t.length !== n.length || t.some((e, t) => e !== n[t]);
		}),
		qqbotEntryRule("QQBot execApprovals must migrate to Tencent QQBot 2.0 allowFrom semantics. Run \"openclaw doctor --fix\".", (e) => Object.hasOwn(e, "execApprovals")),
		qqbotEntryRule("QQBot group tools policies must migrate to Tencent QQBot 2.0 toolPolicy. Run \"openclaw doctor --fix\".", (e) => someQQBotGroup(e, (e) => Object.hasOwn(e, "tools") || Object.hasOwn(e, "toolsBySender")))
	],
	apply: (e, t) => {
		let n = asNullableRecord(e.channels);
		let r = asNullableRecord(n?.qqbot);
		if (!r && shouldCreateEnvironmentOnlyQQBotConfig(e)) {
			n ??= {};
			e.channels = n;
			r = {
				enabled: true,
				dmPolicy: "open",
				allowFrom: [APPROVALS_DISABLED_SENTINEL]
			};
			n.qqbot = r;
			t.push("Created channels.qqbot for environment-only Tencent QQBot 2.0 credentials with native approvals locked; no credential value was copied into config.");
		}
		if (!r) return;
		migrateDefaultAccount(r, t);
		const i = resolveLegacyQQBotCommandsAllowFrom(e);
		for (const n of listQQBotConfigEntries(r)) {
			migrateClientSecretFile({
				raw: e,
				changes: t,
				...n
			});
			migrateExecApprovals({
				changes: t,
				commandsAllowFrom: i,
				...n
			});
			migrateAllowFrom({
				changes: t,
				...n
			});
			migrateStreamingTransport({
				changes: t,
				...n
			});
			migrateGroupTools({
				changes: t,
				...n
			});
			migrateGroupCommandLevels({
				changes: t,
				...n
			});
		}
	}
}];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.agents.ts
const LEGACY_MEMORY_SEARCH_FIELD_MAPPINGS = [
	{
		legacyKey: "chunkSize",
		parentKey: "chunking",
		canonicalKey: "tokens"
	},
	{
		legacyKey: "chunkOverlap",
		parentKey: "chunking",
		canonicalKey: "overlap"
	},
	{
		legacyKey: "maxResults",
		parentKey: "query",
		canonicalKey: "maxResults"
	}
];
function hasLegacyMemorySearchFlatKeys(e) {
	const t = asNullableRecord(e);
	return Boolean(t && LEGACY_MEMORY_SEARCH_FIELD_MAPPINGS.some(({ legacyKey: e }) => Object.hasOwn(t, e)));
}
function getAgentMemorySearchRecord(e) {
	return asNullableRecord(e.memorySearch) ?? asNullableRecord(asNullableRecord(e.memory)?.search);
}
function isLegacyMemorySearchAutoProvider(e) {
	return typeof e === "string" && e.trim().toLowerCase() === "auto";
}
function migrateLegacyMemorySearchFlatKeys(e, t, n) {
	if (!e) return;
	for (const { legacyKey: r, parentKey: i, canonicalKey: a } of LEGACY_MEMORY_SEARCH_FIELD_MAPPINGS) {
		if (!Object.hasOwn(e, r)) continue;
		const o = e[r];
		if (e[i] === void 0) e[i] = {};
		const s = asNullableRecord(e[i]);
		if (!s) n.push(`Removed ${t}.${r} (${t}.${i} already set).`);
		else if (s[a] === void 0) {
			s[a] = o;
			n.push(`Moved ${t}.${r} → ${t}.${i}.${a}.`);
		} else n.push(`Removed ${t}.${r} (${t}.${i}.${a} already set).`);
		delete e[r];
	}
}
function rewriteLegacyMemorySearchAutoProvider(e, t, n) {
	if (!e || !isLegacyMemorySearchAutoProvider(e.provider)) return;
	e.provider = "openai";
	n.push(`Moved ${t}.provider from legacy "auto" to "openai".`);
}
function migrateCanonicalMemorySearches(e, t, n) {
	n(asNullableRecord(asNullableRecord(e.memory)?.search), "memory.search", t);
	visitAgentEntries(e, (e, r) => {
		n(asNullableRecord(asNullableRecord(e.memory)?.search), `${r}.memory.search`, t);
	});
}
function getSandboxBrowserConfig(e) {
	return asNullableRecord(asNullableRecord(asNullableRecord(e)?.sandbox)?.browser);
}
function isUnsupportedSandboxBrowserNetwork(e) {
	return normalizeOptionalLowercaseString(e) === "none";
}
function migrateExplicitUnsupportedSandboxBrowserNetwork(e, t, n) {
	if (!isUnsupportedSandboxBrowserNetwork(e.network)) return;
	e.enabled = false;
	e.network = DEFAULT_SANDBOX_BROWSER_NETWORK;
	n.push(`Disabled ${t} and moved its unsupported network "none" → "${DEFAULT_SANDBOX_BROWSER_NETWORK}".`);
}
function migrateUnsupportedSandboxBrowserNetworks(e, t) {
	const n = asNullableRecord(e.agents);
	const r = getSandboxBrowserConfig(asNullableRecord(n?.defaults));
	const i = isUnsupportedSandboxBrowserNetwork(r?.network);
	const a = r?.enabled === true;
	visitAgentEntries(e, (e, n) => {
		const r = getSandboxBrowserConfig(e);
		if (!r) return;
		const o = `${n}.sandbox.browser`;
		if (isUnsupportedSandboxBrowserNetwork(r.network)) {
			migrateExplicitUnsupportedSandboxBrowserNetwork(r, o, t);
			return;
		}
		if (!i) return;
		const s = typeof r.network === "string";
		if (!s && r.enabled === true) {
			r.enabled = false;
			t.push(`Disabled ${o} because it inherited unsupported browser network "none".`);
		} else if (s && r.enabled === void 0 && a) {
			r.enabled = true;
			t.push(`Set ${o}.enabled to true to preserve its explicit supported network while disabling the unsupported default browser network.`);
		}
	});
	if (r) migrateExplicitUnsupportedSandboxBrowserNetwork(r, "agents.defaults.sandbox.browser", t);
}
function hasOwnRecordProperty(e, t) {
	const n = asNullableRecord(e);
	return Boolean(n && Object.hasOwn(n, t));
}
function hasSurfaceLegacySilentReplyPolicy(e) {
	const t = asNullableRecord(e);
	if (!t) return false;
	return Object.entries(t).some(([e, t]) => !isBlockedObjectKey(e) && hasOwnRecordProperty(asNullableRecord(t)?.silentReply, "internal"));
}
function removeLegacySilentReplyConfig(e, t) {
	const n = [["agents.defaults", asNullableRecord(e.agents)?.defaults]];
	for (const [t, r] of Object.entries(asNullableRecord(e.surfaces) ?? {})) if (!isBlockedObjectKey(t)) n.push([`surfaces.${t}`, r]);
	for (const [e, r] of n) {
		const n = asNullableRecord(r);
		if (!n) continue;
		const i = asNullableRecord(n.silentReply);
		if (i && Object.hasOwn(i, "internal")) {
			delete i.internal;
			t.push(`Removed ${e}.silentReply.internal; internal sessions never use NO_REPLY.`);
		}
	}
}
const CONFIGURED_TOOL_SECTION_GRANTS = [{
	key: "exec",
	grants: ["exec", "process"]
}, {
	key: "fs",
	grants: [
		"read",
		"write",
		"edit"
	]
}];
function readToolPolicyGrantList(e, t) {
	return readOwnToolPolicyGrantList(e, t) ?? [];
}
function readOwnToolPolicyGrantList(e, t) {
	const n = asNullableRecord(e);
	return Array.isArray(n?.[t]) ? n[t].filter((e) => typeof e === "string") : void 0;
}
function resolveToolProfileForMigration(e, t) {
	return typeof e?.profile === "string" ? e.profile : t;
}
function collectProfileConfiguredSectionRepairGrants(e) {
	const t = asNullableRecord(e.value);
	if (!t) return [];
	const n = resolveToolProfileForMigration(t, e.inheritedProfile);
	if (!n || n === "full") return [];
	const r = readToolPolicyGrantList(t, "allow");
	if (r.length === 0) return [];
	const i = readOwnToolPolicyGrantList(t, "alsoAllow");
	const a = { allow: uniqueStrings([...r, ...i ?? []]) };
	const o = mergeAlsoAllowPolicy(resolveCoreToolProfilePolicy(n), i ?? e.inheritedAlsoAllow ?? []);
	return uniqueStrings(e.configuredGrants.filter((e) => isToolAllowedByPolicyName(e, a) && (!isToolAllowedByPolicyName(e, o) || (i ? isToolAllowedByPolicyName(e, { allow: i }) : false))));
}
function toolProfileConfiguredSectionsNeedExplicitRepair(e, t, n, r, i) {
	const a = asNullableRecord(e);
	if (!a) return false;
	const o = r ?? collectConfiguredToolSectionGrants(a);
	return collectProfileConfiguredSectionRepairGrants({
		value: e,
		inheritedProfile: t,
		inheritedAlsoAllow: n,
		configuredGrants: o
	}).length > 0 || byProviderToolProfilesNeedConfiguredSectionMigration(a, o, readOwnToolPolicyGrantList(a, "alsoAllow") ?? n, i);
}
function collectConfiguredToolSectionGrants(e) {
	const t = [];
	for (const n of CONFIGURED_TOOL_SECTION_GRANTS) if (asNullableRecord(e[n.key])) t.push(...n.grants);
	return uniqueStrings(t);
}
function collectEffectiveConfiguredToolSectionGrants(e, t) {
	const n = typeof t?.profile !== "string";
	return uniqueStrings([...n && e ? collectConfiguredToolSectionGrants(e) : [], ...t ? collectConfiguredToolSectionGrants(t) : []]);
}
function resolveProfileBoundAllowGrants(e) {
	const t = readOwnToolPolicyGrantList(e.tools, "alsoAllow");
	const n = mergeAlsoAllowPolicy(resolveCoreToolProfilePolicy(e.profile), t ?? e.inheritedAlsoAllow ?? []);
	const r = expandToolGroups(n?.allow);
	const i = r.includes("*") ? expandToolGroups(e.allow) : r.filter((t) => isToolAllowedByPolicyName(t, { allow: e.allow }));
	const a = expandToolGroups(e.allow).filter((e) => {
		if (e === "*" || isKnownCoreToolId(e)) return false;
		return !r.some((t) => isToolAllowedByPolicyName(t, { allow: [e] }));
	});
	return uniqueStrings([
		...i,
		...a,
		...e.configuredGrants
	]);
}
function byProviderToolProfilesNeedConfiguredSectionMigration(e, t, n, r) {
	const i = asNullableRecord(e.byProvider);
	return Boolean(i && Object.entries(i).some(([e, i]) => {
		const a = resolveInheritedProviderPolicy(r, e);
		const o = resolveToolProfileForMigration(a);
		if (!(typeof asNullableRecord(i)?.profile === "string" || Boolean(o))) return false;
		return collectProfileConfiguredSectionRepairGrants({
			value: i,
			inheritedProfile: o,
			inheritedAlsoAllow: readOwnToolPolicyGrantList(a, "alsoAllow") ?? n,
			configuredGrants: t
		}).length > 0;
	}));
}
function addProfileConfiguredSectionGrants(e, t, n, r, i, a) {
	const o = asNullableRecord(e);
	if (!o) return;
	const s = resolveToolProfileForMigration(o, r);
	if (!s) return;
	const c = collectProfileConfiguredSectionRepairGrants({
		value: o,
		inheritedProfile: r,
		inheritedAlsoAllow: i,
		configuredGrants: a ?? collectConfiguredToolSectionGrants(o)
	});
	const l = readToolPolicyGrantList(o, "allow");
	if (c.length === 0) return;
	const u = readOwnToolPolicyGrantList(o, "alsoAllow");
	o.allow = resolveProfileBoundAllowGrants({
		tools: o,
		profile: s,
		allow: uniqueStrings([...l, ...u ?? []]),
		inheritedAlsoAllow: i,
		configuredGrants: c
	});
	n.push(`Replaced ${t}.allow entries with profile "${s}" grants plus explicit configured-section grants.`);
	if (u) {
		delete o.alsoAllow;
		n.push(`Merged ${t}.alsoAllow into ${t}.allow.`);
	}
	o.profile = "full";
	n.push(`Set ${t}.profile to "full" so ${t}.allow controls explicit configured-section grants directly.`);
}
function addByProviderProfileConfiguredSectionGrants(e, t, n, r, i) {
	const a = asNullableRecord(e);
	if (!a) return;
	const o = r ?? collectConfiguredToolSectionGrants(a);
	if (o.length === 0) return;
	const s = asNullableRecord(a.byProvider);
	for (const [e, r] of Object.entries(s ?? {})) {
		if (isBlockedObjectKey(e)) continue;
		const a = resolveInheritedProviderPolicy(i, e);
		const s = typeof asNullableRecord(r)?.profile === "string";
		const c = resolveToolProfileForMigration(a);
		if (!s && !c) continue;
		const l = readOwnToolPolicyGrantList(a, "alsoAllow");
		addProfileConfiguredSectionGrants(r, `${t}.byProvider.${e}`, n, c, l, o);
	}
}
function resolveInheritedProviderPolicy(e, t) {
	const n = normalizeToolProviderPolicyKey(t);
	const r = n.indexOf("/");
	const i = Object.fromEntries(Object.entries(e ?? {}).filter(([e]) => !isBlockedObjectKey(e)));
	return asNullableRecord(resolveProviderToolPolicy({
		byProvider: i,
		modelProvider: n
	}) ?? (r > 0 ? resolveProviderToolPolicy({
		byProvider: i,
		modelProvider: n.slice(0, r)
	}) : void 0));
}
function bindingMatchHasLegacyDmPeerKind(e) {
	const t = asNullableRecord(asNullableRecord(e)?.match);
	const n = asNullableRecord(t?.peer);
	return n !== null && n.kind === "dm";
}
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_AGENTS = [
	{
		id: "bindings.match.peer.kind.dm-to-direct",
		legacyRules: [{
			path: ["bindings"],
			message: "bindings[].match.peer.kind uses the retired \"dm\" alias; use \"direct\". Run \"openclaw doctor --fix\".",
			match: (e) => Array.isArray(e) && e.some((e) => bindingMatchHasLegacyDmPeerKind(e))
		}],
		apply: (e, t) => {
			if (!Array.isArray(e.bindings)) return;
			let n = 0;
			for (const t of e.bindings) {
				const e = asNullableRecord(asNullableRecord(t)?.match);
				const r = asNullableRecord(e?.peer);
				if (r !== null && r.kind === "dm") {
					r.kind = "direct";
					n += 1;
				}
			}
			if (n > 0) t.push(`Moved deprecated bindings[].match.peer.kind "dm" → "direct" for ${n} binding${n === 1 ? "" : "s"}.`);
		}
	},
	{
		id: "tools.profile-configured-sections-alsoAllow",
		legacyRules: [{
			path: ["tools"],
			message: "tools.profile filters explicit configured-section tool grants; run \"openclaw doctor --fix\" to rewrite the explicit grants into a valid allowlist.",
			match: (e) => toolProfileConfiguredSectionsNeedExplicitRepair(e)
		}, {
			path: ["agents"],
			message: "agents.entries.*.tools.profile filters explicit configured-section tool grants; run \"openclaw doctor --fix\" to rewrite the explicit grants into a valid allowlist.",
			match: (e, t) => {
				const n = asNullableRecord(t.tools);
				const r = resolveToolProfileForMigration(n);
				const i = readToolPolicyGrantList(n, "alsoAllow");
				return someAgentEntry(e, (e) => {
					const t = asNullableRecord(e.tools);
					return toolProfileConfiguredSectionsNeedExplicitRepair(t, r, i, collectEffectiveConfiguredToolSectionGrants(n, t), asNullableRecord(n?.byProvider));
				});
			}
		}],
		apply: (e, t) => {
			const n = asNullableRecord(e.tools);
			const r = resolveToolProfileForMigration(n);
			const i = readToolPolicyGrantList(n, "alsoAllow");
			addProfileConfiguredSectionGrants(e.tools, "tools", t);
			addByProviderProfileConfiguredSectionGrants(e.tools, "tools", t);
			visitAgentEntries(e, (e, a) => {
				const o = asNullableRecord(e.tools);
				const s = collectEffectiveConfiguredToolSectionGrants(n, o);
				addProfileConfiguredSectionGrants(o, `${a}.tools`, t, r, i, s);
				addByProviderProfileConfiguredSectionGrants(o, `${a}.tools`, t, s, asNullableRecord(n?.byProvider));
			});
		}
	},
	{
		id: "silentReply.internal-removed",
		legacyRules: [{
			path: [
				"agents",
				"defaults",
				"silentReply"
			],
			message: "agents.defaults.silentReply.internal was removed; only channel groups may use NO_REPLY. Run \"openclaw doctor --fix\" to remove it.",
			match: (e) => hasOwnRecordProperty(e, "internal")
		}, {
			path: ["surfaces"],
			message: "surfaces.*.silentReply.internal was removed; only channel groups may use NO_REPLY. Run \"openclaw doctor --fix\" to remove it.",
			match: (e) => hasSurfaceLegacySilentReplyPolicy(e)
		}],
		apply: removeLegacySilentReplyConfig
	},
	{
		id: "agents.sandbox.browser.network-none",
		legacyRules: [{
			path: [
				"agents",
				"defaults",
				"sandbox",
				"browser",
				"network"
			],
			message: "agents.defaults.sandbox.browser.network = \"none\" cannot expose the browser control port. Run \"openclaw doctor --fix\" to disable the sidecar and restore the dedicated browser network.",
			match: isUnsupportedSandboxBrowserNetwork
		}, {
			path: ["agents"],
			message: "agents.entries.*.sandbox.browser.network = \"none\" cannot expose the browser control port. Run \"openclaw doctor --fix\" to disable the affected sidecar and restore the dedicated browser network.",
			match: (e) => someAgentEntry(e, (e) => isUnsupportedSandboxBrowserNetwork(getSandboxBrowserConfig(e)?.network))
		}],
		apply: migrateUnsupportedSandboxBrowserNetworks
	},
	{
		id: "memorySearch->memory.search",
		legacyRules: [
			{
				path: ["memorySearch"],
				message: "top-level memorySearch was moved; use memory.search instead. Run \"openclaw doctor --fix\"."
			},
			{
				path: [
					"agents",
					"defaults",
					"memorySearch"
				],
				message: "agents.defaults.memorySearch moved to memory.search. Run \"openclaw doctor --fix\"."
			},
			{
				path: ["agents"],
				message: "agents.entries.*.memorySearch moved to agents.entries.*.memory.search. Run \"openclaw doctor --fix\".",
				match: (e) => someAgentEntry(e, (e) => e.memorySearch !== void 0)
			}
		],
		apply: (e, t) => {
			const n = asNullableRecord(e.agents);
			const r = asNullableRecord(n?.defaults);
			const i = asNullableRecord(r?.memorySearch);
			const a = asNullableRecord(e.memorySearch);
			const o = asNullableRecord(e.memory);
			const s = asNullableRecord(o?.search);
			if (i || a) {
				const n = structuredClone(s ?? {});
				if (i) {
					mergeMissing(n, i);
					delete r.memorySearch;
				}
				if (a) {
					mergeMissing(n, a);
					delete e.memorySearch;
				}
				ensureRecord(e, "memory").search = n;
				t.push(s ? "Merged legacy memorySearch defaults → memory.search (kept explicit memory.search values)." : "Moved legacy memorySearch defaults → memory.search.");
			}
			visitAgentEntries(e, (e, n) => {
				const r = asNullableRecord(e.memorySearch);
				if (!r) return;
				const i = ensureRecord(e, "memory");
				const a = asNullableRecord(i.search);
				const o = structuredClone(a ?? {});
				mergeMissing(o, r);
				i.search = o;
				delete e.memorySearch;
				t.push(a ? `Merged ${n}.memorySearch → ${n}.memory.search (kept explicit memory.search values).` : `Moved ${n}.memorySearch → ${n}.memory.search.`);
			});
		}
	},
	{
		id: "memorySearch.flat-fields->nested-fields",
		legacyRules: [{
			path: ["memory", "search"],
			message: "memory.search uses legacy flat chunkSize, chunkOverlap, or maxResults fields. Run \"openclaw doctor --fix\".",
			match: hasLegacyMemorySearchFlatKeys
		}, {
			path: ["agents"],
			message: "agents.entries.*.memorySearch uses legacy flat chunkSize, chunkOverlap, or maxResults fields. Run \"openclaw doctor --fix\".",
			match: (e) => someAgentEntry(e, (e) => hasLegacyMemorySearchFlatKeys(getAgentMemorySearchRecord(e)))
		}],
		apply: (e, t) => migrateCanonicalMemorySearches(e, t, migrateLegacyMemorySearchFlatKeys)
	},
	{
		id: "memorySearch.provider-auto->openai",
		legacyRules: [
			{
				path: ["memorySearch", "provider"],
				message: "memorySearch.provider = \"auto\" is legacy; use \"openai\" explicitly. Run \"openclaw doctor --fix\".",
				match: isLegacyMemorySearchAutoProvider
			},
			{
				path: [
					"memory",
					"search",
					"provider"
				],
				message: "memory.search.provider = \"auto\" is legacy; use \"openai\" explicitly. Run \"openclaw doctor --fix\".",
				match: isLegacyMemorySearchAutoProvider
			},
			{
				path: ["agents"],
				message: "agents.entries.*.memorySearch.provider = \"auto\" is legacy; use \"openai\" explicitly. Run \"openclaw doctor --fix\".",
				match: (e) => someAgentEntry(e, (e) => isLegacyMemorySearchAutoProvider(getAgentMemorySearchRecord(e)?.provider))
			}
		],
		apply: (e, t) => migrateCanonicalMemorySearches(e, t, rewriteLegacyMemorySearchAutoProvider)
	},
	{
		id: "session.typingMode->agents.defaults.typingMode",
		legacyRules: [{
			path: ["session", "typingMode"],
			message: "session.typingMode moved to agents.defaults.typingMode. Run \"openclaw doctor --fix\"."
		}],
		apply: (e, t) => {
			const n = asNullableRecord(e.session);
			if (!n || !Object.hasOwn(n, "typingMode")) return;
			const r = ensureRecord(ensureRecord(e, "agents"), "defaults");
			const i = r.typingMode !== void 0;
			r.typingMode = n.typingMode;
			t.push(i ? "Moved session.typingMode → agents.defaults.typingMode (replaced the previously shadowed agent default)." : "Moved session.typingMode → agents.defaults.typingMode.");
			delete n.typingMode;
		}
	}
];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.cli-backends.ts
const CLI_BACKENDS_PLUGIN_GUIDE = "https://docs.openclaw.ai/plugins/cli-backend-plugins";
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_CLI_BACKENDS = [{
	id: "agents.defaults.cliBackends-plugin-registration",
	legacyRules: [{
		path: [
			"agents",
			"defaults",
			"cliBackends"
		],
		message: `CLI backend adapters now register through plugins; see ${CLI_BACKENDS_PLUGIN_GUIDE}`
	}],
	apply: (e, t) => {
		if (deleteRetiredPath(asNullableRecord(e.agents)?.defaults, ["cliBackends"])) t.push(`Removed agents.defaults.cliBackends; CLI backend adapters now register through plugins (${CLI_BACKENDS_PLUGIN_GUIDE}).`);
	}
}];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.code-mode.ts
const LEGACY_CONFIG_MIGRATION_RUNTIME_CODE_MODE = {
	id: "tools.codeMode.javascript-only",
	legacyRules: [{
		path: [
			"tools",
			"codeMode",
			"languages"
		],
		message: "tools.codeMode.languages is retired; Code Mode now runs JavaScript only. Run \"openclaw doctor --fix\"."
	}, {
		path: ["agents"],
		message: "Per-agent tools.codeMode.languages is retired; Code Mode now runs JavaScript only. Run \"openclaw doctor --fix\".",
		match: (e) => someAgentEntry(e, (e) => Object.hasOwn(asNullableRecord(asNullableRecord(e.tools)?.codeMode) ?? {}, "languages"))
	}],
	apply: (e, t) => {
		const removeLanguages = (e, n) => {
			const r = asNullableRecord(asNullableRecord(e)?.codeMode);
			if (!r || !Object.hasOwn(r, "languages")) return;
			delete r.languages;
			t.push(`Removed ${n}.codeMode.languages; Code Mode now runs JavaScript only.`);
		};
		removeLanguages(e.tools, "tools");
		visitAgentEntries(e, (e, t) => removeLanguages(e.tools, `${t}.tools`));
	}
};
const LEGACY_CONFIG_MIGRATION_RUNTIME_CODE_MODE_EXECUTOR = {
	id: "tools.codeMode.executor",
	legacyRules: [{
		path: [
			"tools",
			"codeMode",
			"runtime"
		],
		message: "tools.codeMode.runtime moved to tools.codeMode.executor. Run \"openclaw doctor --fix\"."
	}, {
		path: ["agents"],
		message: "Per-agent tools.codeMode.runtime moved to tools.codeMode.executor. Run \"openclaw doctor --fix\".",
		match: (e) => someAgentEntry(e, (e) => Object.hasOwn(asNullableRecord(asNullableRecord(e.tools)?.codeMode) ?? {}, "runtime"))
	}],
	apply: (e, t) => {
		const migrateRuntime = (e, n) => {
			const r = asNullableRecord(asNullableRecord(e)?.codeMode);
			if (r?.runtime !== "quickjs-wasi") return;
			if (Object.hasOwn(r, "executor")) t.push(`Removed ${n}.codeMode.runtime; kept explicit ${n}.codeMode.executor.`);
			else {
				r.executor = "quickjs";
				t.push(`Moved ${n}.codeMode.runtime to ${n}.codeMode.executor (quickjs).`);
			}
			delete r.runtime;
		};
		migrateRuntime(e.tools, "tools");
		visitAgentEntries(e, (e, t) => migrateRuntime(e.tools, `${t}.tools`));
	}
};
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.cron.ts
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_CRON = [{
	id: "cron.webhook-remove",
	legacyRules: [{
		path: ["cron", "webhook"],
		message: "cron.webhook was retired after per-job delivery migration. Run \"openclaw doctor --fix\"."
	}],
	apply: (e, t) => {
		const n = asNullableRecord(e.cron);
		if (!n || !Object.hasOwn(n, "webhook")) return;
		delete n.webhook;
		t.push("Removed retired cron.webhook after stored jobs migrated to per-job delivery.");
	}
}, {
	id: "cron.runLog-remove",
	legacyRules: [{
		path: ["cron", "runLog"],
		message: "cron.runLog is retired; run history now has fixed per-job retention. Run \"openclaw doctor --fix\"."
	}],
	apply: (e, t) => {
		const n = asNullableRecord(e.cron);
		if (!n || !Object.hasOwn(n, "runLog")) return;
		delete n.runLog;
		if (Object.keys(n).length === 0) delete e.cron;
		t.push("Removed retired cron.runLog config; cron history now keeps 2000 runs per job.");
	}
}];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.cyber-failover.ts
const LEGACY_CONFIG_MIGRATION_RUNTIME_CYBER_FAILOVER = {
	id: "agents.defaults.embeddedAgent.cyberFailover.model-removed",
	legacyRules: [{
		path: [
			"agents",
			"defaults",
			"embeddedAgent",
			"cyberFailover"
		],
		message: "agents.defaults.embeddedAgent.cyberFailover.model is retired; automatic cyber-policy retries use the active model through approved Daybreak access. Run \"openclaw doctor --fix\" to remove it.",
		match: (e) => Object.hasOwn(asNullableRecord(e) ?? {}, "model")
	}],
	apply: (e, t) => {
		const n = asNullableRecord(asNullableRecord(e.agents)?.defaults);
		const r = asNullableRecord(asNullableRecord(n?.embeddedAgent)?.cyberFailover);
		if (!r || !Object.hasOwn(r, "model")) return;
		delete r.model;
		t.push("Removed retired agents.defaults.embeddedAgent.cyberFailover.model; automatic cyber-policy retries use the active model through approved Daybreak access. Existing mode and cooloffMs settings were not changed.");
	}
};
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.diagnostics.ts
function hasLegacyGrpcOtlpSignals(e) {
	return e.traces !== false || e.metrics !== false || e.logs === true && e.logsExporter !== "stdout";
}
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_DIAGNOSTICS = [{
	id: "diagnostics.otel.grpc-protocol",
	legacyRules: [{
		path: [
			"diagnostics",
			"otel",
			"protocol"
		],
		message: "diagnostics.otel.protocol = \"grpc\" is no longer accepted because gRPC export is not implemented. Run \"openclaw doctor --fix\", then configure an OTLP/HTTP collector before re-enabling telemetry.",
		match: (e) => e === "grpc"
	}],
	apply: (e, t, n) => {
		const r = asNullableRecord(asNullableRecord(e.diagnostics)?.otel);
		const i = asNullableRecord(n?.resolvedRaw ?? e);
		const a = asNullableRecord(asNullableRecord(i?.diagnostics)?.otel);
		if (!r || a?.protocol !== "grpc") return;
		delete r.protocol;
		t.push("Removed unsupported diagnostics.otel.protocol \"grpc\"; use \"http/protobuf\" with an OTLP/HTTP collector.");
		if (a.enabled === true && hasLegacyGrpcOtlpSignals(a)) {
			r.enabled = false;
			t.push("Disabled diagnostics.otel.enabled because legacy grpc configs with OTLP signals cannot export telemetry; re-enable it after choosing an OTLP/HTTP collector.");
		}
	}
}];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.gateway.ts
const LEGACY_GATEWAY_BIND_HOST_ALIASES = /* @__PURE__ */ new Map([
	["0.0.0.0", "lan"],
	["::", "lan"],
	["[::]", "lan"],
	["*", "lan"],
	["127.0.0.1", "loopback"],
	["localhost", "loopback"],
	["::1", "loopback"],
	["[::1]", "loopback"]
]);
function normalizeLegacyGatewayBindHostAlias(e) {
	const t = normalizeOptionalLowercaseString(e);
	return t ? LEGACY_GATEWAY_BIND_HOST_ALIASES.get(t) ?? null : null;
}
function escapeControlForLog(e) {
	return e.replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
}
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_GATEWAY = [
	{
		id: "gateway.controlUi.experimental.claws->templates",
		legacyRules: [{
			path: [
				"gateway",
				"controlUi",
				"experimental",
				"claws"
			],
			message: "gateway.controlUi.experimental.claws moved to gateway.controlUi.experimental.templates. Run \"openclaw doctor --fix\"."
		}],
		apply: (e, t) => {
			const n = asNullableRecord(asNullableRecord(asNullableRecord(e.gateway)?.controlUi)?.experimental);
			if (!n || !Object.hasOwn(n, "claws")) return;
			if (Object.hasOwn(n, "templates")) t.push("Removed gateway.controlUi.experimental.claws; kept explicit gateway.controlUi.experimental.templates.");
			else {
				n.templates = n.claws;
				t.push("Moved gateway.controlUi.experimental.claws to gateway.controlUi.experimental.templates.");
			}
			delete n.claws;
		}
	},
	{
		id: "gateway.control-ui-tool-titles-remove",
		legacyRules: [{
			path: [
				"gateway",
				"controlUi",
				"toolTitles"
			],
			message: "gateway.controlUi.toolTitles is retired. Tool activity uses agent-provided descriptions automatically, without utility-model calls. Run \"openclaw doctor --fix\" to remove it."
		}],
		apply: (e, t) => {
			if (deleteRetiredPath(asNullableRecord(e.gateway)?.controlUi, ["toolTitles"])) t.push("Removed retired gateway.controlUi.toolTitles; tool activity descriptions are automatic and make no utility-model calls.");
		}
	},
	{
		id: "gateway.tailscale.service-name-remove",
		legacyRules: [{
			path: [
				"gateway",
				"tailscale",
				"serviceName"
			],
			message: "gateway.tailscale.serviceName is retired because named Services require persistent background routes that cannot follow the Gateway lifecycle. Run \"openclaw doctor --fix\"."
		}],
		apply: (e, t) => {
			const n = asNullableRecord(e.gateway);
			const r = asNullableRecord(n?.tailscale);
			if (!r || !Object.hasOwn(r, "serviceName")) return;
			const i = r.mode === "serve";
			delete r.serviceName;
			if (i) r.mode = "off";
			t.push(i ? "Removed gateway.tailscale.serviceName and set gateway.tailscale.mode=off because named Services cannot use lifecycle-owned routes. Inspect the retained Service route, then run `tailscale serve clear <service-name>`; set gateway.tailscale.mode=serve to use device Serve instead." : "Removed retired gateway.tailscale.serviceName; the current Tailscale mode is unchanged because named Services applied only to Serve.");
		}
	},
	{
		id: "gateway.tailscale.reset-on-exit-remove",
		legacyRules: [{
			path: [
				"gateway",
				"tailscale",
				"resetOnExit"
			],
			message: "gateway.tailscale.resetOnExit is retired because managed routes now follow the Gateway lifecycle automatically. Run \"openclaw doctor --fix\".",
			match: (e) => typeof e === "boolean"
		}],
		apply: (e, t) => {
			const n = asNullableRecord(e.gateway);
			const r = asNullableRecord(n?.tailscale);
			if (!r || !Object.hasOwn(r, "resetOnExit")) return;
			const i = r.resetOnExit === true;
			delete r.resetOnExit;
			t.push(i ? "Removed gateway.tailscale.resetOnExit; managed Tailscale routes now end automatically with the Gateway lifecycle." : "Removed retired gateway.tailscale.resetOnExit config.");
		}
	},
	{
		id: "gateway.control-ui-device-auth-bypass->pairing-migration",
		legacyRules: [{
			path: [
				"gateway",
				"controlUi",
				"dangerouslyDisableDeviceAuth"
			],
			message: "gateway.controlUi.dangerouslyDisableDeviceAuth is retired and ignored. Control UI browsers pair through the normal device flow; run \"openclaw doctor --fix\" to remove the legacy key.",
			match: (e) => typeof e === "boolean"
		}],
		apply: (e, t) => {
			if (!deleteRetiredPath(asNullableRecord(e.gateway)?.controlUi, ["dangerouslyDisableDeviceAuth"])) return;
			t.push("Removed retired gateway.controlUi.dangerouslyDisableDeviceAuth legacy config.");
		}
	},
	{
		id: "gateway.port-oob-repair",
		legacyRules: [{
			path: ["gateway", "port"],
			message: "gateway.port is outside the valid TCP range (1–65535) and will be removed to avoid startup failure. Run \"openclaw doctor --fix\".",
			match: (e) => typeof e === "number" && (e < 1 || e > 65535)
		}],
		apply: (e, t) => {
			const n = asNullableRecord(e.gateway);
			if (!n || !Object.hasOwn(n, "port")) return;
			const r = n.port;
			if (typeof r !== "number" || r >= 1 && r <= 65535) return;
			delete n.port;
			if (Object.keys(n).length === 0) delete e.gateway;
			t.push(`Removed out-of-range gateway.port (${String(r)}). Valid TCP ports are 1–65535; the gateway will use the default port ${DEFAULT_GATEWAY_PORT}.`);
		}
	},
	{
		id: "gateway.controlUi.allowedOrigins-seed-for-non-loopback",
		apply: (e, t) => {
			const n = asNullableRecord(e.gateway);
			if (!n) return;
			const r = normalizeLegacyGatewayBindHostAlias(n.bind) ?? n.bind;
			if (!isGatewayNonLoopbackBindMode(r)) return;
			const i = asNullableRecord(n.controlUi) ?? {};
			if (hasConfiguredControlUiAllowedOrigins({
				allowedOrigins: i.allowedOrigins,
				publicOrigin: n.publicOrigin,
				dangerouslyAllowHostHeaderOriginFallback: i.dangerouslyAllowHostHeaderOriginFallback
			})) return;
			const a = resolveGatewayPortWithDefault(n.port);
			const o = buildDefaultControlUiAllowedOrigins({
				port: a,
				bind: r,
				customBindHost: typeof n.customBindHost === "string" ? n.customBindHost : void 0
			});
			n.controlUi = {
				...i,
				allowedOrigins: o
			};
			t.push(`Seeded gateway.controlUi.allowedOrigins ${JSON.stringify(o)} for bind=${r}. Required since v2026.2.26. Add other machine origins to gateway.controlUi.allowedOrigins if needed.`);
		}
	},
	{
		id: "gateway.bind.host-alias->bind-mode",
		legacyRules: [{
			path: ["gateway", "bind"],
			message: "gateway.bind host aliases (for example 0.0.0.0/localhost) are legacy; use bind modes (lan/loopback/custom/tailnet/auto) instead. Run \"openclaw doctor --fix\".",
			match: (e) => normalizeLegacyGatewayBindHostAlias(e) !== null,
			requireSourceLiteral: true
		}],
		apply: (e, t) => {
			const n = asNullableRecord(e.gateway);
			if (!n) return;
			const r = n.bind;
			if (typeof r !== "string") return;
			const i = normalizeLegacyGatewayBindHostAlias(r);
			if (!i) return;
			n.bind = i;
			t.push(`Normalized gateway.bind "${escapeControlForLog(r)}" → "${i}".`);
		}
	}
];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.mcp.ts
const MCP_SERVER_TIMEOUT_ALIASES = [
	["connectTimeout", "connectionTimeoutMs"],
	["connect_timeout", "connectionTimeoutMs"],
	["timeout", "requestTimeoutMs"]
];
function* mcpServerEntries(e) {
	for (const [t, n] of Object.entries(asNullableRecord(e) ?? {})) if (isRecord(n)) yield [t, n];
}
function mcpServerRules(e, t) {
	return [["mcp", "servers"], [
		"nodeHost",
		"mcp",
		"servers"
	]].map((n) => ({
		path: n,
		message: `${n.join(".")} ${e}`,
		match: (e) => isRecord(e) && Object.values(e).some((e) => isRecord(e) && t(e))
	}));
}
function hasMcpServerLegacyAliases(e) {
	const t = isRecord(e.codex) ? e.codex : void 0;
	return Object.hasOwn(e, "workingDirectory") || [
		"supports_parallel_tool_calls",
		"ssl_verify",
		"client_cert",
		"client_key"
	].some((t) => Object.hasOwn(e, t)) || Boolean(t && Object.hasOwn(t, "default_tools_approval_mode"));
}
function migrateMcpServerAliases(e, t, n) {
	const r = asNullableRecord(e);
	if (!r) return;
	for (const [e, i] of mcpServerEntries(r)) {
		if (!hasMcpServerLegacyAliases(i) && !isKnownCliMcpTypeAlias(i.type)) continue;
		const a = canonicalizeConfiguredMcpServer(i);
		if (JSON.stringify(a) === JSON.stringify(i)) continue;
		r[e] = a;
		n.push(`Canonicalized legacy aliases in ${t}.${e}.`);
	}
}
function migrateMcpServerTimeoutAliases(e, t, n) {
	for (const [r, i] of mcpServerEntries(e)) for (const [e, a] of MCP_SERVER_TIMEOUT_ALIASES) {
		if (!Object.hasOwn(i, e)) continue;
		const o = i[e];
		if (i[a] === void 0 && typeof o === "number" && o > 0 && Number.isFinite(o * 1e3)) {
			i[a] = o * 1e3;
			n.push(`Moved ${t}.${r}.${e} → ${a} (${o * 1e3} ms).`);
		} else n.push(`Removed ${t}.${r}.${e} (${a} already set or alias invalid).`);
		delete i[e];
	}
}
function migrateMcpServerDisabledFlags(e, t, n) {
	for (const [r, i] of mcpServerEntries(e)) {
		if (typeof i.disabled !== "boolean") continue;
		const e = i.disabled;
		if (typeof i.enabled !== "boolean") {
			i.enabled = !e;
			n.push(`Moved ${t}.${r}.disabled ${e} → enabled ${!e}.`);
		} else n.push(`Removed ${t}.${r}.disabled ${e} because enabled is already set to ${i.enabled}.`);
		delete i.disabled;
	}
}
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_MCP = [{
	id: "mcp.servers.canonicalize",
	legacyRules: [
		...mcpServerRules("entries use the unsupported \"disabled\" key; use \"enabled\" with the inverse boolean value. Run \"openclaw doctor --fix\" to migrate it.", (e) => typeof e.disabled === "boolean"),
		...mcpServerRules("entries use OpenClaw transport names; CLI-native type aliases are legacy here. Run \"openclaw doctor --fix\".", (e) => isKnownCliMcpTypeAlias(e.type)),
		...mcpServerRules("timeout aliases were retired; use connectionTimeoutMs and requestTimeoutMs. Run \"openclaw doctor --fix\".", (e) => MCP_SERVER_TIMEOUT_ALIASES.some(([t]) => Object.hasOwn(e, t))),
		...mcpServerRules("legacy aliases were retired; use camelCase spellings and cwd. Run \"openclaw doctor --fix\".", hasMcpServerLegacyAliases)
	],
	apply: (e, t) => {
		const n = asNullableRecord(e.mcp);
		const r = asNullableRecord(asNullableRecord(e.nodeHost)?.mcp);
		for (const [e, i] of [[n, "mcp.servers"], [r, "nodeHost.mcp.servers"]]) {
			migrateMcpServerDisabledFlags(e?.servers, i, t);
			migrateMcpServerTimeoutAliases(e?.servers, i, t);
			migrateMcpServerAliases(e?.servers, i, t);
		}
	}
}];
//#endregion
//#region src/commands/doctor/shared/legacy-web-tools-migrate.ts
const LEGACY_WEB_SEARCH_OWNERS = /* @__PURE__ */ new Map([
	["brave", "brave"],
	["duckduckgo", "duckduckgo"],
	["exa", "exa"],
	["firecrawl", "firecrawl"],
	["gemini", "google"],
	["grok", "xai"],
	["kimi", "moonshot"],
	["minimax", "minimax"],
	["ollama", "ollama"],
	["perplexity", "perplexity"],
	["searxng", "searxng"]
]);
const LEGACY_WEB_SEARCH_PROVIDER_IDS = [...LEGACY_WEB_SEARCH_OWNERS.keys()].toSorted((e, t) => e.localeCompare(t));
function resolveWebSlot(e, t) {
	if (!isRecord(e) || !isRecord(e.tools) || !isRecord(e.tools.web)) return;
	const n = e.tools.web[t];
	return isRecord(n) ? n : void 0;
}
function retainedSource(e, t) {
	const n = {};
	for (const [r, i] of Object.entries(e)) {
		if (isBlockedObjectKey(r) || t.has(r) && isRecord(i)) continue;
		n[r] = i;
	}
	return n;
}
function applyPluginMove(e, t, n) {
	const r = ensureRecord(ensureRecord(e, "plugins"), "entries");
	const i = ensureRecord(r, t.pluginId);
	const a = i.enabled === void 0;
	if (a) i.enabled = true;
	const o = ensureRecord(i, "config");
	const s = o[t.configKey];
	const c = isRecord(s);
	const l = { ...c ? s : void 0 };
	if (!c) {
		o[t.configKey] = { ...t.payload };
		n.push(`Moved ${t.legacyPath} → ${t.targetPath}.`);
	} else if (t.mergeMode === "own-api-key") {
		if (!Object.hasOwn(l, "apiKey")) {
			l.apiKey = t.payload.apiKey;
			o[t.configKey] = l;
			n.push(`Merged ${t.legacyPath} → ${t.targetPath} (filled missing plugin auth).`);
		} else n.push(`Removed ${t.legacyPath} (${t.targetPath} already set).`);
	} else {
		const e = { ...l };
		mergeMissing(e, t.payload);
		o[t.configKey] = e;
		if (JSON.stringify(e) !== JSON.stringify(l) || a) n.push(`Merged ${t.legacyPath} → ${t.targetPath} (filled missing fields from legacy; kept explicit plugin config values).`);
		else n.push(`Removed ${t.legacyPath} (${t.targetPath} already set).`);
	}
	return a;
}
function searchMove(e, t, n) {
	const r = LEGACY_WEB_SEARCH_OWNERS.get(e) ?? e;
	return {
		pluginId: r,
		configKey: "webSearch",
		payload: t,
		legacyPath: n?.legacyPath ?? `tools.web.search.${e}`,
		targetPath: n?.targetPath ?? `plugins.entries.${r}.config.webSearch`
	};
}
function migrateLegacyWebSearchConfig(e) {
	const t = resolveWebSlot(e, "search");
	const n = LEGACY_WEB_SEARCH_PROVIDER_IDS;
	if (!t || !Object.hasOwn(t, "apiKey") && !n.some((e) => isRecord(t[e]))) return {
		config: e,
		changes: []
	};
	const r = structuredClone(e);
	const i = retainedSource(t, /* @__PURE__ */ new Set(["apiKey", ...n]));
	delete i.apiKey;
	ensureRecord(ensureRecord(r, "tools"), "web").search = i;
	const a = [];
	const o = isRecord(t.brave) ? t.brave : void 0;
	const s = { ...o };
	if (Object.hasOwn(t, "apiKey")) s.apiKey = t.apiKey;
	if (Object.keys(s).length > 0) applyPluginMove(r, searchMove("brave", s, Object.hasOwn(t, "apiKey") ? {
		legacyPath: "tools.web.search.apiKey",
		targetPath: o ? "plugins.entries.brave.config.webSearch" : "plugins.entries.brave.config.webSearch.apiKey"
	} : void 0), a);
	for (const e of n) {
		if (e === "brave" || !isRecord(t[e])) continue;
		const n = { ...t[e] };
		if (Object.keys(n).length === 0) continue;
		applyPluginMove(r, searchMove(e, n), a);
	}
	return {
		config: r,
		changes: a
	};
}
function migrateLegacyWebFetchConfig(e) {
	const t = resolveWebSlot(e, "fetch");
	if (!t || !isRecord(t.firecrawl)) return {
		config: e,
		changes: []
	};
	const n = structuredClone(e);
	const r = { ...t.firecrawl };
	delete r.enabled;
	ensureRecord(ensureRecord(n, "tools"), "web").fetch = retainedSource(t, /* @__PURE__ */ new Set(["firecrawl"]));
	const i = [];
	if (Object.keys(r).length > 0) applyPluginMove(n, {
		pluginId: "firecrawl",
		configKey: "webFetch",
		payload: r,
		legacyPath: "tools.web.fetch.firecrawl",
		targetPath: "plugins.entries.firecrawl.config.webFetch"
	}, i);
	else i.push("Removed empty tools.web.fetch.firecrawl.");
	return {
		config: n,
		changes: i
	};
}
function migrateLegacyXSearchConfig(e) {
	const t = resolveWebSlot(e, "x_search");
	if (!t) return {
		config: e,
		changes: []
	};
	if (!Object.hasOwn(t, "apiKey")) return {
		config: e,
		changes: []
	};
	const n = structuredClone(e);
	const r = ensureRecord(ensureRecord(n, "tools"), "web");
	const i = { ...t };
	const a = [];
	delete i.apiKey;
	const o = Object.keys(i).length === 0;
	if (o) delete r.x_search;
	else r.x_search = i;
	if (applyPluginMove(n, {
		pluginId: "xai",
		configKey: "webSearch",
		payload: { apiKey: t.apiKey },
		legacyPath: "tools.web.x_search.apiKey",
		targetPath: "plugins.entries.xai.config.webSearch.apiKey",
		mergeMode: "own-api-key"
	}, a) && o) a.push("Removed empty tools.web.x_search.");
	return {
		config: n,
		changes: a
	};
}
/** List legacy tools.web.search provider config paths present in raw config. */
function listLegacyWebSearchConfigPaths(e) {
	const t = resolveWebSlot(e, "search");
	if (!t) return [];
	const n = Object.hasOwn(t, "apiKey") ? ["tools.web.search.apiKey"] : [];
	for (const e of LEGACY_WEB_SEARCH_PROVIDER_IDS) if (isRecord(t[e])) n.push(...Object.keys(t[e]).map((t) => `tools.web.search.${e}.${t}`));
	return n;
}
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.providers.ts
const LEGACY_OPENAI_CODEX_PLUGIN_ID = "openai-codex";
const OPENAI_PLUGIN_ID = "openai";
const LEGACY_CODEX_SUPERVISOR_PLUGIN_ID = "codex-supervisor";
const CODEX_PLUGIN_ID = "codex";
function normalizePluginIdForMigration(e) {
	return typeof e === "string" ? e.trim().toLowerCase() : void 0;
}
function rewritePluginIdList(e, t, n) {
	if (!Array.isArray(e)) return {
		next: e,
		changed: false
	};
	let r = false;
	const i = /* @__PURE__ */ new Set();
	const a = [];
	for (const o of e) {
		const e = normalizePluginIdForMigration(o) === t;
		if (e && n === void 0) {
			r = true;
			continue;
		}
		const s = e ? n : o;
		if (s !== o) r = true;
		if (typeof s === "string") {
			const e = normalizePluginIdForMigration(s) ?? s;
			if (i.has(e)) {
				r = true;
				continue;
			}
			i.add(e);
		}
		a.push(s);
	}
	return {
		next: a,
		changed: r
	};
}
function rewriteLegacyOpenAICodexPluginPolicy(e) {
	const t = isRecord(e.plugins) ? e.plugins : void 0;
	if (!t) return [];
	const n = [];
	for (const e of ["allow", "deny"]) {
		const r = rewritePluginIdList(t[e], LEGACY_OPENAI_CODEX_PLUGIN_ID, OPENAI_PLUGIN_ID);
		if (r.changed) {
			t[e] = r.next;
			n.push(`Rewrote plugins.${e} openai-codex references to openai.`);
		}
	}
	const r = isRecord(t.entries) ? t.entries : void 0;
	if (r && LEGACY_OPENAI_CODEX_PLUGIN_ID in r) {
		if (!(OPENAI_PLUGIN_ID in r)) r[OPENAI_PLUGIN_ID] = r[LEGACY_OPENAI_CODEX_PLUGIN_ID];
		delete r[LEGACY_OPENAI_CODEX_PLUGIN_ID];
		n.push("Rewrote plugins.entries.openai-codex to plugins.entries.openai.");
	}
	const i = isRecord(t.slots) ? t.slots : {};
	let a = false;
	for (const [e, t] of Object.entries(i)) if (t === LEGACY_OPENAI_CODEX_PLUGIN_ID) {
		i[e] = OPENAI_PLUGIN_ID;
		a = true;
	}
	if (a) n.push("Rewrote plugins.slots openai-codex references to openai.");
	return n;
}
function migrateLegacyCodexSupervisorEntry(e, t, n) {
	const r = Object.keys(e).find((e) => normalizePluginIdForMigration(e) === LEGACY_CODEX_SUPERVISOR_PLUGIN_ID);
	if (!r) return;
	const i = e[r];
	if (!isRecord(i)) {
		delete e[r];
		n.push("Removed invalid plugins.entries.codex-supervisor config.");
		return;
	}
	const a = i.enabled === true && !t;
	const o = Object.keys(e).find((e) => normalizePluginIdForMigration(e) === CODEX_PLUGIN_ID) ?? CODEX_PLUGIN_ID;
	const s = ensureRecord(e, o);
	if (a && s.enabled === void 0) s.enabled = true;
	const c = ensureRecord(ensureRecord(s, "config"), "supervision");
	const l = isRecord(i.config) ? i.config : void 0;
	const u = { enabled: a };
	if (Array.isArray(l?.endpoints)) u.endpoints = l.endpoints;
	if (typeof l?.allowRawTranscripts === "boolean") u.allowRawTranscripts = l.allowRawTranscripts;
	if (typeof l?.allowWriteControls === "boolean") u.allowWriteControls = l.allowWriteControls;
	mergeMissing(c, u);
	delete e[r];
	n.push("Moved plugins.entries.codex-supervisor to plugins.entries.codex.config.supervision.");
}
function migrateLegacyCodexSupervisorPlugin(e) {
	const t = isRecord(e.plugins) ? e.plugins : void 0;
	if (!t) return [];
	const n = [];
	const r = Array.isArray(t.deny) && t.deny.some((e) => normalizePluginIdForMigration(e) === LEGACY_CODEX_SUPERVISOR_PLUGIN_ID);
	const i = isRecord(t.entries) ? t.entries : void 0;
	if (i) migrateLegacyCodexSupervisorEntry(i, r, n);
	const a = rewritePluginIdList(t.allow, LEGACY_CODEX_SUPERVISOR_PLUGIN_ID, CODEX_PLUGIN_ID);
	if (a.changed) {
		t.allow = a.next;
		n.push("Rewrote plugins.allow codex-supervisor references to codex.");
	}
	const o = rewritePluginIdList(t.deny, LEGACY_CODEX_SUPERVISOR_PLUGIN_ID);
	if (o.changed) {
		t.deny = o.next;
		n.push("Removed plugins.deny codex-supervisor references.");
	}
	return n;
}
function pluginPolicyMigration(e, t, n) {
	return {
		id: e,
		legacyRules: [{
			path: ["plugins"],
			message: t,
			requireSourceLiteral: true,
			match: (e, t) => n(structuredClone(t)).length > 0
		}],
		apply: (e, t) => {
			t.push(...n(e));
		}
	};
}
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_PROVIDERS = [
	pluginPolicyMigration("plugins.codex-supervisor->plugins.codex.config.supervision", "plugins.entries.codex-supervisor and related plugin policy references are retired; use plugins.entries.codex.config.supervision. Run \"openclaw doctor --fix\".", migrateLegacyCodexSupervisorPlugin),
	pluginPolicyMigration("plugins.openai-codex->plugins.openai", "plugins.openai-codex references are retired; use the openai plugin id. Run \"openclaw doctor --fix\".", rewriteLegacyOpenAICodexPluginPolicy),
	{
		id: "tools.web.x_search.apiKey->plugins.entries.xai.config.webSearch.apiKey",
		legacyRules: [{
			path: [
				"tools",
				"web",
				"x_search",
				"apiKey"
			],
			message: "tools.web.x_search.apiKey moved to the xAI plugin; use plugins.entries.xai.config.webSearch.apiKey instead. Run \"openclaw doctor --fix\"."
		}],
		apply: (e, t) => {
			const n = migrateLegacyXSearchConfig(e);
			if (!n.changes.length) return;
			for (const t of Object.keys(e)) delete e[t];
			Object.assign(e, n.config);
			t.push(...n.changes);
		}
	}
];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.config-tranche.ts
function stripRetiredPresentationPrefs(e, t) {
	const n = asNullableRecord(asNullableRecord(e.ui)?.prefs);
	if (!n) return;
	const r = [
		"chatMessageMaxWidth",
		"textScale",
		"sidebarLiveActivity",
		"showAdvancedSettings"
	].filter((e) => deleteRetiredPath(n, [e]));
	if (r.length > 0) t.push(`Removed browser-local ui.prefs keys: ${r.map((e) => `ui.prefs.${e}`).join(", ")}.`);
	const i = asNullableRecord(e.ui);
	if (Object.keys(n).length === 0) delete i?.prefs;
	if (i && Object.keys(i).length === 0) delete e.ui;
}
function stripRetiredAgentConfig(e, t) {
	let n = false;
	let r = false;
	visitAgentConfigScopes(e, (e, t) => {
		for (const t of ["memoryGetDefaultLines", "toolResultMaxChars"]) n = deleteRetiredPath(e, ["contextLimits", t]) || n;
		if (t !== "agents.defaults") r = deleteRetiredPath(e, ["typingIntervalSeconds"]) || r;
	});
	if (r) t.push("Removed per-agent typingIntervalSeconds overrides; agents.defaults.typingIntervalSeconds now applies to every agent.");
	if (n) t.push("Removed contextLimits.memoryGetDefaultLines/toolResultMaxChars overrides; built-in memory and context-window caps now apply.");
}
function migrateWhatsAppDebounce(e, t) {
	const n = asNullableRecord(asNullableRecord(e.channels)?.whatsapp);
	if (!n) return;
	const r = [];
	const i = asNullableRecord(n.accounts) ?? {};
	for (const [e, t] of [[void 0, n], ...Object.keys(i).toSorted().map((e) => [e, i[e]])]) {
		const n = asNullableRecord(t);
		if (!n || !Object.hasOwn(n, "debounceMs")) continue;
		const i = n.debounceMs;
		delete n.debounceMs;
		r.push({
			path: `channels.whatsapp${e === void 0 ? "" : `.accounts.${e}`}.debounceMs`,
			accountId: e === void 0 ? void 0 : normalizeAccountId(e),
			value: typeof i === "number" && Number.isInteger(i) && i >= 0 ? i : void 0
		});
	}
	if (r.length === 0) return;
	const a = r.filter((e) => e.value !== void 0);
	if (a.length === 0) {
		t.push(`Removed invalid WhatsApp debounce values: ${r.map((e) => e.path).join(", ")}.`);
		return;
	}
	const o = ensureRecord(ensureRecord(e, "messages"), "inbound");
	const s = ensureRecord(o, "byChannel");
	if (s.whatsapp !== void 0) {
		t.push(`Removed ${r.map((e) => e.path).join(", ")} (messages.inbound.byChannel.whatsapp already set).`);
		return;
	}
	const c = normalizeAccountId(typeof n.defaultAccount === "string" ? n.defaultAccount : void 0);
	const l = a.find((e) => e.accountId === c) ?? a.find((e) => e.accountId === "default") ?? a.find((e) => e.path === "channels.whatsapp.debounceMs") ?? a[0];
	if (!l) return;
	s.whatsapp = l.value;
	if (new Set(a.map((e) => e.value)).size === 1 && a.length === r.length) t.push(`Moved ${r.map((e) => e.path).join(", ")} → messages.inbound.byChannel.whatsapp.`);
	else t.push(`Collapsed conflicting WhatsApp debounce values into messages.inbound.byChannel.whatsapp using ${l.path} (${l.value} ms); account-specific debounce is no longer supported.`);
}
function migrateConfigTranche(e, t) {
	stripRetiredPresentationPrefs(e, t);
	if (deleteRetiredPath(e, [
		"skills",
		"load",
		"watchDebounceMs"
	])) t.push("Removed skills.load.watchDebounceMs; passive skill refresh now runs once per minute.");
	stripRetiredAgentConfig(e, t);
	migrateWhatsAppDebounce(e, t);
}
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.retired-media.ts
function migrateDiscordVoice(e, t) {
	visitChannelEntries(e, "discord", (e, n) => {
		const r = asNullableRecord(asNullableRecord(e.voice)?.realtime);
		moveLegacyConfigKey(r, "voice", "speakerVoice", `${n}.voice.realtime`, t);
	});
}
function hasDiscordRealtimeVoice(e) {
	let t = false;
	visitChannelEntries({ channels: { discord: e } }, "discord", (e) => {
		const n = asNullableRecord(asNullableRecord(e.voice)?.realtime);
		t ||= n !== null && Object.hasOwn(n, "voice");
	});
	return t;
}
function mapDeepgram(e) {
	const t = {};
	if (typeof e.detectLanguage === "boolean") t.detect_language = e.detectLanguage;
	if (typeof e.punctuate === "boolean") t.punctuate = e.punctuate;
	if (typeof e.smartFormat === "boolean") t.smart_format = e.smartFormat;
	return t;
}
function migrateDeepgramOwner(e, t, n) {
	const r = asNullableRecord(e.deepgram);
	if (!r) return;
	const i = asNullableRecord(e.providerOptions) ?? {};
	const a = asNullableRecord(i.deepgram) ?? {};
	i.deepgram = {
		...mapDeepgram(r),
		...a
	};
	e.providerOptions = i;
	delete e.deepgram;
	n.push(`Moved ${t}.deepgram → ${t}.providerOptions.deepgram.`);
}
function visitMediaOwners(e, t) {
	const n = asNullableRecord(e);
	if (!n) return;
	const visitModels = (e, n) => {
		if (!Array.isArray(e)) return;
		e.forEach((e, r) => {
			const i = asNullableRecord(e);
			if (i) t(i, `${n}[${r}]`);
		});
	};
	visitModels(n.models, "tools.media.models");
	for (const e of [
		"audio",
		"image",
		"video"
	]) {
		const r = asNullableRecord(n[e]);
		if (!r) continue;
		t(r, `tools.media.${e}`);
		visitModels(r.models, `tools.media.${e}.models`);
	}
}
function migrateMediaDeepgram(e, t) {
	visitMediaOwners(asNullableRecord(e.tools)?.media, (e, n) => migrateDeepgramOwner(e, n, t));
}
function hasMediaDeepgram(e) {
	let t = false;
	visitMediaOwners(e, (e) => {
		t ||= Object.hasOwn(e, "deepgram");
	});
	return t;
}
const RETIRED_LOOP_DETECTION_PATHS = [
	[
		"tools",
		"loopDetection",
		"genericRepeat"
	],
	[
		"tools",
		"loopDetection",
		"knownPollNoProgress"
	],
	[
		"tools",
		"loopDetection",
		"pingPong"
	],
	[
		"tools",
		"loopDetection",
		"windowSize"
	],
	[
		"tools",
		"loopDetection",
		"historySize"
	],
	[
		"tools",
		"loopDetection",
		"warningThreshold"
	],
	[
		"tools",
		"loopDetection",
		"unknownToolThreshold"
	],
	[
		"tools",
		"loopDetection",
		"criticalThreshold"
	],
	[
		"tools",
		"loopDetection",
		"globalCircuitBreakerThreshold"
	],
	[
		"tools",
		"loopDetection",
		"detectors"
	],
	[
		"tools",
		"loopDetection",
		"postCompactionGuard"
	]
];
const RETIRED_MEMORY_SEARCH_PATHS = [
	[
		"memory",
		"search",
		"chunking"
	],
	[
		"memory",
		"search",
		"sync",
		"watchDebounceMs"
	],
	[
		"memory",
		"search",
		"sync",
		"intervalMinutes"
	],
	[
		"memory",
		"search",
		"query",
		"hybrid",
		"vectorWeight"
	],
	[
		"memory",
		"search",
		"query",
		"hybrid",
		"textWeight"
	],
	[
		"memory",
		"search",
		"query",
		"hybrid",
		"candidateMultiplier"
	],
	[
		"memory",
		"search",
		"query",
		"hybrid",
		"mmr",
		"lambda"
	],
	[
		"memory",
		"search",
		"query",
		"hybrid",
		"temporalDecay",
		"halfLifeDays"
	],
	[
		"memory",
		"search",
		"cache",
		"maxEntries"
	]
];
const RETIRED_TUNING_PATHS = [
	["systemAgent"],
	["marketplaces"],
	[
		"cli",
		"banner",
		"taglineMode"
	],
	["commitments"],
	["auth", "cooldowns"],
	["secrets", "resolution"],
	["browser", "remoteCdpTimeoutMs"],
	["browser", "remoteCdpHandshakeTimeoutMs"],
	["browser", "localLaunchTimeoutMs"],
	["browser", "localCdpReadyTimeoutMs"],
	["browser", "actionTimeoutMs"],
	["browser", "cdpPortRangeStart"],
	[
		"browser",
		"tabCleanup",
		"idleMinutes"
	],
	[
		"browser",
		"tabCleanup",
		"maxTabsPerSession"
	],
	[
		"browser",
		"tabCleanup",
		"sweepMinutes"
	],
	...RETIRED_LOOP_DETECTION_PATHS,
	["gateway", "handshakeTimeoutMs"],
	["gateway", "channelHealthCheckMinutes"],
	["gateway", "channelStaleEventThresholdMinutes"],
	["gateway", "channelMaxRestartsPerHour"],
	[
		"gateway",
		"reload",
		"debounceMs"
	],
	[
		"gateway",
		"reload",
		"deferralTimeoutMs"
	],
	[
		"gateway",
		"http",
		"endpoints",
		"chatCompletions",
		"maxBodyBytes"
	],
	[
		"gateway",
		"http",
		"endpoints",
		"chatCompletions",
		"maxImageParts"
	],
	[
		"gateway",
		"http",
		"endpoints",
		"chatCompletions",
		"maxTotalImageBytes"
	],
	[
		"gateway",
		"http",
		"endpoints",
		"responses",
		"maxBodyBytes"
	],
	["session", "typingIntervalSeconds"],
	["session", "writeLock"],
	[
		"session",
		"agentToAgent",
		"maxPingPongTurns"
	],
	["cron", "maxConcurrentRuns"],
	[
		"cron",
		"triggers",
		"minIntervalMs"
	],
	["cron", "retry"],
	["diagnostics", "stuckSessionWarnMs"],
	["diagnostics", "stuckSessionAbortMs"],
	["diagnostics", "memoryPressureSnapshot"],
	["diagnostics", "memoryPressureBundle"],
	["web", "heartbeatSeconds"],
	["web", "reconnect"],
	["web", "whatsapp"],
	[
		"messages",
		"queue",
		"debounceMs"
	],
	[
		"messages",
		"statusReactions",
		"timing"
	],
	[
		"acp",
		"stream",
		"coalesceIdleMs"
	],
	[
		"acp",
		"stream",
		"maxChunkChars"
	],
	[
		"acp",
		"stream",
		"maxOutputChars"
	],
	[
		"acp",
		"stream",
		"maxSessionUpdateChars"
	],
	[
		"acp",
		"stream",
		"hiddenBoundarySeparator"
	],
	["acp", "maxConcurrentSessions"],
	[
		"acp",
		"runtime",
		"ttlMinutes"
	],
	["worktrees"],
	["transcripts", "maxUtterances"],
	["hooks", "maxBodyBytes"],
	[
		"update",
		"auto",
		"stableDelayHours"
	],
	[
		"update",
		"auto",
		"stableJitterHours"
	],
	[
		"update",
		"auto",
		"betaCheckIntervalHours"
	],
	...RETIRED_MEMORY_SEARCH_PATHS,
	[
		"channels",
		"*",
		"streaming",
		"progress",
		"render"
	],
	[
		"channels",
		"*",
		"accounts",
		"*",
		"streaming",
		"progress",
		"render"
	]
];
const RETIRED_AGENT_TUNING_PATHS = [
	["compaction", "reserveTokens"],
	["compaction", "reserveTokensFloor"],
	["compaction", "maxHistoryShare"],
	["contextPruning", "keepLastAssistants"],
	["contextPruning", "softTrimRatio"],
	["contextPruning", "hardClearRatio"],
	["contextPruning", "minPrunableToolChars"],
	["contextPruning", "softTrim"],
	...RETIRED_MEMORY_SEARCH_PATHS,
	["runRetries"],
	...RETIRED_LOOP_DETECTION_PATHS
];
function stripRetiredTuningKnobs(e, t) {
	const n = [];
	for (const t of RETIRED_TUNING_PATHS) deleteRetiredPath(e, t, n);
	visitAgentConfigScopes(e, (e, t) => {
		for (const r of RETIRED_AGENT_TUNING_PATHS) deleteRetiredPath(e, r, n, `${t}.`);
	});
	if (n.length > 0) t?.push(`Removed retired runtime tuning knobs: ${JSON.stringify(n.join(", ")).slice(1, -1)}; built-in defaults now apply.`);
	return n.length > 0;
}
const MEDIA_CAPABILITIES = [
	"image",
	"audio",
	"video"
];
function stableConfigValue(e) {
	if (Array.isArray(e)) return e.map(stableConfigValue);
	const t = asNullableRecord(e);
	if (!t) return e;
	return Object.fromEntries(Object.keys(t).toSorted().map((e) => [e, stableConfigValue(t[e])]));
}
function mediaModelSignature(e) {
	const { capabilities: t, ...n } = e;
	return JSON.stringify(stableConfigValue(n));
}
function scopeLegacyMediaModel(e, t) {
	if (Array.isArray(e.capabilities) && !e.capabilities.some((e) => e === t)) return;
	return {
		...e,
		capabilities: [t]
	};
}
function hasLegacyMediaCapabilityConfig(e) {
	const t = asNullableRecord(e);
	return MEDIA_CAPABILITIES.some((e) => {
		const n = asNullableRecord(t?.[e]);
		return Array.isArray(n?.models);
	});
}
function consolidateMediaCapabilityConfig(e, t) {
	const n = asNullableRecord(asNullableRecord(e.tools)?.media);
	if (!n) return;
	const r = Array.isArray(n.models) ? n.models.filter(isRecord) : [];
	const i = [];
	let a = false;
	for (const e of MEDIA_CAPABILITIES) {
		const t = asNullableRecord(n[e]);
		if (!t) continue;
		const r = Array.isArray(t.models) ? t.models.filter(isRecord) : [];
		const o = /* @__PURE__ */ new Set();
		for (const t of r) {
			const n = scopeLegacyMediaModel(t, e);
			if (!n) continue;
			const r = mediaModelSignature(n);
			if (o.has(r)) continue;
			o.add(r);
			i.push(n);
		}
		if (Object.hasOwn(t, "models")) {
			delete t.models;
			a = true;
		}
		if (Object.keys(t).length === 0) delete n[e];
		a = a || r.length > 0;
	}
	const o = [...i, ...r];
	if (o.length > 0) n.models = o;
	if (a) t.push("Consolidated tools.media image/audio/video model settings into capability-tagged tools.media.models entries.");
}
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.retired-memory-qmd.ts
function hasRetiredAgentMemoryQmd(e) {
	const t = asNullableRecord(asNullableRecord(e)?.memory);
	const n = asNullableRecord(t?.search);
	return Boolean(n && Object.hasOwn(n, "qmd"));
}
function readRetiredQmdExternalPaths(e) {
	if (!Array.isArray(e)) return [];
	const t = [];
	for (const n of e) {
		const e = asNullableRecord(n);
		const r = typeof e?.path === "string" ? e.path.trim() : "";
		if (!r) continue;
		const i = typeof e?.pattern === "string" ? e.pattern.trim() : "";
		t.push({
			path: r,
			...i ? { pattern: i } : {}
		});
	}
	return t;
}
function migrateRetiredQmdExternalPaths(e) {
	if (e.entries.length === 0) return;
	const t = ensureRecord(e.scope, "memory");
	const n = ensureRecord(t, "search");
	const r = normalizeConfiguredMemoryExtraPaths(Array.isArray(n.extraPaths) ? n.extraPaths.filter((e) => typeof e === "string" || typeof asNullableRecord(e)?.path === "string") : []);
	const entryKey = (e) => typeof e === "string" ? `${e}\0` : `${e.path}\0${e.pattern?.trim() ?? ""}`;
	const i = new Set(r.map(entryKey));
	let a = 0;
	for (const t of e.entries) {
		const e = t.pattern ? t : t.path;
		const n = entryKey(e);
		if (i.has(n)) continue;
		i.add(n);
		r.push(e);
		a += 1;
	}
	if (a > 0) {
		n.extraPaths = r;
		e.changes.push(`Migrated ${a} external QMD path${a === 1 ? "" : "s"} from ${e.sourcePath} → ${e.targetPath}.`);
	}
}
function migrateRetiredQmdSessionIndexing(e, t, n, r, i = n === "memory.qmd" ? "memory.search" : n.slice(0, -4)) {
	if (asNullableRecord(e?.sessions)?.enabled !== true) return;
	const a = ensureRecord(ensureRecord(t, "memory"), "search");
	const o = asNullableRecord(a.experimental);
	let s = false;
	if ((o || a.experimental === void 0) && o?.sessionMemory === void 0) {
		ensureRecord(a, "experimental").sessionMemory = true;
		s = true;
	}
	if (a.sources === void 0 || Array.isArray(a.sources) && a.sources.length === 0) {
		a.sources = ["memory", "sessions"];
		s = true;
	} else if (Array.isArray(a.sources) && !a.sources.includes("sessions")) {
		a.sources.push("sessions");
		s = true;
	}
	if (s) r.push(`Migrated ${n}.sessions.enabled → ${i}.experimental.sessionMemory and ${i}.sources.`);
}
function migrateRetiredMemoryQmd(e, t) {
	const n = asNullableRecord(e.memory);
	const r = asNullableRecord(n?.search);
	const i = asNullableRecord(n?.qmd);
	const a = asNullableRecord(r?.qmd);
	migrateRetiredQmdSessionIndexing(i, e, "memory.qmd", t);
	migrateRetiredQmdSessionIndexing(a, e, "memory.search.qmd", t);
	migrateRetiredQmdExternalPaths({
		changes: t,
		entries: [...readRetiredQmdExternalPaths(i?.paths), ...readRetiredQmdExternalPaths(a?.extraCollections)],
		scope: e,
		sourcePath: "memory.qmd.paths and memory.search.qmd.extraCollections",
		targetPath: "memory.search.extraPaths"
	});
	let o = false;
	for (const t of [
		["memory", "backend"],
		["memory", "qmd"],
		[
			"memory",
			"search",
			"qmd"
		]
	]) o = deleteRetiredPath(e, t) || o;
	visitAgentConfigScopes(e, (n, r) => {
		const i = asNullableRecord(asNullableRecord(n.memory)?.search);
		const a = asNullableRecord(i?.qmd);
		const s = r === "agents.defaults" && i?.qmd !== void 0;
		const c = s ? e : n;
		const l = s ? "memory.search" : `${r}.memory.search`;
		if (s && i) {
			o = deleteRetiredPath(n, [
				"memory",
				"search",
				"qmd"
			]) || o;
			mergeMissing(ensureRecord(ensureRecord(e, "memory"), "search"), i);
			delete n.memory;
		}
		migrateRetiredQmdSessionIndexing(a, c, `${r}.memory.search.qmd`, t, l);
		migrateRetiredQmdExternalPaths({
			changes: t,
			entries: readRetiredQmdExternalPaths(a?.extraCollections),
			scope: c,
			sourcePath: `${r}.memory.search.qmd.extraCollections`,
			targetPath: `${l}.extraPaths`
		});
		if (!s) o = deleteRetiredPath(n, [
			"memory",
			"search",
			"qmd"
		]) || o;
	});
	if (o) t.push("Removed retired QMD memory configuration; builtin memory is now the only memory engine.");
}
const LEGACY_CONFIG_MIGRATION_RUNTIME_MEMORY_QMD = {
	id: "runtime.memory-qmd-retired",
	legacyRules: [
		createLegacyConfigRule(["memory", "backend"], "memory.backend is retired; builtin memory is now the only memory engine."),
		createLegacyConfigRule(["memory", "qmd"], "memory.qmd is retired because the QMD memory backend was removed; configured external paths migrate to memory.search.extraPaths."),
		createLegacyConfigRule([
			"memory",
			"search",
			"qmd"
		], "memory.search.qmd is retired because the QMD memory backend was removed; configured external collections migrate to memory.search.extraPaths."),
		createLegacyConfigRule([
			"agents",
			"defaults",
			"memory",
			"search",
			"qmd"
		], "agents.defaults.memory.search.qmd is retired because the QMD memory backend was removed; configured external collections migrate to memory.search.extraPaths."),
		createLegacyConfigRule(["agents", "entries"], "agents.entries.*.memory.search.qmd is retired because the QMD memory backend was removed; configured external collections migrate to the matching agent memory.search.extraPaths.", (e) => {
			const t = asNullableRecord(e);
			return t ? Object.values(t).some(hasRetiredAgentMemoryQmd) : false;
		}),
		createLegacyConfigRule(["agents", "list"], "agents.list.*.memory.search.qmd is retired because the QMD memory backend was removed; configured external collections migrate to the matching agent memory.search.extraPaths.", (e) => Array.isArray(e) && e.some(hasRetiredAgentMemoryQmd))
	],
	apply: migrateRetiredMemoryQmd
};
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.tier-eval.ts
const TIER_EVAL_RETIRED_MEMORY_PATHS = [
	[
		"memory",
		"search",
		"remote",
		"nonBatchConcurrency"
	],
	[
		"memory",
		"search",
		"remote",
		"batch",
		"wait"
	],
	[
		"memory",
		"search",
		"remote",
		"batch",
		"concurrency"
	],
	[
		"memory",
		"search",
		"remote",
		"batch",
		"pollIntervalMs"
	],
	[
		"memory",
		"search",
		"remote",
		"batch",
		"timeoutMinutes"
	],
	[
		"memory",
		"search",
		"local",
		"contextSize"
	],
	[
		"memory",
		"search",
		"local",
		"modelCacheDir"
	],
	[
		"memory",
		"search",
		"store",
		"driver"
	],
	[
		"memory",
		"search",
		"sync"
	],
	[
		"memory",
		"search",
		"query",
		"hybrid"
	]
];
const TIER_EVAL_RETIRED_ROOT_PATHS = [
	[
		"cloudWorkers",
		"profiles",
		"*",
		"lifetime"
	],
	["meta", "lastTouchedAt"],
	[
		"hooks",
		"internal",
		"installs"
	],
	["cron", "store"],
	["plugins", "bundledDiscovery"],
	["tts", "prefsPath"],
	["logging", "redactSensitive"],
	["commands", "useAccessGroups"],
	[
		"gateway",
		"controlUi",
		"allowInsecureAuth"
	],
	...TIER_EVAL_RETIRED_MEMORY_PATHS
];
const TIER_EVAL_RETIRED_AGENT_PATHS = [
	["groupChat", "visibleReplies"],
	...TIER_EVAL_RETIRED_MEMORY_PATHS,
	["heartbeat", "ackMaxChars"],
	["heartbeat", "includeReasoning"],
	["heartbeat", "includeSystemPromptSection"],
	["heartbeat", "skipWhenBusy"],
	["heartbeat", "suppressToolErrorWarnings"]
];
function resolveConfiguredExecPolicy(e) {
	const t = asNullableRecord(asNullableRecord(e.tools)?.exec);
	if (!t) return;
	switch (t.mode) {
		case "deny": return {
			security: "deny",
			ask: "off"
		};
		case "allowlist": return {
			security: "allowlist",
			ask: "off"
		};
		case "ask":
		case "auto": return {
			security: "allowlist",
			ask: "on-miss"
		};
		case "full": return {
			security: "full",
			ask: "off"
		};
	}
	const n = t.security === "deny" || t.security === "allowlist" || t.security === "full" ? t.security : void 0;
	const r = t.ask === "on-miss" || t.ask === "always" || t.ask === "off" ? t.ask : void 0;
	return n && r ? {
		security: n,
		ask: r
	} : void 0;
}
function migrateExecMode(e, t, n, r) {
	const i = asNullableRecord(asNullableRecord(e.tools)?.exec);
	if (!i || !Object.hasOwn(i, "security") && !Object.hasOwn(i, "ask")) return;
	if (i.mode !== void 0) {
		n.push(`Removed ${t}.tools.exec.security/ask (${t}.tools.exec.mode already set).`);
		delete i.security;
		delete i.ask;
		return;
	}
	const a = i.security === "deny" || i.security === "allowlist" || i.security === "full" ? i.security : void 0;
	const o = i.ask === "on-miss" || i.ask === "always" || i.ask === "off" ? i.ask : void 0;
	if (Object.hasOwn(i, "security") && !a || Object.hasOwn(i, "ask") && !o) return;
	const s = a ?? r?.security;
	const c = o ?? r?.ask;
	if (!s || !c) return;
	const l = resolveExactExecModeFromPolicy({
		security: s,
		ask: c
	});
	if (!l) return;
	i.mode = l;
	n.push(`Moved ${t}.tools.exec.security/ask → ${t}.tools.exec.mode.`);
	delete i.security;
	delete i.ask;
}
function migrateSignalEndpoint(e, t, n, r) {
	if (!Object.hasOwn(e, "httpHost") && !Object.hasOwn(e, "httpPort")) return;
	if (e.httpUrl === void 0 && typeof r?.httpUrl === "string") {
		delete e.httpHost;
		delete e.httpPort;
		n.push(`Removed ${t}.httpHost/httpPort (inherited httpUrl already set).`);
		return;
	}
	if (e.httpUrl === void 0) {
		const i = e.httpHost ?? r?.httpHost;
		const a = typeof i === "string" && i.trim() ? i.trim() : "127.0.0.1";
		const o = a.includes(":") && !a.startsWith("[") ? `[${a}]` : a;
		const s = e.httpPort ?? r?.httpPort;
		e.httpUrl = `http://${o}:${typeof s === "number" ? s : 8080}`;
		if (e.autoStart === void 0) e.autoStart = true;
		n.push(`Moved ${t}.httpHost/httpPort → ${t}.httpUrl.`);
	} else n.push(`Removed ${t}.httpHost/httpPort (${t}.httpUrl already set).`);
	delete e.httpHost;
	delete e.httpPort;
}
function migrateChannelAliases(e, t) {
	const n = asNullableRecord(asNullableRecord(e.channels)?.signal);
	if (n) {
		const r = {
			httpUrl: n.httpUrl,
			httpHost: n.httpHost,
			httpPort: n.httpPort
		};
		visitChannelEntries(e, "signal", (e, n) => {
			migrateSignalEndpoint(e, n, t, r);
		});
	}
	visitChannelEntries(e, "googlechat", (e, n) => {
		if (!Object.hasOwn(e, "serviceAccountRef")) return;
		const r = e.serviceAccount !== void 0;
		e.serviceAccount = e.serviceAccountRef;
		delete e.serviceAccountRef;
		t.push(r ? `Moved ${n}.serviceAccountRef → ${n}.serviceAccount (SecretRef precedence preserved).` : `Moved ${n}.serviceAccountRef → ${n}.serviceAccount.`);
	});
}
const RESPONSE_PREFIX_CHANNELS = /* @__PURE__ */ new Set([
	"buzz",
	"clickclack",
	"discord",
	"feishu",
	"googlechat",
	"imessage",
	"irc",
	"matrix",
	"mattermost",
	"msteams",
	"nextcloud-talk",
	"qa-channel",
	"signal",
	"slack",
	"telegram",
	"tlon",
	"twitch",
	"whatsapp",
	"zalo",
	"zalouser",
	"line"
]);
function migrateMessagesResponsePrefix(e, t) {
	const n = asNullableRecord(e.messages);
	if (!n || !Object.hasOwn(n, "responsePrefix")) return;
	const r = [];
	let i = false;
	for (const [t, a] of Object.entries(asNullableRecord(e.channels) ?? {})) {
		const e = asNullableRecord(a);
		if (t === "defaults" || !e) continue;
		if (!RESPONSE_PREFIX_CHANNELS.has(t)) r.push(t);
		else if (e.responsePrefix === void 0) {
			e.responsePrefix = n.responsePrefix;
			i = true;
		}
	}
	if (i) t.push(`Copied messages.responsePrefix to supported channel blocks while retaining the implicit/custom fallback${r.length > 0 ? ` for: ${r.join(", ")}` : ""}.`);
}
function migratePresenceEnabled(e, t) {
	const n = asNullableRecord(asNullableRecord(e.discovery)?.wideArea);
	if (!n || !Object.hasOwn(n, "enabled")) return false;
	if (n.enabled === false && typeof n.domain === "string" && n.domain.trim()) {
		delete n.domain;
		t.push("Removed disabled discovery.wideArea activation fields; domain presence now enables wide-area discovery.");
	}
	delete n.enabled;
	return true;
}
function migrateWebEnabled(e, t) {
	const n = asNullableRecord(e.web);
	if (!n) return false;
	if (Object.hasOwn(n, "enabled")) {
		const r = ensureRecord(ensureRecord(e, "channels"), "whatsapp");
		if (n.enabled === false && r.enabled === true) t.push("Removed web.enabled=false (channels.whatsapp.enabled already set).");
		if (r.enabled === void 0) {
			r.enabled = n.enabled;
			t.push("Moved web.enabled → channels.whatsapp.enabled.");
		}
	}
	delete e.web;
	return true;
}
function stripPromptsFromTtsConfig(e, t, n) {
	for (const [r, i] of Object.entries(asNullableRecord(asNullableRecord(e)?.personas) ?? {})) if (deleteRetiredPath(i, ["prompt"])) n.push(`Removed ${t}.personas.${r}.prompt; move custom shaping into a speech provider prepareSynthesis implementation.`);
}
function stripTtsPersonaPrompts(e, t) {
	stripPromptsFromTtsConfig(e.tts, "tts", t);
	visitAgentConfigScopes(e, (e, n) => {
		stripPromptsFromTtsConfig(e.tts, `${n}.tts`, t);
	});
	for (const n of Object.keys(asNullableRecord(e.channels) ?? {})) visitChannelEntries(e, n, (e, n) => {
		stripPromptsFromTtsConfig(e.tts, `${n}.tts`, t);
		stripPromptsFromTtsConfig(asNullableRecord(e.voice)?.tts, `${n}.voice.tts`, t);
	});
}
function stripCompactionInstructionConfig(e, t, n) {
	const r = asNullableRecord(e.compaction);
	if (!r) return;
	let i = false;
	for (const [e, t] of [[r, ["customInstructions", "identifierInstructions"]], [r.memoryFlush, ["prompt", "systemPrompt"]]]) for (const n of t) i = deleteRetiredPath(e, [n]) || i;
	if (r.identifierPolicy === "custom") {
		r.identifierPolicy = "strict";
		i = true;
	}
	if (i) n.push(`Removed ${t}.compaction custom prompt instructions; use a compaction provider summarize() implementation and before_prompt_build hooks.`);
}
function migrateTierEvalTranche(e, t) {
	const n = t.length;
	let r = false;
	stripTtsPersonaPrompts(e, t);
	r = migratePresenceEnabled(e, t) || r;
	migrateChannelAliases(e, t);
	const i = asNullableRecord(e.session);
	if (i && Object.hasOwn(i, "idleMinutes")) {
		const e = asNullableRecord(i.reset) ?? { mode: "idle" };
		if (e.idleMinutes === void 0) {
			e.idleMinutes = i.idleMinutes;
			i.reset = e;
			t.push("Moved session.idleMinutes → session.reset.idleMinutes.");
		}
		delete i.idleMinutes;
		r = true;
	}
	const a = resolveConfiguredExecPolicy(e);
	migrateExecMode(e, "root", t);
	visitAgentConfigScopes(e, (e, n) => {
		stripCompactionInstructionConfig(e, n, t);
		if (n !== "agents.defaults") migrateExecMode(e, n, t, a);
		for (const t of TIER_EVAL_RETIRED_AGENT_PATHS) r = deleteRetiredPath(e, t) || r;
	});
	r = migrateWebEnabled(e, t) || r;
	migrateMessagesResponsePrefix(e, t);
	for (const t of TIER_EVAL_RETIRED_ROOT_PATHS) r = deleteRetiredPath(e, t) || r;
	for (const t of [...Object.values(asNullableRecord(asNullableRecord(e.secrets)?.providers) ?? {}), asNullableRecord(asNullableRecord(e.security)?.installPolicy)?.exec]) for (const e of ["allowInsecurePath", "allowSymlinkCommand"]) r = deleteRetiredPath(t, [e]) || r;
	if (r || t.length > n) t.push("Applied tier-eval tranche retirements; current settings and built-in defaults now apply.");
}
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.retired.ts
function migrateMessageCrossContext(e, t) {
	const n = asNullableRecord(asNullableRecord(e.tools)?.message);
	const r = n?.allowCrossContextSend;
	const i = asNullableRecord(n?.crossContext);
	const migrate = (e, n, a) => {
		if (!e) return;
		const o = e.allowCrossContextSend;
		const s = a && r === true;
		if (o === void 0 && !s) return;
		const c = asNullableRecord(e.crossContext) ?? {};
		if ((o ?? (a ? r : void 0)) === true) e.crossContext = {
			...c,
			allowWithinProvider: true,
			allowAcrossProviders: true
		};
		else if (s) e.crossContext = {
			...c,
			allowWithinProvider: (c.allowWithinProvider ?? i?.allowWithinProvider) !== false,
			allowAcrossProviders: (c.allowAcrossProviders ?? i?.allowAcrossProviders) === true
		};
		delete e.allowCrossContextSend;
		t.push(`Moved ${n}.allowCrossContextSend → ${n}.crossContext.`);
	};
	visitAgentConfigScopes(e, (e, t) => {
		if (t !== "agents.defaults") migrate(asNullableRecord(asNullableRecord(e.tools)?.message), `${t}.tools.message`, true);
	});
	migrate(n, "tools.message", false);
}
function migrateTruncateAfterCompaction(e, t) {
	const n = asNullableRecord(asNullableRecord(asNullableRecord(e.agents)?.defaults)?.compaction);
	if (!n || !Object.hasOwn(n, "truncateAfterCompaction")) return;
	if (n.truncateAfterCompaction === false && Object.hasOwn(n, "maxActiveTranscriptBytes")) {
		delete n.maxActiveTranscriptBytes;
		t.push("Removed maxActiveTranscriptBytes to preserve truncateAfterCompaction: false.");
	}
	delete n.truncateAfterCompaction;
	t.push("Removed retired agents.defaults.compaction.truncateAfterCompaction.");
}
function migrateFinalLayoutRenames(e, t) {
	const n = asNullableRecord(e.agents);
	const r = asNullableRecord(n?.defaults);
	moveLegacyConfigKey(r, "pdfMaxBytesMb", "pdfMaxMb", "agents.defaults", t);
	if (r) {
		const e = asNullableRecord(r.mediaModels) ?? {};
		for (const [n, i] of [
			["imageGenerationModel", "image"],
			["videoGenerationModel", "video"],
			["musicGenerationModel", "music"]
		]) {
			if (!Object.hasOwn(r, n)) continue;
			if (e[i] === void 0) {
				e[i] = r[n];
				t.push(`Moved agents.defaults.${n} → agents.defaults.mediaModels.${i}.`);
			} else t.push(`Removed agents.defaults.${n} (agents.defaults.mediaModels.${i} already set).`);
			delete r[n];
		}
		if (Object.keys(e).length > 0) r.mediaModels = e;
	}
	visitAgentConfigScopes(e, (e, n) => {
		moveLegacyConfigKey(asNullableRecord(asNullableRecord(e.tools)?.exec), "timeoutSec", "timeoutSeconds", `${n}.tools.exec`, t);
		moveLegacyConfigKey(asNullableRecord(asNullableRecord(e.sandbox)?.browser), "enableNoVnc", "noVncEnabled", `${n}.sandbox.browser`, t);
	});
	moveLegacyConfigKey(asNullableRecord(asNullableRecord(e.tools)?.exec), "timeoutSec", "timeoutSeconds", "tools.exec", t);
	const i = asNullableRecord(e.env);
	if (i) {
		const e = asNullableRecord(i.vars) ?? {};
		let n = false;
		for (const [r, a] of Object.entries(i)) {
			if (r === "vars" || r === "shellEnv" || typeof a !== "string") continue;
			if (e[r] === void 0) {
				e[r] = a;
				t.push(`Moved env.${r} → env.vars.${r}.`);
			} else t.push(`Removed env.${r} (env.vars.${r} already set).`);
			delete i[r];
			n = true;
		}
		if (n) i.vars = e;
	}
	const a = asNullableRecord(e.browser);
	const o = asNullableRecord(a?.ssrfPolicy);
	if (o && Array.isArray(o.hostnameAllowlist)) {
		const e = Array.isArray(o.allowedHostnames) ? o.allowedHostnames : [];
		o.allowedHostnames = [...new Set([...e, ...o.hostnameAllowlist].filter((e) => typeof e === "string"))];
		delete o.hostnameAllowlist;
		t.push("Merged browser.ssrfPolicy.hostnameAllowlist → allowedHostnames.");
	}
	const s = asNullableRecord(e.media);
	if (s) {
		const n = ensureRecord(e, "attachments");
		mergeMissing(n, s);
		delete e.media;
		t.push("Moved media → attachments.");
	}
	const c = asNullableRecord(e.audit);
	if (c) {
		const n = ensureRecord(e, "logging");
		const r = asNullableRecord(n.audit) ?? {};
		mergeMissing(r, c);
		n.audit = r;
		delete e.audit;
		t.push("Moved audit → logging.audit.");
	}
	const l = asNullableRecord(asNullableRecord(e.gateway)?.nodes);
	if (l) {
		const e = asNullableRecord(l.skills);
		if (e && Object.hasOwn(e, "enabled")) {
			if (l.allowSkills === void 0) l.allowSkills = e.enabled;
			delete l.skills;
			t.push("Moved gateway.nodes.skills.enabled → gateway.nodes.allowSkills.");
		}
		const n = asNullableRecord(l.commands) ?? {};
		for (const [e, r] of [["allowCommands", "allow"], ["denyCommands", "deny"]]) {
			if (!Object.hasOwn(l, e)) continue;
			if (n[r] === void 0) n[r] = l[e];
			delete l[e];
			t.push(`Moved gateway.nodes.${e} → gateway.nodes.commands.${r}.`);
		}
		if (Object.keys(n).length > 0) l.commands = n;
	}
	visitChannelEntries(e, "slack", (e, n) => {
		moveLegacyConfigKey(e, "identity", "postAs", n, t);
	});
}
function migrateFinalLayoutKills(e, t) {
	const n = asNullableRecord(asNullableRecord(e.agents)?.defaults);
	if (n && Object.hasOwn(n, "promptOverlays")) {
		const r = asNullableRecord(asNullableRecord(n.promptOverlays)?.gpt5)?.personality;
		if (r !== void 0) {
			const n = ensureRecord(ensureRecord(ensureRecord(ensureRecord(e, "plugins"), "entries"), "openai"), "config");
			if (n.personality === void 0) {
				n.personality = r;
				t.push("Moved agents.defaults.promptOverlays.gpt5.personality → plugins.entries.openai.config.personality.");
			} else t.push("Removed agents.defaults.promptOverlays.gpt5.personality (plugins.entries.openai.config.personality already set).");
		} else t.push("Removed agents.defaults.promptOverlays; built-in behavior now applies.");
		delete n.promptOverlays;
	}
	for (const e of [
		"envelopeTimestamp",
		"envelopeElapsed",
		"envelopeTimezone",
		"timeFormat",
		"bootstrapPromptTruncationWarning",
		"mediaGenerationAutoProviderFallback"
	]) if (deleteRetiredPath(n, [e])) t.push(`Removed agents.defaults.${e}; built-in behavior now applies.`);
	const r = asNullableRecord(e.diagnostics);
	const i = asNullableRecord(r?.otel);
	const a = asNullableRecord(i?.captureContent);
	if (i && a) {
		i.captureContent = typeof a.enabled === "boolean" ? a.enabled : Object.entries(a).some(([e, t]) => e !== "enabled" && t === true);
		t.push("Collapsed diagnostics.otel.captureContent to a boolean.");
	}
	const o = asNullableRecord(r?.cacheTrace);
	if (o && (Object.keys(o).some((e) => e !== "enabled") || o.enabled !== void 0 && typeof o.enabled !== "boolean")) {
		r.cacheTrace = { enabled: o.enabled === true };
		t.push("Removed diagnostics.cacheTrace detail fields; only enabled remains.");
	}
	if (deleteRetiredPath(e.attachments, ["preserveFilenames"])) t.push("Removed attachments.preserveFilenames; temp-safe names now always apply.");
	const s = asNullableRecord(e.browser);
	if (deleteRetiredPath(s, ["color"])) t.push("Removed browser.color; the built-in color now applies.");
	for (const [e, n] of Object.entries(asNullableRecord(s?.profiles) ?? {})) if (deleteRetiredPath(n, ["color"])) t.push(`Removed browser.profiles.${e}.color.`);
	visitChannelEntries(e, "discord", (e, n) => {
		for (const r of [
			"healthyText",
			"degradedText",
			"exhaustedText"
		]) if (deleteRetiredPath(e.autoPresence, [r])) t.push(`Removed ${n}.autoPresence.${r}.`);
		if (deleteRetiredPath(e, [
			"ui",
			"components",
			"accentColor"
		])) t.push(`Removed ${n}.ui.components.accentColor.`);
	});
	const c = asNullableRecord(e.messages);
	if (deleteRetiredPath(c?.statusReactions, ["emojis"])) t.push("Removed messages.statusReactions.emojis; curated defaults now apply.");
	if (deleteRetiredPath(c, ["removeAckAfterReply"])) t.push("Removed messages.removeAckAfterReply; acknowledgements are retained.");
	visitChannelEntries(e, "whatsapp", (e, n) => {
		moveLegacyConfigKey(e, "messagePrefix", "responsePrefix", n, t);
	});
	visitChannelEntries(e, "slack", (e, n) => {
		const r = asNullableRecord(e.socketMode);
		for (const e of [
			"clientPingTimeout",
			"serverPingTimeout",
			"pingPongLoggingEnabled"
		]) if (deleteRetiredPath(r, [e])) t.push(`Removed ${n}.socketMode.${e}.`);
		if (r && Object.keys(r).length === 0) delete e.socketMode;
	});
	visitChannelEntries(e, "imessage", (e, n) => {
		if (deleteRetiredPath(e, ["coalesceSameSenderDms"])) t.push(`Removed ${n}.coalesceSameSenderDms.`);
	});
	for (const n of ["ownerDisplay", "ownerDisplaySecret"]) if (deleteRetiredPath(e.commands, [n])) t.push(`Removed commands.${n}; owner ids now render raw.`);
	const l = asNullableRecord(e.cron);
	const u = asNullableRecord(l?.failureDestination);
	if (l && u) {
		const e = asNullableRecord(l.failureAlert) ?? {};
		mergeMissing(e, u);
		l.failureAlert = e;
		delete l.failureDestination;
		t.push("Merged cron.failureDestination → cron.failureAlert.");
	}
	const d = asNullableRecord(e.gateway);
	const f = asNullableRecord(d?.reload);
	if (f?.mode === "restart" || f?.mode === "hot") {
		f.mode = "hybrid";
		t.push("Mapped gateway.reload.mode to hybrid.");
	}
	const p = asNullableRecord(e.logging);
	if (p?.consoleStyle === "compact") {
		p.consoleStyle = "pretty";
		t.push("Mapped logging.consoleStyle compact → pretty.");
	}
	if (deleteRetiredPath(d?.controlUi, ["chatMessageMaxWidth"])) t.push("Removed gateway.controlUi.chatMessageMaxWidth; chat width is now browser-local.");
}
function removeUiAssistantIdentity(e, t) {
	if (deleteRetiredPath(e, ["ui", "assistant"])) t.push("Removed retired ui.assistant; configure agents.list[].identity instead.");
}
function probedMigration(e, t, n) {
	return {
		id: e,
		legacyRules: [createLegacyConfigRule([], t, (e, t) => {
			const r = [];
			n(structuredClone(t), r);
			return r.length > 0;
		})],
		apply: n
	};
}
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_RETIRED = [
	LEGACY_CONFIG_MIGRATION_RUNTIME_MEMORY_QMD,
	{
		id: "runtime.automatic-local-model-lean",
		legacyRules: [createLegacyConfigRule(["wizard", "localModelLeanAutoModel"], "wizard.localModelLeanAutoModel is retired; local models now use Tool Search without reducing their capabilities.")],
		apply: (e, t) => {
			const n = asNullableRecord(e.wizard);
			if (!n || !Object.hasOwn(n, "localModelLeanAutoModel")) return;
			const r = n.localModelLeanAutoModel;
			const i = asNullableRecord(asNullableRecord(e.agents)?.defaults);
			const a = i?.model;
			const o = typeof a === "string" ? a : asNullableRecord(a)?.primary;
			const s = asNullableRecord(i?.experimental);
			if (s?.localModelLean === true) {
				if (typeof r === "string" && r === o) {
					delete s.localModelLean;
					t.push("Removed onboarding-owned agents.defaults.experimental.localModelLean.");
				} else t.push("Retained explicit or unowned agents.defaults.experimental.localModelLean=true; remove it or set it to false to restore the full tool capabilities through Tool Search.");
			}
			delete n.localModelLeanAutoModel;
			t.push("Removed retired wizard.localModelLeanAutoModel.");
		}
	},
	{
		id: "runtime.messages-suppress-tool-errors",
		legacyRules: [createLegacyConfigRule(["messages", "suppressToolErrors"], "messages.suppressToolErrors is retired; tool failure warnings now appear only when a run ends without a reply.")],
		apply: (e, t) => {
			if (deleteRetiredPath(e.messages, ["suppressToolErrors"])) t.push("Removed messages.suppressToolErrors (tool failure warnings now appear only when a run ends without a reply).");
		}
	},
	{
		id: "runtime.retired-internal-hook-handlers",
		legacyRules: [{
			path: [
				"hooks",
				"internal",
				"handlers"
			],
			message: "hooks.internal.handlers is retired. Move each module to a managed/workspace hook directory with HOOK.md + handler file before running \"openclaw doctor --fix\"; the fix removes retired registrations and does not materialize executable files."
		}],
		apply: (e, t) => {
			const n = asNullableRecord(asNullableRecord(e.hooks)?.internal);
			if (!n || !Object.hasOwn(n, "handlers")) return;
			delete n.handlers;
			t.push("Removed retired hooks.internal.handlers registrations; hook files must be migrated separately.");
			const r = asNullableRecord(n.entries);
			const i = asNullableRecord(n.load)?.extraDirs;
			const a = Boolean(r && Object.keys(r).length > 0);
			const o = Array.isArray(i) && i.some((e) => typeof e === "string" && e.trim().length > 0);
			if (n.enabled === true && !a && !o) {
				delete n.enabled;
				t.push("Removed legacy-only hooks.internal.enabled to avoid enabling broad hook discovery.");
			}
		}
	},
	probedMigration("runtime.doctor-tier-eval-tranche", "Approved tier-eval configuration surfaces were consolidated.", migrateTierEvalTranche),
	probedMigration("runtime.final-layout-polish", "Final layout aliases were retired.", migrateFinalLayoutRenames),
	probedMigration("runtime.final-layout-kills", "Final layout tuning knobs were retired.", migrateFinalLayoutKills),
	{
		id: "runtime.media-models-consolidation",
		legacyRules: [createLegacyConfigRule(["tools", "media"], "Per-capability media model settings moved to capability-tagged tools.media.models entries.", hasLegacyMediaCapabilityConfig)],
		apply: (e, t) => {
			migrateMediaDeepgram(e, t);
			consolidateMediaCapabilityConfig(e, t);
		}
	},
	probedMigration("runtime.config-tranche", "Presentation-only preferences and duplicate tuning options moved to current defaults.", migrateConfigTranche),
	{
		id: "runtime.tuning-knobs-purge",
		legacyRules: [createLegacyConfigRule([], "Numeric runtime tuning knobs were retired and now use built-in defaults.", (e, t) => stripRetiredTuningKnobs(structuredClone(t)))],
		apply: stripRetiredTuningKnobs
	},
	{
		id: "runtime.ui-assistant-identity",
		legacyRules: [createLegacyConfigRule(["ui", "assistant"], "ui.assistant was retired; use agents.list[].identity instead.")],
		apply: removeUiAssistantIdentity
	},
	{
		id: "runtime.retired-config-keys",
		legacyRules: [
			createLegacyConfigRule(["tui"], "tui was retired and is ignored."),
			createLegacyConfigRule(["commands", "modelsWrite"], "commands.modelsWrite was retired and is ignored."),
			createLegacyConfigRule(["messages", "messagePrefix"], "messages.messagePrefix moved to channels.whatsapp.responsePrefix."),
			createLegacyConfigRule([
				"tools",
				"media",
				"asyncCompletion"
			], "tools.media.asyncCompletion.directSend was retired and is ignored."),
			createLegacyConfigRule([
				"tools",
				"message",
				"allowCrossContextSend"
			], "tools.message.allowCrossContextSend moved to tools.message.crossContext."),
			createLegacyConfigRule(["agents"], "Per-agent tools.message.allowCrossContextSend moved to tools.message.crossContext on the same agent.", (e) => {
				let t = false;
				visitAgentConfigScopes({ agents: e }, (e, n) => {
					t ||= n !== "agents.defaults" && Object.hasOwn(asNullableRecord(asNullableRecord(e.tools)?.message) ?? {}, "allowCrossContextSend");
				});
				return t;
			}),
			createLegacyConfigRule(["tools", "experimental"], "tools.experimental.planTool moved to tools.updatePlan."),
			createLegacyConfigRule([
				"talk",
				"realtime",
				"voice"
			], "talk.realtime.voice moved to talk.realtime.speakerVoice."),
			createLegacyConfigRule(["channels", "discord"], "Discord realtime voice aliases moved to speakerVoice.", hasDiscordRealtimeVoice),
			createLegacyConfigRule(["tools", "media"], "Legacy Deepgram options moved to providerOptions.deepgram.", hasMediaDeepgram),
			createLegacyConfigRule([
				"agents",
				"defaults",
				"compaction",
				"truncateAfterCompaction"
			], "agents.defaults.compaction.truncateAfterCompaction is retired; byte-triggered compaction now opts in via maxActiveTranscriptBytes alone."),
			createLegacyConfigRule([
				"agents",
				"defaults",
				"compaction",
				"memoryFlush",
				"model"
			], "agents.defaults.compaction.memoryFlush.model is retired; memory flushes now use the active session model and its fallback chain.")
		],
		apply: (e, t) => {
			migrateTruncateAfterCompaction(e, t);
			if (deleteRetiredPath(e, [
				"agents",
				"defaults",
				"compaction",
				"memoryFlush",
				"model"
			])) t.push("Removed agents.defaults.compaction.memoryFlush.model; memory flushes now use the active session model and its fallback chain.");
			if (deleteRetiredPath(e, ["tui"])) t.push("Removed retired tui config; the footer uses the default compact display.");
			if (deleteRetiredPath(e.commands, ["modelsWrite"])) t.push("Removed retired commands.modelsWrite.");
			const n = asNullableRecord(e.messages);
			if (n && Object.hasOwn(n, "messagePrefix")) {
				const r = ensureRecord(ensureRecord(e, "channels"), "whatsapp");
				if (r.responsePrefix === void 0) {
					r.responsePrefix = n.messagePrefix;
					t.push("Moved messages.messagePrefix → channels.whatsapp.responsePrefix.");
				} else t.push("Removed messages.messagePrefix (channels.whatsapp.responsePrefix already set).");
				delete n.messagePrefix;
			}
			if (deleteRetiredPath(asNullableRecord(e.tools)?.media, ["asyncCompletion"])) t.push("Removed retired tools.media.asyncCompletion.directSend.");
			migrateMessageCrossContext(e, t);
			const r = asNullableRecord(e.tools);
			const i = asNullableRecord(r?.experimental);
			if (r && i) {
				if (Object.hasOwn(i, "planTool") && r.updatePlan === void 0) {
					r.updatePlan = i.planTool;
					t.push("Moved tools.experimental.planTool → tools.updatePlan.");
				} else t.push("Removed tools.experimental; tools.updatePlan now owns the switch.");
				delete r.experimental;
			}
			const a = asNullableRecord(asNullableRecord(e.talk)?.realtime);
			moveLegacyConfigKey(a, "voice", "speakerVoice", "talk.realtime", t);
			migrateDiscordVoice(e, t);
			migrateMediaDeepgram(e, t);
		}
	}
];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.secrets-egress.ts
const HOST_KEYS = ["bypassHosts", "allowedHosts"];
function isValidExactHostname(e) {
	try {
		normalizeExactAllowedHost(e);
		return true;
	} catch {
		return false;
	}
}
const LEGACY_CONFIG_MIGRATION_RUNTIME_SECRETS_EGRESS = {
	id: "runtime.secrets-egress-proxy-hosts",
	legacyRules: HOST_KEYS.map((e) => ({
		path: [
			"secrets",
			"egressProxy",
			e
		],
		message: `secrets.egressProxy.${e} contains entries that are not usable hostnames. Run "openclaw doctor --fix".`,
		match: (e) => Array.isArray(e) && e.some((e) => typeof e !== "string" || !isValidExactHostname(e))
	})),
	apply(e, t) {
		const n = asNullableRecord(asNullableRecord(e.secrets)?.egressProxy);
		if (!n) return;
		for (const e of HOST_KEYS) {
			const r = n[e];
			if (!Array.isArray(r)) continue;
			const i = r.filter((e) => typeof e === "string" && isValidExactHostname(e));
			if (i.length === r.length) continue;
			const a = r.filter((e) => typeof e !== "string" || !isValidExactHostname(e));
			if (i.length > 0 || e === "allowedHosts") n[e] = i;
			else delete n[e];
			t.push(`Removed unusable secrets.egressProxy.${e} entries: ${a.map((e) => JSON.stringify(e)).join(", ")}.`);
		}
	}
};
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.session.ts
/** Match only parser-valid values that resolve to an unsafe zero-duration cutoff. */
function isZeroDuration(e) {
	if (e === false) return false;
	const t = normalizeStringifiedOptionalString(e);
	if (!t) return false;
	try {
		return parseDurationMs(t, { defaultUnit: "d" }) <= 0;
	} catch {
		return false;
	}
}
function hasZeroDuration(e, t) {
	const n = asNullableRecord(e);
	if (!n || !Object.hasOwn(n, t)) return false;
	return isZeroDuration(n[t]);
}
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_SESSION = [
	{
		id: "session.canonical-aliases",
		legacyRules: [{
			path: [
				"session",
				"maintenance",
				"pruneDays"
			],
			message: "session.maintenance.pruneDays was renamed to pruneAfter. Run \"openclaw doctor --fix\"."
		}, {
			path: [
				"session",
				"resetByType",
				"dm"
			],
			message: "session.resetByType.dm was renamed to direct. Run \"openclaw doctor --fix\"."
		}],
		apply: (e, t) => {
			const n = asNullableRecord(e.session);
			for (const [e, r, i] of [[
				"maintenance",
				"pruneDays",
				"pruneAfter"
			], [
				"resetByType",
				"dm",
				"direct"
			]]) {
				const a = asNullableRecord(n?.[e]);
				moveLegacyConfigKey(a, r, i, `session.${e}`, t);
			}
		}
	},
	{
		id: "session.maintenance.rotateBytes",
		legacyRules: [{
			path: ["session", "maintenance"],
			message: "session.maintenance.rotateBytes is deprecated and ignored; run \"openclaw doctor --fix\" to remove it.",
			match: (e) => Object.hasOwn(asNullableRecord(e) ?? {}, "rotateBytes")
		}],
		apply: (e, t) => {
			if (deleteRetiredPath(asNullableRecord(e.session)?.maintenance, ["rotateBytes"])) t.push("Removed deprecated session.maintenance.rotateBytes.");
		}
	},
	{
		id: "session.maintenance.zero-duration-retention",
		legacyRules: [{
			path: ["session", "maintenance"],
			message: "session.maintenance.pruneAfter is a zero duration — this causes immediate deletion of eligible stale/non-preserved session entries. Run \"openclaw doctor --fix\" to remove it so the documented 30d default applies.",
			match: (e) => hasZeroDuration(e, "pruneAfter")
		}, {
			path: ["session", "maintenance"],
			message: "session.maintenance.resetArchiveRetention is a zero duration — this causes immediate deletion of all reset transcript archives. Run \"openclaw doctor --fix\" to remove it so the keep-by-default archive retention applies.",
			match: (e) => hasZeroDuration(e, "resetArchiveRetention")
		}],
		apply: (e, t) => {
			const n = asNullableRecord(asNullableRecord(e.session)?.maintenance);
			if (!n) return;
			for (const e of ["resetArchiveRetention", "pruneAfter"]) {
				if (!hasZeroDuration(n, e)) continue;
				const r = String(n[e]);
				delete n[e];
				const i = e === "resetArchiveRetention" ? "keep-by-default archive retention applies" : "30d session-pruning default applies";
				t.push(`Removed session.maintenance.${e} "${r}" (zero duration); ${i}.`);
			}
		}
	}
];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.skills.ts
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_SKILLS = [
	{
		id: "skills.workshop.autonomous.enabled->mode",
		legacyRules: [{
			path: [
				"skills",
				"workshop",
				"autonomous",
				"enabled"
			],
			message: "skills.workshop.autonomous.enabled is retired; use skills.workshop.autonomous.mode. Run \"openclaw doctor --fix\"."
		}],
		apply: (e, t) => {
			const n = asNullableRecord(asNullableRecord(asNullableRecord(e.skills)?.workshop)?.autonomous);
			if (!n || !Object.hasOwn(n, "enabled")) return;
			if (n.mode === void 0) {
				const e = n.enabled === false ? "off" : "propose";
				n.mode = e;
				t.push(`Mapped skills.workshop.autonomous.enabled to mode: "${e}".`);
			} else t.push("Removed skills.workshop.autonomous.enabled because autonomous.mode is already set.");
			delete n.enabled;
		}
	},
	{
		id: "skills.workshop.proposal-settings-retired",
		legacyRules: ["approvalPolicy", "maxPending"].map((e) => ({
			path: [
				"skills",
				"workshop",
				e
			],
			message: `skills.workshop.${e} was removed with Skill Workshop proposals. Run "openclaw doctor --fix".`
		})),
		apply: (e, t) => {
			for (const n of ["approvalPolicy", "maxPending"]) if (deleteRetiredPath(e, [
				"skills",
				"workshop",
				n
			])) t.push(`Removed skills.workshop.${n}; Skill Workshop proposals were removed.`);
		}
	},
	{
		id: "skills.workshop.allowSymlinkTargetWrites-retired",
		legacyRules: [{
			path: [
				"skills",
				"workshop",
				"allowSymlinkTargetWrites"
			],
			message: "skills.workshop.allowSymlinkTargetWrites is retired; Skill Workshop writes only inside its own directory. Run \"openclaw doctor --fix\"."
		}],
		apply: (e, t) => {
			if (deleteRetiredPath(e, [
				"skills",
				"workshop",
				"allowSymlinkTargetWrites"
			])) t.push("Removed retired skills.workshop.allowSymlinkTargetWrites; Skill Workshop writes only inside its own directory.");
		}
	}
];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.system-agent.ts
function resolveMissingLegacySystemAgent(e) {
	const t = asNullableRecord(e.agents);
	if (!t) return;
	const n = asNullableRecord(t.defaults);
	const r = asNullableRecord(n?.systemAgent);
	if (t.defaults !== void 0 && !n || n?.systemAgent !== void 0 && !r || r?.agentId !== void 0) return;
	const i = t.entries !== void 0 ? asNullableRecord(t.entries) : parseLegacyAgentRoster(t.list)?.entries;
	if (!i) return;
	const a = Object.entries(i).flatMap(([e, t]) => {
		const n = asNullableRecord(t);
		return n && e.trim() ? [{
			id: normalizeAgentId(e),
			config: n
		}] : [];
	});
	const o = a.filter((e) => e.config.default === true);
	if (a.length < 2 || o.length > 1 || o.length === 1 && t.ownership !== "explicit") return;
	const s = o[0] ?? a.find((e) => e.id === "main");
	if (!s) return;
	return { agentId: s.id };
}
function findLegacySystemAgentOwnerIssue(e) {
	const t = asNullableRecord(e);
	return t && resolveMissingLegacySystemAgent(t) ? {
		path: "agents",
		message: "Legacy ambient operations have no system-agent owner; run \"openclaw doctor --fix\" to set agents.defaults.systemAgent.agentId from the default agent."
	} : void 0;
}
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_SYSTEM_AGENT = [{
	id: "crestodian-retired",
	legacyRules: [{
		path: ["crestodian"],
		message: "crestodian config was retired; system-agent rescue now uses built-in policy. Run \"openclaw doctor --fix\" to remove it."
	}],
	apply: (e, t) => {
		if (!Object.hasOwn(e, "crestodian")) return;
		delete e.crestodian;
		t.push("Removed retired crestodian config; system-agent rescue uses built-in policy.");
	}
}, {
	id: "runtime.legacy-system-agent-owner",
	apply: (e, t) => {
		const n = resolveMissingLegacySystemAgent(e);
		if (!n) return;
		const { agentId: r } = n;
		const i = ensureRecord(ensureRecord(e, "agents"), "defaults");
		ensureRecord(i, "systemAgent").agentId = r;
		t.push(`Set agents.defaults.systemAgent.agentId to ${r} for legacy ambient operations.`);
	}
}];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.tool-names.ts
const TOOL_NAME_MIGRATIONS = [{
	id: "tools.suggest-task-name",
	migration: TASK_SUGGESTION_TOOL_NAME_MIGRATION
}, {
	id: "tools.view-image-name",
	migration: IMAGE_INSPECTION_TOOL_NAME_MIGRATION
}];
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_TOOL_NAMES = TOOL_NAME_MIGRATIONS.map((e) => ({
	id: e.id,
	legacyRules: TOOL_POLICY_ROOTS.map((t) => ({
		path: [t],
		message: `Tool policies still rely on legacy ${e.migration.legacyName} coverage; run "openclaw doctor --fix" to preserve equivalent ${e.migration.canonicalName} access.`,
		match: (n) => findLegacyToolNamePaths(n, e.migration, [t]).length > 0
	})),
	apply: (t, n) => {
		const r = TOOL_POLICY_ROOTS.flatMap((n) => migrateLegacyToolNamePolicies(t[n], e.migration, [n]));
		if (r.length === 0) return;
		n.push(`Migrated legacy ${e.migration.legacyName} policy coverage to ${e.migration.canonicalName} in ${r.join(", ")}.`);
	}
}));
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.tool-policy-conflicts.ts
/** Capture independent profile/extras inheritance before changing any supplier. */
function collectProfileConsumers(e) {
	const t = /* @__PURE__ */ new Map();
	const n = asNullableRecord(e.tools);
	const r = [null];
	visitAgentEntries(e, (e) => r.push(asNullableRecord(e.tools)));
	if (!hasAgentRosterProperty(e)) r.push(asNullableRecord(asNullableRecord(asNullableRecord(e.agents)?.defaults)?.tools));
	const add = (e, n) => {
		const r = Array.isArray(n?.alsoAllow) ? n : Array.isArray(e?.alsoAllow) ? e : void 0;
		if (r) {
			const i = t.get(r) ?? [];
			i.push(n?.profile ?? e?.profile);
			t.set(r, i);
		}
	};
	for (const e of r) {
		add(n, e);
		const t = asNullableRecord(n?.byProvider) ?? void 0;
		const r = asNullableRecord(e?.byProvider) ?? void 0;
		const i = /* @__PURE__ */ new Set();
		for (const e of [...Object.keys(t ?? {}), ...Object.keys(r ?? {})]) {
			const t = normalizeToolProviderPolicyKey(e);
			const n = t.indexOf("/");
			i.add(t);
			i.add(n < 0 ? t : t.slice(0, n));
		}
		for (const e of i) {
			const n = e.indexOf("/");
			const i = {
				modelProvider: n < 0 ? e : e.slice(0, n),
				modelId: n < 0 ? void 0 : e.slice(n + 1)
			};
			const a = resolveProviderToolPolicyEntry({
				...i,
				byProvider: t
			});
			const o = resolveProviderToolPolicyEntry({
				...i,
				byProvider: r
			});
			add(asNullableRecord(a?.policy), asNullableRecord(o?.policy));
		}
	}
	return t;
}
function profileDoesNotNeedExtras(e, t) {
	if (e === void 0 || e === null) return true;
	if (typeof e !== "string") return false;
	const n = resolveCoreToolProfilePolicy(e);
	if (!n?.allow) return false;
	if (n.allow.includes("*")) return true;
	const r = normalizeToolList(t);
	if (r.length > 0 && createToolPolicyMatcher({ allow: r })("gateway")) return false;
	const i = new Set(normalizeToolList(n.allow));
	return r.every((e) => i.has(e));
}
function readGrantList(e, t) {
	const n = e[t];
	if (!Array.isArray(n) || n.length === 0) return null;
	return n.every((e) => typeof e === "string") ? n : null;
}
function visitConflictingToolPolicies(e, t, n) {
	if (Array.isArray(e)) {
		for (const [r, i] of e.entries()) visitConflictingToolPolicies(i, [...t, String(r)], n);
		return;
	}
	if (!isRecord(e)) return;
	if (t.at(-2) === "tools" && t.at(-1) === "sandbox") return;
	if (isToolPolicyPath(t)) {
		const r = readGrantList(e, "allow");
		const i = readGrantList(e, "alsoAllow");
		if (r && i) {
			const a = t.reduce((e, t) => /^[a-zA-Z_$][\w$]*$/.test(t) ? `${e}${e ? "." : ""}${t}` : `${e}[${JSON.stringify(t)}]`, "");
			n.push({
				scope: e,
				path: a,
				allow: r,
				alsoAllow: i
			});
		}
	}
	for (const [r, i] of Object.entries(e)) visitConflictingToolPolicies(i, [...t, r], n);
}
/** Reports tool policy scopes that set both allow and alsoAllow, without changing them. */
function findConflicts(e, t) {
	const n = [];
	visitConflictingToolPolicies(e, t, n);
	return n;
}
/** Explain unresolved intent through Doctor's finding channel, without claiming a repair. */
function collectToolPolicyConflictWarnings(e) {
	if (!isRecord(e)) return [];
	return TOOL_POLICY_ROOTS.flatMap((t) => findConflicts(e[t], [t]).map(({ path: e, allow: t, alsoAllow: n }) => {
		const r = uniqueStrings([...t, ...n]);
		return `Left ${e}.allow=${JSON.stringify(t)} and ${e}.alsoAllow=${JSON.stringify(n)} unchanged: merging may change profile grants or Gateway configuration-read access. To choose the profile plus its explicit extras, remove ${e}.allow (may broaden the explicit restriction). To choose the merged allowlist without profile extras, set ${e}.allow=${JSON.stringify(r)} and ${e}.alsoAllow=[] (may remove profile grants). Review these permissions before choosing.`;
	}));
}
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_TOOL_POLICY_CONFLICTS = [{
	id: "tools.allow-also-allow-conflict",
	legacyRules: TOOL_POLICY_ROOTS.map((e) => ({
		path: [e],
		message: "Tool policy sets both allow and alsoAllow in the same scope; run \"openclaw doctor --fix\" for a permission-preserving repair or manual guidance.",
		match: (t) => findConflicts(t, [e]).length > 0
	})),
	apply: (e, t) => {
		if (!isRecord(e)) return;
		const n = collectProfileConsumers(e);
		for (const r of TOOL_POLICY_ROOTS) for (const { scope: i, path: a, allow: o, alsoAllow: s } of findConflicts(e[r], [r])) {
			if (!(n.get(i) ?? []).every((e) => profileDoesNotNeedExtras(e, s))) continue;
			i.allow = uniqueStrings([...o, ...s]);
			i.alsoAllow = [];
			t.push(`Merged ${a}.alsoAllow into ${a}.allow.`);
		}
	}
}];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.tool-search.ts
const LEGACY_CONFIG_MIGRATION_RUNTIME_TOOL_SEARCH = {
	id: "tools.toolSearch.structured-only",
	legacyRules: [{
		path: [
			"tools",
			"toolSearch",
			"mode"
		],
		match: (e) => e === "code",
		message: "Tool Search code mode (tool_search_code) is retired; use structured Tool Search. Run \"openclaw doctor --fix\"."
	}, {
		path: [
			"tools",
			"toolSearch",
			"codeTimeoutMs"
		],
		message: "tools.toolSearch.codeTimeoutMs is retired. Run \"openclaw doctor --fix\"."
	}],
	apply: (e, t) => {
		const n = asNullableRecord(asNullableRecord(e.tools)?.toolSearch);
		if (!n) return;
		if (n.mode === "code") {
			n.mode = "tools";
			t.push("Tool Search code mode (tool_search_code) is retired; using structured Tool Search.");
		}
		if (Object.hasOwn(n, "codeTimeoutMs")) {
			delete n.codeTimeoutMs;
			if (typeof n.enabled !== "boolean" && !Object.keys(n).some((e) => e !== "enabled")) n.enabled = true;
			t.push("Removed tools.toolSearch.codeTimeoutMs; Tool Search no longer executes code.");
		}
	}
};
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.tts.ts
const LEGACY_TTS_PROVIDER_KEYS = [
	"openai",
	"elevenlabs",
	"microsoft",
	"edge"
];
const CHANNEL_ROOT_TTS_UNSUPPORTED_IDS = /* @__PURE__ */ new Set(["discord"]);
function isLegacyEdgeProviderId(e) {
	return typeof e === "string" && e.trim().toLowerCase() === "edge";
}
function hasLegacyTtsProviderKeys(e) {
	const t = asNullableRecord(e);
	if (!t) return false;
	if (isLegacyEdgeProviderId(t.provider)) return true;
	if (LEGACY_TTS_PROVIDER_KEYS.some((e) => Object.hasOwn(t, e))) return true;
	const n = asNullableRecord(t.providers);
	return Boolean(n && Object.hasOwn(n, "edge"));
}
function hasLegacyTtsEnabled(e) {
	return typeof asNullableRecord(e)?.enabled === "boolean";
}
function hasLegacyTtsSpeakerSelection(e) {
	for (const [t] of visitLegacyTtsSpeakerConfigs(e, "")) if ([
		"voice",
		"voiceName",
		"voiceId"
	].some((e) => Object.hasOwn(t, e))) return true;
	return false;
}
function hasLegacyTtsInLocations(e, t) {
	for (const [n] of visitKnownTtsConfigLocations(e)) if (t(n)) return true;
	return false;
}
function ttsLocationRules(e, t) {
	return Object.entries(t).map(([t, n]) => ({
		path: t === "plugins" ? ["plugins", "entries"] : [t],
		message: n,
		match: (n) => t === "tts" ? e(n) : hasLegacyTtsInLocations({ [t]: t === "plugins" ? { entries: n } : n }, e)
	}));
}
function mergeLegacyTtsProviderConfig(e, t, n, r = "tts") {
	const i = r === "providers" ? asNullableRecord(e.providers) : e;
	const a = asNullableRecord(i?.[t]);
	if (!i || !a) return false;
	const o = r === "providers" ? i : ensureRecord(e, "providers");
	const s = asNullableRecord(o[n]) ?? {};
	const c = structuredClone(s);
	mergeMissing(c, a);
	o[n] = c;
	delete i[t];
	return true;
}
function migrateLegacyTtsConfig(e, t, n) {
	if (!e) return;
	if (isLegacyEdgeProviderId(e.provider)) {
		e.provider = "microsoft";
		n.push(`Moved ${t}.provider "edge" → "microsoft".`);
	}
	for (const [r, i, a] of [
		[
			"openai",
			"openai",
			"tts"
		],
		[
			"elevenlabs",
			"elevenlabs",
			"tts"
		],
		[
			"microsoft",
			"microsoft",
			"tts"
		],
		[
			"edge",
			"microsoft",
			"providers"
		],
		[
			"edge",
			"microsoft",
			"tts"
		]
	]) {
		if (!mergeLegacyTtsProviderConfig(e, r, i, a)) continue;
		const o = a === "providers" ? `${t}.providers.${r}` : `${t}.${r}`;
		n.push(`Moved ${o} → ${t}.providers.${i}.`);
	}
}
function migrateLegacyTtsEnabled(e, t, n) {
	if (!e || typeof e.enabled !== "boolean") return;
	const r = e.enabled ? "always" : "off";
	delete e.enabled;
	if (typeof e.auto === "string" && e.auto.trim()) {
		n.push(`Removed ${t}.enabled because ${t}.auto is already set.`);
		return;
	}
	e.auto = r;
	n.push(`Moved ${t}.enabled → ${t}.auto "${r}".`);
}
function* visitLegacySpeakerSelectionScope(e, t) {
	const n = asNullableRecord(e);
	if (!n) return;
	for (const [e, r] of Object.entries(asNullableRecord(n.providers) ?? {})) {
		const n = asNullableRecord(r);
		if (!isBlockedObjectKey(e) && n) yield [n, `${t}.providers.${e}`];
	}
	for (const e of LEGACY_TTS_PROVIDER_KEYS) {
		const r = asNullableRecord(n[e]);
		if (r) yield [r, `${t}.${e}`];
	}
}
function* visitLegacyTtsSpeakerConfigs(e, t) {
	const n = asNullableRecord(e);
	yield* visitLegacySpeakerSelectionScope(n, t);
	for (const [e, r] of Object.entries(asNullableRecord(n?.personas) ?? {})) if (!isBlockedObjectKey(e)) yield* visitLegacySpeakerSelectionScope(r, `${t}.personas.${e}`);
}
function* visitKnownTtsConfigLocations(e) {
	yield [asNullableRecord(e.tts), "tts"];
	const t = [];
	visitAgentEntries(e, (e, n) => t.push([asNullableRecord(e.tts), `${n}.tts`]));
	yield* t;
	const n = asNullableRecord(e.channels);
	for (const [e, t] of Object.entries(n ?? {})) {
		if (isBlockedObjectKey(e)) continue;
		const n = asNullableRecord(t);
		const r = !CHANNEL_ROOT_TTS_UNSUPPORTED_IDS.has(e.trim().toLowerCase());
		if (r) yield [asNullableRecord(n?.tts), `channels.${e}.tts`];
		yield [asNullableRecord(asNullableRecord(n?.voice)?.tts), `channels.${e}.voice.tts`];
		for (const [t, i] of Object.entries(asNullableRecord(n?.accounts) ?? {})) {
			if (isBlockedObjectKey(t)) continue;
			const n = asNullableRecord(i);
			if (r) yield [asNullableRecord(n?.tts), `channels.${e}.accounts.${t}.tts`];
			yield [asNullableRecord(asNullableRecord(n?.voice)?.tts), `channels.${e}.accounts.${t}.voice.tts`];
		}
	}
	const r = asNullableRecord(asNullableRecord(e.plugins)?.entries);
	if (r && Object.prototype.propertyIsEnumerable.call(r, "voice-call")) {
		const e = asNullableRecord(r["voice-call"]);
		yield [asNullableRecord(asNullableRecord(e?.config)?.tts), "plugins.entries.voice-call.config.tts"];
	}
}
const LEGACY_CONFIG_MIGRATIONS_RUNTIME_TTS = [
	{
		id: "tts.top-level-owner",
		legacyRules: [{
			path: ["messages", "tts"],
			message: "messages.tts moved to top-level tts. Run \"openclaw doctor --fix\"."
		}],
		apply: (e, t) => {
			const n = asNullableRecord(e.messages);
			if (!n || !Object.hasOwn(n, "tts")) return;
			const r = asNullableRecord(n.tts);
			if (!r) {
				delete n.tts;
				t.push("Removed messages.tts (invalid value).");
				return;
			}
			const i = asNullableRecord(r.realtime);
			if (i) {
				const n = i.speakerVoice ?? i.voice;
				const a = asNullableRecord(e.talk) ?? {};
				const o = asNullableRecord(a.realtime) ?? {};
				if (n !== void 0 && o.speakerVoice === void 0) {
					o.speakerVoice = n;
					a.realtime = o;
					e.talk = a;
					t.push("Moved messages.tts.realtime voice → talk.realtime.speakerVoice.");
				} else t.push("Removed messages.tts.realtime (talk.realtime already configured).");
				delete r.realtime;
			}
			const a = asNullableRecord(e.tts) ?? {};
			mergeMissing(a, r);
			e.tts = a;
			delete n.tts;
			t.push("Moved messages.tts to top-level tts.");
		}
	},
	{
		id: "tts.providers-generic-shape",
		legacyRules: ttsLocationRules(hasLegacyTtsProviderKeys, {
			tts: "tts legacy provider aliases/keys are legacy; use provider: \"microsoft\" and tts.providers.<provider>. Run \"openclaw doctor --fix\".",
			plugins: "plugins.entries.voice-call.config.tts legacy provider aliases/keys are legacy; use provider: \"microsoft\" and plugins.entries.voice-call.config.tts.providers.<provider>. Run \"openclaw doctor --fix\"."
		}),
		apply: (e, t) => {
			for (const [n, r] of visitKnownTtsConfigLocations({
				tts: e.tts,
				plugins: e.plugins
			})) migrateLegacyTtsConfig(n, r, t);
		}
	},
	{
		id: "tts.speaker-selection-keys",
		legacyRules: ttsLocationRules(hasLegacyTtsSpeakerSelection, {
			tts: "tts speaker selection fields voice/voiceName/voiceId are legacy; use speakerVoice or speakerVoiceId. Run \"openclaw doctor --fix\".",
			agents: "agents.entries.*.tts speaker selection fields voice/voiceName/voiceId are legacy; use speakerVoice or speakerVoiceId. Run \"openclaw doctor --fix\".",
			channels: "supported channel TTS speaker selection fields voice/voiceName/voiceId are legacy; use speakerVoice or speakerVoiceId. Run \"openclaw doctor --fix\".",
			plugins: "plugins.entries.voice-call.config.tts speaker selection fields voice/voiceName/voiceId are legacy; use speakerVoice or speakerVoiceId. Run \"openclaw doctor --fix\"."
		}),
		apply: (e, t) => {
			for (const [n, r] of visitKnownTtsConfigLocations(e)) for (const [e, i] of visitLegacyTtsSpeakerConfigs(n, r)) for (const [n, r] of [
				["voice", "speakerVoice"],
				["voiceName", "speakerVoice"],
				["voiceId", "speakerVoiceId"]
			]) moveLegacyConfigKey(e, n, r, i, t);
		}
	},
	{
		id: "tts.enabled-auto-mode",
		legacyRules: ttsLocationRules(hasLegacyTtsEnabled, {
			tts: "tts.enabled is legacy; use tts.auto. Run \"openclaw doctor --fix\".",
			agents: "agents.entries.*.tts.enabled is legacy; use agents.entries.*.tts.auto. Run \"openclaw doctor --fix\".",
			channels: "supported channel TTS enabled fields are legacy; use the same TTS block auto field. Run \"openclaw doctor --fix\".",
			plugins: "plugins.entries.voice-call.config.tts.enabled is legacy; use plugins.entries.voice-call.config.tts.auto. Run \"openclaw doctor --fix\"."
		}),
		apply: (e, t) => {
			for (const [n, r] of visitKnownTtsConfigLocations(e)) migrateLegacyTtsEnabled(n, r, t);
		}
	}
];
//#endregion
//#region src/commands/doctor/shared/legacy-talk-config-normalizer.ts
/** Preserve flat speech fields for their plugin-owned migration. */
function normalizeLegacyTalkConfig(e, t) {
	const n = e.talk;
	if (!isRecord(n)) return e;
	const r = normalizeTalkSection(n) ?? {};
	for (const e of [
		"voiceId",
		"voiceAliases",
		"modelId",
		"outputFormat",
		"apiKey"
	]) if (n[e] !== void 0) r[e] = n[e];
	if (Object.keys(r).length === 0 || isDeepStrictEqual(r, n)) return e;
	t.push("Normalized talk.provider/providers shape (trimmed provider ids and merged missing compatibility fields).");
	return {
		...e,
		talk: r
	};
}
function prepareVoiceCallTalkInheritance(e) {
	const t = asNullableRecord(asNullableRecord(e.plugins)?.entries);
	const n = asNullableRecord(asNullableRecord(t?.["voice-call"])?.config);
	const r = asNullableRecord(n?.realtime);
	if (!r || e.talk !== void 0 && !isRecord(e.talk)) return;
	const i = normalizeTalkRealtimeConfig({
		provider: r.provider,
		providers: r.providers
	});
	if (!i) return;
	const a = [];
	const o = normalizeLegacyTalkConfig(e, a);
	const s = o.talk?.realtime;
	const c = Object.keys(s?.providers ?? {});
	const l = { ...s?.providers };
	for (const [e, t] of Object.entries(i.providers ?? {})) if (findNormalizedProviderKey(l, e) === void 0) l[e] = t;
	const u = Object.keys(l);
	const d = s?.provider ?? (c.length === 1 ? c[0] : i.provider) ?? (u.length === 1 ? u[0] : void 0);
	const f = {
		...s,
		...d ? { provider: d } : {},
		...u.length > 0 ? { providers: l } : {}
	};
	if (isDeepStrictEqual(s, f)) return;
	return {
		talk: {
			...o.talk,
			realtime: f
		},
		changes: [...a, "Copied inherited Voice Call realtime settings into talk.realtime; explicit Talk settings were preserved."]
	};
}
const LEGACY_TALK_VOICE_CALL_INHERITANCE = {
	id: "talk.voice-call-realtime-inheritance",
	legacyRules: [{
		path: [
			"plugins",
			"entries",
			"voice-call",
			"config",
			"realtime"
		],
		message: "Inherited Talk realtime settings must be persisted under talk.realtime.",
		match: (e, t) => prepareVoiceCallTalkInheritance(t) !== void 0
	}],
	apply: (e, t) => {
		const n = prepareVoiceCallTalkInheritance(e);
		if (n) {
			e.talk = n.talk;
			t.push(...n.changes);
		}
	}
};
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.runtime.ts
const LEGACY_CONFIG_MIGRATIONS_RUNTIME = [
	LEGACY_CONFIG_MIGRATION_RUNTIME_CYBER_FAILOVER,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_AGENTS,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_CLI_BACKENDS,
	LEGACY_CONFIG_MIGRATION_RUNTIME_CODE_MODE,
	LEGACY_CONFIG_MIGRATION_RUNTIME_CODE_MODE_EXECUTOR,
	LEGACY_CONFIG_MIGRATION_RUNTIME_TOOL_SEARCH,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_CRON,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_DIAGNOSTICS,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_GATEWAY,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_MCP,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_MODELS,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_PROVIDERS,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_TTS,
	LEGACY_TALK_VOICE_CALL_INHERITANCE,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_RETIRED,
	LEGACY_CONFIG_MIGRATION_RUNTIME_SECRETS_EGRESS,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_SESSION,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_SKILLS,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_TOOL_NAMES,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_TOOL_POLICY_CONFLICTS,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_ENTRIES,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME_SYSTEM_AGENT
];
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.web-search.ts
const LEGACY_CONFIG_MIGRATIONS_WEB_SEARCH = [{
	id: "tools.web.search-provider-config->plugins.entries",
	legacyRules: [{
		path: [
			"tools",
			"web",
			"search"
		],
		message: "tools.web.search provider-owned config moved to plugins.entries.<plugin>.config.webSearch. Run \"openclaw doctor --fix\".",
		match: (e, t) => listLegacyWebSearchConfigPaths(t).length > 0,
		requireSourceLiteral: true
	}],
	apply: (e, t) => {
		const n = migrateLegacyWebSearchConfig(e);
		if (n.changes.length === 0) return;
		for (const t of Object.keys(e)) delete e[t];
		Object.assign(e, n.config);
		t.push(...n.changes);
	}
}];
//#endregion
//#region src/commands/doctor/shared/legacy-context-budget.ts
const MODEL_CONTEXT_TOKENS_REPLACEMENT = "models.providers.<provider>.models[].contextTokens";
function hasLegacyContextBudgetConfig(e) {
	if (!isRecord(e)) return false;
	const t = isRecord(e.models) ? e.models.providers : void 0;
	if (isRecord(t) && Object.values(t).some((e) => isRecord(e) && (Object.hasOwn(e, "contextTokens") || Object.hasOwn(e, "contextWindow")))) return true;
	return !legacyAgentContextBudgets(e).next().done;
}
function* legacyAgentContextBudgets(e) {
	const t = e.agents;
	if (!isRecord(t)) return;
	const n = [[t.defaults, "agents.defaults.contextTokens"]];
	if (isRecord(t.entries)) n.push(...Object.entries(t.entries).map(([e, t]) => [t, `agents.entries.${e}.contextTokens`]));
	if (Array.isArray(t.list)) for (const [e, r] of t.list.entries()) n.push([r, `agents.list[${e}].contextTokens`]);
	for (const [e, t] of n) if (isRecord(e) && Object.hasOwn(e, "contextTokens")) yield {
		record: e,
		path: t
	};
}
function migrateProviderContextBudgets(e, t, n) {
	const r = isRecord(e.models) ? e.models.providers : void 0;
	if (!isRecord(r)) return;
	for (const [e, i] of Object.entries(r)) {
		if (!isRecord(i)) continue;
		for (const r of ["contextTokens", "contextWindow"]) {
			if (!Object.hasOwn(i, r)) continue;
			const a = `models.providers.${e}.${r}`;
			if (Array.isArray(i.models) && i.models.length > 0) {
				for (const [n, o] of i.models.entries()) {
					if (!isRecord(o) || o[r] !== void 0) continue;
					o[r] = i[r];
					t.push({
						path: a,
						message: `${a} → models.providers.${e}.models[${n}].${r}.`
					});
				}
				delete i[r];
				t.push({
					path: a,
					message: `Removed ${a} after baking it into explicit model entries.`
				});
				continue;
			}
			delete i[r];
			t.push({
				path: a,
				message: `Removed ${a}.`
			});
			n.push({
				path: a,
				message: `${a} had no explicit model entries to receive its value; use ${MODEL_CONTEXT_TOKENS_REPLACEMENT} instead.`
			});
		}
	}
}
/** Doctor preserves provider budgets and reports unrepresentable agent caps before validation. */
function migrateLegacyContextBudgetConfig(e) {
	if (!hasLegacyContextBudgetConfig(e)) return {
		config: e,
		changed: false,
		changes: [],
		warnings: []
	};
	const t = structuredClone(e);
	const n = [];
	const r = [];
	migrateProviderContextBudgets(t, n, r);
	for (const { record: e, path: i } of legacyAgentContextBudgets(t)) {
		delete e.contextTokens;
		n.push({
			path: i,
			message: `Removed ${i}.`
		});
		r.push({
			path: i,
			message: `${i} cannot be represented per model; use ${MODEL_CONTEXT_TOKENS_REPLACEMENT} instead.`
		});
	}
	return {
		config: t,
		changed: true,
		changes: n,
		warnings: r
	};
}
//#endregion
//#region src/commands/doctor/shared/legacy-copilot-discovery.ts
/** Drop the retired discovery switch before validation, including malformed values. */
function removeLegacyCopilotDiscovery(e) {
	const t = isRecord(e.plugins) ? e.plugins : void 0;
	const n = isRecord(t?.entries) ? t.entries : void 0;
	const r = isRecord(n?.["github-copilot"]) ? n["github-copilot"] : void 0;
	const i = isRecord(r?.config) ? r.config : void 0;
	const a = isRecord(i?.discovery) ? i.discovery : void 0;
	if (!a || !Object.hasOwn(a, "enabled") && Object.keys(a).length > 0) return e;
	const { enabled: o, ...s } = a;
	const c = { ...i };
	if (Object.keys(s).length === 0) delete c.discovery;
	else c.discovery = s;
	const l = {
		...e,
		plugins: {
			...t,
			entries: {
				...n,
				"github-copilot": {
					...r,
					config: c
				}
			}
		}
	};
	setRetainedLegacyDefaultAgentId(l, getRetainedLegacyDefaultAgentId(e));
	return l;
}
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrations.ts
const LEGACY_CONFIG_MIGRATIONS = [
	{
		id: "plugins.empty-installs",
		legacyRules: [{
			path: ["plugins", "installs"],
			message: "Empty plugins.installs is retired; run \"openclaw doctor --fix\" to remove it.",
			match: (e) => isRecord(e) && Object.keys(e).length === 0
		}],
		apply: (e, t) => {
			const n = isRecord(e.plugins) ? e.plugins : void 0;
			if (isRecord(n?.installs) && Object.keys(n.installs).length === 0) {
				delete n.installs;
				t.push("Removed empty retired plugins.installs; install records remain in SQLite.");
			}
		}
	},
	...LEGACY_CONFIG_MIGRATIONS_CHANNELS,
	...LEGACY_CONFIG_MIGRATIONS_QQBOT,
	...LEGACY_CONFIG_MIGRATIONS_AUDIO,
	...LEGACY_CONFIG_MIGRATIONS_RUNTIME,
	...LEGACY_CONFIG_MIGRATIONS_WEB_SEARCH,
	LEGACY_CONFIG_MIGRATION_TOOLS_BY_SENDER
];
const LEGACY_HEARTBEAT_CONFIG_RULES = [
	{
		path: [
			"agents",
			"defaults",
			"heartbeat"
		],
		message: "Heartbeat configuration retired; run \"openclaw doctor --fix\" to preserve it as an editable automation."
	},
	{
		path: ["agents", "entries"],
		match: (e) => isRecord(e) && Object.values(e).some((e) => isRecord(e) && e.heartbeat !== void 0),
		message: "Per-agent heartbeat configuration requires \"openclaw doctor --fix\" before startup."
	},
	{
		path: ["agents", "list"],
		match: (e) => Array.isArray(e) && e.some((e) => isRecord(e) && e.heartbeat !== void 0),
		message: "Per-agent heartbeat configuration requires \"openclaw doctor --fix\" before startup."
	},
	{
		path: ["channels"],
		match: (e) => isRecord(e) && Object.entries(e).some(([e, t]) => {
			const hasVisibility = (t, n = false) => isRecord(t) && (selectLegacyHeartbeatVisibility(e, t) !== void 0 || isRecord(t.heartbeat) && (n || Object.keys(t.heartbeat).length > 0) && Object.keys(t.heartbeat).every((e) => [
				"showOk",
				"showAlerts",
				"useIndicator"
			].includes(e)));
			return hasVisibility(t, e === "defaults") || isRecord(t) && isRecord(t.accounts) && Object.values(t.accounts).some((e) => hasVisibility(e));
		}),
		message: "Channel heartbeat visibility requires \"openclaw doctor --fix\" before startup; transport heartbeat settings are not retired."
	}
];
/** Aggregated legacy config rules used for doctor preview issue detection. */
const LEGACY_CONFIG_MIGRATION_RULES = [
	...LEGACY_HEARTBEAT_CONFIG_RULES,
	...LEGACY_CONFIG_MIGRATIONS.flatMap((e) => e.legacyRules ?? []),
	{
		path: [],
		message: "Context budgets use models.providers.<provider>.models[].contextTokens; run \"openclaw doctor --fix\" to migrate retired provider and agent keys.",
		match: hasLegacyContextBudgetConfig
	},
	{
		path: [
			"plugins",
			"entries",
			"github-copilot",
			"config",
			"discovery"
		],
		message: "The GitHub Copilot discovery switch was retired; run \"openclaw doctor --fix\".",
		match: (e, t) => removeLegacyCopilotDiscovery(t) !== t
	}
];
//#endregion
export { LEGACY_TALK_VOICE_CALL_INHERITANCE as a, findLegacySystemAgentOwnerIssue as c, migrateLegacyWebSearchConfig as d, migrateLegacyXSearchConfig as f, migrateLegacyContextBudgetConfig as i, stripRetiredTuningKnobs as l, LEGACY_CONFIG_MIGRATION_RULES as n, normalizeLegacyTalkConfig as o, removeLegacyCopilotDiscovery as r, collectToolPolicyConflictWarnings as s, LEGACY_CONFIG_MIGRATIONS as t, migrateLegacyWebFetchConfig as u };