agentmux_bashwrap/
gh_shim.rs1use std::ffi::{OsStr, OsString};
16use std::path::{Path, PathBuf};
17use std::process::Command;
18
19use agentmux_common::github_broker_shim::GH_FUNCTION_BODY;
20
21const REAL_GH_ENV: &str = "AGENTMUX_REAL_GH";
23const DONE_ENV: &str = "AGENTMUX_GH_SHIM_DONE";
25const BROKER_ENV: &str = "AGENTMUX_GITHUB_BROKER";
27
28pub(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
33fn script() -> String {
35 format!("gh {}\ngh \"$@\"", GH_FUNCTION_BODY.replace("command gh ", &format!("\"${REAL_GH_ENV}\" ")))
36}
37
38pub(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
46fn 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 #[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 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
88pub(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 #[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 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 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 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 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 assert_eq!(run(true, "", "mine").unwrap(), "gh GH_TOKEN=[] GITHUB_TOKEN=[] DONE=[1] args=pr list");
204 }
205
206 #[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}