agy-bridge 0.16.1

Async Rust bridge and native runtime for the Google Antigravity SDK
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! Hook bridge for the Antigravity SDK.
//!
//! Defines Rust-side hook types that wrap callbacks for agent lifecycle
//! hook points: pre-turn, post-turn, pre-tool-call-decide, post-tool-call,
//! compaction, session start/end, tool errors, user interactions, and
//! tool-input transformation.
//!
//! The actual Python wrapping (creating `PyO3` classes that the SDK dispatches to)
//! requires the Python runtime and is gated behind integration tests.

use std::time::SystemTime;

use serde::{Deserialize, Serialize};

/// Result of a hook decision (mirrors SDK `HookResult`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HookResult {
    /// Whether execution should proceed.
    pub allow: bool,
    /// Optional explanation or response message.
    pub message: String,
}

impl HookResult {
    /// Create an "allow" result with an empty message.
    #[must_use]
    pub const fn allow() -> Self {
        Self {
            allow: true,
            message: String::new(),
        }
    }

    /// Create an "allow" result with a message.
    #[must_use]
    pub fn allow_with_message(message: impl Into<String>) -> Self {
        Self {
            allow: true,
            message: message.into(),
        }
    }

    /// Create a "deny" result with a reason.
    #[must_use]
    pub fn deny(reason: impl Into<String>) -> Self {
        Self {
            allow: false,
            message: reason.into(),
        }
    }
}

// ── Hook context structs ────────────────────────────────────────────────────

/// Persistent session metadata passed to session-lifecycle hooks.
///
/// Created when a session starts and carried through to session-end hooks
/// so hooks can correlate events, measure session duration, and identify
/// the agent instance.
#[non_exhaustive]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SessionContext {
    /// Unique identifier for this session.
    pub session_id: String,
    /// Numeric agent identifier within the bridge runtime.
    pub agent_id: u64,
    /// Wall-clock timestamp of when the session was started.
    ///
    /// Defaults to [`UNIX_EPOCH`](SystemTime::UNIX_EPOCH) if the backend
    /// does not supply this field.
    #[serde(default = "SessionContext::default_started_at")]
    pub started_at: SystemTime,
}

impl SessionContext {
    /// Fallback value when `started_at` is absent from the JSON payload.
    fn default_started_at() -> SystemTime {
        SystemTime::UNIX_EPOCH
    }
}

/// Context passed to [`HookPoint::OnSessionStart`] hooks.
#[non_exhaustive]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OnSessionStartContext {
    /// Session metadata for the newly started session.
    pub session: SessionContext,
}

/// Context passed to [`HookPoint::OnSessionEnd`] hooks.
#[non_exhaustive]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OnSessionEndContext {
    /// Session metadata for the ending session.
    pub session: SessionContext,
}

/// Context passed to [`HookPoint::OnCompaction`] hooks.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OnCompactionContext {}

/// Context passed to [`HookPoint::OnInteraction`] hooks.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OnInteractionContext {
    /// The interaction message content.
    pub message: String,
}

/// Context passed to [`HookPoint::PreTurn`] hooks.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PreTurnContext {
    /// The user prompt for this turn.
    pub prompt: String,
    /// The 1-based turn number.
    pub turn_number: u32,
}

impl PreTurnContext {
    /// Create a new pre-turn context.
    #[must_use]
    pub fn new(prompt: impl Into<String>, turn_number: u32) -> Self {
        Self {
            prompt: prompt.into(),
            turn_number,
        }
    }
}

/// Context passed to [`HookPoint::PostTurn`] hooks.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostTurnContext {
    /// The model's response text for this turn.
    pub response_text: String,
    /// The 1-based turn number.
    pub turn_number: u32,
}

/// Context passed to [`HookPoint::PreToolCallDecide`] hooks.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PreToolCallDecideContext {
    /// Name of the tool about to be called.
    #[serde(alias = "name")]
    pub tool_name: String,
    /// Arguments the tool will receive.
    #[serde(alias = "args", default)]
    pub tool_args: serde_json::Value,
}

impl PreToolCallDecideContext {
    /// Create a new pre-tool-call-decide context.
    #[must_use]
    pub fn new(tool_name: impl Into<String>, tool_args: serde_json::Value) -> Self {
        Self {
            tool_name: tool_name.into(),
            tool_args,
        }
    }
}

/// Context passed to [`HookPoint::PostToolCall`] hooks.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostToolCallContext {
    /// Name of the tool that was called.
    #[serde(alias = "name")]
    pub tool_name: String,
    /// Arguments the tool received.
    #[serde(alias = "args", default)]
    pub tool_args: serde_json::Value,
    /// The tool's return value (serialised).
    pub result: String,
    /// Structured metadata from the tool response (if any).
    #[serde(default)]
    pub metadata: serde_json::Value,
}

/// Context passed to [`HookPoint::OnToolError`] hooks.
///
/// # Error contract
///
/// A Rust tool signals failure in one of two ways, and only one of them
/// reaches this hook:
///
/// - Returning `Err(ToolError)` is a **hard** error. The model sees exactly
///   [`ToolError::to_string()`](llm_tool::ToolError) (the human-readable
///   `message`), and this hook fires. Any structured
///   [`metadata`](llm_tool::ToolError::metadata) attached to the `ToolError`
///   — which is *never* shown to the model — is surfaced here on
///   [`metadata`](Self::metadata) so host code can branch on it.
/// - Returning `Ok(ToolOutput)` is a **soft** result: it is delivered to the
///   [`PostToolCall`](HookPoint::PostToolCall) hook instead, carrying its own
///   `result` string and `metadata`.
///
/// This makes success and error handling symmetric: both
/// [`PostToolCallContext`] and `OnToolErrorContext` carry structured
/// `metadata` alongside their model-facing payload.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OnToolErrorContext {
    /// Name of the tool that errored.
    #[serde(alias = "name")]
    pub tool_name: String,
    /// Arguments the tool received.
    #[serde(alias = "args", default)]
    pub tool_args: serde_json::Value,
    /// The error message — exactly what the model sees
    /// ([`ToolError::to_string()`](llm_tool::ToolError)).
    pub error: String,
    /// Structured metadata attached to the originating
    /// [`ToolError`](llm_tool::ToolError), if any.
    ///
    /// This is the error-path counterpart to
    /// [`PostToolCallContext::metadata`]. It is populated from the
    /// `ToolError`'s metadata map and is **never** sent to the model — it
    /// exists purely for hooks, policies, and logging. Defaults to
    /// [`serde_json::Value::Null`] when the error carried no metadata.
    #[serde(default)]
    pub metadata: serde_json::Value,
}

impl OnToolErrorContext {
    /// Whether the error denotes a registry-lookup miss, i.e. the model asked
    /// for a tool that isn't registered.
    ///
    /// This mirrors [`ToolError::is_not_found`](llm_tool::ToolError::is_not_found):
    /// it inspects [`metadata`](Self::metadata) for the
    /// [`ERROR_KIND_KEY`](llm_tool::ToolError::ERROR_KIND_KEY) marker set to
    /// [`KIND_NOT_REGISTERED`](llm_tool::ToolError::KIND_NOT_REGISTERED),
    /// letting hosts distinguish a routing miss from a genuine handler failure
    /// without matching on message strings.
    #[must_use]
    pub fn is_not_found(&self) -> bool {
        self.metadata
            .get(llm_tool::ToolError::ERROR_KIND_KEY)
            .and_then(serde_json::Value::as_str)
            == Some(llm_tool::ToolError::KIND_NOT_REGISTERED)
    }
}
/// Identifies the point in the agent lifecycle where a hook fires.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HookPoint {
    /// Before the model processes a turn (receives the user prompt).
    PreTurn,
    /// After the model completes a turn (receives the model response).
    PostTurn,
    /// Before a tool call is executed — can approve or deny.
    PreToolCallDecide,
    /// After a tool call completes (receives the tool result).
    PostToolCall,
    /// Fires when the context window is compacted (trimmed to fit limits).
    OnCompaction,
    /// Fires when a new agent session begins.
    OnSessionStart,
    /// Fires when an agent session ends.
    OnSessionEnd,
    /// Fires when a tool call returns an error.
    OnToolError,
    /// Fires on each user interaction (message received from user).
    OnInteraction,
    /// Fires when the turn reaches fully idle to decide whether to stop or continue.
    Stop,
}

/// Decision returned by a Stop lifecycle hook.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum StopDecision {
    /// Allows the turn execution to terminate and transition to idle.
    #[default]
    #[serde(rename = "ALLOW_STOP")]
    AllowStop,
    /// Blocks termination, injects reason as a system prompt, and resumes execution.
    #[serde(rename = "CONTINUE")]
    Continue,
}

impl StopDecision {
    /// Returns the string representation.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::AllowStop => "ALLOW_STOP",
            Self::Continue => "CONTINUE",
        }
    }

    /// Returns the proto numeric value for localharness `StopResult`.
    #[must_use]
    pub const fn to_proto_i32(self) -> i32 {
        match self {
            Self::AllowStop => 1,
            Self::Continue => 2,
        }
    }

    /// Convert from protobuf numeric value.
    #[must_use]
    pub const fn from_proto_i32(val: i32) -> Option<Self> {
        match val {
            1 => Some(Self::AllowStop),
            2 => Some(Self::Continue),
            _ => None,
        }
    }
}

impl std::fmt::Display for StopDecision {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for StopDecision {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "ALLOW_STOP" | "allow_stop" => Ok(Self::AllowStop),
            "CONTINUE" | "continue" => Ok(Self::Continue),
            other => Err(format!("Unrecognized StopDecision: {other}")),
        }
    }
}

/// Arguments delivered to a Stop hook when the root turn reaches idle.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct StopArgs {
    /// Most recent assistant response text in the turn.
    #[serde(default)]
    pub response_text: String,
    /// Unique identifier of the trajectory executing this turn.
    #[serde(default)]
    pub trajectory_id: String,
    /// The 0-based iteration count of Stop hook continuations within the current turn cycle.
    #[serde(default)]
    pub continuation_count: u32,
    /// The reason why the trajectory stopped (strongly typed enum).
    #[serde(default)]
    pub stop_reason: crate::types::StopReason,
    /// Error message if execution stopped due to a fatal error.
    #[serde(default)]
    pub error_message: String,
}

/// Result returned by a Stop lifecycle hook.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct StopHookResult {
    /// Whether to allow the turn to stop or continue execution.
    #[serde(default)]
    pub decision: StopDecision,
    /// Feedback/prompt injected into the conversation when decision is CONTINUE.
    #[serde(default)]
    pub reason: String,
}

impl StopHookResult {
    /// Creates a stop result allowing the turn to complete.
    #[must_use]
    pub const fn allow() -> Self {
        Self {
            decision: StopDecision::AllowStop,
            reason: String::new(),
        }
    }

    /// Creates a stop result continuing the turn with the given feedback reason.
    #[must_use]
    pub fn continue_with(reason: impl Into<String>) -> Self {
        Self {
            decision: StopDecision::Continue,
            reason: reason.into(),
        }
    }
}

/// A named hook registration that will be attached to an agent.
///
/// The `callback_id` is an opaque identifier used to look up the actual
/// Rust callback in the hook runner. This decouples serialization from
/// function pointers.
///
/// # Construction
///
/// Prefer [`HookEntry::new`] which validates eagerly. Direct struct
/// construction is allowed for deserialization but skips validation —
/// call [`HookEntry::validate`] before use if constructing manually.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookEntry {
    /// Descriptive name (e.g. `"safety_gate"`).
    pub name: String,
    /// Which lifecycle point this hook fires at.
    pub point: HookPoint,
    /// Opaque callback identifier for the hook runner to resolve.
    pub callback_id: String,
}

impl HookEntry {
    /// Create a new hook entry, validating that `name` and `callback_id`
    /// are non-empty.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidConfig`](crate::error::Error::InvalidConfig)
    /// if `name` or `callback_id` is empty or whitespace-only.
    ///
    /// # Examples
    ///
    /// ```
    /// # use agy_bridge::hooks::{HookEntry, HookPoint};
    /// let entry = HookEntry::new("safety_gate", HookPoint::PreToolCallDecide, "cb_safety")
    ///     .expect("valid entry");
    /// assert_eq!(entry.name, "safety_gate");
    /// ```
    pub fn new(
        name: impl Into<String>,
        point: HookPoint,
        callback_id: impl Into<String>,
    ) -> Result<Self, crate::error::Error> {
        let entry = Self {
            name: name.into(),
            point,
            callback_id: callback_id.into(),
        };
        entry.validate()?;
        Ok(entry)
    }

    /// Validate that the entry has non-empty name and `callback_id`.
    ///
    /// # Errors
    ///
    /// Returns `Err` with a description if the name or `callback_id` is empty.
    pub fn validate(&self) -> Result<(), crate::error::Error> {
        if self.name.trim().is_empty() {
            return Err(crate::error::Error::InvalidConfig {
                message: "HookEntry name must not be empty".to_owned(),
            });
        }
        if self.callback_id.trim().is_empty() {
            return Err(crate::error::Error::InvalidConfig {
                message: format!("HookEntry '{}' has an empty callback_id", self.name),
            });
        }
        Ok(())
    }
}

/// An ordered list of hooks to attach to an agent.
///
/// Hooks at the same [`HookPoint`] fire in registration order.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HookSet {
    entries: Vec<HookEntry>,
}

impl HookSet {
    /// Create an empty hook set.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Register a hook.
    ///
    /// If a hook with the same name AND hook point already exists, it is
    /// replaced and a warning is logged.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the entry fails validation (empty name or `callback_id`).
    pub fn push(&mut self, entry: HookEntry) -> Result<(), crate::error::Error> {
        entry.validate()?;
        if let Some(pos) = self
            .entries
            .iter()
            .position(|e| e.name == entry.name && e.point == entry.point)
        {
            tracing::warn!(
                hook = %entry.name,
                point = %entry.point.label(),
                "duplicate hook name+point in HookSet — replacing previous entry"
            );
            self.entries[pos] = entry;
        } else {
            self.entries.push(entry);
        }
        Ok(())
    }

    /// Iterate over hooks at a specific point, in registration order.
    pub fn at_point(&self, point: HookPoint) -> impl Iterator<Item = &HookEntry> {
        self.entries.iter().filter(move |e| e.point == point)
    }

    /// Iterate over all hooks.
    pub fn iter(&self) -> impl Iterator<Item = &HookEntry> {
        self.entries.iter()
    }

    /// Number of registered hooks.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the set is empty.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

impl From<HookSet> for Vec<HookEntry> {
    fn from(set: HookSet) -> Self {
        set.entries
    }
}

impl From<&HookSet> for Vec<HookEntry> {
    fn from(set: &HookSet) -> Self {
        set.entries.clone()
    }
}

impl IntoIterator for HookSet {
    type Item = HookEntry;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.entries.into_iter()
    }
}

impl FromIterator<HookEntry> for HookSet {
    fn from_iter<T: IntoIterator<Item = HookEntry>>(iter: T) -> Self {
        let mut set = Self::new();
        for entry in iter {
            let name = entry.name.clone();
            if let Err(e) = set.push(entry) {
                tracing::error!(
                    error = %e,
                    hook = %name,
                    "Failed to push hook entry during from_iter"
                );
            }
        }
        set
    }
}

impl From<Vec<HookEntry>> for HookSet {
    fn from(entries: Vec<HookEntry>) -> Self {
        Self::from_iter(entries)
    }
}

impl<const N: usize> From<[HookEntry; N]> for HookSet {
    fn from(entries: [HookEntry; N]) -> Self {
        Self::from_iter(entries)
    }
}
// ── Callback types ──────────────────────────────────────────────────────────

/// Type alias for the transform-tool-input closure signature.
///
/// Accepts a pre-tool-call context and optionally returns replacement
/// arguments.  `None` means "no change".
type TransformToolInputFn =
    dyn Fn(&PreToolCallDecideContext) -> Option<serde_json::Value> + Send + Sync;

/// The boxed closure type behind [`HookCallback::OnToolError`].
///
/// Accepts a tool-error context and returns the error representation the model
/// should see, or `None` to fall back to the harness's default formatting.
type OnToolErrorFn = dyn Fn(&OnToolErrorContext) -> Option<String> + Send + Sync;

/// A registered hook callback, keyed by hook point.
///
/// Each variant wraps a boxed closure that receives the strongly-typed context
/// for that hook point. Mirroring the SDK's hook contracts:
/// [`PreTurn`](Self::PreTurn) and [`PreToolCallDecide`](Self::PreToolCallDecide)
/// are *deciding* hooks that return a [`HookResult`] to allow or deny the turn /
/// tool call; [`OnToolError`](Self::OnToolError) is a *transform* hook that
/// returns the error representation the model should see (`None` = use the
/// harness's default formatting); all other variants are fire-and-forget
/// observers.
#[non_exhaustive]
pub enum HookCallback {
    /// Callback invoked before each agent turn.
    ///
    /// Returns a [`HookResult`] so it can allow or deny the turn before the
    /// model runs (SDK `PreTurnHook`, a `DecideHook[Content]`).
    PreTurn(Box<dyn Fn(&PreTurnContext) -> HookResult + Send + Sync>),
    /// Callback invoked after each agent turn completes.
    PostTurn(Box<dyn Fn(&PostTurnContext) + Send + Sync>),
    /// Callback invoked before deciding whether to execute a tool call.
    PreToolCallDecide(Box<dyn Fn(&PreToolCallDecideContext) -> HookResult + Send + Sync>),
    /// Callback invoked after a tool call completes.
    PostToolCall(Box<dyn Fn(&PostToolCallContext) + Send + Sync>),
    /// Callback invoked when a tool call produces an error.
    ///
    /// Returns the error representation the model should see, or `None` to let
    /// the harness use its default error formatting (SDK `OnToolErrorHook`, a
    /// `TransformHook[Exception, Any]`).
    OnToolError(Box<OnToolErrorFn>),
    /// Callback invoked when a new agent session begins.
    OnSessionStart(Box<dyn Fn(&OnSessionStartContext) + Send + Sync>),
    /// Callback invoked when an agent session ends.
    OnSessionEnd(Box<dyn Fn(&OnSessionEndContext) + Send + Sync>),
    /// Callback invoked when conversation history is compacted.
    OnCompaction(Box<dyn Fn(&OnCompactionContext) + Send + Sync>),
    /// Callback invoked on each interaction event.
    OnInteraction(Box<dyn Fn(&OnInteractionContext) -> HookResult + Send + Sync>),
    /// Callback invoked when the turn reaches fully idle to decide whether to stop or continue.
    Stop(Box<dyn Fn(&StopArgs) -> StopHookResult + Send + Sync>),
    /// Transform tool input arguments before execution.
    ///
    /// The closure receives the pre-tool-call context and may return
    /// `Some(new_args)` to replace the tool arguments, or `None` to
    /// leave them unchanged.  Multiple transform hooks are applied
    /// sequentially — each receives the (possibly already-modified)
    /// arguments from the previous transform.
    TransformToolInput(Box<TransformToolInputFn>),
}

impl HookCallback {
    /// Returns the [`HookPoint`] this callback is associated with.
    #[must_use]
    pub(crate) const fn hook_point(&self) -> HookPoint {
        match self {
            Self::PreTurn(_) => HookPoint::PreTurn,
            Self::PostTurn(_) => HookPoint::PostTurn,
            Self::PreToolCallDecide(_) | Self::TransformToolInput(_) => {
                HookPoint::PreToolCallDecide
            }
            Self::PostToolCall(_) => HookPoint::PostToolCall,
            Self::OnToolError(_) => HookPoint::OnToolError,
            Self::OnSessionStart(_) => HookPoint::OnSessionStart,
            Self::OnSessionEnd(_) => HookPoint::OnSessionEnd,
            Self::OnCompaction(_) => HookPoint::OnCompaction,
            Self::OnInteraction(_) => HookPoint::OnInteraction,
            Self::Stop(_) => HookPoint::Stop,
        }
    }
}

impl HookPoint {
    /// Hook point wire string for `PreTurn`.
    pub const PRE_TURN: &str = "pre_turn";
    /// Hook point wire string for `PostTurn`.
    pub const POST_TURN: &str = "post_turn";
    /// Hook point wire string for `PreToolCallDecide`.
    pub const PRE_TOOL_CALL_DECIDE: &str = "pre_tool_call_decide";
    /// Hook point wire string for `PostToolCall`.
    pub const POST_TOOL_CALL: &str = "post_tool_call";
    /// Hook point wire string for `OnCompaction`.
    pub const ON_COMPACTION: &str = "on_compaction";
    /// Hook point wire string for `OnSessionStart`.
    pub const ON_SESSION_START: &str = "on_session_start";
    /// Hook point wire string for `OnSessionEnd`.
    pub const ON_SESSION_END: &str = "on_session_end";
    /// Hook point wire string for `OnToolError`.
    pub const ON_TOOL_ERROR: &str = "on_tool_error";
    /// Hook point wire string for `OnInteraction`.
    pub const ON_INTERACTION: &str = "on_interaction";
    /// Hook point wire string for `Stop`.
    pub const STOP: &str = "stop";

    /// Human-readable label for logging and wire protocols.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::PreTurn => Self::PRE_TURN,
            Self::PostTurn => Self::POST_TURN,
            Self::PreToolCallDecide => Self::PRE_TOOL_CALL_DECIDE,
            Self::PostToolCall => Self::POST_TOOL_CALL,
            Self::OnCompaction => Self::ON_COMPACTION,
            Self::OnSessionStart => Self::ON_SESSION_START,
            Self::OnSessionEnd => Self::ON_SESSION_END,
            Self::OnToolError => Self::ON_TOOL_ERROR,
            Self::OnInteraction => Self::ON_INTERACTION,
            Self::Stop => Self::STOP,
        }
    }

    /// Return the canonical wire string for this hook point.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        self.label()
    }
}

impl core::str::FromStr for HookPoint {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            Self::PRE_TURN => Ok(Self::PreTurn),
            Self::POST_TURN => Ok(Self::PostTurn),
            Self::PRE_TOOL_CALL_DECIDE => Ok(Self::PreToolCallDecide),
            Self::POST_TOOL_CALL => Ok(Self::PostToolCall),
            Self::ON_COMPACTION => Ok(Self::OnCompaction),
            Self::ON_SESSION_START => Ok(Self::OnSessionStart),
            Self::ON_SESSION_END => Ok(Self::OnSessionEnd),
            Self::ON_TOOL_ERROR => Ok(Self::OnToolError),
            Self::ON_INTERACTION => Ok(Self::OnInteraction),
            Self::STOP => Ok(Self::Stop),
            other => Err(format!("Unknown hook point: {other}")),
        }
    }
}

// Manual Debug impl because closures don't implement Debug.
impl std::fmt::Debug for HookCallback {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("HookCallback::")?;
        match self {
            Self::TransformToolInput(_) => f.write_str("transform_tool_input"),
            other => f.write_str(other.hook_point().label()),
        }
    }
}