Skip to main content

aither_sandbox/
monitor.rs

1//! `monitor` — watch a command or a file and deliver its new output as it
2//! arrives.
3//!
4//! Following a running command or a growing log used to mean polling: sleep,
5//! read, sleep, read. `monitor` runs the source as an ordinary background
6//! job — same sandbox, same PID-only kills, `terminal_kill` reaches it — and
7//! a pump raises its new output as [`ShellEvent::MonitorIncrement`] facts,
8//! which the embedder merges into its agent's next turn boundary.
9
10use std::borrow::Cow;
11use std::fmt;
12use std::time::{Duration, Instant};
13
14use aither_core::llm::{AgentPath, Tool, ToolContext, ToolResult};
15use executor_core::{Executor, Task};
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18
19use crate::events::{EventSender, ShellEvent};
20use crate::interpreter::Interpreter;
21use crate::job_registry::{JobRegistry, JobStatus};
22use crate::limits::LiveDuration;
23use crate::output::MediaResolution;
24use crate::policy::SandboxMode;
25use crate::terminal::{Shell, ShellArgs};
26use crate::wording::{MonitorStarted, Refused};
27
28/// How long the watched job's own `timeout` bound outlasts the monitor's
29/// deadline.
30const JOB_MARGIN: Duration = Duration::from_secs(60);
31
32/// What an embedder decides about monitoring: the tool's name and description
33/// and the bounds of a watch. The bounds are live, so changing one reaches
34/// the tools already running.
35#[derive(Debug, Clone)]
36pub struct MonitorSettings {
37    /// The tool's name, description and argument descriptions.
38    pub identity: crate::ToolIdentity,
39    /// The longest a monitor may run.
40    pub max_timeout: LiveDuration,
41    /// The interval between output collections of a call that states none.
42    pub default_interval: LiveDuration,
43}
44
45// The arguments of the monitor tool, described by its `ToolIdentity`.
46#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
47#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
48pub struct MonitorArgs {
49    // What to watch.
50    pub source: MonitorSource,
51    // Seconds between output collections.
52    #[serde(default)]
53    pub interval_secs: Option<u64>,
54    // Only lines matching it are delivered.
55    #[serde(default)]
56    pub filter: Option<String>,
57    // The first line matching it ends the monitor.
58    #[serde(default)]
59    pub stop_on: Option<String>,
60    // Whether the watched process is killed when `stop_on` matches.
61    #[serde(default)]
62    pub kill_on_stop: bool,
63    // Seconds without new output after which the run is reported stuck.
64    #[serde(default)]
65    pub stall_secs: Option<u64>,
66    // The monitor's maximum lifetime in seconds.
67    pub timeout_secs: u64,
68}
69
70// The `monitor` source: a command's source text or a file path.
71#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
72#[serde(untagged)]
73#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
74pub enum MonitorSource {
75    // Source text run inside the sandbox.
76    Command {
77        // The source to run.
78        command: String,
79        // Its interpreter.
80        #[serde(default)]
81        interpreter: Interpreter,
82    },
83    // A file whose appended lines are followed inside the sandbox.
84    File {
85        // The path, resolved against the working directory when relative.
86        file: String,
87    },
88}
89
90/// New output a monitor collected since the last delivery.
91#[derive(Debug, Clone)]
92#[non_exhaustive]
93pub struct MonitorIncrement {
94    pub(crate) agent: AgentPath,
95    pub(crate) task_id: String,
96    pub(crate) lines: Vec<String>,
97}
98
99impl MonitorIncrement {
100    /// The agent whose shell raised the event.
101    #[must_use]
102    pub const fn agent(&self) -> &AgentPath {
103        &self.agent
104    }
105
106    /// Task id of the watched job.
107    #[must_use]
108    pub fn task_id(&self) -> &str {
109        &self.task_id
110    }
111
112    /// The new lines (filtered when the monitor has a `filter`).
113    #[must_use]
114    pub fn lines(&self) -> &[String] {
115        &self.lines
116    }
117}
118
119/// A monitor saw no new output for `stall_secs`.
120#[derive(Debug, Clone)]
121#[non_exhaustive]
122pub struct MonitorStalled {
123    pub(crate) agent: AgentPath,
124    pub(crate) task_id: String,
125    pub(crate) stall_secs: u64,
126}
127
128impl MonitorStalled {
129    /// The agent whose shell raised the event.
130    #[must_use]
131    pub const fn agent(&self) -> &AgentPath {
132        &self.agent
133    }
134
135    /// Task id of the watched job.
136    #[must_use]
137    pub fn task_id(&self) -> &str {
138        &self.task_id
139    }
140
141    /// How long it has produced nothing.
142    #[must_use]
143    pub const fn stall_secs(&self) -> u64 {
144        self.stall_secs
145    }
146}
147
148/// A monitor ended, and why.
149#[derive(Debug, Clone)]
150#[non_exhaustive]
151pub struct MonitorEnded {
152    pub(crate) agent: AgentPath,
153    pub(crate) task_id: String,
154    pub(crate) end: MonitorEnd,
155}
156
157impl MonitorEnded {
158    /// The agent whose shell raised the event.
159    #[must_use]
160    pub const fn agent(&self) -> &AgentPath {
161        &self.agent
162    }
163
164    /// Task id of the watched job.
165    #[must_use]
166    pub fn task_id(&self) -> &str {
167        &self.task_id
168    }
169
170    /// What ended it.
171    #[must_use]
172    pub const fn end(&self) -> &MonitorEnd {
173        &self.end
174    }
175}
176
177/// What ended a monitor.
178#[derive(Debug, Clone)]
179pub enum MonitorEnd {
180    /// The watched command exited.
181    Exited {
182        /// Its exit code.
183        exit_code: i32,
184    },
185    /// The first line matching `stop_on` arrived.
186    StopMatched {
187        /// The matching line.
188        line: String,
189    },
190    /// The monitor's `timeout_secs` passed.
191    TimedOut,
192    /// The watched job was killed (`terminal_kill` or the watchdog).
193    Killed,
194    /// The watched job failed.
195    Failed {
196        /// Its error.
197        error: String,
198    },
199    /// The job left the registry with no status.
200    Lost,
201}
202
203/// Why a `monitor` call was refused before anything started.
204#[derive(Debug)]
205pub enum MonitorRefusal {
206    /// `timeout_secs` was 0 or above the cap.
207    TimeoutOutOfRange {
208        /// The cap in force.
209        max: Duration,
210    },
211    /// `interval_secs` was 0.
212    IntervalTooSmall,
213    /// `filter` or `stop_on` is not a valid regex.
214    BadRegex {
215        /// Which argument failed to compile.
216        argument: &'static str,
217        /// The regex error.
218        reason: String,
219    },
220    /// A file source the sandbox may not read.
221    UnreadableFile {
222        /// The path as given.
223        file: String,
224    },
225    /// The monitored job would not start.
226    StartFailed {
227        /// The spawn error.
228        reason: String,
229    },
230}
231
232/// Everything a running monitor needs to know to watch and report.
233struct Watch {
234    task_id: String,
235    /// Keeps the job, and its word, until the pump reports its end, so a
236    /// completion the agent took first still leaves the pump its status.
237    _job: crate::Job,
238    registry: JobRegistry,
239    alerts: EventSender,
240    interval: Duration,
241    deadline: Instant,
242    stall: Option<Duration>,
243    filter: Option<regex::Regex>,
244    stop_on: Option<regex::Regex>,
245    kill_on_stop: bool,
246}
247
248/// The native `monitor` tool: starts the watched source as a background job
249/// and a pump that raises its increments as [`ShellEvent`]s.
250pub struct MonitorTool<E> {
251    terminal: Shell<E>,
252    settings: MonitorSettings,
253}
254
255/// Settings for tests, whose values stand for nothing.
256#[cfg(any(test, feature = "test-budgets"))]
257pub(crate) fn fixture_settings() -> MonitorSettings {
258    MonitorSettings {
259        identity: crate::ToolIdentity {
260            name: "monitor".into(),
261            description: "Watches a source.".into(),
262            arguments: crate::test_wording::argument_descriptions(),
263        },
264        max_timeout: LiveDuration::new(Duration::from_secs(7200)),
265        default_interval: LiveDuration::new(Duration::from_secs(10)),
266    }
267}
268
269impl<E> MonitorTool<E> {
270    /// Creates the tool bound to `terminal`, the configured terminal whose
271    /// jobs it watches.
272    #[must_use]
273    pub const fn new(terminal: Shell<E>, settings: MonitorSettings) -> Self {
274        Self { terminal, settings }
275    }
276}
277
278impl<E> std::fmt::Debug for MonitorTool<E> {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        f.write_str("MonitorTool")
281    }
282}
283
284/// The literal `'` inside a shell single-quoted string.
285fn single_quote(text: &str) -> String {
286    format!("'{}'", text.replace('\'', r"'\''"))
287}
288
289impl<E: Executor + Clone + 'static> MonitorTool<E> {
290    /// The seconds between collections a call asks for, the embedder's
291    /// default when it states none.
292    fn interval_secs(&self, args: &MonitorArgs) -> u64 {
293        args.interval_secs
294            .unwrap_or_else(|| self.settings.default_interval.get().as_secs())
295    }
296
297    /// The script the monitored job runs for `source` and its interpreter; an
298    /// unreadable file is refused before anything spawns.
299    fn job_script(&self, source: &MonitorSource) -> Result<(String, Interpreter), MonitorRefusal> {
300        match source {
301            MonitorSource::Command {
302                command,
303                interpreter,
304            } => {
305                if command.trim().is_empty() {
306                    return Err(MonitorRefusal::StartFailed {
307                        reason: "command must not be empty".to_string(),
308                    });
309                }
310                Ok((command.clone(), *interpreter))
311            }
312            MonitorSource::File { file } => {
313                let mut path = std::path::PathBuf::from(file);
314                if path.is_relative() {
315                    path = self.terminal.working_dir().join(path);
316                }
317                let readable = std::fs::metadata(&path).is_ok_and(|meta| meta.is_file())
318                    && (path.starts_with(self.terminal.working_dir())
319                        || self
320                            .terminal
321                            .grants()
322                            .snapshot()
323                            .readable
324                            .iter()
325                            .any(|dir| path.starts_with(dir)));
326                if !readable {
327                    return Err(MonitorRefusal::UnreadableFile { file: file.clone() });
328                }
329                // `tail -F` follows appended lines and survives rotation
330                // (the name is reopened) and truncation.
331                Ok((
332                    format!("tail -Fn0 {}", single_quote(&path.to_string_lossy())),
333                    Interpreter::Shell,
334                ))
335            }
336        }
337    }
338}
339
340impl<E> Tool for MonitorTool<E>
341where
342    E: Executor + Clone + 'static,
343{
344    fn name(&self) -> Cow<'static, str> {
345        self.settings.identity.name.clone()
346    }
347
348    fn description(&self) -> Cow<'static, str> {
349        self.settings.identity.description.clone()
350    }
351
352    fn arguments_schema(&self) -> schemars::Schema {
353        self.settings
354            .identity
355            .describe(schemars::schema_for!(MonitorArgs))
356    }
357
358    type Arguments = MonitorArgs;
359    type Res = ToolResult;
360
361    async fn call(
362        &self,
363        args: Self::Arguments,
364        _cx: ToolContext,
365    ) -> aither_core::Result<Self::Res> {
366        let notices = self.terminal.wording();
367        let interval_secs = self.interval_secs(&args);
368        match self.start(args).await {
369            Ok(task_id) => Ok(ToolResult::text(notices.monitor_started(&MonitorStarted {
370                task_id: &task_id,
371                interval_secs,
372            }))),
373            Err(refusal) => {
374                Err(Refused::rendered(refusal, |refusal| notices.monitor_refusal(refusal)).into())
375            }
376        }
377    }
378}
379
380impl<E: Executor + Clone + 'static> MonitorTool<E> {
381    /// Starts the watched job and its pump; returns the job's task id.
382    async fn start(&self, args: MonitorArgs) -> Result<String, MonitorRefusal> {
383        // The pump owns the deadline and the job's own bound stays a margin
384        // past it, so a monitor is accepted only when the shell accepts that
385        // bound too.
386        let max_timeout = self
387            .settings
388            .max_timeout
389            .get()
390            .min(self.terminal.timeout_cap().saturating_sub(JOB_MARGIN));
391        if args.timeout_secs == 0 || args.timeout_secs > max_timeout.as_secs() {
392            return Err(MonitorRefusal::TimeoutOutOfRange { max: max_timeout });
393        }
394        let interval_secs = self.interval_secs(&args);
395        if interval_secs == 0 {
396            return Err(MonitorRefusal::IntervalTooSmall);
397        }
398        let compile = |argument: &'static str, pattern: &Option<String>| {
399            pattern
400                .as_deref()
401                .map(|pattern| {
402                    regex::Regex::new(pattern).map_err(|error| MonitorRefusal::BadRegex {
403                        argument,
404                        reason: error.to_string(),
405                    })
406                })
407                .transpose()
408        };
409        let filter = compile("filter", &args.filter)?;
410        let stop_on = compile("stop_on", &args.stop_on)?;
411        let (script, interpreter) = self.job_script(&args.source)?;
412        let description = match &args.source {
413            MonitorSource::Command { .. } => "monitored command".to_string(),
414            MonitorSource::File { file } => format!("monitor file {file}"),
415        };
416        let job = self
417            .terminal
418            .run_background(ShellArgs {
419                description,
420                script,
421                interpreter,
422                sandbox: SandboxMode::Sandboxed,
423                location: None,
424                resolution: MediaResolution::Auto,
425                max_lines: Some(1),
426                raw: true,
427                // The job's own watchdog stays a margin past the monitor's
428                // deadline, so the pump's kill — not the watchdog's — ends a
429                // timed-out run and the end reports `TimedOut`.
430                timeout: args.timeout_secs + JOB_MARGIN.as_secs(),
431                background: true,
432            })
433            .await
434            .map_err(|error| MonitorRefusal::StartFailed {
435                reason: error.to_string(),
436            })?;
437        let task_id = job.task_id().to_owned();
438        let watch = Watch {
439            _job: job,
440            task_id: task_id.clone(),
441            registry: self.terminal.job_registry(),
442            alerts: self.terminal.event_sender(),
443            interval: Duration::from_secs(interval_secs),
444            deadline: Instant::now() + Duration::from_secs(args.timeout_secs),
445            stall: args.stall_secs.map(Duration::from_secs),
446            filter,
447            stop_on,
448            kill_on_stop: args.kill_on_stop,
449        };
450        self.terminal
451            .executor()
452            .spawn(async move { watch_task(watch).await })
453            .detach();
454        Ok(task_id)
455    }
456}
457
458/// Trailing bytes of a line without its `\n` yet; kept across polls.
459fn drain_lines(buffer: &mut Vec<u8>) -> Vec<String> {
460    let Some(last_nl) = buffer.iter().rposition(|byte| *byte == b'\n') else {
461        return Vec::new();
462    };
463    let chunk: Vec<u8> = buffer.drain(..=last_nl).collect();
464    String::from_utf8_lossy(&chunk)
465        .lines()
466        .map(ToString::to_string)
467        .collect()
468}
469
470async fn send(alerts: &EventSender, alert: ShellEvent) {
471    let _ = alerts.send(alert).await;
472}
473
474#[allow(clippy::too_many_lines)]
475async fn watch_task(watch: Watch) {
476    let Watch {
477        task_id,
478        _job,
479        registry,
480        alerts,
481        interval,
482        deadline,
483        stall,
484        filter,
485        stop_on,
486        kill_on_stop,
487    } = watch;
488    let mut cursor = 0usize;
489    let mut remainder = Vec::new();
490    let mut last_output = Instant::now();
491    let mut stalled = false;
492    loop {
493        async_io::Timer::after(
494            interval
495                .min(deadline.saturating_duration_since(Instant::now()) + Duration::from_secs(1)),
496        )
497        .await;
498        let now = Instant::now();
499        let mut end = match registry.monitor_read(&task_id, cursor, usize::MAX).await {
500            Ok(delta) => {
501                cursor = delta.cursor;
502                remainder.extend_from_slice(&delta.bytes);
503                let mut stop = None;
504                let mut lines = Vec::new();
505                for line in drain_lines(&mut remainder) {
506                    if stop_on.as_ref().is_some_and(|re| re.is_match(&line)) {
507                        stop = Some(line);
508                        break;
509                    }
510                    if filter.as_ref().is_none_or(|re| re.is_match(&line)) {
511                        lines.push(line);
512                    }
513                }
514                if !lines.is_empty() {
515                    last_output = now;
516                    send(
517                        &alerts,
518                        ShellEvent::MonitorIncrement(MonitorIncrement {
519                            agent: alerts.agent().clone(),
520                            task_id: task_id.clone(),
521                            lines,
522                        }),
523                    )
524                    .await;
525                }
526                if stop.is_some() {
527                    last_output = now;
528                }
529                if let Some(line) = stop {
530                    if kill_on_stop {
531                        registry.kill_by_task_id(&task_id).await;
532                    }
533                    Some(MonitorEnd::StopMatched { line })
534                } else {
535                    match delta.status {
536                        JobStatus::Running => None,
537                        JobStatus::Completed { exit_code, .. } => {
538                            Some(MonitorEnd::Exited { exit_code })
539                        }
540                        JobStatus::Failed { error, .. } => Some(MonitorEnd::Failed { error }),
541                        JobStatus::Killed { .. } => Some(MonitorEnd::Killed),
542                    }
543                }
544            }
545            Err(_) => Some(MonitorEnd::Lost),
546        };
547        if end.is_none() && now >= deadline {
548            registry.kill_by_task_id(&task_id).await;
549            end = Some(MonitorEnd::TimedOut);
550        }
551        if let Some(end) = end {
552            send(
553                &alerts,
554                ShellEvent::MonitorEnded(MonitorEnded {
555                    agent: alerts.agent().clone(),
556                    task_id,
557                    end,
558                }),
559            )
560            .await;
561            return;
562        }
563        if !stalled && stall.is_some_and(|stall| now.duration_since(last_output) >= stall) {
564            stalled = true;
565            send(
566                &alerts,
567                ShellEvent::MonitorStalled(MonitorStalled {
568                    agent: alerts.agent().clone(),
569                    task_id: task_id.clone(),
570                    stall_secs: stall.map_or(0, |s| s.as_secs()),
571                }),
572            )
573            .await;
574        }
575    }
576}