| 1 | //! One private phase of the existing Engine turn loop. |
| 2 | |
| 3 | use super::*; |
| 4 | use crate::rlm::bridge::wait_for_deadline; |
| 5 | |
| 6 | impl Engine { |
| 7 | async fn run_rlm_code_round( |
| 8 | &mut self, |
| 9 | turn: &mut TurnContext, |
| 10 | tool_policy: &ToolSurfacePolicy, |
| 11 | progress: &mut TurnLoopProgress, |
| 12 | code: String, |
| 13 | ) -> PhaseResult<()> { |
| 14 | let Some(state) = self.rlm_host.as_ref() else { |
| 15 | return PhaseResult::Ready(()); |
| 16 | }; |
| 17 | let mut skip_reason = |
| 18 | if code_execution_offered(progress.mode, &progress.tool_catalog, tool_policy) { |
| 19 | self.rlm_round_refusal(&code, state.gate.as_ref()).await |
| 20 | } else { |
| 21 | Some("code execution is not available on this turn".to_string()) |
| 22 | }; |
| 23 | progress.mode = self.current_mode; |
| 24 | if skip_reason.is_none() && self.turn_wall_clock.exhausted() { |
| 25 | let reason = "parent turn deadline exhausted before REPL execution".to_string(); |
| 26 | skip_reason = Some(reason.clone()); |
| 27 | progress.turn_error = Some(reason); |
| 28 | } |
| 29 | if let Some(reason) = skip_reason { |
| 30 | return PhaseResult::Return(( |
| 31 | TurnOutcomeStatus::Failed, |
| 32 | Some(format!("RLM code was not run: {reason}")), |
| 33 | )); |
| 34 | } |
| 35 | let repl_blocks = [codewhale_repl::ReplBlock { |
| 36 | code, |
| 37 | start_offset: 0, |
| 38 | end_offset: 0, |
| 39 | }]; |
| 40 | { |
| 41 | let repl_deadline = self.nested_work_deadline(); |
| 42 | let Some(sandbox_context) = self |
| 43 | .rlm_host |
| 44 | .as_ref() |
| 45 | .map(|state| state.caller.context.clone()) |
| 46 | else { |
| 47 | return PhaseResult::Ready(()); |
| 48 | }; |
| 49 | let kernel_policy = sandbox_context.elevated_sandbox_policy.clone(); |
| 50 | if self.repl_kernel_policy != kernel_policy { |
| 51 | self.repl_kernel = None; |
| 52 | } |
| 53 | // A kernel left broken by a dropped turn refuses every round; kill it. |
| 54 | drop(self.repl_kernel.take_if(|kernel| kernel.is_broken())); |
| 55 | if self.repl_kernel.is_none() { |
| 56 | let startup = tokio::select! { |
| 57 | biased; |
| 58 | () = self.cancel_token.cancelled() => { |
| 59 | Err("REPL startup cancelled".into()) |
| 60 | } |
| 61 | () = wait_for_deadline(repl_deadline) => Err("parent turn deadline reached during REPL startup".into()), |
| 62 | result = crate::rlm::kernel::spawn_kernel( |
| 63 | &sandbox_context, |
| 64 | None, |
| 65 | Some(codewhale_repl::INLINE_ROUND_TIMEOUT), |
| 66 | ) => result, |
| 67 | }; |
| 68 | self.repl_kernel = match startup { |
| 69 | Ok(runtime) => { |
| 70 | self.repl_kernel_policy = kernel_policy; |
| 71 | Some(runtime) |
| 72 | } |
| 73 | Err(e) => { |
| 74 | let _ = self |
| 75 | .send_event(Event::status(format!("REPL init failed: {e}"))) |
| 76 | .await; |
| 77 | progress.turn_error = Some(format!("REPL init failed: {e}")); |
| 78 | return PhaseResult::Break; |
| 79 | } |
| 80 | }; |
| 81 | } |
| 82 | |
| 83 | let captured = self |
| 84 | .rlm_host |
| 85 | .as_ref() |
| 86 | .map(|state| Arc::clone(&state.caller)); |
| 87 | let bridge = captured.as_deref().map(|caller| { |
| 88 | let depth = self.rlm_host.as_ref().map_or(0, |state| match state.mode { |
| 89 | crate::core::engine::rlm_host::RlmMode::Completion => 0, |
| 90 | crate::core::engine::rlm_host::RlmMode::Recursive { depth_remaining } => { |
| 91 | depth_remaining |
| 92 | } |
| 93 | }); |
| 94 | let usage = self |
| 95 | .rlm_host |
| 96 | .as_ref() |
| 97 | .map_or_else(crate::rlm::bridge::RlmUsageAccumulator::new, |state| { |
| 98 | state.usage.clone() |
| 99 | }); |
| 100 | crate::rlm::RlmBridge::with_usage_accumulator(caller, depth, usage) |
| 101 | .with_events(self.tx_event.clone()) |
| 102 | .with_deadline(repl_deadline) |
| 103 | .with_gate(self.rlm_host.as_ref().and_then(|state| state.gate.clone())) |
| 104 | }); |
| 105 | let mut final_result: Option<String> = None; |
| 106 | let mut kernel_failed = false; |
| 107 | for (i, block) in repl_blocks.iter().enumerate() { |
| 108 | let round_num = i + 1; |
| 109 | let _ = self |
| 110 | .send_event(Event::status(format!( |
| 111 | "REPL round {round_num}: executing..." |
| 112 | ))) |
| 113 | .await; |
| 114 | |
| 115 | // Dropping the cancelled round also stops its owned |
| 116 | // RPC/forwarder futures. The ledger below still |
| 117 | // accounts completed and pending provider requests; |
| 118 | // the kernel is discarded after any round failure. |
| 119 | let round_result = tokio::select! { |
| 120 | biased; |
| 121 | () = self.cancel_token.cancelled() => { |
| 122 | Err("REPL execution cancelled".into()) |
| 123 | } |
| 124 | () = wait_for_deadline(repl_deadline) => Err("REPL execution reached the parent turn deadline".into()), |
| 125 | result = self.repl_kernel |
| 126 | .as_mut() |
| 127 | .expect("REPL kernel stays alive during a round") |
| 128 | .run(&block.code, bridge.as_ref()) => result, |
| 129 | }; |
| 130 | |
| 131 | match round_result { |
| 132 | Ok(round) => { |
| 133 | if let Some(state) = self.rlm_host.as_mut() { |
| 134 | state.total_rpcs = state.total_rpcs.saturating_add(round.rpc_count); |
| 135 | let round_output = if round.has_error { |
| 136 | format!("stdout:\n{}\nstderr:\n{}", round.stdout, round.stderr) |
| 137 | } else { |
| 138 | round.stdout.clone() |
| 139 | }; |
| 140 | let stdout = crate::rlm::turn::truncate_text( |
| 141 | &round_output, |
| 142 | crate::rlm::turn::STDOUT_METADATA_PREVIEW_LEN, |
| 143 | ); |
| 144 | state.trace.push(crate::rlm::turn::RlmRoundTrace { |
| 145 | round: state.model_rounds, |
| 146 | code_summary: crate::rlm::turn::summarize_code(&block.code), |
| 147 | stdout_preview: stdout.clone(), |
| 148 | had_error: round.has_error, |
| 149 | rpc_count: round.rpc_count, |
| 150 | elapsed_ms: u64::try_from(round.elapsed.as_millis()) |
| 151 | .unwrap_or(u64::MAX), |
| 152 | }); |
| 153 | let feedback = crate::rlm::turn::metadata_text( |
| 154 | &state.prompt, |
| 155 | state.model_rounds, |
| 156 | Some(&block.code), |
| 157 | Some(&stdout), |
| 158 | ); |
| 159 | if round.final_value.is_none() { |
| 160 | self.add_session_message( |
| 161 | self.runtime_text_message_with_turn_metadata( |
| 162 | feedback, |
| 163 | UserInputProvenance::Runtime, |
| 164 | ), |
| 165 | ) |
| 166 | .await; |
| 167 | } |
| 168 | } |
| 169 | if let Some(val) = &round.final_value { |
| 170 | let _ = self |
| 171 | .send_event(Event::status(format!( |
| 172 | "REPL round {round_num}: FINAL result obtained" |
| 173 | ))) |
| 174 | .await; |
| 175 | final_result = Some(val.clone()); |
| 176 | break; |
| 177 | } |
| 178 | |
| 179 | let is_empty_round = !round.has_error |
| 180 | && round.stdout.trim().is_empty() |
| 181 | && round.stderr.trim().is_empty() |
| 182 | && round.rpc_count == 0; |
| 183 | if is_empty_round { |
| 184 | progress.consecutive_empty_repl_rounds = |
| 185 | progress.consecutive_empty_repl_rounds.saturating_add(1); |
| 186 | let feedback = format!( |
| 187 | "[Your emitted ```repl block (round {round_num}) produced no observable output. Inspect the state or print a result when needed, and finish when the task is complete.]\n[0 child query RPC(s)]" |
| 188 | ); |
| 189 | self.add_session_message(self.runtime_text_message_with_turn_metadata( |
| 190 | feedback, |
| 191 | UserInputProvenance::Runtime, |
| 192 | )) |
| 193 | .await; |
| 194 | } else { |
| 195 | progress.consecutive_empty_repl_rounds = 0; |
| 196 | } |
| 197 | } |
| 198 | Err(e) => { |
| 199 | let _ = self |
| 200 | .send_event(Event::status(format!( |
| 201 | "REPL round {round_num} failed: {e}" |
| 202 | ))) |
| 203 | .await; |
| 204 | self.add_session_message(self.runtime_text_message_with_turn_metadata( |
| 205 | format!("[REPL round {round_num} execution failed]\n{e}"), |
| 206 | UserInputProvenance::Runtime, |
| 207 | )) |
| 208 | .await; |
| 209 | progress.turn_error = Some( |
| 210 | if repl_deadline |
| 211 | .is_some_and(|deadline| tokio::time::Instant::now() >= deadline) |
| 212 | { |
| 213 | format!("RLM original wall-clock deadline exhausted: {e}") |
| 214 | } else { |
| 215 | e.clone() |
| 216 | }, |
| 217 | ); |
| 218 | // A transport error or timeout means Python |
| 219 | // may still be executing unknown code. Do not |
| 220 | // send another block into that process or |
| 221 | // pretend its state is trustworthy. |
| 222 | kernel_failed = true; |
| 223 | break; |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | if kernel_failed { |
| 229 | self.repl_kernel = None; |
| 230 | return PhaseResult::Return(( |
| 231 | TurnOutcomeStatus::Failed, |
| 232 | progress |
| 233 | .turn_error |
| 234 | .take() |
| 235 | .or_else(|| Some("RLM Python execution failed".into())), |
| 236 | )); |
| 237 | } |
| 238 | |
| 239 | if let Some(final_val) = final_result { |
| 240 | if let Some(state) = self.rlm_host.as_mut() { |
| 241 | state.final_answer = Some(final_val.clone()); |
| 242 | state.termination = Some(crate::rlm::turn::RlmTermination::Final); |
| 243 | } |
| 244 | // Replace the assistant's text with the FINAL answer. |
| 245 | if let Some(last_msg) = self.session.messages.last_mut() |
| 246 | && last_msg.role == "assistant" |
| 247 | { |
| 248 | for block in &mut last_msg.content { |
| 249 | if let ContentBlock::Text { text, .. } = block { |
| 250 | *text = final_val; |
| 251 | break; |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | self.emit_session_updated().await; |
| 256 | return PhaseResult::Break; |
| 257 | } |
| 258 | |
| 259 | // No FINAL — let the model iterate with the feedback. |
| 260 | let _ = self.send_event(Event::status(format!( |
| 261 | "Continuing — REPL round feedback (consecutive_empty={consecutive_empty_repl_rounds})", consecutive_empty_repl_rounds = progress.consecutive_empty_repl_rounds |
| 262 | ))) |
| 263 | .await; |
| 264 | turn.next_step(); |
| 265 | PhaseResult::Retry |
| 266 | } |
| 267 | } |
| 268 | pub(super) async fn continue_rlm_model_step( |
| 269 | &mut self, |
| 270 | turn: &mut TurnContext, |
| 271 | tool_policy: &ToolSurfacePolicy, |
| 272 | progress: &mut TurnLoopProgress, |
| 273 | response: AcceptedModelStep, |
| 274 | ) -> PhaseResult<AcceptedModelStep> { |
| 275 | let text = response.current_text_visible; |
| 276 | let state = self.rlm_host.as_mut().expect("RLM host"); |
| 277 | state.last_response = text.clone(); |
| 278 | if state.mode == crate::core::engine::rlm_host::RlmMode::Completion { |
| 279 | if text.trim().is_empty() { |
| 280 | return PhaseResult::Return(( |
| 281 | TurnOutcomeStatus::Failed, |
| 282 | Some("empty LLM response".into()), |
| 283 | )); |
| 284 | } |
| 285 | state.final_answer = Some(text); |
| 286 | state.termination = Some(crate::rlm::turn::RlmTermination::Final); |
| 287 | return PhaseResult::Break; |
| 288 | } |
| 289 | let text_final = crate::rlm::turn::parse_text_final(&text); |
| 290 | if let Some(answer) = text_final.as_ref() { |
| 291 | state.final_answer = Some(answer.clone()); |
| 292 | state.termination = Some(crate::rlm::turn::RlmTermination::Final); |
| 293 | return PhaseResult::Break; |
| 294 | } |
| 295 | let Some(code) = crate::rlm::turn::extract_repl_code(&text) else { |
| 296 | state.consecutive_no_code = state.consecutive_no_code.saturating_add(1); |
| 297 | let reminder = "Continue the task with Python inside a ```repl … ``` fence when computation is needed. Inspect `_context` through bounded helpers when the answer depends on it. Return FINAL(value) or call finalize(value) when the task is complete."; |
| 298 | self.add_session_message(self.runtime_text_message_with_turn_metadata( |
| 299 | reminder.to_string(), |
| 300 | UserInputProvenance::Runtime, |
| 301 | )) |
| 302 | .await; |
| 303 | turn.next_step(); |
| 304 | return PhaseResult::Retry; |
| 305 | }; |
| 306 | state.consecutive_no_code = 0; |
| 307 | match self |
| 308 | .run_rlm_code_round(turn, tool_policy, progress, code) |
| 309 | .await |
| 310 | { |
| 311 | PhaseResult::Ready(()) => PhaseResult::Return(( |
| 312 | TurnOutcomeStatus::Failed, |
| 313 | Some("RLM code was not available on the captured surface".into()), |
| 314 | )), |
| 315 | PhaseResult::Retry => PhaseResult::Retry, |
| 316 | PhaseResult::Break => PhaseResult::Break, |
| 317 | PhaseResult::Return(outcome) => PhaseResult::Return(outcome), |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | async fn rlm_round_refusal( |
| 322 | &self, |
| 323 | code: &str, |
| 324 | gate: Option<&crate::tools::codemode::NestedCallGate>, |
| 325 | ) -> Option<String> { |
| 326 | use crate::tools::codemode::NestedCallVerdict; |
| 327 | let name = tool_catalog::CODE_EXECUTION_TOOL_NAME; |
| 328 | let Some(gate) = gate else { |
| 329 | return Some("no permission gate is serving this RLM turn".into()); |
| 330 | }; |
| 331 | match gate |
| 332 | .ask(name.to_string(), serde_json::json!({"code":code})) |
| 333 | .await |
| 334 | { |
| 335 | NestedCallVerdict::Run { |
| 336 | name: admitted, |
| 337 | input, |
| 338 | .. |
| 339 | } if admitted == name |
| 340 | && input.get("code").and_then(serde_json::Value::as_str) == Some(code) => |
| 341 | { |
| 342 | None |
| 343 | } |
| 344 | NestedCallVerdict::Refused { error, .. } => Some(error.to_string()), |
| 345 | _ => Some("the admitted call was not this code".into()), |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 |