UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

596 lines (595 loc) • 24.7 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { o as writeRuntimeJson, t as ExitError } from "./runtime-B-SLYP-m.mjs"; import { t as parseConfigPathArrayIndex } from "./path-array-index-qP-D1DoI.mjs"; import { s as toDotPath } from "./dot-path-BJ4tyWKJ.mjs"; import { r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { m as resolveConfigPath } from "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { s as readAgentRosterProperty } from "./agent-roster-t1ooUdXp.mjs"; import "./agent-scope-config-DmXgFGKP.mjs"; import { r as withArtifactPreservingStateReads } from "./artifact-preserving-state-reads-BfhmBr-V.mjs"; import "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { n as prepareBundledDiscoveryMode } from "./bundled-discovery-state-Bb0zCvZZ.mjs"; import { r as hasInstalledPluginIndexWorkspaceScopeMismatch } from "./installed-plugin-index-DYqse_gE.mjs"; import { t as dedupeByKey } from "./dedupe-by-key-Cpowmfct.mjs"; import { t as resolvePluginControlPlaneFingerprint } from "./plugin-control-plane-context-BmY6xICT.mjs"; import { t as coerceConfig } from "./io.read-helpers-qAcqsRC0.mjs"; import { r as normalizeAgentModelRefForConfig } from "./model-input-DrM4DWHG.mjs"; import { n as normalizeSubmittedConfigModelRefs } from "./model-input-normalization-BSpz0kXV.mjs"; import { t as AUTO_MANAGED_CONFIG_META_PATHS } from "./io.meta-BrkFioo1.mjs"; import { t as ConfigMutationConflictError } from "./mutation-conflict-Bs0nsNWn.mjs"; import { m as resolvePluginMetadataSnapshotAsync, o as isPluginMetadataSnapshotCompatible } from "./plugin-metadata-snapshot-By9ySblt.mjs"; import { n as getDeferredPluginMigrationConfigFacts, u as resolveManagedUnsetPathsForWrite } from "./deferred-plugin-migration-config-B3TJC-SY.mjs"; import { t as parseLegacyAgentRoster } from "./legacy.roster-BcYJITMZ.mjs"; import { t as REDACTED_SENTINEL } from "./redact-sentinel-Db2p5Put.mjs"; import { r as assertConfigWriteAllowedInCurrentMode } from "./config-write-guard-CxNxfJ_I.mjs"; import { o as isConfigValidationFailedError, t as ConfigWritePostCommitError } from "./io.write-errors-CuPAqPbq.mjs"; import { n as prepareConfigWriteValues } from "./io.write-prepare-B19yEmrf.mjs"; import { n as visitConfigValueTree } from "./value-tree-Deh4eoFD.mjs"; import { r as replaceConfigFile } from "./mutate-DhAOi0-2.mjs"; import "./config-CMA-J084.mjs"; import { n as info, t as danger } from "./globals-CgepmiqE.mjs"; import { t as resolveGatewayReloadSettings } from "./config-reload-settings-CcAkiFrq.mjs"; import { o as diffConfigPaths, t as buildGatewayReloadPlan } from "./config-reload-plan-BWeZCeX8.mjs"; import { r as formatCliJsonFailure } from "./failure-output-DVVDqwuu.mjs"; import { t as exitCliAfterOutput } from "./one-shot-exit-DkbGSQD5.mjs"; import { c as setAtPath, i as getAtPath, l as unsetAtPath, n as formatConfigSetPath, o as mergeAtPath, r as formatConfigUnsetMissingPathMessage, t as assertNonDestructiveReplacement } from "./config-cli-path-rYPQt5Be.mjs"; import { r as restoreRedactedValues } from "./redact-snapshot-HHllfRSn.mjs"; import { t as prepareConfigWriteTopology } from "./io.write-topology-B__9tFVE.mjs"; import { t as formatConfigFilePath } from "./logging-D0RirHBi.mjs"; import { a as validateConfigMutation, i as loadValidConfigForWrite, t as assertStrictConfigForMutation } from "./config-cli-validation-BcBb5zay.mjs"; import { isDeepStrictEqual } from "node:util"; //#region src/cli/config-cli-model-normalization.ts function shouldNormalizeConfigMutationProviderCatalogs(e) { const t = ["models", "providers"]; if (e.touchedPaths.some((e) => t.slice(0, Math.min(e.length, t.length)).every((t, n) => e[n] === t)) || !isDeepStrictEqual(e.before.models?.providers, e.after.models?.providers)) return true; if (!e.before.models?.providers && !e.after.models?.providers) return false; return resolvePluginControlPlaneFingerprint({ config: e.before, env: e.env }) !== resolvePluginControlPlaneFingerprint({ config: e.after, env: e.env }); } async function normalizeConfigMutationModelRefs(e, t = {}) { if (!(t.normalizeProviderCatalogs !== false && Object.values(e.models?.providers ?? {}).some((e) => Array.isArray(e?.models) && e.models.some((e) => typeof e?.id === "string" && e.id.trim())))) return normalizeSubmittedConfigModelRefs(e, void 0, t); return withArtifactPreservingStateReads(async () => { const n = t.env ?? process.env; const r = t.pluginMetadataSnapshot; const i = r && !hasInstalledPluginIndexWorkspaceScopeMismatch(r.index, void 0) ? r : void 0; if (i) (await prepareBundledDiscoveryMode(n))(); const a = i && isPluginMetadataSnapshotCompatible({ snapshot: i, config: e, env: n }) ? i : await resolvePluginMetadataSnapshotAsync({ config: e, env: n }); return normalizeSubmittedConfigModelRefs(e, a.owners.modelIdNormalizationPolicies, t); }); } function normalizeConfigMutationExplicitSetPath(e) { const t = e[0] === "agents" && e[1] === "defaults" && e[2] === "models" ? 3 : e[0] === "agents" && (e[1] === "entries" || e[1] === "list") && e[3] === "models" ? 4 : void 0; if (t !== void 0 && e.length > t) { const n = expectDefined(e[t], `path entry at ${t}`); const r = normalizeAgentModelRefForConfig(n); return r === n ? e : [ ...e.slice(0, t), r, ...e.slice(t + 1) ]; } return e; } //#endregion //#region src/cli/config-cli-roster.ts /** Keeps the documented list input and keyed input on one mutable roster. */ var ConfigMutationAgentRoster = class { constructor(e, t) { this.root = e; const n = readAgentRosterProperty(t); this.legacyOrder = n?.kind === "list" ? parseLegacyAgentRoster(n.value)?.order : void 0; } prepare(e, t) { const n = e.setPath; if (n[0] !== "agents") return; if (n.length === 1 && isRecord(e.value) && Object.hasOwn(e.value, "list") && Object.hasOwn(e.value, "entries")) throw new Error("Set either agents.list or agents.entries in one value, not both."); const r = n.length === 1 ? readAgentRosterProperty({ agents: e.value }) : void 0; const i = n.length === 1 ? r?.kind : n[1]; const a = readAgentRosterProperty(this.root); if (!a) this.legacyOrder = void 0; const o = this.root.agents; if (i !== "list" && i !== "entries" || !isRecord(o)) return; if (n.length <= 2 && !t && (i === "entries" || e.mutation !== "delete")) { delete o[i === "entries" ? "list" : "entries"]; this.legacyOrder = void 0; return; } if (i === "entries") { if (a?.kind === "list") this.canonicalize(true); return; } if (a?.kind !== "entries") return; if (!isRecord(a.value) || Object.values(a.value).some((e) => !isRecord(e) || Object.hasOwn(e, "id"))) throw new Error("Cannot address agents.list while agents.entries contains invalid entries; correct the keyed roster first."); const s = a.value; const c = [.../* @__PURE__ */ new Set([...this.legacyOrder ?? [], ...Object.keys(s)])].filter((e) => Object.hasOwn(s, e)); const l = []; for (const e of c) l.push({ ...s[e], id: e }); o.list = l; delete o.entries; } writePath(e) { if (e[0] !== "agents" || e[1] !== "list") return e; if (e.length === 2) { const t = readAgentRosterProperty(this.root); return t?.kind === "list" && parseLegacyAgentRoster(t.value) ? ["agents", "entries"] : e; } const t = getAtPath(this.root, e.slice(0, 3)); const n = (t.found ? parseLegacyAgentRoster([t.value]) : void 0)?.order[0]; return n === void 0 ? e : [ "agents", "entries", n, ...e.slice(3) ]; } finish() { this.canonicalize(false); } canonicalize(e) { const t = this.root.agents; const n = readAgentRosterProperty(this.root); if (!isRecord(t) || n?.kind !== "list") return; const r = parseLegacyAgentRoster(n.value); if (!r) { if (e) throw new Error("Cannot address agents.entries while agents.list contains invalid or duplicate ids; correct the list first."); return; } this.legacyOrder = r.order; t.entries = r.entries; delete t.list; } }; //#endregion //#region src/cli/config-set-dryrun.ts var ConfigSetDryRunValidationError = class extends Error { constructor(e, t = false) { const n = formatDryRunFailureMessage({ errors: e.errors ?? [], skippedExecRefs: e.skippedExecRefs }); super(t ? n : "config set dry-run validation failed"); this.result = e; this.name = "ConfigSetDryRunValidationError"; this.humanOutput = n; } }; function printConfigDryRunResult(e, t, n) { if (!e.ok) throw new ConfigSetDryRunValidationError(e, !n); if (n) { writeRuntimeJson(t, e); return; } if (!e.checks.schema && !e.checks.resolvability) t.log(info("Dry run note: value mode does not run schema/resolvability checks. Use --strict-json, builder flags, or batch mode to enable validation checks.")); if (e.skippedExecRefs > 0) t.log(info(formatSkippedExecRefs(e.skippedExecRefs))); t.log(info(terminalText`Dry run successful: ${e.operations} update(s) validated against ${formatConfigFilePath(e.configPath)}.`)); } function formatSkippedExecRefs(e) { return `Dry run note: skipped ${e} exec SecretRef resolvability check(s). Re-run with --allow-exec to execute exec providers during dry-run.`; } function formatDryRunFailureMessage(e) { const t = e.errors.filter((e) => e.kind === "missing-path"); const n = e.errors.filter((e) => e.kind === "schema"); const r = e.errors.filter((e) => e.kind === "resolvability"); const i = e.errors.filter((e) => e.kind === "model"); const a = t.map((e) => terminalText`${e.message}`); if (n.length > 0) a.push("Dry run failed: config schema validation failed.", ...n.map((e) => terminalText`- ${e.message}`)); if (r.length > 0) { a.push(`Dry run failed: ${r.length} SecretRef assignment(s) could not be resolved.`, ...r.slice(0, 5).map((e) => terminalText`- ${e.ref ?? "<unknown-ref>"} -> ${e.message}`)); if (r.length > 5) a.push(`- ... ${r.length - 5} more`); } if (i.length > 0) a.push("Dry run failed: model reference validation failed.", ...i.map((e) => terminalText`- ${e.message}`)); if (e.skippedExecRefs > 0) a.push(formatSkippedExecRefs(e.skippedExecRefs)); return a.join("\n"); } //#endregion //#region src/cli/config-cli-runner.ts const GATEWAY_AUTH_MODE_PATH = [ "gateway", "auth", "mode" ]; const PLUGIN_INSTALL_RECORD_PATH_PREFIX = ["plugins", "installs"]; function pathStartsWith(e, t) { return t.every((t, n) => e[n] === t); } function pathEquals(e, t) { return e.length === t.length && e.every((e, n) => e === t[n]); } function remapSuppliedPathsAfterDelete(e, t, n) { const r = t.slice(0, -1); return e.flatMap((e) => { if (pathStartsWith(e, t)) return []; if (n === void 0 || e.length <= r.length || !pathStartsWith(e, r)) return [e]; const i = e[r.length]; const a = i === void 0 ? void 0 : parseConfigPathArrayIndex(i); return a !== void 0 && a > n ? [[ ...r, String(a - 1), ...e.slice(r.length + 1) ]] : [e]; }); } function collectChangedLeafPaths(e, t) { if (!isRecord(e)) return [t]; const n = Object.entries(e); return n.length === 0 ? [t] : n.flatMap(([e, n]) => collectChangedLeafPaths(n, t ? `${t}.${e}` : e)); } async function runConfigOperations(e) { const { runtime: t, operations: n, options: r } = e; if (n.some(({ requestedPath: e }) => pathStartsWith(e, PLUGIN_INSTALL_RECORD_PATH_PREFIX))) throw new Error([ "plugins.installs is managed by the plugin index and cannot be edited with config set.", "", "Use plugin commands instead:", ` ${formatCliCommand("openclaw plugins install <spec>")}`, ` ${formatCliCommand("openclaw plugins update <plugin-id>")}`, ` ${formatCliCommand("openclaw plugins uninstall <plugin-id>")}` ].join("\n")); const i = r.merge; const a = []; for (const e of n) { if (AUTO_MANAGED_CONFIG_META_PATHS.some((t) => pathStartsWith(e.requestedPath, t))) { a.push(e.requestedPath); continue; } const t = e.mutation !== "delete" && (e.mutation === "merge" || i && e.mutation !== "replace"); for (const n of AUTO_MANAGED_CONFIG_META_PATHS) { const r = n.slice(e.requestedPath.length); if (e.requestedPath.length < n.length && pathStartsWith(n, e.requestedPath) && (!t || getAtPath(e.value, r).value !== void 0)) a.push([...n]); } } const o = dedupeByKey(a, toDotPath); if (o.length > 0) { const e = o.map(toDotPath).join(", "); throw new Error([ `${e} is auto-managed by OpenClaw and cannot be edited; the value would be overwritten on the next config write.`, "", "These fields are stamped on every config write to record the OpenClaw version and timestamp that produced the file." ].join("\n")); } const s = await loadValidConfigForWrite(t, e.databaseOnly ? { databaseOnly: true } : void 0); const { snapshot: c } = s; const l = e.currentExpectation; let assertCurrentExpectation; if (l) { const e = n[0]; if (!e) throw new Error("conditional config set requires one resolved operation"); assertCurrentExpectation = () => { const t = getAtPath(c.resolved, e.setPath); if (!(l.kind === "absent" ? !t.found : t.found && isDeepStrictEqual(t.value, l.value))) throw new ConfigMutationConflictError("conditional config set expectation did not match the authored config", { retryable: false }); }; } const u = structuredClone(c.resolved); const d = { pluginMetadataSnapshot: s.writeOptions.basePluginMetadataSnapshot, env: s.writeOptions.envSnapshotForRestore }; let f = e.databaseOnly ? c.resolved : await normalizeConfigMutationModelRefs(c.resolved, { ...d, normalizeProviderCatalogs: false }); let p; const getMutationSchema = () => p ??= import("./runtime-schema-BzOMdj_y.mjs").then(({ readBestEffortRuntimeConfigSchema: e }) => e({ snapshot: c, pluginMetadataSnapshot: s.writeOptions.basePluginMetadataSnapshot })).catch(() => void 0); const m = new ConfigMutationAgentRoster(u, c.sourceConfigBeforeMigrations); let h = []; const g = []; let _ = []; let v = []; const y = []; const recordOperation = (e) => { const t = m.writePath(e.setPath); const n = e.setPath[1] === "list" && t[1] === "entries" && t.length === 4 && t[3] === "id"; const r = normalizeConfigMutationExplicitSetPath(n ? t.slice(0, 3) : t); y.push({ ...e, setPath: r }); return t; }; for (const t of n) { const n = t.mutation === "merge" || r.merge && t.mutation !== "replace"; m.prepare(t, Boolean(n)); if (l && !pathEquals(t.requestedPath, m.writePath(t.setPath))) throw new Error("conditional config set requires a direct, non-redirected config path"); if (t.mutation === "delete") { const n = recordOperation(t); const i = t.setPath.length === 3 && t.setPath[0] === "agents" && t.setPath[1] === "list" && n[1] === "entries"; const a = t.setPath.at(-1); const o = unsetAtPath(u, t.setPath); if (!o.removed && t.inputMode === "unset") { const n = formatConfigSetPath(t.requestedPath, t.pathTokens); const i = getAtPath(c.runtimeConfig, t.setPath).found; const a = formatConfigUnsetMissingPathMessage({ path: n, runtimeOnly: i }); if (r.dryRun && r.json) throw new ConfigSetDryRunValidationError({ ok: false, operations: 1, configPath: c.path, inputModes: ["unset"], checks: { schema: false, resolvability: false, resolvabilityComplete: false }, refsChecked: 0, skippedExecRefs: 0, errors: [{ kind: "missing-path", message: i ? a : `Config path not found: ${n}. Nothing was changed.` }] }); if (!r.dryRun) assertStrictConfigForMutation(f, s.writeOptions.basePluginMetadataSnapshot, getDeferredPluginMigrationConfigFacts(c.sourceConfig), e.databaseOnly); throw new Error(a); } if (!o.removed || o.leafContainer !== "array") h.push(n); if (o.removed) { if (n.length === 3 && n[0] === "agents" && n[1] === "entries") g.push(String(n[2])); const e = o.leafContainer === "array" && !i && a !== void 0 ? parseConfigPathArrayIndex(a) : void 0; v = remapSuppliedPathsAfterDelete(v, n, e); _ = remapSuppliedPathsAfterDelete(_, n, e); for (const t of y) { const [r] = remapSuppliedPathsAfterDelete([t.setPath], n, e); if (r) t.setPath = r; } } continue; } const i = !e.databaseOnly && e.successMode !== "patch" && t.setPath.some((e, n) => n > 0 && parseConfigPathArrayIndex(e) !== void 0 && typeof t.pathTokens?.[n] !== "number" && !t.quotedNumericSegments?.has(n)) ? (await getMutationSchema())?.schema : void 0; const a = { numericObjectKeys: e.successMode === "patch", pathTokens: t.pathTokens, quotedNumericSegments: t.quotedNumericSegments, schema: i, command: e.successMode }; let o; if (n) o = mergeAtPath(u, t.setPath, t.value, a); else { assertNonDestructiveReplacement({ root: u, path: t.setPath, value: t.value, allowReplace: r.replace || t.mutation === "replace", command: e.successMode }); setAtPath(u, t.setPath, t.value, a); o = [t.setPath]; } v.push(...o.map((e) => m.writePath(e))); _.push(recordOperation(t)); } m.finish(); h = h.filter((e) => !getAtPath(u, e).found); const b = []; const x = n.some(({ requestedPath: e }) => pathEquals(e, GATEWAY_AUTH_MODE_PATH)); const S = u.gateway; if (x && isRecord(S)) { const e = S.auth; if (isRecord(e)) { const t = typeof e.mode === "string" ? e.mode.trim() : ""; const remove = (t) => { if (Object.hasOwn(e, t)) { delete e[t]; b.push(`gateway.auth.${t}`); } }; if (t === "token") remove("password"); else if (t === "password") remove("token"); else if (t === "trusted-proxy") { remove("token"); remove("password"); } } } let C = false; visitConfigValueTree(u, (e) => { C ||= e === REDACTED_SENTINEL; return !C; }); let w = coerceConfig(u); if (C) { const e = restoreRedactedValues(u, c.resolved, (await getMutationSchema())?.uiHints); if (!e.ok) throw new Error(e.humanReadableMessage ?? "Cannot restore redacted config values."); w = coerceConfig(e.result); } const T = !e.databaseOnly && shouldNormalizeConfigMutationProviderCatalogs({ before: c.resolved, after: w, touchedPaths: y.map(({ setPath: e }) => e), env: d.env }); if (T) f = await normalizeConfigMutationModelRefs(c.resolved, d); if (!e.databaseOnly) w = await normalizeConfigMutationModelRefs(w, { ...d, normalizeProviderCatalogs: T }); const E = _.map(normalizeConfigMutationExplicitSetPath); const D = s.writeOptions.envSnapshotForRestore ?? process.env; const O = prepareConfigWriteValues({ snapshot: c, nextConfig: w, explicitSetPaths: v.map(normalizeConfigMutationExplicitSetPath), env: D }); const k = O.authoredConfig; const A = prepareConfigWriteValues({ snapshot: c, nextConfig: f, env: D }); const j = A.authoredConfig; let M = { config: k, previousConfig: j, env: O.resolutionEnv, previousEnv: A.resolutionEnv }; if (r.dryRun) { const e = await prepareConfigWriteTopology({ snapshot: c, pluginMetadataSnapshot: s.writeOptions.basePluginMetadataSnapshot, nextConfig: k, options: { explicitSetPaths: E }, unsetPaths: resolveManagedUnsetPathsForWrite(h), env: D }); w = e.nextConfig; M = { config: e.authoredConfig, previousConfig: j, env: e.resolutionEnv, previousEnv: A.resolutionEnv }; } const N = await validateConfigMutation({ config: w, modelValidation: M, previousConfig: f, operations: y, options: r, configPath: c.path, unchanged: e.successMode === "set" && isDeepStrictEqual(f, w) && isDeepStrictEqual(j, k), pluginMetadataSnapshot: s.writeOptions.basePluginMetadataSnapshot, deferredPluginMigrations: getDeferredPluginMigrationConfigFacts(c.sourceConfig), databaseOnly: e.databaseOnly }); if (N.kind === "dry-run") { printConfigDryRunResult(N.result, t, r.json); return; } if (N.kind === "unchanged") { assertCurrentExpectation?.(); t.log(info("No change")); return; } let P; if (e.commit) { assertConfigWriteAllowedInCurrentMode({ configPath: c.path }); assertCurrentExpectation?.(); e.beforePersistentApply?.(); const { prepareConfigOwnerChange: n } = await import("./config-cli-owner-patch-DPt3y-cS.mjs"); const r = await n({ snapshot: c, pluginMetadataSnapshot: s.writeOptions.basePluginMetadataSnapshot, previous: j, next: k, explicitSetPaths: E, unsetPaths: resolveManagedUnsetPathsForWrite(h), env: D }); const i = await e.commit(r); P = i.hint; for (const e of i.warnings) t.error(e); if (r.clearedSessionStoreOwner) t.error("Cleared agents.defaults.sessionStore.agentId because session.store changed. Set that owner path explicitly to assign the destination store's owner."); } else await replaceConfigFile({ sourceConfig: k, snapshot: c, ...c.hash !== void 0 ? { baseHash: c.hash } : {}, writeOptions: { ...s.writeOptions, auditOrigin: "cli", ...assertCurrentExpectation || e.beforePersistentApply ? { assertConfigPathForWrite: () => { s.writeOptions.assertConfigPathForWrite?.(); assertCurrentExpectation?.(); e.beforePersistentApply?.(); } } : {}, ...h.length > 0 ? { unsetPaths: h } : {}, ...g.length > 0 ? { allowedAgentRosterRemovals: g } : {}, ...E.length > 0 ? { explicitSetPaths: E } : {} } }); if (b.length > 0) t.log(info(terminalText`Removed inactive ${b.join(", ")} for gateway.auth.mode=${w.gateway?.auth?.mode ?? "<unset>"}.`)); const F = n.map(({ requestedPath: e }) => toDotPath(e)); const I = diffConfigPaths(f, w); const L = /* @__PURE__ */ new Set(); for (const e of I) { const t = F.filter((t) => t !== e && t.startsWith(`${e}.`)); if (t.length > 0) { t.forEach((e) => L.add(e)); continue; } const n = e === "<root>" ? [] : e.split("."); const r = getAtPath(f, n); const i = getAtPath(w, n); const a = r.found && !i.found ? r : i; (r.found !== i.found ? collectChangedLeafPaths(a.value, e) : [e]).forEach((e) => L.add(e)); } const R = [...L]; let z = P ?? "No gateway restart needed."; if (!P && R.length > 0) { const e = buildGatewayReloadPlan(R, { candidateConfig: w }); if (e.restartGateway || e.hotReasons.length > 0 && resolveGatewayReloadSettings(w).mode === "off") z = "Restart the gateway to apply."; else if (e.hotReasons.length > 0) z = "Change will apply without restarting the gateway."; } if (e.successMode === "set" && n.length === 1) { const e = n[0]; const r = e?.mutation === "delete" ? "Removed" : "Updated"; const i = formatConfigSetPath(e?.requestedPath ?? [], e?.pathTokens, w); t.log(info(terminalText`${r} ${i}. ${z}`)); } else if (e.successMode === "set") t.log(info(terminalText`Updated ${n.length} config paths. ${z}`)); else t.log(info(terminalText`Applied ${n.length} config update(s). ${z}`)); } function handleConfigMutationError(e) { if (e.err instanceof ExitError) throw e.err; const t = e.err instanceof ConfigMutationConflictError ? e.err : void 0; const n = formatErrorMessage(e.err); let r = n; if (t) r = t.retryable ? `The config file changed while this command was writing (${n}), so nothing was changed. Re-run the same command to pick up the new file and try again.` : `Config change declined (${n}). No settings were saved. Review the current config and any conditional expectations before retrying.`; if (e.options.dryRun && e.options.json) { if (e.err instanceof ConfigSetDryRunValidationError) { writeRuntimeJson(e.runtime, e.err.result); exitCliAfterOutput(e.runtime, 1); } const n = { ok: false, operations: 0, configPath: resolveConfigPath(), inputModes: [], checks: { schema: false, resolvability: false, resolvabilityComplete: false }, refsChecked: 0, skippedExecRefs: 0, errors: [{ kind: t ? "conflict" : "schema", message: r }] }; writeRuntimeJson(e.runtime, n); e.runtime.error(danger(terminalText`${r}`)); exitCliAfterOutput(e.runtime, 1); } if (e.jsonOutput) writeRuntimeJson(e.runtime, formatCliJsonFailure(r)); if (isConfigValidationFailedError(e.err)) { e.runtime.error("Config change declined. No settings were saved."); e.runtime.error(terminalText`${r}`); e.runtime.error(`Correct the setting above and retry. Run ${formatCliCommand("openclaw config schema")} to inspect supported settings and values.`); } else e.runtime.error(danger(e.err instanceof ConfigSetDryRunValidationError || e.err instanceof ConfigWritePostCommitError ? e.err.humanOutput : terminalText`${r}`)); exitCliAfterOutput(e.runtime, 1); } //#endregion export { handleConfigMutationError, runConfigOperations };