UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

76 lines • 76.9 kB
import{C as isRecord,_ as normalizeOptionalLowercaseString,b as asNullableRecord,d as isBlockedObjectKey,f as normalizeStringEntries,h as normalizeLowercaseStringOrEmpty,p as normalizeUniqueStringEntries,v as normalizeOptionalString}from"./global-singleton-CTnqrmaI.js";import{C as hasLegacyAccountStreamingAliases,T as normalizeChannelConfigEntries,n as defineKeyMoveMigration,p as normalizeAccountId,r as defineStrayPluginEntryConfigMigration,s as defineChannelAliasMigration}from"./runtime-doctor-migrations-D8alsOFs.js";import{t as createLegacyWebhookListenerDoctorContract}from"./legacy-webhook-listener-migration-Bk_hZlpH.js";import{b as createAccountListHelpers,l as LruCache,x as hasConfiguredAccountValue}from"./account-core-34NfXidI.js";import"./account-resolution-CI_Jf-zG.js";import{_ as tuple,b as toJSONSchema,c as literal,d as number,f as object,g as string,h as strictObject,i as boolean,m as record,n as _null,o as discriminatedUnion,p as preprocess,r as array,t as _enum,v as union,y as unknown}from"./schemas-Bt_o0OU8.js";import{o as ENV_SECRET_REF_ID_RE,s as SECRET_PROVIDER_ALIAS_PATTERN,t as hasConfiguredSecretInput}from"./types.secrets-CpaxAqFj.js";import{n as sensitive,r as SecretInputSchema,t as buildSecretInputSchema}from"./secret-input-IIFLtZo5.js";import"./string-coerce-runtime-DtNToPzY.js";import"./boundary-path-93ijeUSt.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";
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/compat.js
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`};var ZodFirstPartyTypeKind;ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={});
//!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}
//!src/agents/sandbox/network-mode.ts
function normalizeNetworkMode(e){return normalizeOptionalLowercaseString(e)||void 0}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}
//!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)}
//!src/config/web-search-legacy-provider-keys.ts
const LEGACY_WEB_SEARCH_PROVIDER_CONFIG_KEYS=/* @__PURE__ */ new Set([`brave`,`duckduckgo`,`exa`,`firecrawl`,`gemini`,`grok`,`kimi`,`minimax`,`ollama`,`perplexity`,`searxng`,`tavily`]);
//!packages/model-catalog-core/src/provider-id.ts
function normalizeProviderId(e){return normalizeLowercaseStringOrEmpty(e)}
//!packages/model-catalog-core/src/model-catalog-refs.ts
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}
//!src/auto-reply/thinking.shared.ts
const ALL_THINKING_LEVELS=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`adaptive`,`max`,`ultra`];const THINKING_LEVELS_HELP=ALL_THINKING_LEVELS.join(`|`);
//!src/config/zod-schema.agent-model.ts
const DecisionModelSchema=string().trim().max(512).refine(e=>e===``||parseProviderModelRef(e)!==null,`Expected provider/model, or an empty string to disable decision models.`);const AgentModelSchema=union([string(),strictObject({primary:string().optional(),fallbacks:array(string()).optional()})]);const AgentToolModelSchema=union([string(),strictObject({primary:string().optional(),fallbacks:array(string()).optional(),timeoutMs:number().int().positive().optional()})]);
//!src/config/zod-schema.agent-entry-base.ts
const WorkspaceFileModeSchema=_enum([`0600`,`0620`,`0640`,`0660`],{error:`Expected an octal string: 0600, 0620, 0640, or 0660 (owner read/write; group access optional)`});const AgentCompactionMaxSummaryCharsSchema=number().int().min(1e3).max(2e5);const AgentRuntimePolicySchema=strictObject({id:string().optional()}).optional();const AgentModelRuntimeEntrySchema=strictObject({alias:string().optional(),params:record(string(),unknown()).optional(),agentRuntime:AgentRuntimePolicySchema,pickerRuntimes:array(string().trim().min(1).max(128).regex(/^[a-z][a-z0-9-]*$/).refine(e=>e!==`auto`&&e!=="default")).max(8).optional(),codeMode:boolean().optional(),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({allow:array(string()).optional()});const AgentRuntimeAcpSchema=strictObject({agent:string().optional(),backend:string().optional(),mode:_enum([`persistent`,`oneshot`]).optional(),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(),workspaceFileMode:WorkspaceFileModeSchema.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(),newSessionPermissionMode:_enum([`read-only`,`guarded`,`workspace`,`full`]).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({maxSummaryChars:AgentCompactionMaxSummaryCharsSchema.optional()}).optional(),params:record(string(),unknown()).optional(),runtime:AgentRuntimeSchema});
//!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(`\\`)}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)}
//!src/secrets/exact-hostname.ts
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}
//!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`];
//!src/config/model-config-vocabulary.ts
const MODEL_APIS=[...MODEL_DATA_APIS];const MODEL_THINKING_FORMATS=[...MODEL_DATA_THINKING_FORMATS];
//!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`]);function isBuiltInModelProviderOverlayId(e){return BUILT_IN_MODEL_PROVIDER_OVERLAY_IDS.has(normalizeProviderId(e))}
//!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()}
//!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();
//!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()});const ModelCompatSchema=strictObject({supportsStore:boolean().optional(),supportsPromptCacheKey:boolean().optional(),supportsResponsesContinuation:boolean().optional(),supportsDeveloperRole:boolean().optional(),supportsReasoningEffort:boolean().optional(),supportsTemperature:boolean().optional(),supportsInstructions:boolean().optional(),cachesInstructions:boolean().optional(),supportsUsageInStreaming:boolean().optional(),supportsTools:boolean().optional(),codeMode:_enum([`preferred`,`capable`]).optional(),supportsStrictMode:boolean().optional(),supportsJsonSchemaResponseFormat:boolean().optional(),requiresStringContent:boolean().optional(),strictMessageKeys:boolean().optional(),visibleReasoningDetailTypes:array(string().min(1)).optional(),supportedReasoningEfforts:array(string().min(1)).optional(),reasoningEffortMap:record(string().min(1),string().min(1)).optional(),defaultThinkingLevel:string().min(1).optional(),thinkingLevels:array(string().min(1)).optional(),adaptiveThinking:boolean().optional(),thinkingRequired:boolean().optional(),thinkingLevelLabels:record(string().min(1),string().min(1)).optional(),maxTokensField:union([literal(`max_completion_tokens`),literal(`max_tokens`)]).optional(),thinkingFormat:_enum(MODEL_THINKING_FORMATS).optional(),requiresToolResultName:boolean().optional(),requiresAssistantAfterToolResult:boolean().optional(),requiresThinkingAsText:boolean().optional(),requiresReasoningContentOnAssistantMessages:boolean().optional(),toolSchemaProfile:string().optional(),unsupportedToolSchemaKeywords:array(string().min(1)).optional(),toolCallArgumentsEncoding:string().optional(),requiresOpenAiAnthropicToolPayload:boolean().optional(),openRouterRouting:OpenRouterRoutingSchema.optional(),vercelGatewayRouting:VercelGatewayRoutingSchema.optional(),zaiToolStream:boolean().optional(),cacheControlFormat:literal(`anthropic`).optional(),sendSessionAffinityHeaders:boolean().optional(),sendSessionIdHeader:boolean().optional(),supportsEagerToolInputStreaming:boolean().optional(),supportsLongCacheRetention:boolean().optional()}).optional();
//!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)}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`),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({id:string().min(1),name:string().min(1),api:ModelApiSchema.optional(),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(),contextWindow:number().positive().optional(),contextTokens:number().int().positive().optional(),maxTokens:number().positive().optional(),thinkingLevelMap:ThinkingLevelMapSchema.optional(),params:record(string(),unknown()).optional(),agentRuntime:AgentRuntimePolicySchema,headers:record(string(),string()).optional(),compat:ModelCompatSchema,mediaInput:ModelMediaInputSchema.optional(),responseModelEquivalent:boolean().optional(),metadataSource:literal(`models-add`).optional()});const ModelProviderLocalServiceSchema=strictObject({command:string().min(1),args:array(string()).optional(),cwd:string().min(1).optional(),env:record(string(),string().register(sensitive)).optional(),healthUrl:string().min(1).optional(),readyTimeoutMs:number().int().positive().optional(),idleStopMs:number().int().nonnegative().optional()}).optional();const ModelProviderIconSchema=discriminatedUnion(`source`,[strictObject({source:literal(`file`),path:string().trim().min(1).max(4096)}),strictObject({source:literal(`url`),url:string().url().max(4096).refine(e=>{try{const t=new URL(e);return t.protocol===`https:`&&!t.username&&!t.password&&!t.hash}catch{return false}},`Provider icon URL must use HTTPS without credentials or a fragment`)}),strictObject({source:literal(`builtin`),name:string().trim().min(1).max(100)})]);const ModelProviderSchema=strictObject({name:string().trim().min(1).max(100).optional(),icon:ModelProviderIconSchema.optional(),baseUrl:string().optional(),apiKey:SecretInputSchema.optional().register(sensitive),auth:union([literal(`api-key`),literal(`aws-sdk`),literal(`oauth`),literal(`token`),literal(`none`),literal(`native-command`)]).optional(),api:ModelApiSchema.optional(),maxTokens:number().positive().optional(),timeoutSeconds:number().int().positive().optional(),region:string().min(1).optional(),injectNumCtxForOpenAICompat:boolean().optional(),params:record(string(),unknown()).optional(),agentRuntime:AgentRuntimePolicySchema,localService:ModelProviderLocalServiceSchema,remote:boolean().optional(),headers:record(string(),SecretInputSchema.register(sensitive)).optional(),authHeader:boolean().optional(),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({enabled:boolean().optional(),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({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()});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()});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`);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({mode:union([literal(`first`),literal(`all`)]).optional(),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={prompt:string().optional(),timeoutSeconds:number().int().positive().optional(),language:string().optional(),providerOptions:ProviderOptionsSchema,baseUrl:string().optional(),headers:record(string(),string()).optional(),request:ConfiguredProviderRequestSchema};const MediaUnderstandingModelSchema=strictObject({provider:string().optional(),model:string().optional(),capabilities:array(union([literal(`image`),literal(`audio`),literal(`video`)])).optional(),type:union([literal(`provider`),literal(`cli`)]).optional(),command:string().optional(),args:array(string()).optional(),maxChars:number().int().positive().optional(),maxBytes:number().int().positive().optional(),...MediaUnderstandingRuntimeFields,profile:string().optional(),preferredProfile:string().optional()}).optional();const ToolsMediaCapabilitySchema=strictObject({enabled:boolean().optional(),preferredModel:string().trim().min(1).optional(),scope:MediaUnderstandingScopeSchema,maxBytes:number().int().positive().optional(),maxChars:number().int().positive().optional(),...MediaUnderstandingRuntimeFields,attachments:MediaUnderstandingAttachmentsSchema}).optional();const ToolsMediaAudioSchema=ToolsMediaCapabilitySchema.unwrap().extend({echoTranscript:boolean().optional(),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({type:literal(`cli`).optional(),command:string().min(1),args:array(string()).optional(),timeoutSeconds:number().int().positive().optional()});const ToolsLinksSchema=strictObject({enabled:boolean().optional(),scope:MediaUnderstandingScopeSchema,maxLinks:number().int().positive().optional(),timeoutSeconds:number().int().positive().optional(),models:array(LinkModelSchema).optional()}).optional();
//!src/config/github-identity-profile-id.ts
const MANAGED_GITHUB_PROFILE_ID_PATTERN=/^ghp_[a-f0-9]{32}$/u;
//!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();
//!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();
//!src/agents/sandbox/bind-spec.ts
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)}
//!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)}
//!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(`
`):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();
//!src/config/zod-schema.agent-runtime.ts
const AgentTtsConfigSchema=TtsConfigSchema.unwrap().extend({prefsPath:string().optional()}).strict().optional();const AgentContextLimitsSchema=strictObject({memoryGetMaxChars:number().int().min(1).max(25e4).optional(),postCompactionMaxChars:number().int().min(1).max(5e4).optional()}).optional();const AgentSkillsLimitsSchema=strictObject({maxSkillsPromptChars:number().int().min(0).optional()}).optional();const ToolPolicyBaseSchema=strictObject({allow:array(string()).optional(),alsoAllow:array(string()).optional(),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({enabled:boolean().optional(),provider:string().optional(),maxChars:number().int().positive().optional(),maxCharsCap:number().int().positive().optional(),maxResponseBytes:number().int().positive().optional(),timeoutSeconds:number().int().positive().optional(),cacheTtlMinutes:number().nonnegative().optional(),maxRedirects:number().int().nonnegative().optional(),userAgent:string().optional(),headers:record(string(),string().register(sensitive)).optional(),readability:boolean().optional(),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 ExecModeSchema=_enum([`deny`,`allowlist`,`ask`,`auto`,`full`]);const ToolPolicyWithProfileSchema=ToolPolicyBaseSchema.extend({profile:ToolProfileSchema,exec:strictObject({mode:ExecModeSchema.optional()}).optional()}).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({enabled:boolean().optional(),workspaceOnly:boolean().optional(),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={host:_enum([`auto`,`sandbox`,`gateway`,`node`]).optional(),mode:ExecModeSchema.optional(),security:_enum([`deny`,`allowlist`,`full`]).optional(),ask:_enum([`off`,`on-miss`,`always`]).optional(),node:string().optional(),pathPrepend:array(string()).optional(),safeBins:array(string()).optional(),strictInlineEval:boolean().optional(),commandHighlighting:boolean().optional(),grantExpiryDays:number().int().min(1).max(3650).optional(),safeBinTrustedDirs:array(string()).optional(),safeBinProfiles:record(string(),ToolExecSafeBinProfileSchema).optional(),reviewer:strictObject({model:AgentModelSchema.optional(),thinking:_enum([`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]).optional(),fastMode:boolean().optional(),timeoutMs:number().int().positive().optional()}).optional(),backgroundMs:number().int().positive().optional(),approvalRunningNoticeMs:number().int().nonnegative().optional(),timeoutSeconds:number().int().positive().optional(),cleanupMs:number().int().positive().optional(),notifyOnExit:boolean().optional(),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({workspaceOnly:boolean().optional()}).optional();const ToolLoopDetectionSchema=strictObject({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({enabled:boolean().optional(),mode:_enum([`tools`,`directory`]).optional(),include:array(ToolSearchSelectorSchema).optional(),exclude:array(ToolSearchSelectorSchema).optional(),searchDefaultLimit:number().int().positive().optional(),maxSearchLimit:number().int().positive().optional()})]).optional();const CodeModeSchema=union([boolean(),literal(`auto`),strictObject({enabled:union([boolean(),literal(`auto`)]).optional(),executor:_enum([`node`,`quickjs`]).optional(),mode:literal(`only`).optional(),timeoutMs:number().int().positive().optional(),memoryLimitBytes:number().int().positive().optional(),maxOutputBytes:number().int().positive().optional(),maxSnapshotBytes:number().int().positive().optional(),maxPendingToolCalls:number().int().positive().optional(),snapshotTtlSeconds:number().int().positive().optional(),searchDefaultLimit:number().int().positive().optional(),maxSearchLimit:number().int().positive().optional()})]).optional();const SwarmSchema=union([boolean(),strictObject({enabled:boolean().optional(),maxConcurrent:number().int().positive().optional(),maxChildrenPerGroup:number().int().positive().optional(),maxTotalPerGroup:number().int().positive().optional(),waitTimeoutSecondsMax:number().int().positive().optional(),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={profile:ToolProfileSchema,...ToolPolicyBaseSchema.shape,byProvider:record(string(),ToolPolicyWithProfileSchema).optional(),toolsBySender:ToolPolicyBySenderSchema};const NestedToolPolicySchema=strictObject({tools:ToolPolicySchema$1}).optional();const ElevatedToolsSchema=strictObject({enabled:boolean().optional(),allowFrom:ElevatedAllowFromSchema}).optional();const OpenClawToolConfigSchema=strictObject({autoApproveChanges:boolean().optional()}).optional();const MessageToolConfigSchema=strictObject({crossContext:strictObject({allowWithinProvider:boolean().optional(),allowAcrossProviders:boolean().optional(),marker:strictObject({enabled:boolean().optional(),prefix:string().optional(),suffix:string().optional()}).optional()}).optional(),actions:strictObject({allow:array(string()).optional()}).optional(),broadcast:strictObject({enabled:boolean().optional()}).optional()}).optional();const AgentToolsSchema=strictObject({...CommonToolPolicyFields,codeMode:CodeModeSchema,swarm:SwarmSchema,elevated:ElevatedToolsSchema,exec:ToolExecSchema,openclaw:OpenClawToolConfigSchema,github:AgentGitHubToolIdentitySchema,fs:ToolFsSchema,loopDetection:ToolLoopDetectionSchema,agentToAgent:strictObject({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({allow:array(GatewayToolPolicyNameSchema),actions:record(GatewayToolPolicyNameSchema,array(GatewayToolPolicyNameSchema)).optional(),automations:strictObject({scope:literal(`caller`).optional(),allowCommandJobs:boolean().optional()}).optional()});const ToolsSchema=strictObject({...CommonToolPolicyFields,gatewayPolicy:GatewayToolPolicySchema.optional(),web:ToolsWebSchema,github:GitHubToolIdentitySchema,media:ToolsMediaSchema,links:ToolsLinksSchema,sessions:strictObject({visibility:_enum([`self`,`tree`,`agent`,`all`]).optional(),allowThreadTargets:boolean().optional()}).optional(),loopDetection:ToolLoopDetectionSchema,toolSearch:ToolSearchSchema,codeMode:CodeModeSchema,swarm:SwarmSchema,message:MessageToolConfigSchema,agentToAgent:strictObject({enabled:boolean().optional(),allow:array(string()).optional()}).optional(),elevated:ElevatedToolsSchema,exec:ToolExecSchema,openclaw:OpenClawToolConfigSchema,fs:ToolFsSchema,subagents:NestedToolPolicySchema,sandbox:NestedToolPolicySchema,sessions_spawn:strictObject({attachments:strictObject({enabled:boolean().optional(),maxTotalBytes:number().optional(),maxFiles:number().optional(),maxFileBytes:number().optional(),retainOnSessionKeep:boolean().optional()}).optional()}).optional(),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();
//!src/plugins/schema-validator.ts
const schemaCache=new LruCache(512);
//!src/channels/plugins/config-schema.ts
const AllowFromListSchema=array(union([string(),number()])).optional();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();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()}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}:{}}}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)}}}}}
//!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();
//!src/config/zod-schema.channels.ts
const ChannelHeartbeatVisibilitySchema$1=strictObject({showOk:boolean().optional(),showAlerts:boolean().optional(),useIndicator:boolean().optional()}).optional();const ChannelHealthMonitorSchema=strictObject({enabled:boolean().optional()}).optional();
//!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()});
//!src/config/zod-schema.channel-messaging-common.ts
const UnifiedStreamingModeSchema=_enum([`off`,`partial`,`block`,`progress`]);const ChannelGroupDmSchema=strictObject({enabled:boolean().optional(),groupEnabled:boolean().optional(),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`)};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();
//!src/config/zod-schema.implicit-mentions.ts
const ChannelImplicitMentionsSchema=strictObject({replyToBot:boolean().optional(),quotedBot:boolean().optional(),threadParticipation:boolean().optional()});
//!extensions/feishu/src/external-keys.ts
const FEISHU_EXTERNAL_KEY_PATTERN=/^(?!\s)(?![\s\S]*\s$)(?![\s\S]*\.\.)[^\p{Cc}\p{Cs}/\\]{1,512}$/u;
//!extensions/feishu/src/webhook-path.ts
const DEFAULT_FEISHU_WEBHOOK_PATH=`/feishu/events`;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}`}
//!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();const DynamicAgentCreationSchema=object({enabled:boolean().optional(),workspaceTemplate:string().optional(),agentDirTemplate:string().optional(),maxAgents:number().int().positive().optional()}).strict().optional();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();const GroupSessionScopeSchema=_enum([`group`,`group_sender`,`group_topic`,`group_topic_sender`]).optional();const TopicSessionModeSchema=_enum([`disabled`,`enabled`]).optional();const ReactionNotificationModeSchema=_enum([`off`,`own`,`all`]).optional();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};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`});
//!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)}}export{historicalWebhookListener,legacyConfigRules,normalizeCompatibilityConfig,normalizeHistoricalWebhookConfig};