Skip to main content

agentmux_srv/bootstrap/
delivery.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Split out of the single-file bootstrap module unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.3).
5
6use super::*;
7
8/// Deliver cron fires in process, through the server's shared inject path
9/// (`server::reactive::deliver`) on the instance-key tier — identity M4c-3
10/// (SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md §6.5.9). The fire
11/// keeps every tier the route has (this instance, cross-instance,
12/// cross-channel, LAN, cloud) and audits the job's creator UID here only.
13///
14/// Must run AFTER `build_app_state` and BEFORE `cron_scheduler.start()`, so
15/// no fire takes the HTTP fallback. A fire to a stopped agent starts it with `agents:always_available`
16/// on (`server::jekt_start`).
17pub fn install_cron_delivery(state: &AppState) {
18    let st = state.clone();
19    state.cron_scheduler.install_delivery(Arc::new(move |req, creator_uid| {
20        let st = st.clone();
21        Box::pin(async move {
22            crate::server::jekt_start::deliver_cron(&st, &creator_uid, req).await
23        })
24    }));
25    // A pending fire (catch-up `latest`) waits until its agent is back,
26    // here or in another channel on this computer (the inject path reaches
27    // both).
28    let handler = state.reactive_handler;
29    state.cron_scheduler.install_presence(Arc::new(move |uid: &str| {
30        handler.has_uid_registration(uid)
31            || crate::registry::resolve_shared_reactive_dir().is_some_and(|dir| {
32                crate::backend::jobs::registered_in_another_channel(
33                    &dir,
34                    uid,
35                    &crate::backend::reactive::registry::local_channel_id(),
36                )
37            })
38    }));
39}
40
41/// Where a message for an agent block goes, and the routing of one, live in the core (`backend/agent_route.rs`).
42pub(crate) use crate::backend::agent_route::{route_agent_message_from, AgentRoute};
43
44// Live delivery passes inline blocks (`route_agent_message_from`); the tests
45// route text alone.
46#[cfg(test)]
47pub(crate) fn route_agent_message(block_id: &str, message: &str) -> Result<AgentRoute, String> {
48    route_agent_message_from(block_id, message, None, backend::message_origin::MessageOrigin::system(), &[], None)
49}
50
51/// Whether `block_id` is a subprocess agent in the middle of a turn: a message for it queues.
52fn turn_in_flight(block_id: &str) -> bool {
53    backend::blockcontroller::get_controller(block_id)
54        .and_then(|ctrl| {
55            ctrl.as_any()
56                .downcast_ref::<backend::blockcontroller::subprocess::SubprocessController>()
57                .map(|s| s.turn_in_flight())
58        })
59        .unwrap_or(false)
60}
61
62/// Give the reactive handler a delivery route to `SubprocessController` agents.
63///
64/// `spawn_background_subsystems` installs a message sender that can only reach
65/// the two controller kinds `deliver_agent_message` knows about — persistent
66/// (stream-json stdin) and ACP (`session/prompt`). Everything else it reports as
67/// [`AgentDelivery::Pty`], so the caller falls back to keystroke injection.
68///
69/// That fallback is wrong for a `SubprocessController`, which has no PTY and
70/// rejects raw input outright ("subprocess controller does not accept raw input;
71/// use AgentInputCommand"). The result was that EVERY inter-agent message to
72/// such an agent was dropped: 6 of 10 providers as host agents (codex, gemini,
73/// qwen, kimi, muxcode) and every container agent of any provider,
74/// since `agent_open.rs` forces `controller_type = "subprocess"` for container
75/// mode. The swarm pane still listed them as present, because registration and
76/// delivery are separate paths. See
77/// `docs/reports/REPORT_JEKT_DELIVERY_DROPS_SUBPROCESS_AGENTS_2026_09_02.md`.
78///
79/// This re-installs the sender with the missing branch: a subprocess target gets
80/// a real turn via `run_agent_turn` — the same thing `AgentInputCommand` does
81/// when the operator types into the pane — instead of keystrokes it will refuse.
82///
83/// Must run AFTER `build_app_state`: unlike the early sender, the turn needs
84/// `AppState` (stores, identity, broker, container manager) and is async.
85pub fn install_agent_turn_delivery(state: &AppState) {
86    let deps = crate::server::agent_handlers::AgentTurnDeps::from_state(state);
87    state
88        .reactive_handler
89        .set_message_sender(Arc::new(move |block_id: &str, message: &str, inline: &[serde_json::Value], from: &backend::message_origin::MessageOrigin, expires_at_ms: Option<i64>| {
90            // Which controller kinds take a structured message and which need a turn
91            // started is `route_agent_message`, shared with the Swarm broadcast so
92            // the two cannot drift.
93            // Inline blocks reach a running persistent Claude only; a turn
94            // started below gets the text, whose list still names every file.
95            let is_subprocess = match route_agent_message_from(block_id, message, None, from.clone(), inline, expires_at_ms)? {
96                AgentRoute::Sent(outcome) => return Ok(outcome),
97                AgentRoute::StartTurn { subprocess } => subprocess,
98            };
99
100            // `MessageSender` is synchronous but starting a turn is not, so this
101            // waits for the turn to START and reports what actually happened.
102            //
103            // It must NOT spawn-and-return-`Ok(true)` optimistically (codex P1 on
104            // PR #2930). `success` is not advisory: `cloud_subscriber` treats a
105            // successful delivery as final and releases the claim back to pending
106            // for retry ONLY when `!delivery.success`
107            // (`muxbus/cloud_subscriber.rs`). Reporting success before the
108            // fallible work ran would therefore turn every transient failure —
109            // stale block meta, an oauth spawn-gate refusal, Docker down,
110            // `ensure_running` failing — into a WAN message that is marked
111            // delivered, never retried, and permanently lost. An honest `Err` here
112            // is what lets that message come back.
113            //
114            // `block_in_place` yields this worker thread back to the runtime for
115            // the duration, so other tasks keep running. The cost is real and
116            // worth naming: `inject_message_inner` calls this while holding the
117            // reactive `Handler` mutex, so a slow start (first-time container
118            // image pull is the pathological case — everything else is a block
119            // read plus an already-running `docker exec`) serializes other
120            // injections behind it. Bounded stalling beats silent loss.
121            //
122            // `run_agent_turn` returns once the turn has been STARTED, not once
123            // the agent has answered, so this is not waiting on model latency.
124            //
125            // `TurnRegistration::Skip` is LOAD-BEARING, not a tidy-up. We are
126            // running under that same non-reentrant `Mutex<Handler>`, so the
127            // registration tail's `get_global_handler().register_agent(...)`
128            // would try to re-lock a mutex this very thread already holds and
129            // wedge the reactive handler process-wide (reagent P0 on PR #2930).
130            // It is also simply redundant here: this block was resolved BY a
131            // `resolve_target` lookup in that handler's registry, so the agent
132            // is registered by construction. Do not "simplify" this to Register.
133            let Ok(handle) = tokio::runtime::Handle::try_current() else {
134                return Err(
135                    "no tokio runtime available to start an agent turn".to_string(),
136                );
137            };
138            // `block_in_place` panics on a current-thread runtime. Production is
139            // multi-thread (`#[tokio::main]`); refusing loudly on the other flavor
140            // is correct, since the alternative is the optimistic lie above.
141            if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::CurrentThread {
142                return Err(
143                    "cannot start an agent turn from a current-thread runtime"
144                        .to_string(),
145                );
146            }
147            // One turn at a time: a message sent mid-turn queues, and the answer says so.
148            let queued_behind_turn = turn_in_flight(block_id);
149            let deps = deps.clone();
150            let block_id_owned = block_id.to_string();
151            let message = message.to_string();
152            let from = from.clone();
153            tracing::info!(
154                block_id = %block_id_owned,
155                kind = if is_subprocess { "subprocess" } else { "persistent (not yet spawned)" },
156                "reactive delivery: starting agent turn (no PTY fallback)"
157            );
158            let started = tokio::task::block_in_place(|| {
159                handle.block_on(crate::server::agent_handlers::run_agent_turn(
160                    &deps,
161                    block_id_owned.clone(),
162                    message,
163                    None,
164                    crate::server::agent_handlers::TurnRegistration::Skip,
165                    // Reactive delivery: a jekt, cron, nudge, loop, or AgentMux's own note.
166                    from,
167                    Vec::new(),
168                ))
169            });
170            match started {
171                Ok(()) if queued_behind_turn => Ok(reactive::SenderDelivery::Deferred),
172                Ok(()) => Ok(reactive::SenderDelivery::Delivered),
173                Err(e) => {
174                    tracing::error!(
175                        block_id = %block_id_owned,
176                        error = %e,
177                        "reactive delivery: agent turn failed to start"
178                    );
179                    Err(e)
180                }
181            }
182        }));
183}
184
185/// Wires `blockcontroller::close_on_exit` (see that function's own doc
186/// comment) up to the real close action, now that `AppState` exists.
187/// Mirrors `install_agent_turn_delivery` just above — same "backend code
188/// needs a capability only available once `AppState` is built" shape,
189/// solved the same way (a process-wide callback set once at boot).
190///
191/// The callback itself is deliberately synchronous (`Fn(String, String)`,
192/// not `async fn`) — `shell/lifecycle.rs`'s wait/cleanup task calls it from
193/// a plain (non-async) decision point after its own cleanup, and trait
194/// objects can't hold an `async fn` without extra boxing machinery this
195/// doesn't need. `tokio::spawn` here is what actually runs the (necessarily
196/// async) `sagas::delete_block::run` call; the callback returns
197/// immediately, fire-and-forget, matching `close_on_exit`'s own contract.
198///
199/// See `docs/specs/SPEC_TERM_EXIT_RESPAWN_LOOP_2026_09_15.md` §10 for why
200/// this exists: a shell pane's controller has no code path today that
201/// closes it when the shell process exits, which (combined with §7-9's
202/// fix for the OTHER half of that bug) leaves an exited pane sitting inert
203/// — technically correct, but indistinguishable from "hung" to a user.
204pub fn install_close_on_exit_handler(state: &AppState) {
205    let state = state.clone();
206    backend::blockcontroller::set_close_on_exit_handler(Arc::new(move |tab_id: String, block_id: String| {
207        let state = state.clone();
208        tokio::spawn(async move {
209            // An agent's process ending makes it stopped; its block stays (always-available agents).
210            if crate::sagas::park_agents::keeps_block(&state, &block_id) {
211                return;
212            }
213            if let Err(e) = crate::sagas::delete_block::run(&state, tab_id.clone(), block_id.clone()).await {
214                // Best-effort, same posture as every other close-on-exit
215                // failure mode: the shell already exited and its PTY is
216                // already gone either way, so there is nothing left to roll
217                // back — a failed close just leaves the pane sitting inert,
218                // the same as if close-on-exit weren't enabled for it at
219                // all, not a lost or corrupted state.
220                tracing::warn!(
221                    tab_id = %tab_id,
222                    block_id = %block_id,
223                    error = %e,
224                    "close-on-exit: delete_block saga failed"
225                );
226            }
227        });
228    }));
229}
230
231#[cfg(test)]
232mod route_agent_message_tests {
233    use super::*;
234    use backend::blockcontroller::{delete_controller, register_controller};
235
236    #[test]
237    fn a_block_with_no_controller_is_an_error() {
238        let Err(e) = route_agent_message("route-test-no-such-block", "hi") else {
239            panic!("an unregistered block has nowhere to go");
240        };
241        assert!(e.contains("no controller for block"), "{e}");
242    }
243
244    #[test]
245    fn a_subprocess_agent_gets_a_turn_not_keystrokes() {
246        let block_id = "route-test-subprocess";
247        register_controller(
248            block_id,
249            Arc::new(backend::blockcontroller::subprocess::SubprocessController::new(
250                "tab-route".to_string(),
251                block_id.to_string(),
252                None,
253                None,
254                None,
255                None,
256                None,
257                Arc::from("test-boot"),
258            )),
259        );
260        assert!(matches!(
261            route_agent_message(block_id, "hi"),
262            Ok(AgentRoute::StartTurn { subprocess: true })
263        ));
264        delete_controller(block_id);
265    }
266
267    #[test]
268    fn a_delivered_message_ends_the_hidden_reinjection_window() {
269        let block_id = "route-test-window";
270        register_controller(
271            block_id,
272            Arc::new(backend::blockcontroller::subprocess::SubprocessController::new(
273                "tab-route".to_string(),
274                block_id.to_string(),
275                None,
276                None,
277                None,
278                None,
279                None,
280                Arc::from("test-boot"),
281            )),
282        );
283        crate::ambient::digest::set_hidden_reinjection_active(block_id, true);
284        let _ = route_agent_message(block_id, "hi");
285        assert!(!crate::ambient::digest::is_hidden_reinjection_active(block_id));
286        delete_controller(block_id);
287    }
288
289    #[test]
290    fn an_app_server_agent_is_routed_to_its_own_channel_never_to_a_turn_or_keystrokes() {
291        let block_id = "route-test-app-server";
292        register_controller(
293            block_id,
294            Arc::new(backend::blockcontroller::app_server_controller::AppServerController::new(
295                block_id.to_string(),
296                None,
297                None,
298                None,
299                None,
300            )),
301        );
302        // No process yet, so its own `send_message` refuses: reaching that refusal
303        // is the proof the structured route was taken (not StartTurn, not Pty).
304        let Err(e) = route_agent_message(block_id, "hi") else {
305            panic!("an App Server controller with no process cannot take a message");
306        };
307        assert!(e.contains("not initialized"), "{e}");
308        delete_controller(block_id);
309    }
310
311    /// A message for an ACP agent whose process has exited is a turn to
312    /// start (which starts the agent again), not a refusal that leaves the
313    /// message stashed with nothing to run it.
314    #[test]
315    fn a_stopped_acp_agent_is_routed_to_a_turn_that_restarts_it() {
316        let block_id = "route-test-acp-stopped";
317        register_controller(
318            block_id,
319            Arc::new(backend::blockcontroller::acp::AcpController::new(
320                "tab-route".to_string(),
321                block_id.to_string(),
322                None,
323                None,
324                None,
325                None,
326            )),
327        );
328        assert!(matches!(
329            route_agent_message(block_id, "hi"),
330            Ok(AgentRoute::StartTurn { subprocess: false })
331        ));
332        delete_controller(block_id);
333    }
334}