on main help sign in
feat: use vm.lock to ensure process concurrency safety.
commitfc7e95fa22ba6f4ed8968ee0845933a132864c47 authorrobcholz <84130577+robcholz@users.noreply.github.com> dateSat 7 Feb 2026, 12:35 (8 months ago) parentca33633
4 files changed+84−213
LICENSE+1−1 docs/tasks.md+7−1 readme.md−208 src/vm_manager.rs+76−3
LICENSE+1−1
@@ -1,4 +1,4 @@
1−Copyright 2026 Kevin Lynagh
1+Copyright 2026 Finn Sheng
22
33Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
44
docs/tasks.md+7−1
@@ -38,7 +38,7 @@
38381. [x] Wire up the vm and tui.
39392. [x] Use ssh to connect to vm.
40403. [x] allow multi vibebox to connect to the same vm.
41−4. [ ] use vm.lock to ensure process concurrency safety.
41+4. [x] use vm.lock to ensure process concurrency safety.
42425. [ ] wire up SessionManager.
43436. [ ] VM should be separated by a per-session VM daemon process (only accepts if to shut down vm and itself).
44447. [ ] setup vibebox commands
@@ -51,4 +51,10 @@
51512. [ ] setup quick link.
52523. [ ] setup website.
5353
54+## Stage 2
55+
56+1. [ ] Redirect vm output to log.
57+2. [ ] Redirect vm output to vibebox starting it.
58+3. [ ] use anyhow to sync api.
59+
5460[ ]
readme.mddeleted−208
@@ -1,208 +0,0 @@
1−Vibe is a quick, zero-configuration way to spin up a Linux virtual machine on Mac to sandbox LLM agents:
2−
3−```
4−$ cd my-project
5−$ vibe
6−
7−░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░▒▓███████▓▒░░▒▓████████▓▒░
8−░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
9− ░▒▓█▓▒▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
10− ░▒▓█▓▒▒▓█▓▒░░▒▓█▓▒░▒▓███████▓▒░░▒▓██████▓▒░
11− ░▒▓█▓▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
12− ░▒▓█▓▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
13− ░▒▓██▓▒░ ░▒▓█▓▒░▒▓███████▓▒░░▒▓████████▓▒░
14−
15−Host Guest Mode
16−---------------------------------------- ----------------------- ----------
17−/Users/dev/work/my-project /root/my-project read-write
18−/Users/dev/.cache/vibe/.guest-mise-cache /root/.local/share/mise read-write
19−/Users/dev/.m2 /root/.m2 read-write
20−/Users/dev/.cargo/registry /root/.cargo/registry read-write
21−/Users/dev/.codex /root/.codex read-write
22−/Users/dev/.claude /root/.claude read-write
23−
24−root@vibe:~/my-project#
25−```
26−
27−On my M1 MacBook Air it takes ~10 seconds to boot.
28−
29−
30−Dependencies:
31−
32−- An ARM-based Mac running MacOS 13 (Ventura) or higher.
33−- A network connection is required on the first run to download and configure the Debian Linux base image.
34−- That's it!
35−
36−
37−## Why use Vibe?
38−
39−- LLM agents are more fun to use with `--yolo`, since they're not always interrupting you to approve their commands.
40−- Sandboxing the agent in a VM lets it install/remove whatever tools its lil' transformer heart desires, *without* wrecking your actual machine.
41−- You control what the agent (and thus the upstream LLM provider) can actually see, by controlling exactly what's shared into the VM sandbox.
42− (This project was inspired by me running `codex` *without* `--yolo` and seeing it reading files outside of the directory I started it in --- not cool, bro.)
43−
44−I'm using virtual machines rather than containers because:
45−
46−- Virtualization is more secure against malicious escapes than containers or the MacOS sandbox framework.
47−- Containers on MacOS require spinning up a virtual machine anyway.
48−
49−Finally, as a matter of taste and style:
50−
51−- The binary is < 1 MB.
52−- I wrote the entire README myself, 100% with my human brain.
53−- The entire implementation is in one ~1200 line Rust file.
54−- The only Rust dependencies are the [Objc2](https://github.com/madsmtm/objc2) interop crates and the [lexopt](https://github.com/blyxxyz/lexopt) argument parser.
55−- There are no emoji anywhere in this repository.
56−
57−
58−## Install
59−
60−Vibe is a single binary built with Rust.
61−
62−Download [the latest binary built by GitHub actions](https://github.com/lynaghk/vibe/releases/tag/latest) and put it somewhere on your `$PATH`:
63−
64− curl -LO https://github.com/lynaghk/vibe/releases/download/latest/vibe-macos-arm64.zip
65− unzip vibe-macos-arm64.zip
66− mkdir -p ~/.local/bin
67− mv vibe ~/.local/bin
68− export PATH="$HOME/.local/bin:$PATH"
69−
70−If you use [mise-en-place](https://mise.jdx.dev/):
71−
72− mise use github:lynaghk/vibe@latest
73−
74−I'm not making formal releases or keeping a change log.
75−I recommend reading the commit history and pinning to a specific version.
76−
77−You can also install via `cargo`:
78−
79− cargo install --locked --git https://github.com/lynaghk/vibe.git
80−
81−If you don't have `cargo`, you need to install Rust:
82−
83− curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
84−
85−
86−## Using Vibe
87−
88−
89−```
90−vibe [OPTIONS] [disk-image.raw]
91−
92−Options
93−
94− --help Print this help message.
95− --version Print the version (commit SHA).
96− --no-default-mounts Disable all default mounts.
97− --mount host-path:guest-path[:read-only | :read-write] Mount `host-path` inside VM at `guest-path`.
98− Defaults to read-write.
99− Errors if host-path does not exist.
100− --cpus <count> Number of virtual CPUs (default 2).
101− --ram <megabytes> RAM size in megabytes (default 2048).
102− --script <path/to/script.sh> Run script in VM.
103− --send <some-command> Type `some-command` followed by newline into the VM.
104− --expect <string> [timeout-seconds] Wait for `string` to appear in console output before executing next `--script` or `--send`.
105− If `string` does not appear within timeout (default 30 seconds), shutdown VM with error.
106−```
107−
108−Invoking vibe without a disk image:
109−
110−- shares the current directory with the VM
111−- shares package manager cache directories with the VM, so that packages are not re-downloaded
112−- shares the `~/.codex` directory with the VM, so you can use OpenAI's [codex](https://openai.com/codex/)
113−- shares the `~/.claude` directory with the VM, so you can use Anthropic's [claude](https://claude.com/product/claude-code)
114−
115−The first time you run `vibe`, a Debian Linux image is downloaded to `~/.cache/vibe/`, configured with basic tools like gcc, [mise-en-place](https://mise.jdx.dev/), ripgrep, rust, etc., and saved as `default.raw`.
116−(See [provision.sh](/src/provision.sh) for details.)
117−
118−Then when you run `vibe` in a project directory, it copies this default image to `.vibe/instance.raw`, boots it up, and attaches your terminal to this VM.
119−
120−When you `exit` this shell, the VM is shutdown.
121−The disk state persists until you delete it.
122−There is no centralized registry of VMs --- if you want to delete a VM, just delete its disk image file.
123−
124−## Other notes
125−
126−- Apple Filesystem is copy-on-write, so instance images only use disk space when they diverge from the default image.
127− You can use `du -h` to see how much space is actually consumed:
128−
129− $ /bin/ls -lah .vibe/instance.raw
130− -rw-r--r-- 1 dev staff 10G Jan 25 20:41 .vibe/instance.raw
131−
132− $ du -h .vibe/instance.raw
133− 2.3G .vibe/instance.raw
134−
135−- MacOS only lets binaries signed with the `com.apple.security.virtualization` entitlement run virtual machines, so `vibe` checks itself on startup and, if necessary, signs itself using `codesign`. SeCuRiTy!
136−
137−- Debian "nocloud" is used as a base image because it boots directly to a root prompt.
138− The other images use [cloudinit](https://cloudinit.readthedocs.io/en/latest/), which I found much more complex:
139− - Network requests are made during the boot process, and if you're offline they take several *minutes* to timeout before the login prompt is reached (thanks, `systemd-networkd-wait-online.service`).
140− - Subsequent boots are much slower (at least, I couldn't easily figure out how to remove the associated cloud init machinery).
141−
142−
143−## Alternatives
144−
145−Here's what I tried before writing this solution:
146−
147−- [Sandboxtron](https://github.com/lynaghk/sandboxtron/) - My own little wrapper around Mac's `sandbox-exec`.
148−Turns out both Claude Code and Codex rely on this as well, and MacOS doesn't allow creating a sandbox from within a sandbox.
149−I considered writing my own sandboxing rules and running the agents `--yolo`, but didn't like the risk of configuration typos and/or Mac sandbox escapes (there are a lot --- I'm not an expert, but from [this HN discussion](https://news.ycombinator.com/item?id=42084588) I figured virtualization would be safer).
150−
151−- [Lima](https://github.com/lima-vm/lima/), quick Linux VMs on Mac. I wanted to like this, ran into too many issues in first 30 minutes to trust it:
152− - The recommended Debian image took 8 seconds to get to a login prompt, even after the VM was already running.
153− - The CLI flags *mutate hidden state*. E.g., If you `limactl start --mount foo` and then later `limactl start --mount bar`, both `foo` and `bar` will be mounted.
154− - Some capabilities are only available via yaml. E.g., the `--mount` CLI flag always mounts at the same path in the guest. If you want to mount at a different path, you have to do that via YAML.
155− - There are many layers of inheritance/defaults, so even if you do write YAML, you can't see the full configuration.
156−
157−- [Vagrant](https://developer.hashicorp.com/vagrant/) - I fondly remember using this back in the early 2010's, but based on this [2025 Reddit discussion](https://www.reddit.com/r/devops/comments/1axws75/vagrant_doesnt_support_mac_m1/) it seemed like running it on an ARM-based Mac was A Project and so I figured it'd be easier to roll my own thing.
158−
159−- [Tart](https://tart.run/) - I found this via some positive HN comments, but unfortunately wasn't able to run the release binary from their GitHub because it's not signed.
160−They apparently hack around that when installing with homebrew, but I don't use homebrew either.
161−I tried cloning the repo and compiling myself, but the build failed with lots of language syntax errors despite the repo SHA is the same as one of their releases.
162−I assume this is a Swift problem and not Tart's, since this sort of mess happens most times when I try to build Swift. `¯\_(ツ)_/¯`
163−
164−- [OrbStack](https://orbstack.dev/) - This looked nice, but seems mostly geared towards container stuff.
165−It runs a single VM, and I couldn't figure out how to have this VM run *without* my entire disk mounted inside of it.
166−I didn't want to run agents via containers, since containers aren't security boundaries.
167−
168−- [Apple Container Framework](https://github.com/apple/container) - This looks technically promising, as it runs every container within a lightweight VM.
169−Unfortunately it requires MacOS 26 Tahoe, which wrecks [window resizing](https://news.ycombinator.com/item?id=46579864), adds [useless icons everywhere](https://news.ycombinator.com/item?id=46497712), and otherwise seems to be a mess.
170−Sorry excellent Apple programmers and hardware designers, I hope your management can reign in the haute couture folks before we all have to switch to Linux for professional computing.
171−
172−- [QEMU](https://wiki.qemu.org/) - The first prototype of this app was [a single bash script](https://github.com/lynaghk/vibe/blob/1c82fd3b9fabf93abba2680fc856458e97a105cd/qemu.sh) wrapping `qemu`. This worked swimmingly, except for host/guest directory sharing, which ended up being a show-stopper. This is because QEMU doesn't support [virtiofs](https://virtio-fs.gitlab.io/) on Mac hosts, it only supports "9p", which is way slower --- e.g., `mise use node@latest` takes > 10 minutes on 9p and 5 seconds on virtiofs.
173−
174−
175−## Roadmap / Collaboration
176−
177−I wrote this software for myself, and I'm open to pull requests and otherwise collaborating on features that I'd personally use:
178−
179−- resizing disk images
180−- forwarding ports from the host to a guest
181−- running `vibe` against a disk image that's already running should connect to the already-running VM
182− - the VM shouldn't shutdown until all host terminals have logged out
183−- if not the above, at least a check and throw a nice error message when you try to start a VM that's already running
184−- a way to make faster-booting even more minimal Linux virtual machines
185− - this should be bootstrappable on Mac; i.e., if the only way to make a small Linux image is with Linux-only tools, the entire process should still be runnable on MacOS via intermediate VMs
186−- propagate an exit code from within VM to the `vibe` command
187−- don't propagate user typing until all provided `--expect` and `--send` actions have completed
188−- CPU core / memory / networking configuration, possibly via flags or via extended attributes on the disk image file
189−- a `--plan` flag which pretty-prints a CLI invocation with all of the default arguments shown
190− - to keep ourselves honest, we should use the same codepath for the actual execution (maybe we can `exec` into the generated command?)
191− - Being fully "explicit" is tricky due to flag interactions.
192− E.g., the friendly `--mount` would need to be decomposed into two flags: One that exposes the host directory in the guest's staging area at `/mnt/shared/` and another flag `--send 'mount --bind ...'`to bind this to the desired guest location.
193−
194−I'm not sure about (but open to discussing proposals via GitHub issues):
195−
196−- running VMs in the background
197−- supporting Linux hosts
198−- supporting guests beyond Debian Linux
199−- using SSH as a login mechanism; this would eliminate the current stdin/stdout-to-console plumbing (yay!) but require additional setup/configuration (boo!)
200−- making Claude Code work seamlessly
201− - I tried the native installer but it sometimes fails during setup (see 6352d13), so I switched back to NPM via mise which is more reliable.
202− - The `~/.claude` folder is shared in the VM by default, by apparently the `~/.claude.json` file is also required for auth credentials and session history.
203− I'm not sure the best way to share a file between host and VM (virtioFS only works with folders).
204− Also: Wild to me that Anthropic puts both a file and a folder in your home directory --- how rude!
205−
206−I'm not interested in:
207−
208−- anything related to Docker / containers / Kubernetes / distributed systems
src/vm_manager.rs+76−3
@@ -24,6 +24,7 @@ use crate::{
2424};
2525
2626const VM_MANAGER_SOCKET_NAME: &str = "vm.sock";
27+const VM_MANAGER_LOCK_NAME: &str = "vm.lock";
2728
2829pub fn ensure_manager(
2930 raw_args: &[std::ffi::OsString],
@@ -40,8 +41,19 @@ pub fn ensure_manager(
4041 return Ok(stream);
4142 }
4243
43− tracing::info!(path = %socket_path.display(), "spawning vm manager");
44− spawn_manager_process(raw_args, auto_shutdown_ms, &instance_dir)?;
44+ let lock_path = instance_dir.join(VM_MANAGER_LOCK_NAME);
45+ let mut lock_file = acquire_spawn_lock(&lock_path)?;
46+ if lock_file.is_some() {
47+ tracing::info!(path = %socket_path.display(), "spawning vm manager");
48+ spawn_manager_process(raw_args, auto_shutdown_ms, &instance_dir)?;
49+ } else {
50+ tracing::info!(
51+ path = %socket_path.display(),
52+ lock = %lock_path.display(),
53+ lock_pid = read_lock_pid(&lock_path).unwrap_or(0),
54+ "waiting for vm manager spawn lock"
55+ );
56+ }
4557
4658 let start = Instant::now();
4759 let timeout = Duration::from_secs(10);
@@ -50,11 +62,19 @@ pub fn ensure_manager(
5062 Ok(stream) => {
5163 send_client_pid(&stream);
5264 tracing::info!(path = %socket_path.display(), "connected to vm manager");
65+ if lock_file.is_some() {
66+ drop(lock_file.take());
67+ let _ = fs::remove_file(&lock_path);
68+ }
5369 return Ok(stream);
5470 }
5571 Err(err) => {
5672 tracing::debug!(error = %err, "waiting for vm manager socket");
5773 if start.elapsed() > timeout {
74+ if lock_file.is_some() {
75+ drop(lock_file.take());
76+ let _ = fs::remove_file(&lock_path);
77+ }
5878 return Err(format!(
5979 "Timed out waiting for vm manager socket: {} ({})",
6080 socket_path.display(),
@@ -167,6 +187,59 @@ fn send_client_pid(stream: &UnixStream) {
167187 }
168188}
169189
190+fn acquire_spawn_lock(lock_path: &Path) -> Result<Option<fs::File>, Box<dyn std::error::Error>> {
191+ match fs::OpenOptions::new()
192+ .write(true)
193+ .create_new(true)
194+ .open(lock_path)
195+ {
196+ Ok(mut file) => {
197+ let pid = std::process::id();
198+ let _ = writeln!(file, "pid={pid}");
199+ Ok(Some(file))
200+ }
201+ Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
202+ if is_lock_stale(lock_path) {
203+ tracing::warn!(
204+ lock = %lock_path.display(),
205+ lock_pid = read_lock_pid(lock_path).unwrap_or(0),
206+ "stale vm manager lock removed"
207+ );
208+ let _ = fs::remove_file(lock_path);
209+ return acquire_spawn_lock(lock_path);
210+ }
211+ Ok(None)
212+ }
213+ Err(err) => Err(err.into()),
214+ }
215+}
216+
217+fn is_lock_stale(lock_path: &Path) -> bool {
218+ match read_lock_pid(lock_path) {
219+ Some(pid) => !pid_is_alive(pid),
220+ None => true,
221+ }
222+}
223+
224+fn pid_is_alive(pid: u32) -> bool {
225+ let pid = pid as libc::pid_t;
226+ let result = unsafe { libc::kill(pid, 0) };
227+ if result == 0 {
228+ return true;
229+ }
230+ match std::io::Error::last_os_error().raw_os_error() {
231+ Some(code) if code == libc::EPERM => true,
232+ Some(code) if code == libc::ESRCH => false,
233+ _ => false,
234+ }
235+}
236+
237+fn read_lock_pid(lock_path: &Path) -> Option<u32> {
238+ let content = fs::read_to_string(lock_path).ok()?;
239+ let line = content.lines().next()?;
240+ line.strip_prefix("pid=")?.trim().parse::<u32>().ok()
241+}
242+
170243fn read_client_pid(stream: &UnixStream) -> Option<u32> {
171244 let mut stream = stream.try_clone().ok()?;
172245 let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
@@ -514,7 +587,7 @@ fn manager_event_loop(
514587 }
515588 Ok(ManagerEvent::VmExited(err)) => {
516589 if let Some(err) = err {
517− tracing::error!(error = %err, "vm exited with error");
590+ tracing::error!(error = %err, "vm exited with an error");
518591 }
519592 break;
520593 }