vtcode-core 0.164.2

Core library for VT Code - a Rust-based terminal coding agent
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use crate::core::agent::session::AgentSessionState;
use crate::llm::provider::MessageRole;

/// True when assistant text is a genuine safety/permission handoff that must
/// not be auto-continued, even if `task_tracker` still has incomplete steps.
///
/// Shared by the binary outer-loop Completed queue and AgentRunner status
/// continuation so both surfaces use the same vocabulary. Safety/policy
/// denials are evaluated first so a recap that mentions both a budget and a
/// policy denial still counts as a handoff. Pure budget/recovery recaps are
/// not handoffs (outer/in-turn recoverable classifiers treat those as continue).
pub fn tracker_final_text_is_safety_handoff(text: &str) -> bool {
    let lower = text.to_ascii_lowercase();
    if lower.trim().is_empty() {
        return false;
    }
    // True handoffs win even when the text also mentions a budget.
    if lower.contains("permission denied")
        || lower.contains("access denied")
        || lower.contains("safety fuse")
        || lower.contains("tool-call safety fuse")
        || lower.contains("policy block")
        || lower.contains("blocked by policy")
        || lower.contains("requires manual intervention")
        || lower.contains("missing credentials")
        || lower.contains("credentials are missing")
        || lower.contains("denied by policy")
        || lower.contains("denied by workspace tool policy")
        || lower.contains("denied by tool policy")
        || lower.contains("execution denied by policy")
        || lower.contains("blocked by tool policy")
    {
        return true;
    }
    // Pure budget/recovery recaps ("blocked by turn budget", "tool loop
    // budget exhausted", …) are not user handoffs.
    false
}

/// True when final assistant text asks the user for a decision/confirmation.
///
/// Shared by outer tracker auto-queue and in-turn continuation so Completed
/// turns that end with a genuine question are not auto-continued past the ask.
pub fn tracker_final_text_requires_user_input(text: &str) -> bool {
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return false;
    }
    if trimmed.ends_with('?') {
        return true;
    }
    let lower = trimmed.to_ascii_lowercase();
    const STRONG: &[&str] = &[
        "please provide",
        "please confirm",
        "please approve",
        "need your approval",
        "need your permission",
        "need your decision",
        "need you to choose",
        "need you to confirm",
        "waiting for your",
        "awaiting your",
        "your choice",
        "your decision",
        "need approval",
        "requires approval",
        "approval is required",
        "need permission",
        "requires permission",
        "permission is required",
        "grant permission",
        "authorize this",
        "need a decision",
        "need clarification",
        "waiting for input",
        "awaiting input",
        "waiting on you",
        "how should i proceed",
        "what should i do",
        "what would you like",
        "how would you like",
        "do you want me to",
    ];
    const CLAUSE_START: &[&str] = &["could you ", "can you ", "shall i ", "should i "];
    if STRONG.iter().any(|p| lower.contains(p)) {
        return true;
    }
    CLAUSE_START
        .iter()
        .any(|p| lower.trim_start().starts_with(p) || lower.contains(&format!("\n{p}")))
}

/// Checks if the agent's response is a candidate for completion handling.
pub fn check_completion_candidate(response_text: &str) -> bool {
    // High-confidence terminal markers that strongly indicate intent to stop.
    const COMPLETION_SENTENCES: &[&str] = &[
        "the task is complete",
        "task is complete",
        "task has been completed",
        "i have successfully completed the task",
        "work is finished",
        "operation successful",
        "i am done",
        "no more actions needed",
        "successfully accomplished",
        "task is now complete",
        "everything is finished",
        "i've finished the task",
        "all requested changes have been applied",
        "i have finished all the work",
    ];

    // Lower-confidence markers that need to be at the core of the message.
    const SOFT_INDICATORS: &[&str] = &[
        "task completed",
        "task done",
        "all done",
        "finished.",
        "complete.",
        "done.",
    ];

    const UNRESOLVED_PHRASES: &[&str] = &[
        "still need to",
        "remaining step",
        "remaining work",
        "verification pending",
        "verification still pending",
        "tests not run",
        "haven't run",
        "have not run",
        "blocked on",
        "open questions remain",
        "question remains",
        "todo:",
        "not complete yet",
        "once verification",
        "after verification",
    ];

    let response_lower = response_text.to_lowercase();

    if UNRESOLVED_PHRASES.iter().any(|phrase| response_lower.contains(phrase))
        || structured_contract_has_unresolved_sections(response_text)
    {
        return false;
    }

    // Strategy 1: Explicit terminal sentences
    if COMPLETION_SENTENCES.iter().any(|&s| response_lower.contains(s)) {
        return true;
    }

    // Strategy 2: Soft indicators that appear at the very end or are the entire message
    let trimmed = response_lower.trim();
    for &indicator in SOFT_INDICATORS {
        if trimmed.ends_with(indicator) || trimmed == indicator {
            // Heuristic: Ensure it's not "I will soon have the task completed"
            // Check if preceded by future-tense markers within the same sentence
            let sentences: Vec<_> = trimmed.split(['.', '!', '?']).collect();
            if let Some(last_sentence) = sentences.last() {
                let ls = last_sentence.trim();
                if ls.contains(indicator)
                    && !ls.contains("will")
                    && !ls.contains("going to")
                    && !ls.contains("about to")
                    && !ls.contains("once")
                    && !ls.contains("after")
                {
                    return true;
                }
            }
        }
    }

    // Strategy 3: Structured subagent markdown contract output.
    // When the model produces the canonical "## Summary / ## Facts / ..." contract, it has
    // finished its task even without an explicit done phrase.  Detect this by checking that
    // the response opens with a "## Summary" heading (after stripping leading whitespace) and
    // also contains a "## Facts" section.  Headers are matched line-by-line after trimming so
    // CRLF, extra spaces, and capitalisation variations are handled uniformly.
    {
        let mut has_summary_header = false;
        let mut has_facts_header = false;
        for line in response_text.lines() {
            let line_lower = line.trim().to_lowercase();
            if line_lower == "## summary" || line_lower == "# summary" {
                has_summary_header = true;
            }
            if line_lower == "## facts" || line_lower == "# facts" {
                has_facts_header = true;
            }
            if has_summary_header && has_facts_header {
                return true;
            }
        }
    }

    false
}

fn structured_contract_has_unresolved_sections(response_text: &str) -> bool {
    let mut in_open_questions = false;
    let mut in_verification = false;

    for line in response_text.lines() {
        let line_lower = line.trim().to_lowercase();
        if line_lower.starts_with('#') {
            in_open_questions = line_lower == "## open questions" || line_lower == "# open questions";
            in_verification = line_lower == "## verification" || line_lower == "# verification";
            continue;
        }

        if line_lower.is_empty() {
            continue;
        }

        if in_open_questions && !section_entry_is_none(&line_lower) {
            return true;
        }

        if in_verification && section_entry_is_unresolved(&line_lower) {
            return true;
        }
    }

    false
}

fn section_entry_is_none(line: &str) -> bool {
    let normalized = normalized_section_entry(line).trim_end_matches('.');
    matches!(normalized, "none" | "n/a")
}

fn section_entry_is_unresolved(line: &str) -> bool {
    let normalized = normalized_section_entry(line);
    normalized.contains("pending")
        || normalized.contains("not run")
        || normalized.contains("failed")
        || normalized.contains("blocked")
}

fn normalized_section_entry(line: &str) -> &str {
    line.trim_start_matches(['-', '*']).trim()
}

/// Check for repetitive text in assistant responses to catch non-tool-calling loops.
/// Returns true if a loop is detected.
pub fn check_for_response_loop(response_text: &str, session_state: &mut AgentSessionState) -> bool {
    if response_text.len() < 10 {
        return false;
    }

    // Simplistic check: is this response identical to the last one (ignoring whitespace)?
    let normalized_current = response_text.split_whitespace().collect::<Vec<_>>().join(" ");

    let repeated = session_state
        .messages
        .iter()
        .rev()
        .filter(|m| m.role == MessageRole::Assistant)
        .skip(1)
        .take(2)
        .any(|m| {
            let normalized_prev = m.content.as_text().split_whitespace().collect::<Vec<_>>().join(" ");
            normalized_prev == normalized_current
        });

    if repeated {
        let warning = "Repetitive assistant response detected. Breaking potential loop.".to_string();
        session_state.push_warning(warning);
        session_state.consecutive_idle_turns = session_state.consecutive_idle_turns.saturating_add(1);
        return true;
    }

    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::llm::provider::Message;

    #[test]
    fn tracker_final_text_is_safety_handoff_vocabulary() {
        assert!(tracker_final_text_is_safety_handoff(
            "Permission denied for exec_command. Next step: retry after access is granted."
        ));
        assert!(tracker_final_text_is_safety_handoff(
            "I hit the tool-call safety fuse mid-verification; policy block."
        ));
        assert!(tracker_final_text_is_safety_handoff(
            "Blocked action: exec_command is denied by workspace tool policy."
        ));
        assert!(!tracker_final_text_is_safety_handoff(
            "## Status\nBlocked by turn budget. Next step: read design/diff.rs."
        ));
        assert!(!tracker_final_text_is_safety_handoff(
            "## Status\nBlocked by turn tool budget. Next step: patch the struct."
        ));
        assert!(!tracker_final_text_is_safety_handoff(
            "Tool loop budget exhausted; continuing next turn with remaining tracker steps."
        ));
        // Bare tool-policy mention is not a handoff; explicit denial still is.
        assert!(!tracker_final_text_is_safety_handoff("Reviewed tool policy docs; next step is the tracker patch."));
        assert!(tracker_final_text_is_safety_handoff(
            "Blocked action: exec_command is denied by workspace tool policy."
        ));
        assert!(!tracker_final_text_is_safety_handoff("Implemented patch apply; verification passed."));
        assert!(!tracker_final_text_is_safety_handoff(""));
        // Policy denial wins even when a budget is also mentioned.
        assert!(tracker_final_text_is_safety_handoff("Tool budget exhausted; denied by policy for exec_command."));
        assert!(tracker_final_text_is_safety_handoff("Turn budget hit, then permission denied for the write."));
    }

    #[test]
    fn tracker_final_text_requires_user_input_vocabulary() {
        assert!(tracker_final_text_requires_user_input("Step 1 done. Which branch should I use for step 2?"));
        assert!(tracker_final_text_requires_user_input(
            "## Status\nPlease confirm whether to use the stable schema."
        ));
        assert!(tracker_final_text_requires_user_input("Can you confirm the migration path before I edit."));
        assert!(!tracker_final_text_requires_user_input(
            "## Status\nNext we need your workspace path in CONFIG; patching the struct now."
        ));
        assert!(!tracker_final_text_requires_user_input("Blocked by turn budget. Next step: read helpers.rs."));
        assert!(!tracker_final_text_requires_user_input(""));
    }

    #[test]
    fn test_completion_candidates() {
        assert!(check_completion_candidate("The task is complete"));
        assert!(check_completion_candidate("Revision 1: task is complete."));
        assert!(check_completion_candidate("I have successfully completed the task."));
        assert!(check_completion_candidate("Task done"));
        assert!(check_completion_candidate("All done"));

        // Negative cases
        assert!(!check_completion_candidate("I will have the task done soon"));
        assert!(!check_completion_candidate("Is the task done?"));
        assert!(!check_completion_candidate("random text"));
        assert!(!check_completion_candidate("The task is complete once verification finishes."));
        assert!(!check_completion_candidate("All done. Verification pending."));
        assert!(!check_completion_candidate("All done, but open questions remain."));
    }

    #[test]
    fn subagent_markdown_contract_detected_as_complete() {
        let contract = "## Summary\n- Background subprocess launched; PID 86065.\n\n## Facts\n- Script started at 2026-04-25T08:39:10Z.\n\n## Touched Files\n- None\n\n## Verification\n- Process confirmed.\n\n## Open Questions\n- None";
        assert!(check_completion_candidate(contract));
    }

    #[test]
    fn subagent_markdown_contract_with_crlf_detected_as_complete() {
        let contract = "## Summary\r\n- Done.\r\n\r\n## Facts\r\n- Fact 1.\r\n";
        assert!(check_completion_candidate(contract));
    }

    #[test]
    fn subagent_markdown_contract_with_leading_whitespace_detected() {
        let contract = "\n\n## Summary\n- item\n\n## Facts\n- fact\n";
        assert!(check_completion_candidate(contract));
    }

    #[test]
    fn document_with_only_summary_header_not_detected() {
        let doc = "## Summary\n- This is a doc without a Facts section.\n";
        assert!(!check_completion_candidate(doc));
    }

    #[test]
    fn document_with_only_facts_header_not_detected() {
        let doc = "## Facts\n- Fact without summary.\n";
        assert!(!check_completion_candidate(doc));
    }

    #[test]
    fn structured_contract_with_open_questions_is_not_complete() {
        let doc = "## Summary\n- Work applied.\n\n## Facts\n- Fact.\n\n## Verification\n- Process confirmed.\n\n## Open Questions\n- Need to rerun the end-to-end flow.";
        assert!(!check_completion_candidate(doc));
    }

    #[test]
    fn structured_contract_with_unresolved_verification_is_not_complete() {
        let doc = "## Summary\n- Work applied.\n\n## Facts\n- Fact.\n\n## Verification\n- Verification pending.\n\n## Open Questions\n- None";
        assert!(!check_completion_candidate(doc));
    }

    #[test]
    fn structured_contract_with_none_punctuation_is_complete() {
        let doc = "## Summary\n- Work applied.\n\n## Facts\n- Fact.\n\n## Verification\n- Process confirmed.\n\n## Open Questions\n- None.";
        assert!(check_completion_candidate(doc));
    }

    #[test]
    fn response_loop_ignores_current_assistant_message() {
        let repeated_response = "The task is complete";
        let mut state = AgentSessionState::new("session".to_string(), 8, 4, 128_000);
        state.messages_mut().push(Message::assistant(repeated_response.to_string()));

        assert!(!check_for_response_loop(repeated_response, &mut state));
    }

    #[test]
    fn response_loop_still_detects_prior_duplicate_assistant_message() {
        let repeated_response = "The task is complete";
        let mut state = AgentSessionState::new("session".to_string(), 8, 4, 128_000);
        state.messages_mut().push(Message::assistant(repeated_response.to_string()));
        state.messages_mut().push(Message::assistant(repeated_response.to_string()));

        assert!(check_for_response_loop(repeated_response, &mut state));
    }
}