1use std::fs::{File, OpenOptions};
5use std::io::Read;
6use std::path::{Path, PathBuf};
7use std::process::{Command, Stdio};
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::{Arc, Mutex};
10use std::time::{Duration, Instant};
11
12use anyhow::{Context, Result, bail};
13use serde::{Deserialize, Serialize};
14
15use crate::proc::Quiet as _;
16use crate::talk::{self, Talks};
17
18pub const DEFAULT_TIMEOUT: u64 = 900;
20pub const MAX_TIMEOUT: u64 = 3600;
22pub const MAX_CONCURRENT: usize = 4;
24pub const OUTPUT_CAP: usize = 8192;
26
27#[derive(Debug, Serialize, Deserialize)]
28struct Job {
29 id: String,
30 talk: String,
31 cwd: PathBuf,
32 command: Vec<String>,
33 timeout: u64,
34 supervisor: Option<(u32, String)>,
35 child: Option<(u32, String)>,
36 result: Option<String>,
37 tail: String,
38 delivered: bool,
39}
40
41fn root(home: &Path) -> PathBuf {
42 home.join("chat-watches")
43}
44
45struct Lock(File);
46
47impl Drop for Lock {
48 fn drop(&mut self) {
49 unlock_file(&self.0);
50 }
51}
52
53fn open_lock(path: &Path) -> Result<File> {
54 Ok(OpenOptions::new()
55 .create(true)
56 .truncate(false)
57 .read(true)
58 .write(true)
59 .open(path)?)
60}
61
62fn lock(path: &Path) -> Result<Lock> {
63 let file = open_lock(path)?;
64 lock_file(&file, false)?;
65 Ok(Lock(file))
66}
67
68fn try_lock(path: &Path) -> Result<Option<Lock>> {
69 let file = open_lock(path)?;
70 if lock_file(&file, true)? {
71 Ok(Some(Lock(file)))
72 } else {
73 Ok(None)
74 }
75}
76
77#[cfg(unix)]
78fn lock_file(file: &File, immediate: bool) -> std::io::Result<bool> {
79 use std::os::fd::AsRawFd;
80 loop {
81 if unsafe {
82 libc::flock(
83 file.as_raw_fd(),
84 libc::LOCK_EX | if immediate { libc::LOCK_NB } else { 0 },
85 )
86 } == 0
87 {
88 return Ok(true);
89 }
90 let error = std::io::Error::last_os_error();
91 match error.kind() {
92 std::io::ErrorKind::Interrupted => continue,
93 std::io::ErrorKind::WouldBlock if immediate => return Ok(false),
94 _ => return Err(error),
95 }
96 }
97}
98
99#[cfg(unix)]
100fn unlock_file(file: &File) {
101 use std::os::fd::AsRawFd;
102 unsafe {
103 libc::flock(file.as_raw_fd(), libc::LOCK_UN);
104 }
105}
106
107#[cfg(windows)]
108fn lock_file(file: &File, immediate: bool) -> std::io::Result<bool> {
109 use std::os::windows::io::AsRawHandle;
110 windows::lock_file(file.as_raw_handle(), immediate)
111}
112
113#[cfg(windows)]
114fn unlock_file(file: &File) {
115 use std::os::windows::io::AsRawHandle;
116 windows::unlock_file(file.as_raw_handle());
117}
118
119fn load(dir: &Path) -> Result<Job> {
120 Ok(serde_json::from_slice(&std::fs::read(
121 dir.join("job.json"),
122 )?)?)
123}
124
125fn save(dir: &Path, job: &Job) -> Result<()> {
126 let tmp = dir.join("job.tmp");
127 std::fs::write(&tmp, serde_json::to_vec(job)?)?;
128 std::fs::rename(tmp, dir.join("job.json"))?;
129 Ok(())
130}
131
132fn directories(home: &Path) -> Result<Vec<PathBuf>> {
133 Ok(std::fs::read_dir(root(home))?
134 .filter_map(Result::ok)
135 .map(|e| e.path())
136 .filter(|p| {
137 p.is_dir()
138 && !p
139 .file_name()
140 .is_some_and(|n| n.to_string_lossy().starts_with('.'))
141 })
142 .collect())
143}
144
145pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<String> {
147 if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
148 bail!("talk watch requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
149 }
150 let t = talks.get(run)?;
151 if t.id != run || !t.status.open() {
152 bail!("talk watch requires the exact id of an open conversation");
153 }
154 Ok(t.id)
155}
156
157pub fn start(
160 home: &Path,
161 talks: &Talks,
162 run: &str,
163 node: &str,
164 command: Vec<String>,
165 timeout: u64,
166) -> Result<String> {
167 let talk = authorize(talks, run, node)?;
168 if command.is_empty() || !(1..=MAX_TIMEOUT).contains(&timeout) {
169 bail!("watch needs a command and a timeout between 1 and {MAX_TIMEOUT} seconds");
170 }
171 std::fs::create_dir_all(root(home))?;
172 let _store = lock(&root(home).join("store.lock"))?;
173 let active = directories(home)?
174 .iter()
175 .try_fold(0, |n, dir| -> Result<usize> {
176 Ok(n + usize::from(load(dir)?.result.is_none()))
177 })?;
178 if active >= MAX_CONCURRENT {
179 bail!("at most {MAX_CONCURRENT} chat watches may run concurrently");
180 }
181 let id = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
182 let dir = root(home).join(&id);
183 let staging = root(home).join(format!(".new-{id}"));
184 std::fs::create_dir(&staging)?;
185 let mut job = Job {
186 id: id.clone(),
187 talk,
188 cwd: std::env::current_dir()?,
189 command,
190 timeout,
191 supervisor: None,
192 child: None,
193 result: None,
194 tail: String::new(),
195 delivered: false,
196 };
197 save(&staging, &job)?;
198 std::fs::rename(&staging, &dir)?;
199 let mut cmd = Command::new(std::env::current_exe()?);
200 cmd.arg("talk")
201 .arg("watch-run")
202 .arg(home)
203 .arg(&id)
204 .env_remove("MAGI_RUN")
205 .env_remove("MAGI_NODE")
206 .stdin(Stdio::null())
207 .stdout(Stdio::null())
208 .stderr(Stdio::null());
209 #[cfg(unix)]
210 {
211 use std::os::unix::process::CommandExt;
212 unsafe {
214 cmd.pre_exec(|| {
215 if libc::setsid() < 0 {
216 return Err(std::io::Error::last_os_error());
217 }
218 Ok(())
219 });
220 }
221 }
222 #[cfg(windows)]
223 {
224 use std::os::windows::process::CommandExt;
225 cmd.creation_flags(0x0000_0008 | 0x0000_0200);
228 }
229 let mut supervisor = match cmd.spawn() {
230 Ok(child) => child,
231 Err(e) => {
232 job.result = Some(format!("supervisor startup failed: {e}"));
233 save(&dir, &job)?;
234 return Err(e.into());
235 }
236 };
237 let deadline = Instant::now() + Duration::from_secs(10);
238 loop {
239 let fresh = load(&dir)?;
240 if fresh.supervisor.is_some() && (fresh.child.is_some() || fresh.result.is_some()) {
241 std::thread::spawn(move || {
244 let _ = supervisor.wait();
245 });
246 return Ok(id);
247 }
248 if supervisor.try_wait()?.is_some() || Instant::now() >= deadline {
249 let _ = supervisor.kill();
250 let _ = supervisor.wait();
251 bail!(
252 "watch supervisor did not acknowledge startup; its durable reservation will be reconciled"
253 );
254 }
255 std::thread::sleep(Duration::from_millis(20));
256 }
257}
258
259fn identity(pid: u32) -> Result<(u32, String)> {
260 Ok((
261 pid,
262 crate::proc::process_started_at(pid).context("cannot identify watch process")?,
263 ))
264}
265
266fn append_tail(tail: &mut Vec<u8>, bytes: &[u8]) {
267 tail.extend_from_slice(bytes);
268 if tail.len() > OUTPUT_CAP {
269 tail.drain(..tail.len() - OUTPUT_CAP);
270 }
271}
272
273fn reader(
274 mut pipe: impl Pipe + Send + 'static,
275 tail: Arc<Mutex<Vec<u8>>>,
276 stopped: Arc<AtomicBool>,
277) -> std::thread::JoinHandle<()> {
278 std::thread::spawn(move || {
279 let mut chunk = [0; 4096];
280 if pipe.nonblocking().is_err() {
281 return;
282 }
283 let mut final_budget = None;
284 loop {
285 if stopped.load(Ordering::Acquire) {
288 let remaining = final_budget.get_or_insert(OUTPUT_CAP * 16);
289 if *remaining == 0 {
290 break;
291 }
292 }
293 match pipe.read_available(&mut chunk) {
294 Ok(0) => break,
295 Ok(n) => {
296 append_tail(
297 &mut tail.lock().unwrap_or_else(|e| e.into_inner()),
298 &chunk[..n],
299 );
300 if let Some(remaining) = final_budget.as_mut() {
301 *remaining = remaining.saturating_sub(n);
302 }
303 }
304 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
305 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
306 if stopped.load(Ordering::Acquire) {
307 break;
308 }
309 std::thread::sleep(Duration::from_millis(10));
310 }
311 Err(_) => break,
312 }
313 }
314 })
315}
316
317#[cfg(unix)]
318fn kill_group(pid: u32) {
319 if let Ok(pid) = libc::pid_t::try_from(pid) {
320 unsafe {
323 libc::kill(-pid, libc::SIGKILL);
324 }
325 }
326}
327
328#[cfg(not(unix))]
329fn kill_group(_pid: u32) {}
330
331pub fn supervise(home: &Path, id: &str) -> Result<()> {
334 if id.contains(['/', '\\']) || id == "." || id == ".." {
335 bail!("invalid watch id");
336 }
337 let dir = root(home).join(id);
338 let _lease = lock(&dir.join("lease.lock"))?;
339 let mut job = load(&dir)?;
340 if job.result.is_some() || job.supervisor.is_some() {
341 return Ok(());
342 }
343 job.supervisor = Some(identity(std::process::id())?);
344 save(&dir, &job)?;
345 let mut cmd = Command::new(std::env::current_exe()?);
346 cmd.arg("talk")
347 .arg("watch-exec")
348 .arg(home)
349 .arg(id)
350 .current_dir(&job.cwd)
351 .env_remove("MAGI_RUN")
352 .env_remove("MAGI_NODE")
353 .stdin(Stdio::null())
354 .stdout(Stdio::piped())
355 .stderr(Stdio::piped());
356 cmd.quiet();
357 #[cfg(unix)]
358 {
359 use std::os::unix::process::CommandExt;
360 cmd.process_group(0);
361 }
362 let mut child = match cmd.spawn() {
363 Ok(c) => c,
364 Err(e) => {
365 job.result = Some(format!("startup failed: {e}"));
366 save(&dir, &job)?;
367 return Ok(());
368 }
369 };
370 #[cfg(windows)]
371 let containment = match windows::Containment::assign(&child) {
372 Ok(c) => c,
373 Err(e) => {
374 let _ = child.kill();
375 let _ = child.wait();
376 return Err(e.into());
377 }
378 };
379 let registered = identity(child.id()).and_then(|pid| {
381 job.child = Some(pid);
382 save(&dir, &job)
383 });
384 if let Err(e) = registered {
385 kill_group(child.id());
386 #[cfg(windows)]
387 drop(containment);
388 let _ = child.wait();
389 return Err(e);
390 }
391 std::fs::write(dir.join("armed"), b"ready")?;
395 let tail = Arc::new(Mutex::new(Vec::new()));
396 let stopped = Arc::new(AtomicBool::new(false));
397 let out = reader(
398 child.stdout.take().context("missing stdout")?,
399 tail.clone(),
400 stopped.clone(),
401 );
402 let err = reader(
403 child.stderr.take().context("missing stderr")?,
404 tail.clone(),
405 stopped.clone(),
406 );
407 let deadline = Instant::now() + Duration::from_secs(job.timeout);
408 let outcome = loop {
409 match child.try_wait() {
410 Ok(Some(status)) => {
411 #[cfg(unix)]
412 {
413 use std::os::unix::process::ExitStatusExt;
414 break status.code().map_or_else(
415 || format!("terminated by signal {}", status.signal().unwrap_or(0)),
416 |code| format!("exited with status {code}"),
417 );
418 }
419 #[cfg(not(unix))]
420 break status.code().map_or_else(
421 || "terminated without an exit code".to_owned(),
422 |code| format!("exited with status {code}"),
423 );
424 }
425 Err(e) => break format!("result unknown: {e}"),
426 Ok(None) if Instant::now() >= deadline => {
427 break format!(
428 "timed out after {} second{}",
429 job.timeout,
430 if job.timeout == 1 { "" } else { "s" }
431 );
432 }
433 Ok(None) => std::thread::sleep(Duration::from_millis(20)),
434 }
435 };
436 kill_group(child.id());
437 #[cfg(windows)]
438 drop(containment);
439 let _ = child.wait();
440 stopped.store(true, Ordering::Release);
441 let _ = out.join();
442 let _ = err.join();
443 job.tail =
444 String::from_utf8_lossy(&tail.lock().unwrap_or_else(|e| e.into_inner())).into_owned();
445 job.result = Some(match std::fs::read_to_string(dir.join("spawn-error")) {
446 Ok(error) => format!("startup failed: {error}"),
447 Err(_) => outcome,
448 });
449 save(&dir, &job)
450}
451
452pub fn sweep(home: &Path, talks: &Talks) {
455 if !root(home).exists() {
456 return;
457 }
458 let sweep = || -> Result<()> {
459 let _store = lock(&root(home).join("store.lock"))?;
460 for dir in directories(home)? {
461 let Some(_lease) = try_lock(&dir.join("lease.lock"))? else {
462 continue;
463 };
464 let result = reconcile(&dir, talks);
465 if let Err(e) = result {
466 tracing::warn!("watch completion not queued: {e:#}");
467 }
468 }
469 Ok(())
470 };
471 if let Err(e) = sweep() {
472 tracing::warn!("watch sweep: {e:#}");
473 }
474}
475
476fn reconcile(dir: &Path, talks: &Talks) -> Result<()> {
477 let mut job = load(dir)?;
478 if job.delivered {
479 return Ok(());
480 }
481 if job.result.is_none() {
482 if let Some((pid, started)) = &job.child {
483 match (
484 crate::proc::pid_status(*pid),
485 crate::proc::process_started_at(*pid),
486 ) {
487 (Some(false), _) => kill_group(*pid),
488 (Some(true), Some(current)) if current == *started => kill_group(*pid),
489 (Some(true), Some(_)) => {} _ => return Ok(()), }
492 }
493 job.result =
494 Some("result unknown: supervisor was lost; job will not be restarted".to_owned());
495 save(dir, &job)?;
496 }
497 let gone = || {
500 matches!(
501 std::fs::symlink_metadata(talks.path_of(&job.talk)),
502 Err(error) if error.kind() == std::io::ErrorKind::NotFound
503 )
504 };
505 let mut t = match talks.get(&job.talk) {
506 Ok(t) if t.status.open() => t,
507 Ok(_) => {
508 job.delivered = true;
509 return save(dir, &job);
510 }
511 Err(_) if gone() => {
512 job.delivered = true;
513 return save(dir, &job);
514 }
515 Err(e) => return Err(e),
516 };
517 let (text, display) = crate::prompt::chat_watch_report(
518 &job.id,
519 job.result.as_deref().unwrap_or("unknown"),
520 &job.tail,
521 );
522 if let Err(e) = talk::queue_notice(
523 &mut t,
524 talks,
525 &text,
526 &format!("watch:{}:finished", job.id),
527 &|_| false,
528 None,
529 display,
530 ) {
531 match talks.get(&job.talk) {
532 Ok(t) if !t.status.open() => {}
533 Err(_) if gone() => {}
534 _ => return Err(e),
535 }
536 }
537 job.delivered = true;
538 save(dir, &job)
539}
540
541pub fn execute(home: &Path, id: &str) -> Result<()> {
544 #[cfg(unix)]
545 use std::os::unix::process::CommandExt;
546 if id.contains(['/', '\\']) || id == "." || id == ".." {
547 bail!("invalid watch id");
548 }
549 let dir = root(home).join(id);
550 let deadline = Instant::now() + Duration::from_secs(10);
551 loop {
552 let job = load(&dir)?;
553 let (pid, started) = job.supervisor.as_ref().context("missing supervisor")?;
554 if job.result.is_some()
555 || crate::proc::pid_status(*pid) == Some(false)
556 || crate::proc::process_started_at(*pid).is_some_and(|s| s != *started)
557 {
558 bail!("watch supervisor was lost before launch");
559 }
560 if dir.join("armed").exists() {
561 if job.child.as_ref() != Some(&identity(std::process::id())?) {
562 bail!("watch launch belongs to a different process");
563 }
564 let mut command = Command::new(&job.command[0]);
565 command
566 .args(&job.command[1..])
567 .current_dir(&job.cwd)
568 .env_remove("MAGI_RUN")
569 .env_remove("MAGI_NODE");
570 command.quiet();
571 #[cfg(unix)]
572 let error = command.exec();
573 #[cfg(windows)]
574 let error = match command.status() {
575 Ok(status) => std::process::exit(status.code().unwrap_or(1)),
576 Err(error) => error,
577 };
578 std::fs::write(dir.join("spawn-error"), error.to_string())?;
579 return Err(error.into());
580 }
581 if Instant::now() >= deadline {
582 bail!("watch launch was not armed");
583 }
584 std::thread::sleep(Duration::from_millis(10));
585 }
586}
587
588trait Pipe: Read {
589 fn nonblocking(&self) -> std::io::Result<()>;
590 fn read_available(&mut self, bytes: &mut [u8]) -> std::io::Result<usize>;
591}
592
593#[cfg(unix)]
594impl<T: Read + std::os::fd::AsRawFd> Pipe for T {
595 fn nonblocking(&self) -> std::io::Result<()> {
596 let fd = self.as_raw_fd();
597 unsafe {
599 let flags = libc::fcntl(fd, libc::F_GETFL);
600 if flags < 0 || libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 {
601 return Err(std::io::Error::last_os_error());
602 }
603 }
604 Ok(())
605 }
606 fn read_available(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
607 self.read(bytes)
608 }
609}
610
611#[cfg(windows)]
612impl<T: Read + std::os::windows::io::AsRawHandle> Pipe for T {
613 fn nonblocking(&self) -> std::io::Result<()> {
614 Ok(())
615 }
616 fn read_available(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
617 let available = windows::available(self.as_raw_handle())?;
618 if available == 0 {
619 return Err(std::io::ErrorKind::WouldBlock.into());
620 }
621 let count = bytes.len().min(available as usize);
622 self.read(&mut bytes[..count])
623 }
624}
625
626#[cfg(windows)]
629mod windows {
630 use std::ffi::c_void;
631 use std::os::windows::io::AsRawHandle;
632 type Handle = *mut c_void;
633 #[repr(C)]
634 #[derive(Default)]
635 struct Overlapped {
636 internal: usize,
637 internal_high: usize,
638 offset: u32,
639 offset_high: u32,
640 event: Handle,
641 }
642 #[repr(C)]
643 #[derive(Default)]
644 struct BasicLimits {
645 process_time: i64,
646 job_time: i64,
647 flags: u32,
648 min_working_set: usize,
649 max_working_set: usize,
650 active_processes: u32,
651 affinity: usize,
652 priority: u32,
653 scheduling: u32,
654 }
655 #[repr(C)]
656 #[derive(Default)]
657 struct ExtendedLimits {
658 basic: BasicLimits,
659 io: [u64; 6],
660 process_memory: usize,
661 job_memory: usize,
662 peak_process_memory: usize,
663 peak_job_memory: usize,
664 }
665 #[link(name = "kernel32")]
666 unsafe extern "system" {
667 fn LockFileEx(
668 file: Handle,
669 flags: u32,
670 reserved: u32,
671 bytes: u32,
672 bytes_high: u32,
673 overlapped: *mut Overlapped,
674 ) -> i32;
675 fn UnlockFileEx(
676 file: Handle,
677 reserved: u32,
678 bytes: u32,
679 bytes_high: u32,
680 overlapped: *mut Overlapped,
681 ) -> i32;
682 fn CreateJobObjectW(attributes: Handle, name: *const u16) -> Handle;
683 fn SetInformationJobObject(job: Handle, class: i32, info: *const c_void, size: u32) -> i32;
684 fn AssignProcessToJobObject(job: Handle, process: Handle) -> i32;
685 fn CloseHandle(handle: Handle) -> i32;
686 fn PeekNamedPipe(
687 pipe: Handle,
688 buffer: Handle,
689 size: u32,
690 read: *mut u32,
691 available: *mut u32,
692 left: *mut u32,
693 ) -> i32;
694 }
695 pub fn lock_file(file: Handle, immediate: bool) -> std::io::Result<bool> {
696 let mut overlapped = Overlapped::default();
697 if unsafe { LockFileEx(file, 2 | u32::from(immediate), 0, 1, 0, &mut overlapped) } != 0 {
698 return Ok(true);
699 }
700 let error = std::io::Error::last_os_error();
701 if immediate && error.raw_os_error() == Some(33) {
702 return Ok(false);
703 }
704 Err(error)
705 }
706 pub fn unlock_file(file: Handle) {
707 let mut overlapped = Overlapped::default();
708 unsafe {
709 UnlockFileEx(file, 0, 1, 0, &mut overlapped);
710 }
711 }
712 pub struct Containment(Handle);
713 impl Containment {
714 pub fn assign(child: &std::process::Child) -> std::io::Result<Self> {
715 unsafe {
716 let handle = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null());
717 if handle.is_null() {
718 return Err(std::io::Error::last_os_error());
719 }
720 let job = Self(handle);
721 let mut limits = ExtendedLimits::default();
722 limits.basic.flags = 0x2000; if SetInformationJobObject(
724 handle,
725 9,
726 std::ptr::from_ref(&limits).cast(),
727 std::mem::size_of::<ExtendedLimits>() as u32,
728 ) == 0
729 || AssignProcessToJobObject(handle, child.as_raw_handle()) == 0
730 {
731 return Err(std::io::Error::last_os_error());
732 }
733 Ok(job)
734 }
735 }
736 }
737 impl Drop for Containment {
738 fn drop(&mut self) {
739 unsafe {
740 CloseHandle(self.0);
741 }
742 }
743 }
744 pub fn available(pipe: Handle) -> std::io::Result<u32> {
745 let mut available = 0;
746 if unsafe {
747 PeekNamedPipe(
748 pipe,
749 std::ptr::null_mut(),
750 0,
751 std::ptr::null_mut(),
752 &mut available,
753 std::ptr::null_mut(),
754 )
755 } == 0
756 {
757 return Err(std::io::Error::last_os_error());
758 }
759 Ok(available)
760 }
761}
762
763#[cfg(test)]
764mod tests {
765 use super::*;
766
767 struct EndlessOutput;
768 impl Read for EndlessOutput {
769 fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
770 bytes.fill(b'x');
771 Ok(bytes.len())
772 }
773 }
774 impl Pipe for EndlessOutput {
775 fn nonblocking(&self) -> std::io::Result<()> {
776 Ok(())
777 }
778 fn read_available(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
779 self.read(bytes)
780 }
781 }
782
783 #[test]
784 fn stopped_readers_finish_even_if_an_inherited_pipe_never_stops_writing() {
785 let tail = Arc::new(Mutex::new(Vec::new()));
786 reader(EndlessOutput, tail.clone(), Arc::new(AtomicBool::new(true)))
787 .join()
788 .expect("reader finished");
789 assert_eq!(tail.lock().expect("tail").len(), OUTPUT_CAP);
790 }
791}