From 802082f7483e8c69cc3f0890ea1e3e206cfa130b Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 16 Oct 2025 12:49:03 +0100 Subject: [PATCH] R3 --- codex-rs/core/src/executor/runner.rs | 33 ------------- codex-rs/core/src/unified_exec/mod.rs | 68 ++++++++++++++++++++------- 2 files changed, 51 insertions(+), 50 deletions(-) diff --git a/codex-rs/core/src/executor/runner.rs b/codex-rs/core/src/executor/runner.rs index a2278b44a8..9e26c6efd6 100644 --- a/codex-rs/core/src/executor/runner.rs +++ b/codex-rs/core/src/executor/runner.rs @@ -27,8 +27,6 @@ use crate::executor::sandbox::select_sandbox; use crate::function_tool::FunctionCallError; use crate::protocol::AskForApproval; use crate::protocol::SandboxPolicy; -use crate::pty::SpawnedPty; -use crate::pty::spawn_pty_process; use crate::shell; use crate::tools::context::ExecCommandContext; @@ -126,22 +124,6 @@ impl ExecutionPlan { &self.request.approval_command } - pub(crate) async fn spawn_interactive_session( - &self, - session: &Session, - ) -> Result<(SpawnedPty, SandboxType), ExecError> { - self.attempt_with_retry(session, |launch| async move { - let sandbox_type = launch.sandbox_type; - let spawned = spawn_pty_process(&launch.program, &launch.args, &launch.env) - .await - .map_err(|err| { - ExecError::rejection(format!("failed to spawn interactive command: {err}")) - })?; - Ok((spawned, sandbox_type)) - }) - .await - } - pub(crate) async fn prompt_retry_without_sandbox( &self, session: &Session, @@ -168,21 +150,6 @@ impl ExecutionPlan { approval.is_some() } - /// Runs the provided attempt with the initially selected sandbox. - /// If it fails and policy allows, prompt to retry without sandbox and run again. - pub(crate) async fn attempt_with_retry( - &self, - session: &Session, - attempt: Attempt, - ) -> Result - where - Attempt: Fn(SandboxLaunch) -> Fut, - Fut: Future>, - E: From + std::fmt::Display, - { - self.attempt_with_retry_if(session, attempt, |_| true).await - } - /// Like `attempt_with_retry`, but only retries if `should_retry(err)` returns true. pub(crate) async fn attempt_with_retry_if( &self, diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index b8fb544482..222384b1cf 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -58,11 +58,12 @@ pub(crate) struct UnifiedExecResult { #[derive(Debug, Default)] pub(crate) struct UnifiedExecSessionManager { next_session_id: AtomicI32, - sessions: Mutex>, + sessions: Mutex>, } #[derive(Debug)] -struct ManagedUnifiedExecSession { +/// Wraps a PTY session with buffered output and sandbox metadata for unified exec. +struct UnifiedExecSession { session: ExecCommandSession, output_buffer: OutputBuffer, /// Notifies waiters whenever new output has been appended to @@ -118,7 +119,7 @@ impl OutputBufferState { type OutputBuffer = Arc>; type OutputHandles = (OutputBuffer, Arc); -impl ManagedUnifiedExecSession { +impl UnifiedExecSession { fn new( session: ExecCommandSession, initial_output_rx: tokio::sync::broadcast::Receiver>, @@ -191,7 +192,9 @@ impl ManagedUnifiedExecSession { return Ok(()); } - tokio::time::sleep(Duration::from_millis(20)).await; + // Give the reader task a brief moment to flush any final PTY bytes after exit. + let _ = + tokio::time::timeout(Duration::from_millis(20), self.output_notify.notified()).await; let collected_chunks = self.snapshot_output().await; let mut aggregated: Vec = Vec::new(); @@ -247,7 +250,7 @@ impl ManagedUnifiedExecSession { } } -impl Drop for ManagedUnifiedExecSession { +impl Drop for UnifiedExecSession { fn drop(&mut self) { self.output_task.abort(); } @@ -258,7 +261,7 @@ impl UnifiedExecSessionManager { &self, command: Vec, context: &UnifiedExecContext<'_>, - ) -> Result { + ) -> Result { let executor = &context.session.services.executor; let otel_event_manager = context.turn.client.get_otel_event_manager(); let approval_command = command.clone(); @@ -303,12 +306,19 @@ impl UnifiedExecSessionManager { .await .map_err(|err| UnifiedExecError::create_session(err.to_string()))?; - let (spawned, sandbox_type) = plan - .spawn_interactive_session(context.session) - .await - .map_err(|err| UnifiedExecError::create_session(err.to_string()))?; - - ManagedUnifiedExecSession::from_spawned(spawned, sandbox_type).await + plan.attempt_with_retry_if( + context.session, + |launch| async move { + let sandbox_type = launch.sandbox_type; + let spawned = + crate::pty::spawn_pty_process(&launch.program, &launch.args, &launch.env) + .await + .map_err(|err| UnifiedExecError::create_session(err.to_string()))?; + UnifiedExecSession::from_spawned(spawned, sandbox_type).await + }, + |err: &UnifiedExecError| matches!(err, UnifiedExecError::SandboxDenied { .. }), + ) + .await } pub async fn handle_request( @@ -327,7 +337,7 @@ impl UnifiedExecSessionManager { None => (DEFAULT_TIMEOUT_MS, None), }; - let mut new_session: Option = None; + let mut new_session: Option = None; let session_id; let writer_tx; let output_buffer; @@ -369,10 +379,34 @@ impl UnifiedExecSessionManager { }; if context.session_id.is_some() { - let joined_input = request.input_chunks.join(" "); - if !joined_input.is_empty() && writer_tx.send(joined_input.into_bytes()).await.is_err() - { - return Err(UnifiedExecError::WriteToStdin); + let mut trailing_whitespace = true; + for chunk in request.input_chunks { + if chunk.is_empty() { + continue; + } + + let leading_whitespace = chunk + .chars() + .next() + .map(char::is_whitespace) + .unwrap_or(true); + + if !trailing_whitespace + && !leading_whitespace + && writer_tx.send(vec![b' ']).await.is_err() + { + return Err(UnifiedExecError::WriteToStdin); + } + + if writer_tx.send(chunk.as_bytes().to_vec()).await.is_err() { + return Err(UnifiedExecError::WriteToStdin); + } + + trailing_whitespace = chunk + .chars() + .next_back() + .map(char::is_whitespace) + .unwrap_or(trailing_whitespace); } }