Luxe 0.1.3: your sessions on your phone, joinable sessions, and nested AGENTS.md

- luxe remote puts the sessions on your computer in reach of your own phone or tablet over
  Tailscale: write, steer, answer prompts, send photos, browse files, diffs and GitHub, with a
  paired device and your own Tailscale login.
- luxe join lets another program on the same machine join a running session over the RPC protocol.
- An AGENTS.md in a subfolder reaches the model the first time it works there.
- Long sessions stay fast: no stall before each model call, lighter memory, cheaper drawing.
- A session is open in one Luxe at a time, web_search shares results across its phrasings, and a
  grep glob starting with ! excludes.

The CHANGELOG has the full list.
This commit is contained in:
Evan Whittaker
2026-10-20 02:40:13 -05:00
parent 99e30d6d0f
commit d2129a886f
423 changed files with 31666 additions and 1669 deletions

View File

@@ -0,0 +1,115 @@
//! Ancestry — whether a process was started, at any depth, by another.
//!
//! The tripwire that keeps a Luxe's own children (the agent's `bash`, a hook) from joining its
//! session and answering their own prompts. A tripwire, not a wall: a process that detaches itself
//! leaves the chain, and the documentation says so. Blocking: run it off the async runtime.
/// How many parents to walk before giving up; real chains are a handful deep.
const MAX_DEPTH: usize = 64;
/// Whether `pid` is `ancestor` or was started, at any depth, by it. `false` when the chain cannot
/// be read, so a client this cannot place is let in, as it would be without the tripwire.
pub fn descends_from(pid: u32, ancestor: u32) -> bool {
descends_in(pid, ancestor, parent_lookup())
}
/// [`descends_from`] over an explicit parent table.
fn descends_in(pid: u32, ancestor: u32, parent_of: impl Fn(u32) -> Option<u32>) -> bool {
let mut current = pid;
for _ in 0..MAX_DEPTH {
if current == ancestor {
return true;
}
match parent_of(current) {
Some(parent) if parent != current && parent != 0 => current = parent,
_ => return false,
}
}
false
}
#[cfg(target_os = "linux")]
fn parent_lookup() -> impl Fn(u32) -> Option<u32> {
|pid| parent_in_stat(&std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?)
}
/// The parent id from a `/proc/<pid>/stat` line. The command name sits in parentheses and may hold
/// spaces and parentheses itself, so fields are counted from the last `)`.
#[cfg(any(target_os = "linux", test))]
fn parent_in_stat(stat: &str) -> Option<u32> {
let (_, fields) = stat.rsplit_once(')')?;
fields.split_whitespace().nth(1)?.parse().ok()
}
#[cfg(all(unix, not(target_os = "linux")))]
fn parent_lookup() -> impl Fn(u32) -> Option<u32> {
let table = process_table();
move |pid| table.get(&pid).copied()
}
/// Every process's parent, from `ps`, which macOS and the BSDs all have at the same path.
#[cfg(all(unix, not(target_os = "linux")))]
fn process_table() -> std::collections::HashMap<u32, u32> {
let listing = std::process::Command::new("/bin/ps").args(["-A", "-o", "pid=,ppid="]).output();
let Ok(listing) = listing else {
return std::collections::HashMap::new();
};
String::from_utf8_lossy(&listing.stdout)
.lines()
.filter_map(|line| {
let mut ids = line.split_whitespace().map(str::parse::<u32>);
Some((ids.next()?.ok()?, ids.next()?.ok()?))
})
.collect()
}
#[cfg(windows)]
fn parent_lookup() -> impl Fn(u32) -> Option<u32> {
let table = super::windows::process_parents();
move |pid| table.get(&pid).copied()
}
#[cfg(test)]
mod tests {
use super::*;
/// A process is its own descendant, a grandchild is found through its parent, and an
/// unrelated process or a broken chain is not.
#[test]
fn the_chain_is_walked_to_the_ancestor_and_no_further() {
let parents = |pid| match pid {
30 => Some(20),
20 => Some(10),
10 => Some(1),
1 => Some(0),
_ => None,
};
assert!(descends_in(30, 10, parents), "a grandchild");
assert!(descends_in(10, 10, parents), "itself");
assert!(!descends_in(10, 30, parents), "a parent is not a child");
assert!(!descends_in(99, 10, parents), "unknown, so not placed");
assert!(!descends_in(7, 10, |_| Some(7)), "a process that is its own parent ends the walk");
}
/// The parent is the fourth field, counted after a command name that can hold anything.
#[test]
fn the_parent_is_read_past_an_awkward_command_name() {
assert_eq!(parent_in_stat("4242 (bash) S 4000 4242 4242 0"), Some(4000));
assert_eq!(parent_in_stat("4242 (my (odd) prog) R 17 4242"), Some(17));
assert_eq!(parent_in_stat("garbage"), None);
}
/// A real child of this test is found, and this test is not the child's.
#[test]
#[cfg(unix)]
fn a_real_child_descends_from_this_process() {
let mut child = std::process::Command::new("sleep").arg("5").spawn().expect("sleep runs");
let (child_id, own_id) = (child.id(), std::process::id());
let found = descends_from(child_id, own_id);
let reversed = descends_from(own_id, child_id);
let _ = child.kill();
let _ = child.wait();
assert!(found, "the child is placed under this process");
assert!(!reversed);
}
}

View File

@@ -0,0 +1,85 @@
//! Live sessions — which Luxes on this machine can be joined, and where.
//!
//! Each running Luxe with an endpoint leaves a small record in the runtime folder, named for its
//! process, and takes it away when it stops. A record left by a Luxe that died is found out by the
//! one test that matters: its endpoint no longer answers.
use serde::{Deserialize, Serialize};
use std::io;
use std::path::{Path, PathBuf};
/// One running Luxe that can be joined.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LiveSession {
/// The Luxe's process id
pub pid: u32,
/// Session it is running
pub session_id: String,
/// Project folder it was opened in
pub cwd: String,
/// Where to [`super::connect`]
pub address: String,
/// The build serving it
pub luxe_version: String,
}
/// This Luxe's record in the runtime folder, removed when dropped.
pub struct Publication {
path: PathBuf,
}
impl LiveSession {
/// Writes this record into `dir`, readable only by this user.
pub fn publish(&self, dir: &Path) -> io::Result<Publication> {
crate::fs_atomic::create_private_dir(dir)?;
let publication = Publication { path: dir.join(format!("{}.json", self.pid)) };
publication.update(self)?;
Ok(publication)
}
}
impl Publication {
/// Rewrites the record, as when the Luxe moves to another session.
pub fn update(&self, session: &LiveSession) -> io::Result<()> {
let bytes = serde_json::to_vec_pretty(session).map_err(io::Error::other)?;
crate::fs_atomic::replace_private(&self.path, &bytes)
}
}
impl Drop for Publication {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
/// Every record in `dir`, by process id. A missing folder has none, and a record that does not
/// read is skipped, since it is either being written or not one of these.
pub fn live_sessions(dir: &Path) -> Vec<LiveSession> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut found: Vec<LiveSession> =
entries.filter_map(|entry| read_record(&entry.ok()?.path())).collect();
found.sort_by_key(|session| session.pid);
found
}
/// [`live_sessions`] whose Luxe is still running: one that crashed leaves its record behind.
///
/// Checked by process id rather than by connecting, since a connection is a client joining, and the
/// terminal running the session says so each time.
pub fn running_sessions(dir: &Path) -> Vec<LiveSession> {
let mut sessions = live_sessions(dir);
sessions.retain(|session| crate::program::process_is_alive(session.pid));
sessions
}
fn read_record(path: &Path) -> Option<LiveSession> {
if path.extension()? != "json" {
return None;
}
let bytes = std::fs::read(path).ok()?;
serde_json::from_slice(&bytes)
.inspect_err(|error| tracing::debug!(path = %path.display(), %error, "skipped a record"))
.ok()
}

View File

@@ -0,0 +1,71 @@
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
/// A client reaches the endpoint and both directions carry bytes; the listener names the client's
/// process, which here is this test's own.
#[tokio::test]
async fn a_client_reaches_the_endpoint_both_ways() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut listener = EndpointListener::bind(&dir.path().join("run")).expect("binds");
let address = listener.address().to_string();
let (client, joined) = tokio::join!(connect(&address), listener.accept());
let (mut client, mut joined) = (client.expect("connects"), joined.expect("accepts"));
client.write_all(b"ping").await.expect("writes");
let mut heard = [0u8; 4];
joined.stream.read_exact(&mut heard).await.expect("reads");
joined.stream.write_all(b"pong").await.expect("answers");
client.read_exact(&mut heard).await.expect("hears");
assert_eq!(&heard, b"pong");
assert_eq!(joined.peer, Some(std::process::id()));
}
/// The socket and its folder are this user's alone, and the socket goes with the listener.
#[tokio::test]
#[cfg(unix)]
async fn the_socket_is_private_and_goes_with_the_listener() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("a temp dir");
let run = dir.path().join("run");
let listener = EndpointListener::bind(&run).expect("binds");
let socket = std::path::PathBuf::from(listener.address());
let mode = |path: &std::path::Path| {
std::fs::metadata(path).expect("exists").permissions().mode() & 0o777
};
assert_eq!(mode(&run), 0o700, "the folder");
assert_eq!(mode(&socket), 0o600, "the socket");
drop(listener);
assert!(!socket.exists(), "a stopped Luxe leaves no socket behind");
assert!(connect(&socket.to_string_lossy()).await.is_err());
}
/// A published record is listed until it is dropped, and a stray file in the folder is not one.
#[test]
fn a_record_is_listed_while_its_luxe_runs() {
let dir = tempfile::tempdir().expect("a temp dir");
let session = LiveSession {
pid: 4242,
session_id: "session-a".into(),
cwd: "/work/widget".into(),
address: "/run/user/1000/luxe/4242.sock".into(),
luxe_version: "0.1.0".into(),
};
let publication = session.publish(dir.path()).expect("publishes");
std::fs::write(dir.path().join("notes.txt"), "not a record").expect("writes");
std::fs::write(dir.path().join("7.json"), "{ half").expect("writes");
assert_eq!(live_sessions(dir.path()), vec![session.clone()]);
let moved = LiveSession { session_id: "session-b".into(), ..session };
publication.update(&moved).expect("updates");
assert_eq!(live_sessions(dir.path()), vec![moved]);
drop(publication);
assert_eq!(live_sessions(dir.path()), Vec::new());
}
/// The record's shape is what other programs read, so it is pinned, not only round-tripped.
#[test]
fn the_record_shape_is_pinned() {
let literal = r#"{"pid":4242,"session_id":"session-a","cwd":"/work/widget","address":"/run/user/1000/luxe/4242.sock","luxe_version":"0.1.0"}"#;
let read: LiveSession = serde_json::from_str(literal).expect("reads");
assert_eq!(serde_json::to_string(&read).expect("writes"), literal);
}

View File

@@ -0,0 +1,81 @@
//! The Unix endpoint: a socket in a folder only this user can open.
use super::{EndpointError, Joined, LocalStream};
use std::path::{Path, PathBuf};
use tokio::net::{UnixListener, UnixStream};
/// A socket named for this process, removed when the listener is dropped.
pub(super) struct Listener {
listener: UnixListener,
path: PathBuf,
address: String,
}
impl Listener {
pub(super) fn bind(dir: &Path) -> Result<Self, EndpointError> {
crate::fs_atomic::create_private_dir(dir)
.map_err(EndpointError::io(format!("create {}", dir.display())))?;
let path = dir.join(format!("{}.sock", std::process::id()));
// left by an earlier process with this id; only this user can write in this folder
let _ = std::fs::remove_file(&path);
let listener = UnixListener::bind(&path)
.map_err(EndpointError::io(format!("listen on {}", path.display())))?;
restrict(&path)?;
let address = path.to_string_lossy().into_owned();
Ok(Self { listener, path, address })
}
pub(super) fn address(&self) -> &str {
&self.address
}
pub(super) async fn accept(&mut self) -> Result<Joined, EndpointError> {
loop {
let (stream, _) =
self.listener.accept().await.map_err(EndpointError::io("accept a client"))?;
if let Some(joined) = admit(stream) {
return Ok(joined);
}
}
}
}
impl Drop for Listener {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
/// `stream` as a client, unless it runs as another user or will not say who it is.
///
/// The folder already keeps other users out; this holds if it ever does not.
fn admit(stream: UnixStream) -> Option<Joined> {
let credentials = match stream.peer_cred() {
Ok(credentials) => credentials,
Err(error) => {
tracing::warn!(%error, "refused a client whose credentials could not be read");
return None;
}
};
if credentials.uid() != rustix::process::geteuid().as_raw() {
tracing::warn!(uid = credentials.uid(), "refused a client running as another user");
return None;
}
let peer = credentials.pid().and_then(|pid| u32::try_from(pid).ok());
Some(Joined { stream: Box::new(stream), peer })
}
/// Owner read and write only. The folder is private already; this is the second lock.
fn restrict(path: &Path) -> Result<(), EndpointError> {
use std::os::unix::fs::PermissionsExt;
let owner_only = std::fs::Permissions::from_mode(crate::fs_atomic::OWNER_ONLY);
std::fs::set_permissions(path, owner_only)
.map_err(EndpointError::io(format!("restrict {}", path.display())))
}
pub(super) async fn connect(address: &str) -> Result<LocalStream, EndpointError> {
let stream = UnixStream::connect(address)
.await
.map_err(EndpointError::io(format!("connect to {address}")))?;
Ok(Box::new(stream))
}

View File

@@ -0,0 +1,75 @@
//! The Windows endpoint: a named pipe only this user can open, and no other machine can reach.
//!
//! The defaults are wrong for this. A pipe's default security grants read access to Everyone and
//! the anonymous account, and reading is the whole transcript; and a pipe can be opened across the
//! network while the Server service runs. So every instance is created with a descriptor granting
//! this user alone, remote clients are refused, and the first instance must be new, so nothing can
//! claim the name before Luxe does.
use super::{EndpointError, Joined, LocalStream};
use std::path::Path;
use std::time::Duration;
use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeServer, ServerOptions};
use windows_sys::Win32::Foundation::ERROR_PIPE_BUSY;
mod security;
pub(super) use security::process_parents;
/// How long a client waits for the server's next instance, which only lags the last connection.
const BUSY_RETRIES: u32 = 40;
/// A pipe with an instance always waiting for the next client.
pub(super) struct Listener {
next: NamedPipeServer,
address: String,
descriptor: security::OwnerOnly,
}
impl Listener {
/// `_dir` has no part: a pipe has a name rather than a place.
pub(super) fn bind(_dir: &Path) -> Result<Self, EndpointError> {
let descriptor = security::OwnerOnly::new()
.map_err(EndpointError::io("describe who may open the pipe"))?;
let address = format!(r"\\.\pipe\luxe-{}", uuid::Uuid::new_v4().simple());
let next = create(&address, &descriptor, true)?;
Ok(Self { next, address, descriptor })
}
pub(super) fn address(&self) -> &str {
&self.address
}
pub(super) async fn accept(&mut self) -> Result<Joined, EndpointError> {
self.next.connect().await.map_err(EndpointError::io("accept a client"))?;
let waiting = create(&self.address, &self.descriptor, false)?;
let connected = std::mem::replace(&mut self.next, waiting);
let peer = security::client_process_id(&connected);
Ok(Joined { stream: Box::new(connected), peer })
}
}
/// One instance of the pipe at `address`; `first` refuses a name something else already holds.
fn create(
address: &str,
descriptor: &security::OwnerOnly,
first: bool,
) -> Result<NamedPipeServer, EndpointError> {
let mut options = ServerOptions::new();
options.first_pipe_instance(first).reject_remote_clients(true);
descriptor.create(&options, address).map_err(EndpointError::io(format!("open {address}")))
}
pub(super) async fn connect(address: &str) -> Result<LocalStream, EndpointError> {
for _ in 0..BUSY_RETRIES {
match ClientOptions::new().open(address) {
Ok(client) => return Ok(Box::new(client)),
Err(error) if error.raw_os_error() == Some(ERROR_PIPE_BUSY as i32) => {
tokio::time::sleep(Duration::from_millis(50)).await;
}
Err(error) => return Err(EndpointError::io(format!("connect to {address}"))(error)),
}
}
let busy = std::io::Error::from_raw_os_error(ERROR_PIPE_BUSY as i32);
Err(EndpointError::io(format!("connect to {address}"))(busy))
}

View File

@@ -0,0 +1,166 @@
//! The Windows calls behind the pipe: who this user is, a descriptor naming them alone, who
//! connected, and every process's parent.
//!
//! No safe API does any of it, so the `unsafe` lives here and nowhere else in the endpoint.
use std::collections::HashMap;
use std::io;
use std::os::windows::io::AsRawHandle;
use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions};
use windows_sys::Win32::Foundation::{CloseHandle, LocalFree, HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::Security::Authorization::{
ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
};
use windows_sys::Win32::Security::{
GetTokenInformation, TokenUser, PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES, TOKEN_QUERY,
TOKEN_USER,
};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS,
};
use windows_sys::Win32::System::Pipes::GetNamedPipeClientProcessId;
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
/// A security descriptor whose only entry grants this user everything, freed on drop.
pub(super) struct OwnerOnly(PSECURITY_DESCRIPTOR);
// SAFETY: the descriptor is immutable once built and only read by `CreateNamedPipeW`.
#[allow(unsafe_code)]
unsafe impl Send for OwnerOnly {}
// SAFETY: as above.
#[allow(unsafe_code)]
unsafe impl Sync for OwnerOnly {}
impl OwnerOnly {
/// `D:P(A;;GA;;;<this user>)`: a protected list, so nothing is inherited, with one entry.
#[allow(unsafe_code)]
pub(super) fn new() -> io::Result<Self> {
let sddl = format!("D:P(A;;GA;;;{})", current_user_sid()?);
let wide: Vec<u16> = sddl.encode_utf16().chain(std::iter::once(0)).collect();
let mut descriptor: PSECURITY_DESCRIPTOR = std::ptr::null_mut();
// SAFETY: `wide` is NUL-terminated and outlives the call; the descriptor it allocates is
// owned by the returned value and freed in `drop`.
let made = unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
wide.as_ptr(),
SDDL_REVISION_1,
&mut descriptor,
std::ptr::null_mut(),
)
};
if made == 0 {
return Err(io::Error::last_os_error());
}
Ok(Self(descriptor))
}
/// A pipe instance at `address` carrying this descriptor.
#[allow(unsafe_code)]
pub(super) fn create(
&self,
options: &ServerOptions,
address: &str,
) -> io::Result<NamedPipeServer> {
let mut attributes = SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: self.0,
bInheritHandle: 0,
};
// SAFETY: `attributes` is a valid SECURITY_ATTRIBUTES pointing at a live descriptor this
// value owns, and both outlive the call.
unsafe {
options.create_with_security_attributes_raw(
address,
(&mut attributes as *mut SECURITY_ATTRIBUTES).cast(),
)
}
}
}
impl Drop for OwnerOnly {
#[allow(unsafe_code)]
fn drop(&mut self) {
// SAFETY: allocated by `ConvertStringSecurityDescriptorToSecurityDescriptorW`, freed once.
unsafe { LocalFree(self.0) };
}
}
/// This process's user, as a SID string (`S-1-5-21-…`).
#[allow(unsafe_code)]
fn current_user_sid() -> io::Result<String> {
let mut token: HANDLE = std::ptr::null_mut();
// SAFETY: the pseudo-handle needs no closing; `token` is closed below on every path.
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
return Err(io::Error::last_os_error());
}
let user = token_user(token);
// SAFETY: opened above and not used after this.
unsafe { CloseHandle(token) };
let user = user?;
// SAFETY: the buffer holds a TOKEN_USER written by `GetTokenInformation`, and is u64-aligned.
let sid = unsafe { (*user.as_ptr().cast::<TOKEN_USER>()).User.Sid };
let mut text: *mut u16 = std::ptr::null_mut();
// SAFETY: `sid` points into `user`, alive here; the string it allocates is freed below.
if unsafe { ConvertSidToStringSidW(sid, &mut text) } == 0 {
return Err(io::Error::last_os_error());
}
// SAFETY: `text` is a NUL-terminated string from the call above, freed once after copying.
let sid = unsafe {
let length = (0..).take_while(|&at| *text.add(at) != 0).count();
let copied = String::from_utf16_lossy(std::slice::from_raw_parts(text, length));
LocalFree(text.cast());
copied
};
Ok(sid)
}
/// The token's TOKEN_USER, in a buffer aligned for it.
#[allow(unsafe_code)]
fn token_user(token: HANDLE) -> io::Result<Vec<u64>> {
let mut size = 0u32;
// SAFETY: a size query, writing only `size`.
unsafe { GetTokenInformation(token, TokenUser, std::ptr::null_mut(), 0, &mut size) };
let mut buffer = vec![0u64; (size as usize).div_ceil(8)];
// SAFETY: `buffer` holds at least `size` bytes.
let read = unsafe {
GetTokenInformation(token, TokenUser, buffer.as_mut_ptr().cast(), size, &mut size)
};
if read == 0 {
return Err(io::Error::last_os_error());
}
Ok(buffer)
}
/// The process on the other end of a connected pipe.
#[allow(unsafe_code)]
pub(super) fn client_process_id(pipe: &NamedPipeServer) -> Option<u32> {
let mut pid = 0u32;
// SAFETY: the handle is the live, connected pipe, borrowed for the call.
let found = unsafe { GetNamedPipeClientProcessId(pipe.as_raw_handle() as HANDLE, &mut pid) };
(found != 0).then_some(pid)
}
/// Every running process's parent, from one snapshot; empty when Windows will not take one.
#[allow(unsafe_code)]
pub(in crate::local_endpoint) fn process_parents() -> HashMap<u32, u32> {
let mut parents = HashMap::new();
// SAFETY: a snapshot of processes, closed below.
let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
if snapshot == INVALID_HANDLE_VALUE {
return parents;
}
let mut entry = PROCESSENTRY32W {
dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32,
..Default::default()
};
// SAFETY: `entry` is sized as the API requires and reused for each process.
let mut more = unsafe { Process32FirstW(snapshot, &mut entry) } != 0;
while more {
parents.insert(entry.th32ProcessID, entry.th32ParentProcessID);
// SAFETY: as above.
more = unsafe { Process32NextW(snapshot, &mut entry) } != 0;
}
// SAFETY: opened above and not used after this.
unsafe { CloseHandle(snapshot) };
parents
}