Codex hooks: events, hooks.json, exit codes and trust
Every Codex CLI hook event and when it fires, hooks.json or [hooks] in config.toml, the JSON input, exit 2 and deny, /hooks trust, codex exec and notify.
Codex hooks are commands Codex runs at fixed points in a session: when it starts or ends, when you send a prompt, before and after most tool calls, when it is about to ask for approval, when a turn stops, around compaction and around each model request. Put them in ~/.codex/hooks.json, or under [hooks] in ~/.codex/config.toml; a repository’s .codex/hooks.json loads only once you trust the project. Each command gets the event as one JSON object on standard input. On PreToolUse, exit 2 with a reason on standard error, or print a permissionDecision of "deny", and the call is blocked; exit 0 with no output and Codex carries on. A hook you add runs only after you trust it, at the review prompt Codex shows on startup or in /hooks, and editing it sends it back for review. Hooks are on by default. As of Codex CLI 0.171.0, November 2026.
A first hook: refuse force-pushes
A hook is two pieces: a script, and an entry that says which event runs it. This one refuses the usual force-push and hard-reset commands. It needs jq. This script and the Stop hook further down are examples written to the contract OpenAI documents; try each once and watch it act before you rely on it. Save it as ~/.codex/hooks/guard.sh and run chmod +x on it:
#!/usr/bin/env bash
# PreToolUse: refuse force-pushes and hard resets; let everything else through.
# Without jq this would let everything through, so refuse instead.
command -v jq >/dev/null || { echo "guard.sh needs jq" >&2; exit 2; }
cmd=$(jq -r '.tool_input.command // empty')
if printf '%s' "$cmd" | grep -Eq 'git[[:space:]]+push.*(--force|[[:space:]]-f)|git[[:space:]]+reset.*--hard'; then
echo "force-push and hard reset are blocked by a hook; ask the user to run it" >&2
exit 2
fi
exit 0CopiedThen register it in ~/.codex/hooks.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "~/.codex/hooks/guard.sh",
"statusMessage": "Checking command"
}
]
}
]
}
}CopiedStart codex. Because the hook is new, Codex opens a Hooks need review prompt first, warning that “Hooks can run outside the sandbox after you trust them,” with three choices: Review hooks, Trust all and continue, or Continue without trusting (hooks won’t run). Once it is trusted, a matching command never reaches the shell; in the 0.171.0 source the model gets Command blocked by PreToolUse hook: <your reason>. Command: <the command> as the tool’s result and can tell you why. The match is on text, so a command the patterns don’t cover goes through. OpenAI’s own framing in the hooks documentation: “Treat tool hooks as a useful guardrail, not a complete enforcement boundary.”
Every event, and when it fires
Codex 0.171.0 has fourteen events. The matcher column is what a group’s matcher is compared against; where it says “ignored”, every hook on that event runs.
| Event | Fires | Matcher | What the hook can do |
|---|---|---|---|
SessionStart | A session starts, resumes, is cleared, is compacted or is forked | startup, resume, clear, compact, fork | Add context for the model (plain output counts) |
UserPromptSubmit | You send a prompt, before it goes to the model | Ignored | Block the prompt, or add context (plain output counts) |
PreToolUse | Before a shell command, an apply_patch edit, an MCP tool call or another local tool | Tool name | Block the call, rewrite its input, or add context |
PermissionRequest | Codex is about to ask you to approve something | Tool name | Approve or deny in your place, or leave it to you |
PostToolUse | After a tool returns, including shell commands that exit non-zero | Tool name | Replace the result with feedback; it can’t undo what ran |
PreCompact, PostCompact | Before and after the conversation is compacted | manual, auto | Stop Codex before compacting, or after it |
SubagentStart, SubagentStop | A subagent starts, or finishes | Subagent type | Add context for it; send it back for another pass |
Stop | A turn ends | Ignored | Keep Codex going with a new prompt |
PreModelRequest, PostModelRequest | Before and after every model request attempt, retries included | Not supported | Nothing: their output is diagnostic only |
Interrupt | You interrupt a running turn on the main thread | Ignored | Nothing: record it or clean up, within 1 to 3 seconds |
SessionEnd | An open conversation is archived or deleted, Codex closes normally, or a conversation sits idle and unopened for 30 minutes | other (the only reason today) | Nothing: it is advisory, and gets 1 to 3 seconds |
Points that decide whether a tool hook fires at all:
- Shell commands match as
Bash, whichever shell tool Codex used. File edits go throughapply_patch, which a matcher can also callEditorWrite, though the hook’s input still saysapply_patch. MCP tools match by their full name, such asmcp__filesystem__read_file, and spawning a subagent also matchesAgent. - Hosted tools never reach a tool hook. Hosted tools such as web search don’t pass through
PreToolUseorPostToolUse. - Exact name or regular expression. In the 0.171.0 source, a matcher made only of letters, digits,
_and|is a list of exact names, soBashmatches onlyBashandstartup|resumeonly those two. Anything else is a regular expression matched anywhere in the name (mcp__filesystem__.*), and"*", an empty string or no matcher at all matches everything. PermissionRequestis not a command filter. “It doesn’t run for commands that don’t need approval,” so a policy that must see every command belongs onPreToolUse.
Where hooks go: hooks.json or config.toml
| Scope | File | Loads |
|---|---|---|
User | ~/.codex/hooks.json ($CODEX_HOME/hooks.json; on Windows %USERPROFILE%\.codex\hooks.json) | In every project, trusted or not |
Project | .codex/hooks.json in any .codex folder from the project root down to the working directory | Only once the project is trusted |
System | /etc/codex/hooks.json; on Windows %ProgramData%\OpenAI\Codex\hooks.json | In every project, trusted by policy with no review |
Plugin | hooks/hooks.json inside the plugin, or the paths its manifest names | While the plugin is enabled |
Managed | [hooks] in an administrator’s requirements.toml | Trusted by policy, with no review |
Any directory that holds a hooks.json can instead carry the same hooks inline under [hooks] in its config.toml. The structure is the same three levels, event, matcher group, handlers:
# ~/.codex/config.toml: give every new or resumed session the git state
[[hooks.SessionStart]]
matcher = "startup|resume"
[[hooks.SessionStart.hooks]]
type = "command"
command = 'echo "Branch: $(git branch --show-current 2>/dev/null)"; git status --short 2>/dev/null | head -20'
statusMessage = "Reading git status"CopiedOn SessionStart, plain text on standard output is added to the model’s context, so that is the whole hook. The rules for combining files differ from what you might expect:
- Matching hooks from every file run, and command hooks on the same event start concurrently, so one can’t stop another from starting.
- “If two files register the same command for an event, Codex can run it twice when that event occurs.” Put a hook in your user file or in the repository, not both.
- A layer with both a
hooks.jsonand an inline[hooks]loads both and warns at startup. OpenAI’s advice is one format per layer. - In a linked Git worktree, the project layer can read hooks from the matching folder in the main checkout.
- To switch every hook off, set
hooks = falseunder[features]. Older tutorials usecodex_hooks, which still works as a deprecated alias; neither is needed to turn hooks on.
The rest of the file, its precedence and CODEX_HOME are in the config.toml guide. Hooks that ship inside a plugin follow the same rules, with one extra review step, covered in Codex plugins.
What a hook receives
Every command hook gets one JSON object on standard input. For a shell command on PreToolUse, its fields have this shape:
{
"session_id": "<session id>",
"turn_id": "<turn id>",
"transcript_path": "<path to the transcript, or null>",
"cwd": "/home/you/project",
"hook_event_name": "PreToolUse",
"model": "<model slug>",
"permission_mode": "default",
"tool_name": "Bash",
"tool_use_id": "<call id>",
"tool_input": { "command": "git push --force origin main" }
}CopiedThe event-specific fields are the ones you will read: tool_input.command (a string) for Bash and apply_patch, the arguments for MCP and other tools, tool_response on PostToolUse, prompt on UserPromptSubmit, source on SessionStart, and last_assistant_message with stop_hook_active on Stop. The docs list five possible values for permission_mode, but the 0.171.0 source sends bypassPermissions when approvals are set to never and default for every other policy. The transcript file is there for convenience; OpenAI says its format “isn’t a stable interface for hooks.”
How the command itself runs: through a shell, so ~, pipes and $(…) work, in the session’s working directory and with the session’s environment. Codex sets no variable naming the project root, and Codex may be started from a subfolder, so for a script kept in the repository OpenAI’s examples build the path from git: "$(git rev-parse --show-toplevel)/.codex/hooks/pre_tool_use_policy.py". Only plugin hooks get extra variables: PLUGIN_ROOT and PLUGIN_DATA, plus CLAUDE_PLUGIN_ROOT and CLAUDE_PLUGIN_DATA with the same values, for existing plugins that read those names. On Windows, commandWindows (or command_windows in TOML) overrides the command.
Exit codes and output: what changes what Codex does
| The hook | What Codex does |
|---|---|
Exits 0 and prints nothing | Carries on |
Exits 0 and prints JSON | Applies the event’s JSON fields (below) |
Exits 0 and prints plain text | Adds it as context on SessionStart, UserPromptSubmit and SubagentStart; ignores it on the tool and compaction events; treats it as invalid, and the run as failed, on Stop, SubagentStop and Interrupt |
Exits 2 with a reason on standard error | On the events that can act on it: blocks the tool call or the prompt, denies the permission request, feeds the reason back after a tool, or sends a stopping turn or subagent back to work |
Exits 2 with nothing on standard error | Marks the run failed and carries on; on PreToolUse the error is “PreToolUse hook exited with code 2 but did not write a blocking reason to stderr” |
Exits 1 or any other code, times out, or can’t start | Marks the run failed (“hook exited with code 1”, “hook timed out after 600s”) and carries on |
The last two rows are the ones that let a guardrail down. A PreToolUse hook that crashes, hangs past its timeout (600 seconds unless you set timeout) or exits 1 does not block, and in 0.171.0 a command hook has no setting to make a failure block: its fields are type, command, commandWindows, timeout, async, statusMessage and additionalContextLimit. Test a new gate once and watch it block.
The JSON each event takes, from the hooks reference:
PreToolUse:hookSpecificOutput.permissionDecisionset to"deny"with apermissionDecisionReason, or the older"decision": "block"with areason;"allow"withupdatedInputto rewrite the call (forBashandapply_patchit must carry a stringcommand);additionalContextto tell the model something without blocking."ask", the old"approve",continue: falseandstopReasonare not supported here: Codex “marks the hook run as failed, reports the error, and continues the tool call.” Codex can’t ask you on a hook’s behalf from this event.PermissionRequest:hookSpecificOutput.decision.behaviorof"allow"(no prompt is shown) or"deny"with amessage. If several hooks answer, any deny wins; if none does, you get the normal prompt. The reserved fieldsupdatedInput,updatedPermissionsandinterrupt“fail closed today.”UserPromptSubmit,PostToolUse,Stop,SubagentStop:"decision": "block"with areason. On a prompt it refuses it; after a tool it replaces the result the model sees with your reason; onStopthe reason becomes a new prompt and Codex keeps working.- Most events:
systemMessageshows a warning in the interface.continue: falsestops Codex before compacting onPreCompactand after it onPostCompact, ends the turn on aSessionStartthat follows a compaction, and onPostToolUsereplaces the original result with your feedback.
Context a hook adds is capped at roughly 2,500 tokens per message; beyond that Codex saves the full text under <temp_dir>/hook_outputs/<session_id>/ and gives the model a preview with the path. additionalContextLimit on a handler changes the threshold, and since the overflow is written to disk, OpenAI warns against returning secrets in hook output. A handler with "async": true runs in the background, at most eight at a time per session, and “can’t block, approve, rewrite, or otherwise control the operation”; its context arrives at the next safe point.
Keep Codex working until the tests pass
The Stop event is how a hook refuses to let a turn end. This one runs the tests when Codex finishes and, if they fail, sends it back once with the failure. Replace npm test with your project’s command:
#!/usr/bin/env bash
# Stop: if the tests fail, send Codex back for one more pass.
input=$(cat)
# Already sent back once this turn: let it stop rather than loop.
[ "$(jq -r '.stop_hook_active' <<<"$input")" = "true" ] && exit 0
if ! npm test >/tmp/codex-tests.log 2>&1; then
jq -n '{decision: "block", reason: "The tests fail; the output is in /tmp/codex-tests.log. Fix them, then finish."}'
fi
exit 0Copied"Stop": [
{
"hooks": [
{ "type": "command", "command": "~/.codex/hooks/tests-pass.sh", "timeout": 300 }
]
}
]CopiedTwo details make it safe. Stop wants JSON or nothing on standard output, so the test run’s own output goes to a file. And stop_hook_active is true when “this turn was already continued by Stop”. That check is what keeps a suite Codex can’t fix from sending it round again and again; the docs describe no limit of Codex’s own.
Trusting hooks: /hooks and the review prompt
“Before a non-managed hook can run, Codex requires you to review and trust the exact hook definition.” Codex keeps a hash of each hook you trust, so a new or edited hook is skipped until you review it again, and a plugin hook needs a fresh review when an update changes its script even if the definition is unchanged. At startup Codex shows the review prompt described above whenever hooks are waiting. Later, /hooks opens a browser listing each event with how many hooks are installed, active and waiting for review; from there you can read a hook’s command and source, trust it, or switch a single hook off. In the ChatGPT desktop app it is Review hooks in the composer or Settings > Hooks.
In the 0.171.0 source, your decisions are written to your user configuration under hooks.state, one trusted_hash per hook, and only your user configuration and the settings passed for the session are read for them: a repository can bring hooks but cannot mark them trusted. It also means the trust belongs to one account and one CODEX_HOME. Hooks from requirements.toml and other managed sources are trusted by policy and can’t be switched off from /hooks; an administrator can also set allow_managed_hooks_only = true to ignore everyone else’s.
Project hooks and codex exec
A repository’s hooks pass two gates. The first is project trust: Codex “loads hooks only from trusted project layers,” and since 0.169.0 that holds for codex exec too, even with --sandbox workspace-write: it ignores an untrusted project’s .codex/ folder, hooks included, until the project is trusted; codex exec --trust saves that trust from the command line. The warning it prints, and when not to pass --trust, are in the codex exec untrusted project configuration guide. The second gate is hook trust, and codex exec has no review prompt to grant it. Two ways through:
- Trust them interactively first. Open
codexin the project as the same user, with the sameCODEX_HOMEthe job uses, and trust the hooks; laterexecruns in that checkout find the saved hashes. Edit a hook and you have to do it again. Whether trust given in one checkout covers a clone at another path, as on a CI runner, is not documented. - Only for automation that already vets its hook sources,
--dangerously-bypass-hook-trustskips the check for one run. Its help says “Run enabled hooks without requiring persisted hook trust for this invocation. DANGEROUS. Intended only for automation that already vets hook sources.” It is not a way to run a repository you didn’t write.
A skipped hook is easy to miss. Two reports were still open on November 23, 2026: openai/codex#61741, where exec shows hooks skipped for trust only as hook: SessionStart Failed with no reason, and openai/codex#46210, where a SessionStart hook is skipped “with no diagnostic.” Before relying on a hook in a scheduled job, prove it fires with one that leaves a mark, kept in the same file as the hooks you rely on so it passes the same project gate; trust is still per hook, so trust it along with them:
[[hooks.SessionStart]]
[[hooks.SessionStart.hooks]]
type = "command"
command = "date >> /tmp/codex-hooks-fired"CopiedNotifications: notify, a Stop hook, or the terminal
Codex has no Notification event, so “tell me when it’s done” takes one of three routes.
notifyin~/.codex/config.tomlruns a program “whenever Codex emits supported events (currently onlyagent-turn-complete)”, per the advanced configuration page:notify = ["python3", "/path/to/notify.py"]. Unlike a hook, it gets its JSON as the last command-line argument, with dashed field names (last-assistant-message,thread-id,cwd), and the 0.171.0 source discards its output and doesn’t wait for it, so a broken notifier fails silently. Codex ignoresnotifyin a project’s config, so set it in your user file. The source calls it “legacynotifysupport”, with a note to remove the code when that support goes; the docs still document it.- A
Stophook getslast_assistant_messagetoo, and works from a repository as well. Give it"async": trueso a slow send never holds Codex up, and keep its standard output empty. Codex cancels background hooks still unfinished when the session ends. - The terminal itself:
tui.notificationsis on by default, withtui.notification_method(auto,osc9orbel) andtui.notification_condition, which defaults to firing only when the terminal is unfocused.
A working script that sends a phone notification from notify, and why terminal alerts go nowhere on a server you have disconnected from, are in notifications from Claude Code and Codex.
Codex hooks and Claude Code hooks
Codex’s hooks follow Claude Code’s closely: the same event names where they overlap, JSON on standard input in the same shape (Codex adds fields such as model and turn_id), the same permissionDecision output and the same exit-2 rule, and Codex’s /import brings Claude Code hooks over as Codex hooks (OpenAI lists “Hooks whose behavior may differ after import” among what to review afterwards). Where they part, as of Codex 0.171.0 and Claude Code 2.1.330:
| Codex | Claude Code | |
|---|---|---|
Configured in | hooks.json or [hooks] in config.toml, under ~/.codex or .codex | settings.json, under ~/.claude or .claude |
Before a hook runs | You trust each hook, and again after every change | You trust the folder; in claude -p the folder counts as trusted |
Handler types that run | command, mcp_tool | command, http, mcp_tool, prompt, agent |
A gate that crashes or times out | The call goes ahead; no setting changes that | The call goes ahead unless the hook sets onFailure: "block" |
Project root in a command | No variable; use $(git rev-parse --show-toplevel) | $CLAUDE_PROJECT_DIR |
The same hook in two files | Can run twice | Runs once |
Events only one has | Interrupt, PreModelRequest, PostModelRequest | Notification, PostToolUseFailure, FileChanged and many more |
The Claude Code side in depth, including a guardrail script tested in both agents, is in Claude Code hooks.