agentmux_srv_core/backend/agent_route.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where a message for an agent block goes. Moved down from `bootstrap/delivery.rs` unchanged: it reaches only
5//! the controllers and the reactive layer, so the supervisor watcher (core) and the Swarm broadcast (server)
6//! both route through it, and `bootstrap` re-exports it under the old path.
7
8use crate::backend;
9use crate::backend::reactive;
10
11/// Where a message for an agent block goes.
12pub enum AgentRoute {
13 /// Taken on the controller's own channel — persistent stdin, ACP
14 /// `session/prompt`, App Server — either now (`Delivered`) or queued for when
15 /// the process can take it (`Deferred`). `Pty`: the controller is PTY-based,
16 /// and the caller decides what that means for it.
17 Sent(reactive::SenderDelivery),
18 /// No structured channel takes it now: the caller starts a turn
19 /// (`run_agent_turn`). `subprocess` is true for a `SubprocessController`,
20 /// false for a persistent controller that is registered but not yet spawned.
21 StartTurn { subprocess: bool },
22}
23
24/// The routing half of the reactive sender (`bootstrap/delivery.rs`), shared with the Swarm broadcast
25/// (`server::app_api::fleet`) so a broadcast reaches ACP, App Server, running
26/// persistent and not-yet-spawned agents exactly as an inter-agent message does.
27///
28/// Persistent + ACP + App Server keep their structured delivery; genuine PTY
29/// controllers report `Pty`; a `SubprocessController` has no PTY and rejects raw
30/// input, so it gets a turn instead (docs/reports/
31/// REPORT_JEKT_DELIVERY_DROPS_SUBPROCESS_AGENTS_2026_09_02.md). An `Err` is a
32/// structured controller that failed to take the message; it must not be retried
33/// as keystrokes.
34///
35/// Saying who the input is from: the Swarm broadcast
36/// labels its delivery to a running persistent agent as the user's
37/// (`deliver_agent_message_from`). `None` is the plain text route the tests use.
38pub fn route_agent_message_from(
39 block_id: &str,
40 message: &str,
41 origin: Option<backend::blockcontroller::health::TurnInput>,
42 from: backend::message_origin::MessageOrigin,
43 inline: &[serde_json::Value],
44 expires_at_ms: Option<i64>,
45) -> Result<AgentRoute, String> {
46 let Some(ctrl) = backend::blockcontroller::get_controller(block_id) else {
47 return Err(format!("{} {block_id}", reactive::controller_wait::NO_CONTROLLER));
48 };
49 // A jekt, cron or broadcast is a real turn: it ends the hidden-reinjection
50 // window as a person typing does, so ambient reads resume for an agent
51 // that is only ever driven by messages.
52 crate::ambient::digest::set_hidden_reinjection_active(block_id, false);
53 let is_subprocess = ctrl
54 .as_any()
55 .downcast_ref::<backend::blockcontroller::subprocess::SubprocessController>()
56 .is_some();
57 if is_subprocess {
58 return Ok(AgentRoute::StartTurn { subprocess: true });
59 }
60 match backend::blockcontroller::deliver_agent_message_from(block_id, message, origin, from, inline, expires_at_ms) {
61 Ok(backend::blockcontroller::AgentDelivery::Structured) => {
62 Ok(AgentRoute::Sent(reactive::SenderDelivery::Delivered))
63 }
64 Ok(backend::blockcontroller::AgentDelivery::StructuredDeferred) => {
65 Ok(AgentRoute::Sent(reactive::SenderDelivery::Deferred))
66 }
67 Ok(backend::blockcontroller::AgentDelivery::Pty) => Ok(AgentRoute::Sent(reactive::SenderDelivery::Pty)),
68 Err(e) => {
69 // A persistent controller that is REGISTERED BUT NOT YET SPAWNED can't
70 // be steered — `deliver_agent_message` writes to a live stdin and there
71 // isn't one — but it can be STARTED. Controllers register lazily, so
72 // after any srv restart every persistent agent sits in this state until
73 // something is sent to it; without this, first contact fails with
74 // "persistent process not running"
75 // (docs/reports/REPORT_JEKT_DELIVERY_DROPS_UNSPAWNED_PERSISTENT_AGENTS_2026_09_03.md).
76 //
77 // Narrow on purpose: `needs_spawn()` is false while a spawn is already
78 // in flight (that surfaces as the retryable "still starting up"), and
79 // false for a live process whose delivery failed for another reason;
80 // both keep returning the original error rather than start a second
81 // turn.
82 // An ACP or MSP agent whose process exited likewise: the turn
83 // path starts it again (`SessionAgent::ensure_started`).
84 let recoverable = ctrl
85 .as_any()
86 .downcast_ref::<backend::blockcontroller::persistent::PersistentSubprocessController>()
87 .is_some_and(|p| p.needs_spawn())
88 || backend::blockcontroller::session_agent::session_agent(ctrl.as_ref())
89 .is_some_and(|a| !a.is_running());
90 if !recoverable {
91 return Err(e);
92 }
93 // Nothing was persisted or written, so falling through cannot
94 // double-deliver.
95 tracing::info!(
96 block_id = %block_id,
97 error = %e,
98 "reactive delivery: persistent controller not yet spawned — starting a turn instead"
99 );
100 Ok(AgentRoute::StartTurn { subprocess: false })
101 }
102 }
103}