1use 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
29const OUTPUT_FILE: &str = "output";
31const REPLAY_BYTES: i64 = 256 * 1024;
33const CHUNK_BYTES: i64 = 512 * 1024;
35const MAX_SCAN_BYTES: i64 = if cfg!(test) { 1024 * 1024 } else { 16 * 1024 * 1024 };
37const DEFAULT_LINES: usize = 100;
38const MAX_LINES: usize = 500;
39const MAX_LINE_CHARS: usize = 8 * 1024;
41const 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 #[serde(default)]
52 after: Option<u64>,
53 #[serde(default)]
57 gen: Option<String>,
58 #[serde(default)]
59 wait_seconds: Option<u64>,
60}
61
62#[derive(Debug, PartialEq)]
64struct Lines {
65 lines: Vec<String>,
66 next: u64,
68 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
79fn 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 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
118fn 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
132struct Source {
135 fs: std::sync::Arc<crate::backend::storage::filestore::FileStore>,
136 zone: String,
137 whole: Option<Vec<u8>>,
138 size: i64,
139 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 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 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 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 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
218fn 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
223const READ_ATTEMPTS: usize = 3;
225
226struct Read {
228 gen: Option<String>,
230 lines: Lines,
231 reset: bool,
233 archived: bool,
235}
236
237fn 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
259fn 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 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 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 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 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 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 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;