agent_works/guard/
default.rs1use 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
10pub struct DefaultGuard {
14 config: DefaultGuardConfig,
15 llm_client: Option<Arc<dyn LlmProvider>>,
16 provider_source: Mutex<Option<ProviderHandle>>,
22 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 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 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 fn notice_handle(&self) -> Option<agent_base::NoticeHandle> {
60 self.notice.lock().unwrap().clone()
61 }
62
63 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 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 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 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 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 if strikes >= self.config.reasoning_only_max_strikes {
145 if ctx.thinking_disabled {
147 return GuardDecision::Fail {
149 error: "model produced only reasoning even after thinking was disabled"
150 .to_string(),
151 };
152 }
153
154 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 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 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 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 self.judge_completion(ctx).await
242 } else {
243 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 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 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 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 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 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}