agentmux_srv/server/remote_ops/
memory.rs1use serde::de::DeserializeOwned;
12use serde_json::{json, Value};
13
14use super::{AppState, RemoteCaller, RemoteRefusal, RemoteResult};
15use crate::backend::memory::fleet::{self, Actor, FleetEntry, FleetError, FleetRemoval, Outcome};
16use crate::backend::storage::store::Store;
17
18pub(super) const MAX_PUT_PARAMS: usize = 1_200_000;
21
22fn parse<T: DeserializeOwned>(op: &str, params: Value) -> Result<T, RemoteRefusal> {
23 serde_json::from_value(params).map_err(|e| RemoteRefusal::new("bad_params", format!("{op}: {e}")))
24}
25
26async fn write(
28 state: &AppState,
29 caller: &RemoteCaller,
30 run: impl FnOnce(&Store, Actor<'_>) -> Result<Outcome, FleetError> + Send + 'static,
31) -> RemoteResult {
32 let store = state.id_store.clone();
33 let label = caller.actor();
34 let outcome = tokio::task::spawn_blocking(move || run(&store, Actor { label: &label, uid: "" }))
35 .await
36 .map_err(|e| RemoteRefusal::failed(format!("the write did not finish: {e}")))?
37 .map_err(|e| match e {
38 FleetError::Invalid(message) => RemoteRefusal::new("bad_params", message),
39 FleetError::Store(e) => RemoteRefusal::failed(e.to_string()),
40 })?;
41 if matches!(outcome, Outcome::Applied(_)) {
42 state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
43 tracing::info!(actor = %caller.actor(), outcome = %outcome.to_json(), "fleet memory: applied a write from another machine");
44 }
45 Ok(outcome.to_json())
46}
47
48pub(super) async fn put(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
49 let entry: FleetEntry = parse("memory.global.put", params)?;
50 let (id, name) = (entry.id.clone(), entry.name.clone());
51 let answer = write(state, caller, move |store, actor| fleet::apply_put(store, &entry, actor)).await?;
52 if answer.get("outcome").and_then(Value::as_str) == Some("adopted") {
55 let from = caller.actor();
56 tracing::warn!(entry = %id, name = %name, from = %from, "fleet memory: replaced an entry that was machine-only by default; its old text is in its history");
57 super::fleet_sync::status::global().adopted(&id, &name, &from, agentmux_common::time::now_ms());
58 }
59 Ok(answer)
60}
61
62pub(super) async fn remove(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
63 let removal: FleetRemoval = parse("memory.global.remove", params)?;
64 write(state, caller, move |store, actor| fleet::apply_remove(store, &removal, actor)).await
65}
66
67pub(super) async fn list(state: &AppState, _caller: &RemoteCaller, _params: Value) -> RemoteResult {
70 let store = state.id_store.clone();
71 let entries = tokio::task::spawn_blocking(move || fleet::list_meta(&store))
72 .await
73 .map_err(|e| RemoteRefusal::failed(format!("the listing did not finish: {e}")))?
74 .map_err(|e| RemoteRefusal::failed(e.to_string()))?;
75 Ok(json!({ "entries": entries }))
76}
77
78#[cfg(test)]
79mod tests;