use cascade_core::{CascadeError, CascadeResult};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use crate::{EnvironmentKind, ExecutionMode};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentCommand {
pub program: String,
pub args: Vec<String>,
pub env: Vec<(String, String)>,
}
impl EnvironmentCommand {
pub fn new(program: impl Into<String>, args: Vec<String>) -> Self {
Self {
program: program.into(),
args,
env: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentRenderRequest {
pub environment: EnvironmentKind,
pub execution_mode: ExecutionMode,
pub command: EnvironmentCommand,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WslLaunchRequest {
pub distribution: Option<String>,
pub execution_mode: ExecutionMode,
pub cwd: PathBuf,
pub command: EnvironmentCommand,
}
pub trait EnvironmentCommandRenderer {
fn render(&self, request: &EnvironmentRenderRequest) -> CascadeResult<EnvironmentCommand>;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct DefaultEnvironmentCommandRenderer;
impl EnvironmentCommandRenderer for DefaultEnvironmentCommandRenderer {
fn render(&self, request: &EnvironmentRenderRequest) -> CascadeResult<EnvironmentCommand> {
match (&request.environment, request.execution_mode) {
(EnvironmentKind::Host, _) => Ok(request.command.clone()),
(EnvironmentKind::Wsl { .. }, ExecutionMode::HostInterop) => {
Ok(render_wsl_host_interop_command(&request.command))
}
(EnvironmentKind::Wsl { distribution }, ExecutionMode::Native) => {
if is_host_executable_path(&request.command.program) {
return Err(CascadeError::new(format!(
"native WSL environment `{distribution}` requires a guest-side executable; `{}` is host-owned",
request.command.program
)));
}
if let Some((_, mcp_command)) = request
.command
.env
.iter()
.find(|(key, _)| key == "CASCADE_MCP_COMMAND")
&& is_host_executable_path(mcp_command)
{
return Err(CascadeError::new(format!(
"native WSL environment `{distribution}` requires a guest-side Cascade MCP executable; `{mcp_command}` is host-owned"
)));
}
Ok(request.command.clone())
}
}
}
}
pub fn render_wsl_host_interop_command(command: &EnvironmentCommand) -> EnvironmentCommand {
let mut rendered = command.clone();
if let Some(program) = windows_path_to_wsl(&rendered.program) {
rendered.program = program;
}
rendered
}
pub fn render_wsl_launch(request: &WslLaunchRequest) -> CascadeResult<EnvironmentCommand> {
let distribution = request
.distribution
.clone()
.unwrap_or_else(|| "default".to_owned());
let inner = DefaultEnvironmentCommandRenderer.render(&EnvironmentRenderRequest {
environment: EnvironmentKind::Wsl { distribution },
execution_mode: request.execution_mode,
command: request.command.clone(),
})?;
let mut args = Vec::new();
if let Some(distribution) = &request.distribution {
args.extend(["--distribution".to_owned(), distribution.clone()]);
}
args.extend([
"--cd".to_owned(),
request.cwd.to_string_lossy().into_owned(),
"--exec".to_owned(),
]);
if !inner.env.is_empty() {
args.push("env".to_owned());
args.extend(
inner
.env
.iter()
.map(|(key, value)| format!("{key}={value}")),
);
}
args.push(inner.program);
args.extend(inner.args);
Ok(EnvironmentCommand::new("wsl", args))
}
pub fn windows_path_to_wsl(value: &str) -> Option<String> {
let bytes = value.as_bytes();
if bytes.len() < 3
|| !bytes[0].is_ascii_alphabetic()
|| bytes[1] != b':'
|| !matches!(bytes[2], b'\\' | b'/')
{
return None;
}
let drive = (bytes[0] as char).to_ascii_lowercase();
let tail = value[3..].replace('\\', "/");
Some(format!("/mnt/{drive}/{tail}"))
}
fn is_host_executable_path(program: &str) -> bool {
windows_path_to_wsl(program).is_some() || is_wsl_mounted_host_path(program)
}
fn is_wsl_mounted_host_path(program: &str) -> bool {
let normalized = program.replace('\\', "/");
let mut components = normalized.split('/').filter(|part| !part.is_empty());
matches!(
(components.next(), components.next(), components.next()),
(Some("mnt"), Some(drive), Some(_))
if drive.len() == 1
&& drive.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
)
}
#[cfg(test)]
mod tests {
use super::*;
fn request(
environment: EnvironmentKind,
execution_mode: ExecutionMode,
program: &str,
) -> EnvironmentRenderRequest {
EnvironmentRenderRequest {
environment,
execution_mode,
command: EnvironmentCommand {
program: program.to_owned(),
args: vec!["agent-run".to_owned(), "repo".to_owned()],
env: vec![("CASCADE_BRANCH".to_owned(), "dev".to_owned())],
},
}
}
#[test]
fn host_rendering_preserves_structured_command() {
let request = request(EnvironmentKind::Host, ExecutionMode::Native, "cascade");
assert_eq!(
DefaultEnvironmentCommandRenderer.render(&request).unwrap(),
request.command
);
}
#[test]
fn host_interop_translates_only_windows_executable_boundary() {
let request = request(
EnvironmentKind::wsl("Ubuntu").unwrap(),
ExecutionMode::HostInterop,
"Z:\\tools\\cascade.exe",
);
let rendered = DefaultEnvironmentCommandRenderer.render(&request).unwrap();
assert_eq!(rendered.program, "/mnt/z/tools/cascade.exe");
assert_eq!(rendered.args, request.command.args);
assert_eq!(rendered.env, request.command.env);
}
#[test]
fn native_wsl_preserves_guest_command() {
let request = request(
EnvironmentKind::wsl("Ubuntu").unwrap(),
ExecutionMode::Native,
"/home/user/.local/bin/cascade",
);
assert_eq!(
DefaultEnvironmentCommandRenderer.render(&request).unwrap(),
request.command
);
}
#[test]
fn native_wsl_rejects_windows_and_mounted_host_executables() {
for program in ["E:\\code\\cascade\\cascade.exe", "/mnt/c/tools/cascade.exe"] {
let request = request(
EnvironmentKind::wsl("Ubuntu").unwrap(),
ExecutionMode::Native,
program,
);
let error = DefaultEnvironmentCommandRenderer
.render(&request)
.expect_err("host executable must be rejected");
assert!(
error
.to_string()
.contains("requires a guest-side executable")
);
}
}
#[test]
fn native_wsl_rejects_host_owned_mcp_command() {
let mut request = request(
EnvironmentKind::wsl("Ubuntu").unwrap(),
ExecutionMode::Native,
"codex",
);
request.command.env.push((
"CASCADE_MCP_COMMAND".to_owned(),
"E:\\tools\\cascade.exe".to_owned(),
));
let error = DefaultEnvironmentCommandRenderer
.render(&request)
.expect_err("host MCP executable must be rejected");
assert!(
error
.to_string()
.contains("guest-side Cascade MCP executable")
);
}
#[test]
fn wsl_launch_renders_distribution_cwd_environment_and_native_command() {
let rendered = render_wsl_launch(&WslLaunchRequest {
distribution: Some("Ubuntu".to_owned()),
execution_mode: ExecutionMode::Native,
cwd: PathBuf::from("/home/user/project"),
command: EnvironmentCommand {
program: "/home/user/.local/bin/cascade".to_owned(),
args: vec!["agent-run".to_owned(), "dev".to_owned()],
env: vec![("CASCADE_MCP_COMMAND".to_owned(), "cascade".to_owned())],
},
})
.unwrap();
assert_eq!(rendered.program, "wsl");
assert_eq!(
rendered.args,
[
"--distribution",
"Ubuntu",
"--cd",
"/home/user/project",
"--exec",
"env",
"CASCADE_MCP_COMMAND=cascade",
"/home/user/.local/bin/cascade",
"agent-run",
"dev",
]
);
}
#[test]
fn wsl_launch_preserves_default_distribution_and_host_interop_arguments() {
let rendered = render_wsl_launch(&WslLaunchRequest {
distribution: None,
execution_mode: ExecutionMode::HostInterop,
cwd: PathBuf::from("C:/code/project"),
command: EnvironmentCommand::new(
"E:\\tools\\cascade.exe",
vec!["agent-run".to_owned(), "C:/code/project".to_owned()],
),
})
.unwrap();
assert_eq!(
rendered.args,
[
"--cd",
"C:/code/project",
"--exec",
"/mnt/e/tools/cascade.exe",
"agent-run",
"C:/code/project",
]
);
}
#[test]
fn windows_path_conversion_is_drive_and_user_independent() {
assert_eq!(
windows_path_to_wsl("Q:/code/project/cascade.exe").as_deref(),
Some("/mnt/q/code/project/cascade.exe")
);
assert!(windows_path_to_wsl("/usr/local/bin/cascade").is_none());
assert!(windows_path_to_wsl("cascade").is_none());
}
}