Coral

Codex hooks: every event, hooks.json and examples

How Codex hooks work: where hooks.json goes, all 14 events, what each can block or approve, 4 working examples, and why a hook doesn’t run.

Updated

Codex hooks are scripts that Codex runs at fixed points in a session: before a tool call, when it’s about to ask you for approval, after a tool runs, when a turn stops, and more. You put them in ~/.codex/hooks.json (or a [hooks] table in config.toml), and hooks are on by default. The step most people miss: Codex won’t run a new or changed hook until you review and trust it in /hooks.

As of November 2026, from OpenAI’s Codex hooks docs, which OpenAI updates often, so its page wins if they disagree.

Codex stops for approvals, and nobody sees them. Coral puts every waiting Codex session in your Mac’s notch and on your iPhone, so you answer with one key. Download Coral for free

Where Codex hooks go

Codex reads hooks.json from every layer below and runs the matching hooks from all of them:

ScopeFile
You, every project~/.codex/hooks.json (or $CODEX_HOME/hooks.json)
One project.codex/hooks.json, loaded only when you trust the project
The whole Mac or Linux box/etc/codex/hooks.json
Admin-managed[hooks] in requirements.toml
A pluginhooks/hooks.json in the plugin, or its manifest’s hooks entry

Each file has the same three levels: an event, a matcher group that decides when it fires, and the handlers to run.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "^Bash$",
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.codex/hooks/block_destructive.py",
            "statusMessage": "Checking command",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

The same hook inline in config.toml:

[[hooks.PreToolUse]]
matcher = "^Bash$"

[[hooks.PreToolUse.hooks]]
type = "command"
command = "python3 ~/.codex/hooks/block_destructive.py"
timeout = 30

Pick one format per layer. If a layer has both, Codex loads both and warns at startup, and a command registered twice runs twice.

A few rules that apply to every hook:

  • Input is one JSON object on stdin with session_id, cwd, hook_event_name, model, transcript_path, and for most events permission_mode and turn_id.
  • Commands run in the session’s cwd. Codex may start in a subdirectory, so for repo hooks resolve the path from the git root: "$(git rev-parse --show-toplevel)/.codex/hooks/x.py".
  • timeout is in seconds, 600 by default (1 second for SessionEnd and Interrupt, 3 at most).
  • Handler types: command and mcp_tool run. prompt and agent are parsed and skipped.
  • Matching hooks run at the same time, so one hook can’t stop another from starting.

Every Codex hook event, and what it can do

EventFiresMatcher filtersWhat it can do
SessionStartA session starts, resumes, clears, compacts or forksstartup, resume, clear, compact, forkAdd context for the model
UserPromptSubmitYou send a promptignoredBlock the prompt or add context
PreToolUseBefore a tool callTool nameDeny it, rewrite its input, or add context
PermissionRequestCodex is about to ask you for approvalTool nameAllow or deny without showing the prompt
PostToolUseAfter a tool returns, including failed Bash commandsTool nameReplace the result with feedback, add context
PreCompact / PostCompactAround compactionmanual, autoStop compaction (PreCompact)
SubagentStartA subagent startsAgent typeAdd context for the subagent
SubagentStopA subagent finishesAgent typeSend it back for another pass
StopA turn endsignoredKeep Codex going with a new prompt
InterruptYou interrupt a running turnignoredLog or clean up only
PreModelRequest / PostModelRequestEach model request attemptnot supportedLog only (PostModelRequest has status and token usage)
SessionEndThe main session ends, or sits idle 30 minutes with no client openotherClean up only

Tool hooks see shell commands (match Bash), file edits (apply_patch, also matched by Edit or Write), MCP tools (mcp__server__tool) and most local tools such as update_plan. They don’t see hosted tools like web search. (To change which MCP tools ask for approval without a hook, use the Codex MCP approval settings.) OpenAI’s own advice: treat tool hooks as “a useful guardrail, not a complete enforcement boundary.”

How a hook says no. For PreToolUse, UserPromptSubmit, PostToolUse, Stop and SubagentStop, exit with code 2 and write the reason to stderr. For JSON, print it on stdout with exit code 0: PreToolUse uses hookSpecificOutput.permissionDecision: "deny", PermissionRequest uses hookSpecificOutput.decision.behavior. Stop and SubagentStop must print JSON, not plain text, when they exit 0.

What fails open. PreToolUse can’t return "ask" yet. If it does, or returns continue, stopReason or suppressOutput, Codex marks the hook as failed and runs the tool anyway. Test a blocking hook on a harmless command before you rely on it.

4 working examples

Save each script under ~/.codex/hooks/, add its entry to ~/.codex/hooks.json, then open /hooks in the CLI (or Settings → Hooks in the app) and trust it.

1. Block destructive shell commands

#!/usr/bin/env python3
# ~/.codex/hooks/block_destructive.py  (PreToolUse, matcher "^Bash$")
import json, re, sys

event = json.load(sys.stdin)
cmd = event.get("tool_input", {}).get("command", "")
if re.search(r"\brm\s+-(?=\S*r)(?=\S*f)\S+|\bgit\s+push\b.*--force", cmd):
    print("Blocked by hook: destructive command. Ask the user first.", file=sys.stderr)
    sys.exit(2)

The reason on stderr goes back to the model, so Codex knows why and usually asks you instead.

2. Approve your test command without a prompt

PermissionRequest runs only when Codex would otherwise ask you. This one approves test runs and stays silent on everything else, so the normal prompt appears:

#!/usr/bin/env python3
# ~/.codex/hooks/allow_tests.py  (PermissionRequest, matcher "^Bash$")
import json, re, sys

cmd = json.load(sys.stdin).get("tool_input", {}).get("command", "")
if re.fullmatch(r"\s*(npm|pnpm|yarn) (run )?test\b[^;&|]*", cmd):
    print(json.dumps({"hookSpecificOutput": {
        "hookEventName": "PermissionRequest",
        "decision": {"behavior": "allow"}}}))

If several hooks answer the same request, any deny wins. Approving more than you would by hand weakens the sandbox, so keep the pattern narrow.

3. Get a Mac notification when Codex needs approval

Codex’s older notify setting fires only when a turn completes. A PermissionRequest hook that decides nothing fires exactly when Codex is waiting on you:

#!/bin/bash
# ~/.codex/hooks/approval_alert.sh  (PermissionRequest, no matcher)
input=$(cat)
what=$(printf '%s' "$input" | jq -r '.tool_input.command // .tool_name' | head -c 120)
project=$(basename "$(printf '%s' "$input" | jq -r '.cwd')")
osascript - "$what" "$project" <<'EOF'
on run argv
  display notification (item 1 of argv) with title ("Codex needs approval · " & item 2 of argv)
end run
EOF

It needs jq (brew install jq). The command is passed to AppleScript as an argument, so quotes in it don’t break the script.

4. Make Codex run the tests before it stops

#!/usr/bin/env python3
# ~/.codex/hooks/tests_before_stop.py  (Stop)
import json, subprocess, sys

event = json.load(sys.stdin)
if event.get("stop_hook_active"):
    print("{}")  # already sent back once; let it stop
    sys.exit(0)
run = subprocess.run(["npm", "test", "--silent"], cwd=event["cwd"],
                     capture_output=True, text=True)
if run.returncode != 0:
    print(json.dumps({"decision": "block",
        "reason": "Tests fail. Fix them before finishing:\n" + run.stdout[-1500:]}))
else:
    print("{}")

decision: "block" on Stop doesn’t reject anything: Codex starts a new turn with your reason as the prompt. The stop_hook_active check keeps it from looping forever. Give this hook a timeout longer than your test suite.

A notification tells you Codex is waiting; you still have to find the right terminal. Coral shows the waiting Codex request in your Mac’s notch with the full command, and you answer with one key. Get Coral for free

Why your Codex hook doesn’t run

Check these in order:

  1. It isn’t trusted. Codex skips new or changed hooks until you review them. Trust is tied to the hook definition’s hash, so editing the entry in hooks.json needs a new review. Open /hooks; Codex also warns at startup when hooks need review. For one-off scripted runs, --dangerously-bypass-hook-trust runs enabled hooks without stored trust.
  2. Hooks are off. Look for [features] hooks = false (or the old codex_hooks name) in your config.toml, and ask whether an admin set it in requirements.toml.
  3. The project isn’t trusted. .codex/hooks.json loads only from trusted projects. User and system hooks still load everywhere.
  4. Your admin allows only managed hooks. allow_managed_hooks_only = true skips user, project and plugin hooks.
  5. The event never sees that tool. Hosted tools like web search don’t go through tool hooks, and PermissionRequest doesn’t fire for commands that don’t need approval (in full-auto or yolo mode, that’s most of them).
  6. The path is relative. Codex runs the command from the session’s cwd, which may be a subdirectory.
  7. The output is the wrong shape. Plain text on stdout is ignored for tool events and invalid for Stop. Unsupported fields mark the hook as failed and the action goes ahead.

Codex hooks vs Claude Code hooks

The shared events have the same names and a similar JSON shape, so most Claude Code hooks port over with small edits. The differences that matter:

CodexClaude Code
Confighooks.json or [hooks] in config.tomlhooks in settings.json
“Agent is waiting” eventNone; use PermissionRequestNotification
Failed tool callsPostToolUse also runs after a failing Bash commandSeparate PostToolUseFailure event
Handler typescommand, mcp_toolcommand, http, mcp_tool, prompt, agent
Turn them off[features] hooks = false"disableAllHooks": true
Plugin hooksGets PLUGIN_ROOT, plus CLAUDE_PLUGIN_ROOT for compatibilityCLAUDE_PLUGIN_ROOT

The Claude Code column is from Anthropic’s hooks reference. For its examples, see Claude Code hooks; for the rest of the comparison, Codex vs Claude Code.

Where Coral fits

When you connect Codex in Coral, it adds its own Codex hooks for approval requests. It shows you which file changes, backs it up first, and never replaces a hook you edited; your own hooks keep running next to it. To take it out, choose Agent Hooks in the island menu, then Remove Codex Hooks.

Then every waiting Codex session (the CLI or the app) sits in your Mac’s notch next to Claude Code, Copilot, OpenCode and Grok, whoever has waited longest first:

  • Answer with one key. Press 1, 2 or 3 with the full command in front of you. ⌘Z takes it back within two seconds.
  • From any app. A card drops from the notch when Codex asks; ⌃⌥1 answers without leaving your editor.
  • Away from your Mac. Alerts on your iPhone are Free; answering from the phone straight to the agent is Pro.

Your guardrail hooks decide what’s allowed; Coral makes sure the prompts that are left get answered.

Questions

Does Codex support hooks?

Yes. Codex runs lifecycle hooks in the CLI and the desktop app, and they’re on by default. Add them to ~/.codex/hooks.json or .codex/hooks.json, then trust them in /hooks before they run.

Where is the Codex hooks.json file?

Your personal file is ~/.codex/hooks.json (or $CODEX_HOME/hooks.json). A project’s is .codex/hooks.json, and a system-wide one is /etc/codex/hooks.json on macOS and Linux. You can also write hooks inline under [hooks] in the matching config.toml.

Why isn’t my Codex hook running?

Usually it hasn’t been trusted: open /hooks and review it. Otherwise check that [features] hooks isn’t false, that the project is trusted (for .codex/hooks.json), and that the event actually covers the tool you’re matching.

Can a Codex hook approve commands automatically?

Yes. A PermissionRequest hook can return allow or deny for an approval Codex is about to show. If any matching hook denies, the request is denied; if none decides, you get the normal prompt.

What’s the difference between Codex notify and hooks?

notify runs one program when a turn completes and can’t change anything. Hooks run on 14 events, can block, approve or rewrite actions, and can feed context back to the model.

Do Claude Code hooks work in Codex?

Not as is, but they’re close. The shared events (PreToolUse, PostToolUse, PermissionRequest, Stop and others) use the same names, and Codex sets CLAUDE_PLUGIN_ROOT for plugin hooks. Move the entries to hooks.json, swap Notification for PermissionRequest, and trust them in /hooks.

Never leave an agent waiting.

Coral taps you in your Mac’s notch or on your iPhone when an agent needs you. Free.

Download for freeSee pricing

More guides

Coral alternatives and comparisons