codex-cli-sdk 0.0.1

Rust SDK for the OpenAI Codex CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! 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`](crate::ApprovalPolicy)
//! combined with an [`ApprovalCallback`](crate::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`](crate::callback::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
//!
//! ```rust
//! 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
//! };
//! ```

use crate::types::events::ThreadEvent;
use crate::types::items::ThreadItem;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

// ── Hook event classification ─────────────────────────────────

/// The semantic event type that hooks match against.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum HookEvent {
    /// A command execution item started (shell command about to run or running).
    CommandStarted,
    /// A command execution item completed successfully.
    CommandCompleted,
    /// A command execution item failed (non-zero exit or error status).
    CommandFailed,
    /// A file change item completed.
    FileChangeCompleted,
    /// An agent message item completed.
    AgentMessage,
    /// The turn completed successfully.
    TurnCompleted,
    /// The turn failed.
    TurnFailed,
}

// ── Hook callback types ───────────────────────────────────────

/// Input provided to a hook callback.
#[derive(Debug, Clone)]
pub struct HookInput {
    /// The classified hook event.
    pub hook_event: HookEvent,
    /// The shell command (if applicable).
    pub command: Option<String>,
    /// The exit code (if applicable).
    pub exit_code: Option<i32>,
    /// The message text (if applicable, e.g. agent message or error).
    pub message_text: Option<String>,
    /// The raw event that triggered this hook.
    pub raw_event: ThreadEvent,
}

/// Context provided alongside the hook input.
#[derive(Debug, Clone)]
pub struct HookContext {
    /// The current thread ID, if known.
    pub thread_id: Option<String>,
    /// Number of turns completed so far.
    pub turn_count: u32,
}

/// Output returned by a hook callback.
#[derive(Debug, Clone)]
pub struct HookOutput {
    /// The decision for how to handle the event.
    pub decision: HookDecision,
    /// Optional human-readable reason for the decision.
    pub reason: Option<String>,
    /// Replacement event (only used with `HookDecision::Modify`).
    pub replacement_event: Option<ThreadEvent>,
}

impl Default for HookOutput {
    fn default() -> Self {
        Self {
            decision: HookDecision::Allow,
            reason: None,
            replacement_event: None,
        }
    }
}

/// What happens when a hook callback exceeds its timeout.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum HookTimeoutBehavior {
    /// Let the event pass through unchanged (default).
    ///
    /// Safe for observability hooks (logging, metrics) where a slow hook
    /// should not block the event stream.
    #[default]
    FailOpen,

    /// Block (suppress) the event, as if the hook returned [`HookDecision::Block`].
    ///
    /// Use this for security or gating hooks where a timeout must not silently
    /// allow a potentially dangerous event through.
    FailClosed,
}

/// Decision made by a hook.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HookDecision {
    /// Allow the event to pass through unchanged.
    Allow,
    /// Block (suppress) the event — consumer won't see it.
    Block,
    /// Replace the event with `HookOutput::replacement_event`.
    Modify,
    /// Abort — terminate the stream entirely.
    Abort,
}

/// Async hook callback.
pub type HookCallback = Arc<
    dyn Fn(HookInput, HookContext) -> Pin<Box<dyn Future<Output = HookOutput> + Send>>
        + Send
        + Sync,
>;

// ── Hook matcher ──────────────────────────────────────────────

/// A hook registration: matches events and invokes a callback.
#[derive(Clone)]
pub struct HookMatcher {
    /// Which event type this hook matches.
    pub event: HookEvent,
    /// Optional command substring filter (only relevant for Command* events).
    pub command_filter: Option<String>,
    /// The async callback to invoke when matched.
    pub callback: HookCallback,
    /// Per-hook timeout override. Falls back to `ThreadOptions::default_hook_timeout`.
    pub timeout: Option<Duration>,
    /// What to do if the callback exceeds its timeout.
    ///
    /// Defaults to [`HookTimeoutBehavior::FailOpen`] (event passes through).
    /// Set to [`HookTimeoutBehavior::FailClosed`] for security/gating hooks.
    pub on_timeout: HookTimeoutBehavior,
}

impl std::fmt::Debug for HookMatcher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HookMatcher")
            .field("event", &self.event)
            .field("command_filter", &self.command_filter)
            .field("timeout", &self.timeout)
            .field("on_timeout", &self.on_timeout)
            .finish()
    }
}

// ── Classification ────────────────────────────────────────────

/// Classify a `ThreadEvent` into a `HookEvent`, if applicable.
///
/// Returns `None` for events that don't map to any hook (e.g. `ThreadStarted`,
/// `TurnStarted`, approval requests, streaming deltas).
pub fn classify_hook_event(event: &ThreadEvent) -> Option<HookEvent> {
    use crate::types::items::CommandExecutionStatus;

    match event {
        ThreadEvent::ItemStarted {
            item: ThreadItem::CommandExecution { .. },
        } => Some(HookEvent::CommandStarted),

        ThreadEvent::ItemCompleted {
            item: ThreadItem::CommandExecution { status, .. },
        } => match status {
            CommandExecutionStatus::Completed => Some(HookEvent::CommandCompleted),
            CommandExecutionStatus::Failed => Some(HookEvent::CommandFailed),
            CommandExecutionStatus::InProgress => None,
        },

        ThreadEvent::ItemCompleted {
            item: ThreadItem::FileChange { .. },
        } => Some(HookEvent::FileChangeCompleted),

        ThreadEvent::ItemCompleted {
            item: ThreadItem::AgentMessage { .. },
        } => Some(HookEvent::AgentMessage),

        ThreadEvent::TurnCompleted { .. } => Some(HookEvent::TurnCompleted),
        ThreadEvent::TurnFailed { .. } => Some(HookEvent::TurnFailed),

        _ => None,
    }
}

/// Build a `HookInput` from a classified event.
pub fn build_hook_input(hook_event: HookEvent, event: &ThreadEvent) -> HookInput {
    let (command, exit_code, message_text) = match event {
        ThreadEvent::ItemStarted {
            item: ThreadItem::CommandExecution { command, .. },
        }
        | ThreadEvent::ItemCompleted {
            item: ThreadItem::CommandExecution { command, .. },
        } => {
            let exit_code = match event {
                ThreadEvent::ItemCompleted {
                    item: ThreadItem::CommandExecution { exit_code, .. },
                } => *exit_code,
                _ => None,
            };
            (Some(command.clone()), exit_code, None)
        }

        ThreadEvent::ItemCompleted {
            item: ThreadItem::AgentMessage { text, .. },
        } => (None, None, Some(text.clone())),

        ThreadEvent::TurnFailed { error } => (None, None, Some(error.message.clone())),

        _ => (None, None, None),
    };

    HookInput {
        hook_event,
        command,
        exit_code,
        message_text,
        raw_event: event.clone(),
    }
}

// ── Dispatch ──────────────────────────────────────────────────

/// Dispatch an event through the hook chain (first-match).
///
/// Returns the `HookOutput` from the first matching hook, or `None` if no hook matched.
/// On timeout, the hook is skipped (fail-open) and dispatch continues to the next hook.
pub async fn dispatch_hook(
    event: &ThreadEvent,
    hooks: &[HookMatcher],
    context: &HookContext,
    default_timeout: Duration,
) -> Option<HookOutput> {
    let hook_event = classify_hook_event(event)?;
    let input = build_hook_input(hook_event.clone(), event);

    for hook in hooks {
        if hook.event != hook_event {
            continue;
        }

        // Apply command filter if present.
        if let Some(ref filter) = hook.command_filter {
            match &input.command {
                Some(cmd) if cmd.contains(filter.as_str()) => {}
                _ => continue,
            }
        }

        let timeout = hook.timeout.unwrap_or(default_timeout);
        let future = (hook.callback)(input.clone(), context.clone());

        match tokio::time::timeout(timeout, future).await {
            Ok(output) => return Some(output),
            Err(_) => {
                tracing::warn!(
                    "Hook timed out after {:?} for {:?} — {:?}",
                    timeout,
                    hook.event,
                    hook.on_timeout,
                );
                match hook.on_timeout {
                    HookTimeoutBehavior::FailOpen => continue,
                    HookTimeoutBehavior::FailClosed => {
                        return Some(HookOutput {
                            decision: HookDecision::Block,
                            reason: Some(format!("hook timeout after {timeout:?} (fail-closed)")),
                            replacement_event: None,
                        });
                    }
                }
            }
        }
    }

    None
}

// ── Tests ─────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::events::Usage;

    fn make_command_started(cmd: &str) -> ThreadEvent {
        ThreadEvent::ItemStarted {
            item: ThreadItem::CommandExecution {
                id: "cmd-1".into(),
                command: cmd.into(),
                aggregated_output: String::new(),
                exit_code: None,
                status: crate::types::items::CommandExecutionStatus::InProgress,
            },
        }
    }

    fn make_command_completed(cmd: &str, code: i32) -> ThreadEvent {
        ThreadEvent::ItemCompleted {
            item: ThreadItem::CommandExecution {
                id: "cmd-1".into(),
                command: cmd.into(),
                aggregated_output: "output".into(),
                exit_code: Some(code),
                status: crate::types::items::CommandExecutionStatus::Completed,
            },
        }
    }

    fn make_turn_completed() -> ThreadEvent {
        ThreadEvent::TurnCompleted {
            usage: Usage {
                input_tokens: 100,
                cached_input_tokens: 0,
                output_tokens: 50,
            },
        }
    }

    fn make_context() -> HookContext {
        HookContext {
            thread_id: Some("thread-1".into()),
            turn_count: 0,
        }
    }

    #[test]
    fn classify_command_started() {
        let event = make_command_started("ls -la");
        assert_eq!(classify_hook_event(&event), Some(HookEvent::CommandStarted));
    }

    #[test]
    fn classify_command_completed() {
        let event = make_command_completed("ls", 0);
        assert_eq!(
            classify_hook_event(&event),
            Some(HookEvent::CommandCompleted)
        );
    }

    #[test]
    fn classify_turn_completed() {
        let event = make_turn_completed();
        assert_eq!(classify_hook_event(&event), Some(HookEvent::TurnCompleted));
    }

    #[test]
    fn classify_unmatched_returns_none() {
        let event = ThreadEvent::TurnStarted;
        assert_eq!(classify_hook_event(&event), None);
    }

    #[test]
    fn build_input_extracts_command() {
        let event = make_command_started("git status");
        let input = build_hook_input(HookEvent::CommandStarted, &event);
        assert_eq!(input.command, Some("git status".into()));
        assert_eq!(input.exit_code, None);
    }

    #[test]
    fn build_input_extracts_exit_code() {
        let event = make_command_completed("ls", 1);
        let input = build_hook_input(HookEvent::CommandCompleted, &event);
        assert_eq!(input.exit_code, Some(1));
    }

    #[tokio::test]
    async fn dispatch_first_match() {
        let hook = HookMatcher {
            event: HookEvent::CommandStarted,
            command_filter: None,
            callback: Arc::new(|_input, _ctx| {
                Box::pin(async {
                    HookOutput {
                        decision: HookDecision::Block,
                        reason: Some("blocked".into()),
                        replacement_event: None,
                    }
                })
            }),
            timeout: None,
            on_timeout: Default::default(),
        };

        let event = make_command_started("ls");
        let ctx = make_context();
        let result = dispatch_hook(&event, &[hook], &ctx, Duration::from_secs(5)).await;

        assert!(result.is_some());
        let output = result.unwrap();
        assert_eq!(output.decision, HookDecision::Block);
    }

    #[tokio::test]
    async fn dispatch_command_filter() {
        let hook = HookMatcher {
            event: HookEvent::CommandStarted,
            command_filter: Some("rm".into()),
            callback: Arc::new(|_input, _ctx| {
                Box::pin(async {
                    HookOutput {
                        decision: HookDecision::Block,
                        reason: None,
                        replacement_event: None,
                    }
                })
            }),
            timeout: None,
            on_timeout: Default::default(),
        };

        let ctx = make_context();

        // Should NOT match "ls"
        let ls_event = make_command_started("ls -la");
        let result = dispatch_hook(&ls_event, &[hook], &ctx, Duration::from_secs(5)).await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn dispatch_command_filter_matches() {
        let hook = HookMatcher {
            event: HookEvent::CommandStarted,
            command_filter: Some("rm".into()),
            callback: Arc::new(|_input, _ctx| {
                Box::pin(async {
                    HookOutput {
                        decision: HookDecision::Block,
                        reason: None,
                        replacement_event: None,
                    }
                })
            }),
            timeout: None,
            on_timeout: Default::default(),
        };

        let ctx = make_context();

        let rm_event = make_command_started("rm -rf /tmp/test");
        let result = dispatch_hook(&rm_event, &[hook], &ctx, Duration::from_secs(5)).await;
        assert!(result.is_some());
        assert_eq!(result.unwrap().decision, HookDecision::Block);
    }

    #[tokio::test]
    async fn dispatch_no_match_returns_none() {
        let hook = HookMatcher {
            event: HookEvent::TurnCompleted,
            command_filter: None,
            callback: Arc::new(|_input, _ctx| Box::pin(async { HookOutput::default() })),
            timeout: None,
            on_timeout: Default::default(),
        };

        let event = make_command_started("ls");
        let ctx = make_context();
        let result = dispatch_hook(&event, &[hook], &ctx, Duration::from_secs(5)).await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn dispatch_timeout_fails_open() {
        let hook = HookMatcher {
            event: HookEvent::CommandStarted,
            command_filter: None,
            callback: Arc::new(|_input, _ctx| {
                Box::pin(async {
                    // Simulate a slow hook
                    tokio::time::sleep(Duration::from_secs(10)).await;
                    HookOutput {
                        decision: HookDecision::Block,
                        reason: None,
                        replacement_event: None,
                    }
                })
            }),
            timeout: Some(Duration::from_millis(10)),
            on_timeout: HookTimeoutBehavior::FailOpen,
        };

        let event = make_command_started("ls");
        let ctx = make_context();
        let result = dispatch_hook(&event, &[hook], &ctx, Duration::from_secs(5)).await;

        // Timeout → fail-open → no match (since it's the only hook)
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn dispatch_timeout_fail_closed_blocks() {
        let hook = HookMatcher {
            event: HookEvent::CommandStarted,
            command_filter: None,
            callback: Arc::new(|_input, _ctx| {
                Box::pin(async {
                    tokio::time::sleep(Duration::from_secs(10)).await;
                    HookOutput::default()
                })
            }),
            timeout: Some(Duration::from_millis(10)),
            on_timeout: HookTimeoutBehavior::FailClosed,
        };

        let event = make_command_started("dangerous-cmd");
        let ctx = make_context();
        let result = dispatch_hook(&event, &[hook], &ctx, Duration::from_secs(5)).await;

        // Timeout + fail-closed → Block decision returned
        assert!(result.is_some());
        let output = result.unwrap();
        assert_eq!(output.decision, HookDecision::Block);
        assert!(output.reason.as_deref().unwrap_or("").contains("timeout"));
    }

    #[tokio::test]
    async fn dispatch_all_four_decisions() {
        for decision in [
            HookDecision::Allow,
            HookDecision::Block,
            HookDecision::Modify,
            HookDecision::Abort,
        ] {
            let d = decision.clone();
            let hook = HookMatcher {
                event: HookEvent::TurnCompleted,
                command_filter: None,
                callback: Arc::new(move |_input, _ctx| {
                    let d = d.clone();
                    Box::pin(async move {
                        HookOutput {
                            decision: d,
                            reason: None,
                            replacement_event: None,
                        }
                    })
                }),
                timeout: None,
                on_timeout: Default::default(),
            };

            let event = make_turn_completed();
            let ctx = make_context();
            let result = dispatch_hook(&event, &[hook], &ctx, Duration::from_secs(5)).await;
            assert!(result.is_some());
            assert_eq!(result.unwrap().decision, decision);
        }
    }
}