Skip to main content

agentmux_srv_core/backend/
shellintegration.rs

1// Copyright 2026, Command Line Inc.
2// Copyright 2026, AgentMux Corp.
3// SPDX-License-Identifier: Apache-2.0
4
5//! Shell integration script deployment and shell startup configuration.
6//!
7//! Embeds shell integration scripts (bash, zsh, pwsh, fish) and deploys them to
8//! `~/.agentmux/shell/<type>/` on first use or when the version changes.
9//! The shell controller uses these scripts to install prompt hooks that send
10//! OSC 16162;E commands carrying `AGENTMUX_AGENT_ID`, enabling per-pane title
11//! and color to work.
12
13use std::path::{Path, PathBuf};
14
15// ─── Embedded scripts ────────────────────────────────────────────────────────
16
17const BASH_SCRIPT: &str = include_str!("shellintegration/bash.sh");
18const ZSH_SCRIPT: &str = include_str!("shellintegration/zsh.sh");
19const PWSH_SCRIPT: &str = include_str!("shellintegration/pwsh.ps1");
20const FISH_SCRIPT: &str = include_str!("shellintegration/fish.fish");
21/// Shared muxlog core (Node). Deployed once at `<shell>/muxlog.mjs`; every
22/// shell's `muxlog` function delegates to it. One tested implementation does log
23/// discovery + NDJSON rendering + filtering for all shells.
24const MUXLOG_JS: &str = include_str!("shellintegration/muxlog.mjs");
25/// Shared muxspect core (Node) — muxlog's live-state sibling. Deployed once
26/// at `<shell>/muxspect.mjs`; every shell's `muxspect` function delegates to
27/// it. See docs/specs/SPEC_MUXSPECT_LIVE_INTROSPECTION_TOOL_2026_08_01.md.
28const MUXSPECT_JS: &str = include_str!("shellintegration/muxspect.mjs");
29/// muxopen — launch an agent into a pane from a terminal (the constructive
30/// sibling of the stop verbs; REPORT_AGENT_OPEN_API_GAP_2026_09_06.md).
31/// Deployed beside muxlog.mjs/muxspect.mjs; shell `muxopen` functions
32/// delegate here.
33const MUXOPEN_JS: &str = include_str!("shellintegration/muxopen.mjs");
34/// muxsh — open editor/browser panes from a terminal
35/// (REPORT_WSH_STYLE_CLI_FOR_AGENT_APP_API_2026_09_16.md,
36/// SPEC_MUXSH_CLI_2026_09_16.md). Deployed beside its three siblings; shell
37/// `muxsh` functions delegate here.
38const MUXSH_JS: &str = include_str!("shellintegration/muxsh.mjs");
39/// Shared auth-env-read + authenticated-fetch plumbing every core above
40/// (except muxlog, which does no REST calls) imports via a relative
41/// `./lib/muxclient.mjs` — so it must be deployed at `<shell>/lib/`, not
42/// flat beside its callers. See
43/// docs/specs/SPEC_MUXSH_FULL_COLLECTION_2026_09_16.md §2.8.
44const MUXCLIENT_JS: &str = include_str!("shellintegration/lib/muxclient.mjs");
45
46/// Deployment marker: `<package version>-<content hash>`, NOT the bare
47/// package version alone (codex P2 on PR #2380). Local/dev builds routinely
48/// iterate on these embedded scripts WITHOUT a version bump (this repo's own
49/// convention — see CLAUDE.md's "Build versioning — local builds are
50/// *labeled*, not *versioned*"), so a version-only marker left `.version`
51/// already matching on every same-version rebuild/restart, silently
52/// skipping deployment of a newly-added or newly-edited script (muxspect.mjs
53/// specifically, added in the same PR that added the startup call site —
54/// the marker never invalidated to pick it up). Hashing the actual embedded
55/// content means ANY change to ANY script forces a redeploy regardless of
56/// whether the package version moved, while an unchanged rebuild still
57/// skips the (cheap, but not free) disk writes.
58fn version_marker() -> String {
59    use std::collections::hash_map::DefaultHasher;
60    use std::hash::{Hash, Hasher};
61    let mut hasher = DefaultHasher::new();
62    BASH_SCRIPT.hash(&mut hasher);
63    ZSH_SCRIPT.hash(&mut hasher);
64    PWSH_SCRIPT.hash(&mut hasher);
65    FISH_SCRIPT.hash(&mut hasher);
66    MUXLOG_JS.hash(&mut hasher);
67    MUXSPECT_JS.hash(&mut hasher);
68    // MUXOPEN_JS was missing here (an edit to muxopen.mjs alone never changed
69    // this marker, so a running instance never redeployed it) — fixed while
70    // adding MUXSH_JS below, same class of bug this function's own doc
71    // comment already warns about.
72    MUXOPEN_JS.hash(&mut hasher);
73    MUXSH_JS.hash(&mut hasher);
74    MUXCLIENT_JS.hash(&mut hasher);
75    format!("{}-{:x}", env!("CARGO_PKG_VERSION"), hasher.finish())
76}
77
78// ─── Shell type ──────────────────────────────────────────────────────────────
79
80#[derive(Debug, Clone, Copy, PartialEq)]
81pub enum ShellType {
82    Bash,
83    Zsh,
84    Pwsh,
85    Fish,
86    Unknown,
87}
88
89/// Detect shell type from the shell binary path.
90pub fn detect_shell_type(shell_path: &str) -> ShellType {
91    let name = Path::new(shell_path)
92        .file_stem()
93        .and_then(|s| s.to_str())
94        .unwrap_or("")
95        .to_lowercase();
96
97    match name.as_str() {
98        "pwsh" | "powershell" => ShellType::Pwsh,
99        "bash" => ShellType::Bash,
100        "zsh" => ShellType::Zsh,
101        "fish" => ShellType::Fish,
102        _ => ShellType::Unknown,
103    }
104}
105
106// ─── Deploy ──────────────────────────────────────────────────────────────────
107
108/// Deploy shell integration scripts into `<shell_root>/<type>/`.
109/// Skips deployment if the version marker is already current.
110/// Errors are logged but not fatal — a missing script just means no integration.
111/// Root under which this instance's shell-integration scripts are deployed.
112///
113/// Deliberately under the user's home rather than the instance data dir:
114/// MSIX virtualises writes to `%LocalAppData%`, so scripts written there are
115/// invisible to the ConPTY-spawned children that must source them, while `~`
116/// is never virtualised (see `shell/lifecycle.rs`'s spawn path).
117///
118/// Keyed per instance, because the home dir is otherwise machine-global and
119/// every instance of every version writes these same files — on every shell
120/// spawn, not just at boot. Two concurrently-running versions therefore
121/// rewrite each other's scripts indefinitely, and a shell can source an
122/// rcfile another instance is mid-replacement of. That is invariant **I6**
123/// (instances of different `(channel, version)` never share a directory),
124/// and the key mirrors **I5**'s `dir_hash` treatment of named OS objects.
125///
126/// The data dir is the right key: it is `<channel>/versions/<version>/data`
127/// by construction, so it already distinguishes exactly the pairs I6 names.
128pub fn integration_base_for(data_dir: &Path, home_dir: &Path) -> PathBuf {
129    home_dir.join(".agentmux").join("shell").join(instance_key(data_dir))
130}
131
132/// The folder name for an instance: a hash of its canonical, lowercased data dir.
133pub(super) fn instance_key(data_dir: &Path) -> String {
134    let canonical = data_dir.canonicalize().unwrap_or_else(|_| data_dir.to_path_buf());
135    format!("{:016x}", agentmux_common::runtime_mode::fnv1a_64(
136        canonical.to_string_lossy().to_lowercase().as_bytes(),
137    ))
138}
139
140/// The stable, user-facing script root: `~/.agentmux/shell`.
141///
142/// `docs/MUXSPECT.md` and `docs/MUXSH.md` document invoking these directly
143/// (`node ~/.agentmux/shell/muxspect.mjs …`) as the fallback when the shell
144/// function isn't defined. That path has to keep working and has to stay
145/// predictable — a user cannot know their instance's hash — so it is still
146/// deployed, shared, last-writer-wins. Nothing sources it at shell startup;
147/// the rcfiles a terminal actually loads come from `integration_base`.
148pub fn documented_shell_root() -> PathBuf {
149    crate::backend::base::get_mux_data_dir().join("shell")
150}
151
152/// `integration_base_for` bound to this process's real data dir and home.
153///
154/// Ordering note: `get_mux_data_dir()` reads `AGENTMUX_DATA_HOME`, which
155/// `bootstrap::open_stores_and_migrate` overwrites from the resolved
156/// `config.data_home` (CLI `--wavedata` winning over the launcher's env). Until
157/// that runs, the variable may still hold a value INHERITED from whichever
158/// instance spawned this process — observed live: a dev srv started from a
159/// terminal inside a 0.56.2 instance carried that instance's data dir. Both
160/// call sites (bootstrap's own deploy, and the shell spawn in
161/// `blockcontroller/shell/lifecycle.rs`) run after it, so both see the
162/// corrected value. Do not call this earlier in startup without checking that.
163pub fn integration_base() -> PathBuf {
164    integration_base_for(
165        &crate::backend::base::get_mux_data_dir(),
166        &crate::backend::base::get_home_dir(),
167    )
168}
169
170pub fn deploy_scripts(shell_root: &Path) {
171    let shell_base = shell_root.to_path_buf();
172    let version_file = shell_base.join(".version");
173    let marker = version_marker();
174
175    // Check if already up-to-date
176    if let Ok(existing) = std::fs::read_to_string(&version_file) {
177        if existing.trim() == marker {
178            return;
179        }
180    }
181
182    tracing::info!("Deploying shell integration scripts ({})", marker);
183
184    let deploys: &[(&str, &str, &str)] = &[
185        ("bash", ".bashrc", BASH_SCRIPT),
186        ("zsh", ".zshrc", ZSH_SCRIPT),
187        ("pwsh", "wavepwsh.ps1", PWSH_SCRIPT),
188        ("fish", "wave.fish", FISH_SCRIPT),
189    ];
190
191    let mut all_ok = true;
192    for (dir_name, file_name, content) in deploys {
193        let dir = shell_base.join(dir_name);
194        if let Err(e) = std::fs::create_dir_all(&dir) {
195            tracing::warn!("shell integration: failed to create {}: {}", dir.display(), e);
196            all_ok = false;
197            continue;
198        }
199        let path = dir.join(file_name);
200        if let Err(e) = std::fs::write(&path, content) {
201            tracing::warn!("shell integration: failed to write {}: {}", path.display(), e);
202            all_ok = false;
203        }
204    }
205
206    // Deploy the shared muxlog core next to the per-shell dirs. Each rcfile
207    // resolves it relative to its own location and delegates to `node muxlog.mjs`.
208    let muxlog_path = shell_base.join("muxlog.mjs");
209    if let Err(e) = std::fs::write(&muxlog_path, MUXLOG_JS) {
210        tracing::warn!("shell integration: failed to write {}: {}", muxlog_path.display(), e);
211        all_ok = false;
212    }
213
214    // Deploy the shared muxspect core the same way, right next to muxlog.mjs.
215    let muxspect_path = shell_base.join("muxspect.mjs");
216    if let Err(e) = std::fs::write(&muxspect_path, MUXSPECT_JS) {
217        tracing::warn!("shell integration: failed to write {}: {}", muxspect_path.display(), e);
218    }
219    // muxopen deploys the same way, next to its two siblings.
220    let muxopen_path = shell_base.join("muxopen.mjs");
221    if let Err(e) = std::fs::write(&muxopen_path, MUXOPEN_JS) {
222        tracing::warn!("shell integration: failed to write {}: {}", muxopen_path.display(), e);
223        all_ok = false;
224    }
225    // muxsh deploys the same way, next to its three siblings.
226    let muxsh_path = shell_base.join("muxsh.mjs");
227    if let Err(e) = std::fs::write(&muxsh_path, MUXSH_JS) {
228        tracing::warn!("shell integration: failed to write {}: {}", muxsh_path.display(), e);
229        all_ok = false;
230    }
231    // muxclient.mjs is imported via a relative `./lib/muxclient.mjs` from
232    // muxspect/muxopen/muxsh, so it must land in its own lib/ subdirectory,
233    // not flat beside them.
234    let lib_dir = shell_base.join("lib");
235    if let Err(e) = std::fs::create_dir_all(&lib_dir) {
236        tracing::warn!("shell integration: failed to create {}: {}", lib_dir.display(), e);
237        all_ok = false;
238    } else {
239        let muxclient_path = lib_dir.join("muxclient.mjs");
240        if let Err(e) = std::fs::write(&muxclient_path, MUXCLIENT_JS) {
241            tracing::warn!("shell integration: failed to write {}: {}", muxclient_path.display(), e);
242            all_ok = false;
243        }
244    }
245
246    // Write version marker only if all scripts deployed successfully
247    if all_ok {
248        let _ = std::fs::write(&version_file, &marker);
249    }
250}
251
252// ─── Startup configuration ───────────────────────────────────────────────────
253
254/// Shell startup configuration: extra args and env vars to inject.
255pub struct ShellStartup {
256    /// Extra args to append to the shell command.
257    pub extra_args: Vec<String>,
258    /// Environment variables to set in the PTY.
259    pub env_vars: Vec<(String, String)>,
260}
261
262/// Get the startup configuration for launching an interactive shell with
263/// AgentMux integration. Returns `None` for unknown shell types.
264pub fn get_shell_startup(
265    shell_type: ShellType,
266    shell_root: &Path,
267) -> Option<ShellStartup> {
268    match shell_type {
269        ShellType::Bash => {
270            let rcfile = shell_root.join("bash").join(".bashrc");
271            Some(ShellStartup {
272                extra_args: vec![
273                    "--rcfile".to_string(),
274                    rcfile.to_string_lossy().into_owned(),
275                ],
276                env_vars: vec![],
277            })
278        }
279        ShellType::Zsh => {
280            let zdotdir = shell_root.join("zsh");
281            Some(ShellStartup {
282                extra_args: vec![],
283                env_vars: vec![
284                    ("ZDOTDIR".to_string(), zdotdir.to_string_lossy().into_owned()),
285                    // Preserve original ZDOTDIR so the integration script can source ~/.zshrc
286                    ("AGENTMUX_ZDOTDIR".to_string(), zdotdir.to_string_lossy().into_owned()),
287                ],
288            })
289        }
290        ShellType::Pwsh => {
291            let script = shell_root
292                .join("pwsh")
293                .join("wavepwsh.ps1");
294            Some(ShellStartup {
295                extra_args: vec![
296                    "-ExecutionPolicy".to_string(),
297                    "Bypass".to_string(),
298                    "-NoExit".to_string(),
299                    "-File".to_string(),
300                    script.to_string_lossy().into_owned(),
301                ],
302                env_vars: vec![],
303            })
304        }
305        ShellType::Fish => {
306            let script = shell_root
307                .join("fish")
308                .join("wave.fish");
309            Some(ShellStartup {
310                extra_args: vec![
311                    "-C".to_string(),
312                    format!("source {}", agentmux_common::shell_quote::posix_single_quote(&script.to_string_lossy())),
313                ],
314                env_vars: vec![],
315            })
316        }
317        ShellType::Unknown => None,
318    }
319}
320
321// wsh has been retired — see docs/specs/archive/SPEC_RETIRE_WSH_2026_04_12.md.
322// The `AGENTMUX` env var is now a plain "1" sentinel, not a path.
323
324// ─── Helpers ─────────────────────────────────────────────────────────────────
325
326// ─── Tests ───────────────────────────────────────────────────────────────────
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331
332    #[test]
333    fn test_detect_shell_type() {
334        assert_eq!(detect_shell_type("bash"), ShellType::Bash);
335        assert_eq!(detect_shell_type("/bin/bash"), ShellType::Bash);
336        assert_eq!(detect_shell_type("zsh"), ShellType::Zsh);
337        assert_eq!(detect_shell_type("/usr/bin/zsh"), ShellType::Zsh);
338        assert_eq!(detect_shell_type("pwsh"), ShellType::Pwsh);
339        assert_eq!(detect_shell_type("powershell"), ShellType::Pwsh);
340        assert_eq!(detect_shell_type("fish"), ShellType::Fish);
341        assert_eq!(detect_shell_type("cmd.exe"), ShellType::Unknown);
342        assert_eq!(detect_shell_type("cmd"), ShellType::Unknown);
343    }
344
345    #[test]
346    fn test_bash_startup_args() {
347        let dir = Path::new("/home/user/.agentmux");
348        let startup = get_shell_startup(ShellType::Bash, dir).unwrap();
349        assert_eq!(startup.extra_args[0], "--rcfile");
350        assert!(startup.extra_args[1].contains("bash"));
351        assert!(startup.extra_args[1].ends_with(".bashrc"));
352    }
353
354    #[test]
355    fn test_pwsh_startup_args() {
356        let dir = Path::new("/home/user/.agentmux");
357        let startup = get_shell_startup(ShellType::Pwsh, dir).unwrap();
358        assert!(startup.extra_args.contains(&"-NoExit".to_string()));
359        assert!(startup.extra_args.contains(&"-File".to_string()));
360    }
361
362    #[test]
363    fn test_zsh_uses_zdotdir() {
364        let dir = Path::new("/home/user/.agentmux");
365        let startup = get_shell_startup(ShellType::Zsh, dir).unwrap();
366        assert!(startup.extra_args.is_empty());
367        assert!(startup.env_vars.iter().any(|(k, _)| k == "ZDOTDIR"));
368    }
369
370    #[test]
371    fn test_unknown_shell_returns_none() {
372        let dir = Path::new("/tmp");
373        assert!(get_shell_startup(ShellType::Unknown, dir).is_none());
374    }
375
376    /// `muxspect.mjs` deploys next to `muxlog.mjs` — codified as a test since
377    /// it's easy to add a new embedded script and forget the deploy line
378    /// (see docs/specs/SPEC_MUXSPECT_LIVE_INTROSPECTION_TOOL_2026_08_01.md).
379    #[test]
380    fn deploy_scripts_writes_muxlog_and_muxspect_side_by_side() {
381        let tmp = std::env::temp_dir().join(format!(
382            "agentmux-shellintegration-test-{}",
383            std::process::id()
384        ));
385        let _ = std::fs::remove_dir_all(&tmp);
386        deploy_scripts(&tmp.join("shell"));
387
388        let shell_base = tmp.join("shell");
389        let muxlog = shell_base.join("muxlog.mjs");
390        let muxspect = shell_base.join("muxspect.mjs");
391        let muxopen = shell_base.join("muxopen.mjs");
392        let muxsh = shell_base.join("muxsh.mjs");
393        let muxclient = shell_base.join("lib").join("muxclient.mjs");
394        assert!(muxlog.exists(), "muxlog.mjs should be deployed");
395        assert!(muxspect.exists(), "muxspect.mjs should be deployed alongside it");
396        assert!(muxopen.exists(), "muxopen.mjs should be deployed alongside them");
397        assert!(muxsh.exists(), "muxsh.mjs should be deployed alongside them");
398        assert!(
399            muxclient.exists(),
400            "lib/muxclient.mjs should be deployed — muxspect/muxopen/muxsh import it via a relative path"
401        );
402        assert_eq!(std::fs::read_to_string(&muxspect).unwrap(), MUXSPECT_JS);
403        assert_eq!(std::fs::read_to_string(&muxsh).unwrap(), MUXSH_JS);
404        assert_eq!(std::fs::read_to_string(&muxclient).unwrap(), MUXCLIENT_JS);
405
406        let _ = std::fs::remove_dir_all(&tmp);
407    }
408
409    /// codex P2 on PR #2380: a version-only marker left an EXISTING profile
410    /// (same CARGO_PKG_VERSION, older content) permanently skipping
411    /// deployment of a newly-added script — exactly what an existing
412    /// `~/.agentmux` from a prior same-version dev build would have. Content
413    /// hashing must force a redeploy in that case, not just on a genuinely
414    /// fresh profile (the only case the test above covers).
415    #[test]
416    fn deploy_scripts_redeploys_when_marker_predates_a_content_change() {
417        let tmp = std::env::temp_dir().join(format!(
418            "agentmux-shellintegration-test-stale-{}",
419            std::process::id()
420        ));
421        let _ = std::fs::remove_dir_all(&tmp);
422        let shell_base = tmp.join("shell");
423        std::fs::create_dir_all(&shell_base).unwrap();
424
425        // Simulate a profile deployed by an older build of shellintegration.rs
426        // that only ever wrote the bare package version as its marker (i.e.
427        // BEFORE this fix existed) — the exact "same version, no muxspect.mjs
428        // yet" scenario codex's finding describes.
429        std::fs::write(shell_base.join(".version"), env!("CARGO_PKG_VERSION")).unwrap();
430        assert!(!shell_base.join("muxspect.mjs").exists(), "precondition: not deployed yet");
431
432        deploy_scripts(&tmp.join("shell"));
433
434        assert!(
435            shell_base.join("muxspect.mjs").exists(),
436            "a stale version-only marker must not suppress deployment of a script that was never written"
437        );
438        assert_eq!(
439            std::fs::read_to_string(shell_base.join(".version")).unwrap(),
440            version_marker(),
441            "marker must be updated to the new content-hashed form"
442        );
443
444        let _ = std::fs::remove_dir_all(&tmp);
445    }
446
447    // ── Per-instance isolation (I6) ──────────────────────────────────────
448
449    /// THE invariant. Two instances differing only by channel or version must
450    /// never deploy into the same directory — otherwise each shell spawn in
451    /// one rewrites the scripts the other's shells source.
452    #[test]
453    fn two_instances_never_share_a_shell_integration_dir() {
454        let home = Path::new("/home/u");
455        let a = integration_base_for(Path::new("/ch/alpha/versions/0.56.2/data"), home);
456        let b = integration_base_for(Path::new("/ch/alpha/versions/0.56.3/data"), home);
457        let c = integration_base_for(Path::new("/ch/beta/versions/0.56.3/data"), home);
458        assert_ne!(a, b, "same channel, different version must not collide");
459        assert_ne!(b, c, "same version, different channel must not collide");
460        assert_ne!(a, c);
461    }
462
463    /// The path is recomputed on every shell spawn, so an unstable key would
464    /// send a later shell to a directory nothing was deployed into.
465    #[test]
466    fn the_same_instance_always_resolves_to_the_same_dir() {
467        let home = Path::new("/home/u");
468        let d = Path::new("/ch/alpha/versions/0.56.3/data");
469        assert_eq!(integration_base_for(d, home), integration_base_for(d, home));
470    }
471
472    /// Must stay under the home dir: MSIX virtualises `%LocalAppData%`, so a
473    /// data-dir-relative path would be invisible to the shells that source it.
474    #[test]
475    fn deployment_stays_under_the_never_virtualised_home_dir() {
476        let home = Path::new("/home/u");
477        let base = integration_base_for(Path::new("/ch/alpha/versions/0.56.3/data"), home);
478        assert!(base.starts_with(home), "must live under home, got {}", base.display());
479        assert!(!base.starts_with("/ch/alpha"), "must not live under the data dir");
480    }
481
482    /// The coupling that actually matters: whatever `deploy_scripts` writes,
483    /// `get_shell_startup` must point the shell AT. If these two drift apart,
484    /// scripts land where nothing sources them and every terminal silently
485    /// loses shell integration — with no error anywhere. Asserted by resolving
486    /// the startup arg to a real file on disk, not by comparing two strings
487    /// built the same way (which would pass even if both were wrong).
488    #[test]
489    fn the_deployed_rcfile_is_exactly_the_one_the_shell_is_told_to_load() {
490        let tmp = std::env::temp_dir().join(format!("am-si-couple-{}", std::process::id()));
491        let _ = std::fs::remove_dir_all(&tmp);
492        let root = tmp.join("shell");
493        deploy_scripts(&root);
494
495        let startup = get_shell_startup(ShellType::Bash, &root).expect("bash startup");
496        assert_eq!(startup.extra_args[0], "--rcfile");
497        let rcfile = Path::new(&startup.extra_args[1]);
498        assert!(
499            rcfile.exists(),
500            "shell is told to load {} but deploy_scripts never wrote it",
501            rcfile.display()
502        );
503
504        // And it must be the real script, not an empty placeholder.
505        let body = std::fs::read_to_string(rcfile).expect("read rcfile");
506        assert!(body.contains("_agentmux_si_prompt_command"), "rcfile is not the integration script");
507
508        let _ = std::fs::remove_dir_all(&tmp);
509    }
510}