@@ -1,8 +1,7 @@
11use crate::session_manager::{GLOBAL_CACHE_DIR_NAME, INSTANCE_DIR_NAME};
2+use anyhow::{Context, Error, Result, bail};
23use std::{
3− env,
4− ffi::OsString,
5− fs,
4+ env, fs,
65 io::{self, Write},
76 os::{
87 fd::RawFd,
@@ -24,8 +23,8 @@ use std::{
2423};
2524
2625use block2::RcBlock;
26+use bytesize::ByteSize;
2727use dispatch2::DispatchQueue;
28−use lexopt::prelude::*;
2928use objc2::{AnyThread, rc::Retained, runtime::ProtocolObject};
3029use objc2_foundation::*;
3130use objc2_virtualization::*;
@@ -34,39 +33,46 @@ const DEBIAN_COMPRESSED_DISK_URL: &str = "https://cloud.debian.org/images/cloud/
3433const DEBIAN_COMPRESSED_SHA: &str = "6ab9be9e6834adc975268367f2f0235251671184345c34ee13031749fdfbf66fe4c3aafd949a2d98550426090e9ac645e79009c51eb0eefc984c15786570bb38";
3534const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
3635const SHARED_DIRECTORIES_TAG: &str = "shared";
36+pub const PROJECT_GUEST_BASE: &str = "/usr/local/vibebox-mounts";
3737
38−const BYTES_PER_MB: u64 = 1024 * 1024;
39−const DEFAULT_CPU_COUNT: usize = 2;
40−const DEFAULT_RAM_MB: u64 = 2048;
41−const DEFAULT_RAM_BYTES: u64 = DEFAULT_RAM_MB * BYTES_PER_MB;
4238const START_TIMEOUT: Duration = Duration::from_secs(60);
43−const DEFAULT_EXPECT_TIMEOUT: Duration = Duration::from_secs(30);
4439const LOGIN_EXPECT_TIMEOUT: Duration = Duration::from_secs(120);
40+const PROVISION_EXPECT_TIMEOUT: Duration = Duration::from_secs(900);
41+
42+const ERROR_REPORT_SCRIPT: &str = include_str!("error_report.sh");
4543const 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";
4648
4749#[derive(Clone)]
48−pub(crate) enum LoginAction {
49− Expect { text: String, timeout: Duration },
50+pub enum LoginAction {
51+ Expect {
52+ text: String,
53+ timeout: Duration,
54+ },
55+ ExpectEither {
56+ success: String,
57+ failure: String,
58+ timeout: Duration,
59+ },
5060 Send(String),
51− Script { path: PathBuf, index: usize },
5261}
62+use crate::config::BoxConfig;
5363use LoginAction::*;
5464
5565#[derive(Clone)]
56−pub(crate) struct DirectoryShare {
66+pub struct DirectoryShare {
5767 host: PathBuf,
5868 guest: PathBuf,
5969 read_only: bool,
6070}
6171
6272impl DirectoryShare {
63− pub(crate) fn new(
64− host: PathBuf,
65− mut guest: PathBuf,
66− read_only: bool,
67− ) -> Result<Self, Box<dyn std::error::Error>> {
73+ pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
6874 if !host.exists() {
69− return Err(format!("Host path does not exist: {}", host.display()).into());
75+ bail!(format!("host path does not exist: {}", host.display()));
7076 }
7177 if !guest.is_absolute() {
7278 guest = PathBuf::from("/root").join(guest);
@@ -78,23 +84,22 @@ impl DirectoryShare {
7884 })
7985 }
8086
81− 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> {
8288 let parts: Vec<&str> = spec.split(':').collect();
8389 if parts.len() < 2 || parts.len() > 3 {
84− return Err(format!("Invalid mount spec: {spec}").into());
90+ bail!(format!("invalid mount spec: {spec}"));
8591 }
86− let host = PathBuf::from(parts[0]);
92+ let host = expand_tilde_path(parts[0]);
8793 let guest = PathBuf::from(parts[1]);
8894 let read_only = if parts.len() == 3 {
8995 match parts[2] {
9096 "read-only" => true,
9197 "read-write" => false,
9298 _ => {
93− return Err(format!(
99+ bail!(format!(
94100 "Invalid mount mode '{}'; expected read-only or read-write",
95101 parts[2]
96− )
97− .into());
102+ ));
98103 }
99104 }
100105 } else {
@@ -117,19 +122,49 @@ impl DirectoryShare {
117122 }
118123}
119124
120−pub fn run_with_args<F>(args: CliArgs, io_handler: F) -> Result<(), Box<dyn std::error::Error>>
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);
129+ }
130+ } else if value == "~"
131+ && let Ok(home) = env::var("HOME")
132+ {
133+ return PathBuf::from(home);
134+ }
135+ PathBuf::from(value)
136+}
137+
138+pub struct VmArg {
139+ pub cpu_count: usize,
140+ pub ram_bytes: u64,
141+ pub disk_bytes: u64,
142+ pub no_default_mounts: bool,
143+ pub mounts: Vec<String>,
144+}
145+
146+type StatusEmitter<'a> = dyn Fn(&str) + std::marker::Send + Sync + 'a;
147+
148+fn emit_status(status: Option<&StatusEmitter<'_>>, message: &str) {
149+ if let Some(status) = status {
150+ status(message);
151+ }
152+}
153+
154+pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<()>
121155where
122156 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
123157{
124− 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)
125159}
126160
127−pub(crate) fn run_with_args_and_extras<F>(
128− args: CliArgs,
161+pub fn run_with_args_and_extras<F>(
162+ args: VmArg,
129163 io_handler: F,
130164 extra_login_actions: Vec<LoginAction>,
131165 extra_directory_shares: Vec<DirectoryShare>,
132−) -> Result<(), Box<dyn std::error::Error>>
166+ status: Option<&StatusEmitter<'_>>,
167+) -> Result<()>
133168where
134169 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
135170{
@@ -138,7 +173,7 @@ where
138173 let project_root = env::current_dir()?;
139174 let project_name = project_root
140175 .file_name()
141− .ok_or("Project directory has no name")?
176+ .with_context(|| "Project directory has no name")?
142177 .to_string_lossy()
143178 .into_owned();
144179
@@ -150,6 +185,10 @@ where
150185 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
151186
152187 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");
153192
154193 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
155194 let base_compressed = cache_dir.join(basename_compressed);
@@ -158,8 +197,8 @@ where
158197 basename_compressed.trim_end_matches(".tar.xz")
159198 ));
160199
161− let default_raw = cache_dir.join("default.raw");
162− let instance_raw = instance_dir.join("instance.raw");
200+ let default_raw = cache_dir.join(DEFAULT_RAW_NAME);
201+ let instance_raw = instance_dir.join(INSTANCE_RAW_NAME);
163202
164203 // Prepare system-wide directories
165204 fs::create_dir_all(&cache_dir)?;
@@ -168,28 +207,31 @@ where
168207 let mise_directory_share =
169208 DirectoryShare::new(guest_mise_cache, "/root/.local/share/mise".into(), false)?;
170209
171− let disk_path = if let Some(path) = args.disk {
172− if !path.exists() {
173− return Err(format!("Disk image does not exist: {}", path.display()).into());
174− }
175− path
176− } else {
177− ensure_default_image(
178− &base_raw,
179− &base_compressed,
180− &default_raw,
181− std::slice::from_ref(&mise_directory_share),
182− )?;
183− ensure_instance_disk(&instance_raw, &default_raw)?;
184−
185− instance_raw
186− };
210+ ensure_default_image(
211+ &base_raw,
212+ &base_compressed,
213+ &default_raw,
214+ std::slice::from_ref(&mise_directory_share),
215+ Some(&provision_log),
216+ status,
217+ )?;
218+ let _ = ensure_instance_disk(
219+ &instance_raw,
220+ &default_raw,
221+ ByteSize(args.disk_bytes),
222+ status,
223+ )?;
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;
187228
188229 let mut login_actions = Vec::new();
189230 let mut directory_shares = Vec::new();
190231
191232 if !args.no_default_mounts {
192− login_actions.push(Send(format!("cd {project_name}")));
233+ let project_guest_dir = PathBuf::from(PROJECT_GUEST_BASE).join(project_name);
234+ login_actions.push(Send(format!("cd {}", project_guest_dir.display())));
193235
194236 // 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.
195237 // I couldn't find an alternative way to do this --- the MacOS sandbox doesn't apply to the Apple Virtualization system
@@ -197,32 +239,7 @@ where
197239 login_actions.push(Send(r"mount -t tmpfs tmpfs .git/".into()));
198240 }
199241
200− directory_shares.push(
201− DirectoryShare::new(
202− project_root,
203− PathBuf::from("/root/").join(project_name),
204− false,
205− )
206− .expect("Project directory must exist"),
207− );
208−
209242 directory_shares.push(mise_directory_share);
210−
211− // Add default shares, if they exist
212− for share in [
213− DirectoryShare::new(home.join(".codex"), "/usr/local/codex".into(), false),
214− DirectoryShare::new(home.join(".claude"), "/usr/local/claude".into(), false),
215− DirectoryShare::new(
216− "/Users/zhangjie/Documents/Code/CompletePrograms/vibebox/.ssh".into(),
217− "/usr/local/ssh".into(),
218− true,
219− ),
220− ]
221− .into_iter()
222− .flatten()
223− {
224− directory_shares.push(share)
225− }
226243 }
227244
228245 directory_shares.extend(extra_directory_shares);
@@ -231,199 +248,46 @@ where
231248 directory_shares.push(DirectoryShare::from_mount_spec(spec)?);
232249 }
233250
251+ if needs_resize {
252+ let resize_cmd = script_command_from_content("resize_disk.sh", RESIZE_DISK_SCRIPT)?;
253+ login_actions.push(Send(resize_cmd));
254+ }
255+
234256 if let Some(motd_action) = motd_login_action(&directory_shares) {
235257 login_actions.push(motd_action);
236258 }
237259
238260 login_actions.extend(extra_login_actions);
239261
240− // Any user-provided login actions must come after our system ones
241− login_actions.extend(args.login_actions);
242−
243262 run_vm_with_io(
244263 &disk_path,
245264 &login_actions,
246265 &directory_shares[..],
247266 args.cpu_count,
248267 args.ram_bytes,
268+ status,
249269 io_handler,
250270 )
251271}
252272
253−pub fn print_help() {
254− println!(
255− "Vibe is a quick way to spin up a Linux virtual machine on Mac to sandbox LLM agents.
256−
257−vibe [OPTIONS] [disk-image.raw]
258−
259−Options
260−
261− --help Print this help message.
262− --version Print the version (commit SHA).
263− --no-default-mounts Disable all default mounts.
264− --mount host-path:guest-path[:read-only | :read-write] Mount `host-path` inside VM at `guest-path`.
265− Defaults to read-write.
266− Errors if host-path does not exist.
267− --cpus <count> Number of virtual CPUs (default {DEFAULT_CPU_COUNT}).
268− --ram <megabytes> RAM size in megabytes (default {DEFAULT_RAM_MB}).
269− --script <path/to/script.sh> Run script in VM.
270− --send <some-command> Type `some-command` followed by newline into the VM.
271− --expect <string> [timeout-seconds] Wait for `string` to appear in console output before executing next `--script` or `--send`.
272− If `string` does not appear within timeout (default 30 seconds), shutdown VM with error.
273−"
274− );
275−}
276−
277−pub fn print_version() {
278− println!("Vibe");
279− println!("https://github.com/lynaghk/vibe/");
280− println!("Git SHA: {}", env!("GIT_SHA"));
281−}
282−
283−pub struct CliArgs {
284− disk: Option<PathBuf>,
285− version: bool,
286− help: bool,
287− no_default_mounts: bool,
288− mounts: Vec<String>,
289− login_actions: Vec<LoginAction>,
290− cpu_count: usize,
291− ram_bytes: u64,
292−}
293−
294−impl CliArgs {
295− pub fn version(&self) -> bool {
296− self.version
297− }
298−
299− pub fn help(&self) -> bool {
300− self.help
301− }
302−
303− pub fn cpu_count(&self) -> usize {
304− self.cpu_count
305− }
306−
307− pub fn ram_bytes(&self) -> u64 {
308− self.ram_bytes
309− }
310−
311− pub fn ram_mb(&self) -> u64 {
312− self.ram_bytes / BYTES_PER_MB
313− }
314−}
315−
316−pub fn parse_cli() -> Result<CliArgs, Box<dyn std::error::Error>> {
317− parse_cli_from(env::args_os())
318−}
319−
320−pub fn parse_cli_from<I>(args: I) -> Result<CliArgs, Box<dyn std::error::Error>>
321−where
322− I: IntoIterator<Item = OsString>,
323−{
324− fn os_to_string(value: OsString, flag: &str) -> Result<String, Box<dyn std::error::Error>> {
325− value
326− .into_string()
327− .map_err(|_| format!("{flag} expects valid UTF-8").into())
328− }
329−
330− let mut parser = lexopt::Parser::from_iter(args);
331− let mut disk = None;
332− let mut version = false;
333− let mut help = false;
334− let mut no_default_mounts = false;
335− let mut mounts = Vec::new();
336− let mut login_actions = Vec::new();
337− let mut script_index = 0;
338− let mut cpu_count = DEFAULT_CPU_COUNT;
339− let mut ram_bytes = DEFAULT_RAM_BYTES;
340−
341− while let Some(arg) = parser.next()? {
342− match arg {
343− Long("version") => version = true,
344− Long("help") | Short('h') => help = true,
345− Long("no-default-mounts") => no_default_mounts = true,
346− Long("cpus") => {
347− let value = os_to_string(parser.value()?, "--cpus")?.parse()?;
348− if value == 0 {
349− return Err("--cpus must be >= 1".into());
350− }
351− cpu_count = value;
352− }
353− Long("ram") => {
354− let value: u64 = os_to_string(parser.value()?, "--ram")?.parse()?;
355− if value == 0 {
356− return Err("--ram must be >= 1".into());
357− }
358− ram_bytes = value * BYTES_PER_MB;
359− }
360− Long("mount") => {
361− mounts.push(os_to_string(parser.value()?, "--mount")?);
362− }
363− Long("script") => {
364− login_actions.push(Script {
365− path: os_to_string(parser.value()?, "--script")?.into(),
366− index: script_index,
367− });
368− script_index += 1;
369− }
370− Long("send") => {
371− login_actions.push(Send(os_to_string(parser.value()?, "--send")?));
372− }
373− Long("expect") => {
374− let text = os_to_string(parser.value()?, "--expect")?;
375− let timeout = match parser.optional_value() {
376− Some(value) => Duration::from_secs(os_to_string(value, "--expect")?.parse()?),
377− None => DEFAULT_EXPECT_TIMEOUT,
378− };
379− login_actions.push(Expect { text, timeout });
380− }
381− Value(value) => {
382− if disk.is_some() {
383− return Err("Only one disk path may be provided".into());
384− }
385− disk = Some(PathBuf::from(value));
386− }
387− _ => return Err(arg.unexpected().into()),
388− }
389− }
390−
391− Ok(CliArgs {
392− disk,
393− version,
394− help,
395− no_default_mounts,
396− mounts,
397− login_actions,
398− cpu_count,
399− ram_bytes,
400− })
401−}
402−
403−fn script_command_from_path(
404− path: &Path,
405− index: usize,
406−) -> Result<String, Box<dyn std::error::Error>> {
407− let script = fs::read_to_string(path)
408− .map_err(|err| format!("Failed to read script {}: {err}", path.display()))?;
409− let label = format!("{}_{}", index, path.file_name().unwrap().display());
410− script_command_from_content(&label, &script)
411−}
412−
413−pub(crate) fn script_command_from_content(
414− label: &str,
415− script: &str,
416−) -> Result<String, Box<dyn std::error::Error>> {
273+pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
417274 let marker = "VIBE_SCRIPT_EOF";
418275 let guest_dir = "/tmp/vibe-scripts";
419276 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,
279+ _ => script,
280+ };
281+ let wrapped_script = ERROR_REPORT_SCRIPT
282+ .replace("__LABEL__", label)
283+ .replace("__SCRIPT_BODY__", script_body);
420284 let command = format!(
421− "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}"
422286 );
423287 if script.contains(marker) {
424− return Err(
425− format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
426− );
288+ bail!(format!(
289+ "Script '{label}' contains marker '{marker}', cannot safely upload"
290+ ));
427291 }
428292 Ok(command)
429293}
@@ -487,6 +351,12 @@ enum WaitResult {
487351 Found,
488352}
489353
354+#[derive(PartialEq, Eq)]
355+enum WaitAnyResult {
356+ Timeout,
357+ Found(usize),
358+}
359+
490360pub enum VmInput {
491361 Bytes(Vec<u8>),
492362 Shutdown,
@@ -494,6 +364,7 @@ pub enum VmInput {
494364
495365enum VmOutput {
496366 LoginActionTimeout { action: String, timeout: Duration },
367+ LoginActionFailed { action: String, reason: String },
497368}
498369
499370#[derive(Default)]
@@ -530,6 +401,41 @@ impl OutputMonitor {
530401 WaitResult::Found
531402 }
532403 }
404+
405+ fn wait_for_any(&self, needles: &[&str], timeout: Duration) -> WaitAnyResult {
406+ let mut found: Option<usize> = None;
407+ let (_unused, timeout_result) = self
408+ .condvar
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();
412+ found = Some(idx);
413+ false
414+ } else {
415+ true
416+ }
417+ })
418+ .unwrap();
419+
420+ if timeout_result.timed_out() {
421+ WaitAnyResult::Timeout
422+ } else {
423+ WaitAnyResult::Found(found.unwrap_or(0))
424+ }
425+ }
426+}
427+
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);
435+ }
436+ }
437+ }
438+ best
533439}
534440
535441#[derive(Debug)]
@@ -578,15 +484,17 @@ impl IoControl {
578484fn ensure_base_image(
579485 base_raw: &Path,
580486 base_compressed: &Path,
581−) -> Result<(), Box<dyn std::error::Error>> {
487+ status: Option<&StatusEmitter<'_>>,
488+) -> Result<()> {
582489 if base_raw.exists() {
583490 return Ok(());
584491 }
585492
586493 if !base_compressed.exists()
587− || 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
588495 {
589− println!("Downloading base image...");
496+ emit_status(status, "downloading base image...");
497+ tracing::info!("downloading base image");
590498 let status = Command::new("curl")
591499 .args([
592500 "--continue-at",
@@ -600,12 +508,14 @@ fn ensure_base_image(
600508 ])
601509 .status()?;
602510 if !status.success() {
603− return Err("Failed to download base image".into());
511+ bail!("failed to download base image");
604512 }
605513 }
606514
607515 // Check SHA
608516 {
517+ emit_status(status, "verifying base image...");
518+ tracing::info!("verifying base image...");
609519 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
610520
611521 let mut child = Command::new("/usr/bin/shasum")
@@ -623,18 +533,25 @@ fn ensure_base_image(
623533
624534 let status = child.wait().expect("failed to wait on child");
625535 if !status.success() {
626− return Err(format!("SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}").into());
536+ bail!(format!(
537+ "SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}"
538+ ));
627539 }
628540 }
629541
630− println!("Decompressing base image...");
542+ emit_status(status, "decompressing base image...");
543+ tracing::info!("decompressing base image...");
631544 let status = Command::new("tar")
632− .args(["-xOf", &base_compressed.to_string_lossy(), "disk.raw"])
633− .stdout(std::fs::File::create(base_raw)?)
545+ .args([
546+ "-xOf",
547+ &base_compressed.to_string_lossy(),
548+ BASE_DISK_RAW_NAME,
549+ ])
550+ .stdout(fs::File::create(base_raw)?)
634551 .status()?;
635552
636553 if !status.success() {
637− return Err("Failed to decompress base image".into());
554+ bail!("Failed to decompress base image");
638555 }
639556
640557 Ok(())
@@ -645,24 +562,56 @@ fn ensure_default_image(
645562 base_compressed: &Path,
646563 default_raw: &Path,
647564 directory_shares: &[DirectoryShare],
648−) -> Result<(), Box<dyn std::error::Error>> {
565+ provision_log: Option<&Path>,
566+ status: Option<&StatusEmitter<'_>>,
567+) -> Result<()> {
649568 if default_raw.exists() {
650569 return Ok(());
651570 }
652571
653− ensure_base_image(base_raw, base_compressed)?;
572+ ensure_base_image(base_raw, base_compressed, status)?;
654573
655− println!("Configuring base image...");
574+ emit_status(status, "configuring base image...");
575+ tracing::info!("configuring base image...");
656576 fs::copy(base_raw, default_raw)?;
657577
658578 let provision_command = script_command_from_content("provision.sh", PROVISION_SCRIPT)?;
659− run_vm(
660− default_raw,
661− &[Send(provision_command)],
662− directory_shares,
663− DEFAULT_CPU_COUNT,
664− DEFAULT_RAM_BYTES,
665− )?;
579+ let provision_actions = [
580+ Send(provision_command),
581+ ExpectEither {
582+ success: "VIBEBOX_PROVISION_OK".to_string(),
583+ failure: "VIBEBOX_PROVISION_FAILED".to_string(),
584+ timeout: PROVISION_EXPECT_TIMEOUT,
585+ },
586+ ];
587+ let provision_result = if let Some(log_path) = provision_log {
588+ let log_path = log_path.to_path_buf();
589+ run_vm_with_io(
590+ default_raw,
591+ &provision_actions,
592+ directory_shares,
593+ BoxConfig::default().cpu_count,
594+ BoxConfig::default().ram_size.as_u64(),
595+ status,
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)
598+ },
599+ )
600+ } else {
601+ run_vm(
602+ default_raw,
603+ &provision_actions,
604+ directory_shares,
605+ BoxConfig::default().cpu_count,
606+ BoxConfig::default().ram_size.as_u64(),
607+ status,
608+ )
609+ };
610+
611+ if let Err(err) = provision_result {
612+ let _ = fs::remove_file(default_raw);
613+ return Err(err);
614+ }
666615
667616 Ok(())
668617}
@@ -670,15 +619,47 @@ fn ensure_default_image(
670619fn ensure_instance_disk(
671620 instance_raw: &Path,
672621 template_raw: &Path,
673−) -> Result<(), Box<dyn std::error::Error>> {
622+ target_bytes: ByteSize,
623+ status: Option<&StatusEmitter<'_>>,
624+) -> Result<bool> {
674625 if instance_raw.exists() {
675− return Ok(());
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;
630+ tracing::warn!(
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.",
632+ current_gb,
633+ target_gb
634+ );
635+ }
636+ return Ok(false);
676637 }
677638
678− println!("Creating instance disk from {}...", template_raw.display());
679− std::fs::create_dir_all(instance_raw.parent().unwrap())?;
680− fs::copy(template_raw, instance_raw)?;
681− Ok(())
639+ let template_size = ByteSize(fs::metadata(template_raw)?.len());
640+ if target_bytes < template_size {
641+ bail!(format!(
642+ "Requested disk size {} is smaller than base image size {}",
643+ target_bytes, template_size
644+ ));
645+ }
646+ let target_size = target_bytes;
647+ let needs_resize = target_size > template_size;
648+
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);
656+ }
657+
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)?;
662+ Ok(needs_resize)
682663}
683664
684665pub struct IoContext {
@@ -694,18 +675,17 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
694675 (read_stream.into(), write_stream.into())
695676}
696677
697−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,
681+>(
698682 output_monitor: Arc<OutputMonitor>,
699683 vm_output_fd: OwnedFd,
700684 vm_input_fd: OwnedFd,
701685 io_control: Arc<IoControl>,
702686 mut on_line: F,
703687 mut on_output: G,
704−) -> IoContext
705−where
706− F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
707− G: FnMut(&[u8]) + ::std::marker::Send + 'static,
708−{
688+) -> IoContext {
709689 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
710690
711691 // raw_guard is set when we've put the user's terminal into raw mode because we've attached stdin/stdout to the VM.
@@ -853,14 +833,14 @@ where
853833 PollResult::Spurious => continue,
854834 PollResult::Ready(bytes) => {
855835 if io_control.forward_output() {
856− // enable raw mode, if we haven't already
836+ // enable raw mode if we haven't already
857837 if raw_guard.lock().unwrap().is_none()
858838 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
859839 {
860840 *raw_guard.lock().unwrap() = Some(guard);
861841 }
862842
863− let mut stdout = std::io::stdout().lock();
843+ let mut stdout = io::stdout().lock();
864844 if stdout.write_all(bytes).is_err() {
865845 break;
866846 }
@@ -876,7 +856,7 @@ where
876856
877857 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
878858 let mux_thread = thread::spawn(move || {
879− let mut vm_writer = std::fs::File::from(vm_input_fd);
859+ let mut vm_writer = fs::File::from(vm_input_fd);
880860 loop {
881861 match input_rx.recv() {
882862 Ok(VmInput::Bytes(data)) => {
@@ -906,7 +886,7 @@ pub fn spawn_vm_io_with_line_handler<F>(
906886 on_line: F,
907887) -> IoContext
908888where
909− F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
889+ F: FnMut(&str) -> bool + std::marker::Send + 'static,
910890{
911891 spawn_vm_io_with_hooks(
912892 output_monitor,
@@ -926,6 +906,36 @@ pub fn spawn_vm_io(
926906 spawn_vm_io_with_line_handler(output_monitor, vm_output_fd, vm_input_fd, |_| false)
927907}
928908
909+fn spawn_vm_io_with_log(
910+ output_monitor: Arc<OutputMonitor>,
911+ vm_output_fd: OwnedFd,
912+ vm_input_fd: OwnedFd,
913+ log_path: PathBuf,
914+) -> IoContext {
915+ let log_file = fs::OpenOptions::new()
916+ .create(true)
917+ .write(true)
918+ .truncate(true)
919+ .open(&log_path)
920+ .ok()
921+ .map(|file| Arc::new(Mutex::new(file)));
922+
923+ spawn_vm_io_with_hooks(
924+ output_monitor,
925+ vm_output_fd,
926+ vm_input_fd,
927+ IoControl::new(),
928+ |_| false,
929+ move |bytes| {
930+ if let Some(log) = &log_file
931+ && let Ok(mut file) = log.lock()
932+ {
933+ let _ = file.write_all(bytes);
934+ }
935+ },
936+ )
937+}
938+
929939impl IoContext {
930940 pub fn shutdown(self) {
931941 let _ = self.input_tx.send(VmInput::Shutdown);
@@ -943,7 +953,7 @@ fn create_vm_configuration(
943953 vm_writes_to_fd: OwnedFd,
944954 cpu_count: usize,
945955 ram_bytes: u64,
946−) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
956+) -> Result<Retained<VZVirtualMachineConfiguration>> {
947957 unsafe {
948958 let platform =
949959 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -977,7 +987,7 @@ fn create_vm_configuration(
977987 false,
978988 VZDiskImageCachingMode::Automatic,
979989 VZDiskImageSynchronizationMode::Full,
980− ).unwrap();
990+ )?;
981991
982992 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
983993 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -1064,7 +1074,7 @@ fn create_vm_configuration(
10641074 // Validate
10651075 config.validateWithError().map_err(|e| {
10661076 io::Error::other(format!(
1067− "Invalid VM configuration: {:?}",
1077+ "invalid VM configuration: {:?}",
10681078 e.localizedDescription()
10691079 ))
10701080 })?;
@@ -1073,9 +1083,9 @@ fn create_vm_configuration(
10731083 }
10741084}
10751085
1076−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
1086+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
10771087 unsafe {
1078− let temp_dir = std::env::temp_dir();
1088+ let temp_dir = env::temp_dir();
10791089 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
10801090 let url = nsurl_from_path(&temp_path)?;
10811091 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -1091,8 +1101,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std
10911101fn spawn_login_actions_thread(
10921102 login_actions: Vec<LoginAction>,
10931103 output_monitor: Arc<OutputMonitor>,
1094− input_tx: mpsc::Sender<VmInput>,
1095− vm_output_tx: mpsc::Sender<VmOutput>,
1104+ input_tx: Sender<VmInput>,
1105+ vm_output_tx: Sender<VmOutput>,
10961106) -> thread::JoinHandle<()> {
10971107 thread::spawn(move || {
10981108 for a in login_actions {
@@ -1106,22 +1116,31 @@ fn spawn_login_actions_thread(
11061116 return;
11071117 }
11081118 }
1119+ ExpectEither {
1120+ success,
1121+ failure,
1122+ timeout,
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),
1129+ });
1130+ return;
1131+ }
1132+ WaitAnyResult::Timeout => {
1133+ let _ = vm_output_tx.send(VmOutput::LoginActionTimeout {
1134+ action: format!("expect '{}'", success),
1135+ timeout,
1136+ });
1137+ return;
1138+ }
1139+ },
11091140 Send(mut text) => {
11101141 text.push('\n'); // Type the newline so the command is actually submitted.
11111142 input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
11121143 }
1113− Script { path, index } => {
1114− let command = match script_command_from_path(&path, index) {
1115− Ok(command) => command,
1116− Err(err) => {
1117− eprintln!("{err}");
1118− return;
1119− }
1120− };
1121− let mut text = command;
1122− text.push('\n');
1123− input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
1124− }
11251144 }
11261145 }
11271146 })
@@ -1133,8 +1152,9 @@ fn run_vm_with_io<F>(
11331152 directory_shares: &[DirectoryShare],
11341153 cpu_count: usize,
11351154 ram_bytes: u64,
1155+ status: Option<&StatusEmitter<'_>>,
11361156 io_handler: F,
1137−) -> Result<(), Box<dyn std::error::Error>>
1157+) -> Result<()>
11381158where
11391159 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
11401160{
@@ -1181,21 +1201,23 @@ where
11811201
11821202 match rx.try_recv() {
11831203 Ok(result) => {
1184− result.map_err(|e| format!("Failed to start VM: {}", e))?;
1204+ result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
11851205 break;
11861206 }
11871207 Err(mpsc::TryRecvError::Empty) => continue,
11881208 Err(mpsc::TryRecvError::Disconnected) => {
1189− return Err("VM start channel disconnected".into());
1209+ bail!("VM start channel disconnected");
11901210 }
11911211 }
11921212 }
11931213
11941214 if Instant::now() >= start_deadline {
1195− return Err("Timed out waiting for VM to start".into());
1215+ bail!("Timed out waiting for VM to start");
11961216 }
11971217
1198− println!("VM booting...");
1218+ emit_status(status, "vm booting... go vibecoder!");
1219+ tracing::info!("vm booting... go vibecoder!");
1220+ tracing::info!("vm booting");
11991221
12001222 let output_monitor = Arc::new(OutputMonitor::default());
12011223 let io_ctx = io_handler(output_monitor.clone(), we_read_from, we_write_to);
@@ -1240,7 +1262,7 @@ where
12401262 );
12411263
12421264 let mut last_state = None;
1243− let mut exit_result = Ok(());
1265+ let mut exit_result: Result<(), String> = Ok(());
12441266 loop {
12451267 unsafe {
12461268 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1259,12 +1281,28 @@ where
12591281 exit_result = Err(format!(
12601282 "Login action ({}) timed out after {:?}; shutting down.",
12611283 action, timeout
1262− )
1263− .into());
1284+ ));
12641285 unsafe {
12651286 if vm.canRequestStop() {
12661287 if let Err(err) = vm.requestStopWithError() {
1267− eprintln!("Failed to request VM stop: {:?}", err);
1288+ tracing::error!(error = ?err, "failed to request VM stop");
1289+ }
1290+ } else if vm.canStop() {
1291+ let handler = RcBlock::new(|_error: *mut NSError| {});
1292+ vm.stopWithCompletionHandler(&handler);
1293+ }
1294+ }
1295+ break;
1296+ }
1297+ Ok(VmOutput::LoginActionFailed { action, reason }) => {
1298+ exit_result = Err(format!(
1299+ "Login action ({}) failed: {}; shutting down.",
1300+ action, reason
1301+ ));
1302+ unsafe {
1303+ if vm.canRequestStop() {
1304+ if let Err(err) = vm.requestStopWithError() {
1305+ tracing::error!(error = ?err, "failed to request VM stop");
12681306 }
12691307 } else if vm.canStop() {
12701308 let handler = RcBlock::new(|_error: *mut NSError| {});
@@ -1276,7 +1314,7 @@ where
12761314 Err(mpsc::TryRecvError::Empty) => {}
12771315 Err(mpsc::TryRecvError::Disconnected) => {}
12781316 }
1279− if state != objc2_virtualization::VZVirtualMachineState::Running {
1317+ if state != VZVirtualMachineState::Running {
12801318 //eprintln!("VM stopped with state: {:?}", state);
12811319 break;
12821320 }
@@ -1286,7 +1324,7 @@ where
12861324
12871325 io_ctx.shutdown();
12881326
1289− exit_result
1327+ exit_result.map_err(Error::msg)
12901328}
12911329
12921330fn run_vm(
@@ -1295,18 +1333,20 @@ fn run_vm(
12951333 directory_shares: &[DirectoryShare],
12961334 cpu_count: usize,
12971335 ram_bytes: u64,
1298−) -> Result<(), Box<dyn std::error::Error>> {
1336+ status: Option<&StatusEmitter<'_>>,
1337+) -> Result<()> {
12991338 run_vm_with_io(
13001339 disk_path,
13011340 login_actions,
13021341 directory_shares,
13031342 cpu_count,
13041343 ram_bytes,
1344+ status,
13051345 spawn_vm_io,
13061346 )
13071347}
13081348
1309−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
1349+fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
13101350 let abs_path = if path.is_absolute() {
13111351 path.to_path_buf()
13121352 } else {
@@ -1315,7 +1355,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::E
13151355 let ns_path = NSString::from_str(
13161356 abs_path
13171357 .to_str()
1318− .ok_or("Non-UTF8 path encountered while building NSURL")?,
1358+ .with_context(|| "non-UTF8 path encountered while building NSURL")?,
13191359 );
13201360 Ok(NSURL::fileURLWithPath(&ns_path))
13211361}
@@ -1330,7 +1370,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
13301370 let original = attributes;
13311371
13321372 // Disable translation of carriage return to newline on input
1333− attributes.c_iflag &= !(libc::ICRNL);
1373+ attributes.c_iflag &= !libc::ICRNL;
13341374 // Disable canonical mode (line buffering), echo, and signal generation
13351375 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
13361376 attributes.c_cc[libc::VMIN] = 0;
@@ -1358,10 +1398,10 @@ impl Drop for RawModeGuard {
13581398
13591399// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
13601400pub fn ensure_signed() {
1361− if std::env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1401+ if env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
13621402 return;
13631403 }
1364− 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");
13651405 let exe_str = exe.to_str().expect("exe path not valid utf-8");
13661406
13671407 let has_required_entitlements = {
@@ -1383,10 +1423,10 @@ pub fn ensure_signed() {
13831423 }
13841424
13851425 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1386− let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1387− std::fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
1426+ let entitlements_path = env::temp_dir().join("entitlements.plist");
1427+ fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
13881428
1389− let status = Command::new("codesign")
1429+ let output = Command::new("codesign")
13901430 .args([
13911431 "--sign",
13921432 "-",
@@ -1395,22 +1435,27 @@ pub fn ensure_signed() {
13951435 entitlements_path.to_str().unwrap(),
13961436 exe_str,
13971437 ])
1398− .status();
1438+ .output();
13991439
1400− let _ = std::fs::remove_file(&entitlements_path);
1440+ let _ = fs::remove_file(&entitlements_path);
14011441
1402− match status {
1403− Ok(s) if s.success() => {
1404− let err = Command::new(&exe).args(std::env::args_os().skip(1)).exec();
1405− eprintln!("failed to re-exec after signing: {err}");
1442+ match output {
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");
1447+ }
1448+ let err = Command::new(&exe).args(env::args_os().skip(1)).exec();
1449+ tracing::error!(error = %err, "failed to re-exec after signing");
14061450 std::process::exit(1);
14071451 }
1408− Ok(s) => {
1409− eprintln!("codesign failed with status: {s}");
1452+ Ok(o) => {
1453+ let stderr = String::from_utf8_lossy(&o.stderr);
1454+ tracing::error!(status = %o.status, codesign_stderr = %stderr.trim(), "codesign failed");
14101455 std::process::exit(1);
14111456 }
14121457 Err(e) => {
1413− eprintln!("failed to run codesign: {e}");
1458+ tracing::error!(error = %e, "failed to run codesign");
14141459 std::process::exit(1);
14151460 }
14161461 }