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 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 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 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 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 if strikes >= self.config.reasoning_only_max_strikes {
129 if ctx.thinking_disabled {
131 return GuardDecision::Fail {
133 error: "model produced only reasoning even after thinking was disabled"
134 .to_string(),
135 };
136 }
137
138 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 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 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 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 self.judge_completion(ctx).await
226 } else {
227 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 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 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 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 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}