@@ -1,7 +1,7 @@
1+use crate::session_manager::{GLOBAL_CACHE_DIR_NAME, INSTANCE_DIR_NAME};
2+use anyhow::{Context, Error, Result, bail};
5 io::{self, Write},
5 io::{self, Write},
@@ -23,8 +23,8 @@ use std::{
25use block2::RcBlock;
25use block2::RcBlock;
26+use bytesize::ByteSize;
26use dispatch2::DispatchQueue;
27use dispatch2::DispatchQueue;
27−use lexopt::prelude::*;
28use objc2::{AnyThread, rc::Retained, runtime::ProtocolObject};
28use objc2::{AnyThread, rc::Retained, runtime::ProtocolObject};
29use objc2_foundation::*;
29use objc2_foundation::*;
30use objc2_virtualization::*;
30use objc2_virtualization::*;
@@ -33,39 +33,46 @@ const DEBIAN_COMPRESSED_DISK_URL: &str = "https://cloud.debian.org/images/cloud/
33const DEBIAN_COMPRESSED_SHA: &str = "6ab9be9e6834adc975268367f2f0235251671184345c34ee13031749fdfbf66fe4c3aafd949a2d98550426090e9ac645e79009c51eb0eefc984c15786570bb38";
33const DEBIAN_COMPRESSED_SHA: &str = "6ab9be9e6834adc975268367f2f0235251671184345c34ee13031749fdfbf66fe4c3aafd949a2d98550426090e9ac645e79009c51eb0eefc984c15786570bb38";
34const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
34const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
35const SHARED_DIRECTORIES_TAG: &str = "shared";
35const SHARED_DIRECTORIES_TAG: &str = "shared";
36+pub const PROJECT_GUEST_BASE: &str = "/usr/local/vibebox-mounts";
37−const BYTES_PER_MB: u64 = 1024 * 1024;
38−const DEFAULT_CPU_COUNT: usize = 2;
39−const DEFAULT_RAM_MB: u64 = 2048;
40−const DEFAULT_RAM_BYTES: u64 = DEFAULT_RAM_MB * BYTES_PER_MB;
41const START_TIMEOUT: Duration = Duration::from_secs(60);
38const START_TIMEOUT: Duration = Duration::from_secs(60);
42−const DEFAULT_EXPECT_TIMEOUT: Duration = Duration::from_secs(30);
43const LOGIN_EXPECT_TIMEOUT: Duration = Duration::from_secs(120);
39const 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");
44const PROVISION_SCRIPT: &str = include_str!("provision.sh");
43const PROVISION_SCRIPT: &str = include_str!("provision.sh");
44+const RESIZE_DISK_SCRIPT: &str = include_str!("resize_disk.sh");
45+const DEFAULT_RAW_NAME: &str = "default.raw";
46+const INSTANCE_RAW_NAME: &str = "instance.raw";
47+const BASE_DISK_RAW_NAME: &str = "disk.raw";
46#[derive(Clone)]
49#[derive(Clone)]
47−pub(crate) enum LoginAction {
50+pub enum LoginAction {
48− Expect { text: String, timeout: Duration },
53+ timeout: Duration,
49 Send(String),
60 Send(String),
50− Script { path: PathBuf, index: usize },
62+use crate::config::BoxConfig;
52use LoginAction::*;
63use LoginAction::*;
54#[derive(Clone)]
65#[derive(Clone)]
55−pub(crate) struct DirectoryShare {
66+pub struct DirectoryShare {
56 host: PathBuf,
67 host: PathBuf,
57 guest: PathBuf,
68 guest: PathBuf,
58 read_only: bool,
69 read_only: bool,
61impl DirectoryShare {
72impl DirectoryShare {
64− mut guest: PathBuf,
73+ pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
66− ) -> Result<Self, Box<dyn std::error::Error>> {
67 if !host.exists() {
74 if !host.exists() {
68− return Err(format!("Host path does not exist: {}", host.display()).into());
75+ bail!(format!("host path does not exist: {}", host.display()));
70 if !guest.is_absolute() {
77 if !guest.is_absolute() {
71 guest = PathBuf::from("/root").join(guest);
78 guest = PathBuf::from("/root").join(guest);
@@ -77,23 +84,22 @@ impl DirectoryShare {
80− pub(crate) fn from_mount_spec(spec: &str) -> Result<Self, Box<dyn std::error::Error>> {
87+ pub fn from_mount_spec(spec: &str) -> Result<Self> {
81 let parts: Vec<&str> = spec.split(':').collect();
88 let parts: Vec<&str> = spec.split(':').collect();
82 if parts.len() < 2 || parts.len() > 3 {
89 if parts.len() < 2 || parts.len() > 3 {
83− return Err(format!("Invalid mount spec: {spec}").into());
90+ bail!(format!("invalid mount spec: {spec}"));
85− let host = PathBuf::from(parts[0]);
92+ let host = expand_tilde_path(parts[0]);
86 let guest = PathBuf::from(parts[1]);
93 let guest = PathBuf::from(parts[1]);
87 let read_only = if parts.len() == 3 {
94 let read_only = if parts.len() == 3 {
88 match parts[2] {
95 match parts[2] {
89 "read-only" => true,
96 "read-only" => true,
90 "read-write" => false,
97 "read-write" => false,
92− return Err(format!(
99+ bail!(format!(
93 "Invalid mount mode '{}'; expected read-only or read-write",
100 "Invalid mount mode '{}'; expected read-only or read-write",
@@ -116,19 +122,49 @@ impl DirectoryShare {
125+fn expand_tilde_path(value: &str) -> PathBuf {
126+ if let Some(stripped) = value.strip_prefix("~/") {
127+ if let Ok(home) = env::var("HOME") {
128+ return PathBuf::from(home).join(stripped);
130+ } else if value == "~"
131+ && let Ok(home) = env::var("HOME")
133+ return PathBuf::from(home);
135+ PathBuf::from(value)
139+ pub cpu_count: usize,
141+ pub disk_bytes: u64,
142+ pub no_default_mounts: bool,
143+ 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 {
119−pub fn run_with_args<F>(args: CliArgs, io_handler: F) -> Result<(), Box<dyn std::error::Error>>
154+pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<()>
121 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
156 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
123− run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new())
158+ run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new(), None)
126−pub(crate) fn run_with_args_and_extras<F>(
161+pub fn run_with_args_and_extras<F>(
127− args: CliArgs,
162+ args: VmArg,
128 io_handler: F,
163 io_handler: F,
129 extra_login_actions: Vec<LoginAction>,
164 extra_login_actions: Vec<LoginAction>,
130 extra_directory_shares: Vec<DirectoryShare>,
165 extra_directory_shares: Vec<DirectoryShare>,
131−) -> Result<(), Box<dyn std::error::Error>>
166+ status: Option<&StatusEmitter<'_>>,
133 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
169 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
@@ -137,7 +173,7 @@ where
137 let project_root = env::current_dir()?;
173 let project_root = env::current_dir()?;
138 let project_name = project_root
174 let project_name = project_root
139 .file_name()
175 .file_name()
140− .ok_or("Project directory has no name")?
176+ .with_context(|| "Project directory has no name")?
141 .to_string_lossy()
177 .to_string_lossy()
142 .into_owned();
178 .into_owned();
@@ -145,10 +181,14 @@ where
145 let cache_home = env::var("XDG_CACHE_HOME")
181 let cache_home = env::var("XDG_CACHE_HOME")
146 .map(PathBuf::from)
182 .map(PathBuf::from)
147 .unwrap_or_else(|_| home.join(".cache"));
183 .unwrap_or_else(|_| home.join(".cache"));
148− let cache_dir = cache_home.join("vibe");
184+ let cache_dir = cache_home.join(GLOBAL_CACHE_DIR_NAME);
149 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
185 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
151− let instance_dir = project_root.join(".vibe");
187+ 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");
153 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
193 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
154 let base_compressed = cache_dir.join(basename_compressed);
194 let base_compressed = cache_dir.join(basename_compressed);
@@ -157,8 +197,8 @@ where
157 basename_compressed.trim_end_matches(".tar.xz")
197 basename_compressed.trim_end_matches(".tar.xz")
160− let default_raw = cache_dir.join("default.raw");
200+ let default_raw = cache_dir.join(DEFAULT_RAW_NAME);
161− let instance_raw = instance_dir.join("instance.raw");
201+ let instance_raw = instance_dir.join(INSTANCE_RAW_NAME);
163 // Prepare system-wide directories
203 // Prepare system-wide directories
164 fs::create_dir_all(&cache_dir)?;
204 fs::create_dir_all(&cache_dir)?;
@@ -167,28 +207,31 @@ where
167 let mise_directory_share =
207 let mise_directory_share =
168 DirectoryShare::new(guest_mise_cache, "/root/.local/share/mise".into(), false)?;
208 DirectoryShare::new(guest_mise_cache, "/root/.local/share/mise".into(), false)?;
170− let disk_path = if let Some(path) = args.disk {
172− return Err(format!("Disk image does not exist: {}", path.display()).into());
176− ensure_default_image(
210+ ensure_default_image(
177− &base_raw,
211+ &base_raw,
178− &base_compressed,
212+ &base_compressed,
179− &default_raw,
213+ &default_raw,
180− std::slice::from_ref(&mise_directory_share),
214+ std::slice::from_ref(&mise_directory_share),
215+ Some(&provision_log),
182− ensure_instance_disk(&instance_raw, &default_raw)?;
218+ let _ = ensure_instance_disk(
221+ ByteSize(args.disk_bytes),
224+ let base_size = fs::metadata(&default_raw)?.len();
184− instance_raw
225+ let instance_size = fs::metadata(&instance_raw)?.len();
185− };
226+ let needs_resize = instance_size > base_size;
227+ let disk_path = instance_raw;
187 let mut login_actions = Vec::new();
229 let mut login_actions = Vec::new();
188 let mut directory_shares = Vec::new();
230 let mut directory_shares = Vec::new();
190 if !args.no_default_mounts {
232 if !args.no_default_mounts {
233+ let project_guest_dir = PathBuf::from(PROJECT_GUEST_BASE).join(project_name);
191− login_actions.push(Send(format!("cd {project_name}")));
234+ login_actions.push(Send(format!("cd {}", project_guest_dir.display())));
193 // 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.
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.
194 // I couldn't find an alternative way to do this --- the MacOS sandbox doesn't apply to the Apple Virtualization system
237 // I couldn't find an alternative way to do this --- the MacOS sandbox doesn't apply to the Apple Virtualization system
@@ -196,38 +239,7 @@ where
196 login_actions.push(Send(r"mount -t tmpfs tmpfs .git/".into()));
239 login_actions.push(Send(r"mount -t tmpfs tmpfs .git/".into()));
199− directory_shares.push(
200− DirectoryShare::new(
202− PathBuf::from("/root/").join(project_name),
205− .expect("Project directory must exist"),
208 directory_shares.push(mise_directory_share);
242 directory_shares.push(mise_directory_share);
210− // Add default shares, if they exist
212− DirectoryShare::new(home.join(".m2"), "/root/.m2".into(), false),
213− DirectoryShare::new(
214− home.join(".cargo/registry"),
215− "/root/.cargo/registry".into(),
218− DirectoryShare::new(home.join(".codex"), "/root/.codex".into(), false),
219− DirectoryShare::new(home.join(".claude"), "/root/.claude".into(), false),
220− DirectoryShare::new(
221− "/Users/zhangjie/Documents/Code/CompletePrograms/vibebox/.ssh".into(),
222− "/root/.ssh".into(),
229− directory_shares.push(share)
233 directory_shares.extend(extra_directory_shares);
245 directory_shares.extend(extra_directory_shares);
@@ -236,199 +248,46 @@ where
236 directory_shares.push(DirectoryShare::from_mount_spec(spec)?);
248 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));
239 if let Some(motd_action) = motd_login_action(&directory_shares) {
256 if let Some(motd_action) = motd_login_action(&directory_shares) {
240 login_actions.push(motd_action);
257 login_actions.push(motd_action);
243 login_actions.extend(extra_login_actions);
260 login_actions.extend(extra_login_actions);
245− // Any user-provided login actions must come after our system ones
246− login_actions.extend(args.login_actions);
248 run_vm_with_io(
262 run_vm_with_io(
249 &disk_path,
263 &disk_path,
250 &login_actions,
264 &login_actions,
251 &directory_shares[..],
265 &directory_shares[..],
252 args.cpu_count,
266 args.cpu_count,
253 args.ram_bytes,
267 args.ram_bytes,
254 io_handler,
269 io_handler,
258−pub fn print_help() {
260− "Vibe is a quick way to spin up a Linux virtual machine on Mac to sandbox LLM agents.
262−vibe [OPTIONS] [disk-image.raw]
266− --help Print this help message.
267− --version Print the version (commit SHA).
268− --no-default-mounts Disable all default mounts.
269− --mount host-path:guest-path[:read-only | :read-write] Mount `host-path` inside VM at `guest-path`.
270− Defaults to read-write.
271− Errors if host-path does not exist.
272− --cpus <count> Number of virtual CPUs (default {DEFAULT_CPU_COUNT}).
273− --ram <megabytes> RAM size in megabytes (default {DEFAULT_RAM_MB}).
274− --script <path/to/script.sh> Run script in VM.
275− --send <some-command> Type `some-command` followed by newline into the VM.
276− --expect <string> [timeout-seconds] Wait for `string` to appear in console output before executing next `--script` or `--send`.
277− If `string` does not appear within timeout (default 30 seconds), shutdown VM with error.
282−pub fn print_version() {
284− println!("https://github.com/lynaghk/vibe/");
285− println!("Git SHA: {}", env!("GIT_SHA"));
289− disk: Option<PathBuf>,
292− no_default_mounts: bool,
293− mounts: Vec<String>,
294− login_actions: Vec<LoginAction>,
300− pub fn version(&self) -> bool {
304− pub fn help(&self) -> bool {
308− pub fn cpu_count(&self) -> usize {
312− pub fn ram_bytes(&self) -> u64 {
316− pub fn ram_mb(&self) -> u64 {
317− self.ram_bytes / BYTES_PER_MB
321−pub fn parse_cli() -> Result<CliArgs, Box<dyn std::error::Error>> {
322− parse_cli_from(env::args_os())
325−pub fn parse_cli_from<I>(args: I) -> Result<CliArgs, Box<dyn std::error::Error>>
327− I: IntoIterator<Item = OsString>,
329− fn os_to_string(value: OsString, flag: &str) -> Result<String, Box<dyn std::error::Error>> {
332− .map_err(|_| format!("{flag} expects valid UTF-8").into())
335− let mut parser = lexopt::Parser::from_iter(args);
336− let mut disk = None;
337− let mut version = false;
338− let mut help = false;
339− let mut no_default_mounts = false;
340− let mut mounts = Vec::new();
341− let mut login_actions = Vec::new();
342− let mut script_index = 0;
343− let mut cpu_count = DEFAULT_CPU_COUNT;
344− let mut ram_bytes = DEFAULT_RAM_BYTES;
346− while let Some(arg) = parser.next()? {
348− Long("version") => version = true,
349− Long("help") | Short('h') => help = true,
350− Long("no-default-mounts") => no_default_mounts = true,
352− let value = os_to_string(parser.value()?, "--cpus")?.parse()?;
354− return Err("--cpus must be >= 1".into());
359− let value: u64 = os_to_string(parser.value()?, "--ram")?.parse()?;
361− return Err("--ram must be >= 1".into());
363− ram_bytes = value * BYTES_PER_MB;
366− mounts.push(os_to_string(parser.value()?, "--mount")?);
369− login_actions.push(Script {
370− path: os_to_string(parser.value()?, "--script")?.into(),
371− index: script_index,
376− login_actions.push(Send(os_to_string(parser.value()?, "--send")?));
379− let text = os_to_string(parser.value()?, "--expect")?;
380− let timeout = match parser.optional_value() {
381− Some(value) => Duration::from_secs(os_to_string(value, "--expect")?.parse()?),
382− None => DEFAULT_EXPECT_TIMEOUT,
384− login_actions.push(Expect { text, timeout });
388− return Err("Only one disk path may be provided".into());
390− disk = Some(PathBuf::from(value));
392− _ => return Err(arg.unexpected().into()),
408−fn script_command_from_path(
411−) -> Result<String, Box<dyn std::error::Error>> {
412− let script = fs::read_to_string(path)
413− .map_err(|err| format!("Failed to read script {}: {err}", path.display()))?;
414− let label = format!("{}_{}", index, path.file_name().unwrap().display());
415− script_command_from_content(&label, &script)
273+pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
418−pub(crate) fn script_command_from_content(
421−) -> Result<String, Box<dyn std::error::Error>> {
422 let marker = "VIBE_SCRIPT_EOF";
274 let marker = "VIBE_SCRIPT_EOF";
423 let guest_dir = "/tmp/vibe-scripts";
275 let guest_dir = "/tmp/vibe-scripts";
424 let guest_path = format!("{guest_dir}/{label}.sh");
276 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);
425 let command = format!(
284 let command = format!(
426− "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
285+ "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{wrapped_script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
428 if script.contains(marker) {
287 if script.contains(marker) {
429− return Err(
288+ bail!(format!(
430− format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
289+ "Script '{label}' contains marker '{marker}', cannot safely upload"
433 Ok(command)
292 Ok(command)
@@ -492,6 +351,12 @@ enum WaitResult {
354+#[derive(PartialEq, Eq)]
495pub enum VmInput {
360pub enum VmInput {
496 Bytes(Vec<u8>),
361 Bytes(Vec<u8>),
497 Shutdown,
362 Shutdown,
@@ -499,6 +364,7 @@ pub enum VmInput {
500enum VmOutput {
365enum VmOutput {
501 LoginActionTimeout { action: String, timeout: Duration },
366 LoginActionTimeout { action: String, timeout: Duration },
367+ LoginActionFailed { action: String, reason: String },
504#[derive(Default)]
370#[derive(Default)]
@@ -535,6 +401,41 @@ impl OutputMonitor {
535 WaitResult::Found
401 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);
540#[derive(Debug)]
441#[derive(Debug)]
@@ -583,15 +484,17 @@ impl IoControl {
583fn ensure_base_image(
484fn ensure_base_image(
584 base_raw: &Path,
485 base_raw: &Path,
585 base_compressed: &Path,
486 base_compressed: &Path,
586−) -> Result<(), Box<dyn std::error::Error>> {
487+ status: Option<&StatusEmitter<'_>>,
587 if base_raw.exists() {
489 if base_raw.exists() {
588 return Ok(());
490 return Ok(());
591 if !base_compressed.exists()
493 if !base_compressed.exists()
592− || std::fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
494+ || fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
594− println!("Downloading base image...");
496+ emit_status(status, "downloading base image...");
497+ tracing::info!("downloading base image");
595 let status = Command::new("curl")
498 let status = Command::new("curl")
597 "--continue-at",
500 "--continue-at",
@@ -605,12 +508,14 @@ fn ensure_base_image(
606 .status()?;
509 .status()?;
607 if !status.success() {
510 if !status.success() {
608− return Err("Failed to download base image".into());
511+ bail!("failed to download base image");
612 // Check SHA
515 // Check SHA
517+ emit_status(status, "verifying base image...");
518+ tracing::info!("verifying base image...");
614 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
519 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
616 let mut child = Command::new("/usr/bin/shasum")
521 let mut child = Command::new("/usr/bin/shasum")
@@ -628,18 +533,25 @@ fn ensure_base_image(
629 let status = child.wait().expect("failed to wait on child");
534 let status = child.wait().expect("failed to wait on child");
630 if !status.success() {
535 if !status.success() {
631− return Err(format!("SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}").into());
537+ "SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}"
635− println!("Decompressing base image...");
542+ emit_status(status, "decompressing base image...");
543+ tracing::info!("decompressing base image...");
636 let status = Command::new("tar")
544 let status = Command::new("tar")
637− .args(["-xOf", &base_compressed.to_string_lossy(), "disk.raw"])
547+ &base_compressed.to_string_lossy(),
638− .stdout(std::fs::File::create(base_raw)?)
550+ .stdout(fs::File::create(base_raw)?)
639 .status()?;
551 .status()?;
641 if !status.success() {
553 if !status.success() {
642− return Err("Failed to decompress base image".into());
554+ bail!("Failed to decompress base image");
@@ -650,24 +562,56 @@ fn ensure_default_image(
650 base_compressed: &Path,
562 base_compressed: &Path,
651 default_raw: &Path,
563 default_raw: &Path,
652 directory_shares: &[DirectoryShare],
564 directory_shares: &[DirectoryShare],
653−) -> Result<(), Box<dyn std::error::Error>> {
565+ provision_log: Option<&Path>,
566+ status: Option<&StatusEmitter<'_>>,
654 if default_raw.exists() {
568 if default_raw.exists() {
655 return Ok(());
569 return Ok(());
658− ensure_base_image(base_raw, base_compressed)?;
572+ ensure_base_image(base_raw, base_compressed, status)?;
660− println!("Configuring base image...");
574+ emit_status(status, "configuring base image...");
575+ tracing::info!("configuring base image...");
661 fs::copy(base_raw, default_raw)?;
576 fs::copy(base_raw, default_raw)?;
663 let provision_command = script_command_from_content("provision.sh", PROVISION_SCRIPT)?;
578 let provision_command = script_command_from_content("provision.sh", PROVISION_SCRIPT)?;
664− run_vm(
579+ let provision_actions = [
666− &[Send(provision_command)],
580+ 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();
593+ BoxConfig::default().cpu_count,
594+ BoxConfig::default().ram_size.as_u64(),
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)
667− directory_shares,
604+ directory_shares,
668− DEFAULT_CPU_COUNT,
605+ BoxConfig::default().cpu_count,
669− DEFAULT_RAM_BYTES,
606+ BoxConfig::default().ram_size.as_u64(),
611+ if let Err(err) = provision_result {
612+ let _ = fs::remove_file(default_raw);
@@ -675,15 +619,47 @@ fn ensure_default_image(
675fn ensure_instance_disk(
619fn ensure_instance_disk(
676 instance_raw: &Path,
620 instance_raw: &Path,
677 template_raw: &Path,
621 template_raw: &Path,
678−) -> Result<(), Box<dyn std::error::Error>> {
622+ target_bytes: ByteSize,
623+ status: Option<&StatusEmitter<'_>>,
679 if instance_raw.exists() {
625 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.",
680− return Ok(());
636+ return Ok(false);
683− println!("Creating instance disk from {}...", template_raw.display());
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");
684− std::fs::create_dir_all(instance_raw.parent().unwrap())?;
652+ fs::create_dir_all(instance_raw.parent().unwrap())?;
653+ if target_size == template_size {
685− fs::copy(template_raw, instance_raw)?;
654+ fs::copy(template_raw, instance_raw)?;
686− Ok(())
655+ return Ok(needs_resize);
658+ let mut dst = fs::File::create(instance_raw)?;
659+ dst.set_len(target_size.as_u64())?;
660+ let mut src = fs::File::open(template_raw)?;
661+ std::io::copy(&mut src, &mut dst)?;
689pub struct IoContext {
665pub struct IoContext {
@@ -699,18 +675,17 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
699 (read_stream.into(), write_stream.into())
675 (read_stream.into(), write_stream.into())
702−pub fn spawn_vm_io_with_hooks<F, G>(
678+pub fn spawn_vm_io_with_hooks<
679+ F: FnMut(&str) -> bool + std::marker::Send + 'static,
680+ G: FnMut(&[u8]) + std::marker::Send + 'static,
703 output_monitor: Arc<OutputMonitor>,
682 output_monitor: Arc<OutputMonitor>,
704 vm_output_fd: OwnedFd,
683 vm_output_fd: OwnedFd,
705 vm_input_fd: OwnedFd,
684 vm_input_fd: OwnedFd,
706 io_control: Arc<IoControl>,
685 io_control: Arc<IoControl>,
707 mut on_line: F,
686 mut on_line: F,
708 mut on_output: G,
687 mut on_output: G,
709−) -> IoContext
688+) -> IoContext {
711− F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
712− G: FnMut(&[u8]) + ::std::marker::Send + 'static,
714 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
689 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
716 // raw_guard is set when we've put the user's terminal into raw mode because we've attached stdin/stdout to the VM.
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.
@@ -858,14 +833,14 @@ where
858 PollResult::Spurious => continue,
833 PollResult::Spurious => continue,
859 PollResult::Ready(bytes) => {
834 PollResult::Ready(bytes) => {
860 if io_control.forward_output() {
835 if io_control.forward_output() {
861− // enable raw mode, if we haven't already
836+ // enable raw mode if we haven't already
862 if raw_guard.lock().unwrap().is_none()
837 if raw_guard.lock().unwrap().is_none()
863 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
838 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
865 *raw_guard.lock().unwrap() = Some(guard);
840 *raw_guard.lock().unwrap() = Some(guard);
868− let mut stdout = std::io::stdout().lock();
843+ let mut stdout = io::stdout().lock();
869 if stdout.write_all(bytes).is_err() {
844 if stdout.write_all(bytes).is_err() {
@@ -881,7 +856,7 @@ where
882 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
857 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
883 let mux_thread = thread::spawn(move || {
858 let mux_thread = thread::spawn(move || {
884− let mut vm_writer = std::fs::File::from(vm_input_fd);
859+ let mut vm_writer = fs::File::from(vm_input_fd);
886 match input_rx.recv() {
861 match input_rx.recv() {
887 Ok(VmInput::Bytes(data)) => {
862 Ok(VmInput::Bytes(data)) => {
@@ -911,7 +886,7 @@ pub fn spawn_vm_io_with_line_handler<F>(
911 on_line: F,
886 on_line: F,
912) -> IoContext
887) -> IoContext
914− F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
889+ F: FnMut(&str) -> bool + std::marker::Send + 'static,
916 spawn_vm_io_with_hooks(
891 spawn_vm_io_with_hooks(
917 output_monitor,
892 output_monitor,
@@ -931,6 +906,36 @@ pub fn spawn_vm_io(
931 spawn_vm_io_with_line_handler(output_monitor, vm_output_fd, vm_input_fd, |_| false)
906 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);
934impl IoContext {
939impl IoContext {
935 pub fn shutdown(self) {
940 pub fn shutdown(self) {
936 let _ = self.input_tx.send(VmInput::Shutdown);
941 let _ = self.input_tx.send(VmInput::Shutdown);
@@ -948,7 +953,7 @@ fn create_vm_configuration(
948 vm_writes_to_fd: OwnedFd,
953 vm_writes_to_fd: OwnedFd,
949 cpu_count: usize,
954 cpu_count: usize,
950 ram_bytes: u64,
955 ram_bytes: u64,
951−) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
956+) -> Result<Retained<VZVirtualMachineConfiguration>> {
953 let platform =
958 let platform =
954 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
959 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -982,7 +987,7 @@ fn create_vm_configuration(
983 VZDiskImageCachingMode::Automatic,
988 VZDiskImageCachingMode::Automatic,
984 VZDiskImageSynchronizationMode::Full,
989 VZDiskImageSynchronizationMode::Full,
987 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
992 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
988 VZVirtioBlockDeviceConfiguration::alloc(),
993 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -1069,7 +1074,7 @@ fn create_vm_configuration(
1069 // Validate
1074 // Validate
1070 config.validateWithError().map_err(|e| {
1075 config.validateWithError().map_err(|e| {
1071 io::Error::other(format!(
1076 io::Error::other(format!(
1072− "Invalid VM configuration: {:?}",
1077+ "invalid VM configuration: {:?}",
1073 e.localizedDescription()
1078 e.localizedDescription()
@@ -1078,9 +1083,9 @@ fn create_vm_configuration(
1081−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
1086+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
1082 unsafe {
1087 unsafe {
1083− let temp_dir = std::env::temp_dir();
1088+ let temp_dir = env::temp_dir();
1084 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
1089 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
1085 let url = nsurl_from_path(&temp_path)?;
1090 let url = nsurl_from_path(&temp_path)?;
1086 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
1091 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -1096,8 +1101,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std
1096fn spawn_login_actions_thread(
1101fn spawn_login_actions_thread(
1097 login_actions: Vec<LoginAction>,
1102 login_actions: Vec<LoginAction>,
1098 output_monitor: Arc<OutputMonitor>,
1103 output_monitor: Arc<OutputMonitor>,
1099− input_tx: mpsc::Sender<VmInput>,
1104+ input_tx: Sender<VmInput>,
1100− vm_output_tx: mpsc::Sender<VmOutput>,
1105+ vm_output_tx: Sender<VmOutput>,
1101) -> thread::JoinHandle<()> {
1106) -> thread::JoinHandle<()> {
1102 thread::spawn(move || {
1107 thread::spawn(move || {
1103 for a in login_actions {
1108 for a in login_actions {
@@ -1111,22 +1116,31 @@ 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),
1114 Send(mut text) => {
1140 Send(mut text) => {
1115 text.push('\n'); // Type the newline so the command is actually submitted.
1141 text.push('\n'); // Type the newline so the command is actually submitted.
1116 input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
1142 input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
1118− Script { path, index } => {
1119− let command = match script_command_from_path(&path, index) {
1120− Ok(command) => command,
1122− eprintln!("{err}");
1126− let mut text = command;
1128− input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
@@ -1138,8 +1152,9 @@ fn run_vm_with_io<F>(
1138 directory_shares: &[DirectoryShare],
1152 directory_shares: &[DirectoryShare],
1139 cpu_count: usize,
1153 cpu_count: usize,
1140 ram_bytes: u64,
1154 ram_bytes: u64,
1155+ status: Option<&StatusEmitter<'_>>,
1141 io_handler: F,
1156 io_handler: F,
1142−) -> Result<(), Box<dyn std::error::Error>>
1157+) -> Result<()>
1144 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
1159 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
@@ -1186,21 +1201,23 @@ where
1187 match rx.try_recv() {
1202 match rx.try_recv() {
1188 Ok(result) => {
1203 Ok(result) => {
1189− result.map_err(|e| format!("Failed to start VM: {}", e))?;
1204+ result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
1192 Err(mpsc::TryRecvError::Empty) => continue,
1207 Err(mpsc::TryRecvError::Empty) => continue,
1193 Err(mpsc::TryRecvError::Disconnected) => {
1208 Err(mpsc::TryRecvError::Disconnected) => {
1194− return Err("VM start channel disconnected".into());
1209+ bail!("VM start channel disconnected");
1199 if Instant::now() >= start_deadline {
1214 if Instant::now() >= start_deadline {
1200− return Err("Timed out waiting for VM to start".into());
1215+ bail!("Timed out waiting for VM to start");
1203− println!("VM booting...");
1218+ emit_status(status, "vm booting... go vibecoder!");
1219+ tracing::info!("vm booting... go vibecoder!");
1220+ tracing::info!("vm booting");
1205 let output_monitor = Arc::new(OutputMonitor::default());
1222 let output_monitor = Arc::new(OutputMonitor::default());
1206 let io_ctx = io_handler(output_monitor.clone(), we_read_from, we_write_to);
1223 let io_ctx = io_handler(output_monitor.clone(), we_read_from, we_write_to);
@@ -1245,7 +1262,7 @@ where
1247 let mut last_state = None;
1264 let mut last_state = None;
1248− let mut exit_result = Ok(());
1265+ let mut exit_result: Result<(), String> = Ok(());
1250 unsafe {
1267 unsafe {
1251 NSRunLoop::mainRunLoop().runMode_beforeDate(
1268 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1264,12 +1281,28 @@ where
1264 exit_result = Err(format!(
1281 exit_result = Err(format!(
1265 "Login action ({}) timed out after {:?}; shutting down.",
1282 "Login action ({}) timed out after {:?}; shutting down.",
1266 action, timeout
1283 action, timeout
1269 unsafe {
1285 unsafe {
1270 if vm.canRequestStop() {
1286 if vm.canRequestStop() {
1271 if let Err(err) = vm.requestStopWithError() {
1287 if let Err(err) = vm.requestStopWithError() {
1272− eprintln!("Failed to request VM stop: {:?}", err);
1288+ tracing::error!(error = ?err, "failed to request VM stop");
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");
1274 } else if vm.canStop() {
1307 } else if vm.canStop() {
1275 let handler = RcBlock::new(|_error: *mut NSError| {});
1308 let handler = RcBlock::new(|_error: *mut NSError| {});
@@ -1281,7 +1314,7 @@ where
1281 Err(mpsc::TryRecvError::Empty) => {}
1314 Err(mpsc::TryRecvError::Empty) => {}
1282 Err(mpsc::TryRecvError::Disconnected) => {}
1315 Err(mpsc::TryRecvError::Disconnected) => {}
1284− if state != objc2_virtualization::VZVirtualMachineState::Running {
1317+ if state != VZVirtualMachineState::Running {
1285 //eprintln!("VM stopped with state: {:?}", state);
1318 //eprintln!("VM stopped with state: {:?}", state);
@@ -1291,7 +1324,7 @@ where
1292 io_ctx.shutdown();
1325 io_ctx.shutdown();
1294− exit_result
1327+ exit_result.map_err(Error::msg)
1297fn run_vm(
1330fn run_vm(
@@ -1300,18 +1333,20 @@ fn run_vm(
1300 directory_shares: &[DirectoryShare],
1333 directory_shares: &[DirectoryShare],
1301 cpu_count: usize,
1334 cpu_count: usize,
1302 ram_bytes: u64,
1335 ram_bytes: u64,
1303−) -> Result<(), Box<dyn std::error::Error>> {
1336+ status: Option<&StatusEmitter<'_>>,
1304 run_vm_with_io(
1338 run_vm_with_io(
1305 disk_path,
1339 disk_path,
1306 login_actions,
1340 login_actions,
1307 directory_shares,
1341 directory_shares,
1308 cpu_count,
1342 cpu_count,
1309 ram_bytes,
1343 ram_bytes,
1310 spawn_vm_io,
1345 spawn_vm_io,
1314−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
1349+fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
1315 let abs_path = if path.is_absolute() {
1350 let abs_path = if path.is_absolute() {
1316 path.to_path_buf()
1351 path.to_path_buf()
1317 } else {
1352 } else {
@@ -1320,7 +1355,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::E
1320 let ns_path = NSString::from_str(
1355 let ns_path = NSString::from_str(
1321 abs_path
1356 abs_path
1322 .to_str()
1357 .to_str()
1323− .ok_or("Non-UTF8 path encountered while building NSURL")?,
1358+ .with_context(|| "non-UTF8 path encountered while building NSURL")?,
1325 Ok(NSURL::fileURLWithPath(&ns_path))
1360 Ok(NSURL::fileURLWithPath(&ns_path))
@@ -1335,7 +1370,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
1335 let original = attributes;
1370 let original = attributes;
1337 // Disable translation of carriage return to newline on input
1372 // Disable translation of carriage return to newline on input
1338− attributes.c_iflag &= !(libc::ICRNL);
1373+ attributes.c_iflag &= !libc::ICRNL;
1339 // Disable canonical mode (line buffering), echo, and signal generation
1374 // Disable canonical mode (line buffering), echo, and signal generation
1340 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
1375 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
1341 attributes.c_cc[libc::VMIN] = 0;
1376 attributes.c_cc[libc::VMIN] = 0;
@@ -1363,7 +1398,10 @@ impl Drop for RawModeGuard {
1364// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
1399// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
1365pub fn ensure_signed() {
1400pub fn ensure_signed() {
1401+ if env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1366− let exe = std::env::current_exe().expect("failed to get current exe path");
1404+ let exe = env::current_exe().expect("failed to get current exe path");
1367 let exe_str = exe.to_str().expect("exe path not valid utf-8");
1405 let exe_str = exe.to_str().expect("exe path not valid utf-8");
1369 let has_required_entitlements = {
1407 let has_required_entitlements = {
@@ -1385,10 +1423,10 @@ pub fn ensure_signed() {
1387 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1425 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1388− let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1426+ let entitlements_path = env::temp_dir().join("entitlements.plist");
1389− std::fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
1427+ fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
1391− let status = Command::new("codesign")
1429+ let output = Command::new("codesign")
1393 "--sign",
1431 "--sign",
@@ -1397,22 +1435,27 @@ pub fn ensure_signed() {
1397 entitlements_path.to_str().unwrap(),
1435 entitlements_path.to_str().unwrap(),
1398 exe_str,
1436 exe_str,
1400− .status();
1438+ .output();
1402− let _ = std::fs::remove_file(&entitlements_path);
1440+ let _ = fs::remove_file(&entitlements_path);
1404− match status {
1442+ match output {
1405− Ok(s) if s.success() => {
1443+ Ok(o) if o.status.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");
1406− let err = Command::new(&exe).args(std::env::args_os().skip(1)).exec();
1448+ let err = Command::new(&exe).args(env::args_os().skip(1)).exec();
1407− eprintln!("failed to re-exec after signing: {err}");
1449+ tracing::error!(error = %err, "failed to re-exec after signing");
1408 std::process::exit(1);
1450 std::process::exit(1);
1410− Ok(s) => {
1452+ Ok(o) => {
1411− eprintln!("codesign failed with status: {s}");
1453+ let stderr = String::from_utf8_lossy(&o.stderr);
1454+ tracing::error!(status = %o.status, codesign_stderr = %stderr.trim(), "codesign failed");
1412 std::process::exit(1);
1455 std::process::exit(1);
1414 Err(e) => {
1457 Err(e) => {
1415− eprintln!("failed to run codesign: {e}");
1458+ tracing::error!(error = %e, "failed to run codesign");
1416 std::process::exit(1);
1459 std::process::exit(1);