Skip to main content

agentmux_bashwrap/
hook.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `hook` subcommand.
5//!
6//! Reads a PreToolUse JSON event on stdin (the contract Claude Code
7//! uses for hooks: see `docs/specs/SPEC_STREAMING_BASH_RUNNER_2026_05_11.md`
8//! §5). If the event is a Bash invocation whose `command` hasn't
9//! already been wrapped, emit an `updatedInput.command` that invokes
10//! `agentmux-bashwrap exec` with the original command base64-encoded
11//! into argv. Idempotent — if the command is already wrapped, pass
12//! through with no rewrite.
13//!
14//! All errors degrade to a pass-through response so a hook failure
15//! never blocks Claude's tool execution.
16
17use anyhow::Result;
18use base64::Engine as _;
19use base64::engine::general_purpose::URL_SAFE_NO_PAD;
20use serde::Deserialize;
21use serde_json::{json, Value};
22use std::io::{Read, Write};
23
24/// Subset of the PreToolUse payload we care about. Extra fields are
25/// ignored (serde default).
26#[derive(Deserialize)]
27struct PreToolUseInput {
28    tool_name: String,
29    #[serde(default)]
30    tool_use_id: String,
31    #[serde(default)]
32    session_id: String,
33    #[serde(default)]
34    tool_input: Value,
35    /// Present only when a subagent made the call (Claude Code's hook
36    /// input); its working directory is kept apart from the main agent's.
37    #[serde(default)]
38    agent_id: Option<String>,
39}
40
41const WRAPPER_BINARY: &str = "agentmux-bashwrap";
42const WRAPPED_PREFIX: &str = "agentmux-bashwrap exec";
43
44pub fn run_pretooluse_bash() -> Result<()> {
45    // Read entire stdin. Hook payloads are small.
46    let mut buf = String::new();
47    std::io::stdin().read_to_string(&mut buf)?;
48
49    // With AgentMux's wrapper as the CLI's shell prefix, the call is only
50    // recorded: the prefix process streams it, and the CLI keeps the call
51    // as the model made it. Otherwise (an older srv, `claude` run by hand
52    // in an agent's workspace) the command is rewritten as before.
53    let response = if crate::prefix::prefix_active() {
54        record_response(&buf)
55    } else {
56        build_response(&buf)
57    };
58    let stdout = std::io::stdout();
59    let mut handle = stdout.lock();
60    writeln!(handle, "{}", response)?;
61    Ok(())
62}
63
64/// Build the hook response for a PreToolUse payload. Public for
65/// testability — callers in tests feed in a payload string and assert
66/// the response shape without going through stdin.
67pub fn build_response(stdin_payload: &str) -> Value {
68    let input: PreToolUseInput = match serde_json::from_str(stdin_payload) {
69        Ok(i) => i,
70        Err(_) => {
71            // Malformed hook input → pass through. Claude proceeds
72            // with native Bash, no streaming for this call.
73            return passthrough();
74        }
75    };
76
77    if input.tool_name != "Bash" {
78        return passthrough();
79    }
80
81    let command = input
82        .tool_input
83        .get("command")
84        .and_then(|v| v.as_str())
85        .unwrap_or("");
86
87    // Idempotence: if the command already invokes our wrapper, don't
88    // re-wrap. Defends against weird hook re-fire scenarios.
89    if command.starts_with(WRAPPED_PREFIX) {
90        return passthrough();
91    }
92
93    // Tee a trailing file redirect back through the PTY so the agent's tool
94    // feed shows the output live while the file is still written. Conservative:
95    // only unambiguous trailing redirects are rewritten; anything else is
96    // encoded verbatim (today's behavior). See
97    // SPEC_TOOL_OUTPUT_TEE_AND_TERMINAL_RENDER_2026_06_17.md §3.
98    let effective_command =
99        tee_redirect_rewrite(command).unwrap_or_else(|| command.to_string());
100
101    // Issue #2491: the CLI's own `run_in_background` declaration is already
102    // present in `tool_input` right alongside `command` — thread it through
103    // so `bash_wrap.rs::effective_idle_timeout` can exempt a declared
104    // long-runner from the idle-kill safety net instead of that signal
105    // being dropped here and rediscovered from scratch at every consuming
106    // layer (the same duplication trap `docs/retro/retro-stuck-background-
107    // dock-timer-2026-08-10.md` already documented for the frontend's own
108    // `isAcceptedBackgroundLaunch` classifier).
109    let declared_background = input
110        .tool_input
111        .get("run_in_background")
112        .and_then(|v| v.as_bool())
113        .unwrap_or(false);
114
115    let b64 = URL_SAFE_NO_PAD.encode(effective_command.as_bytes());
116    let agent = input
117        .agent_id
118        .as_deref()
119        .map(str::trim)
120        .filter(|a| !a.is_empty())
121        .map(|a| format!(" --agent={}", shell_quote(a)))
122        .unwrap_or_default();
123    let wrapped = format!(
124        "{} exec --tool-id={} --b64-cmd={}{}{}",
125        WRAPPER_BINARY,
126        shell_quote(&input.tool_use_id),
127        b64,
128        if declared_background { " --declared-background" } else { "" },
129        agent
130    );
131
132    // `updatedInput` replaces the tool's whole input; the CLI doesn't merge
133    // it. So every other field the model set (`description`, `timeout`,
134    // `run_in_background`, ...) is copied through, and only `command`
135    // changes. Rebuilt from `command` alone, the CLI ran every background
136    // call in the foreground, cut every command at its 120 s default, and
137    // labelled tasks with the wrapper
138    // (docs/retro/RETRO_BASHWRAP_HOOK_DROPS_BASH_TOOL_FIELDS_2026_10_10.md).
139    let mut updated = match input.tool_input {
140        Value::Object(fields) => fields,
141        _ => serde_json::Map::new(),
142    };
143    updated.insert("command".to_string(), Value::String(wrapped));
144
145    json!({
146        "hookSpecificOutput": {
147            "hookEventName": "PreToolUse",
148            "permissionDecision": "allow",
149            "updatedInput": updated
150        }
151    })
152}
153
154/// The hook's response when the CLI's shell prefix is this wrapper: record
155/// the Bash call for the prefix process to claim (prefix.rs), and answer
156/// nothing, so the CLI runs the call exactly as the model made it, its
157/// permission rules and checks included. The one exception is the call's
158/// timeout (`bash_timeout`), answered as an `updatedInput` with no
159/// permission decision. A call that can't be recorded still runs; it just
160/// isn't streamed.
161/// docs/specs/SPEC_BASH_STREAMING_VIA_SHELL_PREFIX_2026_10_10.md §2.2.
162pub fn record_response(stdin_payload: &str) -> Value {
163    let Ok(input) = serde_json::from_str::<PreToolUseInput>(stdin_payload) else {
164        return passthrough();
165    };
166    let command = input.tool_input.get("command").and_then(|v| v.as_str()).unwrap_or("");
167    let usable = input.tool_name == "Bash"
168        && !input.tool_use_id.is_empty()
169        && !input.session_id.is_empty()
170        && !command.starts_with(WRAPPED_PREFIX);
171    if usable {
172        let background = input.tool_input.get("run_in_background").and_then(|v| v.as_bool()).unwrap_or(false);
173        let mut record = crate::prefix::new_record(&input.tool_use_id, command, background);
174        record.description = input
175            .tool_input
176            .get("description")
177            .and_then(|v| v.as_str())
178            .map(str::trim)
179            .filter(|d| !d.is_empty())
180            .map(str::to_string);
181        record.agent_id = input.agent_id.as_deref().map(str::trim).filter(|a| !a.is_empty()).map(str::to_string);
182        if let Err(e) = crate::prefix::register(&input.session_id, &record) {
183            tracing::warn!(target: "bashwrap", tool_id = %input.tool_use_id, error = %e, "couldn't record the Bash call; it runs unstreamed");
184        }
185    }
186    // The call's timeout: a long one clamped so the call goes to the background, or a long one for a call
187    // the CLI would stop at the timeout (`bash_timeout`).
188    crate::bash_timeout::response_from_env(&input.tool_input).unwrap_or_else(passthrough)
189}
190
191fn passthrough() -> Value {
192    // Empty object → Claude Code treats as "no opinion", proceeds.
193    json!({})
194}
195
196// ─────────────────────────────────────────────────────────────────────────────
197// Trailing-redirect → `tee` rewrite (Feature 1)
198//
199// A command like `task package > build.log 2>&1` sends the inner shell's stdout
200// to the file, so the PTY (hence the tool-chunk stream, hence the feed) sees
201// nothing. We recognize an unambiguous *trailing* file redirect and rewrite it
202// so the same bytes still reach the file AND flow through the PTY via `tee`:
203//
204//   CMD > F            → set -o pipefail; { CMD ; } | tee -- F
205//   CMD >> F           → set -o pipefail; { CMD ; } | tee -a -- F
206//   CMD > F 2>&1       → set -o pipefail; { CMD ; } 2>&1 | tee -- F
207//   CMD >> F 2>&1      → set -o pipefail; { CMD ; } 2>&1 | tee -a -- F
208//   CMD &> F           → set -o pipefail; { CMD ; } 2>&1 | tee -- F
209//   CMD &>> F          → set -o pipefail; { CMD ; } 2>&1 | tee -a -- F
210//
211// `set -o pipefail` makes the pipeline's exit code reflect CMD (not `tee`), so
212// bashwrap still mirrors the real exit code. Wrapping the whole command in a
213// `{ ; }` group is safe for a single command OR a pipeline (a pipeline's stdout
214// is its last stage's stdout — exactly what the trailing `>` redirected), which
215// is why we bail on list operators (`&&`/`||`/`;`/`&`), where the redirect would
216// bind to only one command of the list.
217//
218// EVERYTHING ambiguous bails (returns None → encode verbatim, today's behavior):
219// quoted/comment/heredoc/process-substitution redirects, `/dev/null`, fd-specific
220// or dup redirects (`2>f`, `>&2`, and the `2>&1 > F` order), more than one output
221// redirect, and non-trailing redirects.
222// ─────────────────────────────────────────────────────────────────────────────
223
224#[derive(Clone, Copy)]
225enum OutKind {
226    Out,
227    Append,
228    AmpOut,
229    AmpAppend,
230}
231
232struct ScanResult {
233    redir_start: usize,
234    target_start: usize,
235    target_end: usize,
236    append: bool,
237    combine_stderr: bool,
238}
239
240/// Rewrite a recognized trailing redirect to a `tee` pipeline, or `None` to pass
241/// the command through unchanged.
242pub(crate) fn tee_redirect_rewrite(raw: &str) -> Option<String> {
243    let cmd = raw.trim();
244    if cmd.is_empty() {
245        return None;
246    }
247    let scan = scan_redirect(cmd)?;
248    let cmd_part = cmd[..scan.redir_start].trim();
249    if cmd_part.is_empty() {
250        return None;
251    }
252    let target = cmd[scan.target_start..scan.target_end].trim();
253    if target.is_empty() || is_dev_null(target) {
254        return None;
255    }
256    let aflag = if scan.append { "-a " } else { "" };
257    let stream = if scan.combine_stderr { " 2>&1 |" } else { " |" };
258    Some(format!(
259        "set -o pipefail; {{ {} ; }}{} tee {}-- {}",
260        cmd_part, stream, aflag, target
261    ))
262}
263
264fn is_space(c: u8) -> bool {
265    c == b' ' || c == b'\t' || c == b'\n' || c == b'\r'
266}
267
268/// Strip one layer of matching surrounding quotes for the `/dev/null` check.
269fn is_dev_null(target: &str) -> bool {
270    let t = target.trim();
271    let unq = if (t.starts_with('"') && t.ends_with('"') && t.len() >= 2)
272        || (t.starts_with('\'') && t.ends_with('\'') && t.len() >= 2)
273    {
274        &t[1..t.len() - 1]
275    } else {
276        t
277    };
278    unq == "/dev/null"
279}
280
281/// Quote/group-aware scan for a single top-level trailing output redirect.
282/// Returns None on any bail condition (see the module comment above).
283fn scan_redirect(cmd: &str) -> Option<ScanResult> {
284    let b = cmd.as_bytes();
285    let n = b.len();
286    let mut i = 0usize;
287    let mut in_single = false;
288    let mut in_double = false;
289    let mut in_backtick = false;
290    let mut paren_depth: i32 = 0;
291    let mut brace_depth: i32 = 0; // `${...}` parameter-expansion nesting
292
293    let mut out_redirs: Vec<(OutKind, usize, usize)> = Vec::new();
294    let mut dups: Vec<(usize, usize)> = Vec::new(); // 2>&1 occurrences (start, end)
295    let mut other_redir = false;
296    let mut list_op = false;
297
298    while i < n {
299        let c = b[i];
300        if in_single {
301            if c == b'\'' {
302                in_single = false;
303            }
304            i += 1;
305            continue;
306        }
307        if in_double {
308            if c == b'\\' && i + 1 < n {
309                i += 2;
310                continue;
311            }
312            if c == b'"' {
313                in_double = false;
314            }
315            i += 1;
316            continue;
317        }
318        if in_backtick {
319            if c == b'`' {
320                in_backtick = false;
321            }
322            i += 1;
323            continue;
324        }
325        // Unquoted. Quote/escape/group/comment first.
326        match c {
327            b'\\' => {
328                i += 2;
329                continue;
330            }
331            b'\'' => {
332                in_single = true;
333                i += 1;
334                continue;
335            }
336            b'"' => {
337                in_double = true;
338                i += 1;
339                continue;
340            }
341            b'`' => {
342                in_backtick = true;
343                i += 1;
344                continue;
345            }
346            b'#' => {
347                // Comment iff at a word boundary; otherwise a literal `#`.
348                let prev = if i == 0 { b' ' } else { b[i - 1] };
349                if is_space(prev) || matches!(prev, b';' | b'|' | b'&' | b'(' | b'`') {
350                    return None;
351                }
352                i += 1;
353                continue;
354            }
355            b'(' => {
356                paren_depth += 1;
357                i += 1;
358                continue;
359            }
360            b')' => {
361                if paren_depth > 0 {
362                    paren_depth -= 1;
363                }
364                i += 1;
365                continue;
366            }
367            b'$' => {
368                // `${...}` parameter expansion: a literal `>`/`<`/`|` inside it
369                // (e.g. `${X:->f}`, `${X/>/_}`) must not be read as an operator.
370                // `$(...)` is handled by paren_depth via the `(` below.
371                if i + 1 < n && b[i + 1] == b'{' {
372                    brace_depth += 1;
373                    i += 2;
374                } else {
375                    i += 1;
376                }
377                continue;
378            }
379            b'}' => {
380                if brace_depth > 0 {
381                    brace_depth -= 1;
382                }
383                i += 1;
384                continue;
385            }
386            _ => {}
387        }
388        // Inside a subshell / $(...) / ${...} group: ignore operators (the
389        // redirect there doesn't bind the outer command), but keep tracking
390        // quotes (above).
391        if paren_depth > 0 || brace_depth > 0 {
392            i += 1;
393            continue;
394        }
395        // Depth 0, unquoted — operator recognition.
396        match c {
397            b'<' => {
398                if i + 1 < n && (b[i + 1] == b'(' || b[i + 1] == b'<') {
399                    return None; // process substitution or heredoc
400                }
401                other_redir = true; // input redirect
402                i += 1;
403            }
404            b'>' => {
405                if i + 1 < n && b[i + 1] == b'(' {
406                    return None; // process substitution >(
407                }
408                if i > 0 && b[i - 1].is_ascii_digit() {
409                    // fd-prefixed: recognize exactly `2>&1`, else bail.
410                    if b[i - 1] == b'2' && i + 2 < n && b[i + 1] == b'&' && b[i + 2] == b'1' {
411                        dups.push((i - 1, i + 3));
412                        i += 3;
413                    } else {
414                        other_redir = true;
415                        i += 1;
416                    }
417                } else if i + 1 < n && b[i + 1] == b'>' {
418                    out_redirs.push((OutKind::Append, i, i + 2));
419                    i += 2;
420                } else if i + 1 < n && b[i + 1] == b'&' {
421                    other_redir = true; // >&N dup
422                    i += 1;
423                } else {
424                    out_redirs.push((OutKind::Out, i, i + 1));
425                    i += 1;
426                }
427            }
428            b'&' => {
429                if i + 1 < n && b[i + 1] == b'&' {
430                    list_op = true;
431                    i += 2;
432                } else if i + 1 < n && b[i + 1] == b'>' {
433                    if i + 2 < n && b[i + 2] == b'>' {
434                        out_redirs.push((OutKind::AmpAppend, i, i + 3));
435                        i += 3;
436                    } else {
437                        out_redirs.push((OutKind::AmpOut, i, i + 2));
438                        i += 2;
439                    }
440                } else {
441                    list_op = true; // standalone & (background)
442                    i += 1;
443                }
444            }
445            b'|' => {
446                // Both `||` and a plain pipe bail. A plain pipe is bailed (not
447                // wrapped) because `set -o pipefail` on `{ a | b ; } | tee` would
448                // make the INNER pipeline report its first failure instead of the
449                // last stage's exit — changing the exit code the original
450                // `a | b > f` reported. Single commands have no inner pipe, so
451                // pipefail correctly surfaces their exit through the tee.
452                list_op = true;
453                i += if i + 1 < n && b[i + 1] == b'|' { 2 } else { 1 };
454            }
455            // `;` and an unquoted/unescaped newline both separate commands. A
456            // multi-line command whose LAST line has a trailing redirect must not
457            // be wrapped, or `{ <all lines> ; } | tee` would tee the earlier
458            // lines' stdout into the file too (violating the "same bytes to FILE"
459            // guarantee). Quoted/heredoc/escaped newlines never reach here.
460            b';' | b'\n' | b'\r' => {
461                list_op = true;
462                i += 1;
463            }
464            _ => {
465                i += 1;
466            }
467        }
468    }
469    if in_single || in_double || in_backtick {
470        return None; // unterminated quote
471    }
472    if list_op || other_redir || out_redirs.len() != 1 {
473        return None;
474    }
475    let (kind, rstart, rend) = out_redirs[0];
476    // No dup may precede the redirect (the `2>&1 > F` order has different
477    // semantics; bail rather than mis-tee it).
478    if dups.iter().any(|(ds, _)| *ds < rstart) {
479        return None;
480    }
481    // Target word immediately after the redirect.
482    let (tstart, tend) = read_word(b, rend)?;
483    // After the target: an optional trailing `2>&1`, then EOF.
484    let mut j = skip_spaces(b, tend);
485    let mut combine = matches!(kind, OutKind::AmpOut | OutKind::AmpAppend);
486    if let Some((_, de)) = dups.iter().find(|(ds, _)| *ds == j) {
487        combine = true;
488        j = skip_spaces(b, *de);
489    }
490    if j != n {
491        return None; // trailing junk (incl. a second dup)
492    }
493    Some(ScanResult {
494        redir_start: rstart,
495        target_start: tstart,
496        target_end: tend,
497        append: matches!(kind, OutKind::Append | OutKind::AmpAppend),
498        combine_stderr: combine,
499    })
500}
501
502fn skip_spaces(b: &[u8], mut i: usize) -> usize {
503    while i < b.len() && is_space(b[i]) {
504        i += 1;
505    }
506    i
507}
508
509/// Read one shell word (quote-aware) starting at/after `from`, skipping leading
510/// spaces. Returns the word's byte range, or None if there's no word.
511fn read_word(b: &[u8], from: usize) -> Option<(usize, usize)> {
512    let n = b.len();
513    let mut i = skip_spaces(b, from);
514    if i >= n {
515        return None;
516    }
517    let start = i;
518    let mut in_single = false;
519    let mut in_double = false;
520    while i < n {
521        let c = b[i];
522        if in_single {
523            if c == b'\'' {
524                in_single = false;
525            }
526            i += 1;
527            continue;
528        }
529        if in_double {
530            if c == b'\\' && i + 1 < n {
531                i += 2;
532                continue;
533            }
534            if c == b'"' {
535                in_double = false;
536            }
537            i += 1;
538            continue;
539        }
540        match c {
541            b'\'' => {
542                in_single = true;
543                i += 1;
544            }
545            b'"' => {
546                in_double = true;
547                i += 1;
548            }
549            b'\\' => {
550                i += 2;
551            }
552            _ if is_space(c) => break,
553            // operator chars terminate a bare word
554            b'>' | b'<' | b'|' | b'&' | b';' | b'(' | b')' => break,
555            _ => {
556                i += 1;
557            }
558        }
559    }
560    if i == start {
561        return None;
562    }
563    Some((start, i))
564}
565
566/// Quote a value for embedding in a shell argv position.
567///
568/// The tool-use-id is provider-generated and currently always opaque
569/// ASCII, but be defensive: if it contains a non-safe char, escape
570/// per the host shell's rules.
571///
572/// - **Unix shells** (bash/sh/zsh): single-quote wrap with `'\''`
573///   escape for embedded single quotes.
574/// - **Windows `cmd.exe /C`**: cmd doesn't interpret single quotes
575///   as quoting; we use double quotes and escape embedded `"` per
576///   cmd.exe rules. This is the shell Claude Code's Bash tool
577///   invokes on Win32.
578///
579/// Pure-alphanumeric ids return unchanged on every platform.
580fn shell_quote(s: &str) -> String {
581    if s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') {
582        return s.to_string();
583    }
584    #[cfg(windows)]
585    {
586        // cmd.exe: double-quote wrap, escape `"` as `""`. Reasonable
587        // approximation — full cmd.exe quoting is famously gnarly,
588        // but for opaque-ID-with-weird-char defense this is enough.
589        let escaped = s.replace('"', "\"\"");
590        format!("\"{}\"", escaped)
591    }
592    #[cfg(not(windows))]
593    {
594        // bash/sh/zsh: single-quote wrap, escape `'` as `'\''`.
595        let escaped = s.replace('\'', r"'\''");
596        format!("'{}'", escaped)
597    }
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603    use serde_json::json;
604
605    fn payload(cmd: &str, id: &str) -> String {
606        json!({
607            "tool_name": "Bash",
608            "tool_use_id": id,
609            "tool_input": { "command": cmd },
610            "session_id": "sess-1",
611            "hook_event_name": "PreToolUse"
612        })
613        .to_string()
614    }
615
616    #[test]
617    fn rewrites_simple_bash_command() {
618        let resp = build_response(&payload("echo hi", "toolu_abc"));
619        let cmd = resp["hookSpecificOutput"]["updatedInput"]["command"]
620            .as_str()
621            .unwrap();
622        assert!(cmd.starts_with("agentmux-bashwrap exec"));
623        assert!(cmd.contains("--tool-id=toolu_abc"));
624        // base64("echo hi") = ZWNobyBoaQ
625        assert!(cmd.contains("--b64-cmd=ZWNobyBoaQ"));
626        assert_eq!(
627            resp["hookSpecificOutput"]["permissionDecision"].as_str(),
628            Some("allow")
629        );
630    }
631
632    #[test]
633    fn preserves_multi_line_and_quotes_via_base64() {
634        let cmd = r#"echo "hello" && echo 'multi
635line' && cat $HOME/.env"#;
636        let resp = build_response(&payload(cmd, "toolu_x"));
637        let wrapped = resp["hookSpecificOutput"]["updatedInput"]["command"]
638            .as_str()
639            .unwrap();
640        // The wrapped form must round-trip — pull the b64 back and decode.
641        let b64 = wrapped
642            .split("--b64-cmd=")
643            .nth(1)
644            .expect("b64 arg present");
645        let decoded = URL_SAFE_NO_PAD.decode(b64.as_bytes()).unwrap();
646        let decoded = String::from_utf8(decoded).unwrap();
647        assert_eq!(decoded, cmd);
648    }
649
650    #[test]
651    fn is_no_op_on_already_wrapped_command() {
652        let cmd =
653            "agentmux-bashwrap exec --tool-id=toolu_y --b64-cmd=ZWNobyBoaQ";
654        let resp = build_response(&payload(cmd, "toolu_y"));
655        assert!(
656            resp.as_object().map(|m| m.is_empty()).unwrap_or(false),
657            "should pass through (empty object), got {}",
658            resp
659        );
660    }
661
662    #[test]
663    fn passes_through_non_bash_tools() {
664        let payload = json!({
665            "tool_name": "Read",
666            "tool_use_id": "toolu_r",
667            "tool_input": { "file_path": "x.txt" }
668        })
669        .to_string();
670        let resp = build_response(&payload);
671        assert!(
672            resp.as_object().map(|m| m.is_empty()).unwrap_or(false),
673            "non-Bash should pass through"
674        );
675    }
676
677    #[test]
678    fn passes_through_malformed_input() {
679        let resp = build_response("not json");
680        assert!(
681            resp.as_object().map(|m| m.is_empty()).unwrap_or(false),
682            "malformed → passthrough"
683        );
684    }
685
686    #[test]
687    fn rewrites_with_empty_b64_when_command_field_missing() {
688        // Codex P2 round 3: the previous name `passes_through_when_
689        // command_field_missing` lied about behavior, and the inline
690        // comment claimed `bash -c ""` would "fail at wrapper start
691        // time" — which is wrong; an empty bash command exits 0
692        // silently. Renamed + comment corrected to describe what
693        // actually happens.
694        //
695        // Behavior under test: when `tool_input.command` is missing,
696        // we still emit a rewrite (with `--b64-cmd=` of an empty
697        // string). The wrapper then runs `bash -c ""` which exits 0
698        // immediately. Net effect: a no-op Bash call streams a "0
699        // chars" system chunk + an empty body, and Claude sees an
700        // empty tool_result. Not catastrophic; the empty input was
701        // already going to do nothing.
702        let payload = json!({
703            "tool_name": "Bash",
704            "tool_use_id": "toolu_z",
705            "tool_input": {}
706        })
707        .to_string();
708        let resp = build_response(&payload);
709        let cmd = resp["hookSpecificOutput"]["updatedInput"]["command"]
710            .as_str()
711            .unwrap();
712        // The b64 of an empty string is the empty string, so we
713        // expect `--b64-cmd=` immediately followed by whatever ends
714        // the command (whitespace or EOL). Match the prefix.
715        assert!(
716            cmd.contains("--b64-cmd=") && (cmd.ends_with("--b64-cmd=") || cmd.contains("--b64-cmd= ")),
717            "expected empty b64-cmd argument, got: {}",
718            cmd
719        );
720    }
721
722    #[test]
723    fn threads_declared_background_flag_when_run_in_background_true() {
724        let payload = json!({
725            "tool_name": "Bash",
726            "tool_use_id": "toolu_bg",
727            "tool_input": { "command": "task dev", "run_in_background": true }
728        })
729        .to_string();
730        let resp = build_response(&payload);
731        let cmd = resp["hookSpecificOutput"]["updatedInput"]["command"]
732            .as_str()
733            .unwrap();
734        assert!(
735            cmd.ends_with(" --declared-background"),
736            "expected the wrapped command to carry --declared-background, got: {cmd}"
737        );
738    }
739
740    #[test]
741    fn omits_declared_background_flag_when_run_in_background_false_or_absent() {
742        let with_false = json!({
743            "tool_name": "Bash",
744            "tool_use_id": "toolu_fg",
745            "tool_input": { "command": "echo hi", "run_in_background": false }
746        })
747        .to_string();
748        let without_field = json!({
749            "tool_name": "Bash",
750            "tool_use_id": "toolu_fg2",
751            "tool_input": { "command": "echo hi" }
752        })
753        .to_string();
754        for payload in [with_false, without_field] {
755            let resp = build_response(&payload);
756            let cmd = resp["hookSpecificOutput"]["updatedInput"]["command"]
757                .as_str()
758                .unwrap();
759            assert!(
760                !cmd.contains("--declared-background"),
761                "expected no --declared-background flag, got: {cmd}"
762            );
763        }
764    }
765
766    /// `updatedInput` replaces the whole input, so every field but `command`
767    /// must come back as the model set it: the CLI reads `run_in_background`
768    /// and `timeout` from it, and labels the call and its task with
769    /// `description`.
770    #[test]
771    fn keeps_every_other_field_of_the_tool_input() {
772        let payload = json!({
773            "tool_name": "Bash",
774            "tool_use_id": "toolu_keep",
775            "tool_input": {
776                "command": "task dev",
777                "description": "Start the dev build",
778                "timeout": 7_200_000,
779                "run_in_background": true,
780                "dangerouslyDisableSandbox": false,
781                "some_future_field": { "nested": [1, 2] }
782            }
783        })
784        .to_string();
785        let resp = build_response(&payload);
786        let updated = &resp["hookSpecificOutput"]["updatedInput"];
787        assert!(updated["command"].as_str().unwrap().starts_with("agentmux-bashwrap exec"));
788        assert_eq!(updated["description"], json!("Start the dev build"));
789        assert_eq!(updated["timeout"], json!(7_200_000));
790        assert_eq!(updated["run_in_background"], json!(true));
791        assert_eq!(updated["dangerouslyDisableSandbox"], json!(false));
792        assert_eq!(updated["some_future_field"], json!({ "nested": [1, 2] }));
793        assert_eq!(updated.as_object().unwrap().len(), 6);
794    }
795
796    /// A subagent's call carries its id to the wrapper, which keeps its
797    /// working directory apart (SPEC_BASHWRAP_PER_AGENT_CWD_2026_10_18.md).
798    #[test]
799    fn a_subagents_call_names_the_agent_and_the_main_conversation_none() {
800        let mut p: Value = serde_json::from_str(&payload("echo hi", "toolu_sub")).unwrap();
801        p["agent_id"] = json!("a7e1898179149a4f7");
802        let resp = build_response(&p.to_string());
803        let cmd = resp["hookSpecificOutput"]["updatedInput"]["command"].as_str().unwrap().to_string();
804        assert!(cmd.ends_with(" --agent=a7e1898179149a4f7"), "{cmd}");
805        let main = build_response(&payload("echo hi", "toolu_main"));
806        assert!(!main["hookSpecificOutput"]["updatedInput"]["command"].as_str().unwrap().contains("--agent"));
807    }
808
809    #[test]
810    fn record_mode_keeps_the_subagent_on_the_record() {
811        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
812        let dir = std::env::temp_dir().join(format!("bashwrap-hook-agent-{}", std::process::id()));
813        std::env::set_var("AGENTMUX_BASHWRAP_CALLS_DIR", &dir);
814        let payload = json!({
815            "tool_name": "Bash", "tool_use_id": "toolu_sub", "session_id": "sess-sub", "agent_id": "sub-7",
816            "tool_input": { "command": "git status" }
817        })
818        .to_string();
819        record_response(&payload);
820        let claimed = crate::prefix::claim("sess-sub", "git status");
821        std::env::remove_var("AGENTMUX_BASHWRAP_CALLS_DIR");
822        let _ = std::fs::remove_dir_all(&dir);
823        assert_eq!(claimed.expect("recorded").agent_id.as_deref(), Some("sub-7"));
824    }
825
826    /// While the CLI's default is the short one AgentMux sets: a `git` call with no timeout gets a long
827    /// one, and a long timeout on another call is clamped to the default. The answer is an `updatedInput`
828    /// with no permission decision. Without that default, or with nothing to change, the hook answers nothing.
829    #[test]
830    fn record_mode_gives_a_git_call_a_long_timeout_and_decides_nothing_else() {
831        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
832        let dir = std::env::temp_dir().join(format!("bashwrap-hook-git-{}", std::process::id()));
833        std::env::set_var("AGENTMUX_BASHWRAP_CALLS_DIR", &dir);
834        let call = |command: &str| {
835            json!({
836                "tool_name": "Bash", "tool_use_id": "toolu_git", "session_id": "sess-git",
837                "tool_input": { "command": command, "description": "Push the branch" }
838            })
839            .to_string()
840        };
841        std::env::set_var("BASH_DEFAULT_TIMEOUT_MS", "30000");
842        let git = record_response(&call("git push origin x"));
843        let other = record_response(&call("cargo build"));
844        let long_build = json!({
845            "tool_name": "Bash", "tool_use_id": "toolu_long", "session_id": "sess-git",
846            "tool_input": { "command": "cargo build", "timeout": 600_000 }
847        })
848        .to_string();
849        let clamped = record_response(&long_build);
850        std::env::remove_var("BASH_DEFAULT_TIMEOUT_MS");
851        let no_default = record_response(&call("git push origin x"));
852        std::env::remove_var("AGENTMUX_BASHWRAP_CALLS_DIR");
853        let _ = std::fs::remove_dir_all(&dir);
854        let hso = &git["hookSpecificOutput"];
855        assert_eq!(hso["updatedInput"]["timeout"], 300_000);
856        assert_eq!(hso["updatedInput"]["description"], "Push the branch");
857        assert!(hso.get("permissionDecision").is_none());
858        assert_eq!(other, json!({}));
859        assert_eq!(clamped["hookSpecificOutput"]["updatedInput"]["timeout"], 30_000, "a long timeout is clamped so the call goes to the background");
860        assert_eq!(no_default, json!({}));
861    }
862
863    /// Prefix mode: the call is recorded for the prefix process and the
864    /// response changes nothing (no `updatedInput`, no `permissionDecision`).
865    #[test]
866    fn record_mode_records_the_call_and_answers_nothing() {
867        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
868        let dir = std::env::temp_dir().join(format!("bashwrap-hook-record-{}", std::process::id()));
869        std::env::set_var("AGENTMUX_BASHWRAP_CALLS_DIR", &dir);
870        let payload = json!({
871            "tool_name": "Bash",
872            "tool_use_id": "toolu_rec",
873            "session_id": "sess-rec",
874            "tool_input": { "command": "cargo build", "description": "Build", "run_in_background": true }
875        })
876        .to_string();
877        let resp = record_response(&payload);
878        let claimed = crate::prefix::claim("sess-rec", "cargo build");
879        let described = claimed.as_ref().and_then(|c| c.description.clone());
880        let wrapped = json!({
881            "tool_name": "Bash", "tool_use_id": "toolu_w", "session_id": "sess-rec",
882            "tool_input": { "command": "agentmux-bashwrap exec --tool-id=x --b64-cmd=eA" }
883        })
884        .to_string();
885        let resp_wrapped = record_response(&wrapped);
886        let left = crate::prefix::claim("sess-rec", "any command");
887        std::env::remove_var("AGENTMUX_BASHWRAP_CALLS_DIR");
888        let _ = std::fs::remove_dir_all(&dir);
889
890        assert_eq!(resp, json!({}));
891        let claimed = claimed.expect("the call was recorded");
892        assert_eq!((claimed.tool_use_id.as_str(), claimed.run_in_background), ("toolu_rec", true));
893        assert_eq!(described.as_deref(), Some("Build"), "the call's description, for Tower");
894        assert_eq!(resp_wrapped, json!({}));
895        assert_eq!(left, None, "an already-wrapped command isn't recorded");
896    }
897
898    #[test]
899    fn record_mode_ignores_other_tools_and_malformed_payloads() {
900        assert_eq!(record_response("not json"), json!({}));
901        let read = json!({ "tool_name": "Read", "tool_use_id": "t", "session_id": "s", "tool_input": {} }).to_string();
902        assert_eq!(record_response(&read), json!({}));
903    }
904
905    #[test]
906    fn a_tool_input_that_is_not_an_object_still_gets_the_command() {
907        let payload = json!({
908            "tool_name": "Bash",
909            "tool_use_id": "toolu_odd",
910            "tool_input": "echo hi"
911        })
912        .to_string();
913        let resp = build_response(&payload);
914        let updated = resp["hookSpecificOutput"]["updatedInput"].as_object().unwrap();
915        assert_eq!(updated.len(), 1);
916        assert!(updated["command"].as_str().unwrap().starts_with("agentmux-bashwrap exec"));
917    }
918
919    #[test]
920    fn shell_quote_passes_safe_ids_unchanged() {
921        assert_eq!(shell_quote("toolu_abc-123"), "toolu_abc-123");
922    }
923
924    #[cfg(not(windows))]
925    #[test]
926    fn shell_quote_wraps_unsafe_ids_unix() {
927        let q = shell_quote("weird id");
928        assert_eq!(q, "'weird id'");
929    }
930
931    #[cfg(not(windows))]
932    #[test]
933    fn shell_quote_escapes_embedded_single_quotes_unix() {
934        // Standard bash idiom: `'` → `'\''` (close, escaped, reopen).
935        // For `o'malley` the result is `'o'\''malley'`.
936        let q = shell_quote("o'malley");
937        assert_eq!(q, r"'o'\''malley'");
938    }
939
940    #[cfg(windows)]
941    #[test]
942    fn shell_quote_wraps_unsafe_ids_windows() {
943        let q = shell_quote("weird id");
944        assert_eq!(q, "\"weird id\"");
945    }
946
947    #[cfg(windows)]
948    #[test]
949    fn shell_quote_escapes_embedded_double_quotes_windows() {
950        // cmd.exe `""` is the escape for a literal `"` inside a
951        // double-quoted argument. For `a"b` the result is `"a""b"`.
952        let q = shell_quote("a\"b");
953        assert_eq!(q, "\"a\"\"b\"");
954    }
955
956    // ── tee redirect rewrite (Feature 1) ──────────────────────────────
957
958    #[test]
959    fn tee_rewrites_basic_redirect_forms() {
960        assert_eq!(
961            tee_redirect_rewrite("task package > build.log").unwrap(),
962            "set -o pipefail; { task package ; } | tee -- build.log"
963        );
964        assert_eq!(
965            tee_redirect_rewrite("make >> out.log").unwrap(),
966            "set -o pipefail; { make ; } | tee -a -- out.log"
967        );
968        assert_eq!(
969            tee_redirect_rewrite("task package > build.log 2>&1").unwrap(),
970            "set -o pipefail; { task package ; } 2>&1 | tee -- build.log"
971        );
972        assert_eq!(
973            tee_redirect_rewrite("make >> out.log 2>&1").unwrap(),
974            "set -o pipefail; { make ; } 2>&1 | tee -a -- out.log"
975        );
976        assert_eq!(
977            tee_redirect_rewrite("cmd &> all.log").unwrap(),
978            "set -o pipefail; { cmd ; } 2>&1 | tee -- all.log"
979        );
980        assert_eq!(
981            tee_redirect_rewrite("cmd &>> all.log").unwrap(),
982            "set -o pipefail; { cmd ; } 2>&1 | tee -a -- all.log"
983        );
984    }
985
986    #[test]
987    fn tee_bails_on_internal_pipeline() {
988        // A pipe inside the command bails: `set -o pipefail` on the tee wrapper
989        // would change the inner pipeline's exit-code semantics vs the original.
990        assert!(tee_redirect_rewrite("cargo build | grep error > errors.log").is_none());
991    }
992
993    #[test]
994    fn tee_bails_on_multiline_command() {
995        // A multi-line command with a trailing redirect on the last line must NOT
996        // be wrapped — wrapping would tee the earlier lines' output into the file.
997        assert!(tee_redirect_rewrite("echo building\nmake > build.log").is_none());
998        assert!(tee_redirect_rewrite("cd src\nmake > build.log 2>&1").is_none());
999        // A backslash-newline line continuation is NOT a separator — still rewritten.
1000        assert_eq!(
1001            tee_redirect_rewrite("make \\\n  --flag > build.log").unwrap(),
1002            "set -o pipefail; { make \\\n  --flag ; } | tee -- build.log"
1003        );
1004    }
1005
1006    #[test]
1007    fn tee_handles_subshell_command() {
1008        assert_eq!(
1009            tee_redirect_rewrite("(cd src && make) > b.log 2>&1").unwrap(),
1010            "set -o pipefail; { (cd src && make) ; } 2>&1 | tee -- b.log"
1011        );
1012    }
1013
1014    #[test]
1015    fn tee_preserves_quoted_target() {
1016        assert_eq!(
1017            tee_redirect_rewrite(r#"cmd > "my out.log""#).unwrap(),
1018            r#"set -o pipefail; { cmd ; } | tee -- "my out.log""#
1019        );
1020    }
1021
1022    #[test]
1023    fn tee_bails_on_dev_null() {
1024        assert!(tee_redirect_rewrite("noisy > /dev/null").is_none());
1025        assert!(tee_redirect_rewrite("noisy > /dev/null 2>&1").is_none());
1026        assert!(tee_redirect_rewrite(r#"noisy > "/dev/null""#).is_none());
1027    }
1028
1029    #[test]
1030    fn tee_bails_on_quoted_comment_heredoc_procsub() {
1031        assert!(tee_redirect_rewrite("echo 'a > b'").is_none()); // quoted >
1032        assert!(tee_redirect_rewrite("echo \"x > y\"").is_none()); // quoted >
1033        assert!(tee_redirect_rewrite("make # writes > log").is_none()); // comment
1034        assert!(tee_redirect_rewrite("cat <<EOF > f\nhi\nEOF").is_none()); // heredoc
1035        assert!(tee_redirect_rewrite("diff <(a) > f").is_none()); // process subst
1036    }
1037
1038    #[test]
1039    fn tee_bails_on_non_trailing_multiple_or_fd_redirects() {
1040        assert!(tee_redirect_rewrite("cmd > f | grep x").is_none()); // not trailing
1041        assert!(tee_redirect_rewrite("cmd > f && other").is_none()); // list op
1042        assert!(tee_redirect_rewrite("a > f1 > f2").is_none()); // two redirects
1043        assert!(tee_redirect_rewrite("cmd 2> err.log").is_none()); // fd-specific
1044        assert!(tee_redirect_rewrite("cmd >&2").is_none()); // dup
1045        assert!(tee_redirect_rewrite("cmd 2>&1 > f").is_none()); // leading 2>&1 order
1046        assert!(tee_redirect_rewrite("echo hi").is_none()); // no redirect
1047        assert!(tee_redirect_rewrite("server > log &").is_none()); // background
1048    }
1049
1050    #[test]
1051    fn tee_handles_param_expansion() {
1052        // A literal `>` inside a ${...} expansion is NOT a redirect → no rewrite.
1053        assert!(tee_redirect_rewrite("echo ${X:->f}").is_none());
1054        assert!(tee_redirect_rewrite("echo ${X/>/_}").is_none());
1055        // A real trailing redirect to a ${...}-bearing target IS rewritten.
1056        assert_eq!(
1057            tee_redirect_rewrite("make > ${LOG}/out.log").unwrap(),
1058            "set -o pipefail; { make ; } | tee -- ${LOG}/out.log"
1059        );
1060        // ...and a ${...} with an inner `>` plus a real trailing redirect.
1061        assert_eq!(
1062            tee_redirect_rewrite("echo ${X/>/_} > out.log").unwrap(),
1063            "set -o pipefail; { echo ${X/>/_} ; } | tee -- out.log"
1064        );
1065    }
1066
1067    #[test]
1068    fn tee_rewrite_round_trips_through_build_response_b64() {
1069        let resp = build_response(&payload("task package > build.log 2>&1", "toolu_t"));
1070        let wrapped = resp["hookSpecificOutput"]["updatedInput"]["command"]
1071            .as_str()
1072            .unwrap();
1073        let b64 = wrapped.split("--b64-cmd=").nth(1).expect("b64 arg");
1074        let decoded =
1075            String::from_utf8(URL_SAFE_NO_PAD.decode(b64.as_bytes()).unwrap()).unwrap();
1076        assert_eq!(
1077            decoded,
1078            "set -o pipefail; { task package ; } 2>&1 | tee -- build.log"
1079        );
1080        // pipefail present → pipeline exit code reflects the command, not tee.
1081        assert!(decoded.starts_with("set -o pipefail;"));
1082    }
1083
1084    #[test]
1085    fn tee_non_redirect_command_encodes_verbatim() {
1086        // No recognized redirect → command encodes unchanged (today's behavior).
1087        let resp = build_response(&payload("echo hi", "toolu_a"));
1088        let wrapped = resp["hookSpecificOutput"]["updatedInput"]["command"]
1089            .as_str()
1090            .unwrap();
1091        let b64 = wrapped.split("--b64-cmd=").nth(1).unwrap();
1092        let decoded =
1093            String::from_utf8(URL_SAFE_NO_PAD.decode(b64.as_bytes()).unwrap()).unwrap();
1094        assert_eq!(decoded, "echo hi");
1095    }
1096}