Skip to content

Commit 95b018c

Browse files
feat(acp): wrap workers at the subprocess launch boundary (#7985)
## Summary Replacing `BUZZ_ACP_AGENT_COMMAND` with a sandbox launcher hides the real adapter from Buzz: for example, Goose loses its default `acp` argument. Add optional `BUZZ_ACP_LAUNCH_PREFIX`, a JSON argument array applied at the shared subprocess boundary, after normal worker configuration. On Unix, every spawn runs `prefix... worker args...` without shell interpolation. Worker identity, environment setup, stdio and existing process cleanup are preserved. Invalid or unavailable prefixes fail launch without falling back to the worker; unset keeps direct launch on every platform. Configured prefixes fail closed on non-Unix because per-worker process-tree cleanup is unavailable. Desktop reserves the key against saved user-environment overrides, and spawn failures name the executable. ### Related issue Prerequisite for [Buzz-App #415](block/buzz-app#415). One commit directly on `main`, independent of #7942–#7944. No duplicate launch-prefix PR found. Policy enforcement, verified launcher staging, protected paths and the supporting runtime pin remain Buzz-App/plugin work. ### Testing - Original head `9ae9d82f8`: complete ACP suite (990 passed, three existing ignored), shipped local-task test, real-Goose probe, and full repository-wide `just ci` passed. - Review fixes: five launch tests and 44 Desktop environment-filter tests pass locally, covering the real production platform gate, save rejection, both merge layers, case variants, and executable error context. - Subprocess tests cover direct/wrapped argument defaults, Pi skills, Hermes/Codex environment, adapter identity, repeated spawns and invalid/missing prefix refusal. - Shipped `buzz-acp run` entrypoint completes a task through the wrapper and deterministic ACP peer. - Real Goose 1.52.0: direct and wrapped `auth-methods` return identical results; the wrapper receives `goose acp` with initially empty worker args. - Independent agent review: no blocking findings. - Required push checks passed on the updated head. The existing native Windows CI job now explicitly runs the platform-contract tests. Its result is pending; the non-Unix refusal branch was not exercised on this macOS host. Repeated-spawn coverage is not a full lazy-pool wake/crash test. Protected Goose in the Buzz-App UI and human acceptance remain pending. To try the hook after building `buzz-acp`, use an installed Goose path: ```sh BUZZ_ACP_LAUNCH_PREFIX='["/usr/bin/env"]' target/debug/buzz-acp auth-methods \ --agent-command /absolute/path/to/goose --agent-args '' --json ``` Expect the same authentication methods as without the prefix. Changing the prefix to `["/missing-launcher"]` must fail. Draft pending human testing. Signed-off-by: Alex Rosenzweig <[email protected]>
1 parent d7a35af commit 95b018c

8 files changed

Lines changed: 401 additions & 3 deletions

File tree

‎.github/workflows/_ci-rust.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,9 @@ jobs:
151151
# Serial: windows_resolver_tests mutate process-global env
152152
# (BUZZ_SHELL/GIT_BASH/SystemRoot) that SharedState::new reads.
153153
run: cargo test -p buzz-dev-mcp --target $env:TARGET -- --test-threads=1
154+
- name: Test (ACP launch-prefix platform contract)
155+
# Execute the non-Unix refusal branch; a cross-compile cannot test it.
156+
run: cargo test -p buzz-acp --target $env:TARGET --lib acp::launch::platform_tests
154157
- name: Test (buzz-agent auth coordinator)
155158
# The auth coordinator single-flights on an OS advisory lock, which is
156159
# LockFileEx on Windows; this integration suite drives real second

‎crates/buzz-acp/README.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,34 @@ buzz-acp --respond-to anyone
197197
buzz-acp --respond-to nobody --heartbeat-interval 300
198198
```
199199

200+
### Host-controlled launch wrapper
201+
202+
On Unix, a trusted host can set `BUZZ_ACP_LAUNCH_PREFIX` to a JSON argument array, for
203+
example `["/absolute/launcher", "--policy", "/absolute/policy.json", "--"]`.
204+
Keep `BUZZ_ACP_AGENT_COMMAND` set to the real worker (such as Goose). The harness
205+
launches `prefix... worker normalized-args...` without a shell, preserving worker
206+
identity for argument defaults, environment setup, managed skills and ACP handling.
207+
208+
Configured prefixes are rejected on non-Unix platforms, including Windows, because
209+
per-worker process-tree cleanup is not available there. Unset direct launches
210+
remain available on every platform.
211+
212+
Hosts must reserve this key against user-supplied environment settings and apply
213+
the trusted prefix after merging user environment. Desktop's shared reserved-key
214+
filter covers saved persona/agent settings and local/remote launch environments.
215+
216+
The first prefix element must be an absolute executable path. Unset means direct
217+
launch; empty, malformed or unusable prefixes fail launch with no direct fallback.
218+
The shared spawn path applies the prefix to every worker creation, including pool
219+
startup, wake, crash replacement, local tasks, model discovery and authentication.
220+
The variable is removed from the child's environment to avoid recursive wrapping.
221+
222+
The wrapper must preserve ACP stdin/stdout and either exec the worker or supervise
223+
it within the inherited process group. This hook does not enforce a sandbox or
224+
verify executable contents. The host owns policy, immutable launcher staging and
225+
its lifetime across delayed launches/restarts. Hosts requiring this hook must pin
226+
a supporting runtime; older binaries do not understand the environment setting.
227+
200228
### Configuration Examples
201229

202230
**Single agent, no heartbeat (default):**

‎crates/buzz-acp/src/acp.rs‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
//! 4. [`AcpClient::session_prompt_with_idle_timeout`] — send prompt with idle/hard deadline, return stop reason
99
//! 5. [`AcpClient::session_cancel`] / [`AcpClient::cancel_with_cleanup`] — cancel in-flight turn
1010
11+
mod launch;
12+
1113
use futures_util::StreamExt;
1214
use tokio::io::AsyncWriteExt;
1315
use tokio::process::{Child, ChildStdin, ChildStdout};
@@ -474,8 +476,7 @@ impl AcpClient {
474476
) -> Result<Self, AcpError> {
475477
use std::process::Stdio;
476478

477-
let mut cmd = tokio::process::Command::new(command);
478-
cmd.args(args);
479+
let mut cmd = launch::command(command, args)?;
479480
if crate::config::normalize_agent_command_identity(command) == BUZZ_PI_ACP_NAME {
480481
if !args.iter().any(|arg| arg == "--") {
481482
cmd.arg("--");
@@ -585,7 +586,13 @@ impl AcpClient {
585586
_ => None,
586587
};
587588
cmd.envs(launch_env.iter().cloned());
588-
let mut child = cmd.spawn()?;
589+
cmd.env_remove(launch::PREFIX_ENV);
590+
let mut child = cmd.spawn().map_err(|error| {
591+
std::io::Error::new(
592+
error.kind(),
593+
format!("failed to spawn {:?}: {error}", cmd.as_std().get_program()),
594+
)
595+
})?;
589596

590597
let stdin = child
591598
.stdin

‎crates/buzz-acp/src/acp/launch.rs‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
//! Host-controlled wrapping at the shared ACP subprocess boundary.
2+
use super::AcpError;
3+
use tokio::process::Command;
4+
5+
pub(super) const PREFIX_ENV: &str = "BUZZ_ACP_LAUNCH_PREFIX";
6+
7+
pub(super) fn command(worker: &str, args: &[String]) -> Result<Command, AcpError> {
8+
command_with_prefix(worker, args, std::env::var_os(PREFIX_ENV))
9+
}
10+
11+
fn command_with_prefix(
12+
worker: &str,
13+
args: &[String],
14+
prefix: Option<std::ffi::OsString>,
15+
) -> Result<Command, AcpError> {
16+
// Non-Unix cleanup only owns the immediate child, not a supervised worker.
17+
if prefix.is_some() && !cfg!(unix) {
18+
return Err(AcpError::Protocol(format!(
19+
"{PREFIX_ENV} is supported only on Unix; refusing to launch an uncontained worker"
20+
)));
21+
}
22+
let mut command = match prefix {
23+
None => Command::new(worker),
24+
Some(value) => {
25+
let invalid = || {
26+
AcpError::Protocol(format!(
27+
"{PREFIX_ENV} must be a nonempty JSON string array with an absolute executable path"
28+
))
29+
};
30+
let prefix: Vec<String> =
31+
serde_json::from_str(&value.into_string().map_err(|_| invalid())?)
32+
.map_err(|_| invalid())?;
33+
let executable = prefix
34+
.first()
35+
.filter(|path| std::path::Path::new(path).is_absolute())
36+
.ok_or_else(invalid)?;
37+
if prefix.iter().any(|arg| arg.contains('\0')) {
38+
return Err(invalid());
39+
}
40+
let mut command = Command::new(executable);
41+
command.args(&prefix[1..]).arg(worker);
42+
command
43+
}
44+
};
45+
command.args(args);
46+
Ok(command)
47+
}
48+
49+
#[cfg(all(test, unix))]
50+
mod tests;
51+
52+
#[cfg(test)]
53+
mod platform_tests {
54+
use super::*;
55+
56+
#[test]
57+
fn unset_prefix_keeps_direct_launch_on_every_platform() {
58+
let command = command_with_prefix("worker", &["arg".into()], None).unwrap();
59+
assert_eq!(command.as_std().get_program(), "worker");
60+
assert_eq!(command.as_std().get_args().collect::<Vec<_>>(), ["arg"]);
61+
}
62+
63+
#[test]
64+
fn configured_prefix_requires_unix_process_containment() {
65+
// A real absolute executable prevents a bad path from hiding the guard.
66+
let executable = std::env::current_exe().unwrap();
67+
let prefix = serde_json::to_string(&[&executable]).unwrap();
68+
let result = command_with_prefix("worker", &[], Some(prefix.into()));
69+
if cfg!(unix) {
70+
assert_eq!(
71+
result.unwrap().as_std().get_program(),
72+
executable.as_os_str()
73+
);
74+
} else {
75+
assert!(result
76+
.unwrap_err()
77+
.to_string()
78+
.contains("supported only on Unix"));
79+
// Even an empty setting must refuse rather than downgrade to direct launch.
80+
assert!(command_with_prefix("worker", &[], Some("".into())).is_err());
81+
}
82+
}
83+
}
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
//! Subprocess isolation keeps the harness environment immutable in parallel tests.
2+
use super::PREFIX_ENV;
3+
use crate::{
4+
acp::AcpClient,
5+
config::{CliArgs, Config},
6+
usage::StandardAdapterKind,
7+
};
8+
use clap::Parser;
9+
use serde_json::{json, Value};
10+
use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf, process::Command};
11+
12+
const CHILD: &str = "BUZZ_LAUNCH_TEST_CHILD";
13+
const LITERAL: &str = "policy with spaces, ; $(not-a-shell)";
14+
15+
struct Fixture(PathBuf);
16+
impl Fixture {
17+
fn new() -> Self {
18+
let dir = std::env::temp_dir().join(format!("buzz launch {}", uuid::Uuid::new_v4()));
19+
fs::create_dir(&dir).unwrap();
20+
let wrapper = dir.join("wrapper.py");
21+
fs::write(
22+
&wrapper,
23+
r#"import json, os, sys
24+
with open('wrapper.jsonl', 'a') as log:
25+
log.write(json.dumps(sys.argv[1:]) + '\n')
26+
os.execv(sys.argv[2], sys.argv[2:])
27+
"#,
28+
)
29+
.unwrap();
30+
for name in [
31+
"goose",
32+
"codex-acp",
33+
"claude-agent-acp",
34+
"hermes-acp",
35+
"buzz-pi-acp",
36+
] {
37+
let path = dir.join(name);
38+
fs::write(
39+
&path,
40+
r#"#!/usr/bin/env python3
41+
import json, os, sys
42+
with open('worker-started', 'a') as log:
43+
log.write('started\n')
44+
for line in sys.stdin:
45+
request = json.loads(line)
46+
result = {'protocolVersion': 1, 'argv': sys.argv[1:],
47+
'hermes': os.environ.get('HERMES_ACP_SKIP_CONFIGURED_MCP'),
48+
'codex': os.environ.get('CODEX_CONFIG'),
49+
'prefix': os.environ.get('BUZZ_ACP_LAUNCH_PREFIX')}
50+
print(json.dumps({'jsonrpc': '2.0', 'id': request['id'], 'result': result}), flush=True)
51+
"#,
52+
)
53+
.unwrap();
54+
fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap();
55+
}
56+
Self(dir)
57+
}
58+
fn prefix(&self) -> String {
59+
json!([
60+
"/usr/bin/env",
61+
"python3",
62+
self.0.join("wrapper.py"),
63+
LITERAL
64+
])
65+
.to_string()
66+
}
67+
fn run(&self, mode: &str, prefix: Option<&str>) {
68+
let mut cmd = Command::new(std::env::current_exe().unwrap());
69+
for (name, _) in std::env::vars_os() {
70+
if name.to_string_lossy().starts_with("BUZZ_") {
71+
cmd.env_remove(name);
72+
}
73+
}
74+
cmd.args(["--exact", "acp::launch::tests::spawn_child", "--nocapture"])
75+
.env(CHILD, mode)
76+
.env_remove("CODEX_CONFIG")
77+
.env_remove("HERMES_ACP_SKIP_CONFIGURED_MCP")
78+
.current_dir(&self.0);
79+
if let Some(prefix) = prefix {
80+
cmd.env(PREFIX_ENV, prefix);
81+
}
82+
let output = cmd.output().unwrap();
83+
assert!(
84+
output.status.success(),
85+
"{}\n{}",
86+
String::from_utf8_lossy(&output.stdout),
87+
String::from_utf8_lossy(&output.stderr)
88+
);
89+
}
90+
}
91+
impl Drop for Fixture {
92+
fn drop(&mut self) {
93+
let _ = fs::remove_dir_all(&self.0);
94+
}
95+
}
96+
97+
#[test]
98+
fn wrapper_preserves_worker_identity_and_runs_on_each_spawn() {
99+
for wrapped in [false, true] {
100+
let f = Fixture::new();
101+
let prefix = f.prefix();
102+
f.run("success", wrapped.then_some(prefix.as_str()));
103+
assert_eq!(
104+
fs::read_to_string(f.0.join("worker-started"))
105+
.unwrap()
106+
.lines()
107+
.count(),
108+
10
109+
);
110+
if wrapped {
111+
let calls: Vec<Value> = fs::read_to_string(f.0.join("wrapper.jsonl"))
112+
.unwrap()
113+
.lines()
114+
.map(|line| serde_json::from_str(line).unwrap())
115+
.collect();
116+
assert_eq!(calls.len(), 10);
117+
for call in calls {
118+
assert_eq!(call[0], LITERAL);
119+
}
120+
} else {
121+
assert!(!f.0.join("wrapper.jsonl").exists());
122+
}
123+
}
124+
}
125+
126+
#[test]
127+
fn invalid_or_unavailable_wrapper_never_falls_back_to_worker() {
128+
let f = Fixture::new();
129+
for prefix in [
130+
"",
131+
"[]",
132+
"null",
133+
"{}",
134+
"[1]",
135+
"[\"\"]",
136+
"[\"relative\"]",
137+
"[\"/tmp/\\u0000\"]",
138+
"[\"/missing-buzz-launcher\"]",
139+
] {
140+
f.run("failure", Some(prefix));
141+
assert!(!f.0.join("worker-started").exists());
142+
}
143+
}
144+
145+
#[tokio::test]
146+
async fn spawn_child() {
147+
let Ok(mode) = std::env::var(CHILD) else {
148+
return;
149+
};
150+
// Bound a broken wrapper/stdio regression; no arbitrary timing gates.
151+
tokio::time::timeout(std::time::Duration::from_secs(10), async {
152+
for name in [
153+
"goose",
154+
"codex-acp",
155+
"claude-agent-acp",
156+
"hermes-acp",
157+
"buzz-pi-acp",
158+
] {
159+
let worker = std::env::current_dir().unwrap().join(name);
160+
let args = CliArgs::try_parse_from([
161+
"buzz-acp",
162+
"--private-key",
163+
"0000000000000000000000000000000000000000000000000000000000000001",
164+
"--agent-command",
165+
worker.to_str().unwrap(),
166+
"--agent-args",
167+
"",
168+
])
169+
.unwrap();
170+
let config = Config::from_args(args).unwrap();
171+
// A second spawn uses the same host configuration after shutdown,
172+
// just as a replacement worker does. No prefix is consumed once.
173+
for _ in 0..2 {
174+
let spawned = AcpClient::spawn(
175+
&config.agent_command,
176+
&config.agent_args,
177+
&config.persona_env_vars,
178+
config.has_generated_codex_config,
179+
)
180+
.await;
181+
if mode == "failure" {
182+
let error = spawned.err().expect("invalid wrapper launched a worker");
183+
if std::env::var(PREFIX_ENV)
184+
.unwrap()
185+
.contains("/missing-buzz-launcher")
186+
{
187+
assert!(error.to_string().contains("/missing-buzz-launcher"));
188+
}
189+
return;
190+
}
191+
let mut client = spawned.unwrap();
192+
let probe = client.initialize().await.unwrap();
193+
let expected = match name {
194+
"goose" => json!(["acp"]),
195+
"hermes-acp" => json!([]),
196+
"buzz-pi-acp" => json!([
197+
"--",
198+
"--skill",
199+
std::env::current_dir().unwrap().join(".agents/skills")
200+
]),
201+
_ => json!([]),
202+
};
203+
assert_eq!(probe["argv"], expected, "{name}");
204+
assert!(probe["prefix"].is_null());
205+
if name == "hermes-acp" {
206+
assert_eq!(probe["hermes"], "1");
207+
}
208+
let adapter = match name {
209+
"codex-acp" => {
210+
let config: Value =
211+
serde_json::from_str(probe["codex"].as_str().unwrap()).unwrap();
212+
assert_eq!(config["sandbox_workspace_write"]["network_access"], true);
213+
Some(StandardAdapterKind::Codex)
214+
}
215+
"claude-agent-acp" => Some(StandardAdapterKind::Claude),
216+
_ => None,
217+
};
218+
assert_eq!(client.standard_adapter, adapter);
219+
client.shutdown().await;
220+
}
221+
}
222+
})
223+
.await
224+
.expect("wrapped ACP handshake exceeded test deadline");
225+
}

0 commit comments

Comments
 (0)