openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
334 lines (333 loc) • 18.1 kB
JavaScript
import { n as isConfigSetJsonParseOnly, t as isConfigMachineOutput } from "./config-output-mode-B_Eb6adL.mjs";
import { o as writeRuntimeJson, r as defaultRuntime, s as writeRuntimeStdout, t as ExitError } from "./runtime-B-SLYP-m.mjs";
import { i as parseConcreteConfigPathTokens, r as parseConcreteConfigPath } from "./dot-path-BJ4tyWKJ.mjs";
import { r as terminalText } from "./safe-text-C80HAQ2e.mjs";
import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { m as resolveConfigPath, t as CONFIG_PATH } from "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { n as getDatabaseEngineSelection } from "./context-DE59wyBs.mjs";
import { i as normalizeConfigIssues, n as formatConfigIssueLines } from "./issue-format-WaYQX-7p.mjs";
import { a as isConfigReadFailure } from "./io.invalid-config-DK-BYZ4Y.mjs";
import { t as AUTO_MANAGED_CONFIG_META_PATHS } from "./io.meta-BrkFioo1.mjs";
import { t as quoteCliArg } from "./quote-cli-arg-J7A9UE6m.mjs";
import { a as success, o as warn, t as danger } from "./globals-CgepmiqE.mjs";
import { r as formatCliJsonFailure } from "./failure-output-DVVDqwuu.mjs";
import { t as exitCliAfterOutput } from "./one-shot-exit-DkbGSQD5.mjs";
import { a as isConfigSchemaPath, i as getAtPath } from "./config-cli-path-rYPQt5Be.mjs";
import { t as formatConfigFilePath } from "./logging-D0RirHBi.mjs";
import { t as formatDocsHelp } from "./help-format-D2ytHW5E.mjs";
import { t as collectOption } from "./helpers-Cxs4nwgv.mjs";
import { t as renderConfigValidationIssueLines } from "./issue-location-B-4mXR06.mjs";
import { n as setCommandJsonMode } from "./json-mode-DF5JGxtm.mjs";
//#region src/cli/config-cli.ts
const CONFIG_ALLOW_EXEC_DESCRIPTION = "Dry-run only: allow exec SecretRef resolvability checks (may execute provider commands)";
const CONFIG_SET_DESCRIPTION = [
"Set config values by path (value mode, ref/provider builder mode, or batch JSON mode).",
"Examples:",
formatCliCommand("openclaw config set gateway.port 19001 --strict-json"),
formatCliCommand("openclaw config set channels.discord.token --ref-provider default --ref-source env --ref-id DISCORD_BOT_TOKEN"),
formatCliCommand("openclaw config set secrets.providers.vault --provider-source file --provider-path /etc/openclaw/secrets.json --provider-mode json"),
formatCliCommand("openclaw config set --batch-file ./config-set.batch.json --dry-run")
].join("\n");
const CONFIG_PATCH_DESCRIPTION = [
"Patch config from a JSON5 object in one validated write.",
"Objects merge recursively, arrays/scalars replace, and null deletes a path.",
"Examples:",
formatCliCommand("openclaw config patch --file ./openclaw.patch.json5 --dry-run"),
formatCliCommand("openclaw config patch --stdin")
].join("\n");
async function runConfigMutation(e, t, n = Boolean(e.cliOptions.json)) {
const r = e.runtime ?? defaultRuntime;
const { handleConfigMutationError: i, runConfigOperations: a } = await import("./config-cli-runner-CgpVRJti.mjs");
let o = false;
try {
e.preparationSignal?.throwIfAborted();
const n = await t();
if (e.preparationSignal?.aborted) return;
o = true;
const i = e.localStateOwner !== void 0 && n.operations.length > 0 && n.operations.every(({ setPath: e }) => e[0] === "database");
const run = (t) => a({
runtime: r,
options: e.cliOptions,
...n,
...i ? { databaseOnly: true } : {},
...t ? { commit: t } : {}
});
if (!e.localStateOwner) await run();
else if (e.cliOptions.dryRun) {
if (!i && !getDatabaseEngineSelection()) {
const { readConfigSnapshotForEngineSelection: e } = await import("./config-preflight-snapshot-DXY8QhxC.mjs");
await e();
}
await run();
} else {
const { runWithLocalStateOwner: t } = await import("./local-state-owner-CxFnsNJm.mjs");
const { target: r } = e.localStateOwner;
await t({
...e.localStateOwner,
params: {},
...r === "config" ? {} : { recoveryCommand: `openclaw config get ${quoteCliArg(r)}` },
...n.operations.some(({ setPath: e }) => e[0] === "database") ? {
onForeignOwner: "refuse",
onlineAlternative: "Database settings select the state database the running Gateway holds open, so they change only offline."
} : { onForeignOwner: async ({ env: e, requestOwner: t }) => {
const { bindConfigOwner: n } = await import("./config-cli-owner-patch-DPt3y-cS.mjs");
await run(await n(t, e));
} },
...i ? { databaseAccess: "none" } : { databaseEngine: "configured" },
runLocal: () => run()
});
}
} catch (t) {
if (!o && e.preparationSignal?.aborted) return;
if (e.throwOnError) throw t;
i({
err: t,
runtime: r,
options: e.cliOptions,
jsonOutput: n
});
}
}
async function runConfigSet(e) {
return runConfigMutation(e, async () => {
const { buildConfigSetOperations: t } = await import("./config-cli-input-DQsYJY2N.mjs");
const { parseConfigSetCurrentExpectation: n } = await import("./config-set-input-D3It78on.mjs");
const r = n(e.cliOptions);
return {
operations: t({
path: e.path,
value: e.value,
opts: e.cliOptions
}),
successMode: "set",
...r ? { currentExpectation: r } : {},
...e.beforePersistentApply ? { beforePersistentApply: e.beforePersistentApply } : {}
};
}, Boolean(e.cliOptions.dryRun && e.cliOptions.json));
}
async function runConfigPatch(e) {
const t = e.cliOptions.stdin ? getAsyncWorkSignal() : void 0;
return runConfigMutation({
...e,
preparationSignal: t
}, async () => {
const { configPatchModeError: t, readConfigPatchOperations: n } = await import("./config-cli-input-DQsYJY2N.mjs");
if (e.cliOptions.allowExec && !e.cliOptions.dryRun) throw t("--allow-exec requires --dry-run.");
if (e.cliOptions.json && !e.cliOptions.dryRun) throw t("--json requires --dry-run.");
return {
operations: await n(e.cliOptions),
successMode: "patch"
};
});
}
async function runConfigGet(e) {
const t = e.runtime ?? defaultRuntime;
try {
const n = parseConcreteConfigPath(e.path);
const { readConfigFileSnapshotWithPluginMetadata: r } = await import("./config/config.js");
const { ensureValidConfigSnapshotForCli: i } = await import("./config-cli-validation-CNYkqlWO.mjs");
const a = [
"plugins",
"channels",
"agents"
].includes(n[0] ?? "");
const { snapshot: o, pluginMetadataSnapshot: s } = await r({
observe: false,
completePluginMetadata: a
});
i(o, t, { json: e.json });
if (a && !s) throw new Error("Config plugin metadata unavailable; refusing to display config values.");
const { redactConfigObject: c } = await import("./redact-snapshot-D48uHOIm.mjs");
const l = a && s ? (await import("./runtime-schema-BzOMdj_y.mjs")).buildRuntimeConfigSchemaFromRegistry(s.manifestRegistry, o.sourceConfig) : void 0;
const u = l?.uiHints ?? (await import("./schema-base-CKpwONtI.mjs")).computeBaseConfigUiHints();
const d = getAtPath(c(o.config, u), n);
if (!d.found || d.value === void 0) {
const r = l?.schema ?? (await import("./schema-KMV_ZalZ.mjs")).buildConfigSchemaCore().schema;
const i = AUTO_MANAGED_CONFIG_META_PATHS.some((e) => n.every((t, n) => e[n] === t) || e.every((e, t) => n[t] === e));
const a = isConfigSchemaPath(r, n) ? i ? `Config path is valid but unset: ${e.path}. This path contains metadata managed automatically by OpenClaw on config writes; it cannot be authored with config set.` : `Config path is valid but unset: ${e.path}. The runtime default applies until you set an authored value with ${formatCliCommand(`openclaw config set ${quoteCliArg(e.path)} <value>`)}.` : `Unknown config path: ${e.path}. Run ${formatCliCommand("openclaw config schema")} to inspect valid paths.`;
if (e.json) {
writeRuntimeJson(t, formatCliJsonFailure(a));
exitCliAfterOutput(t, 1);
}
t.error(danger(terminalText`${a}`));
exitCliAfterOutput(t, 1);
}
if (!e.json && (typeof d.value === "string" || typeof d.value === "number" || typeof d.value === "boolean")) writeRuntimeStdout(t, `${String(d.value)}\n`);
else writeRuntimeJson(t, d.value);
} catch (n) {
if (n instanceof ExitError) throw n;
if (e.json) {
writeRuntimeJson(t, formatCliJsonFailure(n));
exitCliAfterOutput(t, 1);
}
t.error(danger(terminalText`${formatErrorMessage(n)}`));
exitCliAfterOutput(t, 1);
}
}
async function runConfigUnset(e) {
const t = e.cliOptions ?? {};
return runConfigMutation({
...e,
cliOptions: t
}, async () => {
const { buildUnsetOperation: n } = await import("./config-cli-input-DQsYJY2N.mjs");
if (t.allowExec && !t.dryRun) throw new Error("--allow-exec can only be used with --dry-run.");
if (t.json && !t.dryRun) throw new Error("--json can only be used with --dry-run.");
const r = parseConcreteConfigPathTokens(e.path);
return {
operations: [n(r.map(String), r)],
successMode: "set",
...e.beforePersistentApply ? { beforePersistentApply: e.beforePersistentApply } : {}
};
});
}
function registerConfigCli(e) {
const t = e.command("config").description("Non-interactive config helpers (get/set/patch/unset/file/schema/validate). Run without subcommand for guided setup.").addHelpText("after", () => formatDocsHelp("/cli/config")).option("--section <section>", "Configuration sections for guided setup (repeatable). Use with no subcommand.", collectOption, []).action(async (e) => {
const { configureCommandFromSectionsArg: t } = await import("./configure.commands-_GHS8-jv.mjs");
await t(e.section);
});
setCommandJsonMode(t, "output", ({ argv: e }) => isConfigMachineOutput(e));
t.command("get").description("Get a config value by dot path").argument("<path>", "Config path (dot or bracket notation)").option("--json", "Output JSON", false).action(async (e, t) => {
await runConfigGet({
path: e,
json: Boolean(t.json)
});
});
setCommandJsonMode(t.command("set"), "parse-only", ({ argv: e }) => isConfigSetJsonParseOnly(e)).description(CONFIG_SET_DESCRIPTION).argument("[path]", "Config path (dot or bracket notation)").argument("[value]", "Value (JSON/JSON5 or raw string)").option("--strict-json", "Strict JSON parsing (error instead of raw string fallback)", false).option("--json", "Legacy alias for --strict-json", false).option("--expect-current-absent", "Write only when the authored path is absent", false).option("--expect-current-json <json>", "Write only when the authored path exactly matches this strict JSON value").option("--dry-run", "Validate changes without writing openclaw.json (checks run in builder/json/batch modes; exec SecretRefs are skipped unless --allow-exec is set)", false).option("--allow-exec", CONFIG_ALLOW_EXEC_DESCRIPTION, false).option("--merge", "Merge object/map values instead of replacing the target path", false).option("--replace", "Allow full replacement of protected map/list paths such as agents.defaults.models", false).option("--ref-provider <alias>", "SecretRef builder: provider alias").option("--ref-source <source>", "SecretRef builder: source (env|file|exec|store)").option("--ref-id <id>", "SecretRef builder: ref id").option("--provider-source <source>", "Provider builder: source (env|file|exec|store)").option("--provider-allowlist <envVar>", "Provider builder (env): allowlist entry (repeatable)", collectOption, []).option("--provider-path <path>", "Provider builder (file): path").option("--provider-mode <mode>", "Provider builder (file): mode (singleValue|json)").option("--provider-timeout-ms <ms>", "Provider builder (file|exec): timeout ms").option("--provider-max-bytes <bytes>", "Provider builder (file): max bytes").option("--provider-command <path>", "Provider builder (exec): absolute command path").option("--provider-arg <arg>", "Provider builder (exec): command arg (repeatable)", collectOption, []).option("--provider-no-output-timeout-ms <ms>", "Provider builder (exec): no-output timeout ms").option("--provider-max-output-bytes <bytes>", "Provider builder (exec): max output bytes").option("--provider-json-only", "Provider builder (exec): require JSON output", false).option("--provider-env <key=value>", "Provider builder (exec): env assignment (repeatable)", collectOption, []).option("--provider-pass-env <envVar>", "Provider builder (exec): pass host env var (repeatable)", collectOption, []).option("--provider-trusted-dir <path>", "Provider builder (exec): trusted directory (repeatable)", collectOption, []).option("--batch-json <json>", "Batch mode: JSON array of set operations").option("--batch-file <path>", "Batch mode: read JSON array of set operations from file").action(async (e, t, n) => {
await runConfigSet({
path: e,
value: t,
cliOptions: n,
localStateOwner: {
method: "config set",
target: e ?? "config"
}
});
});
t.command("patch").description(CONFIG_PATCH_DESCRIPTION).option("--file <path>", "Read a JSON5 config patch object from file").option("--stdin", "Read a JSON5 config patch object from stdin", false).option("--dry-run", "Validate changes without writing openclaw.json (checks schema and SecretRef resolvability; exec SecretRefs are skipped unless --allow-exec is set)", false).option("--allow-exec", CONFIG_ALLOW_EXEC_DESCRIPTION, false).option("--json", "Output dry-run result as JSON", false).option("--replace-path <path>", "Replace the object or array at this dot/bracket path instead of recursively applying it (repeatable)", collectOption, []).action(async (e) => {
await runConfigPatch({
cliOptions: e,
localStateOwner: {
method: "config patch",
target: "config"
}
});
});
t.command("unset").description("Remove a config value by dot path").argument("<path>", "Config path (dot or bracket notation)").option("--dry-run", "validate the removal without writing the config file").option("--allow-exec", "allow exec SecretRef providers during --dry-run").option("--json", "print dry-run result as JSON").action(async (e, t) => {
await runConfigUnset({
path: e,
cliOptions: t,
localStateOwner: {
method: "config unset",
target: e
}
});
});
t.command("file").description("Print the active config file path").option("--json", "Output JSON", false).action(async (e) => {
const t = e.runtime ?? defaultRuntime;
try {
const n = resolveConfigPath();
if (e.json) {
writeRuntimeJson(t, { path: n });
return;
}
writeRuntimeStdout(t, `${n}\n`);
} catch (e) {
t.error(danger(terminalText`${formatErrorMessage(e)}`));
exitCliAfterOutput(t, 1);
}
});
t.command("schema").description("Print the JSON schema for openclaw.json").option("--json", "Output JSON", false).action(async (e = {}) => {
const t = e.runtime ?? defaultRuntime;
try {
const { readBestEffortRuntimeConfigSchema: e } = await import("./runtime-schema-BzOMdj_y.mjs");
const n = (await e()).schema;
writeRuntimeJson(t, {
...n,
properties: {
$schema: { type: "string" },
...n.properties
}
});
} catch (e) {
t.error(danger(terminalText`Config schema error: ${formatErrorMessage(e)}`));
exitCliAfterOutput(t, 1);
}
});
t.command("validate").description("Validate the current config against the schema without starting the gateway").option("--json", "Output validation result as JSON", false).action(async (e) => {
const t = Boolean(e.json);
const n = defaultRuntime;
let r = CONFIG_PATH ?? "openclaw.json";
try {
const { readConfigSnapshotForEngineSelection: e } = await import("./config-preflight-snapshot-DXY8QhxC.mjs");
const { readConfigFileSnapshotWithPluginMetadata: i } = await import("./config/config.js");
const { finishConfigValidationForCli: a } = await import("./config-cli-validation-CNYkqlWO.mjs");
const { formatInvalidConfigRepairHint: o } = await import("./config-recovery-hints-CkKLc1qY.mjs");
const s = await e();
const c = isConfigReadFailure(s) || s.issues.some((e) => e.errorCode === "CONFIG_SOURCE_INVALID") ? s : await a(await i({
observe: false,
prepareValidation: "strict",
completePluginMetadata: false
}));
r = c.path;
const l = shortenHomePath(r);
if (!c.exists) {
if (t) writeRuntimeJson(n, {
...formatCliJsonFailure("file not found"),
valid: false,
path: r
}, 0);
else {
n.error(danger(`Config file not found: ${formatConfigFilePath(r)}`));
n.error(`Create one with ${formatCliCommand("openclaw onboard")} or run ${formatCliCommand("openclaw doctor --fix")}.`);
}
exitCliAfterOutput(n, 1);
}
if (!c.valid) {
const e = normalizeConfigIssues(c.issues);
if (t) writeRuntimeJson(n, {
...formatCliJsonFailure(`OpenClaw config is invalid: ${l}`),
repairHint: o(c, "to repair, then retry."),
valid: false,
path: r,
issues: e
});
else {
n.error(`Config needs correction: ${formatConfigFilePath(r)}`);
for (const e of renderConfigValidationIssueLines(c, "-")) n.error(` ${e}`);
n.error("");
n.error(o(c, "to repair, or fix the keys above manually."));
n.error(`Run ${formatCliCommand("openclaw config schema")} to inspect supported settings and values, then rerun ${formatCliCommand("openclaw config validate")}.`);
}
exitCliAfterOutput(n, 1);
}
const u = normalizeConfigIssues(c.warnings);
if (t) writeRuntimeJson(n, {
valid: true,
path: r,
warnings: u
}, 0);
else {
n.log(success(`Config valid: ${formatConfigFilePath(r)}`));
if (u.length > 0) {
n.log(warn(`${u.length} warning(s):`));
for (const e of formatConfigIssueLines(u, warn("!"), { normalizeRoot: true })) n.log(` ${e}`);
}
}
} catch (e) {
if (e instanceof ExitError) throw e;
if (t) writeRuntimeJson(n, {
...formatCliJsonFailure(e),
valid: false,
path: r
}, 0);
else n.error(danger(terminalText`Config validation error: ${formatErrorMessage(e)}`));
exitCliAfterOutput(n, 1);
}
});
}
//#endregion
export { registerConfigCli, runConfigGet, runConfigSet, runConfigUnset };