systemprompt_models/subprocess/
mod.rs1use std::process::Command;
44use std::sync::OnceLock;
45use std::sync::mpsc::{Sender, channel};
46
47#[cfg(target_os = "linux")]
48mod linux;
49#[cfg(target_os = "linux")]
50pub use linux::{is_zombie, live_pid_is_subprocess};
51
52#[cfg(target_os = "macos")]
53mod darwin;
54#[cfg(target_os = "macos")]
55pub use darwin::{is_zombie, live_pid_is_subprocess};
56
57#[cfg(not(any(target_os = "linux", target_os = "macos")))]
58mod unsupported;
59#[cfg(not(any(target_os = "linux", target_os = "macos")))]
60pub use unsupported::{is_zombie, live_pid_is_subprocess};
61
62pub const SUBPROCESS_MARKER_ENV: &str = "SYSTEMPROMPT_SUBPROCESS";
63pub const AGENT_NAME_ENV: &str = "AGENT_NAME";
64pub const MCP_SERVICE_ID_ENV: &str = "MCP_SERVICE_ID";
65
66pub const DEPLOYMENT_HOST_ENV: &str = "SYSTEMPROMPT_DEPLOYMENT_HOST";
67
68const FLY_HOST_ENV: &str = "FLY_APP_NAME";
70
71pub fn deployment_host(lookup: impl Fn(&str) -> Option<String>) -> Option<String> {
72 [DEPLOYMENT_HOST_ENV, FLY_HOST_ENV].iter().find_map(|name| {
73 lookup(name)
74 .map(|value| value.trim().to_owned())
75 .filter(|value| !value.is_empty())
76 })
77}
78
79pub fn is_deployment_host(lookup: impl Fn(&str) -> Option<String>) -> bool {
80 deployment_host(lookup).is_some()
81}
82
83pub fn inherited_parent_env(lookup: impl Fn(&str) -> Option<String>) -> Vec<(String, String)> {
84 let mut env: Vec<(String, String)> = [
85 DEPLOYMENT_HOST_ENV,
86 FLY_HOST_ENV,
87 "HOSTNAME",
88 "PATH",
89 "HOME",
90 ]
91 .iter()
92 .filter_map(|name| lookup(name).map(|value| ((*name).to_owned(), value)))
93 .collect();
94
95 if let Some(entry) = crate::net::trusted_hosts_env_entry(&lookup) {
96 env.push(entry);
97 }
98
99 env
100}
101
102type SpawnReply = Sender<std::io::Result<u32>>;
103
104pub fn spawn_supervised(cmd: Command) -> std::io::Result<u32> {
105 let sender = spawner()
106 .as_ref()
107 .map_err(|e| std::io::Error::other(e.clone()))?;
108
109 let (reply_tx, reply_rx) = channel();
110 sender
111 .send((cmd, reply_tx))
112 .map_err(|disconnected| std::io::Error::other(disconnected.to_string()))?;
113 reply_rx
114 .recv()
115 .map_err(|disconnected| std::io::Error::other(disconnected.to_string()))?
116}
117
118fn spawner() -> &'static Result<Sender<(Command, SpawnReply)>, String> {
119 static SPAWNER: OnceLock<Result<Sender<(Command, SpawnReply)>, String>> = OnceLock::new();
120 SPAWNER.get_or_init(|| {
121 let (tx, rx) = channel::<(Command, SpawnReply)>();
122 std::thread::Builder::new()
123 .name("subprocess-spawner".to_owned())
124 .spawn(move || {
125 while let Ok((mut cmd, reply)) = rx.recv() {
126 let outcome = spawn_on_this_thread(&mut cmd);
127 if reply.send(outcome).is_err() {
128 tracing::warn!(
129 "Spawn requester vanished before collecting the child pid; the child \
130 is unregistered and will only be cleaned up by its parent-death signal"
131 );
132 }
133 }
134 })
135 .map(|_handle| tx)
136 .map_err(|e| format!("could not start the subprocess spawner thread: {e}"))
137 })
138}
139
140fn spawn_on_this_thread(cmd: &mut Command) -> std::io::Result<u32> {
141 #[cfg(target_os = "linux")]
142 linux::arm_parent_death_signal(cmd);
143
144 let child = cmd.spawn()?;
145 let pid = child.id();
146 #[expect(
147 clippy::mem_forget,
148 reason = "detached child: skip Child's drop-time wait so it keeps running after this \
149 returns; reaping is the caller's business via is_zombie"
150 )]
151 std::mem::forget(child);
152 Ok(pid)
153}
154
155#[cfg(unix)]
158pub fn place_in_own_process_group(command: &mut Command) {
159 use std::os::unix::process::CommandExt;
160 command.process_group(0);
161}
162
163#[cfg(windows)]
164pub fn place_in_own_process_group(command: &mut Command) {
165 use std::os::windows::process::CommandExt;
166 const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
167 command.creation_flags(CREATE_NEW_PROCESS_GROUP);
168}
169
170#[must_use]
171pub const fn identity_verification_supported() -> bool {
172 cfg!(any(target_os = "linux", target_os = "macos"))
173}
174
175#[must_use]
176pub fn signalable_pid(pid: u32) -> Option<i32> {
177 if pid == 0 {
178 return None;
179 }
180 i32::try_from(pid).ok()
181}
182
183#[must_use]
184pub fn environ_identifies_child(environ: &[u8], name_key: &str, service_name: &str) -> bool {
185 let marker = format!("{SUBPROCESS_MARKER_ENV}=1");
186 let expected_name = format!("{name_key}={service_name}");
187
188 let mut has_marker = false;
189 let mut has_name = false;
190 for entry in environ.split(|&b| b == 0) {
191 if entry == marker.as_bytes() {
192 has_marker = true;
193 } else if entry == expected_name.as_bytes() {
194 has_name = true;
195 }
196 }
197
198 has_marker && has_name
199}
200
201#[must_use]
205pub fn environ_from_procargs2(blob: &[u8]) -> Option<&[u8]> {
206 const ARGC_LEN: usize = size_of::<i32>();
207
208 let argc_bytes: [u8; ARGC_LEN] = blob.get(..ARGC_LEN)?.try_into().ok()?;
209 let argc = usize::try_from(i32::from_ne_bytes(argc_bytes)).ok()?;
210
211 let mut rest = blob.get(ARGC_LEN..)?;
212 let exec_path_end = rest.iter().position(|&b| b == 0)?;
213 rest = rest.get(exec_path_end + 1..)?;
214
215 let argv_start = rest.iter().position(|&b| b != 0)?;
216 rest = rest.get(argv_start..)?;
217
218 for _ in 0..argc {
219 let entry_end = rest.iter().position(|&b| b == 0)?;
220 rest = rest.get(entry_end + 1..)?;
221 }
222
223 Some(rest)
224}