1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
//! Production [`ProcessSpawner`] implementation backed by
//! `std::process::Command` + `harn_vm::process_sandbox`.
use std::io::{self, Read, Write};
use std::process::{Child, ChildStderr, ChildStdin, ChildStdout, Stdio};
use std::sync::{Arc, LazyLock};
use std::thread;
use std::time::{Duration, Instant};
use harn_vm::process_sandbox;
use super::handle::{
EnvMode, ExitStatus, ProcessError, ProcessHandle, ProcessKiller, ProcessSpawner, SpawnSpec,
WaitOutcome,
};
/// Spawner that produces real OS processes via `std::process::Command`.
pub struct RealSpawner;
static REAL_SPAWNER: LazyLock<Arc<dyn ProcessSpawner>> =
LazyLock::new(|| Arc::new(RealSpawner) as Arc<dyn ProcessSpawner>);
/// Returns the singleton real spawner used as the default.
pub fn default_spawner() -> Arc<dyn ProcessSpawner> {
Arc::clone(&REAL_SPAWNER)
}
impl ProcessSpawner for RealSpawner {
fn spawn(&self, spec: SpawnSpec) -> Result<Box<dyn ProcessHandle>, ProcessError> {
if spec.program.is_empty() {
return Err(ProcessError::InvalidArgv(
"first element of argv must be a non-empty program name".to_string(),
));
}
let mut command = process_sandbox::std_command_for(&spec.program, &spec.args)
.map_err(|e| ProcessError::SandboxSetup(format!("{e:?}")))?;
if let Some(cwd) = spec.cwd.as_ref() {
process_sandbox::enforce_process_cwd(cwd)
.map_err(|e| ProcessError::SandboxCwd(format!("{e:?}")))?;
command.current_dir(cwd);
}
match spec.env_mode {
// `Replace` starts from an empty environment, so nothing to strip.
EnvMode::Replace => {
command.env_clear();
}
// `InheritClean`/`Patch` inherit the full parent environment. Strip
// secret-bearing variables (provider `*_API_KEY`s, `GITHUB_TOKEN`,
// `HARN_CLOUD_API_KEY`, etc.) so build/test commands — and the model
// that reads their stdout as the tool result — never see them.
// Caller-supplied `env` below is applied afterward and is an
// explicit opt-in, so it is intentionally not filtered here.
EnvMode::InheritClean | EnvMode::Patch => {
for (key, _) in std::env::vars_os() {
if let Some(name) = key.to_str() {
if super::handle::is_sensitive_env_name(name) {
command.env_remove(&key);
}
}
}
}
}
// Caller-requested inherited-env strips (e.g. a harness spawning a
// child harn/burin process that must not write into the parent's
// event-log or transcript dirs). Applied before `spec.env`, so an
// explicitly supplied override still wins.
for key in &spec.env_remove {
command.env_remove(key);
}
for (key, value) in &spec.env {
command.env(key, value);
}
// Point the child's temp dir at a sandbox-writable, workspace-local
// location so compiler linkers (rustc/cc/ld, Go, Swift, …) and other
// toolchains that honor TMPDIR/TMP/TEMP don't false-fail trying to write
// intermediates to the unwritable system /tmp under a restricted
// sandbox profile. Applied after the caller's `spec.env` so an explicit
// caller-set TMPDIR wins; only keys the caller did not set receive the
// overlay. No-op when the active profile is unrestricted or no writable
// workspace root is available. TMPDIR/TMP/TEMP are workspace paths, not
// secrets, so this does not widen the env-secret-scrub surface above.
for (key, value) in process_sandbox::active_workspace_tmpdir_env() {
if spec.env.contains_key(&key) {
continue;
}
command.env(key, value);
}
// Pin tool *message* output to a deterministic English/UTF-8 locale so
// downstream English-diagnostic matchers (deterministic syntax repair,
// error-signature grounding, completion/pass-fail classification) do not
// misfire for a non-Anglosphere user whose shell localizes compiler/test
// output. A user-inherited `LC_ALL` overrides `LC_MESSAGES`, so strip it
// first — unless the caller pinned it. Then apply the overlay with the
// same caller-wins rule as the TMPDIR overlay above.
if !spec
.env
.contains_key(process_sandbox::MESSAGE_LOCALE_OVERRIDE_ENV)
{
command.env_remove(process_sandbox::MESSAGE_LOCALE_OVERRIDE_ENV);
}
for (key, value) in process_sandbox::deterministic_message_locale_env() {
if spec.env.contains_key(&key) {
continue;
}
command.env(key, value);
}
if spec.configure_process_group {
configure_background_process_group(&mut command);
}
command.stdout(Stdio::piped());
command.stderr(Stdio::piped());
command.stdin(if spec.use_stdin {
Stdio::piped()
} else {
Stdio::null()
});
let child = command.spawn().map_err(|e| {
if let Some(violation) = process_sandbox::process_spawn_error(&e) {
return ProcessError::SandboxSpawn(format!("{violation:?}"));
}
ProcessError::Spawn(format!("{e}"))
})?;
let pid = child.id();
let pgid = child_process_group_id(pid);
let killer: Arc<dyn ProcessKiller> = Arc::new(RealKiller { pid });
Ok(Box::new(RealProcess {
pid,
pgid,
killer,
child: Some(child),
stdin: None,
stdout: None,
stderr: None,
stdin_taken: false,
stdout_taken: false,
stderr_taken: false,
}))
}
}
struct RealProcess {
pid: u32,
pgid: Option<u32>,
killer: Arc<dyn ProcessKiller>,
child: Option<Child>,
stdin: Option<ChildStdin>,
stdout: Option<ChildStdout>,
stderr: Option<ChildStderr>,
stdin_taken: bool,
stdout_taken: bool,
stderr_taken: bool,
}
impl RealProcess {
fn ensure_pipes_taken(&mut self) {
if let Some(child) = self.child.as_mut() {
if self.stdin.is_none() && !self.stdin_taken {
self.stdin = child.stdin.take();
}
if self.stdout.is_none() && !self.stdout_taken {
self.stdout = child.stdout.take();
}
if self.stderr.is_none() && !self.stderr_taken {
self.stderr = child.stderr.take();
}
}
}
}
impl ProcessHandle for RealProcess {
fn pid(&self) -> Option<u32> {
Some(self.pid)
}
fn process_group_id(&self) -> Option<u32> {
self.pgid
}
fn killer(&self) -> Arc<dyn ProcessKiller> {
Arc::clone(&self.killer)
}
fn take_stdin(&mut self) -> Option<Box<dyn Write + Send>> {
self.ensure_pipes_taken();
self.stdin_taken = true;
self.stdin
.take()
.map(|s| Box::new(s) as Box<dyn Write + Send>)
}
fn take_stdout(&mut self) -> Option<Box<dyn Read + Send>> {
self.ensure_pipes_taken();
self.stdout_taken = true;
self.stdout
.take()
.map(|s| Box::new(s) as Box<dyn Read + Send>)
}
fn take_stderr(&mut self) -> Option<Box<dyn Read + Send>> {
self.ensure_pipes_taken();
self.stderr_taken = true;
self.stderr
.take()
.map(|s| Box::new(s) as Box<dyn Read + Send>)
}
fn wait_with_timeout(
&mut self,
timeout: Option<Duration>,
interrupt: &dyn Fn() -> bool,
) -> io::Result<WaitOutcome> {
let killer = Arc::clone(&self.killer);
let Some(child) = self.child.as_mut() else {
return Err(io::Error::other("child already reaped"));
};
let deadline = timeout.map(|timeout| Instant::now() + timeout);
loop {
match child.try_wait()? {
Some(status) => return Ok(WaitOutcome::Exited(decode_status(status))),
None => {
if interrupt() {
// Scope cancellation / deadline expiry: graceful
// group termination (SIGTERM, grace, SIGKILL) shared
// with the VM-side `process.*` builtins.
harn_vm::op_interrupt::terminate_child_group(child);
return Ok(WaitOutcome::Interrupted);
}
if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
// `killer.kill()` kills the process tree/group on
// Unix. That path is a no-op on non-Unix targets, so
// also kill the child handle directly
// (TerminateProcess on Windows) to guarantee the
// subsequent `child.wait()` cannot block forever on a
// timed-out process.
killer.kill();
let _ = child.kill();
let _ = child.wait();
return Ok(WaitOutcome::TimedOut);
}
let sleep = deadline
.map(|deadline| deadline.saturating_duration_since(Instant::now()))
.unwrap_or(Duration::MAX)
.min(Duration::from_millis(20));
thread::sleep(sleep);
}
}
}
}
fn wait(&mut self) -> io::Result<ExitStatus> {
let child = self
.child
.as_mut()
.ok_or_else(|| io::Error::other("child already reaped"))?;
let status = child.wait()?;
Ok(decode_status(status))
}
}
struct RealKiller {
pid: u32,
}
impl ProcessKiller for RealKiller {
fn kill(&self) {
harn_vm::op_interrupt::signal_pid_tree_and_group(self.pid, 9);
}
}
#[cfg(unix)]
fn decode_status(status: std::process::ExitStatus) -> ExitStatus {
use std::os::unix::process::ExitStatusExt;
if let Some(code) = status.code() {
ExitStatus::from_code(code)
} else if let Some(sig) = status.signal() {
ExitStatus::from_signal(sig)
} else {
ExitStatus {
code: None,
signal: None,
}
}
}
#[cfg(not(unix))]
fn decode_status(status: std::process::ExitStatus) -> ExitStatus {
ExitStatus::from_code(status.code().unwrap_or(-1))
}
pub(crate) fn child_process_group_id(pid: u32) -> Option<u32> {
#[cfg(unix)]
{
extern "C" {
fn getpgid(pid: i32) -> i32;
}
let pgid = unsafe { getpgid(pid as i32) };
if pgid > 0 {
Some(pgid as u32)
} else {
None
}
}
#[cfg(not(unix))]
{
Some(pid)
}
}
pub(crate) fn configure_background_process_group(command: &mut std::process::Command) {
#[cfg(unix)]
unsafe {
use std::os::unix::process::CommandExt;
command.pre_exec(|| {
extern "C" {
fn setpgid(pid: i32, pgid: i32) -> i32;
}
if setpgid(0, 0) == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
#[cfg(not(unix))]
{
let _ = command;
}
}