aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,455 @@
use akode_protocol::openai_models::CatalogModel;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use tokio::sync::Mutex;
use tokio::time::Duration;
use tokio::time::Instant;
use tokio::time::Sleep;
use super::UnifiedExecContext;
use super::process::OutputBuffers;
use super::process::OutputHandles;
use super::process::UnifiedExecProcess;
use crate::exec::MAX_EXEC_OUTPUT_DELTAS_PER_CALL;
use crate::session::session::Session;
use crate::session::turn_context::TurnContext;
use crate::tools::events::ToolEmitter;
use crate::tools::events::ToolEventCtx;
use crate::tools::events::ToolEventFailure;
use crate::tools::events::ToolEventStage;
use akode_core_plugins::PluginCommandAttribution;
use akode_protocol::exec_output::ExecToolCallOutput;
use akode_protocol::exec_output::StreamOutput;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::ExecCommandOutputDeltaEvent;
use akode_protocol::protocol::ExecCommandSource;
use akode_protocol::protocol::ExecOutputStream;
use akode_utils_path_uri::PathUri;
pub(crate) const TRAILING_OUTPUT_GRACE: Duration = Duration::from_millis(100);
/// Upper bound for a single ExecCommandOutputDelta chunk emitted by unified exec.
///
/// The unified exec output buffer already caps *retained* output (see
/// `UNIFIED_EXEC_OUTPUT_MAX_BYTES`), but we also cap per-event payload size so
/// downstream event consumers (especially app-server JSON-RPC) don't have to
/// process arbitrarily large delta payloads.
const UNIFIED_EXEC_OUTPUT_DELTA_MAX_BYTES: usize = 8192;
struct Emitter {
remaining_deltas: usize,
session: Arc<Session>,
turn: Arc<TurnContext>,
call_id: String,
}
struct Buffer<const MAX_BYTES: usize = UNIFIED_EXEC_OUTPUT_DELTA_MAX_BYTES> {
pending: Vec<u8>,
emitter: Emitter,
}
/// Spawn a background task that emits ExecCommandOutputDelta events on UTF‑8 boundaries.
pub(crate) fn start_streaming_output(process: &UnifiedExecProcess, context: &UnifiedExecContext) {
let mut receiver = process.output_receiver();
let output_drained = process.output_drained_notify();
let exit_token = process.cancellation_token();
let OutputHandles {
output_closed,
output_closed_notify,
..
} = process.output_handles().clone();
let emitter = Emitter {
remaining_deltas: MAX_EXEC_OUTPUT_DELTAS_PER_CALL,
session: Arc::clone(&context.session),
turn: Arc::clone(&context.step_context.turn),
call_id: context.call_id.clone(),
};
tokio::spawn(async move {
use tokio::sync::broadcast::error::RecvError;
let mut output: Buffer = Buffer {
pending: Vec::new(),
emitter,
};
let mut grace_sleep: Option<Pin<Box<Sleep>>> = None;
let output_closed_notified = output_closed_notify.notified();
tokio::pin!(output_closed_notified);
let mut output_complete = false;
loop {
// Register before checking the atomic so a close between the check
// and the select cannot miss the notification.
output_closed_notified.as_mut().enable();
if grace_sleep.is_some() && output_closed.load(Ordering::Acquire) {
output_complete = true;
break;
}
tokio::select! {
_ = exit_token.cancelled(), if grace_sleep.is_none() => {
let deadline = Instant::now() + TRAILING_OUTPUT_GRACE;
grace_sleep.replace(Box::pin(tokio::time::sleep_until(deadline)));
}
_ = async {
if let Some(sleep) = grace_sleep.as_mut() {
sleep.as_mut().await;
}
}, if grace_sleep.is_some() => {
break;
}
_ = &mut output_closed_notified, if grace_sleep.is_some() => {
output_closed_notified.set(output_closed_notify.notified());
}
received = receiver.recv() => {
let chunk = match received {
Ok(chunk) => chunk,
Err(RecvError::Lagged(_)) => {
continue;
},
Err(RecvError::Closed) => {
output_complete = true;
break;
}
};
output.push(chunk).await;
}
}
}
output_complete |= output_closed.load(Ordering::Acquire);
if output_complete {
// Output producers publish all chunks before setting output_closed
// with Release ordering, so the Acquire above makes this a final
// safe drain.
loop {
let chunk = match receiver.try_recv() {
Ok(chunk) => chunk,
Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) => continue,
Err(
tokio::sync::broadcast::error::TryRecvError::Empty
| tokio::sync::broadcast::error::TryRecvError::Closed,
) => break,
};
output.push(chunk).await;
}
}
output.finish().await;
output_drained.notify_one();
});
}
/// Spawn a background watcher that waits for the PTY to exit and then emits a
/// single ExecCommandEnd event with the aggregated transcript.
#[allow(clippy::too_many_arguments)]
pub(crate) fn spawn_exit_watcher(
process: Arc<UnifiedExecProcess>,
context: &UnifiedExecContext,
command: Vec<String>,
cwd: PathUri,
process_id: i32,
plugin_attribution: Option<PluginCommandAttribution>,
output_buffer: Arc<Mutex<OutputBuffers>>,
started_at: Instant,
network_denial_monitor: Option<tokio::task::JoinHandle<()>>,
) {
let session_ref = Arc::clone(&context.session);
let turn_ref = Arc::clone(&context.step_context.turn);
let model_info = Arc::clone(&context.step_context.settings.model_info);
let call_id = context.call_id.clone();
let exit_token = process.cancellation_token();
let output_drained = process.output_drained_notify();
let interaction_lock = process.interaction_lock();
tokio::spawn(async move {
exit_token.cancelled().await;
output_drained.notified().await;
// Deferred network denial deliberately remains observable for a short
// window after process exit. Do not classify the terminal event until
// that monitor has settled, even when output closes immediately.
if let Some(network_denial_monitor) = network_denial_monitor {
let _ = network_denial_monitor.await;
}
let _interaction_guard = interaction_lock.lock_owned().await;
let duration = Instant::now().saturating_duration_since(started_at);
if let Some(message) = process.failure_message() {
emit_failed_exec_end_for_unified_exec(
process.sandbox_type(),
session_ref,
turn_ref,
model_info,
call_id,
command,
cwd,
Some(process_id.to_string()),
plugin_attribution,
output_buffer,
String::new(),
message,
duration,
)
.await;
} else {
let exit_code = process.exit_code().unwrap_or(-1);
let timed_out = process.timed_out();
emit_exec_end_for_unified_exec(
process.sandbox_type(),
session_ref,
turn_ref,
model_info,
call_id,
command,
cwd,
Some(process_id.to_string()),
plugin_attribution,
output_buffer,
String::new(),
exit_code,
duration,
timed_out,
)
.await;
}
});
}
impl<const MAX_BYTES: usize> Buffer<MAX_BYTES> {
async fn push(&mut self, mut bytes: Vec<u8>) {
const {
assert!(
MAX_BYTES >= char::MAX.len_utf8(),
"a frame must fit one UTF-8 scalar"
)
};
let Self { pending, emitter } = self;
// Reuse a producer chunk when it fits, retaining only an incomplete
// UTF-8 suffix for the next push.
if pending.is_empty() && bytes.len() <= MAX_BYTES {
emitter
.emit(|| {
let complete = utf8_boundary(&bytes);
pending.extend(bytes.drain(complete..));
bytes
})
.await;
return;
}
let mut bytes = bytes.as_slice();
let mut next_chunk = || {
let space = MAX_BYTES.saturating_sub(pending.len());
let (prefix, rest) = bytes.split_at_checked(space).unwrap_or((bytes, &[]));
let mut chunk = Vec::with_capacity(pending.len().saturating_add(prefix.len()));
chunk.append(pending); // Empties pending.
chunk.extend_from_slice(prefix);
bytes = rest;
let complete = utf8_boundary(&chunk);
// Only the incomplete suffix passes through pending.
pending.extend(chunk.drain(complete..));
chunk
};
while emitter.emit(&mut next_chunk).await {}
}
async fn finish(self) {
let Self {
pending,
mut emitter,
} = self;
debug_assert!(
pending.len() < char::MAX.len_utf8(),
"only an incomplete UTF-8 scalar can remain"
);
emitter.emit(|| pending).await;
}
}
impl Emitter {
/// Build a frame only while quota remains. Returns whether a nonempty frame was sent.
async fn emit(&mut self, make_chunk: impl FnOnce() -> Vec<u8>) -> bool {
let Self {
remaining_deltas,
session,
turn,
call_id,
} = self;
let Some(remaining) = remaining_deltas.checked_sub(1) else {
return false;
};
let chunk = make_chunk();
let emit = !chunk.is_empty();
if emit {
let event = ExecCommandOutputDeltaEvent {
call_id: call_id.clone(),
stream: ExecOutputStream::Stdout,
chunk,
};
session
.send_event(turn.as_ref(), EventMsg::ExecCommandOutputDelta(event))
.await;
*remaining_deltas = remaining;
}
emit
}
}
/// Emit an ExecCommandEnd event for a unified exec session, using the transcript
/// as the primary source of aggregated_output and falling back to the provided
/// text when the transcript is empty.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn emit_exec_end_for_unified_exec(
sandbox_type: Option<akode_protocol::sandbox::SandboxType>,
session_ref: Arc<Session>,
turn_ref: Arc<TurnContext>,
model_info: Arc<CatalogModel>,
call_id: String,
command: Vec<String>,
cwd: PathUri,
process_id: Option<String>,
plugin_attribution: Option<PluginCommandAttribution>,
output_buffer: Arc<Mutex<OutputBuffers>>,
fallback_output: String,
exit_code: i32,
duration: Duration,
timed_out: bool,
) {
let aggregated_output = resolve_aggregated_output(&output_buffer, fallback_output).await;
let output = ExecToolCallOutput {
exit_code,
stdout: StreamOutput::new(aggregated_output.clone()),
stderr: StreamOutput::new(String::new()),
aggregated_output: StreamOutput::new(aggregated_output),
duration,
timed_out,
};
let mut event_ctx = ToolEventCtx::new(
session_ref.as_ref(),
turn_ref.as_ref(),
&model_info,
&call_id,
/*turn_diff_tracker*/ None,
);
event_ctx.sandbox_type = sandbox_type;
let emitter = ToolEmitter::unified_exec(
&command,
cwd,
ExecCommandSource::UnifiedExecStartup,
process_id,
plugin_attribution,
);
emitter
.emit(
event_ctx,
ToolEventStage::Success {
output,
applied_patch_delta: None,
},
)
.await;
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn emit_failed_exec_end_for_unified_exec(
sandbox_type: Option<akode_protocol::sandbox::SandboxType>,
session_ref: Arc<Session>,
turn_ref: Arc<TurnContext>,
model_info: Arc<CatalogModel>,
call_id: String,
command: Vec<String>,
cwd: PathUri,
process_id: Option<String>,
plugin_attribution: Option<PluginCommandAttribution>,
output_buffer: Arc<Mutex<OutputBuffers>>,
fallback_output: String,
message: String,
duration: Duration,
) {
let stdout = if fallback_output.is_empty() {
resolve_aggregated_output(&output_buffer, fallback_output).await
} else {
fallback_output
};
let aggregated_output = if stdout.is_empty() {
message.clone()
} else {
format!("{stdout}\n{message}")
};
let output = ExecToolCallOutput {
exit_code: -1,
stdout: StreamOutput::new(stdout),
stderr: StreamOutput::new(message),
aggregated_output: StreamOutput::new(aggregated_output),
duration,
timed_out: false,
};
let mut event_ctx = ToolEventCtx::new(
session_ref.as_ref(),
turn_ref.as_ref(),
&model_info,
&call_id,
/*turn_diff_tracker*/ None,
);
event_ctx.sandbox_type = sandbox_type;
let emitter = ToolEmitter::unified_exec(
&command,
cwd,
ExecCommandSource::UnifiedExecStartup,
process_id,
plugin_attribution,
);
emitter
.emit(
event_ctx,
ToolEventStage::Failure(ToolEventFailure::Output(output)),
)
.await;
}
/// Keep only a potentially incomplete UTF-8 suffix; malformed bytes remain raw.
/// A UTF-8 scalar spans at most four bytes, so its incomplete tail fits in three.
fn utf8_boundary(bytes: &[u8]) -> usize {
let mut boundary = bytes.len().saturating_sub(char::MAX.len_utf8() - 1);
while boundary < bytes.len() {
match std::str::from_utf8(&bytes[boundary..]) {
Ok(s) => return boundary + s.len(),
Err(error) => {
boundary += error.valid_up_to();
if let Some(invalid_len) = error.error_len() {
boundary += invalid_len;
} else {
return boundary;
}
}
}
}
bytes.len()
}
async fn resolve_aggregated_output(
output_buffer: &Arc<Mutex<OutputBuffers>>,
fallback: String,
) -> String {
let guard = output_buffer.lock().await;
if guard.transcript.retained_bytes() == 0 {
return fallback;
}
String::from_utf8_lossy(&guard.transcript.to_bytes_with_omission_marker()).to_string()
}
#[cfg(test)]
#[path = "async_watcher_tests.rs"]
mod tests;

View File

@@ -0,0 +1,420 @@
use std::sync::Arc;
use super::Buffer;
use super::Emitter;
use super::TRAILING_OUTPUT_GRACE;
use super::spawn_exit_watcher;
use super::start_streaming_output;
use super::utf8_boundary;
use crate::session::tests::make_session_and_context_with_rx;
use crate::unified_exec::UnifiedExecContext;
use crate::unified_exec::UnifiedExecProcessManager;
use crate::unified_exec::process::OutputBuffers;
use crate::unified_exec::process::UnifiedExecProcess;
use akode_protocol::items::CommandExecutionStatus;
use akode_protocol::items::TurnItem;
use akode_protocol::protocol::Event;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::ExecCommandOutputDeltaEvent;
use akode_protocol::protocol::ExecOutputStream;
use akode_sandboxing::SandboxType;
use pretty_assertions::assert_eq;
use tokio::time::Duration;
use tokio::time::Instant;
struct StreamingOutputHarness {
process: Arc<UnifiedExecProcess>,
stdout_tx: tokio::sync::broadcast::Sender<Vec<u8>>,
exit_tx: tokio::sync::oneshot::Sender<i32>,
output_buffer: Arc<tokio::sync::Mutex<OutputBuffers>>,
context: UnifiedExecContext,
rx_event: async_channel::Receiver<Event>,
}
async fn streaming_output_harness() -> anyhow::Result<StreamingOutputHarness> {
let (writer_tx, _writer_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(1);
let (stdout_tx, stdout_rx) = tokio::sync::broadcast::channel::<Vec<u8>>(8);
let (exit_tx, exit_rx) = tokio::sync::oneshot::channel::<i32>();
let spawned = akode_utils_pty::spawn_from_driver(akode_utils_pty::ProcessDriver {
writer_tx,
stdout_rx,
stderr_rx: None,
exit_rx,
terminator: None,
writer_handle: None,
resizer: None,
#[cfg(windows)]
tty: false,
});
let process = Arc::new(UnifiedExecProcess::from_spawned(spawned, SandboxType::None).await?);
let (session, turn, rx_event) = make_session_and_context_with_rx().await;
let context = UnifiedExecContext::new(
session,
crate::session::step_context::StepContext::for_test(turn),
tokio_util::sync::CancellationToken::new(),
"streaming-output-test".to_string(),
);
let output_buffer = Arc::clone(&process.output_handles().output_buffer);
Ok(StreamingOutputHarness {
process,
stdout_tx,
exit_tx,
output_buffer,
context,
rx_event,
})
}
#[test_case::test_case(b""; "no_late_output")]
#[test_case::test_case(b"late\n"; "with_late_output")]
#[tokio::test]
async fn completed_output_preserves_bytes_before_subscription(
late_output: &[u8],
) -> anyhow::Result<()> {
let StreamingOutputHarness {
process,
stdout_tx,
exit_tx,
output_buffer,
context,
rx_event,
} = streaming_output_harness().await?;
let collected = process.output_handles().output_notify.notified();
tokio::pin!(collected);
collected.as_mut().enable();
stdout_tx.send(b"early\n".to_vec())?;
collected.await;
let model_output = UnifiedExecProcessManager::collect_output_until_deadline(
process.output_handles(),
/*pause_state*/ None,
Instant::now(),
)
.await;
assert_eq!(model_output.to_bytes(), b"early\n");
start_streaming_output(&process, &context);
#[allow(deprecated)]
let cwd = context.step_context.turn.cwd.clone().into();
spawn_exit_watcher(
Arc::clone(&process),
&context,
vec!["proof".to_string()],
cwd,
/*process_id*/ 123,
/*plugin_attribution*/ None,
output_buffer,
Instant::now(),
/*network_denial_monitor*/ None,
);
stdout_tx.send(late_output.to_vec())?;
drop(stdout_tx);
exit_tx.send(0).expect("send exit");
let item = tokio::time::timeout(Duration::from_secs(2), async {
loop {
if let EventMsg::ItemCompleted(completed) = rx_event.recv().await?.msg
&& let TurnItem::CommandExecution(item) = completed.item
{
return Ok::<_, async_channel::RecvError>(item);
}
}
})
.await??;
let expected_output = String::from_utf8([b"early\n".as_slice(), late_output].concat())?;
assert_eq!(
(item.status, item.exit_code, item.aggregated_output),
(
CommandExecutionStatus::Completed,
Some(0),
Some(expected_output)
)
);
Ok(())
}
#[tokio::test]
async fn streaming_output_preserves_multibyte_characters_across_chunks() -> anyhow::Result<()> {
let StreamingOutputHarness {
process,
stdout_tx,
exit_tx,
output_buffer,
rx_event,
context,
} = streaming_output_harness().await?;
start_streaming_output(&process, &context);
let output_drained = process.output_drained_notify();
let drained = output_drained.notified();
tokio::pin!(drained);
stdout_tx.send(vec![0xc3]).expect("send UTF-8 lead byte");
stdout_tx
.send(vec![0xa9])
.expect("send UTF-8 continuation byte");
drop(stdout_tx);
exit_tx.send(0).expect("send exit");
(&mut drained).await;
let event = rx_event.recv().await.expect("receive output delta");
let EventMsg::ExecCommandOutputDelta(delta) = event.msg else {
panic!("expected ExecCommandOutputDelta");
};
assert_eq!(
delta,
ExecCommandOutputDeltaEvent {
call_id: "streaming-output-test".to_string(),
stream: ExecOutputStream::Stdout,
chunk: "é".as_bytes().to_vec(),
}
);
assert_eq!(
output_buffer
.lock()
.await
.transcript
.to_bytes_with_omission_marker(),
"é".as_bytes()
);
assert!(rx_event.try_recv().is_err());
Ok(())
}
#[tokio::test]
async fn streaming_output_finishes_on_close_without_waiting_for_grace() -> anyhow::Result<()> {
let StreamingOutputHarness {
process,
stdout_tx,
exit_tx,
output_buffer,
context,
..
} = streaming_output_harness().await?;
start_streaming_output(&process, &context);
let output_drained = process.output_drained_notify();
let drained = output_drained.notified();
tokio::pin!(drained);
tokio::time::pause();
let exited_at = Instant::now();
exit_tx.send(0).expect("send exit");
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(50)).await;
stdout_tx
.send(b"LATE-OUTPUT-MARKER\xc3".to_vec())
.expect("send late output");
});
(&mut drained).await;
let elapsed = Instant::now().saturating_duration_since(exited_at);
tokio::time::resume();
assert!(
elapsed >= Duration::from_millis(50) && elapsed < TRAILING_OUTPUT_GRACE,
"output close should finish before the grace fallback: {elapsed:?}"
);
assert_eq!(
output_buffer
.lock()
.await
.transcript
.to_bytes_with_omission_marker(),
b"LATE-OUTPUT-MARKER\xc3"
);
Ok(())
}
#[tokio::test]
async fn streaming_output_keeps_grace_as_fallback_without_close() -> anyhow::Result<()> {
let StreamingOutputHarness {
process,
stdout_tx,
exit_tx,
output_buffer,
rx_event,
context,
} = streaming_output_harness().await?;
start_streaming_output(&process, &context);
let output_drained = process.output_drained_notify();
let drained = output_drained.notified();
tokio::pin!(drained);
tokio::time::pause();
let exited_at = Instant::now();
stdout_tx.send(vec![0xc3]).expect("send UTF-8 lead byte");
exit_tx.send(0).expect("send exit");
(&mut drained).await;
let elapsed = Instant::now().saturating_duration_since(exited_at);
tokio::time::resume();
assert!(
elapsed >= TRAILING_OUTPUT_GRACE
&& elapsed <= TRAILING_OUTPUT_GRACE + Duration::from_millis(10),
"missing output close should use the grace fallback: {elapsed:?}"
);
assert_eq!(
output_buffer
.lock()
.await
.transcript
.to_bytes_with_omission_marker(),
vec![0xc3]
);
let event = rx_event.try_recv().expect("receive final output delta");
let EventMsg::ExecCommandOutputDelta(delta) = event.msg else {
panic!("expected ExecCommandOutputDelta");
};
assert_eq!(
delta,
ExecCommandOutputDeltaEvent {
call_id: "streaming-output-test".to_string(),
stream: ExecOutputStream::Stdout,
chunk: vec![0xc3],
}
);
assert!(rx_event.try_recv().is_err());
Ok(())
}
#[tokio::test]
async fn exit_watcher_waits_for_late_network_denial_before_classifying_end() -> anyhow::Result<()> {
let StreamingOutputHarness {
process,
stdout_tx,
exit_tx,
output_buffer,
mut context,
rx_event,
} = streaming_output_harness().await?;
start_streaming_output(&process, &context);
tokio::time::pause();
let process_for_late_denial = Arc::clone(&process);
let (late_denial_armed_tx, late_denial_armed_rx) = tokio::sync::oneshot::channel();
let network_denial_monitor = tokio::spawn(async move {
let sleep = tokio::time::sleep(Duration::from_millis(10));
tokio::pin!(sleep);
late_denial_armed_tx.send(()).expect("arm late denial");
sleep.await;
process_for_late_denial.fail_and_terminate("LATE_DENIAL".to_string());
});
late_denial_armed_rx.await.expect("late denial armed");
#[allow(deprecated)]
let cwd = context.step_context.turn.cwd.clone().into();
let step = Arc::get_mut(&mut context.step_context).expect("unshared test step");
let model_info = Arc::make_mut(&mut Arc::make_mut(&mut step.settings).model_info);
model_info.truncation_policy = akode_protocol::openai_models::TruncationPolicyConfig {
mode: akode_protocol::openai_models::TruncationMode::Bytes,
limit: 4,
};
spawn_exit_watcher(
Arc::clone(&process),
&context,
vec!["proof".to_string()],
cwd,
/*process_id*/ 123,
/*plugin_attribution*/ None,
output_buffer,
Instant::now(),
Some(network_denial_monitor),
);
let exited_at = Instant::now();
exit_tx.send(0).expect("send exit");
drop(stdout_tx);
let event = rx_event.recv().await.expect("command end event");
let elapsed = Instant::now().saturating_duration_since(exited_at);
tokio::time::resume();
let EventMsg::ItemCompleted(completed) = event.msg else {
panic!("expected ItemCompleted");
};
let TurnItem::CommandExecution(item) = completed.item else {
panic!("expected CommandExecution");
};
assert_eq!(
(
item.status,
item.exit_code,
item.aggregated_output.as_deref()
),
(
CommandExecutionStatus::Failed,
Some(-1),
Some("LATE_DENIAL")
)
);
assert!(
elapsed >= Duration::from_millis(10) && elapsed < TRAILING_OUTPUT_GRACE,
"completion should wait for denial without falling back to the output grace: {elapsed:?}"
);
Ok(())
}
#[test]
fn utf8_boundary_preserves_complete_characters() {
assert_eq!(utf8_boundary(b"hello"), 5);
let bytes = "ééé".as_bytes();
assert_eq!(utf8_boundary(&bytes[..3]), 2);
let bytes = "😀".as_bytes();
assert_eq!(utf8_boundary(bytes), bytes.len());
for len in 1..bytes.len() {
assert_eq!(utf8_boundary(&bytes[..len]), 0);
}
assert_eq!(utf8_boundary(&[0xf0, 0x9f, 0x98, 0x80, 0xc3]), 4);
}
#[test]
fn utf8_boundary_batches_malformed_output() {
assert_eq!(utf8_boundary(&[0xff, b'a', b'b']), 3);
assert_eq!(utf8_boundary(&[0xff, 0xc3]), 1);
assert_eq!(utf8_boundary(&[0xff, 0xc3, 0xa9]), 3);
assert_eq!(utf8_boundary(&[0xe0, 0x80]), 2);
assert_eq!(utf8_boundary(b"a\xffbbb"), 5);
}
#[tokio::test]
async fn streaming_output_bounds_invalid_bytes() {
let (session, turn, rx_event) = make_session_and_context_with_rx().await;
let mut output = Buffer::<8> {
pending: Vec::new(),
emitter: Emitter {
remaining_deltas: 2,
session,
turn,
call_id: "bounded-output-test".to_string(),
},
};
// The first frame splits 😀; the last allowed frame leaves é incomplete.
let bytes = b"\xff\xff\xff\xff\xff\xff\xf0\x9f\x98\x80\xff\xff\xff\xc3\xa9";
output.push(bytes.to_vec()).await;
output.push(vec![0xfe, 0xfe]).await;
output.finish().await;
let mut chunks = Vec::new();
while let Ok(event) = rx_event.try_recv() {
let EventMsg::ExecCommandOutputDelta(delta) = event.msg else {
panic!("expected ExecCommandOutputDelta");
};
chunks.push(delta.chunk);
}
assert_eq!(
chunks,
vec![
b"\xff\xff\xff\xff\xff\xff".to_vec(),
b"\xf0\x9f\x98\x80\xff\xff\xff".to_vec(),
]
);
}

View File

@@ -0,0 +1,29 @@
//! Read-only snapshots of retained command sessions, including uncollected exits.
//! Handles stay private until their initial exec_command collection finishes.
use super::UnifiedExecProcessManager;
use crate::context::world_state::CommandSession;
use crate::context::world_state::CommandSessionStatus;
use crate::context::world_state::CommandSessionsState;
use std::sync::atomic::Ordering;
pub(crate) async fn command_sessions_state(
manager: &UnifiedExecProcessManager,
) -> CommandSessionsState {
let store = manager.process_store.lock().await;
CommandSessionsState::new(
store
.processes
.values()
.filter(|entry| !entry.initial_exec_command_active.load(Ordering::Acquire))
.map(|entry| CommandSession {
session_id: entry.process_id,
status: if entry.process.has_exited() {
CommandSessionStatus::Exited
} else {
CommandSessionStatus::Running
},
in_use: entry.process.interaction_lock().try_lock_owned().is_err(),
}),
)
}

View File

@@ -0,0 +1,71 @@
use akode_protocol::exec_output::ExecToolCallOutput;
use akode_utils_path_uri::PathUri;
use std::num::NonZeroUsize;
use thiserror::Error;
#[derive(Debug, Error)]
pub(crate) enum UnifiedExecError {
#[error("Failed to create unified exec process: {message}")]
CreateProcess { message: String },
#[error("Unified exec process failed: {message}")]
ProcessFailed { message: String },
// The model is trained on `session_id`, but internally we track a `process_id`.
#[error("Unknown process id {process_id}")]
UnknownProcessId { process_id: i32 },
#[error("stdin approval failed: {0:?}")]
StdinApproval(crate::tools::sandboxing::ToolError),
#[error("failed to write to stdin")]
WriteToStdin,
#[error(
"stdin is closed for this session; rerun exec_command with tty=true to keep stdin open"
)]
StdinClosed,
#[error("missing command line for unified exec request")]
MissingCommandLine,
#[error("Command denied by sandbox: {message}")]
SandboxDenied {
message: String,
output: ExecToolCallOutput,
original_token_count: Option<usize>,
output_omitted_bytes: Option<NonZeroUsize>,
},
#[error("{path} is not valid on {}", std::env::consts::OS)]
ForeignPath { path: PathUri },
}
impl UnifiedExecError {
pub(crate) fn create_process(message: String) -> Self {
Self::CreateProcess { message }
}
pub(crate) fn process_failed(message: String) -> Self {
Self::ProcessFailed { message }
}
pub(crate) fn sandbox_denied(message: String, output: ExecToolCallOutput) -> Self {
Self::SandboxDenied {
message,
output,
original_token_count: None,
output_omitted_bytes: None,
}
}
pub(crate) fn with_output_collection_metadata(
self,
original_token_count: usize,
output_omitted_bytes: Option<NonZeroUsize>,
) -> Self {
match self {
Self::SandboxDenied {
message, output, ..
} => Self::SandboxDenied {
message,
output,
original_token_count: Some(original_token_count),
output_omitted_bytes,
},
other => other,
}
}
}

View File

@@ -0,0 +1,222 @@
//! Unified Exec: interactive process execution orchestrated with approvals + sandboxing.
//!
//! Responsibilities
//! - Manages interactive processes (create, reuse, buffer output with caps).
//! - Supports completion-only calls that terminate on timeout or cancellation.
//! - Uses the shared ToolOrchestrator to handle approval, sandbox selection, and
//! retry semantics in a single, descriptive flow.
//! - Spawns the PTY from a sandbox-transformed `ExecRequest`; on sandbox denial,
//! retries without sandbox when policy allows (no re‑prompt thanks to caching).
//! - Uses the shared `is_likely_sandbox_denied` heuristic to keep denial messages
//! consistent with other exec paths.
//!
//! Flow at a glance (open process)
//! 1) Build a small request `{ command, cwd }`.
//! 2) Orchestrator: approval (bypass/cache/prompt) → select sandbox → run.
//! 3) Runtime: transform `SandboxTransformRequest` -> `ExecRequest` -> spawn PTY.
//! 4) If denial, orchestrator retries with `SandboxType::None`.
//! 5) Process handle is returned with streaming output + metadata.
//!
//! This keeps policy logic and user interaction centralized while the PTY/process
//! concerns remain isolated here. The implementation is split between:
//! - `process.rs`: PTY process lifecycle + output buffering.
//! - `process_state.rs`: shared exit/failure state for local and remote processes.
//! - `process_manager.rs`: orchestration (approvals, sandboxing, reuse) and request handling.
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Weak;
use akode_network_proxy::NetworkProxy;
use akode_utils_output_truncation::TruncationPolicy;
use akode_utils_path_uri::PathUri;
use rand::Rng;
use rand::rng;
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
use crate::session::session::Session;
use crate::session::step_context::StepContext;
use crate::session::turn_context::TurnContext;
use crate::tools::handlers::unified_exec::preparation::PreparedExecCommand;
use crate::tools::network_approval::DeferredNetworkApproval;
mod async_watcher;
mod command_sessions;
mod errors;
mod oneshot;
pub(crate) mod output;
mod process;
mod process_manager;
pub(crate) use process_manager::exec_env_policy_from_shell_policy;
mod process_state;
mod shell_snapshot;
mod stdin_approval;
pub(crate) fn set_deterministic_process_ids_for_tests(enabled: bool) {
process_manager::set_deterministic_process_ids_for_tests(enabled);
}
pub(crate) use command_sessions::command_sessions_state;
pub(crate) use errors::UnifiedExecError;
pub(crate) use process::UnifiedExecProcess;
pub(crate) use stdin_approval::TerminalPermissions;
pub(crate) use stdin_approval::TerminalSandboxSource;
pub(crate) const MIN_YIELD_TIME_MS: u64 = 250;
pub(crate) const WINDOWS_INITIAL_EXEC_YIELD_TIME_FLOOR_MS: u64 = 10_000;
// Minimum yield time for an empty `write_stdin`.
pub(crate) const MIN_EMPTY_YIELD_TIME_MS: u64 = 5_000;
pub(crate) const MAX_YIELD_TIME_MS: u64 = 30_000;
pub(crate) const DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS: u64 = 300_000;
pub(crate) const DEFAULT_MAX_OUTPUT_TOKENS: usize = 10_000;
pub(crate) const UNIFIED_EXEC_OUTPUT_MAX_BYTES: usize = 1024 * 1024; // 1 MiB
pub(crate) const UNIFIED_EXEC_OUTPUT_MAX_TOKENS: usize = UNIFIED_EXEC_OUTPUT_MAX_BYTES / 4;
pub(crate) const MAX_UNIFIED_EXEC_PROCESSES: usize = 64;
const MAX_TRACE_ID_BYTES: usize = 256;
fn trace_id(id: &str) -> Option<&str> {
(!id.is_empty() && id.len() <= MAX_TRACE_ID_BYTES).then_some(id)
}
pub(crate) struct UnifiedExecContext {
pub session: Arc<Session>,
pub step_context: Arc<StepContext>,
pub cancellation_token: CancellationToken,
pub call_id: String,
}
impl UnifiedExecContext {
pub fn new(
session: Arc<Session>,
step_context: Arc<StepContext>,
cancellation_token: CancellationToken,
call_id: String,
) -> Self {
Self {
session,
step_context,
cancellation_token,
call_id,
}
}
}
#[derive(Debug)]
pub(crate) struct ExecCommandRequest {
pub prepared: PreparedExecCommand,
pub process_id: i32,
pub network: Option<NetworkProxy>,
}
/// The process and environment behind a terminal session ID at the time of lookup.
#[derive(Clone, Debug)]
pub(crate) struct TerminalSession {
pub(crate) process_id: i32,
process: Arc<UnifiedExecProcess>,
call_id: String,
pub(crate) environment_id: String,
}
#[derive(Debug)]
pub(crate) struct WriteStdinRequest<'a> {
pub terminal: &'a TerminalSession,
pub input: &'a str,
pub yield_time_ms: u64,
pub max_output_tokens: Option<usize>,
pub truncation_policy: TruncationPolicy,
pub interaction_event: Option<WriteStdinInteractionEvent<'a>>,
}
pub(crate) struct WriteStdinInteractionEvent<'a> {
pub session: &'a Arc<Session>,
pub turn: &'a Arc<TurnContext>,
}
impl std::fmt::Debug for WriteStdinInteractionEvent<'_> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("WriteStdinInteractionEvent")
}
}
#[derive(Default)]
pub(crate) struct ProcessStore {
processes: HashMap<i32, ProcessEntry>,
reserved_process_ids: HashSet<i32>,
}
impl ProcessStore {
fn remove(&mut self, process_id: i32) -> Option<ProcessEntry> {
if !process_manager::should_use_deterministic_process_ids() {
self.reserved_process_ids.remove(&process_id);
}
self.processes.remove(&process_id)
}
}
pub(crate) struct UnifiedExecProcessManager {
process_store: Mutex<ProcessStore>,
max_write_stdin_yield_time_ms: u64,
}
impl UnifiedExecProcessManager {
pub(crate) fn new(max_write_stdin_yield_time_ms: u64) -> Self {
Self {
process_store: Mutex::new(ProcessStore::default()),
max_write_stdin_yield_time_ms: max_write_stdin_yield_time_ms
.max(MIN_EMPTY_YIELD_TIME_MS),
}
}
}
impl Default for UnifiedExecProcessManager {
fn default() -> Self {
Self::new(DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS)
}
}
struct ProcessEntry {
process: Arc<UnifiedExecProcess>,
call_id: String,
process_id: i32,
cwd: PathUri,
initial_exec_command_active: Arc<std::sync::atomic::AtomicBool>,
hook_command: String,
tty: bool,
environment_id: String,
permissions: TerminalPermissions,
network_approval: Option<DeferredNetworkApproval>,
session: Weak<Session>,
last_used: tokio::time::Instant,
}
pub(crate) fn clamp_yield_time(yield_time_ms: u64) -> u64 {
let yield_time_ms = if cfg!(windows) {
yield_time_ms.max(WINDOWS_INITIAL_EXEC_YIELD_TIME_FLOOR_MS)
} else {
yield_time_ms
};
yield_time_ms.clamp(MIN_YIELD_TIME_MS, MAX_YIELD_TIME_MS)
}
pub(crate) fn resolve_max_tokens(max_tokens: Option<usize>) -> usize {
max_tokens.unwrap_or(DEFAULT_MAX_OUTPUT_TOKENS)
}
pub(crate) fn generate_chunk_id() -> String {
let mut rng = rng();
(0..6)
.map(|_| format!("{:x}", rng.random_range(0..16)))
.collect()
}
#[cfg(test)]
#[cfg(unix)]
#[path = "process_tests.rs"]
mod process_tests;
#[cfg(test)]
#[cfg(unix)]
#[path = "mod_tests.rs"]
mod tests;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,125 @@
//! One-shot execution over the shared unified-exec lifecycle.
//!
//! The caller never receives a resumable process. Timeout and cancellation
//! terminate the exact process handle published by the normal startup path.
use std::sync::Arc;
use std::sync::OnceLock;
use tokio::time::Duration;
use tokio::time::Instant;
use tracing::Instrument;
use super::ExecCommandRequest;
use super::UnifiedExecContext;
use super::UnifiedExecError;
use super::UnifiedExecProcess;
use super::UnifiedExecProcessManager;
use super::trace_id;
use crate::tools::context::ExecCommandToolOutput;
pub(super) struct Completion<'a> {
pub timeout: Duration,
pub timed_out: bool,
pub process: &'a OnceLock<Arc<UnifiedExecProcess>>,
}
impl UnifiedExecProcessManager {
#[tracing::instrument(
name = "unified_exec.exec_command",
level = "info",
skip_all,
fields(
conversation.id = %context.session.thread_id,
turn_id = trace_id(&context.step_context.turn.sub_id),
call_id = trace_id(&context.call_id),
unified_exec_process_id = request.process_id,
mode = "oneshot",
outcome = tracing::field::Empty,
)
)]
pub(crate) async fn exec_command_to_completion(
request: ExecCommandRequest,
context: &UnifiedExecContext,
timeout: Duration,
) -> Result<ExecCommandToolOutput, UnifiedExecError> {
let context = UnifiedExecContext::new(
Arc::clone(&context.session),
Arc::clone(&context.step_context),
context.cancellation_token.child_token(),
context.call_id.clone(),
);
let _cancel_on_drop = context.cancellation_token.clone().drop_guard();
let task = async move {
let manager = &context.session.services.unified_exec_manager;
let process_id = request.process_id;
if Instant::now().checked_add(timeout).is_none() {
manager.release_process_id(process_id).await;
return (
Err(UnifiedExecError::process_failed(
"timeout_ms is too large".into(),
)),
"failed",
);
}
let process = OnceLock::new();
let mut completion = Completion {
timeout,
timed_out: false,
process: &process,
};
let result = {
let mut execution =
Box::pin(manager.exec_command_inner(request, &context, Some(&mut completion)));
tokio::select! {
biased;
_ = context.cancellation_token.cancelled() => {
if let Some(process) = process.get() {
if !process.has_exited()
&& let Err(err) = process.terminate_confirmed().await
{
process.fail_and_terminate(err.to_string());
}
// An exited remote shell can still have open output pipes.
process.cancellation_token().cancel();
let _ = execution.await;
} else {
drop(execution);
manager.release_process_id(process_id).await;
}
return (
Err(UnifiedExecError::process_failed("command cancelled".into())),
"cancelled",
);
}
result = &mut execution => result,
}
};
let outcome = if completion.timed_out {
"timed_out"
} else if result.is_ok() {
"exited"
} else {
"failed"
};
let result = result.map(|mut output| {
if completion.timed_out {
output.process_id = None;
}
output
});
(result, outcome)
};
let (result, outcome) = match tokio::spawn(task.in_current_span()).await {
Ok(result) => result,
Err(err) => (
Err(UnifiedExecError::process_failed(err.to_string())),
"failed",
),
};
tracing::Span::current().record("outcome", outcome);
result
}
}

View File

@@ -0,0 +1,63 @@
//! Text retained for one unified exec output stream and the bytes omitted by its collection cap.
use akode_utils_head_tail_buffer::HeadTailBuffer;
use akode_utils_head_tail_buffer::format_output_omission_marker;
use akode_utils_output_truncation::TruncationPolicy;
use akode_utils_output_truncation::approx_token_count;
use akode_utils_output_truncation::formatted_truncate_text;
use akode_utils_output_truncation::truncate_text;
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct CapturedStream {
pub(crate) text: String,
pub(crate) omitted_bytes: usize,
}
impl From<&str> for CapturedStream {
fn from(text: &str) -> Self {
Self {
text: text.to_string(),
omitted_bytes: 0,
}
}
}
impl<const N: usize> From<&HeadTailBuffer<N>> for CapturedStream {
fn from(buffer: &HeadTailBuffer<N>) -> Self {
Self {
text: String::from_utf8_lossy(&buffer.to_bytes_with_omission_marker()).into_owned(),
omitted_bytes: buffer.omitted_bytes(),
}
}
}
impl CapturedStream {
pub(crate) fn render(
&self,
policy: Option<TruncationPolicy>,
original_tokens: Option<usize>,
) -> String {
let truncated = match policy {
Some(policy) if self.omitted_bytes == 0 => {
return formatted_truncate_text(&self.text, policy);
}
Some(policy) => truncate_text(&self.text, policy),
None if self.omitted_bytes == 0 => return self.text.clone(),
None => self.text.clone(),
};
let marker = format_output_omission_marker(self.omitted_bytes);
let notice = if truncated.contains(&marker) {
String::new()
} else {
format!("{marker}\n")
};
if policy.is_none_or(|policy| self.text.len() <= policy.byte_budget()) {
if notice.is_empty() {
return truncated;
}
return format!("{notice}{truncated}");
}
let tokens = original_tokens.unwrap_or_else(|| approx_token_count(&self.text));
format!("Warning: truncated output (original token count: {tokens})\n{notice}\n{truncated}")
}
}

View File

@@ -0,0 +1,706 @@
#![allow(clippy::module_inception)]
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use tokio::sync::Mutex;
use tokio::sync::Notify;
use tokio::sync::broadcast;
use tokio::sync::oneshot::error::TryRecvError;
use tokio::sync::watch;
use tokio::task::JoinHandle;
use tokio::time::Duration;
use tokio_util::sync::CancellationToken;
use akode_exec_server::ExecOutputStream;
use akode_exec_server::ExecProcess;
use akode_exec_server::ExecProcessEvent;
use akode_exec_server::ProcessSignal as ExecServerProcessSignal;
use akode_exec_server::ReadResponse as ExecReadResponse;
use akode_exec_server::StartedExecProcess;
use akode_exec_server::WriteStatus;
use akode_protocol::exec_output::ExecToolCallOutput;
use akode_protocol::exec_output::StreamOutput;
use akode_protocol::protocol::TruncationPolicy;
use akode_sandboxing::SandboxType;
use akode_sandboxing::is_likely_sandbox_denied;
use akode_sandboxing::record_filesystem_sandbox_violation;
use akode_utils_head_tail_buffer::HeadTailBuffer;
use akode_utils_output_truncation::formatted_truncate_text;
use akode_utils_pty::ExecCommandSession;
use akode_utils_pty::ProcessSignal as PtyProcessSignal;
use akode_utils_pty::SpawnedPty;
use super::UNIFIED_EXEC_OUTPUT_MAX_BYTES;
use super::UNIFIED_EXEC_OUTPUT_MAX_TOKENS;
use super::UnifiedExecError;
use super::process_state::ProcessState;
use crate::shell_snapshot::ShellSnapshotFile;
const EARLY_EXIT_GRACE_PERIOD: Duration = Duration::from_millis(150);
const REMOTE_OUTPUT_DRAIN_GRACE: Duration = Duration::from_secs(5);
/// Output pending model polling and the retained completion transcript.
/// Append both under the same lock so cancellation cannot split an update.
#[derive(Default)]
pub(crate) struct OutputBuffers<const MAX_BYTES: usize = UNIFIED_EXEC_OUTPUT_MAX_BYTES> {
pub(super) pending: HeadTailBuffer<MAX_BYTES>,
pub(super) transcript: HeadTailBuffer<MAX_BYTES>,
}
impl<const MAX_BYTES: usize> OutputBuffers<MAX_BYTES> {
pub(super) fn push_chunk(&mut self, _stream: ExecOutputStream, chunk: &[u8]) {
self.pending.push_chunk(chunk);
self.transcript.push_chunk(chunk);
}
}
/// Shared output state exposed to polling and streaming consumers.
#[derive(Clone)]
pub(crate) struct OutputHandles<const MAX_BYTES: usize = UNIFIED_EXEC_OUTPUT_MAX_BYTES> {
pub(crate) output_buffer: Arc<Mutex<OutputBuffers<MAX_BYTES>>>,
pub(crate) output_notify: Arc<Notify>,
pub(crate) output_closed: Arc<AtomicBool>,
pub(crate) output_closed_notify: Arc<Notify>,
pub(crate) cancellation_token: CancellationToken,
pub(super) drain_policy: OutputDrainPolicy,
/// The initial exec call returned or was cancelled, so background draining may begin.
pub(crate) collection_finished: CancellationToken,
}
struct OutputTaskGuard {
output_closed: Arc<AtomicBool>,
output_closed_notify: Arc<Notify>,
}
impl Drop for OutputTaskGuard {
fn drop(&mut self) {
self.output_closed.store(true, Ordering::Release);
self.output_closed_notify.notify_waiters();
}
}
/// Controls whether process exit can start the collectors' bounded output drain.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum OutputDrainPolicy {
/// Match direct local execution when descendants retain inherited output pipes.
BoundedAfterExit,
/// Remote foreground output may still be buffered or in transit after exit.
WaitForOutputClosure,
}
/// Transport-specific process handle used by unified exec.
enum ProcessHandle {
Local(Box<ExecCommandSession>),
ExecServer(Arc<dyn ExecProcess>),
}
/// Unified wrapper over directly spawned PTY sessions and exec-server-backed
/// processes.
pub(crate) struct UnifiedExecProcess {
process_handle: ProcessHandle,
output_tx: broadcast::Sender<Vec<u8>>,
output: OutputHandles,
output_drained: Arc<Notify>,
interaction_lock: Arc<Mutex<()>>,
state_tx: watch::Sender<ProcessState>,
state_rx: watch::Receiver<ProcessState>,
output_task: Option<JoinHandle<()>>,
sandbox_type: Option<SandboxType>,
timed_out: AtomicBool,
/// Explicit termination overrides retention of remote output after exit.
pub(super) termination_requested: AtomicBool,
// The shell may still need to replay this file after process startup returns.
pub(crate) _shell_snapshot: Option<Arc<ShellSnapshotFile>>,
}
impl std::fmt::Debug for UnifiedExecProcess {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UnifiedExecProcess")
.field("has_exited", &self.has_exited())
.field("exit_code", &self.exit_code())
.field("sandbox_type", &self.sandbox_type)
.finish_non_exhaustive()
}
}
impl UnifiedExecProcess {
fn new(
process_handle: ProcessHandle,
sandbox_type: Option<SandboxType>,
drain_policy: OutputDrainPolicy,
) -> Self {
let output = OutputHandles {
output_buffer: Arc::new(Mutex::new(OutputBuffers::default())),
output_notify: Arc::new(Notify::new()),
output_closed: Arc::new(AtomicBool::new(false)),
output_closed_notify: Arc::new(Notify::new()),
cancellation_token: CancellationToken::new(),
drain_policy,
collection_finished: CancellationToken::new(),
};
let output_drained = Arc::new(Notify::new());
let (output_tx, _) = broadcast::channel(64);
let (state_tx, state_rx) = watch::channel(ProcessState::default());
Self {
process_handle,
output_tx,
output,
output_drained,
interaction_lock: Arc::new(Mutex::new(())),
state_tx,
state_rx,
output_task: None,
sandbox_type,
timed_out: AtomicBool::new(false),
termination_requested: AtomicBool::new(false),
_shell_snapshot: None,
}
}
pub(super) async fn write(&self, data: &[u8]) -> Result<(), UnifiedExecError> {
match &self.process_handle {
ProcessHandle::Local(process_handle) => process_handle
.writer_sender()
.send(data.to_vec())
.await
.map_err(|_| UnifiedExecError::WriteToStdin),
ProcessHandle::ExecServer(process_handle) => {
match process_handle.write(data.to_vec()).await {
Ok(response) => match response.status {
WriteStatus::Accepted => Ok(()),
WriteStatus::UnknownProcess | WriteStatus::StdinClosed => {
let state = self.state_rx.borrow().clone();
let _ = self.state_tx.send_replace(state.exited(state.exit_code));
self.output.cancellation_token.cancel();
Err(UnifiedExecError::WriteToStdin)
}
WriteStatus::Starting => Err(UnifiedExecError::WriteToStdin),
},
Err(err) => Err(UnifiedExecError::process_failed(err.to_string())),
}
}
}
}
pub(super) fn output_handles(&self) -> &OutputHandles {
&self.output
}
pub(super) fn output_receiver(&self) -> tokio::sync::broadcast::Receiver<Vec<u8>> {
self.output_tx.subscribe()
}
pub(super) fn cancellation_token(&self) -> CancellationToken {
self.output.cancellation_token.clone()
}
pub(super) fn output_drained_notify(&self) -> Arc<Notify> {
Arc::clone(&self.output_drained)
}
pub(super) fn interaction_lock(&self) -> Arc<Mutex<()>> {
Arc::clone(&self.interaction_lock)
}
pub(super) fn has_exited(&self) -> bool {
let state = self.state_rx.borrow().clone();
match &self.process_handle {
ProcessHandle::Local(process_handle) => state.has_exited || process_handle.has_exited(),
ProcessHandle::ExecServer(_) => state.has_exited,
}
}
pub(super) fn exit_code(&self) -> Option<i32> {
if self.timed_out() {
return Some(124);
}
let state = self.state_rx.borrow().clone();
match &self.process_handle {
ProcessHandle::Local(process_handle) => {
state.exit_code.or_else(|| process_handle.exit_code())
}
ProcessHandle::ExecServer(_) => state.exit_code,
}
}
pub(super) fn mark_timed_out(&self) {
self.timed_out.store(true, Ordering::Release);
}
pub(super) fn timed_out(&self) -> bool {
self.timed_out.load(Ordering::Acquire)
}
fn finish_termination(&self) {
self.termination_requested.store(true, Ordering::Release);
self.output.cancellation_token.cancel();
if let Some(output_task) = &self.output_task {
output_task.abort();
}
}
pub(super) fn terminate(&self) {
match &self.process_handle {
ProcessHandle::Local(process_handle) => process_handle.terminate(),
ProcessHandle::ExecServer(process_handle) => {
let process_handle = Arc::clone(process_handle);
tokio::spawn(async move {
let _ = process_handle.terminate().await;
});
}
}
self.finish_termination();
}
pub(super) async fn terminate_confirmed(&self) -> Result<(), UnifiedExecError> {
match &self.process_handle {
ProcessHandle::Local(process_handle) => process_handle.terminate(),
ProcessHandle::ExecServer(process_handle) => {
process_handle
.terminate()
.await
.map_err(|err| UnifiedExecError::process_failed(err.to_string()))?;
}
}
self.signal_exit(self.exit_code());
self.finish_termination();
Ok(())
}
pub(super) async fn interrupt(&self) -> Result<(), UnifiedExecError> {
match &self.process_handle {
ProcessHandle::Local(process_handle) => process_handle
.signal(PtyProcessSignal::Interrupt)
.map_err(|err| UnifiedExecError::process_failed(err.to_string())),
ProcessHandle::ExecServer(process_handle) => process_handle
.signal(ExecServerProcessSignal::Interrupt)
.await
.map_err(|err| UnifiedExecError::process_failed(err.to_string())),
}
}
pub(super) fn fail_and_terminate(&self, message: String) {
let state = self.state_rx.borrow().clone();
if state.failure_message.is_none() {
let _ = self.state_tx.send_replace(state.failed(message));
}
self.terminate();
}
async fn snapshot_output(&self) -> Vec<u8> {
let guard = self.output.output_buffer.lock().await;
guard.pending.to_bytes()
}
pub(crate) fn sandbox_type(&self) -> Option<SandboxType> {
self.sandbox_type
}
pub(super) fn failure_message(&self) -> Option<String> {
self.state_rx.borrow().failure_message.clone()
}
pub(super) async fn check_for_sandbox_denial(&self) -> Result<(), UnifiedExecError> {
let _ = tokio::time::timeout(
Duration::from_millis(20),
self.output.output_notify.notified(),
)
.await;
let aggregated = self.snapshot_output().await;
let aggregated_text = String::from_utf8_lossy(&aggregated);
self.check_for_sandbox_denial_with_text(aggregated_text.as_ref())
.await?;
Ok(())
}
pub(super) async fn check_for_sandbox_denial_with_text(
&self,
text: &str,
) -> Result<(), UnifiedExecError> {
let executor_reported_denial = self.state_rx.borrow().sandbox_denied;
let sandbox_type = self.sandbox_type().unwrap_or(SandboxType::None);
if !self.has_exited() || (!executor_reported_denial && sandbox_type == SandboxType::None) {
return Ok(());
}
let exit_code = self.exit_code().unwrap_or(-1);
let exec_output = ExecToolCallOutput {
exit_code,
stderr: StreamOutput::new(text.to_string()),
aggregated_output: StreamOutput::new(text.to_string()),
..Default::default()
};
let likely_sandbox_denial = is_likely_sandbox_denied(sandbox_type, &exec_output);
if likely_sandbox_denial {
record_filesystem_sandbox_violation(sandbox_type, &exec_output);
}
if executor_reported_denial || likely_sandbox_denial {
let snippet = formatted_truncate_text(
text,
TruncationPolicy::Tokens(UNIFIED_EXEC_OUTPUT_MAX_TOKENS),
);
let message = if snippet.is_empty() {
format!("Process exited with code {exit_code}")
} else {
snippet
};
return Err(UnifiedExecError::sandbox_denied(message, exec_output));
}
Ok(())
}
pub(super) async fn from_spawned(
spawned: SpawnedPty,
sandbox_type: SandboxType,
) -> Result<Self, UnifiedExecError> {
let SpawnedPty {
session: process_handle,
stdout_rx,
stderr_rx,
mut exit_rx,
} = spawned;
let mut managed = Self::new(
ProcessHandle::Local(Box::new(process_handle)),
Some(sandbox_type),
OutputDrainPolicy::BoundedAfterExit,
);
managed.output_task = Some(Self::spawn_local_output_task(
stdout_rx,
stderr_rx,
managed.output_handles().clone(),
managed.output_tx.clone(),
));
match exit_rx.try_recv() {
Ok(exit_code) => {
managed.signal_exit(Some(exit_code));
managed.check_for_sandbox_denial().await?;
return Ok(managed);
}
Err(TryRecvError::Closed) => {
managed.signal_exit(/*exit_code*/ None);
managed.check_for_sandbox_denial().await?;
return Ok(managed);
}
Err(TryRecvError::Empty) => {}
}
if let Ok(exit_result) = tokio::time::timeout(EARLY_EXIT_GRACE_PERIOD, &mut exit_rx).await {
managed.signal_exit(exit_result.ok());
managed.check_for_sandbox_denial().await?;
return Ok(managed);
}
tokio::spawn({
let state_tx = managed.state_tx.clone();
let cancellation_token = managed.output.cancellation_token.clone();
async move {
let exit_code = exit_rx.await.ok();
let state = state_tx.borrow().clone();
let _ = state_tx.send_replace(state.exited(exit_code));
cancellation_token.cancel();
}
});
Ok(managed)
}
pub(super) async fn from_exec_server_started(
started: StartedExecProcess,
output_drain_policy: OutputDrainPolicy,
) -> Result<Self, UnifiedExecError> {
let process_handle = ProcessHandle::ExecServer(Arc::clone(&started.process));
// Older peers do not report this field. In that case, skip local
// classification rather than attributing a violation to a guessed backend.
let sandbox_type = started.sandbox_type;
let mut managed = Self::new(process_handle, sandbox_type, output_drain_policy);
let output_handles = managed.output_handles().clone();
managed.output_task = Some(Self::spawn_exec_server_output_task(
started,
output_drain_policy,
output_handles,
managed.output_tx.clone(),
managed.state_tx.clone(),
managed.interaction_lock(),
));
let mut state_rx = managed.state_rx.clone();
if tokio::time::timeout(EARLY_EXIT_GRACE_PERIOD, async {
loop {
let state = state_rx.borrow().clone();
if state.has_exited || state.failure_message.is_some() {
break;
}
if state_rx.changed().await.is_err() {
break;
}
}
})
.await
.is_ok()
{
managed.check_for_sandbox_denial().await?;
}
Ok(managed)
}
fn spawn_exec_server_output_task(
started: StartedExecProcess,
output_drain_policy: OutputDrainPolicy,
output_handles: OutputHandles,
output_tx: broadcast::Sender<Vec<u8>>,
state_tx: watch::Sender<ProcessState>,
interaction_lock: Arc<Mutex<()>>,
) -> JoinHandle<()> {
let OutputHandles {
output_buffer,
output_notify,
output_closed,
output_closed_notify,
cancellation_token,
collection_finished,
..
} = output_handles;
let process = started.process;
let mut events = process.subscribe_events();
let mut state_rx = state_tx.subscribe();
tokio::spawn(async move {
let _output_task_guard = OutputTaskGuard {
output_closed: Arc::clone(&output_closed),
output_closed_notify: Arc::clone(&output_closed_notify),
};
let drain = async {
collection_finished.cancelled().await;
let _ = state_rx.wait_for(|state| state.has_exited).await;
tokio::time::sleep(REMOTE_OUTPUT_DRAIN_GRACE).await;
// An active poll keeps its own deadline, including transport recovery.
interaction_lock.lock_owned().await
};
tokio::pin!(drain);
let mut final_drain = false;
let mut last_seq: u64 = 0;
loop {
let received = tokio::select! {
received = events.recv() => Some(received),
guard = &mut drain, if output_drain_policy == OutputDrainPolicy::WaitForOutputClosure
&& !final_drain => {
// Later polls must remain able to collect output while this read recovers.
drop(guard);
final_drain = true;
None
}
};
let event = match received {
Some(Ok(event)) => Some(event),
Some(Err(broadcast::error::RecvError::Lagged(_))) | None => None,
Some(Err(broadcast::error::RecvError::Closed)) => {
let state = state_tx.borrow().clone();
let _ = state_tx.send_replace(
state.failed("exec-server process event stream closed".to_string()),
);
output_closed.store(true, Ordering::Release);
output_closed_notify.notify_waiters();
cancellation_token.cancel();
break;
}
};
let event_seq = event.as_ref().and_then(|event| match event {
ExecProcessEvent::Output(chunk) => Some(chunk.seq),
ExecProcessEvent::Exited { seq, .. } | ExecProcessEvent::Closed { seq } => {
Some(*seq)
}
ExecProcessEvent::Failed(_) => None,
});
let missing_sandbox_denial = matches!(
event.as_ref(),
Some(ExecProcessEvent::Exited {
sandbox_denied: None,
..
})
);
if event.is_none()
|| event_seq.is_some_and(|seq| seq > last_seq.saturating_add(1))
|| missing_sandbox_denial
{
// The final drain read waits for transport recovery and collects retained
// output before closing an idle session with inherited pipes still open.
let response = match process
.read(
Some(last_seq),
/*max_bytes*/ None,
/*wait_ms*/ Some(0),
)
.await
{
Ok(response) => response,
Err(err) => {
let state = state_tx.borrow().clone();
let _ = state_tx.send_replace(state.failed(err.to_string()));
output_closed.store(true, Ordering::Release);
output_closed_notify.notify_waiters();
cancellation_token.cancel();
break;
}
};
let ExecReadResponse {
chunks,
next_seq,
exited,
exit_code,
closed,
failure,
sandbox_denied,
} = response;
for chunk in chunks.into_iter().filter(|chunk| chunk.seq > last_seq) {
let bytes = chunk.chunk.into_inner();
let mut guard = output_buffer.lock().await;
guard.push_chunk(chunk.stream, &bytes);
drop(guard);
let _ = output_tx.send(bytes);
output_notify.notify_waiters();
}
last_seq = last_seq.max(next_seq.saturating_sub(1));
if let Some(message) = failure {
let state = state_tx.borrow().clone();
let _ = state_tx.send_replace(state.failed(message));
output_closed.store(true, Ordering::Release);
output_closed_notify.notify_waiters();
cancellation_token.cancel();
break;
}
if sandbox_denied || exited {
let mut state = state_tx.borrow().clone();
state.sandbox_denied |= sandbox_denied;
let _ = state_tx.send_replace(if exited {
state.exited(exit_code)
} else {
state
});
}
if exited && output_drain_policy == OutputDrainPolicy::BoundedAfterExit {
cancellation_token.cancel();
}
if closed || final_drain {
output_closed.store(true, Ordering::Release);
output_closed_notify.notify_waiters();
cancellation_token.cancel();
break;
}
continue;
}
let Some(event) = event else {
continue;
};
match event {
ExecProcessEvent::Output(chunk) => {
if chunk.seq <= last_seq {
continue;
}
last_seq = chunk.seq;
let bytes = chunk.chunk.into_inner();
let mut guard = output_buffer.lock().await;
guard.push_chunk(chunk.stream, &bytes);
drop(guard);
let _ = output_tx.send(bytes);
output_notify.notify_waiters();
}
ExecProcessEvent::Exited {
seq,
exit_code,
sandbox_denied,
} => {
if seq <= last_seq {
continue;
}
last_seq = seq;
let mut state = state_tx.borrow().clone();
state.sandbox_denied |= sandbox_denied.unwrap_or(false);
let _ = state_tx.send_replace(state.exited(Some(exit_code)));
if output_drain_policy == OutputDrainPolicy::BoundedAfterExit {
cancellation_token.cancel();
}
}
ExecProcessEvent::Closed { seq } => {
if seq <= last_seq {
continue;
}
output_closed.store(true, Ordering::Release);
output_closed_notify.notify_waiters();
cancellation_token.cancel();
break;
}
ExecProcessEvent::Failed(message) => {
let state = state_tx.borrow().clone();
let _ = state_tx.send_replace(state.failed(message));
output_closed.store(true, Ordering::Release);
output_closed_notify.notify_waiters();
cancellation_token.cancel();
break;
}
}
}
if final_drain {
tokio::spawn(async move {
let _ = process.terminate().await;
});
}
cancellation_token.cancel();
})
}
fn spawn_local_output_task(
mut stdout: tokio::sync::mpsc::Receiver<Vec<u8>>,
mut stderr: tokio::sync::mpsc::Receiver<Vec<u8>>,
output_handles: OutputHandles,
output_tx: broadcast::Sender<Vec<u8>>,
) -> JoinHandle<()> {
let OutputHandles {
output_buffer,
output_notify,
output_closed,
output_closed_notify,
..
} = output_handles;
tokio::spawn(async move {
let _output_task_guard = OutputTaskGuard {
output_closed: Arc::clone(&output_closed),
output_closed_notify: Arc::clone(&output_closed_notify),
};
let mut stdout_open = true;
let mut stderr_open = true;
while stdout_open || stderr_open {
let (stream, chunk) = tokio::select! {
chunk = stdout.recv(), if stdout_open => (ExecOutputStream::Stdout, chunk),
chunk = stderr.recv(), if stderr_open => (ExecOutputStream::Stderr, chunk),
};
if let Some(chunk) = chunk {
output_buffer.lock().await.push_chunk(stream, &chunk);
let _ = output_tx.send(chunk);
output_notify.notify_waiters();
} else if stream == ExecOutputStream::Stdout {
stdout_open = false;
} else {
stderr_open = false;
}
}
})
}
fn signal_exit(&self, exit_code: Option<i32>) {
let state = self.state_rx.borrow().clone();
let _ = self.state_tx.send_replace(state.exited(exit_code));
self.output.cancellation_token.cancel();
}
}
impl Drop for UnifiedExecProcess {
fn drop(&mut self) {
self.terminate();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,771 @@
use super::*;
use crate::tools::handlers::unified_exec::preparation::ExecCommandLifetime;
use crate::tools::handlers::unified_exec::preparation::ParsedExecCommand;
use crate::unified_exec::clamp_yield_time;
use akode_exec_server::ExecOutputStream;
use akode_network_proxy::ManagedNetworkSandboxContext;
use core_test_support::assert_regex_match;
use pretty_assertions::assert_eq;
use tokio::sync::Notify;
use tokio::time::Duration;
use tokio::time::Instant;
#[test]
fn unified_exec_env_injects_defaults() {
let env = apply_unified_exec_env(HashMap::new());
let expected = HashMap::from([
("NO_COLOR".to_string(), "1".to_string()),
("TERM".to_string(), "dumb".to_string()),
("LANG".to_string(), "C.UTF-8".to_string()),
("LC_CTYPE".to_string(), "C.UTF-8".to_string()),
("LC_ALL".to_string(), "C.UTF-8".to_string()),
("COLORTERM".to_string(), String::new()),
("PAGER".to_string(), "cat".to_string()),
("GIT_PAGER".to_string(), "cat".to_string()),
("GH_PAGER".to_string(), "cat".to_string()),
("AKODE_CI".to_string(), "1".to_string()),
]);
assert_eq!(env, expected);
}
#[test]
fn unified_exec_env_overrides_existing_values() {
let mut base = HashMap::new();
base.insert("NO_COLOR".to_string(), "0".to_string());
base.insert("PATH".to_string(), "/usr/bin".to_string());
let env = apply_unified_exec_env(base);
assert_eq!(env.get("NO_COLOR"), Some(&"1".to_string()));
assert_eq!(env.get("PATH"), Some(&"/usr/bin".to_string()));
}
#[tokio::test]
async fn deterministic_process_ids_are_not_reused_after_release() {
let manager = UnifiedExecProcessManager::default();
let first = manager.allocate_process_id().await;
manager.release_process_id(first).await;
let second = manager.allocate_process_id().await;
assert_eq!((first, second), (1000, 1001));
}
#[tokio::test]
async fn deterministic_process_ids_are_not_reused_after_removal() {
let manager = UnifiedExecProcessManager::default();
let first = manager.allocate_process_id().await;
let _removed = manager.process_store.lock().await.remove(first);
let second = manager.allocate_process_id().await;
assert_eq!((first, second), (1000, 1001));
}
#[test]
fn env_overlay_for_exec_server_keeps_runtime_changes_only() {
let local_policy_env = HashMap::from([
("HOME".to_string(), "/client-home".to_string()),
("PATH".to_string(), "/client-path".to_string()),
("SHELL_SET".to_string(), "policy".to_string()),
(
AKODE_VERSION_ENV_VAR.to_string(),
"client-version".to_string(),
),
(
AKODE_PERMISSION_PROFILE_ENV_VAR.to_string(),
"current-profile".to_string(),
),
(
akode_apply_patch::AKODE_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR.to_string(),
"1".to_string(),
),
]);
let request_env = HashMap::from([
("HOME".to_string(), "/client-home".to_string()),
("PATH".to_string(), "/sandbox-path".to_string()),
("OpenAI_Federation_Rule_Id".to_string(), "rule".to_string()),
("SHELL_SET".to_string(), "policy".to_string()),
("AKODE_THREAD_ID".to_string(), "thread-1".to_string()),
(
AKODE_VERSION_ENV_VAR.to_string(),
"client-version".to_string(),
),
(
AKODE_PERMISSION_PROFILE_ENV_VAR.to_string(),
"current-profile".to_string(),
),
(
akode_apply_patch::AKODE_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR.to_string(),
"1".to_string(),
),
(
"AKODE_SANDBOX_NETWORK_DISABLED".to_string(),
"1".to_string(),
),
]);
assert_eq!(
env_overlay_for_exec_server(&request_env, &local_policy_env),
HashMap::from([
("PATH".to_string(), "/sandbox-path".to_string()),
("AKODE_THREAD_ID".to_string(), "thread-1".to_string()),
(
AKODE_VERSION_ENV_VAR.to_string(),
"client-version".to_string()
),
(
AKODE_PERMISSION_PROFILE_ENV_VAR.to_string(),
"current-profile".to_string(),
),
(
akode_apply_patch::AKODE_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR.to_string(),
"1".to_string(),
),
(
"AKODE_SANDBOX_NETWORK_DISABLED".to_string(),
"1".to_string()
),
])
);
}
#[test]
fn exec_env_policy_excludes_non_inheritable_and_runtime_variables() {
let policy = ShellEnvironmentPolicy {
r#set: HashMap::from([
("codex_version".to_string(), "stale-version".to_string()),
(
"codex_permission_profile".to_string(),
"stale-profile".to_string(),
),
(
"openai_identity_token_file".to_string(),
"/run/identity-token".to_string(),
),
(
"codex_apply_patch_preserve_line_endings".to_string(),
"1".to_string(),
),
("KEEP".to_string(), "value".to_string()),
]),
..Default::default()
};
assert_eq!(
exec_env_policy_from_shell_policy(&policy),
akode_exec_server::ExecEnvPolicy {
inherit: policy.inherit,
ignore_default_excludes: policy.ignore_default_excludes,
exclude: vec![
AKODE_PERMISSION_PROFILE_ENV_VAR.to_string(),
AKODE_VERSION_ENV_VAR.to_string(),
akode_apply_patch::AKODE_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR.to_string(),
],
r#set: HashMap::from([("KEEP".to_string(), "value".to_string())]),
include_only: Vec::new(),
}
);
}
#[test]
fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
let cwd: akode_utils_absolute_path::AbsolutePathBuf = std::env::current_dir()
.expect("current dir")
.try_into()
.expect("absolute path");
let permission_profile = akode_protocol::models::PermissionProfile::Disabled;
let managed_network = ManagedNetworkSandboxContext {
loopback_ports: vec![43123],
allow_local_binding: false,
..Default::default()
};
let mut request = ExecRequest {
command: vec!["bash".to_string(), "-lc".to_string(), "true".to_string()],
cwd: cwd.clone().into(),
env: HashMap::from([
("HOME".to_string(), "/client-home".to_string()),
("PATH".to_string(), "/sandbox-path".to_string()),
("AKODE_THREAD_ID".to_string(), "thread-1".to_string()),
(
"HTTP_PROXY".to_string(),
"http://127.0.0.1:43123".to_string(),
),
("AKODE_NETWORK_PROXY_ACTIVE".to_string(), "1".to_string()),
(
"SSL_CERT_FILE".to_string(),
"/client/custom-ca.pem".to_string(),
),
]),
exec_server_env_config: Some(ExecServerEnvConfig {
policy: akode_exec_server::ExecEnvPolicy {
inherit: akode_protocol::config_types::ShellEnvironmentPolicyInherit::Core,
ignore_default_excludes: false,
exclude: Vec::new(),
r#set: HashMap::new(),
include_only: Vec::new(),
},
local_policy_env: HashMap::from([
("HOME".to_string(), "/client-home".to_string()),
("PATH".to_string(), "/client-path".to_string()),
(
"HTTP_PROXY".to_string(),
"http://127.0.0.1:43123".to_string(),
),
("AKODE_NETWORK_PROXY_ACTIVE".to_string(), "1".to_string()),
(
"SSL_CERT_FILE".to_string(),
"/client/custom-ca.pem".to_string(),
),
]),
}),
exec_server_shell_snapshot: None,
network: None,
network_environment_id: None,
expiration: crate::exec::ExecExpiration::DefaultTimeout,
capture_policy: crate::exec::ExecCapturePolicy::ShellTool,
sandbox: akode_sandboxing::SandboxType::None,
windows_sandbox_policy_cwd: cwd.clone().into(),
windows_sandbox_workspace_roots: vec![cwd],
windows_sandbox_level: akode_protocol::config_types::WindowsSandboxLevel::Disabled,
permission_profile: permission_profile.clone(),
windows_sandbox_filesystem_overrides: None,
arg0: None,
exec_server_sandbox: None,
exec_server_enforce_managed_network: true,
exec_server_managed_network: Some(managed_network.clone()),
exec_server_network_proxy: None,
};
let proxy_settings_mode = akode_sandboxing::WindowsSandboxProxySettingsMode::Preserve;
let params_for_request = |request: &ExecRequest| {
exec_server_params_for_request(
/*process_id*/ 123,
request,
/*tool_ctx*/ None,
proxy_settings_mode,
/*tty*/ true,
)
};
let params = params_for_request(&request);
assert_regex_match(
r"^123-[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$",
params.process_id.as_str(),
);
assert_ne!(params.process_id, params_for_request(&request).process_id);
assert_eq!(params.metadata, None);
assert_eq!(params.cwd, request.cwd);
assert!(params.enforce_managed_network);
assert_eq!(params.managed_network, Some(managed_network));
assert!(params.env_policy.is_some());
assert_eq!(
params.env,
HashMap::from([
("PATH".to_string(), "/sandbox-path".to_string()),
("AKODE_THREAD_ID".to_string(), "thread-1".to_string()),
(
"HTTP_PROXY".to_string(),
"http://127.0.0.1:43123".to_string(),
),
("AKODE_NETWORK_PROXY_ACTIVE".to_string(), "1".to_string(),),
])
);
request.exec_server_shell_snapshot = Some(akode_exec_server::ShellSnapshotRequest {
scope_id: "attachment-1".to_string(),
shell: akode_exec_server::ShellInfo {
name: "bash".to_string(),
path: "/bin/bash".to_string(),
},
});
let mut snapshot_env = params.env;
snapshot_env.remove("PATH");
assert_eq!(params_for_request(&request).env, snapshot_env);
request.exec_server_shell_snapshot = None;
request.exec_server_sandbox = Some(
akode_exec_server::FileSystemSandboxContext::from_permission_profile(
permission_profile,
request.cwd.clone(),
),
);
let first = params_for_request(&request);
let second = params_for_request(&request);
assert_eq!(
first
.sandbox
.as_ref()
.and_then(|sandbox| sandbox.windows_sandbox_proxy_settings_mode),
Some(akode_sandboxing::WindowsSandboxProxySettingsMode::Preserve)
);
assert!(first.process_id.as_str().starts_with("123-"));
assert!(second.process_id.as_str().starts_with("123-"));
assert_ne!(first.process_id, second.process_id);
}
#[cfg(windows)]
#[test]
fn initial_exec_yield_time_uses_windows_floor() {
let above_max_yield_time_ms = crate::unified_exec::MAX_YIELD_TIME_MS + 1;
assert_eq!(
clamp_yield_time(/*yield_time_ms*/ 1_000),
crate::unified_exec::WINDOWS_INITIAL_EXEC_YIELD_TIME_FLOOR_MS
);
assert_eq!(
clamp_yield_time(/*yield_time_ms*/ 2_000),
crate::unified_exec::WINDOWS_INITIAL_EXEC_YIELD_TIME_FLOOR_MS
);
assert_eq!(
clamp_yield_time(/*yield_time_ms*/ 5_000),
crate::unified_exec::WINDOWS_INITIAL_EXEC_YIELD_TIME_FLOOR_MS
);
assert_eq!(clamp_yield_time(/*yield_time_ms*/ 10_000), 10_000);
assert_eq!(
clamp_yield_time(/*yield_time_ms*/ above_max_yield_time_ms),
crate::unified_exec::MAX_YIELD_TIME_MS
);
}
#[cfg(not(windows))]
#[test]
fn initial_exec_yield_time_has_no_platform_floor() {
assert_eq!(clamp_yield_time(/*yield_time_ms*/ 1_000), 1_000);
assert_eq!(
clamp_yield_time(/*yield_time_ms*/ 1),
crate::unified_exec::MIN_YIELD_TIME_MS
);
}
#[tokio::test]
async fn output_collection_stays_bounded_across_repeated_drains() {
let chunks: [&[u8]; 4] = [b"01234567", b"89ABCDEF", b"ghijklmnopq", b"rs"];
let output_buffer = Arc::new(tokio::sync::Mutex::new(OutputBuffers::<10>::default()));
let output_notify = Arc::new(Notify::new());
let output_closed = Arc::new(AtomicBool::new(false));
let output_closed_notify = Arc::new(Notify::new());
let cancellation_token = CancellationToken::new();
let output = OutputHandles {
output_buffer: Arc::clone(&output_buffer),
output_notify: Arc::clone(&output_notify),
output_closed: Arc::clone(&output_closed),
output_closed_notify: Arc::clone(&output_closed_notify),
cancellation_token: cancellation_token.clone(),
collection_finished: CancellationToken::new(),
drain_policy: OutputDrainPolicy::BoundedAfterExit,
};
let collect = UnifiedExecProcessManager::collect_output_until_deadline(
&output,
/*pause_state*/ None,
Instant::now() + Duration::from_secs(5),
);
let produce = async {
for chunk in chunks {
output_buffer
.lock()
.await
.push_chunk(ExecOutputStream::Stdout, chunk);
output_notify.notify_one();
tokio::time::timeout(Duration::from_secs(1), async {
loop {
if output_buffer.lock().await.pending.retained_bytes() == 0 {
break;
}
tokio::task::yield_now().await;
}
})
.await
.expect("collector should drain each chunk");
}
output_closed.store(true, Ordering::Release);
cancellation_token.cancel();
output_closed_notify.notify_waiters();
output_notify.notify_waiters();
};
let (collected, ()) = tokio::join!(collect, produce);
let mut expected = HeadTailBuffer::<10>::default();
for chunk in chunks {
expected.push_chunk(chunk);
}
assert_eq!(collected, expected);
assert_eq!(output_buffer.lock().await.transcript, expected);
}
#[tokio::test]
async fn output_collection_preserves_omissions_from_drained_buffer() {
let mut buffered_output = OutputBuffers::<10>::default();
buffered_output.push_chunk(ExecOutputStream::Stdout, &[b'a'; 10]);
buffered_output.push_chunk(ExecOutputStream::Stdout, b"overflow");
let mut expected = HeadTailBuffer::<10>::default();
expected.push_chunk(&[b'a'; 10]);
expected.push_chunk(b"overflow");
let output_buffer = Arc::new(tokio::sync::Mutex::new(buffered_output));
let output_notify = Arc::new(Notify::new());
let output_closed = Arc::new(AtomicBool::new(true));
let output_closed_notify = Arc::new(Notify::new());
let cancellation_token = CancellationToken::new();
cancellation_token.cancel();
let output = OutputHandles {
output_buffer,
output_notify,
output_closed,
output_closed_notify,
cancellation_token,
collection_finished: CancellationToken::new(),
drain_policy: OutputDrainPolicy::BoundedAfterExit,
};
let collected = UnifiedExecProcessManager::collect_output_until_deadline(
&output,
/*pause_state*/ None,
Instant::now() + Duration::from_secs(1),
)
.await;
assert_eq!(collected, expected);
}
#[tokio::test]
async fn network_denial_fallback_message_names_sandbox_network_proxy() {
let message = network_denial_message_for_session(/*session*/ None, /*deferred*/ None).await;
assert_eq!(
message,
"Network access was denied by the Codex sandbox network proxy."
);
}
#[tokio::test(start_paused = true)]
async fn late_network_denial_grace_observes_cancellation_after_exit() -> anyhow::Result<()> {
use crate::environment_selection::EnvironmentAttachment;
use crate::environment_selection::TurnEnvironmentSnapshot;
use crate::environment_selection::TurnEnvironmentState;
use crate::guardian::GuardianNetworkAccessTrigger;
use crate::tools::network_approval::NetworkApprovalSpec;
use crate::tools::network_approval::begin_network_approval;
use crate::tools::network_approval::build_blocked_request_observer;
use akode_network_proxy::BlockedRequest;
use akode_network_proxy::BlockedRequestArgs;
use akode_network_proxy::EnvironmentNetworkPolicy;
use akode_tools::ToolName;
let (session, mut turn) = crate::session::tests::make_session_and_context().await;
let session = Arc::new(session);
Arc::make_mut(&mut turn.config).permissions.network = None;
let mut remote = turn
.initial_environments
.primary()
.expect("primary environment")
.clone();
let remote_id = akode_exec_server::REMOTE_ENVIRONMENT_ID;
let (attachment, _guard, _) = EnvironmentAttachment::new(
remote_id,
Arc::new(akode_exec_server::Environment::create_for_tests(Some(
"ws://127.0.0.1:1".into(),
))?),
);
remote.attachment = attachment;
remote.selection.environment_id = remote_id.to_string();
remote.config_mut().permission_profile =
akode_protocol::models::PermissionProfileSnapshot::legacy(
akode_protocol::models::PermissionProfile::workspace_write(),
);
remote.config_mut().network_policy = Some(EnvironmentNetworkPolicy::from_config(
&akode_network_proxy::NetworkProxyConfig {
enabled: true,
..Default::default()
},
/*managed_allowed_domains_only*/ false,
));
let environments = TurnEnvironmentSnapshot {
environments: vec![TurnEnvironmentState::Ready(remote)],
};
let remote = environments.primary().expect("remote environment");
for register_shared_listener in [false, true] {
let approval = begin_network_approval(
&session,
&turn,
&environments,
/*managed_network_active*/ true,
Some(NetworkApprovalSpec {
network: None,
environment_id: remote_id.to_string(),
tool_name: ToolName::plain("exec_command"),
command: "pwd".into(),
trigger: GuardianNetworkAccessTrigger {
call_id: "exec".into(),
tool_name: "exec_command".into(),
command: vec!["pwd".into()],
cwd: remote.cwd().clone(),
sandbox_permissions: crate::sandboxing::SandboxPermissions::UseDefault,
additional_permissions: None,
justification: None,
tty: None,
},
permission_profile: remote.permission_profile().clone(),
network_policy: remote.config().network_policy.clone(),
}),
)
.await
.expect("build network proxy")
.expect("network approval");
let callback = approval
.execution_proxy()
.remote_policy_decider(/*allow_local_binding*/ true)
.expect("remote policy callback");
let finish = finish_deferred_network_approval_after_process_exit_for_session(
Some(&session),
approval.into_deferred(),
);
tokio::pin!(finish);
assert!(futures::poll!(&mut finish).is_pending());
let observer = register_shared_listener.then(|| {
build_blocked_request_observer(Arc::clone(&session.services.network_approval))
});
drop(callback);
if let Some(observer) = observer {
// A shared listener started during the command and can report an untagged denial.
tokio::time::advance(Duration::from_millis(10)).await;
assert!(futures::poll!(&mut finish).is_pending());
let blocked = BlockedRequest::new(BlockedRequestArgs {
host: "blocked.example".into(),
protocol: "http".into(),
port: Some(80),
reason: "not_allowed".into(),
decision: Some("deny".into()),
source: Some("decider".into()),
client: None,
method: None,
mode: None,
});
let expected = crate::network_policy_decision::denied_network_policy_message(&blocked)
.expect("blocked request must describe the denied host");
observer.on_blocked_request(blocked).await;
assert_eq!(finish.await, Err(expected));
} else {
assert_eq!(futures::poll!(&mut finish), std::task::Poll::Ready(Ok(())));
}
}
Ok(())
}
#[tokio::test]
async fn failed_initial_end_for_unstored_process_uses_fallback_output() {
let (session, turn, rx_event) = crate::session::tests::make_session_and_context_with_rx().await;
let context = UnifiedExecContext::new(
Arc::clone(&session),
crate::session::step_context::StepContext::for_test(Arc::clone(&turn)),
tokio_util::sync::CancellationToken::new(),
"call-unified-denied".to_string(),
);
let environment = turn
.initial_environments
.primary()
.expect("primary environment");
let prepared = ParsedExecCommand::parse(
r#"{"cmd":"echo before"}"#,
&session,
&context.step_context,
environment,
)
.expect("parse command")
.prepare(ExecCommandLifetime::Interactive)
.expect("prepare command");
let request = ExecCommandRequest {
prepared,
process_id: 123,
network: None,
};
let output_buffer = Arc::new(tokio::sync::Mutex::new(OutputBuffers::default()));
output_buffer
.lock()
.await
.push_chunk(ExecOutputStream::Stdout, b"PARTIAL_TRANSCRIPT");
emit_failed_initial_exec_end_if_unstored(
/*process_stored*/ false,
Some(akode_protocol::sandbox::SandboxType::WindowsMxc),
&context,
&request,
request.prepared.cwd.clone(),
/*plugin_attribution*/ None,
output_buffer,
"PRE_DENIAL_MARKER".to_string(),
"Network access denied".to_string(),
Duration::from_millis(7),
)
.await;
let event = tokio::time::timeout(Duration::from_secs(1), rx_event.recv())
.await
.expect("timed out waiting for failed command execution item")
.expect("event channel closed");
let akode_protocol::protocol::EventMsg::ItemCompleted(completed_event) = event.msg else {
panic!("expected ItemCompleted event");
};
let akode_protocol::items::TurnItem::CommandExecution(item) = completed_event.item else {
panic!("expected CommandExecution item");
};
assert_eq!(item.id, "call-unified-denied");
assert_eq!(
item.sandbox_type,
Some(akode_protocol::sandbox::SandboxType::WindowsMxc)
);
assert_eq!(
item.status,
akode_protocol::items::CommandExecutionStatus::Failed
);
assert_eq!(item.exit_code, Some(-1));
assert_eq!(item.process_id.as_deref(), Some("123"));
assert_eq!(
item.aggregated_output.as_deref(),
Some("PRE_DENIAL_MARKER\nNetwork access denied")
);
}
#[test]
fn pruning_prefers_exited_processes_outside_recently_used() {
let now = Instant::now();
let meta = vec![
(1, now - Duration::from_secs(40), false),
(2, now - Duration::from_secs(30), true),
(3, now - Duration::from_secs(20), false),
(4, now - Duration::from_secs(19), false),
(5, now - Duration::from_secs(18), false),
(6, now - Duration::from_secs(17), false),
(7, now - Duration::from_secs(16), false),
(8, now - Duration::from_secs(15), false),
(9, now - Duration::from_secs(14), false),
(10, now - Duration::from_secs(13), false),
];
let candidate = UnifiedExecProcessManager::process_id_to_prune_from_meta(&meta);
assert_eq!(candidate, Some(2));
}
#[test]
fn pruning_falls_back_to_lru_when_no_exited() {
let now = Instant::now();
let meta = vec![
(1, now - Duration::from_secs(40), false),
(2, now - Duration::from_secs(30), false),
(3, now - Duration::from_secs(20), false),
(4, now - Duration::from_secs(19), false),
(5, now - Duration::from_secs(18), false),
(6, now - Duration::from_secs(17), false),
(7, now - Duration::from_secs(16), false),
(8, now - Duration::from_secs(15), false),
(9, now - Duration::from_secs(14), false),
(10, now - Duration::from_secs(13), false),
];
let candidate = UnifiedExecProcessManager::process_id_to_prune_from_meta(&meta);
assert_eq!(candidate, Some(1));
}
#[test]
fn pruning_protects_recent_processes_even_if_exited() {
let now = Instant::now();
let meta = vec![
(1, now - Duration::from_secs(40), false),
(2, now - Duration::from_secs(30), false),
(3, now - Duration::from_secs(20), true),
(4, now - Duration::from_secs(19), false),
(5, now - Duration::from_secs(18), false),
(6, now - Duration::from_secs(17), false),
(7, now - Duration::from_secs(16), false),
(8, now - Duration::from_secs(15), false),
(9, now - Duration::from_secs(14), false),
(10, now - Duration::from_secs(13), true),
];
let candidate = UnifiedExecProcessManager::process_id_to_prune_from_meta(&meta);
// (10) is exited but among the last 8; we should drop the LRU outside that set.
assert_eq!(candidate, Some(1));
}
#[cfg(unix)]
#[tokio::test]
async fn pruning_does_not_evict_live_process_while_exited_process_is_finalizing() {
let (_, turn) = crate::session::tests::make_session_and_context().await;
let exited_process = Arc::new(
crate::unified_exec::process_tests::remote_process(
akode_exec_server::WriteStatus::Accepted,
/*terminate_error*/ None,
akode_sandboxing::SandboxType::None,
)
.await,
);
exited_process
.terminate_confirmed()
.await
.expect("exited process should terminate");
let live_process = Arc::new(
crate::unified_exec::process_tests::remote_process(
akode_exec_server::WriteStatus::Accepted,
/*terminate_error*/ None,
akode_sandboxing::SandboxType::None,
)
.await,
);
let _interaction_guard = exited_process.interaction_lock().lock_owned().await;
let now = Instant::now();
let cwd = PathUri::parse("file:///tmp").expect("test cwd should be valid");
let mut store = ProcessStore::default();
let max_process_id =
i32::try_from(MAX_UNIFIED_EXEC_PROCESSES).expect("process cap should fit in i32");
for process_id in 1..=max_process_id {
let is_exited = process_id == 1;
store.processes.insert(
process_id,
ProcessEntry {
process: if is_exited {
Arc::clone(&exited_process)
} else {
Arc::clone(&live_process)
},
call_id: format!("call-{process_id}"),
process_id,
cwd: cwd.clone(),
initial_exec_command_active: Arc::new(AtomicBool::new(false)),
hook_command: format!("command-{process_id}"),
tty: false,
environment_id: akode_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
permissions: super::super::TerminalPermissions::for_launch(
turn.initial_environments
.primary()
.expect("turn environment"),
&turn,
super::super::TerminalSandboxSource::Native,
crate::sandboxing::SandboxPermissions::UseDefault,
/*additional_permissions*/ None,
/*internal_permissions*/ None,
),
network_approval: None,
session: std::sync::Weak::new(),
last_used: if is_exited {
now - Duration::from_secs(1)
} else {
now
},
},
);
}
let pruned = UnifiedExecProcessManager::prune_processes_if_needed(&mut store);
assert_eq!(
(pruned.map(|entry| entry.process_id), store.processes.len()),
(None, MAX_UNIFIED_EXEC_PROCESSES)
);
}

View File

@@ -0,0 +1,27 @@
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct ProcessState {
pub(crate) has_exited: bool,
pub(crate) exit_code: Option<i32>,
pub(crate) failure_message: Option<String>,
pub(crate) sandbox_denied: bool,
}
impl ProcessState {
pub(crate) fn exited(&self, exit_code: Option<i32>) -> Self {
Self {
has_exited: true,
exit_code,
failure_message: self.failure_message.clone(),
sandbox_denied: self.sandbox_denied,
}
}
pub(crate) fn failed(&self, message: String) -> Self {
Self {
has_exited: true,
exit_code: self.exit_code,
failure_message: Some(message),
sandbox_denied: self.sandbox_denied,
}
}
}

View File

@@ -0,0 +1,216 @@
use super::process::OutputDrainPolicy;
use super::process::UnifiedExecProcess;
use crate::unified_exec::UnifiedExecError;
use akode_exec_server::ExecProcess;
use akode_exec_server::ExecProcessEventReceiver;
use akode_exec_server::ExecProcessFuture;
use akode_exec_server::ExecServerError;
use akode_exec_server::ProcessId;
use akode_exec_server::ProcessSignal;
use akode_exec_server::ReadResponse;
use akode_exec_server::StartedExecProcess;
use akode_exec_server::WriteResponse;
use akode_exec_server::WriteStatus;
use pretty_assertions::assert_eq;
use std::collections::VecDeque;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::sync::watch;
struct MockExecProcess {
process_id: ProcessId,
write_response: WriteResponse,
read_responses: Mutex<VecDeque<ReadResponse>>,
terminate_error: Option<String>,
wake_tx: watch::Sender<u64>,
}
impl MockExecProcess {
async fn read(&self) -> Result<ReadResponse, ExecServerError> {
Ok(self
.read_responses
.lock()
.await
.pop_front()
.unwrap_or(ReadResponse {
chunks: Vec::new(),
next_seq: 1,
exited: false,
exit_code: None,
closed: false,
failure: None,
sandbox_denied: false,
}))
}
async fn terminate(&self) -> Result<(), ExecServerError> {
if let Some(message) = &self.terminate_error {
return Err(ExecServerError::Protocol(message.clone()));
}
Ok(())
}
}
impl ExecProcess for MockExecProcess {
fn process_id(&self) -> &ProcessId {
&self.process_id
}
fn subscribe_wake(&self) -> watch::Receiver<u64> {
self.wake_tx.subscribe()
}
fn subscribe_events(&self) -> ExecProcessEventReceiver {
ExecProcessEventReceiver::empty()
}
fn read(
&self,
_after_seq: Option<u64>,
_max_bytes: Option<usize>,
_wait_ms: Option<u64>,
) -> ExecProcessFuture<'_, ReadResponse> {
Box::pin(MockExecProcess::read(self))
}
fn write(&self, _chunk: Vec<u8>) -> ExecProcessFuture<'_, WriteResponse> {
Box::pin(async { Ok(self.write_response.clone()) })
}
fn signal(&self, _signal: ProcessSignal) -> ExecProcessFuture<'_, ()> {
Box::pin(async { Ok(()) })
}
fn terminate(&self) -> ExecProcessFuture<'_, ()> {
Box::pin(MockExecProcess::terminate(self))
}
}
pub(super) async fn remote_process(
write_status: WriteStatus,
terminate_error: Option<String>,
sandbox_type: impl Into<Option<akode_sandboxing::SandboxType>>,
) -> UnifiedExecProcess {
let (wake_tx, _wake_rx) = watch::channel(0);
let started = StartedExecProcess {
process: Arc::new(MockExecProcess {
process_id: "test-process".to_string().into(),
write_response: WriteResponse {
status: write_status,
},
read_responses: Mutex::new(VecDeque::new()),
terminate_error,
wake_tx,
}),
sandbox_type: sandbox_type.into(),
};
UnifiedExecProcess::from_exec_server_started(started, OutputDrainPolicy::WaitForOutputClosure)
.await
.expect("remote process should start")
}
#[tokio::test]
async fn remote_write_unknown_process_marks_process_exited() {
let process = remote_process(
WriteStatus::UnknownProcess,
/*terminate_error*/ None,
akode_sandboxing::SandboxType::None,
)
.await;
let err = process
.write(b"hello")
.await
.expect_err("expected write failure");
assert!(matches!(err, UnifiedExecError::WriteToStdin));
assert!(process.has_exited());
}
#[tokio::test]
async fn remote_write_closed_stdin_marks_process_exited() {
let process = remote_process(
WriteStatus::StdinClosed,
/*terminate_error*/ None,
akode_sandboxing::SandboxType::None,
)
.await;
let err = process
.write(b"hello")
.await
.expect_err("expected write failure");
assert!(matches!(err, UnifiedExecError::WriteToStdin));
assert!(process.has_exited());
}
#[tokio::test]
async fn fail_and_terminate_preserves_failure_message() {
let process = remote_process(
WriteStatus::Accepted,
/*terminate_error*/ None,
akode_sandboxing::SandboxType::None,
)
.await;
process.fail_and_terminate("network denied".to_string());
process.fail_and_terminate("second failure".to_string());
assert!(process.has_exited());
assert_eq!(
process.failure_message(),
Some("network denied".to_string())
);
}
#[tokio::test]
async fn remote_terminate_confirmed_updates_state_on_success_only() {
let process = remote_process(
WriteStatus::Accepted,
Some("terminate unavailable".to_string()),
akode_sandboxing::SandboxType::None,
)
.await;
let err = process
.terminate_confirmed()
.await
.expect_err("expected terminate failure");
assert!(matches!(err, UnifiedExecError::ProcessFailed { .. }));
assert!(!process.has_exited());
let process = remote_process(
WriteStatus::Accepted,
/*terminate_error*/ None,
akode_sandboxing::SandboxType::None,
)
.await;
process
.terminate_confirmed()
.await
.expect("terminate should succeed");
assert!(process.has_exited());
}
#[tokio::test]
async fn remote_process_preserves_executor_sandbox_type() {
use akode_sandboxing::SandboxType;
for sandbox_type in [
None,
Some(SandboxType::None),
Some(SandboxType::LinuxSeccomp),
] {
let process = remote_process(
WriteStatus::Accepted,
/*terminate_error*/ None,
sandbox_type,
)
.await;
assert_eq!(process.sandbox_type(), sandbox_type);
}
}

View File

@@ -0,0 +1,193 @@
use std::collections::HashMap;
use std::sync::Arc;
use akode_exec_server::ExecParams;
use akode_exec_server::FileSystemSandboxContext;
use akode_exec_server::ShellInfo;
use akode_exec_server::ShellSnapshotRequest;
use akode_features::Feature;
use akode_protocol::protocol::AskForApproval;
use akode_protocol::sandbox::SandboxOverride;
use akode_sandboxing::SandboxManager;
use akode_sandboxing::SandboxablePreference;
use akode_tools::ToolName;
use tokio_util::task::AbortOnDropHandle;
use uuid::Uuid;
use super::UnifiedExecContext;
use super::process_manager::apply_unified_exec_env;
use super::process_manager::exec_env_policy_from_shell_policy;
use crate::config::NetworkProxySpec;
use crate::exec_env::AKODE_THREAD_ID_ENV_VAR;
use crate::exec_env::inject_apply_patch_env;
use crate::exec_env::inject_permission_profile_env;
use crate::exec_env::inject_session_env;
use crate::session::session::Session;
use crate::session::step_context::StepContext;
use crate::shell::ShellType;
use crate::tools::handlers::unified_exec::preparation::PreparedExecCommand;
use crate::tools::sandboxing::executor_windows_sandbox_selection;
impl Session {
pub(crate) fn prewarm_shell_snapshots(
self: &Arc<Self>,
step_context: &StepContext,
) -> Option<AbortOnDropHandle<()>> {
if !self.features().enabled(Feature::ShellSnapshotV2)
|| step_context
.tool_router
.registered_tool(&ToolName::plain("exec_command"))
.is_none()
{
return None;
}
let config = Arc::clone(&step_context.turn.config);
let user_shell = self.user_shell();
if config.active_project.is_untrusted()
|| matches!(
step_context.settings.approval_policy(),
AskForApproval::UnlessTrusted
)
|| step_context.turn.network.is_some()
|| config
.permissions
.network
.as_ref()
.is_some_and(NetworkProxySpec::enabled)
{
return None;
}
let environments = step_context.environments.clone();
let session = Arc::clone(self);
Some(AbortOnDropHandle::new(tokio::spawn(async move {
for environment in environments.turn_environments() {
// Remote starts cannot cancel an in-flight capture. Leave them, deferred
// environments, and managed networking on the normal lazy capture path.
if environment.environment().is_remote()
|| !environment.shell_snapshot_v2_supported
|| !environment.config().allow_login_shell
|| environment.config().network_policy.is_some()
{
continue;
}
let shell = environment.shell.as_ref().unwrap_or(user_shell.as_ref());
if !matches!(
shell.shell_type,
ShellType::Bash | ShellType::Zsh | ShellType::Sh
) {
continue;
}
let sandbox = SandboxManager::new()
.should_sandbox(
environment.permission_profile(),
SandboxablePreference::Auto,
/*has_managed_network_requirements*/ false,
)
.then(|| FileSystemSandboxContext {
sandbox_override: SandboxOverride::NoOverride,
permissions: environment.permission_profile().clone(),
cwd: environment.cwd().clone(),
workspace_roots: environment.workspace_roots().to_vec(),
user_home_dir: None,
temporary_directories: None,
windows_sandbox_selection: executor_windows_sandbox_selection(
environment.config().windows_sandbox_type,
environment.config().windows_sandbox_level,
environment.cwd(),
),
windows_sandbox_proxy_settings_mode: Some(
session.windows_sandbox_proxy_settings_mode,
),
use_legacy_landlock: environment.config().use_legacy_landlock,
});
let mut env = apply_unified_exec_env(HashMap::new());
env.insert(
AKODE_THREAD_ID_ENV_VAR.to_string(),
session.thread_id().to_string(),
);
inject_session_env(&mut env, session.session_id());
inject_apply_patch_env(&mut env);
inject_permission_profile_env(
&mut env,
environment.active_permission_profile().as_ref(),
);
#[cfg(unix)]
if let Some(path) = environment.shell_environment_policy().r#set.get("PATH") {
env.insert("PATH".to_string(), path.clone());
crate::tools::runtimes::apply_package_path_prepend(
&mut env,
&mut crate::tools::runtimes::RuntimePathPrepends::default(),
);
}
let params = ExecParams {
process_id: format!("shell-snapshot-warmup-{}", Uuid::new_v4()).into(),
metadata: None,
// This capture-only operation never starts the command or routes
// speculative work through tool approvals or exec-policy bypass.
argv: shell.derive_exec_args("", /*use_login_shell*/ true),
cwd: environment.cwd().clone(),
env_policy: Some(exec_env_policy_from_shell_policy(
environment.shell_environment_policy(),
)),
shell_snapshot: Some(ShellSnapshotRequest {
scope_id: format!(
"{}:{}",
session.thread_id(),
environment.selection.environment_id
),
shell: ShellInfo {
name: shell.name().to_string(),
path: shell.shell_path.to_string_lossy().into_owned(),
},
}),
env,
tty: false,
pipe_stdin: false,
arg0: None,
sandbox,
enforce_managed_network: false,
managed_network: None,
network_proxy: None,
};
let result = environment
.environment()
.get_exec_backend()
.prewarm_shell_snapshot(params)
.await;
if let Err(err) = result {
tracing::debug!("failed to warm shell snapshot: {err}");
}
}
})))
}
}
pub(super) fn shell_snapshot_request(
request: &PreparedExecCommand,
context: &UnifiedExecContext,
) -> Option<ShellSnapshotRequest> {
if !context.session.features().enabled(Feature::ShellSnapshotV2)
|| !request.turn_environment.shell_snapshot_v2_supported
|| request.turn_environment.selection.cwd != request.cwd
|| !request.resolved.shell.is_posix_login()
{
return None;
}
let shell = &request.resolved.shell.shell;
Some(ShellSnapshotRequest {
scope_id: format!(
"{}:{}",
context.session.thread_id(),
request.turn_environment.selection.environment_id
),
shell: ShellInfo {
name: shell.name().to_string(),
path: shell.shell_path.to_string_lossy().into_owned(),
},
})
}

View File

@@ -0,0 +1,5 @@
---
source: core/src/unified_exec/stdin_approval_tests.rs
expression: reason
---
Send input to an existing terminal. This terminal uses the current permissions. It also has an internal filesystem grant. The cwd is its launch directory; the terminal's current directory and state may have changed.

View File

@@ -0,0 +1,5 @@
---
source: core/src/unified_exec/stdin_approval_tests.rs
expression: reason
---
Send input to an existing terminal. This terminal retains sandbox or network settings that differ from the current permissions. The cwd is its launch directory; the terminal's current directory and state may have changed.

View File

@@ -0,0 +1,5 @@
---
source: core/src/unified_exec/stdin_approval_tests.rs
expression: reason
---
Send input to an existing terminal. This terminal was launched outside the sandbox, bypassing any managed network proxy. The cwd is its launch directory; the terminal's current directory and state may have changed.

View File

@@ -0,0 +1,5 @@
---
source: core/src/unified_exec/stdin_approval_tests.rs
expression: permissions.approval_reason(expected)?
---
Send input to an existing terminal. This terminal runs without a filesystem sandbox. The cwd is its launch directory; the terminal's current directory and state may have changed.

View File

@@ -0,0 +1,297 @@
//! Reviews terminal input against retained launch permissions and current policy.
//! Permission snapshots stay host-owned; neither an earlier approval nor a policy
//! change alters the sandbox of an already-running process. Native launches keep
//! their configured Windows sandbox selection; executor launches use executor defaults.
//! Runtime-internal grants alone do not require review; agent grants and policy drift do.
use super::ProcessEntry;
use super::UnifiedExecContext;
use super::UnifiedExecError;
use crate::config::NetworkProxySpec;
use crate::session::turn_context::TurnContext;
use crate::session::turn_context::TurnEnvironment;
use crate::tools::sandboxing::ApprovalAction;
use crate::tools::sandboxing::ToolError;
use crate::windows_sandbox::windows_sandbox_level_for_legacy_checks;
use akode_features::Feature;
use akode_file_system::FileSystemSandboxContext;
use akode_network_proxy::EnvironmentNetworkPolicy;
use akode_protocol::models::AdditionalPermissionProfile;
use akode_protocol::models::PermissionProfile;
use akode_protocol::models::SandboxPermissions;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_protocol::protocol::AskForApproval;
use akode_sandboxing::policy_transforms::effective_permission_profile;
use akode_sandboxing::policy_transforms::merge_permission_profiles;
#[derive(Clone, Copy)]
pub(crate) enum TerminalSandboxSource {
Native,
Executor,
}
pub(crate) struct TerminalPermissions {
policy: TerminalPolicy,
sandbox_source: TerminalSandboxSource,
launch_permissions: SandboxPermissions,
filesystem_escalated: bool,
additional_permissions: Option<AdditionalPermissionProfile>,
internal_permissions: Option<AdditionalPermissionProfile>,
}
/// Host-owned launch settings. Never serialize these into approval messages.
#[derive(PartialEq, Eq)]
struct TerminalPolicy {
sandbox: FileSystemSandboxContext,
environment_network: Option<EnvironmentNetworkPolicy>,
controller_network: Option<NetworkProxySpec>,
controller_proxy: bool,
}
impl TerminalPolicy {
fn capture(
environment: &TurnEnvironment,
turn: &TurnContext,
sandbox_source: TerminalSandboxSource,
additional_permissions: Option<AdditionalPermissionProfile>,
) -> Self {
let mut sandbox = environment.sandbox_context(additional_permissions);
if matches!(sandbox_source, TerminalSandboxSource::Native)
&& windows_sandbox_level_for_legacy_checks(
environment.config().windows_sandbox_type,
environment.config().windows_sandbox_level,
) == akode_protocol::config_types::WindowsSandboxLevel::Disabled
{
// The filesystem helper applies executor defaults, but native process
// launches honor Disabled. Preserve it so later enablement is detected.
sandbox.windows_sandbox_selection =
akode_protocol::config_types::WindowsSandboxLevel::Disabled.into();
}
Self {
sandbox,
environment_network: environment.config().network_policy.clone(),
controller_network: turn.config.permissions.network.clone(),
controller_proxy: turn.network.is_some(),
}
}
fn file_system_context(&self) -> FileSystemSandboxContext {
let mut context = self.sandbox.clone();
// Network changes require review, not rejection for denied-read drift.
if let PermissionProfile::Managed { network, .. } = &mut context.permissions {
*network = NetworkSandboxPolicy::Restricted;
}
context
}
}
impl TerminalPermissions {
pub(crate) fn for_launch(
environment: &TurnEnvironment,
turn: &TurnContext,
sandbox_source: TerminalSandboxSource,
launch_permissions: SandboxPermissions,
additional_permissions: Option<&AdditionalPermissionProfile>,
internal_permissions: Option<&AdditionalPermissionProfile>,
) -> Self {
Self {
policy: TerminalPolicy::capture(
environment,
turn,
sandbox_source,
merge_permission_profiles(additional_permissions, internal_permissions),
),
sandbox_source,
// Retain the successful attempt's authority independently from its baseline.
launch_permissions,
filesystem_escalated: false,
additional_permissions: additional_permissions.cloned(),
internal_permissions: internal_permissions.cloned(),
}
}
pub(crate) fn with_filesystem_escalation(mut self) -> Self {
self.filesystem_escalated = true;
self
}
/// Compares launch policy with current policy including retained grants,
/// without reading turn state or touching a process.
fn review_requirement(
&self,
current: &TerminalPolicy,
baseline: &PermissionProfile,
) -> Result<SandboxPermissions, &'static str> {
let bypassed = self.launch_permissions.requires_escalated_permissions();
// Approval cannot retrofit denied reads onto a running process. Unless
// its sandbox still matches, start a new terminal under the current policy.
if baseline
.file_system_sandbox_policy()
.has_denied_read_restrictions()
&& (bypassed || self.policy.file_system_context() != current.file_system_context())
{
return Err(
"this terminal cannot enforce the current denied-read restrictions; start a new terminal",
);
}
// Runtime-internal grants are part of an ordinary launch, so only permissions
// beyond the baseline plus those grants need a fresh stdin approval.
Ok(
if bypassed || self.filesystem_escalated || &self.policy != current {
SandboxPermissions::RequireEscalated
} else if self.policy.sandbox.permissions
== effective_permission_profile(baseline, self.internal_permissions.as_ref())
{
SandboxPermissions::UseDefault
} else {
SandboxPermissions::WithAdditionalPermissions
},
)
}
fn approval_reason(
&self,
sandbox_permissions: SandboxPermissions,
) -> Result<String, serde_json::Error> {
let authority = if self.launch_permissions.requires_escalated_permissions() {
"This terminal was launched outside the sandbox, bypassing any managed network proxy."
} else if self.filesystem_escalated {
"This terminal has approved broader filesystem access; denied reads are still enforced."
} else if self.policy.sandbox.permissions == PermissionProfile::Disabled {
"This terminal runs without a filesystem sandbox."
} else {
match sandbox_permissions {
SandboxPermissions::UseDefault => "This terminal uses the current permissions.",
SandboxPermissions::WithAdditionalPermissions => {
"This terminal retains additional permissions."
}
SandboxPermissions::RequireEscalated => {
"This terminal retains sandbox or network settings that differ from the current permissions."
}
}
};
let mut reason = format!("Send input to an existing terminal. {authority}");
if self.internal_permissions.is_some() {
reason.push_str(" It also has an internal filesystem grant.");
}
reason.push_str(" The cwd is its launch directory; the terminal's current directory and state may have changed.");
if let Some(grants) = &self.additional_permissions {
// Stable reason text also reaches clients that strip the experimental
// additionalPermissions field. Internal paths never enter this text.
reason.push_str(&format!(
" Retained grants: {}.",
serde_json::to_string(grants)?
));
}
Ok(reason)
}
}
impl ProcessEntry {
pub(super) fn stdin_approval(
&self,
context: &UnifiedExecContext,
input: &str,
strict_auto_review: bool,
) -> Result<Option<(ApprovalAction, String)>, UnifiedExecError> {
if input.is_empty()
|| (!self.tty && input == "\u{3}")
|| !context
.session
.features()
.enabled(Feature::WriteStdinApproval)
{
return Ok(None);
}
let environment = context
.step_context
.environments
.turn_environments()
.find(|environment| environment.selection.environment_id == self.environment_id)
.ok_or_else(|| {
approval_error(
"cannot access the terminal's original environment; select it before retrying",
)
})?;
let permissions = &self.permissions;
let current = TerminalPolicy::capture(
environment,
&context.step_context.turn,
permissions.sandbox_source,
merge_permission_profiles(
permissions.additional_permissions.as_ref(),
permissions.internal_permissions.as_ref(),
),
);
let sandbox_permissions = permissions
.review_requirement(&current, environment.permission_profile())
.map_err(approval_error)?;
if sandbox_permissions == SandboxPermissions::UseDefault && !strict_auto_review {
return Ok(None);
}
// Manual approvals shell-quote the input, which cannot preserve NUL bytes.
if input.contains('\0') {
return Err(approval_error(
"terminal input contains a NUL byte and cannot be reviewed safely",
));
}
let reason = permissions
.approval_reason(sandbox_permissions)
.map_err(approval_error)?;
// A scoped grant can authorize retained authority without permitting new
// sandbox escalations. Still review every input, and only recognize grants
// that remain active for this terminal's environment with the same policy.
let additional_permissions_preapproved = matches!(
context.step_context.turn.approval_policy(),
AskForApproval::Granular(policy) if !policy.sandbox_approval
) && sandbox_permissions
== SandboxPermissions::WithAdditionalPermissions
&& permissions
.additional_permissions
.as_ref()
.zip(
context
.step_context
.turn
.granted_permissions(&self.environment_id),
)
.is_some_and(|(retained, current_grants)| {
// Root containment does not prove filesystem coverage: child
// restrictions, protected metadata, and symlinks can differ.
// Require the original filesystem grants, including their order.
retained.file_system == current_grants.file_system
&& (retained
.network
.as_ref()
.and_then(|network| network.enabled)
!= Some(true)
|| current_grants
.network
.as_ref()
.and_then(|network| network.enabled)
== Some(true))
});
let action = ApprovalAction::WriteStdin {
id: self.call_id.clone(),
approval_id: context.call_id.clone(),
environment_id: self.environment_id.clone(),
process_id: self.process_id,
original_command: self.hook_command.clone(),
input: input.to_string(),
cwd: self.cwd.clone(),
tty: self.tty,
sandbox_permissions,
additional_permissions: permissions.additional_permissions.clone(),
additional_permissions_preapproved,
};
Ok(Some((action, reason)))
}
}
fn approval_error(reason: impl std::fmt::Display) -> UnifiedExecError {
UnifiedExecError::StdinApproval(ToolError::Rejected(reason.to_string()))
}
#[cfg(test)]
#[path = "stdin_approval_tests.rs"]
mod tests;

View File

@@ -0,0 +1,311 @@
//! Direct policy comparisons, launch capture, and private approval text.
use super::*;
use crate::session::tests::make_session_and_context;
use akode_network_proxy::NetworkMode;
use akode_network_proxy::NetworkProxyConfig;
use akode_protocol::config_types::WindowsSandboxLevel;
use akode_protocol::models::PermissionProfileSnapshot;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_sandboxing::SandboxType;
use akode_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Arc;
fn terminal_permissions(profile: &PermissionProfile) -> TerminalPermissions {
TerminalPermissions {
policy: TerminalPolicy {
sandbox: FileSystemSandboxContext::from_permission_profile(
effective_permission_profile(profile, /*additional_permissions*/ None),
PathUri::from_host_native_path(std::env::temp_dir()).expect("local temporary cwd"),
),
environment_network: None,
controller_network: None,
controller_proxy: false,
},
sandbox_source: TerminalSandboxSource::Native,
launch_permissions: SandboxPermissions::UseDefault,
filesystem_escalated: false,
additional_permissions: None,
internal_permissions: None,
}
}
#[test]
fn reduced_permissions_require_review() -> anyhow::Result<()> {
let permissions = terminal_permissions(&PermissionProfile::Disabled);
let baseline = PermissionProfile::read_only();
let current = terminal_permissions(&baseline);
let expected = SandboxPermissions::RequireEscalated;
assert_eq!(
permissions.review_requirement(&current.policy, &baseline),
Ok(expected)
);
insta::assert_snapshot!(
"reduced_permissions",
permissions.approval_reason(expected)?
);
Ok(())
}
#[test]
fn proxy_bypass_requires_review_even_when_permissions_match() -> anyhow::Result<()> {
let baseline = PermissionProfile::Disabled;
let mut permissions = terminal_permissions(&baseline);
permissions.launch_permissions = SandboxPermissions::RequireEscalated;
let expected = SandboxPermissions::RequireEscalated;
assert_eq!(
permissions.review_requirement(&permissions.policy, &baseline),
Ok(expected)
);
insta::assert_snapshot!("proxy_bypass", permissions.approval_reason(expected)?);
Ok(())
}
#[test]
fn denied_reads_reject_file_system_changes_but_only_review_network_changes() {
let mut file_system = FileSystemSandboxPolicy::read_only();
file_system.entries.push(FileSystemSandboxEntry::new(
FileSystemPath::GlobPattern {
pattern: "**/.env".into(),
},
FileSystemAccessMode::Deny,
));
let baseline =
PermissionProfile::from_runtime_permissions(&file_system, NetworkSandboxPolicy::Restricted);
let permissions = terminal_permissions(&PermissionProfile::Disabled);
let current = terminal_permissions(&baseline);
assert_eq!(
permissions.review_requirement(&current.policy, &baseline),
Err(
"this terminal cannot enforce the current denied-read restrictions; start a new terminal"
)
);
let permissions = current;
let baseline =
PermissionProfile::from_runtime_permissions(&file_system, NetworkSandboxPolicy::Enabled);
let current = terminal_permissions(&baseline);
assert_eq!(
permissions.review_requirement(&current.policy, &baseline),
Ok(SandboxPermissions::RequireEscalated)
);
}
#[tokio::test]
async fn captured_network_changes_require_review() -> anyhow::Result<()> {
let (_session, mut turn) = make_session_and_context().await;
let mut environment = turn
.initial_environments
.primary()
.expect("environment")
.clone();
environment.config_mut().permission_profile =
PermissionProfileSnapshot::legacy(PermissionProfile::read_only());
let mut proxy = NetworkProxyConfig {
enabled: true,
..Default::default()
};
Arc::make_mut(&mut turn.config).permissions.network =
Some(NetworkProxySpec::from_config_and_constraints(
proxy.clone(),
/*requirements*/ None,
&turn.permission_profile(),
)?);
let permissions = TerminalPermissions::for_launch(
&environment,
&turn,
TerminalSandboxSource::Native,
SandboxPermissions::UseDefault,
/*additional_permissions*/ None,
/*internal_permissions*/ None,
);
proxy.mode = NetworkMode::Limited;
Arc::make_mut(&mut turn.config).permissions.network =
Some(NetworkProxySpec::from_config_and_constraints(
proxy.clone(),
/*requirements*/ None,
&turn.permission_profile(),
)?);
let current = TerminalPolicy::capture(
&environment,
&turn,
TerminalSandboxSource::Native,
/*additional_permissions*/ None,
);
let expected = SandboxPermissions::RequireEscalated;
assert_eq!(
permissions.review_requirement(&current, environment.permission_profile()),
Ok(expected)
);
insta::assert_snapshot!("network_mode", permissions.approval_reason(expected)?);
environment.config_mut().network_policy = Some(EnvironmentNetworkPolicy::from_config(
&proxy, /*managed_allowed_domains_only*/ false,
));
let current = TerminalPolicy::capture(
&environment,
&turn,
TerminalSandboxSource::Native,
/*additional_permissions*/ None,
);
assert_eq!(
permissions.review_requirement(&current, environment.permission_profile()),
Ok(SandboxPermissions::RequireEscalated)
);
Ok(())
}
#[tokio::test]
async fn internal_grants_do_not_require_review_or_hide_agent_grants() -> anyhow::Result<()> {
let (_session, turn) = make_session_and_context().await;
let mut environment = turn
.initial_environments
.primary()
.expect("environment")
.clone();
environment.config_mut().permission_profile =
PermissionProfileSnapshot::legacy(PermissionProfile::read_only());
let grants = serde_json::from_value(json!({
"file_system": {
"read": [turn.config.cwd.join("private-snapshot")],
"write": [turn.config.cwd.join("private-metrics")]
}
}))?;
for (additional_permissions, expected) in [
(None, SandboxPermissions::UseDefault),
(
Some(serde_json::from_value(json!({
"file_system": {"write": [turn.config.cwd.join("agent-output")]}
}))?),
SandboxPermissions::WithAdditionalPermissions,
),
(
Some(serde_json::from_value(
json!({"network": {"enabled": true}}),
)?),
SandboxPermissions::WithAdditionalPermissions,
),
] {
let permissions = TerminalPermissions::for_launch(
&environment,
&turn,
TerminalSandboxSource::Native,
SandboxPermissions::UseDefault,
additional_permissions.as_ref(),
Some(&grants),
);
assert_eq!(
permissions.review_requirement(&permissions.policy, environment.permission_profile()),
Ok(expected)
);
if additional_permissions.is_none() {
// Strict review can still request this description for ordinary stdin.
insta::assert_snapshot!("internal_grant", permissions.approval_reason(expected)?);
}
let mut bypassed = permissions;
bypassed.launch_permissions = SandboxPermissions::RequireEscalated;
assert_eq!(
bypassed.review_requirement(&bypassed.policy, environment.permission_profile()),
Ok(SandboxPermissions::RequireEscalated)
);
}
Ok(())
}
#[tokio::test]
async fn readable_snapshot_does_not_require_stdin_approval() -> anyhow::Result<()> {
let (_session, turn) = make_session_and_context().await;
let mut environment = turn
.initial_environments
.primary()
.expect("environment")
.clone();
environment.config_mut().permission_profile =
PermissionProfileSnapshot::legacy(PermissionProfile::read_only());
let snapshot = turn.config.cwd.join("shell-snapshot.sh");
let grant = crate::shell_snapshot::snapshot_read_permissions(
&snapshot,
&environment.permission_profile_with_workspace_roots(),
environment.cwd(),
);
assert_eq!(grant, None);
let permissions = TerminalPermissions::for_launch(
&environment,
&turn,
TerminalSandboxSource::Native,
SandboxPermissions::UseDefault,
/*additional_permissions*/ None,
grant.as_ref(),
);
assert_eq!(
permissions.review_requirement(&permissions.policy, environment.permission_profile()),
Ok(SandboxPermissions::UseDefault)
);
Ok(())
}
#[test_case::test_case(TerminalSandboxSource::Native, SandboxType::None, SandboxPermissions::RequireEscalated; "native_disabled_sandbox_needs_review_when_enabled")]
#[test_case::test_case(TerminalSandboxSource::Executor, SandboxType::None, SandboxPermissions::UseDefault; "executor_keeps_its_restricted_token_default")]
#[test_case::test_case(TerminalSandboxSource::Native, SandboxType::WindowsMxc, SandboxPermissions::UseDefault; "native_mxc_ignores_legacy_level_changes")]
#[tokio::test]
async fn enabling_windows_sandbox_respects_the_launch_backend(
source: TerminalSandboxSource,
sandbox_type: SandboxType,
expected: SandboxPermissions,
) -> anyhow::Result<()> {
let (_session, turn) = make_session_and_context().await;
let mut environment = turn
.initial_environments
.primary()
.expect("environment")
.clone();
environment.selection.cwd = PathUri::parse("file:///C:/workspace")?;
environment.config_mut().permission_profile =
PermissionProfileSnapshot::legacy(PermissionProfile::read_only());
environment.config_mut().windows_sandbox_type = sandbox_type;
environment.config_mut().windows_sandbox_level = WindowsSandboxLevel::Disabled;
assert_eq!(
environment.windows_sandbox_selection_for_turn_metadata(),
if sandbox_type == SandboxType::WindowsMxc {
akode_file_system::WindowsSandboxSelection::Mxc
} else {
akode_file_system::WindowsSandboxSelection::Disabled
}
);
let permissions = TerminalPermissions::for_launch(
&environment,
&turn,
source,
SandboxPermissions::UseDefault,
/*additional_permissions*/ None,
/*internal_permissions*/ None,
);
let current = TerminalPolicy::capture(
&environment,
&turn,
source,
/*additional_permissions*/ None,
);
assert_eq!(
permissions.review_requirement(&current, environment.permission_profile()),
Ok(SandboxPermissions::UseDefault)
);
environment.config_mut().windows_sandbox_level = WindowsSandboxLevel::RestrictedToken;
let current = TerminalPolicy::capture(
&environment,
&turn,
source,
/*additional_permissions*/ None,
);
assert_eq!(
permissions.review_requirement(&current, environment.permission_profile()),
Ok(expected)
);
Ok(())
}