Sub topic 17
Custom commands, hooks, and subagents
This chapter assumes you have used slash commands, read a settings file, and understand the agent loop and permissions from earlier chapters. It covers three ways to extend an agent: saved prompts, scripts that run at fixed points in the loop, and helper agents with separate context. Claude Code supports all three directly. Codex CLI and Copilot CLI cover parts of them, and both change quickly, so check their current documentation before you rely on a feature.
Three extension points
| Mechanism | What it is | Who decides when it runs |
|---|---|---|
| Custom command | A saved prompt, stored as a Markdown file | You, by typing `/name` |
| Hook | A shell command attached to an event in the agent loop | The tool, every time the event happens |
| Subagent | A named agent with its own instructions, tools, and context window | The main agent, or you |
The difference that matters most is who is in control. A command is a shortcut for a person. A hook is deterministic: it runs whether or not the model "remembers" to do something. A subagent is delegation: the model decides when to use it.
Custom commands
A custom command is a prompt you have written down once. In Claude Code, each Markdown file in .claude/commands/ becomes a slash command named after the file. Commit the directory and your team shares the commands. Files in ~/.claude/commands/ are personal and apply to every project.
---
description: Review the current branch against main
allowed-tools: Bash(git diff:*), Bash(git log:*)
---
Review the changes on this branch compared with main.
Focus area: $ARGUMENTS
1. Run `git diff main...HEAD` and read the changed files.
2. List bugs, missing tests, and violations of the conventions in CLAUDE.md.
3. Do not edit any files. Report findings only.Save this as .claude/commands/review.md. Typing /review error handling runs the prompt with $ARGUMENTS replaced by error handling. The allowed-tools field limits which tools the command may use without asking, so a review command can read git history but cannot change files.
Codex CLI has a similar feature called custom prompts: Markdown files in ~/.codex/prompts/, invoked with a /prompts: prefix. Newer releases may move this toward other mechanisms, so verify in your version. Copilot CLI relies mainly on custom instructions and custom agents, covered below.
When a command is the right tool
Use a command for a task you repeat with the same structure, such as reviewing a branch, writing a changelog entry, or triaging a failing test. If the file grows long or needs logic, move that logic into a script and have the command call it.
Hooks
A hook is a shell command that the tool runs at a defined event. Because the tool runs it and not the model, a hook is the right place for rules that must always hold: formatting after every edit, blocking writes to generated files, or logging every command.
Claude Code defines hooks in the settings files you met earlier. Common events include:
PreToolUse: before a tool runs. The hook can block the call.PostToolUse: after a tool succeeds.UserPromptSubmit: when you submit a prompt, before the model sees it.Stop: when the agent finishes responding.SessionStart: when a session begins.
A matcher selects which tools trigger the hook. The hook receives details about the event as JSON on standard input.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "python3 .claude/hooks/block_generated.py" }
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "npm run lint --silent" }
]
}
]
}
}The blocking script reads the event and checks the target path:
import json
import sys
event = json.load(sys.stdin)
path = event.get("tool_input", {}).get("file_path", "")
if "/dist/" in path or "/generated/" in path:
print(f"Blocked: {path} is generated. Edit the source instead.", file=sys.stderr)
sys.exit(2)
sys.exit(0)In Claude Code, exit code 2 from a PreToolUse hook blocks the tool call and sends the stderr text back to the model, so it can adjust. Exit code 0 allows the call. Other non-zero codes report an error to you but do not block. Confirm these exit-code rules against your installed version.
Hook gotchas
- A hook runs with your user permissions and no sandbox. Treat a hook script like any code that runs on your machine, and review hook changes in pull requests.
- Slow hooks slow every loop iteration. Running the full test suite after every edit is usually too much. Run a formatter after edits and tests on
Stop. - Hooks in a committed settings file execute for everyone who opens the repository. That makes them powerful for teams and a risk when you open an untrusted repository.
- A
PostToolUsehook cannot undo an edit. UsePreToolUsefor prevention.
Subagents
A subagent is a separate agent the main session can hand work to. It has its own system prompt, its own tool list, and its own context window. It does its work, then returns a summary. The files it read and the commands it ran do not fill the main session's context.
In Claude Code, subagents are Markdown files in .claude/agents/ (project) or ~/.claude/agents/ (personal):
---
name: test-runner
description: Runs the test suite and reports failures. Use after code changes.
tools: Read, Grep, Bash
---
You run tests and diagnose failures.
1. Run `npm test`.
2. For each failing test, read the test and the code it covers.
3. Report the test name, the likely cause, and the file to change.
4. Never edit files. Return only the report.The description matters most. The main agent reads it to decide when to delegate, so state what the subagent does and when to use it. The tools list limits what it can do, which makes a read-only reviewer safe to run freely.
Subagents help in two cases:
- Context protection. A search through hundreds of files produces a short answer without bloating the main history.
- Role separation. A reviewer with no edit tools cannot quietly "fix" what it was asked to judge.
They cost extra model calls and time, and the summary can lose detail. Do not use one for a small, single-file task. Copilot CLI supports custom agents defined in files under .github/agents/, with a similar idea of a named role and instructions. Check the current file format in its documentation.
Choosing between them
- Same prompt, you trigger it: a command.
- A rule that must always run, with no model judgment: a hook.
- Heavy reading or a distinct role: a subagent.
- Guidance the model should always keep in mind: the instruction file, not any of these.
Exercise
Your team wants every edit to be formatted with Prettier, and wants the agent never to modify files in generated/. For each requirement, say whether you would use a command, a hook, or a subagent, and which hook event. Why not rely on a line in CLAUDE.md?
Show answer
Both are hooks. Formatting is a PostToolUse hook matched on Edit|Write that runs Prettier. The generated/ rule is a PreToolUse hook on Edit|Write that exits with code 2 when the path is under generated/. A CLAUDE.md line is guidance the model may miss or ignore under a long context. Hooks run in the tool itself, so they apply every time.