Skip to content

Commit 9d558b5

Browse files
committed
fix(cli): keep parse JSON terminal-neutral
1 parent 8f1ed5c commit 9d558b5

4 files changed

Lines changed: 70 additions & 16 deletions

File tree

‎src/cli/failure-output.test.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,9 @@ describe("formatCliJsonFailure", () => {
3737
new CliParseError({
3838
message: 'OpenClaw sessions has no command "lst".',
3939
humanOutput:
40-
'OpenClaw sessions has no command "lst".\nDid you mean this?\n openclaw sessions list\nTry: openclaw sessions --help\n',
40+
'\u001B[31mOpenClaw sessions has no command "lst".\u001B[39m\nDid you mean this?\n openclaw sessions list\nTry: openclaw sessions --help\nDocs: \u001B]8;;https://docs.openclaw.ai/cli\u0007docs.openclaw.ai/cli\u001B]8;;\u0007\n',
41+
machineOutput:
42+
'OpenClaw sessions has no command "lst".\nDid you mean this?\n openclaw sessions list\nTry: openclaw sessions --help\nDocs: https://docs.openclaw.ai/cli\n',
4143
}),
4244
{ cause: new Error("internal parse cause") },
4345
);
@@ -48,7 +50,7 @@ describe("formatCliJsonFailure", () => {
4850
error: {
4951
type: "cli_error",
5052
message:
51-
'OpenClaw sessions has no command "lst".\nDid you mean this?\n openclaw sessions list\nTry: openclaw sessions --help',
53+
'OpenClaw sessions has no command "lst".\nDid you mean this?\n openclaw sessions list\nTry: openclaw sessions --help\nDocs: https://docs.openclaw.ai/cli',
5254
},
5355
});
5456
expect(payload.error.message).not.toContain("internal parse cause");
@@ -60,15 +62,20 @@ describe("formatCliFailureLines", () => {
6062
{ label: "default output", env: {} },
6163
{ label: "debug output", env: { OPENCLAW_DEBUG: "1" } },
6264
])("emits parse guidance only when not already written in $label", ({ env }) => {
63-
const pending = new CliParseError({ message: "bad input", humanOutput: "first\nsecond\n" });
65+
const pending = new CliParseError({
66+
message: "bad input",
67+
humanOutput: "\u001B[31mfirst\u001B[39m\nsecond\n",
68+
machineOutput: "first\nsecond\n",
69+
});
6470
const written = new CliParseError({
6571
message: "bad input",
66-
humanOutput: "first\nsecond\n",
72+
humanOutput: "\u001B[31mfirst\u001B[39m\nsecond\n",
6773
humanOutputWritten: true,
74+
machineOutput: "first\nsecond\n",
6875
});
6976

7077
expect(formatCliFailureLines({ title: "ignored", error: pending, env })).toEqual([
71-
"first",
78+
"\u001B[31mfirst\u001B[39m",
7279
"second",
7380
]);
7481
expect(formatCliFailureLines({ title: "ignored", error: written, env })).toEqual([]);

‎src/cli/failure-output.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,19 @@ export type CliJsonFailure = {
2424
export class CliParseError extends Error {
2525
readonly humanOutput: string;
2626
readonly humanOutputWritten: boolean;
27+
readonly machineOutput: string;
2728

28-
constructor(params: { message: string; humanOutput: string; humanOutputWritten?: boolean }) {
29+
constructor(params: {
30+
message: string;
31+
humanOutput: string;
32+
humanOutputWritten?: boolean;
33+
machineOutput: string;
34+
}) {
2935
super(params.message);
3036
this.name = "CliParseError";
3137
this.humanOutput = params.humanOutput;
3238
this.humanOutputWritten = params.humanOutputWritten ?? false;
39+
this.machineOutput = params.machineOutput;
3340
}
3441
}
3542

@@ -40,7 +47,7 @@ export function formatCliJsonFailure(
4047
): CliJsonFailure {
4148
const message =
4249
error instanceof CliParseError
43-
? formatErrorMessage(error.humanOutput.trimEnd())
50+
? formatErrorMessage(error.machineOutput.trimEnd())
4451
: formatCliOperatorError(error, options);
4552
return {
4653
ok: false,

‎src/cli/program/error-output.ts‎

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Friendly parse-error formatter for Commander errors and root CLI recovery hints.
2+
import { stripAnsi } from "../../../packages/terminal-core/src/ansi.js";
23
import { formatDocsLink } from "../../../packages/terminal-core/src/links.js";
34
import { theme } from "../../../packages/terminal-core/src/theme.js";
45
import { getCommandPathWithRootOptions } from "../argv.js";
@@ -39,13 +40,19 @@ function lines(...items: Array<string | undefined>): string {
3940
}
4041

4142
function formatHelpHint(argv: string[] | undefined, options?: { commandPath?: string[] }): string {
42-
return `${theme.muted("Try:")} ${theme.command(resolveHelpCommand(argv, options))}`;
43+
const command = resolveHelpCommand(argv, options);
44+
return `${theme.muted("Try:")} ${theme.command(command)}`;
4345
}
4446

4547
function formatDocsHint(): string {
4648
return `${theme.muted("Docs:")} ${formatDocsLink("/cli", "docs.openclaw.ai/cli")}`;
4749
}
4850

51+
function formatCliMachineOutput(humanOutput: string): string {
52+
const docs = `Docs: ${formatDocsLink("/cli", "docs.openclaw.ai/cli", { force: false })}`;
53+
return stripAnsi(humanOutput).replace(/^Docs:.*$/mu, docs);
54+
}
55+
4956
function formatUnknownCommandMessage(command: string, commandPath: readonly string[]): string {
5057
return commandPath.length > 0
5158
? `OpenClaw ${commandPath.join(" ")} has no command ${quote(command)}.`
@@ -79,16 +86,20 @@ export function createCliParseError(
7986
if (unknownCommand) {
8087
const command = unknownCommand[1] ?? "";
8188
const commandPath = options.commandPath ?? [];
89+
const humanOutput = formatCliUnknownCommandOutput(command, options);
8290
return new CliParseError({
8391
message: formatUnknownCommandMessage(command, commandPath),
84-
humanOutput: formatCliUnknownCommandOutput(command, options),
92+
humanOutput,
8593
humanOutputWritten: errorOptions.humanOutputWritten,
94+
machineOutput: formatCliMachineOutput(humanOutput),
8695
});
8796
}
97+
const humanOutput = formatCliParseErrorOutput(raw, options);
8898
return new CliParseError({
8999
message,
90-
humanOutput: formatCliParseErrorOutput(raw, options),
100+
humanOutput,
91101
humanOutputWritten: errorOptions.humanOutputWritten,
102+
machineOutput: formatCliMachineOutput(humanOutput),
92103
});
93104
}
94105

@@ -97,9 +108,11 @@ export function createCliUnknownCommandError(
97108
options: FormatCliParseErrorOptions = {},
98109
): CliParseError {
99110
const commandPath = options.commandPath ?? [];
111+
const humanOutput = formatCliUnknownCommandOutput(command, options);
100112
return new CliParseError({
101113
message: formatUnknownCommandMessage(command, commandPath),
102-
humanOutput: formatCliUnknownCommandOutput(command, options),
114+
humanOutput,
115+
machineOutput: formatCliMachineOutput(humanOutput),
103116
});
104117
}
105118

@@ -117,39 +130,44 @@ export function formatCliParseErrorOutput(
117130
const unknownOption = message.match(/^unknown option ['"`](.+?)['"`]/i);
118131
if (unknownOption) {
119132
const option = unknownOption[1] ?? "";
133+
const output = `OpenClaw does not recognize option ${quote(option)}.`;
120134
return lines(
121-
theme.error(`OpenClaw does not recognize option ${quote(option)}.`),
135+
theme.error(output),
122136
formatHelpHint(options.argv, { commandPath: options.commandPath }),
123137
);
124138
}
125139

126140
const missingArgument = message.match(/^missing required argument ['"`](.+?)['"`]/i);
127141
if (missingArgument) {
128142
const argument = missingArgument[1] ?? "";
143+
const output = `Missing required argument ${quote(argument)}.`;
129144
return lines(
130-
theme.error(`Missing required argument ${quote(argument)}.`),
145+
theme.error(output),
131146
formatHelpHint(options.argv, { commandPath: options.commandPath }),
132147
);
133148
}
134149

135150
const missingOption = message.match(/^required option ['"`](.+?)['"`] not specified/i);
136151
if (missingOption) {
137152
const option = missingOption[1] ?? "";
153+
const output = `Missing required option ${quote(option)}.`;
138154
return lines(
139-
theme.error(`Missing required option ${quote(option)}.`),
155+
theme.error(output),
140156
formatHelpHint(options.argv, { commandPath: options.commandPath }),
141157
);
142158
}
143159

144160
if (/^too many arguments\b/i.test(message)) {
161+
const output = "Too many arguments for this command.";
145162
return lines(
146-
theme.error("Too many arguments for this command."),
163+
theme.error(output),
147164
formatHelpHint(options.argv, { commandPath: options.commandPath }),
148165
);
149166
}
150167

168+
const output = `OpenClaw could not parse this command: ${message}`;
151169
return lines(
152-
theme.error(`OpenClaw could not parse this command: ${message}`),
170+
theme.error(output),
153171
formatHelpHint(options.argv, { commandPath: options.commandPath }),
154172
);
155173
}

‎test/cli-json-stdout.e2e.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,28 @@ describe("cli json stdout contract", () => {
416416
);
417417
});
418418

419+
it("keeps parse-error JSON free of terminal controls when color is forced", async () => {
420+
await withTempHome(
421+
async (tempHome) => {
422+
const result = runSourceCli(tempHome, ["sessions", "lst", "--json"], {
423+
FORCE_COLOR: "1",
424+
});
425+
426+
expect(result.status).toBe(1);
427+
const payload = JSON.parse(result.stdout) as {
428+
error: { message: string };
429+
};
430+
expect(payload.error.message).toBe(
431+
'OpenClaw sessions has no command "lst".\nDid you mean this?\n openclaw sessions list\nTry: openclaw sessions --help\nDocs: https://docs.openclaw.ai/cli',
432+
);
433+
expect(payload.error.message).not.toMatch(/[\u001B\u0007]/u);
434+
expect(result.stdout).not.toContain("\\u001b");
435+
expect(result.stderr).toContain("\u001B[");
436+
},
437+
{ prefix: "openclaw-unknown-command-color-json-e2e-" },
438+
);
439+
});
440+
419441
it("keeps representative success payload bytes unchanged", async () => {
420442
await withTempHome(
421443
async (tempHome) => {

0 commit comments

Comments
 (0)