UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

13 lines • 31.3 kB
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{f as normalizeStringEntries}from"./string-normalization-D_oBUpO3.mjs";import"./utils-Dlk0IYAa.mjs";import{t as isPlainObject}from"./plain-object-CHrMoU5Q.mjs";import{u as redactToolDetail}from"./redact-BT59pdZ_.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import"./session-key-BPgKfU2m.mjs";import{s as readAgentRosterProperty}from"./agent-roster-4XrgUgPK.mjs";import"./agent-scope-config-CG9CFpGX.mjs";import{$r as validateConfigGetParams,Qr as validateConfigApplyParams,ei as validateConfigPatchParams,ii as validateConfigSetParams,ri as validateConfigSchemaParams,ti as validateConfigSchemaLookupParams}from"./src-BDZMFmKa.mjs";import{i as getCurrentPluginMetadataSnapshot}from"./current-plugin-metadata-snapshot-CYi8VAby.mjs";import{n as formatConfigIssueLines}from"./issue-format-CeCSO2Ku.mjs";import{i as normalizeConfigPatchReplacePaths,n as formatConfigPatchPath,r as isMergePatchObjectKeyAllowed,t as collectBaseArrayPaths}from"./patch-replace-paths-BCUuHDoH.mjs";import{n as createMergePatch,t as applyMergePatch}from"./merge-patch-CKGPHlQC.mjs";import{p as resolveConfigSnapshotHash,s as parseConfigJson5}from"./io.read-helpers-B0XuPBY2.mjs";import{r as collectConfiguredModelRefs}from"./configured-model-refs-BvslYBsZ.mjs";import{i as GATEWAY_CLIENT_NAMES,r as GATEWAY_CLIENT_MODES}from"./client-info-Dr3-kuD1.mjs";import{n as normalizeSubmittedConfigModelRefs}from"./model-input-normalization-CChsFZq0.mjs";import{t as ConfigMutationConflictError}from"./mutation-conflict-qTMp0e4U.mjs";import{n as openClawIdAccessWarning}from"./access-plugin-C41HMCfK.mjs";import{q as isBuiltInModelProviderOverlayId}from"./zod-schema.core-D4C8kcop.mjs";import{t as projectRuntimeChangesOntoSource}from"./source-value-projection-CpsXB50D.mjs";import{i as validateConfigObjectWithPlugins,r as validateConfigObjectRawWithPlugins}from"./validation-CGAl0yU4.mjs";import{t as createConfigIO}from"./io.factory-y6nIrp_4.mjs";import{t as ConfigWritePostCommitError}from"./io.write-errors-CQyW8lY6.mjs";import{S as attachRuntimeConfigWriteApplication,l as readConfigFileSnapshotForWrite,w as createRuntimeConfigWriteApplication}from"./io.runtime-BvSeVFIY.mjs";import"./io-Di_yuX3t.mjs";import{a as captureGatewayRootWorkAdmissionContinuationScope}from"./gateway-work-admission-CnMW3_qr.mjs";import{g as redactSecretDegradationReason,u as isRetryableSecretDegradationReason}from"./runtime-degraded-state-DZJvpZUM.mjs";import{u as getActiveSecretsRuntimeSnapshotState}from"./runtime-state-lO6JkIdi.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{p as errorShape}from"./error-codes-CQNGhXT-.mjs";import{r as replaceConfigFile}from"./mutate-DcH8aT_4.mjs";import"./config-DkZ8y8Gv.mjs";import"./sessions-DQD7zQ95.mjs";import{t as extractDeliveryInfo}from"./delivery-info-BTs-RtuV.mjs";import{n as holdGatewayPolicyResponse}from"./ws-policy-close-piWBcH1L.mjs";import{r as SerializedJsonPayload}from"./serialized-json-DvvcynCi.mjs";import{r as resolveGatewayAuth}from"./auth-resolve-UwT9_UjV.mjs";import{d as scheduleGatewayRestart}from"./restart-B5SqvVCi.mjs";import"./auth-BwgQGI6W.mjs";import{t as resolveGatewayReloadSettings}from"./config-reload-settings-5eHwvDcn.mjs";import{t as resolveSharedGatewaySessionGeneration}from"./ws-shared-generation-BJ1DAER5.mjs";import{i as resolveConfigReloadMetadata,n as isNoopGatewayReloadPlan,o as diffConfigPaths,r as listConfigReloadRefinementPrefixes,s as diffGatewayReloadPaths,t as buildGatewayReloadPlan}from"./config-reload-plan-BiVybSc3.mjs";import{t as respondError}from"./response-BYbuAh7a.mjs";import{n as defineValidatedGatewayHandler,t as assertValidParams}from"./validation-CM41YclJ.mjs";import{s as formatDoctorNonInteractiveHint,w as writeRestartSentinel}from"./restart-sentinel-CElXdt9r.mjs";import{a as readGatewayRequestMutationAuthority}from"./session-mutation-guards-Bqnc5JYL.mjs";import{r as restoreRedactedValues,t as redactConfigObject}from"./redact-snapshot-B-h1qJ6D.mjs";import{i as lookupConfigSchema}from"./schema-BEC99qUT.mjs";import{i as loadGatewayRuntimeConfigSchema,n as invalidateGatewayRuntimeConfigSchema,r as loadGatewayConfigRedactionHints}from"./runtime-schema-Bs3owTmg.mjs";import{i as summarizeChangedPaths,r as resolveControlPlaneActor,t as formatControlPlaneActor}from"./control-plane-audit-Ds7o9s4B.mjs";import{n as parseRestartRequestParams}from"./restart-request-DS_ljYEL.mjs";import{a as prepareSecretsRuntimeSnapshot}from"./runtime-_5KWLVzx.mjs";import{n as readConfigGetResponse,t as invalidateConfigGetResponseCache}from"./config-get-response-CKOymYdp.mjs";import{t as resolveBaseHashParam}from"./base-hash-Dr6KwQMC.mjs";import{a as sanitizePathForLog,i as resolveOpenPathCommand,n as formatOpenPathError,r as isHeadlessOpenPathError,t as execOpenPath}from"./open-path-BJlg8P6I.mjs";import{isDeepStrictEqual}from"node:util"; //!src/gateway/server-methods/config-patch-intent.ts function isHashlessPatchLwwPath(e){return e===`ui.prefs`||e.startsWith(`ui.prefs.`)}function hasHashlessPatchLwwStructure(e){if(!isPlainObject(e))return false;if(!Object.hasOwn(e,`ui`))return true;const t=e.ui;return isPlainObject(t)&&(!Object.hasOwn(t,`prefs`)||isPlainObject(t.prefs))}function diffConfigLeafPaths(e,t,n=``){if(isPlainObject(e)||isPlainObject(t)){const r=isPlainObject(e)?e:{};const i=isPlainObject(t)?t:{};const a=[.../* @__PURE__ */ new Set([...Object.keys(r),...Object.keys(i)])];if(a.length===0)return isDeepStrictEqual(e,t)?[]:[n||`<root>`];return a.flatMap(e=>diffConfigLeafPaths(r[e],i[e],n?`${n}.${e}`:e))}return diffConfigPaths(e,t,n)} //!src/gateway/server-methods/config-submission-validation.ts const MAX_CONFIG_ISSUES_IN_ERROR_SUMMARY=3;function summarizeConfigValidationIssues(e){const t=e.slice(0,MAX_CONFIG_ISSUES_IN_ERROR_SUMMARY);const n=normalizeStringEntries(formatConfigIssueLines(t,``,{normalizeRoot:true}));if(n.length===0)return`invalid config`;const r=Math.max(0,e.length-n.length);return`invalid config: ${n.join(`; `)}${r>0?` (+${r} more issue${r===1?``:`s`})`:``}`}function validateSubmittedConfigOrRespond(e){const t=e.candidate;const n=normalizeSubmittedConfigModelRefs(t,e.pluginMetadataSnapshot?.owners.modelIdNormalizationPolicies);const respondInvalid=t=>{e.respond(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,summarizeConfigValidationIssues(t),{details:{issues:t}}))};const r={pluginMetadataSnapshot:e.pluginMetadataSnapshot};const i=validateConfigObjectRawWithPlugins(n,r);if(!i.ok){respondInvalid(i.issues);return null}const a=validateConfigObjectWithPlugins(n,r);if(!a.ok){respondInvalid(a.issues);return null}return{validationCandidate:n,config:a.config}} //!src/gateway/server-methods/config-write-reply.ts function replyWithBillingRouteWarnings(e,t,n,r){return(...i)=>{const[a,o]=i;if(a&&t.length>0&&isRecord(o)){for(const e of t)n?.logGateway?.warn(e);i[1]={...o,billingRouteWarnings:t}}if(a&&r&&isRecord(i[1]))i[1]={...i[1],warnings:[r]};e?.(...i)}} //!src/gateway/server-methods/config-write-flow.ts function resolveGatewayConfigPath(e){return e?.path??createConfigIO().configPath}function didSharedGatewayAuthChange(e,t){const n=resolveGatewayAuth({authConfig:e.gateway?.auth,env:process.env,tailscaleMode:e.gateway?.tailscale?.mode});const r=resolveGatewayAuth({authConfig:t.gateway?.auth,env:process.env,tailscaleMode:t.gateway?.tailscale?.mode});return n.mode!==r.mode||n.mode!==`trusted-proxy`&&resolveSharedGatewaySessionGeneration(n,e.gateway?.trustedProxies)!==resolveSharedGatewaySessionGeneration(r,t.gateway?.trustedProxies)}function projectAuthoredValuesOntoRuntimeOverlay(e){const{source:t,active:n}=e;if(n===void 0)return structuredClone(e.fallback);if(!isRecord(t)||!isRecord(n))return structuredClone(isDeepStrictEqual(t,e.activeSource)?n:e.fallback);const r=isRecord(e.fallback)?e.fallback:{};const i=isRecord(e.activeSource)?e.activeSource:{};const a=new Set(Object.keys(t));return Object.fromEntries([...Object.entries(r).filter(([e])=>!a.has(e)),...Object.keys(t).map(e=>[e,projectAuthoredValuesOntoRuntimeOverlay({source:t[e],activeSource:i[e],active:n[e],fallback:r[e]})])])}function didActiveSharedGatewayAuthChange(e){const t=getActiveSecretsRuntimeSnapshotState();if(!t)return didSharedGatewayAuthChange(e.fallbackPrev,e.next);const n=(e.fallbackSource??t.sourceConfig).gateway;const r=t.sourceConfig.gateway;const i=t.config.gateway;const a=e.fallbackPrev.gateway;const selectOwnedGatewayValue=e=>n&&Object.hasOwn(n,e)?projectAuthoredValuesOntoRuntimeOverlay({source:n[e],activeSource:r?.[e],active:i?.[e],fallback:a?.[e]}):a?.[e];return didSharedGatewayAuthChange({...e.fallbackPrev,gateway:{...a,auth:selectOwnedGatewayValue(`auth`),tailscale:selectOwnedGatewayValue(`tailscale`),trustedProxies:selectOwnedGatewayValue(`trustedProxies`)}},e.next)}function resolveConfigRestartRequirement(e){const t=resolveGatewayReloadSettings(e.nextConfig);const n=buildGatewayReloadPlan(e.changedPaths,{previousConfig:e.previousConfig,candidateConfig:e.nextConfig});const r=!isNoopGatewayReloadPlan(n)&&(t.mode===`off`||n.restartGateway);return{requiresRestart:r,scheduleDirectRestart:r&&t.mode===`off`&&!e.deferRestartWhenReloadOff}}function isCliRoutedConfigPatch(e,t){const n=t?.connect?.client;return e===`config.patch`&&n?.id===GATEWAY_CLIENT_NAMES.CLI&&n.mode===GATEWAY_CLIENT_MODES.CLI}function respondConfigWriteApplicationOutcome(e){const{outcome:t,mode:n}=e;if(t===`applied`)return false;if(t===`restart-pending`&&isCliRoutedConfigPatch(n,e.client)){e.respond(true,{...e.success,restartPending:true},void 0);return true}const r=typeof t===`object`?{...t,reason:redactToolDetail(t.reason),appliesWhen:redactToolDetail(t.appliesWhen)}:void 0;const i=typeof t===`object`?t.status:t;const a=r?`${n} saved but deferred: ${r.reason} ${r.appliesWhen}`:t===`applied-restart-required`?`${n} persisted and updated the active Gateway, but a recovery restart is required; wait for the Gateway to restart, then run config.get to confirm the active revision`:t===`restart-pending`?`${n} persisted and was accepted for restart; wait for the Gateway to restart, then run config.get to confirm the active revision`:`${n} persisted but was not applied to the active Gateway (${i}); run config.get, then use config.apply to reapply the saved config or restart the Gateway`;e.respond(false,void 0,errorShape(ErrorCodes.UNAVAILABLE,a,{details:{persistedConfig:e.persistedConfig,...r?{application:r}:{}}}));return true}function shouldAwaitGatewayConfigApplication(e){return resolveGatewayReloadSettings(e.nextConfig).mode!==`off`&&!resolveConfigRestartRequirement({...e,changedPaths:e.changedPaths??diffGatewayReloadPaths(e.previousConfig,e.nextConfig,listConfigReloadRefinementPrefixes())}).requiresRestart}const pickModelRouteKeys=e=>[e?.model,e?.models,e?.subagents,e?.heartbeat];function billingRouteInputs(e){return{models:e.models,auth:e.auth,requiredProfile:e.cloudWorkers?.requiredProfile,defaults:pickModelRouteKeys(e.agents?.defaults),entries:Object.entries(e.agents?.entries??{}).map(([e,t])=>[e,pickModelRouteKeys(t)]),refs:collectConfiguredModelRefs(e)}}async function collectConfigWriteBillingRouteWarnings(e){const t=e.before??{};const{after:n}=e;try{if(isDeepStrictEqual(billingRouteInputs(t),billingRouteInputs(n)))return[];const{collectModelBillingRouteMigrationWarnings:e}=await import(`./model-billing-route-migration-DVl4YIDw.mjs`);return await e({before:t,after:n,metadataSnapshot:getCurrentPluginMetadataSnapshot({config:n})})}catch(t){e.context?.logGateway?.warn(`billing route comparison skipped: ${String(t)}`);return[]}}async function commitGatewayConfigWrite(e){const t=e.context?.getCommittedRuntimeConfig?.()??e.snapshot.config;const n=e.awaitRuntimeApplication?createRuntimeConfigWriteApplication(captureGatewayRootWorkAdmissionContinuationScope()?.run):void 0;holdGatewayPolicyResponse(e.respond);const r=await replaceConfigFile({sourceConfig:e.nextConfig,baseHash:resolveConfigSnapshotHash(e.snapshot)??void 0,writeOptions:attachRuntimeConfigWriteApplication({...e.writeOptions,auditOrigin:`config-rpc`,runtimeRefresh:{...e.writeOptions.runtimeRefresh,includeAuthStoreRefs:false}},n),afterWrite:{mode:`auto`}});const i=await collectConfigWriteBillingRouteWarnings({before:e.snapshot.sourceConfig,after:e.nextConfig,context:e.context});return{path:resolveGatewayConfigPath(e.snapshot),config:r.nextConfig,...i.length>0?{billingRouteWarnings:i}:{},reply:replyWithBillingRouteWarnings(e.respond,i,e.context,openClawIdAccessWarning(r.nextConfig)),hash:r.persistedHash,...n?{application:n.claimed?n.result:Promise.resolve(`unclaimed`)}:{},queueFollowUp:()=>{if(!n?.claimed)queueMicrotask(()=>{e.context?.enforceSharedGatewayAuthGenerationForConfigWrite?.(r.nextConfig,t);if(e.disconnectSharedAuthClients)e.context?.disconnectClientsUsingSharedGatewayAuth?.()})}}}async function finishGatewayConfigWrite(e){const{write:t}=e;invalidateGatewayRuntimeConfigSchema();const n={...t.hash?{hash:e.context.configRevisionProjector.projectRawHash(t.hash)}:{},config:redactConfigObject(t.config,e.uiHints)};if(!t.application||!respondConfigWriteApplicationOutcome({outcome:await t.application,mode:`config.set`,client:e.client,respond:t.reply,success:{},persistedConfig:n}))t.reply(true,{ok:true,path:t.path,...n,...e.successDetails},void 0);t.queueFollowUp()}async function resolveGatewayConfigRestartWriteResult(e){const{sessionKey:t,note:n,restartDelayMs:r,deliveryContext:i,threadId:a}=parseRestartRequestParams(e.requestParams);const o=await extractDeliveryInfo(t);const s=resolveControlPlaneActor(e.client);const c=resolveConfigRestartRequirement({...e,deferRestartWhenReloadOff:isCliRoutedConfigPatch(e.mode,e.client)});const l={kind:e.kind,status:`ok`,ts:Date.now(),sessionKey:t,deliveryContext:i??o.deliveryContext,threadId:a??o.threadId,message:n??null,doctorHint:formatDoctorNonInteractiveHint(),stats:{mode:e.mode,root:e.configPath,requiresRestart:c.requiresRestart}};const u=await writeRestartSentinel(l).then(()=>true,()=>false);const d=c.scheduleDirectRestart?scheduleGatewayRestart({delayMs:r,reason:e.mode,audit:{actor:s.actor,deviceId:s.deviceId,clientIp:s.clientIp,changedPaths:e.changedPaths}}):void 0;if(d?.coalesced)e.context?.logGateway?.warn(`${e.mode} restart coalesced ${formatControlPlaneActor(s)} delayMs=${d.delayMs}`);return{payload:l,sentinelPersisted:u,restart:d}} //!src/gateway/server-methods/config-write-snapshot.ts function requireConfigBaseHash(e,t,n,r){if(!t.exists)return true;const i=resolveConfigSnapshotHash(t);const a=resolveBaseHashParam(e);if(!i||!a){respondError(n,ErrorCodes.INVALID_REQUEST,`config base hash ${i?`required`:`unavailable`}; re-run config.get and retry`);return false}if(a!==r.projectRawHash(i)){invalidateConfigGetResponseCache();respondError(n,ErrorCodes.INVALID_REQUEST,`config changed since last load; re-run config.get and retry`);return false}return true}async function readConfigWriteSnapshotOrRespond(e,t,n){const r=await readConfigFileSnapshotForWrite();if(!requireConfigBaseHash(e,r.snapshot,t,n))return null;return r} //!src/gateway/server-methods/config.ts const configWriteRecovery=/* @__PURE__ */ new WeakMap;const serializedConfigReads=/* @__PURE__ */ new WeakMap;function configReadPayload(e,t){if(!t)return e;let n=serializedConfigReads.get(e);if(!n){n=new SerializedJsonPayload(e);serializedConfigReads.set(e,n)}return n}function collectDestructiveArrayPatchPaths(e){if(!isPlainObject(e.patch)||!isPlainObject(e.base))return[];const t=isPlainObject(e.merged)?e.merged:{};const n=[];for(const[r,i]of Object.entries(e.patch)){const a=formatConfigPatchPath(e.path??``,r);if(!isMergePatchObjectKeyAllowed(r,e.path))continue;const o=e.base[r];const s=t[r];if(Array.isArray(o)){if(i===null||!Array.isArray(i)){n.push(a);continue}if(Array.isArray(s)){if(isConfigPatchIdKeyedArray(o)){if(!idKeyedArrayPreservesBaseIds(o,s)){n.push(a);continue}n.push(...collectDestructiveIdKeyedArrayEntryPatchPaths({base:o,patch:i,merged:s,path:a}))}else if(!arrayPreservesBaseEntries(o,s)){n.push(a);continue}}}else if(isPlainObject(o)&&!isPlainObject(i)){n.push(...collectBaseArrayPaths(o,a));continue}if(isPlainObject(i))n.push(...collectDestructiveArrayPatchPaths({base:o,patch:i,merged:s,path:a}))}return n}function isConfigPatchObjectWithStringId(e){return isPlainObject(e)&&typeof e.id===`string`&&e.id.length>0}function assertNoDuplicateConfigPatchIds(e){const t=e.path??``;if(Array.isArray(e.patch)){if(!Array.isArray(e.current)||e.replacePaths.has(t)||!isConfigPatchIdKeyedArray(e.current))return;const n=/* @__PURE__ */ new Set;for(const r of e.current){if(n.has(r.id))throw new Error(`Cannot ID-merge array at ${t||`<root>`}: current config contains duplicate ID ${r.id}; use replacePaths for an explicit replacement.`);n.add(r.id)}const r=/* @__PURE__ */ new Set;for(const n of e.patch){if(!isConfigPatchObjectWithStringId(n))continue;if(r.has(n.id))throw new Error(`Ambiguous duplicate ID ${n.id} in array at ${t||`<root>`}.`);r.add(n.id)}const i=new Map(e.current.map(e=>[e.id,e]));for(const n of e.patch){if(!isConfigPatchObjectWithStringId(n))continue;const r=i.get(n.id);if(r)assertNoDuplicateConfigPatchIds({patch:n,current:r,replacePaths:e.replacePaths,path:`${t}[]`})}return}if(!isRecord(e.patch)||!isRecord(e.current))return;for(const[n,r]of Object.entries(e.patch))assertNoDuplicateConfigPatchIds({patch:r,current:e.current[n],replacePaths:e.replacePaths,path:formatConfigPatchPath(t,n)})}function isConfigPatchIdKeyedArray(e){return e.every(isConfigPatchObjectWithStringId)}function idKeyedArrayPreservesBaseIds(e,t){const n=new Set(t.filter(isConfigPatchObjectWithStringId).map(e=>e.id));return e.every(e=>n.has(e.id))}function arrayPreservesBaseEntries(e,t){const n=[...t];for(const t of e){const e=n.findIndex(e=>isDeepStrictEqual(e,t));if(e===-1)return false;n.splice(e,1)}return true}function collectDestructiveIdKeyedArrayEntryPatchPaths(e){const t=new Map(e.base.map(e=>[e.id,e]));const n=new Map(e.merged.filter(isConfigPatchObjectWithStringId).map(e=>[e.id,e]));const r=[];for(const i of e.patch){if(!isConfigPatchObjectWithStringId(i))continue;const a=t.get(i.id);const o=n.get(i.id);if(!a||!o)continue;r.push(...collectDestructiveArrayPatchPaths({base:a,patch:i,merged:o,path:`${e.path}[]`}))}return r}function rejectDestructiveArrayPatchWithoutIntent(e){const t=collectDestructiveArrayPatchPaths({base:e.currentConfig,patch:e.patch,merged:e.mergedConfig}).filter(t=>!e.replacePaths.has(t));if(t.length===0)return false;respondError(e.respond,ErrorCodes.INVALID_REQUEST,`config.patch would remove entries from array path(s): ${t.join(`, `)}. Pass replacePaths with the exact path(s) when this is intentional, or use config.apply for full-config replacement.`);return true}function hasOwnRecordValue(e,t){return isRecord(e)&&Object.hasOwn(e,t)}function stripBundledProviderRuntimeDefaults(e){if(!isRecord(e.candidate))return e.candidate;const t=e.candidate.models;if(!isRecord(t)||!isRecord(t.providers))return e.candidate;const n=isRecord(e.sourceConfig)?e.sourceConfig.models:void 0;const r=isRecord(n)?n.providers:void 0;let i;for(const[e,n]of Object.entries(t.providers)){if(!isBuiltInModelProviderOverlayId(e)||!isRecord(n))continue;const a=isRecord(r)?r[e]:void 0;let o;if(n.baseUrl===``&&!hasOwnRecordValue(a,`baseUrl`)){o={...n};delete o.baseUrl}if(Array.isArray(n.models)&&n.models.length===0&&!hasOwnRecordValue(a,`models`)){o??={...n};delete o.models}if(o){i??={...t.providers};i[e]=o}}if(!i)return e.candidate;return{...e.candidate,models:{...t,providers:i}}}async function prepareConfigReplacementOrRespond(e,t,n){const r=await readConfigWriteSnapshotOrRespond(e,t,n);if(!r)return null;const{snapshot:i,writeOptions:a}=r;const o=parseConfigJson5(e.raw);if(!o.ok){respondError(t,ErrorCodes.INVALID_REQUEST,o.error);return null}const s=loadGatewayConfigRedactionHints();const c=restoreRedactedValues(o.parsed,i.config,s);if(!c.ok){respondError(t,ErrorCodes.INVALID_REQUEST,c.humanReadableMessage??`invalid config`);return null}const l=i.valid?projectRuntimeChangesOntoSource(i.resolved,i.config,c.result):c.result;const u=validateSubmittedConfigOrRespond({candidate:stripBundledProviderRuntimeDefaults({candidate:l,sourceConfig:i.sourceConfig}),pluginMetadataSnapshot:a.basePluginMetadataSnapshot,respond:t});if(!u)return null;return{writeSnapshot:r,config:u.config,writeConfig:u.validationCandidate,uiHints:s}}function listExplicitAgentRosterIds(e){const t=readAgentRosterProperty(e);if(t?.kind===`entries`&&isRecord(t.value))return Object.keys(t.value);if(t?.kind!==`list`||!Array.isArray(t.value))return[];return t.value.flatMap(e=>isRecord(e)&&typeof e.id===`string`?[e.id]:[])}function rejectDroppedAgentRosterEntries(e){const t=new Set(listExplicitAgentRosterIds(e.submittedConfig).map(e=>normalizeAgentId(e)));const n=listExplicitAgentRosterIds(e.currentConfig).filter(e=>!t.has(normalizeAgentId(e))).toSorted();if(n.length===0)return false;respondError(e.respond,ErrorCodes.INVALID_REQUEST,`config.set would remove existing agent entries: ${n.join(`, `)}. Use the agents.delete RPC or \`openclaw agents delete <id>\` for intentional deletion.`);return true}async function ensureResolvableSecretRefsOrRespond(e){try{const t=await prepareSecretsRuntimeSnapshot({config:e.config,includeAuthStoreRefs:false,allowUnavailableSecretOwners:true});for(const e of t.degradedOwners??[]){const t=redactSecretDegradationReason(e.reason);if(!isRetryableSecretDegradationReason(t))throw new Error(t)}return t}catch(t){const n=formatErrorMessage(t);e.respond(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,`invalid config: active SecretRef resolution failed (${n})`));return null}}function preparedSecretDegradationPayload(e){const t=(e.degradedOwners??[]).map(e=>({ownerKind:e.ownerKind,ownerId:e.ownerId,state:e.degradationState??`cold`,paths:[...e.paths],reason:redactSecretDegradationReason(e.reason)}));return t.length>0?{degradedSecretOwners:t}:{}}async function commitConfigRestartWrite(e){const{snapshot:t,writeOptions:n}=e.writeSnapshot;const r=diffGatewayReloadPaths(t.config,e.nextConfig,listConfigReloadRefinementPrefixes());e.context?.logGateway?.info(`${e.mode} write ${formatControlPlaneActor(resolveControlPlaneActor(e.client))} changedPaths=${summarizeChangedPaths(r)} restartReason=${e.mode}`);const i=didSharedGatewayAuthChange(t.config,e.nextConfig)||didActiveSharedGatewayAuthChange({fallbackPrev:t.config,fallbackSource:t.sourceConfig,next:e.preparedSecretsSnapshot.config});const a=await commitGatewayConfigWriteOrRespond({snapshot:t,writeOptions:n,nextConfig:e.writeConfig,context:e.context,disconnectSharedAuthClients:i,awaitRuntimeApplication:shouldAwaitGatewayConfigApplication({changedPaths:r,previousConfig:t.config,nextConfig:e.nextConfig}),respond:e.respond});if(!a)return;const o={...a.hash?{hash:e.context.configRevisionProjector.projectRawHash(a.hash)}:{},...!e.summary?{config:redactConfigObject(a.config,e.uiHints)}:{}};if(a.application&&respondConfigWriteApplicationOutcome({outcome:await a.application,mode:e.mode,client:e.client,respond:a.reply,success:{ok:true,path:a.path,...o,changedPaths:r},persistedConfig:o})){a.queueFollowUp();return}const s=isNoopGatewayReloadPlan(buildGatewayReloadPlan(r,{previousConfig:t.config,candidateConfig:e.nextConfig}));if(!s)invalidateGatewayRuntimeConfigSchema();if(e.summary&&s){a.reply(true,{ok:true,path:a.path,...o,changedPaths:r});a.queueFollowUp();return}const{payload:c,sentinelPersisted:l,restart:u}=await resolveGatewayConfigRestartWriteResult({requestParams:e.requestParams,kind:e.mode===`config.patch`?`config-patch`:`config-apply`,mode:e.mode,configPath:a.path,changedPaths:r,previousConfig:t.config,nextConfig:e.nextConfig,client:e.client,context:e.context});a.reply(true,{ok:true,path:a.path,...o,...e.mode===`config.patch`?{changedPaths:r}:{},...preparedSecretDegradationPayload(e.preparedSecretsSnapshot),restart:u,sentinel:{persisted:l,payload:c}},void 0);a.queueFollowUp()}async function commitGatewayConfigWriteOrRespond(e){const t=e.context.configRevisionProjector;const n=configWriteRecovery.get(t);try{const r=await commitGatewayConfigWrite(e);if(configWriteRecovery.get(t)===n)configWriteRecovery.delete(t);return r}catch(n){if(n instanceof ConfigWritePostCommitError){const r=errorShape(ErrorCodes.UNAVAILABLE,redactToolDetail(formatErrorMessage(n)),{details:{publication:n.publication,rollbackStatus:n.rollbackStatus,configPath:n.configPath,...n.recoveryBackupPath!==void 0?{recoveryBackupPath:n.recoveryBackupPath}:{}}});if(n.rollbackStatus!==`restored`){configWriteRecovery.set(t,{configPath:n.configPath,error:r});invalidateConfigGetResponseCache()}e.respond(false,void 0,r);return null}if(!(n instanceof ConfigMutationConflictError))throw n;if(n.retryable)invalidateConfigGetResponseCache();e.respond(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,n.retryable?`${n.message}; re-run config.get and retry`:n.message));return null}}const configHandlers={"config.get":async({params:e,respond:t,context:n,acceptsSerializedJson:r})=>{if(!assertValidParams(e,validateConfigGetParams,`config.get`,t))return;const i=n.configRevisionProjector;const a=configWriteRecovery.get(i);const o=await readConfigGetResponse({getHotReloadStatus:n.getConfigReloaderHotReloadStatus,revisionProjector:n.configRevisionProjector});const s=configWriteRecovery.get(i);if(s?.configPath===o.path){if(s===a&&o.exists&&o.valid)configWriteRecovery.delete(i);else{t(true,{...o,writeError:s.error},void 0);return}}t(true,configReadPayload(o,r),void 0)},"config.schema":({params:e,respond:t,acceptsSerializedJson:n})=>{if(!assertValidParams(e,validateConfigSchemaParams,`config.schema`,t))return;t(true,configReadPayload(loadGatewayRuntimeConfigSchema(),n),void 0)},"config.schema.lookup":defineValidatedGatewayHandler(`config.schema.lookup`,validateConfigSchemaLookupParams,({params:e,respond:t})=>{const{path:n}=e;const r=loadGatewayRuntimeConfigSchema();const i=lookupConfigSchema(r,n,resolveConfigReloadMetadata);if(!i){respondError(t,ErrorCodes.INVALID_REQUEST,`config schema path not found`);return}t(true,i,void 0)}),"config.set":async({params:e,respond:t,context:n,client:r})=>{if(!assertValidParams(e,validateConfigSetParams,`config.set`,t))return;const i=await prepareConfigReplacementOrRespond(e,t,n.configRevisionProjector);if(!i)return;const{snapshot:a,writeOptions:o}=i.writeSnapshot;if(rejectDroppedAgentRosterEntries({currentConfig:a.config,submittedConfig:i.config,respond:t}))return;const s=await ensureResolvableSecretRefsOrRespond({config:i.config,respond:t});if(!s)return;const c=await commitGatewayConfigWriteOrRespond({snapshot:a,writeOptions:o,nextConfig:i.writeConfig,context:n,respond:t,awaitRuntimeApplication:shouldAwaitGatewayConfigApplication({previousConfig:a.config,nextConfig:i.config})});if(!c)return;await finishGatewayConfigWrite({write:c,context:n,client:r,uiHints:i.uiHints,successDetails:preparedSecretDegradationPayload(s)})},"config.patch":async e=>{const{params:t,respond:n,client:r,context:i}=e;const a=readGatewayRequestMutationAuthority(e);if(!assertValidParams(t,validateConfigPatchParams,`config.patch`,n))return;const o=resolveBaseHashParam(t)===null;const s=o?await readConfigFileSnapshotForWrite():await readConfigWriteSnapshotOrRespond(t,n,i.configRevisionProjector);if(!s)return;const{snapshot:c,writeOptions:l}=s;const u=l.basePluginMetadataSnapshot?.owners.modelIdNormalizationPolicies;if(!c.valid){n(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,`${summarizeConfigValidationIssues(c.issues)}; fix (openclaw doctor) before patching`,{details:{issues:c.issues}}));return}const d=parseConfigJson5(t.raw);if(!d.ok){respondError(n,ErrorCodes.INVALID_REQUEST,d.error);return}if(!isRecord(d.parsed)){respondError(n,ErrorCodes.INVALID_REQUEST,`config.patch raw must be an object`);return}const f=normalizeSubmittedConfigModelRefs(d.parsed,u);if(o&&!hasHashlessPatchLwwStructure(f)){respondError(n,ErrorCodes.INVALID_REQUEST,`config base hash required; re-run config.get and retry`);return}const p=normalizeConfigPatchReplacePaths(t.replacePaths);try{assertNoDuplicateConfigPatchIds({patch:f,current:c.config,replacePaths:p})}catch(e){n(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,formatErrorMessage(e)));return}const m=normalizeSubmittedConfigModelRefs(c.sourceConfig,u);const h=applyMergePatch(m,f,{mergeObjectArraysById:true,replaceArrayPaths:p});const g=loadGatewayConfigRedactionHints();const _=restoreRedactedValues(h,c.config,g);if(!_.ok){respondError(n,ErrorCodes.INVALID_REQUEST,_.humanReadableMessage??`invalid config`);return}if(rejectDestructiveArrayPatchWithoutIntent({currentConfig:c.config,mergedConfig:applyMergePatch(c.config,createMergePatch(m,_.result)),patch:f,replacePaths:p,respond:n}))return;const v=diffConfigLeafPaths(m,_.result);if(o&&!v.every(isHashlessPatchLwwPath)){const e=v.filter(e=>!isHashlessPatchLwwPath(e));respondError(n,ErrorCodes.INVALID_REQUEST,`config base hash required for ${e.join(`, `)}; re-run config.get and retry with baseHash`);return}const y=resolveControlPlaneActor(r);if(v.length===0){i?.logGateway?.info(`config.patch noop ${formatControlPlaneActor(y)} (no changed paths)`);n(true,{ok:true,noop:true,changedPaths:[],path:resolveGatewayConfigPath(c),...t.response!==`summary`?{config:redactConfigObject(c.config,g)}:{}},void 0);return}const b=validateSubmittedConfigOrRespond({candidate:_.result,pluginMetadataSnapshot:l.basePluginMetadataSnapshot,respond:n});if(!b)return;const x=b.validationCandidate;const S=b.config;const C=await ensureResolvableSecretRefsOrRespond({config:S,respond:n});if(!C)return;const w=[];const T=m.agents?.entries;const E=f.agents?.entries;if(!o&&T&&E){for(const[e,t]of Object.entries(E))if(t===null&&Object.hasOwn(T,e))w.push(e)}await commitConfigRestartWrite({requestParams:t,mode:`config.patch`,writeSnapshot:{...s,writeOptions:{...l,allowedAgentRosterRemovals:w,assertBeforePublish:()=>{l.assertBeforePublish?.();a.assertCurrent()}}},writeConfig:x,nextConfig:S,client:r,context:i,respond:n,uiHints:g,preparedSecretsSnapshot:C,summary:t.response===`summary`})},"config.apply":async({params:e,respond:t,client:n,context:r})=>{if(!assertValidParams(e,validateConfigApplyParams,`config.apply`,t))return;const i=await prepareConfigReplacementOrRespond(e,t,r.configRevisionProjector);if(!i)return;const a=await ensureResolvableSecretRefsOrRespond({config:i.config,respond:t});if(!a)return;await commitConfigRestartWrite({requestParams:e,mode:`config.apply`,writeSnapshot:i.writeSnapshot,writeConfig:i.writeConfig,nextConfig:i.config,client:n,context:r,respond:t,uiHints:i.uiHints,preparedSecretsSnapshot:a})},"config.openFile":async({params:e,respond:t,context:n})=>{if(!assertValidParams(e,validateConfigGetParams,`config.openFile`,t))return;const r=createConfigIO().configPath;const i=resolveOpenPathCommand(r);try{await execOpenPath(i);t(true,{ok:true,path:r},void 0)}catch(e){const a=formatOpenPathError(e);const o=isHeadlessOpenPathError(e,i)?`Cannot open file in headless environment. File path: ${r}. This environment appears to lack a graphical or terminal browser handler.`:`Failed to open config file: ${a}`;n?.logGateway?.warn(`config.openFile failed path=${sanitizePathForLog(r)}: ${a}`);t(true,{ok:false,path:r,error:o},void 0)}}};export{configHandlers};