| 1 | //! One private phase of the existing Engine turn loop. |
| 2 | |
| 3 | use super::*; |
| 4 | |
| 5 | impl Engine { |
| 6 | pub(super) async fn prepare_model_step( |
| 7 | &mut self, |
| 8 | turn: &mut TurnContext, |
| 9 | tool_policy: &ToolSurfacePolicy, |
| 10 | progress: &mut TurnLoopProgress, |
| 11 | client: &SharedModelClient, |
| 12 | inspection_surface: Option<&crate::tool_inspection::ToolSurfaceContext>, |
| 13 | ) -> PhaseResult<PreparedModelStep> { |
| 14 | let _timing = codewhale_runtime::logging::PhaseTimer::start("model_preparation"); |
| 15 | if self.rlm_host.is_some() { |
| 16 | return self |
| 17 | .prepare_rlm_model_step(turn, client, inspection_surface) |
| 18 | .await; |
| 19 | } |
| 20 | let strict_tool_mode = tool_policy.strict_tool_mode; |
| 21 | |
| 22 | if self.cancel_token.is_cancelled() { |
| 23 | let _ = self.send_event(Event::status("Request cancelled")).await; |
| 24 | return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None)); |
| 25 | } |
| 26 | self.turn_heartbeat.enter( |
| 27 | super::turn_heartbeat::TurnPhase::Preparing, |
| 28 | None, |
| 29 | Some(super::turn_heartbeat::PREPARING_PHASE_BOUND), |
| 30 | ); |
| 31 | self.refresh_boot_mcp_catalog( |
| 32 | tool_policy, |
| 33 | &mut progress.tool_catalog, |
| 34 | &mut progress.active_tool_names, |
| 35 | ) |
| 36 | .await; |
| 37 | self.record_mcp_runtime_context(tool_policy, &mut progress.tool_catalog) |
| 38 | .await; |
| 39 | self.record_current_constitution().await; |
| 40 | self.record_current_extension_prompt_contributions().await; |
| 41 | self.record_current_project_instructions().await; |
| 42 | self.record_current_skills_context().await; |
| 43 | |
| 44 | // R1: the cumulative per-turn wall-clock budget. Checked at the |
| 45 | // provider-request boundary so a turn that runs out of time stops |
| 46 | // before authorizing another billable request, and every tool |
| 47 | // result already produced stays in the transcript. Hitting it is |
| 48 | // never a clean success — the turn ends `Failed` with the limit |
| 49 | // named, matching how the step ceiling below reports. |
| 50 | if let Some(error) = self.turn_wall_clock_exhausted_error() { |
| 51 | self.post_turn_budget_stop(&error).await; |
| 52 | return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error))); |
| 53 | } |
| 54 | |
| 55 | if self.apply_pending_runtime_authority().await { |
| 56 | if let Some(guard) = progress.fleet_denial_guard.as_mut() { |
| 57 | guard.reset(); |
| 58 | turn.stop_diagnostics |
| 59 | .permission_denial_rounds_without_progress = 0; |
| 60 | } |
| 61 | progress.mode = self.current_mode; |
| 62 | } |
| 63 | if self.record_mode_context(self.current_mode) { |
| 64 | self.emit_session_updated().await; |
| 65 | } |
| 66 | |
| 67 | let mut accepted_steer = false; |
| 68 | while let Some(pending) = self.next_turn_steer() { |
| 69 | if pending.content.trim().is_empty() { |
| 70 | // Nothing to deliver; dropping `pending` settles it. |
| 71 | continue; |
| 72 | } |
| 73 | let (raw_steer, person_text) = self.commit_pending_steer_with_intent(pending); |
| 74 | let steer = raw_steer.trim().to_string(); |
| 75 | accepted_steer = true; |
| 76 | self.session |
| 77 | .working_set |
| 78 | .observe_user_message(&steer, &self.session.workspace); |
| 79 | self.add_session_message(self.user_text_message_with_turn_metadata(steer)) |
| 80 | .await; |
| 81 | if let Some(person_text) = person_text { |
| 82 | let index = self.session.messages.len().saturating_sub(1); |
| 83 | self.session.record_person_message(person_text, Some(index)); |
| 84 | } |
| 85 | } |
| 86 | if accepted_steer && let Some(guard) = progress.fleet_denial_guard.as_mut() { |
| 87 | guard.reset(); |
| 88 | turn.stop_diagnostics |
| 89 | .permission_denial_rounds_without_progress = 0; |
| 90 | } |
| 91 | |
| 92 | // Child agents can finish while the parent model is still taking |
| 93 | // tool steps. Surface queued completions before the next provider |
| 94 | // request so the parent can use them immediately instead of |
| 95 | // discovering them only when it eventually emits no more tools or |
| 96 | // the idle handler starts a separate follow-up turn. |
| 97 | if !self.is_acp_turn() { |
| 98 | self.drain_subagent_completion_events("queued").await; |
| 99 | } |
| 100 | |
| 101 | // The pinned system + tools prefix is frozen for the session: |
| 102 | // recomposing it here from disk on every tool step is exactly what |
| 103 | // kills DeepSeek's KV prefix cache once the agent writes a file |
| 104 | // (the project pack listing changes -> the system hash changes -> |
| 105 | // the next same-turn request is a full miss). Header changes come |
| 106 | // only from explicit ops (`/model`, mode, goal, session sync), |
| 107 | // which refresh under a declared reason. Volatile facts the model |
| 108 | // must see mid-turn (LSP diagnostics, steer input, subagent |
| 109 | // completions) are appended to history above, never spliced into |
| 110 | // the frozen prefix. |
| 111 | let zero_tool_turn = progress.tool_catalog.is_empty(); |
| 112 | if let Some(job) = self.child_job() { |
| 113 | if job.authority.runtime.cancel_token.is_cancelled() { |
| 114 | return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None)); |
| 115 | } |
| 116 | if job |
| 117 | .deadline |
| 118 | .is_some_and(|deadline| Instant::now() >= deadline) |
| 119 | { |
| 120 | job.stop_for_limit(codewhale_protocol::agent_run::AgentLimitKind::WallTime); |
| 121 | return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None)); |
| 122 | } |
| 123 | if turn.at_max_steps() { |
| 124 | job.stop_for_limit(codewhale_protocol::agent_run::AgentLimitKind::Step); |
| 125 | return PhaseResult::Return(( |
| 126 | TurnOutcomeStatus::Failed, |
| 127 | Some("child model-step work budget exhausted".into()), |
| 128 | )); |
| 129 | } |
| 130 | } |
| 131 | if turn.at_max_steps() { |
| 132 | turn.stop_diagnostics.reason = Some(TurnStopReason::StepBudgetExhausted); |
| 133 | if self.child_host.is_none() |
| 134 | && progress.step_budget_exhaustion_is_terminal |
| 135 | && !progress.final_report_sent |
| 136 | && !zero_tool_turn |
| 137 | { |
| 138 | // A2 report-on-exhaustion: the budget died while the model |
| 139 | // still owes work. Never finish silently — grant exactly |
| 140 | // one final provider turn to write a bounded report, then |
| 141 | // let the natural no-tool termination close the turn. |
| 142 | progress.final_report_sent = true; |
| 143 | turn.budget_exhausted_final_report = true; |
| 144 | let notice = format!( |
| 145 | "Your model-step budget was exhausted (limit: {}, {}). You cannot continue working. Write your final report now: what you did, what you proved or found, what remains, and exact evidence. This is your last turn.", |
| 146 | turn.max_steps, |
| 147 | turn.budget_source.key_label(), |
| 148 | ); |
| 149 | self.add_session_message(self.user_text_message_with_turn_metadata(notice)) |
| 150 | .await; |
| 151 | let _ = self |
| 152 | .send_event(Event::status( |
| 153 | "Model budget exhausted — final report requested", |
| 154 | )) |
| 155 | .await; |
| 156 | } else if !progress.step_budget_exhaustion_is_terminal { |
| 157 | return PhaseResult::Break; |
| 158 | } else { |
| 159 | let error = format!( |
| 160 | "Maximum model steps reached before completion (limit: {}, {})", |
| 161 | turn.max_steps, |
| 162 | turn.budget_source.key_label(), |
| 163 | ); |
| 164 | self.post_turn_budget_stop(&error).await; |
| 165 | return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error))); |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | // A tool-producing response can spend the remaining goal budget |
| 170 | // before this loop reaches the no-tool continuation check below. |
| 171 | // Stop at the provider-request boundary so tool results remain in |
| 172 | // the transcript, but no additional model request is authorized. |
| 173 | // GoalState remains untouched here: the outer turn bookkeeping |
| 174 | // records this usage once, then the normal cross-turn reconciler |
| 175 | // publishes the terminal Blocked projection. |
| 176 | // Token budget is advisory (unbounded) — surface telemetry but don't break. |
| 177 | // Like grokbuild/kimicode, only verifier completion/block or backstop ends the run. |
| 178 | if let Some(snapshot) = self.goal_snapshot_with_current_turn_usage(&turn.usage) |
| 179 | && let Some(budget) = snapshot.token_budget |
| 180 | && snapshot.tokens_used >= u64::from(budget) |
| 181 | { |
| 182 | let _ = self.send_event(Event::status(format!( |
| 183 | "Goal over token budget ({} / {budget} tokens) — continuing (unbounded); verify or /goal clear when done.", |
| 184 | snapshot.tokens_used |
| 185 | ))) |
| 186 | .await; |
| 187 | } |
| 188 | |
| 189 | let active_tools = active_tools_for_request( |
| 190 | &super::super::tool_catalog::mode_visible_catalog( |
| 191 | &progress.tool_catalog, |
| 192 | progress.mode, |
| 193 | ), |
| 194 | &progress.active_tool_names, |
| 195 | strict_tool_mode, |
| 196 | ); |
| 197 | let guard_effort = resolve_auto_effort( |
| 198 | self.session.reasoning_effort.as_deref(), |
| 199 | self.api_provider, |
| 200 | &self.api_config.active_route_base_url(), |
| 201 | &self.config.model, |
| 202 | ); |
| 203 | let mut output_tokens = |
| 204 | crate::route_budget::effective_max_output_tokens_for_turn_with_window( |
| 205 | self.api_provider, |
| 206 | &self.session.model, |
| 207 | self.active_route_limits, |
| 208 | self.active_context_window.map(|window| window.tokens), |
| 209 | turn.max_output_tokens, |
| 210 | guard_effort.as_deref(), |
| 211 | ); |
| 212 | if turn.max_output_tokens.is_some() { |
| 213 | output_tokens = |
| 214 | output_tokens.min(client.effective_max_output_tokens(&self.session.model)); |
| 215 | } |
| 216 | if let Err(error) = self |
| 217 | .apply_instruction_budget_notices( |
| 218 | active_tools.as_deref().unwrap_or_default(), |
| 219 | output_tokens, |
| 220 | ) |
| 221 | .await |
| 222 | { |
| 223 | self.post_turn_budget_stop(&error).await; |
| 224 | return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error))); |
| 225 | } |
| 226 | match self |
| 227 | .run_auto_compaction( |
| 228 | client.as_ref(), |
| 229 | active_tools.as_deref(), |
| 230 | turn, |
| 231 | &mut progress.auto_compaction_suppressed, |
| 232 | ) |
| 233 | .await |
| 234 | { |
| 235 | AutoCompactionStep::Proceed => {} |
| 236 | AutoCompactionStep::Restart => return PhaseResult::Retry, |
| 237 | AutoCompactionStep::EndTurn(status, error) => { |
| 238 | return PhaseResult::Return((status, error)); |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | // Resolve `auto` reasoning_effort to a concrete tier (#663). |
| 243 | let effective_reasoning_effort = resolve_auto_effort( |
| 244 | self.session.reasoning_effort.as_deref(), |
| 245 | self.api_provider, |
| 246 | &self.api_config.active_route_base_url(), |
| 247 | &self.config.model, |
| 248 | ); |
| 249 | |
| 250 | // The guard measures what the compaction gate measures: the honest |
| 251 | // estimate, lifted to the provider's last bill plus the growth |
| 252 | // since it. The ×1.5-inflated overflow estimate, compared against |
| 253 | // the honest ceiling, refused at two |
| 254 | // thirds of the budget, and emergency compaction — which targets |
| 255 | // the honest budget — could never satisfy it (#6374). A request |
| 256 | // the estimate still undercounts is rejected by the provider and |
| 257 | // takes the bounded context-length recovery below. |
| 258 | let estimated_input = turn |
| 259 | .live_input_tokens_for_compaction( |
| 260 | &self.session.messages, |
| 261 | self.session.system_prompt.as_ref(), |
| 262 | self.session.latest_parent_input_tokens, |
| 263 | ) |
| 264 | .and_then(|tokens| usize::try_from(tokens).ok()) |
| 265 | .unwrap_or(0); |
| 266 | if let Some(budget) = crate::route_budget::route_context_budget_with_window( |
| 267 | self.api_provider, |
| 268 | &self.session.model, |
| 269 | self.active_route_limits, |
| 270 | self.active_context_window.map(|window| window.tokens), |
| 271 | estimated_input, |
| 272 | ) { |
| 273 | let input_budget = usize::try_from( |
| 274 | crate::route_budget::route_admission_input_ceiling_with_window( |
| 275 | self.api_provider, |
| 276 | &self.session.model, |
| 277 | self.active_route_limits, |
| 278 | self.active_context_window.map(|window| window.tokens), |
| 279 | ) |
| 280 | .unwrap_or(budget.input_budget_ceiling), |
| 281 | ) |
| 282 | .unwrap_or(usize::MAX); |
| 283 | let triggered = estimated_input > input_budget; |
| 284 | let output_ceiling = |
| 285 | crate::route_budget::output_ceiling_source(self.api_provider, &self.session.model); |
| 286 | let route_input_limit = |
| 287 | crate::route_budget::route_input_limit_tokens(self.active_route_limits); |
| 288 | let input_ceiling_source = |
| 289 | route_input_limit.map_or("window-minus-output-headroom", |limit| { |
| 290 | if u64::from(limit) <= budget.input_budget_ceiling { |
| 291 | "route-declared-input-limit" |
| 292 | } else { |
| 293 | "window-minus-output-headroom" |
| 294 | } |
| 295 | }); |
| 296 | tracing::debug!( |
| 297 | target: "context_budget", |
| 298 | provider = self.api_provider.as_str(), |
| 299 | model = %self.session.model, |
| 300 | resolved_route_window_tokens = budget.window_tokens, |
| 301 | resolved_model_output_ceiling_tokens = ?output_ceiling.clamp_tokens(), |
| 302 | resolved_model_output_ceiling_source = output_ceiling.as_str(), |
| 303 | effective_request_output_cap_tokens = crate::route_budget::effective_max_output_tokens_for_turn_with_window( |
| 304 | self.api_provider, |
| 305 | &self.session.model, |
| 306 | self.active_route_limits, |
| 307 | self.active_context_window.map(|window| window.tokens), |
| 308 | turn.max_output_tokens, |
| 309 | effective_reasoning_effort.as_deref(), |
| 310 | ), |
| 311 | reserved_response_headroom_tokens = budget.output_cap_tokens, |
| 312 | safety_headroom_tokens = codewhale_runtime::context_budget::CONTEXT_HEADROOM_TOKENS, |
| 313 | resolved_route_input_limit_tokens = ?route_input_limit, |
| 314 | estimated_input_tokens = estimated_input, |
| 315 | input_budget_ceiling_tokens = budget.input_budget_ceiling, |
| 316 | input_budget_ceiling_source = input_ceiling_source, |
| 317 | remaining_input_budget_tokens = budget.available_input_tokens, |
| 318 | compaction_trigger_tokens = budget.compaction_trigger_tokens, |
| 319 | configured_compaction_trigger_tokens = self.config.compaction.token_threshold, |
| 320 | trigger = if triggered { "preflight-token-budget" } else { "none" }, |
| 321 | "resolved route context budget" |
| 322 | ); |
| 323 | if triggered { |
| 324 | return self |
| 325 | .context_budget_overflow( |
| 326 | turn, |
| 327 | progress, |
| 328 | client, |
| 329 | active_tools.as_deref(), |
| 330 | estimated_input, |
| 331 | input_budget, |
| 332 | ) |
| 333 | .await; |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | // #136: drain any LSP diagnostics collected since the last |
| 338 | // request and inject them as a synthetic user message so the |
| 339 | // model sees compile errors before its next reasoning step. |
| 340 | self.flush_pending_lsp_diagnostics().await; |
| 341 | |
| 342 | // Check prefix-cache stability before building the request. |
| 343 | // This detects system-prompt or tool-set drift that would |
| 344 | // invalidate DeepSeek's KV prefix cache for this turn. |
| 345 | // Sends an event on EVERY check so the TUI can maintain |
| 346 | // its own counter for the stable-checks tally. |
| 347 | let declared_change = self.session.pending_prefix_change_reason.take(); |
| 348 | let mut prefix_check = json!({"outcome": "unavailable"}); |
| 349 | if let Some(pm) = self.session.prefix_stability.as_mut() { |
| 350 | let system_text = codewhale_core::prefix_cache::system_prompt_text( |
| 351 | self.session.system_prompt.as_ref(), |
| 352 | ); |
| 353 | let tools_ref: Option<&[codewhale_models::Tool]> = active_tools.as_deref(); |
| 354 | let outcome = pm.check(&system_text, tools_ref, declared_change.as_deref()); |
| 355 | prefix_check = match &outcome { |
| 356 | codewhale_core::prefix_cache::PrefixCheck::Stable => json!({"outcome": "stable"}), |
| 357 | codewhale_core::prefix_cache::PrefixCheck::Repinned { reason, change } => { |
| 358 | json!({"outcome": "repinned", "reason": reason, "system_changed": change.system_changed, "tools_changed": change.tools_changed}) |
| 359 | } |
| 360 | codewhale_core::prefix_cache::PrefixCheck::Drift { change } => { |
| 361 | json!({"outcome": "drift", "component": change.label(), "system_changed": change.system_changed, "tools_changed": change.tools_changed}) |
| 362 | } |
| 363 | }; |
| 364 | // C5: request N's prefix may only diverge from N-1 across a |
| 365 | // DECLARED change. An undeclared drift means the pinned header |
| 366 | // moved without stamping a context update — the failure that |
| 367 | // silently kills the provider cache while stability claims |
| 368 | // still read well. The first check initializes the pin, so it |
| 369 | // is exempt. |
| 370 | #[cfg(debug_assertions)] |
| 371 | if pm.check_count() > 1 |
| 372 | && declared_change.is_none() |
| 373 | && let codewhale_core::prefix_cache::PrefixCheck::Drift { change } |
| 374 | | codewhale_core::prefix_cache::PrefixCheck::Repinned { change, .. } = &outcome |
| 375 | { |
| 376 | debug_assert!( |
| 377 | false, |
| 378 | "prefix drift without a declared change (C5): the {} changed but no context update was stamped", |
| 379 | change.label() |
| 380 | ); |
| 381 | } |
| 382 | let pinned_hash = pm |
| 383 | .pinned_fingerprint() |
| 384 | .map(|fp| fp.combined_sha256.clone()) |
| 385 | .unwrap_or_default(); |
| 386 | let stability_pct = (pm.stability_ratio() * 100.0).round() as u32; |
| 387 | let pin_reason = pm.pin_reason().unwrap_or_default().to_string(); |
| 388 | let last_miss_reason = pm.last_miss_reason().unwrap_or_default().to_string(); |
| 389 | let context_updates = pm.context_update_count(); |
| 390 | let event = match outcome { |
| 391 | codewhale_core::prefix_cache::PrefixCheck::Stable => Event::PrefixCacheChange { |
| 392 | description: String::new(), |
| 393 | system_prompt_changed: false, |
| 394 | tools_changed: false, |
| 395 | stability_pct, |
| 396 | changed: false, |
| 397 | pinned_combined_hash: pinned_hash, |
| 398 | pin_reason, |
| 399 | last_miss_reason, |
| 400 | context_updates, |
| 401 | }, |
| 402 | codewhale_core::prefix_cache::PrefixCheck::Repinned { reason, change } => { |
| 403 | // A declared header change re-pins under a logged |
| 404 | // reason: the miss is expected and attributable. |
| 405 | tracing::debug!( |
| 406 | target: "prefix_cache", |
| 407 | reason = %reason, |
| 408 | "prefix re-pinned: {}", |
| 409 | change.description() |
| 410 | ); |
| 411 | Event::PrefixCacheChange { |
| 412 | description: format!("{reason} — {}", change.description()), |
| 413 | system_prompt_changed: change.system_changed, |
| 414 | tools_changed: change.tools_changed, |
| 415 | stability_pct, |
| 416 | changed: true, |
| 417 | pinned_combined_hash: pinned_hash, |
| 418 | pin_reason, |
| 419 | last_miss_reason, |
| 420 | context_updates, |
| 421 | } |
| 422 | } |
| 423 | codewhale_core::prefix_cache::PrefixCheck::Drift { change } => { |
| 424 | // Undeclared drift: the pin is kept so the same prefix |
| 425 | // keeps counting as a miss until an explicit op moves |
| 426 | // it. This should not happen after the mid-loop |
| 427 | // refresh removal — if it does it is a real bug. |
| 428 | tracing::warn!( |
| 429 | target: "prefix_cache", |
| 430 | "undeclared prefix drift (pin held): {}", |
| 431 | change.description() |
| 432 | ); |
| 433 | Event::PrefixCacheChange { |
| 434 | description: format!("drift — {}", change.description()), |
| 435 | system_prompt_changed: change.system_changed, |
| 436 | tools_changed: change.tools_changed, |
| 437 | stability_pct, |
| 438 | changed: true, |
| 439 | pinned_combined_hash: pinned_hash, |
| 440 | pin_reason, |
| 441 | last_miss_reason, |
| 442 | context_updates, |
| 443 | } |
| 444 | } |
| 445 | }; |
| 446 | let _ = self.send_event(event).await; |
| 447 | } |
| 448 | |
| 449 | if prefix_check.get("tools_changed").and_then(Value::as_bool) == Some(true) |
| 450 | || (self.session.prefix_stability.is_none() && declared_change.is_some()) |
| 451 | { |
| 452 | let active_deferred_tools: Vec<&str> = active_tools |
| 453 | .iter() |
| 454 | .flatten() |
| 455 | .filter(|tool| { |
| 456 | tool.defer_loading.unwrap_or(false) |
| 457 | && self |
| 458 | .session |
| 459 | .tool_activation_cache |
| 460 | .names() |
| 461 | .any(|cached| cached == tool.name) |
| 462 | }) |
| 463 | .map(|tool| tool.name.as_str()) |
| 464 | .collect(); |
| 465 | let previous_deferred = self |
| 466 | .session |
| 467 | .messages |
| 468 | .iter() |
| 469 | .rev() |
| 470 | .find_map(crate::runtime_handoff::deferred_toolbox_tools); |
| 471 | let deferred_changed = match previous_deferred.as_deref() { |
| 472 | None => !active_deferred_tools.is_empty(), |
| 473 | Some(previous) => { |
| 474 | previous.len() != active_deferred_tools.len() |
| 475 | || previous |
| 476 | .iter() |
| 477 | .zip(active_deferred_tools.iter()) |
| 478 | .any(|(left, right)| left != right) |
| 479 | } |
| 480 | }; |
| 481 | if deferred_changed { |
| 482 | self.add_session_message(crate::runtime_handoff::deferred_toolbox_runtime_message( |
| 483 | &active_deferred_tools, |
| 484 | )) |
| 485 | .await; |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | for notice in self.take_auto_review_retry_notices() { |
| 490 | self.add_session_message( |
| 491 | self.runtime_text_message_with_turn_metadata(notice, UserInputProvenance::Runtime), |
| 492 | ) |
| 493 | .await; |
| 494 | } |
| 495 | |
| 496 | // Three-zone prefix contract (#2264): freeze baseline on first |
| 497 | // turn, verify against it on subsequent turns. Operates alongside |
| 498 | // PrefixStabilityManager as an independent diagnostic layer. |
| 499 | // Phase 3: emit a one-shot 'frozen' event on first turn. |
| 500 | // Drift is logged (tracing::debug!) but not re-emitted — |
| 501 | // PrefixStabilityManager already reports the change above. |
| 502 | let system_text = |
| 503 | codewhale_core::prefix_cache::system_prompt_text(self.session.system_prompt.as_ref()); |
| 504 | let current_tools: &[codewhale_models::Tool] = active_tools.as_deref().unwrap_or_default(); |
| 505 | |
| 506 | match &self.session.frozen_prefix { |
| 507 | Some(frozen) => { |
| 508 | if let Err(drift) = frozen.verify(&system_text, current_tools) { |
| 509 | // Report drift; never replace the frozen baseline. The |
| 510 | // original freeze is the byte prefix the provider cache |
| 511 | // is keyed on — re-freezing here would make `/cache` |
| 512 | // look stable while the provider cache is already dead. |
| 513 | // A declared header change is re-pinned through the |
| 514 | // PrefixStabilityManager path above under a logged |
| 515 | // reason; the three-zone baseline stays put. |
| 516 | tracing::debug!( |
| 517 | target: "prefix_cache", |
| 518 | "three-zone drift (baseline held): {drift}" |
| 519 | ); |
| 520 | } |
| 521 | } |
| 522 | None => { |
| 523 | let pinned = |
| 524 | PinnedPrefix::new(self.session.system_prompt.as_ref(), current_tools.to_vec()); |
| 525 | let frozen = pinned.freeze(); |
| 526 | let _ = self |
| 527 | .send_event(Event::PrefixCacheChange { |
| 528 | description: format!("frozen: {}", frozen.short_id()), |
| 529 | system_prompt_changed: false, |
| 530 | tools_changed: false, |
| 531 | stability_pct: 100, |
| 532 | changed: false, |
| 533 | pinned_combined_hash: frozen.hash().to_string(), |
| 534 | pin_reason: "initial".to_string(), |
| 535 | last_miss_reason: String::new(), |
| 536 | context_updates: 0, |
| 537 | }) |
| 538 | .await; |
| 539 | self.session.frozen_prefix = Some(frozen); |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | let fleet_report_response = progress |
| 544 | .fleet_denial_guard |
| 545 | .as_ref() |
| 546 | .is_some_and(FleetDenialGuard::report_only); |
| 547 | // `take` is what keeps this request-scoped: the nudge is spent |
| 548 | // here and never reaches `self.session.messages`. |
| 549 | let request_nudge = progress.reasoning_only_nudge.take(); |
| 550 | // Build the request. Tool selection goes through the same |
| 551 | // helper that seeded this turn and that `/preview-request` |
| 552 | // reports, so a deferred tool activated mid-turn is reflected |
| 553 | // identically in both places. |
| 554 | let mut request = prepare_primary_turn_request(PrimaryTurnRequest { |
| 555 | model: self.session.model.clone(), |
| 556 | messages: { |
| 557 | let mut messages = self.messages_with_turn_metadata(); |
| 558 | if let Some(nudge) = request_nudge.as_ref() { |
| 559 | messages.push(self.runtime_text_message_with_turn_metadata( |
| 560 | nudge.clone(), |
| 561 | UserInputProvenance::Runtime, |
| 562 | )); |
| 563 | } |
| 564 | messages |
| 565 | }, |
| 566 | max_tokens: crate::route_budget::effective_max_output_tokens_for_turn_with_window( |
| 567 | self.api_provider, |
| 568 | &self.session.model, |
| 569 | self.active_route_limits, |
| 570 | self.active_context_window.map(|window| window.tokens), |
| 571 | turn.max_output_tokens, |
| 572 | effective_reasoning_effort.as_deref(), |
| 573 | ), |
| 574 | system: self.session.system_prompt.clone(), |
| 575 | tools: active_tools.clone(), |
| 576 | tool_choice: if active_tools.is_some() { |
| 577 | if fleet_report_response || turn.budget_exhausted_final_report { |
| 578 | // Keep the pinned tool prefix; only this request's |
| 579 | // choice changes. Admission below also enforces this |
| 580 | // if a provider ignores the report-only request |
| 581 | // (C02-10: the step-budget final report included). |
| 582 | Some(json!("none")) |
| 583 | } else { |
| 584 | Some(default_tool_choice(strict_tool_mode)) |
| 585 | } |
| 586 | } else { |
| 587 | None |
| 588 | }, |
| 589 | reasoning_effort: effective_reasoning_effort, |
| 590 | }); |
| 591 | if turn.max_output_tokens.is_some() { |
| 592 | request.max_tokens = request |
| 593 | .max_tokens |
| 594 | .min(client.effective_max_output_tokens(&self.session.model)); |
| 595 | } |
| 596 | // Normalize images against the route this request is actually |
| 597 | // going to. Session history keeps the real image so that switching |
| 598 | // to a vision-capable model later makes it visible again; only the |
| 599 | // outbound copy is rewritten, and it is rewritten to text that says |
| 600 | // why rather than being dropped. |
| 601 | let fresh_images = crate::image_attach::images_since_last_user_prompt(&request.messages); |
| 602 | let image_provider = self.image_route_provider_key(); |
| 603 | let (image_input, image_cap) = self.request_image_policy( |
| 604 | &image_provider, |
| 605 | &self.session.model, |
| 606 | self.active_route_capabilities.image_input, |
| 607 | ); |
| 608 | let stripped_images = crate::image_attach::strip_images_when_unsupported( |
| 609 | &mut request.messages, |
| 610 | image_input, |
| 611 | &self.session.model, |
| 612 | ); |
| 613 | if stripped_images > 0 { |
| 614 | codewhale_runtime::logging::warn(format!( |
| 615 | "{stripped_images} image block(s) replaced with text: model {} does not accept image input", |
| 616 | self.session.model |
| 617 | )); |
| 618 | if fresh_images > 0 && !progress.image_omission_notified { |
| 619 | progress.image_omission_notified = true; |
| 620 | let status = codewhale_localization::tr( |
| 621 | codewhale_localization::resolve_locale(&self.config.locale_tag), |
| 622 | codewhale_localization::MessageId::ImageInputOmitted, |
| 623 | ) |
| 624 | .replace("{model}", &self.session.model) |
| 625 | .replace("{count}", &fresh_images.to_string()); |
| 626 | let _ = self.send_event(Event::status(status)).await; |
| 627 | } |
| 628 | } |
| 629 | if let Some(cap) = image_cap { |
| 630 | let window = |
| 631 | codewhale_models::image_window::cap_request_images(&mut request.messages, cap); |
| 632 | self.note_request_image_window(image_provider, window).await; |
| 633 | } |
| 634 | let request_input = crate::compaction::estimate_request_input_tokens( |
| 635 | &request.messages, |
| 636 | request.system.as_ref(), |
| 637 | request.tools.as_deref(), |
| 638 | ); |
| 639 | let request_input = turn |
| 640 | .calibrated_input_tokens(request_input) |
| 641 | .max(estimated_input); |
| 642 | let output_cap = crate::route_budget::request_output_cap_for_input_with_window( |
| 643 | self.api_provider, |
| 644 | &self.session.model, |
| 645 | self.active_route_limits, |
| 646 | self.active_context_window.map(|window| window.tokens), |
| 647 | request.max_tokens, |
| 648 | u64::try_from(request_input).unwrap_or(u64::MAX), |
| 649 | ) |
| 650 | .filter(|cap| { |
| 651 | *cap == request.max_tokens |
| 652 | || u64::from(*cap) >= crate::route_budget::MIN_REQUEST_OUTPUT_TOKENS |
| 653 | }); |
| 654 | let Some(output_cap) = output_cap else { |
| 655 | progress.reasoning_only_nudge = request_nudge; |
| 656 | let input_budget = crate::route_budget::route_admission_input_ceiling_with_window( |
| 657 | self.api_provider, |
| 658 | &self.session.model, |
| 659 | self.active_route_limits, |
| 660 | self.active_context_window.map(|window| window.tokens), |
| 661 | ) |
| 662 | .map_or(0, |ceiling| usize::try_from(ceiling).unwrap_or(usize::MAX)); |
| 663 | return self |
| 664 | .context_budget_overflow( |
| 665 | turn, |
| 666 | progress, |
| 667 | client, |
| 668 | active_tools.as_deref(), |
| 669 | request_input, |
| 670 | input_budget, |
| 671 | ) |
| 672 | .await; |
| 673 | }; |
| 674 | request.max_tokens = output_cap; |
| 675 | let tool_request_snapshot = |
| 676 | crate::tool_inspection::ToolInspectionSnapshot::from_prepared_request_with_surface( |
| 677 | &turn.id, |
| 678 | turn.step, |
| 679 | request.tools.as_deref(), |
| 680 | inspection_surface, |
| 681 | ); |
| 682 | turn.last_request_snapshot = Some(tool_request_snapshot.clone()); |
| 683 | turn.stop_diagnostics.route_context_window_tokens = self |
| 684 | .active_route_limits |
| 685 | .and_then(|limits| limits.context_tokens); |
| 686 | |
| 687 | turn.stop_diagnostics.last_prepared_output_limit_tokens = Some(request.max_tokens); |
| 688 | self.session.last_request_tools.clone_from(&request.tools); |
| 689 | |
| 690 | // Stream the response. Keep the request around (cloned into the |
| 691 | // first call) so we can resend it on a transparent retry below |
| 692 | // when the wire dies before any content was streamed (#103). |
| 693 | let stream_request = request; |
| 694 | if turn.step == 0 { |
| 695 | crate::superfast::warn_on_removed_env(); |
| 696 | } |
| 697 | let _ = self |
| 698 | .send_event(Event::ToolRequestSnapshot { |
| 699 | snapshot: tool_request_snapshot, |
| 700 | }) |
| 701 | .await; |
| 702 | if let Some(mut route) = turn.pending_route.take() { |
| 703 | if let Some(billing) = route.billing.as_mut() { |
| 704 | // Freeze the exact provider-live row at CodeWhale's |
| 705 | // pre-permit application-dispatch boundary. This is an |
| 706 | // admission contract, not provider invoice-time evidence; |
| 707 | // a later cancellation/preparation failure has no usage |
| 708 | // and therefore contributes no usage cost. |
| 709 | let dispatched_at = chrono::Utc::now(); |
| 710 | billing.dispatched_at = dispatched_at; |
| 711 | billing.provider_live_pricing = u64::try_from(dispatched_at.timestamp()) |
| 712 | .ok() |
| 713 | .and_then(|dispatched_at_unix| { |
| 714 | crate::client::main_turn_pricing_quote_at( |
| 715 | self.codewhale_client.as_ref(), |
| 716 | route.provider, |
| 717 | &route.provider_identity, |
| 718 | &route.model, |
| 719 | billing.endpoint_fingerprint.as_deref()?, |
| 720 | dispatched_at_unix, |
| 721 | ) |
| 722 | }); |
| 723 | } |
| 724 | let _ = self |
| 725 | .send_event(Event::RouteDispatched { |
| 726 | turn_id: turn.id.clone(), |
| 727 | route, |
| 728 | }) |
| 729 | .await; |
| 730 | } |
| 731 | |
| 732 | PhaseResult::Ready(PreparedModelStep { |
| 733 | request_nudge, |
| 734 | prefix_check, |
| 735 | request: stream_request, |
| 736 | zero_tool_turn, |
| 737 | fleet_report_response, |
| 738 | }) |
| 739 | } |
| 740 | async fn context_budget_overflow( |
| 741 | &mut self, |
| 742 | turn: &mut TurnContext, |
| 743 | progress: &mut TurnLoopProgress, |
| 744 | client: &SharedModelClient, |
| 745 | tools: Option<&[codewhale_models::Tool]>, |
| 746 | estimated_input: usize, |
| 747 | input_budget: usize, |
| 748 | ) -> PhaseResult<PreparedModelStep> { |
| 749 | if let Some(message) = turn.compaction_thrash_message() { |
| 750 | let _ = self |
| 751 | .send_event(Event::error(ErrorEnvelope::context_overflow( |
| 752 | message.clone(), |
| 753 | ))) |
| 754 | .await; |
| 755 | return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(message))); |
| 756 | } |
| 757 | if progress.context_recovery_attempts >= MAX_CONTEXT_RECOVERY_ATTEMPTS { |
| 758 | let message = context_overflow_exhausted_message( |
| 759 | self.config.terminal_chrome_enabled, |
| 760 | turn.stop_diagnostics.emergency_compaction_attempts, |
| 761 | estimated_input, |
| 762 | input_budget, |
| 763 | ); |
| 764 | progress.turn_error = Some(message.clone()); |
| 765 | let _ = self |
| 766 | .send_event(Event::error(ErrorEnvelope::context_overflow(message))) |
| 767 | .await; |
| 768 | return PhaseResult::Return((TurnOutcomeStatus::Failed, progress.turn_error.take())); |
| 769 | } |
| 770 | |
| 771 | if self |
| 772 | .recover_context_overflow(client.as_ref(), tools, "preflight token budget", turn) |
| 773 | .await |
| 774 | { |
| 775 | progress.context_recovery_attempts = |
| 776 | progress.context_recovery_attempts.saturating_add(1); |
| 777 | return PhaseResult::Retry; |
| 778 | } |
| 779 | if self.cancel_token.is_cancelled() { |
| 780 | return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None)); |
| 781 | } |
| 782 | // One failure, one true sentence (experience mark 2): a |
| 783 | // provider that refused the recovery request is the |
| 784 | // cause, and a history with nothing to summarize is a |
| 785 | // window problem, not a failed compaction. |
| 786 | if let Some(message) = self.report_context_recovery_failure(turn).await { |
| 787 | return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(message))); |
| 788 | } |
| 789 | let message = if crate::compaction::has_compactable_history(&self.session.messages) { |
| 790 | "The request still exceeds this model's context budget and automatic recovery did not complete. The conversation is saved; retry or choose a larger context route.".to_string() |
| 791 | } else { |
| 792 | let prefix_tokens = crate::compaction::estimate_request_input_tokens( |
| 793 | &[], |
| 794 | self.session.system_prompt.as_ref(), |
| 795 | tools, |
| 796 | ); |
| 797 | super::context::context_does_not_fit_message( |
| 798 | self.config.terminal_chrome_enabled, |
| 799 | self.api_provider == codewhale_config::ProviderKind::Ollama, |
| 800 | &self.session.model, |
| 801 | estimated_input, |
| 802 | input_budget, |
| 803 | prefix_tokens, |
| 804 | ) |
| 805 | }; |
| 806 | let _ = self |
| 807 | .send_event(Event::error(ErrorEnvelope::context_overflow( |
| 808 | message.clone(), |
| 809 | ))) |
| 810 | .await; |
| 811 | PhaseResult::Return((TurnOutcomeStatus::Failed, Some(message))) |
| 812 | } |
| 813 | |
| 814 | /// The same pure primary request builder and the same dispatch phase, |
| 815 | /// with a whole bounded RLM history and no autonomous recovery producer. |
| 816 | async fn prepare_rlm_model_step( |
| 817 | &mut self, |
| 818 | turn: &mut TurnContext, |
| 819 | client: &SharedModelClient, |
| 820 | inspection_surface: Option<&crate::tool_inspection::ToolSurfaceContext>, |
| 821 | ) -> PhaseResult<PreparedModelStep> { |
| 822 | let state = self.rlm_host.as_ref().expect("RLM host"); |
| 823 | if let Err(error) = state.caller.validate_live() { |
| 824 | return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error.to_string()))); |
| 825 | } |
| 826 | if self.cancel_token.is_cancelled() { |
| 827 | return PhaseResult::Return(( |
| 828 | TurnOutcomeStatus::Interrupted, |
| 829 | Some("RLM evaluation cancelled".into()), |
| 830 | )); |
| 831 | } |
| 832 | if let Some(error) = self.turn_wall_clock_exhausted_error() { |
| 833 | return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error))); |
| 834 | } |
| 835 | if turn.at_max_steps() { |
| 836 | let state = self.rlm_host.as_mut().expect("RLM host"); |
| 837 | state.termination = Some(crate::rlm::turn::RlmTermination::Exhausted); |
| 838 | return PhaseResult::Return(( |
| 839 | TurnOutcomeStatus::Failed, |
| 840 | Some(format!( |
| 841 | "RLM exhausted {} iterations without FINAL", |
| 842 | turn.step_limit() |
| 843 | .expect("exhausted turn has an owner step limit") |
| 844 | )), |
| 845 | )); |
| 846 | } |
| 847 | self.record_current_constitution().await; |
| 848 | self.record_current_extension_prompt_contributions().await; |
| 849 | self.record_current_project_instructions().await; |
| 850 | self.record_current_skills_context().await; |
| 851 | let reasoning_effort = resolve_auto_effort( |
| 852 | self.session.reasoning_effort.as_deref(), |
| 853 | self.api_provider, |
| 854 | &self.api_config.active_route_base_url(), |
| 855 | &self.config.model, |
| 856 | ); |
| 857 | let mut planned_output_tokens = |
| 858 | crate::route_budget::effective_max_output_tokens_for_turn_with_window( |
| 859 | self.api_provider, |
| 860 | &self.session.model, |
| 861 | self.active_route_limits, |
| 862 | self.active_context_window.map(|window| window.tokens), |
| 863 | turn.max_output_tokens, |
| 864 | reasoning_effort.as_deref(), |
| 865 | ); |
| 866 | if turn.max_output_tokens.is_some() { |
| 867 | planned_output_tokens = |
| 868 | planned_output_tokens.min(client.effective_max_output_tokens(&self.session.model)); |
| 869 | } |
| 870 | if let Err(error) = self |
| 871 | .apply_instruction_budget_notices(&[], planned_output_tokens) |
| 872 | .await |
| 873 | { |
| 874 | return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error))); |
| 875 | } |
| 876 | let estimated = turn |
| 877 | .live_input_tokens_for_compaction( |
| 878 | &self.session.messages, |
| 879 | self.session.system_prompt.as_ref(), |
| 880 | self.session.latest_parent_input_tokens, |
| 881 | ) |
| 882 | .unwrap_or(0); |
| 883 | if crate::route_budget::route_context_budget_with_window( |
| 884 | self.api_provider, |
| 885 | &self.session.model, |
| 886 | self.active_route_limits, |
| 887 | self.active_context_window.map(|window| window.tokens), |
| 888 | usize::try_from(estimated).unwrap_or(usize::MAX), |
| 889 | ) |
| 890 | .is_some_and(|budget| { |
| 891 | estimated |
| 892 | > crate::route_budget::route_admission_input_ceiling_with_window( |
| 893 | self.api_provider, |
| 894 | &self.session.model, |
| 895 | self.active_route_limits, |
| 896 | self.active_context_window.map(|window| window.tokens), |
| 897 | ) |
| 898 | .unwrap_or(budget.input_budget_ceiling) |
| 899 | }) { |
| 900 | return PhaseResult::Return((TurnOutcomeStatus::Failed, Some("RLM whole round history exceeds the captured route context budget; history was not truncated".into()))); |
| 901 | } |
| 902 | let mut request = prepare_primary_turn_request(PrimaryTurnRequest { |
| 903 | model: self.session.model.clone(), |
| 904 | messages: self.messages_with_turn_metadata(), |
| 905 | max_tokens: crate::route_budget::effective_max_output_tokens_for_turn_with_window( |
| 906 | self.api_provider, |
| 907 | &self.session.model, |
| 908 | self.active_route_limits, |
| 909 | self.active_context_window.map(|window| window.tokens), |
| 910 | turn.max_output_tokens, |
| 911 | reasoning_effort.as_deref(), |
| 912 | ), |
| 913 | system: self.session.system_prompt.clone(), |
| 914 | tools: None, |
| 915 | tool_choice: None, |
| 916 | reasoning_effort, |
| 917 | }); |
| 918 | let Some(output_cap) = crate::route_budget::request_output_cap_for_input_with_window( |
| 919 | self.api_provider, |
| 920 | &self.session.model, |
| 921 | self.active_route_limits, |
| 922 | self.active_context_window.map(|window| window.tokens), |
| 923 | request.max_tokens, |
| 924 | estimated, |
| 925 | ) else { |
| 926 | return PhaseResult::Return((TurnOutcomeStatus::Failed, Some("RLM whole round history leaves no output room in the captured route context window; history was not truncated".into()))); |
| 927 | }; |
| 928 | request.max_tokens = |
| 929 | output_cap.min(client.effective_max_output_tokens(&self.session.model)); |
| 930 | let snapshot = |
| 931 | crate::tool_inspection::ToolInspectionSnapshot::from_prepared_request_with_surface( |
| 932 | &turn.id, |
| 933 | turn.step, |
| 934 | None, |
| 935 | inspection_surface, |
| 936 | ); |
| 937 | turn.last_request_snapshot = Some(snapshot.clone()); |
| 938 | turn.stop_diagnostics.last_prepared_output_limit_tokens = Some(request.max_tokens); |
| 939 | self.session.last_request_tools.clone_from(&request.tools); |
| 940 | let _ = self |
| 941 | .send_event(Event::ToolRequestSnapshot { snapshot }) |
| 942 | .await; |
| 943 | PhaseResult::Ready(PreparedModelStep { |
| 944 | request_nudge: None, |
| 945 | prefix_check: json!({"outcome": "unavailable", "surface": "rlm"}), |
| 946 | request, |
| 947 | zero_tool_turn: true, |
| 948 | fleet_report_response: false, |
| 949 | }) |
| 950 | } |
| 951 | } |
| 952 |