1use std::io::{Read, Write};
23use std::path::{Path, PathBuf};
24use std::process::{Child, ChildStdin, Command, Stdio};
25use std::sync::atomic::{AtomicBool, Ordering};
26use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
27use std::sync::{Arc, Mutex};
28use std::time::{Duration, Instant};
29
30use crate::sandbox::Profile;
31
32pub const HARNESS_ENV: &[&str] = &[
39 "GEMINI_API_KEY",
40 "GOOGLE_API_KEY",
41 "ANTHROPIC_API_KEY",
42 "OLLAMA_API_KEY",
43 "OLLAMA_HOST",
44 "OPENAI_API_KEY",
45 "OPENAI_BASE_URL",
46 "OPENROUTER_API_KEY",
47];
48
49const CREDENTIAL_SEGMENTS: &[&str] = &[
50 "TOKEN",
51 "SECRET",
52 "SECRETS",
53 "PASSWORD",
54 "PASSWD",
55 "PASS",
56 "KEY",
57 "CREDENTIAL",
58 "CREDENTIALS",
59 "AUTH",
60 "COOKIE",
61 "SESSION",
62];
63
64const CREDENTIAL_NAMES: &[&str] = &[
67 "AWS_PROFILE",
68 "AWS_DEFAULT_PROFILE",
69 "SSH_AUTH_SOCK",
70 "SSH_AGENT_PID",
71];
72
73static PASS_ENV: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
74
75pub fn credential_like(name: &str, value: &str) -> bool {
78 let upper = name.to_ascii_uppercase();
79 if CREDENTIAL_NAMES.contains(&upper.as_str()) {
80 return true;
81 }
82 if upper
83 .split('_')
84 .any(|seg| CREDENTIAL_SEGMENTS.contains(&seg))
85 {
86 return true;
87 }
88 has_inline_credentials(value)
89}
90
91fn has_inline_credentials(value: &str) -> bool {
92 let mut rest = value;
93 while let Some(idx) = rest.find("://") {
94 let after_scheme = &rest[idx + 3..];
95 let len = after_scheme
96 .find(|c: char| c == '/' || c.is_whitespace())
97 .unwrap_or(after_scheme.len());
98 let authority_prefix = &after_scheme[..len];
99 if let Some((userinfo, _)) = authority_prefix.split_once('@') {
100 if let Some((_user, pass)) = userinfo.split_once(':') {
101 if !pass.is_empty() {
102 return true;
103 }
104 }
105 }
106 rest = after_scheme;
107 }
108 false
109}
110
111pub fn set_pass_env(names: Vec<String>) {
115 let _ = PASS_ENV.set(names);
116}
117
118pub fn is_pass_env(name: &str) -> bool {
120 PASS_ENV
121 .get()
122 .is_some_and(|passed| passed.iter().any(|p| p == name))
123}
124
125pub fn withheld_env() -> Vec<String> {
127 let mut withheld = Vec::new();
128 for (key, val) in std::env::vars_os() {
129 let name = key.to_string_lossy();
130 if HARNESS_ENV.iter().any(|&h| h == name.as_ref()) {
131 continue;
132 }
133 if name.starts_with("BLYTE_") {
134 continue;
135 }
136 if is_pass_env(&name) {
137 continue;
138 }
139 let value = val.to_string_lossy();
140 if credential_like(&name, &value) {
141 withheld.push(name.into_owned());
142 }
143 }
144 withheld.sort();
145 withheld.dedup();
146 withheld
147}
148
149pub const MODEL_SHELL_ENV: &str = "BLYTE_MODEL_SHELL";
150
151pub fn model_shell_refusal_message(command: &str) -> String {
152 format!(
153 "error: blyte {command} writes a record only the user or the harness may write, and cannot be run from a model's shell"
154 )
155}
156
157fn scrub_harness(cmd: &mut Command) {
158 cmd.env_remove(MODEL_SHELL_ENV);
159 for name in HARNESS_ENV {
160 cmd.env_remove(name);
161 }
162 for (name, _) in std::env::vars_os() {
163 let n = name.to_string_lossy();
164 if n.starts_with("BLYTE_") && n != "BLYTE_SESSION" {
165 cmd.env_remove(&name);
166 }
167 }
168}
169
170fn scrub(cmd: &mut Command) {
172 scrub_harness(cmd);
173 for name in withheld_env() {
174 cmd.env_remove(name);
175 }
176}
177
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct Output {
180 pub stdout: String,
181 pub stderr: String,
182 pub exit_code: i32,
183}
184
185impl Output {
186 pub fn merged(&self) -> String {
189 format!("{}{}", self.stdout, self.stderr)
190 }
191}
192
193pub trait Shell: Send + Sync {
194 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String>;
196
197 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
201 self.exec(command, cwd, timeout)
202 }
203
204 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
205 let _ = (command, cwd, timeout);
206 Err("this shell cannot run a command outside the sandbox".into())
207 }
208
209 fn describe(&self) -> String;
212
213 fn available_binaries(
215 &self,
216 cwd: &Path,
217 candidates: &[&'static str],
218 ) -> Result<Vec<String>, String> {
219 let probe = if candidates.is_empty() {
222 "true".to_string()
223 } else {
224 candidates
225 .iter()
226 .map(|b| format!("if command -v {b} >/dev/null 2>&1; then echo {b}; fi"))
227 .collect::<Vec<_>>()
228 .join("; ")
229 };
230 let o = self
231 .exec(&probe, cwd, Duration::from_secs(30))
232 .map_err(|e| format!("environment probe `{probe}` failed: {e}"))?;
233 if o.exit_code != 0 {
234 let detail = o.stderr.trim();
235 return Err(if detail.is_empty() {
236 format!(
237 "environment probe `{probe}` failed with exit status {}",
238 o.exit_code
239 )
240 } else {
241 format!(
242 "environment probe `{probe}` failed with exit status {}: {detail}",
243 o.exit_code
244 )
245 });
246 }
247 Ok(o.stdout
248 .lines()
249 .map(|l| l.trim().to_string())
250 .filter(|l| !l.is_empty())
251 .collect())
252 }
253}
254
255#[derive(Debug, Default)]
257pub struct CancelHandle {
258 cancelled: AtomicBool,
259 active_pgid: Mutex<Option<i32>>,
260}
261
262impl CancelHandle {
263 pub fn new() -> Self {
264 Self::default()
265 }
266
267 pub fn is_cancelled(&self) -> bool {
268 self.cancelled.load(Ordering::SeqCst)
269 }
270
271 pub fn flag(&self) -> &AtomicBool {
272 &self.cancelled
273 }
274
275 pub fn cancel(&self) {
276 let pgid = {
277 let guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
278 self.cancelled.store(true, Ordering::SeqCst);
279 *guard
280 };
281 #[cfg(unix)]
282 if let Some(pgid) = pgid {
283 if pgid > 0 {
284 unsafe {
285 libc::kill(-pgid, libc::SIGKILL);
286 }
287 }
288 }
289 #[cfg(not(unix))]
290 let _ = pgid;
291 }
292
293 fn register_pgid(&self, pgid: i32) -> bool {
294 let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
295 if self.cancelled.load(Ordering::SeqCst) {
296 return false;
297 }
298 *guard = Some(pgid);
299 true
300 }
301
302 fn clear_pgid(&self) {
303 let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
304 *guard = None;
305 }
306}
307
308fn kill_child_group(child: &mut Child) {
309 #[cfg(unix)]
313 {
314 let pgid = child.id() as i32;
315 if pgid > 0 {
316 unsafe {
317 libc::kill(-pgid, libc::SIGKILL);
318 }
319 } else {
320 let _ = child.kill();
321 }
322 }
323 #[cfg(not(unix))]
324 {
325 let _ = child.kill();
326 }
327 let _ = child.wait();
328}
329
330pub const POLL_START: Duration = Duration::from_millis(1);
331
332pub fn poll_backoff(current: Duration, remaining: Duration) -> (Duration, Duration) {
335 (
336 current.min(remaining),
337 (current * 2).min(Duration::from_millis(50)),
338 )
339}
340
341fn exec_command(cmd: Command, timeout: Duration) -> Result<Output, String> {
354 exec_command_cancellable(cmd, timeout, None)
355}
356
357fn exec_command_cancellable(
358 mut cmd: Command,
359 timeout: Duration,
360 cancel: Option<&CancelHandle>,
361) -> Result<Output, String> {
362 use std::process::Stdio;
363
364 if cancel.is_some_and(CancelHandle::is_cancelled) {
365 return Err("command cancelled".into());
366 }
367
368 cmd.stdin(Stdio::null())
372 .stdout(Stdio::piped())
373 .stderr(Stdio::piped());
374
375 #[cfg(unix)]
380 {
381 use std::os::unix::process::CommandExt;
382 cmd.process_group(0);
383 }
384
385 let program = cmd.get_program().to_string_lossy().into_owned();
386 let mut child = cmd
387 .spawn()
388 .map_err(|e| format!("cannot run command `{program}`: {e}"))?;
389
390 if let Some(handle) = cancel {
391 if !handle.register_pgid(child.id() as i32) {
392 kill_child_group(&mut child);
393 return Err("command cancelled".into());
394 }
395 }
396
397 let mut so = child.stdout.take().ok_or("no stdout")?;
400 let mut se = child.stderr.take().ok_or("no stderr")?;
401 let t_out = std::thread::spawn(move || {
402 let mut b = String::new();
403 let _ = so.read_to_string(&mut b);
404 b
405 });
406 let t_err = std::thread::spawn(move || {
407 let mut b = String::new();
408 let _ = se.read_to_string(&mut b);
409 b
410 });
411
412 let deadline = std::time::Instant::now() + timeout;
413 let mut poll = POLL_START;
414 let mut was_cancelled = false;
415 let status = loop {
416 match child.try_wait().map_err(|e| format!("wait failed: {e}"))? {
417 Some(s) => break Some(s),
418 None if cancel.is_some_and(CancelHandle::is_cancelled) => {
419 was_cancelled = true;
420 kill_child_group(&mut child);
421 break None;
422 }
423 None if std::time::Instant::now() >= deadline => {
424 kill_child_group(&mut child);
425 break None;
426 }
427 None => {
428 let remaining = deadline.saturating_duration_since(Instant::now());
429 let (sleep, next) = poll_backoff(poll, remaining);
430 std::thread::sleep(sleep);
431 poll = next;
432 }
433 }
434 };
435
436 if let Some(handle) = cancel {
437 handle.clear_pgid();
438 }
439
440 let stdout = t_out.join().unwrap_or_default();
441 let stderr = t_err.join().unwrap_or_default();
442
443 if was_cancelled {
444 return Err("command cancelled".into());
445 }
446
447 match status {
448 Some(s) => Ok(Output {
449 stdout,
450 stderr,
451 exit_code: s.code().unwrap_or(-1),
452 }),
453 None => Ok(Output {
456 stdout,
457 stderr: format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
458 exit_code: 124, }),
460 }
461}
462
463#[derive(Debug, Default, Clone, PartialEq, Eq)]
465pub struct LocalShell {
466 pub profile: Option<Profile>,
467}
468
469#[allow(non_upper_case_globals)]
470pub const LocalShell: LocalShell = LocalShell { profile: None };
471
472impl LocalShell {
473 pub fn new() -> Self {
475 Self { profile: None }
476 }
477
478 pub fn sandboxed(profile: impl Into<Profile>) -> Self {
480 Self {
481 profile: Some(profile.into()),
482 }
483 }
484
485 fn build_command(&self, command: &str, cwd: &Path) -> Result<Command, String> {
486 let full_command = inherited_path_prefix() + command;
487 let command = full_command.as_str();
488 let mut cmd = match &self.profile {
489 Some(Profile::Seatbelt(profile)) => {
490 let mut c = Command::new("/usr/bin/sandbox-exec");
491 c.args(["-p", profile, "bash", "-lc", command]);
492 c
493 }
494 Some(Profile::Landlock(paths)) => {
495 #[cfg(target_os = "linux")]
496 {
497 let mut c = Command::new("bash");
498 c.arg("-lc").arg(command);
499 crate::sandbox::landlock_pre_exec(&mut c, paths, None, false)
500 .map_err(|e| e.to_string())?;
501 c
502 }
503 #[cfg(not(target_os = "linux"))]
504 {
505 let _ = paths;
506 return Err(std::io::Error::new(
507 std::io::ErrorKind::Unsupported,
508 "Landlock is only supported on Linux",
509 )
510 .to_string());
511 }
512 }
513 Some(Profile::LandlockOffline(paths)) => {
514 #[cfg(target_os = "linux")]
515 {
516 let mut c = Command::new("bash");
517 c.arg("-lc").arg(command);
518 crate::sandbox::landlock_pre_exec(&mut c, paths, None, true)
519 .map_err(|e| e.to_string())?;
520 c
521 }
522 #[cfg(not(target_os = "linux"))]
523 {
524 let _ = paths;
525 return Err(std::io::Error::new(
526 std::io::ErrorKind::Unsupported,
527 "Landlock is only supported on Linux",
528 )
529 .to_string());
530 }
531 }
532 Some(Profile::LandlockConfined {
533 write,
534 read,
535 block_tcp,
536 }) => {
537 #[cfg(target_os = "linux")]
538 {
539 let mut c = Command::new("bash");
540 c.arg("-lc").arg(command);
541 crate::sandbox::landlock_pre_exec(&mut c, write, Some(read), *block_tcp)
542 .map_err(|e| e.to_string())?;
543 c
544 }
545 #[cfg(not(target_os = "linux"))]
546 {
547 let _ = (write, read, block_tcp);
548 return Err(std::io::Error::new(
549 std::io::ErrorKind::Unsupported,
550 "Landlock is only supported on Linux",
551 )
552 .to_string());
553 }
554 }
555 None => {
556 let mut c = Command::new("bash");
557 c.arg("-lc").arg(command);
558 c
559 }
560 };
561 cmd.current_dir(cwd);
562 scrub(&mut cmd);
563 Ok(cmd)
564 }
565}
566
567impl Shell for LocalShell {
568 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
569 let cmd = self.build_command(command, cwd)?;
570 exec_command(cmd, timeout)
571 }
572
573 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
574 let mut cmd = self.build_command(command, cwd)?;
575 cmd.env(MODEL_SHELL_ENV, "1");
576 exec_command(cmd, timeout)
577 }
578
579 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
580 let full_command = inherited_path_prefix() + command;
581 let mut cmd = Command::new("bash");
582 cmd.arg("-lc").arg(&full_command);
583 cmd.current_dir(cwd);
584 scrub_harness(&mut cmd);
585 cmd.env(MODEL_SHELL_ENV, "1");
586 exec_command(cmd, timeout)
587 }
588
589 fn describe(&self) -> String {
590 "Commands run directly on this machine, in the workspace directory.".into()
591 }
592}
593
594#[derive(Debug, Clone)]
596pub struct CancellableLocalShell {
597 pub inner: LocalShell,
598 pub cancel: Arc<CancelHandle>,
599}
600
601impl Shell for CancellableLocalShell {
602 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
603 let cmd = self.inner.build_command(command, cwd)?;
604 exec_command_cancellable(cmd, timeout, Some(&self.cancel))
605 }
606
607 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
608 let mut cmd = self.inner.build_command(command, cwd)?;
609 cmd.env(MODEL_SHELL_ENV, "1");
610 exec_command_cancellable(cmd, timeout, Some(&self.cancel))
611 }
612
613 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
614 let full_command = inherited_path_prefix() + command;
615 let mut cmd = Command::new("bash");
616 cmd.arg("-lc").arg(&full_command);
617 cmd.current_dir(cwd);
618 scrub_harness(&mut cmd);
619 cmd.env(MODEL_SHELL_ENV, "1");
620 exec_command_cancellable(cmd, timeout, Some(&self.cancel))
621 }
622
623 fn describe(&self) -> String {
624 self.inner.describe()
625 }
626}
627
628#[derive(Debug, Clone)]
633pub struct ContainerShell {
634 pub container_id: String,
635 pub workdir: PathBuf,
637}
638
639impl ContainerShell {
640 fn build_command(&self, command: &str, model_shell: bool) -> Command {
641 let mut cmd = Command::new("docker");
642 cmd.args(["exec", "-i"]);
643 if model_shell {
644 cmd.args(["-e", "BLYTE_MODEL_SHELL=1"]);
645 }
646 cmd.arg("-w")
647 .arg(&self.workdir)
648 .arg(&self.container_id)
649 .args(["bash", "-lc", command]);
650 cmd
651 }
652}
653
654impl Shell for ContainerShell {
655 fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
656 exec_command(self.build_command(command, false), timeout)
657 }
658
659 fn exec_user(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
660 exec_command(self.build_command(command, true), timeout)
661 }
662
663 fn describe(&self) -> String {
664 format!(
665 "Commands run inside the project container at {}. Project dependencies are \
666 installed there, not on the host.",
667 self.workdir.display()
668 )
669 }
670}
671
672#[derive(Debug, Clone)]
674pub struct CancellableContainerShell {
675 pub inner: ContainerShell,
676 pub cancel: Arc<CancelHandle>,
677}
678
679impl Shell for CancellableContainerShell {
680 fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
681 exec_command_cancellable(
682 self.inner.build_command(command, false),
683 timeout,
684 Some(&self.cancel),
685 )
686 }
687
688 fn exec_user(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
689 exec_command_cancellable(
690 self.inner.build_command(command, true),
691 timeout,
692 Some(&self.cancel),
693 )
694 }
695
696 fn describe(&self) -> String {
697 self.inner.describe()
698 }
699}
700
701fn quote(s: &str) -> String {
703 format!("'{}'", s.replace('\'', r"'\''"))
704}
705
706pub fn inherited_path_prefix() -> String {
708 match std::env::var("PATH") {
709 Ok(path) if !path.is_empty() => format!("export PATH={}:\"$PATH\"; ", quote(&path)),
710 _ => String::new(),
711 }
712}
713
714#[derive(Debug, Clone)]
716pub enum Launcher {
717 Local {
719 root: PathBuf,
720 profile: Option<Profile>,
721 },
722 Container {
724 container_id: String,
725 workdir: PathBuf,
726 },
727}
728
729impl Launcher {
730 fn command(&self, model_shell: bool) -> std::io::Result<Command> {
731 match self {
732 Launcher::Local { root, profile } => {
733 let mut c = match profile {
734 Some(Profile::Seatbelt(p)) => {
735 let mut cmd = Command::new("/usr/bin/sandbox-exec");
736 cmd.args(["-p", p, "bash", "-l"]);
737 cmd
738 }
739 Some(Profile::Landlock(paths)) => {
740 #[cfg(target_os = "linux")]
741 {
742 let mut cmd = Command::new("bash");
743 cmd.arg("-l");
744 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, false)?;
745 cmd
746 }
747 #[cfg(not(target_os = "linux"))]
748 {
749 let _ = paths;
750 return Err(std::io::Error::new(
751 std::io::ErrorKind::Unsupported,
752 "Landlock is only supported on Linux",
753 ));
754 }
755 }
756 Some(Profile::LandlockOffline(paths)) => {
757 #[cfg(target_os = "linux")]
758 {
759 let mut cmd = Command::new("bash");
760 cmd.arg("-l");
761 crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, true)?;
762 cmd
763 }
764 #[cfg(not(target_os = "linux"))]
765 {
766 let _ = paths;
767 return Err(std::io::Error::new(
768 std::io::ErrorKind::Unsupported,
769 "Landlock is only supported on Linux",
770 ));
771 }
772 }
773 Some(Profile::LandlockConfined {
774 write,
775 read,
776 block_tcp,
777 }) => {
778 #[cfg(target_os = "linux")]
779 {
780 let mut cmd = Command::new("bash");
781 cmd.arg("-l");
782 crate::sandbox::landlock_pre_exec(
783 &mut cmd,
784 write,
785 Some(read),
786 *block_tcp,
787 )?;
788 cmd
789 }
790 #[cfg(not(target_os = "linux"))]
791 {
792 let _ = (write, read, block_tcp);
793 return Err(std::io::Error::new(
794 std::io::ErrorKind::Unsupported,
795 "Landlock is only supported on Linux",
796 ));
797 }
798 }
799 None => {
800 let mut cmd = Command::new("bash");
801 cmd.arg("-l");
802 cmd
803 }
804 };
805 c.current_dir(root);
806 scrub(&mut c);
807 if model_shell {
808 c.env(MODEL_SHELL_ENV, "1");
809 }
810 Ok(c)
811 }
812 Launcher::Container {
813 container_id,
814 workdir,
815 } => {
816 let mut c = Command::new("docker");
817 c.args(["exec", "-i"]);
818 if model_shell {
819 c.args(["-e", "BLYTE_MODEL_SHELL=1"]);
820 }
821 c.arg("-w")
822 .arg(workdir)
823 .arg(container_id)
824 .args(["bash", "-l"]);
825 Ok(c)
826 }
827 }
828 }
829
830 fn with_profile(&self, profile: Profile) -> Self {
831 match self {
832 Launcher::Local { root, .. } => Launcher::Local {
833 root: root.clone(),
834 profile: Some(profile),
835 },
836 Launcher::Container {
837 container_id,
838 workdir,
839 } => Launcher::Container {
840 container_id: container_id.clone(),
841 workdir: workdir.clone(),
842 },
843 }
844 }
845
846 fn fallback(&self) -> Box<dyn Shell> {
849 match self {
850 Launcher::Local { profile, .. } => match profile {
851 Some(p) => Box::new(LocalShell::sandboxed(p.clone())),
852 None => Box::new(LocalShell),
853 },
854 Launcher::Container {
855 container_id,
856 workdir,
857 } => Box::new(ContainerShell {
858 container_id: container_id.clone(),
859 workdir: workdir.clone(),
860 }),
861 }
862 }
863}
864
865pub enum RunResult {
867 Done(Output),
868 TimedOut {
870 out: String,
871 err: String,
872 },
873 Died {
875 out: String,
876 err: String,
877 },
878 Failed(String),
879}
880
881pub struct Session {
886 child: Child,
887 stdin: ChildStdin,
888 chunks: Receiver<Vec<u8>>,
889 buf: Vec<u8>,
890 tmp: String,
891 next: u64,
892 nonce: String,
893}
894
895const READY: &str = "__BLYTE_READY__ ";
896
897fn nonce() -> String {
899 let t = std::time::SystemTime::now()
900 .duration_since(std::time::UNIX_EPOCH)
901 .map(|d| d.as_nanos())
902 .unwrap_or(0);
903 format!("{t:x}{:x}", std::process::id())
904}
905
906enum ReadErr {
907 Timeout,
908 Closed,
909 Malformed(String),
910}
911
912fn parse_header(header: &str) -> Result<(i32, usize, usize), String> {
913 let malformed = || format!("shell returned a malformed result header: {header}");
914 let mut f = header.split(' ');
915 let exit_code: i32 = f
916 .next()
917 .ok_or_else(malformed)?
918 .parse()
919 .map_err(|_| malformed())?;
920 let no: usize = f
921 .next()
922 .ok_or_else(malformed)?
923 .parse()
924 .map_err(|_| malformed())?;
925 let ne: usize = f
926 .next()
927 .ok_or_else(malformed)?
928 .parse()
929 .map_err(|_| malformed())?;
930 if f.next().is_some() || no.checked_add(ne).is_none() {
931 return Err(malformed());
932 }
933 Ok((exit_code, no, ne))
934}
935
936impl Session {
937 pub fn start(launcher: &Launcher) -> Result<Session, String> {
938 Self::start_with_marker(launcher, false)
939 }
940
941 fn start_with_marker(launcher: &Launcher, model_shell: bool) -> Result<Session, String> {
942 let mut cmd = launcher
943 .command(model_shell)
944 .map_err(|e| format!("cannot start a shell session: {e}"))?;
945 cmd.stdin(Stdio::piped())
946 .stdout(Stdio::piped())
947 .stderr(Stdio::null());
948 #[cfg(unix)]
949 {
950 use std::os::unix::process::CommandExt;
951 cmd.process_group(0);
952 }
953 let mut child = cmd
954 .spawn()
955 .map_err(|e| format!("cannot start a shell session: {e}"))?;
956 let stdin = child.stdin.take().ok_or("no stdin")?;
957 let mut stdout = child.stdout.take().ok_or("no stdout")?;
958 let (tx, rx) = mpsc::channel();
959 std::thread::spawn(move || {
960 let mut chunk = vec![0u8; 64 * 1024];
961 loop {
962 match stdout.read(&mut chunk) {
963 Ok(0) | Err(_) => break,
964 Ok(n) => {
965 if tx.send(chunk[..n].to_vec()).is_err() {
966 break;
967 }
968 }
969 }
970 }
971 });
972 let mut s = Session {
973 child,
974 stdin,
975 chunks: rx,
976 buf: Vec::new(),
977 tmp: String::new(),
978 next: 0,
979 nonce: nonce(),
980 };
981 let init = match launcher {
982 Launcher::Local { .. } => inherited_path_prefix(),
983 Launcher::Container { .. } => String::new(),
984 };
985 s.send(&format!(
986 "{init}__blyte_t=$(mktemp -d 2>/dev/null || {{ mkdir -p /tmp/blyte.$$ && echo /tmp/blyte.$$; }}); \
987 echo \"__BLYTE_READY__ $__blyte_t\"\n",
988 ))?;
989 let deadline = Instant::now() + Duration::from_secs(30);
990 loop {
991 match s.read_line(deadline) {
992 Ok(l) if l.starts_with(READY) => {
993 s.tmp = l[READY.len()..].trim().to_string();
994 return Ok(s);
995 }
996 Ok(_) => continue, Err(_) => {
998 s.kill();
999 return Err("the shell session did not start".into());
1000 }
1001 }
1002 }
1003 }
1004
1005 fn send(&mut self, script: &str) -> Result<(), String> {
1006 self.stdin
1007 .write_all(script.as_bytes())
1008 .and_then(|_| self.stdin.flush())
1009 .map_err(|e| format!("the shell session closed: {e}"))
1010 }
1011
1012 fn fill(&mut self, deadline: Instant) -> Result<(), ReadErr> {
1013 match self
1014 .chunks
1015 .recv_timeout(deadline.saturating_duration_since(Instant::now()))
1016 {
1017 Ok(c) => {
1018 self.buf.extend_from_slice(&c);
1019 Ok(())
1020 }
1021 Err(RecvTimeoutError::Timeout) => Err(ReadErr::Timeout),
1022 Err(RecvTimeoutError::Disconnected) => Err(ReadErr::Closed),
1023 }
1024 }
1025
1026 fn read_line(&mut self, deadline: Instant) -> Result<String, ReadErr> {
1028 loop {
1029 if let Some(i) = self.buf.iter().position(|&b| b == b'\n') {
1030 let line: Vec<u8> = self.buf.drain(..=i).collect();
1031 return Ok(String::from_utf8_lossy(&line[..i]).into_owned());
1032 }
1033 self.fill(deadline)?;
1034 }
1035 }
1036
1037 fn read_exact(&mut self, n: usize, deadline: Instant) -> Result<Vec<u8>, ReadErr> {
1039 while self.buf.len() < n {
1040 self.fill(deadline)?;
1041 }
1042 Ok(self.buf.drain(..n).collect())
1043 }
1044
1045 pub fn kill(&mut self) {
1047 #[cfg(unix)]
1048 {
1049 let pgid = self.child.id() as i32;
1050 if pgid > 0 {
1051 unsafe {
1052 libc::kill(-pgid, libc::SIGKILL);
1053 }
1054 }
1055 }
1056 let _ = self.child.kill();
1057 let _ = self.child.wait();
1058 }
1059
1060 pub fn run(&mut self, command: &str, cwd: Option<&Path>, timeout: Duration) -> RunResult {
1063 let id = self.next;
1064 self.next += 1;
1065 let (out, err) = (
1066 format!("{}/{id}.o", self.tmp),
1067 format!("{}/{id}.e", self.tmp),
1068 );
1069 let (qo, qe, qt) = (quote(&out), quote(&err), quote(&self.tmp));
1070 let delim = format!("__BLYTE_CMD_{id}_{}__", self.nonce);
1071 let body = match cwd {
1072 Some(d) => format!(
1073 "( cd {} && eval \"$__blyte_c\" )",
1074 quote(&d.to_string_lossy())
1075 ),
1076 None => "eval \"$__blyte_c\"".to_string(),
1077 };
1078 let script = format!(
1083 "IFS= read -r -d '' __blyte_c <<'{delim}' || true\n{command}\n{delim}\n\
1084 [ -d {qt} ] || mkdir -p {qt} 2>/dev/null; {body} </dev/null >{qo} 2>{qe}; __blyte_r=$?; \
1085 IFS= read -r -d '' __blyte_o <{qo} || true; \
1086 IFS= read -r -d '' __blyte_e <{qe} || true; \
1087 __blyte_l=${{LC_ALL-__blyte_unset__}}; LC_ALL=C; \
1088 printf '__BLYTE_{id}__ %s %s %s\\n%s%s' \"$__blyte_r\" \"${{#__blyte_o}}\" \
1089 \"${{#__blyte_e}}\" \"$__blyte_o\" \"$__blyte_e\"; \
1090 if [ \"$__blyte_l\" = __blyte_unset__ ]; then unset LC_ALL; else LC_ALL=$__blyte_l; fi; \
1091 unset __blyte_c __blyte_o __blyte_e __blyte_l\n"
1092 );
1093 if self.send(&script).is_err() {
1094 return RunResult::Died { out, err };
1095 }
1096 let marker = format!("__BLYTE_{id}__ ");
1097 let deadline = Instant::now() + timeout;
1098 let fail = |e: ReadErr, out: String, err: String| match e {
1099 ReadErr::Timeout => RunResult::TimedOut { out, err },
1100 ReadErr::Closed => RunResult::Died { out, err },
1101 ReadErr::Malformed(msg) => RunResult::Failed(msg),
1102 };
1103 let header = loop {
1104 match self.read_line(deadline) {
1105 Ok(l) => {
1106 if let Some(rest) = l.strip_prefix(&marker) {
1107 break rest.to_string();
1108 }
1109 }
1110 Err(e) => return fail(e, out, err),
1111 }
1112 };
1113 let (exit_code, no, ne) = match parse_header(&header) {
1114 Ok(parsed) => parsed,
1115 Err(msg) => return fail(ReadErr::Malformed(msg), out, err),
1116 };
1117 match self.read_exact(no + ne, deadline) {
1118 Ok(bytes) => RunResult::Done(Output {
1119 stdout: String::from_utf8_lossy(&bytes[..no]).into_owned(),
1120 stderr: String::from_utf8_lossy(&bytes[no..]).into_owned(),
1121 exit_code,
1122 }),
1123 Err(e) => fail(e, out, err),
1124 }
1125 }
1126
1127 fn close(&mut self) {
1129 let _ = self.send(&format!("rm -rf {}; exit 0\n", quote(&self.tmp)));
1130 let deadline = Instant::now() + Duration::from_millis(300);
1131 while Instant::now() < deadline {
1132 if let Ok(Some(_)) = self.child.try_wait() {
1133 return;
1134 }
1135 std::thread::sleep(Duration::from_millis(10));
1136 }
1137 self.kill();
1138 }
1139}
1140
1141pub type ProfileBuilder = Arc<dyn Fn() -> Result<Profile, String> + Send + Sync>;
1142
1143pub const SHELL_RESTART_NOTICE: &str =
1144 "blyte: the shell restarted because the open edits changed; exported variables were reset";
1145
1146struct UserSession {
1147 session: Session,
1148 profile: Option<Profile>,
1149}
1150
1151pub struct PersistentShell {
1160 launcher: Launcher,
1161 profile_builder: Option<ProfileBuilder>,
1162 harness: Mutex<Option<Session>>,
1163 user: Mutex<Option<UserSession>>,
1164 fallback: Box<dyn Shell>,
1165}
1166
1167impl PersistentShell {
1168 pub fn new(launcher: Launcher) -> Self {
1169 let fallback = launcher.fallback();
1170 Self {
1171 launcher,
1172 profile_builder: None,
1173 harness: Mutex::new(None),
1174 user: Mutex::new(None),
1175 fallback,
1176 }
1177 }
1178
1179 pub fn with_profile_builder(mut self, builder: ProfileBuilder) -> Self {
1180 self.profile_builder = Some(builder);
1181 self
1182 }
1183
1184 pub fn local(root: PathBuf) -> Self {
1185 Self::new(Launcher::Local {
1186 root,
1187 profile: None,
1188 })
1189 }
1190
1191 pub fn local_sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1192 Self::new(Launcher::Local {
1193 root,
1194 profile: Some(profile.into()),
1195 })
1196 }
1197
1198 pub fn sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1199 Self::local_sandboxed(root, profile)
1200 }
1201
1202 pub fn container(container_id: String, workdir: PathBuf) -> Self {
1203 Self::new(Launcher::Container {
1204 container_id,
1205 workdir,
1206 })
1207 }
1208
1209 pub fn is_persistent(&self) -> bool {
1211 let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1212 if g.is_none() {
1213 *g = Session::start(&self.launcher).ok();
1214 }
1215 g.is_some()
1216 }
1217
1218 fn collect_aborted_output(
1219 &self,
1220 fallback: &dyn Shell,
1221 out: &str,
1222 err: &str,
1223 note: String,
1224 code: i32,
1225 ) -> Output {
1226 let cat = |p: &str| {
1227 fallback
1228 .exec(
1229 &format!("cat -- {q} 2>/dev/null; rm -f -- {q}", q = quote(p)),
1230 Path::new("/"),
1231 Duration::from_secs(30),
1232 )
1233 .map(|o| o.stdout)
1234 .unwrap_or_default()
1235 };
1236 let (stdout, stderr) = (cat(out), cat(err));
1237 Output {
1238 stdout,
1239 stderr: format!("{stderr}{note}"),
1240 exit_code: code,
1241 }
1242 }
1243
1244 fn run_harness(
1246 &self,
1247 command: &str,
1248 cwd: &Path,
1249 timeout: Duration,
1250 ) -> Option<Result<Output, String>> {
1251 let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1252 if g.is_none() {
1253 *g = Session::start_with_marker(&self.launcher, false).ok();
1254 }
1255 let session = g.as_mut()?;
1256 let (out, err, note, code) = match session.run(command, Some(cwd), timeout) {
1257 RunResult::Done(o) => return Some(Ok(o)),
1258 RunResult::Failed(msg) => {
1259 session.kill();
1260 *g = None;
1261 return Some(Err(msg));
1262 }
1263 RunResult::TimedOut { out, err } => (
1264 out,
1265 err,
1266 format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1267 124,
1268 ),
1269 RunResult::Died { out, err } => (
1270 out,
1271 err,
1272 "[the shell exited; the next command starts a fresh shell in the workspace root]"
1273 .to_string(),
1274 1,
1275 ),
1276 };
1277 session.kill();
1278 *g = None;
1279 drop(g);
1280 Some(Ok(self.collect_aborted_output(
1281 self.fallback.as_ref(),
1282 &out,
1283 &err,
1284 note,
1285 code,
1286 )))
1287 }
1288
1289 fn run_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1290 let desired_profile = match &self.profile_builder {
1291 Some(builder) => Some(builder()?),
1292 None => None,
1293 };
1294 let launcher = match &desired_profile {
1295 Some(profile) => self.launcher.with_profile(profile.clone()),
1296 None => self.launcher.clone(),
1297 };
1298
1299 let mut restarted = false;
1300 let mut g = self.user.lock().unwrap_or_else(|e| e.into_inner());
1301
1302 let mut saved_cwd = None;
1303 if let (Some(desired), Some(existing)) = (&desired_profile, g.as_mut()) {
1304 if existing.profile.as_ref() != Some(desired) {
1305 if let RunResult::Done(o) =
1306 existing.session.run("pwd", None, Duration::from_secs(5))
1307 {
1308 if o.exit_code == 0 {
1309 let dir = o.stdout.trim_end_matches(&['\n', '\r'][..]);
1310 if !dir.is_empty() {
1311 saved_cwd = Some(PathBuf::from(dir));
1312 }
1313 }
1314 }
1315 existing.session.close();
1316 *g = None;
1317 restarted = true;
1318 }
1319 }
1320
1321 if g.is_none() {
1322 match Session::start_with_marker(&launcher, true) {
1323 Ok(mut session) => {
1324 if let Some(dir) = saved_cwd {
1325 let _ = session.run(
1326 &format!("cd -- {}", quote(&dir.to_string_lossy())),
1327 None,
1328 Duration::from_secs(5),
1329 );
1330 }
1331 *g = Some(UserSession {
1332 session,
1333 profile: desired_profile,
1334 });
1335 }
1336 Err(_) => {
1337 drop(g);
1338 let mut out = if self.profile_builder.is_some() {
1339 launcher.fallback().exec_user(command, cwd, timeout)?
1340 } else {
1341 self.fallback.exec_user(command, cwd, timeout)?
1342 };
1343 if restarted {
1344 out.stdout = format!("{SHELL_RESTART_NOTICE}\n{}", out.stdout);
1345 }
1346 return Ok(out);
1347 }
1348 }
1349 }
1350
1351 let user = g.as_mut().unwrap();
1352 let mut output = match user.session.run(command, None, timeout) {
1353 RunResult::Done(o) => o,
1354 RunResult::Failed(msg) => {
1355 user.session.kill();
1356 *g = None;
1357 return Err(msg);
1358 }
1359 RunResult::TimedOut { out, err } => {
1360 user.session.kill();
1361 *g = None;
1362 drop(g);
1363 let fallback = if self.profile_builder.is_some() {
1364 launcher.fallback()
1365 } else {
1366 self.launcher.fallback()
1367 };
1368 self.collect_aborted_output(
1369 fallback.as_ref(),
1370 &out,
1371 &err,
1372 format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1373 124,
1374 )
1375 }
1376 RunResult::Died { out, err } => {
1377 user.session.kill();
1378 *g = None;
1379 drop(g);
1380 let fallback = if self.profile_builder.is_some() {
1381 launcher.fallback()
1382 } else {
1383 self.launcher.fallback()
1384 };
1385 self.collect_aborted_output(
1386 fallback.as_ref(),
1387 &out,
1388 &err,
1389 "[the shell exited; the next command starts a fresh shell in the workspace root]"
1390 .to_string(),
1391 1,
1392 )
1393 }
1394 };
1395 if restarted {
1396 output.stdout = format!("{SHELL_RESTART_NOTICE}\n{}", output.stdout);
1397 }
1398 Ok(output)
1399 }
1400}
1401
1402impl Shell for PersistentShell {
1403 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1404 self.run_harness(command, cwd, timeout)
1405 .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
1406 }
1407
1408 fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1409 self.run_user(command, cwd, timeout)
1410 }
1411
1412 fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1413 self.fallback.exec_host(command, cwd, timeout)
1414 }
1415
1416 fn describe(&self) -> String {
1417 format!(
1418 "{} Your `bash` commands share one shell session: `cd` and `export` carry over to \
1419 later commands. File tools always resolve paths from the workspace root.",
1420 self.fallback.describe()
1421 )
1422 }
1423}
1424
1425impl Drop for PersistentShell {
1426 fn drop(&mut self) {
1427 if let Some(mut s) = self
1428 .harness
1429 .lock()
1430 .unwrap_or_else(|e| e.into_inner())
1431 .take()
1432 {
1433 s.close();
1434 }
1435 if let Some(mut u) = self.user.lock().unwrap_or_else(|e| e.into_inner()).take() {
1436 u.session.close();
1437 }
1438 }
1439}
1440
1441#[cfg(test)]
1442mod tests {
1443 use super::*;
1444
1445 #[test]
1446 fn persistent_shell_profile_builder_error_fails_command() {
1447 let tmp = tempfile::tempdir().unwrap();
1448 let shell =
1449 PersistentShell::local(tmp.path().to_path_buf()).with_profile_builder(Arc::new(|| {
1450 Err("cannot read .wt: permission denied".into())
1451 }));
1452 let err = shell
1453 .exec_user("echo hi", tmp.path(), Duration::from_secs(5))
1454 .unwrap_err();
1455 assert_eq!(err, "cannot read .wt: permission denied");
1456 }
1457
1458 #[test]
1459 fn parse_header_accepts_valid_and_rejects_malformed() {
1460 assert_eq!(parse_header("0 3 4"), Ok((0, 3, 4)));
1461 assert_eq!(parse_header("127 0 12"), Ok((127, 0, 12)));
1462 assert_eq!(parse_header("-1 0 0"), Ok((-1, 0, 0)));
1463
1464 for bad in ["", "x 1 2", "0 1", "0 -1 2", "0 1 2 3"] {
1465 let err = parse_header(bad).unwrap_err();
1466 assert_eq!(
1467 err,
1468 format!("shell returned a malformed result header: {bad}")
1469 );
1470 }
1471 }
1472
1473 #[cfg(unix)]
1474 #[test]
1475 fn persistent_shell_rejects_malformed_result_header_and_recovers() {
1476 let tmp = tempfile::tempdir().unwrap();
1477 let root = tmp.path().canonicalize().unwrap();
1478 let shell = PersistentShell::local(root.clone());
1479 let err = shell
1480 .exec_user(
1481 "printf() { builtin printf '__BLYTE_0__ x 1 2\\n'; }",
1482 &root,
1483 Duration::from_secs(10),
1484 )
1485 .unwrap_err();
1486 assert_eq!(err, "shell returned a malformed result header: x 1 2");
1487
1488 let recovered = shell
1489 .exec_user("echo ok", &root, Duration::from_secs(10))
1490 .unwrap();
1491 assert_eq!(recovered.exit_code, 0);
1492 assert_eq!(recovered.stdout, "ok\n");
1493 }
1494
1495 struct FailingExecShell {
1496 outcome: Result<Output, String>,
1497 }
1498
1499 impl Shell for FailingExecShell {
1500 fn exec(&self, _command: &str, _cwd: &Path, _timeout: Duration) -> Result<Output, String> {
1501 self.outcome.clone()
1502 }
1503
1504 fn describe(&self) -> String {
1505 "failing".into()
1506 }
1507 }
1508
1509 struct UnspawnableShell;
1510
1511 impl Shell for UnspawnableShell {
1512 fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1513 let mut cmd = Command::new("/nonexistent-blyte-probe-binary");
1514 cmd.arg("-c").arg(command).current_dir(cwd);
1515 exec_command(cmd, timeout)
1516 }
1517
1518 fn describe(&self) -> String {
1519 "unspawnable".into()
1520 }
1521 }
1522
1523 #[test]
1524 fn available_binaries_returns_err_when_probe_cannot_be_spawned() {
1525 let tmp = tempfile::tempdir().unwrap();
1526 let err = UnspawnableShell
1527 .available_binaries(tmp.path(), &["git", "cargo"])
1528 .unwrap_err();
1529 assert!(err.contains("command -v git"), "got: {err}");
1530 assert!(
1531 err.contains("/nonexistent-blyte-probe-binary"),
1532 "got: {err}"
1533 );
1534 }
1535
1536 #[test]
1537 fn available_binaries_returns_err_when_probe_exits_nonzero() {
1538 let shell = FailingExecShell {
1539 outcome: Ok(Output {
1540 stdout: String::new(),
1541 stderr: "Error response from daemon: container is not running\n".into(),
1542 exit_code: 125,
1543 }),
1544 };
1545 let err = shell
1546 .available_binaries(Path::new("."), &["git", "cargo"])
1547 .unwrap_err();
1548 assert!(err.contains("command -v git"), "got: {err}");
1549 assert!(err.contains("125"), "got: {err}");
1550 assert!(err.contains("container is not running"), "got: {err}");
1551 }
1552
1553 #[test]
1554 fn available_binaries_succeeds_when_all_candidates_are_absent() {
1555 let tmp = tempfile::tempdir().unwrap();
1556 let bins = LocalShell
1557 .available_binaries(
1558 tmp.path(),
1559 &[
1560 "blyte_nonexistent_probe_binary_a",
1561 "blyte_nonexistent_probe_binary_b",
1562 ],
1563 )
1564 .expect("missing candidates must not fail the probe");
1565 assert!(bins.is_empty(), "got: {bins:?}");
1566 }
1567}