@@ -1,5 +1,4 @@
1use crate::session_manager::{GLOBAL_CACHE_DIR_NAME, INSTANCE_DIR_NAME};
1use crate::session_manager::{GLOBAL_CACHE_DIR_NAME, INSTANCE_DIR_NAME};
2−use anyhow::{Context, Error, Result, bail};
5 io::{self, Write},
4 io::{self, Write},
@@ -23,7 +22,6 @@ use std::{
25use block2::RcBlock;
24use block2::RcBlock;
26−use bytesize::ByteSize;
27use dispatch2::DispatchQueue;
25use dispatch2::DispatchQueue;
28use objc2::{AnyThread, rc::Retained, runtime::ProtocolObject};
26use objc2::{AnyThread, rc::Retained, runtime::ProtocolObject};
29use objc2_foundation::*;
27use objc2_foundation::*;
@@ -33,46 +31,42 @@ const DEBIAN_COMPRESSED_DISK_URL: &str = "https://cloud.debian.org/images/cloud/
33const DEBIAN_COMPRESSED_SHA: &str = "6ab9be9e6834adc975268367f2f0235251671184345c34ee13031749fdfbf66fe4c3aafd949a2d98550426090e9ac645e79009c51eb0eefc984c15786570bb38";
31const DEBIAN_COMPRESSED_SHA: &str = "6ab9be9e6834adc975268367f2f0235251671184345c34ee13031749fdfbf66fe4c3aafd949a2d98550426090e9ac645e79009c51eb0eefc984c15786570bb38";
34const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
32const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
35const SHARED_DIRECTORIES_TAG: &str = "shared";
33const SHARED_DIRECTORIES_TAG: &str = "shared";
36−pub const PROJECT_GUEST_BASE: &str = "/usr/local/vibebox-mounts";
35+const BYTES_PER_MB: u64 = 1024 * 1024;
36+const DEFAULT_CPU_COUNT: usize = 2;
37+const DEFAULT_RAM_MB: u64 = 2048;
38+const DEFAULT_RAM_BYTES: u64 = DEFAULT_RAM_MB * BYTES_PER_MB;
38const START_TIMEOUT: Duration = Duration::from_secs(60);
39const START_TIMEOUT: Duration = Duration::from_secs(60);
39const LOGIN_EXPECT_TIMEOUT: Duration = Duration::from_secs(120);
40const LOGIN_EXPECT_TIMEOUT: Duration = Duration::from_secs(120);
40−const PROVISION_EXPECT_TIMEOUT: Duration = Duration::from_secs(900);
42−const ERROR_REPORT_SCRIPT: &str = include_str!("error_report.sh");
43const PROVISION_SCRIPT: &str = include_str!("provision.sh");
41const PROVISION_SCRIPT: &str = include_str!("provision.sh");
44−const RESIZE_DISK_SCRIPT: &str = include_str!("resize_disk.sh");
42+const PROVISION_SCRIPT_NAME: &str = "provision.sh";
45const DEFAULT_RAW_NAME: &str = "default.raw";
43const DEFAULT_RAW_NAME: &str = "default.raw";
46const INSTANCE_RAW_NAME: &str = "instance.raw";
44const INSTANCE_RAW_NAME: &str = "instance.raw";
47const BASE_DISK_RAW_NAME: &str = "disk.raw";
45const BASE_DISK_RAW_NAME: &str = "disk.raw";
49#[derive(Clone)]
47#[derive(Clone)]
50−pub enum LoginAction {
48+pub(crate) enum LoginAction {
58− timeout: Duration,
49+ Expect { text: String, timeout: Duration },
60 Send(String),
50 Send(String),
51+ Script { path: PathBuf, index: usize },
62−use crate::config::BoxConfig;
63use LoginAction::*;
53use LoginAction::*;
65#[derive(Clone)]
55#[derive(Clone)]
66−pub struct DirectoryShare {
56+pub(crate) struct DirectoryShare {
67 host: PathBuf,
57 host: PathBuf,
68 guest: PathBuf,
58 guest: PathBuf,
69 read_only: bool,
59 read_only: bool,
72impl DirectoryShare {
62impl DirectoryShare {
73− pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
65+ mut guest: PathBuf,
67+ ) -> Result<Self, Box<dyn std::error::Error>> {
74 if !host.exists() {
68 if !host.exists() {
75− bail!(format!("host path does not exist: {}", host.display()));
69+ return Err(format!("Host path does not exist: {}", host.display()).into());
77 if !guest.is_absolute() {
71 if !guest.is_absolute() {
78 guest = PathBuf::from("/root").join(guest);
72 guest = PathBuf::from("/root").join(guest);
@@ -84,10 +78,10 @@ impl DirectoryShare {
87− pub fn from_mount_spec(spec: &str) -> Result<Self> {
81+ pub(crate) fn from_mount_spec(spec: &str) -> Result<Self, Box<dyn std::error::Error>> {
88 let parts: Vec<&str> = spec.split(':').collect();
82 let parts: Vec<&str> = spec.split(':').collect();
89 if parts.len() < 2 || parts.len() > 3 {
83 if parts.len() < 2 || parts.len() > 3 {
90− bail!(format!("invalid mount spec: {spec}"));
84+ return Err(format!("Invalid mount spec: {spec}").into());
92 let host = expand_tilde_path(parts[0]);
86 let host = expand_tilde_path(parts[0]);
93 let guest = PathBuf::from(parts[1]);
87 let guest = PathBuf::from(parts[1]);
@@ -96,10 +90,11 @@ impl DirectoryShare {
96 "read-only" => true,
90 "read-only" => true,
97 "read-write" => false,
91 "read-write" => false,
99− bail!(format!(
93+ return Err(format!(
100 "Invalid mount mode '{}'; expected read-only or read-write",
94 "Invalid mount mode '{}'; expected read-only or read-write",
@@ -127,10 +122,10 @@ fn expand_tilde_path(value: &str) -> PathBuf {
127 if let Ok(home) = env::var("HOME") {
122 if let Ok(home) = env::var("HOME") {
128 return PathBuf::from(home).join(stripped);
123 return PathBuf::from(home).join(stripped);
130− } else if value == "~"
125+ } else if value == "~" {
131− && let Ok(home) = env::var("HOME")
126+ if let Ok(home) = env::var("HOME") {
133− return PathBuf::from(home);
127+ return PathBuf::from(home);
135 PathBuf::from(value)
130 PathBuf::from(value)
@@ -138,33 +133,23 @@ fn expand_tilde_path(value: &str) -> PathBuf {
138pub struct VmArg {
133pub struct VmArg {
139 pub cpu_count: usize,
134 pub cpu_count: usize,
140 pub ram_bytes: u64,
135 pub ram_bytes: u64,
141− pub disk_bytes: u64,
142 pub no_default_mounts: bool,
136 pub no_default_mounts: bool,
143 pub mounts: Vec<String>,
137 pub mounts: Vec<String>,
146−type StatusEmitter<'a> = dyn Fn(&str) + std::marker::Send + Sync + 'a;
148−fn emit_status(status: Option<&StatusEmitter<'_>>, message: &str) {
149− if let Some(status) = status {
154−pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<()>
140+pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<(), Box<dyn std::error::Error>>
156 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
142 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
158− run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new(), None)
144+ run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new())
161−pub fn run_with_args_and_extras<F>(
147+pub(crate) fn run_with_args_and_extras<F>(
162 args: VmArg,
148 args: VmArg,
163 io_handler: F,
149 io_handler: F,
164 extra_login_actions: Vec<LoginAction>,
150 extra_login_actions: Vec<LoginAction>,
165 extra_directory_shares: Vec<DirectoryShare>,
151 extra_directory_shares: Vec<DirectoryShare>,
166− status: Option<&StatusEmitter<'_>>,
152+) -> Result<(), Box<dyn std::error::Error>>
169 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
154 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
@@ -173,7 +158,7 @@ where
173 let project_root = env::current_dir()?;
158 let project_root = env::current_dir()?;
174 let project_name = project_root
159 let project_name = project_root
175 .file_name()
160 .file_name()
176− .with_context(|| "Project directory has no name")?
161+ .ok_or("Project directory has no name")?
177 .to_string_lossy()
162 .to_string_lossy()
178 .into_owned();
163 .into_owned();
@@ -185,10 +170,6 @@ where
185 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
170 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
187 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
172 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
188− fs::create_dir_all(&instance_dir)?;
189− emit_status(status, "preparing VM image...");
190− tracing::info!("preparing VM image...");
191− let provision_log = instance_dir.join("provision.log");
193 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
174 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
194 let base_compressed = cache_dir.join(basename_compressed);
175 let base_compressed = cache_dir.join(basename_compressed);
@@ -212,26 +193,15 @@ where
212 &base_compressed,
193 &base_compressed,
213 &default_raw,
194 &default_raw,
214 std::slice::from_ref(&mise_directory_share),
195 std::slice::from_ref(&mise_directory_share),
215− Some(&provision_log),
218− let _ = ensure_instance_disk(
197+ ensure_instance_disk(&instance_raw, &default_raw)?;
221− ByteSize(args.disk_bytes),
224− let base_size = fs::metadata(&default_raw)?.len();
225− let instance_size = fs::metadata(&instance_raw)?.len();
226− let needs_resize = instance_size > base_size;
227 let disk_path = instance_raw;
198 let disk_path = instance_raw;
229 let mut login_actions = Vec::new();
200 let mut login_actions = Vec::new();
230 let mut directory_shares = Vec::new();
201 let mut directory_shares = Vec::new();
232 if !args.no_default_mounts {
203 if !args.no_default_mounts {
233− let project_guest_dir = PathBuf::from(PROJECT_GUEST_BASE).join(project_name);
234− login_actions.push(Send(format!("cd {}", project_guest_dir.display())));
204+ login_actions.push(Send(format!("cd {project_name}")));
236 // discourage read/write of .git folder from within the VM. note that this isn't secure, since the VM runs as root and could unmount this.
206 // discourage read/write of .git folder from within the VM. note that this isn't secure, since the VM runs as root and could unmount this.
237 // I couldn't find an alternative way to do this --- the MacOS sandbox doesn't apply to the Apple Virtualization system
207 // I couldn't find an alternative way to do this --- the MacOS sandbox doesn't apply to the Apple Virtualization system
@@ -239,6 +209,15 @@ where
239 login_actions.push(Send(r"mount -t tmpfs tmpfs .git/".into()));
209 login_actions.push(Send(r"mount -t tmpfs tmpfs .git/".into()));
212+ directory_shares.push(
213+ DirectoryShare::new(
215+ PathBuf::from("/root/").join(project_name),
218+ .expect("Project directory must exist"),
242 directory_shares.push(mise_directory_share);
221 directory_shares.push(mise_directory_share);
@@ -248,11 +227,6 @@ where
248 directory_shares.push(DirectoryShare::from_mount_spec(spec)?);
227 directory_shares.push(DirectoryShare::from_mount_spec(spec)?);
252− let resize_cmd = script_command_from_content("resize_disk.sh", RESIZE_DISK_SCRIPT)?;
253− login_actions.push(Send(resize_cmd));
256 if let Some(motd_action) = motd_login_action(&directory_shares) {
230 if let Some(motd_action) = motd_login_action(&directory_shares) {
257 login_actions.push(motd_action);
231 login_actions.push(motd_action);
@@ -265,29 +239,34 @@ where
265 &directory_shares[..],
239 &directory_shares[..],
266 args.cpu_count,
240 args.cpu_count,
267 args.ram_bytes,
241 args.ram_bytes,
269 io_handler,
242 io_handler,
246+fn script_command_from_path(
249+) -> Result<String, Box<dyn std::error::Error>> {
250+ let script = fs::read_to_string(path)
251+ .map_err(|err| format!("Failed to read script {}: {err}", path.display()))?;
252+ let label = format!("{}_{}", index, path.file_name().unwrap().display());
253+ script_command_from_content(&label, &script)
273−pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
256+pub(crate) fn script_command_from_content(
259+) -> Result<String, Box<dyn std::error::Error>> {
274 let marker = "VIBE_SCRIPT_EOF";
260 let marker = "VIBE_SCRIPT_EOF";
275 let guest_dir = "/tmp/vibe-scripts";
261 let guest_dir = "/tmp/vibe-scripts";
276 let guest_path = format!("{guest_dir}/{label}.sh");
262 let guest_path = format!("{guest_dir}/{label}.sh");
277− let script_body = match script.split_once('\n') {
278− Some((first, rest)) if first.starts_with("#!") => rest,
281− let wrapped_script = ERROR_REPORT_SCRIPT
282− .replace("__LABEL__", label)
283− .replace("__SCRIPT_BODY__", script_body);
284 let command = format!(
263 let command = format!(
285− "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{wrapped_script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
264+ "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
287 if script.contains(marker) {
266 if script.contains(marker) {
288− bail!(format!(
267+ return Err(
289− "Script '{label}' contains marker '{marker}', cannot safely upload"
268+ format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
292 Ok(command)
271 Ok(command)
@@ -351,12 +330,6 @@ enum WaitResult {
354−#[derive(PartialEq, Eq)]
360pub enum VmInput {
333pub enum VmInput {
361 Bytes(Vec<u8>),
334 Bytes(Vec<u8>),
362 Shutdown,
335 Shutdown,
@@ -364,7 +337,6 @@ pub enum VmInput {
365enum VmOutput {
338enum VmOutput {
366 LoginActionTimeout { action: String, timeout: Duration },
339 LoginActionTimeout { action: String, timeout: Duration },
367− LoginActionFailed { action: String, reason: String },
370#[derive(Default)]
342#[derive(Default)]
@@ -401,41 +373,6 @@ impl OutputMonitor {
401 WaitResult::Found
373 WaitResult::Found
405− fn wait_for_any(&self, needles: &[&str], timeout: Duration) -> WaitAnyResult {
406− let mut found: Option<usize> = None;
407− let (_unused, timeout_result) = self
409− .wait_timeout_while(self.buffer.lock().unwrap(), timeout, |buf| {
410− if let Some((pos, idx, len)) = find_any(buf, needles) {
411− *buf = buf[(pos + len)..].to_string();
420− if timeout_result.timed_out() {
421− WaitAnyResult::Timeout
423− WaitAnyResult::Found(found.unwrap_or(0))
428−fn find_any(buf: &str, needles: &[&str]) -> Option<(usize, usize, usize)> {
429− let mut best: Option<(usize, usize, usize)> = None; // (pos, idx, len)
430− for (idx, needle) in needles.iter().enumerate() {
431− if let Some(pos) = buf.find(needle) {
432− let candidate = (pos, idx, needle.len());
433− if best.is_none_or(|b| candidate.0 < b.0) {
434− best = Some(candidate);
441#[derive(Debug)]
378#[derive(Debug)]
@@ -484,17 +421,15 @@ impl IoControl {
484fn ensure_base_image(
421fn ensure_base_image(
485 base_raw: &Path,
422 base_raw: &Path,
486 base_compressed: &Path,
423 base_compressed: &Path,
487− status: Option<&StatusEmitter<'_>>,
424+) -> Result<(), Box<dyn std::error::Error>> {
489 if base_raw.exists() {
425 if base_raw.exists() {
490 return Ok(());
426 return Ok(());
493 if !base_compressed.exists()
429 if !base_compressed.exists()
494− || fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
430+ || std::fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
496− emit_status(status, "downloading base image...");
432+ println!("Downloading base image...");
497− tracing::info!("downloading base image");
498 let status = Command::new("curl")
433 let status = Command::new("curl")
500 "--continue-at",
435 "--continue-at",
@@ -508,14 +443,12 @@ fn ensure_base_image(
509 .status()?;
444 .status()?;
510 if !status.success() {
445 if !status.success() {
511− bail!("failed to download base image");
446+ return Err("Failed to download base image".into());
515 // Check SHA
450 // Check SHA
517− emit_status(status, "verifying base image...");
518− tracing::info!("verifying base image...");
519 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
452 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
521 let mut child = Command::new("/usr/bin/shasum")
454 let mut child = Command::new("/usr/bin/shasum")
@@ -533,25 +466,22 @@ fn ensure_base_image(
534 let status = child.wait().expect("failed to wait on child");
467 let status = child.wait().expect("failed to wait on child");
535 if !status.success() {
468 if !status.success() {
537− "SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}"
469+ return Err(format!("SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}").into());
542− emit_status(status, "decompressing base image...");
473+ println!("Decompressing base image...");
543− tracing::info!("decompressing base image...");
544 let status = Command::new("tar")
474 let status = Command::new("tar")
547 &base_compressed.to_string_lossy(),
477 &base_compressed.to_string_lossy(),
548 BASE_DISK_RAW_NAME,
478 BASE_DISK_RAW_NAME,
550− .stdout(fs::File::create(base_raw)?)
480+ .stdout(std::fs::File::create(base_raw)?)
551 .status()?;
481 .status()?;
553 if !status.success() {
483 if !status.success() {
554− bail!("Failed to decompress base image");
484+ return Err("Failed to decompress base image".into());
@@ -562,56 +492,24 @@ fn ensure_default_image(
562 base_compressed: &Path,
492 base_compressed: &Path,
563 default_raw: &Path,
493 default_raw: &Path,
564 directory_shares: &[DirectoryShare],
494 directory_shares: &[DirectoryShare],
565− provision_log: Option<&Path>,
495+) -> Result<(), Box<dyn std::error::Error>> {
566− status: Option<&StatusEmitter<'_>>,
568 if default_raw.exists() {
496 if default_raw.exists() {
569 return Ok(());
497 return Ok(());
572− ensure_base_image(base_raw, base_compressed, status)?;
500+ ensure_base_image(base_raw, base_compressed)?;
574− emit_status(status, "configuring base image...");
502+ println!("Configuring base image...");
575− tracing::info!("configuring base image...");
576 fs::copy(base_raw, default_raw)?;
503 fs::copy(base_raw, default_raw)?;
578− let provision_command = script_command_from_content("provision.sh", PROVISION_SCRIPT)?;
505+ let provision_command = script_command_from_content(PROVISION_SCRIPT_NAME, PROVISION_SCRIPT)?;
579− let provision_actions = [
506+ run_vm(
580− Send(provision_command),
508+ &[Send(provision_command)],
582− success: "VIBEBOX_PROVISION_OK".to_string(),
583− failure: "VIBEBOX_PROVISION_FAILED".to_string(),
584− timeout: PROVISION_EXPECT_TIMEOUT,
587− let provision_result = if let Some(log_path) = provision_log {
588− let log_path = log_path.to_path_buf();
592− directory_shares,
509+ directory_shares,
593− BoxConfig::default().cpu_count,
510+ DEFAULT_CPU_COUNT,
594− BoxConfig::default().ram_size.as_u64(),
511+ DEFAULT_RAM_BYTES,
596− move |output_monitor, vm_output_fd, vm_input_fd| {
597− spawn_vm_io_with_log(output_monitor, vm_output_fd, vm_input_fd, log_path)
605− BoxConfig::default().cpu_count,
606− BoxConfig::default().ram_size.as_u64(),
611− if let Err(err) = provision_result {
612− let _ = fs::remove_file(default_raw);
@@ -619,47 +517,15 @@ fn ensure_default_image(
619fn ensure_instance_disk(
517fn ensure_instance_disk(
620 instance_raw: &Path,
518 instance_raw: &Path,
621 template_raw: &Path,
519 template_raw: &Path,
622− target_bytes: ByteSize,
520+) -> Result<(), Box<dyn std::error::Error>> {
623− status: Option<&StatusEmitter<'_>>,
625 if instance_raw.exists() {
521 if instance_raw.exists() {
626− let current_size = ByteSize(fs::metadata(instance_raw)?.len());
627− if current_size != target_bytes {
628− let current_gb = current_size;
629− let target_gb = target_bytes;
631− "instance disk size does not match config (current {}, config {}); disk_gb applies only on init. Run `vibebox reset` to recreate or set disk_gb to match; using existing disk.",
636− return Ok(false);
522+ return Ok(());
639− let template_size = ByteSize(fs::metadata(template_raw)?.len());
640− if target_bytes < template_size {
642− "Requested disk size {} is smaller than base image size {}",
643− target_bytes, template_size
646− let target_size = target_bytes;
647− let needs_resize = target_size > template_size;
649− emit_status(status, "creating instance disk...");
650− tracing::info!("creating instance disk...");
651− tracing::info!(path = %template_raw.display(), "creating instance disk");
652− fs::create_dir_all(instance_raw.parent().unwrap())?;
653− if target_size == template_size {
654− fs::copy(template_raw, instance_raw)?;
655− return Ok(needs_resize);
658− let mut dst = fs::File::create(instance_raw)?;
525+ println!("Creating instance disk from {}...", template_raw.display());
659− dst.set_len(target_size.as_u64())?;
526+ std::fs::create_dir_all(instance_raw.parent().unwrap())?;
660− let mut src = fs::File::open(template_raw)?;
527+ fs::copy(template_raw, instance_raw)?;
661− std::io::copy(&mut src, &mut dst)?;
528+ Ok(())
665pub struct IoContext {
531pub struct IoContext {
@@ -675,17 +541,18 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
675 (read_stream.into(), write_stream.into())
541 (read_stream.into(), write_stream.into())
678−pub fn spawn_vm_io_with_hooks<
544+pub fn spawn_vm_io_with_hooks<F, G>(
679− F: FnMut(&str) -> bool + std::marker::Send + 'static,
680− G: FnMut(&[u8]) + std::marker::Send + 'static,
682 output_monitor: Arc<OutputMonitor>,
545 output_monitor: Arc<OutputMonitor>,
683 vm_output_fd: OwnedFd,
546 vm_output_fd: OwnedFd,
684 vm_input_fd: OwnedFd,
547 vm_input_fd: OwnedFd,
685 io_control: Arc<IoControl>,
548 io_control: Arc<IoControl>,
686 mut on_line: F,
549 mut on_line: F,
687 mut on_output: G,
550 mut on_output: G,
688−) -> IoContext {
551+) -> IoContext
553+ F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
554+ G: FnMut(&[u8]) + ::std::marker::Send + 'static,
689 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
556 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
691 // raw_guard is set when we've put the user's terminal into raw mode because we've attached stdin/stdout to the VM.
558 // raw_guard is set when we've put the user's terminal into raw mode because we've attached stdin/stdout to the VM.
@@ -833,14 +700,14 @@ pub fn spawn_vm_io_with_hooks<
833 PollResult::Spurious => continue,
700 PollResult::Spurious => continue,
834 PollResult::Ready(bytes) => {
701 PollResult::Ready(bytes) => {
835 if io_control.forward_output() {
702 if io_control.forward_output() {
836− // enable raw mode if we haven't already
703+ // enable raw mode, if we haven't already
837 if raw_guard.lock().unwrap().is_none()
704 if raw_guard.lock().unwrap().is_none()
838 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
705 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
840 *raw_guard.lock().unwrap() = Some(guard);
707 *raw_guard.lock().unwrap() = Some(guard);
843− let mut stdout = io::stdout().lock();
710+ let mut stdout = std::io::stdout().lock();
844 if stdout.write_all(bytes).is_err() {
711 if stdout.write_all(bytes).is_err() {
@@ -856,7 +723,7 @@ pub fn spawn_vm_io_with_hooks<
857 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
724 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
858 let mux_thread = thread::spawn(move || {
725 let mux_thread = thread::spawn(move || {
859− let mut vm_writer = fs::File::from(vm_input_fd);
726+ let mut vm_writer = std::fs::File::from(vm_input_fd);
861 match input_rx.recv() {
728 match input_rx.recv() {
862 Ok(VmInput::Bytes(data)) => {
729 Ok(VmInput::Bytes(data)) => {
@@ -886,7 +753,7 @@ pub fn spawn_vm_io_with_line_handler<F>(
886 on_line: F,
753 on_line: F,
887) -> IoContext
754) -> IoContext
889− F: FnMut(&str) -> bool + std::marker::Send + 'static,
756+ F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
891 spawn_vm_io_with_hooks(
758 spawn_vm_io_with_hooks(
892 output_monitor,
759 output_monitor,
@@ -906,36 +773,6 @@ pub fn spawn_vm_io(
906 spawn_vm_io_with_line_handler(output_monitor, vm_output_fd, vm_input_fd, |_| false)
773 spawn_vm_io_with_line_handler(output_monitor, vm_output_fd, vm_input_fd, |_| false)
909−fn spawn_vm_io_with_log(
910− output_monitor: Arc<OutputMonitor>,
911− vm_output_fd: OwnedFd,
912− vm_input_fd: OwnedFd,
915− let log_file = fs::OpenOptions::new()
921− .map(|file| Arc::new(Mutex::new(file)));
923− spawn_vm_io_with_hooks(
930− if let Some(log) = &log_file
931− && let Ok(mut file) = log.lock()
933− let _ = file.write_all(bytes);
939impl IoContext {
776impl IoContext {
940 pub fn shutdown(self) {
777 pub fn shutdown(self) {
941 let _ = self.input_tx.send(VmInput::Shutdown);
778 let _ = self.input_tx.send(VmInput::Shutdown);
@@ -953,7 +790,7 @@ fn create_vm_configuration(
953 vm_writes_to_fd: OwnedFd,
790 vm_writes_to_fd: OwnedFd,
954 cpu_count: usize,
791 cpu_count: usize,
955 ram_bytes: u64,
792 ram_bytes: u64,
956−) -> Result<Retained<VZVirtualMachineConfiguration>> {
793+) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
958 let platform =
795 let platform =
959 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
796 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -987,7 +824,7 @@ fn create_vm_configuration(
988 VZDiskImageCachingMode::Automatic,
825 VZDiskImageCachingMode::Automatic,
989 VZDiskImageSynchronizationMode::Full,
826 VZDiskImageSynchronizationMode::Full,
992 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
829 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
993 VZVirtioBlockDeviceConfiguration::alloc(),
830 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -1074,7 +911,7 @@ fn create_vm_configuration(
1074 // Validate
911 // Validate
1075 config.validateWithError().map_err(|e| {
912 config.validateWithError().map_err(|e| {
1076 io::Error::other(format!(
913 io::Error::other(format!(
1077− "invalid VM configuration: {:?}",
914+ "Invalid VM configuration: {:?}",
1078 e.localizedDescription()
915 e.localizedDescription()
@@ -1083,9 +920,9 @@ fn create_vm_configuration(
1086−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
923+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
1087 unsafe {
924 unsafe {
1088− let temp_dir = env::temp_dir();
925+ let temp_dir = std::env::temp_dir();
1089 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
926 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
1090 let url = nsurl_from_path(&temp_path)?;
927 let url = nsurl_from_path(&temp_path)?;
1091 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
928 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -1101,8 +938,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
1101fn spawn_login_actions_thread(
938fn spawn_login_actions_thread(
1102 login_actions: Vec<LoginAction>,
939 login_actions: Vec<LoginAction>,
1103 output_monitor: Arc<OutputMonitor>,
940 output_monitor: Arc<OutputMonitor>,
1104− input_tx: Sender<VmInput>,
941+ input_tx: mpsc::Sender<VmInput>,
1105− vm_output_tx: Sender<VmOutput>,
942+ vm_output_tx: mpsc::Sender<VmOutput>,
1106) -> thread::JoinHandle<()> {
943) -> thread::JoinHandle<()> {
1107 thread::spawn(move || {
944 thread::spawn(move || {
1108 for a in login_actions {
945 for a in login_actions {
@@ -1116,31 +953,22 @@ fn spawn_login_actions_thread(
1123− } => match output_monitor.wait_for_any(&[&success, &failure], timeout) {
1124− WaitAnyResult::Found(0) => {}
1125− WaitAnyResult::Found(_) => {
1126− let _ = vm_output_tx.send(VmOutput::LoginActionFailed {
1127− action: format!("expect '{}'", success),
1128− reason: format!("saw failure marker '{}'", failure),
1132− WaitAnyResult::Timeout => {
1133− let _ = vm_output_tx.send(VmOutput::LoginActionTimeout {
1134− action: format!("expect '{}'", success),
1140 Send(mut text) => {
956 Send(mut text) => {
1141 text.push('\n'); // Type the newline so the command is actually submitted.
957 text.push('\n'); // Type the newline so the command is actually submitted.
1142 input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
958 input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
960+ Script { path, index } => {
961+ let command = match script_command_from_path(&path, index) {
962+ Ok(command) => command,
968+ let mut text = command;
970+ input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
@@ -1152,9 +980,8 @@ fn run_vm_with_io<F>(
1152 directory_shares: &[DirectoryShare],
980 directory_shares: &[DirectoryShare],
1153 cpu_count: usize,
981 cpu_count: usize,
1154 ram_bytes: u64,
982 ram_bytes: u64,
1155− status: Option<&StatusEmitter<'_>>,
1156 io_handler: F,
983 io_handler: F,
1157−) -> Result<()>
984+) -> Result<(), Box<dyn std::error::Error>>
1159 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
986 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
@@ -1201,23 +1028,21 @@ where
1202 match rx.try_recv() {
1029 match rx.try_recv() {
1203 Ok(result) => {
1030 Ok(result) => {
1204− result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
1031+ result.map_err(|e| format!("Failed to start VM: {}", e))?;
1207 Err(mpsc::TryRecvError::Empty) => continue,
1034 Err(mpsc::TryRecvError::Empty) => continue,
1208 Err(mpsc::TryRecvError::Disconnected) => {
1035 Err(mpsc::TryRecvError::Disconnected) => {
1209− bail!("VM start channel disconnected");
1036+ return Err("VM start channel disconnected".into());
1214 if Instant::now() >= start_deadline {
1041 if Instant::now() >= start_deadline {
1215− bail!("Timed out waiting for VM to start");
1042+ return Err("Timed out waiting for VM to start".into());
1218− emit_status(status, "vm booting... go vibecoder!");
1045+ println!("VM booting...");
1219− tracing::info!("vm booting... go vibecoder!");
1220− tracing::info!("vm booting");
1222 let output_monitor = Arc::new(OutputMonitor::default());
1047 let output_monitor = Arc::new(OutputMonitor::default());
1223 let io_ctx = io_handler(output_monitor.clone(), we_read_from, we_write_to);
1048 let io_ctx = io_handler(output_monitor.clone(), we_read_from, we_write_to);
@@ -1262,7 +1087,7 @@ where
1264 let mut last_state = None;
1089 let mut last_state = None;
1265− let mut exit_result: Result<(), String> = Ok(());
1090+ let mut exit_result = Ok(());
1267 unsafe {
1092 unsafe {
1268 NSRunLoop::mainRunLoop().runMode_beforeDate(
1093 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1281,28 +1106,12 @@ where
1281 exit_result = Err(format!(
1106 exit_result = Err(format!(
1282 "Login action ({}) timed out after {:?}; shutting down.",
1107 "Login action ({}) timed out after {:?}; shutting down.",
1283 action, timeout
1108 action, timeout
1285 unsafe {
1111 unsafe {
1286 if vm.canRequestStop() {
1112 if vm.canRequestStop() {
1287 if let Err(err) = vm.requestStopWithError() {
1113 if let Err(err) = vm.requestStopWithError() {
1288− tracing::error!(error = ?err, "failed to request VM stop");
1114+ eprintln!("Failed to request VM stop: {:?}", err);
1290− } else if vm.canStop() {
1291− let handler = RcBlock::new(|_error: *mut NSError| {});
1292− vm.stopWithCompletionHandler(&handler);
1297− Ok(VmOutput::LoginActionFailed { action, reason }) => {
1298− exit_result = Err(format!(
1299− "Login action ({}) failed: {}; shutting down.",
1303− if vm.canRequestStop() {
1304− if let Err(err) = vm.requestStopWithError() {
1305− tracing::error!(error = ?err, "failed to request VM stop");
1307 } else if vm.canStop() {
1116 } else if vm.canStop() {
1308 let handler = RcBlock::new(|_error: *mut NSError| {});
1117 let handler = RcBlock::new(|_error: *mut NSError| {});
@@ -1314,7 +1123,7 @@ where
1314 Err(mpsc::TryRecvError::Empty) => {}
1123 Err(mpsc::TryRecvError::Empty) => {}
1315 Err(mpsc::TryRecvError::Disconnected) => {}
1124 Err(mpsc::TryRecvError::Disconnected) => {}
1317− if state != VZVirtualMachineState::Running {
1126+ if state != objc2_virtualization::VZVirtualMachineState::Running {
1318 //eprintln!("VM stopped with state: {:?}", state);
1127 //eprintln!("VM stopped with state: {:?}", state);
@@ -1324,7 +1133,7 @@ where
1325 io_ctx.shutdown();
1134 io_ctx.shutdown();
1327− exit_result.map_err(Error::msg)
1136+ exit_result
1330fn run_vm(
1139fn run_vm(
@@ -1333,20 +1142,18 @@ fn run_vm(
1333 directory_shares: &[DirectoryShare],
1142 directory_shares: &[DirectoryShare],
1334 cpu_count: usize,
1143 cpu_count: usize,
1335 ram_bytes: u64,
1144 ram_bytes: u64,
1336− status: Option<&StatusEmitter<'_>>,
1145+) -> Result<(), Box<dyn std::error::Error>> {
1338 run_vm_with_io(
1146 run_vm_with_io(
1339 disk_path,
1147 disk_path,
1340 login_actions,
1148 login_actions,
1341 directory_shares,
1149 directory_shares,
1342 cpu_count,
1150 cpu_count,
1343 ram_bytes,
1151 ram_bytes,
1345 spawn_vm_io,
1152 spawn_vm_io,
1349−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
1156+fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
1350 let abs_path = if path.is_absolute() {
1157 let abs_path = if path.is_absolute() {
1351 path.to_path_buf()
1158 path.to_path_buf()
1352 } else {
1159 } else {
@@ -1355,7 +1162,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
1355 let ns_path = NSString::from_str(
1162 let ns_path = NSString::from_str(
1356 abs_path
1163 abs_path
1357 .to_str()
1164 .to_str()
1358− .with_context(|| "non-UTF8 path encountered while building NSURL")?,
1165+ .ok_or("Non-UTF8 path encountered while building NSURL")?,
1360 Ok(NSURL::fileURLWithPath(&ns_path))
1167 Ok(NSURL::fileURLWithPath(&ns_path))
@@ -1370,7 +1177,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
1370 let original = attributes;
1177 let original = attributes;
1372 // Disable translation of carriage return to newline on input
1179 // Disable translation of carriage return to newline on input
1373− attributes.c_iflag &= !libc::ICRNL;
1180+ attributes.c_iflag &= !(libc::ICRNL);
1374 // Disable canonical mode (line buffering), echo, and signal generation
1181 // Disable canonical mode (line buffering), echo, and signal generation
1375 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
1182 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
1376 attributes.c_cc[libc::VMIN] = 0;
1183 attributes.c_cc[libc::VMIN] = 0;
@@ -1398,10 +1205,10 @@ impl Drop for RawModeGuard {
1399// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
1206// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
1400pub fn ensure_signed() {
1207pub fn ensure_signed() {
1401− if env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1208+ if std::env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1404− let exe = env::current_exe().expect("failed to get current exe path");
1211+ let exe = std::env::current_exe().expect("failed to get current exe path");
1405 let exe_str = exe.to_str().expect("exe path not valid utf-8");
1212 let exe_str = exe.to_str().expect("exe path not valid utf-8");
1407 let has_required_entitlements = {
1214 let has_required_entitlements = {
@@ -1423,10 +1230,10 @@ pub fn ensure_signed() {
1425 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1232 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1426− let entitlements_path = env::temp_dir().join("entitlements.plist");
1233+ let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1427− fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
1234+ std::fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
1429− let output = Command::new("codesign")
1236+ let status = Command::new("codesign")
1431 "--sign",
1238 "--sign",
@@ -1435,27 +1242,22 @@ pub fn ensure_signed() {
1435 entitlements_path.to_str().unwrap(),
1242 entitlements_path.to_str().unwrap(),
1436 exe_str,
1243 exe_str,
1438− .output();
1245+ .status();
1440− let _ = fs::remove_file(&entitlements_path);
1247+ let _ = std::fs::remove_file(&entitlements_path);
1442− match output {
1249+ match status {
1443− Ok(o) if o.status.success() => {
1250+ Ok(s) if s.success() => {
1444− let stderr = String::from_utf8_lossy(&o.stderr);
1445− if !stderr.trim().is_empty() {
1446− tracing::debug!(codesign_stderr = %stderr.trim(), "codesign output");
1448− let err = Command::new(&exe).args(env::args_os().skip(1)).exec();
1251+ let err = Command::new(&exe).args(std::env::args_os().skip(1)).exec();
1449− tracing::error!(error = %err, "failed to re-exec after signing");
1252+ eprintln!("failed to re-exec after signing: {err}");
1450 std::process::exit(1);
1253 std::process::exit(1);
1452− Ok(o) => {
1255+ Ok(s) => {
1453− let stderr = String::from_utf8_lossy(&o.stderr);
1256+ eprintln!("codesign failed with status: {s}");
1454− tracing::error!(status = %o.status, codesign_stderr = %stderr.trim(), "codesign failed");
1455 std::process::exit(1);
1257 std::process::exit(1);
1457 Err(e) => {
1259 Err(e) => {
1458− tracing::error!(error = %e, "failed to run codesign");
1260+ eprintln!("failed to run codesign: {e}");
1459 std::process::exit(1);
1261 std::process::exit(1);