返回 CodeWhale
runtime.rs
根目录 / crates / repl / src / runtime.rs
1 //! Long-lived Python REPL runtime.
2 //!
3 //! One Python subprocess lives for the duration of an RLM turn (or an
4 //! inline `repl` block sequence in the agent loop). Code blocks are sent
5 //! over stdin framed by `__RLM_RUN__`/`__RLM_END__` sentinels; the bootstrap
6 //! `exec()`s them into the same global namespace so variables, imports,
7 //! and even open file handles persist naturally across rounds.
8 //!
9 //! Sub-LLM helpers (`sub_query`, `sub_query_batch`, `sub_rlm`, plus legacy
10 //! `llm_query`, `llm_query_batched`, `rlm_query`, `rlm_query_batched`) are
11 //! wired through a stdin/stdout RPC protocol:
12 //! Python emits `__RLM_REQ_<sid>__::{json}` on stdout, Rust dispatches the
13 //! request and writes `__RLM_RESP_<sid>__::{json}` back on stdin. No HTTP
14 //! sidecar, no temp ports — the same pipes carry both control and data.
15 //!
16 //! The session id (`<sid>`) is a UUID generated per spawn, so user output
17 //! that happens to contain "REQ" or "FINAL" can't be confused with control
18 //! messages.
19
20 use std::process::Stdio;
21 use std::sync::{Arc, Mutex as StdMutex};
22 use std::time::{Duration, Instant};
23
24 use serde::{Deserialize, Serialize};
25 use serde_json::Value;
26 use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
27 use tokio::process::{Child, ChildStdin, ChildStdout};
28 use uuid::Uuid;
29
30 // ---------------------------------------------------------------------------
31 // Public types
32 // ---------------------------------------------------------------------------
33
34 /// Result of executing one code block.
35 #[derive(Debug, Clone)]
36 pub struct ReplRound {
37 /// Stdout shown to the model as metadata next round.
38 pub stdout: String,
39 /// Full stdout (with sentinels stripped, but otherwise raw).
40 pub full_stdout: String,
41 /// Stderr from this round (if any).
42 pub stderr: String,
43 /// `True` if the user code raised an unhandled Python exception.
44 pub has_error: bool,
45 /// Captured `finalize(value, confidence=...)` payload, if any.
46 pub final_value: Option<String>,
47 /// Captured final value before string fallback. Structured `finalize`
48 /// payloads use this so `handle_read` can expose JSON instead of a Python
49 /// repr string.
50 pub final_json: Option<Value>,
51 /// Optional confidence supplied to `finalize(...)`.
52 pub final_confidence: Option<Value>,
53 /// Number of `sub_query`/`sub_rlm` RPCs the round issued.
54 pub rpc_count: u32,
55 /// Wall-clock duration of the round.
56 pub elapsed: Duration,
57 }
58
59 /// One RPC request emitted by Python during a round.
60 #[derive(Debug, Clone, Serialize, Deserialize)]
61 #[serde(tag = "type", rename_all = "snake_case")]
62 pub enum RpcRequest {
63 /// `llm_query(prompt, model=None, max_tokens=None, system=None)`
64 Llm {
65 prompt: String,
66 #[serde(default)]
67 model: Option<String>,
68 #[serde(default)]
69 max_tokens: Option<u32>,
70 #[serde(default)]
71 system: Option<String>,
72 },
73 /// `llm_query_batched(prompts, model=None, dependency_mode="independent")`
74 LlmBatch {
75 prompts: Vec<String>,
76 #[serde(default)]
77 model: Option<String>,
78 #[serde(default)]
79 dependency_mode: Option<String>,
80 #[serde(default)]
81 safety_note: Option<String>,
82 },
83 /// `rlm_query(prompt, model=None)` — recursive sub-RLM (paper's `sub_RLM`).
84 Rlm {
85 prompt: String,
86 #[serde(default)]
87 model: Option<String>,
88 },
89 /// `rlm_query_batched(prompts, model=None, dependency_mode="independent")`
90 RlmBatch {
91 prompts: Vec<String>,
92 #[serde(default)]
93 model: Option<String>,
94 #[serde(default)]
95 dependency_mode: Option<String>,
96 #[serde(default)]
97 safety_note: Option<String>,
98 },
99 }
100
101 /// Response for one RPC request.
102 #[derive(Debug, Clone, Serialize, Deserialize)]
103 #[serde(untagged)]
104 pub enum RpcResponse {
105 /// Single-text reply (Llm / Rlm).
106 Single(SingleResp),
107 /// Batch reply (LlmBatch / RlmBatch).
108 Batch(BatchResp),
109 }
110
111 #[derive(Debug, Clone, Serialize, Deserialize)]
112 pub struct SingleResp {
113 #[serde(default)]
114 pub text: String,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub error: Option<String>,
117 }
118
119 #[derive(Debug, Clone, Serialize, Deserialize)]
120 pub struct BatchResp {
121 pub results: Vec<SingleResp>,
122 }
123
124 /// Trait-object handle for dispatching Python RPCs back into Rust.
125 ///
126 /// Each RLM turn supplies one. Implementations forward to the LLM client
127 /// (and recursively through the same captured Engine for `Rlm` / `RlmBatch`).
128 pub trait RpcDispatcher: Send + Sync {
129 fn dispatch<'a>(
130 &'a self,
131 req: RpcRequest,
132 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = RpcResponse> + Send + 'a>>;
133 }
134
135 // ---------------------------------------------------------------------------
136 // Constants
137 // ---------------------------------------------------------------------------
138
139 const DEFAULT_STDOUT_LIMIT: usize = 8_192;
140 const MAX_STDERR_CAPTURE_BYTES: usize = 64 * 1024;
141 /// Longest single stdout line (protocol or plain output) held in memory. An
142 /// RPC request is one line, so this also bounds what a request can make Rust
143 /// deserialize before the bridge's own caps apply; an over-long request is
144 /// truncated, fails to parse, and is answered with an error.
145 const MAX_STDOUT_LINE_BYTES: usize = 32 * 1024 * 1024;
146 /// Most stdout one round retains (`full_stdout`); the rest is counted and
147 /// reported, never buffered.
148 const MAX_ROUND_STDOUT_BYTES: usize = 32 * 1024 * 1024;
149 const ROUND_TIMEOUT: Duration = Duration::from_secs(180);
150 const CONTEXT_LOAD_TIMEOUT: Duration = Duration::from_secs(60);
151 #[cfg(not(windows))]
152 const SPAWN_READY_TIMEOUT: Duration = Duration::from_secs(10);
153 #[cfg(windows)]
154 const SPAWN_READY_TIMEOUT: Duration = Duration::from_secs(30);
155
156 // ---------------------------------------------------------------------------
157 // PythonRuntime
158 // ---------------------------------------------------------------------------
159
160 #[derive(Debug, Default)]
161 struct StderrCapture {
162 bytes: Vec<u8>,
163 omitted: usize,
164 }
165
166 /// Long-lived Python REPL.
167 pub struct PythonRuntime {
168 tree: Option<codewhale_runtime::process_tree::ProcessTree>,
169 child: Child,
170 stdin: ChildStdin,
171 stdout: BufReader<ChildStdout>,
172 stderr_capture: Arc<StdMutex<StderrCapture>>,
173 stderr_task: tokio::task::JoinHandle<()>,
174 /// Per-spawn session id used in protocol sentinels.
175 session_id: String,
176 stdout_limit: usize,
177 round_count: u64,
178 started: Instant,
179 round_timeout: Option<Duration>,
180 /// Set while a round has not yet read its own DONE sentinel, and kept
181 /// when a round ends without it (timeout, I/O failure, or a caller that
182 /// dropped the round mid-flight). The protocol stream is then out of step
183 /// — the interrupted round may still print — so a failed round kills the
184 /// interpreter and every later round refuses instead of reading another
185 /// round's output as its own.
186 broken: Option<String>,
187 }
188
189 impl std::fmt::Debug for PythonRuntime {
190 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
191 f.debug_struct("PythonRuntime")
192 .field("child", &self.child)
193 .field("session_id", &self.session_id)
194 .field("round_count", &self.round_count)
195 .field("round_timeout", &self.round_timeout)
196 .field("broken", &self.broken)
197 .finish_non_exhaustive()
198 }
199 }
200
201 pub const AGENT_PROJECT_ENV: &str = "CODEWHALE_AGENT_PROJECT";
202
203 pub const INLINE_ROUND_TIMEOUT: Duration = ROUND_TIMEOUT;
204
205 impl PythonRuntime {
206 pub async fn spawn<F>(
207 context: Option<&str>,
208 round_timeout: Option<Duration>,
209 command: F,
210 ) -> Result<Self, String>
211 where
212 F: FnOnce(Vec<String>) -> Result<tokio::process::Command, String>,
213 {
214 let session_id = Uuid::new_v4().simple().to_string();
215 let bootstrap = render_bootstrap(&session_id);
216
217 let mut cmd = command(vec!["-u".to_string(), "-c".to_string(), bootstrap])?;
218 cmd.stdin(Stdio::piped())
219 .stdout(Stdio::piped())
220 .stderr(Stdio::piped())
221 .kill_on_drop(true);
222 #[cfg(unix)]
223 cmd.process_group(0);
224
225 let mut child = cmd
226 .spawn()
227 .map_err(|e| format!("failed to spawn Python interpreter: {e}"))?;
228 let tree = codewhale_runtime::process_tree::ProcessTree::attach_tokio(&child).ok();
229
230 let stdin = child
231 .stdin
232 .take()
233 .ok_or_else(|| "Python interpreter stdin pipe missing".to_string())?;
234 let raw_stdout = child
235 .stdout
236 .take()
237 .ok_or_else(|| "Python interpreter stdout pipe missing".to_string())?;
238 let stdout = BufReader::new(raw_stdout);
239 let mut stderr = child
240 .stderr
241 .take()
242 .ok_or_else(|| "Python interpreter stderr pipe missing".to_string())?;
243 let stderr_capture = Arc::new(StdMutex::new(StderrCapture::default()));
244 let capture = Arc::clone(&stderr_capture);
245 let stderr_task = tokio::spawn(async move {
246 let mut chunk = [0u8; 4096];
247 loop {
248 let n = match stderr.read(&mut chunk).await {
249 Ok(0) => break,
250 Ok(n) => n,
251 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
252 Err(_) => break,
253 };
254 let mut capture = capture.lock().unwrap_or_else(|poison| poison.into_inner());
255 let keep = n.min(MAX_STDERR_CAPTURE_BYTES.saturating_sub(capture.bytes.len()));
256 capture.bytes.extend_from_slice(&chunk[..keep]);
257 capture.omitted = capture.omitted.saturating_add(n - keep);
258 }
259 });
260
261 let mut rt = Self {
262 tree,
263 child,
264 stdin,
265 stdout,
266 stderr_capture,
267 stderr_task,
268 session_id: session_id.clone(),
269 stdout_limit: DEFAULT_STDOUT_LIMIT,
270 round_count: 0,
271 started: Instant::now(),
272 round_timeout,
273 broken: None,
274 };
275
276 let ready_sentinel = format!("__RLM_READY_{session_id}__");
277 match tokio::time::timeout(SPAWN_READY_TIMEOUT, rt.read_until_ready(&ready_sentinel)).await
278 {
279 Ok(Ok(())) => {}
280 Ok(Err(e)) => {
281 rt.kill_tree();
282 let _ = rt.child.kill().await;
283 let detail = rt.drain_stderr().await;
284 return Err(startup_failure(
285 format!("Python interpreter bootstrap failed: {e}"),
286 &detail,
287 ));
288 }
289 Err(_) => {
290 rt.kill_tree();
291 let _ = rt.child.kill().await;
292 return Err(format!(
293 "Python interpreter bootstrap did not signal ready within {}s",
294 SPAWN_READY_TIMEOUT.as_secs()
295 ));
296 }
297 }
298 if let Some(body) = context
299 && let Err(error) = rt.load_context(body).await
300 {
301 rt.kill_tree();
302 let _ = rt.child.kill().await;
303 return Err(format!(
304 "Python interpreter could not load context: {error}"
305 ));
306 }
307 Ok(rt)
308 }
309
310 #[cfg(any(test, feature = "test-support"))]
311 pub async fn unconfined(project: &std::path::Path) -> Result<Self, String> {
312 Self::unconfined_inner(None, project).await
313 }
314
315 #[cfg(any(test, feature = "test-support"))]
316 pub async fn unconfined_with_context(
317 context: &str,
318 project: &std::path::Path,
319 ) -> Result<Self, String> {
320 Self::unconfined_inner(Some(context), project).await
321 }
322
323 #[cfg(any(test, feature = "test-support"))]
324 async fn unconfined_inner(
325 context: Option<&str>,
326 project: &std::path::Path,
327 ) -> Result<Self, String> {
328 use codewhale_dependencies::ExternalTool as _;
329 let round_timeout = context.is_none().then_some(ROUND_TIMEOUT);
330 Self::spawn(context, round_timeout, |args| {
331 let mut cmd = codewhale_dependencies::Python::tokio_command()
332 .ok_or_else(|| "no Python interpreter found".to_string())?;
333 cmd.args(args);
334 codewhale_runtime::child_env::apply_to_tokio_command(
335 &mut cmd,
336 [(AGENT_PROJECT_ENV, project.as_os_str())],
337 );
338 Ok(cmd)
339 })
340 .await
341 }
342
343 fn kill_tree(&mut self) {
344 if let Some(tree) = self.tree.take() {
345 let _ = tree.kill();
346 }
347 let _ = self.child.start_kill();
348 }
349
350 async fn read_until_ready(&mut self, ready_sentinel: &str) -> Result<(), String> {
351 loop {
352 let line = match self.read_stdout_line_lossy().await? {
353 Some(line) => line,
354 None => {
355 return Err("Python interpreter closed stdout before ready signal".to_string());
356 }
357 };
358 let trimmed = line.trim_end_matches(['\n', '\r']);
359 if trimmed == ready_sentinel {
360 return Ok(());
361 }
362 // Pre-ready output is rare; ignore it.
363 }
364 }
365
366 /// One stdout line, holding at most [`MAX_STDOUT_LINE_BYTES`] of it: the
367 /// rest of an over-long line is consumed and replaced by an omission note.
368 async fn read_stdout_line_lossy(&mut self) -> Result<Option<String>, String> {
369 let mut buf = Vec::new();
370 let mut omitted = 0usize;
371 loop {
372 let available = self
373 .stdout
374 .fill_buf()
375 .await
376 .map_err(|e| format!("stdout read: {e}"))?;
377 if available.is_empty() {
378 break;
379 }
380 let (take, ends_line) = match available.iter().position(|&byte| byte == b'\n') {
381 Some(index) => (index + 1, true),
382 None => (available.len(), false),
383 };
384 let keep = take.min(MAX_STDOUT_LINE_BYTES.saturating_sub(buf.len()));
385 buf.extend_from_slice(&available[..keep]);
386 omitted += take - keep;
387 self.stdout.consume(take);
388 if ends_line {
389 break;
390 }
391 }
392 if buf.is_empty() && omitted == 0 {
393 return Ok(None);
394 }
395 let mut line = String::from_utf8_lossy(&buf).into_owned();
396 if omitted > 0 {
397 line.truncate(line.trim_end_matches(['\n', '\r']).len());
398 line.push_str(&format!(
399 "[... {omitted} bytes of this line omitted by the REPL line limit ...]\n"
400 ));
401 }
402 Ok(Some(line))
403 }
404
405 /// Execute a Python code block with no RPC dispatcher. Used for inline
406 /// `repl` blocks where `llm_query()` should fall back to a sentinel.
407 pub async fn execute(&mut self, code: &str) -> Result<ReplRound, String> {
408 self.run(code, None::<&dyn RpcDispatcher>).await
409 }
410
411 /// Replace the long context visible to bounded helpers without restarting
412 /// the Python process. User-created variables, imports, and handles stay
413 /// alive across the refresh, which is what lets the normal agent loop use
414 /// one working kernel instead of rebuilding a throwaway REPL each turn.
415 pub async fn replace_context(&mut self, body: &str) -> Result<(), String> {
416 self.load_context(body)
417 .await
418 .map_err(|error| format!("refresh REPL context failed: {error}"))
419 }
420
421 async fn load_context(&mut self, body: &str) -> Result<(), String> {
422 if let Some(reason) = &self.broken {
423 return Err(format!(
424 "Python REPL is unusable after an earlier round failed ({reason}); start a new REPL"
425 ));
426 }
427 self.broken = Some("a context load was cancelled before it finished".to_string());
428 let frame = format!(
429 "__RLM_CTX_{}__::{}\n",
430 self.session_id,
431 ascii_json_string(body)
432 );
433 let ok_line = format!("__RLM_CTXOK_{}__", self.session_id);
434 let err_prefix = format!("__RLM_CTXERR_{}__::", self.session_id);
435 let exchange = async {
436 self.stdin
437 .write_all(frame.as_bytes())
438 .await
439 .map_err(|e| format!("stdin write: {e}"))?;
440 self.stdin
441 .flush()
442 .await
443 .map_err(|e| format!("stdin flush: {e}"))?;
444 loop {
445 let Some(line) = self.read_stdout_line_lossy().await? else {
446 return Err(
447 "Python interpreter closed stdout while loading context".to_string()
448 );
449 };
450 let trimmed = line.trim_end_matches(['\n', '\r']);
451 if trimmed == ok_line {
452 return Ok(None);
453 }
454 if let Some(rest) = trimmed.strip_prefix(&err_prefix) {
455 return Ok(Some(
456 serde_json::from_str::<String>(rest).unwrap_or_else(|_| rest.to_string()),
457 ));
458 }
459 }
460 };
461 let outcome = tokio::time::timeout(CONTEXT_LOAD_TIMEOUT, exchange)
462 .await
463 .unwrap_or_else(|_| {
464 Err(format!(
465 "loading context timed out after {}s",
466 CONTEXT_LOAD_TIMEOUT.as_secs()
467 ))
468 });
469 match outcome {
470 Ok(None) => {
471 self.broken = None;
472 Ok(())
473 }
474 Ok(Some(message)) => {
475 self.broken = None;
476 Err(message)
477 }
478 Err(error) => {
479 self.kill_tree();
480 self.broken = Some(error.clone());
481 Err(error)
482 }
483 }
484 }
485
486 /// Execute a code block, dispatching any sub-LLM RPCs through `bridge`.
487 ///
488 /// Returns once Python emits `__RLM_DONE_<sid>__` or the round timeout
489 /// elapses (whichever happens first).
490 ///
491 /// Known limitations (F02-07): the sentinels share stdout with the code
492 /// they frame, and `_SID`/`_DONE` are ordinary Python globals, so code in
493 /// this round (or a subprocess inheriting fd 1) can still print its own
494 /// round's DONE line and end the round early; only another round's DONE
495 /// is refused. Closing that needs an out-of-band protocol channel.
496 ///
497 /// A failed or timed-out round, `shutdown` and drop kill the interpreter's
498 /// process tree: its process group on Unix, a Job Object on Windows. A
499 /// descendant that moved to its own session or process group on Unix, or
500 /// one started on Windows before the job was assigned, can still outlive
501 /// the kernel; if the tree could not be attached, only the interpreter is
502 /// killed.
503 pub async fn run<D>(&mut self, code: &str, bridge: Option<&D>) -> Result<ReplRound, String>
504 where
505 D: RpcDispatcher + ?Sized,
506 {
507 if let Some(reason) = &self.broken {
508 return Err(format!(
509 "Python REPL is unusable after an earlier round failed ({reason}); start a new REPL"
510 ));
511 }
512 // Pessimistic until this round reads its own DONE: a caller that
513 // drops this future mid-round leaves the stream out of step too.
514 self.broken = Some("an earlier round was cancelled before it finished".to_string());
515 let started = Instant::now();
516 self.round_count += 1;
517 let round_id = self.round_count;
518 let round_tag = round_id.to_string();
519
520 // Send the code header + body + end marker in one write.
521 let header = format!("__RLM_RUN_{}__::{round_id}\n", self.session_id);
522 let footer = format!("__RLM_END_{}__\n", self.session_id);
523 let payload = format!("{header}{code}\n{footer}");
524 self.stdin
525 .write_all(payload.as_bytes())
526 .await
527 .map_err(|e| format!("stdin write: {e}"))?;
528 self.stdin
529 .flush()
530 .await
531 .map_err(|e| format!("stdin flush: {e}"))?;
532
533 // Sentinels for this session.
534 let req_prefix = format!("__RLM_REQ_{}__::", self.session_id);
535 let final_prefix = format!("__RLM_FINAL_{}__::", self.session_id);
536 let err_prefix = format!("__RLM_ERR_{}__::", self.session_id);
537 let done_prefix = format!("__RLM_DONE_{}__::", self.session_id);
538
539 let mut stdout_buf = String::new();
540 let mut stdout_omitted = 0usize;
541 let mut final_value: Option<String> = None;
542 let mut final_json: Option<Value> = None;
543 let mut final_confidence: Option<Value> = None;
544 let mut had_error = false;
545 let mut rpc_count: u32 = 0;
546 let round_timeout = self.round_timeout;
547
548 let read_loop = async {
549 loop {
550 let line = match self.read_stdout_line_lossy().await? {
551 Some(line) => line,
552 None => {
553 return Err("Python interpreter closed stdout mid-round".to_string());
554 }
555 };
556 let trimmed = line.trim_end_matches(['\n', '\r']);
557
558 if let Some(rest) = trimmed.strip_prefix(&done_prefix) {
559 if rest == round_tag {
560 break;
561 }
562 // Another round's completion (or user output imitating
563 // one) never ends this round.
564 push_bounded(&mut stdout_buf, &line, &mut stdout_omitted);
565 continue;
566 }
567 if let Some(rest) = trimmed.strip_prefix(&final_prefix) {
568 // New sessions emit an object with value/confidence;
569 // legacy helpers emitted a JSON string.
570 match serde_json::from_str::<Value>(rest) {
571 Ok(Value::Object(map)) => {
572 let value_json = map
573 .get("value")
574 .cloned()
575 .unwrap_or(Value::String(rest.to_string()));
576 let value = value_json
577 .as_str()
578 .map(str::to_string)
579 .unwrap_or_else(|| value_json.to_string());
580 final_json = Some(value_json);
581 final_value = Some(value);
582 final_confidence = map.get("confidence").cloned();
583 }
584 Ok(Value::String(value)) => {
585 final_json = Some(Value::String(value.clone()));
586 final_value = Some(value);
587 final_confidence = None;
588 }
589 Ok(other) => {
590 final_json = Some(other.clone());
591 final_value = Some(other.to_string());
592 final_confidence = None;
593 }
594 Err(_) => {
595 final_value = Some(rest.to_string());
596 final_confidence = None;
597 }
598 }
599 continue;
600 }
601 if let Some(rest) = trimmed.strip_prefix(&err_prefix) {
602 let traceback =
603 serde_json::from_str::<String>(rest).unwrap_or_else(|_| rest.to_string());
604 had_error = true;
605 push_bounded(
606 &mut stdout_buf,
607 &format!("[traceback]\n{traceback}\n"),
608 &mut stdout_omitted,
609 );
610 continue;
611 }
612 if let Some(rest) = trimmed.strip_prefix(&req_prefix) {
613 rpc_count = rpc_count.saturating_add(1);
614 let req: RpcRequest = match serde_json::from_str(rest) {
615 Ok(r) => r,
616 Err(e) => {
617 // Send an error response so Python isn't blocked.
618 self.send_resp(&RpcResponse::Single(SingleResp {
619 text: String::new(),
620 error: Some(format!("malformed RPC: {e}")),
621 }))
622 .await?;
623 continue;
624 }
625 };
626 let resp = match bridge {
627 Some(b) => b.dispatch(req).await,
628 None => RpcResponse::Single(SingleResp {
629 text: String::new(),
630 error: Some("no LLM bridge bound to this REPL".to_string()),
631 }),
632 };
633 self.send_resp(&resp).await?;
634 continue;
635 }
636
637 push_bounded(&mut stdout_buf, &line, &mut stdout_omitted);
638 }
639 Ok::<_, String>(())
640 };
641
642 let outcome = match round_timeout {
643 Some(round_timeout) => tokio::time::timeout(round_timeout, read_loop)
644 .await
645 .unwrap_or_else(|_| {
646 Err(format!(
647 "REPL round timed out after {}s",
648 round_timeout.as_secs()
649 ))
650 }),
651 None => read_loop.await,
652 };
653 if let Err(error) = outcome {
654 // The interpreter may still be executing this round. Kill it and
655 // what it started now (the handle is reaped on drop) rather than
656 // leave it running and let its late output land in a later round.
657 self.kill_tree();
658 self.broken = Some(error.clone());
659 return Err(error);
660 }
661 self.broken = None;
662 if stdout_omitted > 0 {
663 stdout_buf.push_str(&format!(
664 "\n[... REPL round output capped: {stdout_omitted} bytes omitted ...]\n"
665 ));
666 }
667
668 let stderr = self.drain_stderr().await;
669 let display = truncate_stdout(stdout_buf.trim_end_matches('\n'), self.stdout_limit);
670
671 Ok(ReplRound {
672 stdout: display,
673 full_stdout: stdout_buf,
674 stderr,
675 has_error: had_error,
676 final_value,
677 final_json,
678 final_confidence,
679 rpc_count,
680 elapsed: started.elapsed(),
681 })
682 }
683
684 async fn send_resp(&mut self, resp: &RpcResponse) -> Result<(), String> {
685 let body = serde_json::to_string(resp).map_err(|e| format!("encode rpc resp: {e}"))?;
686 let line = format!("__RLM_RESP_{}__::{body}\n", self.session_id);
687 self.stdin
688 .write_all(line.as_bytes())
689 .await
690 .map_err(|e| format!("stdin write resp: {e}"))?;
691 self.stdin
692 .flush()
693 .await
694 .map_err(|e| format!("stdin flush resp: {e}"))?;
695 Ok(())
696 }
697
698 async fn drain_stderr(&mut self) -> String {
699 tokio::time::sleep(Duration::from_millis(20)).await;
700 let capture = std::mem::take(
701 &mut *self
702 .stderr_capture
703 .lock()
704 .unwrap_or_else(|poison| poison.into_inner()),
705 );
706 let mut text = String::from_utf8_lossy(&capture.bytes).into_owned();
707 if capture.omitted > 0 {
708 text.push_str(&format!(
709 "\n[... REPL stderr capped: {} bytes omitted ...]\n",
710 capture.omitted
711 ));
712 }
713 text
714 }
715
716 /// True once a round failed or was dropped before reading its own DONE
717 /// sentinel. Every later round refuses, so a holder that wants to keep
718 /// going replaces the kernel instead of reusing it.
719 pub fn is_broken(&self) -> bool {
720 self.broken.is_some()
721 }
722
723 /// Total rounds executed.
724 pub fn round_count(&self) -> u64 {
725 self.round_count
726 }
727
728 /// Current per-round timeout policy. RLM context runs intentionally return
729 /// `None` so long map-reduce jobs are not killed by the old 180s cap.
730 pub fn round_timeout(&self) -> Option<Duration> {
731 self.round_timeout
732 }
733
734 /// Wall-clock uptime since spawn.
735 pub fn uptime(&self) -> Duration {
736 self.started.elapsed()
737 }
738
739 /// Cleanly tear down the subprocess.
740 pub async fn shutdown(mut self) {
741 let _ = self.stdin.shutdown().await;
742 self.kill_tree();
743 let _ = self.child.kill().await;
744 }
745 }
746
747 impl Drop for PythonRuntime {
748 fn drop(&mut self) {
749 self.stderr_task.abort();
750 }
751 }
752
753 fn render_bootstrap(session_id: &str) -> String {
754 BOOTSTRAP_TEMPLATE.replace("__SID__", session_id)
755 }
756
757 const BOOTSTRAP_TEMPLATE: &str = r#"
758 import sys as _sys
759 _cwd_entries = [p for p in _sys.path if p in ("", ".")]
760 _sys.path[:] = [p for p in _sys.path if p not in ("", ".")] + _cwd_entries
761 import json as _json
762 import os as _os
763 import re as _re
764 import traceback as _traceback
765
766 _SID = "__SID__"
767 _REQ = f"__RLM_REQ_{_SID}__::"
768 _RESP = f"__RLM_RESP_{_SID}__::"
769 _FINAL = f"__RLM_FINAL_{_SID}__::"
770 _ERR = f"__RLM_ERR_{_SID}__::"
771 _RUN = f"__RLM_RUN_{_SID}__::"
772 _CTX = f"__RLM_CTX_{_SID}__::"
773 _CTX_OK = f"__RLM_CTXOK_{_SID}__"
774 _CTX_ERR = f"__RLM_CTXERR_{_SID}__::"
775 _END = f"__RLM_END_{_SID}__"
776 _DONE = f"__RLM_DONE_{_SID}__::"
777 _READY = f"__RLM_READY_{_SID}__"
778
779 def _rpc(req):
780 _sys.stdout.write(_REQ + _json.dumps(req) + "\n")
781 _sys.stdout.flush()
782 line = _sys.stdin.readline()
783 if not line:
784 return {"error": "rust driver closed stdin"}
785 if line.startswith(_RESP):
786 try:
787 return _json.loads(line[len(_RESP):])
788 except Exception as e:
789 return {"error": f"malformed rpc resp: {e}"}
790 return {"error": f"unexpected protocol line: {line[:120]!r}"}
791
792 def llm_query(prompt, model=None, max_tokens=None, system=None):
793 """One-shot sub-LLM call. The model arg is accepted for compatibility but ignored by Rust."""
794 resp = _rpc({"type":"llm","prompt":str(prompt),"model":model,
795 "max_tokens":max_tokens,"system":system})
796 if isinstance(resp, dict) and resp.get("error"):
797 return f"[llm_query error: {resp['error']}]"
798 if isinstance(resp, dict):
799 return resp.get("text","")
800 return str(resp)
801
802 def _normalize_dependency_mode(mode):
803 if mode is None:
804 return ""
805 return str(mode).strip().lower().replace("-", "_").replace(" ", "_")
806
807 def _batch_dependency_error(helper, prompts, dependency_mode):
808 mode = _normalize_dependency_mode(dependency_mode)
809 if mode in ("independent", "parallel_safe", "map_reduce"):
810 return None
811 if mode in ("sequential", "dependent", "ordered", "chain", "serial"):
812 return (
813 f"[{helper}: refused parallel batch because dependency_mode={dependency_mode!r}. "
814 "Use sub_query_sequence(...) or an explicit for-loop with sub_query(...) so each step can consume the previous result.]"
815 )
816 return (
817 f"[{helper}: batch helpers require dependency_mode='independent'. "
818 "Use only for independent slices/items; for A->B dependencies, global-state refactors, migrations, or rollback-sensitive work, use sub_query_sequence(...).]"
819 )
820
821 def llm_query_batched(prompts, model=None, dependency_mode=None, safety_note=None):
822 """Run independent sub-LLM calls concurrently. Declare dependency_mode='independent'."""
823 if not isinstance(prompts, (list, tuple)):
824 return ["[llm_query_batched: prompts must be a list]"]
825 err = _batch_dependency_error("llm_query_batched", prompts, dependency_mode)
826 if err is not None:
827 return [err for _ in prompts]
828 resp = _rpc({
829 "type":"llm_batch",
830 "prompts":[str(p) for p in prompts],
831 "model":model,
832 "dependency_mode":dependency_mode,
833 "safety_note":safety_note,
834 })
835 if isinstance(resp, dict) and resp.get("error"):
836 return [f"[llm_query_batched: {resp['error']}]" for _ in prompts]
837 results = (resp or {}).get("results", []) if isinstance(resp, dict) else []
838 if len(results) != len(prompts):
839 return [f"[llm_query_batched: size mismatch ({len(results)}/{len(prompts)})]" for _ in prompts]
840 out = []
841 for r in results:
842 if r.get("error"):
843 out.append(f"[child err: {r['error']}]")
844 else:
845 out.append(r.get("text",""))
846 return out
847
848 def _rlm_child_text(r, err_label):
849 # A sub-RLM can end with a partial answer AND an error (it ran out of
850 # rounds before FINAL). Keep the text and mark it incomplete; only an
851 # error with no text collapses to the error marker.
852 text = r.get("text") or ""
853 err = r.get("error")
854 if not err:
855 return text
856 if text.strip():
857 return f"{text}\n[rlm_query incomplete: {err}]"
858 return f"[{err_label}: {err}]"
859
860 def rlm_query(prompt, model=None):
861 """Recursive sub-RLM. The model arg is accepted for compatibility but ignored by Rust."""
862 resp = _rpc({"type":"rlm","prompt":str(prompt),"model":model})
863 if isinstance(resp, dict):
864 return _rlm_child_text(resp, "rlm_query error")
865 return str(resp)
866
867 def rlm_query_batched(prompts, model=None, dependency_mode=None, safety_note=None):
868 """Run independent recursive sub-RLMs in parallel. Declare dependency_mode='independent'."""
869 if not isinstance(prompts, (list, tuple)):
870 return ["[rlm_query_batched: prompts must be a list]"]
871 err = _batch_dependency_error("rlm_query_batched", prompts, dependency_mode)
872 if err is not None:
873 return [err for _ in prompts]
874 resp = _rpc({
875 "type":"rlm_batch",
876 "prompts":[str(p) for p in prompts],
877 "model":model,
878 "dependency_mode":dependency_mode,
879 "safety_note":safety_note,
880 })
881 if isinstance(resp, dict) and resp.get("error"):
882 return [f"[rlm_query_batched: {resp['error']}]" for _ in prompts]
883 results = (resp or {}).get("results", []) if isinstance(resp, dict) else []
884 if len(results) != len(prompts):
885 return [f"[rlm_query_batched: size mismatch ({len(results)}/{len(prompts)})]" for _ in prompts]
886 return [_rlm_child_text(r, "child err") for r in results]
887
888 def _slice_text(slice_value):
889 if slice_value is None:
890 return ""
891 if isinstance(slice_value, dict):
892 if "text" in slice_value:
893 return str(slice_value["text"])
894 return _json.dumps(slice_value, ensure_ascii=False)
895 return str(slice_value)
896
897 def _prompt_with_slice(prompt, slice_value):
898 text = _slice_text(slice_value)
899 if not text:
900 return str(prompt)
901 if isinstance(slice_value, dict) and ("index" in slice_value or ("start" in slice_value and "end" in slice_value)):
902 label = f"slice index={slice_value.get('index', '?')} range={slice_value.get('start', '?')}:{slice_value.get('end', '?')}"
903 else:
904 label = "slice"
905 return f"{prompt}\n\n--- {label} ---\n{text}"
906
907 def sub_query(prompt, slice=None, timeout_secs=None, **kwargs):
908 """One child LLM call, optionally scoped to a bounded slice."""
909 return llm_query(_prompt_with_slice(prompt, slice))
910
911 def sub_query_batch(prompt, slices, timeout_secs=None, dependency_mode=None, safety_note=None, **kwargs):
912 """Apply one prompt to many independent bounded slices concurrently."""
913 if not isinstance(slices, (list, tuple)):
914 return ["[sub_query_batch: slices must be a list]"]
915 return llm_query_batched(
916 [_prompt_with_slice(prompt, s) for s in slices],
917 dependency_mode=dependency_mode,
918 safety_note=safety_note,
919 )
920
921 def sub_query_map(prompts, slices=None, timeout_secs=None, dependency_mode=None, safety_note=None, **kwargs):
922 """Run N distinct independent prompts, optionally paired with N bounded slices."""
923 if not isinstance(prompts, (list, tuple)):
924 return ["[sub_query_map: prompts must be a list]"]
925 if slices is None:
926 return llm_query_batched(
927 [str(p) for p in prompts],
928 dependency_mode=dependency_mode,
929 safety_note=safety_note,
930 )
931 if not isinstance(slices, (list, tuple)):
932 return ["[sub_query_map: slices must be a list]"]
933 if len(prompts) != len(slices):
934 return [f"[sub_query_map: size mismatch ({len(prompts)}/{len(slices)})]" for _ in prompts]
935 return llm_query_batched(
936 [_prompt_with_slice(p, s) for p, s in zip(prompts, slices)],
937 dependency_mode=dependency_mode,
938 safety_note=safety_note,
939 )
940
941 def sub_query_sequence(prompt, slices, carry_prompt=None, timeout_secs=None, **kwargs):
942 """Apply one prompt to slices sequentially, feeding each result into the next step."""
943 if not isinstance(slices, (list, tuple)):
944 return ["[sub_query_sequence: slices must be a list]"]
945 out = []
946 previous = ""
947 carry = str(carry_prompt or "Previous step result; treat it as required input for this step:")
948 total = len(slices)
949 for i, s in enumerate(slices):
950 step_prompt = _prompt_with_slice(prompt, s)
951 if previous:
952 step_prompt = (
953 f"{step_prompt}\n\n--- dependency_state step {i}/{total} ---\n"
954 f"{carry}\n{previous}"
955 )
956 result = llm_query(step_prompt)
957 out.append(result)
958 previous = result
959 return out
960
961 def sub_rlm(prompt, source=None, timeout_secs=None, **kwargs):
962 """Recursive sub-RLM call for tasks that need their own decomposition."""
963 return rlm_query(_prompt_with_slice(prompt, source))
964
965 def _json_safe(value):
966 try:
967 _json.dumps(value, ensure_ascii=False)
968 return value
969 except Exception:
970 return str(value)
971
972 def _emit_final(value, confidence=None):
973 safe_value = _json_safe(value)
974 _sys.stdout.write(_FINAL + _json.dumps({
975 "value": safe_value,
976 "confidence": confidence,
977 }, ensure_ascii=False) + "\n")
978 _sys.stdout.flush()
979
980 def FINAL(value):
981 """Legacy compatibility alias for finalize(value)."""
982 _emit_final(value)
983
984 def FINAL_VAR(name):
985 """Legacy compatibility alias for finalize(repl_get(name))."""
986 name_str = str(name).strip().strip("'\"")
987 if name_str in globals():
988 _emit_final(globals()[name_str])
989 else:
990 print(f"FINAL_VAR error: variable '{name_str}' not found. "
991 f"Use SHOW_VARS() to list available variables.", flush=True)
992
993 def SHOW_VARS():
994 """Return a dict of {name: type-name} for all user variables in the REPL."""
995 out = {}
996 for k, v in list(globals().items()):
997 if k.startswith('_') or k in _BOOTSTRAP_NAMES:
998 continue
999 out[k] = type(v).__name__
1000 return out
1001
1002 def repl_get(name, default=None):
1003 return globals().get(str(name), default)
1004
1005 def repl_set(name, value):
1006 globals()[str(name)] = value
1007
1008 def context_meta():
1009 """Return bounded metadata about the loaded input; never includes the full text."""
1010 text = _context
1011 line_count = 0 if text == "" else text.count("\n") + (0 if text.endswith("\n") else 1)
1012 return {
1013 "chars": len(text),
1014 "lines": line_count,
1015 "preview": text[:500],
1016 "tail_preview": text[-500:] if len(text) > 500 else text,
1017 }
1018
1019 def _slice_chars(start, end):
1020 total = len(_context)
1021 s = max(0, int(start))
1022 e = max(s, min(total, int(end)))
1023 return _context[s:e]
1024
1025 def _slice_lines(start, end):
1026 lines = _context.splitlines()
1027 s = max(0, int(start))
1028 e = max(s, min(len(lines), int(end)))
1029 return "\n".join(lines[s:e])
1030
1031 def peek(start, end, unit="chars"):
1032 """Return a bounded slice of the input by char offsets or line numbers."""
1033 if str(unit).lower() in ("line", "lines"):
1034 return _slice_lines(start, end)
1035 if str(unit).lower() not in ("char", "chars"):
1036 raise ValueError("unit must be 'chars' or 'lines'")
1037 return _slice_chars(start, end)
1038
1039 def search(pattern, max_hits=100):
1040 """Regex-search the input and return bounded hit records with snippets."""
1041 max_hits = max(0, int(max_hits))
1042 hits = []
1043 if max_hits == 0:
1044 return hits
1045 rx = _re.compile(str(pattern), _re.MULTILINE)
1046 for i, m in enumerate(rx.finditer(_context)):
1047 if i >= max_hits:
1048 break
1049 start, end = m.span()
1050 snippet_start = max(0, start - 120)
1051 snippet_end = min(len(_context), end + 120)
1052 hits.append({
1053 "index": i,
1054 "start": start,
1055 "end": end,
1056 "match": m.group(0),
1057 "snippet": _context[snippet_start:snippet_end],
1058 })
1059 return hits
1060
1061 def chunk(max_chars=20000, overlap=0):
1062 """Return full-coverage input chunks with index/start/end/text fields."""
1063 max_chars = int(max_chars)
1064 overlap = max(0, int(overlap))
1065 if max_chars <= 0:
1066 raise ValueError("max_chars must be > 0")
1067 if overlap >= max_chars:
1068 raise ValueError("overlap must be smaller than max_chars")
1069 chunks = []
1070 start = 0
1071 idx = 0
1072 total = len(_context)
1073 while start < total:
1074 end = min(total, start + max_chars)
1075 chunks.append({"index": idx, "start": start, "end": end, "text": _context[start:end]})
1076 idx += 1
1077 if end >= total:
1078 break
1079 start = end - overlap
1080 return chunks
1081
1082 def chunk_context(max_chars=20000, overlap=0):
1083 """Compatibility alias for chunk()."""
1084 return chunk(max_chars=max_chars, overlap=overlap)
1085
1086 def chunk_coverage(chunks):
1087 """Summarize coverage for chunks produced by chunk()."""
1088 spans = []
1089 for c in chunks:
1090 try:
1091 spans.append((int(c["start"]), int(c["end"])))
1092 except Exception:
1093 continue
1094 spans.sort()
1095 covered = 0
1096 cursor = 0
1097 gaps = []
1098 for start, end in spans:
1099 if start > cursor:
1100 gaps.append((cursor, start))
1101 if end > cursor:
1102 covered += end - max(start, cursor)
1103 cursor = end
1104 if cursor < len(_context):
1105 gaps.append((cursor, len(_context)))
1106 return {
1107 "chunks": len(chunks),
1108 "context_chars": len(_context),
1109 "input_chars": len(_context),
1110 "covered_chars": covered,
1111 "gaps": gaps,
1112 "complete": covered >= len(_context) and not gaps,
1113 }
1114
1115 def finalize(value, confidence=None):
1116 """Signal the session's final answer and persist confidence metadata."""
1117 global final_answer, final_confidence, final_result
1118 final_answer = _json_safe(value)
1119 final_confidence = confidence
1120 final_result = {
1121 "value": final_answer,
1122 "confidence": confidence,
1123 }
1124 _emit_final(final_answer, confidence=confidence)
1125 return final_answer
1126
1127 def evaluate_progress():
1128 """Return lightweight state useful before deciding the next REPL step."""
1129 vars_now = SHOW_VARS()
1130 return {
1131 "has_final_answer": "final_answer" in globals(),
1132 "final_confidence": globals().get("final_confidence", None),
1133 "user_variables": vars_now,
1134 }
1135
1136 # The long input arrives as a `__RLM_CTX_<sid>__::` frame on stdin, handled by
1137 # `_main_loop`, so no file or path has to be visible to the interpreter.
1138 _context = ""
1139 content = _context
1140
1141 def _load_context(payload):
1142 global _context, content
1143 _context = _json.loads(payload)
1144 content = _context
1145
1146 _BOOTSTRAP_NAMES = {
1147 "_SID","_REQ","_RESP","_FINAL","_ERR","_RUN","_CTX","_CTX_OK","_CTX_ERR","_END","_DONE","_READY",
1148 "_rpc","_context","_slice_chars","_slice_lines","_load_context","_BOOTSTRAP_NAMES","_main_loop",
1149 "_emit_final","_json_safe","_slice_text","_prompt_with_slice",
1150 "_normalize_dependency_mode","_batch_dependency_error",
1151 "llm_query","llm_query_batched","rlm_query","rlm_query_batched",
1152 "sub_query","sub_query_batch","sub_query_map","sub_query_sequence","sub_rlm",
1153 "FINAL","FINAL_VAR","SHOW_VARS","repl_get","repl_set",
1154 "context_meta","peek","search","chunk","chunk_context","chunk_coverage",
1155 "finalize","evaluate_progress","content",
1156 "_json","_os","_re","_sys","_traceback",
1157 }
1158
1159 def _main_loop():
1160 _sys.stdout.write(_READY + "\n")
1161 _sys.stdout.flush()
1162 while True:
1163 header = _sys.stdin.readline()
1164 if not header:
1165 return
1166 if header.startswith(_CTX):
1167 try:
1168 _load_context(header[len(_CTX):])
1169 _sys.stdout.write(_CTX_OK + "\n")
1170 except BaseException as e:
1171 _sys.stdout.write(_CTX_ERR + _json.dumps(str(e)) + "\n")
1172 _sys.stdout.flush()
1173 continue
1174 if not header.startswith(_RUN):
1175 continue
1176 round_id = header.rstrip("\n")[len(_RUN):]
1177 code_lines = []
1178 while True:
1179 line = _sys.stdin.readline()
1180 if not line:
1181 return
1182 if line.rstrip("\n") == _END:
1183 break
1184 code_lines.append(line)
1185 code = "".join(code_lines)
1186 try:
1187 exec(compile(code, f"<repl-{round_id}>", "exec"), globals())
1188 except SystemExit:
1189 _sys.stdout.write(_DONE + round_id + "\n")
1190 _sys.stdout.flush()
1191 return
1192 except BaseException:
1193 tb = _traceback.format_exc()
1194 _sys.stdout.write(_ERR + _json.dumps(tb) + "\n")
1195 _sys.stdout.flush()
1196 _sys.stdout.write(_DONE + round_id + "\n")
1197 _sys.stdout.flush()
1198
1199 _main_loop()
1200 "#;
1201
1202 // ---------------------------------------------------------------------------
1203 // Helpers
1204 // ---------------------------------------------------------------------------
1205
1206 fn ascii_json_string(text: &str) -> String {
1207 use std::fmt::Write as _;
1208 let mut out = String::with_capacity(text.len() + 2);
1209 out.push('"');
1210 for ch in text.chars() {
1211 match ch {
1212 '"' => out.push_str("\\\""),
1213 '\\' => out.push_str("\\\\"),
1214 '\n' => out.push_str("\\n"),
1215 '\r' => out.push_str("\\r"),
1216 '\t' => out.push_str("\\t"),
1217 ' '..='~' => out.push(ch),
1218 _ => {
1219 let mut units = [0u16; 2];
1220 for unit in ch.encode_utf16(&mut units) {
1221 let _ = write!(out, "\\u{unit:04x}");
1222 }
1223 }
1224 }
1225 }
1226 out.push('"');
1227 out
1228 }
1229
1230 fn startup_failure(message: String, stderr: &str) -> String {
1231 let detail = stderr.trim();
1232 if detail.is_empty() {
1233 return message;
1234 }
1235 let cut = (0..=detail.len().min(2_000))
1236 .rev()
1237 .find(|&index| detail.is_char_boundary(index))
1238 .unwrap_or(0);
1239 format!("{message}: {}", &detail[..cut])
1240 }
1241
1242 /// Append to a round's retained stdout without exceeding
1243 /// [`MAX_ROUND_STDOUT_BYTES`]; whatever does not fit is only counted.
1244 fn push_bounded(buf: &mut String, text: &str, omitted: &mut usize) {
1245 let room = MAX_ROUND_STDOUT_BYTES.saturating_sub(buf.len());
1246 if text.len() <= room {
1247 buf.push_str(text);
1248 return;
1249 }
1250 let cut = (0..=room)
1251 .rev()
1252 .find(|&index| text.is_char_boundary(index))
1253 .unwrap_or(0);
1254 buf.push_str(&text[..cut]);
1255 *omitted += text.len() - cut;
1256 }
1257
1258 fn truncate_stdout(stdout: &str, limit: usize) -> String {
1259 if stdout.len() <= limit {
1260 return stdout.to_string();
1261 }
1262 let take = limit.saturating_sub(80);
1263 let cut = (0..=take)
1264 .rev()
1265 .find(|&index| stdout.is_char_boundary(index))
1266 .unwrap_or(0);
1267 let mut out = stdout[..cut].to_string();
1268 let omitted = stdout.len().saturating_sub(out.len());
1269 out.push_str(&format!(
1270 "\n\n[... REPL output truncated: {omitted} bytes omitted ...]\n"
1271 ));
1272 out
1273 }
1274
1275 // ---------------------------------------------------------------------------
1276 // Tests
1277 // ---------------------------------------------------------------------------
1278
1279 #[cfg(test)]
1280 mod tests {
1281 use super::*;
1282 use std::sync::Arc;
1283 use std::sync::atomic::{AtomicU32, Ordering};
1284 use tokio::sync::Mutex;
1285
1286 /// In-process dispatcher that records what was asked and replies with
1287 /// canned text. Lets tests verify the round-trip without real network.
1288 struct StubBridge {
1289 calls: Arc<Mutex<Vec<RpcRequest>>>,
1290 canned: Arc<AtomicU32>,
1291 }
1292
1293 impl StubBridge {
1294 fn new() -> Self {
1295 Self {
1296 calls: Arc::new(Mutex::new(Vec::new())),
1297 canned: Arc::new(AtomicU32::new(0)),
1298 }
1299 }
1300 }
1301
1302 impl RpcDispatcher for StubBridge {
1303 fn dispatch<'a>(
1304 &'a self,
1305 req: RpcRequest,
1306 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = RpcResponse> + Send + 'a>> {
1307 Box::pin(async move {
1308 self.calls.lock().await.push(req.clone());
1309 let n = self.canned.fetch_add(1, Ordering::Relaxed);
1310 match req {
1311 RpcRequest::Llm { prompt, .. } | RpcRequest::Rlm { prompt, .. } => {
1312 RpcResponse::Single(SingleResp {
1313 text: format!("stub#{n}: {prompt}"),
1314 error: None,
1315 })
1316 }
1317 RpcRequest::LlmBatch { prompts, .. } | RpcRequest::RlmBatch { prompts, .. } => {
1318 let results = prompts
1319 .into_iter()
1320 .enumerate()
1321 .map(|(i, p)| SingleResp {
1322 text: format!("stub#{n}.{i}: {p}"),
1323 error: None,
1324 })
1325 .collect();
1326 RpcResponse::Batch(BatchResp { results })
1327 }
1328 }
1329 })
1330 }
1331 }
1332
1333 #[tokio::test]
1334 async fn a_command_run_from_the_kernel_carries_the_agent_project() {
1335 let project = std::env::temp_dir().join(format!("agent-project-{}", Uuid::new_v4()));
1336 let mut rt = PythonRuntime::unconfined(&project).await.expect("spawn");
1337 let round = rt
1338 .execute(
1339 "import subprocess, sys\n\
1340 out = subprocess.run([sys.executable, '-c', \
1341 'import os; print(\"MARK=\" + os.environ.get(\"CODEWHALE_AGENT_PROJECT\", \"unset\"))'], \
1342 capture_output=True, text=True).stdout\n\
1343 print(out)",
1344 )
1345 .await
1346 .expect("execute");
1347 assert!(
1348 round
1349 .stdout
1350 .contains(&format!("MARK={}", project.display())),
1351 "{}",
1352 round.stdout
1353 );
1354 rt.shutdown().await;
1355 }
1356
1357 #[tokio::test]
1358 async fn spawns_and_executes_simple_print() {
1359 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1360 .await
1361 .expect("spawn");
1362 let round = rt.execute("print('hello world')").await.expect("execute");
1363 assert!(round.stdout.contains("hello world"));
1364 assert!(!round.has_error);
1365 assert!(round.final_value.is_none());
1366 assert_eq!(round.rpc_count, 0);
1367 rt.shutdown().await;
1368 }
1369
1370 #[tokio::test]
1371 async fn non_utf8_stdout_decodes_lossy_and_runtime_survives() {
1372 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1373 .await
1374 .expect("spawn");
1375 let round = rt
1376 .execute(
1377 "import sys\n\
1378 sys.stdout.buffer.write(b'bad:\\xff\\n')\n\
1379 sys.stdout.buffer.flush()\n\
1380 print('after invalid')",
1381 )
1382 .await
1383 .expect("execute");
1384
1385 assert!(round.stdout.contains("bad:\u{fffd}"), "{}", round.stdout);
1386 assert!(round.stdout.contains("after invalid"), "{}", round.stdout);
1387 rt.shutdown().await;
1388 }
1389
1390 #[tokio::test]
1391 async fn variables_persist_across_rounds() {
1392 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1393 .await
1394 .expect("spawn");
1395 rt.execute("x = [1, 2, 3]").await.expect("r1");
1396 rt.execute("x.append(99)").await.expect("r2");
1397 let round = rt.execute("print(x)").await.expect("r3");
1398 assert!(round.stdout.contains("[1, 2, 3, 99]"));
1399 rt.shutdown().await;
1400 }
1401
1402 #[tokio::test]
1403 async fn imports_persist_across_rounds() {
1404 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1405 .await
1406 .expect("spawn");
1407 rt.execute("import math").await.expect("r1");
1408 let round = rt.execute("print(math.pi)").await.expect("r2");
1409 assert!(round.stdout.contains("3.14"));
1410 rt.shutdown().await;
1411 }
1412
1413 #[tokio::test]
1414 async fn context_loads_over_stdin() {
1415 let body = "the quick brown fox";
1416 let mut rt = PythonRuntime::unconfined_with_context(body, &std::env::temp_dir())
1417 .await
1418 .expect("spawn");
1419 let round = rt
1420 .execute("print(context_meta()['chars'], peek(0, 5))")
1421 .await
1422 .expect("execute");
1423 assert!(round.stdout.contains("19"));
1424 assert!(round.stdout.contains("the q"));
1425 rt.shutdown().await;
1426 }
1427
1428 #[tokio::test]
1429 async fn context_survives_framing_and_leaves_no_file_for_the_kernel() {
1430 let body = "quote \" backslash \\ tab\t\r\nastral \u{1F600} caf\u{e9} nul\u{0} \u{7f}\n\
1431 __RLM_CTX_x__::{} __RLM_END_x__\n__RLM_DONE_x__::1\n";
1432 let mut rt = PythonRuntime::unconfined_with_context(body, &std::env::temp_dir())
1433 .await
1434 .expect("spawn");
1435 let round = rt
1436 .execute(
1437 "print(content.encode('utf-8').hex())\n\
1438 print('RLM_CONTEXT_FILE' in _os.environ)",
1439 )
1440 .await
1441 .expect("execute");
1442 let expected: String = body.bytes().map(|byte| format!("{byte:02x}")).collect();
1443 assert!(round.stdout.contains(&expected), "{}", round.stdout);
1444 assert!(round.stdout.contains("False"), "{}", round.stdout);
1445 rt.replace_context(body).await.expect("replace");
1446 let again = rt.execute("print(len(content))").await.expect("execute");
1447 assert!(
1448 again.stdout.contains(&body.chars().count().to_string()),
1449 "{}",
1450 again.stdout
1451 );
1452 rt.shutdown().await;
1453 }
1454
1455 #[tokio::test]
1456 async fn a_workspace_module_named_like_the_standard_library_does_not_run_at_start() {
1457 use codewhale_dependencies::ExternalTool as _;
1458 let workspace =
1459 std::env::temp_dir().join(format!("repl-planted-{}", Uuid::new_v4().simple()));
1460 std::fs::create_dir_all(&workspace).expect("workspace");
1461 let marker = workspace.join("planted-ran");
1462 std::fs::write(
1463 workspace.join("json.py"),
1464 format!(
1465 "import pathlib\npathlib.Path({:?}).write_text('x')\n",
1466 marker.to_string_lossy()
1467 ),
1468 )
1469 .expect("planted module");
1470 let mut rt = PythonRuntime::spawn(None, Some(INLINE_ROUND_TIMEOUT), |args| {
1471 let mut cmd = codewhale_dependencies::Python::tokio_command()
1472 .ok_or_else(|| "no Python interpreter found".to_string())?;
1473 cmd.args(args).current_dir(&workspace);
1474 codewhale_runtime::child_env::apply_to_tokio_command(
1475 &mut cmd,
1476 [(AGENT_PROJECT_ENV, workspace.as_os_str())],
1477 );
1478 Ok(cmd)
1479 })
1480 .await
1481 .expect("spawn");
1482 let round = rt.execute("print(1 + 1)").await.expect("execute");
1483 assert!(round.stdout.contains('2'), "{}", round.stdout);
1484 let planted_ran = marker.exists();
1485 rt.shutdown().await;
1486 let _ = std::fs::remove_dir_all(&workspace);
1487 assert!(!planted_ran, "the workspace module ran at kernel start");
1488
1489 let refused =
1490 PythonRuntime::spawn(None, None, |_| Err("sandbox refused".to_string())).await;
1491 assert_eq!(refused.err().as_deref(), Some("sandbox refused"));
1492 }
1493
1494 #[tokio::test]
1495 async fn context_aliases_keep_common_content_name_bounded() {
1496 let body = "aleph-style";
1497 let mut rt = PythonRuntime::unconfined_with_context(body, &std::env::temp_dir())
1498 .await
1499 .expect("spawn");
1500 let round = rt
1501 .execute("print(content == _context, 'context' in globals(), 'ctx' in globals())")
1502 .await
1503 .expect("execute");
1504 assert!(round.stdout.contains("True False False"));
1505 rt.shutdown().await;
1506 }
1507
1508 #[tokio::test]
1509 async fn replacing_context_keeps_kernel_variables_and_refreshes_helpers() {
1510 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1511 .await
1512 .expect("spawn");
1513 rt.execute("remembered = {'answer': 42}")
1514 .await
1515 .expect("seed persistent variable");
1516 rt.replace_context("fresh transcript\nwith a needle")
1517 .await
1518 .expect("refresh context");
1519
1520 let round = rt
1521 .execute(
1522 "print(remembered['answer'])\n\
1523 print(context_meta()['chars'])\n\
1524 print(search('needle')[0]['match'])",
1525 )
1526 .await
1527 .expect("inspect refreshed context");
1528
1529 assert!(round.stdout.contains("42"), "{}", round.stdout);
1530 assert!(round.stdout.contains("30"), "{}", round.stdout);
1531 assert!(round.stdout.contains("needle"), "{}", round.stdout);
1532 rt.shutdown().await;
1533 }
1534
1535 #[tokio::test]
1536 async fn context_chunk_helpers_report_full_coverage() {
1537 let body = "abcdefghijklmnopqrstuvwxyz";
1538 let mut rt = PythonRuntime::unconfined_with_context(body, &std::env::temp_dir())
1539 .await
1540 .expect("spawn");
1541 let round = rt
1542 .execute(
1543 "chunks = chunk_context(max_chars=10)\n\
1544 coverage = chunk_coverage(chunks)\n\
1545 print(len(chunks), coverage['covered_chars'], coverage['complete'])",
1546 )
1547 .await
1548 .expect("execute");
1549 assert!(round.stdout.contains("3 26 True"), "{}", round.stdout);
1550 rt.shutdown().await;
1551 }
1552
1553 #[tokio::test]
1554 async fn bounded_input_helpers_work() {
1555 let body = "alpha\nbeta needle\ngamma needle\nomega";
1556 let mut rt = PythonRuntime::unconfined_with_context(body, &std::env::temp_dir())
1557 .await
1558 .expect("spawn");
1559 let round = rt
1560 .execute(
1561 "meta = context_meta()\n\
1562 hits = search('needle', max_hits=1)\n\
1563 print(meta['chars'], meta['lines'])\n\
1564 print(peek(6, 17))\n\
1565 print(peek(1, 3, unit='lines'))\n\
1566 print(len(hits), hits[0]['match'], hits[0]['start'])",
1567 )
1568 .await
1569 .expect("execute");
1570 let stdout = round.stdout.replace("\r\n", "\n");
1571 assert!(stdout.contains("36 4"), "{stdout}");
1572 assert!(stdout.contains("beta needle"), "{stdout}");
1573 assert!(stdout.contains("beta needle\ngamma needle"), "{stdout}");
1574 assert!(stdout.contains("1 needle 11"), "{stdout}");
1575 rt.shutdown().await;
1576 }
1577
1578 #[tokio::test]
1579 async fn new_chunk_helper_reports_full_coverage() {
1580 let body = "abcdefghijklmnopqrstuvwxyz";
1581 let mut rt = PythonRuntime::unconfined_with_context(body, &std::env::temp_dir())
1582 .await
1583 .expect("spawn");
1584 let round = rt
1585 .execute(
1586 "chunks = chunk(max_chars=10)\n\
1587 coverage = chunk_coverage(chunks)\n\
1588 print(len(chunks), coverage['input_chars'], coverage['covered_chars'], coverage['complete'])",
1589 )
1590 .await
1591 .expect("execute");
1592 assert!(round.stdout.contains("3 26 26 True"), "{}", round.stdout);
1593 rt.shutdown().await;
1594 }
1595
1596 #[tokio::test]
1597 async fn finalize_helper_is_captured_directly() {
1598 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1599 .await
1600 .expect("spawn");
1601 let round = rt
1602 .execute("finalize('computed answer', confidence='high')")
1603 .await
1604 .expect("execute");
1605 assert_eq!(round.final_value.as_deref(), Some("computed answer"));
1606 assert_eq!(
1607 round.final_json.as_ref().and_then(Value::as_str),
1608 Some("computed answer")
1609 );
1610 assert_eq!(
1611 round.final_confidence.as_ref().and_then(Value::as_str),
1612 Some("high")
1613 );
1614 rt.shutdown().await;
1615 }
1616
1617 #[tokio::test]
1618 async fn finalize_preserves_json_values_for_handles() {
1619 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1620 .await
1621 .expect("spawn");
1622 let round = rt
1623 .execute("finalize({'answer': 42, 'items': ['a', 'b']})")
1624 .await
1625 .expect("execute");
1626
1627 assert_eq!(
1628 round.final_value.as_deref(),
1629 Some(r#"{"answer":42,"items":["a","b"]}"#)
1630 );
1631 assert_eq!(
1632 round.final_json,
1633 Some(serde_json::json!({"answer": 42, "items": ["a", "b"]}))
1634 );
1635 rt.shutdown().await;
1636 }
1637
1638 #[tokio::test]
1639 async fn sub_query_accepts_timeout_keyword_for_agent_guesses() {
1640 let bridge = StubBridge::new();
1641 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1642 .await
1643 .expect("spawn");
1644 let round = rt
1645 .run(
1646 "answer = sub_query('summarize', timeout_secs=2)\nprint(answer)",
1647 Some(&bridge),
1648 )
1649 .await
1650 .expect("execute");
1651
1652 assert!(!round.has_error, "{}", round.stdout);
1653 assert!(
1654 round.stdout.contains("stub#0: summarize"),
1655 "{}",
1656 round.stdout
1657 );
1658 rt.shutdown().await;
1659 }
1660
1661 #[tokio::test]
1662 async fn rlm_context_runtime_has_no_fixed_round_timeout() {
1663 let body = "long input";
1664 let rt = PythonRuntime::unconfined_with_context(body, &std::env::temp_dir())
1665 .await
1666 .expect("spawn");
1667 assert!(
1668 rt.round_timeout().is_none(),
1669 "RLM context runs must not inherit the old 180s REPL round timeout"
1670 );
1671 rt.shutdown().await;
1672 }
1673
1674 #[tokio::test]
1675 async fn timed_out_round_kills_the_interpreter_and_refuses_later_rounds() {
1676 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1677 .await
1678 .expect("spawn");
1679 rt.round_timeout = Some(Duration::from_millis(300));
1680 let error = rt
1681 .execute("import time\ntime.sleep(30)\nprint('late output')")
1682 .await
1683 .expect_err("the round must time out");
1684 assert!(error.contains("timed out"), "{error}");
1685
1686 let refused = rt
1687 .execute("print('next round')")
1688 .await
1689 .expect_err("a desynchronized REPL must not run another round");
1690 assert!(refused.contains("unusable"), "{refused}");
1691
1692 let deadline = Instant::now() + Duration::from_secs(5);
1693 while rt.child.try_wait().expect("child status").is_none() {
1694 assert!(
1695 Instant::now() < deadline,
1696 "the timed-out interpreter must be killed"
1697 );
1698 tokio::time::sleep(Duration::from_millis(25)).await;
1699 }
1700 }
1701
1702 #[cfg(unix)]
1703 #[tokio::test]
1704 async fn timed_out_round_kills_a_process_the_interpreter_started() {
1705 use codewhale_runtime::process_tree::{read_pid_file, wait_for_pid_exit};
1706 let dir = std::env::temp_dir().join(format!("repl-tree-{}", Uuid::new_v4().simple()));
1707 std::fs::create_dir_all(&dir).expect("tempdir");
1708 let pid_file = dir.join("grandchild.pid");
1709 let mut rt = PythonRuntime::unconfined(&dir).await.expect("spawn");
1710 rt.execute(&format!(
1711 "import subprocess\n\
1712 grandchild = subprocess.Popen(['sleep', '300'])\n\
1713 open({:?}, 'w').write(str(grandchild.pid))",
1714 pid_file.to_string_lossy()
1715 ))
1716 .await
1717 .expect("start grandchild");
1718 let grandchild = read_pid_file(&pid_file, Duration::from_secs(5));
1719
1720 rt.round_timeout = Some(Duration::from_millis(300));
1721 let error = rt
1722 .execute("import time\ntime.sleep(30)")
1723 .await
1724 .expect_err("the round must time out");
1725 assert!(error.contains("timed out"), "{error}");
1726
1727 let gone = tokio::task::spawn_blocking(move || {
1728 wait_for_pid_exit(grandchild, Duration::from_secs(5))
1729 })
1730 .await
1731 .expect("cleanup probe");
1732 drop(rt);
1733 let _ = std::fs::remove_dir_all(&dir);
1734 assert!(
1735 gone,
1736 "a process the timed-out round's interpreter started is still running"
1737 );
1738 }
1739
1740 #[tokio::test]
1741 async fn another_rounds_done_sentinel_does_not_end_this_round() {
1742 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1743 .await
1744 .expect("spawn");
1745 let round = rt
1746 .execute("print(_DONE + '999')\nprint('still this round')")
1747 .await
1748 .expect("execute");
1749 assert!(
1750 round.stdout.contains("still this round"),
1751 "{}",
1752 round.stdout
1753 );
1754 let next = rt.execute("print('second')").await.expect("next round");
1755 assert!(next.stdout.contains("second"), "{}", next.stdout);
1756 assert!(!next.stdout.contains("still this round"), "{}", next.stdout);
1757 rt.shutdown().await;
1758 }
1759
1760 #[tokio::test]
1761 async fn inline_runtime_keeps_bounded_round_timeout() {
1762 let rt = PythonRuntime::unconfined(&std::env::temp_dir())
1763 .await
1764 .expect("spawn");
1765 assert_eq!(rt.round_timeout(), Some(ROUND_TIMEOUT));
1766 rt.shutdown().await;
1767 }
1768
1769 #[tokio::test]
1770 async fn legacy_final_is_captured() {
1771 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1772 .await
1773 .expect("spawn");
1774 let round = rt
1775 .execute("FINAL('the answer is 42')")
1776 .await
1777 .expect("execute");
1778 assert_eq!(round.final_value.as_deref(), Some("the answer is 42"));
1779 rt.shutdown().await;
1780 }
1781
1782 #[tokio::test]
1783 async fn legacy_final_var_is_captured() {
1784 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1785 .await
1786 .expect("spawn");
1787 rt.execute("answer = 'computed'").await.expect("r1");
1788 let round = rt.execute("FINAL_VAR('answer')").await.expect("r2");
1789 assert_eq!(round.final_value.as_deref(), Some("computed"));
1790 rt.shutdown().await;
1791 }
1792
1793 #[tokio::test]
1794 async fn errors_are_reported_without_killing_runtime() {
1795 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1796 .await
1797 .expect("spawn");
1798 let r1 = rt.execute("raise ValueError('boom')").await.expect("r1");
1799 assert!(r1.has_error);
1800 assert!(r1.full_stdout.contains("boom") || r1.stdout.contains("boom"));
1801 // The runtime is still alive — next round should work.
1802 let r2 = rt.execute("print('still here')").await.expect("r2");
1803 assert!(r2.stdout.contains("still here"));
1804 rt.shutdown().await;
1805 }
1806
1807 #[tokio::test]
1808 async fn rpc_dispatcher_round_trips_llm_query() {
1809 let bridge = StubBridge::new();
1810 let calls = Arc::clone(&bridge.calls);
1811
1812 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1813 .await
1814 .expect("spawn");
1815 let round = rt
1816 .run("print(llm_query('hello'))", Some(&bridge))
1817 .await
1818 .expect("execute");
1819 assert!(
1820 round.stdout.contains("stub#0: hello"),
1821 "stdout: {:?}",
1822 round.stdout
1823 );
1824 assert_eq!(round.rpc_count, 1);
1825
1826 let recorded = calls.lock().await;
1827 assert_eq!(recorded.len(), 1);
1828 match &recorded[0] {
1829 RpcRequest::Llm { prompt, .. } => assert_eq!(prompt, "hello"),
1830 other => panic!("expected Llm request, got {other:?}"),
1831 }
1832 drop(recorded);
1833 rt.shutdown().await;
1834 }
1835
1836 /// A sub-RLM that ran out of rounds returns its last answer AND an
1837 /// error. Answers every recursive request with that shape.
1838 struct ExhaustedRlmBridge;
1839
1840 impl RpcDispatcher for ExhaustedRlmBridge {
1841 fn dispatch<'a>(
1842 &'a self,
1843 req: RpcRequest,
1844 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = RpcResponse> + Send + 'a>> {
1845 Box::pin(async move {
1846 let partial = |i: usize| SingleResp {
1847 text: if i == 1 {
1848 String::new()
1849 } else {
1850 format!("partial answer {i}")
1851 },
1852 error: Some("RLM loop exhausted after 25 iterations without FINAL".to_string()),
1853 };
1854 match req {
1855 RpcRequest::RlmBatch { prompts, .. } => RpcResponse::Batch(BatchResp {
1856 results: (0..prompts.len()).map(partial).collect(),
1857 }),
1858 _ => RpcResponse::Single(partial(0)),
1859 }
1860 })
1861 }
1862 }
1863
1864 /// #6511: the Rust loop kept the exhausted sub-RLM's last answer, but the
1865 /// Python helpers returned only the error marker whenever `error` was
1866 /// set, so the calling code never saw the text.
1867 #[tokio::test]
1868 async fn rlm_query_keeps_partial_answer_from_an_exhausted_child() {
1869 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1870 .await
1871 .expect("spawn");
1872 let round = rt
1873 .run(
1874 "print(rlm_query('go'))\nfor r in rlm_query_batched(['a', 'b'], dependency_mode='independent'):\n print(r)",
1875 Some(&ExhaustedRlmBridge),
1876 )
1877 .await
1878 .expect("execute");
1879 // Windows Python prints CRLF; compare line content, not line endings.
1880 let out = &round.stdout.replace("\r\n", "\n");
1881 assert!(
1882 out.contains("partial answer 0\n[rlm_query incomplete: RLM loop exhausted"),
1883 "{out}"
1884 );
1885 // Batched: a child with text keeps it; one with none keeps the old marker.
1886 assert!(out.matches("partial answer 0").count() == 2, "{out}");
1887 assert!(out.contains("[child err: RLM loop exhausted"), "{out}");
1888 rt.shutdown().await;
1889 }
1890
1891 #[tokio::test]
1892 async fn rpc_dispatcher_round_trips_sub_query_alias() {
1893 let bridge = StubBridge::new();
1894 let calls = Arc::clone(&bridge.calls);
1895
1896 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1897 .await
1898 .expect("spawn");
1899 let round = rt
1900 .run("print(sub_query('hello from sub'))", Some(&bridge))
1901 .await
1902 .expect("execute");
1903 assert!(
1904 round.stdout.contains("stub#0: hello from sub"),
1905 "stdout: {:?}",
1906 round.stdout
1907 );
1908 assert_eq!(round.rpc_count, 1);
1909
1910 let recorded = calls.lock().await;
1911 assert_eq!(recorded.len(), 1);
1912 match &recorded[0] {
1913 RpcRequest::Llm { prompt, .. } => assert_eq!(prompt, "hello from sub"),
1914 other => panic!("expected Llm request, got {other:?}"),
1915 }
1916 drop(recorded);
1917 rt.shutdown().await;
1918 }
1919
1920 #[tokio::test]
1921 async fn rpc_dispatcher_round_trips_batch() {
1922 let bridge = StubBridge::new();
1923 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1924 .await
1925 .expect("spawn");
1926 let round = rt
1927 .run(
1928 "outs = llm_query_batched(['a','b','c'], dependency_mode='independent', safety_note='same independent classification')\n\
1929 print('|'.join(outs))",
1930 Some(&bridge),
1931 )
1932 .await
1933 .expect("execute");
1934 assert!(round.stdout.contains("stub#0.0: a"));
1935 assert!(round.stdout.contains("stub#0.1: b"));
1936 assert!(round.stdout.contains("stub#0.2: c"));
1937 assert_eq!(round.rpc_count, 1);
1938 rt.shutdown().await;
1939 }
1940
1941 #[tokio::test]
1942 async fn batched_helpers_require_independence_declaration() {
1943 let bridge = StubBridge::new();
1944 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1945 .await
1946 .expect("spawn");
1947 let round = rt
1948 .run(
1949 "outs = sub_query_batch('summarize', [{'text': 'a'}, {'text': 'b'}])\n\
1950 print(outs[0])",
1951 Some(&bridge),
1952 )
1953 .await
1954 .expect("execute");
1955
1956 assert!(
1957 round.stdout.contains("dependency_mode='independent'"),
1958 "{}",
1959 round.stdout
1960 );
1961 assert_eq!(round.rpc_count, 0);
1962 rt.shutdown().await;
1963 }
1964
1965 #[tokio::test]
1966 async fn dependent_batch_mode_points_to_sequence_helper() {
1967 let bridge = StubBridge::new();
1968 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1969 .await
1970 .expect("spawn");
1971 let round = rt
1972 .run(
1973 "outs = llm_query_batched(['migrate A', 'migrate B'], dependency_mode='sequential')\n\
1974 print(outs[0])",
1975 Some(&bridge),
1976 )
1977 .await
1978 .expect("execute");
1979
1980 assert!(
1981 round.stdout.contains("sub_query_sequence"),
1982 "{}",
1983 round.stdout
1984 );
1985 assert_eq!(round.rpc_count, 0);
1986 rt.shutdown().await;
1987 }
1988
1989 #[tokio::test]
1990 async fn sub_query_sequence_feeds_prior_result_into_next_prompt() {
1991 let bridge = StubBridge::new();
1992 let calls = Arc::clone(&bridge.calls);
1993
1994 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
1995 .await
1996 .expect("spawn");
1997 let round = rt
1998 .run(
1999 "outs = sub_query_sequence('process this step', [{'text': 'A'}, {'text': 'B'}])\n\
2000 print(len(outs))",
2001 Some(&bridge),
2002 )
2003 .await
2004 .expect("execute");
2005
2006 assert!(round.stdout.contains("2"), "{}", round.stdout);
2007 assert_eq!(round.rpc_count, 2);
2008
2009 let recorded = calls.lock().await;
2010 assert_eq!(recorded.len(), 2);
2011 let second_prompt = match &recorded[1] {
2012 RpcRequest::Llm { prompt, .. } => prompt,
2013 other => panic!("expected second Llm request, got {other:?}"),
2014 };
2015 assert!(second_prompt.contains("--- dependency_state step 1/2 ---"));
2016 assert!(second_prompt.contains("stub#0: process this step"));
2017 drop(recorded);
2018 rt.shutdown().await;
2019 }
2020
2021 #[tokio::test]
2022 async fn no_dispatcher_returns_unavailable_sentinel() {
2023 let mut rt = PythonRuntime::unconfined(&std::env::temp_dir())
2024 .await
2025 .expect("spawn");
2026 let round = rt.execute("print(llm_query('hi'))").await.expect("execute");
2027 assert!(
2028 round.stdout.contains("[llm_query error:") || round.stdout.contains("no LLM bridge"),
2029 "stdout: {:?}",
2030 round.stdout
2031 );
2032 rt.shutdown().await;
2033 }
2034
2035 #[test]
2036 fn truncate_keeps_short_unchanged() {
2037 assert_eq!(truncate_stdout("hello", 100), "hello");
2038 }
2039
2040 #[test]
2041 fn truncate_clips_long() {
2042 let long = "a".repeat(10_000);
2043 let out = truncate_stdout(&long, 1024);
2044 assert!(out.len() < 1500);
2045 assert!(out.contains("truncated"));
2046 }
2047
2048 #[test]
2049 fn truncate_caps_multibyte_output_by_bytes() {
2050 let cjk = "中".repeat(2000);
2051 let out = truncate_stdout(&cjk, 1024);
2052 assert!(out.len() <= 1024, "len: {}", out.len());
2053 assert!(out.contains("bytes omitted"));
2054 }
2055
2056 #[tokio::test]
2057 async fn workspace_stdlib_module_does_not_shadow_bootstrap() {
2058 let dir = std::env::temp_dir().join(format!("repl-shadow-{}", Uuid::new_v4().simple()));
2059 std::fs::create_dir_all(&dir).expect("tempdir");
2060 std::fs::write(
2061 dir.join("json.py"),
2062 "from pathlib import Path\nPath('planted-ran').write_text('yes')\n",
2063 )
2064 .expect("write");
2065 let mut rt = PythonRuntime::unconfined(&dir).await.expect("spawn");
2066 let round = rt
2067 .execute("import json; print(json.dumps({'ok': 1}))")
2068 .await
2069 .expect("execute");
2070 assert!(round.stdout.contains("\"ok\": 1"), "{}", round.stdout);
2071 let planted_ran = dir.join("planted-ran").exists();
2072 rt.shutdown().await;
2073 let _ = std::fs::remove_dir_all(&dir);
2074 assert!(!planted_ran);
2075 }
2076 }
2077
2077 lines RUST