agentmux_bashwrap/bash_timeout.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The timeout of a Bash call, set by the `PreToolUse` hook so the agent is free after 30 seconds.
5//!
6//! AgentMux has Claude Code move a Bash call to the background once it has run for
7//! `BASH_DEFAULT_TIMEOUT_MS` (30 s), so the agent can take the next message. That default applies only
8//! to a call with no `timeout` of its own: a model that sets one (a build, a wait on the build slot)
9//! holds its turn for it. So the hook clamps a longer `timeout` to the default.
10//!
11//! The CLI does not move every command to the background. A command it cannot parse into simple
12//! commands is stopped at the timeout instead (exit 143): one with `git` in it, a command or process
13//! substitution, a parameter, brace or `$'...'` expansion. Measured on 2.1.218; `$VAR`, `~`, globs,
14//! loops, `if`, subshells, `bash -c`, `eval`, heredocs, redirects, pipes, `&&`, `;` and `&` are
15//! moved. For a call of that kind the hook does the reverse and gives a timeout long enough to
16//! finish when the model set none; a timeout the model chose stands, as it did before the 30 s
17//! default. It answers `updatedInput` only, with no permission decision, so the user's `allow`,
18//! `ask` and `deny` rules still apply to the call.
19
20use serde_json::{json, Value};
21
22/// The timeout a call the CLI would stop gets when the model set none: long enough for a push or a clone.
23pub const LONG_TIMEOUT_MS: u64 = 5 * 60 * 1000;
24
25/// The CLI's default Bash timeout, which AgentMux sets at launch (`backend/bash_background.rs` in srv).
26const DEFAULT_ENV: &str = "BASH_DEFAULT_TIMEOUT_MS";
27
28/// Spellings that make the CLI stop a command at the timeout instead of moving it to the background.
29/// Wider than what was measured on purpose: a `{` alone, or one inside quotes, is also taken as one, so
30/// a call is clamped only when it is known to be moved.
31const STOPPED_SPELLINGS: [&str; 6] = ["$(", "$'", "`", "<(", ">(", "{"];
32
33/// Whether `command` contains `git` as a word. A path like `~/git/x` counts; `digit` and `gitleaks` do not.
34pub fn mentions_git(command: &str) -> bool {
35 let word = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
36 let bytes = command.as_bytes();
37 command.match_indices("git").any(|(at, _)| {
38 let before = at.checked_sub(1).map(|i| bytes[i]);
39 let after = bytes.get(at + 3).copied();
40 !before.is_some_and(word) && !after.is_some_and(word)
41 })
42}
43
44/// Whether the CLI may stop `command` at the timeout rather than move it to the background.
45pub fn stopped_at_timeout(command: &str) -> bool {
46 mentions_git(command) || STOPPED_SPELLINGS.iter().any(|s| command.contains(s))
47}
48
49/// The call's `timeout` in ms, when it sets one.
50fn timeout_of(fields: &serde_json::Map<String, Value>) -> Result<Option<u64>, ()> {
51 match fields.get("timeout") {
52 None | Some(Value::Null) => Ok(None),
53 // A float (`600000.0`) is a timeout too; anything else is not ours to read.
54 Some(v) => v.as_u64().or_else(|| v.as_f64().filter(|f| *f >= 0.0).map(|f| f as u64)).map(Some).ok_or(()),
55 }
56}
57
58/// The timeout this call should have, or `None` to leave it as it is.
59///
60/// - `default_ms`: the CLI's default (`BASH_DEFAULT_TIMEOUT_MS`). Nothing is done without one shorter than
61/// [`LONG_TIMEOUT_MS`], so turning the 30 s default off turns this off too.
62/// - A call the CLI would stop gets [`LONG_TIMEOUT_MS`] when it sets no `timeout`; one it sets stands.
63/// - Any other call that sets a `timeout` longer than the default is clamped to the default, which is what
64/// moves it to the background then. A shorter one stands, and so does a call with none (the default applies).
65/// - A background call (`run_in_background`) is left alone.
66pub fn timeout_for(fields: &serde_json::Map<String, Value>, default_ms: Option<u64>) -> Option<u64> {
67 let default_ms = default_ms.filter(|d| *d < LONG_TIMEOUT_MS)?;
68 let command = fields.get("command")?.as_str()?;
69 if fields.get("run_in_background").and_then(Value::as_bool).unwrap_or(false) {
70 return None;
71 }
72 let set = timeout_of(fields).ok()?;
73 if stopped_at_timeout(command) {
74 return set.is_none().then_some(LONG_TIMEOUT_MS);
75 }
76 set.filter(|t| *t > default_ms).map(|_| default_ms)
77}
78
79/// The hook's `updatedInput` answer for this Bash call, or `None` to leave it alone. Every other field the
80/// model set is carried through, as `updatedInput` replaces the whole input.
81pub fn response(tool_input: &Value, default_ms: Option<u64>) -> Option<Value> {
82 let fields = tool_input.as_object()?;
83 let timeout = timeout_for(fields, default_ms)?;
84 let mut updated = fields.clone();
85 updated.insert("timeout".to_string(), json!(timeout));
86 Some(json!({ "hookSpecificOutput": { "hookEventName": "PreToolUse", "updatedInput": updated } }))
87}
88
89/// [`response`] with the default read from this process's environment (the CLI's, which it inherits).
90pub fn response_from_env(tool_input: &Value) -> Option<Value> {
91 response(tool_input, std::env::var(DEFAULT_ENV).ok().and_then(|v| v.trim().parse().ok()))
92}
93
94#[cfg(test)]
95#[path = "bash_timeout_tests.rs"]
96mod tests;