UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

20 lines • 19.2 kB
import{_ as resolvePrimaryStringValue}from"./string-coerce-CpTFcSwY.mjs";import{i as asOptionalObjectRecord,l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{c as getAuthoredConfigSecretRef,d as hasUnresolvedConfigPath,n as cloneConfigWithResolutionFacts}from"./resolution-facts-DYKtoyes.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import"./utils-Dlk0IYAa.mjs";import{i as INCLUDE_KEY}from"./includes-gwK90iIZ.mjs";import{t as CONFIG_PATH}from"./paths-D_FOvGon.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{n as listAgentEntries,r as listAgentEntriesWithSource,s as readAgentRosterProperty}from"./agent-roster-4XrgUgPK.mjs";import{A as tryResolveLegacyCompatibilityAgentId}from"./agent-scope-config-CG9CFpGX.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{n as formatConfigIssueLines}from"./issue-format-CeCSO2Ku.mjs";import{n as createMergePatch}from"./merge-patch-CKGPHlQC.mjs";import{t as coerceConfig}from"./io.read-helpers-B0XuPBY2.mjs";import{r as collectConfiguredModelRefs}from"./configured-model-refs-BvslYBsZ.mjs";import{c as setDeferredPluginMigrationConfigFacts,n as getDeferredPluginMigrationConfigFacts}from"./deferred-plugin-migration-config-D1j_2i5D.mjs";import{t as inheritLegacyDefaultAgentId}from"./legacy.default-agent-owner-DUgZJ5NH.mjs";import{t as OpenClawSchema}from"./zod-schema-BZ5x0MkX.mjs";import{t as planEffectiveModelCatalogRows}from"./model-catalog-BG6rYCD1.mjs";import{s as loadManifestMetadataSnapshot}from"./manifest-contract-eligibility-BFn2JM5T.mjs";import{r as validateConfigObjectRawWithPlugins}from"./validation-CGAl0yU4.mjs";import{t as logConfigWarningsOnce}from"./io.warnings-Dshur5lA.mjs";import{r as restoreEnvVarRefsFromResolved}from"./env-preserve-aj205DNy.mjs";import{r as projectAuthoredAgentRosterForWrite}from"./io.write-prepare-B9fpYBu2.mjs";import"./config-DkZ8y8Gv.mjs";import{h as resolvePluginDoctorProviderRenames}from"./doctor-contract-registry-DTv7VdR4.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import{a as migratePluginConfigId}from"./update-config-wZZTYV_h.mjs";import{n as protectActiveAuthProfileConfig}from"./doctor-auth-profile-config-CWPdp-6v.mjs";import{t as resolveCliModelEntry}from"./resolve-WTRz3hbx.mjs";import{r as sanitizeDoctorNote}from"./emit-notes-DCY5wFZF.mjs";import{t as createDoctorModelRefResolver}from"./model-reference-resolver-BGZiYjtD.mjs";import{t as applyDoctorConfigMutation}from"./config-mutation-state-Cwwz-hgQ.mjs";import{n as containsAuthoredInclude,t as classifyOtelGrpcMigrationOwnership}from"./include-migration-ownership-KASn2yVx.mjs";import{t as applyLegacyDoctorMigrations}from"./legacy-config-compat-BG3tvxTV.mjs";import{n as planProviderRenames,t as applyProviderRenames}from"./provider-rename-PnqDJPfZ.mjs";import path from"node:path";import{isDeepStrictEqual}from"node:util"; //!src/commands/doctor-config-analysis.ts const configLog=createSubsystemLogger(`config`);function noteMediaCliModelWarnings(e){const t=e.tools?.media?.models;if(!Array.isArray(t))return;const n=[];t.forEach((e,t)=>{if(!e||(e.type??(e.command?`cli`:`provider`))!==`cli`)return;const r=resolveCliModelEntry(e);if(!r.ok){const e=r.error.reason===`cli-missing-command`?`command`:`args`;n.push(`- tools.media.models[${t}].${e}: Invalid CLI media model. ${r.error.message} Doctor cannot choose a command or attachment arguments; edit this entry.`)}});if(n.length>0)note(n.join(` `),`Doctor warnings`)}function noteDoctorConfigPreflightIssues(e,t){const n=t.invalidConfigNote??`Config invalid; doctor will run with best-effort config.`;if(n&&e.exists&&!e.valid&&!t.activeRepair&&e.legacyIssues.length===0){note(n,`Config`);noteIncludeConfinementWarning(e)}const r=e.warnings??[];if(r.length>0){if(process.stdout.isTTY)note(formatConfigIssueLines(r,`-`).join(` `),`Config warnings`);else logConfigWarningsOnce({configPath:e.path,warnings:r,logger:configLog})}}function collectInvalidHookTransformsDirWarnings(e,t){const n=e.hooks?.transformsDir?.trim();if(!n)return[];const r=path.dirname(t);const i=path.join(r,`hooks`,`transforms`);const a=path.isAbsolute(n)?path.resolve(n):path.resolve(i,n);if(isPathInside(i,a))return[];return[`- hooks.transformsDir: ${n} is outside ${i}. Hook transform modules must live under ${i}; move custom transforms there or remove hooks.transformsDir.`]}function collectUnsupportedInternalHookEntryWarnings(e){return Object.entries(e.hooks?.internal?.entries??{}).flatMap(([e,t])=>{if(!isRecord(t))return[];const n=[`handler`,`module`,`extraDirs`,`installs`].filter(e=>Object.hasOwn(t,e));return n.length>0?[`- hooks.internal.entries.${e}: unsupported loader key${n.length===1?``:`s`} ${n.join(`, `)} will not load hook modules. Use bootstrap-extra-files for session bootstrap content, or create a managed/workspace hook directory with HOOK.md + handler.js. Doctor cannot rewrite this automatically because per-hook entry keys are open-ended hook configuration.`]:[]})}function noteDoctorHookConfigWarnings(e,t){if(e.hooks?.enabled===true&&(hasUnresolvedConfigPath(e,`hooks.token`)||getAuthoredConfigSecretRef(e,`hooks.token`)))note([`hooks.token has an unresolved environment reference in the current Doctor environment.`,`External HTTP hooks are disabled on Gateway startup if its environment cannot resolve the secret; an invalid hot reload keeps the previous valid hooks configuration.`,`Supply the configured secret to the Gateway service environment, then reload or restart. The CLI and service environments may differ.`,`To leave hooks disabled explicitly, run ${formatCliCommand(`openclaw config set hooks.enabled false`)}.`,`Doctor does not generate a replacement secret or overwrite the configured reference.`].join(` `),`Doctor warnings`);for(const n of[collectInvalidHookTransformsDirWarnings(e,t),collectUnsupportedInternalHookEntryWarnings(e)])if(n.length>0)note(sanitizeDoctorNote(n.join(` `)),`Doctor warnings`)}function noteMissingDefaultAgentOwner(e){if(e.agents?.ownership===`explicit`&&listAgentEntries(e).length>1&&!tryResolveLegacyCompatibilityAgentId(e))note(`No default agent is designated. Set a configured agent with "${formatCliCommand(`openclaw config set agents.defaults.systemAgent.agentId <id>`)}".`,`Agent ownership`)}function formatConfigKeyPath(e){let t=``;for(const n of e){if(typeof n===`number`){t+=`[${n}]`;continue}t=t?`${t}.${n}`:n}return t||`<root>`}function resolveConfigPathTarget(e,t){let n=e;for(const e of t){if(typeof e===`number`){if(!Array.isArray(n)||e<0||e>=n.length)return null;n=n[e];continue}if(!isRecord(n)||!(e in n))return null;n=n[e]}return n}function stripUnknownConfigKeys(e,t=[]){const n=OpenClawSchema.safeParse(e);if(n.success)return{config:e,removed:[]};const r=structuredClone(e);const i=[];for(const e of n.error.issues){if(e.code!==`unrecognized_keys`)continue;const n=e.path.filter(e=>typeof e!==`symbol`);const a=resolveConfigPathTarget(r,n);if(!isRecord(a))continue;for(const r of e.keys){if(!(r in a))continue;if(r===`$include`)continue;const e=[...n,r].map(String);if(r===`heartbeat`&&n[0]===`agents`||r===`heartbeatVisibility`&&n[0]===`channels`||t.some(t=>t.slice(0,e.length).every((t,n)=>e[n]===t)))continue;delete a[r];i.push(formatConfigKeyPath([...n,r]))}}return{config:r,removed:i}}async function noteConfigAdvisories(e,t){const n=[e.models?.providers?.opencode||e.models?.providers?.[`opencode-zen`]?`opencode`:void 0,e.models?.providers?.[`opencode-go`]?`opencode-go`:void 0].filter(e=>e!==void 0);let r=[];if(n.length>0){const{resolveEnabledProviderPluginIds:i}=await import(`./providers-PV4Dd0vY.mjs`);r=t(e,()=>i({config:e,onlyPluginIds:n}))}noteOpencodeProviderOverrides(e,{opencodePluginActive:r.includes(`opencode`),opencodeGoPluginActive:r.includes(`opencode-go`)});noteImplicitFallbackClobberWarnings(e);noteSandboxOriginProxyWarning(e);noteMcpOriginWarning(e);noteMediaCliModelWarnings(e);noteMissingDefaultAgentOwner(e);noteDeprecatedConfiguredModels(e,t)}function noteDeprecatedConfiguredModels(e,t){const n=createDoctorModelRefResolver(e);const r=/* @__PURE__ */ new Map;for(const t of collectConfiguredModelRefs(e)){const e=/^agents\.entries\.([^.]+)\./u.exec(t.path)?.[1];const i=n(t.value,e);if(i)r.set(i,[...r.get(i)??[],t.path])}if(r.size===0)return;const{rows:i}=t(e,()=>planEffectiveModelCatalogRows({registry:loadManifestMetadataSnapshot({config:e,env:process.env}).manifestRegistry,config:e,providerFilters:[...new Set([...r.keys()].map(e=>e.slice(0,e.indexOf(`/`))))]}));const a=[];for(const e of i){const t=r.get(`${e.provider}/${e.id}`);if(t&&e.status===`deprecated`&&e.statusReason)a.push(`- ${e.provider}/${e.id} (${t.join(`, `)}): ${e.statusReason}`)}if(a.length>0)note(sanitizeDoctorNote(a.join(` `)),`Doctor warnings`)}function noteOpencodeProviderOverrides(e,t={}){const n=e.models?.providers;if(!n)return;const r=[...t.opencodePluginActive===true?[`opencode`,`opencode-zen`]:[],...t.opencodeGoPluginActive===true?[`opencode-go`]:[]].filter(e=>n[e]);if(r.length===0)return;const i=r.flatMap(e=>{const t=e===`opencode-go`?`OpenCode Go`:`OpenCode Zen`;const r=n[e];const i=isRecord(r)&&typeof r.api===`string`?r.api:void 0;return[`- models.providers.${e} is set; this overrides the plugin-provided ${t} catalog.`,i?`- models.providers.${e}.api=${i}`:null].filter(e=>Boolean(e))});i.push(`- Remove these entries to restore per-model API routing + costs (then re-run setup if needed).`);note(i.join(` `),`OpenCode`)}function isImplicitFallbackClobber(e){const t=resolvePrimaryStringValue(e);if(typeof e===`string`)return t!==void 0;if(isRecord(e))return Object.hasOwn(e,`primary`)&&!Object.hasOwn(e,`fallbacks`)&&t!==void 0;return false}function noteImplicitFallbackClobberWarnings(e){const t=isRecord(e)&&isRecord(e.agents)?e.agents:void 0;const n=(isRecord(t?.defaults)?t.defaults:void 0)?.model;const r=isRecord(n)&&Array.isArray(n.fallbacks)?n.fallbacks:[];if(r.length===0)return;const i=readAgentRosterProperty(e);const a=i?.kind===`entries`&&isRecord(i.value)?{agents:{entries:i.value}}:i?.kind===`list`&&Array.isArray(i.value)?{agents:{list:i.value}}:void 0;if(!a)return;const o=[];for(const{entry:e,source:t}of listAgentEntriesWithSource(a)){if(!e||!isImplicitFallbackClobber(e.model))continue;const n=e.id?.trim()||(t.kind===`list`?String(t.index):t.key);const i=resolvePrimaryStringValue(e.model);const a=t.kind===`entries`?`agents.entries.${t.key}.model`:`agents.list[${t.index}].model (id=${n})`;const s=typeof e.model===`string`?`"${e.model}"`:`{ primary: "${i}" }`;const c=typeof e.model===`string`?`bare string with no fallbacks`:`object with no explicit "fallbacks" key`;o.push([`- ${a} is ${s}, a ${c}. At runtime this clobbers agents.defaults.model.fallbacks (${r.join(`, `)}), leaving the agent with no fallbacks.`,` Fix: add "fallbacks": [...] to inherit or override, or "fallbacks": [] to explicitly disable.`].join(` `))}if(o.length>0)note(o.join(` `),`Doctor warnings`)}function noteIncludeConfinementWarning(e){const t=(e.issues??[]).find(e=>e.message.includes(`Include path escapes config directory`)||e.message.includes(`Include path resolves outside config directory`));if(!t)return;const n=path.dirname(e.path??CONFIG_PATH);note([`- $include paths must stay under: ${n}`,`- Move shared include files under that directory and update to relative paths like "./shared/common.json".`,`- Error: ${t.message}`].join(` `),`Doctor warnings`)}function noteSandboxOriginProxyWarning(e){if(e.gateway?.auth?.mode!==`trusted-proxy`||e.mcp?.apps?.sandboxOrigin)return;note([`- gateway.auth.mode is "trusted-proxy" but mcp.apps.sandboxOrigin is not set.`,` Dashboard widgets and MCP apps render from a separate sandbox listener (gateway port + 1). If your proxy or tunnel does not also route that port, widget frames cannot load.`,` Check: either route the sandbox port through your proxy, or set mcp.apps.sandboxOrigin to a dedicated public origin routed to the sandbox listener (see docs/cli/mcp/apps.md).`].join(` `),`Doctor warnings`)}function noteMcpOriginWarning(e){if(!Object.values(e.mcp?.servers??{}).some(e=>e.oauth?.identity===`per-requester`)||e.gateway?.publicOrigin)return;note([`- An MCP server uses oauth.identity "per-requester", but gateway.publicOrigin is not set.`,` Set gateway.publicOrigin to the externally reachable Gateway origin so senders can complete MCP sign-in.`].join(` `),`Doctor warnings`)} //!src/commands/doctor/shared/legacy-config-migrate.ts function migrateLegacyConfig(e,t,n){const{context:r}=t;const{next:i,changes:a,warnings:o}=applyLegacyDoctorMigrations(e,t);const s={changes:a,...o?.length?{warnings:o}:{}};if(!i)return{config:null,...s};const c=r&&r.resolvedRaw!==e?applyLegacyDoctorMigrations(r.resolvedRaw,t).next??r.resolvedRaw:i;const l=validateConfigObjectRawWithPlugins(c,{semanticValidation:n,deferredPluginMigrations:getDeferredPluginMigrationConfigFacts(r?.resolvedRaw??e)});if(!l.ok){a.push(`Migration applied; other validation issues remain — run doctor to review.`);return{config:i,...s,partiallyValid:true}}return{config:inheritLegacyDefaultAgentId(c,l.config),sourceConfig:i,...s}} //!src/commands/doctor/shared/config-flow-steps.ts function applyLegacyCompatibilityStep(e){if(e.snapshot.legacyIssues.length===0)return{state:e.state,issueLines:[],changeLines:[]};const t=formatConfigIssueLines(e.snapshot.legacyIssues,`-`);const n=classifyOtelGrpcMigrationOwnership({snapshot:e.snapshot,authoredConfig:e.snapshot.parsed,resolvedConfig:e.snapshot.sourceConfig});if(n?.kind===`manual`){const r=`diagnostics.otel.protocol`;const i=n.targetPaths.length>0?` Inspect these candidate source files and remove or replace ${r} = "grpc" from every definition: ${n.targetPaths.join(`, `)}.`:` Remove or replace ${r} = "grpc" in the owning $include directive or included file.`;return{state:e.state,issueLines:[...t,`- ${r}: Doctor cannot safely rewrite this $include ownership.${i} No config files were changed.`],changeLines:[],blocksWrite:true}}const r=containsAuthoredInclude(e.snapshot.parsed);const{config:i,sourceConfig:a,changes:o,warnings:s,partiallyValid:c}=migrateLegacyConfig(e.snapshot.sourceConfig,{sourceConfigBeforeMigrations:e.snapshot.sourceConfigBeforeMigrations,context:{authoredRaw:e.snapshot.parsed,resolvedRaw:e.snapshot.sourceConfig}});const l=a??i;const u=o.length>0||!isDeepStrictEqual(e.snapshot.sourceConfigBeforeMigrations??(r?e.snapshot.sourceConfig:e.snapshot.parsed),e.snapshot.sourceConfig);return{state:{...e.state,...l?{cfg:l,candidate:l}:{},pendingChanges:e.state.pendingChanges||u,fixHints:e.shouldRepair||!u?e.state.fixHints:[...e.state.fixHints,`Run "${e.doctorFixCommand}" to ${c?`finish fixing`:`migrate`} legacy config keys.`]},issueLines:[...t,...s??[]],changeLines:o,partiallyValid:c===true?true:void 0}}async function applyRetiredConfigStep(e){let t=e.state;if(e.preflight?.heartbeatMigrationDeferred)return t;if(e.shouldRepair&&!e.preflight?.cronStoreSelectionUnresolved){const{tryProjectRetiredHeartbeatConfig:n}=await import(`./doctor-heartbeat-legacy-CR4UkMoG.mjs`);const{retireHeartbeatWithDoctor:r}=await import(`./doctor-heartbeat-retirement-CSbLpw57.mjs`);const i=n(t.candidate)?await r(t.candidate):void 0;if(i&&JSON.stringify(i)!==JSON.stringify(t.candidate)){const n={config:i,changes:[`Retired heartbeat configuration after ordinary automation data was verified.`]};e.emitChanges(n.changes);t=applyDoctorConfigMutation({state:t,mutation:n,shouldRepair:e.shouldRepair,fixHint:`Run "${e.doctorFixCommand}" to finish the heartbeat migration.`})}}const n=stripUnknownConfigKeys(t.candidate,getDeferredPluginMigrationConfigFacts(e.sourceConfig)?.flatMap(e=>(e.configPaths??[]).concat(e.validationExcludedPaths??[])));if(n.removed.length===0)return t;const r=protectActiveAuthProfileConfig({before:t.candidate,after:n.config});t=applyDoctorConfigMutation({state:t,mutation:{config:r.config,changes:n.removed},shouldRepair:e.shouldRepair,fixHint:`Run "${e.doctorFixCommand}" to remove these keys.`});const i=[...n.removed.map(e=>`- ${e}`),...r.repairs.map(e=>`- ${e}`)];if(e.shouldRepair)e.emitChanges(i);else note(i.join(` `),`Unknown config keys`);if(r.warnings.length>0)note(r.warnings.join(` `),`Doctor warnings`);return t}function prepareDoctorConfigReferenceSource(e){if(!e.authoredConfig||!e.sourceConfigBeforeMigrations)return;return{authored:structuredClone(e.authoredConfig),resolved:cloneConfigWithResolutionFacts(e.sourceConfigBeforeMigrations),parsed:structuredClone(e.parsed)}}function retainValuePreservingMigrationRefs(e,t,n){const r=/* @__PURE__ */ new Map;const i=/* @__PURE__ */ new Set;const resolvedEntry=(e,t)=>asOptionalObjectRecord(e)?.[t];const collect=(e,t)=>{if(typeof e===`string`&&/\$\{[A-Z_][A-Z0-9_]*\}/.test(e)){if(r.has(e)&&!isDeepStrictEqual(r.get(e),t))i.add(e);r.set(e,t)}else if(e&&typeof e===`object`)for(const[n,r]of Object.entries(e))collect(r,resolvedEntry(t,n))};collect(n.authored,n.resolved);const retain=(e,t)=>{if(typeof e===`string`&&/\$\{[A-Z_][A-Z0-9_]*\}/.test(e))return r.has(e)&&!i.has(e)&&isDeepStrictEqual(r.get(e),t)?e:void 0;if(Array.isArray(e))return e.map((e,n)=>retain(e,Array.isArray(t)?t[n]:void 0));if(e&&typeof e===`object`)return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,retain(n,resolvedEntry(t,e))]));return e};return retain(e,t)}function restoreDoctorConfigEnvRefs(e,t,n,r={}){if(!t)return e;const projectRoster=e=>projectAuthoredAgentRosterForWrite({rootAuthoredConfig:e,sourceConfigBeforeMigrations:t.resolved});const i=coerceConfig(projectRoster(t.authored));const a=coerceConfig(projectRoster(t.resolved));const o=restoreEnvVarRefsFromResolved(e,i,a,n);const s={sourceConfigBeforeMigrations:t.resolved,context:{authoredRaw:t.parsed,resolvedRaw:t.resolved},pluginCompatibility:r.pluginCompatibility};const c=planProviderRenames(a,resolvePluginDoctorProviderRenames({config:a}));const l=applyProviderRenames(i,c).config;const u=applyLegacyDoctorMigrations(l,s);const d=applyProviderRenames(a,c).config;const f=applyLegacyDoctorMigrations(d,s);const p=u.next??l;const m=f.next??d;if(!isRecord(p)||!isRecord(m))throw new Error(`Doctor reference migrations must preserve config object roots.`);const h=coerceConfig(p);const g=coerceConfig(m);const _=createMergePatch(i,h);const v=createMergePatch(a,g);const y=restoreEnvVarRefsFromResolved(o,retainValuePreservingMigrationRefs(_,v,t),v,n);let b=h;let x=g;const S=new Map(Object.entries(r.appliedPluginIdMigrations??{}));for(const[e,n]of t.installedPluginIdRecovery??[])S.set(e,n.pluginId);for(const[e,t]of S){b=migratePluginConfigId(b,e,t);x=migratePluginConfigId(x,e,t)}const C=createMergePatch(h.plugins?.entries??{},b.plugins?.entries??{});const w=createMergePatch(g.plugins?.entries??{},x.plugins?.entries??{});const T=restoreEnvVarRefsFromResolved(y,{plugins:{entries:C}},{plugins:{entries:w}},n);if(!isRecord(T))throw new Error(`Doctor reference restoration must preserve the config object root.`);const E=coerceConfig(T);setDeferredPluginMigrationConfigFacts(E,getDeferredPluginMigrationConfigFacts(e));return E}export{migrateLegacyConfig as a,noteDoctorHookConfigWarnings as c,restoreDoctorConfigEnvRefs as i,applyRetiredConfigStep as n,noteConfigAdvisories as o,prepareDoctorConfigReferenceSource as r,noteDoctorConfigPreflightIssues as s,applyLegacyCompatibilityStep as t};