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