agentmux_srv/server/prep/
ledger.rs1use 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 pub ready: bool,
31 pub now: bool,
33 pub now_by: String,
35 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
57pub(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
62static CLOSING: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Default::default);
65
66pub(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
75pub(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 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
86pub 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#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct Opened {
96 pub id: String,
97 pub until_ms: u64,
99}
100
101pub(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
111pub(super) fn clear_meta(state: &AppState, prep: &Prep) {
113 set_block_meta(state, &refs(&prep.blocks), &[(META_PREP, Value::Null)]);
114}
115
116pub fn open(state: &AppState, prep: Prep, proceed: Proceed) -> Opened {
120 open_with(state, prep, proceed, || {})
121}
122
123pub 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
164pub 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, ¬e::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#[derive(Debug, Default)]
180pub struct Answer {
181 pub handoff: Option<String>,
182 pub more_time: bool,
183 pub why: Option<String>,
184}
185
186pub(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
223pub 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
234pub(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}