Skip to main content

agentmux_bashwrap/
main.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3// Suppress console windows on Windows — bashwrap communicates via pipes and
4// HTTP, never via a console. Without this attribute every Bash tool call
5// produces a blank transparent window (Windows auto-creates one for any
6// CUI-subsystem process unless CREATE_NO_WINDOW is passed by the spawner,
7// which Claude Code's hook mechanism does not do).
8#![cfg_attr(windows, windows_subsystem = "windows")]
9
10//! agentmux-bashwrap — streaming bash wrapper for AgentMux agents.
11//!
12//! Two subcommands:
13//!
14//! - `exec` — runs a user-supplied command inside an owned PTY,
15//!   streams stdout/stderr line-by-line to the AgentMux sidecar's
16//!   MPS broker (HTTP), and prints the aggregated output on its own
17//!   stdout for Claude's native Bash tool to capture as `tool_result`.
18//!
19//! - `hook` — reads a PreToolUse JSON payload on stdin. When the CLI's
20//!   shell prefix is this binary, it records the call for the prefix
21//!   process and changes nothing. Otherwise it emits a hook response that
22//!   rewrites the command so Claude's native Bash invokes
23//!   `agentmux-bashwrap exec` instead, the command base64-encoded into the
24//!   rewrite argv so quoting + multi-line bodies survive.
25//!
26//! - prefix mode (one argument: the CLI's script) — Claude Code's
27//!   `CLAUDE_CODE_SHELL_PREFIX`. Runs the script the way `exec` runs a
28//!   command, for the call the hook recorded. See `prefix.rs` and
29//!   `docs/specs/SPEC_BASH_STREAMING_VIA_SHELL_PREFIX_2026_10_10.md`.
30//!
31//! - `precompact` — registered as Claude Code's `PreCompact` hook.
32//!   Fires the instant compaction begins; pings the sidecar's MPS
33//!   broker with a `compaction_started` event so the UI can show
34//!   live status instead of a silent gap. See `precompact.rs` and
35//!   `docs/specs/SPEC_COMPACTION_DETECTION_AND_HANDLING_2026_07_31.md`.
36//!
37//! - askpass mode (no subcommand) — `ssh`'s `SSH_ASKPASS` when AgentMux
38//!   runs ssh for an agent: shows ssh's prompt to the user through srv and
39//!   prints the answer. See `askpass.rs`.
40//!
41//! - `git-credential <op>` and `github-token -- <gh args>` — GitHub tokens for an agent's `git`
42//!   and `gh`, from srv. See `github.rs`.
43//!
44//! - `github-container -- <gh args>` — a container's `gh pr merge` (srv does it) and the raw `gh api` writes its token
45//!   cannot make (refused, with the command that does the job). See `container_verbs.rs`.
46//!
47//! - `git-hook <name>`, `git-env -- <git args>` and `github-owner-tag -- <gh args>` — the guards
48//!   and attribution on an agent's pushes and commits. See `git_hooks.rs`, `secret_scan.rs`.
49//!
50//! - `github-text-guard -- <gh args>` — the scan of the text an agent's `gh` sends (PR, issue and
51//!   comment text) for credentials. See `github_text.rs`.
52//!
53//! - `sessionstart --part N` — registered as Claude Code's `SessionStart`
54//!   hook, once per part. Delivers part N of the agent's memory as the
55//!   hook's `additionalContext`. See `sessionstart.rs` and
56//!   `docs/specs/SPEC_GLOBAL_MEMORY_DELIVERY_2026_09_27.md` §7 P2.
57//!
58//! See `docs/specs/SPEC_STREAMING_BASH_RUNNER_2026_05_11.md` for the
59//! full design rationale (why command rewrite vs. MCP deny-redirect,
60//! why a separate binary vs. extending an MCP server, channel
61//! correlation by `tool_use_id`, etc).
62
63use anyhow::Result;
64use clap::{Parser, Subcommand};
65
66mod askpass;
67mod container_verbs;
68mod bash_wrap;
69mod cwd_state;
70mod exec_args;
71mod aws;
72mod gh_shim;
73mod git_hooks;
74mod bash_timeout;
75mod github;
76mod github_text;
77mod idle_gate;
78mod hook;
79mod precompact;
80mod prefix;
81mod publish_scan;
82mod secret_scan;
83mod sessionstart;
84mod shim_functions;
85#[cfg(test)]
86mod test_env_lock;
87mod mps_client;
88
89#[derive(Parser)]
90#[command(name = "agentmux-bashwrap", version)]
91#[command(about = "AgentMux streaming bash wrapper + PreToolUse hook helper")]
92struct Cli {
93    #[command(subcommand)]
94    command: Command,
95}
96
97#[derive(Subcommand)]
98enum Command {
99    /// Run a bash command inside an owned PTY, stream its stdout/stderr
100    /// to the AgentMux sidecar's MPS broker, and print the aggregated
101    /// output on this process's stdout for Claude to capture.
102    Exec(bash_wrap::Args),
103    /// Read a PreToolUse JSON payload on stdin (from Claude Code) and
104    /// emit a hook response that rewrites the command to invoke `exec`.
105    Hook,
106    /// Registered as Claude Code's `PreCompact` hook. Publishes a
107    /// `compaction_started` MPS event and exits 0 with no stdout
108    /// output — observe-only, never blocks compaction.
109    Precompact(precompact::Args),
110    /// Registered as Claude Code's `SessionStart` hook, once per part.
111    /// Prints this part of the agent's memory as the hook's
112    /// `additionalContext` (or nothing), then acknowledges it.
113    Sessionstart(sessionstart::Args),
114    /// git's credential helper (`get`, `store`, `erase`) for an agent whose person connected
115    /// GitHub through AgentMux Cloud: the GitHub App's token for the repository, from srv.
116    GitCredential {
117        /// What git asks: get, store or erase.
118        op: String,
119    },
120    /// Print a token for the repository a `gh` command is about, or say why there is none. The
121    /// `gh` function this wrapper exports calls it.
122    GithubToken {
123        /// The arguments `gh` was given.
124        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
125        gh_args: Vec<String>,
126    },
127    /// A container's `gh pr merge` (done by srv) or a raw `gh api` write its token cannot make (refused, naming the
128    /// command that does the job); exit 3 for any other command. The `gh` function this wrapper exports calls it.
129    GithubContainer {
130        /// The arguments `gh` was given.
131        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
132        gh_args: Vec<String>,
133    },
134    /// The arguments of a `gh pr create` or `gh pr edit` with the owner tag in its body, each
135    /// followed by a NUL byte. The `gh` function this wrapper exports calls it.
136    GithubOwnerTag {
137        /// The arguments `gh` was given.
138        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
139        gh_args: Vec<String>,
140    },
141    /// Scan the text a `gh` command sends (a PR, issue or comment body, release notes, an API field)
142    /// for credentials: print the arguments to run, each followed by a NUL, then `ok`; or `refused`
143    /// and the reason on stderr. The `gh` function this wrapper exports calls it.
144    GithubTextGuard {
145        /// The arguments `gh` was given.
146        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
147        gh_args: Vec<String>,
148    },
149    /// One of the git hooks srv installs for an agent (`pre-push`, `prepare-commit-msg`): the
150    /// repository's own hook, then AgentMux's part (the push scan, the commit trailers).
151    GitHook {
152        /// The hook's name.
153        name: String,
154        /// What git gave the hook.
155        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
156        args: Vec<String>,
157    },
158    /// AWS's `credential_process` for a container agent's AWS config: print the credentials of the grant
159    /// `--profile` names as JSON, or say on stderr why there are none. srv writes the config that calls it.
160    AwsCredentials {
161        /// The grant (a profile of the container's AWS config).
162        #[arg(long)]
163        profile: String,
164    },
165    /// Refuse a `git` command that would skip the hooks, and print the environment a commit needs.
166    /// The `git` function this wrapper exports calls it.
167    GitEnv {
168        /// The arguments `git` was given.
169        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
170        git_args: Vec<String>,
171    },
172}
173
174#[cfg(test)]
175mod tls_test_init;
176
177fn main() -> Result<()> {
178    // Started as `gh` (a container image's symlink): the GitHub CLI with the per-call token, before anything else
179    // (gh_shim.rs).
180    if let Some(code) = gh_shim::run_if_invoked_as_gh() {
181        std::process::exit(code);
182    }
183    agentmux_common::tls_provider::install_ring_provider(); // reqwest 0.13 builds no client without it
184    init_tracing();
185    // Before any bash is started, by the prefix or exec path alike (shim_functions.rs).
186    shim_functions::export();
187
188    // ssh's askpass for an agent's SSH command: the prompt is the only
189    // argument, so this is decided before clap sees it (askpass.rs).
190    if let Some(code) = askpass::run_if_asked() {
191        std::process::exit(code);
192    }
193
194    // Claude Code's shell prefix: the CLI's script is the only argument, so
195    // this too is decided before clap sees it (prefix.rs).
196    let argv: Vec<std::ffi::OsString> = std::env::args_os().collect();
197    if let Some(script) = prefix::prefix_script(&argv) {
198        let rt = tokio::runtime::Runtime::new()?;
199        let exit_code = rt.block_on(prefix::run(script))?;
200        std::process::exit(exit_code);
201    }
202
203    let cli = Cli::parse();
204    // The git ones are synchronous, and git hooks run them on every ref update and index write of
205    // an agent's git, so they start without an async runtime.
206    match &cli.command {
207        Command::GitCredential { op } => std::process::exit(github::run_git_credential(op)),
208        Command::GithubToken { gh_args } => std::process::exit(github::run_github_token(gh_args)),
209        Command::GithubOwnerTag { gh_args } => std::process::exit(github::run_github_owner_tag(gh_args)),
210        Command::GithubContainer { gh_args } => std::process::exit(container_verbs::run_github_container(gh_args)),
211        Command::GithubTextGuard { gh_args } => std::process::exit(github_text::run_github_text_guard(gh_args)),
212        Command::GitHook { name, args } => std::process::exit(git_hooks::run_git_hook(name, args)),
213        Command::AwsCredentials { profile } => std::process::exit(aws::run_aws_credentials(profile)),
214        Command::GitEnv { git_args } => std::process::exit(git_hooks::run_git_env(git_args)),
215        _ => {}
216    }
217    let rt = tokio::runtime::Runtime::new()?;
218    match cli.command {
219        Command::Exec(args) => {
220            // Propagate the inner command's exit code as our own
221            // process exit. Without this the wrapper always exited 0
222            // and Claude's native Bash tool saw success for every
223            // wrapped command regardless of the actual outcome —
224            // codex P1 on PR #804.
225            let exit_code = rt.block_on(bash_wrap::run(args))?;
226            std::process::exit(exit_code);
227        }
228        Command::Hook => hook::run_pretooluse_bash(),
229        Command::Precompact(args) => rt.block_on(precompact::run(args)),
230        Command::Sessionstart(args) => rt.block_on(sessionstart::run(args)),
231        // Handled above.
232        Command::GitCredential { .. } | Command::AwsCredentials { .. } | Command::GithubToken { .. } | Command::GithubOwnerTag { .. } | Command::GithubContainer { .. } | Command::GithubTextGuard { .. } | Command::GitHook { .. } | Command::GitEnv { .. } => Ok(()),
233    }
234}
235
236/// Initialize tracing to write to `~/.agentmux/logs/bashwrap-debug.log`
237/// at INFO by default. Writing to a file instead of stderr means:
238///
239/// 1. Diagnostics survive bash's stdio capture — Claude's tool_result
240///    `stderr` field is empty for successful commands, so anything we
241///    write to stderr is lost to us as developers.
242/// 2. We don't pollute the model's tool_result with bashwrap-internal
243///    noise (env snapshot, publish attempts, etc.).
244/// 3. We can tail the file from outside the agentmux process tree.
245///
246/// Falls back to stderr at WARN level if the file can't be opened.
247fn init_tracing() {
248    let log_path = dirs::home_dir()
249        .map(|h| h.join(".agentmux").join("logs").join("bashwrap-debug.log"));
250    if let Some(path) = log_path {
251        if let Some(parent) = path.parent() {
252            let _ = std::fs::create_dir_all(parent);
253        }
254        if let Ok(file) = std::fs::OpenOptions::new()
255            .append(true)
256            .create(true)
257            .open(&path)
258        {
259            let writer = std::sync::Mutex::new(file);
260            let _ = tracing_subscriber::fmt()
261                .with_writer(writer)
262                .with_ansi(false)
263                .with_env_filter(
264                    tracing_subscriber::EnvFilter::try_from_default_env()
265                        .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
266                )
267                .try_init();
268            return;
269        }
270    }
271    let _ = tracing_subscriber::fmt()
272        .with_writer(std::io::stderr)
273        .with_env_filter(
274            tracing_subscriber::EnvFilter::try_from_default_env()
275                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")),
276        )
277        .try_init();
278}
279
280// This test binary must hold this checkout's code, not another clone's from
281// a shared target directory (`agentmux_common::checkout`).
282#[cfg(test)]
283agentmux_common::checkout_guard!(agentmux_procstats::CHECKOUT_DIR);