Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

[RSI] Reject slash-command typos with a suggested correction (#2243)

Seth Karten1fc1adb6e806
diff --git a/packages/coding-agent/.changes/eng-6102-slash-command-typo-guard.md b/packages/coding-agent/.changes/eng-6102-slash-command-typo-guard.md
new file mode 100644
index 0000000000..dda0759f2a
--- /dev/null
+++ b/packages/coding-agent/.changes/eng-6102-slash-command-typo-guard.md
@@ -0,0 +1 @@
+- Typo'd slash commands now fail fast with a suggested correction instead of being sent to the model as a prompt; genuine messages that merely start with a slash still pass through.
diff --git a/packages/coding-agent/src/cli/command-registry.ts b/packages/coding-agent/src/cli/command-registry.ts
index 6b48151ad4..706f03ffbf 100644
--- a/packages/coding-agent/src/cli/command-registry.ts
+++ b/packages/coding-agent/src/cli/command-registry.ts
@@ -1,4 +1,5 @@
import { APP_NAME } from "../config.js";
+import { findSlashCommandSuggestion } from "../core/slash-commands.js";
export interface CommandSpec {
path: readonly string[];
@@ -295,17 +296,7 @@ export function isHelpCommandRequest(path: readonly string[]): boolean {
}
export function findCommandSuggestion(input: string, candidates: readonly string[]): string | undefined {
- let closest: { candidate: string; distance: number } | undefined;
- for (const candidate of candidates) {
- const distance = editDistance(input, candidate);
- if (!closest || distance < closest.distance) {
- closest = { candidate, distance };
- }
- }
- if (!closest || closest.distance > Math.max(2, Math.floor(input.length / 3))) {
- return undefined;
- }
- return closest.candidate;
+ return findSlashCommandSuggestion(input, candidates);
}
export function formatTopLevelHelp(): string {
@@ -358,21 +349,3 @@ export function formatCommandHelp(path: readonly string[]): string | undefined {
}
return sections.join("\n");
}
-
-function editDistance(left: string, right: string): number {
- const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
- for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {
- let diagonal = previous[0]!;
- previous[0] = leftIndex;
- for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {
- const above = previous[rightIndex]!;
- previous[rightIndex] = Math.min(
- previous[rightIndex]! + 1,
- previous[rightIndex - 1]! + 1,
- diagonal + (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),
- );
- diagonal = above;
- }
- }
- return previous[right.length]!;
-}
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index ba3df77b31..d5351155ae 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -314,9 +314,13 @@ import type { SessionStats } from "./session-stats.js";
import type { SettingsManager } from "./settings-manager.js";
import { getPythonSkillRuntimeInfo, type Skill } from "./skills.js";
import {
+ BUILTIN_SLASH_COMMANDS,
+ findSlashCommandSuggestion,
+ isBuiltinSlashCommandName,
parseRefineCommandOptions,
parseSessionSlashCommand,
parseSlashCommand,
+ SESSION_SLASH_COMMAND_NAMES,
type SessionSlashCommand,
type SlashCommandInfo,
} from "./slash-commands.js";
@@ -4976,6 +4980,7 @@ export class AgentSession {
images: ImageContent[] | undefined,
policy: SubmissionNormalizationPolicy,
): NormalizedSubmission {
+ if (policy.expandPromptTemplates) this._throwIfUnknownSlashCommand(text);
let expandedText = text;
if (policy.expandSkills) expandedText = this._expandSkillCommand(expandedText);
if (policy.expandPromptTemplates) {
@@ -4984,6 +4989,40 @@ export class AgentSession {
return { kind: "prompt", text: expandedText, images };
}
+ /**
+ * Reject slash-command typos before they burn a model round trip and
+ * pollute the transcript. Only fires when a registered command name is
+ * close enough to be the intended one; anything else passes through so
+ * genuine prompts that merely start with "/" keep working.
+ */
+ private _throwIfUnknownSlashCommand(text: string): void {
+ const parsed = parseSlashCommand(text);
+ if (!parsed) return;
+ // No registered command name is anywhere near this long; oversized
+ // /-prefixed inputs are prompts, and fuzzy-matching them would be
+ // quadratic work on the event loop.
+ if (parsed.name.length > 64) return;
+ if (isBuiltinSlashCommandName(parsed.name)) return;
+ if (this.promptTemplates.some((template) => template.name === parsed.name)) return;
+ if (
+ parsed.name.startsWith("skill:") &&
+ this.resourceLoader.getSkills().skills.some((skill) => skill.name === parsed.name.slice("skill:".length))
+ ) {
+ return;
+ }
+ const skills = this.resourceLoader.getSkills().skills.map((skill) => skill.name);
+ const candidates = [
+ ...BUILTIN_SLASH_COMMANDS.flatMap((command) => [command.name, ...(command.aliases ?? [])]),
+ ...SESSION_SLASH_COMMAND_NAMES,
+ ...this.promptTemplates.map((template) => template.name),
+ ...this._extensionRunner.getRegisteredCommands().map((command) => command.invocationName),
+ ...skills.map((skill) => `skill:${skill}`),
+ ];
+ const suggestion = findSlashCommandSuggestion(parsed.name, candidates);
+ if (!suggestion) return;
+ throw new Error(`Unknown command: /${parsed.name}. Did you mean /${suggestion}?`);
+ }
+
private _normalizeSubmission(
text: string,
images: ImageContent[] | undefined,
diff --git a/packages/coding-agent/src/core/slash-commands.ts b/packages/coding-agent/src/core/slash-commands.ts
index d5916f4ea8..c1707bd0de 100644
--- a/packages/coding-agent/src/core/slash-commands.ts
+++ b/packages/coding-agent/src/core/slash-commands.ts
@@ -280,3 +280,44 @@ export function parseSessionSlashCommand(text: string): SessionSlashCommand | un
if (command?.execution !== "session" || !isSessionSlashCommandName(name)) return undefined;
return { name, args: parsed.args, text };
}
+
+/**
+ * Closest command-name suggestion for an unrecognized slash command, or
+ * undefined when nothing is near enough. Shared by the CLI's unknown-
+ * command notice and the session's typo guard.
+ */
+export function findSlashCommandSuggestion(input: string, candidates: readonly string[]): string | undefined {
+ let closest: { candidate: string; distance: number } | undefined;
+ for (const candidate of candidates) {
+ const distance = slashCommandEditDistance(input, candidate);
+ if (!closest || distance < closest.distance) {
+ closest = { candidate, distance };
+ }
+ }
+ // Very short tokens match only on a single-character typo: two-character
+ // tolerance on a three-character token lets unrelated path-like words
+ // (tmp vs mcp) masquerade as command typos.
+ const threshold = input.length <= 3 ? 1 : Math.max(2, Math.floor(input.length / 3));
+ if (!closest || closest.distance > threshold) {
+ return undefined;
+ }
+ return closest.candidate;
+}
+
+function slashCommandEditDistance(left: string, right: string): number {
+ const previous = new Array<number>(right.length + 1);
+ const current = new Array<number>(right.length + 1);
+ for (let j = 0; j <= right.length; j++) previous[j] = j;
+ for (let i = 1; i <= left.length; i++) {
+ current[0] = i;
+ for (let j = 1; j <= right.length; j++) {
+ current[j] = Math.min(
+ previous[j] + 1,
+ current[j - 1] + 1,
+ previous[j - 1] + (left[i - 1] === right[j - 1] ? 0 : 1),
+ );
+ }
+ for (let j = 0; j <= right.length; j++) previous[j] = current[j];
+ }
+ return previous[right.length];
+}
diff --git a/packages/coding-agent/test/agent-session-slash-guard.test.ts b/packages/coding-agent/test/agent-session-slash-guard.test.ts
new file mode 100644
index 0000000000..a0b3668536
--- /dev/null
+++ b/packages/coding-agent/test/agent-session-slash-guard.test.ts
@@ -0,0 +1,282 @@
+import { mkdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Agent, type StreamFn } from "@earendil-works/pi-agent-core";
+import { type Context, createAssistantMessageEventStream, getModel, type Usage } from "@earendil-works/pi-ai";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { AgentSession } from "../src/core/agent-session.js";
+import { AuthStorage } from "../src/core/auth-storage.js";
+import { convertToLlm } from "../src/core/messages.js";
+import { ModelRegistry } from "../src/core/model-registry.js";
+import type { PromptTemplate } from "../src/core/prompt-templates.js";
+import { createTestResourceLoader } from "./utilities.js";
+
+const model = getModel("anthropic", "claude-sonnet-4-5")!;
+
+function usage(): Usage {
+ return {
+ input: 7,
+ output: 3,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 10,
+ cost: { input: 7, output: 3, cacheRead: 0, cacheWrite: 0, total: 10 },
+ };
+}
+
+function lastUserText(context: Context): string {
+ for (let i = context.messages.length - 1; i >= 0; i--) {
+ const message = context.messages[i]!;
+ if (message.role === "user") {
+ return typeof message.content === "string"
+ ? message.content
+ : message.content
+ .filter((block): block is { type: "text"; text: string } => block.type === "text")
+ .map((block) => block.text)
+ .join(" ");
+ }
+ }
+ return "";
+}
+
+function makeSkill(name: string) {
+ return {
+ name,
+ description: `Test skill ${name}`,
+ filePath: `/tmp/skills/${name}/SKILL.md`,
+ baseDir: "/tmp/skills",
+ disableModelInvocation: false,
+ };
+}
+
+function makeTemplate(name: string): PromptTemplate {
+ return {
+ name,
+ description: `Test template ${name}`,
+ content: `TEMPLATE_BODY_${name.toUpperCase()}`,
+ sourceInfo: { source: "local", scope: "project", baseDir: "/tmp" } as PromptTemplate["sourceInfo"],
+ filePath: `/tmp/${name}.md`,
+ };
+}
+
+describe("AgentSession slash-command typo guard", () => {
+ let tempDir: string;
+ let prompts: PromptTemplate[];
+ let promptCalls: string[];
+
+ beforeEach(() => {
+ tempDir = join(tmpdir(), `pi-slash-guard-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(tempDir, { recursive: true });
+ prompts = [];
+ promptCalls = [];
+ });
+
+ afterEach(() => {
+ rmSync(tempDir, { recursive: true, force: true });
+ });
+
+ function createSession() {
+ const streamFn: StreamFn = (_model, context) => {
+ promptCalls.push(lastUserText(context));
+ const stream = createAssistantMessageEventStream();
+ queueMicrotask(() => {
+ stream.push({
+ type: "done",
+ reason: "stop",
+ message: {
+ role: "assistant",
+ content: [{ type: "text", text: "ok" }],
+ api: model.api,
+ provider: model.provider,
+ model: model.id,
+ usage: usage(),
+ stopReason: "stop",
+ timestamp: Date.now(),
+ },
+ });
+ });
+ return stream;
+ };
+ const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
+ authStorage.setRuntimeApiKey("anthropic", "test-key");
+ const agent = new Agent({
+ convertToLlm,
+ getApiKey: () => "test-key",
+ initialState: { model, systemPrompt: "", tools: [], thinkingLevel: "off" },
+ streamFn,
+ });
+ const resourceLoader = createTestResourceLoader();
+ const loader = resourceLoader as unknown as {
+ getPrompts: () => { prompts: PromptTemplate[]; diagnostics: unknown[] };
+ };
+ loader.getPrompts = () => ({ prompts, diagnostics: [] });
+ return { agent, resourceLoader };
+ }
+
+ it("rejects slash-command typos with a suggestion before any model call", async () => {
+ const { agent, resourceLoader } = createSession();
+ const authStorage = AuthStorage.create(join(tempDir, "auth2.json"));
+ authStorage.setRuntimeApiKey("anthropic", "test-key");
+ const { SessionManager } = await import("../src/core/session-manager.js");
+ const { SettingsManager } = await import("../src/core/settings-manager.js");
+ const session = new AgentSession({
+ agent,
+ sessionManager: SessionManager.create(tempDir, join(tempDir, "sessions")),
+ settingsManager: SettingsManager.create(tempDir, tempDir),
+ cwd: tempDir,
+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models.json")),
+ resourceLoader,
+ });
+ try {
+ await expect(session.prompt("/resuem")).rejects.toThrow("Unknown command: /resuem. Did you mean /resume?");
+ expect(promptCalls).toEqual([]);
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("passes through short path-like tokens that only weakly resemble a command", async () => {
+ const { agent, resourceLoader } = createSession();
+ const authStorage = AuthStorage.create(join(tempDir, "auth7.json"));
+ authStorage.setRuntimeApiKey("anthropic", "test-key");
+ const { SessionManager } = await import("../src/core/session-manager.js");
+ const { SettingsManager } = await import("../src/core/settings-manager.js");
+ const session = new AgentSession({
+ agent,
+ sessionManager: SessionManager.create(tempDir, join(tempDir, "sessions7")),
+ settingsManager: SettingsManager.create(tempDir, tempDir),
+ cwd: tempDir,
+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models7.json")),
+ resourceLoader,
+ });
+ try {
+ // "tmp" differs from "mcp" by two characters; short tokens only match
+ // on a single-character typo, so this prompt reaches the model.
+ await session.prompt("/tmp notes for the cleanup");
+ expect(promptCalls).toEqual(["/tmp notes for the cleanup"]);
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("still rejects single-character typos of short commands", async () => {
+ const { agent, resourceLoader } = createSession();
+ const authStorage = AuthStorage.create(join(tempDir, "auth8.json"));
+ authStorage.setRuntimeApiKey("anthropic", "test-key");
+ const { SessionManager } = await import("../src/core/session-manager.js");
+ const { SettingsManager } = await import("../src/core/settings-manager.js");
+ const session = new AgentSession({
+ agent,
+ sessionManager: SessionManager.create(tempDir, join(tempDir, "sessions8")),
+ settingsManager: SettingsManager.create(tempDir, tempDir),
+ cwd: tempDir,
+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models8.json")),
+ resourceLoader,
+ });
+ try {
+ // "log" is one insertion away from the /logs builtin.
+ await expect(session.prompt("/log rotate policies")).rejects.toThrow(
+ "Unknown command: /log. Did you mean /logs?",
+ );
+ expect(promptCalls).toEqual([]);
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("passes through slash-prefixed prompts without a near command match", async () => {
+ const { agent, resourceLoader } = createSession();
+ const authStorage = AuthStorage.create(join(tempDir, "auth3.json"));
+ authStorage.setRuntimeApiKey("anthropic", "test-key");
+ const { SessionManager } = await import("../src/core/session-manager.js");
+ const { SettingsManager } = await import("../src/core/settings-manager.js");
+ const session = new AgentSession({
+ agent,
+ sessionManager: SessionManager.create(tempDir, join(tempDir, "sessions2")),
+ settingsManager: SettingsManager.create(tempDir, tempDir),
+ cwd: tempDir,
+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models2.json")),
+ resourceLoader,
+ });
+ try {
+ await session.prompt("/etc/hosts is where hostname lookups start");
+ expect(promptCalls).toEqual(["/etc/hosts is where hostname lookups start"]);
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("suggests registered skills for typo'd skill commands", async () => {
+ const { agent, resourceLoader } = createSession();
+ const loader = resourceLoader as unknown as {
+ getSkills: () => { skills: ReturnType<typeof makeSkill>[]; diagnostics: unknown[] };
+ };
+ loader.getSkills = () => ({ skills: [makeSkill("python")], diagnostics: [] });
+ const authStorage = AuthStorage.create(join(tempDir, "auth5.json"));
+ authStorage.setRuntimeApiKey("anthropic", "test-key");
+ const { SessionManager } = await import("../src/core/session-manager.js");
+ const { SettingsManager } = await import("../src/core/settings-manager.js");
+ const session = new AgentSession({
+ agent,
+ sessionManager: SessionManager.create(tempDir, join(tempDir, "sessions5")),
+ settingsManager: SettingsManager.create(tempDir, tempDir),
+ cwd: tempDir,
+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models5.json")),
+ resourceLoader,
+ });
+ try {
+ await expect(session.prompt("/skill:pythno fix the bug")).rejects.toThrow(
+ "Unknown command: /skill:pythno. Did you mean /skill:python?",
+ );
+ expect(promptCalls).toEqual([]);
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("passes through oversized /-prefixed prompts without fuzzy matching", async () => {
+ const { agent, resourceLoader } = createSession();
+ const authStorage = AuthStorage.create(join(tempDir, "auth6.json"));
+ authStorage.setRuntimeApiKey("anthropic", "test-key");
+ const { SessionManager } = await import("../src/core/session-manager.js");
+ const { SettingsManager } = await import("../src/core/settings-manager.js");
+ const session = new AgentSession({
+ agent,
+ sessionManager: SessionManager.create(tempDir, join(tempDir, "sessions6")),
+ settingsManager: SettingsManager.create(tempDir, tempDir),
+ cwd: tempDir,
+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models6.json")),
+ resourceLoader,
+ });
+ try {
+ const longPath = `/very/long/${"a".repeat(500)}/path`;
+ await session.prompt(`${longPath} is the file to inspect`);
+ expect(promptCalls).toEqual([`${longPath} is the file to inspect`]);
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("expands registered templates instead of guarding them", async () => {
+ prompts.push(makeTemplate("worktree-check"));
+ const { agent, resourceLoader } = createSession();
+ const authStorage = AuthStorage.create(join(tempDir, "auth4.json"));
+ authStorage.setRuntimeApiKey("anthropic", "test-key");
+ const { SessionManager } = await import("../src/core/session-manager.js");
+ const { SettingsManager } = await import("../src/core/settings-manager.js");
+ const session = new AgentSession({
+ agent,
+ sessionManager: SessionManager.create(tempDir, join(tempDir, "sessions3")),
+ settingsManager: SettingsManager.create(tempDir, tempDir),
+ cwd: tempDir,
+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models3.json")),
+ resourceLoader,
+ });
+ try {
+ await session.prompt("/worktree-check");
+ expect(promptCalls).toEqual(["TEMPLATE_BODY_WORKTREE-CHECK"]);
+ } finally {
+ session.dispose();
+ }
+ });
+});