Skip to main content

agentmux_srv_core/backend/
bash_background.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Bash call that runs long goes to the background, so the agent is free to take the next message.
5//!
6//! Claude Code moves a Bash call to the background by itself when it has run past its timeout, gives
7//! the model the tool result ("Command did not complete within its Ns timeout and was moved to the
8//! background") and ends the turn; the command's end arrives later as a task notification that
9//! starts a turn. That needs no terminal: it holds in AgentMux's hosting (stream-json, no PTY). The
10//! timeout is the CLI's own `BASH_DEFAULT_TIMEOUT_MS` when the model sets none; the dock already
11//! promotes a call at the same age (`TOOL_PROMOTION_MS`, `frontend/app/agent-model/tool-adapter.ts`).
12//!
13//! Only the default is set, not `BASH_MAX_TIMEOUT_MS`. The CLI does not background a command that
14//! contains `git` (or starts with `sleep`): it stops it at the timeout. With the maximum at the same
15//! age, a `git push`, a clone or a commit with slow hooks would be stopped at that age whatever
16//! `timeout` the model asked for. A `timeout` the model sets itself is the `PreToolUse` hook's to
17//! shape (`agentmux-bashwrap`, `bash_timeout.rs`): it clamps a longer one to the default so the call
18//! goes to the background too, and leaves it alone for the commands the CLI stops at the limit, which
19//! it also gives five minutes when the model set none.
20
21use std::collections::HashMap;
22
23use super::obj::{meta_get_string, MetaMapType};
24
25/// How long a Bash call may run before it goes to the background.
26pub const BACKGROUND_AFTER_MS: u64 = 30_000;
27const DEFAULT_ENV: &str = "BASH_DEFAULT_TIMEOUT_MS";
28/// srv's own environment variable that changes the age, in ms; `0` turns the behaviour off.
29const AFTER_ENV: &str = "AGENTMUX_BASH_BACKGROUND_AFTER_MS";
30
31/// Set the default Bash timeout in a launch environment: a Claude agent's only. A value the
32/// environment already carries (the agent's own `cmd:env`) is kept, so an operator can still choose
33/// otherwise; `after_ms` of `0` sets nothing.
34pub fn apply(env_vars: &mut HashMap<String, String>, provider: &str, after_ms: u64) {
35    if provider != "claude" || after_ms == 0 {
36        return;
37    }
38    env_vars.entry(DEFAULT_ENV.to_string()).or_insert_with(|| after_ms.to_string());
39}
40
41/// The age in force: srv's override, else [`BACKGROUND_AFTER_MS`].
42fn after_ms(override_value: Option<&str>) -> u64 {
43    override_value.and_then(|v| v.trim().parse().ok()).unwrap_or(BACKGROUND_AFTER_MS)
44}
45
46/// [`apply`] for a block's launch, reading the provider from its meta. A block with no provider is a
47/// Claude one, as elsewhere in the launch code.
48pub fn apply_for_spawn(env_vars: &mut HashMap<String, String>, block_meta: &MetaMapType) {
49    let provider = super::providers::resolve_provider_alias(&meta_get_string(block_meta, "agentProvider", "claude"));
50    let provider = if provider.is_empty() { "claude" } else { provider };
51    apply(env_vars, provider, after_ms(std::env::var(AFTER_ENV).ok().as_deref()));
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn a_claude_launch_gets_the_default_timeout_and_not_the_maximum() {
60        let mut env = HashMap::new();
61        apply(&mut env, "claude", BACKGROUND_AFTER_MS);
62        assert_eq!(env[DEFAULT_ENV], "30000");
63        assert_eq!(env.len(), 1, "a model's longer timeout must still be honoured (git commands are stopped, not backgrounded)");
64    }
65
66    #[test]
67    fn another_provider_is_left_alone() {
68        for provider in ["codex", "gemini", "qwen", ""] {
69            let mut env = HashMap::new();
70            apply(&mut env, provider, BACKGROUND_AFTER_MS);
71            assert!(env.is_empty(), "{provider}");
72        }
73    }
74
75    #[test]
76    fn the_agents_own_timeout_is_kept() {
77        let mut env = HashMap::from([(DEFAULT_ENV.to_string(), "600000".to_string())]);
78        apply(&mut env, "claude", BACKGROUND_AFTER_MS);
79        assert_eq!(env[DEFAULT_ENV], "600000");
80    }
81
82    #[test]
83    fn zero_turns_it_off_and_a_bad_value_means_the_default() {
84        let mut env = HashMap::new();
85        apply(&mut env, "claude", after_ms(Some("0")));
86        assert!(env.is_empty());
87        assert_eq!(after_ms(Some("45000")), 45_000);
88        assert_eq!(after_ms(Some("soon")), BACKGROUND_AFTER_MS);
89        assert_eq!(after_ms(None), BACKGROUND_AFTER_MS);
90    }
91
92    #[test]
93    fn a_block_with_no_provider_or_an_alias_is_a_claude_launch() {
94        for meta in [MetaMapType::new(), MetaMapType::from_iter([("agentProvider".to_string(), serde_json::json!("claude-code"))])] {
95            let mut env = HashMap::new();
96            apply_for_spawn(&mut env, &meta);
97            if std::env::var(AFTER_ENV).is_err() {
98                assert_eq!(env[DEFAULT_ENV], "30000");
99            }
100        }
101    }
102}