Skip to main content

agent_works/guard/
default.rs

1use agent_base::ProviderHandle;
2use agent_base::engine::react_loop_guard::{GuardCtx, GuardDecision, ReactLoopGuard};
3use agent_base::llm_trait::LlmProvider;
4use async_trait::async_trait;
5use std::sync::{Arc, Mutex};
6
7use super::config::{DefaultGuardConfig, ReasoningOnlyAction};
8use super::judge::call_completion_judge;
9
10/// Default guard implementation
11///
12/// Does not manage its own state; uses RunState information from GuardCtx.
13pub struct DefaultGuard {
14    config: DefaultGuardConfig,
15    llm_client: Option<Arc<dyn LlmProvider>>,
16    /// The engine's live provider handle, injected at registration
17    /// (`ReactLoopGuard::set_provider_source`). When set, the completion
18    /// judge resolves its client through it at call time — the provider that
19    /// served the turn, never a build-time snapshot. `llm_client` is the
20    /// fallback for guards not mounted on an engine.
21    provider_source: Mutex<Option<ProviderHandle>>,
22    /// Notice handle injected by the engine (Batch E). `None` until
23    /// `set_notice` is called — without it, guard behavior is unchanged.
24    notice: Mutex<Option<agent_base::NoticeHandle>>,
25}
26
27impl DefaultGuard {
28    pub fn new(config: DefaultGuardConfig) -> Self {
29        Self {
30            config,
31            llm_client: None,
32            provider_source: Mutex::new(None),
33            notice: Mutex::new(None),
34        }
35    }
36
37    /// Create a new DefaultGuard with LLM client for judge functionality
38    pub fn with_llm_client(config: DefaultGuardConfig, llm_client: Arc<dyn LlmProvider>) -> Self {
39        Self {
40            config,
41            llm_client: Some(llm_client),
42            provider_source: Mutex::new(None),
43            notice: Mutex::new(None),
44        }
45    }
46
47    /// The client the completion judge runs on: the engine's live provider
48    /// when the engine injected a source (post-`/model`-swap this is the
49    /// provider that served the turn being judged), else the client wired at
50    /// build time. See [`ProviderHandle`].
51    fn judge_client(&self) -> Option<Arc<dyn LlmProvider>> {
52        if let Some(source) = self.provider_source.lock().unwrap().as_ref() {
53            return Some(source.current());
54        }
55        self.llm_client.clone()
56    }
57
58    /// Snapshot the notice handle, if the engine injected one.
59    fn notice_handle(&self) -> Option<agent_base::NoticeHandle> {
60        self.notice.lock().unwrap().clone()
61    }
62
63    /// Run the completion judge for a text-only turn and map its verdict to a
64    /// guard decision: nudge back into the loop on `done:false`, the
65    /// configured fail-open/fail-closed behavior when the judge call fails.
66    async fn judge_completion(&self, ctx: &GuardCtx) -> GuardDecision {
67        let client = self.judge_client();
68        match call_completion_judge(
69            client.as_ref(),
70            &ctx.user_input,
71            &ctx.model_response,
72            &ctx.all_user_inputs,
73            self.config.judge_fail_open,
74            self.config.judge_timeout_secs,
75            self.config.recent_user_count,
76            self.notice_handle().as_ref(),
77        )
78        .await
79        {
80            Ok(judge) => {
81                if judge.done {
82                    GuardDecision::Complete
83                } else {
84                    GuardDecision::Continue {
85                        nudge: Some(format!(
86                            "Your answer is incomplete: {}. Continue working on the task.",
87                            judge.reason
88                        )),
89                    }
90                }
91            }
92            Err(e) => {
93                // Judge failed — behavior depends on judge_fail_open config
94                tracing::warn!("completion judge failed: {}", e);
95                if self.config.judge_fail_open {
96                    GuardDecision::Complete
97                } else {
98                    GuardDecision::Continue {
99                        nudge: Some(
100                            "Cannot verify task completion, please continue working.".to_string(),
101                        ),
102                    }
103                }
104            }
105        }
106    }
107
108    // ── Scene handlers ──────────────────────────────────────────────────
109
110    async fn handle_reasoning_only(&self, ctx: &GuardCtx) -> GuardDecision {
111        let strikes = ctx.reasoning_only_strikes;
112
113        match self.config.reasoning_only_action {
114            ReasoningOnlyAction::Fail => {
115                // Default behavior: fail after max strikes
116                if strikes >= self.config.reasoning_only_max_strikes {
117                    return GuardDecision::Fail {
118                        error: "model produced only reasoning across multiple turns".to_string(),
119                    };
120                }
121
122                GuardDecision::Continue {
123                    nudge: Some(self.config.reasoning_only_nudge.clone()),
124                }
125            }
126            ReasoningOnlyAction::DisableThinking => {
127                // New behavior: disable thinking after max strikes
128                if strikes >= self.config.reasoning_only_max_strikes {
129                    // Check if thinking is already disabled
130                    if ctx.thinking_disabled {
131                        // Thinking is already disabled but still reasoning-only → fail
132                        return GuardDecision::Fail {
133                            error: "model produced only reasoning even after thinking was disabled"
134                                .to_string(),
135                        };
136                    }
137
138                    // Disable thinking and continue
139                    return GuardDecision::DisableThinking {
140                        nudge: self.config.disable_thinking_nudge.clone(),
141                    };
142                }
143
144                GuardDecision::Continue {
145                    nudge: Some(self.config.reasoning_only_nudge.clone()),
146                }
147            }
148        }
149    }
150
151    async fn handle_empty_response(&self, ctx: &GuardCtx) -> GuardDecision {
152        let strikes = ctx.empty_response_strikes;
153
154        if strikes >= self.config.empty_response_max_strikes {
155            return GuardDecision::Fail {
156                error: "model returned empty responses repeatedly".to_string(),
157            };
158        }
159
160        GuardDecision::Continue {
161            nudge: Some(self.config.empty_response_nudge.clone()),
162        }
163    }
164
165    async fn handle_text_only(&self, ctx: &GuardCtx) -> GuardDecision {
166        // Session 20260904_efad759c: after the react-side truncation guard
167        // rejected a spawn_agent call, the model replied with a text-only
168        // "success" narrative and the completion judge — which sees only the
169        // user inputs and that narrative — passed it, ending the run with
170        // zero children spawned. A text-only turn that follows rejected tool
171        // calls is definitionally not completion: the work the text describes
172        // never executed. Skip the judge, push the model back to re-issuing.
173        // (Bounded: the react truncation breaker fails the run at its strike
174        // limit, and max_turns still applies.)
175        if ctx.last_tool_calls_invalid {
176            tracing::info!(
177                session_id = ctx.session_id.id,
178                turn = ctx.turn_count,
179                "text-only response after rejected tool calls — not completion, re-issuing"
180            );
181            return GuardDecision::Continue {
182                nudge: Some(
183                    "Your previous tool call was NOT executed — its arguments \
184                     were invalid or truncated. The report you just wrote \
185                     describes work that never happened; do not narrate \
186                     results. Re-issue the tool call with complete, valid \
187                     JSON arguments."
188                        .to_string(),
189                ),
190            };
191        }
192
193        let input_len = ctx.user_input.chars().count();
194        let output_len = ctx.model_response.chars().count();
195
196        // Short-response detection: user asked a substantial question but the
197        // model gave a very short answer — likely incomplete.
198        let is_short_response = self.config.detect_short_response
199            && input_len > self.config.short_response_min_input
200            && output_len < self.config.short_response_max_output
201            && input_len > output_len;
202
203        if is_short_response {
204            tracing::info!(
205                input_chars = input_len,
206                output_chars = output_len,
207                min_input = self.config.short_response_min_input,
208                max_output = self.config.short_response_max_output,
209                run_has_actions = ctx.run_has_actions,
210                "short response detected in text-only branch"
211            );
212
213            if ctx.run_has_actions && self.config.use_llm_judge {
214                // Skip LLM judge for very large inputs — judge would be too slow
215                const INPUT_LEN_LIMIT: usize = 10_000;
216                if input_len > INPUT_LEN_LIMIT {
217                    tracing::info!(
218                        input_chars = input_len,
219                        input_limit = INPUT_LEN_LIMIT,
220                        "skipping LLM judge — user input too large, trusting model"
221                    );
222                    return GuardDecision::Complete;
223                }
224                // Short response after tools — call judge to verify completion
225                self.judge_completion(ctx).await
226            } else {
227                // Short response without tools or judge disabled — nudge
228                GuardDecision::Continue {
229                    nudge: Some(self.config.short_response_nudge.clone()),
230                }
231            }
232        } else if ctx.run_has_actions && self.config.use_llm_judge {
233            // Non-short response after tools — check skip threshold
234            if output_len >= self.config.judge_skip_threshold {
235                tracing::debug!(
236                    response_chars = output_len,
237                    threshold = self.config.judge_skip_threshold,
238                    "text-only response long enough, skipping judge"
239                );
240                return GuardDecision::Complete;
241            }
242
243            // Skip LLM judge for very large inputs — judge would be too slow
244            const INPUT_LEN_LIMIT: usize = 10_000;
245            if input_len > INPUT_LEN_LIMIT {
246                tracing::info!(
247                    input_chars = input_len,
248                    input_limit = INPUT_LEN_LIMIT,
249                    "skipping LLM judge — user input too large, trusting model"
250                );
251                return GuardDecision::Complete;
252            }
253
254            tracing::info!(
255                response_chars = output_len,
256                threshold = self.config.judge_skip_threshold,
257                "text-only response short, calling judge"
258            );
259            self.judge_completion(ctx).await
260        } else {
261            GuardDecision::Complete
262        }
263    }
264}
265
266#[async_trait]
267impl ReactLoopGuard for DefaultGuard {
268    fn set_notice(&self, handle: agent_base::NoticeHandle) {
269        *self.notice.lock().unwrap() = Some(handle);
270    }
271
272    fn set_provider_source(&self, handle: ProviderHandle) {
273        *self.provider_source.lock().unwrap() = Some(handle);
274    }
275
276    async fn on_turn(&self, ctx: &GuardCtx) -> GuardDecision {
277        if ctx.is_reasoning_only {
278            self.handle_reasoning_only(ctx).await
279        } else if ctx.is_empty_response {
280            self.handle_empty_response(ctx).await
281        } else if ctx.awaiting_human {
282            // The latest tool batch parked on a human step (a design-canvas
283            // screen awaiting a pick) and no tool ran after it: ending here is
284            // *waiting for the user*, not an incomplete task — their pick (or
285            // skip) is the next input. A "continue working" nudge in this
286            // state steamrolls interactive flows (session 20261022_bb8c2dc3:
287            // the completion judge pushed the model on and it decided the
288            // user's design choices for them).
289            GuardDecision::Complete
290        } else if ctx.is_text_only {
291            self.handle_text_only(ctx).await
292        } else {
293            GuardDecision::Complete
294        }
295    }
296
297    async fn on_tool_call(&self, ctx: &GuardCtx) -> GuardDecision {
298        // Restore thinking when:
299        // 1. Thinking is currently disabled (by guard)
300        // 2. Original thinking was enabled (user wanted thinking)
301        // 3. Model calls a tool (showing it's working again)
302        if ctx.thinking_disabled && ctx.original_thinking_enabled {
303            tracing::info!(
304                session_id = ctx.session_id.id,
305                turn = ctx.turn_count,
306                "tool call detected while thinking disabled, restoring thinking"
307            );
308            return GuardDecision::RestoreThinking;
309        }
310
311        GuardDecision::Complete
312    }
313}