Skip to main content

vtcode_core/core/agent/state/
mod.rs

1use crate::llm::provider::Message;
2use hashbrown::{HashMap, HashSet};
3use std::sync::Arc;
4use std::time::Duration;
5use vtcode_macros::StringNewtype;
6
7// ============================================================================
8// Context Manager: Call/Output Pairing Invariants (OpenAI Codex pattern)
9// ============================================================================
10
11/// Unique identifier for a tool call.
12#[derive(Debug, Clone, PartialEq, Eq, Hash, StringNewtype)]
13pub struct ToolCallId(String);
14
15/// Status of a tool execution
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum OutputStatus {
18    Success,
19    Failed,
20    Canceled,
21    Timeout,
22}
23
24impl OutputStatus {
25    /// Convert to string representation
26    pub fn as_str(&self) -> &'static str {
27        match self {
28            Self::Success => "success",
29            Self::Failed => "failed",
30            Self::Canceled => "canceled",
31            Self::Timeout => "timeout",
32        }
33    }
34}
35
36/// Items that participate in call/output pairing for validation
37#[derive(Debug, Clone)]
38pub enum PairableHistoryItem {
39    /// Tool call without output (yet)
40    ToolCall { call_id: ToolCallId, tool_name: String },
41    /// Tool output for a previous call
42    ToolOutput { call_id: ToolCallId, status: OutputStatus },
43}
44
45/// Record of a missing output in conversation history
46#[derive(Debug, Clone)]
47pub struct MissingOutput {
48    pub call_id: ToolCallId,
49    pub tool_name: String,
50}
51
52/// Validation report for conversation history state
53#[derive(Debug, Default, Clone)]
54pub struct HistoryValidationReport {
55    /// Tool calls without corresponding outputs
56    pub missing_outputs: Vec<MissingOutput>,
57    /// Outputs without corresponding calls (orphans)
58    pub orphan_outputs: Vec<ToolCallId>,
59}
60
61impl HistoryValidationReport {
62    /// Check if history is in a valid state
63    pub fn is_valid(&self) -> bool {
64        self.missing_outputs.is_empty() && self.orphan_outputs.is_empty()
65    }
66
67    /// Get a human-readable summary
68    pub fn summary(&self) -> String {
69        if self.is_valid() {
70            "History invariants are valid".to_string()
71        } else {
72            format!("{} missing outputs, {} orphan outputs", self.missing_outputs.len(), self.orphan_outputs.len())
73        }
74    }
75
76    /// Filter out missing outputs that correspond to pending actions.
77    ///
78    /// A "missing output" is expected when the corresponding tool call is still
79    /// in flight (pending action). Removing these from the report prevents
80    /// false positives during crash recovery that would insert synthetic
81    /// outputs for tools that are legitimately still running.
82    pub fn exclude_pending(&mut self, is_pending: impl Fn(&str) -> bool) {
83        self.missing_outputs.retain(|m| !is_pending(m.call_id.as_str()));
84    }
85}
86
87#[cfg(test)]
88#[inline]
89pub(crate) fn record_turn_duration(
90    turn_durations: &mut Vec<u128>,
91    turn_total_ms: &mut u128,
92    turn_max_ms: &mut u128,
93    turn_count: &mut usize,
94    recorded: &mut bool,
95    start: &std::time::Instant,
96) {
97    if !*recorded {
98        let duration_ms = start.elapsed().as_millis();
99        turn_durations.push(duration_ms);
100        *turn_total_ms += duration_ms;
101        if duration_ms > *turn_max_ms {
102            *turn_max_ms = duration_ms;
103        }
104        *turn_count += 1;
105        *recorded = true;
106    }
107}
108
109/// API failure tracking for exponential backoff
110pub struct ApiFailureTracker {
111    pub consecutive_failures: u32,
112    pub last_failure: Option<std::time::Instant>,
113}
114
115impl Default for ApiFailureTracker {
116    fn default() -> Self {
117        Self::new()
118    }
119}
120
121impl ApiFailureTracker {
122    pub fn new() -> Self {
123        Self { consecutive_failures: 0, last_failure: None }
124    }
125
126    pub fn record_failure(&mut self) {
127        self.consecutive_failures += 1;
128        self.last_failure = Some(std::time::Instant::now());
129    }
130
131    pub fn reset(&mut self) {
132        self.consecutive_failures = 0;
133        self.last_failure = None;
134    }
135
136    pub fn should_circuit_break(&self) -> bool {
137        self.consecutive_failures >= 3
138    }
139
140    pub fn backoff_duration(&self) -> Duration {
141        let base_ms = 1000;
142        let max_ms = 30000;
143        let backoff_ms = base_ms * 2_u64.pow(self.consecutive_failures.saturating_sub(1));
144        Duration::from_millis(backoff_ms.min(max_ms))
145    }
146}
147
148pub fn summarize_list(items: &[String]) -> String {
149    const MAX_ITEMS: usize = 5;
150    if items.is_empty() {
151        return "none".into();
152    }
153    let shown: Vec<&str> = items.iter().take(MAX_ITEMS).map(|s| s.as_str()).collect();
154    if items.len() > MAX_ITEMS {
155        format!("{} [+{} more]", shown.join(", "), items.len() - MAX_ITEMS)
156    } else {
157        shown.join(", ")
158    }
159}
160
161// ============================================================================
162// Standalone History Invariant Functions
163// ============================================================================
164
165/// Validate that conversation history maintains call/output invariants.
166pub fn validate_history_invariants(messages: &[Message]) -> HistoryValidationReport {
167    let mut call_map: HashMap<String, String> = HashMap::new();
168    let mut output_ids: HashSet<String> = HashSet::new();
169
170    // Scan messages to find tool calls and responses
171    for msg in messages {
172        // Tool calls: assistant messages with tool_calls field
173        if let Some(tool_calls) = &msg.tool_calls {
174            for tool_call in tool_calls {
175                call_map.insert(tool_call.id.clone(), msg.role.to_string());
176            }
177        }
178
179        // Tool responses: messages with tool_call_id set
180        if let Some(tool_call_id) = &msg.tool_call_id {
181            output_ids.insert(tool_call_id.clone());
182        }
183    }
184
185    // Find missing outputs (calls without corresponding responses)
186    let missing_outputs: Vec<_> = call_map
187        .keys()
188        .filter(|call_id| !output_ids.contains(*call_id))
189        .map(|call_id| MissingOutput {
190            call_id: ToolCallId::new(call_id.clone()),
191            tool_name: "unknown".to_string(),
192        })
193        .collect();
194
195    // Find orphan outputs (responses without matching calls)
196    let orphan_outputs: Vec<_> = output_ids
197        .iter()
198        .filter(|output_id| !call_map.contains_key(*output_id))
199        .map(|output_id| ToolCallId::new(output_id.clone()))
200        .collect();
201
202    HistoryValidationReport { missing_outputs, orphan_outputs }
203}
204
205const REQUEST_HISTORY_CANCELLATION_RESULT: &str =
206    "canceled: no tool result was recorded; this bounded placeholder preserves the tool-call protocol.";
207const REQUEST_HISTORY_AMBIGUOUS_RESULT: &str = "unattributed: multiple outstanding tool calls shared an ID, so their recorded results cannot be safely assigned; original results remain in session history.";
208const REQUEST_HISTORY_EMPTY_ID_RESULT: &str = "unattributed: the tool call had an empty ID, so no result can be safely matched; original history remains available.";
209
210#[derive(Debug)]
211struct MatchedRequestToolResult {
212    message_index: usize,
213    call_index: usize,
214}
215
216#[derive(Debug)]
217struct RequestToolBatch {
218    assistant_index: usize,
219    matched_calls: Vec<bool>,
220    results: Vec<MatchedRequestToolResult>,
221}
222
223#[derive(Debug, Default)]
224struct RequestHistoryAnalysis {
225    batches: Vec<RequestToolBatch>,
226    batch_by_assistant_index: HashMap<usize, usize>,
227    result_batch_by_index: HashMap<usize, usize>,
228    invalid_result_indices: HashSet<usize>,
229    duplicate_call_ids: HashSet<String>,
230    has_empty_call_id: bool,
231    ambiguous_calls: HashSet<(usize, usize)>,
232}
233
234impl RequestHistoryAnalysis {
235    fn needs_repair(&self) -> bool {
236        if !self.invalid_result_indices.is_empty() || !self.duplicate_call_ids.is_empty() || self.has_empty_call_id {
237            return true;
238        }
239
240        self.batches.iter().any(|batch| {
241            batch.matched_calls.iter().any(|matched| !matched)
242                || batch
243                    .results
244                    .iter()
245                    .enumerate()
246                    .any(|(offset, result)| result.message_index != batch.assistant_index + offset + 1)
247        })
248    }
249}
250
251fn analyze_request_history(messages: &[Message]) -> RequestHistoryAnalysis {
252    let mut analysis = RequestHistoryAnalysis::default();
253    let mut calls_by_id: HashMap<&str, Vec<(usize, usize)>> = HashMap::new();
254
255    for (message_index, message) in messages.iter().enumerate() {
256        if message.role != crate::llm::provider::MessageRole::Assistant {
257            continue;
258        }
259
260        let Some(tool_calls) = message.tool_calls.as_ref().filter(|calls| !calls.is_empty()) else {
261            continue;
262        };
263
264        let batch_index = analysis.batches.len();
265        let matched_calls = vec![false; tool_calls.len()];
266        analysis.batch_by_assistant_index.insert(message_index, batch_index);
267        analysis.batches.push(RequestToolBatch {
268            assistant_index: message_index,
269            matched_calls,
270            results: Vec::new(),
271        });
272
273        for (call_index, call) in tool_calls.iter().enumerate() {
274            analysis.has_empty_call_id |= call.id.is_empty();
275            calls_by_id.entry(call.id.as_str()).or_default().push((batch_index, call_index));
276        }
277    }
278
279    analysis.duplicate_call_ids = calls_by_id
280        .iter()
281        .filter(|(_, calls)| calls.len() > 1)
282        .map(|(id, _)| (*id).to_owned())
283        .collect();
284
285    for (message_index, message) in messages.iter().enumerate() {
286        let has_tool_call_id = message.tool_call_id.is_some();
287        let is_tool_result = message.role == crate::llm::provider::MessageRole::Tool;
288        if !is_tool_result && !has_tool_call_id {
289            continue;
290        }
291
292        let Some(tool_call_id) = message.tool_call_id.as_deref().filter(|id| !id.is_empty()) else {
293            analysis.invalid_result_indices.insert(message_index);
294            continue;
295        };
296
297        if !is_tool_result {
298            analysis.invalid_result_indices.insert(message_index);
299            continue;
300        }
301
302        let Some(candidates) = calls_by_id.get_mut(tool_call_id) else {
303            analysis.invalid_result_indices.insert(message_index);
304            continue;
305        };
306
307        let mut eligible = candidates.iter().copied().filter(|&(batch_index, call_index)| {
308            analysis.batches[batch_index].assistant_index < message_index
309                && !analysis.batches[batch_index].matched_calls[call_index]
310        });
311        let Some((batch_index, call_index)) = eligible.next() else {
312            // Results before their call and repeated results have no match.
313            analysis.invalid_result_indices.insert(message_index);
314            continue;
315        };
316        if let Some(second) = eligible.next() {
317            // Concurrent calls with the same ID are indistinguishable. Never
318            // attach an observed result to a guessed call or credit it as proof.
319            analysis.ambiguous_calls.insert((batch_index, call_index));
320            analysis.ambiguous_calls.insert(second);
321            analysis.ambiguous_calls.extend(eligible);
322            analysis.invalid_result_indices.insert(message_index);
323            continue;
324        }
325
326        analysis.batches[batch_index].matched_calls[call_index] = true;
327        analysis.batches[batch_index]
328            .results
329            .push(MatchedRequestToolResult { message_index, call_index });
330        analysis.result_batch_by_index.insert(message_index, batch_index);
331    }
332
333    analysis
334}
335
336/// Return whether the provider-facing message view needs tool-history repair.
337///
338/// This deliberately analyzes only the request view. Durable session history
339/// is repaired by its own crash-recovery path and is never changed here.
340pub fn request_history_needs_normalization(messages: &[Message]) -> bool {
341    analyze_request_history(messages).needs_repair()
342}
343
344/// Rebuild a shared provider-facing message view with each assistant
345/// tool-call batch followed immediately by its matching results.
346///
347/// The rebuild is request-scoped and idempotent: orphaned, causally early, and
348/// duplicate results are omitted; repeated call IDs are replaced along with
349/// their matching result IDs, while ambiguous concurrent results are not
350/// attributed to a guessed call; missing calls receive a bounded cancellation
351/// result; and messages interleaved between a call batch and its results move
352/// after the complete batch. A clean input is returned unchanged; repairs use
353/// copy-on-write and never mutate the source history.
354pub fn normalize_history_for_request_shared(messages: Arc<Vec<Message>>) -> Arc<Vec<Message>> {
355    let analysis = analyze_request_history(&messages);
356    if !analysis.needs_repair() {
357        return messages;
358    }
359
360    let mut normalized = Vec::with_capacity(messages.len());
361    let mut used_ids: HashSet<String> = messages
362        .iter()
363        .flat_map(|message| message.tool_calls.iter().flatten().map(|call| call.id.clone()))
364        .collect();
365    let mut next_repaired_id = 0usize;
366    let mut seen_duplicate_ids = HashSet::new();
367    for (message_index, message) in messages.iter().enumerate() {
368        if analysis.invalid_result_indices.contains(&message_index)
369            || analysis.result_batch_by_index.contains_key(&message_index)
370        {
371            continue;
372        }
373
374        let Some(&batch_index) = analysis.batch_by_assistant_index.get(&message_index) else {
375            normalized.push(message.clone());
376            continue;
377        };
378
379        let batch = &analysis.batches[batch_index];
380        let mut assistant = message.clone();
381        for call in assistant.tool_calls.iter_mut().flatten() {
382            if call.id.is_empty()
383                || (analysis.duplicate_call_ids.contains(&call.id) && !seen_duplicate_ids.insert(call.id.clone()))
384            {
385                let prefix = if call.id == "harness-auto-verify" || call.id.starts_with("harness-auto-verify-") {
386                    "harness-auto-verify-repaired"
387                } else {
388                    "vtcode-repaired-tool-call"
389                };
390                loop {
391                    let candidate = format!("{prefix}-{next_repaired_id}");
392                    next_repaired_id += 1;
393                    if used_ids.insert(candidate.clone()) {
394                        call.id = candidate;
395                        break;
396                    }
397                }
398            }
399        }
400        for matched_result in &batch.results {
401            let mut result = messages[matched_result.message_index].clone();
402            if let Some(call) = assistant
403                .tool_calls
404                .as_ref()
405                .and_then(|calls| calls.get(matched_result.call_index))
406            {
407                result.tool_call_id = Some(call.id.clone());
408            }
409            normalized.push(result);
410        }
411        let result_start = normalized.len() - batch.results.len();
412        normalized.insert(result_start, assistant.clone());
413        for (call_index, (call, matched)) in assistant.tool_calls.iter().flatten().zip(&batch.matched_calls).enumerate()
414        {
415            if !matched {
416                let result = if message
417                    .tool_calls
418                    .as_ref()
419                    .and_then(|calls| calls.get(call_index))
420                    .is_some_and(|call| call.id.is_empty())
421                {
422                    REQUEST_HISTORY_EMPTY_ID_RESULT
423                } else if analysis.ambiguous_calls.contains(&(batch_index, call_index)) {
424                    REQUEST_HISTORY_AMBIGUOUS_RESULT
425                } else {
426                    REQUEST_HISTORY_CANCELLATION_RESULT
427                };
428                normalized.push(Message::tool_response(call.id.clone(), result.to_owned()));
429            }
430        }
431    }
432
433    Arc::new(normalized)
434}
435
436/// Compatibility wrapper for callers that own a slice rather than shared
437/// request history. The shared implementation avoids cloning clean message
438/// histories; this wrapper retains the historical
439/// owned return type for small slice-based callers and tests.
440pub fn normalize_history_for_request(messages: &[Message]) -> Vec<Message> {
441    Arc::unwrap_or_clone(normalize_history_for_request_shared(Arc::new(messages.to_vec())))
442}
443
444/// Placeholder body for a cleared tool result. Mirrors Anthropic
445/// `clear_tool_uses` semantics as request-only shaping: the durable history
446/// and `ThreadEvent` log keep the original payload.
447const CLEARED_TOOL_RESULT_NOTE: &str = "Older tool result cleared to bound context growth. Full output remains in session logs; re-run the tool if raw bytes are needed.";
448
449/// Cap local clearing at 60% of the history capacity left after the request
450/// prefix and output reserve. Zero capacity is unknown; zero trigger or an
451/// explicit opt-out keeps clearing disabled.
452#[must_use]
453pub fn resolve_tool_result_clearing_trigger(
454    config: &crate::config::VTCodeConfig,
455    provider: &dyn crate::llm::provider::LLMProvider,
456    model: &str,
457    prompt_overhead_tokens: usize,
458    reserved_output_tokens: usize,
459) -> u64 {
460    let clearing = &config.agent.harness.tool_result_clearing;
461    if !clearing.enabled || clearing.trigger_tokens == 0 {
462        return 0;
463    }
464    let capacity = crate::compaction::effective_context_budget(Some(config), provider, model);
465    if capacity == 0 {
466        return clearing.trigger_tokens;
467    }
468    let history_budget = capacity
469        .saturating_sub(reserved_output_tokens)
470        .saturating_sub(prompt_overhead_tokens) as u64;
471    // Divide before multiplying, retaining the remainder to avoid overflow
472    // even at the largest representable context budget.
473    let cap = (history_budget / 5)
474        .saturating_mul(3)
475        .saturating_add((history_budget % 5) * 3 / 5)
476        .max(1);
477    clearing.trigger_tokens.min(cap)
478}
479
480/// Request-only local stand-in for Anthropic `clear_tool_uses_20250919`.
481///
482/// Providers without `context_management.edits` never get native tool-result
483/// clearing, so long histories keep paying full price for every old tool body
484/// on each request. Once estimated history tokens exceed `trigger_tokens`, this
485/// rewrites old tool-result *request* messages outside a bounded recent
486/// evidence window and the newest `keep_tool_uses` originating batches to a
487/// bounded stub. Small results stay intact when a stub would not save tokens.
488/// `clear_at_least_tokens` is a floor on reclaimed tokens (not a ceiling):
489/// clearing must stub all eligible non-retained results so
490/// re-running on full durable history cannot leave a permanently growing tail.
491///
492/// Contract (same as [`normalize_history_for_request`]):
493/// - never mutates durable session history or `ThreadEvent`s;
494/// - preserves `role`, `tool_call_id`, `origin_tool`, and message order so
495///   provider tool-pairing validation still passes;
496/// - idempotent: re-running on already-stubbed output is a no-op below the
497///   trigger and cannot re-clear stubs usefully.
498///
499/// When `clear_tool_inputs` is set, assistant `tool_calls[].function.arguments`
500/// and freeform `text` larger than 1 KiB for cleared results are replaced with
501/// a JSON placeholder. Small arguments retain usable command/path identity.
502pub fn clear_old_tool_results(
503    messages: &[Message],
504    trigger_tokens: u64,
505    keep_tool_uses: u32,
506    clear_at_least_tokens: u64,
507    clear_tool_inputs: bool,
508) -> Vec<Message> {
509    clear_old_tool_results_with_recent_batches(
510        messages,
511        trigger_tokens,
512        keep_tool_uses,
513        0,
514        clear_at_least_tokens,
515        clear_tool_inputs,
516    )
517}
518
519/// Request-only clearing that also protects the newest assistant tool-call
520/// batches by originating message order. Count-based protection is additive;
521/// unmatched results retain the compatibility wrapper's count-based fallback.
522pub fn clear_old_tool_results_with_recent_batches(
523    messages: &[Message],
524    trigger_tokens: u64,
525    keep_tool_uses: u32,
526    keep_recent_tool_batches: u32,
527    clear_at_least_tokens: u64,
528    clear_tool_inputs: bool,
529) -> Vec<Message> {
530    if trigger_tokens == 0 || messages.is_empty() {
531        return messages.to_vec();
532    }
533
534    let estimated_tokens: u64 = messages
535        .iter()
536        .map(|message| message.estimate_tokens() as u64)
537        .fold(0u64, u64::saturating_add);
538    if estimated_tokens < trigger_tokens {
539        return messages.to_vec();
540    }
541
542    let tool_indices: Vec<usize> = messages
543        .iter()
544        .enumerate()
545        .filter(|(_, message)| message.role == crate::llm::provider::MessageRole::Tool)
546        .map(|(index, _)| index)
547        .collect();
548    let keep = keep_tool_uses as usize;
549    if tool_indices.len() <= keep {
550        return messages.to_vec();
551    }
552
553    let mut cleared_tokens = 0u64;
554    let analysis = analyze_request_history(messages);
555    let mut retained_batches: HashSet<usize> = tool_indices
556        .iter()
557        .rev()
558        .take(keep)
559        .filter_map(|index| analysis.result_batch_by_index.get(index).copied())
560        .collect();
561    // Analysis records assistant messages in source order, independently of
562    // completion order and reused call IDs.
563    retained_batches.extend((0..analysis.batches.len()).rev().take(keep_recent_tool_batches as usize));
564    // Two batches can be only two short searches. Clearing everything before
565    // them discards the source needed for the pending edit, provoking rereads
566    // that the navigation guards correctly bound. Reserve half of the
567    // already capacity-capped trigger for recent complete evidence batches.
568    // This window stays bounded when rebuilding from full durable history.
569    let evidence_budget = trigger_tokens / 2;
570    let mut batch_tokens: Vec<u64> = analysis
571        .batches
572        .iter()
573        .map(|batch| messages[batch.assistant_index].estimate_tokens() as u64)
574        .collect();
575    for (&result_index, &batch_index) in &analysis.result_batch_by_index {
576        batch_tokens[batch_index] =
577            batch_tokens[batch_index].saturating_add(messages[result_index].estimate_tokens() as u64);
578    }
579    let mut retained_tokens = 0u64;
580    for (batch_index, &tokens) in batch_tokens.iter().enumerate().rev() {
581        let next_tokens = retained_tokens.saturating_add(tokens);
582        if next_tokens > evidence_budget {
583            break;
584        }
585        retained_tokens = next_tokens;
586        retained_batches.insert(batch_index);
587    }
588    let mut cleared_result_count = 0usize;
589    let mut cleared_calls_by_assistant: HashMap<usize, HashSet<&str>> = HashMap::new();
590    // Stub every eligible non-kept tool result (oldest-first). `clear_at_least_tokens`
591    // is a floor on reclaimed tokens; stopping early would leave a permanently
592    // growing tail on the next request that re-shapes full durable history.
593    let mut out = messages.to_vec();
594    for &tool_index in &tool_indices[..tool_indices.len() - keep] {
595        let batch_index = analysis.result_batch_by_index.get(&tool_index);
596        if batch_index.is_some_and(|index| retained_batches.contains(index)) {
597            continue;
598        }
599        let original = &messages[tool_index];
600        let original_tokens = original.estimate_tokens() as u64;
601        let stub = build_cleared_tool_result_stub(original);
602        let stub_tokens = stub.estimate_tokens() as u64;
603        if stub_tokens >= original_tokens {
604            continue;
605        }
606        if let Some(&batch_index) = batch_index
607            && let Some(call_id) = original.tool_call_id.as_deref()
608        {
609            cleared_calls_by_assistant
610                .entry(analysis.batches[batch_index].assistant_index)
611                .or_default()
612                .insert(call_id);
613        }
614        out[tool_index] = stub;
615        cleared_result_count += 1;
616        cleared_tokens = cleared_tokens.saturating_add(original_tokens.saturating_sub(stub_tokens));
617    }
618
619    // The floor is advisory: every eligible result is already stubbed. A
620    // protected batch or small results can leave less reclaimable than the
621    // configured floor.
622    if cleared_tokens < clear_at_least_tokens {
623        tracing::debug!(
624            cleared_tokens,
625            clear_at_least_tokens,
626            "tool-result clearing reclaimed less than the configured floor"
627        );
628    }
629
630    if clear_tool_inputs {
631        for (assistant_index, original_message) in out.iter_mut().enumerate() {
632            let Some(cleared_call_ids) = cleared_calls_by_assistant.remove(&assistant_index) else {
633                continue;
634            };
635            let mut message = original_message.clone();
636            let Some(tool_calls) = message.tool_calls.as_mut() else {
637                continue;
638            };
639            for call in tool_calls.iter_mut() {
640                if cleared_call_ids.contains(call.id.as_str()) {
641                    if let Some(function) = call.function.as_mut()
642                        && function.arguments.len() > RETAINED_TOOL_INPUT_BYTES
643                    {
644                        // Valid JSON placeholder: providers send `arguments`
645                        // verbatim; prose would break OpenAI tool-call parsing.
646                        function.arguments = CLEARED_TOOL_INPUT_PLACEHOLDER.to_string();
647                    }
648                    // Freeform custom tool payloads ride in `text`, not
649                    // `function.arguments` (see ToolCall::custom).
650                    if call.text.as_ref().is_some_and(|text| text.len() > RETAINED_TOOL_INPUT_BYTES) {
651                        call.text = Some(CLEARED_TOOL_INPUT_PLACEHOLDER.to_string());
652                    }
653                    call.thought_signature = None;
654                }
655            }
656            // Tiny arguments can be cheaper than the JSON placeholder. Do
657            // not spend more tokens on inputs than the results reclaimed.
658            let input_growth =
659                (message.estimate_tokens() as u64).saturating_sub(original_message.estimate_tokens() as u64);
660            if input_growth <= cleared_tokens {
661                *original_message = message;
662                cleared_tokens = cleared_tokens.saturating_sub(input_growth);
663            }
664        }
665    }
666
667    tracing::debug!(
668        original_tokens = estimated_tokens,
669        projected_tokens = out
670            .iter()
671            .map(|message| message.estimate_tokens() as u64)
672            .fold(0u64, u64::saturating_add),
673        cleared_result_count,
674        protected_batch_count = retained_batches.len(),
675        first_changed_message_index = messages.iter().zip(&out).position(|(before, after)| before != after),
676        "local tool-result clearing projection"
677    );
678    out
679}
680
681/// JSON placeholder for cleared tool-call inputs (must stay valid JSON).
682const CLEARED_TOOL_INPUT_PLACEHOLDER: &str = "{\"cleared\":\"tool_input\"}";
683// Keep ordinary command/path arguments intact instead of teaching providers
684// to emit synthetic arguments that cannot pass the tool's declared schema.
685const RETAINED_TOOL_INPUT_BYTES: usize = 1024;
686
687/// Whether request assembly should apply local [`clear_old_tool_results`].
688///
689/// Local clearing and Anthropic `clear_tool_uses` are mutually exclusive:
690/// native edits already reclaim tool bodies on the wire, so applying both
691/// would double-shape the same history.
692pub fn should_apply_local_tool_result_clearing(
693    provider_name: &str,
694    context_edits: bool,
695    clearing_enabled: bool,
696) -> bool {
697    clearing_enabled && !(provider_name.eq_ignore_ascii_case("anthropic") && context_edits)
698}
699
700fn build_cleared_tool_result_stub(original: &Message) -> Message {
701    let mut stub = original.clone();
702    // serde_json (not `{:?}`) so non-ASCII tool names / call ids stay valid JSON.
703    let body = serde_json::json!({
704        "cleared": "tool_result",
705        "reason": "tool_result_clearing",
706        "note": CLEARED_TOOL_RESULT_NOTE,
707        "tool": original.origin_tool.as_deref().unwrap_or("tool"),
708        "tool_call_id": original.tool_call_id.as_deref().unwrap_or(""),
709    })
710    .to_string();
711    stub.content = crate::llm::provider::MessageContent::Text(body);
712    stub
713}
714
715/// Find a split point that keeps tool-call outputs paired with their calls.
716pub fn safe_history_split_point(messages: &[Message], conversation_len: usize, preferred_split_at: usize) -> usize {
717    if preferred_split_at == 0 || preferred_split_at >= conversation_len {
718        return preferred_split_at;
719    }
720
721    let mut call_indices: HashMap<&str, usize> = HashMap::new();
722    for (i, msg) in messages.iter().enumerate() {
723        if let Some(tool_calls) = &msg.tool_calls {
724            for call in tool_calls {
725                call_indices.insert(&call.id, i);
726            }
727        }
728    }
729
730    let mut safe_split_at = preferred_split_at;
731    loop {
732        if safe_split_at == 0 {
733            break;
734        }
735
736        let has_orphan = ((safe_split_at + 1)..messages.len()).any(|i| {
737            messages
738                .get(i)
739                .and_then(|msg| msg.tool_call_id.as_ref())
740                .and_then(|id| call_indices.get(id.as_str()))
741                .is_some_and(|&call_idx| call_idx <= safe_split_at)
742        });
743
744        if !has_orphan {
745            break;
746        }
747
748        safe_split_at -= 1;
749    }
750
751    safe_split_at
752}
753
754/// Ensure all tool calls have corresponding outputs in the message list.
755pub fn ensure_call_outputs_present(messages: &mut Vec<Message>) {
756    let report = validate_history_invariants(messages);
757
758    // Create synthetic outputs for missing calls in reverse order to avoid index shifting
759    for missing in report.missing_outputs.iter().rev() {
760        let synthetic_message = Message::tool_response(
761            missing.call_id.as_str().to_string(),
762            "canceled: Tool execution was interrupted. This synthetic output was created \
763             during history normalization to maintain conversation invariants."
764                .to_string(),
765        );
766
767        tracing::warn!("Creating synthetic output for call {} due to missing execution result", missing.call_id);
768
769        // Find the position to insert: right after the corresponding call
770        let insert_pos = messages
771            .iter()
772            .position(|msg| {
773                msg.tool_calls
774                    .as_ref()
775                    .is_some_and(|calls| calls.iter().any(|call| call.id == missing.call_id.as_str()))
776            })
777            .map(|pos| pos + 1);
778
779        if let Some(pos) = insert_pos {
780            messages.insert(pos, synthetic_message);
781        } else {
782            // If we can't find the call, just append the synthetic output
783            messages.push(synthetic_message);
784        }
785    }
786}
787
788/// Remove outputs without corresponding calls (orphaned outputs) from the message list.
789pub fn remove_orphan_outputs(messages: &mut Vec<Message>) {
790    let report = validate_history_invariants(messages);
791
792    if report.orphan_outputs.is_empty() {
793        return;
794    }
795
796    let orphan_ids: HashSet<String> = report.orphan_outputs.iter().map(|id| id.as_str().to_string()).collect();
797
798    let initial_len = messages.len();
799
800    // Retain only messages that either:
801    // - Don't have a tool_call_id (not a tool response)
802    // - Have a tool_call_id that matches an existing call
803    messages.retain(|msg| {
804        if let Some(tool_call_id) = msg.tool_call_id.as_ref()
805            && orphan_ids.contains(tool_call_id)
806        {
807            tracing::warn!("Removing orphan output for call {}", tool_call_id);
808            return false;
809        }
810        true
811    });
812
813    if messages.len() != initial_len {
814        tracing::info!("Removed {} orphan outputs", initial_len - messages.len());
815    }
816}
817
818/// Normalize history to enforce call/output pairing invariants.
819pub fn normalize_history(messages: &mut Vec<Message>) {
820    ensure_call_outputs_present(messages);
821    remove_orphan_outputs(messages);
822
823    // Log if issues were found
824    let report = validate_history_invariants(messages);
825    if !report.is_valid() {
826        tracing::warn!("History validation: {}", report.summary());
827    } else {
828        tracing::debug!("History normalized successfully");
829    }
830}
831
832/// Recover from crashed or interrupted session by fixing history invariants.
833pub fn recover_history_from_crash(messages: &mut Vec<Message>) {
834    let report = validate_history_invariants(messages);
835
836    if !report.missing_outputs.is_empty() {
837        tracing::warn!("Found {} missing outputs during recovery", report.missing_outputs.len());
838        ensure_call_outputs_present(messages);
839    }
840
841    if !report.orphan_outputs.is_empty() {
842        tracing::warn!("Found {} orphan outputs during recovery", report.orphan_outputs.len());
843        remove_orphan_outputs(messages);
844    }
845
846    if report.is_valid() {
847        tracing::debug!("History invariants are valid");
848    }
849}
850
851// ============================================================================
852// Tests: Context Manager - Call/Output Pairing Invariants
853// ============================================================================
854
855#[cfg(test)]
856mod tests;
857#[cfg(test)]
858mod tool_result_clearing_tests;