CODEX · HOOKS

Codex hooks
from hooks.json to exit code 127.

Codex hooks are commands Codex runs at fixed points in a session, such as SessionStart or PreToolUse, set in hooks.json or config.toml in ~/.codex or a repo's .codex folder. Each gets the event as JSON on stdin; exit code 2 blocks, and 127 means the command wasn't found.

Start freeGet started Explore the team demo

Free for 3 seats · No credit cardStarter covers 3 seats · Pro is $49 a month for 5 · The demo needs no signup

Open the live team demo

Sample data, no signup · Create a free accountCreate your account

Zest lemon in its mech suit

01See your team’s AI stack

Winding / Teams Last 30 days

Zest

3 Members 1 Agent
Team overview
67%
AI Adoption▲ 34 pts
240
PRs Merged▲ 101
96.1h
Median AI Time▲ 9.5h
57.2h
Build Hours▲ 20.3h
This week
Member AI PRs/wk AI Task Plan Impl Last Standup AI Stack
22.8/wk28 min ago
15.8/wk12 min ago
4/wkAug 14
—2 hours ago
Current AI models & harnesses As of Sep 8
Claude CodeFable 5.1 (max) (with fallback)70.4 · Coding Agent Index
CodexGPT-6 Astra (max)67.0 · Coding Agent Index
Muse CodeMuse Spark 1.3 (xhigh)64.2 · Coding Agent Index
Grok BuildGrok 4.5 (high)64.1 · Coding Agent Index
Kimi Code CLIKimi K362.6 · Coding Agent Index
OpencodeGemini 3.8 Flash (high)61.2 · Coding Agent Index
Cursor CLIComposer 2.5 Fast38.3 · Coding Agent Index

Demo setups use current model families. The pairings above are the combinations benchmarked by Artificial Analysis; rankings measure performance, not popularity.

Intelligence Index

Illustrative daily trends · Other totals: last 30 days. Build Hours: this week, model-estimated activity including overlap; not engineer hours.

USED BY ENGINEERING TEAMS AT

Flyps Charm Wildfires Geoforge MisaLabs

How to add a hook to Codex

Create .codex/hooks.json at the root of the repository, or ~/.codex/hooks.json for every project, and point an event at a script. This one stops Codex from force-pushing: before each Bash call, PreToolUse hands the script the command, and exit code 2 with a reason on stderr blocks it.

Make the script executable, then run /hooks in the CLI and trust the new hook. Codex skips a new or changed hook until you do, and it loads a repository's hooks only after you trust the project. In the desktop app the same review sits under Settings > Hooks.

  • Codex runs the command from the session's working directory, which can be a subfolder, so OpenAI builds repo paths from git rev-parse --show-toplevel, as this one does.
  • timeout is in seconds, and statusMessage is the line Codex shows while the hook runs.
  • The script reads the event with jq. Without it on PATH the guard lets every push through, as the exit code 127 section shows.
.codex/hooks.json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "\"$(git rev-parse --show-toplevel)/.codex/hooks/block-force-push.sh\"",
            "statusMessage": "Checking git push",
            "timeout": 10
          }
        ]
      }
    ]
  }
}
.codex/hooks/block-force-push.sh (chmod +x)
#!/usr/bin/env bash
# Reads the PreToolUse event on stdin; exit 2 blocks the call.
cmd=$(jq -r '.tool_input.command // empty')
if [[ "$cmd" == *"git push"* && ( "$cmd" == *"--force"* || "$cmd" == *" -f"* ) ]]; then
  echo "Force push blocked by .codex/hooks/block-force-push.sh" >&2
  exit 2
fi
exit 0

Where do Codex hooks go: hooks.json or config.toml?

Either one, in your own Codex folder or a repository's. Codex reads a hooks.json file and inline [hooks] tables in config.toml next to every config layer it loads, and each matching hook from each source runs: a project's hooks add to yours rather than replacing them. If one folder has both forms, Codex merges them and warns at startup, so pick one per folder.

The force-push guard as inline TOML in config.toml looks like this:

.codex/config.toml
[[hooks.PreToolUse]]
matcher = "^Bash$"

[[hooks.PreToolUse.hooks]]
type = "command"
command = '"$(git rev-parse --show-toplevel)/.codex/hooks/block-force-push.sh"'
statusMessage = "Checking git push"
timeout = 10
Where Codex finds hooks, from OpenAI's hooks and plugin docs, read November 11, 2026.
LocationRuns for
~/.codex/hooks.json or ~/.codex/config.tomlEvery session you start
<repo>/.codex/hooks.json or <repo>/.codex/config.tomlThat repository, once you trust the project
A plugin's hooks/hooks.json, or the files its manifest namesWhile the plugin is enabled
requirements.toml from an adminEveryone it is deployed to: trusted by policy, and /hooks can't turn them off

Which events can a Codex hook use?

Codex has 14 hook events. The matcher is a regex: on tool events it is tested against the tool name, on SessionStart against how the session began, on the compaction events against manual or auto. *, an empty string or no matcher at all fires on every occurrence, and UserPromptSubmit, Stop and Interrupt ignore the field.

Tool hooks see Bash, apply_patch (which also matches Edit and Write), MCP tools named like mcp__server__tool, and Codex's other local tools. Hosted tools such as web search skip them, and OpenAI calls tool hooks a guardrail rather than a complete enforcement boundary.

Codex hook events and what each can do, from OpenAI's hooks docs, read November 11, 2026.
EventFiresMatcherWhat the hook can do
SessionStartA session starts or resumes, or after /clear, compaction or a forkstartup, resume, clear, compact, forkAdd context for the model
UserPromptSubmitBefore your prompt is sentIgnoredBlock the prompt or add context
PreToolUseBefore a tool callTool nameBlock the call, or rewrite its input
PermissionRequestWhen Codex is about to ask for approvalTool nameAllow or deny without the prompt
PostToolUseAfter a tool returns, including a Bash command that failedTool nameReplace the result with feedback; it can't undo the call
PreCompact, PostCompactBefore or after the chat is compactedmanual, autoStop there with continue: false
SubagentStartA subagent startsSubagent typeAdd context for the subagent
SubagentStopA subagent finishesSubagent typeSend it back for another pass
StopA turn finishesIgnoredKeep Codex going, with your reason as the next prompt
PreModelRequest, PostModelRequestEach model request attempt, retries includedNot supportedLog it; output can't change anything
InterruptYou interrupt a running turnIgnoredRecord or clean up, within 1 second by default (3 at most)
SessionEndThe main thread ends: closed, archived, or idle for 30 minutesotherRecord or clean up; it can't keep the thread open

What does a Codex hook get on stdin?

One JSON object per run. Every event carries session_id, transcript_path, cwd, hook_event_name and model, turn events add turn_id, and most add permission_mode. PreToolUse and PostToolUse add tool_name, tool_use_id and tool_input (PermissionRequest gets tool_name and tool_input), where Bash and apply_patch put their text in tool_input.command; PostToolUse also gets tool_response. A subagent's hooks see the parent session's id.

transcript_path is there if you want the whole conversation, but OpenAI says the transcript format isn't a stable interface for hooks, so a script that parses it can break on an update.

PreToolUse input (example values, trimmed)
{
  "session_id": "thr_123",
  "transcript_path": "/workspace/.codex/rollout.jsonl",
  "cwd": "/workspace",
  "hook_event_name": "PreToolUse",
  "turn_id": "turn_456",
  "permission_mode": "default",
  "tool_name": "Bash",
  "tool_use_id": "call_789",
  "tool_input": { "command": "git push --force origin main" }
}

How do Codex hook exit codes work?

Exit code 0 is success. SessionStart, UserPromptSubmit and SubagentStart add plain text on stdout to the model's context, Stop, SubagentStop and Interrupt accept only JSON, and the tool and compaction events ignore plain text. Exit code 2 with a reason on stderr blocks on the events that can block. Any other exit code marks the hook failed, and the action goes ahead.

For finer control, exit 0 and print JSON, such as the PreToolUse deny below.

  • On PreToolUse, permissionDecision: "ask", the older decision: "approve" and continue: false don't work yet: Codex marks the run failed and the tool call goes ahead.
  • updatedInput rewrites a call only next to permissionDecision: "allow", and for Bash and apply_patch it needs a string command.
  • On PermissionRequest, one deny from any matching hook denies the request.
  • Interpreters have exit codes of their own. python3 exits 2 when it can't open the script, so a PreToolUse hook pointing at a missing .py file blocks every call it matches, with Python's error as the reason.
stdout of a PreToolUse hook
{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Destructive command blocked by hook."
  }
}
What Codex does with each result, from OpenAI's hooks docs and the hook runner's source at rust-v0.167.2, read November 11, 2026.
ResultWhat Codex does
Exit 0, no outputCarries on
Exit 2, reason on stderrBlocks a tool call or a prompt, sends a PostToolUse reason back to the model, or keeps a Stop or SubagentStop going
Exit 2, nothing on stderrHook failed, nothing blocked: “PreToolUse hook exited with code 2 but did not write a blocking reason to stderr” (other events name a denial reason, feedback or a continuation prompt)
Any other exit codeHook failed, shown as “hook exited with code N”; the action goes ahead
Past its timeoutHook failed, “hook timed out after Ns”, and Codex kills the hook's process tree

How long can a Codex hook run, and can it run in the background?

Up to 600 seconds unless you set timeout. SessionEnd and Interrupt are the exceptions: 1 second by default and 3 at most. Command hooks matching the same event start together, so one can't keep another from running.

Add "async": true to a command hook and Codex stops waiting for it. The output reaches the model at the next safe point. Up to eight background hooks run at once per session, and the rest wait their turn. A background hook can't block or rewrite anything. SessionEnd hooks run synchronously whatever the setting says.

Keep what a hook returns short. Past about 2,500 tokens of additionalContext, Codex saves the full text to a file under its temp folder and gives the model a preview with the path; additionalContextLimit on the hook moves that line.

Why does a Codex hook exit with code 127?

Because the shell couldn't find what the command names. Codex hands the command string to a shell, usually the one it runs its own commands in, from the session's working directory and with the environment it captured for the session. Exit code 127 is that shell reporting the program, the script, or the interpreter on the script's first line missing.

Codex's terminal UI shows the run as “Hook failed”, with “hook exited with code 127” under it, and leaves out the shell's own error. So run the command yourself, from the repository, with a sample event on stdin: the line the shell prints names what it couldn't find.

We ran the usual causes through sh, bash and zsh on macOS, and the table at the end has what each returned. A script without the execute bit gives 126, not 127, and python3 with a missing script gives 2, which Codex treats as a block. What fixes them:

  • Give interpreters a full path, as OpenAI's examples do with /usr/bin/python3, or check them with command -v first.
  • Build script paths from the git root, not .codex/hooks/…: a session started in a subfolder looks for the script there.
  • chmod +x the script, and save it with Unix line endings.
  • In a plugin, start paths with ${PLUGIN_ROOT}. Codex sets it only for plugin hooks, so a plugin's hook copied into your own hooks.json points at /hooks/ instead.
  • A failing guard stops nothing. With jq missing, our force-push script exited 0 with an empty command, and 127 once we added set -e; Codex runs the push after either.
Run a hook the way Codex does
cd "$(git rev-parse --show-toplevel)"
echo '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"git push --force"}}' \
  | "$SHELL" -c '"$(git rev-parse --show-toplevel)/.codex/hooks/block-force-push.sh"'
echo $?        # 2: blocked; 127: the line above says what was missing

command -v jq python3 node                  # prints a path for each one it finds
ls -l .codex/hooks/block-force-push.sh      # needs an x
file .codex/hooks/block-force-push.sh       # "CRLF line terminators" means Windows line endings
Exit codes we got on macOS 26.5 with sh, bash 3.2 and zsh 5.9, November 11, 2026.
CauseExit code
The program isn't on the hook's PATH (node, python3, jq)127
The script path doesn't exist from the working directory127
#!/usr/bin/env python3 (or any interpreter) that isn't installed127
Windows line endings after #!/usr/bin/env bash127
A full interpreter path that doesn't exist, or #!/bin/bash with Windows line endings126 in sh and bash, 127 in zsh
The script isn't executable126
python3 given a script file that doesn't exist2, which Codex reads as a block
node given a script file that doesn't exist1

Codex notify vs hooks

notify is the older, simpler setting, and it still works. It runs one program each time a turn completes, passing the event as a single JSON argument rather than on stdin, and it can't block or change anything. It belongs in ~/.codex/config.toml: Codex ignores notify in a project's config and warns at startup.

The JSON has type (only agent-turn-complete for now), thread-id, turn-id, cwd, input-messages and last-assistant-message. For a desktop alert, the TUI's built-in tui.notifications may be all you need. To check Codex's work or keep it going, use a Stop hook.

~/.codex/config.toml
notify = ["python3", "/path/to/notify.py"]

How do Codex plugins ship hooks?

In hooks/hooks.json at the plugin's root, or in whatever files its manifest's hooks entry names, with the same events and JSON as yours. Their commands get PLUGIN_ROOT and PLUGIN_DATA, plus CLAUDE_PLUGIN_ROOT and CLAUDE_PLUGIN_DATA so Claude Code plugins' hooks keep working. Packaging and marketplaces are on Codex plugins.

Installing a plugin doesn't trust its hooks: review them in /hooks like your own, and again after an update that changes a bundled script, even when hooks.json stays the same. A plugin with hooks isn't eligible for OpenAI's public plugin directory, and installing one on the web doesn't put its scripts on your machine.

There's no flag to turn on. Plugin hooks have run by default since Codex CLI 0.131.0 (May 18, 2026), and 0.134.0 dropped the plugin_hooks flag. codex features enable plugin_hooks still succeeds today, but all it does is write plugin_hooks = true to config.toml, and Codex skips that key. To turn hooks off, set hooks = false under [features]; that covers plugin hooks too.

How Zest's Codex plugin uses two hooks

Zest's plugin for Codex runs one script from two hooks: SessionStart, with a 10-second timeout, and UserPromptSubmit, with 5. The script refreshes the Zest login, records that the session is active and starts a small background process if none is running; that process syncs every minute and exits after 10 quiet minutes. On SessionStart it also installs a newer plugin version when there is one, trying at most once a day; ZEST_CODEX_AUTOUPDATE_DISABLED=1 turns that off.

The script can't stop Codex; at worst it holds a prompt for its 5-second timeout. It takes the event name as an argument and never reads stdin. It prints nothing to stdout, so it adds nothing to the model's context, and it catches each step's error into a local log, so it exits 0 even offline.

The one deliberate failure is Node. The hook's sh -c wrapper checks that node is on PATH and at least 22.13 before it starts the script, and otherwise prints “Zest: Node >= 22.13 required” and exits 1 rather than letting a missing node end in 127. Codex shows that run only as “hook exited with code 1”, so the message appears when you run the command yourself. Native Windows can't run the wrapper, so commandWindows calls a small Node launcher that checks the version instead.

The plugin's first version landed in our repository on April 15, 2026, eight days before Codex hooks became stable in 0.124.0, so the plugin doesn't depend on them: the hooks only wake it up. The session data comes from Codex's own session files under ~/.codex, and logging in, checking status and a manual sync all work with hooks off.

That data is what Zest shows a team: each Codex session's model, tokens, skills and MCP tools per engineer, next to the pull requests they merged (setup, and more in Codex usage). Zest doesn't report on your own hooks: it doesn't count their runs, failures or blocks.

hooks/hooks.json in Zest's Codex plugin (trimmed)
{
  "hooks": {
    "SessionStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "sh -c '<check node >= 22.13>; exec node \"$HOME/.codex/plugins/cache/zest/zest/<version>/dist/hooks/refresh-auth.js\" SessionStart'",
            "commandWindows": "node \"${PLUGIN_ROOT}/dist/launch.cjs\" hooks/refresh-auth.js SessionStart",
            "timeout": 10
          }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "sh -c '<check node >= 22.13>; exec node \"$HOME/.codex/plugins/cache/zest/zest/<version>/dist/hooks/refresh-auth.js\" UserPromptSubmit'",
            "commandWindows": "node \"${PLUGIN_ROOT}/dist/launch.cjs\" hooks/refresh-auth.js UserPromptSubmit",
            "timeout": 5
          }
        ]
      }
    ]
  }
}

TRY IT ON YOUR TEAM

See what your team ships with AI.

Starter is free (3 seats, no credit card). Pro is $49 a month with 5 seats and Max is $149 a month with 10 seats — priced per workspace, not per engineer, with extra seats at $19 a month. See pricing

A FEW THINGS TO KNOW

Questions

Are Codex hooks enabled by default?+

Yes. Current Codex releases run hooks by default; they became stable in Codex CLI 0.124.0 in April 2026. To turn them all off, set hooks = false under [features] in config.toml. The older key name, codex_hooks, still works.

Do I need to run codex features enable plugin_hooks?+

No. Plugin hooks have been on by default since Codex CLI 0.131.0, and the flag was removed in 0.134.0. Running the command now only adds a plugin_hooks line to config.toml that Codex ignores.

Can I reuse Claude Code hooks in Codex?+

Often, with small changes. The common event names and stdin fields match, and plugin hooks get CLAUDE_PLUGIN_ROOT. But Codex runs only command and mcp_tool handlers, skipping prompt and agent ones, and a PreToolUse ask decision fails the hook instead of asking you.

Why isn't my Codex hook running?+

Open /hooks first: Codex skips a new or changed hook until you trust it, and loads a repository's hooks only in a trusted project. Then check that hooks isn't set to false under [features], that the tool runs locally (hosted tools such as web search skip tool hooks), and that the matcher regex matches the tool name.