Skip to main content

agent_base/engine/
react_loop_guard.rs

1use async_trait::async_trait;
2
3// Re-export from agent-types (single source of truth).
4pub use agent_types::{GuardCtx, GuardDecision, StreamIntegrity};
5
6use crate::engine::runtime::{NoticeHandle, ProviderHandle};
7
8/// React Loop Guard trait — single unified entry point.
9///
10/// Runtime builds GuardCtx (with scene hints), guard decides what to do.
11/// The guard has full control: it can trust the hints or re-detect.
12#[async_trait]
13pub trait ReactLoopGuard: Send + Sync {
14    /// Unified entry point — guard judges the scene and returns a decision.
15    async fn on_turn(&self, ctx: &GuardCtx) -> GuardDecision;
16
17    /// Callback when model calls a tool (new)
18    ///
19    /// Default implementation: returns Complete (let other logic continue)
20    ///
21    /// Usage:
22    /// - DefaultGuard can return RestoreThinking here
23    /// - Other guards can record tool call history
24    ///
25    /// Note: This callback is called before tool execution, Guard cannot prevent tool execution
26    async fn on_tool_call(&self, _ctx: &GuardCtx) -> GuardDecision {
27        GuardDecision::Complete
28    }
29
30    /// Receive the engine's notice handle (Batch E). Called once by the
31    /// runtime when the guard is registered, before any run starts. Guards
32    /// that want to surface display-only notices (e.g. judge degradation)
33    /// store the handle; the default implementation ignores it, so existing
34    /// implementers are unaffected.
35    fn set_notice(&self, _handle: NoticeHandle) {}
36
37    /// Receive the engine's live provider handle. Called once by the runtime
38    /// when the guard is registered (next to [`Self::set_notice`]). A guard
39    /// that runs LLM calls of its own (e.g. a completion judge) MUST resolve
40    /// its client through this handle instead of holding the provider clone
41    /// it was built with: a `/model` swap replaces the engine's provider, and
42    /// a build-time clone keeps answering as the old model (session
43    /// 20261107_27dc727a). Default: ignore, so existing implementers are
44    /// unaffected.
45    fn set_provider_source(&self, _handle: ProviderHandle) {}
46}
47
48/// Default guard — fails on degenerate states, completes on normal flow.
49///
50/// This is the default guard injected when no custom guard is set.
51/// It provides basic safety: reasoning-only and empty responses fail,
52/// text-only responses complete normally.
53pub struct NoopGuard;
54
55#[async_trait]
56impl ReactLoopGuard for NoopGuard {
57    async fn on_turn(&self, ctx: &GuardCtx) -> GuardDecision {
58        if ctx.is_reasoning_only || ctx.is_empty_response {
59            GuardDecision::Fail {
60                error: if ctx.is_reasoning_only {
61                    "model produced only reasoning, no output".to_string()
62                } else {
63                    "model returned empty response".to_string()
64                },
65            }
66        } else {
67            GuardDecision::Complete
68        }
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use agent_types::{FinishReason, SessionId};
76
77    #[tokio::test]
78    async fn test_noop_guard_returns_complete() {
79        let guard = NoopGuard;
80        let ctx = GuardCtx {
81            run_actions: vec![],
82            session_id: SessionId {
83                id: 1,
84                external_id: None,
85            },
86            turn_count: 1,
87            user_input: "test".to_string(),
88            model_response: "response".to_string(),
89            finish_reason: FinishReason::Stop,
90            available_tools: vec![],
91            reasoning_only_strikes: 0,
92            empty_response_strikes: 0,
93            run_has_actions: false,
94            last_tool_calls_invalid: false,
95            all_user_inputs: vec!["test".to_string()],
96            is_reasoning_only: false,
97            is_empty_response: false,
98            is_text_only: false,
99            awaiting_human: false,
100            thinking_disabled: false,
101            original_thinking_enabled: true,
102            remaining_turns: 50,
103            integrity: Default::default(),
104            has_visible_text: false,
105            has_thinking: false,
106            silent_retries_in_round: 0,
107        };
108
109        assert!(matches!(guard.on_turn(&ctx).await, GuardDecision::Complete));
110    }
111
112    #[tokio::test]
113    async fn test_noop_guard_handles_degenerate_states() {
114        let guard = NoopGuard;
115
116        // reasoning-only → Fail
117        let ctx = GuardCtx {
118            session_id: SessionId::new(1),
119            turn_count: 1,
120            user_input: "test".to_string(),
121            model_response: "".to_string(),
122            finish_reason: FinishReason::Stop,
123            available_tools: vec![],
124            reasoning_only_strikes: 1,
125            empty_response_strikes: 0,
126            run_has_actions: false,
127            run_actions: vec![],
128            last_tool_calls_invalid: false,
129            all_user_inputs: vec!["test".to_string()],
130            is_reasoning_only: true,
131            is_empty_response: false,
132            is_text_only: false,
133            awaiting_human: false,
134            thinking_disabled: false,
135            original_thinking_enabled: true,
136            remaining_turns: 50,
137            integrity: Default::default(),
138            has_visible_text: false,
139            has_thinking: false,
140            silent_retries_in_round: 0,
141        };
142        assert!(matches!(
143            guard.on_turn(&ctx).await,
144            GuardDecision::Fail { .. }
145        ));
146
147        // empty response → Fail
148        let mut ctx2 = ctx.clone();
149        ctx2.is_reasoning_only = false;
150        ctx2.is_empty_response = true;
151        assert!(matches!(
152            guard.on_turn(&ctx2).await,
153            GuardDecision::Fail { .. }
154        ));
155
156        // text-only → Complete
157        let mut ctx3 = ctx.clone();
158        ctx3.is_reasoning_only = false;
159        ctx3.is_empty_response = false;
160        ctx3.is_text_only = true;
161        assert!(matches!(
162            guard.on_turn(&ctx3).await,
163            GuardDecision::Complete
164        ));
165
166        // no flags → Complete
167        let mut ctx4 = ctx.clone();
168        ctx4.is_reasoning_only = false;
169        ctx4.is_text_only = false;
170        assert!(matches!(
171            guard.on_turn(&ctx4).await,
172            GuardDecision::Complete
173        ));
174    }
175}