Skip to main content

cascade_environment/
rendering.rs

1//! Environment-owned command adaptation.
2//!
3//! This module renders a command that is valid at the selected execution
4//! boundary. It does not open terminals or choose tabs, panes, or shells.
5
6use cascade_core::{CascadeError, CascadeResult};
7use serde::{Deserialize, Serialize};
8use std::path::PathBuf;
9
10use crate::{EnvironmentKind, ExecutionMode};
11
12/// Structured command before or after environment adaptation.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct EnvironmentCommand {
15    pub program: String,
16    pub args: Vec<String>,
17    pub env: Vec<(String, String)>,
18}
19
20impl EnvironmentCommand {
21    pub fn new(program: impl Into<String>, args: Vec<String>) -> Self {
22        Self {
23            program: program.into(),
24            args,
25            env: Vec::new(),
26        }
27    }
28}
29
30/// Complete input for one side-effect-free command adaptation.
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32pub struct EnvironmentRenderRequest {
33    pub environment: EnvironmentKind,
34    pub execution_mode: ExecutionMode,
35    pub command: EnvironmentCommand,
36}
37
38/// Host-side request for launching a command inside one WSL distribution.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct WslLaunchRequest {
41    /// Optional named distribution; `None` uses the user's default distribution.
42    pub distribution: Option<String>,
43    /// Native guest execution or Windows-host interoperability.
44    pub execution_mode: ExecutionMode,
45    /// Working directory passed to WSL before command execution.
46    pub cwd: PathBuf,
47    /// Inner agent or Cascade supervisor command.
48    pub command: EnvironmentCommand,
49}
50
51/// Side-effect-free boundary for host, WSL-native, and interoperability rendering.
52pub trait EnvironmentCommandRenderer {
53    fn render(&self, request: &EnvironmentRenderRequest) -> CascadeResult<EnvironmentCommand>;
54}
55
56/// Default renderer for host and WSL execution boundaries.
57#[derive(Debug, Clone, Copy, Default)]
58pub struct DefaultEnvironmentCommandRenderer;
59
60impl EnvironmentCommandRenderer for DefaultEnvironmentCommandRenderer {
61    fn render(&self, request: &EnvironmentRenderRequest) -> CascadeResult<EnvironmentCommand> {
62        match (&request.environment, request.execution_mode) {
63            (EnvironmentKind::Host, _) => Ok(request.command.clone()),
64            (EnvironmentKind::Wsl { .. }, ExecutionMode::HostInterop) => {
65                Ok(render_wsl_host_interop_command(&request.command))
66            }
67            (EnvironmentKind::Wsl { distribution }, ExecutionMode::Native) => {
68                if is_host_executable_path(&request.command.program) {
69                    return Err(CascadeError::new(format!(
70                        "native WSL environment `{distribution}` requires a guest-side executable; `{}` is host-owned",
71                        request.command.program
72                    )));
73                }
74                if let Some((_, mcp_command)) = request
75                    .command
76                    .env
77                    .iter()
78                    .find(|(key, _)| key == "CASCADE_MCP_COMMAND")
79                    && is_host_executable_path(mcp_command)
80                {
81                    return Err(CascadeError::new(format!(
82                        "native WSL environment `{distribution}` requires a guest-side Cascade MCP executable; `{mcp_command}` is host-owned"
83                    )));
84                }
85                Ok(request.command.clone())
86            }
87        }
88    }
89}
90
91/// Adapts a host command for WSL interoperability without choosing a shell.
92///
93/// This path is infallible: bare commands and already guest-visible paths are
94/// preserved, while absolute Windows executables are translated to `/mnt/...`.
95pub fn render_wsl_host_interop_command(command: &EnvironmentCommand) -> EnvironmentCommand {
96    let mut rendered = command.clone();
97    if let Some(program) = windows_path_to_wsl(&rendered.program) {
98        rendered.program = program;
99    }
100    rendered
101}
102
103/// Renders the complete host-side `wsl` invocation for one inner command.
104pub fn render_wsl_launch(request: &WslLaunchRequest) -> CascadeResult<EnvironmentCommand> {
105    let distribution = request
106        .distribution
107        .clone()
108        .unwrap_or_else(|| "default".to_owned());
109    let inner = DefaultEnvironmentCommandRenderer.render(&EnvironmentRenderRequest {
110        environment: EnvironmentKind::Wsl { distribution },
111        execution_mode: request.execution_mode,
112        command: request.command.clone(),
113    })?;
114    let mut args = Vec::new();
115    if let Some(distribution) = &request.distribution {
116        args.extend(["--distribution".to_owned(), distribution.clone()]);
117    }
118    args.extend([
119        "--cd".to_owned(),
120        request.cwd.to_string_lossy().into_owned(),
121        "--exec".to_owned(),
122    ]);
123    if !inner.env.is_empty() {
124        args.push("env".to_owned());
125        args.extend(
126            inner
127                .env
128                .iter()
129                .map(|(key, value)| format!("{key}={value}")),
130        );
131    }
132    args.push(inner.program);
133    args.extend(inner.args);
134
135    Ok(EnvironmentCommand::new("wsl", args))
136}
137
138/// Converts an absolute Windows path to its generic WSL mount path.
139///
140/// Non-Windows paths return `None`; callers can preserve them unchanged.
141pub fn windows_path_to_wsl(value: &str) -> Option<String> {
142    let bytes = value.as_bytes();
143    if bytes.len() < 3
144        || !bytes[0].is_ascii_alphabetic()
145        || bytes[1] != b':'
146        || !matches!(bytes[2], b'\\' | b'/')
147    {
148        return None;
149    }
150
151    let drive = (bytes[0] as char).to_ascii_lowercase();
152    let tail = value[3..].replace('\\', "/");
153    Some(format!("/mnt/{drive}/{tail}"))
154}
155
156fn is_host_executable_path(program: &str) -> bool {
157    windows_path_to_wsl(program).is_some() || is_wsl_mounted_host_path(program)
158}
159
160fn is_wsl_mounted_host_path(program: &str) -> bool {
161    let normalized = program.replace('\\', "/");
162    let mut components = normalized.split('/').filter(|part| !part.is_empty());
163    matches!(
164        (components.next(), components.next(), components.next()),
165        (Some("mnt"), Some(drive), Some(_))
166            if drive.len() == 1
167                && drive.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
168    )
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    fn request(
176        environment: EnvironmentKind,
177        execution_mode: ExecutionMode,
178        program: &str,
179    ) -> EnvironmentRenderRequest {
180        EnvironmentRenderRequest {
181            environment,
182            execution_mode,
183            command: EnvironmentCommand {
184                program: program.to_owned(),
185                args: vec!["agent-run".to_owned(), "repo".to_owned()],
186                env: vec![("CASCADE_BRANCH".to_owned(), "dev".to_owned())],
187            },
188        }
189    }
190
191    #[test]
192    fn host_rendering_preserves_structured_command() {
193        let request = request(EnvironmentKind::Host, ExecutionMode::Native, "cascade");
194
195        assert_eq!(
196            DefaultEnvironmentCommandRenderer.render(&request).unwrap(),
197            request.command
198        );
199    }
200
201    #[test]
202    fn host_interop_translates_only_windows_executable_boundary() {
203        let request = request(
204            EnvironmentKind::wsl("Ubuntu").unwrap(),
205            ExecutionMode::HostInterop,
206            "Z:\\tools\\cascade.exe",
207        );
208        let rendered = DefaultEnvironmentCommandRenderer.render(&request).unwrap();
209
210        assert_eq!(rendered.program, "/mnt/z/tools/cascade.exe");
211        assert_eq!(rendered.args, request.command.args);
212        assert_eq!(rendered.env, request.command.env);
213    }
214
215    #[test]
216    fn native_wsl_preserves_guest_command() {
217        let request = request(
218            EnvironmentKind::wsl("Ubuntu").unwrap(),
219            ExecutionMode::Native,
220            "/home/user/.local/bin/cascade",
221        );
222
223        assert_eq!(
224            DefaultEnvironmentCommandRenderer.render(&request).unwrap(),
225            request.command
226        );
227    }
228
229    #[test]
230    fn native_wsl_rejects_windows_and_mounted_host_executables() {
231        for program in ["E:\\code\\cascade\\cascade.exe", "/mnt/c/tools/cascade.exe"] {
232            let request = request(
233                EnvironmentKind::wsl("Ubuntu").unwrap(),
234                ExecutionMode::Native,
235                program,
236            );
237
238            let error = DefaultEnvironmentCommandRenderer
239                .render(&request)
240                .expect_err("host executable must be rejected");
241            assert!(
242                error
243                    .to_string()
244                    .contains("requires a guest-side executable")
245            );
246        }
247    }
248
249    #[test]
250    fn native_wsl_rejects_host_owned_mcp_command() {
251        let mut request = request(
252            EnvironmentKind::wsl("Ubuntu").unwrap(),
253            ExecutionMode::Native,
254            "codex",
255        );
256        request.command.env.push((
257            "CASCADE_MCP_COMMAND".to_owned(),
258            "E:\\tools\\cascade.exe".to_owned(),
259        ));
260
261        let error = DefaultEnvironmentCommandRenderer
262            .render(&request)
263            .expect_err("host MCP executable must be rejected");
264
265        assert!(
266            error
267                .to_string()
268                .contains("guest-side Cascade MCP executable")
269        );
270    }
271
272    #[test]
273    fn wsl_launch_renders_distribution_cwd_environment_and_native_command() {
274        let rendered = render_wsl_launch(&WslLaunchRequest {
275            distribution: Some("Ubuntu".to_owned()),
276            execution_mode: ExecutionMode::Native,
277            cwd: PathBuf::from("/home/user/project"),
278            command: EnvironmentCommand {
279                program: "/home/user/.local/bin/cascade".to_owned(),
280                args: vec!["agent-run".to_owned(), "dev".to_owned()],
281                env: vec![("CASCADE_MCP_COMMAND".to_owned(), "cascade".to_owned())],
282            },
283        })
284        .unwrap();
285
286        assert_eq!(rendered.program, "wsl");
287        assert_eq!(
288            rendered.args,
289            [
290                "--distribution",
291                "Ubuntu",
292                "--cd",
293                "/home/user/project",
294                "--exec",
295                "env",
296                "CASCADE_MCP_COMMAND=cascade",
297                "/home/user/.local/bin/cascade",
298                "agent-run",
299                "dev",
300            ]
301        );
302    }
303
304    #[test]
305    fn wsl_launch_preserves_default_distribution_and_host_interop_arguments() {
306        let rendered = render_wsl_launch(&WslLaunchRequest {
307            distribution: None,
308            execution_mode: ExecutionMode::HostInterop,
309            cwd: PathBuf::from("C:/code/project"),
310            command: EnvironmentCommand::new(
311                "E:\\tools\\cascade.exe",
312                vec!["agent-run".to_owned(), "C:/code/project".to_owned()],
313            ),
314        })
315        .unwrap();
316
317        assert_eq!(
318            rendered.args,
319            [
320                "--cd",
321                "C:/code/project",
322                "--exec",
323                "/mnt/e/tools/cascade.exe",
324                "agent-run",
325                "C:/code/project",
326            ]
327        );
328    }
329
330    #[test]
331    fn windows_path_conversion_is_drive_and_user_independent() {
332        assert_eq!(
333            windows_path_to_wsl("Q:/code/project/cascade.exe").as_deref(),
334            Some("/mnt/q/code/project/cascade.exe")
335        );
336        assert!(windows_path_to_wsl("/usr/local/bin/cascade").is_none());
337        assert!(windows_path_to_wsl("cascade").is_none());
338    }
339}