Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@
"test:native-failure-events": "pnpm exec tsx test/continuous-test-suite-native-failure-events.ts",
"test:native-audio-model-aware": "pnpm exec tsx test/continuous-test-suite-native-audio-model-aware.ts",
"test:cli-json-output": "pnpm exec tsx test/continuous-test-suite-cli-json-output.ts",
"test:cli-unknown-option": "pnpm exec tsx test/continuous-test-suite-cli-unknown-option.ts",
"test:logging-guidelines": "pnpm exec tsx test/continuous-test-suite-logging-guidelines.ts",
"test:proxy-polyfills": "pnpm exec tsx test/continuous-test-suite-proxy-polyfills.ts",
"test:mcp:startup-readiness": "pnpm exec tsx test/continuous-test-suite-mcp-startup-readiness.ts",
Expand Down
44 changes: 43 additions & 1 deletion src/cli/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { hideBin } from "yargs/helpers";
import packageJson from "../../package.json" with { type: "json" };
import { globalSession } from "../lib/session/globalSessionState.js";
import { logger } from "../lib/utils/logger.js";
import { suggestClosest } from "../lib/utils/stringDistance.js";
import { handleError } from "./errorHandler.js";
import { CLICommandFactory } from "./factories/commandFactory.js";
import { SetupCommandFactory } from "./factories/setupCommandFactory.js";
Expand Down Expand Up @@ -47,6 +48,47 @@ import { DocsCommandFactory } from "./commands/docs.js";
import { UsageCommandFactory } from "./commands/usage.js";
import { VoicesCommandFactory } from "./commands/voices.js";

// yargs passes `.fail()` its usage object, whose getDescriptions() lists the failing command's visible options
const hasOptionDescriptions = (
value: object,
): value is { getDescriptions: () => unknown } =>
typeof (value as { getDescriptions?: unknown }).getDescriptions ===
"function";

function suggestKnownFlags(msg: string, usage: object): string {
const unknown = /Unknown arguments?: (.+)/.exec(msg)?.[1].split(", ");
if (!unknown || !hasOptionDescriptions(usage)) {
return "";
}
const described = usage.getDescriptions();
if (!described || typeof described !== "object") {
return "";
}
const flags = new Map(
Object.keys(described).map((key) => [
key.replace(/-/g, "").toLowerCase(),
key,
]),
);
// yargs also reports the camelCase twin of an unknown kebab-case flag
const seen = new Set<string>();
return unknown
.map((arg) => {
const typed = arg.replace(/-/g, "").toLowerCase();
if (seen.has(typed)) {
return "";
}
seen.add(typed);
const [closest] = suggestClosest(typed, [...flags.keys()], {
limit: 1,
maxDistance: Math.min(3, Math.ceil(typed.length / 3)),
});
const flag = closest ? flags.get(closest) : undefined;
return flag ? `Did you mean --${flag} instead of --${arg}?\n` : "";
})
.join("");
}

// Enhanced CLI with Professional UX
export function initializeCliParser() {
return (
Expand Down Expand Up @@ -179,7 +221,7 @@ export function initializeCliParser() {
msg.includes("Unknown argument") ||
msg.includes("Invalid values")
) {
processedMsg = `Error: ${msg}\nUse --help to see available options.\n`;
processedMsg = `Error: ${msg}\n${suggestKnownFlags(msg, yargsInstance)}Use --help to see available options.\n`;
}
process.stderr.write(chalk.red(processedMsg));
} else {
Expand Down
7 changes: 6 additions & 1 deletion src/lib/hitl/hitlManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
HITLConfigurationError,
} from "./hitlErrors.js";
import { logger } from "../utils/logger.js";
import { suggestClosest } from "../utils/stringDistance.js";

// Default configuration constants
const DEFAULT_TIMEOUT = 30000; // 30 seconds
Expand Down Expand Up @@ -103,8 +104,12 @@ export class HITLManager extends EventEmitter {
for (const key of Object.keys(config)) {
if (!KNOWN_CONFIG_KEYS.has(key) && !this.warnedUnknownKeys.has(key)) {
this.warnedUnknownKeys.add(key);
const [closest] = suggestClosest(key, [...KNOWN_CONFIG_KEYS], {
limit: 1,
});
const didYouMean = closest ? ` Did you mean "${closest}"?` : "";
logger.alwaysStderr(
`[HITL] Unknown config key "${key}" is ignored and has no effect. Supported keys: ${[...KNOWN_CONFIG_KEYS].join(", ")}. See docs/features/enterprise-hitl.md`,
`[HITL] Unknown config key "${key}" is ignored and has no effect.${didYouMean} Supported keys: ${[...KNOWN_CONFIG_KEYS].join(", ")}. See docs/features/enterprise-hitl.md`,
);
}
}
Expand Down
85 changes: 85 additions & 0 deletions test/continuous-test-suite-cli-unknown-option.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#!/usr/bin/env tsx
/**
* The CLI parser runs with `strictOptions()`, so a mistyped flag fails the
* command. The error must name the closest flag of the command that failed,
* and stay quiet when nothing is close.
*
* Offline: every case fails in argument parsing, before a provider is built.
*
* Run: pnpm run test:cli-unknown-option
*/
import {
assert,
assertEqual,
assertIncludes,
defineSuite,
runCLI,
} from "./helpers/harness.js";
import { assertDistFresh } from "./helpers/distFreshness.js";

assertDistFresh({ entrypoints: ["dist/cli/index.js"] });
const { test, runSuite } = defineSuite("CLI unknown-option suggestions", {
offline: true,
});

const countOf = (haystack: string, needle: string): number =>
haystack.split(needle).length - 1;

await test("a one-letter typo of a generate flag names the real flag", async () => {
const result = await runCLI(["generate", "hi", "--temprature", "0.2"]);
assert(result.exitCode !== 0, "a mistyped flag did not fail the command");
assertIncludes(
result.stderr,
"Did you mean --temperature instead of --temprature?",
"no suggestion for --temprature",
);
assertIncludes(result.stderr, "Use --help to see available options.");
});

await test("each mistyped flag gets one suggestion, a kebab-case typo only once", async () => {
const result = await runCLI([
"generate",
"hi",
"--providr",
"openai",
"--max-tokenz",
"5",
]);
assertIncludes(
result.stderr,
"Did you mean --provider instead of --providr?",
"no suggestion for --providr",
);
assertEqual(
countOf(result.stderr, "Did you mean --maxTokens"),
1,
"--max-tokenz was not suggested exactly once",
);
});

await test("suggestions come from the failing command's own flags", async () => {
const typo = await runCLI(["models", "list", "--providr", "openai"]);
assertIncludes(
typo.stderr,
"Did you mean --provider instead of --providr?",
"models list did not suggest its own --provider",
);
const otherCommand = await runCLI(["models", "list", "--temprature", "1"]);
assert(otherCommand.exitCode !== 0, "a generate-only flag was accepted");
assert(
!otherCommand.stderr.includes("Did you mean"),
"models list suggested a flag it does not have",
);
});

await test("a name far from every flag gets no suggestion", async () => {
const result = await runCLI(["generate", "hi", "--zzzzzzzz"]);
assert(result.exitCode !== 0, "an unknown flag did not fail the command");
assert(
!result.stderr.includes("Did you mean"),
"a suggestion was made for a name near no flag",
);
assertIncludes(result.stderr, "Use --help to see available options.");
});

await runSuite();
33 changes: 33 additions & 0 deletions test/continuous-test-suite-hitl-documented-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,39 @@ await test("new NeuroLink prints one default-visible stderr line per unknown hit
assertEqual(clean.lines.filter((w) => w.includes("[HITL]")).length, 0);
});

await test("an unknown hitl key near a supported one suggests it; a planned key gets no suggestion", async () => {
const { lines } = captureStderr(
() =>
new NeuroLink({
hitl: {
enabled: true,
dangerousActions: ["delete"],
// @ts-expect-error -- typos of HITLConfig keys
timout: 5000,
autoApproveOnTimeOut: false,
requireApproval: ["writeFile"],
},
}),
);
const lineFor = (key: string): string =>
lines.find((w) => w.includes("[HITL]") && w.includes(`"${key}" is`)) ?? "";
assertIncludes(
lineFor("timout"),
'Did you mean "timeout"?',
"a one-letter typo did not suggest timeout",
);
assertIncludes(
lineFor("autoApproveOnTimeOut"),
'Did you mean "autoApproveOnTimeout"?',
"a casing typo did not suggest autoApproveOnTimeout",
);
assert(
lineFor("requireApproval") !== "" &&
!lineFor("requireApproval").includes("Did you mean"),
"requireApproval was missing or got a suggestion",
);
});

await test("every documented hitl key, including confirmDirectToolCalls, constructs without a warning", async () => {
const documented = captureStderr(
() =>
Expand Down
Loading