Skip to main content

Module hooks

Module hooks 

Source
Expand description

Hook system for observing and reacting to SDK events.

Hooks fire on stream events after the Codex CLI has already acted. Block/Abort affect what the SDK consumer sees, not what the CLI executes. Pre-execution gating requires ApprovalPolicy::OnRequest combined with an ApprovalCallback.

§Design

  • First-match dispatch: hooks are evaluated in order; the first matching hook handles the event.
  • Configurable timeout behavior: if a hook callback exceeds its timeout, the behavior is controlled per-hook via HookTimeoutBehavior. Defaults to FailOpen (event passes through). Use FailClosed for security/gating hooks where a timeout must not silently allow the event.
  • Async callbacks: hooks can perform I/O (logging, webhooks, etc.).

§Processing order

Hooks run before the EventCallback. For each event the pipeline is:

  1. Hooks (async, semantically classified, first-match)
  2. EventCallback (sync, raw event, observe/filter/transform)

If a hook returns HookDecision::Block or HookDecision::Abort, the EventCallback is not invoked for that event.

§Example

use std::sync::Arc;
use std::time::Duration;
use codex_cli_sdk::hooks::{HookMatcher, HookEvent, HookDecision, HookOutput, HookTimeoutBehavior};

let hook = HookMatcher {
    event: HookEvent::CommandStarted,
    command_filter: Some("rm".into()),
    callback: Arc::new(|input, _ctx| {
        Box::pin(async move {
            eprintln!("Blocked dangerous command: {:?}", input.command);
            HookOutput {
                decision: HookDecision::Block,
                reason: Some("dangerous command".into()),
                replacement_event: None,
            }
        })
    }),
    timeout: Some(Duration::from_secs(5)),
    on_timeout: HookTimeoutBehavior::FailClosed, // block on timeout for security hooks
};

Structs§

HookContext
Context provided alongside the hook input.
HookInput
Input provided to a hook callback.
HookMatcher
A hook registration: matches events and invokes a callback.
HookOutput
Output returned by a hook callback.

Enums§

HookDecision
Decision made by a hook.
HookEvent
The semantic event type that hooks match against.
HookTimeoutBehavior
What happens when a hook callback exceeds its timeout.

Functions§

build_hook_input
Build a HookInput from a classified event.
classify_hook_event
Classify a ThreadEvent into a HookEvent, if applicable.
dispatch_hook
Dispatch an event through the hook chain (first-match).

Type Aliases§

HookCallback
Async hook callback.