Skip to main content

agentmux_srv/server/app_api/
agent_watch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents watch` (`POST /api/v1/agent/watch`): replay the recent transcript of an agent, then tail it,
5//! for a leader that supervises a worker without opening a pane
6//! (docs/specs/SPEC_ALWAYS_AVAILABLE_AGENTS_2026_10_27.md §5.1). It reads the same output file a pane
7//! reads, by the agent's block, so an agent with no pane (parked, or stopped) can be watched too.
8//!
9//! A call returns whole lines and `next`, a byte position. Pass `next` back as `after` to get what was
10//! written since; with `wait_seconds` the call waits for a new line instead of answering empty. Without
11//! `after` it is the replay: the last `max_lines` lines. The position is a byte offset into the file, so
12//! a line being written is not returned until it is complete, and a read costs the new bytes, not the
13//! whole transcript. If the file shrank (a fresh session) the answer says `reset` and replays.
14//!
15//! Who may watch: the same as `transcript` for an agent on this host, any agent on this machine; the
16//! call is not an action on the watched agent and is not audited.
17
18use axum::extract::State;
19use axum::http::StatusCode;
20use axum::response::{IntoResponse, Response};
21use axum::{Extension, Json};
22use serde::Deserialize;
23use serde_json::{json, Value};
24
25use super::agent_lifecycle::{actor_of, refuse, target_of, Refusal};
26use crate::server::caller::Caller;
27use crate::server::state::AppState;
28
29/// The zone's file the transcript is.
30const OUTPUT_FILE: &str = "output";
31/// The most a replay reads back from the end of the file.
32const REPLAY_BYTES: i64 = 256 * 1024;
33/// The most one tail read takes.
34const CHUNK_BYTES: i64 = 512 * 1024;
35/// The most searched for the end of one line before it is given up on.
36const MAX_SCAN_BYTES: i64 = if cfg!(test) { 1024 * 1024 } else { 16 * 1024 * 1024 };
37const DEFAULT_LINES: usize = 100;
38const MAX_LINES: usize = 500;
39/// The longest a line is shown; a tool result can be much larger.
40const MAX_LINE_CHARS: usize = 8 * 1024;
41/// The longest a call waits for a new line.
42const MAX_WAIT_SECONDS: u64 = 25;
43const POLL_EVERY: std::time::Duration = std::time::Duration::from_millis(500);
44
45#[derive(Debug, Deserialize)]
46pub(crate) struct WatchRequest {
47    agent: String,
48    #[serde(default)]
49    max_lines: Option<usize>,
50    /// The `next` of the last answer: only lines after it.
51    #[serde(default)]
52    after: Option<u64>,
53    /// The `gen` of the answer `after` came from. When the transcript was rewritten since (swapped for
54    /// its compact form), `after` is moved to the same place in the new file; without it, a cursor
55    /// that no longer fits is a replay.
56    #[serde(default)]
57    gen: Option<String>,
58    #[serde(default)]
59    wait_seconds: Option<u64>,
60}
61
62/// Whole lines read from a window of the file, and where the next read starts.
63#[derive(Debug, PartialEq)]
64struct Lines {
65    lines: Vec<String>,
66    /// Absolute byte position after the last line returned.
67    next: u64,
68    /// Older lines were left out (a replay) or newer ones are still to read (a tail).
69    more: bool,
70}
71
72fn shown(line: &str) -> String {
73    match line.char_indices().nth(MAX_LINE_CHARS) {
74        Some((cut, _)) => format!("{}…[{} more characters]", &line[..cut], line[cut..].chars().count()),
75        None => line.to_string(),
76    }
77}
78
79/// The whole lines in `data`, which starts at byte `from` of the file. `mid_line`: `from` may fall inside
80/// a line, so the first piece is dropped. `from_end`: keep the last `max` lines (a replay) rather than the
81/// first (a tail). A last line with no newline yet is not returned and `next` stays before it.
82fn lines_of(data: &[u8], from: u64, mid_line: bool, from_end: bool, max: usize) -> Lines {
83    let mut start = 0;
84    if mid_line {
85        match data.iter().position(|&b| b == b'\n') {
86            Some(i) => start = i + 1,
87            None => return Lines { lines: Vec::new(), next: from, more: false },
88        }
89    }
90    let Some(end) = data.iter().rposition(|&b| b == b'\n').map(|i| i + 1).filter(|&e| e > start) else {
91        return Lines { lines: Vec::new(), next: from + start as u64, more: false };
92    };
93    // (end offset in `data`, text) of each non-blank line.
94    let mut found: Vec<(usize, String)> = Vec::new();
95    let mut at = start;
96    for piece in data[start..end].split_inclusive(|&b| b == b'\n') {
97        at += piece.len();
98        let text = String::from_utf8_lossy(piece);
99        let text = text.trim();
100        if !text.is_empty() {
101            found.push((at, shown(&crate::backend::transcript::withhold::text(text))));
102        }
103    }
104    let more_than_max = found.len() > max;
105    let (kept, next_at): (Vec<(usize, String)>, usize) = if !more_than_max {
106        (found, end)
107    } else if from_end {
108        let skip = found.len() - max;
109        (found.split_off(skip), end)
110    } else {
111        found.truncate(max);
112        let next_at = found.last().map_or(start, |(e, _)| *e);
113        (found, next_at)
114    };
115    Lines { lines: kept.into_iter().map(|(_, t)| t).collect(), next: from + next_at as u64, more: more_than_max }
116}
117
118/// Whether the agent's zone is still the copy being written: false when the block's own copy is clearly newer
119/// (the zone stopped receiving lines), so a watch reads what the agent is writing now and agrees with
120/// `Agents transcript` (`TranscriptSource::resolve`, the same rule), not hours-old lines from the zone.
121fn zone_is_live(
122    gfs: &crate::backend::storage::filestore::FileStore,
123    zone: &str,
124    own_fs: &crate::backend::storage::filestore::FileStore,
125    block_id: &str,
126    slack_ms: i64,
127) -> bool {
128    let stat = |fs: &crate::backend::storage::filestore::FileStore, zone: &str| fs.stat(zone, OUTPUT_FILE).ok().flatten().map(|f| (f.size, f.modts));
129    !crate::backend::transcript::source::own_is_newer(stat(own_fs, block_id), stat(gfs, zone), slack_ms)
130}
131
132/// The transcript, whole in memory (an archived session) or read in spans from the file store the pane
133/// reads: the agent's own zone in the global transcript store when it has content, else the block's.
134struct Source {
135    fs: std::sync::Arc<crate::backend::storage::filestore::FileStore>,
136    zone: String,
137    whole: Option<Vec<u8>>,
138    size: i64,
139    /// The counted generation of the file (a different one is a rewritten file); `None` for an archive.
140    gen: Option<String>,
141}
142
143impl Source {
144    fn open(state: &AppState, block_id: &str) -> Result<Option<Source>, String> {
145        let archived = state
146            .mstore
147            .get::<crate::backend::obj::Block>(block_id)
148            .ok()
149            .flatten()
150            .and_then(|b| b.meta.get(crate::backend::session_archive::META_SESSION_ARCHIVED_AT).and_then(|v| v.as_i64()))
151            .is_some_and(|at| at > 0);
152        if archived {
153            let (bytes, _) = crate::backend::session_archive::read_session_output(&state.mstore, &state.filestore, block_id)?;
154            return Ok(Some(Source { fs: state.filestore.clone(), zone: block_id.to_string(), size: bytes.len() as i64, whole: Some(bytes), gen: None }));
155        }
156        let (fs, zone) = super::global_output_source(&state.filestore, &state.global_transcript_store, &state.mstore, block_id, OUTPUT_FILE)
157            .filter(|(gfs, zone)| zone_is_live(gfs, zone, &state.filestore, block_id, crate::backend::transcript::source::OWN_NEWER_SLACK_MS))
158            .unwrap_or_else(|| (state.filestore.clone(), block_id.to_string()));
159        let gen = counted_gen(&fs, &zone);
160        let stat = fs.stat(&zone, OUTPUT_FILE).map_err(|e| format!("filestore stat: {e}"))?;
161        Ok(stat.map(|f| Source { fs, zone, whole: None, size: f.size, gen }))
162    }
163
164    /// The generation of the file now: not the one it was opened with when a swap came in between.
165    fn gen_now(&self) -> Option<String> {
166        match &self.whole {
167            Some(_) => None,
168            None => counted_gen(&self.fs, &self.zone),
169        }
170    }
171
172    /// `len` bytes from `from`, and where they really start (a circular file may have dropped the front).
173    fn span(&self, from: i64, len: i64) -> Result<(i64, Vec<u8>), String> {
174        match &self.whole {
175            Some(bytes) => {
176                let end = ((from + len) as usize).min(bytes.len());
177                Ok((from, bytes[(from as usize).min(end)..end].to_vec()))
178            }
179            None if len <= 0 => Ok((from, Vec::new())),
180            None => self.fs.read_at(&self.zone, OUTPUT_FILE, from, len).map_err(|e| format!("filestore read: {e}")),
181        }
182    }
183
184    /// The position just after the last line break in the file (0 with none): a place a cursor can
185    /// stand without being inside a line, however long the line at the end is.
186    fn last_boundary(&self) -> Result<i64, String> {
187        let mut end = self.size;
188        while end > 0 {
189            let start = (end - CHUNK_BYTES).max(0);
190            let (at, data) = self.span(start, end - start)?;
191            if let Some(i) = data.iter().rposition(|&b| b == b'\n') {
192                return Ok(at + i as i64 + 1);
193            }
194            if at >= end {
195                break;
196            }
197            end = start;
198        }
199        Ok(0)
200    }
201
202    /// The position of the first line break at or after `from`, reading on in spans.
203    fn find_newline(&self, mut from: i64) -> Result<Option<i64>, String> {
204        while from < self.size {
205            let (at, data) = self.span(from, CHUNK_BYTES)?;
206            if let Some(i) = data.iter().position(|&b| b == b'\n') {
207                return Ok(Some(at + i as i64));
208            }
209            if data.is_empty() {
210                break;
211            }
212            from = at + data.len() as i64;
213        }
214        Ok(None)
215    }
216}
217
218/// The counted generation of the transcript file, `None` when it has none.
219fn counted_gen(fs: &crate::backend::storage::filestore::FileStore, zone: &str) -> Option<String> {
220    fs.line_state(zone, OUTPUT_FILE).ok().flatten().and_then(|s| s.counted).map(|c| c.gen)
221}
222
223/// Times a read starts again because the file was swapped while it was read.
224const READ_ATTEMPTS: usize = 3;
225
226/// What one read of the transcript gave.
227struct Read {
228    /// The generation of the file the lines came from.
229    gen: Option<String>,
230    lines: Lines,
231    /// The cursor asked for bytes the file no longer holds, or is past its end: this is a replay.
232    reset: bool,
233    /// A session that ended: its file never grows, so waiting for a line is pointless.
234    archived: bool,
235}
236
237/// The lines after `after`, or the tail of the transcript when `after` is `None` or no longer valid.
238/// A line longer than a read is searched for its end, up to [`MAX_SCAN_BYTES`], and a longer one is
239/// skipped with a marker line, so a cursor never stops in front of a line or lands inside one.
240///
241/// The generation, the size and the bytes must be of one file: a swap that lands during the read
242/// would pair a position in the new file with the old generation, so the generation is read again
243/// afterwards and the read starts over when it changed.
244fn read_lines(state: &AppState, block_id: &str, after: Option<u64>, gen: Option<&str>, max: usize) -> Result<Read, String> {
245    let mut attempt = 1;
246    loop {
247        let Some(src) = Source::open(state, block_id)? else {
248            let lines = Lines { lines: Vec::new(), next: 0, more: false };
249            return Ok(Read { gen: None, lines, reset: after.is_some_and(|a| a > 0), archived: false });
250        };
251        let read = read_from(&src, after, gen, max)?;
252        if attempt >= READ_ATTEMPTS || src.gen_now() == src.gen {
253            return Ok(read);
254        }
255        attempt += 1;
256    }
257}
258
259/// One read of an opened source.
260fn read_from(src: &Source, after: Option<u64>, gen: Option<&str>, max: usize) -> Result<Read, String> {
261    let archived = src.whole.is_some();
262    let size = src.size;
263    let mut reset = false;
264    // The file was rewritten since the cursor was given out: the same place in the new file, or a replay.
265    let after = match (after, gen, src.gen.as_deref()) {
266        (Some(at), Some(then), Some(now)) if then != now => {
267            let maps = crate::backend::transcript::consol::maps(&src.fs, &src.zone);
268            let moved = crate::backend::transcript::consol::translate_byte(&maps, then, now, at as i64).filter(|b| *b >= 0);
269            reset = moved.is_none();
270            moved.map(|b| b as u64)
271        }
272        _ => after,
273    };
274    if let Some(after) = after.map(|a| a as i64) {
275        if after <= size {
276            let mut len = (size - after).min(CHUNK_BYTES);
277            loop {
278                let (at, data) = src.span(after, len)?;
279                if at > after {
280                    // A circular file dropped what the cursor pointed at.
281                    reset = true;
282                    break;
283                }
284                let mut lines = lines_of(&data, at as u64, false, false, max);
285                if !lines.lines.is_empty() || lines.next > after as u64 || after + len >= size {
286                    // Bytes past this window are still to read, even when it held few lines.
287                    lines.more |= at + (data.len() as i64) < size;
288                    return Ok(Read { gen: src.gen.clone(), lines, reset: false, archived });
289                }
290                if len >= MAX_SCAN_BYTES {
291                    let lines = match src.find_newline(after + len)? {
292                        Some(end) => Lines {
293                            lines: vec![format!("[a line of {} bytes is too long to show and was skipped]", end + 1 - after)],
294                            next: (end + 1) as u64,
295                            more: true,
296                        },
297                        // Still being written: nothing to move past yet.
298                        None => Lines { lines: Vec::new(), next: after as u64, more: false },
299                    };
300                    return Ok(Read { gen: src.gen.clone(), lines, reset: false, archived });
301                }
302                len = (len * 2).min(size - after);
303            }
304        } else {
305            reset = true;
306        }
307    }
308    // The replay: the last lines, from a window that grows until it holds a whole line.
309    let mut window = REPLAY_BYTES;
310    loop {
311        let start = (size - window).max(0);
312        let (at, data) = src.span(start, size - start)?;
313        let lines = lines_of(&data, at as u64, at > 0, true, max);
314        if !lines.lines.is_empty() || at == 0 {
315            return Ok(Read { gen: src.gen.clone(), lines, reset, archived });
316        }
317        if window >= MAX_SCAN_BYTES {
318            // The last line is longer than a replay looks back (and may still be written): the cursor
319            // stands after the last line break before it, so the tail skips that line whole, or waits
320            // for it to end, and never returns a piece of it.
321            let skipped = Lines {
322                lines: vec![format!("[no line break in the last {} bytes: older output was skipped]", size - at)],
323                next: src.last_boundary()? as u64,
324                more: true,
325            };
326            return Ok(Read { gen: src.gen.clone(), lines: skipped, reset, archived });
327        }
328        window *= 2;
329    }
330}
331
332async fn watch(state: &AppState, req: &WatchRequest) -> Result<Value, Refusal> {
333    let blocking = state.clone();
334    let named = req.agent.clone();
335    let target = tokio::task::spawn_blocking(move || target_of(&blocking, &named))
336        .await
337        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents watch: {e}")))??;
338    let Some(block_id) = target.block_id.clone() else {
339        return Ok(json!({
340            "agent": target.name, "agent_id": target.agent_id, "lines": [], "next": 0, "more": false,
341            "runtime": { "state": target.state, "desired": target.desired },
342            "note": "it has never run: there is no transcript yet; Agents start runs it",
343        }));
344    };
345    let max = req.max_lines.unwrap_or(DEFAULT_LINES).clamp(1, MAX_LINES);
346    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(req.wait_seconds.unwrap_or(0).min(MAX_WAIT_SECONDS));
347    loop {
348        let (reader, block) = (state.clone(), block_id.clone());
349        let (after, gen, max_lines) = (req.after, req.gen.clone(), max);
350        let read = tokio::task::spawn_blocking(move || read_lines(&reader, &block, after, gen.as_deref(), max_lines))
351            .await
352            .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents watch: {e}")))?
353            .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents watch {}: {e}", target.name)))?;
354        if !read.lines.lines.is_empty()
355            || read.lines.more
356            || read.reset
357            || read.archived
358            || tokio::time::Instant::now() >= deadline
359            || req.after.is_none()
360        {
361            let turn_active = crate::backend::blockcontroller::get_block_controller_status(&block_id).is_some_and(|s| s.turn_active);
362            let now = agentmux_common::time::now_ms_u64();
363            let runtime = crate::server::agent_runtime::list(state, now).into_iter().find(|r| r.agent_id == target.agent_id);
364            return Ok(json!({
365                "agent": target.name, "agent_id": target.agent_id, "block_id": block_id,
366                "lines": read.lines.lines, "next": read.lines.next, "gen": read.gen, "more": read.lines.more, "reset": read.reset,
367                "turn_active": turn_active,
368                "runtime": runtime.map(|r| json!({ "state": r.state, "desired": r.desired })),
369            }));
370        }
371        tokio::time::sleep(POLL_EVERY).await;
372    }
373}
374
375pub(crate) async fn handle_agent_watch(
376    State(state): State<AppState>,
377    caller: Option<Extension<Caller>>,
378    Json(req): Json<WatchRequest>,
379) -> Response {
380    let caller = caller.map(|Extension(c)| c);
381    let result = async {
382        actor_of(&state, caller.as_ref(), "watch")?;
383        watch(&state, &req).await
384    }
385    .await;
386    match result {
387        Ok(body) => Json(body).into_response(),
388        Err(r) => (r.status, Json(json!({ "error": r.message }))).into_response(),
389    }
390}
391
392#[cfg(test)]
393#[path = "tests/agent_watch_tests.rs"]
394mod tests;