-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathconfig-cli.ts
More file actions
526 lines (508 loc) · 19.2 KB
/
Copy pathconfig-cli.ts
File metadata and controls
526 lines (508 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
// Config CLI command implementation for get/set/unset/patch/validate and secret refs.
import type { Command } from "commander";
import { formatDocsLink } from "../../packages/terminal-core/src/links.js";
import { theme } from "../../packages/terminal-core/src/theme.js";
import { readConfigFileSnapshot, replaceConfigFile } from "../config/config.js";
import { formatConfigIssueLines, normalizeConfigIssues } from "../config/issue-format.js";
import { attachConfigIssueDiagnostics } from "../config/issue-location.js";
import { CONFIG_PATH, resolveConfigPath } from "../config/paths.js";
import { redactConfigObject } from "../config/redact-snapshot.js";
import { readBestEffortRuntimeConfigSchema } from "../config/runtime-schema.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { danger, info, success, warn } from "../globals.js";
import { ExitError, type RuntimeEnv, defaultRuntime, writeRuntimeJson } from "../runtime.js";
import { shortenHomePath } from "../utils.js";
import { formatCliCommand } from "./command-format.js";
import {
buildConfigSetOperations,
buildUnsetOperation,
ConfigSetDryRunValidationError,
configPatchModeError,
modeError,
readConfigPatchOperations,
type ConfigPatchOptions,
type ConfigUnsetOptions,
} from "./config-cli-input.js";
import { normalizeConfigMutationModelRefs } from "./config-cli-model-normalization.js";
import {
formatConfigUnsetMissingPathMessage,
getAtPath,
parseConfigSetPath,
unsetAtPath,
} from "./config-cli-path.js";
import {
assertConfigPathIsNotAutoManaged,
configApplyHintForOperations,
handleConfigMutationError,
runConfigOperations,
} from "./config-cli-runner.js";
import { formatInvalidConfigRepairHint, loadValidConfig } from "./config-cli-validation.js";
import { checkTouchedTextModelRefs } from "./config-model-validation.js";
import {
hasBatchMode,
hasProviderBuilderOptions,
hasRefBuilderOptions,
parseBatchSource,
type ConfigSetOptions,
} from "./config-set-input.js";
import { resolveConfigSetMode } from "./config-set-parser.js";
import { setCommandJsonMode } from "./program/json-mode.js";
export { parseConfigSetPath } from "./config-cli-path.js";
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");
export async function runConfigSet(opts: {
path?: string;
value?: string;
cliOptions: ConfigSetOptions;
runtime?: RuntimeEnv;
}) {
const runtime = opts.runtime ?? defaultRuntime;
try {
const isBatchMode = hasBatchMode(opts.cliOptions);
const modeResolution = resolveConfigSetMode({
hasBatchMode: isBatchMode,
hasRefBuilderOptions: hasRefBuilderOptions(opts.cliOptions),
hasProviderBuilderOptions: hasProviderBuilderOptions(opts.cliOptions),
strictJson: Boolean(opts.cliOptions.strictJson || opts.cliOptions.json),
});
if (!modeResolution.ok) {
throw modeError(modeResolution.error);
}
if (opts.cliOptions.allowExec && !opts.cliOptions.dryRun) {
throw modeError("--allow-exec requires --dry-run.");
}
if (opts.cliOptions.merge && opts.cliOptions.replace) {
throw modeError("choose either --merge or --replace, not both.");
}
const batchEntries = parseBatchSource(opts.cliOptions);
if (batchEntries && (opts.path !== undefined || opts.value !== undefined)) {
throw modeError("batch mode does not accept <path> or <value> arguments.");
}
await runConfigOperations({
runtime,
operations: buildConfigSetOperations({
path: opts.path,
value: opts.value,
opts: opts.cliOptions,
batchEntries: batchEntries ?? null,
}),
options: opts.cliOptions,
successMode: "set",
});
} catch (err) {
handleConfigMutationError({ err, runtime, options: opts.cliOptions });
}
}
export async function runConfigPatch(opts: {
cliOptions: ConfigPatchOptions;
runtime?: RuntimeEnv;
}) {
const runtime = opts.runtime ?? defaultRuntime;
try {
if (opts.cliOptions.allowExec && !opts.cliOptions.dryRun) {
throw configPatchModeError("--allow-exec requires --dry-run.");
}
if (opts.cliOptions.json && !opts.cliOptions.dryRun) {
throw configPatchModeError("--json requires --dry-run.");
}
await runConfigOperations({
runtime,
operations: await readConfigPatchOperations(opts.cliOptions),
options: opts.cliOptions,
successMode: "patch",
});
} catch (err) {
handleConfigMutationError({ err, runtime, options: opts.cliOptions });
}
}
export async function runConfigGet(opts: { path: string; json?: boolean; runtime?: RuntimeEnv }) {
const runtime = opts.runtime ?? defaultRuntime;
try {
const parsedPath = parseConfigSetPath(opts.path);
const snapshot = await loadValidConfig(runtime);
const res = getAtPath(redactConfigObject(snapshot.config), parsedPath);
if (!res.found) {
if (opts.json) {
writeRuntimeJson(runtime, { error: `Config path not found: ${opts.path}` });
runtime.exit(1);
return;
}
runtime.error(
danger(
`Config path not found: ${opts.path}. Run ${formatCliCommand("openclaw config validate")} to inspect config shape.`,
),
);
runtime.exit(1);
return;
}
if (opts.json) {
writeRuntimeJson(runtime, res.value ?? null);
} else if (
typeof res.value === "string" ||
typeof res.value === "number" ||
typeof res.value === "boolean"
) {
runtime.log(String(res.value));
} else {
writeRuntimeJson(runtime, res.value ?? null);
}
} catch (err) {
if (err instanceof ExitError) {
throw err;
}
runtime.error(danger(String(err)));
runtime.exit(1);
}
}
export async function runConfigUnset(opts: {
path: string;
cliOptions?: ConfigUnsetOptions;
runtime?: RuntimeEnv;
}) {
const runtime = opts.runtime ?? defaultRuntime;
const cliOptions = opts.cliOptions ?? {};
try {
if (cliOptions.allowExec && !cliOptions.dryRun) {
throw new Error("--allow-exec can only be used with --dry-run.");
}
if (cliOptions.json && !cliOptions.dryRun) {
throw new Error("--json can only be used with --dry-run.");
}
const parsedPath = parseConfigSetPath(opts.path);
assertConfigPathIsNotAutoManaged(parsedPath);
const snapshot = await loadValidConfig(runtime);
// Mutate resolved config so runtime defaults never leak into the authored file.
const next = structuredClone(snapshot.resolved) as Record<string, unknown>;
const currentConfig = normalizeConfigMutationModelRefs(
structuredClone(snapshot.resolved) as OpenClawConfig,
);
const unsetResult = unsetAtPath(next, parsedPath);
if (!unsetResult.removed) {
const runtimeOnly = getAtPath(snapshot.runtimeConfig, parsedPath).found;
const missingPathMessage = formatConfigUnsetMissingPathMessage({
path: opts.path,
runtimeOnly,
});
if (cliOptions.dryRun && cliOptions.json) {
throw new ConfigSetDryRunValidationError({
ok: false,
operations: 1,
configPath: snapshot.path,
inputModes: ["unset"],
checks: { schema: false, resolvability: false, resolvabilityComplete: false },
refsChecked: 0,
skippedExecRefs: 0,
errors: [
{
kind: "missing-path",
message: runtimeOnly
? missingPathMessage
: `Config path not found: ${opts.path}. Nothing was changed.`,
},
],
});
}
runtime.error(danger(missingPathMessage));
runtime.exit(1);
return;
}
const operation = buildUnsetOperation(parsedPath);
if (cliOptions.dryRun) {
await runConfigOperations({
runtime,
operations: [operation],
options: cliOptions,
successMode: "set",
});
return;
}
const nextConfig = normalizeConfigMutationModelRefs(structuredClone(next) as OpenClawConfig);
const modelRefCheck = await checkTouchedTextModelRefs({
config: nextConfig,
previousConfig: currentConfig,
touchedPaths: [parsedPath],
redactDependencyValues: true,
});
if (modelRefCheck.errors[0]) {
throw new Error(modelRefCheck.errors[0]);
}
await replaceConfigFile({
nextConfig,
...(snapshot.hash !== undefined ? { baseHash: snapshot.hash } : {}),
writeOptions:
unsetResult.leafContainer === "array"
? { auditOrigin: "cli" }
: { auditOrigin: "cli", unsetPaths: [parsedPath] },
});
const hint = configApplyHintForOperations([operation], currentConfig, nextConfig);
runtime.log(info(`Removed ${opts.path}. ${hint}`));
} catch (err) {
handleConfigMutationError({ err, runtime, options: cliOptions });
}
}
async function runConfigFile(opts: { runtime?: RuntimeEnv }) {
const runtime = opts.runtime ?? defaultRuntime;
try {
runtime.log(resolveConfigPath());
} catch (err) {
runtime.error(danger(String(err)));
runtime.exit(1);
}
}
async function runConfigSchema(opts: { runtime?: RuntimeEnv } = {}) {
const runtime = opts.runtime ?? defaultRuntime;
try {
const schema = structuredClone((await readBestEffortRuntimeConfigSchema()).schema) as {
properties?: Record<string, unknown>;
};
schema.properties = { $schema: { type: "string" }, ...schema.properties };
writeRuntimeJson(runtime, schema);
} catch (err) {
runtime.error(danger(`Config schema error: ${String(err)}`));
runtime.exit(1);
}
}
async function runConfigValidate(opts: { json?: boolean; runtime?: RuntimeEnv } = {}) {
const runtime = opts.runtime ?? defaultRuntime;
let outputPath = CONFIG_PATH ?? "openclaw.json";
try {
const snapshot = await readConfigFileSnapshot();
outputPath = snapshot.path;
const shortPath = shortenHomePath(outputPath);
if (!snapshot.exists) {
if (opts.json) {
writeRuntimeJson(runtime, { valid: false, path: outputPath, error: "file not found" }, 0);
} else {
runtime.error(danger(`Config file not found: ${shortPath}`));
runtime.error(
`Create one with ${formatCliCommand("openclaw onboard")} or run ${formatCliCommand("openclaw doctor --fix")}.`,
);
}
runtime.exit(1);
return;
}
if (!snapshot.valid) {
const issues = normalizeConfigIssues(snapshot.issues);
if (opts.json) {
writeRuntimeJson(runtime, { valid: false, path: outputPath, issues });
} else {
const displayIssues = attachConfigIssueDiagnostics(issues, {
raw: snapshot.raw,
parsed: snapshot.parsed,
effective: snapshot.sourceConfig,
configPath: snapshot.path,
formatPathForDisplay: true,
includeReceivedValueHint: true,
});
runtime.error(danger(`OpenClaw config is invalid: ${shortPath}`));
for (const line of formatConfigIssueLines(displayIssues, danger("×"), {
normalizeRoot: true,
})) {
runtime.error(` ${line}`);
}
runtime.error("");
runtime.error(
formatInvalidConfigRepairHint(snapshot, "to repair, or fix the keys above manually."),
);
runtime.error(`Inspect with ${formatCliCommand("openclaw config validate")}.`);
}
runtime.exit(1);
return;
}
const warnings = normalizeConfigIssues(snapshot.warnings);
if (opts.json) {
writeRuntimeJson(runtime, { valid: true, path: outputPath, warnings }, 0);
} else {
runtime.log(success(`Config valid: ${shortPath}`));
if (warnings.length > 0) {
runtime.log(warn(`${warnings.length} warning(s):`));
for (const line of formatConfigIssueLines(warnings, warn("!"), { normalizeRoot: true })) {
runtime.log(` ${line}`);
}
}
}
} catch (err) {
if (opts.json) {
writeRuntimeJson(runtime, { valid: false, path: outputPath, error: String(err) }, 0);
} else {
runtime.error(danger(`Config validation error: ${String(err)}`));
}
runtime.exit(1);
}
}
function collectOption(value: string, previous: string[]): string[] {
return [...previous, value];
}
export function registerConfigCli(program: Command) {
const cmd = program
.command("config")
.description(
"Non-interactive config helpers (get/set/patch/unset/file/schema/validate). Run without subcommand for guided setup.",
)
.addHelpText(
"after",
() =>
`\n${theme.muted("Docs:")} ${formatDocsLink("/cli/config", "docs.openclaw.ai/cli/config")}\n`,
)
.option(
"--section <section>",
"Configuration sections for guided setup (repeatable). Use with no subcommand.",
collectOption,
[] as string[],
)
.action(async (opts) => {
const { configureCommandFromSectionsArg } = await import("../commands/configure.js");
await configureCommandFromSectionsArg(opts.section, defaultRuntime);
});
cmd
.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 (path: string, opts) => {
await runConfigGet({ path, json: Boolean(opts.json) });
});
setCommandJsonMode(cmd.command("set"), "parse-only")
.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(
"--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",
"Dry-run only: allow exec SecretRef resolvability checks (may execute provider commands)",
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)")
.option("--ref-id <id>", "SecretRef builder: ref id")
.option("--provider-source <source>", "Provider builder: source (env|file|exec)")
.option(
"--provider-allowlist <envVar>",
"Provider builder (env): allowlist entry (repeatable)",
collectOption,
[] as string[],
)
.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,
[] as string[],
)
.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,
[] as string[],
)
.option(
"--provider-pass-env <envVar>",
"Provider builder (exec): pass host env var (repeatable)",
collectOption,
[] as string[],
)
.option(
"--provider-trusted-dir <path>",
"Provider builder (exec): trusted directory (repeatable)",
collectOption,
[] as string[],
)
.option(
"--provider-allow-insecure-path",
"Provider builder (file|exec): bypass strict path permission checks",
false,
)
.option(
"--provider-allow-symlink-command",
"Provider builder (exec): allow command symlink path",
false,
)
.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 (path: string | undefined, value: string | undefined, opts: ConfigSetOptions) => {
await runConfigSet({ path, value, cliOptions: opts });
});
cmd
.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",
"Dry-run only: allow exec SecretRef resolvability checks (may execute provider commands)",
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,
[] as string[],
)
.action(async (opts: ConfigPatchOptions) => {
await runConfigPatch({ cliOptions: opts });
});
cmd
.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 (path: string, options: ConfigUnsetOptions) => {
await runConfigUnset({ path, cliOptions: options });
});
cmd.command("file").description("Print the active config file path").action(runConfigFile);
cmd
.command("schema")
.description("Print the JSON schema for openclaw.json")
.action(runConfigSchema);
cmd
.command("validate")
.description("Validate the current config against the schema without starting the gateway")
.option("--json", "Output validation result as JSON", false)
.action(async (opts) => {
await runConfigValidate({ json: Boolean(opts.json) });
});
}