Event Hooks

Resolved 💬 76 comments Opened Aug 9, 2025 by aehlke Closed Mar 27, 2026
💡 Likely answer: A maintainer (etraut-openai, contributor) responded on this thread — see the highlighted reply below.

Let us define event hooks with pattern matching, to trigger scripts/commands before/after codex behaviors.

View original on GitHub ↗

76 Comments

backnotprop · 10 months ago

Prioritize please 🙏 - hooks in the lifecycle will allow for advanced steering/context-engineering, and enterprise guardrailing. Plus cool community whatever.

andrewschreiber · 10 months ago

Would encourage the Codex team to follow Claude Code's schema!

https://docs.claude.com/en/docs/claude-code/hooks

nikhil-pandey · 9 months ago

+1

fullofcaffeine · 9 months ago

+1000, I'm really missing this from CC.

backnotprop · 9 months ago

Claude Code and Cursor both support blocking + feedback providing hooks.

This will prove to be an integral feature for harnesses... looking forward to Codex's implementation.

InakiBes · 8 months ago

Please prioritize 🙏 - hooks are very necessary

Thevetat · 8 months ago

This is the final feature that will make me throw anthropic in the trash and never look back. You would get so many power users if you add hooks in.

doggy8088 · 7 months ago

Indeed, hooks unlock so much potential.

vilnitsky · 7 months ago

Missing this too!

ZeldOcarina · 7 months ago

We are badly missing approval requests hooks!!

raine · 7 months ago

My use case is that I need to run a script when user submits their prompt, so that I can show in a tmux status bar that an agent is active in that window. Claude can handle this with the UserPromptSubmit hook.

a112121788 · 7 months ago

My solution: clone this repository and implement the corresponding functionality using Claude; I really can't wait for the official team to add this feature.

backnotprop · 7 months ago

Unfortunately, we are releasing https://github.com/eqtylab/cupcake without codex native support.

Optimistic in this getting implemented... working with large enterprises on cupcake and we want to get codex out there where stakeholders (cyber assurance, dev directors) feel confident and have an opportunity to own their own alignment.

sebthom · 6 months ago

I'd love to see hooks so I can apply things like newline separator normalization, formatting etc after edits. the builtin edit tool screws up new line separators on every edit.

numman-ali · 6 months ago

+1

RobertHH-IS · 6 months ago

+1

backnotprop · 6 months ago

This is important for holistic governance. The agentic OS is coming. If codex intends to compete - hooks are mandatory. In this harness and any future non-harness.

Also it's fun to build random integrations. For those that prefer plan mode - hooks around agent mode would enable better management or custom planning (similar to how opencode does plugins) - https://github.com/backnotprop/plannotator

Otherwise you can offload tasks like lint/format/test. You can prevent the agent from stopping. You can automate governance. Etc etc

Eriz1818 · 6 months ago

I implemented an event hooks system in my fork, xCodex (xcodex), that can run external scripts on lifecycle events (fire-and-forget) and pass a JSON payload via stdin (with a payload-path file fallback for large payloads). It’s still WIP and may have bugs, but if you want to try it today: https://github.com/Eriz1818/xCodex (docs: docs/xcodex/hooks.md, examples: examples/hooks/).

If maintainers are interested in upstreaming something like this, I’m happy to open an issue/PR proposal and adapt it to match Codex’s contribution guidelines / desired behavior (I understand new feature PRs may not be accepted right now).

Supported events in xCodex include:

  • session-start / session-end
  • agent-turn-complete
  • model-request-started / model-response-completed
  • tool-call-started / tool-call-finished
  • approval-requested (with kind: exec | apply-patch | elicitation)

Config example ($CODEX_HOME/config.toml)

[hooks]
tool_call_finished = [["python3", "/absolute/path/to/tool_call_summary.py"]]
approval_requested = [["python3", "/absolute/path/to/approval_notify.py"]]

Pattern matching example (in the hook script)

#!/usr/bin/env python3
import json, pathlib, sys

payload = json.loads(sys.stdin.read() or "{}")
if payload.get("payload-path"):
    payload = json.loads(pathlib.Path(payload["payload-path"]).read_text())

# Only react to a specific tool and only on success
if payload.get("type") != "tool-call-finished":
    raise SystemExit(0)
if (payload.get("tool-name") or payload.get("tool_name")) != "shell":
    raise SystemExit(0)
if payload.get("success") is not True:
    raise SystemExit(0)

print("shell finished successfully")

You can also scaffold and test hooks in the fork:

xcodex hooks init
xcodex hooks test --configured-only
davidagold · 6 months ago

Will there be a Rust API for this? If so, I'd be very interested to see what can be done with PyO3 to allow users to write Python hooks for Codex.

Eriz1818 · 6 months ago

Interesting idea. I am not 100% sure, but I believe even Claude Code doesn't have in-process hooks yet. I am also concerned about the security, stability, and sandbox policy concerns with in-process hooks. But I am experimenting with it.

Galgol23 · 6 months ago

Yes please, ASAP, CC is starting to pass you from behind, do not sleep, add HOOKS :)

juanre · 6 months ago

This is the single most important missing feature holding codex behind.

Thevetat · 6 months ago

As of last night, OpenAI subscriptions work with OpenCode officially. You can use the plugin feature of OpenCode to create hooks 1:1 of Claude Code etc. I converted everything over to using it last night, and it is an amazing experience.

dipree · 6 months ago

Event hooks would help open source tooling integrate with Codex, similar to how Claude Code exposes pre/post command hooks. Given the recent commitment to OSS support, this seems well-aligned.

Eriz1818 · 6 months ago

xCodex (https://github.com/Eriz1818/xCodex) now has three hook modes:

  • External hooks (spawn per event): simplest/most portable; runs a command per hook event.
  • Python Host hooks (“py-box”, long-lived): recommended for stateful Python; a single persistent Python process receives JSONL events over stdin. In practice it’s “near in-proc” performance while staying out-of-process. No surprise xCodex freezes/crashes, because of the hook crashing.
  • PyO3 hooks (in-proc): Python runs inside xcodex via PyO3. This is available, but requires compiling a separate PyO3-enabled build.

Claude hooks are supported, as is.

xcodex hooks build pyo3 --yes --python "$(command -v python3.11)" --ref main

Performance (release build, Python 3.11.14, payload 373 bytes; 3 runs):

  • External spawn: ~20.87–21.48 ms/event (~47–48 ev/s)
  • Python Host (“py-box”): ~1.88–1.90 µs/event (~526k–532k ev/s)
  • In-proc PyO3: ~1.38–1.45 µs/event (~690k–725k ev/s)

Larger payloads:

  • ~12 KB (12040 bytes): external 20.98–22.07 ms, py-box 11.71–12.85 µs, PyO3 2.09–2.48 µs
  • ~20 KB (20040 bytes): external 21.80–22.37 ms, py-box 17.41–19.55 µs, PyO3 2.35–2.84 µs
  • ~200 KB (200040 bytes): external 24.03–24.51 ms, py-box 162.56–170.48 µs, PyO3 12.19–13.49 µs
taf2 · 6 months ago

that was easy - codex FTW

<img width="1907" height="767" alt="Image" src="https://github.com/user-attachments/assets/c3756c20-1765-44c5-b29d-a12a13398072" />

https://github.com/openai/codex/pull/9440

am-will · 5 months ago

I created all of Claude Code's hooks, plus PostCompact hooks. I tried to make a PR, but they don't accept them. Slightly rude reponse from them but its my fault for letting Codex do the PR. I didnt read the contribution guidelines lol

Anyway, they work. Hopefully we get Hooks added sooner rather than later.

https://github.com/openai/codex/pull/9796

am-will · 5 months ago
that was easy - codex FTW <img alt="Image" width="1907" height="767" src="https://private-user-images.githubusercontent.com/1568/537302340-c3756c20-1765-44c5-b29d-a12a13398072.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NjkzMTYyNDUsIm5iZiI6MTc2OTMxNTk0NSwicGF0aCI6Ii8xNTY4LzUzNzMwMjM0MC1jMzc1NmMyMC0xNzY1LTQ0YzUtYjI5ZC1hMTJhMTMzOTgwNzIucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFNBNTNQUUs0WkElMkYyMDI2MDEyNSUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNjAxMjVUMDQzOTA1WiZYLUFtei1FeHBpcmVzPTMwMCZYLUFtei1TaWduYXR1cmU9NzUwNjU3ZWNhY2NmMmViMDkwZDMzZjNmZTBkYmFjNjBkY2QzZWUwY2IzN2YwMGNjNTVjY2YyNDFiYzY5MDVjMSZYLUFtei1TaWduZWRIZWFkZXJzPWhvc3QifQ.i310Pdpz8jeuko8E1euQ8rhWTMb9EAOzjq8XHCVpxKs"> #9440

Oh I see you got the same comment I did. I dont feel so bad now lol. Nice to see they're coming soon. This will make Codex, more or less, as featured as Claude Code. Exciting times.

<img width="1010" height="360" alt="Image" src="https://github.com/user-attachments/assets/41ccf8fc-cf6f-4c9e-8fae-41a3a65e242a" />

svarlamov · 5 months ago

@etraut-openai Thank you so much for all your work on Codex, it's one of my favorite agents, especially for complicated problems! I'm just wondering if you have an idea of the timeline for hooks? Don't mean to push -- just trying to figure out if it's worth spending the time to work on alternatives or if support is right around the corner.

For context, I'm trying to support Codex in Git AI. Thank you!

etraut-openai contributor · 5 months ago

@svarlamov, support for hooks is under development. I'll be able to share more details once it's a little further along.

taf2 · 5 months ago

looks like agent-turn-start is in main now

abhisek · 5 months ago

This is an important feature. Need this to maintain audit trail of coding agents in https://github.com/safedep/gryph

atbabers · 5 months ago

I’d also like this for https://github.com/atbabers/intentra-cli

You’ll notice a lot of other vendors support this. Excited to see this come into fruition.

jbeno · 5 months ago

@etraut-openai congrats on Codex desktop app launch! Are hooks planned for both that and CLI?

etraut-openai contributor · 5 months ago

@jbeno, we will integrate it into the core agent loop so all Codex surfaces will benefit from it.

am-will · 5 months ago

Event Hooks are in the latest 0.99 build, all the plumbing for new event types have been added.

Stopping semantics need to be added, but this logic should be easy to implement since it already technically exists (for example, when it stops to ask for permissions).

I bet they launch soon.

michaeljboscia · 5 months ago

I got hooks working. I'll let folks know if it blows up.

am-will · 5 months ago
I got hooks working. I'll let folks know if it blows up.

tell us or else

michaeljboscia · 5 months ago
tell us or else

I'm new to GitHub.
You can't see the PR?

etraut-openai contributor · 5 months ago

@michaeljboscia, we're not accepting unsolicited code contributions in this project. Please refer to our contribution guidelines for details.

Work on event hooks is underway. We'll announce when it's ready for use.

am-will · 5 months ago
> tell us or else I'm new to GitHub. You can't see the PR?

haha nah boss. i thought you were talking about the official hooks. they arent fully wired up yet so that's why i was confused lol.

they just added AfterToolUse hook. Not functional yet tho.

Mygod · 5 months ago

Meanwhile, I ported my changes from https://github.com/openai/codex/issues/3247#issuecomment-3762213637 to event hooks and it's available here: https://github.com/Mygod/codex/commit/f4d7a3dd174e10eea7a8af3158cf83b7f8ed70d0
Just in case anyone wants approval notifications. :)

Mygod · 5 months ago

Not sure if this issue is better separate so I kept it as a comment in this thread for now. Details below.

We hit a notify-hook noise issue with multi-agent sessions:

  • agent-turn-complete fires for subagent completions (spawned/delegated threads), not just the top-level user turn.
  • In contrast, other user-blocking notify paths (exec/apply-patch/input/elicitation) are already gated to avoid subagent dispatch.

Why this is hard to handle downstream:

  • The legacy notify payload for agent-turn-complete does not include subagent/session-source metadata, so hooks can’t reliably filter parent vs subagent turns.

Local patch we applied:

Suggested upstream direction (backward-compatible):

  1. Make agent-turn-complete top-level-only by default, and/or
  2. Add a distinct subagent-turn-complete notify event, and/or
  3. Include session_source/subagent info in notify payloads so hooks can filter.
alario-tang · 4 months ago

Use case: real-time tool call progress in SDK integrations

We're building a chat application that integrates Codex via @openai/codex-sdk.
Currently thread.run() only returns finalResponse after the entire turn
completes — there's no way to receive intermediate tool call events (tool name,
status, input/output) as they happen.

This makes it impossible to show users real-time progress like "running shell
command X" or "reading file Y" during long-running tasks. Users see a blank
loading state for several minutes with zero feedback.

What we need:

  • An onToolCall / onProgress callback in thread.run() options, or
  • A streaming variant that emits tool call events as they occur

The Claude Code Agent SDK (@anthropic-ai/claude-agent-sdk) has the same gap.
Both SDKs expose only a final-result API, making it hard to build responsive UIs
on top of them.

veilm · 4 months ago

For anyone who urgently needs this feature for functionality you're building on top, note that codex already supports CODEX_TUI_RECORD_SESSION=1 and CODEX_TUI_SESSION_LOG_PATH=/path/to/file.jsonl which log all events for the current session immediately. So if your hooks are read-only (as in my use case), it's already possible to implement them with a simple wrapper that calls codex and polls the log file in the background

Kitenite · 4 months ago

This feature as been opened for over 6 months now? Wondering if there's an actual timeline for this or should we consider the hack above?

Mygod · 4 months ago

Given that it's already been over 6 "AI years", you can safely assume that this issue has been abandoned. /j

etraut-openai contributor · 4 months ago

We are actively working on it! More details to come soon.

alario-tang · 4 months ago
We are actively working on it! More details to come soon.

nice

am-will · 4 months ago

There have been numerous commits related to hooks in the last 3 weeks. They built the scaffolding already. I predict they release an experimental version in the next 2-3 weeks

EddyVinck · 4 months ago
We are actively working on it! More details to come soon.

Awesome news. I just switched from Claude and this was one of the first few things I noticed were missing in Codex. Looking forward to this!

solomatov · 4 months ago

@aehlke Is there any documentation on using hooks?

Nabstar3 · 4 months ago
@aehlke Is there any documentation on using hooks?

Is this feature complete yet?

cameronfyfe · 4 months ago

We need this if codex is to be fully embraced in enterprise. It's my preferred coding agent harness by far right now but lack of custom hooks on bash calls is preventing me from using it for devops monitoring workflows at work because I can't satisfy our guardrail policies using codex.

2tbmz9y2xt-lang · 4 months ago

Production Use Case: Multi-Agent Memory Discipline with External DB

We run a multi-agent setup (4 agents: Codex CLI, Claude Code, Cursor, GPT-5) coordinating on a consensus-critical blockchain codebase. All agents share persistent memory via Neon PostgreSQL (pgvector embeddings for semantic search).

What we need hooks for (prioritized)

| Priority | Event | Use Case |
|----------|-------|----------|
| P0 | SessionStart | Load hot context from Neon DB (agent statuses, recent memories, active tasks) before first turn. Currently using MCP tool call as workaround — agent can forget to call it. |
| P0 | Stop / SessionEnd | Persist session summary + embeddings to Neon before exit. Without this, work done in last turns is lost if agent doesn't self-checkpoint. |
| P1 | PreCompact | Write checkpoint with full-context embedding before compaction destroys it. This is the single highest-value hook for long-running sessions — once context is compacted, the agent can't recover what it knew. |
| P1 | PreToolUse (blocking) | Governance: block destructive git commands (push --force, reset --hard, rm -rf). Currently using approval_policy but need finer control. |
| P2 | PostToolUse (config-driven) | Detect merge/push events in tool output → trigger compliance checks. Currently the after_tool_use Vec is always empty — only programmatic registration. |
| P2 | UserPromptSubmit | Inject cross-agent delta (what other agents did since last check) before each turn. |

Current workaround: Discipline MCP Server

Since Codex lacks lifecycle hooks, we built a custom MCP server providing 6 lifecycle-equivalent tool calls: session_init, checkpoint, session_summary, cross_agent_delta, post_merge_check, compliance_status.

Problem: This is "soft enforcement" — the agent can skip calling session_init even though AGENTS.md says "MANDATORY". Real hooks would be deterministic.

Config suggestion

Aligned with Claude Code's proven pattern, but adapted to TOML:

[[hooks.session_start]]
command = "/path/to/load-hot-context.sh"
timeout_ms = 5000
on_failure = "continue"

[[hooks.pre_compact]]
command = "/path/to/checkpoint.sh"
timeout_ms = 10000
on_failure = "abort"  # Don't lose context without checkpoint

[[hooks.stop]]
command = "/path/to/session-summary.sh"
timeout_ms = 10000

[[hooks.pre_tool_use]]
command = "/path/to/governance-check.sh"
on_failure = "abort"  # Block dangerous commands

Context injection (critical)

The most valuable feature from Claude Code hooks is additionalContext — hook stdout can inject text that the model sees as system context:

{"hookSpecificOutput": {"additionalContext": "Agent status: codex=IDLE, claude=working on PR#413..."}}

This turns hooks from "fire-and-forget notifications" into "active context providers." Without this, SessionStart hooks can run scripts but can't feed results back to the model.

Source analysis notes

From reading the Rust source: HookEvent enum currently has only AfterAgent and AfterToolUse. The Hooks struct has after_tool_use: Vec::new() (always empty — no config path). The notify field is the only config-driven hook and only populates after_agent. The scaffolding for expansion is clean — adding variants to the enum + config parsing + dispatch points in tui/src/lib.rs and core/src/tools/orchestrator.rs would cover all the events above.

Looking forward to the official release! Happy to test early/experimental builds.

Morriz · 4 months ago

@aehlke may I ask why you closed this already?

> We are actively working on it! More details to come soon. Awesome news. I just switched from Claude and this was one of the first few things I noticed were missing in Codex. Looking forward to this!

@EddyVinck and where did you hear this?

aehlke · 4 months ago

@Morriz Many unnecessary pings in the ticket - that's why I closed it since they stated it's officially on the way. But I didn't realize they were using my ticket to officially track it. It's been reopened. I've unsubscribed from notifications instead.

zyb2569-ops · 4 months ago

We need hooks, has this feature been implemented?

am-will · 4 months ago

<img width="603" height="823" alt="Image" src="https://github.com/user-attachments/assets/268b9e87-a901-4fd3-b3e4-ac69b9eb1f77" />

https://x.com/LLMJunky/status/2031582374064951414?s=20

First of many hooks are starting to roll out.

jpcaparas · 4 months ago

Async hooks would be awesome too!

Geogboe · 4 months ago

@am-will I'm not available to view that thread. Can anyone give a quick overview of where these are defined? I'm not seeing options in config.toml or slash commands.

peytonrunyan · 4 months ago

@Geogboe in the release notes you'll find the link to this PR: https://github.com/openai/codex/pull/13276/changes

am-will · 4 months ago
@am-will I'm not available to view that thread. Can anyone give a quick overview of where these are defined? I'm not seeing options in config.toml or slash commands.

you should be able to. its public.

here's a start. ask codex to read the prs and help you set it up, it'll oblige! cheers

<img width="609" height="1093" alt="Image" src="https://github.com/user-attachments/assets/99a19ac1-9107-47b5-888d-db23d2ecbbc9" />

<img width="680" height="601" alt="Image" src="https://github.com/user-attachments/assets/65ed6144-a474-4fec-b2f7-c7e261a72e1f" />

m13v · 4 months ago

Claude Code shipped hooks recently and the pattern matching approach works well in practice. from our setup:

we define hooks in settings that fire on specific events - pre-tool-call, post-tool-call, notification triggers. the key design decision is whether hooks block the agent or run async.

for the scheduling side, we use launchd plists that trigger shell scripts on intervals. each script spawns an agent with a specific prompt. the hook system complements this by handling event-driven triggers that don't fit fixed schedules.

one thing that matters a lot: hooks that modify state need to be idempotent. our posting pipeline runs hourly and checks a database before posting to avoid duplicates - if the hook fires twice (launchd can do this on wake-from-sleep), the dedup query catches it.

would be useful if codex hooks supported: before/after patterns on specific tool names, environment variable injection from the hook config, and a way to pass hook output back into the agent context (not just succeed/fail)

m13v · 4 months ago

our hook + scheduling setup: https://github.com/m13v/social-autoposter/tree/main/launchd - launchd plists that trigger Claude agents on intervals. the dedup and rate limiting logic: https://github.com/m13v/social-autoposter/blob/main/skill/SKILL.md. the multi-agent tmux orchestration: https://github.com/m13v/tmux-background-agents

ori-cofounder · 4 months ago

Event hooks + GNAP could enable powerful multi-agent workflows:

Agent A completes task → event hook → triggers Agent B via shared git repo.

GNAP provides the coordination layer (tasks, runs, messages as JSON files). Codex event hooks could be the trigger mechanism. No external server needed.

ksdf7235 · 4 months ago

I’d like to add one more request to the hook expansion discussion: please publish a documented contract alongside the feature.

At the moment, Codex hooks look promising, but from a user/operator perspective, the rollout still feels incomplete. If hooks are going to be exposed even in an experimental state, I believe there should be at least a minimal official reference covering the following:

  • a list of supported event names
  • the config schema / valid structure
  • execution semantics and guarantees
  • stability expectations for experimental vs. stable behavior
  • a few working examples

Right now, users are left to reverse-engineer behavior from short changelog notes, scattered examples, and community experimentation. That makes it much harder to adopt hooks safely in real workflows, especially for people building orchestration, guardrails, or session lifecycle tooling.

The current frustration does not come only from the limited hook coverage, but also from the lack of a clear contract for the functionality that already exists. I think that is exactly the core issue. Even before adding many more events, it would already help a lot to properly document the current surface.

So my request is:

  1. Please expand hook coverage over time.
  2. But separately from that, please publish documentation, schema details, and the list of currently supported events for the existing hook surface as soon as possible.

Without that, users are not integrating against a documented interface; they are effectively beta-testing it through reverse engineering.

That is what ChatGPT 5.4 said. As for my own opinion, I do not really have any strong thoughts either way.

eternal-openai contributor · 4 months ago

Coming up soon @ksdf7235 ! It's all still experimental, but shaping up fast

etraut-openai contributor · 3 months ago

Event hooks are now available as an experimental feature. Refer to this documentation for details.

ofek · 3 months ago

@etraut-openai Why is Windows support temporarily disabled?

3Spiders · 3 months ago

do you have a plan to support "Edit|Write" matcher in PostToolUse、PreToolUse ? i think plenty of feature relies on this
@etraut-openai

YSAA1 · 3 months ago

补充一条建议:在现有 Hooks 体系中新增 PreCompact 生命周期事件(或 BeforeCompact),触发于手动/自动 compaction 前。建议包含 reason(manual/auto)、total_usage_tokens_before_compactionauto_compact_limitsession_id/thread_id/turn_idcwd、可选 recent_rollup_summary,并支持失败策略 on_error: continue|abort 与可选 decision 返回(continue/abort)。这个可以直接承接之前 #12208 的诉求。

3Spiders · 3 months ago
do you have a plan to support "Edit|Write" matcher in PostToolUse、PreToolUse ? i think plenty of feature relies on this @etraut-openai

@etraut-openai May I ask about the progress of this?

am-will · 3 months ago
do you have a plan to support "Edit|Write" matcher in PostToolUse、PreToolUse ? i think plenty of feature relies on this @etraut-openai

please and thank you. i have many hooks i can't even use because of this

etraut-openai contributor · 3 months ago

I'm going to lock this thread since it's now closed. If you'd like to report bugs or request additional extensions to the Event Hooks feature, please open new issues.