Skip to main content

agentmux_srv/server/account_episodes/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One notice per account episode, and the move to another account
5//! (`docs/specs/SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md` §6).
6//!
7//! An **episode** is every agent pane that is `limited` or `signed_out` on one
8//! account (`agent_state::unavailable_of_block`, which reads the account its
9//! run launched on through `run_accounts_of_block`), from the first until none
10//! is: the reset passed, the agents moved, or they recovered. srv keeps them
11//! in memory ([`machine::Episodes`]) and rebuilds them from block meta on
12//! start; a failure stored before the start is the episode rebuilt, not news.
13//!
14//! **What follows** from an episode:
15//! - the `accountavailability` event when it opens, changes or closes (`ok`),
16//!   and `identity.account.availability` for the open ones, which the Kanban
17//!   and Swarm strips show with the move action;
18//! - one OS toast (`NotifyKind::AccountUnavailable`) for a sign-in problem or
19//!   a weekly (or unknown) limit, never for a session limit, and no per-pane
20//!   `AgentCrashed` or "finished" toast for a pane it covers ([`covers_block`]);
21//! - one `[AgentMux]` note to the agent that requested each task a newly
22//!   blocked agent holds. A worker's leader already hears from
23//!   `backend::worker_notes`.
24//!
25//! An agent that hits a usage limit moves by itself to an account with quota after its turn
26//! ([`failover`]); so do the agents of a login that expired, to a valid login of the same account
27//! first, and the one that was mid-turn carries on ([`login_expiry`]).
28//!
29//! `identity.account.move_agents` ([`moves`]) links an episode's idle agents
30//! to another signed-in account of the same provider and restarts their
31//! panes; any link change clears the failure its old account caused
32//! ([`failed_panes`], [`after_rebind`]), and a sign-in that proves an
33//! account works clears its panes' "signed out" ([`after_sign_in`]).
34
35mod accounts;
36pub mod failover;
37mod login_expiry;
38mod login_recheck;
39mod fresh;
40mod key_account;
41mod machine;
42mod moves;
43mod resume;
44mod switch;
45mod switch_error;
46
47use std::collections::HashMap;
48use std::sync::{Arc, Mutex, OnceLock};
49use std::time::Duration;
50
51use serde::{Deserialize, Serialize};
52
53use crate::agents::failure::FailureClass;
54use crate::backend::agent_state::{self, failure_of_block, run_accounts_of_block, AgentState};
55use crate::backend::eventbus::EventBus;
56use crate::backend::mps::MuxEvent;
57use crate::backend::obj::{self, Block, Tab};
58use crate::backend::rpc::engine::WshRpcEngine;
59use crate::backend::rpc_types::{NoArgsReq, COMMAND_IDENTITY_ACCOUNT_AVAILABILITY, COMMAND_IDENTITY_ACCOUNT_USAGE, COMMAND_AGENT_ACCOUNT_SWITCH, COMMAND_IDENTITY_ACCOUNT_MOVE_AGENTS, COMMAND_IDENTITY_ACCOUNT_SET_FAILOVER, COMMAND_IDENTITY_ACCOUNT_SIGNED_IN};
60use crate::backend::storage::store::Store;
61use crate::server::AppState;
62
63use machine::{BlockedPane, Effect, Episode, Episodes};
64use resume::Failed;
65
66pub use crate::backend::account_availability::{
67    AccountAvailabilityEvent, AccountEpisodeAgent, AccountEpisodeTask,
68};
69
70/// How often the episodes are rebuilt without a prompt: a reset passing
71/// changes them with no event.
72const TICK: Duration = Duration::from_secs(15);
73/// After a failure or a turn end, how long to wait for the other to land.
74const SETTLE: Duration = Duration::from_millis(1_500);
75
76/// An account the agents can move to.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
78#[ts(export, export_to = "../../../frontend/types/rpc/")]
79pub struct AccountMoveCandidate {
80    pub account_id: String,
81    pub label: String,
82    /// Its last known sign-in status (`valid`, `ok`, `unknown`, …).
83    pub status: String,
84}
85
86/// One account's episode, as `identity.account.availability` lists it for the
87/// operator's windows and for agents. The label never goes in a toast or an
88/// event; it reaches another machine only through the proven `identity.accounts`
89/// remote operation.
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
91#[ts(export, export_to = "../../../frontend/types/rpc/")]
92pub struct AccountAvailability {
93    pub account_id: String,
94    pub account_label: String,
95    pub provider: String,
96    #[ts(type = r#""limited" | "signed_out" | "ok""#)]
97    pub state: String,
98    /// When the last of its limits lifts (unix ms), when known.
99    #[ts(type = "number | null")]
100    pub resets_at_ms: Option<u64>,
101    /// The provider's name for that limit's window (`five_hour`, `seven_day`, …).
102    pub limit_window: Option<String>,
103    /// When the episode opened (unix ms).
104    #[ts(type = "number")]
105    pub since_ms: u64,
106    pub agents: Vec<AccountEpisodeAgent>,
107    pub tasks: Vec<AccountEpisodeTask>,
108    /// Where the agents can move, the first valid one first.
109    pub candidates: Vec<AccountMoveCandidate>,
110    /// The agents it covers, by definition id and by pane, so a view can tell
111    /// whether a task's holder is in it without another call (the Kanban's
112    /// Needs-you count, which counts an episode once, not each holder).
113    pub agent_ids: Vec<String>,
114    pub block_ids: Vec<String>,
115}
116
117impl From<AccountAvailability> for AccountAvailabilityEvent {
118    fn from(a: AccountAvailability) -> Self {
119        AccountAvailabilityEvent { account_id: a.account_id, provider: a.provider, state: a.state, resets_at_ms: a.resets_at_ms, agents: a.agents, tasks: a.tasks }
120    }
121}
122
123/// `identity.account.availability`: the open episodes. Open to agents (spec §4.4): it names
124/// accounts and their limits, never a credential.
125#[derive(Debug, Clone, Serialize, ts_rs::TS)]
126#[ts(export, export_to = "../../../frontend/types/rpc/")]
127pub struct IdentityAccountAvailabilityResult {
128    pub episodes: Vec<AccountAvailability>,
129}
130
131/// `identity.account.signed_in`: the window's sign-in to this account
132/// completed and its CLI confirmed the credential (#2237).
133#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
134#[ts(export, export_to = "../../../frontend/types/rpc/")]
135pub struct IdentityAccountSignedInReq {
136    pub account_id: String,
137}
138
139/// `identity.account.signed_in`: how many of the account's panes stopped
140/// being signed out.
141#[derive(Debug, Clone, Serialize, ts_rs::TS)]
142#[ts(export, export_to = "../../../frontend/types/rpc/")]
143pub struct IdentityAccountSignedInResult {
144    pub cleared: u32,
145}
146
147use failover::IdentityAccountSetFailoverReq;
148use moves::IdentityAccountMoveAgentsReq;
149pub(crate) use accounts::IdentityAccountsResult;
150pub(crate) use switch_error::{SwitchError, SwitchRefusal};
151pub(crate) use switch::{is_all_limited, AccountSwitchAllResult, AccountSwitchWhen, AgentAccountSwitchReq, AgentAccountSwitchResult};
152
153struct Runtime {
154    state: AppState,
155    episodes: Mutex<Episodes>,
156    wake: tokio::sync::Notify,
157}
158
159static RUNTIME: OnceLock<Runtime> = OnceLock::new();
160
161/// Start following the episodes. Call once at startup.
162pub fn install(state: AppState) {
163    crate::identity::sign_in_hook::set_after_sign_in(after_sign_in);
164    crate::backend::account_availability::set_covers_block(covers_block);
165    let baseline = baseline(&state.mstore);
166    let broker = state.broker.clone();
167    let sign_in_watch = (state.fs_watch_pool.clone(), state.id_store.clone());
168    if RUNTIME.set(Runtime { state, episodes: Mutex::new(Episodes::new(baseline)), wake: tokio::sync::Notify::new() }).is_err() {
169        return;
170    }
171    // Observers run inside `Broker::publish`, under its locks: only a poke.
172    broker.add_observer(Arc::new(|ev: &MuxEvent| {
173        if ev.event == crate::backend::mps::EVENT_AGENT_FAILURE || ev.event == crate::backend::mps::EVENT_AGENT_TURN {
174            refresh_soon();
175        }
176    }));
177    if tokio::runtime::Handle::try_current().is_err() {
178        return;
179    }
180    crate::identity::staged_watch::start(sign_in_watch.0.clone());
181    crate::identity::sign_in_watch::start(sign_in_watch.0, sign_in_watch.1);
182    tokio::spawn(async {
183        let Some(rt) = RUNTIME.get() else { return };
184        loop {
185            tokio::select! {
186                _ = tokio::time::sleep(TICK) => {}
187                _ = rt.wake.notified() => tokio::time::sleep(SETTLE).await,
188            }
189            let _ = tokio::task::spawn_blocking(refresh).await;
190        }
191    });
192}
193
194/// `agent.account.switch` for a caller that is not on the RPC engine (the `Identity` tool's HTTP
195/// route). `caller` is the agent's slug. Runs off the async workers.
196pub(crate) async fn switch_account(state: AppState, caller: String, req: AgentAccountSwitchReq) -> Result<AgentAccountSwitchResult, SwitchError> {
197    tokio::task::spawn_blocking(move || switch::switch(&state, &caller, &req)).await.map_err(|e| SwitchError::new(SwitchRefusal::Failed, e.to_string()))?
198}
199
200/// `Identity` `switch` with the agent `all limited`. `caller` is the agent's slug. Runs off the async workers.
201pub(crate) async fn switch_all_limited(state: AppState, caller: String, req: AgentAccountSwitchReq) -> Result<AccountSwitchAllResult, String> {
202    tokio::task::spawn_blocking(move || switch::switch_all_limited(&state, &caller, &req)).await.map_err(|e| e.to_string())?
203}
204
205/// `identity.accounts`: every signed-in account here with its stable id and quota. Runs off the async workers.
206pub(crate) async fn identity_accounts(state: AppState) -> Result<IdentityAccountsResult, String> {
207    tokio::task::spawn_blocking(move || accounts::accounts(&state, agentmux_common::time::now_ms_u64())).await.map_err(|e| e.to_string())?
208}
209
210/// Rebuild the episodes soon (a failure, a turn end, a rebind).
211pub(crate) fn refresh_soon() {
212    if let Some(rt) = RUNTIME.get() {
213        rt.wake.notify_one();
214    }
215}
216
217/// Rebuild the episodes now and act on what changed. BLOCKING (store reads).
218fn refresh() {
219    let Some(rt) = RUNTIME.get() else { return };
220    let now = agentmux_common::time::now_ms_u64();
221    let panes = scan(&rt.state, now);
222    let effects = rt.episodes.lock().unwrap_or_else(|e| e.into_inner()).update(panes.clone(), now);
223    for effect in effects {
224        apply(&rt.state, effect);
225    }
226    switch::apply_pending(&rt.state);
227    failover::run(&rt.state, &panes);
228    login_expiry::run(&rt.state, &panes);
229    login_recheck::run(&rt.state, &panes);
230    crate::identity::credential_watch::check(&rt.state.id_store, &rt.state.identity_store, Some(&rt.state.broker));
231}
232
233/// The failure kinds an episode is made of: a usage limit or a refused sign-in.
234fn blocking_failure(block: &Block) -> Option<agent_state::StoredFailure> {
235    // A route out of credits is no account's limit: no account moves or wakes for it (`backend::route_credits`).
236    failure_of_block(block)
237        .filter(|f| matches!(f.code, FailureClass::UsageLimit | FailureClass::Auth) && f.title != crate::agents::failure::ROUTE_CREDITS_TITLE)
238}
239
240fn signature(f: &agent_state::StoredFailure) -> String {
241    format!("{:?}|{:?}|{}", f.code, f.resets_at_ms, f.title)
242}
243
244/// Every pane in a tab, and every parked agent block: one in no tab whose agent keeps running with
245/// no pane showing it. Its limit or sign-in refusal is as much an episode as a shown pane's.
246fn tab_blocks(mstore: &Store) -> Vec<Block> {
247    let Ok(tabs) = mstore.get_all::<Tab>() else {
248        return Vec::new();
249    };
250    let mut out: Vec<Block> = tabs.iter().flat_map(|t| t.blockids.iter()).filter_map(|id| mstore.get::<Block>(id).ok().flatten()).collect();
251    let parked = mstore.get_all::<Block>().unwrap_or_default().into_iter().filter(|b| obj::meta_get_bool(&b.meta, crate::persist_subscriber::parked::PARKED_META_KEY, false));
252    out.extend(parked);
253    out
254}
255
256/// The failures already stored when srv starts, whether or not their panes
257/// have a controller yet.
258fn baseline(mstore: &Store) -> HashMap<String, String> {
259    tab_blocks(mstore).into_iter().filter_map(|b| blocking_failure(&b).map(|f| (b.oid.clone(), signature(&f)))).collect()
260}
261
262/// `p` canonical, or as given when it isn't a known provider.
263fn canonical(provider: &str) -> String {
264    match crate::backend::providers::resolve_provider_alias(provider) {
265        "" => provider.to_lowercase(),
266        c => c.to_string(),
267    }
268}
269
270fn agent_name(mstore: &Store, block: &Block) -> String {
271    let name = obj::meta_get_string(&block.meta, "agentName", "");
272    if !name.trim().is_empty() {
273        return name;
274    }
275    let def_id = obj::meta_get_string(&block.meta, "agentId", "");
276    mstore
277        .agent_def_list()
278        .ok()
279        .and_then(|defs| defs.into_iter().find(|d| d.id == def_id))
280        .map(|d| d.name)
281        .unwrap_or(def_id)
282}
283
284/// The pane's account and state while its stored failure keeps it in an
285/// episode: a usage limit whose reset (if known) hasn't passed, or a refused
286/// sign-in, on an account. Read from the stored failure, not the live state:
287/// a retry turn shows the pane `working` for a moment, and that must not
288/// close its episode and open a new one with a second toast when the turn
289/// fails again. Only a clean turn, a rebind or the reset clears it.
290fn membership(identity: &Store, block: &Block, failure: &agent_state::StoredFailure, now_ms: u64) -> Option<(String, AgentState)> {
291    let state = match failure.code {
292        FailureClass::UsageLimit if failure.resets_at_ms.is_none_or(|r| r > now_ms) => AgentState::Limited,
293        FailureClass::Auth => AgentState::SignedOut,
294        _ => return None,
295    };
296    let account = run_accounts_of_block(identity, block).into_iter().next()?;
297    // A pane on an API key is in no episode: nothing moves an agent off or onto a key but a person's choice, and its
298    // failure (a rejected key, no credit, the daily cap) stands on the pane, with its own toast.
299    if identity.identity_get(&account).ok().flatten().is_some_and(|a| key_account::is_key(&a)) {
300        return None;
301    }
302    Some((account, state))
303}
304
305/// Every agent pane whose stored failure puts it in an account's episode now.
306fn scan(state: &AppState, now_ms: u64) -> Vec<BlockedPane> {
307    let accounts = state.id_store.identity_list(None).unwrap_or_default();
308    let mut out = Vec::new();
309    for block in tab_blocks(&state.mstore) {
310        let Some(failure) = blocking_failure(&block) else { continue };
311        let Some((account_id, pane_state)) = membership(&state.identity_store, &block, &failure, now_ms) else { continue };
312        let provider = accounts
313            .iter()
314            .find(|a| a.id == account_id)
315            .map(|a| a.provider.clone())
316            .unwrap_or_else(|| obj::meta_get_string(&block.meta, "agentProvider", ""));
317        let limit_window = block
318            .meta
319            .get(crate::backend::blockcontroller::core::META_LAST_FAILURE)
320            .and_then(|f| f.get("limitWindow"))
321            .and_then(|w| w.as_str())
322            .map(str::to_string);
323        out.push(BlockedPane {
324            agent_id: obj::meta_get_string(&block.meta, "agentId", ""),
325            agent_name: agent_name(&state.mstore, &block),
326            block_id: block.oid.clone(),
327            account_id,
328            provider: canonical(&provider),
329            state: pane_state,
330            resets_at_ms: failure.resets_at_ms,
331            limit_window,
332            signature: signature(&failure),
333        });
334    }
335    out
336}
337
338/// Whether an account episode speaks for this pane's failure, so its own
339/// `AgentCrashed` or "finished" toast is left out (spec §6.2): its stored
340/// failure is a usage limit that hasn't reset or a refused sign-in, on an
341/// account. A pane with no account keeps its own toast. BLOCKING.
342pub fn covers_block(block_id: &str) -> bool {
343    let Some(rt) = RUNTIME.get() else { return false };
344    covers(&rt.state.mstore, &rt.state.identity_store, block_id, agentmux_common::time::now_ms_u64())
345}
346
347/// [`covers_block`] against these stores at `now_ms`.
348fn covers(mstore: &Store, identity: &Store, block_id: &str, now_ms: u64) -> bool {
349    let Some(block) = mstore.get::<Block>(block_id).ok().flatten() else { return false };
350    blocking_failure(&block).is_some_and(|f| membership(identity, &block, &f, now_ms).is_some())
351}
352
353/// The toast's key for an account: its group, and the id it is taken down by.
354/// Hashed, so the account id isn't in the notification.
355fn toast_key(account_id: &str) -> String {
356    format!("account:{}", crate::backend::notify::policy::tag_for(account_id))
357}
358
359fn apply(state: &AppState, effect: Effect) {
360    match effect {
361        Effect::Changed(ep) => {
362            tracing::info!(provider = %ep.provider, agents = ep.panes.len(), state = ep.state().as_str(), "account episode: changed");
363            publish(state, AccountAvailabilityEvent::from(view(state, &ep)));
364        }
365        Effect::Closed { account_id, provider } => {
366            tracing::info!(provider = %provider, "account episode: closed");
367            let ok = AccountAvailabilityEvent {
368                account_id: account_id.clone(),
369                provider,
370                state: "ok".to_string(),
371                resets_at_ms: None,
372                agents: Vec::new(),
373                tasks: Vec::new(),
374            };
375            publish(state, ok);
376            if let Some(router) = crate::backend::notify::router::get(&state.broker) {
377                router.resolve(&toast_key(&account_id), crate::backend::notify::policy::Family::Account);
378            }
379        }
380        Effect::Toast(ep) => match crate::backend::notify::router::get(&state.broker) {
381            Some(router) => router.account_unavailable(&toast_key(&ep.account_id), machine::toast_body(&ep)),
382            None => tracing::info!("account episode: no notification router yet (no window connected); the strip shows it"),
383        },
384        Effect::Announce { episode, panes } => announce(state, &episode.account_id, &panes),
385    }
386}
387
388fn publish(state: &AppState, payload: AccountAvailabilityEvent) {
389    state.broker.publish_event::<crate::backend::mps_events::AccountAvailability>(&payload, vec![], 0);
390}
391
392fn label_of(state: &AppState, account_id: &str) -> String {
393    let all = state.id_store.identity_list(None).unwrap_or_default();
394    all.iter()
395        .find(|a| a.id == account_id)
396        .map(|a| crate::server::app_api::agent_spawn::account_label_in(a, &all))
397        .unwrap_or_else(|| "an account no longer in AgentMux".to_string())
398}
399
400/// The claimed or blocked tasks each of `block_ids` holds, by block, and who
401/// requested each one.
402fn held_tasks(state: &AppState, block_ids: &[&str]) -> HashMap<String, Vec<(AccountEpisodeTask, String)>> {
403    use crate::backend::storage::work_board::requested;
404    use crate::backend::storage::work_queue::work_state;
405    let regs = state.reactive_handler.list_agents();
406    let now = agentmux_common::time::now_ms();
407    let tasks = state
408        .work_store
409        .work_board_list(now - crate::backend::kanban::FINISHED_WINDOW_MS, 500, now)
410        .unwrap_or_default();
411    let mut out: HashMap<String, Vec<(AccountEpisodeTask, String)>> = HashMap::new();
412    for t in tasks.iter().filter(|t| t.item.state == work_state::CLAIMED || t.item.state == work_state::BLOCKED) {
413        let holder = regs.iter().find(|r| {
414            if t.item.claimed_by_uid.is_empty() {
415                !t.item.claimed_by.is_empty() && r.agent_id.eq_ignore_ascii_case(&t.item.claimed_by)
416            } else {
417                r.uid.as_deref() == Some(t.item.claimed_by_uid.as_str())
418            }
419        });
420        let Some(holder) = holder.filter(|h| block_ids.contains(&h.block_id.as_str())) else { continue };
421        let requester = if t.card.requested_by_kind == requested::AGENT && !t.card.requested_by.eq_ignore_ascii_case(&holder.agent_id) {
422            t.card.requested_by.clone()
423        } else {
424            String::new()
425        };
426        let task = AccountEpisodeTask { id: t.item.id.clone(), number: t.card.num, task_ref: t.card.name(), title: t.item.title.clone() };
427        out.entry(holder.block_id.clone()).or_default().push((task, requester));
428    }
429    out
430}
431
432/// What the strips and the event show for `ep`.
433fn view(state: &AppState, ep: &Episode) -> AccountAvailability {
434    let ids: Vec<&str> = ep.panes.iter().map(|p| p.block_id.as_str()).collect();
435    let held = held_tasks(state, &ids);
436    let mut tasks: Vec<AccountEpisodeTask> = ids.iter().flat_map(|b| held.get(*b).into_iter().flatten().map(|(t, _)| t.clone())).collect();
437    tasks.sort_by_key(|t| t.number);
438    tasks.dedup_by(|a, b| a.id == b.id);
439    AccountAvailability {
440        account_id: ep.account_id.clone(),
441        account_label: label_of(state, &ep.account_id),
442        provider: ep.provider.clone(),
443        state: ep.state().as_str().to_string(),
444        resets_at_ms: ep.resets_at_ms(),
445        limit_window: ep.limit_window(),
446        since_ms: ep.opened_at_ms,
447        agents: ep
448            .panes
449            .iter()
450            .map(|p| AccountEpisodeAgent { block_id: p.block_id.clone(), agent_id: p.agent_id.clone(), agent_name: p.agent_name.clone() })
451            .collect(),
452        tasks,
453        candidates: moves::candidates(state, &ep.account_id, &ep.provider),
454        agent_ids: {
455            let mut ids: Vec<String> = ep.panes.iter().map(|p| p.agent_id.clone()).filter(|a| !a.is_empty()).collect();
456            ids.sort();
457            ids.dedup();
458            ids
459        },
460        block_ids: ep.panes.iter().map(|p| p.block_id.clone()).collect(),
461    }
462}
463
464/// For each requester of a task the newly blocked `panes` hold: the panes,
465/// and the refs of that requester's tasks each one holds.
466fn requester_items(state: &AppState, panes: &[BlockedPane]) -> std::collections::BTreeMap<String, Vec<(BlockedPane, Vec<String>)>> {
467    let ids: Vec<&str> = panes.iter().map(|p| p.block_id.as_str()).collect();
468    let held = held_tasks(state, &ids);
469    let mut out: std::collections::BTreeMap<String, Vec<(BlockedPane, Vec<String>)>> = Default::default();
470    for pane in panes {
471        let mut by_requester: std::collections::BTreeMap<String, Vec<(i64, String)>> = Default::default();
472        for (task, requester) in held.get(&pane.block_id).into_iter().flatten() {
473            if !requester.is_empty() {
474                by_requester.entry(requester.clone()).or_default().push((task.number, task.task_ref.clone()));
475            }
476        }
477        for (requester, mut held) in by_requester {
478            held.sort_unstable();
479            out.entry(requester).or_default().push((pane.clone(), held.into_iter().map(|(_, r)| r).collect()));
480        }
481    }
482    out
483}
484
485/// The notes to send for the newly blocked `panes` of `account_id`'s episode:
486/// one per requester per episode (spec §6.2), naming each of its agents and
487/// tasks. A requester already told in this episode gets nothing more when
488/// another agent joins: the strip shows the rest.
489fn requester_notes(state: &AppState, episodes: &Mutex<Episodes>, account_id: &str, panes: &[BlockedPane]) -> Vec<(String, String)> {
490    let items = requester_items(state, panes);
491    let fresh = episodes.lock().unwrap_or_else(|e| e.into_inner()).first_notes(account_id, items.keys().cloned());
492    items
493        .into_iter()
494        .filter(|(requester, _)| fresh.contains(requester))
495        .map(|(requester, items)| {
496            let refs: Vec<(&BlockedPane, &[String])> = items.iter().map(|(p, n)| (p, n.as_slice())).collect();
497            let text = format!("[AgentMux] {}", crate::backend::reactive::sanitize::quote_in_system_note(&machine::leader_note(&refs)));
498            (requester, text)
499        })
500        .collect()
501}
502
503fn announce(state: &AppState, account_id: &str, panes: &[BlockedPane]) {
504    let Some(rt) = RUNTIME.get() else { return };
505    for (requester, text) in requester_notes(state, &rt.episodes, account_id, panes) {
506        if let Err(e) = state.reactive_handler.deliver_system_note(&requester, &text) {
507            tracing::info!(requester = %requester, error = %e, "account episode: requester note not delivered");
508        }
509    }
510}
511
512/// The open episodes, as the strips show them. BLOCKING.
513fn availability(state: &AppState) -> IdentityAccountAvailabilityResult {
514    let open: Vec<Episode> = match RUNTIME.get() {
515        Some(rt) => rt.episodes.lock().unwrap_or_else(|e| e.into_inner()).list().cloned().collect(),
516        None => Vec::new(),
517    };
518    let shown: Vec<String> = open.iter().map(|ep| ep.account_id.clone()).collect();
519    let mut episodes: Vec<AccountAvailability> = open.iter().map(|ep| view(state, ep)).collect();
520    episodes.extend(login_expiry::rows(state, &shown));
521    IdentityAccountAvailabilityResult { episodes }
522}
523
524/// `agent_id`'s panes for `provider` whose stored failure is a usage limit
525/// or a refused sign-in, with the accounts their runs count against. Read
526/// before a link changes: a pane from before `agent:run_account` counts
527/// against the agent's links, which the change replaces.
528pub fn failed_panes(mstore: &Store, identity: &Store, agent_id: &str, provider: &str) -> Vec<(String, Vec<String>)> {
529    let provider = canonical(provider);
530    tab_blocks(mstore)
531        .into_iter()
532        .filter(|b| obj::meta_get_string(&b.meta, "agentId", "") == agent_id)
533        .filter(|b| canonical(&obj::meta_get_string(&b.meta, "agentProvider", "")) == provider)
534        .filter(|b| blocking_failure(b).is_some())
535        .map(|b| {
536            let accounts = run_accounts_of_block(identity, &b);
537            (b.oid, accounts)
538        })
539        .collect()
540}
541
542/// An agent was linked to `account_id` (spec §6.3, "on rebind"): clear the
543/// stored failure of each of `before` ([`failed_panes`]) whose run wasn't on
544/// that account, then wake held messages and the episodes. Returns how many
545/// were cleared.
546pub fn after_rebind(mstore: &Arc<Store>, event_bus: &Arc<EventBus>, before: Vec<(String, Vec<String>)>, account_id: &str) -> usize {
547    after_rebind_telling(mstore, event_bus, before, account_id, false)
548}
549
550/// [`after_rebind`], and with `tell` set the agents whose last turn failed on the old login are told they are
551/// signed in ([`resume::start`]). Set it only when the new login is known to work: a move to an account the
552/// choice found valid, or a key that just passed its check. Not for an unlink (no account at all) or a key
553/// nobody has checked, whose next turn could fail again.
554pub fn after_rebind_telling(mstore: &Arc<Store>, event_bus: &Arc<EventBus>, before: Vec<(String, Vec<String>)>, account_id: &str, tell: bool) -> usize {
555    let (cleared, signed_out) = rebind_clearing(mstore, event_bus, before, account_id, tell);
556    resume::start(signed_out, agentmux_common::time::now_ms());
557    cleared
558}
559
560/// [`after_rebind_telling`] without the telling: how many failures were cleared, and the panes among them (with
561/// `tell` set) whose last turn failed on the login, for the caller to pass to [`resume::start`] once the pane is
562/// running on the new account. A move restarts its panes after the relink, so telling at the relink would reach
563/// the old process, still on the expired login.
564pub(super) fn rebind_clearing(mstore: &Arc<Store>, event_bus: &Arc<EventBus>, before: Vec<(String, Vec<String>)>, account_id: &str, tell: bool) -> (usize, Vec<Failed>) {
565    let mut cleared = 0;
566    let mut signed_out = Vec::new();
567    for (block_id, accounts) in before {
568        if accounts.iter().any(|a| a == account_id) {
569            continue;
570        }
571        // The agent now runs on a login that works: one whose last turn failed on the old login is told.
572        if let Some(failure) = mstore.get::<Block>(&block_id).ok().flatten().and_then(|b| failure_of_block(&b)).filter(|f| tell && !account_id.is_empty() && f.code == FailureClass::Auth) {
573            signed_out.push(Failed { block_id: block_id.clone(), failed_at_ms: failure.at_ms });
574        }
575        crate::backend::blockcontroller::core::persist_last_failure(&block_id, None, &Some(mstore.clone()), &Some(event_bus.clone()));
576        cleared += 1;
577    }
578    if cleared > 0 {
579        tracing::info!(cleared, "account episode: a rebind cleared its old account's failures");
580        after_clearing();
581    }
582    (cleared, signed_out)
583}
584
585/// Failures were cleared: replay what was held for those agents, and let the
586/// episodes see that their panes left.
587fn after_clearing() {
588    crate::backend::reactive::held_jekt_wake().notify_one();
589    refresh_soon();
590}
591
592/// `account_id`'s credentials were just proven good: a sign-in to it
593/// completed, or a validate of it passed (#2237). A rebind to the same
594/// account clears nothing ([`after_rebind`]), so without this its panes
595/// stayed signed out until a turn ran. A token refresh isn't a proof and
596/// doesn't call this. Runs off the async workers; does nothing before
597/// [`install`].
598pub fn after_sign_in(account_id: &str) {
599    let Some(rt) = RUNTIME.get() else { return };
600    let account_id = account_id.to_string();
601    let run = move || {
602        resume::start(clear_signed_out_panes(&rt.state.mstore, &rt.state.identity_store, &rt.state.event_bus, &account_id), agentmux_common::time::now_ms());
603    };
604    match tokio::runtime::Handle::try_current() {
605        Ok(handle) => drop(handle.spawn_blocking(run)),
606        Err(_) => run(),
607    }
608}
609
610/// Clear the refused sign-in stored on each pane whose run was on
611/// `account_id`, then wake held messages and the episodes. A usage limit
612/// stays: it ends at the reset or a move. Returns how many were cleared.
613/// BLOCKING.
614pub(crate) fn clear_signed_out(mstore: &Arc<Store>, identity: &Store, event_bus: &Arc<EventBus>, account_id: &str) -> usize {
615    clear_signed_out_panes(mstore, identity, event_bus, account_id).len()
616}
617
618/// [`clear_signed_out`], returning the panes it cleared with when their turn failed, for
619/// [`resume::start`], which tells those agents. BLOCKING.
620fn clear_signed_out_panes(mstore: &Arc<Store>, identity: &Store, event_bus: &Arc<EventBus>, account_id: &str) -> Vec<Failed> {
621    let mut cleared = Vec::new();
622    for block in tab_blocks(mstore) {
623        let Some(failure) = failure_of_block(&block).filter(|f| f.code == FailureClass::Auth) else { continue };
624        if !run_accounts_of_block(identity, &block).iter().any(|a| a == account_id) {
625            continue;
626        }
627        crate::backend::blockcontroller::core::persist_last_failure(&block.oid, None, &Some(mstore.clone()), &Some(event_bus.clone()));
628        cleared.push(Failed { block_id: block.oid.clone(), failed_at_ms: failure.at_ms });
629    }
630    if !cleared.is_empty() {
631        tracing::info!(cleared = cleared.len(), "account episode: a sign-in cleared its account's signed-out panes");
632        after_clearing();
633    }
634    cleared
635}
636
637/// Restarts every open pane of the agent with its conversation resumed. A persistent pane in a turn is restarted when the
638/// turn ends. A one-shot (subprocess) pane, a container agent's, is not restarted: a restart would end the turn it is in,
639/// and its next turn reads the agent's choice anyway; nor is a stopped agent, which would be started by it. Those are counted apart. Returns how many were restarted, how many
640/// pick the change up at their next turn, and why the others were not restarted.
641pub(crate) fn restart_panes_of(state: &AppState, def_id: &str) -> (u32, u32, Vec<String>) {
642    let (mut restarted, mut next_turn, mut failed) = (0, 0, Vec::new());
643    for block in switch::open_panes(state, def_id) {
644        // No controller: the agent is stopped, and a restart would start it. It reads the choice when it is started.
645        let one_shot = crate::backend::blockcontroller::get_controller(&block.oid)
646            .is_none_or(|c| c.controller_type() == crate::backend::blockcontroller::BLOCK_CONTROLLER_SUBPROCESS);
647        if one_shot {
648            next_turn += 1;
649            continue;
650        }
651        match moves::restart(state, &block) {
652            Ok(()) => restarted += 1,
653            Err(e) => failed.push(e),
654        }
655    }
656    (restarted, next_turn, failed)
657}
658
659/// The panes (open, or parked) an agent's definition has: what a change to the agent's runtime is written to.
660pub(crate) fn panes_of(state: &AppState, def_id: &str) -> Vec<Block> {
661    switch::open_panes(state, def_id)
662}
663
664/// These RPCs are the operator's, except `agent.account.switch` and
665/// `identity.account.availability`: an agent connection (`bus:register`) is refused for the
666/// others, since the move relinks and restarts other agents and a sign-in clears other agents'
667/// state. A switch is open to agents (the caller is `ctx.agent_id`) and is audited under their
668/// name. The availability names accounts and their limits, never a credential, and an agent has
669/// to see it to choose where to move (spec §4.4).
670pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
671    let s = state.clone();
672    engine.register_typed(COMMAND_IDENTITY_ACCOUNT_SIGNED_IN, move |req: IdentityAccountSignedInReq, ctx| {
673        let s = s.clone();
674        async move {
675            ctx.operator_only("only the operator's window reports a sign-in")?;
676            if req.account_id.is_empty() {
677                return Err("identity.account.signed_in: account_id is required".to_string());
678            }
679            let cleared = tokio::task::spawn_blocking(move || clear_signed_out_panes(&s.mstore, &s.identity_store, &s.event_bus, &req.account_id))
680                .await
681                .map_err(|e| e.to_string())?;
682            let count = cleared.len();
683            resume::start(cleared, agentmux_common::time::now_ms());
684            Ok(IdentityAccountSignedInResult { cleared: u32::try_from(count).unwrap_or(u32::MAX) })
685        }
686    });
687    // The mark is for the operator's window and for agents: it changes where agents are moved
688    // when they run out, not any credential.
689    let s = state.clone();
690    engine.register_typed(COMMAND_IDENTITY_ACCOUNT_SET_FAILOVER, move |req: IdentityAccountSetFailoverReq, ctx| {
691        let s = s.clone();
692        async move {
693            if ctx.agent_id.is_empty() {
694                ctx.operator_only("only the AgentMux window or an agent marks an account never to fail over to")?;
695            }
696            tokio::task::spawn_blocking(move || failover::set_failover(&s, &req)).await.map_err(|e| e.to_string())?
697        }
698    });
699    let s = state.clone();
700    engine.register_typed(COMMAND_IDENTITY_ACCOUNT_AVAILABILITY, move |_req: Option<NoArgsReq>, ctx| {
701        let s = s.clone();
702        async move {
703            // A registered agent may read it; any other connection must be the proven window.
704            if ctx.agent_id.is_empty() {
705                ctx.operator_only("only the AgentMux window or an agent sees which accounts can't run")?;
706            }
707            tokio::task::spawn_blocking(move || availability(&s)).await.map_err(|e| e.to_string())
708        }
709    });
710    // The usage is as open as the availability: accounts and how much of their windows is used, never a credential.
711    let s = state.clone();
712    engine.register_typed(COMMAND_IDENTITY_ACCOUNT_USAGE, move |_req: Option<NoArgsReq>, ctx| {
713        let s = s.clone();
714        async move {
715            if ctx.agent_id.is_empty() {
716                ctx.operator_only("only the AgentMux window or an agent sees how much of an account is used")?;
717            }
718            identity_accounts(s).await
719        }
720    });
721    let s = state.clone();
722    engine.register_typed(COMMAND_IDENTITY_ACCOUNT_MOVE_AGENTS, move |req: IdentityAccountMoveAgentsReq, ctx| {
723        let s = s.clone();
724        async move {
725            ctx.operator_only("only the operator moves agents to another account")?;
726            let result = tokio::task::spawn_blocking(move || moves::move_agents(&s, &req)).await.map_err(|e| e.to_string())??;
727            refresh_soon();
728            Ok(result)
729        }
730    });
731    // Open to agents (spec §3.4): an agent switches itself or another; the
732    // audit row names the caller. The window's calls are recorded as the operator.
733    let s = state.clone();
734    engine.register_typed(COMMAND_AGENT_ACCOUNT_SWITCH, move |req: AgentAccountSwitchReq, ctx| {
735        let s = s.clone();
736        async move {
737            let caller = ctx.agent_id.clone();
738            // Not a registered agent: only the proven window may, and it is recorded as the operator.
739            if caller.is_empty() {
740                ctx.operator_only("changing an agent's account is for the AgentMux window or an agent")?;
741            }
742            tokio::task::spawn_blocking(move || switch::switch(&s, &caller, &req)).await.map_err(|e| e.to_string())?.map_err(String::from)
743        }
744    });
745}
746
747#[cfg(test)]
748#[path = "tests.rs"]
749mod tests;