Skip to main content

agentmux_srv_core/backend/
agent_availability.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Whether an agent can take a message now: the fact ([`Availability`]) and the
5//! rule that turns it into a decision for one message ([`verdict`]), in one
6//! place (`docs/specs/SPEC_AGENT_AVAILABILITY_ONE_STATE_2026_10_26.md` ยง3).
7//! The fact comes from what `agent_state` already reads; nothing here reads a
8//! controller or a store. The jekt path (`server/jekt_hold.rs`, `jekt_cold.rs`)
9//! applies the verdict.
10
11use super::agent_state::{AgentState, Unavailable};
12
13/// What can be said about an agent on this instance for a message to it.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Availability {
16    /// Defined here, no live process: never started, ended, or its pane closed.
17    NotRunning { exited_with_error: bool },
18    /// Alive, no turn in flight. `quiet_for_ms`: since its last output, when the controller knows it.
19    Idle { quiet_for_ms: Option<u64> },
20    /// A turn is in flight (working, or waiting on a question).
21    Running { waiting_on_user: bool },
22    /// Out of quota; `resets_at_ms` when the provider said when it lifts.
23    Limited { resets_at_ms: Option<u64>, since_ms: u64 },
24    SignedOut { since_ms: u64 },
25    /// Nothing tracks its turns (a terminal pane): the tiers below decide.
26    Unknown,
27}
28
29/// Why a message waits. The wire strings are the existing `held_reason` values.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum WaitReason {
32    NotRunning,
33    NeedsLogin,
34    UsageLimit,
35    /// The session has gone cold (`cold_hold`); named `idle` on the wire.
36    Cold,
37    /// Quota mode is tight and no turn is in flight (`quota_mode`).
38    Quota,
39    /// The agent is between turns and its model API is offline: a message would start a turn that fails.
40    ApiOffline,
41}
42
43impl WaitReason {
44    pub fn as_str(self) -> &'static str {
45        match self {
46            Self::NotRunning => "not_running",
47            Self::NeedsLogin => "needs_login",
48            Self::UsageLimit => "usage_limit",
49            Self::Cold => "idle",
50            Self::Quota => "quota",
51            Self::ApiOffline => "api_offline",
52        }
53    }
54}
55
56impl WaitReason {
57    /// What ends the wait, as the answer names it (`retry_when`): the sender decides from this,
58    /// never from the wording of the error.
59    pub fn retry_when(self) -> &'static str {
60        match self {
61            Self::NotRunning => "start",
62            Self::NeedsLogin => "sign_in",
63            Self::UsageLimit => "reset_or_account_move",
64            Self::Cold => "session_active",
65            Self::Quota => "mode_off_or_session_active",
66            Self::ApiOffline => "api_online",
67        }
68    }
69}
70
71/// What to do with one message.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Verdict {
74    Deliver,
75    /// Keep it, or refuse it where it can't be kept (the caller's rule), until `until_ms` when known.
76    Wait { reason: WaitReason, until_ms: Option<u64> },
77}
78
79impl Verdict {
80    pub fn waits(self) -> bool {
81        matches!(self, Verdict::Wait { .. })
82    }
83}
84
85/// The fact for a registered pane: its [`AgentState`], and while it is `limited` or `signed_out`
86/// the [`Unavailable`] that says why. `quiet_for_ms` is only for an idle one.
87pub fn availability(state: Option<AgentState>, unavailable: Option<&Unavailable>, quiet_for_ms: Option<u64>) -> Availability {
88    match state {
89        None => Availability::Unknown,
90        Some(AgentState::Working) => Availability::Running { waiting_on_user: false },
91        Some(AgentState::Waiting) => Availability::Running { waiting_on_user: true },
92        Some(AgentState::Idle) => Availability::Idle { quiet_for_ms },
93        Some(AgentState::Stopped) => Availability::NotRunning { exited_with_error: false },
94        Some(AgentState::Error) => Availability::NotRunning { exited_with_error: true },
95        Some(AgentState::Limited) => {
96            Availability::Limited { resets_at_ms: unavailable.and_then(|u| u.resets_at_ms), since_ms: unavailable.map_or(0, |u| u.since_ms) }
97        }
98        Some(AgentState::SignedOut) => Availability::SignedOut { since_ms: unavailable.map_or(0, |u| u.since_ms) },
99    }
100}
101
102/// The fact for an unavailable agent (`Unavailable` is only ever limited or signed out).
103pub fn of_unavailable(u: &Unavailable) -> Availability {
104    availability(Some(u.state), Some(u), None)
105}
106
107/// The decision for a message to an agent in `availability`.
108///
109/// - `urgent`: the sender asked for it now (`cold_hold::asks_to_wake`). It wakes a cold session; it
110///   does not deliver into an agent out of quota or signed out, which would only fail the turn.
111/// - `routine`: it may wait (`cold_hold::is_routine`); anything else goes to a cold session.
112/// - `cold_after_ms`: the setting's quiet time after which a session is cold; `None` turns the hold off.
113/// - `hands_over_work`: asked only for a routine message to a cold session.
114///
115/// A limited agent with no known reset is delivered to: a turn is how it finds out it can work again.
116pub fn verdict(
117    availability: &Availability,
118    urgent: bool,
119    routine: bool,
120    cold_after_ms: Option<u64>,
121    hands_over_work: impl FnOnce() -> bool,
122) -> Verdict {
123    match *availability {
124        Availability::Limited { resets_at_ms: Some(until), .. } => Verdict::Wait { reason: WaitReason::UsageLimit, until_ms: Some(until) },
125        Availability::SignedOut { .. } => Verdict::Wait { reason: WaitReason::NeedsLogin, until_ms: None },
126        Availability::NotRunning { .. } => Verdict::Wait { reason: WaitReason::NotRunning, until_ms: None },
127        Availability::Idle { quiet_for_ms: Some(quiet) } => {
128            let cold = cold_after_ms.is_some_and(|after| quiet > after);
129            if cold && routine && !urgent && !hands_over_work() {
130                Verdict::Wait { reason: WaitReason::Cold, until_ms: None }
131            } else {
132                Verdict::Deliver
133            }
134        }
135        Availability::Idle { quiet_for_ms: None } | Availability::Running { .. } | Availability::Limited { resets_at_ms: None, .. } | Availability::Unknown => {
136            Verdict::Deliver
137        }
138    }
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144    use crate::agents::failure::FailureClass;
145
146    const AFTER: u64 = 55 * 60_000;
147
148    fn unavailable(state: AgentState, resets_at_ms: Option<u64>) -> Unavailable {
149        let code = if state == AgentState::Limited { FailureClass::UsageLimit } else { FailureClass::Auth };
150        Unavailable { state, code, title: String::new(), resets_at_ms, since_ms: 7, account_id: None }
151    }
152
153    fn never() -> bool {
154        panic!("asked whether the message hands over work, but it could not matter")
155    }
156
157    #[test]
158    fn each_state_maps_to_its_fact() {
159        let lim = unavailable(AgentState::Limited, Some(9));
160        let out = unavailable(AgentState::SignedOut, None);
161        let cases = [
162            (None, None, Availability::Unknown),
163            (Some(AgentState::Working), None, Availability::Running { waiting_on_user: false }),
164            (Some(AgentState::Waiting), None, Availability::Running { waiting_on_user: true }),
165            (Some(AgentState::Idle), None, Availability::Idle { quiet_for_ms: Some(5) }),
166            (Some(AgentState::Stopped), None, Availability::NotRunning { exited_with_error: false }),
167            (Some(AgentState::Error), None, Availability::NotRunning { exited_with_error: true }),
168            (Some(AgentState::Limited), Some(&lim), Availability::Limited { resets_at_ms: Some(9), since_ms: 7 }),
169            (Some(AgentState::SignedOut), Some(&out), Availability::SignedOut { since_ms: 7 }),
170        ];
171        for (state, u, want) in cases {
172            assert_eq!(availability(state, u, Some(5)), want, "{state:?}");
173        }
174        assert_eq!(of_unavailable(&lim), Availability::Limited { resets_at_ms: Some(9), since_ms: 7 });
175    }
176
177    #[test]
178    fn the_table_of_verdicts() {
179        let wait = |reason, until_ms| Verdict::Wait { reason, until_ms };
180        let v = |a: Availability, urgent| verdict(&a, urgent, true, Some(AFTER), || false);
181        // Out of quota until a known reset, and signed out: held, even for an urgent message.
182        for urgent in [false, true] {
183            assert_eq!(v(Availability::Limited { resets_at_ms: Some(50), since_ms: 1 }, urgent), wait(WaitReason::UsageLimit, Some(50)));
184            assert_eq!(v(Availability::SignedOut { since_ms: 1 }, urgent), wait(WaitReason::NeedsLogin, None));
185            assert_eq!(v(Availability::NotRunning { exited_with_error: false }, urgent), wait(WaitReason::NotRunning, None));
186            // A limit with no reset known: delivered, a turn finds out.
187            assert_eq!(v(Availability::Limited { resets_at_ms: None, since_ms: 1 }, urgent), Verdict::Deliver);
188            assert_eq!(v(Availability::Running { waiting_on_user: true }, urgent), Verdict::Deliver);
189            assert_eq!(v(Availability::Unknown, urgent), Verdict::Deliver);
190            assert_eq!(v(Availability::Idle { quiet_for_ms: None }, urgent), Verdict::Deliver);
191            assert_eq!(v(Availability::Idle { quiet_for_ms: Some(AFTER) }, urgent), Verdict::Deliver, "quiet exactly as long as the limit is not cold");
192        }
193        let cold = Availability::Idle { quiet_for_ms: Some(AFTER + 1) };
194        assert_eq!(v(cold, false), wait(WaitReason::Cold, None));
195        assert_eq!(v(cold, true), Verdict::Deliver, "urgent wakes a cold session");
196        assert_eq!(verdict(&cold, false, true, Some(AFTER), || true), Verdict::Deliver, "a message that hands over work goes");
197        assert_eq!(verdict(&cold, false, false, Some(AFTER), never), Verdict::Deliver, "only a routine message waits");
198        assert_eq!(verdict(&cold, false, true, None, never), Verdict::Deliver, "the setting off turns the hold off");
199        assert_eq!(verdict(&Availability::Idle { quiet_for_ms: Some(5) }, false, true, Some(AFTER), never), Verdict::Deliver, "warm");
200    }
201
202    #[test]
203    fn the_wire_strings_are_the_existing_held_reasons() {
204        let all = [WaitReason::NotRunning, WaitReason::NeedsLogin, WaitReason::UsageLimit, WaitReason::Cold, WaitReason::Quota, WaitReason::ApiOffline];
205        assert_eq!(all.map(WaitReason::as_str), ["not_running", "needs_login", "usage_limit", "idle", "quota", "api_offline"]);
206        assert_eq!(
207            all.map(WaitReason::retry_when),
208            ["start", "sign_in", "reset_or_account_move", "session_active", "mode_off_or_session_active", "api_online"]
209        );
210    }
211
212    /// What `jekt_hold::holding_unavailable` filtered before it asked this module: out of quota with
213    /// a known reset, or signed out.
214    fn legacy_holds(u: &Unavailable) -> bool {
215        u.state == AgentState::SignedOut || (u.state == AgentState::Limited && u.resets_at_ms.is_some())
216    }
217
218    /// What `jekt_cold::decide` and `cold_hold::is_cold` answered before it asked this module.
219    fn legacy_cold_holds(last_output_ms: Option<i64>, now_ms: i64, after_ms: i64, urgent: bool, hands_over: bool) -> bool {
220        !urgent && crate::backend::cold_hold::is_cold(last_output_ms, now_ms, after_ms) && !hands_over
221    }
222
223    #[test]
224    fn unavailable_agents_wait_exactly_when_the_old_filter_held_them() {
225        for state in [AgentState::Limited, AgentState::SignedOut] {
226            for resets in [None, Some(100)] {
227                let u = unavailable(state, resets);
228                for urgent in [false, true] {
229                    let got = verdict(&of_unavailable(&u), urgent, true, Some(AFTER), || false).waits();
230                    assert_eq!(got, legacy_holds(&u), "{state:?} reset={resets:?} urgent={urgent}");
231                }
232            }
233        }
234    }
235
236    #[test]
237    fn a_cold_session_waits_exactly_when_the_old_decision_held_it() {
238        let now: i64 = 100_000_000;
239        for last in [None, Some(now - 1), Some(now - AFTER as i64), Some(now - AFTER as i64 - 1), Some(now - 10 * AFTER as i64)] {
240            for urgent in [false, true] {
241                for hands_over in [false, true] {
242                    let quiet = last.map(|at| (now - at) as u64);
243                    let got = verdict(&Availability::Idle { quiet_for_ms: quiet }, urgent, true, Some(AFTER), || hands_over).waits();
244                    assert_eq!(got, legacy_cold_holds(last, now, AFTER as i64, urgent, hands_over), "last={last:?} urgent={urgent} hands_over={hands_over}");
245                }
246            }
247        }
248    }
249}