openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
424 lines (423 loc) • 20.9 kB
JavaScript
import { _ as resolvePrimaryStringValue } from "./string-coerce-CCIiB4H7.mjs";
import { i as asOptionalObjectRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { i as INCLUDE_KEY } from "./includes-wjVi5Ymt.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import "./utils-C8YECn2Q.mjs";
import { t as CONFIG_PATH } from "./paths-DAcAg5aV.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { n as listAgentEntries, r as listAgentEntriesWithSource, s as readAgentRosterProperty } from "./agent-roster-t1ooUdXp.mjs";
import { A as tryResolveLegacyCompatibilityAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { c as getAuthoredConfigSecretRef, d as hasUnresolvedConfigPath, n as cloneConfigWithResolutionFacts } from "./resolution-facts-xaIKuREs.mjs";
import { n as formatConfigIssueLines } from "./issue-format-WaYQX-7p.mjs";
import { n as createMergePatch } from "./merge-patch-D-7aajuy.mjs";
import { t as coerceConfig } from "./io.read-helpers-qAcqsRC0.mjs";
import { c as setDeferredPluginMigrationConfigFacts, n as getDeferredPluginMigrationConfigFacts } from "./deferred-plugin-migration-config-B3TJC-SY.mjs";
import { t as inheritLegacyDefaultAgentId } from "./legacy.default-agent-owner-DpmHgK0A.mjs";
import { t as OpenClawSchema } from "./zod-schema-C_dxckdb.mjs";
import { r as validateConfigObjectRawWithPlugins } from "./validation-DSwgLhC7.mjs";
import { t as logConfigWarningsOnce } from "./io.warnings-BbJvBO5E.mjs";
import { r as restoreEnvVarRefsFromResolved } from "./env-preserve-D_8K8swo.mjs";
import { r as projectAuthoredAgentRosterForWrite } from "./io.write-prepare-B19yEmrf.mjs";
import "./config-CMA-J084.mjs";
import { p as resolvePluginDoctorProviderRenames } from "./doctor-contract-registry-CFzLZXmq.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { o as migratePluginConfigId } from "./update-config-BFVDqf5S.mjs";
import { n as protectActiveAuthProfileConfig } from "./doctor-auth-profile-config-glGfSiZJ.mjs";
import { t as resolveCliModelEntry } from "./resolve-Qea3Nian.mjs";
import { r as sanitizeDoctorNote } from "./emit-notes-llcc2fq-.mjs";
import { t as applyDoctorConfigMutation } from "./config-mutation-state-C7DKFhoa.mjs";
import { n as containsAuthoredInclude, t as classifyOtelGrpcMigrationOwnership } from "./include-migration-ownership-CWJZ0wk-.mjs";
import { t as applyLegacyDoctorMigrations } from "./legacy-config-compat-B1mpdXN2.mjs";
import { n as planProviderRenames, t as applyProviderRenames } from "./provider-rename-DQduEyIE.mjs";
import path from "node:path";
import { isDeepStrictEqual } from "node:util";
//#region 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("\n"), "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("\n"), "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("\n"), "Doctor warnings");
for (const n of [collectInvalidHookTransformsDirWarnings(e, t), collectUnsupportedInternalHookEntryWarnings(e)]) if (n.length > 0) note(sanitizeDoctorNote(n.join("\n")), "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>";
}
/** Resolves a config path against a loose config tree, returning null for invalid traversal. */
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;
}
/**
* Removes unknown config keys reported by schema validation.
*
* Runs after migrations; retained plugin inputs must survive until their owner can finish.
*/
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
};
}
/** Warns when legacy OpenCode overrides shadow an active plugin-provided catalog. */
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("\n"), "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("\n"));
}
if (o.length > 0) note(o.join("\n"), "Doctor warnings");
}
/** Emits a config include warning when an include path escapes the config directory. */
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("\n"), "Doctor warnings");
}
/** Warns when a trusted-proxy gateway has no public sandbox origin for widget/MCP-app frames. */
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("\n"), "Doctor warnings");
}
/** Warns when per-requester MCP OAuth cannot build a public callback URL. */
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("\n"), "Doctor warnings");
}
//#endregion
//#region src/commands/doctor/shared/legacy-config-migrate.ts
/** Apply legacy migrations and validate the resulting OpenClaw config shape when possible. */
function migrateLegacyConfig(e, t) {
const { context: n } = t;
const { next: r, changes: i, warnings: a } = applyLegacyDoctorMigrations(e, t);
const o = {
changes: i,
...a?.length ? { warnings: a } : {}
};
if (!r) return {
config: null,
...o
};
const s = n && n.resolvedRaw !== e ? applyLegacyDoctorMigrations(n.resolvedRaw, t).next ?? n.resolvedRaw : r;
const c = validateConfigObjectRawWithPlugins(s, { deferredPluginMigrations: getDeferredPluginMigrationConfigFacts(n?.resolvedRaw ?? e) });
if (!c.ok) {
i.push("Migration applied; other validation issues remain — run doctor to review.");
return {
config: r,
...o,
partiallyValid: true
};
}
return {
config: inheritLegacyDefaultAgentId(s, c.config),
sourceConfig: r,
...o
};
}
//#endregion
//#region 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
};
}
/** Retire heartbeat data before removing unknown configuration keys. */
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-COP4rUJ3.mjs");
const { retireHeartbeatWithDoctor: r } = await import("./doctor-heartbeat-retirement-z8KwWn-S.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("\n"), "Unknown config keys");
if (r.warnings.length > 0) note(r.warnings.join("\n"), "Doctor warnings");
return t;
}
/** Keep the matched planning read independent of later write receipts and environment changes. */
function prepareDoctorConfigReferenceSource(e) {
if (!e.authoredConfig || !e.sourceConfigBeforeMigrations) return;
return {
authored: structuredClone(e.authoredConfig),
resolved: cloneConfigWithResolutionFacts(e.sourceConfigBeforeMigrations),
parsed: structuredClone(e.parsed)
};
}
/** A moved template must still have its original read-time value after migration. */
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);
}
/** Restore unchanged and moved references without substituting a later environment. */
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;
}
//#endregion
export { migrateLegacyConfig as a, noteImplicitFallbackClobberWarnings as c, noteMissingDefaultAgentOwner as d, noteOpencodeProviderOverrides as f, restoreDoctorConfigEnvRefs as i, noteMcpOriginWarning as l, applyRetiredConfigStep as n, noteDoctorConfigPreflightIssues as o, noteSandboxOriginProxyWarning as p, prepareDoctorConfigReferenceSource as r, noteDoctorHookConfigWarnings as s, applyLegacyCompatibilityStep as t, noteMediaCliModelWarnings as u };