git.delta.rocks / remowt / refs/commits / 113f1e5ab113

difftreelog

fix privileged agent plugins

tyzsxvmrYaroslav Bolyukin2026-06-12parent: #62007a6.patch.diff
in: trunk

4 files changed

modifiedcmds/remowt-agent/src/main.rsdiffbeforeafterboth
before · cmds/remowt-agent/src/main.rs
1use std::borrow::Cow;2use std::collections::{BTreeMap, HashMap};3use std::fs::Permissions;4use std::future::pending;5use std::os::unix::fs::PermissionsExt as _;6use std::path::PathBuf;7use std::sync::{Arc, Mutex, OnceLock};89use bifrostlink::declarative::RemoteEndpoints;10use bifrostlink::Rpc;11use bifrostlink_ports::stdio::from_stdio;12use bifrostlink_ports::unix_socket::from_socket;13use clap::Parser;14use remowt_link_shared::editor::EditorEndpointsClient;15use remowt_link_shared::{Address, BifConfig, Fs, Pty, Systemd};16use remowt_polkit_shared::{emphasize, BackendRequest, Identity, PidDisplay};17use remowt_ui_prompt::bifrost::PromptEndpointsClient;18use remowt_ui_prompt::{PrependSourcePrompter, Prompter, Source};19use tokio::fs;20use tokio::net::UnixStream;21use tokio::runtime::Builder;22use tokio::task::AbortHandle;23use tracing::{info, trace};24use zbus::fdo;25use zbus::zvariant::{OwnedValue, Str};26use zbus::{interface, proxy, Connection};27use zbus_polkit::policykit1::Subject;2829use self::helper::{Helper, SocketHelper, SuidHelper};3031pub mod askpass;32pub mod bus;33pub mod editor;34pub mod helper;3536struct CancelTaskOnDrop {37	tasks: Arc<Mutex<HashMap<String, AbortHandle>>>,38	handle: String,39}40impl Drop for CancelTaskOnDrop {41	fn drop(&mut self) {42		info!("cancel on drop");43		if let Some(task) = self44			.tasks45			.lock()46			.expect("not poisoned")47			.remove(&self.handle)48		{49			task.abort();50		}51	}52}5354struct Agent<H, P> {55	tasks: Arc<Mutex<HashMap<String, AbortHandle>>>,56	helper: H,57	prompter: P,58}59impl<H, P> Agent<H, P> {60	fn new(helper: H, prompter: P) -> Self {61		Agent {62			tasks: Arc::new(Mutex::new(HashMap::new())),63			helper,64			prompter,65		}66	}67}6869#[interface(name = "org.freedesktop.PolicyKit1.AuthenticationAgent")]70impl<H, P> Agent<H, P>71where72	H: Helper + Clone + Send + Sync + 'static,73	P: Prompter + Clone + Send + Sync + 'static,74{75	/// BeginAuthentication method76	#[allow(clippy::too_many_arguments)]77	async fn begin_authentication(78		&self,79		action_id: String,80		message: String,81		_icon_name: String,82		mut details: BTreeMap<String, String>,83		cookie: String,84		identities: Vec<Identity>,85	) -> zbus::fdo::Result<()> {86		use std::fmt::Write;87		info!("begin auth");88		let _cancel_guard = Arc::new(OnceLock::new());89		let task = {90			let helper = self.helper.clone();91			let prompter = self.prompter.clone();92			let cookie = cookie.clone();93			let _cancel_guard = _cancel_guard.clone();94			tokio::task::spawn(async move {95				let _cancel_guard = _cancel_guard.clone();96				trace!("conversation task");97				let mut description = format!("{message}\n\n<b>Action id:</b> {action_id}",);98				if let Some(subject) = details.remove("polkit.caller-pid") {99					let _ = write!(description, "\n<b>Caller:</b> ");100					if let Ok(pid) = subject.parse::<u32>() {101						let _ = write!(description, "{}", PidDisplay(pid));102					} else {103						let _ = write!(description, "{}", emphasize("invalid pid"));104					}105				}106				if let Some(subject) = details.remove("polkit.subject-pid") {107					let _ = write!(description, "\n<b>Subject:</b> ");108					if let Ok(pid) = subject.parse::<u32>() {109						let _ = write!(description, "{}", PidDisplay(pid));110					} else {111						let _ = write!(description, "{}", emphasize("invalid pid"));112					}113				}114				let mut prompter = PrependSourcePrompter {115					source: vec![Source(Cow::Borrowed("polkit agent"))],116					description: description.clone(),117					prompter,118				};119120				let identity_displays: Vec<String> =121					identities.iter().map(|v| v.to_string()).collect();122				let identity_displays: Vec<&str> =123					identity_displays.iter().map(|v| v.as_str()).collect();124				info!("choose identity");125				let choosen_identity = match identity_displays.len() {126					0 => {127						return Err(fdo::Error::AuthFailed(128							"no identity to authenticate as".to_owned(),129						))130					}131					1 => 0,132					_ => {133						prompter134							.prompt_enum(135								"Identity",136								"Select identity to use for polkit authorization",137								&identity_displays,138								&[],139							)140							.await?141					}142				};143				info!("identity chosen");144145				let _ = write!(146					description,147					"\n<b>Identity:</b> {}",148					identities[choosen_identity as usize]149				);150				prompter.description = description;151152				prompter.source.push(Source(Cow::Borrowed("polkit daemon")));153154				helper155					.help_me(156						&cookie,157						prompter,158						identities[choosen_identity as usize].clone(),159					)160					.await161					.map_err(|e| fdo::Error::Failed(e.to_string()))?;162				// let connection = Connection::system().await?;163				// let helper = PolkitHelperProxy::new(&connection).await?;164165				Ok(())166			})167		};168		self.tasks169			.lock()170			.unwrap()171			.insert(cookie.clone(), task.abort_handle());172		info!("abort handle stored");173		let _ = _cancel_guard.set(CancelTaskOnDrop {174			tasks: self.tasks.clone(),175			handle: cookie.clone(),176		});177178		let _ = task.await;179180		Ok(())181	}182183	/// CancelAuthentication method184	async fn cancel_authentication(&self, cookie: &str) -> zbus::fdo::Result<()> {185		info!("auth cancelled");186		if let Some(abort) = self.tasks.lock().unwrap().remove(cookie) {187			info!("abort handle found");188			abort.abort();189		}190		// debug!("Authentication cancled ! {cookie}");191		Ok(())192	}193}194195const OBJ_PATH: &str = "/org/freedesktop/PolicyKit1/AuthenticationAgent";196197#[proxy(198	interface = "lach.PolkitHelper",199	default_service = "lach.polkit.helper1",200	default_path = "/lach/PolkitHelper"201)]202trait PolkitHelper {203	fn init_conversation(&self, request: BackendRequest) -> zbus::Result<()>;204}205206#[derive(Parser)]207enum Opts {208	AskPass {209		prompt: String,210		description: String,211	},212	Editor {213		/// Argument to nvim214		path: String,215	},216	RealAgent {217		#[arg(long)]218		path: Option<PathBuf>,219		/// Expect own address to be AgentPrivileged, skip installing polkit agent220		#[arg(long)]221		privileged: bool,222	},223}224225fn main() -> anyhow::Result<()> {226	// Log to stderr: `privileged-agent` uses stdout as the bifrost transport,227	// so anything written there would corrupt the stream.228	tracing_subscriber::fmt()229		.with_writer(std::io::stderr)230		.init();231	let opts = Opts::parse();232233	let runtime = Builder::new_current_thread().enable_all().build()?;234235	match opts {236		Opts::AskPass {237			prompt,238			description,239		} => runtime.block_on(askpass::ask(&prompt, description)),240		Opts::Editor { path } => runtime.block_on(editor::edit(path)),241		Opts::RealAgent { path, privileged } => runtime.block_on(main_real_agent(path, privileged)),242	}243}244async fn main_real_agent(path: Option<PathBuf>, privileged: bool) -> anyhow::Result<()> {245	let address = if privileged {246		Address::AgentPrivileged247	} else {248		Address::Agent249	};250	let mut rpc = Rpc::<BifConfig>::new(address);251252	Fs::new().register_endpoints(&mut rpc);253	Systemd.register_endpoints(&mut rpc);254	Pty::new().register_endpoints(&mut rpc);255256	remowt_plugin::host::serve(&mut rpc);257258	let user_prompter = PromptEndpointsClient::wrap(rpc.remote(Address::User));259	let editor_client = EditorEndpointsClient::wrap(rpc.remote(Address::User));260261	let bus = bus::spawn().await?;262	askpass::serve(&bus.conn, user_prompter.clone()).await?;263	editor::serve(&bus.conn, editor_client).await?;264265	let helpers = tempfile::Builder::new().prefix("remowt-path.").tempdir()?;266	let exe = std::env::current_exe()?;267	let askpass_helper = helpers.path().join("remowt-askpass");268	let editor_helper = helpers.path().join("remowt-editor");269	{270		let script = format!(271			"#!/bin/sh\nexec {} ask-pass \"password\" \"$1\"\n",272			sh_quote(&exe.to_string_lossy())273		);274		fs::write(&askpass_helper, script).await?;275		fs::set_permissions(&askpass_helper, Permissions::from_mode(0o755)).await?;276	}277	{278		let script = format!(279			"#!/bin/sh\nexec {} editor \"$1\"\n",280			sh_quote(&exe.to_string_lossy())281		);282		fs::write(&editor_helper, script).await?;283		fs::set_permissions(&editor_helper, Permissions::from_mode(0o755)).await?;284	}285286	// Safety: Hoping tokio own threads won't read any of those...287	unsafe {288		prepend_path(helpers.path());289		std::env::set_var("SUDO_ASKPASS", &askpass_helper);290		std::env::set_var("SSH_ASKPASS", &askpass_helper);291		std::env::set_var("SSH_ASKPASS_REQUIRE", "force");292		std::env::set_var("EDITOR", &editor_helper);293		std::env::set_var("VISUAL", &editor_helper);294		std::env::set_var("DBUS_SESSION_BUS_ADDRESS", &bus.address);295	}296297	let port = match path {298		Some(path) => from_socket(UnixStream::connect(path).await?),299		None => from_stdio(),300	};301	rpc.add_direct(Address::User, port, bifrostlink::Rtt(0));302303	let polkit_conn = if !privileged {304		// The unprivileged agent doubles as a polkit authentication agent so305		// `run0` (e.g. our own elevation) routes its prompt to the User over306		// bifrost instead of failing on a tty-less session.307		let conn = Connection::system().await?;308		let helper = SocketHelper {309			fallback: SuidHelper,310		};311		register_auth_agent(&conn, Agent::new(helper, user_prompter)).await?;312		Some(conn)313	} else {314		None315	};316317	let _keep_alive = (bus, helpers, polkit_conn);318	pending().await319}320321async fn register_auth_agent<H, P>(conn: &Connection, agent: Agent<H, P>) -> anyhow::Result<()>322where323	H: Helper + Clone + Send + Sync + 'static,324	P: Prompter + Clone + Send + Sync + 'static,325{326	let proxy = zbus_polkit::policykit1::AuthorityProxy::new(conn).await?;327	conn.object_server().at(OBJ_PATH, agent).await?;328329	let subject = auth_agent_subject()?;330	proxy331		.register_authentication_agent(&subject, "C", OBJ_PATH)332		.await?;333	info!(kind = subject.subject_kind, "registered polkit agent");334	Ok(())335}336337fn auth_agent_subject() -> anyhow::Result<Subject> {338	let mut details = HashMap::new();339	if let Ok(session_id) = std::env::var("XDG_SESSION_ID") {340		let val: OwnedValue = Str::from(session_id).into();341		details.insert("session-id".to_string(), val);342		return Ok(Subject {343			subject_kind: "unix-session".to_string(),344			subject_details: details,345		});346	}347348	details.insert("pid".to_string(), OwnedValue::from(std::process::id()));349	Ok(Subject {350		subject_kind: "unix-process".to_string(),351		subject_details: details,352	})353}354355fn sh_quote(s: &str) -> String {356	format!("'{}'", s.replace('\'', "'\\''"))357}358359/// Prepend `dir` to the process `PATH`.360///361/// # SAFETY362///363/// Same as `set_var`364unsafe fn prepend_path(dir: &std::path::Path) {365	let value = match std::env::var_os("PATH") {366		Some(existing) => {367			let mut v = dir.as_os_str().to_owned();368			v.push(":");369			v.push(existing);370			v371		}372		None => dir.as_os_str().to_owned(),373	};374	unsafe {375		std::env::set_var("PATH", value);376	}377}
after · cmds/remowt-agent/src/main.rs
1use std::borrow::Cow;2use std::collections::{BTreeMap, HashMap};3use std::fs::Permissions;4use std::future::pending;5use std::os::unix::fs::PermissionsExt as _;6use std::path::PathBuf;7use std::sync::{Arc, Mutex, OnceLock};89use bifrostlink::declarative::RemoteEndpoints;10use bifrostlink::Rpc;11use bifrostlink_ports::stdio::from_stdio;12use bifrostlink_ports::unix_socket::from_socket;13use clap::Parser;14use remowt_link_shared::editor::EditorEndpointsClient;15use remowt_link_shared::{Address, BifConfig, Fs, Pty, Systemd};16use remowt_polkit_shared::{emphasize, BackendRequest, Identity, PidDisplay};17use remowt_ui_prompt::bifrost::PromptEndpointsClient;18use remowt_ui_prompt::rofi::RofiPrompter;19use remowt_ui_prompt::{PrependSourcePrompter, Prompter, Source};20use tokio::fs;21use tokio::net::UnixStream;22use tokio::runtime::Builder;23use tokio::task::AbortHandle;24use tracing::{debug, info, trace};25use zbus::fdo;26use zbus::zvariant::{OwnedValue, Str};27use zbus::{interface, proxy, Connection};28use zbus_polkit::policykit1::Subject;2930use self::helper::{Helper, SocketHelper, SuidHelper};3132pub mod askpass;33pub mod bus;34pub mod editor;35pub mod helper;3637struct CancelTaskOnDrop {38	tasks: Arc<Mutex<HashMap<String, AbortHandle>>>,39	handle: String,40}41impl Drop for CancelTaskOnDrop {42	fn drop(&mut self) {43		debug!("cancel on drop");44		if let Some(task) = self45			.tasks46			.lock()47			.expect("not poisoned")48			.remove(&self.handle)49		{50			task.abort();51		}52	}53}5455struct Agent<H, P> {56	tasks: Arc<Mutex<HashMap<String, AbortHandle>>>,57	helper: H,58	prompter: P,59}60impl<H, P> Agent<H, P> {61	fn new(helper: H, prompter: P) -> Self {62		Agent {63			tasks: Arc::new(Mutex::new(HashMap::new())),64			helper,65			prompter,66		}67	}68}6970#[interface(name = "org.freedesktop.PolicyKit1.AuthenticationAgent")]71impl<H, P> Agent<H, P>72where73	H: Helper + Clone + Send + Sync + 'static,74	P: Prompter + Clone + Send + Sync + 'static,75{76	/// BeginAuthentication method77	#[allow(clippy::too_many_arguments)]78	async fn begin_authentication(79		&self,80		action_id: String,81		message: String,82		_icon_name: String,83		mut details: BTreeMap<String, String>,84		cookie: String,85		identities: Vec<Identity>,86	) -> zbus::fdo::Result<()> {87		use std::fmt::Write;88		info!("begin auth");89		let _cancel_guard = Arc::new(OnceLock::new());90		let task = {91			let helper = self.helper.clone();92			let prompter = self.prompter.clone();93			let cookie = cookie.clone();94			let _cancel_guard = _cancel_guard.clone();95			tokio::task::spawn(async move {96				let _cancel_guard = _cancel_guard.clone();97				trace!("conversation task");98				let mut description = format!("{message}\n\n<b>Action id:</b> {action_id}",);99				if let Some(subject) = details.remove("polkit.caller-pid") {100					let _ = write!(description, "\n<b>Caller:</b> ");101					if let Ok(pid) = subject.parse::<u32>() {102						let _ = write!(description, "{}", PidDisplay(pid));103					} else {104						let _ = write!(description, "{}", emphasize("invalid pid"));105					}106				}107				if let Some(subject) = details.remove("polkit.subject-pid") {108					let _ = write!(description, "\n<b>Subject:</b> ");109					if let Ok(pid) = subject.parse::<u32>() {110						let _ = write!(description, "{}", PidDisplay(pid));111					} else {112						let _ = write!(description, "{}", emphasize("invalid pid"));113					}114				}115				let mut prompter = PrependSourcePrompter {116					source: vec![Source(Cow::Borrowed("polkit agent"))],117					description: description.clone(),118					prompter,119				};120121				let identity_displays: Vec<String> =122					identities.iter().map(|v| v.to_string()).collect();123				let identity_displays: Vec<&str> =124					identity_displays.iter().map(|v| v.as_str()).collect();125				debug!("choose identity");126				let choosen_identity = match identity_displays.len() {127					0 => {128						return Err(fdo::Error::AuthFailed(129							"no identity to authenticate as".to_owned(),130						))131					}132					1 => 0,133					_ => {134						prompter135							.prompt_enum(136								"Identity",137								"Select identity to use for polkit authorization",138								&identity_displays,139								&[],140							)141							.await?142					}143				};144				debug!("identity chosen");145146				let _ = write!(147					description,148					"\n<b>Identity:</b> {}",149					identities[choosen_identity as usize]150				);151				prompter.description = description;152153				prompter.source.push(Source(Cow::Borrowed("polkit daemon")));154155				helper156					.help_me(157						&cookie,158						prompter,159						identities[choosen_identity as usize].clone(),160					)161					.await162					.map_err(|e| fdo::Error::Failed(e.to_string()))?;163				// let connection = Connection::system().await?;164				// let helper = PolkitHelperProxy::new(&connection).await?;165166				Ok(())167			})168		};169		self.tasks170			.lock()171			.unwrap()172			.insert(cookie.clone(), task.abort_handle());173		debug!("abort handle stored");174		let _ = _cancel_guard.set(CancelTaskOnDrop {175			tasks: self.tasks.clone(),176			handle: cookie.clone(),177		});178179		let _ = task.await;180181		Ok(())182	}183184	/// CancelAuthentication method185	async fn cancel_authentication(&self, cookie: &str) -> zbus::fdo::Result<()> {186		debug!("auth cancelled");187		if let Some(abort) = self.tasks.lock().unwrap().remove(cookie) {188			debug!("abort handle found");189			abort.abort();190		}191		// debug!("Authentication cancled ! {cookie}");192		Ok(())193	}194}195196const OBJ_PATH: &str = "/org/freedesktop/PolicyKit1/AuthenticationAgent";197198#[proxy(199	interface = "lach.PolkitHelper",200	default_service = "lach.polkit.helper1",201	default_path = "/lach/PolkitHelper"202)]203trait PolkitHelper {204	fn init_conversation(&self, request: BackendRequest) -> zbus::Result<()>;205}206207#[derive(Parser)]208enum Opts {209	AskPass {210		prompt: String,211		description: String,212	},213	Editor {214		/// Argument to nvim215		path: String,216	},217	RealAgent {218		#[arg(long)]219		path: Option<PathBuf>,220		/// Expect own address to be AgentPrivileged, skip installing polkit agent221		#[arg(long)]222		privileged: bool,223	},224	LocalAgent,225}226227fn main() -> anyhow::Result<()> {228	// Log to stderr: `privileged-agent` uses stdout as the bifrost transport,229	// so anything written there would corrupt the stream.230	tracing_subscriber::fmt()231		.with_writer(std::io::stderr)232		.without_time()233		.init();234	let opts = Opts::parse();235236	let runtime = Builder::new_current_thread().enable_all().build()?;237238	match opts {239		Opts::AskPass {240			prompt,241			description,242		} => runtime.block_on(askpass::ask(&prompt, description)),243		Opts::LocalAgent => runtime.block_on(main_real()),244		Opts::Editor { path } => runtime.block_on(editor::edit(path)),245		Opts::RealAgent { path, privileged } => runtime.block_on(main_real_agent(path, privileged)),246	}247}248async fn main_real() -> anyhow::Result<()> {249	let conn = Connection::system().await?;250	let helper = SocketHelper {251		fallback: SuidHelper,252	};253	register_auth_agent(&conn, Agent::new(helper, RofiPrompter)).await?;254255	let _conn = conn;256	pending().await257}258async fn main_real_agent(path: Option<PathBuf>, privileged: bool) -> anyhow::Result<()> {259	let address = if privileged {260		Address::AgentPrivileged261	} else {262		Address::Agent263	};264	let mut rpc = Rpc::<BifConfig>::new(address);265266	Fs::new().register_endpoints(&mut rpc);267	Systemd.register_endpoints(&mut rpc);268	Pty::new().register_endpoints(&mut rpc);269270	remowt_plugin::host::serve(&mut rpc);271272	let user_prompter = PromptEndpointsClient::wrap(rpc.remote(Address::User));273	let editor_client = EditorEndpointsClient::wrap(rpc.remote(Address::User));274275	let bus = bus::spawn().await?;276	askpass::serve(&bus.conn, user_prompter.clone()).await?;277	editor::serve(&bus.conn, editor_client).await?;278279	let helpers = tempfile::Builder::new().prefix("remowt-path.").tempdir()?;280	let exe = std::env::current_exe()?;281	let askpass_helper = helpers.path().join("remowt-askpass");282	let editor_helper = helpers.path().join("remowt-editor");283	{284		let script = format!(285			"#!/bin/sh\nexec {} ask-pass \"password\" \"$1\"\n",286			sh_quote(&exe.to_string_lossy())287		);288		fs::write(&askpass_helper, script).await?;289		fs::set_permissions(&askpass_helper, Permissions::from_mode(0o755)).await?;290	}291	{292		let script = format!(293			"#!/bin/sh\nexec {} editor \"$1\"\n",294			sh_quote(&exe.to_string_lossy())295		);296		fs::write(&editor_helper, script).await?;297		fs::set_permissions(&editor_helper, Permissions::from_mode(0o755)).await?;298	}299300	// Safety: Hoping tokio own threads won't read any of those...301	unsafe {302		prepend_path(helpers.path());303		std::env::set_var("SUDO_ASKPASS", &askpass_helper);304		std::env::set_var("SSH_ASKPASS", &askpass_helper);305		std::env::set_var("SSH_ASKPASS_REQUIRE", "force");306		std::env::set_var("EDITOR", &editor_helper);307		std::env::set_var("VISUAL", &editor_helper);308		std::env::set_var("DBUS_SESSION_BUS_ADDRESS", &bus.address);309	}310311	let port = match path {312		Some(path) => from_socket(UnixStream::connect(path).await?),313		None => from_stdio(),314	};315	rpc.add_direct(Address::User, port, bifrostlink::Rtt(0));316317	let polkit_conn = if !privileged {318		// The unprivileged agent doubles as a polkit authentication agent so319		// `run0` (e.g. our own elevation) routes its prompt to the User over320		// bifrost instead of failing on a tty-less session.321		let conn = Connection::system().await?;322		let helper = SocketHelper {323			fallback: SuidHelper,324		};325		register_auth_agent(&conn, Agent::new(helper, user_prompter)).await?;326		Some(conn)327	} else {328		None329	};330331	let _keep_alive = (bus, helpers, polkit_conn);332	pending().await333}334335async fn register_auth_agent<H, P>(conn: &Connection, agent: Agent<H, P>) -> anyhow::Result<()>336where337	H: Helper + Clone + Send + Sync + 'static,338	P: Prompter + Clone + Send + Sync + 'static,339{340	let proxy = zbus_polkit::policykit1::AuthorityProxy::new(conn).await?;341	conn.object_server().at(OBJ_PATH, agent).await?;342343	let subject = auth_agent_subject()?;344	proxy345		.register_authentication_agent(&subject, "C", OBJ_PATH)346		.await?;347	debug!(kind = subject.subject_kind, "registered polkit agent");348	Ok(())349}350351fn auth_agent_subject() -> anyhow::Result<Subject> {352	let mut details = HashMap::new();353	if let Ok(session_id) = std::env::var("XDG_SESSION_ID") {354		let val: OwnedValue = Str::from(session_id).into();355		details.insert("session-id".to_string(), val);356		return Ok(Subject {357			subject_kind: "unix-session".to_string(),358			subject_details: details,359		});360	}361362	details.insert("pid".to_string(), OwnedValue::from(std::process::id()));363	Ok(Subject {364		subject_kind: "unix-process".to_string(),365		subject_details: details,366	})367}368369fn sh_quote(s: &str) -> String {370	format!("'{}'", s.replace('\'', "'\\''"))371}372373/// Prepend `dir` to the process `PATH`.374///375/// # SAFETY376///377/// Same as `set_var`378unsafe fn prepend_path(dir: &std::path::Path) {379	let value = match std::env::var_os("PATH") {380		Some(existing) => {381			let mut v = dir.as_os_str().to_owned();382			v.push(":");383			v.push(existing);384			v385		}386		None => dir.as_os_str().to_owned(),387	};388	unsafe {389		std::env::set_var("PATH", value);390	}391}
modifiedcrates/remowt-plugin/Cargo.tomldiffbeforeafterboth
--- a/crates/remowt-plugin/Cargo.toml
+++ b/crates/remowt-plugin/Cargo.toml
@@ -11,6 +11,7 @@
 bifrostlink-ports.workspace = true
 bytes.workspace = true
 remowt-link-shared.workspace = true
+serde_json.workspace = true
 tokio = { workspace = true, features = [
 	"rt",
 	"net",
modifiedcrates/remowt-plugin/src/host.rsdiffbeforeafterboth
--- a/crates/remowt-plugin/src/host.rs
+++ b/crates/remowt-plugin/src/host.rs
@@ -13,6 +13,7 @@
 
 pub fn serve(rpc: &mut Rpc<BifConfig>) {
 	let host = Host {
+		me: rpc.me(),
 		rpc: rpc.clone().downgrade(),
 		children: Mutex::new(Vec::new()),
 	};
@@ -20,6 +21,7 @@
 }
 
 struct Host {
+	me: Address,
 	rpc: WeakRpc<BifConfig>,
 	children: Mutex<Vec<Child>>,
 }
@@ -30,6 +32,7 @@
 
 		let mut child = Command::new(path)
 			.arg(id.to_string())
+			.arg(serde_json::to_string(&self.me).expect("address serializes"))
 			.stdin(Stdio::piped())
 			.stdout(Stdio::piped())
 			.kill_on_drop(true)
modifiedcrates/remowt-plugin/src/lib.rsdiffbeforeafterboth
--- a/crates/remowt-plugin/src/lib.rs
+++ b/crates/remowt-plugin/src/lib.rs
@@ -18,6 +18,13 @@
 		.map_err(|e| anyhow::anyhow!("invalid plugin index {arg:?}: {e}"))
 }
 
+pub fn host_address() -> Result<Address> {
+	let arg = std::env::args()
+		.nth(2)
+		.ok_or_else(|| anyhow::anyhow!("missing host address argument"))?;
+	serde_json::from_str(&arg).map_err(|e| anyhow::anyhow!("invalid host address {arg:?}: {e}"))
+}
+
 pub fn run<F>(register: F) -> Result<()>
 where
 	F: FnOnce(&mut Rpc<BifConfig>),
@@ -27,10 +34,11 @@
 		.init();
 
 	let index = plugin_index()?;
+	let host = host_address()?;
 	let runtime = Builder::new_current_thread().enable_all().build()?;
 	runtime.block_on(async move {
 		let mut rpc = Rpc::<BifConfig>::new(Address::Plugin(index));
-		rpc.add_direct(Address::Agent, from_stdio(), Rtt(0));
+		rpc.add_direct(host, from_stdio(), Rtt(0));
 		register(&mut rpc);
 		let _rpc = rpc;
 		pending::<Result<()>>().await