1use std::collections::HashMap;
6use std::io::{Read, Seek, SeekFrom};
7use std::path::{Path, PathBuf};
8use std::sync::{Arc, Mutex};
9use std::time::{Duration, Instant};
10
11use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, Tool, ToolContext};
12use adk_devtools::{INLINE_OUTPUT_CHARS, OutputFile, OutputStore};
13use async_trait::async_trait;
14use serde_json::{Value, json};
15
16use super::background::{ShellStatus, ShellSupervisor};
17
18const WINDOW_BYTES: u64 = INLINE_OUTPUT_CHARS as u64 * 4;
21
22const MAX_RECORDS: usize = 4096;
24
25#[derive(Clone, Debug)]
27pub(crate) struct OutputRecord {
28 pub(crate) command: String,
29 pub(crate) started: Instant,
30 pub(crate) finished: Option<(Option<i32>, Duration)>,
32}
33
34#[derive(Debug)]
52pub struct ShellOutputs {
53 root: PathBuf,
54 next: Mutex<HashMap<PathBuf, u64>>,
56 records: Mutex<HashMap<(PathBuf, String), OutputRecord>>,
57}
58
59impl Default for ShellOutputs {
60 fn default() -> Self {
63 #[cfg(unix)]
64 let name = format!("adk-harness-output-{}", unsafe { libc::geteuid() });
66 #[cfg(not(unix))]
67 let name = "adk-harness-output".to_string();
68 Self::new(std::env::temp_dir().join(name))
69 }
70}
71
72impl ShellOutputs {
73 pub fn new(root: impl Into<PathBuf>) -> Self {
75 Self { root: root.into(), next: Mutex::default(), records: Mutex::default() }
76 }
77
78 pub fn session_dir(&self, app: &str, user: &str, session: &str) -> PathBuf {
80 let key = crate::fsutil::sha256_hex(&format!("{app}\u{1f}{user}\u{1f}{session}"));
81 self.root.join(&key[..32]).join("shells")
82 }
83
84 fn path_of(dir: &Path, id: &str) -> Option<PathBuf> {
87 (!id.is_empty() && id.len() <= 20 && id.bytes().all(|byte| byte.is_ascii_digit()))
88 .then(|| dir.join(format!("{id}.log")))
89 }
90
91 fn prepare(dir: &Path) -> std::io::Result<()> {
93 std::fs::create_dir_all(dir)?;
94 #[cfg(unix)]
95 {
96 use std::os::unix::fs::{MetadataExt, PermissionsExt};
97 let session = dir.parent().unwrap_or(dir);
98 for path in [dir, session, session.parent().unwrap_or(session)] {
99 let meta = std::fs::symlink_metadata(path)?;
100 let me = unsafe { libc::geteuid() };
102 if !meta.is_dir() || meta.uid() != me {
103 return Err(std::io::Error::other(format!(
104 "{} is not a directory this user owns",
105 path.display()
106 )));
107 }
108 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))?;
109 }
110 }
111 Ok(())
112 }
113
114 pub(crate) fn allocate(
116 &self,
117 app: &str,
118 user: &str,
119 session: &str,
120 command: &str,
121 ) -> std::io::Result<OutputFile> {
122 let dir = self.session_dir(app, user, session);
123 Self::prepare(&dir)?;
124 let mut next = self.next.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
125 let counter = next.entry(dir.clone()).or_insert_with(|| highest_id(&dir) + 1);
126 let (id, path, file) = loop {
128 let id = counter.to_string();
129 *counter += 1;
130 let path = dir.join(format!("{id}.log"));
131 let mut options = std::fs::File::options();
132 options.write(true).create_new(true);
133 #[cfg(unix)]
134 {
135 use std::os::unix::fs::OpenOptionsExt;
136 options.mode(0o600);
137 }
138 match options.open(&path) {
139 Ok(file) => break (id, path, file),
140 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
141 Err(error) => return Err(error),
142 }
143 };
144 drop(next);
145 let mut records = self.records.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
146 if records.len() >= MAX_RECORDS {
147 let oldest =
148 records.iter().min_by_key(|(_, record)| record.started).map(|(k, _)| k.clone());
149 if let Some(oldest) = oldest {
150 records.remove(&oldest);
151 }
152 }
153 records.insert(
154 (dir, id.clone()),
155 OutputRecord { command: command.to_string(), started: Instant::now(), finished: None },
156 );
157 Ok(OutputFile { id, path, file })
158 }
159
160 pub(crate) fn finish(
162 &self,
163 (app, user, session): (&str, &str, &str),
164 id: &str,
165 exit_code: Option<i32>,
166 duration: Duration,
167 ) {
168 let key = (self.session_dir(app, user, session), id.to_string());
169 let mut records = self.records.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
170 if let Some(record) = records.get_mut(&key) {
171 record.finished = Some((exit_code, duration));
172 }
173 }
174
175 pub(crate) fn record(
177 &self,
178 (app, user, session): (&str, &str, &str),
179 id: &str,
180 ) -> Option<OutputRecord> {
181 let key = (self.session_dir(app, user, session), id.to_string());
182 self.records.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key).cloned()
183 }
184
185 pub(crate) fn read(
191 &self,
192 (app, user, session): (&str, &str, &str),
193 id: &str,
194 slice: &Slice,
195 ) -> std::io::Result<OutputRead> {
196 let dir = self.session_dir(app, user, session);
197 let not_found =
198 || std::io::Error::new(std::io::ErrorKind::NotFound, format!("no output {id}"));
199 let path = Self::path_of(&dir, id).ok_or_else(not_found)?;
200 match std::fs::symlink_metadata(&path) {
202 Ok(meta) if meta.is_file() => {}
203 Ok(_) => return Err(not_found()),
204 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Err(not_found()),
205 Err(error) => return Err(error),
206 }
207 let mut file = std::fs::File::open(&path)?;
208 let total = file.metadata()?.len();
209 read_slice(&mut file, total, slice)
210 }
211}
212
213impl OutputStore for ShellOutputs {
214 fn create(&self, ctx: &dyn ToolContext, command: &str) -> std::io::Result<OutputFile> {
215 self.allocate(ctx.app_name(), ctx.user_id(), ctx.session_id(), command)
216 }
217}
218
219pub const SHELL_OUTPUT: &str = "shell_output";
227
228#[derive(Debug)]
252pub struct ShellOutputTool {
253 shells: Arc<ShellSupervisor>,
254}
255
256impl ShellOutputTool {
257 pub fn new(shells: Arc<ShellSupervisor>) -> Self {
259 Self { shells }
260 }
261}
262
263fn invalid(code: &'static str, message: impl Into<String>) -> AdkError {
264 AdkError::new(ErrorComponent::Tool, ErrorCategory::InvalidInput, code, message)
265}
266
267#[async_trait]
268impl Tool for ShellOutputTool {
269 fn name(&self) -> &str {
270 SHELL_OUTPUT
271 }
272
273 fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
275 adk_core::egress::ToolEgress::None
276 }
277
278 fn description(&self) -> &str {
279 "Read the output of a background shell by its shell_id, or the whole output of a bash \
280 call whose result was cut by its output_id. Returns the status, exit code, duration \
281 and at most 30,000 characters of the output: by default its end; offset and limit \
282 read bytes from a position, such as the bytes a cut result left out; tail_lines reads \
283 the last lines; pattern, a regular expression, returns the matching lines with their \
284 numbers."
285 }
286
287 fn parameters_schema(&self) -> Option<Value> {
288 Some(json!({
289 "type": "object",
290 "properties": {
291 "shell_id": { "type": "string", "description": "The shell_id or output_id a bash result named." },
292 "tail_lines": { "type": "integer", "minimum": 1, "description": "Read the last N lines." },
293 "offset": { "type": "integer", "minimum": 0, "description": "Read from this byte offset." },
294 "limit": { "type": "integer", "minimum": 1, "description": "With offset: how many bytes to read (default and most 30000 characters' worth)." },
295 "pattern": { "type": "string", "description": "Return only the lines matching this regular expression." }
296 },
297 "required": ["shell_id"]
298 }))
299 }
300
301 fn is_read_only(&self) -> bool {
302 true
303 }
304
305 fn is_concurrency_safe(&self) -> bool {
306 true
307 }
308
309 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
310 let id = match args.get("shell_id") {
311 Some(Value::String(id)) => id.trim().to_string(),
312 Some(Value::Number(id)) => id.to_string(),
313 _ => {
314 return Err(invalid("harness.shell_output.no_id", "shell_output needs a shell_id"));
315 }
316 };
317 let pattern = match args.get("pattern").and_then(Value::as_str) {
318 Some(pattern) => Some(regex::Regex::new(pattern).map_err(|error| {
319 invalid(
320 "harness.shell_output.bad_pattern",
321 format!("the pattern is not a valid regular expression: {error}"),
322 )
323 })?),
324 None => None,
325 };
326 let slice = Slice {
327 pattern,
328 offset: args.get("offset").and_then(Value::as_u64),
329 limit: args.get("limit").and_then(Value::as_u64),
330 tail_lines: args
331 .get("tail_lines")
332 .and_then(Value::as_u64)
333 .map(|n| usize::try_from(n).unwrap_or(usize::MAX)),
334 };
335 let session = (ctx.app_name(), ctx.user_id(), ctx.session_id());
336 let outputs = self.shells.outputs();
337 let read = outputs.read(session, &id, &slice).map_err(|error| {
338 if error.kind() == std::io::ErrorKind::NotFound {
339 AdkError::new(
340 ErrorComponent::Tool,
341 ErrorCategory::NotFound,
342 "harness.shell_output.unknown",
343 format!("this session has no output {id}"),
344 )
345 } else {
346 AdkError::tool(format!("output {id} could not be read: {error}"))
347 }
348 })?;
349 let key = (session.0.to_string(), session.1.to_string(), session.2.to_string());
350 let shell = self.shells.read(&key, &id).await;
351 let record = outputs.record(session, &id);
352 let mut result = json!({
353 "shell_id": id,
354 "total_bytes": read.total_bytes,
355 "output": read.text,
356 });
357 if slice.pattern.is_some() {
358 result["more_matches"] = json!(read.cut);
359 } else {
360 result["offset"] = json!(read.range.0);
361 result["next_offset"] = json!(read.range.1);
362 result["truncated"] = json!(read.cut);
363 }
364 let millis = |duration: Duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX);
365 match (shell, record) {
366 (Some(shell), _) => {
367 result["status"] = json!(shell.status.name());
368 result["command"] = json!(shell.command);
369 result["duration_ms"] = json!(millis(shell.elapsed));
370 match shell.status {
371 ShellStatus::Exited { exit_code } => result["exit_code"] = json!(exit_code),
372 ShellStatus::Killed { cause } => result["killed_by"] = json!(cause),
373 ShellStatus::Running => {}
374 }
375 }
376 (None, Some(record)) => {
377 result["command"] = json!(record.command);
378 match record.finished {
379 Some((exit_code, duration)) => {
380 result["status"] = json!("exited");
381 result["exit_code"] = json!(exit_code);
382 result["duration_ms"] = json!(millis(duration));
383 }
384 None => result["status"] = json!("running"),
385 }
386 }
387 (None, None) => result["status"] = json!("exited"),
388 }
389 Ok(result)
390 }
391}
392
393fn highest_id(dir: &Path) -> u64 {
395 std::fs::read_dir(dir)
396 .into_iter()
397 .flatten()
398 .flatten()
399 .filter_map(|entry| entry.file_name().to_str()?.strip_suffix(".log")?.parse::<u64>().ok())
400 .max()
401 .unwrap_or(0)
402}
403
404#[derive(Clone, Debug, Default)]
406pub(crate) struct Slice {
407 pub(crate) pattern: Option<regex::Regex>,
409 pub(crate) offset: Option<u64>,
411 pub(crate) limit: Option<u64>,
413 pub(crate) tail_lines: Option<usize>,
415}
416
417#[derive(Clone, Debug, PartialEq, Eq)]
419pub(crate) struct OutputRead {
420 pub(crate) text: String,
422 pub(crate) total_bytes: u64,
424 pub(crate) range: (u64, u64),
426 pub(crate) cut: bool,
428}
429
430fn read_slice(file: &mut std::fs::File, total: u64, slice: &Slice) -> std::io::Result<OutputRead> {
431 if let Some(pattern) = &slice.pattern {
432 return grep(file, total, pattern);
433 }
434 if let Some(offset) = slice.offset {
435 let offset = offset.min(total);
436 let limit = slice.limit.unwrap_or(INLINE_OUTPUT_CHARS as u64).min(WINDOW_BYTES);
437 let window = read_at(file, offset, limit.min(total - offset))?;
438 let skipped = if offset > 0 {
440 window.iter().take(3).take_while(|&&b| b & 0xC0 == 0x80).count()
441 } else {
442 0
443 };
444 let end = if offset + window.len() as u64 == total {
445 window.len()
446 } else {
447 complete_end(&window)
448 };
449 let body = &window[skipped..end.max(skipped)];
450 let used = prefix_len(body, INLINE_OUTPUT_CHARS);
451 let start = offset + skipped as u64;
452 return Ok(OutputRead {
453 text: String::from_utf8_lossy(&body[..used]).into_owned(),
454 total_bytes: total,
455 range: (start, start + used as u64),
456 cut: used < body.len(),
457 });
458 }
459 let start = total.saturating_sub(WINDOW_BYTES);
461 let window = read_at(file, start, total - start)?;
462 let skipped = if start > 0 {
463 window.iter().take(3).take_while(|&&b| b & 0xC0 == 0x80).count()
464 } else {
465 0
466 };
467 let window = &window[skipped..];
468 let mut from = suffix_start(window, INLINE_OUTPUT_CHARS);
469 let mut cut = false;
470 if let Some(lines) = slice.tail_lines {
471 let line_start = nth_line_from_end(window, lines);
473 let wanted = line_start.unwrap_or(0);
474 cut = wanted < from || (line_start.is_none() && start > 0);
475 from = from.max(wanted);
476 }
477 let begin = start + (skipped + from) as u64;
478 Ok(OutputRead {
479 text: String::from_utf8_lossy(&window[from..]).into_owned(),
480 total_bytes: total,
481 range: (begin, total),
482 cut,
483 })
484}
485
486fn grep(
488 file: &mut std::fs::File,
489 total: u64,
490 pattern: ®ex::Regex,
491) -> std::io::Result<OutputRead> {
492 use std::io::BufRead;
493 file.seek(SeekFrom::Start(0))?;
494 let mut reader = std::io::BufReader::new(file);
495 let mut text = String::new();
496 let mut chars = 0;
497 let mut cut = false;
498 let mut line = Vec::new();
499 let mut number = 0usize;
500 loop {
501 line.clear();
502 if reader.read_until(b'\n', &mut line)? == 0 {
503 break;
504 }
505 number += 1;
506 let decoded = String::from_utf8_lossy(&line);
507 let decoded = decoded.trim_end_matches(['\n', '\r']);
508 if !pattern.is_match(decoded) {
509 continue;
510 }
511 let entry = format!("{number}: {decoded}\n");
512 let length = entry.chars().count();
513 if chars + length > INLINE_OUTPUT_CHARS {
514 cut = true;
515 break;
516 }
517 chars += length;
518 text.push_str(&entry);
519 }
520 Ok(OutputRead { text, total_bytes: total, range: (0, total), cut })
521}
522
523fn read_at(file: &mut std::fs::File, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
524 file.seek(SeekFrom::Start(offset))?;
525 let mut buf = Vec::with_capacity(usize::try_from(len).unwrap_or(0));
526 file.take(len).read_to_end(&mut buf)?;
527 Ok(buf)
528}
529
530fn complete_end(bytes: &[u8]) -> usize {
532 let n = bytes.len();
533 for back in 1..=n.min(4) {
534 let byte = bytes[n - back];
535 if byte & 0xC0 == 0x80 {
536 continue;
537 }
538 let needs = match byte {
539 0xF0..=0xF7 => 4,
540 0xE0..=0xEF => 3,
541 0xC0..=0xDF => 2,
542 _ => 1,
543 };
544 return if needs > back { n - back } else { n };
545 }
546 n
547}
548
549fn nth_line_from_end(bytes: &[u8], lines: usize) -> Option<usize> {
552 if lines == 0 {
553 return Some(bytes.len());
554 }
555 let body = bytes.strip_suffix(b"\n").unwrap_or(bytes);
556 body.iter()
557 .enumerate()
558 .rev()
559 .filter(|(_, byte)| **byte == b'\n')
560 .nth(lines - 1)
561 .map(|(index, _)| index + 1)
562}
563
564fn char_count(bytes: &[u8]) -> usize {
566 bytes
567 .utf8_chunks()
568 .map(|chunk| chunk.valid().chars().count() + usize::from(!chunk.invalid().is_empty()))
569 .sum()
570}
571
572fn prefix_len(bytes: &[u8], chars: usize) -> usize {
574 let mut left = chars;
575 let mut at = 0;
576 for chunk in bytes.utf8_chunks() {
577 let valid = chunk.valid();
578 if let Some((index, _)) = valid.char_indices().nth(left) {
579 return at + index;
580 }
581 left -= valid.chars().count();
582 at += valid.len();
583 if !chunk.invalid().is_empty() {
584 if left == 0 {
585 return at;
586 }
587 left -= 1;
588 at += chunk.invalid().len();
589 }
590 }
591 at
592}
593
594fn suffix_start(bytes: &[u8], chars: usize) -> usize {
596 let total = char_count(bytes);
597 if chars >= total { 0 } else { prefix_len(bytes, total - chars) }
598}
599
600#[cfg(test)]
601mod tests {
602 use super::*;
603 use std::io::Write;
604
605 fn file_with(bytes: &[u8]) -> (tempfile::NamedTempFile, std::fs::File, u64) {
606 let mut temp = tempfile::NamedTempFile::new().unwrap();
607 temp.write_all(bytes).unwrap();
608 let file = temp.reopen().unwrap();
609 (temp, file, bytes.len() as u64)
610 }
611
612 fn numbered(lines: usize) -> String {
613 (0..lines).map(|i| format!("{i:015}\n")).collect()
614 }
615
616 #[test]
617 fn an_offset_reads_bytes_from_the_middle() {
618 let text = numbered(327_680);
619 let (_temp, mut file, total) = file_with(text.as_bytes());
620 let slice = Slice { offset: Some(2_621_440), limit: Some(32), ..Slice::default() };
621 let read = read_slice(&mut file, total, &slice).unwrap();
622 assert_eq!(
623 read,
624 OutputRead {
625 text: format!("{:015}\n{:015}\n", 163_840, 163_841),
626 total_bytes: total,
627 range: (2_621_440, 2_621_472),
628 cut: false,
629 }
630 );
631 }
632
633 #[test]
634 fn the_default_is_the_last_characters_and_tail_lines_the_last_lines() {
635 let text = numbered(10_000);
636 let (_temp, mut file, total) = file_with(text.as_bytes());
637 let read = read_slice(&mut file, total, &Slice::default()).unwrap();
638 assert_eq!(read.text, text[text.len() - INLINE_OUTPUT_CHARS..]);
639 let lines = Slice { tail_lines: Some(2), ..Slice::default() };
640 let read = read_slice(&mut file, total, &lines).unwrap();
641 assert_eq!(read.text, format!("{:015}\n{:015}\n", 9_998, 9_999));
642 assert_eq!(read.range, (total - 32, total));
643 }
644
645 #[test]
646 fn a_pattern_returns_numbered_matching_lines() {
647 let (_temp, mut file, total) = file_with(b"ok\nerror[E0308]: mismatched\nok\nerror: x\n");
648 let slice =
649 Slice { pattern: Some(regex::Regex::new("^error").unwrap()), ..Slice::default() };
650 let read = read_slice(&mut file, total, &slice).unwrap();
651 assert_eq!(read.text, "2: error[E0308]: mismatched\n4: error: x\n");
652 assert!(!read.cut);
653 }
654
655 #[test]
656 fn a_range_inside_characters_moves_to_their_boundaries() {
657 let text = "€".repeat(10);
658 let (_temp, mut file, total) = file_with(text.as_bytes());
659 let slice = Slice { offset: Some(1), limit: Some(7), ..Slice::default() };
660 let read = read_slice(&mut file, total, &slice).unwrap();
661 assert_eq!((read.text.as_str(), read.range), ("€", (3, 6)));
663 }
664
665 #[test]
666 fn ids_are_numbers_and_never_reuse_an_earlier_file() {
667 let root = tempfile::tempdir().unwrap();
668 let outputs = ShellOutputs::new(root.path());
669 let first = outputs.allocate("app", "alice", "s1", "make").unwrap();
670 assert_eq!(first.id, "1");
671 let again = ShellOutputs::new(root.path());
672 assert_eq!(again.allocate("app", "alice", "s1", "make").unwrap().id, "2");
673 assert_eq!(again.allocate("app", "bob", "s1", "make").unwrap().id, "1");
674 assert!(ShellOutputs::path_of(Path::new("/x"), "../1").is_none());
675 let error = outputs.read(("app", "bob", "s2"), "1", &Slice::default()).unwrap_err();
676 assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
677 }
678
679 #[cfg(unix)]
680 #[test]
681 fn a_link_in_place_of_an_output_is_not_followed() {
682 let root = tempfile::tempdir().unwrap();
683 let outputs = ShellOutputs::new(root.path());
684 let dir = outputs.session_dir("app", "alice", "s1");
685 ShellOutputs::prepare(&dir).unwrap();
686 let secret = root.path().join("secret");
687 std::fs::write(&secret, "token").unwrap();
688 std::os::unix::fs::symlink(&secret, dir.join("7.log")).unwrap();
689 let error = outputs.read(("app", "alice", "s1"), "7", &Slice::default()).unwrap_err();
690 assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
691 }
692}