UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2,647 lines • 107 kB
import { A as normalizeStringEntries, B as isRecord, D as isBlockedObjectKey, E as hasLegacyAccountStreamingAliases, F as normalizeOptionalString, L as asNullableRecord, N as normalizeLowercaseStringOrEmpty, P as normalizeOptionalLowercaseString, a as defineChannelAliasMigration, d as normalizeAccountId, j as normalizeUniqueStringEntries, k as normalizeChannelConfigEntries, n as defineKeyMoveMigration, r as defineStrayPluginEntryConfigMigration } from "./runtime-doctor-migrations-JGL9tD-z.js";
import { t as createLegacyWebhookListenerDoctorContract } from "./legacy-webhook-listener-migration-s2MKGUiS.js";
import { _ as createAccountListHelpers, c as LruCache, v as hasConfiguredAccountValue } from "./account-core-u1qUW4Od.js";
import "./account-resolution-D0wF8tG-.js";
import { _ as toJSONSchema, a as discriminatedUnion, c as number, d as record, f as strictObject, g as unknown, h as union, i as boolean, l as object, m as tuple, n as _null, p as string, r as array, s as literal, t as _enum, u as preprocess } from "./schemas-DkgI5ZNg.js";
import { a as ENV_SECRET_REF_ID_RE, o as SECRET_PROVIDER_ALIAS_PATTERN, t as hasConfiguredSecretInput } from "./types.secrets-Dt3OCDui.js";
import { n as sensitive, r as SecretInputSchema, t as buildSecretInputSchema } from "./secret-input-BZwvogpO.js";
import "./string-coerce-runtime-DkwxSzQP.js";
import "./boundary-path-BJflOsrm.js";
import path, { posix } from "node:path";
import net from "node:net";
import { domainToASCII } from "node:url";
import "typebox/guard";
import "typebox/schema";
import "typebox/format";
//#region node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/compat.js
/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
const ZodIssueCode = {
	invalid_type: "invalid_type",
	too_big: "too_big",
	too_small: "too_small",
	invalid_format: "invalid_format",
	not_multiple_of: "not_multiple_of",
	unrecognized_keys: "unrecognized_keys",
	invalid_union: "invalid_union",
	invalid_key: "invalid_key",
	invalid_element: "invalid_element",
	invalid_value: "invalid_value",
	custom: "custom"
};
/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
var ZodFirstPartyTypeKind;
ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
//#endregion
//#region extensions/feishu/src/accounts.ts
const { listAccountIds: listFeishuAccountIds, resolveDefaultAccountId: resolveDefaultFeishuAccountId, resolveAccountConfig: resolveMergedFeishuAccountConfig } = createAccountListHelpers("feishu", {
	allowUnlistedDefaultAccount: true,
	omitKeys: ["defaultAccount"],
	nestedObjectKeys: ["tools"],
	hasImplicitDefaultAccount: (e) => {
		const t = e.channels?.feishu;
		return hasConfiguredAccountValue(t?.appId) && hasConfiguredAccountValue(t?.appSecret);
	}
});
function mergeFeishuAccountConfig(e, t) {
	const n = e.channels?.feishu;
	const r = resolveMergedFeishuAccountConfig(e, t);
	const i = n?.tools;
	if (r.tools === void 0 && i !== void 0) return {
		...r,
		tools: i
	};
	if (i?.bitable === false) return {
		...r,
		tools: {
			...r.tools,
			bitable: false
		}
	};
	return r;
}
//#endregion
//#region src/agents/sandbox/network-mode.ts
/**
* Docker network mode safety helpers.
*
* Flags host networking and container namespace joins because they bypass normal sandbox network isolation.
*/
/** Normalizes optional Docker network mode strings for policy checks. */
function normalizeNetworkMode(e) {
	return normalizeOptionalLowercaseString(e) || void 0;
}
/** Returns the concrete block reason for dangerous network modes, if blocked. */
function getBlockedNetworkModeReason(e) {
	const t = normalizeNetworkMode(e.network);
	if (!t) return null;
	if (t === "host") return "host";
	if (t.startsWith("container:") && e.allowContainerNamespaceJoin !== true) return "container_namespace_join";
	return null;
}
//#endregion
//#region src/infra/exec-approvals-core.ts
function resolveExecModeFromPolicy(e) {
	if (e.security === "deny") return "deny";
	if (e.security === "allowlist" && e.ask === "off") return "allowlist";
	if (e.security === "full" && e.ask !== "always") return "full";
	return "ask";
}
function resolveExactExecModeFromPolicy(e) {
	if (e.ask === "always" || e.security === "full" && e.ask === "on-miss") return null;
	return resolveExecModeFromPolicy(e);
}
//#endregion
//#region src/config/web-search-legacy-provider-keys.ts
/** Legacy config keys that used to live under web search provider config. */
const LEGACY_WEB_SEARCH_PROVIDER_CONFIG_KEYS = /* @__PURE__ */ new Set([
	"brave",
	"duckduckgo",
	"exa",
	"firecrawl",
	"gemini",
	"grok",
	"kimi",
	"minimax",
	"ollama",
	"perplexity",
	"searxng",
	"tavily"
]);
//#endregion
//#region packages/model-catalog-core/src/provider-id.ts
function normalizeProviderId(e) {
	return normalizeLowercaseStringOrEmpty(e);
}
//#endregion
//#region packages/model-catalog-core/src/model-catalog-refs.ts
/** Parse a strict provider/model reference without normalizing either segment. */
function parseProviderModelRef(e) {
	const t = e.trim();
	const n = t.indexOf("/");
	if (n <= 0 || n >= t.length - 1) return null;
	const r = t.slice(0, n).trim();
	const i = t.slice(n + 1).trim();
	return r && i ? {
		provider: r,
		model: i
	} : null;
}
//#endregion
//#region src/auto-reply/thinking.shared.ts
/** Canonical thinking level values accepted by chat commands and session state. */
const ALL_THINKING_LEVELS = [
	"off",
	"minimal",
	"low",
	"medium",
	"high",
	"xhigh",
	"adaptive",
	"max",
	"ultra"
];
const THINKING_LEVELS_HELP = ALL_THINKING_LEVELS.join("|");
//#endregion
//#region src/config/zod-schema.agent-model.ts
/** Decision providers require an explicit model; an empty value disables the role. */
const DecisionModelSchema = string().trim().max(512).refine((e) => e === "" || parseProviderModelRef(e) !== null, "Expected provider/model, or an empty string to disable decision models.");
/** Schema for agent model config accepting a string or fallback object. */
const AgentModelSchema = union([string(), strictObject({
	/** Primary model (provider/model). */
	primary: string().optional(),
	/** Per-agent model fallbacks (provider/model). */
	fallbacks: array(string()).optional()
})]);
const AgentToolModelSchema = union([string(), strictObject({
	primary: string().optional(),
	/** Per-tool model fallbacks (provider/model). */
	fallbacks: array(string()).optional(),
	/** Optional provider request timeout in milliseconds for capabilities that support it. */
	timeoutMs: number().int().positive().optional()
})]);
//#endregion
//#region src/config/zod-schema.agent-entry-base.ts
/** Persisted client-side summary ceiling; the active model token budget may require less. */
const AgentCompactionMaxSummaryCharsSchema = number().int().min(1e3).max(2e5);
const AgentRuntimePolicySchema = strictObject({ id: string().optional() }).optional();
const AgentModelRuntimeEntrySchema = strictObject({
	/** Optional display/lookup alias for this provider/model entry. */
	alias: string().optional(),
	/** Provider-specific API parameters (e.g., GLM-4.7 thinking mode). */
	params: record(string(), unknown()).optional(),
	/** Optional agent execution runtime for this specific provider/model entry. */
	agentRuntime: AgentRuntimePolicySchema,
	/** Additional explicit runtime choices in the model picker; does not change the default. */
	pickerRuntimes: array(string().trim().min(1).max(128).regex(/^[a-z][a-z0-9-]*$/).refine((e) => e !== "auto" && e !== "default")).max(8).optional(),
	/** OpenClaw Code Mode override; omitted inherits the enclosing activation policy. */
	codeMode: boolean().optional(),
	/** Enable streaming for this model (default: true, false for Ollama to avoid SDK issue #1205). */
	streaming: boolean().optional()
});
const AgentModelMapSchema = record(string(), AgentModelRuntimeEntrySchema).superRefine((e, t) => {
	for (const [n, r] of Object.entries(e)) for (const [e, i] of [["pickerRuntimes", "Picker runtimes require an exact provider/model entry."], ["codeMode", "Code Mode requires an exact provider/model entry; wildcard and bare model keys are not supported."]]) if (r[e] !== void 0 && (n.includes("*") || !parseProviderModelRef(n))) t.addIssue({
		code: ZodIssueCode.custom,
		path: [n, e],
		message: i
	});
});
const AgentModelPolicySchema = strictObject({ 
/** Model refs allowed for session/run overrides. Empty or omitted allows any model. */
allow: array(string()).optional() });
const AgentRuntimeAcpSchema = strictObject({
	/** ACP harness adapter id (for example codex, claude). */
	agent: string().optional(),
	/** Optional ACP backend override for this agent runtime. */
	backend: string().optional(),
	/** Optional ACP session mode override. */
	mode: _enum(["persistent", "oneshot"]).optional(),
	/** Optional runtime working directory override. */
	cwd: string().optional()
}).optional();
const AgentRuntimeSchema = union([strictObject({ type: literal("embedded") }), strictObject({
	type: literal("acp"),
	acp: AgentRuntimeAcpSchema
})]).optional();
const AgentEntryBaseSchema = strictObject({
	id: string(),
	name: string().optional(),
	description: string().optional(),
	workspace: string().optional(),
	cwd: string().optional(),
	agentDir: string().optional(),
	model: AgentModelSchema.optional(),
	utilityModel: AgentModelSchema.optional(),
	decisionModel: DecisionModelSchema.optional(),
	models: AgentModelMapSchema.optional(),
	modelPolicy: AgentModelPolicySchema.optional(),
	thinkingDefault: _enum(ALL_THINKING_LEVELS).optional(),
	verboseDefault: _enum([
		"off",
		"on",
		"full"
	]).optional(),
	toolProgressDetail: _enum(["explain", "raw"]).optional(),
	reasoningDefault: _enum([
		"on",
		"off",
		"stream"
	]).optional(),
	fastModeDefault: union([
		boolean(),
		literal("auto"),
		literal("ultrafast")
	]).optional(),
	contextInjection: union([
		literal("always"),
		literal("continuation-skip"),
		literal("never")
	]).optional(),
	bootstrapMaxChars: number().int().positive().optional(),
	bootstrapTotalMaxChars: number().int().positive().optional(),
	experimental: strictObject({ localModelLean: boolean().optional() }).optional(),
	skills: array(string()).optional(),
	subagents: strictObject({
		delegationMode: _enum(["suggest", "prefer"]).optional(),
		allowAgents: array(string()).optional(),
		delegateToolsTo: array(string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/)).optional(),
		model: AgentModelSchema.optional(),
		thinking: string().optional(),
		requireAgentId: boolean().optional()
	}).optional(),
	embeddedAgent: strictObject({ executionContract: union([literal("default"), literal("strict-agentic")]).optional() }).optional(),
	compaction: strictObject({ 
	/** Override the default persisted client-side summary character ceiling. */
maxSummaryChars: AgentCompactionMaxSummaryCharsSchema.optional() }).optional(),
	params: record(string(), unknown()).optional(),
	runtime: AgentRuntimeSchema
});
//#endregion
//#region src/infra/exec-safety.ts
const SHELL_METACHARS = /[;&|`$<>]/;
const CONTROL_CHARS = /[\r\n]/;
const QUOTE_CHARS = /["']/;
const BARE_NAME_PATTERN = /^[A-Za-z0-9._+-]+$/;
function isLikelyPath(e) {
	return e.startsWith(".") || e.startsWith("~") || e.includes("/") || e.includes("\\");
}
/** Validates that a configured executable value cannot smuggle shell syntax. */
function isSafeExecutableValue(e) {
	if (!e) return false;
	const t = e.trim();
	if (!t || t.includes("\0") || CONTROL_CHARS.test(t) || SHELL_METACHARS.test(t) || QUOTE_CHARS.test(t)) return false;
	if (isLikelyPath(t)) return true;
	if (t.startsWith("-")) return false;
	return BARE_NAME_PATTERN.test(t);
}
//#endregion
//#region src/secrets/exact-hostname.ts
/**
* Canonical exact-host contract shared by per-secret destination bindings and the
* egress-proxy config allowlists: lowercase ASCII/punycode, unbracketed IP literals,
* no wildcard, scheme, path, or port. Throws with an operator-actionable message so
* config validation and the secret store surface the same policy.
*/
function normalizeExactAllowedHost(e) {
	const t = e.trim().toLowerCase().replace(/\.+$/u, "");
	if (t.includes("*")) throw new Error(`Allowed host "${e}" cannot contain a wildcard; use one exact hostname.`);
	const n = t.startsWith("[") && t.endsWith("]") ? t.slice(1, -1) : t;
	if (net.isIP(n)) return n;
	if (!n || n.includes(":") || /[\s/?#@]/u.test(n)) throw new Error(`Allowed host "${e}" must be a hostname without a scheme, path, wildcard, or port.`);
	const r = domainToASCII(n);
	if (!r || r.length > 253 || r.split(".").some((e) => !e || e.length > 63 || e.startsWith("-") || e.endsWith("-") || !/^[a-z0-9-]+$/u.test(e))) throw new Error(`Allowed host "${e}" is not a valid hostname.`);
	return r;
}
//#endregion
//#region packages/llm-core/src/model-data.ts
const MODEL_DATA_APIS = [
	"openai-completions",
	"openai-responses",
	"openai-chatgpt-responses",
	"anthropic-messages",
	"google-generative-ai",
	"google-interactions",
	"google-vertex",
	"github-copilot",
	"bedrock-converse-stream",
	"ollama",
	"pi-messages",
	"azure-openai-responses"
];
const MODEL_DATA_THINKING_FORMATS = [
	"openai",
	"openrouter",
	"deepseek",
	"together",
	"qwen",
	"qwen-chat-template",
	"zai"
];
//#endregion
//#region src/config/model-config-vocabulary.ts
/** Provider API adapter ids accepted by model/provider config and schema generation. */
const MODEL_APIS = [...MODEL_DATA_APIS];
/** Thinking/reasoning payload dialects emitted by OpenAI-compatible providers. */
const MODEL_THINKING_FORMATS = [...MODEL_DATA_THINKING_FORMATS];
//#endregion
//#region src/config/model-provider-overlay-ids.ts
const BUILT_IN_MODEL_PROVIDER_OVERLAY_IDS = /* @__PURE__ */ new Set([
	"amazon-bedrock",
	"amazon-bedrock-mantle",
	"anthropic",
	"anthropic-vertex",
	"arcee",
	"azure-openai-responses",
	"byteplus",
	"byteplus-plan",
	"cerebras",
	"chutes",
	"claude-cli",
	"clawrouter",
	"cloudflare-ai-gateway",
	"codex",
	"comfy",
	"copilot-proxy",
	"dashscope",
	"deepinfra",
	"deepseek",
	"fal",
	"fireworks",
	"github-copilot",
	"gmi",
	"gmi-cloud",
	"gmicloud",
	"google",
	"google-antigravity",
	"google-gemini-cli",
	"google-vertex",
	"groq",
	"huggingface",
	"kie",
	"kilocode",
	"kimi",
	"kimi-coding",
	"litellm",
	"lmstudio",
	"meta",
	"microsoft-foundry",
	"minimax",
	"minimax-portal",
	"mistral",
	"modelstudio",
	"moonshot",
	"moonshot-ai",
	"moonshotai",
	"nvidia",
	"novita",
	"novita-ai",
	"novitaai",
	"ollama",
	"ollama-cloud",
	"openai",
	"opencode",
	"opencode-go",
	"openrouter",
	"qianfan",
	"qwen",
	"qwen-token-plan",
	"qwencloud",
	"requesty",
	"runway",
	"sglang",
	"stepfun",
	"stepfun-plan",
	"synthetic",
	"tencent-tokenhub",
	"tencent-tokenplan",
	"together",
	"venice",
	"vercel-ai-gateway",
	"vllm",
	"volcengine",
	"volcengine-plan",
	"vydra",
	"x-ai",
	"xai",
	"xiaomi",
	"xiaomi-token-plan",
	"z.ai",
	"z-ai",
	"zai"
]);
/** Identifies provider overlays already known to the bundled config contract. */
function isBuiltInModelProviderOverlayId(e) {
	return BUILT_IN_MODEL_PROVIDER_OVERLAY_IDS.has(normalizeProviderId(e));
}
//#endregion
//#region src/config/zod-schema.allowdeny.ts
const AllowDenyActionSchema = union([literal("allow"), literal("deny")]);
const AllowDenyChatTypeSchema = union([
	literal("direct"),
	literal("group"),
	literal("channel")
]).optional();
function createAllowDenyChannelRulesSchema() {
	return strictObject({
		default: AllowDenyActionSchema.optional(),
		rules: array(strictObject({
			action: AllowDenyActionSchema,
			match: strictObject({
				channel: string().optional(),
				chatType: AllowDenyChatTypeSchema,
				keyPrefix: string().optional(),
				rawKeyPrefix: string().optional()
			}).optional()
		})).optional()
	}).optional();
}
//#endregion
//#region src/config/zod-schema.messages.ts
const VisibleRepliesSchema = union([_enum(["automatic", "message_tool"]), boolean()]).overwrite((e) => {
	if (e === true) return "automatic";
	if (e === false) return "message_tool";
	return e;
});
const MentionPatternsPolicySchema = strictObject({
	mode: union([literal("allow"), literal("deny")]).optional(),
	allowIn: array(string()).optional(),
	denyIn: array(string()).optional()
});
const GroupChatSchema = strictObject({
	mentionPatterns: array(string()).optional(),
	historyLimit: number().int().min(0).optional(),
	unmentionedInbound: _enum(["user_request", "room_event"]).optional(),
	visibleReplies: VisibleRepliesSchema.optional()
}).optional();
const DmConfigSchema$1 = strictObject({ historyLimit: number().int().min(0).optional() });
const QueueModeSchema = union([
	literal("steer"),
	literal("followup"),
	literal("collect"),
	literal("interrupt")
]);
const QueueModeBySurfaceSchema = record(string(), QueueModeSchema).optional();
const DebounceMsBySurfaceSchema = record(string(), number().int().nonnegative()).optional();
const QueueSchema = strictObject({
	mode: QueueModeSchema.optional(),
	allowCollaborativeSteering: boolean().optional(),
	collaborativeSteeringFallback: _enum(["queue", "reject"]).optional(),
	byChannel: QueueModeBySurfaceSchema,
	debounceMsByChannel: DebounceMsBySurfaceSchema,
	cap: number().int().positive().optional(),
	drop: union([
		literal("old"),
		literal("new"),
		literal("summarize")
	]).optional()
}).optional();
const InboundDebounceSchema = strictObject({
	debounceMs: number().int().nonnegative().optional(),
	byChannel: DebounceMsBySurfaceSchema
}).optional();
const NativeCommandsSettingSchema = union([boolean(), literal("auto")]);
const ProviderCommandsSchema = strictObject({
	native: NativeCommandsSettingSchema.optional(),
	nativeSkills: NativeCommandsSettingSchema.optional()
}).optional();
const ResponseUsageModeSchema = _enum([
	"on",
	"off",
	"tokens",
	"full"
]);
const MessagesSchema = strictObject({
	visibleReplies: VisibleRepliesSchema.optional(),
	responsePrefix: string().optional(),
	usageTemplate: union([string(), record(string(), unknown())]).optional(),
	responseUsage: union([ResponseUsageModeSchema, record(string(), ResponseUsageModeSchema)]).optional(),
	groupChat: GroupChatSchema,
	queue: QueueSchema,
	inbound: InboundDebounceSchema,
	ackReaction: string().optional(),
	ackReactionScope: _enum([
		"group-mentions",
		"group-all",
		"direct",
		"all",
		"off",
		"none"
	]).optional(),
	statusReactions: strictObject({ enabled: boolean().optional() }).optional()
}).optional();
const BroadcastGroupSchema = strictObject({
	agents: array(string()).max(16),
	mentionGating: boolean().optional(),
	maxRounds: number().int().min(1).max(4).optional(),
	maxTurns: number().int().min(1).max(32).optional()
});
const BroadcastSchema = object({ strategy: _enum(["parallel", "sequential"]).optional() }).catchall(union([array(string()), BroadcastGroupSchema])).superRefine((e, t) => {
	for (const [n, r] of Object.entries(e)) {
		if (typeof r !== "object") continue;
		const e = /^[a-z][a-z0-9_-]*:.+$/i.test(n);
		if (!Array.isArray(r) && !e) t.addIssue({
			code: ZodIssueCode.custom,
			path: [n],
			message: "Group options require a channel-qualified key (<channel>:<peerId>)."
		});
		else if (Array.isArray(r) && e && r.length > 16) t.addIssue({
			code: ZodIssueCode.custom,
			path: [n],
			message: "Agent group threads support at most 16 agents."
		});
	}
}).optional();
//#endregion
//#region src/config/zod-schema.model-compat.ts
const RoutingPercentileCutoffsSchema = strictObject({
	p50: number().optional(),
	p75: number().optional(),
	p90: number().optional(),
	p99: number().optional()
});
const OpenRouterRoutingSchema = strictObject({
	allow_fallbacks: boolean().optional(),
	require_parameters: boolean().optional(),
	data_collection: _enum(["deny", "allow"]).optional(),
	zdr: boolean().optional(),
	enforce_distillable_text: boolean().optional(),
	order: array(string()).optional(),
	only: array(string()).optional(),
	ignore: array(string()).optional(),
	quantizations: array(string()).optional(),
	sort: union([string(), strictObject({
		by: string().optional(),
		partition: string().nullable().optional()
	})]).optional(),
	max_price: strictObject({
		prompt: union([number(), string()]).optional(),
		completion: union([number(), string()]).optional(),
		image: union([number(), string()]).optional(),
		audio: union([number(), string()]).optional(),
		request: union([number(), string()]).optional()
	}).optional(),
	preferred_min_throughput: union([number(), RoutingPercentileCutoffsSchema]).optional(),
	preferred_max_latency: union([number(), RoutingPercentileCutoffsSchema]).optional()
});
const VercelGatewayRoutingSchema = strictObject({
	only: array(string()).optional(),
	order: array(string()).optional()
});
/** Provider/model compatibility switches consumed by request builders and tool schema adapters. */
const ModelCompatSchema = strictObject({
	/** Whether the provider supports the `store` field. Default: auto-detected from URL. */
	supportsStore: boolean().optional(),
	/** Whether provider accepts prompt-cache/session affinity keys. */
	supportsPromptCacheKey: boolean().optional(),
	/** Opts this model into stored HTTP continuation on a verified compatible endpoint. */
	supportsResponsesContinuation: boolean().optional(),
	/** Whether the provider supports the `developer` role (vs `system`). Default: auto-detected from URL. */
	supportsDeveloperRole: boolean().optional(),
	/** Whether the provider supports `reasoning_effort`. Default: auto-detected from URL. */
	supportsReasoningEffort: boolean().optional(),
	/** Whether the model accepts the `temperature` parameter. Default: true. */
	supportsTemperature: boolean().optional(),
	/**
	* Whether the provider honors top-level `instructions`. Defaults to true only for verified
	* native routes (OpenAI, xAI); every other route defaults to false and embeds the system
	* prompt in `input` unless set true here after verifying against that endpoint.
	*/
	supportsInstructions: boolean().optional(),
	/**
	* Whether the provider supports `stream_options: { include_usage: true }` for token usage in
	* streaming responses. Default: true.
	*/
	supportsUsageInStreaming: boolean().optional(),
	/** Whether this model supports tool/function calling. */
	supportsTools: boolean().optional(),
	/** Code-mode tier consumed by `tools.codeMode.enabled: "auto"`; absent means "capable". */
	codeMode: _enum(["preferred", "capable"]).optional(),
	/** Whether the provider supports the `strict` field in tool definitions. Default: true. */
	supportsStrictMode: boolean().optional(),
	/**
	* Whether the provider supports JSON Schema through `response_format`. Default: false for
	* unknown compatible endpoints.
	*/
	supportsJsonSchemaResponseFormat: boolean().optional(),
	/** Whether all message parts must be coerced to plain strings. */
	requiresStringContent: boolean().optional(),
	/** Whether unknown message payload keys must be stripped before requests. */
	strictMessageKeys: boolean().optional(),
	/** Reasoning detail block types safe to expose in visible transcripts. */
	visibleReasoningDetailTypes: array(string().min(1)).optional(),
	/** Provider-accepted reasoning effort labels. */
	supportedReasoningEfforts: array(string().min(1)).optional(),
	/** Per-level reasoning effort overrides, e.g. map "off" to "low" for models that cannot disable thinking. */
	reasoningEffortMap: record(string().min(1), string().min(1)).optional(),
	/** Which field to use for max tokens. Default: auto-detected from URL. */
	maxTokensField: union([literal("max_completion_tokens"), literal("max_tokens")]).optional(),
	/** Reasoning/thinking payload dialect for provider-compatible APIs. */
	thinkingFormat: _enum(MODEL_THINKING_FORMATS).optional(),
	/** Whether tool results require the `name` field. Default: auto-detected from URL. */
	requiresToolResultName: boolean().optional(),
	/**
	* Whether a user message after tool results requires an assistant message in between. Default:
	* auto-detected from URL.
	*/
	requiresAssistantAfterToolResult: boolean().optional(),
	/**
	* Whether thinking blocks must be converted to text blocks with <thinking> delimiters.
	* Default: auto-detected from URL.
	*/
	requiresThinkingAsText: boolean().optional(),
	/**
	* Whether all replayed assistant messages must include an empty reasoning_content field when
	* reasoning is enabled. Default: auto-detected from URL.
	*/
	requiresReasoningContentOnAssistantMessages: boolean().optional(),
	/** Named tool-schema profile used by provider adapters. */
	toolSchemaProfile: string().optional(),
	/** JSON Schema keywords rejected by this provider's tool schema validator. */
	unsupportedToolSchemaKeywords: array(string().min(1)).optional(),
	/** Encoding expected for tool-call arguments in provider payloads. */
	toolCallArgumentsEncoding: string().optional(),
	/** Whether OpenAI-style calls must be reshaped to Anthropic-compatible tool payloads. */
	requiresOpenAiAnthropicToolPayload: boolean().optional(),
	/** OpenRouter-specific routing preferences. Only used when baseUrl points to OpenRouter. */
	openRouterRouting: OpenRouterRoutingSchema.optional(),
	/** Vercel AI Gateway routing preferences. Only used when baseUrl points to Vercel AI Gateway. */
	vercelGatewayRouting: VercelGatewayRoutingSchema.optional(),
	/** Whether z.ai supports top-level `tool_stream: true` for streaming tool call deltas. Default: false. */
	zaiToolStream: boolean().optional(),
	/**
	* Cache control convention for prompt caching. "anthropic" applies Anthropic-style
	* `cache_control` markers to the system prompt, last tool definition, and last user/assistant
	* text content.
	*/
	cacheControlFormat: literal("anthropic").optional(),
	/**
	* Whether to send known session-affinity headers (`session_id`, `x-client-request-id`,
	* `x-session-affinity`) from `options.sessionId` when caching is enabled. Default: false.
	*/
	sendSessionAffinityHeaders: boolean().optional(),
	/**
	* Whether to send the OpenAI `session_id` cache-affinity header from `options.sessionId` when
	* caching is enabled. Default: true.
	*/
	sendSessionIdHeader: boolean().optional(),
	/**
	* Whether the provider accepts per-tool `eager_input_streaming`. When false, the Anthropic
	* provider omits `tools[].eager_input_streaming` and sends the legacy
	* `fine-grained-tool-streaming-2025-05-14` beta header for tool-enabled requests. Default:
	* true.
	*/
	supportsEagerToolInputStreaming: boolean().optional(),
	/**
	* Whether the provider supports long prompt cache retention (`prompt_cache_retention: "24h"`
	* or Anthropic-style `cache_control.ttl: "1h"`, depending on format). Default: true.
	*/
	supportsLongCacheRetention: boolean().optional()
}).optional();
//#endregion
//#region src/config/zod-schema.core.ts
const WINDOWS_ABS_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
const WINDOWS_UNC_PATH_PATTERN = /^\\\\[^\\]+\\[^\\]+/;
function isAbsolutePath(e) {
	return path.isAbsolute(e) || WINDOWS_ABS_PATH_PATTERN.test(e) || WINDOWS_UNC_PATH_PATTERN.test(e);
}
/** Canonical operator-configurable SSRF policy shared by network-capable surfaces. */
const SsrFPolicyConfigSchema = strictObject({
	dangerouslyAllowPrivateNetwork: boolean().optional(),
	allowRfc2544BenchmarkRange: boolean().optional(),
	allowIpv6UniqueLocalRange: boolean().optional(),
	allowedHostnames: array(string()).optional(),
	blockedHostnames: array(string()).optional()
});
const SecretsEnvProviderSchema = strictObject({
	source: literal("env"),
	/** Optional env var allowlist (exact names). */
	allowlist: array(string().regex(ENV_SECRET_REF_ID_RE)).max(256).optional()
});
const SecretsFileProviderSchema = strictObject({
	source: literal("file"),
	path: string().min(1),
	mode: union([literal("singleValue"), literal("json")]).optional(),
	timeoutMs: number().int().positive().max(12e4).optional(),
	maxBytes: number().int().positive().max(20971520).optional()
});
const SecretsManualExecProviderSchema = strictObject({
	source: literal("exec"),
	command: string().min(1).refine(isSafeExecutableValue, "secrets.providers.*.command is unsafe.").refine(isAbsolutePath, "secrets.providers.*.command must be an absolute path."),
	args: array(string().max(1024)).max(128).optional(),
	timeoutMs: number().int().positive().max(12e4).optional(),
	noOutputTimeoutMs: number().int().positive().max(12e4).optional(),
	maxOutputBytes: number().int().positive().max(20971520).optional(),
	jsonOnly: boolean().optional(),
	env: record(string(), string()).optional(),
	passEnv: array(string().regex(ENV_SECRET_REF_ID_RE)).max(128).optional(),
	trustedDirs: array(string().min(1).refine(isAbsolutePath, "trustedDirs entries must be absolute paths.")).max(64).optional()
});
const SecretsPluginIntegrationExecProviderSchema = strictObject({
	source: literal("exec"),
	pluginIntegration: strictObject({
		pluginId: string().min(1).max(128),
		integrationId: string().min(1).max(128)
	})
});
const SecretsExecProviderSchema = union([SecretsManualExecProviderSchema, SecretsPluginIntegrationExecProviderSchema]);
const SecretsStoreProviderSchema = strictObject({ source: literal("store") });
const EgressProxyExactHostSchema = string().trim().min(1).superRefine((e, t) => {
	try {
		normalizeExactAllowedHost(e);
	} catch (e) {
		t.addIssue({
			code: "custom",
			message: e instanceof Error ? e.message : "Invalid allowed host"
		});
	}
});
const SecretProviderSchema = union([
	SecretsEnvProviderSchema,
	SecretsFileProviderSchema,
	SecretsExecProviderSchema,
	SecretsStoreProviderSchema
]);
const SecretsConfigSchema = strictObject({
	egressProxy: strictObject({
		enabled: boolean().optional(),
		allowedHosts: array(EgressProxyExactHostSchema).max(256).optional(),
		bypassHosts: array(EgressProxyExactHostSchema).max(256).optional()
	}).optional(),
	providers: object({}).catchall(SecretProviderSchema).optional(),
	defaults: strictObject({
		env: string().regex(SECRET_PROVIDER_ALIAS_PATTERN).optional(),
		file: string().regex(SECRET_PROVIDER_ALIAS_PATTERN).optional(),
		exec: string().regex(SECRET_PROVIDER_ALIAS_PATTERN).optional(),
		store: string().regex(SECRET_PROVIDER_ALIAS_PATTERN).optional()
	}).optional()
}).optional();
const LEGACY_OPENAI_CODEX_RESPONSES_API = "openai-codex-responses";
const OPENAI_CHATGPT_RESPONSES_API = "openai-chatgpt-responses";
const ModelApiSchema = _enum(MODEL_APIS, { error: (e) => e.input === LEGACY_OPENAI_CODEX_RESPONSES_API ? `"${LEGACY_OPENAI_CODEX_RESPONSES_API}" is a removed api id; use "${OPENAI_CHATGPT_RESPONSES_API}"` : void 0 });
const ConfiguredProviderRequestTlsSchema = strictObject({
	ca: SecretInputSchema.optional().register(sensitive),
	cert: SecretInputSchema.optional().register(sensitive),
	key: SecretInputSchema.optional().register(sensitive),
	passphrase: SecretInputSchema.optional().register(sensitive),
	serverName: string().optional(),
	insecureSkipVerify: boolean().optional()
}).optional();
const ConfiguredProviderRequestAuthSchema = union([
	strictObject({ mode: literal("provider-default") }),
	strictObject({
		mode: literal("authorization-bearer"),
		token: SecretInputSchema.register(sensitive)
	}),
	strictObject({
		mode: literal("header"),
		headerName: string().min(1),
		value: SecretInputSchema.register(sensitive),
		prefix: string().optional()
	})
]).optional();
const ConfiguredProviderRequestProxySchema = union([strictObject({
	mode: literal("env-proxy"),
	tls: ConfiguredProviderRequestTlsSchema
}), strictObject({
	mode: literal("explicit-proxy"),
	url: string().min(1),
	tls: ConfiguredProviderRequestTlsSchema
})]).optional();
const ConfiguredProviderRequestFields = {
	headers: record(string(), SecretInputSchema.register(sensitive)).optional(),
	auth: ConfiguredProviderRequestAuthSchema,
	proxy: ConfiguredProviderRequestProxySchema,
	tls: ConfiguredProviderRequestTlsSchema
};
const ConfiguredProviderRequestSchema = strictObject(ConfiguredProviderRequestFields).optional();
const ConfiguredModelProviderRequestSchema = strictObject({
	...ConfiguredProviderRequestFields,
	allowPrivateNetwork: boolean().optional()
}).optional();
const ModelImageInputSchema = strictObject({
	maxBytes: number().int().positive().optional(),
	maxPixels: number().int().positive().optional(),
	maxSidePx: number().int().positive().optional(),
	preferredSidePx: number().int().positive().optional(),
	tokenMode: union([
		literal("tile"),
		literal("detail"),
		literal("provider")
	]).optional()
});
const ModelMediaInputSchema = strictObject({ image: ModelImageInputSchema.optional() });
const ThinkingLevelMapValueSchema = string().nullable();
const ThinkingLevelMapSchema = strictObject({
	off: ThinkingLevelMapValueSchema.optional(),
	minimal: ThinkingLevelMapValueSchema.optional(),
	low: ThinkingLevelMapValueSchema.optional(),
	medium: ThinkingLevelMapValueSchema.optional(),
	high: ThinkingLevelMapValueSchema.optional(),
	xhigh: ThinkingLevelMapValueSchema.optional(),
	max: ThinkingLevelMapValueSchema.optional()
});
const ModelDefinitionSchema = strictObject({
	/** Provider-facing model id. */
	id: string().min(1),
	name: string().min(1),
	/** Optional API adapter override for this model. */
	api: ModelApiSchema.optional(),
	/** Optional base URL override for this model. */
	baseUrl: string().min(1).optional(),
	reasoning: boolean().optional(),
	input: array(union([
		literal("text"),
		literal("image"),
		literal("video"),
		literal("audio")
	])).optional(),
	cost: strictObject({
		input: number().optional(),
		output: number().optional(),
		cacheRead: number().optional(),
		cacheWrite: number().optional(),
		tieredPricing: array(strictObject({
			input: number(),
			output: number(),
			cacheRead: number(),
			cacheWrite: number(),
			range: union([tuple([number(), number()]), tuple([number()])])
		})).optional()
	}).optional(),
	/** Provider/native maximum context window in tokens. */
	contextWindow: number().positive().optional(),
	/**
	* Optional effective runtime cap used for compaction/session budgeting.
	* Keeps provider/native contextWindow metadata intact while letting configs
	* prefer a smaller practical window.
	*/
	contextTokens: number().int().positive().optional(),
	maxTokens: number().positive().optional(),
	/** Maps OpenClaw thinking levels to provider/model-specific values. */
	thinkingLevelMap: ThinkingLevelMapSchema.optional(),
	/** Provider-specific request/runtime parameters passed through to provider plugins. */
	params: record(string(), unknown()).optional(),
	/** Optional agent execution runtime override for this provider/model pair. */
	agentRuntime: AgentRuntimePolicySchema,
	/** Static headers merged into requests for this model. */
	headers: record(string(), string()).optional(),
	/** Provider compatibility flags for payload shaping and feature gating. */
	compat: ModelCompatSchema,
	/** Media input limits used by routing and preflight compression. */
	mediaInput: ModelMediaInputSchema.optional(),
	/** Custom authored rows may accept endpoint-selected response ids; official policy still wins. */
	responseModelEquivalent: boolean().optional(),
	/** Metadata source marker for models added by CLI/catalog tooling. */
	metadataSource: literal("models-add").optional()
});
const ModelProviderLocalServiceSchema = strictObject({
	/** Executable started before model requests are sent. */
	command: string().min(1),
	/** Arguments passed without shell expansion. */
	args: array(string()).optional(),
	cwd: string().min(1).optional(),
	/** Environment variables added to the service process. */
	env: record(string(), string().register(sensitive)).optional(),
	/** Optional health endpoint polled before the provider is considered ready. */
	healthUrl: string().min(1).optional(),
	readyTimeoutMs: number().int().positive().optional(),
	/** Idle timeout in milliseconds before stopping the local service. */
	idleStopMs: number().int().nonnegative().optional()
}).optional();
const ModelProviderSchema = strictObject({
	baseUrl: string().optional(),
	/** API key or secret reference for this provider. */
	apiKey: SecretInputSchema.optional().register(sensitive),
	/** Authentication mode used when resolving credentials for this provider. */
	auth: union([
		literal("api-key"),
		literal("aws-sdk"),
		literal("oauth"),
		literal("token"),
		literal("none")
	]).optional(),
	/** Default API adapter for models under this provider. */
	api: ModelApiSchema.optional(),
	/** Provider-level default max output tokens. */
	maxTokens: number().positive().optional(),
	timeoutSeconds: number().int().positive().optional(),
	/** Optional provider deployment/API region used by provider plugins that expose regional endpoints. */
	region: string().min(1).optional(),
	injectNumCtxForOpenAICompat: boolean().optional(),
	/** Provider-specific runtime parameters interpreted by provider plugins. */
	params: record(string(), unknown()).optional(),
	/** Optional default agent execution runtime for models under this provider. */
	agentRuntime: AgentRuntimePolicySchema,
	/** Optional local service to start before calling this provider. */
	localService: ModelProviderLocalServiceSchema,
	/** Override locality for watchdog timing only, including localService-managed relays. */
	remote: boolean().optional(),
	/** Secret-bearing headers merged into provider requests. */
	headers: record(string(), SecretInputSchema.register(sensitive)).optional(),
	/** Whether default Authorization header injection is enabled. */
	authHeader: boolean().optional(),
	/** Provider request transport/retry overrides. */
	request: ConfiguredModelProviderRequestSchema,
	models: array(ModelDefinitionSchema).optional()
});
const ModelProvidersSchema = record(string(), ModelProviderSchema).superRefine((e, t) => {
	for (const [n, r] of Object.entries(e)) {
		if (isBuiltInModelProviderOverlayId(n)) continue;
		if (!r.baseUrl) t.addIssue({
			code: "custom",
			path: [n, "baseUrl"],
			message: "custom model providers must declare baseUrl; provider overlays without baseUrl are only supported for bundled providers"
		});
		if (!Array.isArray(r.models)) t.addIssue({
			code: "custom",
			path: [n, "models"],
			message: "custom model providers must declare models; provider overlays without models are only supported for bundled providers"
		});
	}
});
const ModelCatalogRefreshConfigSchema = strictObject({
	/** Fetch model catalog updates from the hosted OpenClaw catalog. Default: true. */
	enabled: boolean().optional(),
	/** Override the hosted catalog URL (HTTPS mirrors, or localhost HTTP for testing). */
	url: string().refine((e) => {
		const t = URL.parse(e);
		return t !== null && (t.protocol === "https:" || t.protocol === "http:" && [
			"localhost",
			"127.0.0.1",
			"[::1]"
		].includes(t.hostname));
	}, { message: "models.catalogRefresh.url must use https, or http on localhost" }).optional()
}).optional();
const ModelsConfigSchema = strictObject({
	/** Merge provider config with bundled catalogs or replace bundled catalogs entirely. */
	mode: union([literal("merge"), literal("replace")]).optional(),
	providers: ModelProvidersSchema.optional(),
	catalogRefresh: ModelCatalogRefreshConfigSchema,
	usage: strictObject({ cacheTtlMs: number().int().nonnegative().optional() }).optional()
}).optional();
const IdentitySchema = strictObject({
	name: string().optional(),
	theme: string().optional(),
	emoji: string().optional(),
	avatar: string().optional()
}).optional();
const ReplyToModeSchema = union([
	literal("off"),
	literal("first"),
	literal("all"),
	literal("batched")
]);
const TypingModeSchema = union([
	literal("never"),
	literal("instant"),
	literal("thinking"),
	literal("message")
]);
const GroupPolicySchema = _enum([
	"open",
	"disabled",
	"allowlist"
]);
const DmPolicySchema = _enum([
	"pairing",
	"allowlist",
	"open",
	"disabled"
]);
const ContextVisibilityModeSchema = _enum([
	"all",
	"allowlist",
	"allowlist_quote"
]);
const BlockStreamingCoalesceSchema = strictObject({
	minChars: number().int().positive().optional(),
	maxChars: number().int().positive().optional(),
	idleMs: number().int().nonnegative().optional()
});
const TextChunkModeSchema = _enum(["length", "newline"]);
const ChannelStreamingBlockSchema = strictObject({
	enabled: boolean().optional(),
	coalesce: BlockStreamingCoalesceSchema.optional()
});
/** Delivery-only nested streaming config for channels without preview modes. */
const ChannelDeliveryStreamingConfigSchema = strictObject({
	chunkMode: TextChunkModeSchema.optional(),
	block: ChannelStreamingBlockSchema.optional()
});
const ReplyRuntimeConfigSchemaShape = {
	historyLimit: number().int().min(0).optional(),
	dmHistoryLimit: number().int().min(0).optional(),
	contextVisibility: ContextVisibilityModeSchema.optional(),
	dms: record(string(), DmConfigSchema$1.optional()).optional(),
	textChunkLimit: number().int().positive().optional(),
	streaming: ChannelDeliveryStreamingConfigSchema.optional(),
	responsePrefix: string().optional(),
	mediaMaxMb: number().positive().optional()
};
const BlockStreamingChunkSchema = strictObject({
	minChars: number().int().positive().optional(),
	maxChars: number().int().positive().optional(),
	breakPreference: union([
		literal("paragraph"),
		literal("newline"),
		literal("sentence")
	]).optional()
});
const MarkdownConfigSchema$1 = strictObject({ tables: _enum([
	"off",
	"bullets",
	"code",
	"block"
]).optional() }).optional();
const TtsProviderSchema = string().min(1);
const TtsModeSchema = _enum(["final", "all"]);
const TtsAutoSchema = _enum([
	"off",
	"always",
	"inbound",
	"tagged"
]);
const TtsProviderConfigSchema = object({ apiKey: SecretInputSchema.optional().register(sensitive) }).catchall(union([
	string(),
	number(),
	boolean(),
	_null(),
	array(unknown()),
	record(string(), unknown())
]));
const TtsPersonaSchema = strictObject({
	label: string().optional(),
	description: string().optional(),
	provider: TtsProviderSchema.optional(),
	fallbackPolicy: union([
		literal("preserve-persona"),
		literal("provider-defaults"),
		literal("fail")
	]).optional(),
	providers: record(string(), TtsProviderConfigSchema).optional()
});
const TtsConfigSchema = strictObject({
	auto: TtsAutoSchema.optional(),
	enabled: boolean().optional(),
	mode: TtsModeSchema.optional(),
	provider: TtsProviderSchema.optional(),
	persona: string().optional(),
	personas: record(string(), TtsPersonaSchema).optional(),
	summaryModel: string().optional(),
	modelOverrides: strictObject({
		enabled: boolean().optional(),
		allowText: boolean().optional(),
		allowProvider: boolean().optional(),
		allowVoice: boolean().optional(),
		allowModelId: boolean().optional(),
		allowVoiceSettings: boolean().optional(),
		allowNormalization: boolean().optional(),
		allowSeed: boolean().optional()
	}).optional(),
	providers: record(string(), TtsProviderConfigSchema).optional(),
	maxTextLength: number().int().min(1).optional(),
	timeoutMs: number().int().min(1e3).max(12e4).optional()
}).optional();
const HumanDelaySchema = strictObject({
	mode: union([
		literal("off"),
		literal("natural"),
		literal("custom")
	]).optional(),
	minMs: number().int().nonnegative().optional(),
	maxMs: number().int().nonnegative().optional()
});
/**
* Canonical cross-field check for dmPolicy vs allowFrom. This is the single
* source of truth shared by the Zod schema refinements and the CLI config
* validator so the rule cannot drift between the two surfaces.
*/
const evaluateDmPolicyAllowFromDependency = (e) => {
	const t = normalizeStringEntries(e.allowFrom);
	if (e.policy === "open" && !t.includes("*")) return "open_requires_wildcard";
	if (e.policy === "allowlist" && t.length === 0) return "allowlist_requires_entries";
	return null;
};
function createDmPolicyAllowFromValidator(e) {
	return (t) => {
		if (evaluateDmPolicyAllowFromDependency(t) === e) t.ctx.addIssue({
			code: ZodIssueCode.custom,
			path: t.path,
			message: t.message
		});
	};
}
const requireOpenAllowFrom = createDmPolicyAllowFromValidator("open_requires_wildcard");
/**
* Validate that dmPolicy="allowlist" has a non-empty allowFrom array.
* Without this, all DMs are silently dropped because the allowlist is empty
* and no senders can match.
*/
const requireAllowlistAllowFrom = createDmPolicyAllowFromValidator("allowlist_requires_entries");
const MSTeamsReplyStyleSchema = _enum(["thread", "top-level"]);
const HexColorSchema = string().regex(/^#?[0-9a-fA-F]{6}$/, "expected hex color (RRGGBB)");
const ExecutableTokenSchema = string().refine(isSafeExecutableValue, "expected safe executable name or path");
const MediaUnderstandingScopeSchema = createAllowDenyChannelRulesSchema();
const MediaUnderstandingAttachmentsSchema = strictObject({
	/** Select the first matching attachment or process multiple. */
	mode: union([literal("first"), literal("all")]).optional(),
	/** Max number of attachments to process (default: 1). */
	maxAttachments: number().int().positive().optional(),
	prefer: union([
		literal("first"),
		literal("last"),
		literal("path"),
		literal("url")
	]).optional()
}).optional();
const ProviderOptionsSchema = record(string(), record(string(), union([
	string(),
	number(),
	boolean(),
	array(string())
]))).optional();
const MediaUnderstandingRuntimeFields = {
	/** Default prompt; model entries can override it. */
	prompt: string().optional(),
	/** Default timeout (seconds); model entries can override it. */
	timeoutSeconds: number().int().positive().optional(),
	/** Default language hint for audio transcription; model entries can override it. */
	language: string().optional(),
	/** Optional provider-specific query params (merged into requests). */
	providerOptions: ProviderOptionsSchema,
	/** Optional base URL override for provider requests. */
	baseUrl: string().optional(),
	/** Optional headers merged into provider requests. */
	headers: record(string(), string()).optional(),
	/** Optional request transport overrides for provider HTTP calls. */
	request: ConfiguredProviderRequestSchema
};
const MediaUnderstandingModelSchema = strictObject({
	/** provider API id (e.g. openai, google). */
	provider: string().optional(),
	/** Model id for provider-based understanding. */
	model: string().optional(),
	/** Optional capability tags for shared model lists. */
	capabilities: array(union([
		literal("image"),
		literal("audio"),
		literal("video")
	])).optional(),
	/** Use a CLI command instead of provider API. */
	type: union([literal("provider"), literal("cli")]).optional(),
	/** CLI binary (required when type=cli). */
	command: string().optional(),
	/** CLI args (template-enabled). */
	args: array(string()).optional(),
	/** Optional max output characters for this model entry. */
	maxChars: number().int().positive().optional(),
	maxBytes: number().int().positive().optional(),
	...MediaUnderstandingRuntimeFields,
	/** Auth profile id to use for this provider. */
	profile: string().optional(),
	/** Preferred profile id if multiple are available. */
	preferredProfile: string().optional()
}).optional();
const ToolsMediaCapabilitySchema = strictObject({
	/** Enable media understanding when models are configured. */
	enabled: boolean().optional(),
	/** Prefer a matching shared model entry. */
	preferredModel: string().trim().min(1).optional(),
	/** Optional scope gating for understanding. */
	scope: MediaUnderstandingScopeSchema,
	/** Default max bytes to send. */
	maxBytes: number().int().positive().optional(),
	/** Default max output characters. */
	maxChars: number().int().positive().optional(),
	...MediaUnderstandingRuntimeFields,
	attachments: MediaUnderstandingAttachmentsSchema
}).optional();
const ToolsMediaAudioSchema = ToolsMediaCapabilitySchema.unwrap().extend({
	/**
	* Echo the audio transcript back to the originating chat before agent processing.
	* Lets users verify what was heard. Default: false.
	*/
	echoTranscript: boolean().optional(),
	/**
	* Format string for the echoed transcript. Use `{transcript}` as placeholder.
	* Default: '📝 "{transcript}"'
	*/
	echoFormat: string().optional()
}).optional();
const ToolsMediaSchema = strictObject({
	models: array(MediaUnderstandingModelSchema).optional(),
	concurrency: number().int().positive().optional(),
	image: ToolsMediaCapabilitySchema.optional(),
	audio: ToolsMediaAudioSchema.optional(),
	video: ToolsMediaCapabilitySchema.optional()
}).optional();
const LinkModelSchema = strictObject({
	/** Use a CLI command for link processing. */
	type: literal("cli").optional(),
	command: string().min(1),
	args: array(string()).optional(),
	timeoutSeconds: number().int().positive().optional()
});
const ToolsLinksSchema = strictObject({
	/** Enable link understanding when models are configured. */
	enabled: boolean().optional(),
	scope: MediaUnderstandingScopeSchema,
	/** Max number of links to process per message. */
	maxLinks: number().int().positive().optional(),
	timeoutSeconds: number().int().positive().optional(),
	/** Ordered model list (fallbacks in order). */
	models: array(LinkModelSchema).optional()
}).optional();
//#endregion
//#region src/config/github-identity-profile-id.ts
const MANAGED_GITHUB_PROFILE_ID_PATTERN = /^ghp_[a-f0-9]{32}$/u;
//#endregion
//#region src/config/zod-schema.github-identity.ts
const identityFields = {
	profileId: string().regex(MANAGED_GITHUB_PROFILE_ID_PATTERN),
	gitAuthor: strictObject({
		name: string().trim().min(1).optional(),
		email: string().trim().min(1).optional()
	}).optional()
};
const id = number().int().positive().max(Number.MAX_SAFE_INTEGER);
const GitHubAppInstallationSchema = strictObject({
	appId: id,
	installationId: id,
	accountId: id,
	repositories: array(strictObject({
		id,
		fullName: string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u)
	})).min(1).max(100).refine((e) => new Set(e.map((e) => e.id)).size === e.length),
	permissions: record(string().regex(/^[a-z_]+$/u), _enum(["read", "write"])),
	privateKey: SecretInputSchema.register(sensitive),
	keyVersion: string().trim().min(1).max(256)
});
const credentialSchemas = [strictObject({
	...identityFields,
	kind: literal("oauth").optional()
}), strictObject({
	...identityFields,
	kind: literal("app-installation"),
	app: GitHubAppInstallationSchema
})];
const GitHubToolIdentitySchema = discriminatedUnion("kind", credentialSchemas).optional();
const AgentGitHubToolIdentitySchema = discriminatedUnion("kind", [credentialSchemas[0].extend({ allowInSandbox: boolean().optional() }), credentialSchemas[1].extend({ allowInSandbox: boolean().optional() })]).optional();
//#endregion
//#region src/config/zod-schema.memory-search.ts
const MemorySearchSchema = strictObject({
	enabled: boolean().optional(),
	rememberAcrossConversations: boolean().optional(),
	sources: array(union([literal("memory"), literal("sessions")])).optional(),
	extraPaths: array(union([string(), strictObject({
		path: string(),
		pattern: string().optional(),
		evergreen: boolean().optional()
	})])).optional(),
	multimodal: strictObject({
		enabled: boolean().optional(),
		modalities: array(union([
			literal("image"),
			literal("audio"),
			literal("all")
		])).optional(),
		maxFileBytes: number().int().positive().optional()
	}).optional(),
	experimental: strictObject({ sessionMemory: boolean().optional() }).optional(),
	provider: string().optional(),
	remote: strictObject({
		baseUrl: string().optional(),
		apiKey: SecretInputSchema.optional().register(sensitive),
		headers: record(string(), string()).optional(),
		batch: strictObject({ enabled: boolean().optional() }).optional()
	}).optional(),
	fallback: string().optional(),
	model: string().optional(),
	inputFormat: strictObject({
		query: string(),
		document: string()
	}).optional(),
	inputType: string().min(1).optional(),
	queryInputType: string().min(1).optional(),
	queryInstruction: string().optional(),
	documentInputType: string().min(1).optional(),
	outputDimensionality: number().int().positive().optional(),
	local: strictObject({ modelPath: string().optional() }).optional(),
	store: strictObject({
		fts: strictObject({ tokenizer: union([literal("unicode61"), literal("trigram")]).optional() }).optional(),
		vector: strictObject({
			enabled: boolean().optional(),
			extensionPath: string().optional()
		}).optional()
	}).optional(),
	query: strictObject({
		maxResults: number().int().positive().optional(),
		minScore: number().min(0).max(1).optional()
	}).optional(),
	cache: strictObject({ enabled: boolean().optional() }).optional()
}).optional();
//#endregion
//#region src/agents/sandbox/bind-spec.ts
/**
* Parser for Docker-style host:container[:options] bind specs.
*/
/** Splits a bind spec while preserving Windows drive-letter prefixes in host paths. */
function splitSandboxBindSpec(e, t) {
	const n = getBindSeparatorIndex(e);
	if (n === -1) return null;
	const r = e.slice(0, n);
	const i = e.slice(n + 1);
	const a = t?.allowWindowsContainerPath === true ? getBindSeparatorIndex(i) : i.indexOf(":");
	if (a === -1) return {
		host: r,
		container: i,
		options: ""
	};
	return {
		host: r,
		container: i.slice(0, a),
		options: i.slice(a + 1)
	};
}
function getBindSeparatorIndex(e) {
	const t = /^[A-Za-z]:[\\/]/.test(e);
	return e.indexOf(":", t ? 2 : 0);
}
//#endregion
//#region src/agents/sandbox/host-paths.ts
function stripWindowsNamespacePrefix(e) {
	if (e.startsWith("\\\\?\\")) {
		const t = e.slice(4);
		if (t.toUpperCase().startsWith("UNC\\")) return `\\\\${t.slice(4)}`;
		return t;
	}
	if (e.startsWith("//?/")) {
		const t = e.slice(4);
		if (t.toUpperCase().startsWith("UNC/")) return `//${t.slice(4)}`;
		return t;
	}
	return e;
}
function isWindowsDriveAbsolutePath(e) {
	return /^[A-Za-z]:[\\/]/.test(stripWindowsNamespacePrefix(e));
}
function isSandboxHostPathAbsolute(e) {
	const t = stripWindowsNamespacePrefix(e);
	return t.startsWith("/") || isWindowsDriveAbsolutePath(t);
}
//#endregion
//#region src/config/zod-schema.sandbox.ts
function validateSandboxBindEntries(e, t) {
	if (!e) return;
	for (let n = 0; n < e.length; n += 1) {
		const r = e[n] ?? "";
		if (!r.trim()) {
			t.addIssue({
				code: ZodIssueCode.custom,
				path: ["binds", n],
				message: "Sandbox security: bind mount entry must be a non-empty string."
			});
			continue;
		}
		const i = splitSandboxBindSpec(r);
		const a = i ? i.host : r;
		if (!isSandboxHostPathAbsolute(a)) t.addIssue({
			code: ZodIssueCode.custom,
			path: ["binds", n],
			message: `Sandbox security: bind mount "${r}" uses a non-absolute source path "${a}". Only absolute POSIX or Windows drive-letter paths are supported for sandbox binds.`
		});
	}
}
const SandboxDockerSchema = strictObject({
	image: string().optional(),
	containerPrefix: string().optional(),
	workdir: string().optional(),
	readOnlyRoot: boolean().optional(),
	tmpfs: array(string()).optional(),
	network: string().optional(),
	user: string().optional(),
	capDrop: array(string()).optional(),
	env: record(string(), string()).optional(),
	setupCommand: union([string(), array(string())]).transform((e) => Array.isArray(e) ? e.join("\n") : e).pipe(string()).optional(),
	pidsLimit: number().int().positive().optional(),
	memory: union([string(), number()]).optional(),
	memorySwap: union([string(), number()]).optional(),
	cpus: number().positive().optional(),
	gpus: string().min(1).optional(),
	ulimits: record(string(), union([
		string(),
		number(),
		strictObject({
			soft: number().int().nonnegative().optional(),
			hard: number().int().nonnegative().optional()
		})
	])).optional(),
	seccompProfile: string().optional(),
	apparmorProfile: string().optional(),
	dns: array(string()).optional(),
	extraHosts: array(string()).optional(),
	binds: array(string()).optional(),
	dangerouslyAllowReservedContainerTargets: boolean().optional(),
	dangerouslyAllowExternalBindSources: boolean().optional(),
	dangerouslyAllowContainerNamespaceJoin: boolean().optional()
}).superRefine((e, t) => {
	validateSandboxBindEntries(e.binds, t);
	const n = getBlockedNetworkModeReason({
		network: e.network,
		allowContainerNamespaceJoin: e.dangerouslyAllowContainerNamespaceJoin === true
	});
	if (n === "host") t.addIssue({
		code: ZodIssueCode.custom,
		path: ["network"],
		message: "Sandbox security: network mode \"host\" is blocked. Use \"bridge\" or \"none\" instead."
	});
	if (n === "container_namespace_join") t.addIssue({
		code: ZodIssueCode.custom,
		path: ["network"],
		message: "Sandbox security: network mode \"container:*\" is blocked by default. Use a custom bridge network, or set dangerouslyAllowContainerNamespaceJoin=true only when you fully trust this runtime."
	});
	for (const [n, r, i] of [[
		"seccompProfile",
		"seccomp",
		"a custom seccomp profile file"
	], [
		"apparmorProfile",
		"AppArmor",
		"a named AppArmor profile"
	]]) if (normalizeLowercaseStringOrEmpty(e[n] ?? "") === "unconfined") t.addIssue({
		code: ZodIssueCode.custom,
		path: [n],
		message: `Sandbox security: ${r} profile "unconfined" is blocked. Use ${i} or omit this setting.`
	});
}).optional();
const SandboxBrowserSchema = object({
	enabled: boolean().optional(),
	image: string().optional(),
	containerPrefix: string().optional(),
	network: string().optional(),
	cdpPort: number().int().positive().optional(),
	cdpSourceRange: string().optional(),
	vncPort: number().int().positive().optional(),
	noVncPort: number().int().positive().optional(),
	headless: boolean().optional(),
	noVncEnabled: boolean().optional(),
	allowHostControl: boolean().optional(),
	autoStart: boolean().optional(),
	autoStartTimeoutMs: number().int().positive().optional(),
	binds: array(string()).optional()
}).superRefine((e, t) => {
	validateSandboxBindEntries(e.binds, t);
	if (normalizeLowercaseStringOrEmpty(e.network ?? "") === "host") t.addIssue({
		code: ZodIssueCode.custom,
		path: ["network"],
		message: "Sandbox security: browser network mode \"host\" is blocked. Use \"bridge\" or a custom bridge network instead."
	});
}).strict().optional();
const SandboxPruneSchema = strictObject({
	idleHours: number().int().nonnegative().optional(),
	maxAgeDays: number().int().nonnegative().optional()
}).optional();
//#endregion
//#region src/config/zod-schema.agent-runtime.ts
const AgentTtsConfigSchema = TtsConfigSchema.unwrap().extend({ prefsPath: string().optional() }).strict().optional();
const AgentContextLimitsSchema = strictObject({
	/** Default max chars returned by memory_get before truncation metadata/notice (default: 12000). */
	memoryGetMaxChars: number().int().min(1).max(25e4).optional(),
	/** Max chars retained from post-compaction AGENTS.md context injection (default: 1800). */
	postCompactionMaxChars: number().int().min(1).max(5e4).optional()
}).optional();
const AgentSkillsLimitsSchema = strictObject({ maxSkillsPromptChars: number().int().min(0).optional() }).optional();
const ToolPolicyBaseSchema = strictObject({
	/** Exact tool names allowed in this policy scope. */
	allow: array(string()).optional(),
	/** Additional allowlist entries merged into the inherited policy. */
	alsoAllow: array(string()).optional(),
	/** Exact tool names denied after allow expansion; deny wins. */
	deny: array(string()).optional()
});
const ToolPolicySchema$1 = ToolPolicyBaseSchema.superRefine(createAllowAlsoAllowConflictValidator("tools policy cannot set both allow and alsoAllow in the same scope (merge alsoAllow into allow, or remove allow and use profile + alsoAllow)")).optional();
const ToolPolicyBySenderSchema = record(string(), ToolPolicySchema$1).optional();
const TrimmedOptionalConfigStringSchema = string().transform(normalizeOptionalString).optional();
const CodexAllowedDomainsSchema = array(string()).transform((e) => {
	const t = normalizeUniqueStringEntries(e);
	return t.length > 0 ? t : void 0;
}).optional();
const CodexUserLocationSchema = strictObject({
	country: TrimmedOptionalConfigStringSchema,
	region: TrimmedOptionalConfigStringSchema,
	city: TrimmedOptionalConfigStringSchema,
	timezone: TrimmedOptionalConfigStringSchema
}).transform((e) => {
	return e.country || e.region || e.city || e.timezone ? e : void 0;
}).optional();
const BLOCKED_WEB_SEARCH_KEYS_ISSUE_FIELD = "__openclawBlockedWebSearchKeys";
const ToolsWebSearchSchema = preprocess((e) => {
	if (!isRecord(e)) return e;
	const t = Object.getOwnPropertyNames(e).filter((e) => isBlockedObjectKey(e));
	if (t.length === 0) return e;
	return {
		...e,
		[BLOCKED_WEB_SEARCH_KEYS_ISSUE_FIELD]: t
	};
}, object({
	enabled: boolean().optional(),
	provider: string().optional(),
	maxResults: number().int().positive().optional(),
	timeoutSeconds: number().int().positive().optional(),
	cacheTtlMinutes: number().nonnegative().optional(),
	openaiCodex: strictObject({
		enabled: boolean().optional(),
		mode: union([literal("cached"), literal("live")]).optional(),
		allowedDomains: CodexAllowedDomainsSchema,
		contextSize: union([
			literal("low"),
			literal("medium"),
			literal("high")
		]).optional(),
		userLocation: CodexUserLocationSchema
	}).optional()
}).catchall(unknown()).superRefine((e, t) => {
	const n = e[BLOCKED_WEB_SEARCH_KEYS_ISSUE_FIELD];
	if (Array.isArray(n)) for (const e of n) {
		if (typeof e !== "string") continue;
		t.addIssue({
			code: ZodIssueCode.custom,
			path: [e],
			message: "tools.web.search must not contain blocked object keys"
		});
	}
	for (const [n, r] of Object.entries(e)) {
		if (n === BLOCKED_WEB_SEARCH_KEYS_ISSUE_FIELD || isBlockedObjectKey(n)) continue;
		if (n === "apiKey" || LEGACY_WEB_SEARCH_PROVIDER_CONFIG_KEYS.has(n) && isRecord(r)) t.addIssue({
			code: ZodIssueCode.custom,
			path: [n],
			message: "legacy web_search provider config must use plugins.entries.<plugin>.config.webSearch"
		});
	}
})).optional();
const ToolsWebFetchSchema = strictObject({
	/** Enable web fetch tool (default: true). */
	enabled: boolean().optional(),
	/** Web fetch fallback provider id. */
	provider: string().optional(),
	maxChars: number().int().positive().optional(),
	/** Hard cap for maxChars (tool or config), defaults to 20000. */
	maxCharsCap: number().int().positive().optional(),
	/** Max download size before truncation, defaults to 750000 bytes. */
	maxResponseBytes: number().int().positive().optional(),
	timeoutSeconds: number().int().positive().optional(),
	cacheTtlMinutes: number().nonnegative().optional(),
	/** Maximum number of redirects to follow (default: 3). */
	maxRedirects: number().int().nonnegative().optional(),
	/** Override User-Agent header for fetch requests. */
	userAgent: string().optional(),
	/**
	* Extra request headers sent with direct web_fetch requests. Every value is
	* treated as sensitive in exposed config. Entries a request cannot carry are
	* dropped with a warning at request time.
	*/
	headers: record(string(), string().register(sensitive)).optional(),
	/** Use Readability to extract main content (default: true). */
	readability: boolean().optional(),
	/** Route web_fetch through a trusted HTTP(S) env proxy and let the proxy resolve DNS. Enable only when that proxy enforces outbound policy. */
	useTrustedEnvProxy: boolean().optional(),
	ssrfPolicy: SsrFPolicyConfigSchema.optional()
}).optional();
const ToolsWebSchema = strictObject({
	search: ToolsWebSearchSchema,
	fetch: ToolsWebFetchSchema
}).optional();
const ToolProfileSchema = union([
	literal("minimal"),
	literal("coding"),
	literal("messaging"),
	literal("full")
]).optional();
function createAllowAlsoAllowConflictValidator(e) {
	return (t, n) => {
		if (t.allow && t.allow.length > 0 && t.alsoAllow && t.alsoAllow.length > 0) n.addIssue({
			code: ZodIssueCode.custom,
			message: e
		});
	};
}
const ToolPolicyWithProfileSchema = ToolPolicyBaseSchema.extend({ profile: ToolProfileSchema }).superRefine(createAllowAlsoAllowConflictValidator("tools.byProvider policy cannot set both allow and alsoAllow in the same scope (merge alsoAllow into allow, or remove allow and use profile + alsoAllow)"));
const ElevatedAllowFromSchema = record(string(), array(union([string(), number()]))).optional();
const ToolExecApplyPatchSchema = strictObject({
	/** Enable apply_patch for OpenAI models (default: true; set false to disable). */
	enabled: boolean().optional(),
	/**
	* Restrict apply_patch paths to the workspace directory.
	* Default: false on the host; explicit containment and required roots still apply.
	*/
	workspaceOnly: boolean().optional(),
	/**
	* Optional allowlist of model ids that can use apply_patch.
	* Accepts either raw ids (e.g. "gpt-5.4") or full ids (e.g. "openai/gpt-5.4").
	*/
	allowModels: array(string()).optional()
}).optional();
const ToolExecSafeBinProfileSchema = strictObject({
	minPositional: number().int().nonnegative().optional(),
	maxPositional: number().int().nonnegative().optional(),
	allowedValueFlags: array(string()).optional(),
	deniedFlags: array(string()).optional()
});
const ToolExecBaseShape = {
	/** Exec host routing (default: auto). */
	host: _enum([
		"auto",
		"sandbox",
		"gateway",
		"node"
	]).optional(),
	/** Normalized exec policy mode. Prefer this over raw security/ask knobs. */
	mode: _enum([
		"deny",
		"allowlist",
		"ask",
		"auto",
		"full"
	]).optional(),
	/** Legacy exec security mode retained when no canonical mode can preserve policy. */
	security: _enum([
		"deny",
		"allowlist",
		"full"
	]).optional(),
	/** Legacy exec ask mode retained when no canonical mode can preserve policy. */
	ask: _enum([
		"off",
		"on-miss",
		"always"
	]).optional(),
	/** Default node binding for exec.host=node (node id/name). */
	node: string().optional(),
	/** Directories to prepend to PATH when running exec (gateway/sandbox). */
	pathPrepend: array(string()).optional(),
	/** Safe stdin-only binaries that can run without allowlist entries. */
	safeBins: array(string()).optional(),
	/**
	* Require explicit approval for interpreter inline-eval forms (`python -c`, `node -e`, etc.).
	* Prevents silent allowlist reuse and allow-always persistence for those forms.
	*/
	strictInlineEval: boolean().optional(),
	/** Render parser-derived command highlights in exec approval prompts (default: false). */
	commandHighlighting: boolean().optional(),
	/**
	* Default lifetime, in days, stamped onto standing grants minted by
	* allow-always on automation approvals. Unset means grants live until
	* revoked or the owning job changes. Terms freeze at mint; changing this
	* affects only future grants.
	*/
	grantExpiryDays: number().int().min(1).max(3650).optional(),
	/** Extra explicit directories trusted for safeBins path checks (never derived from PATH). */
	safeBinTrustedDirs: array(string()).optional(),
	safeBinProfiles: record(string(), ToolExecSafeBinProfileSchema).optional(),
	/** Model-backed reviewer used by tools.exec.mode=auto before falling back to human approval. */
	reviewer: strictObject({
		/** Optional reviewer model override (provider/model or agent model config). */
		model: AgentModelSchema.optional(),
		thinking: _enum([
			"minimal",
			"low",
			"medium",
			"high",
			"xhigh",
			"max"
		]).optional(),
		/** Optional Fast processing for supported provider requests. */
		fastMode: boolean().optional(),
		/** Reviewer timeout in milliseconds (default: 30000). */
		timeoutMs: number().int().positive().optional()
	}).optional(),
	/** Default time (ms) before an exec command auto-backgrounds. */
	backgroundMs: number().int().positive().optional(),
	/** Emit a running notice (ms) when approval-backed exec runs long (default: 10000, 0 = off). */
	approvalRunningNoticeMs: number().int().nonnegative().optional(),
	/** Default timeout (seconds) before auto-killing exec commands. */
	timeoutSeconds: number().int().positive().optional(),
	/** How long to keep finished sessions in memory (ms). */
	cleanupMs: number().int().positive().optional(),
	/** Emit a system event and heartbeat when a backgrounded exec exits. */
	notifyOnExit: boolean().optional(),
	/**
	* Also wake the session when a backgrounded exec succeeds with no output.
	* Default true, so every exit of a wake-armed command reports back.
	*/
	notifyOnExitEmptySuccess: boolean().optional(),
	applyPatch: ToolExecApplyPatchSchema
};
function addExecPolicyModeConflictIssue(e, t) {
	if (e.mode === void 0 || e.security === void 0 && e.ask === void 0) return;
	const n = e.security !== void 0 && e.ask !== void 0 ? resolveExactExecModeFromPolicy({
		security: e.security,
		ask: e.ask
	}) : null;
	const r = n ? `Replace security/ask with mode="${n}" (the equivalent of security="${e.security}" + ask="${e.ask}").` : e.security !== void 0 && e.ask !== void 0 ? "This security/ask pair has no exact mode equivalent. To keep this policy, retain both legacy fields and remove mode." : "The legacy policy is incomplete. Choose the intended security and ask values before converting; no mode equivalent can be inferred.";
	t.addIssue({
		code: ZodIssueCode.custom,
		path: ["mode"],
		message: `mode cannot be combined with security or ask in the same exec object. Update the deploy script, template, or patch at this scope. ${r} Doctor migrates supported legacy policies to mode; run "openclaw doctor --fix" only when the saved file still needs migration.`
	});
}
const ToolExecSchema = strictObject(ToolExecBaseShape).superRefine(addExecPolicyModeConflictIssue).optional();
const ToolFsSchema = strictObject({ 
/**
* Restrict filesystem tools (read/write/edit/apply_patch) to the agent workspace directory.
* Default: false (unrestricted, matches legacy behavior).
*/
workspaceOnly: boolean().optional() }).optional();
const ToolLoopDetectionSchema = strictObject({ 
/** Enable tool-loop protection (default: false). */
enabled: boolean().optional() }).optional();
const ToolSearchSelectorSchema = strictObject({
	source: _enum([
		"openclaw",
		"mcp",
		"client"
	]).optional(),
	name: string().trim().min(1).optional()
}).refine((e) => e.source !== void 0 || e.name !== void 0, { message: "Tool Search selectors must specify source, name, or both." });
const ToolSearchSchema = union([boolean(), strictObject({
	/** Enable compact search/call cataloging for large tool sets. */
	enabled: boolean().optional(),
	/** Exposed model surface. "tools" exposes structured search/describe/call tools; "directory" keeps a bounded directory plus selected schemas visible while deferring the rest behind search/describe/call. */
	mode: _enum(["tools", "directory"]).optional(),
	/** Presentation only: omitted includes all eligible tools; [] includes none. */
	include: array(ToolSearchSelectorSchema).optional(),
	/** Matching tools remain directly visible. Exclusion wins over inclusion. */
	exclude: array(ToolSearchSelectorSchema).optional(),
	/** Default search result count when the model omits a limit. Runtime clamps to maxSearchLimit. */
	searchDefaultLimit: number().int().positive().optional(),
	/** Maximum search result count. Runtime clamps to 1..50. */
	maxSearchLimit: number().int().positive().optional()
})]).optional();
const CodeModeSchema = union([
	boolean(),
	literal("auto"),
	strictObject({
		/** Explicit object-form activation. Omitted stays off; "auto" engages catalog-preferred models. A completely absent global codeMode setting defaults separately to auto. */
		enabled: union([boolean(), literal("auto")]).optional(),
		/** Executor. Node is the default; QuickJS provides a separate WASM guest. */
		executor: _enum(["node", "quickjs"]).optional(),
		/** Model-facing mode. Only "only" is supported: expose exec/wait and hide normal tools. */
		mode: literal("only").optional(),
		/** Wall-clock limit in milliseconds for one exec or wait call. */
		timeoutMs: number().int().positive().optional(),
		/** QuickJS guest heap limit or best-effort Node worker V8 heap budget in bytes; excludes external buffers and process RSS. */
		memoryLimitBytes: number().int().positive().optional(),
		/** Maximum serialized output bytes. */
		maxOutputBytes: number().int().positive().optional(),
		/** Maximum serialized snapshot bytes. */
		maxSnapshotBytes: number().int().positive().optional(),
		/** Maximum concurrent nested tool calls. */
		maxPendingToolCalls: number().int().positive().optional(),
		/** Retention for suspended snapshots. */
		snapshotTtlSeconds: number().int().positive().optional(),
		/** Default search result count for catalog.search. */
		searchDefaultLimit: number().int().positive().optional(),
		/** Maximum search result count for catalog.search. */
		maxSearchLimit: number().int().positive().optional()
	})
]).optional();
const SwarmSchema = union([boolean(), strictObject({
	/** Enable collector-mode subagents and agents_wait. Default: true. */
	enabled: boolean().optional(),
	/** Maximum concurrently running collector children per swarm group. */
	maxConcurrent: number().int().positive().optional(),
	/** Maximum live collector children per swarm group. */
	maxChildrenPerGroup: number().int().positive().optional(),
	/** Maximum lifetime collector spawns per swarm group. */
	maxTotalPerGroup: number().int().positive().optional(),
	waitTimeoutSecondsMax: number().int().positive().optional(),
	/** Default child agent id when sessions_spawn omits agentId. */
	defaultAgentId: string().optional()
})]).optional();
const SandboxSshSchema = strictObject({
	target: string().min(1).optional(),
	command: string().min(1).optional(),
	workspaceRoot: string().min(1).optional(),
	strictHostKeyChecking: boolean().optional(),
	updateHostKeys: boolean().optional(),
	identityFile: string().min(1).optional(),
	certificateFile: string().min(1).optional(),
	knownHostsFile: string().min(1).optional(),
	identityData: SecretInputSchema.optional().register(sensitive),
	certificateData: SecretInputSchema.optional().register(sensitive),
	knownHostsData: SecretInputSchema.optional().register(sensitive)
}).optional();
const AgentSandboxSchema = strictObject({
	mode: union([
		literal("off"),
		literal("non-main"),
		literal("all")
	]).optional(),
	backend: string().min(1).optional(),
	workspaceAccess: union([
		literal("none"),
		literal("ro"),
		literal("rw")
	]).optional(),
	sessionToolsVisibility: union([literal("spawned"), literal("all")]).optional(),
	scope: union([
		literal("session"),
		literal("agent"),
		literal("shared")
	]).optional(),
	workspaceRoot: string().optional(),
	docker: SandboxDockerSchema,
	ssh: SandboxSshSchema,
	browser: SandboxBrowserSchema,
	prune: SandboxPruneSchema
}).superRefine((e, t) => {
	if (getBlockedNetworkModeReason({
		network: e.browser?.network,
		allowContainerNamespaceJoin: e.docker?.dangerouslyAllowContainerNamespaceJoin === true
	}) === "container_namespace_join") t.addIssue({
		code: ZodIssueCode.custom,
		path: ["browser", "network"],
		message: "Sandbox security: browser network mode \"container:*\" is blocked by default. Set sandbox.docker.dangerouslyAllowContainerNamespaceJoin=true only when you fully trust this runtime."
	});
}).optional();
const CommonToolPolicyFields = {
	/** Base tool profile applied before allow/deny lists. */
	profile: ToolProfileSchema,
	...ToolPolicyBaseSchema.shape,
	/** Optional tool policy overrides keyed by provider id or "provider/model". */
	byProvider: record(string(), ToolPolicyWithProfileSchema).optional(),
	/** Per-sender tool policy overrides keyed by sender identity. */
	toolsBySender: ToolPolicyBySenderSchema
};
const NestedToolPolicySchema = strictObject({ tools: ToolPolicySchema$1 }).optional();
const ElevatedToolsSchema = strictObject({
	/** Enable or disable elevated mode (default: true). */
	enabled: boolean().optional(),
	/** Approved senders for /elevated (per-provider allowlists). */
	allowFrom: ElevatedAllowFromSchema
}).optional();
const OpenClawToolConfigSchema = strictObject({ 
/** Standing delegated administration grant; false requires exact human approval. */
autoApproveChanges: boolean().optional() }).optional();
const MessageToolConfigSchema = strictObject({
	crossContext: strictObject({
		/** Allow sends to other channels within the same provider (default: true). */
		allowWithinProvider: boolean().optional(),
		/** Allow sends across different providers (default: true). */
		allowAcrossProviders: boolean().optional(),
		marker: strictObject({
			/** Enable origin markers for cross-context sends (default: true). */
			enabled: boolean().optional(),
			/** Text prefix template, supports {channel}. */
			prefix: string().optional(),
			/** Text suffix template, supports {channel}. */
			suffix: string().optional()
		}).optional()
	}).optional(),
	actions: strictObject({ 
	/** Message action names exposed and accepted by the message tool. */
allow: array(string()).optional() }).optional(),
	broadcast: strictObject({ 
	/** Enable broadcast action (default: true). */
enabled: boolean().optional() }).optional()
}).optional();
const AgentToolsSchema = strictObject({
	...CommonToolPolicyFields,
	/** Per-agent code mode override; merges over the top-level tools.codeMode config. */
	codeMode: CodeModeSchema,
	/** Per-agent swarm override; merges over the top-level tools.swarm config. */
	swarm: SwarmSchema,
	/** Per-agent elevated exec gate (can only further restrict global tools.elevated). */
	elevated: ElevatedToolsSchema,
	exec: ToolExecSchema,
	openclaw: OpenClawToolConfigSchema,
	/** Complete per-agent GitHub CLI identity and Git author override. */
	github: AgentGitHubToolIdentitySchema,
	/** Filesystem tool path guards. */
	fs: ToolFsSchema,
	loopDetection: ToolLoopDetectionSchema,
	/** Explicit outbound destinations; does not grant session reads or bypass global/sandbox policy. */
	agentToAgent: strictObject({ 
	/** Agent ids or * globs for sessions_send. Omitted inherits visibility; [] denies cross-agent sends. */
send: array(string()).optional() }).optional(),
	message: MessageToolConfigSchema,
	sandbox: NestedToolPolicySchema
}).superRefine(createAllowAlsoAllowConflictValidator("agent tools cannot set both allow and alsoAllow in the same scope (merge alsoAllow into allow, or remove allow and use profile + alsoAllow)")).optional();
const AgentEntrySchema = AgentEntryBaseSchema.extend({
	nativeRuntimeConsent: array(string().trim().min(1)).optional(),
	memory: strictObject({ search: MemorySearchSchema }).optional(),
	humanDelay: HumanDelaySchema.optional(),
	typingMode: TypingModeSchema.optional(),
	tts: AgentTtsConfigSchema,
	skillsLimits: AgentSkillsLimitsSchema,
	contextLimits: AgentContextLimitsSchema,
	identity: IdentitySchema,
	groupChat: GroupChatSchema.unwrap().omit({ visibleReplies: true }).optional(),
	sandbox: AgentSandboxSchema,
	tools: AgentToolsSchema
}).strict();
const GatewayToolPolicyNameSchema = string().trim().min(1).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.:/-]*$/, "Use a concrete tool or action identity").refine((e) => !e.toLowerCase().startsWith("group:"), "Tool groups are not permitted");
const GatewayToolPolicySchema = strictObject({
	/** Required ceiling on model-visible Gateway tools. Empty means no tools. */
	allow: array(GatewayToolPolicyNameSchema),
	/** Action-bearing tools require an explicit list, including tools with a default action. */
	actions: record(GatewayToolPolicyNameSchema, array(GatewayToolPolicyNameSchema)).optional(),
	automations: strictObject({
		/** Model calls keep ordinary caller scope, even in administrator-started turns. */
		scope: literal("caller").optional(),
		/** Restricts model calls; direct human automation administration is unchanged. */
		allowCommandJobs: boolean().optional()
	}).optional()
});
const ToolsSchema = strictObject({
	...CommonToolPolicyFields,
	gatewayPolicy: GatewayToolPolicySchema.optional(),
	web: ToolsWebSchema,
	/** Managed local GitHub CLI identity and Git author; never overrides Git transport. */
	github: GitHubToolIdentitySchema,
	media: ToolsMediaSchema,
	links: ToolsLinksSchema,
	/**
	* Session tool visibility controls which sessions can be targeted by session tools
	* (sessions_list, sessions_history, sessions_search, sessions_send, session_status).
	*
	* Default: "all" (all sessions on the Gateway, with cross-agent access scoped by agentToAgent).
	*/
	sessions: strictObject({
		/**
		* - "self": only the current session
		* - "tree": current session + sessions spawned by this session
		* - "agent": any session belonging to the current agent id (can include other users)
		* - "all": any session (default; cross-agent access is governed by tools.agentToAgent)
		*/
		visibility: _enum([
			"self",
			"tree",
			"agent",
			"all"
		]).optional(),
		/** Allow sessions_send to target thread/topic sessions (default: false). */
		allowThreadTargets: boolean().optional()
	}).optional(),
	loopDetection: ToolLoopDetectionSchema,
	/** Compact large OpenClaw, MCP, and client tool catalogs behind search/call tools. */
	toolSearch: ToolSearchSchema,
	/** Global Code Mode defaults and limits; agent/model settings can override activation. */
	codeMode: CodeModeSchema,
	/** Collector-mode subagents and wait controls. */
	swarm: SwarmSchema,
	message: MessageToolConfigSchema,
	agentToAgent: strictObject({
		/** Default: true. False blocks ordinary cross-agent session tool access; requester-owned native subagent and ACP child sessions remain reachable under tree/all visibility. */
		enabled: boolean().optional(),
		/**
		* Agent ids or `*` glob patterns; the requesting and target agent must both match.
		* Omitted or empty counts as unset: every agent pair is allowed by default; blank entries deny.
		*/
		allow: array(string()).optional()
	}).optional(),
	/** Elevated exec permissions for the host machine. */
	elevated: ElevatedToolsSchema,
	exec: ToolExecSchema,
	openclaw: OpenClawToolConfigSchema,
	fs: ToolFsSchema,
	/** Sub-agent tool policy defaults (deny wins; progress_card is always denied). */
	subagents: NestedToolPolicySchema,
	/** Sandbox tool policy defaults (deny wins). */
	sandbox: NestedToolPolicySchema,
	sessions_spawn: strictObject({ attachments: strictObject({
		enabled: boolean().optional(),
		maxTotalBytes: number().optional(),
		maxFiles: number().optional(),
		maxFileBytes: number().optional(),
		retainOnSessionKeep: boolean().optional()
	}).optional() }).optional(),
	/** Unified progress_card status tool for parent sessions; enabled by default. False opts out. */
	updatePlan: boolean().optional()
}).superRefine(createAllowAlsoAllowConflictValidator("tools cannot set both allow and alsoAllow in the same scope (merge alsoAllow into allow, or remove allow and use profile + alsoAllow)")).optional();
//#endregion
//#region src/plugins/schema-validator.ts
const schemaCache = new LruCache(512);
//#endregion
//#region src/channels/plugins/config-schema.ts
const AllowFromListSchema = array(union([string(), number()])).optional();
/** Canonical per-group/room channel policy shape. */
const ChannelGroupEntrySchema = object({
	requireMention: boolean().optional(),
	tools: ToolPolicySchema$1,
	toolsBySender: record(string(), ToolPolicySchema$1).optional(),
	skills: array(string()).optional(),
	enabled: boolean().optional(),
	allowFrom: AllowFromListSchema,
	systemPrompt: string().optional()
}).strict();
/** Extend the canonical group/room policy shape with channel-owned fields. */
function buildGroupEntrySchema(e, t) {
	const n = new Set(t?.omit ?? []);
	const r = Object.fromEntries(Object.entries(ChannelGroupEntrySchema.shape).filter(([e]) => !n.has(e)));
	return object({
		...r,
		...e ?? {}
	}).strict();
}
/** Add the standard accounts/defaultAccount envelope and optional shared account/root refinement. */
function buildMultiAccountChannelSchema(e, t = {}) {
	const n = t.refine;
	const r = t.accountSchema ?? e;
	const i = n ? r.superRefine((e, t) => {
		return n(e, t);
	}) : r;
	const a = t.optionalAccount ? i.optional() : i;
	const o = t.accountsMode === "catchall" ? object({}).catchall(a).optional() : record(string(), a).optional();
	const s = e.extend({
		accounts: o,
		defaultAccount: string().optional()
	});
	return n ? s.superRefine((e, t) => {
		return n(e, t);
	}) : s;
}
function cloneRuntimeIssue(e) {
	const t = e && typeof e === "object" ? e : {};
	const n = Array.isArray(t.path) ? t.path.filter((e) => {
		const t = typeof e;
		return t === "string" || t === "number";
	}) : void 0;
	return {
		...t,
		...n ? { path: n } : {}
	};
}
/** Build a channel config schema from Zod, exporting JSON Schema when available. */
function buildChannelConfigSchema(e, t) {
	return {
		schema: "_zod" in e ? toJSONSchema(e, {
			target: "draft-07",
			...t?.jsonSchemaMode ? { io: t.jsonSchemaMode } : {},
			unrepresentable: "any"
		}) : {
			type: "object",
			additionalProperties: true
		},
		...t?.uiHints ? { uiHints: t.uiHints } : {},
		runtime: { safeParse(t) {
			const n = e.safeParse(t);
			return n.success ? {
				success: true,
				data: n.data
			} : {
				success: false,
				issues: n.error.issues.map(cloneRuntimeIssue)
			};
		} }
	};
}
//#endregion
//#region src/config/zod-schema.approvals.ts
const NativeExecApprovalEnableModeSchema = union([boolean(), literal("auto")]);
const ExecApprovalForwardTargetSchema = strictObject({
	channel: string().min(1),
	to: string().min(1),
	accountId: string().optional(),
	threadId: union([string(), number()]).optional()
});
const ExecApprovalForwardingSchema = strictObject({
	enabled: boolean().optional(),
	mode: union([
		literal("session"),
		literal("targets"),
		literal("both")
	]).optional(),
	agentFilter: array(string()).optional(),
	sessionFilter: array(string()).optional(),
	targets: array(ExecApprovalForwardTargetSchema).optional()
}).optional();
const SlackPluginApproverSchema = string().regex(/^(?:team:T[A-Z0-9]+:user:)?[UW][A-Z0-9]+$/i);
const PluginSlackApproversSchema = strictObject({
	approvers: array(SlackPluginApproverSchema).optional(),
	plugins: record(string(), strictObject({
		approvers: array(SlackPluginApproverSchema).optional(),
		tools: record(string(), strictObject({ approvers: array(SlackPluginApproverSchema) })).optional()
	})).optional()
});
const PluginApprovalConfigSchema = ExecApprovalForwardingSchema.unwrap().extend({ slack: PluginSlackApproversSchema.optional() }).optional();
const ApprovalsSchema = strictObject({
	exec: ExecApprovalForwardingSchema,
	plugin: PluginApprovalConfigSchema
}).optional();
//#endregion
//#region src/config/zod-schema.channels.ts
/** Optional heartbeat visibility controls shared by channel schemas. */
const ChannelHeartbeatVisibilitySchema$1 = strictObject({
	showOk: boolean().optional(),
	showAlerts: boolean().optional(),
	useIndicator: boolean().optional()
}).optional();
const ChannelHealthMonitorSchema = strictObject({ enabled: boolean().optional() }).optional();
//#endregion
//#region src/config/zod-schema.channel-bot-loop.ts
const ChannelBotLoopProtectionSchema = strictObject({
	enabled: boolean().optional(),
	maxEventsPerWindow: number().int().positive().optional(),
	windowSeconds: number().int().positive().optional(),
	cooldownSeconds: number().int().positive().optional()
});
//#endregion
//#region src/config/zod-schema.channel-messaging-common.ts
const UnifiedStreamingModeSchema = _enum([
	"off",
	"partial",
	"block",
	"progress"
]);
/** Shared DM switches; channels can specialize their group identifier validator. */
const ChannelGroupDmSchema = strictObject({
	/** If false, ignore incoming DMs. Default: true. */
	enabled: boolean().optional(),
	/** Allow group DMs. Default: false. */
	groupEnabled: boolean().optional(),
	/** Optional allowlist for group DM channels (ids or slugs). */
	groupChannels: array(union([string(), number()])).optional()
});
const ChannelThreadBindingsSchema = strictObject({
	enabled: boolean().optional(),
	idleHours: number().nonnegative().optional(),
	maxAgeHours: number().nonnegative().optional(),
	spawnSessions: boolean().optional(),
	defaultSpawnContext: _enum(["isolated", "fork"]).optional()
});
const ChannelStreamingPreviewSchema = strictObject({
	chunk: BlockStreamingChunkSchema.optional(),
	toolProgress: boolean().optional(),
	commandText: _enum(["raw", "status"]).optional()
});
const ChannelStreamingProgressSchema = strictObject({
	label: union([string(), literal(false)]).optional(),
	labels: array(string()).optional(),
	maxLines: number().int().positive().optional(),
	maxLineChars: number().int().positive().optional(),
	toolProgress: boolean().optional(),
	commandText: _enum(["raw", "status"]).optional(),
	commentary: boolean().optional(),
	narration: boolean().optional()
});
const ChannelPreviewStreamingConfigSchema = strictObject({
	mode: UnifiedStreamingModeSchema.optional(),
	chunkMode: TextChunkModeSchema.optional(),
	preview: ChannelStreamingPreviewSchema.optional(),
	progress: ChannelStreamingProgressSchema.optional(),
	block: ChannelStreamingBlockSchema.optional()
});
const CommonCapabilitiesSchema = array(string()).optional();
const CommonIdListSchema = array(union([string(), number()])).optional();
const CommonDefaultToSchema = string().optional();
const CommonMentionPatternsSchema = MentionPatternsPolicySchema.optional();
const CommonStreamingSchema = ChannelDeliveryStreamingConfigSchema.optional();
const CommonMediaMaxMbSchema = number().positive().optional();
const CommonReplyToModeSchema = ReplyToModeSchema.optional();
const ChannelAccountPolicyDefaults = {
	dmPolicy: DmPolicySchema.optional().default("pairing"),
	groupPolicy: GroupPolicySchema.optional().default("allowlist")
};
/** Canonical optional account contract shared by bundled messaging channels. */
const CommonChannelAccountSchema = strictObject({
	name: string().optional(),
	capabilities: CommonCapabilitiesSchema,
	markdown: MarkdownConfigSchema$1,
	configWrites: boolean().optional(),
	enabled: boolean().optional(),
	dmPolicy: DmPolicySchema.optional(),
	allowFrom: CommonIdListSchema,
	defaultTo: CommonDefaultToSchema,
	groupAllowFrom: CommonIdListSchema,
	groupPolicy: GroupPolicySchema.optional(),
	mentionPatterns: CommonMentionPatternsSchema,
	contextVisibility: ContextVisibilityModeSchema.optional(),
	historyLimit: number().int().min(0).optional(),
	dmHistoryLimit: number().int().min(0).optional(),
	dms: record(string(), DmConfigSchema$1.optional()).optional(),
	textChunkLimit: number().int().positive().optional(),
	streaming: CommonStreamingSchema,
	healthMonitor: ChannelHealthMonitorSchema,
	responsePrefix: string().optional(),
	mediaMaxMb: CommonMediaMaxMbSchema,
	replyToMode: CommonReplyToModeSchema
});
const ChannelDangerouslyAllowNameMatchingSchema = boolean().optional();
const ChannelSendReadReceiptsSchema = boolean().optional();
//#endregion
//#region src/config/zod-schema.implicit-mentions.ts
const ChannelImplicitMentionsSchema = strictObject({
	replyToBot: boolean().optional(),
	quotedBot: boolean().optional(),
	threadParticipation: boolean().optional()
});
//#endregion
//#region extensions/feishu/src/external-keys.ts
const FEISHU_EXTERNAL_KEY_PATTERN = /^(?!\s)(?![\s\S]*\s$)(?![\s\S]*\.\.)[^\p{Cc}\p{Cs}/\\]{1,512}$/u;
//#endregion
//#region extensions/feishu/src/webhook-path.ts
const DEFAULT_FEISHU_WEBHOOK_PATH = "/feishu/events";
/** Normalize trusted configuration only; incoming request targets must remain unmodified. */
function normalizeFeishuWebhookPath(e) {
	const t = e?.trim();
	if (!t) return DEFAULT_FEISHU_WEBHOOK_PATH;
	const n = URL.parse(t, "http://localhost");
	if (!n || n.protocol !== "http:" && n.protocol !== "https:") return null;
	const r = !n.search && n.href.endsWith("?") && !t.includes("#") ? "?" : "";
	return `${n.pathname}${n.search}${r}`;
}
//#endregion
//#region extensions/feishu/src/config-schema.ts
const ChannelActionsSchema = object({
	reactions: boolean().optional(),
	sticker: boolean().optional()
}).strict().optional();
const MAX_STICKER_SETS = 32;
const MAX_STICKERS_PER_SET = 256;
function canonicalTextPattern(e) {
	return new RegExp(`^(?!\\s)(?![\\s\\S]*\\s$)[^\\p{Cs}]{1,${e}}$`, "u");
}
const FeishuStickerSetSchema = record(string().regex(FEISHU_EXTERNAL_KEY_PATTERN), array(string().regex(canonicalTextPattern(64))).min(1).max(8)).refine((e) => Object.keys(e).length <= MAX_STICKERS_PER_SET, { message: `At most ${MAX_STICKERS_PER_SET} stickers per bot set are allowed` }).meta({ maxProperties: MAX_STICKERS_PER_SET });
const FeishuStickerSetsSchema = record(string().regex(canonicalTextPattern(128)), FeishuStickerSetSchema).refine((e) => Object.keys(e).length <= MAX_STICKER_SETS, { message: `At most ${MAX_STICKER_SETS} bot sticker sets are allowed` }).meta({ maxProperties: MAX_STICKER_SETS });
const FeishuGroupPolicySchema = union([GroupPolicySchema, literal("allowall").transform(() => "open")]);
const FeishuDomainSchema = union([_enum(["feishu", "lark"]), string().regex(/^[Hh][Tt][Tt][Pp][Ss]:\/\//).url()]);
const FeishuConnectionModeSchema = _enum(["websocket", "webhook"]);
const FeishuWebhookPathSchema = string().refine((e) => normalizeFeishuWebhookPath(e) === e, { message: "webhookPath must be a normalized HTTP request path; run \"openclaw doctor --fix\" to repair it" });
const TtsOverrideSchema = object({
	auto: TtsConfigSchema.unwrap().shape.auto,
	enabled: boolean().optional(),
	mode: _enum(["final", "all"]).optional(),
	provider: string().optional(),
	persona: string().optional(),
	personas: record(string(), record(string(), unknown())).optional(),
	summaryModel: string().optional(),
	modelOverrides: record(string(), unknown()).optional(),
	providers: record(string(), record(string(), unknown())).optional(),
	prefsPath: string().optional(),
	maxTextLength: number().int().min(1).optional(),
	timeoutMs: number().int().min(1e3).max(12e4).optional()
}).strict().optional();
const ToolPolicySchema = object({
	allow: array(string()).optional(),
	deny: array(string()).optional()
}).strict().optional();
const DmConfigSchema = object({
	enabled: boolean().optional(),
	systemPrompt: string().optional()
}).strict().optional();
const MarkdownConfigSchema = object({
	mode: _enum([
		"native",
		"escape",
		"strip"
	]).optional(),
	tableMode: _enum([
		"native",
		"ascii",
		"simple"
	]).optional()
}).strict().optional();
const RenderModeSchema = _enum([
	"auto",
	"raw",
	"card"
]).optional();
const FeishuStreamingSchema = object({
	mode: _enum(["off", "partial"]).optional(),
	...ChannelDeliveryStreamingConfigSchema.shape
}).strict().optional();
const ChannelHeartbeatVisibilitySchema = object({
	visibility: _enum(["visible", "hidden"]).optional(),
	intervalMs: number().int().positive().optional()
}).strict().optional();
/**
* Dynamic agent creation configuration.
* When enabled, a new agent is created for each unique DM user.
*/
const DynamicAgentCreationSchema = object({
	enabled: boolean().optional(),
	workspaceTemplate: string().optional(),
	agentDirTemplate: string().optional(),
	maxAgents: number().int().positive().optional()
}).strict().optional();
/**
* Dependencies:
* - wiki requires doc (wiki content is edited via doc tools)
* - perm can work independently but is typically used with drive
*/
const FeishuToolsConfigSchema = object({
	doc: boolean().optional(),
	chat: boolean().optional(),
	wiki: boolean().optional(),
	drive: boolean().optional(),
	perm: boolean().optional(),
	scopes: boolean().optional(),
	bitable: boolean().optional()
}).strict().optional();
/**
* Group session scope for routing Feishu group messages.
* - "group" (default): one session per group chat
* - "group_sender": one session per (group + sender)
* - "group_topic": one session per group topic thread (falls back to group if no topic)
* - "group_topic_sender": one session per (group + topic thread + sender),
*   falls back to (group + sender) if no topic
*/
const GroupSessionScopeSchema = _enum([
	"group",
	"group_sender",
	"group_topic",
	"group_topic_sender"
]).optional();
/**
* @deprecated Use groupSessionScope instead.
*
* Topic session isolation mode for group chats.
* - "disabled" (default): All messages in a group share one session
* - "enabled": Messages in different topics get separate sessions
*
* Topic routing uses Feishu topic-group `thread_id` when the event identifies a
* native topic group, and keeps `root_id` precedence for normal groups so
* reply-created threads stay on the initiating message session.
*/
const TopicSessionModeSchema = _enum(["disabled", "enabled"]).optional();
const ReactionNotificationModeSchema = _enum([
	"off",
	"own",
	"all"
]).optional();
/**
* Reply-in-thread mode for group chats.
* - "disabled" (default): Bot replies are normal inline replies
* - "enabled": Bot replies create or continue a Feishu topic thread
*
* When enabled, the Feishu reply API is called with `reply_in_thread: true`,
* causing the reply to appear as a topic (话题) under the original message.
*/
const ReplyInThreadSchema = _enum(["disabled", "enabled"]).optional();
const RequireMentionInBotThreadsSchema = boolean().optional().describe("Require mentions in threads started by this bot. False permits unmentioned messages; true requires a mention. Omit to preserve existing mention behavior.");
const FeishuGroupSchema = buildGroupEntrySchema({
	tools: ToolPolicySchema,
	requireMentionInBotThreads: RequireMentionInBotThreadsSchema,
	groupSessionScope: GroupSessionScopeSchema,
	topicSessionMode: TopicSessionModeSchema,
	replyInThread: ReplyInThreadSchema
}).omit({ toolsBySender: true });
const FeishuSharedConfigShape = {
	legacyWebhook: object({
		port: number().int().min(1).max(65535),
		host: string().optional()
	}).strict().or(literal(false)).optional(),
	capabilities: array(string()).optional(),
	markdown: MarkdownConfigSchema,
	configWrites: boolean().optional(),
	contextVisibility: ContextVisibilityModeSchema.optional(),
	replyToMode: ReplyToModeSchema.optional(),
	responsePrefix: string().optional(),
	dmPolicy: DmPolicySchema.optional(),
	allowFrom: array(union([string(), number()])).optional(),
	groupPolicy: FeishuGroupPolicySchema.optional(),
	groupAllowFrom: array(union([string(), number()])).optional(),
	groupSenderAllowFrom: array(union([string(), number()])).optional(),
	requireMention: boolean().optional(),
	requireMentionInBotThreads: RequireMentionInBotThreadsSchema,
	groups: record(string(), FeishuGroupSchema.optional()).optional(),
	historyLimit: number().int().min(0).optional(),
	dmHistoryLimit: number().int().min(0).optional(),
	dms: record(string(), DmConfigSchema).optional(),
	textChunkLimit: number().int().positive().optional(),
	mediaMaxMb: number().positive().optional(),
	httpTimeoutMs: number().int().positive().max(3e5).optional(),
	heartbeatVisibility: ChannelHeartbeatVisibilitySchema,
	renderMode: RenderModeSchema,
	streaming: FeishuStreamingSchema,
	tools: FeishuToolsConfigSchema,
	actions: ChannelActionsSchema,
	replyInThread: ReplyInThreadSchema,
	reactionNotifications: ReactionNotificationModeSchema,
	typingIndicator: boolean().optional(),
	resolveSenderNames: boolean().optional(),
	allowBots: boolean().optional(),
	vcAutoJoin: boolean().optional(),
	tts: TtsOverrideSchema
};
/**
* Per-account configuration.
* All fields are optional - missing fields inherit from top-level config.
*/
const FeishuAccountConfigSchema = object({
	enabled: boolean().optional(),
	name: string().optional(),
	appId: string().optional(),
	appSecret: buildSecretInputSchema().optional(),
	encryptKey: buildSecretInputSchema().optional(),
	verificationToken: buildSecretInputSchema().optional(),
	domain: FeishuDomainSchema.optional(),
	connectionMode: FeishuConnectionModeSchema.optional(),
	webhookPath: FeishuWebhookPathSchema.optional(),
	...FeishuSharedConfigShape,
	groupSessionScope: GroupSessionScopeSchema,
	topicSessionMode: TopicSessionModeSchema
}).strict();
const FeishuConfigSchemaBase = object({
	enabled: boolean().optional(),
	defaultAccount: string().optional(),
	stickerSets: FeishuStickerSetsSchema.optional(),
	appId: string().optional(),
	appSecret: buildSecretInputSchema().optional(),
	encryptKey: buildSecretInputSchema().optional(),
	verificationToken: buildSecretInputSchema().optional(),
	domain: FeishuDomainSchema.optional().default("feishu"),
	connectionMode: FeishuConnectionModeSchema.optional().default("websocket"),
	webhookPath: FeishuWebhookPathSchema.optional().default(DEFAULT_FEISHU_WEBHOOK_PATH),
	...FeishuSharedConfigShape,
	dmPolicy: DmPolicySchema.optional().default("pairing"),
	reactionNotifications: ReactionNotificationModeSchema.optional().default("own"),
	groupPolicy: FeishuGroupPolicySchema.optional().default("allowlist"),
	requireMention: boolean().optional(),
	groupSessionScope: GroupSessionScopeSchema,
	topicSessionMode: TopicSessionModeSchema,
	dynamicAgentCreation: DynamicAgentCreationSchema,
	typingIndicator: boolean().optional().default(true),
	resolveSenderNames: boolean().optional().default(true)
}).strict();
const FeishuConfigSchema = buildMultiAccountChannelSchema(FeishuConfigSchemaBase, {
	accountSchema: FeishuAccountConfigSchema,
	optionalAccount: true
}).superRefine((e, t) => {
	const n = e.defaultAccount?.trim();
	if (n && e.accounts && Object.keys(e.accounts).length > 0) {
		const r = normalizeAccountId(n);
		if (!Object.hasOwn(e.accounts, r)) t.addIssue({
			code: ZodIssueCode.custom,
			path: ["defaultAccount"],
			message: `channels.feishu.defaultAccount="${n}" does not match a configured account key`
		});
	}
	const r = e.connectionMode ?? "websocket";
	const i = hasConfiguredSecretInput(e.verificationToken);
	const a = hasConfiguredSecretInput(e.encryptKey);
	if (r === "webhook") {
		if (!i) t.addIssue({
			code: ZodIssueCode.custom,
			path: ["verificationToken"],
			message: "channels.feishu.connectionMode=\"webhook\" requires channels.feishu.verificationToken"
		});
		if (!a) t.addIssue({
			code: ZodIssueCode.custom,
			path: ["encryptKey"],
			message: "channels.feishu.connectionMode=\"webhook\" requires channels.feishu.encryptKey"
		});
	}
	for (const [n, o] of Object.entries(e.accounts ?? {})) {
		if (!o) continue;
		if ((o.connectionMode ?? r) !== "webhook") continue;
		const e = hasConfiguredSecretInput(o.verificationToken) || i;
		const s = hasConfiguredSecretInput(o.encryptKey) || a;
		if (!e) t.addIssue({
			code: ZodIssueCode.custom,
			path: [
				"accounts",
				n,
				"verificationToken"
			],
			message: `channels.feishu.accounts.${n}.connectionMode="webhook" requires a verificationToken (account-level or top-level)`
		});
		if (!s) t.addIssue({
			code: ZodIssueCode.custom,
			path: [
				"accounts",
				n,
				"encryptKey"
			],
			message: `channels.feishu.accounts.${n}.connectionMode="webhook" requires an encryptKey (account-level or top-level)`
		});
	}
	if (e.dmPolicy === "open") {
		if (!(e.allowFrom ?? []).some((e) => String(e).trim() === "*")) t.addIssue({
			code: ZodIssueCode.custom,
			path: ["allowFrom"],
			message: "channels.feishu.dmPolicy=\"open\" requires channels.feishu.allowFrom to include \"*\""
		});
	}
});
const FeishuChannelConfigSchema = buildChannelConfigSchema(FeishuConfigSchema, { jsonSchemaMode: "input" });
//#endregion
//#region extensions/feishu/src/doctor-contract.ts
const webhookListenerMigration = createLegacyWebhookListenerDoctorContract({
	channelKey: "feishu",
	defaultPort: 3e3,
	defaultHost: "127.0.0.1"
});
const { historicalWebhookListener } = webhookListenerMigration;
const streamingAliasMigration = defineChannelAliasMigration({
	channelId: "feishu",
	streaming: { defaultMode: "partial" },
	accountStreamingReplacesRoot: true
});
const LEGACY_COALESCE_FIELDS = [
	"enabled",
	"minDelayMs",
	"maxDelayMs"
];
const LEGACY_HEARTBEAT_FIELDS = ["visibility", "intervalMs"];
const toolsBaseMigration = defineKeyMoveMigration({
	from: ["tools", "base"],
	to: ["tools", "bitable"],
	match: (e) => typeof e === "boolean",
	sourceOwn: false
});
function hasLegacyWebhookPath(e) {
	const t = asNullableRecord(e)?.webhookPath;
	return typeof t === "string" && normalizeFeishuWebhookPath(t) !== t;
}
function normalizeFeishuLegacyConfigEntries(e, t) {
	return normalizeChannelConfigEntries({
		cfg: e,
		channelId: "feishu",
		changes: t,
		normalizeEntry: (e) => {
			let { entry: t, changed: n } = toolsBaseMigration.normalize(e);
			const r = asNullableRecord(t.streaming);
			const i = asNullableRecord(r?.block);
			const a = asNullableRecord(i?.coalesce);
			if (r && i && a) {
				const o = LEGACY_COALESCE_FIELDS.filter((e) => a[e] !== void 0);
				if (o.length > 0) {
					const s = { ...a };
					for (const e of o) delete s[e];
					e.changes.push(`Removed ${e.pathPrefix}.streaming.block.coalesce.{${o.join(",")}} (legacy Feishu-only fields; block delivery reads minChars/maxChars/idleMs).`);
					t = {
						...t,
						streaming: {
							...r,
							block: {
								...i,
								coalesce: s
							}
						}
					};
					n = true;
				}
			}
			const o = asNullableRecord(t.heartbeat);
			if (o && (Object.keys(o).length === 0 || LEGACY_HEARTBEAT_FIELDS.some((e) => Object.hasOwn(o, e)))) {
				const r = { ...t };
				delete r.heartbeat;
				e.changes.push(`Removed ${e.pathPrefix}.heartbeat (legacy Feishu fields were never read by runtime).`);
				t = r;
				n = true;
			}
			const s = t.webhookPath;
			if (typeof s === "string") {
				const r = normalizeFeishuWebhookPath(s);
				const i = r ?? "/feishu/events";
				if (i !== s) {
					e.changes.push(r === null ? `Reset invalid ${e.pathPrefix}.webhookPath to ${DEFAULT_FEISHU_WEBHOOK_PATH}.` : `Normalized ${e.pathPrefix}.webhookPath to its HTTP request path.`);
					t = {
						...t,
						webhookPath: i
					};
					n = true;
				}
			}
			return {
				entry: t,
				changed: n
			};
		}
	}).config;
}
const feishuStrayEntryConfigMigration = defineStrayPluginEntryConfigMigration({
	pluginId: "feishu",
	channelId: "feishu",
	validateMergedChannelConfig: (e) => FeishuConfigSchema.safeParse(e).success
});
const legacyConfigRules = [
	...streamingAliasMigration.legacyConfigRules,
	...webhookListenerMigration.legacyConfigRules,
	feishuStrayEntryConfigMigration.legacyConfigRule,
	{
		path: ["channels", "feishu"],
		message: "channels.feishu[.accounts.<id>].webhookPath must be a normalized HTTP request path; run \"openclaw doctor --fix\".",
		match: (e) => {
			const t = asNullableRecord(e);
			return hasLegacyWebhookPath(t) || hasLegacyAccountStreamingAliases(t?.accounts, hasLegacyWebhookPath);
		}
	},
	{
		path: ["channels", "feishu"],
		message: "channels.feishu[.accounts.<id>].tools.base is legacy; use tools.bitable. Run \"openclaw doctor --fix\".",
		match: (e) => {
			const t = asNullableRecord(e);
			return toolsBaseMigration.hasLegacy(t) || hasLegacyAccountStreamingAliases(t?.accounts, toolsBaseMigration.hasLegacy);
		}
	}
];
function resolveHistoricalWebhookAccountIds(e) {
	return e.channels?.feishu?.enabled === false ? [] : listFeishuAccountIds(e).filter((t) => {
		const n = mergeFeishuAccountConfig(e, t);
		return n.enabled !== false && n.connectionMode === "webhook";
	});
}
function normalizeHistoricalWebhookConfig({ cfg: e }) {
	const t = webhookListenerMigration.normalizeCompatibilityConfig({ cfg: e });
	return {
		...t,
		historicalWebhookAccountIds: resolveHistoricalWebhookAccountIds(t.config)
	};
}
function normalizeCompatibilityConfig({ cfg: e }) {
	const t = streamingAliasMigration.normalizeChannelConfig({ cfg: e });
	const n = webhookListenerMigration.normalizeCompatibilityConfig({ cfg: t.config });
	const r = [...t.changes, ...n.changes];
	const i = normalizeFeishuLegacyConfigEntries(n.config, r);
	const a = feishuStrayEntryConfigMigration.normalizeConfig({ cfg: i });
	return {
		config: a.config,
		changes: [...r, ...a.changes],
		historicalWebhookAccountIds: resolveHistoricalWebhookAccountIds(a.config)
	};
}
//#endregion
export { historicalWebhookListener, legacyConfigRules, normalizeCompatibilityConfig, normalizeHistoricalWebhookConfig };