Skip to main content

ai6_terminal_pipe/
lib.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! `ai6-terminal-pipe`: the `pipe` terminal provider. The program gets plain pipes for its
6//! standard input and output, and no terminal, so a harness that checks whether its input is a
7//! terminal (Claude Code's `-p`) reads what is written to it, and its output arrives exactly as
8//! written. What differs per platform (starting the child alone, owning its process tree,
9//! finding the program) is in `unix.rs` and `windows.rs` behind one `os` interface.
10//!
11//! Output is read on a thread into a channel, so `read` can time out. The output ends when the
12//! program has exited and its output pipe is closed, or, when a process it left behind holds the
13//! pipe open, once the program has exited and nothing has arrived for 200 ms.
14
15#![doc = include_str!("../README.md")]
16#![deny(unsafe_code)]
17
18ai6::guatiao::providers!(Pipe);
19
20#[cfg(unix)]
21#[path = "unix.rs"]
22mod os;
23#[cfg(windows)]
24#[path = "windows.rs"]
25mod os;
26
27use std::collections::{BTreeMap, VecDeque};
28use std::io::{PipeReader, PipeWriter, Read, Write};
29use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
30use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
31use std::sync::{Arc, Mutex};
32use std::time::{Duration, Instant};
33
34use ai6::directorates::q::terminal::{ExitInfo, READ_TIMED_OUT, Spec, Terminal, TerminalRun};
35use ai6::guatiao::library::{Object, ProviderError};
36use ai6::guatiao::{FromValue, Provider, Schema, Status, ToValue, Value};
37
38use agentic_host_process::ProcessTree;
39use os::Process;
40
41const EXIT_POLL: Duration = Duration::from_millis(10);
42/// How often a waiting `read` asks whether the child has exited.
43const EXIT_CHECK: Duration = Duration::from_millis(50);
44
45/// What becomes of the program's standard error.
46#[derive(ToValue, FromValue, Schema, Debug, Clone, Copy, PartialEq, Eq, Default)]
47#[map(crate = ::ai6::guatiao, rename_all = "lowercase")]
48pub enum StderrMode {
49    /// Read through a pipe of its own, and only its last [`PipeConfig::stderr_tail_bytes`] (from the first
50    /// whole line in them) added to the output after the program's own output has ended, as
51    /// lines of their own. A JSON stream on standard output is never broken up by it, and what
52    /// the program said last on standard error, such as why it failed, is still read.
53    #[default]
54    Tail,
55    /// Written into the output stream, in the order the program wrote it.
56    Merge,
57    /// Discarded.
58    Drop,
59}
60
61/// `pipe` provider configuration; every field has a default.
62#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq)]
63#[map(crate = ::ai6::guatiao)]
64pub struct PipeConfig {
65    /// What becomes of standard error: `tail` (the default), `merge` or `drop`.
66    #[map(default = StderrMode::Tail)]
67    pub stderr: StderrMode,
68    /// Bytes of one read of the program's output. At least 1. Default 65536.
69    #[map(default = 65536)]
70    pub read_chunk_bytes: u64,
71    /// Milliseconds the output must stay quiet after the program has exited before `read`
72    /// reports its end, while a process the program left behind holds the output pipe. Default
73    /// 200.
74    #[map(default = 200)]
75    pub drain_quiet_ms: u64,
76    /// Milliseconds `kill` waits for the program and its process tree to have exited. Default
77    /// 2000.
78    #[map(default = 2_000)]
79    pub kill_wait_ms: u64,
80    /// Bytes of the end of standard error [`StderrMode::Tail`] keeps. Default 8192.
81    #[map(default = 8192)]
82    pub stderr_tail_bytes: u64,
83    /// On Unix, the highest descriptor the child marks close-on-exec where `close_range` is
84    /// not there to do it at once (before Linux 5.11, and on other systems): a soft
85    /// `RLIMIT_NOFILE` of a million would take as many calls. Default 65536. Windows ignores it.
86    #[map(default = 65536)]
87    pub swept_fds: u64,
88    /// On Unix, how many times the process table is read again for processes started
89    /// meanwhile when a tree is killed. Default 32. Windows ignores it.
90    #[map(default = 32)]
91    pub tree_scans: u64,
92    /// On Unix, the user the program runs as, which must not be uid 0; resolved when the provider
93    /// is built, and an unknown name refuses it. Unset runs it as the Station's own user, which a
94    /// Station running as root refuses unless `allow_root` is set. Windows has no uid and refuses it.
95    pub run_as: Option<String>,
96    /// Lets a Station that runs as root start programs as root, with no `run_as`: the operator's
97    /// weakening, which the startup log names. Default false.
98    #[map(default = false)]
99    pub allow_root: bool,
100}
101
102impl Default for PipeConfig {
103    fn default() -> Self {
104        Self {
105            stderr: StderrMode::Tail,
106            read_chunk_bytes: 65536,
107            drain_quiet_ms: 200,
108            kill_wait_ms: 2_000,
109            stderr_tail_bytes: 8192,
110            swept_fds: 65536,
111            tree_scans: 32,
112            run_as: None,
113            allow_root: false,
114        }
115    }
116}
117
118/// Starts programs on plain pipes, with no terminal.
119#[derive(Debug, Clone, Default, Provider)]
120#[provider(
121    Terminal,
122    id = "pipe",
123    name = "pipe",
124    crate = ::ai6::guatiao,
125    config = PipeConfig
126)]
127pub struct Pipe {
128    config: PipeConfig,
129}
130
131impl Pipe {
132    /// A provider with `config`.
133    pub fn new(config: PipeConfig) -> Self {
134        if config.allow_root {
135            eprintln!(
136                "ai6: terminal provider pipe: allow_root = true: a Station that runs as root starts \
137                 harnesses as root"
138            );
139        }
140        Self { config }
141    }
142}
143
144impl TryFrom<PipeConfig> for Pipe {
145    type Error = ProviderError;
146
147    fn try_from(config: PipeConfig) -> Result<Self, Self::Error> {
148        if config.read_chunk_bytes == 0 {
149            return Err(refuse(
150                Status::GUATIAO_ERR_BAD_VALUE,
151                "read_chunk_bytes is 0: a read of no bytes never sees any output",
152            ));
153        }
154        // A user that does not exist, or is uid 0, refuses the provider rather than a later start.
155        os::run_as(config.run_as.as_deref(), true)
156            .map_err(|reason| refuse(Status::GUATIAO_ERR_BAD_VALUE, reason))?;
157        Ok(Self::new(config))
158    }
159}
160
161impl Terminal for Pipe {
162    fn spawn(&self, spec: &Value) -> Result<Object<dyn TerminalRun>, ProviderError> {
163        let spec = Spec::from_value(spec).map_err(|e| refuse(Status::GUATIAO_ERR_BAD_VALUE, e))?;
164        let run_as = os::run_as(self.config.run_as.as_deref(), self.config.allow_root)
165            .map_err(|reason| refuse(Status::GUATIAO_ERR_BAD_VALUE, reason))?;
166        Ok(PipeRun::start(&spec, &self.config, run_as)?.into_object())
167    }
168
169    fn tty(&self) -> bool {
170        false
171    }
172}
173
174struct PipeRun {
175    pid: i64,
176    chunks: Mutex<Receiver<Vec<u8>>>,
177    /// The part of a chunk that did not fit the caller's buffer.
178    pending: Mutex<Vec<u8>>,
179    /// Whether `read` has reported the end of the output.
180    eof: AtomicBool,
181    /// Whether the output pipe has closed and everything it carried has been taken.
182    closed: AtomicBool,
183    /// Since when the child has been seen exited with no output arriving.
184    quiet_since: Mutex<Option<Instant>>,
185    stdin: Mutex<PipeWriter>,
186    child: Mutex<Process>,
187    tree: ProcessTree,
188    /// Dropped after the child is reaped, which ends the thread that started it.
189    _starter: Sender<()>,
190    exit: Mutex<Option<ExitInfo>>,
191    /// With [`StderrMode::Tail`], the end of standard error, until the output has ended.
192    errors: Option<Arc<Mutex<ErrorTail>>>,
193    /// The last byte `read` handed out, `\n` before any.
194    last_byte: AtomicU8,
195    /// How long the output must stay quiet after the child has exited, and how long `kill`
196    /// waits for it to have gone.
197    drain_quiet: Duration,
198    kill_wait: Duration,
199}
200
201/// The end of a program's standard error, as its own pipe delivers it.
202struct ErrorTail {
203    bytes: VecDeque<u8>,
204    /// How many of the last bytes are kept.
205    keep: usize,
206    /// Whether bytes were dropped from the front.
207    cut: bool,
208    /// Whether the pipe has closed.
209    closed: bool,
210    /// Whether the tail has been added to the output.
211    taken: bool,
212}
213
214impl ErrorTail {
215    fn new(keep: usize) -> Self {
216        Self {
217            bytes: VecDeque::new(),
218            keep,
219            cut: false,
220            closed: false,
221            taken: false,
222        }
223    }
224
225    fn push(&mut self, chunk: &[u8]) {
226        self.bytes.extend(chunk);
227        let over = self.bytes.len().saturating_sub(self.keep);
228        if over > 0 {
229            self.bytes.drain(..over);
230            self.cut = true;
231        }
232    }
233
234    /// The tail as whole lines, once: from the first line that was not cut, ending with a line
235    /// feed, and starting with one when the output it follows (whose last byte is `last`) ended
236    /// inside a line.
237    fn take(&mut self, last: u8) -> Vec<u8> {
238        if self.taken {
239            return Vec::new();
240        }
241        self.taken = true;
242        let mut bytes: Vec<u8> = std::mem::take(&mut self.bytes).into();
243        if self.cut
244            && let Some(at) = bytes.iter().position(|&byte| byte == b'\n')
245            && at + 1 < bytes.len()
246        {
247            bytes.drain(..=at);
248        }
249        if bytes.is_empty() {
250            return bytes;
251        }
252        if bytes.last() != Some(&b'\n') {
253            bytes.push(b'\n');
254        }
255        if last != b'\n' {
256            bytes.insert(0, b'\n');
257        }
258        bytes
259    }
260}
261
262/// A program to start, and the child's ends of its pipes, which `os::spawn` closes in this
263/// process once the child has them: until they close, the output never ends.
264pub(crate) struct Launch<'a> {
265    pub(crate) program: &'a str,
266    pub(crate) args: &'a [String],
267    /// The whole environment, or `None` for this process's.
268    pub(crate) env: Option<&'a BTreeMap<String, String>>,
269    pub(crate) cwd: Option<&'a str>,
270    pub(crate) stdin: PipeReader,
271    pub(crate) stdout: PipeWriter,
272    pub(crate) stderr: ErrorOutput,
273    /// The highest descriptor swept close-on-exec where `close_range` is not there (Unix).
274    #[cfg_attr(windows, allow(dead_code))]
275    pub(crate) swept_fds: u64,
276    /// How many times the process table is read again when a tree is killed (Unix).
277    #[cfg_attr(windows, allow(dead_code))]
278    pub(crate) tree_scans: usize,
279    /// The user and group ids the program runs as, resolved by `os::run_as` (Unix).
280    #[cfg_attr(windows, allow(dead_code))]
281    pub(crate) run_as: Option<(u32, u32)>,
282}
283
284/// Where the child's standard error goes.
285pub(crate) enum ErrorOutput {
286    /// Into standard output's pipe, which keeps the order the program wrote them in.
287    Stdout,
288    /// To the null device.
289    Null,
290    /// Into a pipe of its own.
291    Pipe(PipeWriter),
292}
293
294impl PipeRun {
295    fn start(
296        spec: &Spec,
297        config: &PipeConfig,
298        run_as: Option<(u32, u32)>,
299    ) -> Result<Self, ProviderError> {
300        let read_chunk = usize::try_from(config.read_chunk_bytes).unwrap_or(usize::MAX);
301        let stderr = config.stderr;
302        let (program, args) = spec
303            .argv
304            .split_first()
305            .ok_or_else(|| refuse(Status::GUATIAO_ERR_BAD_VALUE, "argv is empty"))?;
306        let (stdin, input) = std::io::pipe().map_err(internal)?;
307        let (mut output, writer) = std::io::pipe().map_err(internal)?;
308        let (error_output, error_reader) = match stderr {
309            StderrMode::Tail => {
310                let (reader, writer) = std::io::pipe().map_err(internal)?;
311                (ErrorOutput::Pipe(writer), Some(reader))
312            }
313            StderrMode::Merge => (ErrorOutput::Stdout, None),
314            StderrMode::Drop => (ErrorOutput::Null, None),
315        };
316        // A program may ask to be signalled when the thread that started it ends (Linux's
317        // PR_SET_PDEATHSIG, which the Grok CLI sets), and the caller's thread can end at any
318        // time, so the start happens on a thread of its own that lasts as long as the run.
319        let (started, start) = channel();
320        let (starter, keep) = channel::<()>();
321        let (swept_fds, tree_scans) = (
322            config.swept_fds,
323            usize::try_from(config.tree_scans).unwrap_or(usize::MAX),
324        );
325        let owned = (
326            program.clone(),
327            args.to_vec(),
328            spec.env.clone(),
329            spec.cwd.clone(),
330        );
331        std::thread::Builder::new()
332            .name("pipe-start".to_owned())
333            .spawn(move || {
334                let (program, args, env, cwd) = &owned;
335                let launch = Launch {
336                    program,
337                    args,
338                    env: env.as_ref(),
339                    cwd: cwd.as_deref(),
340                    stdin,
341                    stdout: writer,
342                    stderr: error_output,
343                    swept_fds,
344                    tree_scans,
345                    run_as,
346                };
347                let _ = started.send(os::spawn(launch));
348                let _ = keep.recv();
349            })
350            .map_err(internal)?;
351        let (child, tree) = start
352            .recv()
353            .map_err(internal)?
354            .map_err(|error| internal(format!("cannot start {program:?}: {error}")))?;
355        let pid = i64::from(child.id());
356        let stdin = input;
357
358        let errors = match error_reader {
359            Some(mut reader) => {
360                let errors = Arc::new(Mutex::new(ErrorTail::new(
361                    usize::try_from(config.stderr_tail_bytes).unwrap_or(usize::MAX),
362                )));
363                let tail = errors.clone();
364                std::thread::Builder::new()
365                    .name(format!("pipe-{pid}-stderr"))
366                    .spawn(move || {
367                        let mut buf = vec![0u8; read_chunk];
368                        loop {
369                            let read = reader.read(&mut buf);
370                            let Ok(mut tail) = tail.lock() else { break };
371                            match read {
372                                Ok(0) | Err(_) => {
373                                    tail.closed = true;
374                                    break;
375                                }
376                                Ok(n) => tail.push(&buf[..n]),
377                            }
378                        }
379                    })
380                    .map_err(internal)?;
381                Some(errors)
382            }
383            None => None,
384        };
385
386        let (tx, rx) = channel();
387        std::thread::Builder::new()
388            .name(format!("pipe-{pid}"))
389            .spawn(move || {
390                let mut buf = vec![0u8; read_chunk];
391                loop {
392                    match output.read(&mut buf) {
393                        Ok(0) | Err(_) => break,
394                        Ok(n) => {
395                            if tx.send(buf[..n].to_vec()).is_err() {
396                                break;
397                            }
398                        }
399                    }
400                }
401            })
402            .map_err(internal)?;
403
404        Ok(Self {
405            pid,
406            chunks: Mutex::new(rx),
407            pending: Mutex::new(Vec::new()),
408            eof: AtomicBool::new(false),
409            closed: AtomicBool::new(false),
410            quiet_since: Mutex::new(None),
411            stdin: Mutex::new(stdin),
412            child: Mutex::new(child),
413            tree,
414            _starter: starter,
415            exit: Mutex::new(None),
416            errors,
417            last_byte: AtomicU8::new(b'\n'),
418            drain_quiet: Duration::from_millis(config.drain_quiet_ms),
419            kill_wait: Duration::from_millis(config.kill_wait_ms),
420        })
421    }
422
423    /// The tail of standard error, once the output has ended, if it holds anything and has not
424    /// been taken: waits up to `drain_quiet_ms` for its pipe to close, which a process the
425    /// program left running may hold open.
426    fn error_tail(&self) -> Result<Option<Vec<u8>>, ProviderError> {
427        let Some(errors) = &self.errors else {
428            return Ok(None);
429        };
430        let deadline = Instant::now() + self.drain_quiet;
431        loop {
432            let mut tail = lock(errors)?;
433            if tail.taken {
434                return Ok(None);
435            }
436            if tail.closed || Instant::now() >= deadline {
437                let bytes = tail.take(self.last_byte.load(Ordering::Acquire));
438                return Ok((!bytes.is_empty()).then_some(bytes));
439            }
440            drop(tail);
441            std::thread::sleep(EXIT_POLL);
442        }
443    }
444
445    fn poll_exit(&self) -> Result<Option<ExitInfo>, ProviderError> {
446        let mut exit = lock(&self.exit)?;
447        if exit.is_none()
448            && let Some(status) = lock(&self.child)?.try_wait().map_err(internal)?
449        {
450            *exit = Some(status);
451        }
452        Ok(*exit)
453    }
454
455    /// Reports the end of the output; every later `read` reports it again.
456    fn end(&self) -> Result<i64, ProviderError> {
457        self.eof.store(true, Ordering::Release);
458        Ok(0)
459    }
460}
461
462impl TerminalRun for PipeRun {
463    fn pid(&self) -> i64 {
464        self.pid
465    }
466
467    fn read(&self, dst: &mut [u8], timeout_ms: i64) -> Result<i64, ProviderError> {
468        let mut pending = lock(&self.pending)?;
469        if pending.is_empty() {
470            if self.eof.load(Ordering::Acquire) {
471                return Ok(0);
472            }
473            let deadline = Instant::now() + Duration::from_millis(timeout_ms.max(0) as u64);
474            let chunks = lock(&self.chunks)?;
475            loop {
476                let now = Instant::now();
477                let exited = self.poll_exit()?.is_some();
478                if self.closed.load(Ordering::Acquire) {
479                    // The pipe has closed; the output ends with the program.
480                    if exited {
481                        if let Some(tail) = self.error_tail()? {
482                            *pending = tail;
483                            break;
484                        }
485                        return self.end();
486                    }
487                    if now >= deadline {
488                        return Ok(READ_TIMED_OUT);
489                    }
490                    std::thread::sleep(EXIT_POLL.min(deadline - now));
491                    continue;
492                }
493                let drained_at = match exited {
494                    true => Some(*lock(&self.quiet_since)?.get_or_insert(now) + self.drain_quiet),
495                    false => None,
496                };
497                let until = drained_at.unwrap_or(now + EXIT_CHECK).min(deadline);
498                match chunks.recv_timeout(until.saturating_duration_since(now)) {
499                    Ok(chunk) => {
500                        *lock(&self.quiet_since)? = None;
501                        *pending = chunk;
502                        break;
503                    }
504                    Err(RecvTimeoutError::Disconnected) => {
505                        self.closed.store(true, Ordering::Release);
506                    }
507                    Err(RecvTimeoutError::Timeout) => {
508                        let now = Instant::now();
509                        if drained_at.is_some_and(|at| now >= at) {
510                            if let Some(tail) = self.error_tail()? {
511                                *pending = tail;
512                                break;
513                            }
514                            return self.end();
515                        }
516                        if now >= deadline {
517                            return Ok(READ_TIMED_OUT);
518                        }
519                    }
520                }
521            }
522        }
523        let n = pending.len().min(dst.len());
524        dst[..n].copy_from_slice(&pending[..n]);
525        pending.drain(..n);
526        if let Some(&last) = dst[..n].last() {
527            self.last_byte.store(last, Ordering::Release);
528        }
529        Ok(n as i64)
530    }
531
532    fn write(&self, data: &[u8]) -> Result<(), ProviderError> {
533        let mut stdin = lock(&self.stdin)?;
534        stdin
535            .write_all(data)
536            .and_then(|()| stdin.flush())
537            .map_err(internal)
538    }
539
540    /// Nothing to resize: there is no terminal.
541    fn resize(&self, _rows: i64, _cols: i64) -> Result<(), ProviderError> {
542        Ok(())
543    }
544
545    fn kill(&self) -> Result<(), ProviderError> {
546        let leader_alive = lock(&self.exit)?.is_none();
547        self.tree.kill(leader_alive).map_err(internal)?;
548        // An error here means it already exited, which is what was asked.
549        let _ = lock(&self.child)?.kill();
550        // Killing is asynchronous; a caller may remove the working directory next.
551        let deadline = Instant::now() + self.kill_wait;
552        while (self.poll_exit()?.is_none() || self.tree.running()) && Instant::now() < deadline {
553            std::thread::sleep(EXIT_POLL);
554        }
555        Ok(())
556    }
557
558    fn exit_status(&self, timeout_ms: i64) -> Result<Value, ProviderError> {
559        let deadline = Instant::now() + Duration::from_millis(timeout_ms.max(0) as u64);
560        loop {
561            if let Some(exit) = self.poll_exit()? {
562                return exit.to_value().map_err(internal);
563            }
564            if Instant::now() >= deadline {
565                return ExitInfo {
566                    running: true,
567                    ..ExitInfo::default()
568                }
569                .to_value()
570                .map_err(internal);
571            }
572            std::thread::sleep(EXIT_POLL);
573        }
574    }
575}
576
577impl Drop for PipeRun {
578    fn drop(&mut self) {
579        let _ = TerminalRun::kill(self);
580        if let Ok(mut child) = self.child.lock() {
581            let _ = child.wait();
582        }
583    }
584}
585
586fn lock<T>(m: &Mutex<T>) -> Result<std::sync::MutexGuard<'_, T>, ProviderError> {
587    m.lock()
588        .map_err(|_| refuse(Status::GUATIAO_ERR_INTERNAL, "a run lock was poisoned"))
589}
590
591fn refuse(status: Status, message: impl std::fmt::Display) -> ProviderError {
592    ProviderError::new(status, &message.to_string())
593}
594
595fn internal(e: impl std::fmt::Display) -> ProviderError {
596    refuse(Status::GUATIAO_ERR_INTERNAL, e)
597}