Skip to content

Commit ca52bdc

Browse files
committed
fix(hitl/cli): suggest the closest valid name for unknown HITL keys and CLI flags
- HITL validateConfig appends 'Did you mean "<key>"?' when an unknown key is within 3 edits of one - planned HITL keys like requireApproval are near no supported key and get no hint - the CLI's unknown-argument error names the closest flag of the command that failed - CLI matching ignores hyphens and case, and reports a kebab-case typo once - both reuse suggestClosest from utils/stringDistance - hitl-documented-config covers typo, casing and planned keys; new offline cli-unknown-option suite
1 parent 10314c5 commit ca52bdc

5 files changed

Lines changed: 168 additions & 2 deletions

File tree

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,7 @@
390390
"test:native-failure-events": "pnpm exec tsx test/continuous-test-suite-native-failure-events.ts",
391391
"test:native-audio-model-aware": "pnpm exec tsx test/continuous-test-suite-native-audio-model-aware.ts",
392392
"test:cli-json-output": "pnpm exec tsx test/continuous-test-suite-cli-json-output.ts",
393+
"test:cli-unknown-option": "pnpm exec tsx test/continuous-test-suite-cli-unknown-option.ts",
393394
"test:logging-guidelines": "pnpm exec tsx test/continuous-test-suite-logging-guidelines.ts",
394395
"test:proxy-polyfills": "pnpm exec tsx test/continuous-test-suite-proxy-polyfills.ts",
395396
"test:mcp:startup-readiness": "pnpm exec tsx test/continuous-test-suite-mcp-startup-readiness.ts",

‎src/cli/parser.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { hideBin } from "yargs/helpers";
1212
import packageJson from "../../package.json" with { type: "json" };
1313
import { globalSession } from "../lib/session/globalSessionState.js";
1414
import { logger } from "../lib/utils/logger.js";
15+
import { suggestClosest } from "../lib/utils/stringDistance.js";
1516
import { handleError } from "./errorHandler.js";
1617
import { CLICommandFactory } from "./factories/commandFactory.js";
1718
import { SetupCommandFactory } from "./factories/setupCommandFactory.js";
@@ -47,6 +48,47 @@ import { DocsCommandFactory } from "./commands/docs.js";
4748
import { UsageCommandFactory } from "./commands/usage.js";
4849
import { VoicesCommandFactory } from "./commands/voices.js";
4950

51+
// yargs passes `.fail()` its usage object, whose getDescriptions() lists the failing command's visible options
52+
const hasOptionDescriptions = (
53+
value: object,
54+
): value is { getDescriptions: () => unknown } =>
55+
typeof (value as { getDescriptions?: unknown }).getDescriptions ===
56+
"function";
57+
58+
function suggestKnownFlags(msg: string, usage: object): string {
59+
const unknown = /Unknown arguments?: (.+)/.exec(msg)?.[1].split(", ");
60+
if (!unknown || !hasOptionDescriptions(usage)) {
61+
return "";
62+
}
63+
const described = usage.getDescriptions();
64+
if (!described || typeof described !== "object") {
65+
return "";
66+
}
67+
const flags = new Map(
68+
Object.keys(described).map((key) => [
69+
key.replace(/-/g, "").toLowerCase(),
70+
key,
71+
]),
72+
);
73+
// yargs also reports the camelCase twin of an unknown kebab-case flag
74+
const seen = new Set<string>();
75+
return unknown
76+
.map((arg) => {
77+
const typed = arg.replace(/-/g, "").toLowerCase();
78+
if (seen.has(typed)) {
79+
return "";
80+
}
81+
seen.add(typed);
82+
const [closest] = suggestClosest(typed, [...flags.keys()], {
83+
limit: 1,
84+
maxDistance: Math.min(3, Math.ceil(typed.length / 3)),
85+
});
86+
const flag = closest ? flags.get(closest) : undefined;
87+
return flag ? `Did you mean --${flag} instead of --${arg}?\n` : "";
88+
})
89+
.join("");
90+
}
91+
5092
// Enhanced CLI with Professional UX
5193
export function initializeCliParser() {
5294
return (
@@ -179,7 +221,7 @@ export function initializeCliParser() {
179221
msg.includes("Unknown argument") ||
180222
msg.includes("Invalid values")
181223
) {
182-
processedMsg = `Error: ${msg}\nUse --help to see available options.\n`;
224+
processedMsg = `Error: ${msg}\n${suggestKnownFlags(msg, yargsInstance)}Use --help to see available options.\n`;
183225
}
184226
process.stderr.write(chalk.red(processedMsg));
185227
} else {

‎src/lib/hitl/hitlManager.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
HITLConfigurationError,
2727
} from "./hitlErrors.js";
2828
import { logger } from "../utils/logger.js";
29+
import { suggestClosest } from "../utils/stringDistance.js";
2930

3031
// Default configuration constants
3132
const DEFAULT_TIMEOUT = 30000; // 30 seconds
@@ -103,8 +104,12 @@ export class HITLManager extends EventEmitter {
103104
for (const key of Object.keys(config)) {
104105
if (!KNOWN_CONFIG_KEYS.has(key) && !this.warnedUnknownKeys.has(key)) {
105106
this.warnedUnknownKeys.add(key);
107+
const [closest] = suggestClosest(key, [...KNOWN_CONFIG_KEYS], {
108+
limit: 1,
109+
});
110+
const didYouMean = closest ? ` Did you mean "${closest}"?` : "";
106111
logger.alwaysStderr(
107-
`[HITL] Unknown config key "${key}" is ignored and has no effect. Supported keys: ${[...KNOWN_CONFIG_KEYS].join(", ")}. See docs/features/enterprise-hitl.md`,
112+
`[HITL] Unknown config key "${key}" is ignored and has no effect.${didYouMean} Supported keys: ${[...KNOWN_CONFIG_KEYS].join(", ")}. See docs/features/enterprise-hitl.md`,
108113
);
109114
}
110115
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#!/usr/bin/env tsx
2+
/**
3+
* The CLI parser runs with `strictOptions()`, so a mistyped flag fails the
4+
* command. The error must name the closest flag of the command that failed,
5+
* and stay quiet when nothing is close.
6+
*
7+
* Offline: every case fails in argument parsing, before a provider is built.
8+
*
9+
* Run: pnpm run test:cli-unknown-option
10+
*/
11+
import {
12+
assert,
13+
assertEqual,
14+
assertIncludes,
15+
defineSuite,
16+
runCLI,
17+
} from "./helpers/harness.js";
18+
import { assertDistFresh } from "./helpers/distFreshness.js";
19+
20+
assertDistFresh({ entrypoints: ["dist/cli/index.js"] });
21+
const { test, runSuite } = defineSuite("CLI unknown-option suggestions", {
22+
offline: true,
23+
});
24+
25+
const countOf = (haystack: string, needle: string): number =>
26+
haystack.split(needle).length - 1;
27+
28+
await test("a one-letter typo of a generate flag names the real flag", async () => {
29+
const result = await runCLI(["generate", "hi", "--temprature", "0.2"]);
30+
assert(result.exitCode !== 0, "a mistyped flag did not fail the command");
31+
assertIncludes(
32+
result.stderr,
33+
"Did you mean --temperature instead of --temprature?",
34+
"no suggestion for --temprature",
35+
);
36+
assertIncludes(result.stderr, "Use --help to see available options.");
37+
});
38+
39+
await test("each mistyped flag gets one suggestion, a kebab-case typo only once", async () => {
40+
const result = await runCLI([
41+
"generate",
42+
"hi",
43+
"--providr",
44+
"openai",
45+
"--max-tokenz",
46+
"5",
47+
]);
48+
assertIncludes(
49+
result.stderr,
50+
"Did you mean --provider instead of --providr?",
51+
"no suggestion for --providr",
52+
);
53+
assertEqual(
54+
countOf(result.stderr, "Did you mean --maxTokens"),
55+
1,
56+
"--max-tokenz was not suggested exactly once",
57+
);
58+
});
59+
60+
await test("suggestions come from the failing command's own flags", async () => {
61+
const typo = await runCLI(["models", "list", "--providr", "openai"]);
62+
assertIncludes(
63+
typo.stderr,
64+
"Did you mean --provider instead of --providr?",
65+
"models list did not suggest its own --provider",
66+
);
67+
const otherCommand = await runCLI(["models", "list", "--temprature", "1"]);
68+
assert(otherCommand.exitCode !== 0, "a generate-only flag was accepted");
69+
assert(
70+
!otherCommand.stderr.includes("Did you mean"),
71+
"models list suggested a flag it does not have",
72+
);
73+
});
74+
75+
await test("a name far from every flag gets no suggestion", async () => {
76+
const result = await runCLI(["generate", "hi", "--zzzzzzzz"]);
77+
assert(result.exitCode !== 0, "an unknown flag did not fail the command");
78+
assert(
79+
!result.stderr.includes("Did you mean"),
80+
"a suggestion was made for a name near no flag",
81+
);
82+
assertIncludes(result.stderr, "Use --help to see available options.");
83+
});
84+
85+
await runSuite();

‎test/continuous-test-suite-hitl-documented-config.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,39 @@ await test("new NeuroLink prints one default-visible stderr line per unknown hit
213213
assertEqual(clean.lines.filter((w) => w.includes("[HITL]")).length, 0);
214214
});
215215

216+
await test("an unknown hitl key near a supported one suggests it; a planned key gets no suggestion", async () => {
217+
const { lines } = captureStderr(
218+
() =>
219+
new NeuroLink({
220+
hitl: {
221+
enabled: true,
222+
dangerousActions: ["delete"],
223+
// @ts-expect-error -- typos of HITLConfig keys
224+
timout: 5000,
225+
autoApproveOnTimeOut: false,
226+
requireApproval: ["writeFile"],
227+
},
228+
}),
229+
);
230+
const lineFor = (key: string): string =>
231+
lines.find((w) => w.includes("[HITL]") && w.includes(`"${key}" is`)) ?? "";
232+
assertIncludes(
233+
lineFor("timout"),
234+
'Did you mean "timeout"?',
235+
"a one-letter typo did not suggest timeout",
236+
);
237+
assertIncludes(
238+
lineFor("autoApproveOnTimeOut"),
239+
'Did you mean "autoApproveOnTimeout"?',
240+
"a casing typo did not suggest autoApproveOnTimeout",
241+
);
242+
assert(
243+
lineFor("requireApproval") !== "" &&
244+
!lineFor("requireApproval").includes("Did you mean"),
245+
"requireApproval was missing or got a suggestion",
246+
);
247+
});
248+
216249
await test("every documented hitl key, including confirmDirectToolCalls, constructs without a warning", async () => {
217250
const documented = captureStderr(
218251
() =>

0 commit comments

Comments
 (0)