Skip to main content

agentmux_bashwrap/
prefix.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Prefix mode: `agentmux-bashwrap '<script>'` as Claude Code's
5//! `CLAUDE_CODE_SHELL_PREFIX`.
6//!
7//! The CLI runs every Bash tool command as `<prefix> '<its script>'` when the
8//! variable is set, and leaves the tool call itself alone: its permission
9//! rules, labels and checks see the model's own command. The `PreToolUse`
10//! hook records each call here (`register`) instead of rewriting it; the
11//! prefix process takes the model's command back out of the CLI's script,
12//! claims the matching record for the call's `tool_use_id`, and runs the
13//! whole script the way `exec` runs a command (bash_wrap.rs).
14//!
15//! docs/specs/SPEC_BASH_STREAMING_VIA_SHELL_PREFIX_2026_10_10.md §2.
16
17use std::ffi::OsString;
18use std::ops::Range;
19use std::path::{Path, PathBuf};
20use std::time::Duration;
21
22#[cfg(windows)]
23use agentmux_common::win32::NoWindow;
24use agentmux_common::time::now_ms_u64 as now_ms;
25use anyhow::{Context, Result};
26
27use serde::{Deserialize, Serialize};
28
29/// The CLI's environment variable naming the prefix.
30pub const SHELL_PREFIX_ENV: &str = "CLAUDE_CODE_SHELL_PREFIX";
31/// The CLI's session id, as the prefix process sees it. Equal to the
32/// `session_id` in the hook's payload.
33pub const SESSION_ID_ENV: &str = "CLAUDE_CODE_SESSION_ID";
34/// Overrides where records are kept (tests).
35const CALLS_DIR_OVERRIDE_ENV: &str = "AGENTMUX_BASHWRAP_CALLS_DIR";
36/// Records older than this are deleted on each claim: a call the CLI never
37/// ran (denied, interrupted) leaves its record behind.
38const RECORD_MAX_AGE: Duration = Duration::from_secs(3600);
39/// The subcommands, which a lone argument must not be mistaken for.
40const SUBCOMMANDS: &[&str] = &["exec", "hook", "precompact", "sessionstart", "git-credential", "github-token", "github-owner-tag", "github-text-guard", "git-hook", "git-env", "help"];
41
42/// One Bash call, as the hook saw it.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct CallRecord {
45    pub tool_use_id: String,
46    pub command: String,
47    #[serde(default)]
48    pub run_in_background: bool,
49    pub created_ms: u64,
50    /// What the model said the call does: Tower labels the process that ran
51    /// it with this (`report_call`).
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub description: Option<String>,
54    /// The subagent that made the call (the PreToolUse payload's
55    /// `agent_id`); none for the main conversation. Its working directory is
56    /// its own (`cwd_state::CwdState::load`).
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub agent_id: Option<String>,
59    /// Set on a claimed record when another agent ran the very same command
60    /// at the same moment: the CLI gives its shell no agent identity, so which
61    /// of the two records is this call's can't be told, and neither agent's
62    /// working directory is used (`claim`, `run`). Never stored.
63    #[serde(skip)]
64    pub agent_ambiguous: bool,
65}
66
67/// The marker, in a session's directory, saying two agents wait on `command`.
68/// Not a `.json`, so it is never read as a record. It holds the command, and
69/// lasts as long as a record of that command waits (`read_records`): the
70/// second call can wait at a permission prompt for long after the first.
71fn marker_path(dir: &Path, command: &str) -> PathBuf {
72    let hash = command.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));
73    dir.join(format!("{hash:016x}.ambiguous"))
74}
75
76fn mark_ambiguous(dir: &Path, command: &str) {
77    let _ = std::fs::write(marker_path(dir, command), command.as_bytes());
78}
79
80fn marked_ambiguous(dir: &Path, command: &str) -> bool {
81    marker_path(dir, command).exists()
82}
83
84/// Two waiting records of `command` from different agents (or one agent and
85/// the main conversation).
86fn agents_differ(records: &[&(PathBuf, CallRecord)]) -> bool {
87    records.windows(2).any(|w| w[0].1.agent_id != w[1].1.agent_id)
88}
89
90/// The longest description reported for a call.
91const MAX_DESCRIPTION_CHARS: usize = 200;
92
93/// The script, when this process was started as the CLI's shell prefix:
94/// exactly one argument, which is neither a subcommand nor a flag.
95///
96/// The CLI puts the prefix in front of more than Bash calls: hook commands,
97/// and every stdio MCP server, whose command and arguments it joins into
98/// that one argument. So a lone word is a prefix call too: the `agentmux`
99/// MCP server arrives as just `agentmux-mcp`, and refusing it as an unknown
100/// subcommand left agents without their AgentMux tools
101/// (docs/reports/REPORT_AGENT_MCP_DOWN_THROUGH_SHELL_PREFIX_2026_10_11.md).
102pub fn prefix_script(args: &[OsString]) -> Option<String> {
103    if args.len() != 2 {
104        return None;
105    }
106    let script = args[1].to_str()?;
107    let looks_like_cli_arg = script.starts_with('-') || SUBCOMMANDS.contains(&script);
108    (!looks_like_cli_arg && !script.trim().is_empty()).then(|| script.to_string())
109}
110
111/// Whether this process runs under a CLI whose shell prefix is AgentMux's
112/// wrapper, so the hook records calls instead of rewriting them.
113pub fn prefix_active() -> bool {
114    std::env::var_os(SHELL_PREFIX_ENV)
115        .map(|v| is_bashwrap_path(Path::new(&v)))
116        .unwrap_or(false)
117}
118
119fn is_bashwrap_path(path: &Path) -> bool {
120    path.file_stem()
121        .and_then(|s| s.to_str())
122        .map(|s| s.eq_ignore_ascii_case("agentmux-bashwrap"))
123        .unwrap_or(false)
124}
125
126/// The model's command inside the CLI's script, and where its quoted form
127/// sits in the script: the shell word after the CLI's `eval `, which the CLI
128/// quotes with single quotes (an embedded `'` becomes `'"'"'`). `None` when
129/// the script doesn't have one, e.g. after a change to the CLI's format.
130pub fn extract_command(script: &str) -> Option<(String, Range<usize>)> {
131    // The CLI's own `eval` comes before the command, which is inside it.
132    let at = script.find("&& eval '")? + "&& eval ".len();
133    let (command, end) = read_shell_word(script, at)?;
134    Some((command, at..end))
135}
136
137/// Read one shell word starting at `start`: single-quoted, double-quoted and
138/// backslash-escaped parts, up to unquoted whitespace or the end. Returns the
139/// word's value and the byte offset after it.
140fn read_shell_word(s: &str, start: usize) -> Option<(String, usize)> {
141    let bytes = s.as_bytes();
142    let mut out = String::new();
143    let mut i = start;
144    while i < bytes.len() {
145        match bytes[i] {
146            b'\'' => {
147                let close = s[i + 1..].find('\'')? + i + 1;
148                out.push_str(&s[i + 1..close]);
149                i = close + 1;
150            }
151            b'"' => {
152                i += 1;
153                loop {
154                    let c = *bytes.get(i)?;
155                    if c == b'"' {
156                        i += 1;
157                        break;
158                    }
159                    if c == b'\\' && matches!(bytes.get(i + 1), Some(b'"' | b'\\' | b'$' | b'`')) {
160                        out.push(bytes[i + 1] as char);
161                        i += 2;
162                        continue;
163                    }
164                    let ch = s[i..].chars().next()?;
165                    out.push(ch);
166                    i += ch.len_utf8();
167                }
168            }
169            b'\\' => {
170                let ch = s[i + 1..].chars().next()?;
171                out.push(ch);
172                i += 1 + ch.len_utf8();
173            }
174            c if c.is_ascii_whitespace() => break,
175            _ => {
176                let ch = s[i..].chars().next()?;
177                out.push(ch);
178                i += ch.len_utf8();
179            }
180        }
181    }
182    (i > start).then_some((out, i))
183}
184
185/// `s` as one single-quoted shell word, the way the CLI quotes it.
186pub fn single_quote(s: &str) -> String {
187    format!("'{}'", s.replace('\'', "'\"'\"'"))
188}
189
190/// The script with the command at `range` replaced by `command`.
191pub fn replace_command(script: &str, range: Range<usize>, command: &str) -> String {
192    format!("{}{}{}", &script[..range.start], single_quote(command), &script[range.end..])
193}
194
195fn calls_root() -> Option<PathBuf> {
196    if let Some(over) = std::env::var_os(CALLS_DIR_OVERRIDE_ENV).filter(|v| !v.is_empty()) {
197        return Some(PathBuf::from(over));
198    }
199    Some(dirs::home_dir()?.join(".agentmux").join("state").join("bashwrap-calls"))
200}
201
202fn session_dir(session_id: &str) -> Option<PathBuf> {
203    Some(calls_root()?.join(sanitize(session_id)))
204}
205
206fn sanitize(raw: &str) -> String {
207    raw.chars()
208        .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
209        .collect()
210}
211
212/// Record a call for the prefix process to claim. Written to a temporary
213/// name and renamed, so a claim never reads half a record. Then other
214/// sessions' leftovers are swept (`sweep_other_sessions`).
215pub fn register(session_id: &str, record: &CallRecord) -> std::io::Result<()> {
216    let dir = session_dir(session_id)
217        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no home directory"))?;
218    let name = format!("{}.json", sanitize(&record.tool_use_id));
219    let tmp = dir.join(format!(".{name}.{}", std::process::id()));
220    let bytes = serde_json::to_vec(record)?;
221    let write = || -> std::io::Result<()> {
222        std::fs::create_dir_all(&dir)?;
223        std::fs::write(&tmp, &bytes)?;
224        std::fs::rename(&tmp, dir.join(&name))
225    };
226    // A claim or a sweep removes a directory it finds empty, which can land
227    // between creating it and writing into it: then once more.
228    write().or_else(|e| if e.kind() == std::io::ErrorKind::NotFound { write() } else { Err(e) })?;
229    // Another agent waiting on the very same command: mark it before either
230    // is claimed, so both claims know (`claim`).
231    let records = read_records(&dir);
232    let same: Vec<&(PathBuf, CallRecord)> = records.iter().filter(|(_, r)| r.command == record.command).collect();
233    if agents_differ(&same) {
234        mark_ambiguous(&dir, &record.command);
235    }
236    if let Some(root) = calls_root() {
237        sweep_other_sessions(&root, &dir);
238    }
239    Ok(())
240}
241
242/// Every other session's directory: its stale records deleted, and the
243/// directory itself removed once nothing is left in it. Sessions end
244/// without telling anyone, and a call the CLI never ran (denied) leaves its
245/// record; without this both would stay forever.
246fn sweep_other_sessions(root: &Path, keep: &Path) {
247    let Ok(entries) = std::fs::read_dir(root) else { return };
248    for entry in entries.flatten() {
249        let path = entry.path();
250        if path == keep || !path.is_dir() {
251            continue;
252        }
253        if read_records(&path).is_empty() {
254            // Fails (and is left) if a record or a temporary file is in it.
255            let _ = std::fs::remove_dir(&path);
256        }
257    }
258}
259
260/// Claim the record of the call this script runs: the newest one for the
261/// session whose command is `command`; failing that, the session's only
262/// record. Newest, because the hook records a call just before the CLI runs
263/// it, while a call the CLI never ran (a deny rule, a refused prompt) leaves
264/// an older record behind that a retry of the same command must not take. A claim renames the record away, so two
265/// prefix processes never claim the same call. `None` when there is nothing
266/// to claim: the script then runs unlinked. Only a Bash call's script, one
267/// with a command in its `eval`, ever claims (`run`).
268pub fn claim(session_id: &str, command: &str) -> Option<CallRecord> {
269    let dir = session_dir(session_id)?;
270    let mut records = read_records(&dir);
271    records.sort_by_key(|(_, r)| std::cmp::Reverse(r.created_ms));
272    let matching: Vec<&(PathBuf, CallRecord)> =
273        records.iter().filter(|(_, r)| r.command == command).collect();
274    // Two agents ran this very command at once: either record could be this
275    // call's. Marked before claiming, so the other claim knows too.
276    if agents_differ(&matching) {
277        mark_ambiguous(&dir, command);
278    }
279    let candidates: Vec<&(PathBuf, CallRecord)> = if !matching.is_empty() {
280        matching
281    } else if records.len() == 1 {
282        records.iter().collect()
283    } else {
284        Vec::new()
285    };
286    let mut claimed_record = None;
287    for (path, record) in candidates {
288        let claimed = path.with_extension(format!("claimed.{}", std::process::id()));
289        if std::fs::rename(path, &claimed).is_ok() {
290            let _ = std::fs::remove_file(&claimed);
291            // By the record's own command: the lone-record fallback can take
292            // a record whose command the CLI tidied (#5096).
293            let ambiguous = marked_ambiguous(&dir, &record.command);
294            claimed_record = Some(CallRecord { agent_ambiguous: ambiguous, ..record.clone() });
295            break;
296        }
297    }
298    // The last waiting record of an ambiguous command takes its marker along.
299    if let Some(r) = claimed_record.as_ref().filter(|r| r.agent_ambiguous) {
300        if !read_records(&dir).iter().any(|(_, w)| w.command == r.command) {
301            let _ = std::fs::remove_file(marker_path(&dir, &r.command));
302        }
303    }
304    // The session's last waiting call: its directory goes too (it is made
305    // again for the next one). Fails, and stays, while anything is in it.
306    let _ = std::fs::remove_dir(&dir);
307    claimed_record
308}
309
310/// The session's unclaimed records, deleting any past their age.
311fn read_records(dir: &Path) -> Vec<(PathBuf, CallRecord)> {
312    let Ok(entries) = std::fs::read_dir(dir) else {
313        return Vec::new();
314    };
315    let cutoff = now_ms().saturating_sub(RECORD_MAX_AGE.as_millis() as u64);
316    let mut out = Vec::new();
317    let mut markers = Vec::new();
318    for entry in entries.flatten() {
319        let path = entry.path();
320        let ext = path.extension().and_then(|e| e.to_str());
321        if ext == Some("ambiguous") {
322            markers.push(path);
323            continue;
324        }
325        let is_record = ext == Some("json") && !path.file_name().and_then(|n| n.to_str()).unwrap_or("").starts_with('.');
326        if !is_record {
327            continue;
328        }
329        match std::fs::read(&path).ok().and_then(|b| serde_json::from_slice::<CallRecord>(&b).ok()) {
330            Some(record) if record.created_ms >= cutoff => out.push((path, record)),
331            _ => {
332                let _ = std::fs::remove_file(&path);
333            }
334        }
335    }
336    // A marker whose command no longer waits (claimed, or a denied call's
337    // record expired) is done, and must not keep the directory.
338    for marker in markers {
339        let command = std::fs::read_to_string(&marker).unwrap_or_default();
340        if !out.iter().any(|(_, r)| r.command == command) {
341            let _ = std::fs::remove_file(&marker);
342        }
343    }
344    out
345}
346
347/// Run the CLI's whole `script` for the Bash call it belongs to, streaming it
348/// exactly as `exec` streams a command. The call is the record the hook left
349/// for this session's command. A script that can't be linked to a call (a
350/// `claude` run by hand or nested inside an agent, whose session has no
351/// records, or the CLI's own shell calls) runs as plain bash, as if there
352/// were no prefix: no live output, nothing else changed.
353/// docs/specs/SPEC_BASH_STREAMING_VIA_SHELL_PREFIX_2026_10_10.md §2.2, §2.3.
354pub async fn run(script: String) -> Result<i32> {
355    // Only a Bash call's script has the CLI's `eval`. Anything else is a hook
356    // or an MCP server, which runs as it is and never takes a Bash call's
357    // record: in the PTY, a hook's answer or a server's JSON-RPC would be
358    // garbled, and the call it took would lose its live output.
359    let Some((command, range)) = extract_command(&script) else {
360        tracing::info!(target: "bashwrap", "prefix: not a Bash call; running it as it is");
361        return run_passthrough(&script);
362    };
363    let session = std::env::var(SESSION_ID_ENV).ok().filter(|s| !s.is_empty());
364    let record = session.as_deref().and_then(|s| claim(s, &command));
365    let Some(record) = record else {
366        tracing::info!(target: "bashwrap", session = ?session, "prefix: no call to link; running the script as plain bash");
367        return run_plain(&script);
368    };
369    // The tee rewrite works on the model's command, so it is applied to the
370    // command inside the script's `eval` and the script rebuilt around it.
371    let script = match crate::hook::tee_redirect_rewrite(&command) {
372        Some(teed) => replace_command(&script, range, &teed),
373        None => script,
374    };
375    // Not awaited before the command starts: a slow srv must not hold it up.
376    let report = record.description.clone().map(|d| tokio::spawn(report_call(record.tool_use_id.clone(), d)));
377    let args = crate::bash_wrap::Args {
378        tool_id: record.tool_use_id,
379        b64_cmd: String::new(),
380        block_id: None,
381        declared_background: record.run_in_background,
382        agent: if record.agent_ambiguous { None } else { record.agent_id },
383        agent_unknown: record.agent_ambiguous,
384    };
385    if record.agent_ambiguous {
386        // Said where the model reads it: no agent's folder was used.
387        println!(
388            "[bashwrap] another agent ran this same command at the same moment, so which agent it belongs to can't be \
389             told: it runs in the folder Claude Code gave it, and no agent's saved folder is used or changed"
390        );
391    }
392    let result = crate::bash_wrap::run_command(args, script).await;
393    if let Some(task) = report {
394        // Bounded past the publish's own timeout; main exits right after.
395        let _ = tokio::time::timeout(Duration::from_secs(6), task).await;
396    }
397    result
398}
399
400/// Tell srv which call this process runs, once per linked call, so srv can say which tool call
401/// a process tree is (Tower's "started by"): this wrapper's pid, the call and what it does. srv
402/// keeps it and does not forward it to the pane, which would take an unknown op for output.
403/// SPEC_TOWER_AGENT_CENTRIC_VIEWS_2026_10_08.md §5.3. Best effort.
404async fn report_call(tool_id: String, description: String) {
405    let Some(client) = crate::mps_client::WpsClient::from_env() else { return };
406    let block_id = std::env::var("AGENTMUX_BLOCKID").ok().filter(|b| !b.is_empty());
407    let description: String = description.chars().take(MAX_DESCRIPTION_CHARS).collect();
408    let msg = agentmux_common::client_events::ToolChunk::Call { tool_id: tool_id.clone(), pid: std::process::id(), description, timestamp: now_ms() };
409    if let Err(e) = client.publish_chunk(block_id.as_deref(), &msg).await {
410        tracing::warn!(target: "bashwrap", tool_id, error = %e, "call report failed");
411    }
412}
413
414/// Run a hook command or an MCP server's command line on this process's own
415/// stdio, untouched: an MCP server speaks JSON-RPC on it, so one added byte
416/// breaks it. A lone word is a program, started directly (no shell to
417/// mangle a Windows path, nothing to locate first); anything else is a
418/// command line, which the CLI joined unquoted, so bash runs it. Except on
419/// Windows when the program is a Windows path: bash would strip its
420/// backslashes, and only an MCP server's line can have one (the CLI makes a
421/// hook's paths POSIX), so it is split back into words, as the CLI joined it
422/// ([`windows_path_words`]).
423fn run_passthrough(script: &str) -> Result<i32> {
424    let script = script.trim();
425    if cfg!(windows) {
426        if let Some(words) = windows_path_words(script) {
427            let args: Vec<&str> = words[1..].iter().map(String::as_str).collect();
428            return run_program(&words[0], &args);
429        }
430    }
431    if !script.contains(char::is_whitespace) {
432        return run_program(script, &[]);
433    }
434    run_plain(script)
435}
436
437/// The words of a line whose program is a Windows path, or `None` for any
438/// other line. The CLI joins a server's command and arguments with spaces and
439/// puts a word it finds unsafe (a path with a backslash is one) in single
440/// quotes, so `'C:\tools\my server.exe' --port 1` is three words. A quoted
441/// part is taken as written, `'\''` inside single quotes is a quote, and a
442/// backslash is never an escape: it is the path's own. A line whose quotes
443/// don't pair is split at its spaces alone.
444fn windows_path_words(line: &str) -> Option<Vec<String>> {
445    let words = quoted_words(line).unwrap_or_else(|| line.split_whitespace().map(str::to_owned).collect());
446    words.first().is_some_and(|program| program.contains('\\')).then_some(words)
447}
448
449/// A line's words, each quoted part taken as written. `None` when a quote is never closed.
450fn quoted_words(line: &str) -> Option<Vec<String>> {
451    let mut words = Vec::new();
452    let mut word = String::new();
453    let mut in_word = false;
454    let mut rest = line;
455    while let Some(c) = rest.chars().next() {
456        rest = &rest[c.len_utf8()..];
457        match c {
458            '\'' | '"' => {
459                in_word = true;
460                loop {
461                    let close = rest.find(c)?;
462                    word.push_str(&rest[..close]);
463                    rest = &rest[close + 1..];
464                    // `'it'\''s'`: the quote ends, a quote is written, the quote opens again.
465                    match rest.strip_prefix("\\''") {
466                        Some(after) if c == '\'' => {
467                            word.push('\'');
468                            rest = after;
469                        }
470                        _ => break,
471                    }
472                }
473            }
474            c if c.is_whitespace() => {
475                if in_word {
476                    words.push(std::mem::take(&mut word));
477                    in_word = false;
478                }
479            }
480            c => {
481                in_word = true;
482                word.push(c);
483            }
484        }
485    }
486    if in_word {
487        words.push(word);
488    }
489    Some(words)
490}
491
492/// Become the program, so the CLI's signals and pid reach it. Returns only
493/// when it can't be started.
494#[cfg(unix)]
495fn run_program(program: &str, args: &[&str]) -> Result<i32> {
496    use std::os::unix::process::CommandExt;
497    let err = std::process::Command::new(program).args(args).exec();
498    eprintln!("agentmux-bashwrap: cannot run {program}: {err}");
499    Ok(127)
500}
501
502/// Run the program and wait for it. The block's Job Object ends it with the
503/// agent, and it sees stdin close when the CLI closes its end. Found through
504/// `PATHEXT` the way the CLI would find it without a prefix, so a `.cmd`
505/// shim (what a global npm install puts on `PATH`) starts too: std looks
506/// only for `.exe`, but runs a `.cmd` given its full path.
507#[cfg(windows)]
508fn run_program(program: &str, args: &[&str]) -> Result<i32> {
509    let resolved = which::which(program).unwrap_or_else(|_| PathBuf::from(program));
510    let mut cmd = std::process::Command::new(resolved);
511    cmd.args(args);
512    // A console program, like bash.exe in `run_plain`.
513    cmd.no_window();
514    match cmd.status() {
515        Ok(status) => Ok(status.code().unwrap_or(1)),
516        Err(e) => {
517            eprintln!("agentmux-bashwrap: cannot run {program}: {e}");
518            Ok(127)
519        }
520    }
521}
522
523/// Run `script` with bash on this process's own stdio, for its exit code.
524fn run_plain(script: &str) -> Result<i32> {
525    let bash = crate::bash_wrap::locate_bash()?;
526    let mut cmd = std::process::Command::new(&bash);
527    cmd.arg("-c").arg(script);
528    // Windows only: bash.exe is a console program; without this it opens a
529    // console window (SPEC_ELIMINATE_BASHWRAP_CONSOLE_WINDOWS_2026_06_20).
530    #[cfg(windows)]
531    cmd.no_window();
532    let status = cmd.status().with_context(|| format!("running {}", bash.display()))?;
533    Ok(status.code().unwrap_or(1))
534}
535
536/// A record for a call the hook just saw.
537pub fn new_record(tool_use_id: &str, command: &str, run_in_background: bool) -> CallRecord {
538    CallRecord {
539        tool_use_id: tool_use_id.to_string(),
540        command: command.to_string(),
541        run_in_background,
542        created_ms: now_ms(),
543        description: None,
544        agent_id: None,
545        agent_ambiguous: false,
546    }
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552
553    /// The script Claude Code 2.1.288 passed to the prefix, recorded for
554    /// `echo 'it''s' "q" && echo two > out.txt; cat out.txt`.
555    const CLI_SCRIPT: &str = r#"source /c/Users/u/AppData/Local/Temp/config/shell-snapshots/snapshot-bash-1.sh 2>/dev/null || true && export TEMP='C:\Users\u\AppData\Local\Temp' TMP='C:\Users\u\AppData\Local\Temp' && { shopt -u extglob || setopt NO_EXTENDED_GLOB NO_BARE_GLOB_QUAL; } >/dev/null 2>&1 || true && { \builtin unalias -- 'unsetenv'; \builtin unset -f -- 'unsetenv'; } >/dev/null 2>&1 || true && eval 'echo '"'"'it'"'"''"'"'s'"'"' "q" && echo two > out.txt; cat out.txt' < /dev/null && pwd -P >| /c/Users/u/AppData/Local/Temp/claude-941e-cwd"#;
556
557    fn os(args: &[&str]) -> Vec<OsString> {
558        args.iter().map(OsString::from).collect()
559    }
560
561    #[test]
562    fn a_lone_script_argument_is_a_prefix_call() {
563        assert_eq!(prefix_script(&os(&["bw", CLI_SCRIPT])).as_deref(), Some(CLI_SCRIPT));
564    }
565
566    #[test]
567    fn subcommands_flags_and_other_shapes_are_not() {
568        for args in [
569            vec!["bw", "hook"],
570            vec!["bw", "exec"],
571            vec!["bw", "--version"],
572            vec!["bw", "--help"],
573            vec!["bw"],
574            vec!["bw", "exec", "--tool-id=x"],
575            vec!["bw", "  "],
576        ] {
577            assert_eq!(prefix_script(&os(&args)), None, "{args:?}");
578        }
579    }
580
581    /// The CLI also prefixes hooks and stdio MCP servers, joining a server's
582    /// command and arguments into one argument; `agentmux-mcp` arrives alone.
583    #[test]
584    fn hooks_and_mcp_servers_are_prefix_calls_too() {
585        for script in ["agentmux-mcp", r"C:\tools\server.exe", "npx -y @scope/server", "agentmux-bashwrap hook"] {
586            assert_eq!(prefix_script(&os(&["bw", script])).as_deref(), Some(script));
587        }
588    }
589
590    /// A hook or an MCP server started while a Bash call waits must not take
591    /// that call's record: it would run in the PTY, and the call would lose
592    /// its live output.
593    #[test]
594    fn a_script_without_the_clis_eval_never_claims_a_call() {
595        with_calls_dir(|| {
596            register("s", &new_record("toolu_1", "cargo build", false)).unwrap();
597            std::env::set_var(SESSION_ID_ENV, "s");
598            let rt = tokio::runtime::Runtime::new().unwrap();
599            let code = rt.block_on(run("agentmux-no-such-program-4f1c".to_string())).unwrap();
600            std::env::remove_var(SESSION_ID_ENV);
601            assert_eq!(code, 127, "a program that can't be started exits like a shell's");
602            assert_eq!(claim("s", "cargo build").unwrap().tool_use_id, "toolu_1", "the call is still waiting");
603        });
604    }
605
606    /// A global npm install puts a `.cmd` shim on `PATH`; named alone, as an
607    /// MCP server's command, it must start.
608    #[cfg(windows)]
609    #[test]
610    fn a_cmd_shim_on_path_starts_as_a_lone_word() {
611        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
612        let dir = std::env::temp_dir().join(format!("bashwrap-shim-test-{}-{}", std::process::id(), now_ms()));
613        std::fs::create_dir_all(&dir).unwrap();
614        std::fs::write(dir.join("bw-shim-test.cmd"), "@exit /b 9\r\n").unwrap();
615        let old_path = std::env::var_os("PATH").unwrap_or_default();
616        let mut paths = vec![dir.clone()];
617        paths.extend(std::env::split_paths(&old_path));
618        std::env::set_var("PATH", std::env::join_paths(paths).unwrap());
619        let code = run_program("bw-shim-test", &[]);
620        std::env::set_var("PATH", &old_path);
621        let _ = std::fs::remove_dir_all(&dir);
622        assert_eq!(code.unwrap(), 9);
623    }
624
625    /// `C:\tools\server.exe --port 1`, an MCP server's joined line: started
626    /// directly with its arguments, not through bash, which would eat the
627    /// backslashes.
628    #[cfg(windows)]
629    #[test]
630    fn a_windows_path_with_arguments_starts_without_bash() {
631        let dir = std::env::temp_dir().join(format!("bashwrap-winpath-test-{}-{}", std::process::id(), now_ms()));
632        if dir.to_string_lossy().contains(char::is_whitespace) {
633            return; // A path with a space is a command line the CLI made ambiguous.
634        }
635        std::fs::create_dir_all(&dir).unwrap();
636        let script = dir.join("server.cmd");
637        std::fs::write(&script, "@exit /b %1\r\n").unwrap();
638        let line = format!("{} 5", script.display());
639        let code = run_passthrough(&line);
640        let _ = std::fs::remove_dir_all(&dir);
641        assert_eq!(code.unwrap(), 5, "its argument reached it");
642    }
643
644    /// The CLI puts a path with a backslash in single quotes: the quotes are
645    /// the line's, not the program's name, and a folder with a space is one word.
646    #[cfg(windows)]
647    #[test]
648    fn a_quoted_windows_path_starts_and_its_arguments_reach_it() {
649        let dir = std::env::temp_dir().join(format!("bashwrap quoted path test-{}-{}", std::process::id(), now_ms()));
650        std::fs::create_dir_all(&dir).unwrap();
651        let script = dir.join("server.cmd");
652        std::fs::write(&script, "@exit /b %1\r\n").unwrap();
653        let alone = run_passthrough(&format!("'{}'", script.display()));
654        let with_an_argument = run_passthrough(&format!("'{}' 7", script.display()));
655        let _ = std::fs::remove_dir_all(&dir);
656        assert_eq!(alone.unwrap(), 0, "the quoted path alone is the program");
657        assert_eq!(with_an_argument.unwrap(), 7, "its argument reached it");
658    }
659
660    #[test]
661    fn a_windows_path_line_is_read_word_by_word_with_its_quotes_taken_off() {
662        let words = |line: &str| windows_path_words(line);
663        let own = |list: &[&str]| Some(list.iter().map(|w| (*w).to_owned()).collect::<Vec<_>>());
664        // As the CLI joins it: the path quoted, a plain argument not.
665        assert_eq!(words(r"'C:\tools\my server.exe' --port 1"), own(&[r"C:\tools\my server.exe", "--port", "1"]));
666        assert_eq!(words(r"'C:\tools\server.exe'"), own(&[r"C:\tools\server.exe"]));
667        // Unquoted, as it was joined before: a backslash is the path's own.
668        assert_eq!(words(r"C:\tools\server.exe --port 1"), own(&[r"C:\tools\server.exe", "--port", "1"]));
669        // A quote inside a quoted word, double quotes, and an empty argument.
670        assert_eq!(words(r#"'C:\a\it'\''s.exe' "two words" ''"#), own(&[r"C:\a\it's.exe", "two words", ""]));
671        // A quote that is never closed: split at the spaces, as before.
672        assert_eq!(words(r"C:\tools\server.exe it's"), own(&[r"C:\tools\server.exe", "it's"]));
673        // Not a Windows path: not this function's line.
674        assert_eq!(words("node 'C:\\x\\server.js'"), None);
675        assert_eq!(words("agentmux-mcp"), None);
676        assert_eq!(words(""), None);
677    }
678
679    #[test]
680    fn takes_the_command_out_of_the_clis_script() {
681        let (command, range) = extract_command(CLI_SCRIPT).unwrap();
682        assert_eq!(command, r#"echo 'it''s' "q" && echo two > out.txt; cat out.txt"#);
683        assert!(CLI_SCRIPT[range.end..].starts_with(" < /dev/null && pwd -P"));
684        assert!(CLI_SCRIPT[..range.start].ends_with("&& eval "));
685    }
686
687    #[test]
688    fn putting_the_command_back_round_trips() {
689        let (command, range) = extract_command(CLI_SCRIPT).unwrap();
690        assert_eq!(replace_command(CLI_SCRIPT, range.clone(), &command), CLI_SCRIPT);
691        let rewritten = replace_command(CLI_SCRIPT, range, "echo 'a' | tee out.txt");
692        assert_eq!(extract_command(&rewritten).unwrap().0, "echo 'a' | tee out.txt");
693    }
694
695    #[test]
696    fn multi_line_and_unicode_commands_survive() {
697        let cmd = "for f in *; do\n  echo \"$f\" — ✓ 'x'\ndone";
698        let script = format!("source s.sh || true && eval {} < /dev/null && pwd -P >| f", single_quote(cmd));
699        assert_eq!(extract_command(&script).unwrap().0, cmd);
700    }
701
702    #[test]
703    fn a_script_without_the_clis_eval_has_no_command() {
704        assert_eq!(extract_command("echo hi && ls"), None);
705        assert_eq!(extract_command("x && eval 'unterminated"), None);
706    }
707
708    #[test]
709    fn only_a_path_to_agentmux_bashwrap_turns_the_prefix_on() {
710        assert!(is_bashwrap_path(Path::new("C:/Program Files/AgentMux/tools/bin/agentmux-bashwrap.exe")));
711        assert!(is_bashwrap_path(Path::new("/usr/local/bin/agentmux-bashwrap")));
712        assert!(!is_bashwrap_path(Path::new("/usr/local/bin/logger.sh")));
713        assert!(!is_bashwrap_path(Path::new("")));
714    }
715
716    fn with_calls_dir<T>(f: impl FnOnce() -> T) -> T {
717        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
718        let dir = std::env::temp_dir().join(format!("bashwrap-calls-test-{}-{}", std::process::id(), now_ms()));
719        std::env::set_var(CALLS_DIR_OVERRIDE_ENV, &dir);
720        let out = f();
721        std::env::remove_var(CALLS_DIR_OVERRIDE_ENV);
722        let _ = std::fs::remove_dir_all(&dir);
723        out
724    }
725
726    #[test]
727    fn a_claim_takes_the_matching_record_once() {
728        with_calls_dir(|| {
729            register("s1", &new_record("toolu_a", "cargo build", false)).unwrap();
730            register("s1", &new_record("toolu_b", "npm test", true)).unwrap();
731            register("s1", &new_record("toolu_c", "ls", false)).unwrap();
732            let got = claim("s1", "npm test").unwrap();
733            assert_eq!((got.tool_use_id.as_str(), got.run_in_background), ("toolu_b", true));
734            assert_eq!(claim("s1", "npm test"), None, "claimed once: two others left, neither matches");
735            assert_eq!(claim("s1", "cargo build").unwrap().tool_use_id, "toolu_a");
736            // One record left: a command that doesn't match exactly (the CLI
737            // may tidy it) still gets the session's only waiting call.
738            assert_eq!(claim("s1", "ls ").unwrap().tool_use_id, "toolu_c");
739        });
740    }
741
742    /// A call the CLI never ran (denied) leaves its record; the retry of the
743    /// same command, recorded later, is the one its run claims.
744    #[test]
745    fn the_newest_record_for_a_command_is_claimed_first() {
746        with_calls_dir(|| {
747            let mut denied = new_record("toolu_denied", "make", false);
748            denied.created_ms -= 10_000;
749            register("s", &denied).unwrap();
750            register("s", &new_record("toolu_retry", "make", true)).unwrap();
751            let got = claim("s", "make").unwrap();
752            assert_eq!((got.tool_use_id.as_str(), got.run_in_background), ("toolu_retry", true));
753        });
754    }
755
756    #[test]
757    fn without_a_match_only_a_lone_record_is_claimed() {
758        with_calls_dir(|| {
759            register("s", &new_record("toolu_1", "a", false)).unwrap();
760            assert_eq!(claim("s", "no match").unwrap().tool_use_id, "toolu_1");
761            register("s", &new_record("toolu_2", "b", false)).unwrap();
762            register("s", &new_record("toolu_3", "c", false)).unwrap();
763            assert_eq!(claim("s", "zzz"), None, "two candidates: ambiguous");
764            assert_eq!(claim("other-session", "b"), None, "another session's records are never claimed");
765        });
766    }
767
768    fn by(id: &str, command: &str, agent: Option<&str>) -> CallRecord {
769        CallRecord { agent_id: agent.map(str::to_string), ..new_record(id, command, false) }
770    }
771
772    /// The CLI gives a subagent's shell no identity (#5096), so
773    /// two agents' identical commands at once can't be told apart. Both
774    /// claims say so, the second too although it sees one record, and
775    /// neither takes an agent's directory (`run`).
776    #[test]
777    fn two_agents_identical_commands_are_claimed_as_ambiguous() {
778        with_calls_dir(|| {
779            register("s", &by("toolu_a", "git status", Some("sub-a"))).unwrap();
780            register("s", &by("toolu_b", "git status", Some("sub-b"))).unwrap();
781            let first = claim("s", "git status").unwrap();
782            let second = claim("s", "git status").unwrap();
783            assert!(first.agent_ambiguous && second.agent_ambiguous);
784            assert!(!marker_path(&session_dir("s").unwrap(), "git status").exists(), "gone with the last record");
785            // Alone again, the command is its agent's again.
786            register("s", &by("toolu_c", "git status", Some("sub-a"))).unwrap();
787            assert!(!claim("s", "git status").unwrap().agent_ambiguous);
788        });
789    }
790
791    /// The second call can wait at a permission prompt for minutes: its
792    /// marker stays while its record waits, however old, and goes once no
793    /// record of the command waits (a denied call's expires), so it never
794    /// keeps the session's directory.
795    #[test]
796    fn a_marker_lasts_as_long_as_its_command_waits() {
797        with_calls_dir(|| {
798            register("s", &by("toolu_a", "git status", Some("sub-a"))).unwrap();
799            register("s", &by("toolu_b", "git status", Some("sub-b"))).unwrap();
800            let dir = session_dir("s").unwrap();
801            let marker = marker_path(&dir, "git status");
802            assert!(claim("s", "git status").unwrap().agent_ambiguous);
803            let old = std::time::SystemTime::now() - Duration::from_secs(30 * 60);
804            std::fs::File::options().write(true).open(&marker).unwrap().set_modified(old).unwrap();
805            read_records(&dir);
806            assert!(marker.exists(), "the other call still waits");
807            assert!(claim("s", "git status").unwrap().agent_ambiguous, "and is still told");
808            // A marker with nothing of its command waiting goes.
809            mark_ambiguous(&dir, "ls");
810            register("s", &by("toolu_c", "pwd", None)).unwrap();
811            read_records(&dir);
812            assert!(!marker_path(&dir, "ls").exists());
813            assert!(claim("s", "pwd").is_some());
814            assert!(std::fs::remove_dir(&dir).is_ok() || !dir.exists(), "nothing keeps the directory");
815        });
816    }
817
818    /// The lone-record fallback claims a record whose command the CLI tidied:
819    /// its marker is found by the record's command, not the incoming text.
820    #[test]
821    fn a_tidied_command_still_finds_its_records_marker() {
822        with_calls_dir(|| {
823            register("s", &by("toolu_a", "git status", Some("sub-a"))).unwrap();
824            register("s", &by("toolu_b", "git status", Some("sub-b"))).unwrap();
825            assert!(claim("s", "git status").unwrap().agent_ambiguous);
826            assert!(claim("s", "git status ").unwrap().agent_ambiguous, "the remaining record is still unsure");
827            assert!(!marker_path(&session_dir("s").unwrap(), "git status").exists());
828        });
829    }
830
831    #[test]
832    fn one_agents_parallel_calls_and_different_commands_are_not_ambiguous() {
833        with_calls_dir(|| {
834            register("s", &by("t1", "cargo test", Some("sub-a"))).unwrap();
835            register("s", &by("t2", "cargo test", Some("sub-a"))).unwrap();
836            register("s", &by("t3", "ls", Some("sub-b"))).unwrap();
837            assert!(!claim("s", "cargo test").unwrap().agent_ambiguous);
838            assert!(!claim("s", "cargo test").unwrap().agent_ambiguous);
839            assert!(!claim("s", "ls").unwrap().agent_ambiguous);
840        });
841    }
842
843    #[test]
844    fn a_session_directory_goes_once_its_last_call_is_claimed() {
845        with_calls_dir(|| {
846            register("s", &new_record("toolu_1", "a", false)).unwrap();
847            register("s", &new_record("toolu_2", "b", false)).unwrap();
848            let dir = session_dir("s").unwrap();
849            claim("s", "a").unwrap();
850            assert!(dir.is_dir(), "a call still waits in it");
851            claim("s", "b").unwrap();
852            assert!(!dir.exists());
853            // The next call makes it again.
854            register("s", &new_record("toolu_3", "c", false)).unwrap();
855            assert_eq!(claim("s", "c").unwrap().tool_use_id, "toolu_3");
856        });
857    }
858
859    #[test]
860    fn a_new_record_sweeps_other_sessions_left_behind() {
861        with_calls_dir(|| {
862            // A session whose only call was denied: its record is past its age.
863            let mut denied = new_record("toolu_old", "x", false);
864            denied.created_ms -= RECORD_MAX_AGE.as_millis() as u64 + 1;
865            register("ended", &denied).unwrap();
866            // A session that ended with nothing waiting: an empty directory.
867            std::fs::create_dir_all(session_dir("empty").unwrap()).unwrap();
868            // A live session with a call waiting.
869            register("live", &new_record("toolu_live", "y", false)).unwrap();
870            register("current", &new_record("toolu_now", "z", false)).unwrap();
871            assert!(!session_dir("ended").unwrap().exists());
872            assert!(!session_dir("empty").unwrap().exists());
873            assert_eq!(claim("live", "y").unwrap().tool_use_id, "toolu_live");
874            assert_eq!(claim("current", "z").unwrap().tool_use_id, "toolu_now");
875        });
876    }
877
878    #[test]
879    fn stale_records_are_dropped() {
880        with_calls_dir(|| {
881            let mut old = new_record("toolu_old", "x", false);
882            old.created_ms -= RECORD_MAX_AGE.as_millis() as u64 + 1;
883            register("s", &old).unwrap();
884            assert_eq!(claim("s", "x"), None);
885            assert!(read_records(&session_dir("s").unwrap()).is_empty());
886        });
887    }
888}