use std::borrow::Cow;
use std::fmt::{self, Display};
use std::time::{Duration, Instant};
use aither_core::llm::{CommandOutcome, Tool, ToolContext, ToolResult};
use askama::Template;
use executor_core::{Executor, Task};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::job_registry::{JobRegistry, JobStatus};
use crate::output::{MediaResolution, OutputFormat};
use crate::permission::PermissionHandler;
use crate::terminal::{Configured, JobAlert, TerminalArgs, TerminalExecutionMode, TerminalTool};
const MAX_TIMEOUT_SECS: u64 = 7200;
const fn default_interval_secs() -> u64 {
10
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct MonitorArgs {
pub source: MonitorSource,
#[serde(default = "default_interval_secs")]
pub interval_secs: u64,
#[serde(default)]
pub filter: Option<String>,
#[serde(default)]
pub stop_on: Option<String>,
#[serde(default)]
pub kill_on_stop: bool,
#[serde(default)]
pub stall_secs: Option<u64>,
pub timeout_secs: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum MonitorSource {
Command {
command: String,
#[serde(default)]
language: MonitorLanguage,
},
File {
file: String,
},
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum MonitorLanguage {
#[default]
Shell,
Python,
}
#[derive(Debug, Clone)]
pub struct MonitorIncrement {
pub task_id: String,
pub lines: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct MonitorStalled {
pub task_id: String,
pub stall_secs: u64,
}
#[derive(Debug, Clone)]
pub struct MonitorEnded {
pub task_id: String,
pub end: MonitorEnd,
}
#[derive(Debug, Clone)]
pub enum MonitorEnd {
Exited {
exit_code: i32,
},
StopMatched {
line: String,
},
TimedOut,
Killed,
Failed {
error: String,
},
Lost,
}
#[derive(Debug)]
pub enum MonitorRefusal {
TimeoutOutOfRange,
IntervalTooSmall,
BadRegex {
argument: &'static str,
reason: String,
},
UnreadableFile {
file: String,
},
StartFailed {
reason: String,
},
}
#[derive(Template)]
#[template(path = "monitor_refused.txt", escape = "none")]
struct MonitorRefusedTemplate<'a> {
reason: &'a str,
}
impl Display for MonitorRefusal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let reason = match self {
Self::TimeoutOutOfRange => {
format!("timeout_secs must be between 1 and {MAX_TIMEOUT_SECS}")
}
Self::IntervalTooSmall => "interval_secs must be at least 1".to_string(),
Self::BadRegex { argument, reason } => {
format!("{argument} is not a valid regex: {reason}")
}
Self::UnreadableFile { file } => format!(
"`{file}` is not readable inside the sandbox: give a path under the working directory or a readable mount"
),
Self::StartFailed { reason } => reason.clone(),
};
let rendered = MonitorRefusedTemplate { reason: &reason }
.render()
.map_err(|_| fmt::Error)?;
f.write_str(&rendered)
}
}
impl std::error::Error for MonitorRefusal {}
struct Watch {
task_id: String,
registry: JobRegistry,
alerts: async_channel::Sender<JobAlert>,
interval: Duration,
deadline: Instant,
stall: Option<Duration>,
filter: Option<regex::Regex>,
stop_on: Option<regex::Regex>,
kill_on_stop: bool,
}
pub struct MonitorTool<P, E> {
terminal: TerminalTool<P, E, Configured>,
}
impl<P, E> MonitorTool<P, E> {
#[must_use]
pub const fn new(terminal: TerminalTool<P, E, Configured>) -> Self {
Self { terminal }
}
}
impl<P, E> std::fmt::Debug for MonitorTool<P, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("MonitorTool")
}
}
fn single_quote(text: &str) -> String {
format!("'{}'", text.replace('\'', r"'\''"))
}
impl<P: PermissionHandler + 'static, E: Executor + Clone + 'static> MonitorTool<P, E> {
fn job_script(&self, source: &MonitorSource) -> Result<String, MonitorRefusal> {
match source {
MonitorSource::Command { command, language } => {
if command.trim().is_empty() {
return Err(MonitorRefusal::StartFailed {
reason: "command must not be empty".to_string(),
});
}
Ok(match language {
MonitorLanguage::Shell => command.clone(),
MonitorLanguage::Python => format!(
"python3 - <<'__AITHER_MONITOR_PY__'\n{command}\n__AITHER_MONITOR_PY__"
),
})
}
MonitorSource::File { file } => {
let mut path = std::path::PathBuf::from(file);
if path.is_relative() {
path = self.terminal.working_dir().join(path);
}
let readable = std::fs::metadata(&path).is_ok_and(|meta| meta.is_file())
&& (path.starts_with(self.terminal.working_dir())
|| self
.terminal
.grants()
.snapshot()
.readable
.iter()
.any(|dir| path.starts_with(dir)));
if !readable {
return Err(MonitorRefusal::UnreadableFile { file: file.clone() });
}
Ok(format!(
"tail -Fn0 {}",
single_quote(&path.to_string_lossy())
))
}
}
}
}
impl<P, E> Tool for MonitorTool<P, E>
where
P: PermissionHandler + 'static,
E: Executor + Clone + 'static,
{
fn name(&self) -> Cow<'static, str> {
"monitor".into()
}
fn description(&self) -> Cow<'static, str> {
"Watch a command or a file and receive its new output as it arrives. \
The source runs as a background job under the same sandbox as `terminal`; \
non-empty increments are delivered at turn boundaries or wake an idle agent. \
`source` is `{\"command\": <source>, \"language\": \"shell\"|\"python\"}` or \
`{\"file\": <path>}`. `timeout_secs` is required (max 7200). Options: \
`interval_secs` (default 10), `filter` regex, `stop_on` regex, `kill_on_stop`, \
`stall_secs`."
.into()
}
type Arguments = MonitorArgs;
type Res = ToolResult;
async fn call(
&self,
args: Self::Arguments,
_cx: ToolContext,
) -> aither_core::Result<Self::Res> {
if args.timeout_secs == 0 || args.timeout_secs > MAX_TIMEOUT_SECS {
return Err(MonitorRefusal::TimeoutOutOfRange.into());
}
if args.interval_secs == 0 {
return Err(MonitorRefusal::IntervalTooSmall.into());
}
let compile = |argument: &'static str, pattern: &Option<String>| {
pattern
.as_deref()
.map(|pattern| {
regex::Regex::new(pattern).map_err(|error| MonitorRefusal::BadRegex {
argument,
reason: error.to_string(),
})
})
.transpose()
};
let filter = compile("filter", &args.filter)?;
let stop_on = compile("stop_on", &args.stop_on)?;
let script = self.job_script(&args.source)?;
let description = match &args.source {
MonitorSource::Command { .. } => "monitored command".to_string(),
MonitorSource::File { file } => format!("monitor file {file}"),
};
let result = self
.terminal
.run_background(TerminalArgs {
description,
script,
mode: TerminalExecutionMode::Default,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 1,
raw: true,
timeout: (args.timeout_secs + 60).min(MAX_TIMEOUT_SECS),
background: true,
})
.await
.map_err(|error| MonitorRefusal::StartFailed {
reason: error.to_string(),
})?;
let task_id = match result.command().map(|command| &command.outcome) {
Some(CommandOutcome::Running { task_id, .. }) => task_id.clone(),
_ => {
return Err(MonitorRefusal::StartFailed {
reason: "the monitored job did not start detached".to_string(),
}
.into());
}
};
let watch = Watch {
task_id: task_id.clone(),
registry: self.terminal.job_registry(),
alerts: self.terminal.job_alert_sender(),
interval: Duration::from_secs(args.interval_secs),
deadline: Instant::now() + Duration::from_secs(args.timeout_secs),
stall: args.stall_secs.map(Duration::from_secs),
filter,
stop_on,
kill_on_stop: args.kill_on_stop,
};
self.terminal
.executor()
.spawn(async move { watch_task(watch).await })
.detach();
Ok(ToolResult::text(
MonitorStartedTemplate {
task_id: &task_id,
interval_secs: args.interval_secs,
}
.render()
.expect("monitor started template must render"),
))
}
}
#[derive(Template)]
#[template(path = "monitor_started.txt", escape = "none")]
struct MonitorStartedTemplate<'a> {
task_id: &'a str,
interval_secs: u64,
}
fn drain_lines(buffer: &mut Vec<u8>) -> Vec<String> {
let Some(last_nl) = buffer.iter().rposition(|byte| *byte == b'\n') else {
return Vec::new();
};
let chunk: Vec<u8> = buffer.drain(..=last_nl).collect();
String::from_utf8_lossy(&chunk)
.lines()
.map(ToString::to_string)
.collect()
}
async fn send(alerts: &async_channel::Sender<JobAlert>, alert: JobAlert) {
let _ = alerts.send(alert).await;
}
async fn watch_task(watch: Watch) {
let Watch {
task_id,
registry,
alerts,
interval,
deadline,
stall,
filter,
stop_on,
kill_on_stop,
} = watch;
let mut cursor = 0usize;
let mut remainder = Vec::new();
let mut last_output = Instant::now();
let mut stalled = false;
loop {
async_io::Timer::after(
interval
.min(deadline.saturating_duration_since(Instant::now()) + Duration::from_secs(1)),
)
.await;
let now = Instant::now();
let mut end = match registry.monitor_read(&task_id, cursor, usize::MAX).await {
Ok(delta) => {
cursor = delta.cursor;
remainder.extend_from_slice(&delta.bytes);
let mut stop = None;
let mut lines = Vec::new();
for line in drain_lines(&mut remainder) {
if stop_on.as_ref().is_some_and(|re| re.is_match(&line)) {
stop = Some(line);
break;
}
if filter.as_ref().is_none_or(|re| re.is_match(&line)) {
lines.push(line);
}
}
if !lines.is_empty() {
last_output = now;
send(
&alerts,
JobAlert::MonitorIncrement(MonitorIncrement {
task_id: task_id.clone(),
lines,
}),
)
.await;
}
if stop.is_some() {
last_output = now;
}
if let Some(line) = stop {
if kill_on_stop {
registry.kill_by_task_id(&task_id).await;
}
Some(MonitorEnd::StopMatched { line })
} else {
match delta.status {
JobStatus::Running => None,
JobStatus::Completed { exit_code } => {
Some(MonitorEnd::Exited { exit_code })
}
JobStatus::Failed { error } => Some(MonitorEnd::Failed { error }),
JobStatus::Killed => Some(MonitorEnd::Killed),
}
}
}
Err(_) => Some(MonitorEnd::Lost),
};
if end.is_none() && now >= deadline {
registry.kill_by_task_id(&task_id).await;
end = Some(MonitorEnd::TimedOut);
}
if let Some(end) = end {
send(
&alerts,
JobAlert::MonitorEnded(MonitorEnded { task_id, end }),
)
.await;
return;
}
if !stalled && stall.is_some_and(|stall| now.duration_since(last_output) >= stall) {
stalled = true;
send(
&alerts,
JobAlert::MonitorStalled(MonitorStalled {
task_id: task_id.clone(),
stall_secs: stall.map_or(0, |s| s.as_secs()),
}),
)
.await;
}
}
}