Skip to main content

agentmux_srv/server/prep/
ledger.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The open windows, one per agent. A window is read and changed under the lock and nowhere else, and
5//! its closure is taken out under the same lock by the window's task alone, so it runs exactly once
6//! however `Agents ready`, "Switch now", a cancel and the deadline race.
7
8use std::collections::{HashMap, HashSet};
9use std::sync::{Arc, LazyLock, Mutex, MutexGuard};
10use tokio::time::Instant;
11
12use serde_json::Value;
13use tokio::sync::Notify;
14
15use crate::backend::continuity_handoff::{self, Handoff};
16use crate::server::AppState;
17
18use super::meta::{prep_value, set_block_meta};
19use super::{note, window, How, Prep, Proceed, AUDIT_ANSWERED, AUDIT_REQUESTED, EXTENDED_WINDOW, META_PREP, WINDOW};
20
21pub(super) struct Entry {
22    pub id: String,
23    pub prep: Prep,
24    pub started: Instant,
25    pub started_ms: u64,
26    pub until: Instant,
27    pub extended: bool,
28    pub why: Option<String>,
29    /// The agent answered with a handoff: the closure runs once its turn has ended.
30    pub ready: bool,
31    /// The person pressed "Switch now".
32    pub now: bool,
33    /// Who pressed it: the agent's slug when an agent did, empty for the window (the person).
34    pub now_by: String,
35    /// How long the handoff the agent left is, for the audit row.
36    pub handoff_chars: Option<usize>,
37    pub proceed: Option<Proceed>,
38    pub wake: Arc<Notify>,
39}
40
41impl Entry {
42    fn until_ms(&self) -> u64 {
43        self.started_ms + u64::try_from((self.until - self.started).as_millis()).unwrap_or(0)
44    }
45
46    pub(super) fn meta(&self) -> Value {
47        prep_value(&self.id, self.prep.action, self.until_ms(), self.extended, self.why.as_deref())
48    }
49}
50
51static LEDGER: LazyLock<Mutex<HashMap<String, Entry>>> = LazyLock::new(Default::default);
52
53fn ledger() -> MutexGuard<'static, HashMap<String, Entry>> {
54    LEDGER.lock().unwrap_or_else(|e| e.into_inner())
55}
56
57/// Read or change the window `id` of `def_id`; `None` when it is gone (it ended, or was replaced).
58pub(super) fn with<R>(def_id: &str, id: &str, f: impl FnOnce(&mut Entry) -> R) -> Option<R> {
59    ledger().get_mut(def_id).filter(|e| e.id == id).map(f)
60}
61
62/// Agents whose window has ended and whose closure is still running. They count as open, so
63/// `apply_pending` doesn't apply the same switch a second time while the closure does.
64static CLOSING: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Default::default);
65
66/// Held while a window's closure runs; the agent is open until it is dropped.
67pub(super) struct Closing(String);
68
69impl Drop for Closing {
70    fn drop(&mut self) {
71        CLOSING.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.0);
72    }
73}
74
75/// Take the window `id` of `def_id` out of the ledger: whoever gets it runs its closure.
76pub(super) fn take(def_id: &str, id: &str) -> Option<(Entry, Closing)> {
77    let mut guard = ledger();
78    if !guard.get(def_id).is_some_and(|e| e.id == id) {
79        return None;
80    }
81    // Both under the ledger's lock, so `is_open` never sees the agent in neither.
82    CLOSING.lock().unwrap_or_else(|e| e.into_inner()).insert(def_id.to_string());
83    guard.remove(def_id).map(|e| (e, Closing(def_id.to_string())))
84}
85
86/// Whether a window is open for the agent, or its closure is still running: the account change it
87/// waited on is the window's to apply, not `apply_pending`'s.
88pub fn is_open(def_id: &str) -> bool {
89    let open = ledger().contains_key(def_id);
90    open || CLOSING.lock().unwrap_or_else(|e| e.into_inner()).contains(def_id)
91}
92
93/// An open window.
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct Opened {
96    pub id: String,
97    /// When it ends, unless the agent asks for more time (epoch milliseconds).
98    pub until_ms: u64,
99}
100
101/// One audit row for the request `id`, recorded as `actor`.
102pub(super) fn audit(state: &AppState, prep: &Prep, id: &str, actor: &str, action: &str, reason: &str) {
103    let block = prep.blocks.first().map_or("", String::as_str);
104    state.reactive_handler.log_fleet_action_audit(Some(actor), &prep.agent_name, block, action, true, None, id, Some(reason));
105}
106
107fn refs(blocks: &[String]) -> Vec<&str> {
108    blocks.iter().map(String::as_str).collect()
109}
110
111/// Clear the chip on the agent's panes.
112pub(super) fn clear_meta(state: &AppState, prep: &Prep) {
113    set_block_meta(state, &refs(&prep.blocks), &[(META_PREP, Value::Null)]);
114}
115
116/// Open the window for `prep` and ask the agent; `proceed` runs once when it ends. Asking again for the
117/// same target changes nothing; for another one replaces the closure and keeps the window and its
118/// deadline. BLOCKING (store writes); needs a tokio runtime for the window's task.
119pub fn open(state: &AppState, prep: Prep, proceed: Proceed) -> Opened {
120    open_with(state, prep, proceed, || {})
121}
122
123/// [`open`], running `record` (the choice the closure acts on) before the window can end: with the window
124/// already open it runs under the ledger lock, so the window cannot end between the two, and for a new
125/// window it runs before the window's task starts. The closure therefore always finds `record`'s write
126/// already made, never one that outlives it.
127pub fn open_with(state: &AppState, prep: Prep, proceed: Proceed, record: impl FnOnce()) -> Opened {
128    let mut guard = ledger();
129    if let Some(e) = guard.get_mut(&prep.def_id) {
130        if e.prep.target != prep.target {
131            e.prep = prep;
132            e.proceed = Some(proceed);
133        }
134        record();
135        return Opened { id: e.id.clone(), until_ms: e.until_ms() };
136    }
137    let id = format!("p-{}", &uuid::Uuid::new_v4().simple().to_string()[..8]);
138    let started = Instant::now();
139    let entry = Entry {
140        id: id.clone(),
141        prep: prep.clone(),
142        started,
143        started_ms: agentmux_common::time::now_ms_u64(),
144        until: started + WINDOW,
145        extended: false,
146        why: None,
147        ready: false,
148        now: false,
149        now_by: String::new(),
150        handoff_chars: None,
151        proceed: Some(proceed),
152        wake: Arc::new(Notify::new()),
153    };
154    let (opened, meta) = (Opened { id: id.clone(), until_ms: entry.until_ms() }, entry.meta());
155    guard.insert(prep.def_id.clone(), entry);
156    drop(guard);
157    set_block_meta(state, &refs(&prep.blocks), &[(META_PREP, meta)]);
158    audit(state, &prep, &id, &prep.actor, AUDIT_REQUESTED, &format!("{}: {}", prep.action, prep.what));
159    record();
160    tokio::spawn(window::run(state.clone(), prep.def_id.clone(), id));
161    opened
162}
163
164/// The change is not going to happen (the person chose the account the agent is on): end the window
165/// without running the closure, take back what the agent left and tell it to carry on. BLOCKING.
166pub fn cancel(state: &AppState, def_id: &str) {
167    let Some(entry) = ledger().remove(def_id) else { return };
168    entry.wake.notify_one();
169    clear_meta(state, &entry.prep);
170    continuity_handoff::drop_for_request(def_id, &entry.id);
171    audit(state, &entry.prep, &entry.id, "agentmux", AUDIT_ANSWERED, "cancelled");
172    let route = agentmux_common::slug::agent_route_name(&entry.prep.agent_name);
173    if let Err(e) = window::send_note(state, &route, &note::cancelled(&entry.id)) {
174        tracing::debug!(agent = %entry.prep.agent_name, error = %e, "prep: the agent was not told the change was cancelled");
175    }
176}
177
178/// What an agent answers with `Agents ready`.
179#[derive(Debug, Default)]
180pub struct Answer {
181    pub handoff: Option<String>,
182    pub more_time: bool,
183    pub why: Option<String>,
184}
185
186/// The agent `def_id` (its slug `slug`) answers the window open for it. The handoff is stored at once, so
187/// it is kept even if the window runs out; a request for more time moves the deadline, once.
188pub(crate) fn answer(state: &AppState, def_id: &str, slug: &str, a: Answer) -> Result<Value, String> {
189    let text = a.handoff.as_deref().map(continuity_handoff::clamp).filter(|t| !t.is_empty());
190    if text.is_none() && !a.more_time {
191        return Err("say what your next session must know: handoff (at most about 10 lines), or more_time true with why".to_string());
192    }
193    let mut guard = ledger();
194    let Some(e) = guard.get_mut(def_id) else {
195        return Err("no change is waiting on you: nothing to hand off (it may have already happened)".to_string());
196    };
197    if let Some(text) = &text {
198        let handoff = Handoff { prep_id: e.id.clone(), at_ms: agentmux_common::time::now_ms(), actor: e.prep.actor.clone(), action: e.prep.action.to_string(), text: text.clone() };
199        continuity_handoff::store(def_id, &handoff)?;
200        e.handoff_chars = Some(text.chars().count());
201    }
202    let mut said = Vec::new();
203    if a.more_time {
204        if e.extended {
205            return Err("you already asked for more time: it is once. Call Agents ready with your handoff".to_string());
206        }
207        e.extended = true;
208        e.until = e.started + EXTENDED_WINDOW;
209        e.why = a.why.as_deref().map(crate::backend::reactive::sanitize::quote_in_system_note).filter(|w| !w.is_empty());
210        said.push(format!("more time: until {} seconds from the change", EXTENDED_WINDOW.as_secs()));
211    } else {
212        e.ready = true;
213        said.push("handoff stored: the change runs when your turn ends".to_string());
214    }
215    let (meta, prep, id, wake) = (e.meta(), e.prep.clone(), e.id.clone(), e.wake.clone());
216    drop(guard);
217    set_block_meta(state, &refs(&prep.blocks), &[(META_PREP, meta)]);
218    tracing::info!(agent = %slug, prep = %id, more_time = a.more_time, handoff = text.is_some(), "prep: the agent answered");
219    wake.notify_one();
220    Ok(serde_json::json!({ "status": if a.more_time { "more_time" } else { "ready" }, "note": said.join("; "), "prep": id }))
221}
222
223/// "Switch now" for the agent `def_id`, pressed by the window (`caller` empty: the person) or by the agent
224/// `caller`: the window ends and the closure runs. BLOCKING.
225pub fn person_says_now(def_id: &str, caller: &str) -> Result<(), String> {
226    let mut guard = ledger();
227    let e = guard.get_mut(def_id).ok_or("nothing is waiting for that agent")?;
228    e.now = true;
229    e.now_by = caller.to_string();
230    e.wake.notify_one();
231    Ok(())
232}
233
234/// The `prep.answered` row of a window that ended as `how`: who it is recorded as (the agent when it
235/// answered, whoever pressed "Switch now" (the person, or the agent that did), AgentMux otherwise) and why.
236pub(super) fn finish_row(e: &Entry, how: How) -> (String, String) {
237    let who = match how {
238        How::Ready => agentmux_common::slug::agent_route_name(&e.prep.agent_name),
239        How::PersonSaidNow if e.now_by.is_empty() => "operator".to_string(),
240        How::PersonSaidNow => e.now_by.clone(),
241        How::TimedOut | How::NotAsked => "agentmux".to_string(),
242    };
243    let handoff = e.handoff_chars.map_or_else(String::new, |n| format!(", handoff {n} characters"));
244    let more = if e.extended { ", asked for more time" } else { "" };
245    (who, format!("{}{handoff}{more}", how.reason()))
246}