Skip to main content

agentmux_srv/server/account_episodes/
machine.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The account episodes, as a pure state machine: a scan's blocked panes in,
5//! what to publish, raise and tell out
6//! (`docs/specs/SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md` §6.1, §6.2). No clock,
7//! no store: `mod.rs` scans and applies.
8
9use std::collections::{BTreeMap, HashMap, HashSet};
10
11use crate::backend::agent_state::AgentState;
12
13/// The provider's name for a session (five-hour) limit window. A session limit
14/// raises no toast (spec §13, decision 1).
15pub(crate) const SESSION_WINDOW: &str = "five_hour";
16
17/// How long a closed episode is remembered: the same account failing again
18/// with the same reset within it reopens the episode as it was (already
19/// toasted, its requesters already told) rather than notifying again.
20pub(crate) const REOPEN_GRACE_MS: u64 = 5 * 60_000;
21
22/// A pane that is `limited` or `signed_out` on an account, as one scan found it.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub(crate) struct BlockedPane {
25    pub block_id: String,
26    /// Its definition id (`agentId`).
27    pub agent_id: String,
28    pub agent_name: String,
29    pub account_id: String,
30    /// Canonical provider.
31    pub provider: String,
32    pub state: AgentState,
33    pub resets_at_ms: Option<u64>,
34    pub limit_window: Option<String>,
35    /// The stored failure's class, reset and title: the same signature is the
36    /// same failure.
37    pub signature: String,
38}
39
40impl BlockedPane {
41    /// A sign-in problem, or a usage limit that isn't a session limit (weekly,
42    /// monthly, or no window known).
43    fn wants_toast(&self) -> bool {
44        self.state == AgentState::SignedOut || self.limit_window.as_deref() != Some(SESSION_WINDOW)
45    }
46}
47
48/// Every pane blocked on one account, from the first until none is.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub(crate) struct Episode {
51    pub account_id: String,
52    pub provider: String,
53    pub opened_at_ms: u64,
54    /// Sorted by agent name, then block.
55    pub panes: Vec<BlockedPane>,
56    /// Its toast was raised (or is owed no more).
57    pub toasted: bool,
58    /// Panes whose leaders were told, or that needed no telling.
59    pub announced: HashSet<String>,
60    /// Requesters already sent this episode's note (lowercase).
61    pub told: HashSet<String>,
62}
63
64impl Episode {
65    /// `signed_out` when any pane on the account is: the operator has to act.
66    pub fn state(&self) -> AgentState {
67        if self.panes.iter().any(|p| p.state == AgentState::SignedOut) {
68            AgentState::SignedOut
69        } else {
70            AgentState::Limited
71        }
72    }
73
74    /// When the last of its limited panes' limits lifts; `None` while signed
75    /// out, or when no reset is known.
76    pub fn resets_at_ms(&self) -> Option<u64> {
77        if self.state() == AgentState::SignedOut {
78            return None;
79        }
80        self.panes.iter().filter_map(|p| p.resets_at_ms).max()
81    }
82
83    /// The window of the pane whose limit lifts last (or any pane's).
84    pub fn limit_window(&self) -> Option<String> {
85        let latest = self.resets_at_ms();
86        self.panes
87            .iter()
88            .find(|p| latest.is_some() && p.resets_at_ms == latest)
89            .or_else(|| self.panes.iter().find(|p| p.limit_window.is_some()))
90            .and_then(|p| p.limit_window.clone())
91    }
92}
93
94/// What a scan changed.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub(crate) enum Effect {
97    /// Opened, or its panes, state or reset changed: publish it.
98    Changed(Episode),
99    /// Raise its one toast.
100    Toast(Episode),
101    /// Tell the leaders of these newly blocked panes.
102    Announce { episode: Episode, panes: Vec<BlockedPane> },
103    /// No pane is blocked on the account any more: publish `ok`, take the toast down.
104    Closed { account_id: String, provider: String },
105}
106
107/// The open episodes, by account.
108#[derive(Debug, Default)]
109pub(crate) struct Episodes {
110    open: BTreeMap<String, Episode>,
111    /// Failures stored before srv started (block → signature). Finding one is
112    /// the episode rebuilt, not news: no toast and no notes for it.
113    baseline: HashMap<String, String>,
114    /// Episodes closed in the last [`REOPEN_GRACE_MS`], by account, with when.
115    closed: HashMap<String, (Episode, u64)>,
116}
117
118impl Episodes {
119    pub fn new(baseline: HashMap<String, String>) -> Self {
120        Episodes { open: BTreeMap::new(), baseline, closed: HashMap::new() }
121    }
122
123    pub fn list(&self) -> impl Iterator<Item = &Episode> {
124        self.open.values()
125    }
126
127    pub fn get(&self, account_id: &str) -> Option<&Episode> {
128        self.open.get(account_id)
129    }
130
131    /// Of `requesters`, the ones `account_id`'s open episode hasn't sent its
132    /// note to yet; they count as told from now on (spec §6.2: one note per
133    /// requester per episode).
134    pub fn first_notes(&mut self, account_id: &str, requesters: impl IntoIterator<Item = String>) -> Vec<String> {
135        let Some(ep) = self.open.get_mut(account_id) else { return Vec::new() };
136        requesters.into_iter().filter(|r| ep.told.insert(r.to_lowercase())).collect()
137    }
138
139    /// Take one scan's blocked panes (every account's) at `now_ms`.
140    pub fn update(&mut self, panes: Vec<BlockedPane>, now_ms: u64) -> Vec<Effect> {
141        let mut by_account: BTreeMap<String, Vec<BlockedPane>> = BTreeMap::new();
142        for p in panes {
143            by_account.entry(p.account_id.clone()).or_default().push(p);
144        }
145        let mut out = Vec::new();
146        self.closed.retain(|_, (_, at)| now_ms.saturating_sub(*at) <= REOPEN_GRACE_MS);
147        let closed: Vec<String> = self.open.keys().filter(|a| !by_account.contains_key(*a)).cloned().collect();
148        for account_id in closed {
149            if let Some(ep) = self.open.remove(&account_id) {
150                out.push(Effect::Closed { account_id: account_id.clone(), provider: ep.provider.clone() });
151                self.closed.insert(account_id, (ep, now_ms));
152            }
153        }
154        for (account_id, mut panes) in by_account {
155            panes.sort_by(|a, b| a.agent_name.to_lowercase().cmp(&b.agent_name.to_lowercase()).then(a.block_id.cmp(&b.block_id)));
156            panes.dedup_by(|a, b| a.block_id == b.block_id);
157            if !self.open.contains_key(&account_id) {
158                let fresh = Episode {
159                    account_id: account_id.clone(),
160                    provider: panes[0].provider.clone(),
161                    opened_at_ms: now_ms,
162                    panes: panes.clone(),
163                    toasted: false,
164                    announced: HashSet::new(),
165                    told: HashSet::new(),
166                };
167                // The same outage back within the grace: what was told stands.
168                let reopened = match self.closed.remove(&account_id) {
169                    Some((old, _)) if old.resets_at_ms() == fresh.resets_at_ms() && old.state() == fresh.state() => {
170                        Episode { panes: Vec::new(), ..old }
171                    }
172                    _ => Episode { panes: Vec::new(), ..fresh },
173                };
174                self.open.insert(account_id.clone(), reopened);
175            }
176            let ep = self.open.get_mut(&account_id).expect("just inserted");
177            // A pane that left and came back is news again.
178            ep.announced.retain(|b| panes.iter().any(|p| &p.block_id == b));
179            let changed = ep.panes != panes;
180            if changed {
181                ep.panes = panes;
182            }
183            let fresh: Vec<BlockedPane> = ep.panes.iter().filter(|p| !ep.announced.contains(&p.block_id)).cloned().collect();
184            let mut news = Vec::new();
185            for p in fresh {
186                ep.announced.insert(p.block_id.clone());
187                let rebuilt = self.baseline.get(&p.block_id) == Some(&p.signature);
188                self.baseline.remove(&p.block_id);
189                if !rebuilt {
190                    news.push(p);
191                }
192            }
193            if changed {
194                out.push(Effect::Changed(ep.clone()));
195            }
196            if !ep.toasted && news.iter().any(BlockedPane::wants_toast) {
197                ep.toasted = true;
198                out.push(Effect::Toast(ep.clone()));
199            }
200            if !news.is_empty() {
201                out.push(Effect::Announce { episode: ep.clone(), panes: news });
202            }
203        }
204        out
205    }
206}
207
208/// "until Sun 7:00 PM", in this machine's time zone.
209pub(crate) fn until_label(resets_at_ms: u64) -> Option<String> {
210    let t = chrono::DateTime::from_timestamp_millis(resets_at_ms as i64)?;
211    Some(format!("until {}", t.with_timezone(&chrono::Local).format("%a %-I:%M %p")))
212}
213
214/// The toast's body: how many agents, and why. Never the account (spec §6.2).
215pub(crate) fn toast_body(ep: &Episode) -> String {
216    let n = ep.panes.len();
217    let agents = if n == 1 { "1 agent".to_string() } else { format!("{n} agents") };
218    match ep.state() {
219        AgentState::SignedOut => format!("{agents} {} you to sign in again", if n == 1 { "needs" } else { "need" }),
220        _ => {
221            let verb = if n == 1 { "is" } else { "are" };
222            match ep.resets_at_ms().and_then(until_label) {
223                Some(until) => format!("{agents} {verb} out of quota {until}"),
224                None => format!("{agents} {verb} out of quota"),
225            }
226        }
227    }
228}
229
230/// "#163", "#163 and work#2", "#1, #2 and #3".
231fn task_list(refs: &[String]) -> String {
232    match refs {
233        [] => String::new(),
234        [one] => one.clone(),
235        [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
236    }
237}
238
239/// The body of the note a task's requester gets about its blocked agents
240/// (spec §6.2): "Naki-2 is out of quota until Sun 7:00 PM and holds #163. …".
241/// `mod.rs` quotes it into an `[AgentMux]` note.
242pub(crate) fn leader_note(items: &[(&BlockedPane, &[String])]) -> String {
243    let clauses: Vec<String> = items
244        .iter()
245        .map(|(pane, refs)| {
246            let why = match pane.state {
247                AgentState::SignedOut => "needs the user to sign in again".to_string(),
248                _ => match pane.resets_at_ms.and_then(until_label) {
249                    Some(until) => format!("is out of quota {until}"),
250                    None => "is out of quota".to_string(),
251                },
252            };
253            format!("{} {why} and holds {}", pane.agent_name, task_list(refs))
254        })
255        .collect();
256    // Until step 2c holds messages to an unavailable agent (#1849), one sent
257    // to it fails; when that lands, say they are held instead.
258    let signed_out = items.iter().filter(|(p, _)| p.state == AgentState::SignedOut).count();
259    let after = match (items.len(), signed_out) {
260        (1, 0) => "Until then, a message to it starts a turn that fails; move it to another account or wait for the reset.",
261        (1, _) => "Until it is signed in again, a message to it starts a turn that fails; sign it in again or move it to another account.",
262        (_, 0) => "Until then, a message to one of them starts a turn that fails; move them to another account or wait for the reset.",
263        (n, s) if n == s => {
264            "Until they are signed in again, a message to one of them starts a turn that fails; sign them in again or move them to another account."
265        }
266        _ => "Until then, a message to one of them starts a turn that fails; sign them in again, move them to another account or wait for the reset.",
267    };
268    format!("{}. {after}", clauses.join("; "))
269}
270
271#[cfg(test)]
272#[path = "machine_tests.rs"]
273mod tests;