| 1 | //! One private phase of the existing Engine turn loop. |
| 2 | |
| 3 | use super::*; |
| 4 | |
| 5 | impl Engine { |
| 6 | pub(super) async fn continue_model_step( |
| 7 | &mut self, |
| 8 | turn: &mut TurnContext, |
| 9 | tool_policy: &ToolSurfacePolicy, |
| 10 | progress: &mut TurnLoopProgress, |
| 11 | response: AcceptedModelStep, |
| 12 | ) -> PhaseResult<AcceptedModelStep> { |
| 13 | let _timing = codewhale_runtime::logging::PhaseTimer::start("model_continuation"); |
| 14 | if self.rlm_host.is_some() { |
| 15 | return self |
| 16 | .continue_rlm_model_step(turn, tool_policy, progress, response) |
| 17 | .await; |
| 18 | } |
| 19 | let tool_registry = Some(&tool_policy.registry); |
| 20 | let AcceptedModelStep { |
| 21 | current_text_visible, |
| 22 | tool_uses, |
| 23 | mut pending_steers, |
| 24 | mut output_limit_truncated, |
| 25 | zero_tool_turn, |
| 26 | zero_tool_text_call, |
| 27 | fleet_report_response, |
| 28 | fleet_no_progress_report, |
| 29 | has_sendable_assistant_content, |
| 30 | has_provider_reasoning, |
| 31 | no_sendable_assistant_content, |
| 32 | stop_reason, |
| 33 | stream_errors, |
| 34 | prepared_output_tokens, |
| 35 | } = response; |
| 36 | // A truncated response with no tool call cannot continue through |
| 37 | // tool execution: surface the truncation as a bounded observation |
| 38 | // and resume the loop so the model can act on it instead of the |
| 39 | // turn silently ending on a cut-off answer. Resume only when the |
| 40 | // truncated response actually delivered partial content — a |
| 41 | // reasoning-only length stop delivered nothing to continue from. |
| 42 | // The default fails that turn; opt-in answer recovery is handled below. |
| 43 | if output_limit_truncated.is_some() |
| 44 | && !fleet_no_progress_report |
| 45 | && tool_uses.is_empty() |
| 46 | && has_sendable_assistant_content |
| 47 | { |
| 48 | let reason = output_limit_truncated |
| 49 | .take() |
| 50 | .expect("output_limit_truncated checked above"); |
| 51 | self.add_session_message( |
| 52 | self.runtime_text_message_with_turn_metadata( |
| 53 | format!( |
| 54 | "[runtime] The provider stopped generation at its output limit (`{reason}`) before completing. Your last response was cut off. Continue from where you left off; do not repeat content already delivered." |
| 55 | ), |
| 56 | UserInputProvenance::Runtime, |
| 57 | ), |
| 58 | ) |
| 59 | .await; |
| 60 | let _ = self |
| 61 | .send_event(Event::status( |
| 62 | "Continuing — provider output limit reached; asking the model to continue" |
| 63 | .to_string(), |
| 64 | )) |
| 65 | .await; |
| 66 | turn.next_step(); |
| 67 | return PhaseResult::Retry; |
| 68 | } |
| 69 | |
| 70 | if tool_uses.is_empty() && !fleet_no_progress_report { |
| 71 | if !pending_steers.is_empty() { |
| 72 | if let Some(guard) = progress.fleet_denial_guard.as_mut() { |
| 73 | guard.reset(); |
| 74 | turn.stop_diagnostics |
| 75 | .permission_denial_rounds_without_progress = 0; |
| 76 | } |
| 77 | for pending in pending_steers.drain(..) { |
| 78 | let (raw_steer, person_text) = self.commit_pending_steer_with_intent(pending); |
| 79 | let steer = raw_steer.trim().to_string(); |
| 80 | self.session |
| 81 | .working_set |
| 82 | .observe_user_message(&steer, &self.session.workspace); |
| 83 | self.add_session_message(self.user_text_message_with_turn_metadata(steer)) |
| 84 | .await; |
| 85 | if let Some(person_text) = person_text { |
| 86 | let index = self.session.messages.len().saturating_sub(1); |
| 87 | self.session.record_person_message(person_text, Some(index)); |
| 88 | } |
| 89 | } |
| 90 | let _ = self |
| 91 | .send_event(Event::status("Continuing — queued steer input".to_string())) |
| 92 | .await; |
| 93 | turn.next_step(); |
| 94 | return PhaseResult::Retry; |
| 95 | } |
| 96 | |
| 97 | self.deliver_shell_completions("").await; |
| 98 | |
| 99 | // Sub-agent completion handoff (issue #756). Resuming when |
| 100 | // queued completions exist is correct; #3216 says do not wait |
| 101 | // indefinitely for every running child here. Healthy work |
| 102 | // keeps running and reports by sentinel on a later turn. |
| 103 | let subagent_completions = if self.is_acp_turn() { |
| 104 | 0 |
| 105 | } else { |
| 106 | self.drain_subagent_completion_events("").await |
| 107 | }; |
| 108 | if subagent_completions > 0 { |
| 109 | let _ = self |
| 110 | .send_event(Event::status(format!( |
| 111 | "Continuing — {subagent_completions} sub-agent(s) completed" |
| 112 | ))) |
| 113 | .await; |
| 114 | turn.next_step(); |
| 115 | return PhaseResult::Retry; |
| 116 | } |
| 117 | |
| 118 | // Issue #1727: the turn is now genuinely finishing with no |
| 119 | // sendable content. Control only reaches here when there were |
| 120 | // no pending steers (`continue`d above) and no sub-agent |
| 121 | // completions to resume with. Healthy running children do |
| 122 | // not force another model request. |
| 123 | // If the assistant produced ONLY a reasoning block, the prior |
| 124 | // code fell straight through to this `break`, emitting nothing |
| 125 | // and leaving the UI spinner hung. Surface a status now — |
| 126 | // safe because the turn can no longer resume. |
| 127 | // #1961: Before breaking, drain any sub-agent completions that |
| 128 | // arrived between the last hold check and now. If a child finished |
| 129 | // while we were running the thinking-only check, surface its |
| 130 | // sentinel rather than delaying it to the next turn. |
| 131 | self.deliver_shell_completions("late").await; |
| 132 | |
| 133 | if !self.is_acp_turn() && self.drain_subagent_completion_events("late").await > 0 { |
| 134 | let _ = self |
| 135 | .send_event(Event::status( |
| 136 | "Continuing — late sub-agent completion".to_string(), |
| 137 | )) |
| 138 | .await; |
| 139 | turn.next_step(); |
| 140 | return PhaseResult::Retry; |
| 141 | } |
| 142 | |
| 143 | // A goal continuation is optional work on top of a productive |
| 144 | // step. A response that produced nothing sendable and ran no |
| 145 | // tools is a failed step (incomplete/length-stopped provider |
| 146 | // response): continuing would re-issue the exact request that |
| 147 | // just failed — for an output-length stop it can only |
| 148 | // reproduce — instead of failing the turn honestly. |
| 149 | let step_produced_nothing = no_sendable_assistant_content && tool_uses.is_empty(); |
| 150 | if !self.is_acp_turn() |
| 151 | && !step_produced_nothing |
| 152 | && let Some(continuation) = self |
| 153 | .goal_continuation_message_if_needed( |
| 154 | tool_registry, |
| 155 | &mut progress.goal_continuations_this_turn, |
| 156 | &turn.usage, |
| 157 | ) |
| 158 | .await |
| 159 | { |
| 160 | // The model already delivered a complete answer this step; |
| 161 | // the continuation is optional runtime work on top of it. |
| 162 | // If the step budget then runs out, the turn is finished, |
| 163 | // not failed. |
| 164 | progress.step_budget_exhaustion_is_terminal = false; |
| 165 | self.add_session_message(self.runtime_text_message_with_turn_metadata( |
| 166 | continuation, |
| 167 | UserInputProvenance::GoalContinuation, |
| 168 | )) |
| 169 | .await; |
| 170 | let _ = self |
| 171 | .send_event(Event::status(format!( |
| 172 | "Continuing — goal still active (pass {goal_continuations_this_turn})", |
| 173 | goal_continuations_this_turn = progress.goal_continuations_this_turn |
| 174 | ))) |
| 175 | .await; |
| 176 | turn.next_step(); |
| 177 | return PhaseResult::Retry; |
| 178 | } |
| 179 | |
| 180 | let output_limit_stop = is_output_limit_stop_reason(stop_reason.as_deref()); |
| 181 | let opted_in_output_limit = |
| 182 | self.config.reasoning_only_on_output_limit && output_limit_stop; |
| 183 | if no_sendable_assistant_content |
| 184 | && !zero_tool_text_call |
| 185 | && (has_provider_reasoning || opted_in_output_limit) |
| 186 | && should_fail_no_sendable_content( |
| 187 | tool_uses.is_empty(), |
| 188 | progress.turn_error.is_none(), |
| 189 | self.cancel_token.is_cancelled(), |
| 190 | !pending_steers.is_empty(), |
| 191 | false, |
| 192 | ) |
| 193 | && (!output_limit_stop || opted_in_output_limit) |
| 194 | && progress.reasoning_only_reprompts < self.config.reasoning_only_max_reprompts |
| 195 | { |
| 196 | progress.reasoning_only_reprompts += 1; |
| 197 | turn.stop_diagnostics.reasoning_only_reprompts = progress.reasoning_only_reprompts; |
| 198 | let attempt = progress.reasoning_only_reprompts; |
| 199 | let max_reprompts = self.config.reasoning_only_max_reprompts; |
| 200 | progress.reasoning_only_nudge = (attempt > 1 || output_limit_stop) |
| 201 | .then(|| { |
| 202 | self.config |
| 203 | .reasoning_only_reprompt_message |
| 204 | .clone() |
| 205 | .unwrap_or_else(|| { |
| 206 | codewhale_runtime::config::DEFAULT_REASONING_ONLY_REPROMPT_MESSAGE |
| 207 | .to_string() |
| 208 | }) |
| 209 | }) |
| 210 | .filter(|text| !text.trim().is_empty()); |
| 211 | let nudged = progress.reasoning_only_nudge.is_some(); |
| 212 | let how = if nudged { |
| 213 | "re-requesting the answer with a nudge" |
| 214 | } else { |
| 215 | "re-requesting the answer" |
| 216 | }; |
| 217 | let reason = if output_limit_stop { |
| 218 | "output-limit reply" |
| 219 | } else { |
| 220 | "reasoning-only reply" |
| 221 | }; |
| 222 | codewhale_runtime::logging::warn(format!( |
| 223 | "Model returned {reason} with no answer or tool call (attempt {attempt}/{max_reprompts}); {how}" |
| 224 | )); |
| 225 | let locale = codewhale_localization::resolve_locale(&self.config.locale_tag); |
| 226 | let action = codewhale_localization::tr( |
| 227 | locale, |
| 228 | if nudged { |
| 229 | codewhale_localization::MessageId::AnswerRetryActionNudge |
| 230 | } else { |
| 231 | codewhale_localization::MessageId::AnswerRetryActionBare |
| 232 | }, |
| 233 | ); |
| 234 | let body = codewhale_localization::tr( |
| 235 | locale, |
| 236 | if output_limit_stop { |
| 237 | codewhale_localization::MessageId::OutputLimitAnswerRetryBody |
| 238 | } else { |
| 239 | codewhale_localization::MessageId::ReasoningOnlyRetryBody |
| 240 | }, |
| 241 | ) |
| 242 | .replace("{attempt}", &attempt.to_string()) |
| 243 | .replace("{limit}", &max_reprompts.to_string()) |
| 244 | .replace("{action}", action.as_ref()); |
| 245 | let _ = self |
| 246 | .send_retry_status(format!("Retry attempt: {body}")) |
| 247 | .await; |
| 248 | progress.turn_error = None; |
| 249 | return PhaseResult::Retry; |
| 250 | } |
| 251 | |
| 252 | // #6310: a clean terminal stop with no text, no reasoning and |
| 253 | // no tool call. The stream finished without a transport error, |
| 254 | // so the NoContentStreamDeath resume above never sees it; it |
| 255 | // is the same transient failure all the same. Nothing was |
| 256 | // persisted for this response, so the first retry re-issues |
| 257 | // the identical request, the second carries the request-scoped |
| 258 | // nudge, and after that the turn fails visibly below. |
| 259 | let empty_clean_stop = no_sendable_assistant_content |
| 260 | && !zero_tool_text_call |
| 261 | && !has_provider_reasoning |
| 262 | && stream_errors == 0 |
| 263 | && stop_reason.is_some() |
| 264 | && !is_output_limit_stop_reason(stop_reason.as_deref()) |
| 265 | && should_fail_no_sendable_content( |
| 266 | tool_uses.is_empty(), |
| 267 | progress.turn_error.is_none(), |
| 268 | self.cancel_token.is_cancelled(), |
| 269 | !pending_steers.is_empty(), |
| 270 | false, |
| 271 | ); |
| 272 | if empty_clean_stop |
| 273 | && let Some(retry) = plan_empty_stop_retry(progress.empty_stop_retries) |
| 274 | { |
| 275 | progress.empty_stop_retries += 1; |
| 276 | turn.stop_diagnostics.empty_stop_retries = progress.empty_stop_retries; |
| 277 | let attempt = progress.empty_stop_retries; |
| 278 | let reason = stop_reason_detail(stop_reason.as_deref()); |
| 279 | let how = match retry { |
| 280 | EmptyStopRetry::ExactPrefix => "re-requesting the answer", |
| 281 | EmptyStopRetry::Nudged => { |
| 282 | let text = self |
| 283 | .config |
| 284 | .reasoning_only_reprompt_message |
| 285 | .clone() |
| 286 | .unwrap_or_else(|| { |
| 287 | codewhale_runtime::config::DEFAULT_REASONING_ONLY_REPROMPT_MESSAGE |
| 288 | .to_string() |
| 289 | }); |
| 290 | if !text.trim().is_empty() { |
| 291 | progress.reasoning_only_nudge = Some(text); |
| 292 | } |
| 293 | "re-requesting the answer with a nudge" |
| 294 | } |
| 295 | }; |
| 296 | codewhale_runtime::logging::warn(format!( |
| 297 | "Model returned terminal stop reason `{reason}` with no answer or tool call (attempt {attempt}/{EMPTY_STOP_MAX_RETRIES}); {how}" |
| 298 | )); |
| 299 | let _ = self.send_retry_status(format!( |
| 300 | "Retry attempt: empty-stop {attempt}/{EMPTY_STOP_MAX_RETRIES}; no answer, reasoning or tool call; {how}" |
| 301 | )) |
| 302 | .await; |
| 303 | return PhaseResult::Retry; |
| 304 | } |
| 305 | |
| 306 | if no_sendable_assistant_content |
| 307 | && should_fail_no_sendable_content( |
| 308 | tool_uses.is_empty(), |
| 309 | progress.turn_error.is_none(), |
| 310 | self.cancel_token.is_cancelled(), |
| 311 | !pending_steers.is_empty(), |
| 312 | false, |
| 313 | ) |
| 314 | { |
| 315 | let message = if zero_tool_text_call { |
| 316 | "Model answered only with a tool call, and this turn offers no tools." |
| 317 | .to_string() |
| 318 | } else if is_output_limit_stop_reason(stop_reason.as_deref()) { |
| 319 | // With or without streamed reasoning: a provider that |
| 320 | // keeps its reasoning to itself still spends the |
| 321 | // allowance on it (#6889). |
| 322 | format!( |
| 323 | "Model reached the response output limit with no answer or tool call (requested allowance: {} tokens, including reasoning).", |
| 324 | prepared_output_tokens |
| 325 | ) |
| 326 | } else if has_provider_reasoning { |
| 327 | let reason = codewhale_models::stop_reason_detail(stop_reason.as_deref()); |
| 328 | format!( |
| 329 | "Model returned reasoning but no answer or tool call; the provider response was incomplete (stop reason: {}).", |
| 330 | reason |
| 331 | .chars() |
| 332 | .flat_map(char::escape_default) |
| 333 | .take(120) |
| 334 | .collect::<String>() |
| 335 | ) |
| 336 | } else if let Some(reason) = stop_reason.as_deref() { |
| 337 | if progress.empty_stop_retries > 0 { |
| 338 | format!( |
| 339 | "Model returned terminal stop reason `{reason}` with no answer or tool call (after {empty_stop_retries} retries).", |
| 340 | empty_stop_retries = progress.empty_stop_retries |
| 341 | ) |
| 342 | } else { |
| 343 | format!( |
| 344 | "Model returned terminal stop reason `{reason}` with no answer or tool call." |
| 345 | ) |
| 346 | } |
| 347 | } else { |
| 348 | "Model stream ended with no answer or tool call.".to_string() |
| 349 | }; |
| 350 | codewhale_runtime::logging::warn(&message); |
| 351 | progress.turn_error = Some(message.clone()); |
| 352 | let _ = self |
| 353 | .send_event(Event::error(ErrorEnvelope::classify(message, true))) |
| 354 | .await; |
| 355 | } |
| 356 | |
| 357 | if progress.turn_error.is_none() { |
| 358 | if !turn.budget_exhausted_final_report { |
| 359 | turn.stop_diagnostics.reason = Some(TurnStopReason::ProviderNoToolCall); |
| 360 | } |
| 361 | // This branch received no calls and dispatches no tools. |
| 362 | turn.stop_diagnostics.last_response_tool_calls_suppressed = Some(0); |
| 363 | } |
| 364 | return PhaseResult::Break; |
| 365 | } |
| 366 | |
| 367 | PhaseResult::Ready(AcceptedModelStep { |
| 368 | current_text_visible, |
| 369 | tool_uses, |
| 370 | pending_steers, |
| 371 | output_limit_truncated, |
| 372 | zero_tool_turn, |
| 373 | zero_tool_text_call, |
| 374 | fleet_report_response, |
| 375 | fleet_no_progress_report, |
| 376 | has_sendable_assistant_content, |
| 377 | has_provider_reasoning, |
| 378 | no_sendable_assistant_content, |
| 379 | stop_reason, |
| 380 | stream_errors, |
| 381 | prepared_output_tokens, |
| 382 | }) |
| 383 | } |
| 384 | } |
| 385 |