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
9 changes: 9 additions & 0 deletions .changeset/command-not-found-suggestions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"browse": patch
---

Add did-you-mean suggestions and telemetry for unknown commands.

- Unknown commands (e.g. `browse sessions`, `browse search`, `browse auth status` — old Commander-era syntax — plus plain typos like `browse opne`) now print an actionable suggestion on stderr: an explicit alias table maps old syntax to the current command tree, with a Levenshtein nearest-match fallback for typos. The clause is omitted when there is no decent match.
- A new `cli.command_not_found` telemetry event makes this failure class measurable. Privacy: only the sanitized attempted command id and the computed suggestion are sent — never raw argv, which can contain URLs, selectors, or secrets.
- oclif's standard "command not found" error and exit code 2 are preserved; no new runtime dependency (deliberately avoids `@oclif/plugin-not-found`, which prompts interactively and is agent-hostile).
4 changes: 3 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"hooks": {
"init": "./dist/hooks/init.js",
"prerun": "./dist/hooks/prerun.js",
"finally": "./dist/hooks/finally.js"
"finally": "./dist/hooks/finally.js",
"command_not_found": "./dist/hooks/command-not-found.js"
},
"topicSeparator": " ",
"topics": {
Expand Down Expand Up @@ -107,6 +108,7 @@
"archiver": "^7.0.1",
"deepmerge": "^4.3.1",
"dotenv": "^16.5.0",
"fastest-levenshtein": "^1.0.16",
"ignore": "^7.0.5",
"node-html-markdown": "^1.3.0",
"semver": "^7.7.4",
Expand Down
55 changes: 55 additions & 0 deletions packages/cli/src/hooks/command-not-found.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Errors, type Hook } from "@oclif/core";

import { suggestCommand } from "../lib/command-suggestions.js";
import { captureCommandNotFound } from "../lib/telemetry.js";

function toSpaced(commandId: string): string {
return commandId.replaceAll(":", " ");
}

const hook: Hook.CommandNotFound = async function ({ config, id }) {
let attempted = "";
let suggestion: string | null = null;

try {
const commandIds = config.commands
.filter((command) => !command.hidden)
.map((command) => command.id);
const result = suggestCommand(id, commandIds);
attempted = result.attempted;
suggestion = result.suggestion;
if (
suggestion &&
!config.findCommand(suggestion) &&
!config.findTopic(suggestion)
) {
// Guards against alias targets drifting out of the command tree.
suggestion = null;
}

const displayAttempted = toSpaced(attempted || (id.split(":")[0] ?? id));
const didYouMean = suggestion
? ` Did you mean "${config.bin} ${toSpaced(suggestion)}"?`
: "";
process.stderr.write(
`"${config.bin} ${displayAttempted}" is not a ${config.bin} command.${didYouMean} Run ${config.bin} --help for all commands.\n`,
);
} catch {
// Suggestions are best-effort and must never mask the not-found error.
}

try {
// Awaited so the event is delivered before the process exits; the
// transport aborts after a short timeout, so this cannot hang the CLI.
await captureCommandNotFound(config.version, attempted || null, suggestion);
} catch {
// Best-effort telemetry should never affect CLI behavior.
}

// Re-throw oclif's standard not-found error. Returning normally from a
// command_not_found hook makes oclif treat the invocation as handled
// (exit 0), so this throw preserves the default error and exit code 2.
throw new Errors.CLIError(`command ${id} not found`);
};

export default hook;
138 changes: 138 additions & 0 deletions packages/cli/src/lib/command-suggestions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/**
* Suggestion engine for unknown commands.
*
* oclif's spaced-topic parsing glues unknown leading argv tokens into the
* attempted command id (e.g. `browse opne https://example.com` arrives as
* `opne:https://example.com`), so the id may contain user-provided values.
* Everything here works on a sanitized token prefix and never returns raw
* argv content beyond the tokens that matched a known command shape.
*/

import { distance } from "fastest-levenshtein";

/**
* Old Commander-era syntax (and common agent guesses) mapped to the current
* command tree. Keys and values are colon-separated oclif ids; values may
* also be topics (e.g. `cloud:contexts`, which prints topic help).
*/
export const aliasSuggestions: ReadonlyMap<string, string> = new Map([
["sessions", "cloud:sessions:list"],
["sessions:list", "cloud:sessions:list"],
["sessions:create", "cloud:sessions:create"],
["sessions:get", "cloud:sessions:get"],
["projects", "cloud:projects:list"],
["projects:list", "cloud:projects:list"],
["contexts", "cloud:contexts"],
["extensions", "cloud:extensions"],
["search", "cloud:search"],
["fetch", "cloud:fetch"],
["goto", "open"],
["navigate", "open"],
]);

const safeTokenPattern = /^[A-Za-z][A-Za-z0-9_-]*$/;
const maxCommandTokens = 4;
const maxSuggestionDistance = 5;

export interface CommandSuggestion {
/** Sanitized colon-separated tokens treated as the attempted command. */
attempted: string;
/** Colon-separated suggested command or topic, when a decent match exists. */
suggestion: string | null;
}

/**
* Extracts the leading command-shaped tokens from an attempted id, stopping
* at the first token that does not look like a command word (URLs, selectors,
* flags, and other argument-like values).
*/
export function extractCommandTokens(id: string): string[] {
const tokens: string[] = [];
for (const token of id.split(":")) {
if (tokens.length >= maxCommandTokens || !safeTokenPattern.test(token)) {
break;
}
tokens.push(token.toLowerCase());
}
return tokens;
}

function tokenThreshold(token: string): number {
return Math.max(2, Math.floor(token.length / 3));
}

/**
* Segment-aligned fuzzy distance between a token prefix and a command id.
* Only command ids with the same number of segments are considered, and every
* token must be within its own edit-distance threshold of the corresponding
* segment. This means a trailing token can only ever be retained in the
* attempted command when it itself looks like a typo of a real command
* segment — free-form user values can never ride along.
*/
function prefixDistance(
Comment thread
shrey150 marked this conversation as resolved.
tokens: readonly string[],
commandId: string,
): number | null {
const segments = commandId.split(":");
if (segments.length !== tokens.length) {
return null;
}

let total = 0;
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i] ?? "";
const segmentDistance = distance(token, segments[i] ?? "");
if (segmentDistance > tokenThreshold(token)) {
return null;
}
total += segmentDistance;
}

return total > maxSuggestionDistance ? null : total;
}

/**
* Computes a suggestion for an unknown command id. Explicit aliases win over
* fuzzy matches, and longer token prefixes win over shorter ones so that
* `auth status` resolves before `auth`. Returns only the matched prefix as
* `attempted` (or the first token when nothing matches) so user-provided
* values never escape into messaging or telemetry.
*/
export function suggestCommand(
id: string,
commandIds: readonly string[],
): CommandSuggestion {
const tokens = extractCommandTokens(id);
if (tokens.length === 0) {
return { attempted: "", suggestion: null };
}

for (let length = tokens.length; length >= 1; length--) {
const attempted = tokens.slice(0, length).join(":");
const alias = aliasSuggestions.get(attempted);
if (alias) {
return { attempted, suggestion: alias };
}
}

let best: (CommandSuggestion & { distance: number }) | undefined;
for (let length = tokens.length; length >= 1; length--) {
const prefix = tokens.slice(0, length);
for (const commandId of commandIds) {
const prefixDist = prefixDistance(prefix, commandId);
if (prefixDist !== null && (!best || prefixDist < best.distance)) {
best = {
attempted: prefix.join(":"),
suggestion: commandId,
distance: prefixDist,
};
}
}
}

if (best) {
return { attempted: best.attempted, suggestion: best.suggestion };
}

return { attempted: tokens[0] ?? "", suggestion: null };
}
29 changes: 28 additions & 1 deletion packages/cli/src/lib/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ const browserbaseTelemetryProjectToken =
type TelemetryPrimitive = string | number | boolean | null;
type TelemetryProperties = Record<string, TelemetryPrimitive>;

type CliTelemetryEvent = "cli.command_invoked" | "cli.command_completed";
type CliTelemetryEvent =
| "cli.command_invoked"
| "cli.command_completed"
| "cli.command_not_found";
type CliTelemetryErrorType = "oclif" | "runtime";

interface CliTelemetry {
Expand Down Expand Up @@ -133,6 +136,30 @@ export async function captureCommandCompleted(
]);
}

/**
* Captures a `cli.command_not_found` event. Privacy: only the sanitized
* attempted command id and the computed suggestion are sent — never raw argv,
* which can contain URLs, selectors, or secrets.
*/
export async function captureCommandNotFound(
cliVersion: string,
attemptedCommand: string | null,
suggestedCommand: string | null,
): Promise<void> {
await getCliTelemetry(cliVersion)
.capture("cli.command_not_found", {
attempted_command: attemptedCommand
? resolveCommandPath(attemptedCommand)
: null,
suggested_command: suggestedCommand
? resolveCommandPath(suggestedCommand)
: null,
})
.catch(() => {
// Best-effort telemetry should never affect CLI behavior.
});
}

function createCliTelemetry(options: CreateCliTelemetryOptions): CliTelemetry {
const env = options.env ?? process.env;
const transport = resolveTransportConfig(env);
Expand Down
Loading
Loading