Skip to main content

agentmux_srv/server/app_api/
agent_history_reclaim.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `App history_reclaim` (`GET`/`POST /api/v1/agent/history/reclaim`): a host or container agent asks for the
5//! shared pane-history store's free space to be given back at the next start, withdraws that request, or reads
6//! where it stands. The window does the same with `history.reclaim` (History > Storage); nothing in
7//! the request touches the host's files from the agent's side: srv writes the one marker beside its own store.
8//!
9//! The request is recorded as the calling agent (the marker's `requested_by` is its slug, and the HTTP layer
10//! records the call under its token, never as the operator). It runs only at an srv start, so the operator
11//! sees it pending in Storage and can cancel it there. Asking again keeps the first request.
12
13use axum::extract::State;
14use axum::http::StatusCode;
15use axum::response::{IntoResponse, Response};
16use axum::{Extension, Json};
17use serde::Deserialize;
18use serde_json::{json, Value};
19
20use crate::backend::history_usage;
21use crate::backend::storage::filestore::reclaim;
22use crate::server::caller::Caller;
23use crate::server::state::AppState;
24
25#[derive(Debug, Deserialize)]
26pub(crate) struct ReclaimRequest {
27    /// `request` or `cancel`.
28    action: String,
29}
30
31struct Refusal {
32    status: StatusCode,
33    message: String,
34}
35
36fn refuse(status: StatusCode, message: impl Into<String>) -> Refusal {
37    Refusal { status, message: message.into() }
38}
39
40/// The slug of the agent the request's token names.
41fn caller_slug(state: &AppState, caller: Option<&Caller>) -> Result<String, Refusal> {
42    let Some(uid) = caller.and_then(Caller::uid) else {
43        return Err(refuse(
44            StatusCode::UNAUTHORIZED,
45            "no agent token: App history_reclaim acts as the calling agent; the operator uses History > Storage",
46        ));
47    };
48    let def = state
49        .mstore
50        .agent_def_get(uid)
51        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("history reclaim: {e}")))?
52        .ok_or_else(|| refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"))?;
53    Ok(def.slug)
54}
55
56/// The shared store's database file.
57fn store_db() -> Result<std::path::PathBuf, Refusal> {
58    crate::backend::agent_session::global_transcript_store()
59        .and_then(|s| s.path().map(|p| p.to_path_buf()))
60        .ok_or_else(|| refuse(StatusCode::CONFLICT, "the shared pane-history store isn't open"))
61}
62
63/// The request and last result, as the answer says them.
64fn status_of(db: &std::path::Path) -> Value {
65    let r = history_usage::reclaim_of(db);
66    let (marker, _) = reclaim::status(db);
67    let mut out = json!({
68        "pending": r.pending,
69        "waiting_for": r.waiting_for,
70        "last_error": r.last_error,
71        "last_done_ms": r.last_done_ms,
72        "last_before_bytes": r.last_before_bytes,
73        "last_after_bytes": r.last_after_bytes,
74    });
75    if let Some(m) = marker {
76        out["requested_by"] = json!(m.requested_by);
77        out["requested_at_ms"] = json!(m.requested_at_ms);
78    }
79    out
80}
81
82/// Request, cancel or read the reclaim of the store at `db`, as `by`.
83fn change(db: &std::path::Path, action: &str, by: &str, now_ms: u64) -> Result<Value, Refusal> {
84    // Whose request a cancel takes back: anyone may withdraw it (the person can in Storage, an agent here),
85    // but the answer and the log say whose it was.
86    let withdrawn = reclaim::status(db).0.map(|m| m.requested_by);
87    let done = match action {
88        "request" => reclaim::request(db, by, now_ms),
89        "cancel" => reclaim::cancel(db),
90        other => return Err(refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: unknown action {other:?} (request or cancel)"))),
91    };
92    done.map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("history reclaim: {e}")))?;
93    tracing::info!(agent = by, action, previously_requested_by = ?withdrawn, "history reclaim: {}", if action == "request" { "asked for at the next start" } else { "withdrawn" });
94    let mut out = status_of(db);
95    if action == "cancel" {
96        if let Some(was) = withdrawn {
97            out["withdrew_request_of"] = json!(was);
98        }
99    }
100    Ok(out)
101}
102
103fn respond(result: Result<Value, Refusal>) -> Response {
104    match result {
105        Ok(body) => Json(body).into_response(),
106        Err(r) => (r.status, Json(json!({ "error": r.message }))).into_response(),
107    }
108}
109
110/// The same request, cancel or read as the route, for a caller that is not on this machine (`app.history_reclaim`):
111/// `by` is the actor the marker and the log name. `action` is `request`, `cancel` or `status`.
112pub(crate) fn run_for(action: &str, by: &str) -> Result<Value, String> {
113    let db = store_db().map_err(|r| r.message)?;
114    match action {
115        "status" => Ok(status_of(&db)),
116        _ => change(&db, action, by, agentmux_common::time::now_ms_u64()).map_err(|r| r.message),
117    }
118}
119
120/// `POST /api/v1/agent/history/reclaim`: `{ "action": "request" | "cancel" }`.
121pub(crate) async fn handle_history_reclaim(
122    State(state): State<AppState>,
123    caller: Option<Extension<Caller>>,
124    Json(req): Json<ReclaimRequest>,
125) -> Response {
126    let caller = caller.map(|Extension(c)| c);
127    respond(caller_slug(&state, caller.as_ref()).and_then(|by| {
128        let db = store_db()?;
129        change(&db, &req.action, &by, agentmux_common::time::now_ms_u64())
130    }))
131}
132
133/// `GET /api/v1/agent/history/reclaim`: where the request and the last reclaim stand; changes nothing.
134pub(crate) async fn handle_history_reclaim_status(State(state): State<AppState>, caller: Option<Extension<Caller>>) -> Response {
135    let caller = caller.map(|Extension(c)| c);
136    respond(caller_slug(&state, caller.as_ref()).and_then(|_| Ok(status_of(&store_db()?))))
137}
138
139#[cfg(test)]
140#[path = "tests/agent_history_reclaim_tests.rs"]
141mod tests;