Skip to main content

agentmux_srv_core/backend/
agent_status.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One status for an agent and one decision function for everything that wants to reach it
5//! (`docs/specs/SPEC_AGENT_AVAILABILITY_EVERY_PATH_ONE_DECISION_2026_10_31.md` ยง4). The status adds
6//! three facts to [`Availability`]: whether the agent has a pane, whether it is wanted running, and
7//! whether its model API answers. [`decide`] turns a status and an [`Intent`] into one [`Decision`].
8//!
9//! A message is still ruled by [`verdict`] (the contract is that `Intent::Message` answers exactly as
10//! it does). The other intents say, in one table, what the path that asks them does now; a path moves
11//! onto this function in its own change, and the two behaviour changes the spec lists (held input for
12//! a limited or signed-out parked agent, a turn-starting message while the API is offline) are marked
13//! where they will land. Nothing here reads a store, a controller or the clock.
14
15use super::agent_availability::{verdict, Availability, Verdict, WaitReason};
16
17/// Whether the agent has a pane to show.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Pane {
20    /// Its block is in a tab of a workspace an open window shows.
21    Shown,
22    /// Its block is in a tab, but no open window shows that tab's workspace: the process runs and nothing
23    /// on screen is its pane, until a window opens that workspace.
24    NotInWindow,
25    /// Its block is in no tab (`agent:parked`): the process runs, no pane shows it.
26    Parked,
27    /// No block at all: defined, never opened.
28    None,
29}
30
31impl Pane {
32    /// The wire name, as the availability route and `Agents list` give it.
33    pub fn as_str(self) -> &'static str {
34        match self {
35            Pane::Shown => "shown",
36            Pane::NotInWindow => "not_in_window",
37            Pane::Parked => "parked",
38            Pane::None => "none",
39        }
40    }
41}
42
43/// What the agent's own block says it should be doing (`agent:desired`).
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Wanted {
46    Running,
47    Stopped,
48    /// The block records nothing (or nothing we know).
49    Unset,
50}
51
52impl Wanted {
53    pub fn as_str(self) -> &'static str {
54        match self {
55            Wanted::Running => "running",
56            Wanted::Stopped => "stopped",
57            Wanted::Unset => "unset",
58        }
59    }
60}
61
62/// Whether the agent's model API answers.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum Reach {
65    Online,
66    Degraded,
67    Offline,
68    /// Tracked and not checked yet, for `for_ms` so far.
69    Unchecked { for_ms: u64 },
70    /// Not a model API srv tracks: it never holds anything.
71    NotTracked,
72}
73
74impl Reach {
75    pub fn as_str(self) -> &'static str {
76        match self {
77            Reach::Online => "online",
78            Reach::Degraded => "degraded",
79            Reach::Offline => "offline",
80            Reach::Unchecked { .. } => "unchecked",
81            Reach::NotTracked => "not_tracked",
82        }
83    }
84}
85
86/// How long a model API may stay "not checked yet" before it no longer holds input: the pane's rule.
87pub const UNCHECKED_HOLD_MS: u64 = 20_000;
88
89impl Reach {
90    /// Whether text the user typed may go to the agent now: not while `Offline`, and not while "not
91    /// checked yet" for less than [`UNCHECKED_HOLD_MS`].
92    pub fn lets_input_go(self) -> bool {
93        match self {
94            Reach::Online | Reach::Degraded | Reach::NotTracked => true,
95            Reach::Offline => false,
96            Reach::Unchecked { for_ms } => for_ms > UNCHECKED_HOLD_MS,
97        }
98    }
99}
100
101/// Everything a path needs to know about an agent before it sends something to it.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub struct AgentStatus {
104    pub availability: Availability,
105    pub pane: Pane,
106    pub wanted: Wanted,
107    pub api: Reach,
108    /// A controller holds the agent's process (or is about to start it): something can be sent to it.
109    pub controller: bool,
110}
111
112/// What a path wants to do with the agent.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum Intent {
115    /// A jekt. `urgent`, `routine` and `cold_after_ms` are [`verdict`]'s arguments.
116    Message { urgent: bool, routine: bool, cold_after_ms: Option<u64> },
117    /// An `[AgentMux]` note or a bulletin: it never starts a turn.
118    Note,
119    /// The text the user typed for a pane with no view, which srv sends.
120    HeldInput,
121    /// A message or cron that may start a stopped agent; `allowed` is the setting and the sender's right.
122    Start { allowed: bool },
123    /// Whether a holder's claim on a task stays with it. `aimed_at_agent`: the task names an agent.
124    Lease { aimed_at_agent: bool, now_ms: u64 },
125}
126
127/// What to do.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum Decision {
130    Deliver,
131    /// Keep it, or refuse it where it can't be kept (the caller's rule), until `until_ms` when known.
132    Wait { reason: WaitReason, until_ms: Option<u64> },
133    /// Keep it until the model API answers.
134    WaitApi,
135    /// It rides the next message and never starts a turn.
136    Attach,
137    /// Start the agent, then deliver.
138    Start,
139    /// Nobody to give it to.
140    Drop,
141    /// The holder keeps its claim.
142    Renew,
143    /// The claim lapses so someone else can take the task.
144    Lapse,
145}
146
147/// How long a holder must have been out of quota or signed out before its lease on a task open to
148/// anyone stops being renewed (R5 of `SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md`).
149pub const UNAVAILABLE_LEASE_AFTER_MS: u64 = 30 * 60 * 1000;
150/// And how far off its reset must be (or unknown): a limit that lifts within the hour is waited out.
151pub const RESET_FAR_MS: u64 = 60 * 60 * 1000;
152
153/// The decision for `intent` to the agent in `status`. `hands_over_work` is asked only for a routine
154/// message to a cold session ([`verdict`]'s argument); other intents never call it.
155pub fn decide(status: &AgentStatus, intent: Intent, hands_over_work: impl FnOnce() -> bool) -> Decision {
156    match intent {
157        Intent::Message { urgent, routine, cold_after_ms } => match verdict(&status.availability, urgent, routine, cold_after_ms, hands_over_work) {
158            // A message to an agent between turns starts one, and the turn fails while its model API is
159            // offline: it waits, as for a limited agent (spec D2). One that joins a turn in flight, or
160            // goes to an agent nothing tracks, is unchanged; an API merely "not checked yet" holds nothing.
161            Verdict::Deliver if matches!(status.availability, Availability::Idle { .. }) && status.api == Reach::Offline => {
162                Decision::Wait { reason: WaitReason::ApiOffline, until_ms: None }
163            }
164            Verdict::Deliver => Decision::Deliver,
165            Verdict::Wait { reason, until_ms } => Decision::Wait { reason, until_ms },
166        },
167        // Right for every agent that has a pane to ride on; an agent with no process takes it only when it
168        // is wanted running (the pane that starts shows it).
169        Intent::Note => match (status.availability, status.wanted) {
170            (Availability::NotRunning { .. }, Wanted::Running) => Decision::Attach,
171            (Availability::NotRunning { .. }, _) => Decision::Drop,
172            _ => Decision::Attach,
173        },
174        // The text waits for a process, for a limit that has a known reset to pass, for a sign-in, and for
175        // the API (spec D1). A limit with no known reset does not hold it: like a message, it is tried and
176        // finds out. That the agent is between turns is the caller's check.
177        Intent::HeldInput => match status.availability {
178            // A process that exited under a controller is restarted by the text (the persistent
179            // controller spawns on input); with no controller there is nothing to send it to.
180            Availability::NotRunning { .. } if !status.controller => Decision::Wait { reason: WaitReason::NotRunning, until_ms: None },
181            Availability::Limited { resets_at_ms: Some(reset), .. } => Decision::Wait { reason: WaitReason::UsageLimit, until_ms: Some(reset) },
182            Availability::SignedOut { .. } => Decision::Wait { reason: WaitReason::NeedsLogin, until_ms: None },
183            _ if !status.api.lets_input_go() => Decision::WaitApi,
184            _ => Decision::Deliver,
185        },
186        Intent::Start { allowed } => match status.availability {
187            Availability::NotRunning { .. } if allowed => Decision::Start,
188            Availability::NotRunning { .. } => Decision::Wait { reason: WaitReason::NotRunning, until_ms: None },
189            _ => Decision::Deliver,
190        },
191        Intent::Lease { aimed_at_agent, now_ms } => {
192            let (since_ms, resets_at_ms) = match status.availability {
193                Availability::Limited { resets_at_ms, since_ms } => (since_ms, resets_at_ms),
194                Availability::SignedOut { since_ms } => (since_ms, None),
195                _ => return Decision::Renew,
196            };
197            let for_long = now_ms.saturating_sub(since_ms) >= UNAVAILABLE_LEASE_AFTER_MS;
198            let reset_far = resets_at_ms.is_none_or(|r| r > now_ms + RESET_FAR_MS);
199            if !aimed_at_agent && for_long && reset_far {
200                Decision::Lapse
201            } else {
202                Decision::Renew
203            }
204        }
205    }
206}
207
208#[cfg(test)]
209#[path = "agent_status_tests.rs"]
210mod tests;
211
212#[cfg(test)]
213#[path = "agent_state_readers_tests.rs"]
214mod readers_guard;