Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(commands): 20 commands, enforced read-only, and they work in Agent too

purple71cf14f6d262
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index e265630e..6a59411b 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -261,7 +261,7 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApp
{cmdMenu.length > 0 && (
<div className="absolute bottom-full left-0 right-0 mb-1.5 z-50 max-h-64 overflow-y-auto scrollbar-thin rounded-lg border border-gray-200 dark:border-white/10 bg-white dark:bg-[#1f1f1f] shadow-xl py-1">
<div className="px-2.5 py-1 flex items-center gap-1 text-[0.5rem] uppercase tracking-widest text-gray-400 dark:text-gray-600">
- <Terminal size={9} /> Coding commands
+ <Terminal size={9} /> Agent commands
</div>
{cmdMenu.map((cmd, i) => (
<button
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsx
index 98208827..ebee4d04 100644
--- a/src/components/chat/ChatView.tsx
+++ b/src/components/chat/ChatView.tsx
@@ -333,6 +333,9 @@ export function ChatView() {
pendingApproval={pendingApproval}
onApprove={approveToolCall}
onReject={rejectToolCall}
+ // Commands need the tool catalog to drive, which only Agent
+ // mode has here. Plain chat leaves "/cmd" as ordinary text.
+ slashCommands={isAgentActive}
onAttachDocs={appMode !== 'cloud' ? () => setRagPanelOpen(true) : undefined}
composerModel={<ModelSelector openUpward />}
composerActions={
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 6556eda5..3c953269 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -38,6 +38,7 @@ import { useAgentWorkflowStore } from '../stores/agentWorkflowStore'
import { WorkflowEngine } from '../lib/workflow-engine'
import type { AgentBlock, AgentToolCall, OllamaChatMessage } from '../types/agent-mode'
import { selectRelevantToolsAsync } from '../lib/tool-selection'
+import { MUTATING_TOOLS } from '../lib/mutating-tools'
import { generateEmbeddings } from '../api/rag'
import { truncateToolResult } from '../lib/truncate-tool-result'
import { budgetFromSettings } from '../api/agents/budget'
@@ -177,6 +178,10 @@ export function useAgentChat() {
curatedTools?: readonly string[]
chatToolsMode?: boolean
displayContent?: string
+ // A read-only slash command (/review, /plan, /diff, …). Strips the
+ // mutating tools for this turn so the command cannot do what it just
+ // told the user it would not do.
+ readOnly?: boolean
// Chat-tools router hint (David 2026-06-20): when a bare follow-up like
// "nochmal"/"ok generiere jetzt" continues an in-progress media task, the
// router passes the task kind + the prior generation's exact args so a weak
@@ -435,7 +440,8 @@ export function useAgentChat() {
// model in plain chat only ever sees the 5 chat tools (and small models
// aren't drowned in the full ~24-tool set).
const curated = opts?.curatedTools
- const toolMatchesCurated = (name: string) => !curated || curated.includes(name)
+ const toolMatchesCurated = (name: string) =>
+ (!curated || curated.includes(name)) && !(opts?.readOnly && MUTATING_TOOLS.has(name))
// Build agent system prompt FIRST, then append caveman style as a modifier
const hermesToolDefs = toolRegistry.toHermesToolDefs(permissions)
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 8b86fc4b..58bfb630 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -13,6 +13,7 @@ import { getModelContextCached } from "../api/ollama"
import { requestGenerationCancel } from "../api/vram-handoff"
import { effectiveContextWindow } from "../lib/context-window"
import { useAgentChat } from "./useAgentChat"
+import { parseAgentCommand } from '../lib/agent-commands'
import { useMemory } from "./useMemory"
import { useAgentModeStore } from "../stores/agentModeStore"
import { useGenerationStore } from "../stores/generationStore"
@@ -66,14 +67,22 @@ export function useChat() {
const store = useChatStore.getState()
const persona = useSettingsStore.getState().getActivePersona()
- // NB: slash commands ("/review", "/commit", …) are NOT handled here — they
- // belong to the Coding Agent (Code view), not the normal chat/agent (David
- // 2026-06-12). useCodex.sendInstruction expands them there; in plain chat a
- // "/cmd" is just ordinary text. The normal Agent gets its own commands later
- // (slash loop / remember / scheduler).
-
- // Agent mode delegation: if active for this conversation, use agent chat
+ // Agent mode delegation: if active for this conversation, use agent chat.
+ //
+ // 2.5.9: slash commands work here too. They were Code-only, which meant the
+ // Agent — same tool catalog, same executor — could not use a single one of
+ // them. The expansion goes to the model, the raw "/cmd" stays on screen, and
+ // a read-only command has the mutating tools stripped for the turn exactly
+ // like it does in Code. In PLAIN chat (no agent mode) a "/cmd" is still just
+ // text: there is no tool catalog there for the templates to drive.
if (store.activeConversationId && useAgentModeStore.getState().isActive(store.activeConversationId)) {
+ const slash = parseAgentCommand(content)
+ if (slash) {
+ return agentChat.sendAgentMessage(slash.expanded, images, {
+ displayContent: content,
+ readOnly: slash.command.readOnly === true,
+ })
+ }
return agentChat.sendAgentMessage(content, images)
}
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 8a58c4b6..8171f482 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -9,6 +9,7 @@ import { markToolsUnsupported } from '../api/tool-capability'
import { toolRegistry } from '../api/mcp'
import { usePermissionStore } from '../stores/permissionStore'
import { toolStrategyFor } from '../lib/tool-support'
+import { MUTATING_TOOLS } from '../lib/mutating-tools'
import { CODEX_CONFIRM_TOOLS, codexConfirmEnabled } from './codexShellGate'
import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
import { chatNonStreaming } from '../api/agents'
@@ -60,7 +61,7 @@ function diagLog(_tag: string, _data: unknown): void {
// Review-mode system prompt (B13). In review mode this REPLACES the base
// CODEX_SYSTEM_PROMPT entirely — the autonomy/build contract is the wrong
// framing for a read-only reviewer and would fight the executor gate. The
-// list-stripping below (REVIEW_MODE_FORBIDDEN_TOOLS) still enforces
+// list-stripping below (MUTATING_TOOLS) still enforces
// read-only programmatically even if the model tries a write tool anyway.
const CODEX_REVIEW_SYSTEM_PROMPT = `You are the Coding Agent in REVIEW MODE, a read-only code reviewer inside LU. You DO NOT modify any files, run any commands, or change any state. Your job is to read code with file_read / file_list / file_search / git_diff / git_log and return INLINE COMMENTS only.
@@ -126,33 +127,6 @@ const streamWithTools = streamOllamaChatWithTools
// pure coding turns keep the same lean tool list as before.
const CODEX_CATEGORIES = ['filesystem', 'terminal', 'system', 'web', 'image', 'video'] as const
-// Tools blocked in Code-Review Mode (B13). The agent goes read-only —
-// it inspects the codebase and writes inline comments, but never
-// mutates the filesystem, the shell, or remote state. Anything that
-// could change a file, run a command, or push to git/GitHub goes here.
-// Read-only inspectors (git_status / git_log / git_diff, pr_resume,
-// shell_task_status / shell_task_list, file_read / file_list / file_search)
-// stay allowed so the agent can do its job.
-const REVIEW_MODE_FORBIDDEN_TOOLS = new Set([
- 'file_write',
- 'file_edit',
- 'shell_execute',
- 'code_execute',
- 'shell_execute_background',
- 'shell_task_kill',
- 'git_commit',
- 'git_push',
- 'project_init',
- 'gh_pr_create',
- 'run_tests',
- 'image_generate',
- 'video_generate',
- 'run_workflow',
- // Parity with uselu's review blocklist — a reviewer must not capture the
- // screen or hand work off to a sub-agent that could mutate state.
- 'screenshot',
- 'delegate_task',
-])
// `.lurules` reader. MUST go through `fs_read` (the workspace-aware command)
// with the run's chatId + workingDirectory — NOT the older `file_read`, which
@@ -232,6 +206,10 @@ export function useCodex() {
const slash = parseAgentCommand(rawInstruction)
const instruction = slash ? slash.expanded : rawInstruction
const displayInstruction = slash ? rawInstruction : opts?.displayContent
+ // `readOnly` used to be documentation. Now it strips the mutating tools for
+ // this turn, so /review and /security physically cannot rewrite the files
+ // they were asked to look at.
+ const readOnlyTurn = slash?.command.readOnly === true
const store = useChatStore.getState()
const codexStore = useCodexStore.getState()
@@ -299,6 +277,20 @@ export function useCodex() {
})
}
+ // Review Mode strips every mutating tool. A command whose whole job is to
+ // change something would then run to completion narrating work it could not
+ // do, with nothing on screen explaining why. Say it and stop.
+ if (settings.codexReviewMode && slash && !slash.command.readOnly) {
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(), role: 'user', content: rawInstruction, timestamp: Date.now(),
+ })
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(), role: 'assistant', timestamp: Date.now(),
+ content: `Review Mode is on, so I cannot write files or run commands, and /${slash.command.name} needs both. Turn Review Mode off in Settings, or use a read-only command such as /review, /plan, /diff or /explain.`,
+ })
+ return
+ }
+
// Add instruction event
codexStore.addEvent(convId, {
id: uuid(), type: 'instruction', content: instruction, timestamp: Date.now(),
@@ -364,7 +356,7 @@ export function useCodex() {
// System prompt with working directory. Review mode swaps the base
// prompt to lock the model into read-only behaviour — the
- // list-stripping below (REVIEW_MODE_FORBIDDEN_TOOLS) still enforces it
+ // list-stripping below (MUTATING_TOOLS) still enforces it
// programmatically even if the model tries to call a write tool anyway.
const reviewMode = settings.codexReviewMode === true
// Review mode always wins; otherwise Small-Model Mode swaps in the lean
@@ -430,7 +422,7 @@ export function useCodex() {
// Code-Review Mode (B13) — the dedicated CODEX_REVIEW_SYSTEM_PROMPT
// above already replaced the base prompt with the read-only contract,
// so no extra banner append is needed here. The list-stripping in the
- // tool-build path (REVIEW_MODE_FORBIDDEN_TOOLS) remains the
+ // tool-build path (MUTATING_TOOLS) remains the
// belt-and-braces programmatic guard.
// Caveman mode: append as response style modifier after Codex instructions
@@ -719,8 +711,12 @@ export function useCodex() {
// physically cannot fire them. Belt-and-braces with the
// system-prompt banner above — covers the case where the model
// ignores the instruction and tries anyway.
- const codexTools = settings.codexReviewMode
- ? codexToolsAll.filter((t) => !REVIEW_MODE_FORBIDDEN_TOOLS.has(t.name))
+ // Two reasons to strip the mutating tools: Code-Review Mode is on, or
+ // this turn was started by a read-only slash command. Belt-and-braces
+ // with the system prompt — covers the model ignoring the instruction
+ // and trying anyway.
+ const codexTools = (settings.codexReviewMode || readOnlyTurn)
+ ? codexToolsAll.filter((t) => !MUTATING_TOOLS.has(t.name))
: codexToolsAll
// Keep the tool list LEAN — exactly like the uselu reference. A small
// model (qwen2.5-coder:7b) handed the full ~24-tool category set every
@@ -930,7 +926,7 @@ export function useCodex() {
const def = toolRegistry.getToolByName(t.name)
if (!def) return true
if (!(CODEX_CATEGORIES as readonly string[]).includes(def.category)) return false
- if (settings.codexReviewMode && REVIEW_MODE_FORBIDDEN_TOOLS.has(t.name)) return false
+ if ((settings.codexReviewMode || readOnlyTurn) && MUTATING_TOOLS.has(t.name)) return false
return true
},
)
diff --git a/src/lib/__tests__/agent-commands.test.ts b/src/lib/__tests__/agent-commands.test.ts
index 5d28a320..bb2beeee 100644
--- a/src/lib/__tests__/agent-commands.test.ts
+++ b/src/lib/__tests__/agent-commands.test.ts
@@ -1,15 +1,28 @@
import { describe, it, expect } from 'vitest'
import {
AGENT_COMMANDS,
+ getAgentCommand,
parseAgentCommand,
matchAgentCommands,
} from '../agent-commands'
+import { MUTATING_TOOLS } from '../mutating-tools'
+
+// The 2.5.9 set. Kept as an explicit list rather than a count so a rename or an
+// accidental drop fails loudly instead of quietly changing a number.
+const EXPECTED = [
+ // understand
+ 'plan', 'explain', 'find', 'diff', 'log', 'todo',
+ // change
+ 'fix', 'types', 'test', 'refactor', 'clean', 'optimize',
+ // check
+ 'review', 'security', 'deps',
+ // ship
+ 'commit', 'pr', 'undo', 'docs', 'init',
+]
describe('AGENT_COMMANDS registry', () => {
- it('ships exactly the 10 named commands', () => {
- expect(AGENT_COMMANDS.map((c) => c.name).sort()).toEqual(
- ['commit', 'docs', 'explain', 'fix', 'init', 'optimize', 'refactor', 'review', 'security', 'test'].sort(),
- )
+ it('ships the expected command set', () => {
+ expect(AGENT_COMMANDS.map((c) => c.name).sort()).toEqual([...EXPECTED].sort())
})
it('every command has a summary and a non-empty expansion', () => {
@@ -25,12 +38,51 @@ describe('AGENT_COMMANDS registry', () => {
expect(new Set(names).size).toBe(names.length)
})
- it('read-only commands never instruct file_write in their template', () => {
+ it('every command tells the model to act via tools', () => {
+ for (const c of AGENT_COMMANDS) {
+ expect(c.build('')).toContain('Use your tools')
+ }
+ })
+
+ it('an argument the user typed always reaches the expansion', () => {
+ // A template that silently drops its args looks like it worked and does the
+ // wrong thing, which is worse than refusing.
+ const arg = 'src/hooks/useChat.ts'
+ for (const c of AGENT_COMMANDS) {
+ // /init takes no argument by design.
+ if (c.name === 'init') continue
+ expect(c.build(arg), `${c.name} dropped its argument`).toContain(arg)
+ }
+ })
+
+ it('read-only commands never name a mutating tool in their template', () => {
+ // The runner strips these tools for the turn, so a template that asks for
+ // one would be instructing the model to reach for something that is gone.
for (const c of AGENT_COMMANDS.filter((c) => c.readOnly)) {
- expect(c.build('x').toLowerCase()).toContain('read-only')
- expect(c.build('x')).not.toMatch(/\bfile_write\b/)
+ const text = c.build('x')
+ for (const tool of MUTATING_TOOLS) {
+ expect(text, `${c.name} names ${tool}`).not.toContain(tool)
+ }
}
})
+
+ it('read-only commands say up front that they cannot write or run', () => {
+ for (const c of AGENT_COMMANDS.filter((c) => c.readOnly)) {
+ expect(c.build('x')).toContain('no write or shell tools')
+ }
+ })
+
+ it('marks exactly the inspection commands read-only', () => {
+ expect(AGENT_COMMANDS.filter((c) => c.readOnly).map((c) => c.name).sort()).toEqual(
+ ['diff', 'explain', 'find', 'plan', 'review', 'security', 'todo'].sort(),
+ )
+ })
+
+ it('getAgentCommand looks up by name, case-insensitively', () => {
+ expect(getAgentCommand('review')?.name).toBe('review')
+ expect(getAgentCommand('REVIEW')?.name).toBe('review')
+ expect(getAgentCommand('nope')).toBeUndefined()
+ })
})
describe('parseAgentCommand', () => {
@@ -58,6 +110,10 @@ describe('parseAgentCommand', () => {
expect(r?.expanded).toContain('TypeError')
})
+ it('tolerates leading whitespace', () => {
+ expect(parseAgentCommand(' /review')?.command.name).toBe('review')
+ })
+
it('returns null for unknown commands so they fall through to chat', () => {
expect(parseAgentCommand('/notacommand do thing')).toBeNull()
expect(parseAgentCommand('/')).toBeNull()
@@ -72,19 +128,53 @@ describe('parseAgentCommand', () => {
it('commit template forbids pushing', () => {
expect(parseAgentCommand('/commit')?.expanded.toLowerCase()).toContain('do not push')
})
+
+ it('undo shows what would be lost before destroying it', () => {
+ const t = parseAgentCommand('/undo')!.expanded
+ expect(t).toContain('show the user exactly what would be lost')
+ expect(t.toLowerCase()).toContain('never rewrite published history')
+ })
+
+ it('pr does not silently sweep in uncommitted work', () => {
+ expect(parseAgentCommand('/pr')?.expanded).toContain('ask before including them')
+ })
+
+ it('deps reports without upgrading', () => {
+ expect(parseAgentCommand('/deps')?.expanded).toContain('Do NOT upgrade anything yet')
+ })
+
+ it('types refuses to silence errors quietly', () => {
+ const t = parseAgentCommand('/types')!.expanded
+ expect(t).toContain('never silence one with')
+ })
+
+ it('clean proves a symbol is unused before deleting it', () => {
+ expect(parseAgentCommand('/clean')?.expanded).toContain('Prove each one is unused')
+ })
+
+ it('plan stops at the plan', () => {
+ expect(parseAgentCommand('/plan add caching')?.expanded).toContain('Do not start implementing')
+ })
})
describe('matchAgentCommands (autocomplete)', () => {
- it('returns all commands for a lone slash', () => {
- expect(matchAgentCommands('/').length).toBe(10)
+ it('returns every command for a lone slash', () => {
+ expect(matchAgentCommands('/').length).toBe(AGENT_COMMANDS.length)
})
it('prefix-filters by name', () => {
expect(matchAgentCommands('/re').map((c) => c.name).sort()).toEqual(['refactor', 'review'])
expect(matchAgentCommands('/sec').map((c) => c.name)).toEqual(['security'])
+ expect(matchAgentCommands('/d').map((c) => c.name).sort()).toEqual(['deps', 'diff', 'docs'])
+ })
+
+ it('opens the menu even when the line starts with whitespace', () => {
+ // parseAgentCommand trimmed and matchAgentCommands did not, so hitting
+ // space first killed the menu while sending still expanded the command.
+ expect(matchAgentCommands(' /re').map((c) => c.name).sort()).toEqual(['refactor', 'review'])
})
- it('returns [] once the user has typed a space (now typing args, not picking)', () => {
+ it('closes once the user has typed a space (now typing args, not picking)', () => {
expect(matchAgentCommands('/review ')).toEqual([])
expect(matchAgentCommands('/review changes')).toEqual([])
})
diff --git a/src/lib/agent-commands.ts b/src/lib/agent-commands.ts
index a26b6af3..48ca9460 100644
--- a/src/lib/agent-commands.ts
+++ b/src/lib/agent-commands.ts
@@ -1,17 +1,23 @@
/**
- * Agent slash commands (v2.5.3, David 2026-06-11: "10 funktionelle slash
- * commands für den agent mode, guck dir die besten von claude code ab").
+ * Agent slash commands (v2.5.3, extended in 2.5.9).
*
- * Each command is a high-quality prompt template modeled on Claude Code's most
- * popular commands (/review, /commit, /test, /fix, /explain, /refactor, /docs,
- * /security, /optimize, /init). A slash command is shorthand for an AGENT task:
- * the chat hook expands it to the full instruction below, enables agent mode
- * for that conversation, and runs it through the normal agent executor (full
- * tool catalog — file_*, shell_execute, web_*, …). So the templates are written
- * for an agent that ACTS via tools, not one that describes.
+ * Each command is a high-quality prompt template. A slash command is shorthand
+ * for an AGENT task: the hook expands it to the full instruction below and runs
+ * it through the normal executor with the full tool catalog (file_*,
+ * shell_execute, git_*, web_*, …). So the templates are written for an agent
+ * that ACTS via tools, not one that describes.
+ *
+ * Because a command is only text, it works the same on every tool-calling
+ * schema — native function calling, the Hermes XML fallback, and the
+ * template-fix path all receive the identical expansion.
+ *
+ * `readOnly` is ENFORCED, not decorative: useCodex strips the mutating tools
+ * from the catalog for the turn a read-only command starts. Before 2.5.9 the
+ * flag existed but nothing read it, so /review and /security could and did
+ * rewrite files they were only meant to look at.
*
* Pure data + pure functions here — no React, no side effects — so it unit-tests
- * cleanly and the ChatInput autocomplete + the useChat router share one source.
+ * cleanly and the ChatInput autocomplete + the hooks share one source.
*/
export interface AgentCommand {
@@ -21,7 +27,13 @@ export interface AgentCommand {
summary: string
/** Argument hint shown after the name, e.g. "[file | \"changes\"]". */
argHint?: string
- /** True when the command is read-only (no file/shell mutations). */
+ /**
+ * True when the command must not touch anything. Enforced by the runner:
+ * file_write / file_edit / shell_execute / code_execute / run_tests /
+ * git_commit / git_push and the other mutating tools are removed from the
+ * catalog for that turn, and read-only shell inspection is still available
+ * through the read tools.
+ */
readOnly?: boolean
/** Expand to the full agent instruction. `args` is the trimmed text after the command. */
build: (args: string) => string
@@ -30,52 +42,99 @@ export interface AgentCommand {
/** Shared closing line so every command nudges the agent to act, not narrate. */
const ACT = 'Use your tools to do this for real — do not just describe the steps. Be concise in text; the work happens in tool calls. Reply in the user\'s language.'
+/** Read-only commands cannot run shell, so they must be told how to look. */
+const LOOK = 'Read the real code with file_read / file_list / file_search first — never answer from memory. You have no write or shell tools on this turn, so do not plan to use them.'
+
export const AGENT_COMMANDS: AgentCommand[] = [
+ // ── Understand ────────────────────────────────────────────────────────
{
- name: 'review',
- summary: 'Review code for bugs, security and style',
- argHint: '[file | "changes"]',
+ name: 'plan',
+ summary: 'Work out the steps before changing anything',
+ argHint: '<what you want done>',
readOnly: true,
build: (a) => {
- const target = a.trim() || 'the current uncommitted changes (use shell_execute "git diff" / "git status"; if not a git repo, review the most relevant source files)'
- return `Do a focused code review of ${target}. Read the actual code with file_read / file_list first — never review from memory. Report findings grouped by severity (Critical / Major / Minor), each with the file:line, what's wrong, and a concrete fix. Cover correctness/bugs, security, error handling, and clarity. This is a READ-ONLY review — do not modify files. End with a one-line verdict. ${ACT}`
+ const goal = a.trim() || 'the task the user just described'
+ return `Produce a concrete plan for: ${goal}. ${LOOK} Then give: the files that actually need to change and why each one, the order to do them in, the one risk most likely to bite, and how you would know it worked. Keep it to the steps a person would follow, no padding. Do not start implementing — this is the plan only. ${ACT}`
},
},
{
- name: 'commit',
- summary: 'Stage changes and write a clean git commit',
- argHint: '[message hint]',
+ name: 'explain',
+ summary: 'Explain how a file, function or the codebase works',
+ argHint: '<file | function | topic>',
+ readOnly: true,
build: (a) => {
- const hint = a.trim() ? `\nThe user suggests this focus for the message: "${a.trim()}".` : ''
- return `Create a git commit for the current changes. Steps, each as a real tool call: 1) "git status" and "git diff" to see what changed. 2) Group the changes and stage the right files ("git add"). 3) Write a clear Conventional-Commits message (type(scope): summary, then a short body explaining WHY). 4) Commit. 5) Show the resulting "git log -1 --stat".${hint} Do NOT push. If this is not a git repository, say so and stop. ${ACT}`
+ const what = a.trim() || 'this project: scan the structure with file_list and read the entry points'
+ return `Explain ${what}. ${LOOK} Give: a one-paragraph overview, then the key pieces (what each does and how they connect), the important data flow or control flow, and any non-obvious gotchas. Use short concrete references like file:line. ${ACT}`
},
},
{
- name: 'test',
- summary: 'Find, run and report the project tests',
- argHint: '[file | pattern]',
+ name: 'find',
+ summary: 'Locate where something is implemented',
+ argHint: '<symbol | behaviour | string>',
+ readOnly: true,
build: (a) => {
- const scope = a.trim() ? `Focus on tests matching "${a.trim()}".` : 'Run the most relevant test suite.'
- return `Run the project's tests and report the result. 1) Detect the test runner (look for package.json scripts, pytest, cargo test, go test, etc. via file_read / file_list). 2) ${scope} Run it with shell_execute. 3) Summarize pass/fail counts and quote the first few real failures with their file:line. 4) If a failure has an obvious, low-risk fix, apply it and re-run to confirm; otherwise just report it. ${ACT}`
+ const what = a.trim() || 'the thing the user just asked about'
+ return `Find where ${what} lives in this codebase. Use file_search for the obvious spellings, then widen: the same idea under a different name, the call sites, the tests that cover it, and the config that switches it on. ${LOOK} Report the definition first with its file:line, then the call sites, then anything closely related worth knowing. If it does not exist here, say so plainly rather than guessing at the nearest match. ${ACT}`
+ },
+ },
+ {
+ name: 'diff',
+ summary: 'Show and explain what changed',
+ argHint: '[file | ref]',
+ readOnly: true,
+ build: (a) => {
+ const scope = a.trim()
+ ? `the changes in "${a.trim()}"`
+ : 'the current uncommitted changes'
+ return `Explain ${scope}. Read the changed files with file_read and work out what actually changed and why it matters. ${LOOK} Group by intent, not by file: what behaviour is different now, what is pure refactor, what looks accidental. Flag anything that looks unintentional — a stray debug line, a commented-out block, a changed default. End with one line on whether this is safe to commit. ${ACT}`
+ },
+ },
+ {
+ name: 'log',
+ summary: 'Summarize what happened recently in this repo',
+ argHint: '[count | path]',
+ build: (a) => {
+ const scope = a.trim() ? `Focus on "${a.trim()}".` : 'Look at roughly the last 20 commits.'
+ return `Summarize this repository's recent history. Run "git log" with a useful format via shell_execute (include stat so you can see scale). ${scope} Report: the themes of the work, which areas of the codebase moved most, anything that looks like a revert or a hotfix, and the current branch state versus its upstream. If this is not a git repository, say so and stop. ${ACT}`
+ },
+ },
+ {
+ name: 'todo',
+ summary: 'Find and triage TODO, FIXME and HACK markers',
+ argHint: '[path]',
+ readOnly: true,
+ build: (a) => {
+ const scope = a.trim() ? `under "${a.trim()}"` : 'across the project'
+ return `Find every TODO, FIXME, HACK and XXX marker ${scope} with file_search, then read enough around each one to judge it. ${LOOK} Report them grouped: still relevant and worth doing, already done and safe to delete, and vague notes that need their author. Give each a file:line and one line on what it would take. Put the ones that are actually load-bearing first. ${ACT}`
},
},
+
+ // ── Change ────────────────────────────────────────────────────────────
{
name: 'fix',
summary: 'Diagnose and fix a bug or failing test end-to-end',
argHint: '<error text | file>',
build: (a) => {
const what = a.trim() || 'the failing test or error in the current project (run the tests / build to surface it first)'
- return `Diagnose and fix: ${what}. 1) Reproduce — run the test/build/command that fails and read the real error. 2) Locate the root cause with file_search / file_read (fix the cause, not the symptom). 3) Apply the minimal correct fix with file_write. 4) Re-run to prove it's fixed. 5) Briefly state the root cause and the fix. ${ACT}`
+ return `Diagnose and fix: ${what}. 1) Reproduce — run the test/build/command that fails and read the real error. 2) Locate the root cause with file_search / file_read (fix the cause, not the symptom). 3) Apply the minimal correct fix with file_edit. 4) Re-run to prove it's fixed. 5) Briefly state the root cause and the fix. ${ACT}`
},
},
{
- name: 'explain',
- summary: 'Explain how a file, function or the codebase works',
- argHint: '<file | function | topic>',
- readOnly: true,
+ name: 'types',
+ summary: 'Fix type or compile errors until the build is clean',
+ argHint: '[file | package]',
build: (a) => {
- const what = a.trim() || 'this project: scan the structure with file_list and read the entry points'
- return `Explain ${what}. Read the actual code first (file_read / file_list / file_search) — do not guess. Give: a one-paragraph overview, then the key pieces (what each does and how they connect), the important data flow or control flow, and any non-obvious gotchas. Use short concrete references like file:line. This is read-only — do not modify anything. ${ACT}`
+ const scope = a.trim() ? `Start with "${a.trim()}".` : 'Start with whatever the checker reports first.'
+ return `Get this project type-checking or compiling cleanly. 1) Find the right checker and run it via shell_execute (tsc --noEmit, mypy, cargo check, go build — whatever this project actually uses; read package.json / the build config first). 2) ${scope} 3) Fix the real cause of each error with file_edit — never silence one with "any", a blanket ignore comment, or a cast, unless you explain in the summary why nothing else was possible. 4) Re-run the checker until it is clean or only pre-existing unrelated errors remain. 5) Report what you fixed and what you deliberately left. ${ACT}`
+ },
+ },
+ {
+ name: 'test',
+ summary: 'Find, run and report the project tests',
+ argHint: '[file | pattern]',
+ build: (a) => {
+ const scope = a.trim() ? `Focus on tests matching "${a.trim()}".` : 'Run the most relevant test suite.'
+ return `Run the project's tests and report the result. 1) Detect the test runner (look for package.json scripts, pytest, cargo test, go test, etc. via file_read / file_list). 2) ${scope} Run it with shell_execute. 3) Summarize pass/fail counts and quote the first few real failures with their file:line. 4) If a failure has an obvious, low-risk fix, apply it and re-run to confirm; otherwise just report it. ${ACT}`
},
},
{
@@ -84,18 +143,37 @@ export const AGENT_COMMANDS: AgentCommand[] = [
argHint: '<file | function>',
build: (a) => {
const what = a.trim() || 'the file the user is focused on (ask which if it is unclear)'
- return `Refactor ${what} to improve readability and structure WITHOUT changing its observable behavior. 1) Read it fully first. 2) Make the change with file_write — improve names, remove duplication, simplify control flow, tighten types; keep the public API identical. 3) If tests exist, run them to prove behavior is unchanged. 4) Summarize what you changed and why. Do not mix in unrelated changes. ${ACT}`
+ return `Refactor ${what} to improve readability and structure WITHOUT changing its observable behavior. 1) Read it fully first. 2) Make the change with file_edit — improve names, remove duplication, simplify control flow, tighten types; keep the public API identical. 3) If tests exist, run them to prove behavior is unchanged. 4) Summarize what you changed and why. Do not mix in unrelated changes. ${ACT}`
},
},
{
- name: 'docs',
- summary: 'Generate or update documentation',
- argHint: '[file | "readme"]',
+ name: 'clean',
+ summary: 'Remove dead code, unused imports and leftovers',
+ argHint: '[file | path]',
build: (a) => {
- const target = a.trim()
- ? `documentation for "${a.trim()}"`
- : 'the project README (create or update README.md)'
- return `Write or update ${target}. Read the real code first so the docs are accurate. For a README: a clear title + one-line description, install/setup, usage with a runnable example, and key features — match the project's actual stack. For a file/module: concise doc-comments on the public functions. Write the file(s) with file_write. Keep it accurate and skimmable, no filler. ${ACT}`
+ const scope = a.trim() || 'the files the user has been working in (identify them from git status if this is a repo)'
+ return `Clean up ${scope}. Look for: unused imports, unreachable code, functions and constants nothing references, commented-out blocks, stray debug logging, and files nothing imports. Prove each one is unused with file_search BEFORE deleting it — a dynamic import, a string-keyed lookup or a test can be the only reference. Remove them with file_edit, then run the tests and the type checker to show nothing broke. List everything you removed and everything you suspected but left, with the reason. ${ACT}`
+ },
+ },
+ {
+ name: 'optimize',
+ summary: 'Find and apply performance improvements',
+ argHint: '<file | function>',
+ build: (a) => {
+ const what = a.trim() || 'the hottest path in the current project (identify it first by reading the code)'
+ return `Optimize the performance of ${what}. 1) Read it and identify the real bottleneck (algorithmic complexity, redundant work, N+1 calls, unnecessary allocations, blocking I/O) — measure with a quick benchmark via shell_execute if feasible. 2) Apply the highest-impact change with file_edit, preserving behavior. 3) Verify correctness (run tests if present) and, if you benchmarked, report before/after. Don't micro-optimize cold paths. ${ACT}`
+ },
+ },
+
+ // ── Check ─────────────────────────────────────────────────────────────
+ {
+ name: 'review',
+ summary: 'Review code for bugs, security and style',
+ argHint: '[file | "changes"]',
+ readOnly: true,
+ build: (a) => {
+ const target = a.trim() || 'the current uncommitted changes (read the changed files directly; if this is not a repo, review the most relevant source files)'
+ return `Do a focused code review of ${target}. ${LOOK} Report findings grouped by severity (Critical / Major / Minor), each with the file:line, what's wrong, and a concrete fix. Cover correctness/bugs, security, error handling, and clarity. End with a one-line verdict. ${ACT}`
},
},
{
@@ -105,16 +183,56 @@ export const AGENT_COMMANDS: AgentCommand[] = [
readOnly: true,
build: (a) => {
const scope = a.trim() || 'the project (scan the most security-relevant files: auth, input handling, file/network/shell access, secrets, dependencies)'
- return `Do a security audit of ${scope}. Read the real code with file_read / file_search. Look for: injection (SQL/command/path), unsafe input handling, auth/authorization gaps, SSRF, secrets committed in code, unsafe deserialization, and risky dependencies. Report each finding with severity (Critical/High/Medium/Low), the file:line, why it's exploitable, and the fix. READ-ONLY — do not modify files. If you find nothing serious, say so honestly. ${ACT}`
+ return `Do a security audit of ${scope}. ${LOOK} Look for: injection (SQL/command/path), unsafe input handling, auth/authorization gaps, SSRF, secrets committed in code, unsafe deserialization, and risky dependencies. Report each finding with severity (Critical/High/Medium/Low), the file:line, why it's exploitable, and the fix. If you find nothing serious, say so honestly rather than padding the list. ${ACT}`
},
},
{
- name: 'optimize',
- summary: 'Find and apply performance improvements',
- argHint: '<file | function>',
+ name: 'deps',
+ summary: 'Audit dependencies — outdated, unused, risky',
+ argHint: '[package]',
build: (a) => {
- const what = a.trim() || 'the hottest path in the current project (identify it first by reading the code)'
- return `Optimize the performance of ${what}. 1) Read it and identify the real bottleneck (algorithmic complexity, redundant work, N+1 calls, unnecessary allocations, blocking I/O) — measure with a quick benchmark via shell_execute if feasible. 2) Apply the highest-impact change with file_write, preserving behavior. 3) Verify correctness (run tests if present) and, if you benchmarked, report before/after. Don't micro-optimize cold paths. ${ACT}`
+ const focus = a.trim() ? `Pay particular attention to "${a.trim()}".` : ''
+ return `Audit this project's dependencies. 1) Read the manifest and lockfile (package.json, requirements.txt, Cargo.toml, go.mod — whichever exists). 2) Run the ecosystem's own audit and outdated commands via shell_execute where they exist (npm audit, pip-audit, cargo audit, …); if none is available say so instead of guessing at versions. 3) Cross-check for dependencies nothing imports, using file_search. ${focus} Report: known vulnerabilities worth acting on, majors that are far behind, and unused entries safe to drop. Do NOT upgrade anything yet — this is the report. ${ACT}`
+ },
+ },
+
+ // ── Ship ──────────────────────────────────────────────────────────────
+ {
+ name: 'commit',
+ summary: 'Stage changes and write a clean git commit',
+ argHint: '[message hint]',
+ build: (a) => {
+ const hint = a.trim() ? `\nThe user suggests this focus for the message: "${a.trim()}".` : ''
+ return `Create a git commit for the current changes. Steps, each as a real tool call: 1) "git status" and "git diff" to see what changed. 2) Group the changes and stage the right files ("git add"). 3) Write a clear Conventional-Commits message (type(scope): summary, then a short body explaining WHY). 4) Commit. 5) Show the resulting "git log -1 --stat".${hint} Do NOT push. If this is not a git repository, say so and stop. ${ACT}`
+ },
+ },
+ {
+ name: 'pr',
+ summary: 'Push the branch and open a pull request',
+ argHint: '[title or focus]',
+ build: (a) => {
+ const hint = a.trim() ? `\nThe user suggests this focus for the title: "${a.trim()}".` : ''
+ return `Open a pull request for the current work. 1) "git status" and "git log" against the base branch so you know exactly what is going out. 2) If the work is still on the default branch, create a descriptive branch first. 3) Make sure everything intended is committed — if there are uncommitted changes, say what they are and ask before including them. 4) Push the branch. 5) Open the PR with a title that says what changed and a body covering what, why, and how it was verified.${hint} If this is not a git repository, or there is no remote, say so and stop. ${ACT}`
+ },
+ },
+ {
+ name: 'undo',
+ summary: 'Revert the last change and explain what was rolled back',
+ argHint: '[file]',
+ build: (a) => {
+ const scope = a.trim() ? `Limit this to "${a.trim()}".` : ''
+ return `Roll back the most recent change. 1) FIRST show the user exactly what would be lost — "git status" and "git diff" (or "git show HEAD" if the change is already committed). 2) ${scope} Decide the right mechanism: restore the working tree for uncommitted edits, or revert the commit if it is already in history. Never rewrite published history and never force anything. 3) Do it. 4) Confirm the result with a fresh status and diff. If this is not a git repository there is no safety net, so stop and say so instead of deleting anything. ${ACT}`
+ },
+ },
+ {
+ name: 'docs',
+ summary: 'Generate or update documentation',
+ argHint: '[file | "readme"]',
+ build: (a) => {
+ const target = a.trim()
+ ? `documentation for "${a.trim()}"`
+ : 'the project README (create or update README.md)'
+ return `Write or update ${target}. Read the real code first so the docs are accurate. For a README: a clear title + one-line description, install/setup, usage with a runnable example, and key features — match the project's actual stack. For a file/module: concise doc-comments on the public functions. Write the file(s) with file_write. Keep it accurate and skimmable, no filler. ${ACT}`
},
},
{
@@ -128,6 +246,11 @@ export const AGENT_COMMANDS: AgentCommand[] = [
const BY_NAME = new Map(AGENT_COMMANDS.map((c) => [c.name, c]))
+/** Look a command up by name (without the slash). */
+export function getAgentCommand(name: string): AgentCommand | undefined {
+ return BY_NAME.get(name.toLowerCase())
+}
+
/**
* Parse a chat input into a slash command + expanded agent prompt, or null if
* it isn't a known command. Matches only `/<name>` at the very start (optionally
@@ -150,9 +273,15 @@ export function parseAgentCommand(
* matching commands (prefix match on the name, case-insensitive). An empty
* prefix returns all of them. Returns [] when the text isn't a lone slash token
* (e.g. there's already a space → the user is typing args, not picking).
+ *
+ * Only LEADING whitespace is trimmed, matching parseAgentCommand. They
+ * disagreed before 2.5.9: a leading space or newline killed the menu while
+ * sending still expanded the command, so the feature looked broken exactly when
+ * someone hit space first. A TRAILING space still closes the menu, because that
+ * is the user moving on to type arguments.
*/
export function matchAgentCommands(input: string): AgentCommand[] {
- const m = /^\/([a-z0-9_-]*)$/i.exec(input)
+ const m = /^\/([a-z0-9_-]*)$/i.exec(input.replace(/^\s+/, ''))
if (!m) return []
const prefix = m[1].toLowerCase()
return AGENT_COMMANDS.filter((c) => c.name.startsWith(prefix))
diff --git a/src/lib/mutating-tools.ts b/src/lib/mutating-tools.ts
new file mode 100644
index 00000000..9d018d07
--- /dev/null
+++ b/src/lib/mutating-tools.ts
@@ -0,0 +1,31 @@
+/**
+ * Tools that can change something outside the conversation.
+ *
+ * Two things strip these from a turn's catalog: Code-Review Mode, and a
+ * read-only slash command (/review, /plan, /diff, /explain, /find, /todo,
+ * /security). Read-only inspectors stay — git_status / git_log / git_diff,
+ * shell_task_status / shell_task_list, file_read / file_list / file_search —
+ * so the agent can still do the looking the command asked for.
+ *
+ * Shared between useCodex and useAgentChat so the same command behaves the same
+ * in the Code tab and in Agent mode. It lived only in useCodex until 2.5.9,
+ * which is part of why the flag was decorative in the first place.
+ */
+export const MUTATING_TOOLS = new Set([
+ 'file_write',
+ 'file_edit',
+ 'shell_execute',
+ 'code_execute',
+ 'shell_execute_background',
+ 'shell_task_kill',
+ 'git_commit',
+ 'git_push',
+ 'project_init',
+ 'gh_pr_create',
+ 'run_tests',
+ 'image_generate',
+ 'video_generate',
+ 'run_workflow',
+ 'delegate_task',
+ 'screenshot',
+])