diff --git a/crates/buzz-acp/src/config.rs b/crates/buzz-acp/src/config.rs index 80d527673fd..202bbcbda06 100644 --- a/crates/buzz-acp/src/config.rs +++ b/crates/buzz-acp/src/config.rs @@ -49,6 +49,9 @@ pub enum ConfigError { #[error("config file error: {0}")] ConfigFile(String), + + #[error("key broker: {0}")] + KeyBroker(String), } #[derive(Debug, Clone, PartialEq, clap::ValueEnum)] @@ -251,9 +254,26 @@ pub struct CliArgs { #[arg(long, env = "BUZZ_RELAY_URL", default_value = "ws://localhost:3000")] pub relay_url: String, - #[arg(long, env = "BUZZ_PRIVATE_KEY", hide_env_values = true)] + /// Required unless --key-broker-account is set. + #[arg( + long, + env = "BUZZ_PRIVATE_KEY", + hide_env_values = true, + default_value = "", + hide_default_value = true + )] pub private_key: String, + /// Read the signing key from the local key broker instead of the + /// environment, and give children only this account name. + #[arg( + long, + env = "BUZZ_KEY_BROKER_ACCOUNT", + hide_env_values = true, + conflicts_with = "private_key" + )] + pub key_broker_account: Option, + /// Agent owner pubkey (64-char hex). Used for --respond-to=owner-only gate. #[arg(long, env = "BUZZ_ACP_AGENT_OWNER")] pub agent_owner: Option, @@ -461,6 +481,13 @@ pub struct CliArgs { #[arg(long, env = "BUZZ_ACP_SESSION_TITLE")] pub session_title: Option, + /// Register Claude Agent SDK sessions with Claude Remote Control so they + /// are discoverable in the owner's Claude app. Claude-only and opt-in: + /// other ACP adapters ignore it, and the default preserves local-only + /// session behavior. + #[arg(long, env = "BUZZ_ACP_CLAUDE_REMOTE_CONTROL", default_value_t = false)] + pub claude_remote_control: bool, + /// Permission mode for agents that support `session/set_config_option` /// with `configId: "mode"` (e.g. `claude-agent-acp`). /// @@ -546,6 +573,7 @@ pub struct ChannelFilter { #[derive(Debug)] pub struct Config { pub keys: Keys, + pub key_broker_account: Option, pub relay_url: String, pub agent_command: String, pub agent_args: Vec, @@ -594,6 +622,8 @@ pub struct Config { /// Sanitized session title, sent as `_meta.sessionTitle` on `session/new`. /// `None` when unset or when the configured value sanitized to empty. pub session_title: Option, + /// Whether Claude sessions should start the Remote Control bridge. + pub claude_remote_control: bool, /// Permission mode to apply after session creation. `Default` = skip. pub permission_mode: PermissionMode, /// Inbound author gate mode. @@ -963,7 +993,10 @@ impl Config { /// tests can construct `CliArgs` via `CliArgs::try_parse_from` and exercise the full /// validation path without going through process args. pub fn from_args(mut args: CliArgs) -> Result { - let keys = Keys::parse(&args.private_key)?; + let keys = match &args.key_broker_account { + Some(account) => Keys::parse(crate::key_broker::fetch(account)?.as_str())?, + None => Keys::parse(&args.private_key)?, + }; // Best-effort zeroize: overwrite the raw private key string to reduce // exposure via core dumps or heap inspection (#41). Without the `zeroize` // crate we can only clear the String — the allocator may retain copies. @@ -1185,6 +1218,7 @@ impl Config { let config = Config { keys, + key_broker_account: args.key_broker_account, relay_url: args.relay_url, agent_command, agent_args, @@ -1223,6 +1257,7 @@ impl Config { .session_title .as_deref() .and_then(sanitize_session_title), + claude_remote_control: args.claude_remote_control, permission_mode: args.permission_mode, respond_to: args.respond_to, respond_to_allowlist, @@ -1567,10 +1602,38 @@ mod tests { use crate::filter::{ChannelScope, SubscriptionRule}; use clap::{Parser, ValueEnum}; + #[test] + fn broker_account_replaces_the_private_key_argument() { + let args = CliArgs::parse_from([ + "buzz-acp", + "--key-broker-account", + "claude-agent-private-key", + ]); + assert_eq!( + args.key_broker_account.as_deref(), + Some("claude-agent-private-key") + ); + assert!(args.private_key.is_empty()); + } + + #[test] + fn broker_account_and_private_key_cannot_both_be_set() { + let key = "0".repeat(64); + let parsed = CliArgs::try_parse_from([ + "buzz-acp", + "--private-key", + &key, + "--key-broker-account", + "claude-agent-private-key", + ]); + assert!(parsed.is_err()); + } + /// Build a minimal Config for testing without CLI parsing. fn test_config(mode: SubscribeMode) -> Config { Config { keys: nostr::Keys::generate(), + key_broker_account: None, relay_url: "ws://localhost:3000".into(), agent_command: "goose".into(), agent_args: vec!["acp".into()], @@ -1601,6 +1664,7 @@ mod tests { model: None, effort_level: None, session_title: None, + claude_remote_control: false, permission_mode: PermissionMode::BypassPermissions, respond_to: RespondTo::Anyone, respond_to_allowlist: HashSet::new(), @@ -3245,4 +3309,32 @@ channels = "ALL" Add `hide_env_values = true` to each: {violations:?}" ); } + + #[test] + fn help_exposes_explicit_claude_remote_control_opt_in() { + use clap::CommandFactory; + + let help = CliArgs::command().render_long_help().to_string(); + assert!( + help.contains("--claude-remote-control"), + "operators need an explicit opt-in before Claude ACP sessions register for Remote Control" + ); + } + + #[test] + fn claude_remote_control_is_opt_in_and_reaches_config() { + let defaults = CliArgs::try_parse_from(["buzz-acp", "--private-key", TEST_PRIVATE_KEY]) + .expect("parse defaults"); + assert!(!defaults.claude_remote_control); + + let enabled = CliArgs::try_parse_from([ + "buzz-acp", + "--private-key", + TEST_PRIVATE_KEY, + "--claude-remote-control", + ]) + .expect("parse opt-in"); + let config = Config::from_args(enabled).expect("build config"); + assert!(config.claude_remote_control); + } } diff --git a/crates/buzz-acp/src/git.rs b/crates/buzz-acp/src/git.rs index e438e41cc13..a66b97843c6 100644 --- a/crates/buzz-acp/src/git.rs +++ b/crates/buzz-acp/src/git.rs @@ -12,8 +12,22 @@ pub(crate) struct GitEnvironment { impl GitEnvironment { pub(crate) fn for_config(config: &mut crate::config::Config) -> anyhow::Result { - let environment = - Self::install(&config.keys, &config.relay_url, &std::env::current_exe()?)?; + let broker_mode = config.key_broker_account.is_some(); + let mut environment = Self::install_with( + &config.keys, + &config.relay_url, + &std::env::current_exe()?, + !broker_mode, + )?; + // Broker mode keeps the key out of every child's environment. + if let Some(account) = &config.key_broker_account { + environment + .env + .retain(|(name, _)| name != "BUZZ_PRIVATE_KEY"); + environment + .env + .push((crate::key_broker::ACCOUNT_ENV.into(), account.clone())); + } config .persona_env_vars .retain(|(name, _)| !is_managed_env(name)); @@ -23,10 +37,23 @@ impl GitEnvironment { Ok(environment) } + /// Test seam: production goes through `for_config`, which decides `persist_key`. + #[cfg(test)] pub(crate) fn install( keys: &nostr::Keys, relay_url: &str, executable: &Path, + ) -> anyhow::Result { + Self::install_with(keys, relay_url, executable, true) + } + + /// With `persist_key` false, no key file exists and no config names one: + /// the Git helpers read the key from the broker when Git runs them. + fn install_with( + keys: &nostr::Keys, + relay_url: &str, + executable: &Path, + persist_key: bool, ) -> anyhow::Result { let agent = GitIdentityMode::from_value(std::env::var_os(GIT_IDENTITY_ENV).as_deref())? == GitIdentityMode::Agent; @@ -37,8 +64,10 @@ impl GitEnvironment { symlink(executable, &dir.path().join("git-sign-nostr"))?; } let keyfile = dir.path().join(".nostr-key"); - let secret = Zeroizing::new(keys.secret_key().to_secret_hex()); - write_keyfile_atomic(&keyfile, secret.as_bytes())?; + if persist_key { + let secret = Zeroizing::new(keys.secret_key().to_secret_hex()); + write_keyfile_atomic(&keyfile, secret.as_bytes())?; + } let info = KeyInfo { keyfile_path: keyfile .to_str() @@ -61,12 +90,15 @@ impl GitEnvironment { let relay = relay.as_str().trim_end_matches('/'); // `user` mode keeps only relay auth; its commits carry the operator's // own identity, so no attribution or signing is installed. - let managed = if agent { + let mut managed = if agent { let display_name = std::env::var("BUZZ_ACP_DISPLAY_NAME").ok(); identity_entries(&info, relay, display_name.as_deref()) } else { vec![("nostr.keyfile".into(), info.keyfile_path.clone())] }; + if !persist_key { + managed.retain(|(key, _)| !same_config_key(key, "nostr.keyfile")); + } // In `user` mode nothing later overrides inherited identity or signing, // so drop agent mode's own managed keys, the author/committer // overrides and includes. @@ -83,6 +115,9 @@ impl GitEnvironment { .any(|(managed, _)| same_config_key(managed, key)) }); } + if !persist_key { + inherited.retain(|(key, _)| !same_config_key(key, "nostr.keyfile")); + } let mut env = build_git_env(relay, &managed, inherited); let mut paths = vec![dir.path().to_path_buf()]; paths.extend(std::env::split_paths( @@ -96,7 +131,10 @@ impl GitEnvironment { )); env.push(("GIT_TERMINAL_PROMPT".into(), "0".into())); // CLI flags must work even when the caller did not export these variables. - env.push(("BUZZ_PRIVATE_KEY".into(), secret.to_string())); + if persist_key { + let secret = Zeroizing::new(keys.secret_key().to_secret_hex()); + env.push(("BUZZ_PRIVATE_KEY".into(), secret.to_string())); + } env.push(("BUZZ_RELAY_URL".into(), relay_url.to_owned())); // MCP children start from a cleared env; forward the resolved mode so a // nested harness keeps it instead of defaulting to `agent`. @@ -387,6 +425,7 @@ pub(crate) fn is_managed_env(name: &str) -> bool { "PATH" | "GIT_TERMINAL_PROMPT" | "BUZZ_PRIVATE_KEY" + | crate::key_broker::ACCOUNT_ENV | "BUZZ_RELAY_URL" | GIT_IDENTITY_ENV ) diff --git a/crates/buzz-acp/src/key_broker.rs b/crates/buzz-acp/src/key_broker.rs new file mode 100644 index 00000000000..cc3705b93fc --- /dev/null +++ b/crates/buzz-acp/src/key_broker.rs @@ -0,0 +1,162 @@ +//! Fetch the agent's signing key from the local key broker. +//! +//! A process's launch environment can be read by any process under the same +//! OS user, and children inherit it. With `BUZZ_KEY_BROKER_ACCOUNT` set, the +//! key never enters this process's environment: it is read once from the +//! broker's owner-only UNIX socket into memory, and children get only the +//! account name. +//! +//! Protocol: send `GET \n`, receive `OK \n` or `ERR \n`. + +#[cfg(unix)] +use std::io::{BufRead, BufReader, Write}; +#[cfg(unix)] +use std::os::unix::net::UnixStream; +use std::path::{Path, PathBuf}; +use std::thread::sleep; +use std::time::Duration; + +use base64::Engine; +use zeroize::Zeroizing; + +use crate::config::ConfigError; + +pub(crate) const ACCOUNT_ENV: &str = "BUZZ_KEY_BROKER_ACCOUNT"; +const SOCKET_ENV: &str = "BUZZ_KEY_BROKER_SOCKET"; +#[cfg(unix)] +const IO_TIMEOUT: Duration = Duration::from_secs(10); +const ATTEMPTS: u32 = 5; +const RETRY_DELAY: Duration = Duration::from_secs(2); + +fn socket_path() -> Result { + if let Some(path) = std::env::var_os(SOCKET_ENV) { + return Ok(PathBuf::from(path)); + } + let home = + std::env::var_os("HOME").ok_or_else(|| ConfigError::KeyBroker("HOME is not set".into()))?; + Ok(Path::new(&home).join(".buzz/broker.sock")) +} + +#[cfg(unix)] +fn request(socket: &Path, account: &str) -> std::io::Result> { + let mut stream = UnixStream::connect(socket)?; + stream.set_read_timeout(Some(IO_TIMEOUT))?; + stream.set_write_timeout(Some(IO_TIMEOUT))?; + writeln!(stream, "GET {account}")?; + let mut line = Zeroizing::new(String::new()); + BufReader::new(stream).read_line(&mut line)?; + Ok(line) +} + +/// The broker is an owner-only UNIX socket; other platforms have no broker mode. +#[cfg(not(unix))] +fn request(_socket: &Path, _account: &str) -> std::io::Result> { + Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "the key broker needs a UNIX socket", + )) +} + +/// Read one account's key. The broker can start after this process at boot, +/// so a socket failure is retried briefly. A refusal from the broker is final. +pub(crate) fn fetch(account: &str) -> Result, ConfigError> { + let socket = socket_path()?; + let mut last_error = None; + for attempt in 0..ATTEMPTS { + if attempt > 0 { + sleep(RETRY_DELAY); + } + match request(&socket, account) { + Ok(line) => return parse_reply(&line), + Err(error) => last_error = Some(error), + } + } + Err(ConfigError::KeyBroker(format!( + "could not reach {}: {}", + socket.display(), + last_error.map_or_else(|| "no attempt ran".to_string(), |e| e.to_string()) + ))) +} + +/// Git runs the credential and signing helpers as short-lived children of the +/// agent. In broker mode they get the key here, for their own process only. +/// A failure is reported, and the helper then fails with its own missing-key error. +pub(crate) fn prime_git_helper() { + let Ok(account) = std::env::var(ACCOUNT_ENV) else { + return; + }; + match fetch(&account) { + // Called from the helper entry point, before any thread starts. + Ok(key) => std::env::set_var("NOSTR_PRIVATE_KEY", key.as_str()), + Err(error) => eprintln!("buzz-acp git helper: {error}"), + } +} + +fn parse_reply(line: &str) -> Result, ConfigError> { + let line = line.trim(); + let Some(encoded) = line.strip_prefix("OK ") else { + // Only a broker's own short reason is ever echoed, never a key reply. + let reason = line.strip_prefix("ERR ").unwrap_or("malformed reply"); + return Err(ConfigError::KeyBroker(format!("broker refused: {reason}"))); + }; + let bytes = Zeroizing::new( + base64::engine::general_purpose::STANDARD + .decode(encoded) + .map_err(|_| ConfigError::KeyBroker("broker reply is not base64".into()))?, + ); + let key = std::str::from_utf8(&bytes) + .map_err(|_| ConfigError::KeyBroker("broker reply is not UTF-8".into()))?; + Ok(Zeroizing::new(key.to_owned())) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::os::unix::net::UnixListener; + + fn serve_once( + reply: &'static str, + ) -> (tempfile::TempDir, PathBuf, std::thread::JoinHandle) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("broker.sock"); + let listener = UnixListener::bind(&path).unwrap(); + let handle = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut line = String::new(); + BufReader::new(stream.try_clone().unwrap()) + .read_line(&mut line) + .unwrap(); + stream.write_all(reply.as_bytes()).unwrap(); + line + }); + (dir, path, handle) + } + + #[test] + fn asks_for_the_account_and_decodes_the_value() { + let (_dir, path, handle) = serve_once("OK dGVzdC12YWx1ZQ==\n"); + let line = request(&path, "claude-agent-private-key").unwrap(); + assert_eq!(parse_reply(&line).unwrap().as_str(), "test-value"); + assert_eq!(handle.join().unwrap(), "GET claude-agent-private-key\n"); + } + + #[test] + fn a_refusal_names_the_reason() { + let error = parse_reply("ERR not allowlisted\n") + .unwrap_err() + .to_string(); + assert!(error.contains("not allowlisted"), "{error}"); + } + + #[test] + fn a_malformed_reply_never_echoes_its_content() { + let error = parse_reply("not-a-reply-with-secret-looking-text\n") + .unwrap_err() + .to_string(); + assert!(!error.contains("secret-looking"), "{error}"); + let error = parse_reply("OK !!!not-base64!!!\n") + .unwrap_err() + .to_string(); + assert!(!error.contains("not-base64!!!"), "{error}"); + } +} diff --git a/crates/buzz-acp/src/lib.rs b/crates/buzz-acp/src/lib.rs index c969f8f17b8..4438a788441 100644 --- a/crates/buzz-acp/src/lib.rs +++ b/crates/buzz-acp/src/lib.rs @@ -10,6 +10,7 @@ mod edit_routing; mod engram_fetch; mod filter; mod isolated_execution; +mod key_broker; mod observer; mod pool; mod pool_lifecycle; @@ -2760,8 +2761,14 @@ pub fn run() -> Result<()> { .file_stem() .and_then(|name| name.to_str()) { - Some("git-credential-nostr") => std::process::exit(git_credential_nostr::run()), - Some("git-sign-nostr") => std::process::exit(git_sign_nostr::run()), + Some("git-credential-nostr") => { + key_broker::prime_git_helper(); + std::process::exit(git_credential_nostr::run()) + } + Some("git-sign-nostr") => { + key_broker::prime_git_helper(); + std::process::exit(git_sign_nostr::run()) + } _ => {} } config::propagate_legacy_env_vars(); @@ -6511,16 +6518,23 @@ fn build_mcp_servers(config: &Config) -> Vec { name: "BUZZ_RELAY_URL".into(), value: config.relay_url.clone(), }, - EnvVar { - name: "BUZZ_PRIVATE_KEY".into(), - // bech32 encoding of a valid secret key is infallible. - // Panic here is correct: injecting a bogus secret would cause - // delayed, hard-to-diagnose agent failures downstream. - value: config - .keys - .secret_key() - .to_bech32() - .expect("secret key bech32 encoding should never fail"), + match &config.key_broker_account { + // Broker mode: the MCP child resolves its own key at use time. + Some(account) => EnvVar { + name: key_broker::ACCOUNT_ENV.into(), + value: account.clone(), + }, + None => EnvVar { + name: "BUZZ_PRIVATE_KEY".into(), + // bech32 encoding of a valid secret key is infallible. + // Panic here is correct: injecting a bogus secret would cause + // delayed, hard-to-diagnose agent failures downstream. + value: config + .keys + .secret_key() + .to_bech32() + .expect("secret key bech32 encoding should never fail"), + }, }, ]; // Forward BUZZ_AUTH_TAG (NIP-OA owner attestation credential) @@ -9516,6 +9530,17 @@ mod observer_chunk_coalescer_tests { #[cfg(test)] mod build_mcp_servers_tests { + #[test] + fn broker_mode_gives_the_mcp_child_an_account_and_no_key() { + let mut config = test_config(); + config.mcp_command = "/usr/local/bin/test-mcp".into(); + config.key_broker_account = Some("claude-agent-private-key".into()); + let servers = super::build_mcp_servers(&config); + let names: Vec<&str> = servers[0].env.iter().map(|e| e.name.as_str()).collect(); + assert!(!names.contains(&"BUZZ_PRIVATE_KEY"), "{names:?}"); + assert!(names.contains(&crate::key_broker::ACCOUNT_ENV), "{names:?}"); + } + use super::*; use std::sync::Mutex; @@ -9525,6 +9550,7 @@ mod build_mcp_servers_tests { pub(super) fn test_config() -> Config { Config { keys: nostr::Keys::generate(), + key_broker_account: None, relay_url: "ws://localhost:3000".into(), agent_command: "goose".into(), agent_args: vec!["acp".into()], @@ -9555,6 +9581,7 @@ mod build_mcp_servers_tests { model: None, effort_level: None, session_title: None, + claude_remote_control: false, permission_mode: config::PermissionMode::BypassPermissions, respond_to: config::RespondTo::Anyone, respond_to_allowlist: std::collections::HashSet::new(), @@ -9710,6 +9737,21 @@ mod build_mcp_servers_tests { assert_eq!(value_of("BUZZ_GIT_IDENTITY").as_deref(), Some("user")); } + #[test] + fn broker_mode_keeps_the_key_out_of_child_env() { + let _guard = ENV_LOCK.lock().unwrap(); + let mut config = test_config(); + config.key_broker_account = Some("claude-agent-private-key".into()); + let _git = git::GitEnvironment::for_config(&mut config).unwrap(); + let names: Vec<&str> = config + .persona_env_vars + .iter() + .map(|(n, _)| n.as_str()) + .collect(); + assert!(!names.contains(&"BUZZ_PRIVATE_KEY"), "{names:?}"); + assert!(names.contains(&crate::key_broker::ACCOUNT_ENV), "{names:?}"); + } + #[test] fn for_config_replaces_persona_git_identity_with_resolved_mode() { let _guard = ENV_LOCK.lock().unwrap(); @@ -10659,6 +10701,7 @@ mod error_outcome_emission_tests { fn test_config() -> Config { Config { keys: nostr::Keys::generate(), + key_broker_account: None, relay_url: "ws://localhost:3000".into(), // `true` exits cleanly, so the async respawn fails fast and // harmlessly off the JoinSet — irrelevant to the synchronous @@ -10692,6 +10735,7 @@ mod error_outcome_emission_tests { model: None, effort_level: None, session_title: None, + claude_remote_control: false, permission_mode: config::PermissionMode::BypassPermissions, respond_to: config::RespondTo::Anyone, respond_to_allowlist: HashSet::new(), diff --git a/crates/buzz-acp/src/pool.rs b/crates/buzz-acp/src/pool.rs index 7a7e3229e70..6898887269d 100644 --- a/crates/buzz-acp/src/pool.rs +++ b/crates/buzz-acp/src/pool.rs @@ -901,6 +901,9 @@ pub struct PromptContext { /// Channel sessions add the channel name; thread sessions also add the root /// ID prefix. Never part of the prompt. pub session_title: Option, + /// Start Claude sessions with Remote Control registration. This remains + /// opt-in because it exposes session presence to the owner's Claude app. + pub claude_remote_control: bool, pub team_instructions: Option, pub heartbeat_prompt: Option, /// Base instructions with the configured policy's Session Model appended, @@ -1622,6 +1625,9 @@ async fn create_session_and_apply_model( channel.channel_type, ctx.session_title.as_deref(), ); + let claude_remote_control_name = ctx + .claude_remote_control + .then(|| session_title.as_deref().unwrap_or("Buzz agent")); let resp = agent .acp @@ -1638,6 +1644,34 @@ async fn create_session_and_apply_model( ) .await?; + if let Some(name) = claude_remote_control_name { + let command = format!("/remote-control {name}"); + match agent + .acp + .session_prompt_with_idle_timeout( + &resp.session_id, + &command, + std::time::Duration::from_secs(15), + std::time::Duration::from_secs(30), + ) + .await + { + Ok(_) => tracing::info!( + target: "pool::session", + session_id = %resp.session_id, + name, + "Claude Remote Control registered through the adapter" + ), + Err(error) => tracing::warn!( + target: "pool::session", + session_id = %resp.session_id, + name, + %error, + "Claude Remote Control registration failed; continuing with the local session" + ), + } + } + if is_goose && agent.goose_system_prompt_supported != Some(false) { if let Some(prompt) = combined_system_prompt.as_deref() { match agent @@ -10456,6 +10490,7 @@ printf '%s\n' '{{"jsonrpc":"2.0","id":0,"result":{{"stopReason":"end_turn"}}}}'" dedup_mode: DedupMode::Drop, system_prompt: None, session_title: None, + claude_remote_control: false, team_instructions: None, heartbeat_prompt: None, base_prompt: None, @@ -11746,6 +11781,82 @@ exit 0"# } } +#[cfg(test)] +mod claude_remote_control_tests { + use super::*; + use crate::acp::AcpClient; + use tests::make_prompt_context_no_owner; + + #[tokio::test] + async fn opt_in_starts_remote_control_through_the_adapter_command() { + let dir = + std::env::temp_dir().join(format!("buzz-claude-remote-control-{}", Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let capture = dir.join("remote-control-request.json"); + let script = format!( + r#"IFS= read -r _session_new +printf '%s\n' '{{"jsonrpc":"2.0","id":0,"result":{{"sessionId":"claude-session"}}}}' +if IFS= read -r remote_control; then + printf '%s\n' "$remote_control" > '{}' + printf '%s\n' '{{"jsonrpc":"2.0","id":1,"result":{{"stopReason":"end_turn"}}}}' +else + printf '%s\n' 'MISSING' > '{}' +fi"#, + capture.display(), + capture.display(), + ); + let acp = AcpClient::spawn("bash", &["-c".to_string(), script], &[], false) + .await + .expect("spawn scripted Claude adapter"); + let mut agent = OwnedAgent { + index: 0, + acp, + state: SessionState::default(), + model_capabilities: None, + desired_model: None, + model_overridden: false, + desired_model_request_id: None, + desired_model_pending_ack: false, + startup_effort: None, + agent_name: CLAUDE_AGENT_ACP_NAME.into(), + goose_system_prompt_supported: None, + protocol_version: 1, + }; + let mut ctx = make_prompt_context_no_owner(); + ctx.session_title = Some("Buzz Claude".into()); + ctx.claude_remote_control = true; + + create_session_and_apply_model( + &mut agent, + &ctx, + None, + NewSessionChannelContext { + huddle_instructions: None, + canvas: None, + name: Some("general"), + scope: None, + channel_type: Some("public"), + }, + ) + .await + .expect("session creation must succeed"); + agent.acp.shutdown().await; + + let request: serde_json::Value = serde_json::from_str( + &std::fs::read_to_string(&capture).expect("remote-control request capture"), + ) + .expect("captured request is JSON"); + assert_eq!(request["method"], "session/prompt"); + assert_eq!(request["params"]["sessionId"], "claude-session"); + assert_eq!( + request["params"]["prompt"][0]["text"], + "/remote-control Buzz Claude · #general" + ); + + let _ = std::fs::remove_dir_all(dir); + } +} + #[cfg(test)] mod model_switch_tests { use super::*; diff --git a/crates/buzz-acp/src/runtime.rs b/crates/buzz-acp/src/runtime.rs index e6745b63313..8d87fefd7c6 100644 --- a/crates/buzz-acp/src/runtime.rs +++ b/crates/buzz-acp/src/runtime.rs @@ -91,6 +91,7 @@ fn make_prompt_context( dedup_mode: config.dedup_mode, system_prompt: config.system_prompt.clone(), session_title: config.session_title.clone(), + claude_remote_control: config.claude_remote_control, team_instructions: config.team_instructions.clone(), base_prompt: if config.no_base_prompt { None