# 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 November 20, 2026 · https://usecoral.app/guides/codex-hooks

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](https://learn.chatgpt.com/docs/hooks), which OpenAI updates often, so its page wins if they disagree.

<p data-cta="guide_top">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. <a href="/download">Download Coral for free</a></p>

## Where Codex hooks go

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

| Scope | File |
|---|---|
| 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 plugin | `hooks/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.

```json
{
  "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`:

```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

| Event | Fires | Matcher filters | What it can do |
|---|---|---|---|
| `SessionStart` | A session starts, resumes, clears, compacts or forks | `startup`, `resume`, `clear`, `compact`, `fork` | Add context for the model |
| `UserPromptSubmit` | You send a prompt | ignored | Block the prompt or add context |
| `PreToolUse` | Before a tool call | Tool name | Deny it, rewrite its input, or add context |
| `PermissionRequest` | Codex is about to ask you for approval | Tool name | Allow or deny without showing the prompt |
| `PostToolUse` | After a tool returns, including failed Bash commands | Tool name | Replace the result with feedback, add context |
| `PreCompact` / `PostCompact` | Around compaction | `manual`, `auto` | Stop compaction (`PreCompact`) |
| `SubagentStart` | A subagent starts | Agent type | Add context for the subagent |
| `SubagentStop` | A subagent finishes | Agent type | Send it back for another pass |
| `Stop` | A turn ends | ignored | Keep Codex going with a new prompt |
| `Interrupt` | You interrupt a running turn | ignored | Log or clean up only |
| `PreModelRequest` / `PostModelRequest` | Each model request attempt | not supported | Log only (`PostModelRequest` has status and token usage) |
| `SessionEnd` | The main session ends, or sits idle 30 minutes with no client open | `other` | Clean 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](https://usecoral.app/guides/codex-mcp).) 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

```python
#!/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:

```python
#!/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](https://usecoral.app/guides/codex-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:

```bash
#!/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

```python
#!/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.

<p data-cta="guide_body">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. <a href="/download">Get Coral for free</a></p>

## 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](https://usecoral.app/guides/codex-sandbox), 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:

| | Codex | Claude Code |
|---|---|---|
| Config | `hooks.json` or `[hooks]` in `config.toml` | `hooks` in `settings.json` |
| “Agent is waiting” event | None; use `PermissionRequest` | `Notification` |
| Failed tool calls | `PostToolUse` also runs after a failing Bash command | Separate `PostToolUseFailure` event |
| Handler types | `command`, `mcp_tool` | `command`, `http`, `mcp_tool`, `prompt`, `agent` |
| Turn them off | `[features] hooks = false` | `"disableAllHooks": true` |
| Plugin hooks | Gets `PLUGIN_ROOT`, plus `CLAUDE_PLUGIN_ROOT` for compatibility | `CLAUDE_PLUGIN_ROOT` |

The Claude Code column is from Anthropic’s [hooks reference](https://code.claude.com/docs/en/hooks). For its examples, see [Claude Code hooks](https://usecoral.app/guides/claude-code-hooks); for the rest of the comparison, [Codex vs Claude Code](https://usecoral.app/guides/codex-vs-claude-code).

## Where Coral fits

When you connect Codex in [Coral](https://usecoral.app/features), 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](https://usecoral.app/pricing).

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`.
