| 1 | //! One private phase of the existing Engine turn loop. |
| 2 | |
| 3 | use super::*; |
| 4 | |
| 5 | impl Engine { |
| 6 | pub(super) async fn run_tool_batch_phase( |
| 7 | &mut self, |
| 8 | turn: &mut TurnContext, |
| 9 | tool_policy: &mut ToolSurfacePolicy, |
| 10 | progress: &mut TurnLoopProgress, |
| 11 | client: &SharedModelClient, |
| 12 | response: AcceptedModelStep, |
| 13 | ) -> PhaseResult<()> { |
| 14 | let _timing = codewhale_runtime::logging::PhaseTimer::start("tool_batch"); |
| 15 | let tool_registry = Some(&tool_policy.registry); |
| 16 | let AcceptedModelStep { |
| 17 | current_text_visible, |
| 18 | mut tool_uses, |
| 19 | mut pending_steers, |
| 20 | mut output_limit_truncated, |
| 21 | fleet_report_response, |
| 22 | fleet_no_progress_report, |
| 23 | .. |
| 24 | } = response; |
| 25 | // A user can change Ask / Auto-Review / Full Access while the |
| 26 | // provider is streaming. Apply the newest typed authority before |
| 27 | // planning this tool batch; already-running tools are never |
| 28 | // retroactively reclassified. |
| 29 | let authority_changed_before_tools = self.apply_pending_runtime_authority().await; |
| 30 | if authority_changed_before_tools { |
| 31 | // A response requested as report-only never acquires execution |
| 32 | // authority after it streamed. Reset only after pairing its |
| 33 | // suppressed calls; the next response can use the new posture. |
| 34 | if !fleet_report_response && let Some(guard) = progress.fleet_denial_guard.as_mut() { |
| 35 | guard.reset(); |
| 36 | turn.stop_diagnostics |
| 37 | .permission_denial_rounds_without_progress = 0; |
| 38 | } |
| 39 | progress.mode = self.current_mode; |
| 40 | } |
| 41 | |
| 42 | // Execute tools |
| 43 | if self.shared_paused.lock().is_ok_and(|paused| *paused) { |
| 44 | let _ = self.send_event(Event::status("Request was Paused")).await; |
| 45 | self.add_interrupted_assistant_text(¤t_text_visible) |
| 46 | .await; |
| 47 | return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None)); |
| 48 | } |
| 49 | |
| 50 | let tool_exec_lock = self.tool_exec_lock.clone(); |
| 51 | let mcp_pool = if !fleet_report_response |
| 52 | && self.config.features.enabled(Feature::Mcp) |
| 53 | && tool_uses.iter().any(|tool| { |
| 54 | McpPool::is_mcp_tool(&tool.name) |
| 55 | || tool.name == EXECUTE_TOOLS_TOOL_NAME |
| 56 | || tool_policy |
| 57 | .registry |
| 58 | .get(&tool.name) |
| 59 | .is_some_and(|spec| spec.extension_caller().is_some()) |
| 60 | }) { |
| 61 | match self.ensure_mcp_pool().await { |
| 62 | Ok(pool) => Some(pool), |
| 63 | Err(err) => { |
| 64 | let _ = self.send_event(Event::status(err.to_string())).await; |
| 65 | None |
| 66 | } |
| 67 | } |
| 68 | } else { |
| 69 | None |
| 70 | }; |
| 71 | |
| 72 | // Tool discovery may be the first action after a model request |
| 73 | // that overlapped MCP startup. Search the ready catalog now. |
| 74 | self.refresh_boot_mcp_catalog( |
| 75 | tool_policy, |
| 76 | &mut progress.tool_catalog, |
| 77 | &mut progress.active_tool_names, |
| 78 | ) |
| 79 | .await; |
| 80 | // Per-tool timeouts own a running tool, but the batch also covers the |
| 81 | // engine's own post-tool bookkeeping, which no per-tool timeout sees. |
| 82 | // The ceiling keeps that window owned by the heartbeat. |
| 83 | self.turn_heartbeat.enter( |
| 84 | super::turn_heartbeat::TurnPhase::Tools, |
| 85 | Some( |
| 86 | tool_uses |
| 87 | .iter() |
| 88 | .map(|tool| tool.name.as_str()) |
| 89 | .collect::<Vec<_>>() |
| 90 | .join(", "), |
| 91 | ), |
| 92 | Some(super::turn_heartbeat::TOOLS_PHASE_BOUND), |
| 93 | ); |
| 94 | let PlannedToolCalls { |
| 95 | plans, |
| 96 | hook_contexts, |
| 97 | batch_sandbox_policy, |
| 98 | } = self |
| 99 | .plan_tool_calls( |
| 100 | client.as_ref(), |
| 101 | turn, |
| 102 | tool_policy, |
| 103 | &mut tool_uses, |
| 104 | &progress.tool_catalog, |
| 105 | tool_registry, |
| 106 | &mut progress.active_tool_names, |
| 107 | &mut progress.tool_call_budget, |
| 108 | progress.mode, |
| 109 | progress.fleet_denial_guard.as_ref(), |
| 110 | ToolCallSource::Model, |
| 111 | None, |
| 112 | ) |
| 113 | .await; |
| 114 | |
| 115 | let origin_turn_id = turn.id.clone(); |
| 116 | let mut nested_gate_env = NestedGateEnv { |
| 117 | client: client.as_ref(), |
| 118 | turn: &mut *turn, |
| 119 | tool_policy, |
| 120 | tool_call_budget: &mut progress.tool_call_budget, |
| 121 | fleet_denial_guard: progress.fleet_denial_guard.as_ref(), |
| 122 | authority_changed: false, |
| 123 | }; |
| 124 | let (outcomes, authority_changed_during_tools) = self |
| 125 | .execute_planned_tools( |
| 126 | plans, |
| 127 | &origin_turn_id, |
| 128 | ¤t_text_visible, |
| 129 | &mut progress.tool_catalog, |
| 130 | &mut progress.active_tool_names, |
| 131 | tool_registry, |
| 132 | tool_exec_lock, |
| 133 | mcp_pool, |
| 134 | &batch_sandbox_policy, |
| 135 | &mut progress.mode, |
| 136 | &mut nested_gate_env, |
| 137 | ) |
| 138 | .await; |
| 139 | |
| 140 | let _post_timing = codewhale_runtime::logging::PhaseTimer::start("tool_postprocessing"); |
| 141 | let authority_changed = authority_changed_before_tools || authority_changed_during_tools; |
| 142 | self.turn_heartbeat.enter( |
| 143 | super::turn_heartbeat::TurnPhase::Preparing, |
| 144 | None, |
| 145 | Some(super::turn_heartbeat::PREPARING_PHASE_BOUND), |
| 146 | ); |
| 147 | let denial_action = self |
| 148 | .process_tool_results( |
| 149 | client.as_ref(), |
| 150 | tool_policy, |
| 151 | outcomes, |
| 152 | turn, |
| 153 | &mut progress.tool_catalog, |
| 154 | &mut progress.active_tool_names, |
| 155 | &hook_contexts, |
| 156 | if authority_changed || fleet_report_response { |
| 157 | None |
| 158 | } else { |
| 159 | progress.fleet_denial_guard.as_mut() |
| 160 | }, |
| 161 | progress.mode, |
| 162 | ) |
| 163 | .await; |
| 164 | |
| 165 | let accepted_steer_after_tools = !pending_steers.is_empty() |
| 166 | || (!self.cancel_token.is_cancelled() && self.has_pending_turn_steer()); |
| 167 | if !pending_steers.is_empty() { |
| 168 | for pending in pending_steers.drain(..) { |
| 169 | let (raw_steer, person_text) = self.commit_pending_steer_with_intent(pending); |
| 170 | let steer = raw_steer.trim().to_string(); |
| 171 | self.session |
| 172 | .working_set |
| 173 | .observe_user_message(&steer, &self.session.workspace); |
| 174 | self.add_session_message(self.user_text_message_with_turn_metadata(steer)) |
| 175 | .await; |
| 176 | if let Some(person_text) = person_text { |
| 177 | let index = self.session.messages.len().saturating_sub(1); |
| 178 | self.session.record_person_message(person_text, Some(index)); |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | if let Some(stop) = self.auto_review_stop_reason() { |
| 184 | let _ = self.send_event(Event::status(stop.clone())).await; |
| 185 | return PhaseResult::Return((TurnOutcomeStatus::Interrupted, Some(stop))); |
| 186 | } |
| 187 | |
| 188 | if authority_changed || accepted_steer_after_tools { |
| 189 | if let Some(guard) = progress.fleet_denial_guard.as_mut() { |
| 190 | guard.reset(); |
| 191 | turn.stop_diagnostics |
| 192 | .permission_denial_rounds_without_progress = 0; |
| 193 | } |
| 194 | } else if fleet_no_progress_report { |
| 195 | // Exactly one accepted report response, including empty, |
| 196 | // reasoning-only, truncated or tool-producing responses. |
| 197 | if self.cancel_token.is_cancelled() { |
| 198 | return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None)); |
| 199 | } |
| 200 | turn.stop_diagnostics.last_response_tool_calls_suppressed = Some(tool_uses.len()); |
| 201 | let error = if turn.budget_exhausted_final_report { |
| 202 | // One response can serve both report requests; the |
| 203 | // explicit budget retains its existing stop provenance. |
| 204 | format!( |
| 205 | "Maximum model steps reached before completion (limit: {}, {})", |
| 206 | turn.max_steps, |
| 207 | turn.budget_source.key_label() |
| 208 | ) |
| 209 | } else { |
| 210 | turn.stop_diagnostics.reason = Some(TurnStopReason::NoProgress); |
| 211 | FLEET_NO_PROGRESS_STOP.to_string() |
| 212 | }; |
| 213 | if turn.budget_exhausted_final_report { |
| 214 | self.post_turn_budget_stop(&error).await; |
| 215 | } else { |
| 216 | let _ = self.send_event(Event::status(error.clone())).await; |
| 217 | } |
| 218 | return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error))); |
| 219 | } else { |
| 220 | let notice = match denial_action { |
| 221 | FleetDenialAction::Continue => None, |
| 222 | FleetDenialAction::SwitchStrategy => { |
| 223 | turn.stop_diagnostics.permission_strategy_switches = turn |
| 224 | .stop_diagnostics |
| 225 | .permission_strategy_switches |
| 226 | .saturating_add(1); |
| 227 | Some(FLEET_STRATEGY_SWITCH_NOTICE) |
| 228 | } |
| 229 | FleetDenialAction::FinalReport => { |
| 230 | turn.stop_diagnostics.final_report_requested = true; |
| 231 | Some(FLEET_FINAL_REPORT_NOTICE) |
| 232 | } |
| 233 | }; |
| 234 | if let Some(notice) = notice { |
| 235 | // Dynamic guard facts are append-only runtime history; |
| 236 | // BASE_PROMPT and the session's pinned prefix stay intact. |
| 237 | self.add_session_message(self.runtime_text_message_with_turn_metadata( |
| 238 | notice.to_string(), |
| 239 | UserInputProvenance::Runtime, |
| 240 | )) |
| 241 | .await; |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | // Surface an output-limit truncation after the tool result so the |
| 246 | // transcript stays well-formed (a `tool_result` must follow the |
| 247 | // assistant `tool_use` directly) and the model can act on it. |
| 248 | if let Some(reason) = output_limit_truncated.take() { |
| 249 | self.add_session_message( |
| 250 | self.runtime_text_message_with_turn_metadata( |
| 251 | format!( |
| 252 | "[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." |
| 253 | ), |
| 254 | UserInputProvenance::Runtime, |
| 255 | ), |
| 256 | ) |
| 257 | .await; |
| 258 | } |
| 259 | |
| 260 | self.deliver_shell_completions("").await; |
| 261 | |
| 262 | // A successful tool step is productive progress, not a runaway |
| 263 | // synthetic resume. Declared per-task tool budgets and max_steps |
| 264 | // remain the explicit limits for tool-driven work. |
| 265 | let _ = self |
| 266 | .send_event(Event::status("Continuing — tool results".to_string())) |
| 267 | .await; |
| 268 | turn.next_step(); |
| 269 | |
| 270 | PhaseResult::Ready(()) |
| 271 | } |
| 272 | } |
| 273 |