1use 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
28const JOB_MARGIN: Duration = Duration::from_secs(60);
31
32#[derive(Debug, Clone)]
36pub struct MonitorSettings {
37 pub identity: crate::ToolIdentity,
39 pub max_timeout: LiveDuration,
41 pub default_interval: LiveDuration,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
47#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
48pub struct MonitorArgs {
49 pub source: MonitorSource,
51 #[serde(default)]
53 pub interval_secs: Option<u64>,
54 #[serde(default)]
56 pub filter: Option<String>,
57 #[serde(default)]
59 pub stop_on: Option<String>,
60 #[serde(default)]
62 pub kill_on_stop: bool,
63 #[serde(default)]
65 pub stall_secs: Option<u64>,
66 pub timeout_secs: u64,
68}
69
70#[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 Command {
77 command: String,
79 #[serde(default)]
81 interpreter: Interpreter,
82 },
83 File {
85 file: String,
87 },
88}
89
90#[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 #[must_use]
102 pub const fn agent(&self) -> &AgentPath {
103 &self.agent
104 }
105
106 #[must_use]
108 pub fn task_id(&self) -> &str {
109 &self.task_id
110 }
111
112 #[must_use]
114 pub fn lines(&self) -> &[String] {
115 &self.lines
116 }
117}
118
119#[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 #[must_use]
131 pub const fn agent(&self) -> &AgentPath {
132 &self.agent
133 }
134
135 #[must_use]
137 pub fn task_id(&self) -> &str {
138 &self.task_id
139 }
140
141 #[must_use]
143 pub const fn stall_secs(&self) -> u64 {
144 self.stall_secs
145 }
146}
147
148#[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 #[must_use]
160 pub const fn agent(&self) -> &AgentPath {
161 &self.agent
162 }
163
164 #[must_use]
166 pub fn task_id(&self) -> &str {
167 &self.task_id
168 }
169
170 #[must_use]
172 pub const fn end(&self) -> &MonitorEnd {
173 &self.end
174 }
175}
176
177#[derive(Debug, Clone)]
179pub enum MonitorEnd {
180 Exited {
182 exit_code: i32,
184 },
185 StopMatched {
187 line: String,
189 },
190 TimedOut,
192 Killed,
194 Failed {
196 error: String,
198 },
199 Lost,
201}
202
203#[derive(Debug)]
205pub enum MonitorRefusal {
206 TimeoutOutOfRange {
208 max: Duration,
210 },
211 IntervalTooSmall,
213 BadRegex {
215 argument: &'static str,
217 reason: String,
219 },
220 UnreadableFile {
222 file: String,
224 },
225 StartFailed {
227 reason: String,
229 },
230}
231
232struct Watch {
234 task_id: String,
235 _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
248pub struct MonitorTool<E> {
251 terminal: Shell<E>,
252 settings: MonitorSettings,
253}
254
255#[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 #[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
284fn single_quote(text: &str) -> String {
286 format!("'{}'", text.replace('\'', r"'\''"))
287}
288
289impl<E: Executor + Clone + 'static> MonitorTool<E> {
290 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 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 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 async fn start(&self, args: MonitorArgs) -> Result<String, MonitorRefusal> {
383 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 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
458fn 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}