1#![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);
42const EXIT_CHECK: Duration = Duration::from_millis(50);
44
45#[derive(ToValue, FromValue, Schema, Debug, Clone, Copy, PartialEq, Eq, Default)]
47#[map(crate = ::ai6::guatiao, rename_all = "lowercase")]
48pub enum StderrMode {
49 #[default]
54 Tail,
55 Merge,
57 Drop,
59}
60
61#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq)]
63#[map(crate = ::ai6::guatiao)]
64pub struct PipeConfig {
65 #[map(default = StderrMode::Tail)]
67 pub stderr: StderrMode,
68 #[map(default = 65536)]
70 pub read_chunk_bytes: u64,
71 #[map(default = 200)]
75 pub drain_quiet_ms: u64,
76 #[map(default = 2_000)]
79 pub kill_wait_ms: u64,
80 #[map(default = 8192)]
82 pub stderr_tail_bytes: u64,
83 #[map(default = 65536)]
87 pub swept_fds: u64,
88 #[map(default = 32)]
91 pub tree_scans: u64,
92 pub run_as: Option<String>,
96 #[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#[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 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 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 pending: Mutex<Vec<u8>>,
179 eof: AtomicBool,
181 closed: AtomicBool,
183 quiet_since: Mutex<Option<Instant>>,
185 stdin: Mutex<PipeWriter>,
186 child: Mutex<Process>,
187 tree: ProcessTree,
188 _starter: Sender<()>,
190 exit: Mutex<Option<ExitInfo>>,
191 errors: Option<Arc<Mutex<ErrorTail>>>,
193 last_byte: AtomicU8,
195 drain_quiet: Duration,
198 kill_wait: Duration,
199}
200
201struct ErrorTail {
203 bytes: VecDeque<u8>,
204 keep: usize,
206 cut: bool,
208 closed: bool,
210 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 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
262pub(crate) struct Launch<'a> {
265 pub(crate) program: &'a str,
266 pub(crate) args: &'a [String],
267 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 #[cfg_attr(windows, allow(dead_code))]
275 pub(crate) swept_fds: u64,
276 #[cfg_attr(windows, allow(dead_code))]
278 pub(crate) tree_scans: usize,
279 #[cfg_attr(windows, allow(dead_code))]
281 pub(crate) run_as: Option<(u32, u32)>,
282}
283
284pub(crate) enum ErrorOutput {
286 Stdout,
288 Null,
290 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 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 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 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 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 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 let _ = lock(&self.child)?.kill();
550 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}