Skip to content

Commit f085882

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7npub16v54tttfqacx9ycvc3k0ut0npj564ahcuajzy6qjvh57ntmsf4uq4806j2npub1fgdl5qqnh3k3f2xkqrvt7cujalhm623x4s7fdjdj5yrtp5fzjl9qrjpucw
authored
feat(acp): implement systemPrompt with protocol version gating (#981)
Signed-off-by: Will Pfleger <[email protected]> Signed-off-by: Will Pfleger <[email protected]> Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub16v54tttfqacx9ycvc3k0ut0npj564ahcuajzy6qjvh57ntmsf4uq4806j2 <d32955ad69077062930cc46cfe2df30ca9aaf6f8e76422681265e9e9af704d78@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub1fgdl5qqnh3k3f2xkqrvt7cujalhm623x4s7fdjdj5yrtp5fzjl9qrjpucw <4a1bfa0013bc6d14a8d600d8bf6392efefbd2a26ac3c96c9b2a106b0d12297ca@sprout-oss.stage.blox.sqprod.co>
1 parent d07c821 commit f085882

9 files changed

Lines changed: 721 additions & 100 deletions

File tree

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

Lines changed: 78 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -280,8 +280,10 @@ impl AcpClient {
280280
/// Must be called exactly once, before any other ACP method.
281281
/// The caller may inspect `agentCapabilities` in the returned value.
282282
pub async fn initialize(&mut self) -> Result<serde_json::Value, AcpError> {
283+
// Requesting version 2 is an intentional temporary pin — we are squatting
284+
// on ACP v2 ahead of the upstream ACP RFD. Revisit when that RFD merges.
283285
let params = serde_json::json!({
284-
"protocolVersion": 1,
286+
"protocolVersion": 2,
285287
"clientCapabilities": {},
286288
"clientInfo": {
287289
"name": "buzz-acp",
@@ -296,17 +298,23 @@ impl AcpClient {
296298
/// Send `session/new` and return the full response alongside the session ID.
297299
///
298300
/// `cwd` must be an absolute path. `mcp_servers` may be empty.
301+
/// `system_prompt` is included in the request when `Some` — agents that
302+
/// support the field will use it; others ignore unknown fields per JSON-RPC.
299303
/// Callers use [`extract_model_config_options`] and [`extract_model_state`]
300304
/// to pull model info from the raw result.
301305
pub async fn session_new_full(
302306
&mut self,
303307
cwd: &str,
304308
mcp_servers: Vec<McpServer>,
309+
system_prompt: Option<&str>,
305310
) -> Result<SessionNewResponse, AcpError> {
306-
let params = serde_json::json!({
311+
let mut params = serde_json::json!({
307312
"cwd": cwd,
308313
"mcpServers": mcp_servers,
309314
});
315+
if let Some(sp) = system_prompt {
316+
params["systemPrompt"] = serde_json::Value::String(sp.to_owned());
317+
}
310318
let result = self.send_request("session/new", params).await?;
311319
let session_id = result["sessionId"]
312320
.as_str()
@@ -327,8 +335,12 @@ impl AcpClient {
327335
&mut self,
328336
cwd: &str,
329337
mcp_servers: Vec<McpServer>,
338+
system_prompt: Option<&str>,
330339
) -> Result<String, AcpError> {
331-
Ok(self.session_new_full(cwd, mcp_servers).await?.session_id)
340+
Ok(self
341+
.session_new_full(cwd, mcp_servers, system_prompt)
342+
.await?
343+
.session_id)
332344
}
333345

334346
/// Send `session/set_config_option` (stable ACP path).
@@ -1401,15 +1413,15 @@ mod tests {
14011413
"id": 0u64,
14021414
"method": "initialize",
14031415
"params": {
1404-
"protocolVersion": 1,
1416+
"protocolVersion": 2,
14051417
"clientCapabilities": {},
14061418
"clientInfo": {
14071419
"name": "buzz-acp",
14081420
"version": "0.1.0"
14091421
}
14101422
}
14111423
});
1412-
assert_eq!(msg["params"]["protocolVersion"].as_u64(), Some(1));
1424+
assert_eq!(msg["params"]["protocolVersion"].as_u64(), Some(2));
14131425
assert_eq!(
14141426
msg["params"]["clientInfo"]["name"].as_str(),
14151427
Some("buzz-acp")
@@ -2031,4 +2043,65 @@ mod tests {
20312043
"expected IdleTimeout after silence, got {result:?}"
20322044
);
20332045
}
2046+
2047+
// ── session_new_full systemPrompt serialization ──────────────────────
2048+
2049+
#[tokio::test]
2050+
async fn session_new_full_includes_system_prompt_when_some() {
2051+
// Script: respond to initialize, then echo back the session/new request.
2052+
let script = r#"
2053+
read -t 2 _init
2054+
echo '{"jsonrpc":"2.0","id":0,"result":{"protocolVersion":1,"agentCapabilities":{}}}'
2055+
read -t 2 REQ
2056+
echo '{"jsonrpc":"2.0","id":1,"result":{"sessionId":"ses_test","_receivedRequest":'"$REQ"'}}'
2057+
sleep 1
2058+
"#;
2059+
let mut client = spawn_script(script).await;
2060+
client
2061+
.initialize()
2062+
.await
2063+
.expect("initialize should succeed");
2064+
2065+
let resp = client
2066+
.session_new_full("/tmp", vec![], Some("Custom system prompt"))
2067+
.await
2068+
.expect("session_new_full should succeed");
2069+
2070+
assert_eq!(resp.session_id, "ses_test");
2071+
let received = &resp.raw["_receivedRequest"];
2072+
assert_eq!(
2073+
received["params"]["systemPrompt"].as_str(),
2074+
Some("Custom system prompt"),
2075+
"systemPrompt should be included in params when Some"
2076+
);
2077+
}
2078+
2079+
#[tokio::test]
2080+
async fn session_new_full_omits_system_prompt_when_none() {
2081+
// When system_prompt is None, the field should not appear in params.
2082+
let script = r#"
2083+
read -t 2 _init
2084+
echo '{"jsonrpc":"2.0","id":0,"result":{"protocolVersion":1,"agentCapabilities":{}}}'
2085+
read -t 2 REQ
2086+
echo '{"jsonrpc":"2.0","id":1,"result":{"sessionId":"ses_test","_receivedRequest":'"$REQ"'}}'
2087+
sleep 1
2088+
"#;
2089+
let mut client = spawn_script(script).await;
2090+
client
2091+
.initialize()
2092+
.await
2093+
.expect("initialize should succeed");
2094+
2095+
let resp = client
2096+
.session_new_full("/tmp", vec![], None)
2097+
.await
2098+
.expect("session_new_full should succeed");
2099+
2100+
assert_eq!(resp.session_id, "ses_test");
2101+
let received = &resp.raw["_receivedRequest"];
2102+
assert!(
2103+
received["params"]["systemPrompt"].is_null(),
2104+
"systemPrompt should NOT be in params when value is None"
2105+
);
2106+
}
20342107
}

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

Lines changed: 49 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ use pool::{
3131
AgentPool, ControlSignal, OwnedAgent, PromptContext, PromptOutcome, PromptResult, PromptSource,
3232
SessionState,
3333
};
34-
use queue::{prepend_base_prompt, EventQueue, QueuedEvent, ThreadTags};
34+
use queue::{EventQueue, QueuedEvent, ThreadTags};
3535
use relay::{HarnessRelay, RelayEventPublisher};
3636
use tokio::sync::{mpsc, watch};
3737
use tracing_subscriber::EnvFilter;
@@ -695,7 +695,7 @@ fn any_respawn_in_flight(crash_history: &[SlotCircuit]) -> bool {
695695
/// Result of a background respawn task.
696696
struct RespawnResult {
697697
index: usize,
698-
result: Result<AcpClient>,
698+
result: Result<(AcpClient, u32)>,
699699
}
700700

701701
/// RAII guard that ensures a `RespawnResult` is sent even if the task panics.
@@ -719,7 +719,7 @@ impl RespawnGuard {
719719
/// Send the result and disarm the guard. Uses `try_send` (sync) so there
720720
/// is no await boundary between marking `sent` and actually enqueueing —
721721
/// cancellation cannot slip between the two.
722-
fn send(mut self, result: Result<AcpClient>) {
722+
fn send(mut self, result: Result<(AcpClient, u32)>) {
723723
// Invariant: try_send succeeds because the channel capacity equals the
724724
// slot count, and respawn_in_flight guarantees at most one outstanding
725725
// result per slot. If this ever fails, the channel sizing or the
@@ -839,6 +839,8 @@ async fn tokio_main() -> Result<()> {
839839
match tokio::time::timeout(Duration::from_secs(60), acp.initialize()).await {
840840
Ok(Ok(init_result)) => {
841841
tracing::info!(agent = i, "agent initialized: {init_result}");
842+
let protocol_version =
843+
init_result["protocolVersion"].as_u64().unwrap_or(1) as u32;
842844
acp.observe(
843845
"agent_initialized",
844846
serde_json::json!({
@@ -852,6 +854,7 @@ async fn tokio_main() -> Result<()> {
852854
state: SessionState::default(),
853855
model_capabilities: None,
854856
desired_model: config.model.clone(),
857+
protocol_version,
855858
}));
856859
}
857860
Ok(Err(e)) => {
@@ -1279,13 +1282,14 @@ async fn tokio_main() -> Result<()> {
12791282
while let Ok(rr) = respawn_rx.try_recv() {
12801283
crash_history[rr.index].respawn_in_flight = false;
12811284
match rr.result {
1282-
Ok(acp) => {
1285+
Ok((acp, protocol_version)) => {
12831286
let agent = OwnedAgent {
12841287
index: rr.index,
12851288
acp,
12861289
state: SessionState::default(),
12871290
model_capabilities: None,
12881291
desired_model: config.model.clone(),
1292+
protocol_version,
12891293
};
12901294
pool.return_agent(agent);
12911295
tracing::info!(agent = rr.index, "respawn complete");
@@ -1887,7 +1891,7 @@ async fn tokio_main() -> Result<()> {
18871891
// Drain any respawn results that completed before the abort. Explicitly
18881892
// shut down returned agents instead of relying on AcpClient::Drop.
18891893
while let Ok(rr) = respawn_rx.try_recv() {
1890-
if let Ok(mut acp) = rr.result {
1894+
if let Ok((mut acp, _)) = rr.result {
18911895
acp.shutdown().await;
18921896
tracing::debug!(agent = rr.index, "reaped respawned agent on shutdown");
18931897
}
@@ -2429,10 +2433,10 @@ fn dispatch_heartbeat(
24292433
.heartbeat_prompt
24302434
.clone()
24312435
.unwrap_or_else(default_heartbeat_prompt);
2432-
let prompt_text = match ctx.base_prompt {
2433-
Some(bp) => prepend_base_prompt(bp, &prompt_text),
2434-
None => prompt_text,
2435-
};
2436+
// For legacy agents (protocol_version < 2), prepend base_prompt to the
2437+
// heartbeat user message since they don't receive it via session/new.
2438+
let prompt_text =
2439+
pool::prepend_base_for_legacy(agent.protocol_version, ctx.base_prompt, &prompt_text);
24362440
let result_tx = pool.result_tx();
24372441
let ctx_clone = Arc::clone(ctx);
24382442
let agent_index = agent.index;
@@ -2546,7 +2550,7 @@ async fn spawn_and_init(
25462550
extra_env: &[(String, String)],
25472551
agent_index: usize,
25482552
observer: Option<observer::ObserverHandle>,
2549-
) -> Result<AcpClient> {
2553+
) -> Result<(AcpClient, u32)> {
25502554
let mut acp = AcpClient::spawn(command, args, extra_env)
25512555
.await
25522556
.map_err(|e| anyhow::anyhow!("failed to spawn agent: {e}"))?;
@@ -2555,14 +2559,15 @@ async fn spawn_and_init(
25552559
match acp.initialize().await {
25562560
Ok(init_result) => {
25572561
tracing::info!("agent initialized: {init_result}");
2562+
let protocol_version = init_result["protocolVersion"].as_u64().unwrap_or(1) as u32;
25582563
acp.observe(
25592564
"agent_initialized",
25602565
serde_json::json!({
25612566
"agentIndex": agent_index,
25622567
"initializeResult": init_result,
25632568
}),
25642569
);
2565-
Ok(acp)
2570+
Ok((acp, protocol_version))
25662571
}
25672572
Err(e) => {
25682573
// Explicitly shut down the spawned child to prevent zombie/leak.
@@ -2605,7 +2610,7 @@ async fn run_models(args: ModelsArgs) -> Result<()> {
26052610
// so shutdown() runs on all paths (success, error, timeout).
26062611
let protocol_result = tokio::time::timeout(MODELS_TIMEOUT, async {
26072612
let init = client.initialize().await?;
2608-
let session = client.session_new_full(&cwd, vec![]).await?;
2613+
let session = client.session_new_full(&cwd, vec![], None).await?;
26092614
Ok::<_, acp::AcpError>((init, session))
26102615
})
26112616
.await;
@@ -2764,6 +2769,38 @@ fn build_mcp_servers(config: &Config) -> Vec<McpServer> {
27642769

27652770
// ── Tests ─────────────────────────────────────────────────────────────────────
27662771

2772+
#[cfg(test)]
2773+
mod heartbeat_base_prompt_tests {
2774+
use super::*;
2775+
2776+
// Pins the heartbeat dispatch path (dispatch_heartbeat, ~line 2359): a
2777+
// legacy agent WITH a base_prompt must get [Base] prepended to the
2778+
// heartbeat user message, composed as `[Base]\n{bp}\n\n{prompt}`. This is
2779+
// the second half of the round-2 regression (the first being initial_message).
2780+
2781+
#[test]
2782+
fn test_heartbeat_legacy_agent_gets_base_prepended() {
2783+
// protocol_version 1 + Some(base_prompt): heartbeat prompt is prefixed
2784+
// with the [Base] section exactly as the legacy session/new path would.
2785+
let prompt = "[System: Heartbeat]\nrun feed get";
2786+
let composed = pool::prepend_base_for_legacy(1, Some("you are a helpful agent"), prompt);
2787+
assert_eq!(
2788+
composed,
2789+
"[Base]\nyou are a helpful agent\n\n[System: Heartbeat]\nrun feed get"
2790+
);
2791+
assert!(composed.starts_with("[Base]\nyou are a helpful agent\n\n"));
2792+
}
2793+
2794+
#[test]
2795+
fn test_heartbeat_modern_agent_omits_base() {
2796+
// protocol_version 2 gets base_prompt via session/new; the heartbeat
2797+
// prompt is sent verbatim.
2798+
let prompt = "[System: Heartbeat]\nrun feed get";
2799+
let composed = pool::prepend_base_for_legacy(2, Some("you are a helpful agent"), prompt);
2800+
assert_eq!(composed, prompt);
2801+
}
2802+
}
2803+
27672804
#[cfg(test)]
27682805
mod owner_control_command_tests {
27692806
use super::*;

0 commit comments

Comments
 (0)