Skip to main content

agent_hub_runtime/core/terminal/
shell.rs

1use anyhow::Result;
2use portable_pty::CommandBuilder;
3use serde::Serialize;
4use std::path::{Path, PathBuf};
5
6/// Prompt markers are shell integration, never Agent activity inference.
7pub struct ShellIntegration {
8    _files: Option<tempfile::TempDir>,
9    nonce: String,
10}
11#[derive(Clone, Default, Serialize)]
12pub struct LaunchState {
13    pub ready: bool,
14    pub revision: u64,
15    pub herdr_active: bool,
16}
17pub(super) struct ShellState {
18    pub state: LaunchState,
19    tail: Vec<u8>,
20    awaiting_prompt: bool,
21    pub integration: Option<ShellIntegration>,
22}
23impl Default for ShellState {
24    fn default() -> Self {
25        Self {
26            state: LaunchState::default(),
27            tail: Vec::new(),
28            integration: None,
29            awaiting_prompt: true,
30        }
31    }
32}
33impl ShellState {
34    pub fn input(&mut self, bytes: &[u8], foreground_program: bool) {
35        self.state.revision += 1;
36        self.state.ready = false;
37        if !foreground_program {
38            for byte in bytes {
39                self.awaiting_prompt = matches!(byte, b'\r' | b'\n' | 3);
40            }
41        }
42    }
43
44    pub fn new(integration: Option<ShellIntegration>) -> Self {
45        Self {
46            integration,
47            ..Default::default()
48        }
49    }
50    pub fn observe(&mut self, data: &[u8]) {
51        let Some(integration) = &self.integration else {
52            return;
53        };
54        let ready = format!("\x1b]633;AH;{};R\x07", integration.nonce).into_bytes();
55        let busy = format!("\x1b]633;AH;{};B\x07", integration.nonce).into_bytes();
56        self.tail.extend_from_slice(data);
57        let r = self
58            .tail
59            .windows(ready.len())
60            .rposition(|value| value == ready);
61        let b = self
62            .tail
63            .windows(busy.len())
64            .rposition(|value| value == busy);
65        if let Some(r) = r {
66            if b.map_or(true, |b| r > b) {
67                self.state.ready = self.awaiting_prompt;
68                self.awaiting_prompt = false;
69                self.state.herdr_active = false;
70            }
71        }
72        if let Some(b) = b {
73            if r.map_or(true, |r| b > r) {
74                self.state.ready = false;
75            }
76        }
77        let keep = ready.len().max(busy.len()) - 1;
78        if self.tail.len() > keep {
79            self.tail.drain(..self.tail.len() - keep);
80        }
81    }
82}
83use super::launch_command::quote_posix as quote;
84fn source(path: &Path) -> String {
85    format!(
86        "if [ -r {0} ]; then . {0}; fi\n",
87        quote(&path.to_string_lossy())
88    )
89}
90
91/// Prepare prompt integration without modifying the user's startup files.
92/// Unknown shells remain usable without prompt markers.
93pub fn prepare_shell(
94    program: Option<&Path>,
95    startup_directory: Option<&Path>,
96) -> Result<(CommandBuilder, ShellIntegration)> {
97    #[cfg(windows)]
98    let default = std::env::var_os("COMSPEC").unwrap_or_else(|| "cmd.exe".into());
99    #[cfg(not(windows))]
100    let default = std::env::var_os("SHELL").unwrap_or_else(|| "/bin/sh".into());
101    let program = program.map(PathBuf::from).unwrap_or_else(|| default.into());
102    let kind = program
103        .file_stem()
104        .and_then(|value| value.to_str())
105        .unwrap_or("")
106        .to_ascii_lowercase();
107    let nonce = uuid::Uuid::new_v4().simple().to_string();
108    let marker = format!("\\033]633;AH;{nonce};R\\007");
109    let busy = format!("\\033]633;AH;{nonce};B\\007");
110    let mut command = CommandBuilder::new(&program);
111    command.env("TERM", "xterm-256color");
112    command.env("COLORTERM", "truecolor");
113    // A nested launch must not inherit a different Herdr pane's caller identity.
114    for name in crate::core::agent_runtime::INHERITED_CONTEXT {
115        command.env_remove(name);
116    }
117    let mut files = None;
118    match kind.as_str() {
119        "zsh" => {
120            let directory = tempfile::tempdir()?;
121            let original = startup_directory
122                .map(PathBuf::from)
123                .or_else(|| std::env::var_os("ZDOTDIR").map(PathBuf::from))
124                .or_else(dirs::home_dir)
125                .ok_or_else(|| anyhow::anyhow!("Cannot resolve Shell startup directory"))?;
126            /* original user configuration, independent of the temporary integration directory */
127            let setup = directory.path();
128            std::fs::write(
129                setup.join(".zshenv"),
130                format!(
131                    "{}\nZDOTDIR={}\n",
132                    source(&original.join(".zshenv")),
133                    quote(&setup.to_string_lossy())
134                ),
135            )?;
136            std::fs::write(setup.join(".zshrc"), format!("ZDOTDIR={}\n{}\nautoload -Uz add-zsh-hook\n_agent_hub_ready() {{ printf '{marker}'; }}\n_agent_hub_busy() {{ printf '{busy}'; }}\nadd-zsh-hook precmd _agent_hub_ready\nadd-zsh-hook preexec _agent_hub_busy\n", quote(&original.to_string_lossy()), source(&original.join(".zshrc"))))?;
137            command.env("ZDOTDIR", setup);
138            command.arg("-i");
139            files = Some(directory);
140        }
141        "bash" => {
142            let directory = tempfile::tempdir()?;
143            let rc = directory.path().join("bashrc");
144            let user_rc = startup_directory
145                .map(PathBuf::from)
146                .or_else(dirs::home_dir)
147                .map(|home| source(&home.join(".bashrc")))
148                .unwrap_or_default();
149            // PROMPT_COMMAND runs only on prompt entry. PS1 is also printed on
150            // readline redraw (e.g. Ctrl+L), when an unfinished draft may exist.
151            std::fs::write(&rc, format!("{user_rc}\n_agent_hub_prompt() {{ printf '{marker}'; }}\nif [[ $(declare -p PROMPT_COMMAND 2>/dev/null) == 'declare -a '* ]]; then\n  PROMPT_COMMAND+=(_agent_hub_prompt)\nelse\n  PROMPT_COMMAND=\"${{PROMPT_COMMAND}}\"$'\\n''_agent_hub_prompt'\nfi\n"))?;
152            command.arg("--rcfile");
153            command.arg(rc);
154            command.arg("-i");
155            files = Some(directory);
156        }
157        "cmd" => {
158            command.env("PROMPT", format!("\x1b]633;AH;{nonce};R\x07$P$G"));
159        }
160        _ => {
161            #[cfg(not(windows))]
162            command.arg("-i");
163        }
164    }
165    Ok((
166        command,
167        ShellIntegration {
168            _files: files,
169            nonce,
170        },
171    ))
172}