Skip to main content

agentmux_bashwrap/
gh_shim.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `gh` as a program, for the callers the `gh` shell function never reaches.
5//!
6//! An agent's `gh` is a bash function (`agentmux_common::github_broker_shim::GH_FUNCTION_BODY`) that asks this
7//! wrapper for the token of the repository the command is about. A function exists only in the bash that imported
8//! it: `timeout 60 gh pr create`, `xargs gh`, `env gh`, `make`, a script with a `#!/bin/sh` line or a Python
9//! `subprocess` all start the real `gh` binary, which has no login in a container and says "gh auth login".
10//!
11//! In a container's image this wrapper is also installed as `/usr/local/bin/gh` (a symlink, ahead of the real `gh`
12//! on PATH). Started under that name it does what the function does, with the function's own text, and then runs
13//! the real `gh`. No token is stored: each call asks for one, as the function does.
14
15use std::ffi::{OsStr, OsString};
16use std::path::{Path, PathBuf};
17use std::process::Command;
18
19use agentmux_common::github_broker_shim::GH_FUNCTION_BODY;
20
21/// Where the function body finds the real `gh` (it says `command gh` in a shell, which would find this program).
22const REAL_GH_ENV: &str = "AGENTMUX_REAL_GH";
23/// Set by the function when it runs `gh`, so this program does not do the same work a second time.
24const DONE_ENV: &str = "AGENTMUX_GH_SHIM_DONE";
25/// Set by srv for an agent whose GitHub access goes through AgentMux.
26const BROKER_ENV: &str = "AGENTMUX_GITHUB_BROKER";
27
28/// Whether the program was started as `gh` (or `gh.exe`).
29pub(crate) fn invoked_as_gh(argv0: &OsStr) -> bool {
30    Path::new(argv0).file_stem().is_some_and(|s| s.eq_ignore_ascii_case("gh"))
31}
32
33/// The shell text that is the function, calling the real `gh` by the path in [`REAL_GH_ENV`], then running it.
34fn script() -> String {
35    format!("gh {}\ngh \"$@\"", GH_FUNCTION_BODY.replace("command gh ", &format!("\"${REAL_GH_ENV}\" ")))
36}
37
38/// The first `gh` on `path` that is not `me` (this program, which the symlink makes one of them).
39pub(crate) fn real_gh_in(path: &OsStr, me: Option<&Path>) -> Option<PathBuf> {
40    let me = me.map(|m| m.canonicalize().unwrap_or_else(|_| m.to_path_buf()));
41    std::env::split_paths(path).map(|d| d.join("gh")).find(|c| {
42        c.is_file() && me.as_ref().is_none_or(|me| &c.canonicalize().unwrap_or_else(|_| c.clone()) != me)
43    })
44}
45
46/// The command that runs `gh` with `args`: through the function's steps when the agent's GitHub access is
47/// brokered and the function has not run them already, else the real `gh` as it is.
48fn command_for(bash: &Path, real: &Path, args: &[OsString], brokered: bool) -> Command {
49    let mut cmd = if brokered {
50        let mut cmd = Command::new(bash);
51        cmd.arg("-c").arg(script()).arg("gh").args(args).env(REAL_GH_ENV, real);
52        cmd
53    } else {
54        let mut cmd = Command::new(real);
55        cmd.args(args);
56        cmd
57    };
58    // Only a container's image has this program as `gh`; the flag keeps a console from opening if it is ever run on Windows.
59    #[cfg(windows)]
60    {
61        use agentmux_common::win32::NoWindow;
62        cmd.no_window();
63    }
64    cmd
65}
66
67fn launch(mut cmd: Command) -> i32 {
68    #[cfg(unix)]
69    {
70        use std::os::unix::process::CommandExt;
71        // exec only returns when it failed.
72        let err = cmd.exec();
73        eprintln!("agentmux: gh could not be started: {err}");
74        127
75    }
76    #[cfg(not(unix))]
77    {
78        match cmd.status() {
79            Ok(s) => s.code().unwrap_or(1),
80            Err(e) => {
81                eprintln!("agentmux: gh could not be started: {e}");
82                127
83            }
84        }
85    }
86}
87
88/// When this program was started as `gh`: run `gh` and give the exit code. `None` for any other name.
89pub(crate) fn run_if_invoked_as_gh() -> Option<i32> {
90    let argv: Vec<OsString> = std::env::args_os().collect();
91    if !invoked_as_gh(argv.first()?) {
92        return None;
93    }
94    let me = std::env::current_exe().ok();
95    let path = std::env::var_os("PATH").unwrap_or_default();
96    let Some(real) = std::env::var_os(REAL_GH_ENV).map(PathBuf::from).or_else(|| real_gh_in(&path, me.as_deref())) else {
97        eprintln!("agentmux: the GitHub CLI (gh) is not installed here, so there is nothing to run. Ask your leader to update this agent's image.");
98        return Some(127);
99    };
100    let set = |name: &str| std::env::var_os(name).is_some_and(|v| !v.is_empty());
101    let brokered = set(BROKER_ENV) && !set(DONE_ENV);
102    Some(launch(command_for(Path::new("bash"), &real, &argv[1..], brokered)))
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    fn os(a: &[&str]) -> Vec<OsString> {
110        a.iter().map(OsString::from).collect()
111    }
112
113    #[test]
114    fn it_answers_to_the_name_gh_and_no_other() {
115        assert!(invoked_as_gh(OsStr::new("/usr/local/bin/gh")));
116        assert!(invoked_as_gh(OsStr::new("gh")));
117        assert!(invoked_as_gh(OsStr::new("/usr/local/bin/GH.exe")));
118        assert!(!invoked_as_gh(OsStr::new("/usr/local/bin/agentmux-bashwrap")));
119        assert!(!invoked_as_gh(OsStr::new("ghost")));
120    }
121
122    /// Backslashes separate directories on Windows only.
123    #[cfg(windows)]
124    #[test]
125    fn a_windows_path_names_gh_too() {
126        assert!(invoked_as_gh(OsStr::new("C:\\bin\\GH.exe")));
127    }
128
129    #[test]
130    fn the_script_is_the_function_calling_the_real_gh_by_path() {
131        let s = script();
132        assert!(!s.contains("command gh"), "{s}");
133        assert!(s.contains("\"$AGENTMUX_REAL_GH\" \"$@\""), "{s}");
134        assert!(s.starts_with("gh () {") || s.starts_with("gh() {") || s.starts_with("gh () "), "{s}");
135        assert!(s.ends_with("gh \"$@\""), "{s}");
136        // The same steps as the function: the container verbs, the text guard, the token, the owner tag.
137        for step in ["github-container", "github-text-guard", "github-token", "github-owner-tag"] {
138            assert!(s.contains(step), "{step}");
139        }
140    }
141
142    #[cfg(unix)]
143    #[test]
144    fn the_real_gh_is_the_first_one_that_is_not_this_program() {
145        use std::os::unix::fs::{symlink, PermissionsExt};
146        let root = std::env::temp_dir().join(format!("amx-gh-shim-find-{}", std::process::id()));
147        let (a, b) = (root.join("a"), root.join("b"));
148        std::fs::create_dir_all(&a).unwrap();
149        std::fs::create_dir_all(&b).unwrap();
150        let me = a.join("agentmux-bashwrap");
151        std::fs::write(&me, "x").unwrap();
152        symlink(&me, a.join("gh")).unwrap();
153        std::fs::write(b.join("gh"), "#!/bin/sh\n").unwrap();
154        std::fs::set_permissions(b.join("gh"), std::fs::Permissions::from_mode(0o755)).unwrap();
155        let path = std::env::join_paths([&a, &b]).unwrap();
156        assert_eq!(real_gh_in(&path, Some(&me)), Some(b.join("gh")));
157        // Nothing else on PATH: no gh, so no answer, never this program again.
158        assert_eq!(real_gh_in(&std::env::join_paths([&a]).unwrap(), Some(&me)), None);
159        let _ = std::fs::remove_dir_all(&root);
160    }
161
162    /// A fake `agentmux-bashwrap` (the text guard passes the arguments on, the token helper prints `token`) and a
163    /// fake real `gh` that says what it was given.
164    fn run(brokered: bool, token: &str, inherited: &str) -> Option<String> {
165        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
166        let bash = crate::bash_wrap::locate_bash().ok()?;
167        let dir = std::env::temp_dir().join(format!("amx-gh-shim-run-{}-{}", std::process::id(), brokered as u8));
168        std::fs::create_dir_all(&dir).unwrap();
169        let script_file = |name: &str, body: &str| {
170            let p = dir.join(name);
171            std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
172            #[cfg(unix)]
173            {
174                use std::os::unix::fs::PermissionsExt;
175                std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
176            }
177            p
178        };
179        let real = script_file("real-gh", "echo \"gh GH_TOKEN=[$GH_TOKEN] GITHUB_TOKEN=[$GITHUB_TOKEN] DONE=[$AGENTMUX_GH_SHIM_DONE] args=$*\"");
180        script_file(
181            "agentmux-bashwrap",
182            &format!("case \"$1\" in github-text-guard) shift; shift; for a in \"$@\"; do printf '%s\\0' \"$a\"; done; printf 'ok\\0';; github-token) printf '%s' '{token}';; esac"),
183        );
184        let path = std::env::join_paths(std::iter::once(dir.clone()).chain(std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()))).unwrap();
185        let mut cmd = command_for(&bash, &real, &os(&["pr", "list"]), brokered);
186        cmd.env("PATH", path).env(BROKER_ENV, "1").env("GH_TOKEN", inherited).env_remove("GITHUB_TOKEN").env_remove("AGENTMUX_IN_CONTAINER");
187        #[cfg(windows)]
188        {
189            use agentmux_common::win32::NoWindow;
190            cmd.no_window();
191        }
192        let out = cmd.output().unwrap();
193        let _ = std::fs::remove_dir_all(&dir);
194        Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
195    }
196
197    #[test]
198    fn a_brokered_call_runs_the_real_gh_with_the_repositorys_token_or_none() {
199        // The token srv gave, for both names, and the marker that says the steps were done.
200        let Some(got) = run(true, "ghs_X", "mine") else { return };
201        assert_eq!(got, "gh GH_TOKEN=[ghs_X] GITHUB_TOKEN=[ghs_X] DONE=[1] args=pr list");
202        // No token (a refusal): none, never the one the environment happened to carry.
203        assert_eq!(run(true, "", "mine").unwrap(), "gh GH_TOKEN=[] GITHUB_TOKEN=[] DONE=[1] args=pr list");
204    }
205
206    /// Windows can't start a shell script as a program, so the fake real `gh` runs there only through bash (the test above).
207    #[cfg(unix)]
208    #[test]
209    fn a_call_with_no_broker_is_the_real_gh_as_it_is() {
210        let Some(got) = run(false, "ghs_X", "mine") else { return };
211        assert_eq!(got, "gh GH_TOKEN=[mine] GITHUB_TOKEN=[] DONE=[] args=pr list");
212    }
213}