@@ -349,6 +349,10 @@ pub async fn run_agent_loop(
349349 // pair across the cut boundary, leaving orphaned blocks that cause the LLM
350350 // to return empty responses (input_tokens=0).
351351 messages = crate :: session_repair:: validate_and_repair ( & messages) ;
352+ // Ensure history starts with a user turn: trimming may have left an
353+ // assistant turn at position 0, which strict providers (e.g. Gemini)
354+ // reject with INVALID_ARGUMENT on function-call turns.
355+ messages = crate :: session_repair:: ensure_starts_with_user ( messages) ;
352356 }
353357
354358 // Use autonomous config max_iterations if set, else default
@@ -388,6 +392,8 @@ pub async fn run_agent_loop(
388392 // which may have broken assistant→tool ordering invariants.
389393 if recovery != RecoveryStage :: None {
390394 messages = crate :: session_repair:: validate_and_repair ( & messages) ;
395+ // Ensure history starts with a user turn after overflow recovery.
396+ messages = crate :: session_repair:: ensure_starts_with_user ( messages) ;
391397 }
392398
393399 // Context guard: compact oversized tool results before LLM call
@@ -1512,6 +1518,10 @@ pub async fn run_agent_loop_streaming(
15121518 // pair across the cut boundary, leaving orphaned blocks that cause the LLM
15131519 // to return empty responses (input_tokens=0).
15141520 messages = crate :: session_repair:: validate_and_repair ( & messages) ;
1521+ // Ensure history starts with a user turn: trimming may have left an
1522+ // assistant turn at position 0, which strict providers (e.g. Gemini)
1523+ // reject with INVALID_ARGUMENT on function-call turns.
1524+ messages = crate :: session_repair:: ensure_starts_with_user ( messages) ;
15151525 }
15161526
15171527 // Use autonomous config max_iterations if set, else default
@@ -1569,6 +1579,8 @@ pub async fn run_agent_loop_streaming(
15691579 // be followed by tool messages" errors after context overflow recovery.)
15701580 if recovery != RecoveryStage :: None {
15711581 messages = crate :: session_repair:: validate_and_repair ( & messages) ;
1582+ // Ensure history starts with a user turn after overflow recovery.
1583+ messages = crate :: session_repair:: ensure_starts_with_user ( messages) ;
15721584 }
15731585
15741586 // Context guard: compact oversized tool results before LLM call
0 commit comments