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            &ctx.run_actions,
74            self.config.judge_fail_open,
75            self.config.judge_timeout_secs,
76            self.config.recent_user_count,
77            self.notice_handle().as_ref(),
78        )
79        .await
80        {
81            Ok(judge) => {
82                // Observability only, and it was missing: the judge ran silent,
83                // so a run could not show whether it fired or on what. Log the
84                // verdict and what it had to judge with — the response length
85                // is the old signal (`judge_skip_threshold`), the tool trace is
86                // the new one, and watching the two together is how this gets
87                // tuned instead of guessed at.
88                tracing::info!(
89                    session_id = ctx.session_id.id,
90                    turn = ctx.turn_count,
91                    done = judge.done,
92                    response_chars = ctx.model_response.len(),
93                    run_tool_calls = ctx.run_actions.len(),
94                    reason = %judge.reason,
95                    "completion judge verdict"
96                );
97                if judge.done {
98                    GuardDecision::Complete
99                } else {
100                    GuardDecision::Continue {
101                        nudge: Some(format!(
102                            "Your answer is incomplete: {}. Continue working on the task.",
103                            judge.reason
104                        )),
105                    }
106                }
107            }
108            Err(e) => {
109                // Judge failed — behavior depends on judge_fail_open config
110                tracing::warn!("completion judge failed: {}", e);
111                if self.config.judge_fail_open {
112                    GuardDecision::Complete
113                } else {
114                    GuardDecision::Continue {
115                        nudge: Some(
116                            "Cannot verify task completion, please continue working.".to_string(),
117                        ),
118                    }
119                }
120            }
121        }
122    }
123
124    // ── Scene handlers ──────────────────────────────────────────────────
125
126    async fn handle_reasoning_only(&self, ctx: &GuardCtx) -> GuardDecision {
127        let strikes = ctx.reasoning_only_strikes;
128
129        match self.config.reasoning_only_action {
130            ReasoningOnlyAction::Fail => {
131                // Default behavior: fail after max strikes
132                if strikes >= self.config.reasoning_only_max_strikes {
133                    return GuardDecision::Fail {
134                        error: "model produced only reasoning across multiple turns".to_string(),
135                    };
136                }
137
138                GuardDecision::Continue {
139                    nudge: Some(self.config.reasoning_only_nudge.clone()),
140                }
141            }
142            ReasoningOnlyAction::DisableThinking => {
143                // New behavior: disable thinking after max strikes
144                if strikes >= self.config.reasoning_only_max_strikes {
145                    // Check if thinking is already disabled
146                    if ctx.thinking_disabled {
147                        // Thinking is already disabled but still reasoning-only → fail
148                        return GuardDecision::Fail {
149                            error: "model produced only reasoning even after thinking was disabled"
150                                .to_string(),
151                        };
152                    }
153
154                    // Disable thinking and continue
155                    return GuardDecision::DisableThinking {
156                        nudge: self.config.disable_thinking_nudge.clone(),
157                    };
158                }
159
160                GuardDecision::Continue {
161                    nudge: Some(self.config.reasoning_only_nudge.clone()),
162                }
163            }
164        }
165    }
166
167    async fn handle_empty_response(&self, ctx: &GuardCtx) -> GuardDecision {
168        let strikes = ctx.empty_response_strikes;
169
170        if strikes >= self.config.empty_response_max_strikes {
171            return GuardDecision::Fail {
172                error: "model returned empty responses repeatedly".to_string(),
173            };
174        }
175
176        GuardDecision::Continue {
177            nudge: Some(self.config.empty_response_nudge.clone()),
178        }
179    }
180
181    async fn handle_text_only(&self, ctx: &GuardCtx) -> GuardDecision {
182        // Session 20260904_efad759c: after the react-side truncation guard
183        // rejected a spawn_agent call, the model replied with a text-only
184        // "success" narrative and the completion judge — which sees only the
185        // user inputs and that narrative — passed it, ending the run with
186        // zero children spawned. A text-only turn that follows rejected tool
187        // calls is definitionally not completion: the work the text describes
188        // never executed. Skip the judge, push the model back to re-issuing.
189        // (Bounded: the react truncation breaker fails the run at its strike
190        // limit, and max_turns still applies.)
191        if ctx.last_tool_calls_invalid {
192            tracing::info!(
193                session_id = ctx.session_id.id,
194                turn = ctx.turn_count,
195                "text-only response after rejected tool calls — not completion, re-issuing"
196            );
197            return GuardDecision::Continue {
198                nudge: Some(
199                    "Your previous tool call was NOT executed — its arguments \
200                     were invalid or truncated. The report you just wrote \
201                     describes work that never happened; do not narrate \
202                     results. Re-issue the tool call with complete, valid \
203                     JSON arguments."
204                        .to_string(),
205                ),
206            };
207        }
208
209        let input_len = ctx.user_input.chars().count();
210        let output_len = ctx.model_response.chars().count();
211
212        // Short-response detection: user asked a substantial question but the
213        // model gave a very short answer — likely incomplete.
214        let is_short_response = self.config.detect_short_response
215            && input_len > self.config.short_response_min_input
216            && output_len < self.config.short_response_max_output
217            && input_len > output_len;
218
219        if is_short_response {
220            tracing::info!(
221                input_chars = input_len,
222                output_chars = output_len,
223                min_input = self.config.short_response_min_input,
224                max_output = self.config.short_response_max_output,
225                run_has_actions = ctx.run_has_actions,
226                "short response detected in text-only branch"
227            );
228
229            if ctx.run_has_actions && self.config.use_llm_judge {
230                // Skip LLM judge for very large inputs — judge would be too slow
231                const INPUT_LEN_LIMIT: usize = 10_000;
232                if input_len > INPUT_LEN_LIMIT {
233                    tracing::info!(
234                        input_chars = input_len,
235                        input_limit = INPUT_LEN_LIMIT,
236                        "skipping LLM judge — user input too large, trusting model"
237                    );
238                    return GuardDecision::Complete;
239                }
240                // Short response after tools — call judge to verify completion
241                self.judge_completion(ctx).await
242            } else {
243                // Short response without tools or judge disabled — nudge
244                GuardDecision::Continue {
245                    nudge: Some(self.config.short_response_nudge.clone()),
246                }
247            }
248        } else if ctx.run_has_actions && self.config.use_llm_judge {
249            // Non-short response after tools — check skip threshold
250            if output_len >= self.config.judge_skip_threshold {
251                tracing::debug!(
252                    response_chars = output_len,
253                    threshold = self.config.judge_skip_threshold,
254                    "text-only response long enough, skipping judge"
255                );
256                return GuardDecision::Complete;
257            }
258
259            // Skip LLM judge for very large inputs — judge would be too slow
260            const INPUT_LEN_LIMIT: usize = 10_000;
261            if input_len > INPUT_LEN_LIMIT {
262                tracing::info!(
263                    input_chars = input_len,
264                    input_limit = INPUT_LEN_LIMIT,
265                    "skipping LLM judge — user input too large, trusting model"
266                );
267                return GuardDecision::Complete;
268            }
269
270            tracing::info!(
271                response_chars = output_len,
272                threshold = self.config.judge_skip_threshold,
273                "text-only response short, calling judge"
274            );
275            self.judge_completion(ctx).await
276        } else {
277            GuardDecision::Complete
278        }
279    }
280}
281
282#[async_trait]
283impl ReactLoopGuard for DefaultGuard {
284    fn set_notice(&self, handle: agent_base::NoticeHandle) {
285        *self.notice.lock().unwrap() = Some(handle);
286    }
287
288    fn set_provider_source(&self, handle: ProviderHandle) {
289        *self.provider_source.lock().unwrap() = Some(handle);
290    }
291
292    async fn on_turn(&self, ctx: &GuardCtx) -> GuardDecision {
293        if ctx.is_reasoning_only {
294            self.handle_reasoning_only(ctx).await
295        } else if ctx.is_empty_response {
296            self.handle_empty_response(ctx).await
297        } else if ctx.awaiting_human {
298            // The latest tool batch parked on a human step (a design-canvas
299            // screen awaiting a pick) and no tool ran after it: ending here is
300            // *waiting for the user*, not an incomplete task — their pick (or
301            // skip) is the next input. A "continue working" nudge in this
302            // state steamrolls interactive flows (session 20261022_bb8c2dc3:
303            // the completion judge pushed the model on and it decided the
304            // user's design choices for them).
305            GuardDecision::Complete
306        } else if ctx.is_text_only {
307            self.handle_text_only(ctx).await
308        } else {
309            GuardDecision::Complete
310        }
311    }
312
313    async fn on_tool_call(&self, ctx: &GuardCtx) -> GuardDecision {
314        // Turn-as-transaction policy (judgment; the kernel executes): a
315        // structurally corrupt tool batch on a silent round is discarded
316        // whole and the LLM re-asked from the same state. Visible text
317        // blocks discard (the user has already seen it); thinking is
318        // tolerated unless `thinking_is_visible`. Budget is per round;
319        // `max_silent_retries: 0` disables the gate. Checked BEFORE
320        // RestoreThinking — discarding a corrupt batch beats executing it.
321        if !ctx.integrity.is_clean()
322            && !ctx.has_visible_text
323            && !(self.config.thinking_is_visible && ctx.has_thinking)
324            && self.config.max_silent_retries > 0
325            && ctx.silent_retries_in_round < self.config.max_silent_retries
326        {
327            return GuardDecision::RetryTurn;
328        }
329
330        // Restore thinking when:
331        // 1. Thinking is currently disabled (by guard)
332        // 2. Original thinking was enabled (user wanted thinking)
333        // 3. Model calls a tool (showing it's working again)
334        if ctx.thinking_disabled && ctx.original_thinking_enabled {
335            tracing::info!(
336                session_id = ctx.session_id.id,
337                turn = ctx.turn_count,
338                "tool call detected while thinking disabled, restoring thinking"
339            );
340            return GuardDecision::RestoreThinking;
341        }
342
343        GuardDecision::Complete
344    }
345}