Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions crates/buzz-acp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,15 @@ The harness works with any agent that implements the [ACP spec](https://agentcli
- Accept `session/prompt` with a text message and stream `session/update` notifications
- Return a `stopReason` (`end_turn`, `cancelled`, `max_tokens`, etc.)

An adapter that hands a turn's work to a durable backend which keeps working
after the ACP turn ends may return, with a successful `session/prompt` result,
`_meta.buzz.indicators: {"owner": "external", "eventIds": ["<event id>", ...]}`
naming the events whose indicators that backend now owns. The harness leaves
exactly those messages marked as seen (👀) instead of clearing the reaction;
every other event of the turn is cleared as usual, and the harness stops its
own typing indicator either way. The backend removes the mark when its work
ends. Failed, cancelled and retried turns ignore the hint.

Set `BUZZ_ACP_AGENT_COMMAND` and `BUZZ_ACP_AGENT_ARGS` to point at your agent binary.

## Testing
Expand Down
67 changes: 67 additions & 0 deletions crates/buzz-acp/src/acp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,11 @@ pub struct AcpClient {
steer_rx: Option<tokio::sync::mpsc::Receiver<crate::pool::SteerRequest>>,
/// Usage tracker for goose/buzz-agent's cumulative notification format.
goose_usage: UsageTracker,
/// Events whose seen/working indicators the last `session/prompt` result
/// handed to an external owner (`_meta.buzz.indicators = {"owner":
/// "external", "eventIds": [...]}`): a durable backend that keeps working
/// after the turn ends. Consumed once per prompt result.
external_indicator_event_ids: Vec<String>,
/// Optional, explicitly enabled publisher for the local ACP extension.
/// It holds the Buzz signer in this parent process; the child only emits
/// validated publication intents and never receives private key material.
Expand Down Expand Up @@ -661,6 +666,7 @@ impl AcpClient {
single_event_prompts: false,
steer_rx: None,
goose_usage: UsageTracker::default(),
external_indicator_event_ids: Vec::new(),
local_publication_publisher: None,
buzz_prompt_metadata: None,
standard_usage: StandardUsageTracker::default(),
Expand Down Expand Up @@ -1126,6 +1132,12 @@ impl AcpClient {
self.steer_rx = None;
}

/// The events whose seen/working indicators the prompt that just ended
/// handed to an external owner. Resets, so the hint never outlives its turn.
pub fn take_external_indicator_event_ids(&mut self) -> Vec<String> {
std::mem::take(&mut self.external_indicator_event_ids)
}

/// Returns `true` if no steer receiver is currently installed.
///
/// Test-only: used by `pool` tests to assert the post-return invariant
Expand Down Expand Up @@ -2228,6 +2240,7 @@ impl AcpClient {
result: &serde_json::Value,
) -> Result<StopReason, AcpError> {
let stop_reason = self.parse_stop_reason(result)?;
self.external_indicator_event_ids = parse_external_indicator_event_ids(result);
if let Some(adapter) = self.standard_adapter {
match serde_json::from_value::<PromptResponseUsage>(result["usage"].clone()) {
Ok(usage) => self
Expand All @@ -2253,6 +2266,27 @@ impl AcpClient {
}
}

/// Bounded, lower-cased 64-hex event ids from `_meta.buzz.indicators` when its
/// owner is `"external"`; anything malformed hands nothing over.
fn parse_external_indicator_event_ids(result: &serde_json::Value) -> Vec<String> {
let Some(indicators) = result.pointer("/_meta/buzz/indicators") else {
return Vec::new();
};
if indicators.get("owner").and_then(serde_json::Value::as_str) != Some("external") {
return Vec::new();
}
indicators
.get("eventIds")
.and_then(serde_json::Value::as_array)
.into_iter()
.flatten()
.filter_map(serde_json::Value::as_str)
.filter(|id| id.len() == 64 && id.bytes().all(|b| b.is_ascii_hexdigit()))
.map(str::to_ascii_lowercase)
.take(64)
.collect()
}

/// Build `session/prompt` params from one or more text content blocks.
fn build_prompt_params(
session_id: &str,
Expand Down Expand Up @@ -4933,6 +4967,39 @@ sleep 1"#,
assert_eq!(usage.cumulative_output_tokens, None);
}

#[tokio::test]
async fn prompt_response_external_indicator_hint_is_consumed_once() {
let mut client = spawn_inert_client().await;
let owned = "A".repeat(64);
client
.parse_prompt_response(
"session",
&serde_json::json!({
"stopReason": "end_turn",
"_meta": {"buzz": {"indicators": {
"owner": "external",
"eventIds": [owned, "not-hex"]
}}}
}),
)
.unwrap();
assert_eq!(
client.take_external_indicator_event_ids(),
vec!["a".repeat(64)]
);
assert!(client.take_external_indicator_event_ids().is_empty());
for result in [
serde_json::json!({"stopReason": "end_turn"}),
serde_json::json!({"stopReason": "end_turn", "_meta": {"buzz": {"indicators": "external"}}}),
serde_json::json!({"stopReason": "end_turn", "_meta": {"buzz": {"indicators": {
"owner": "self", "eventIds": ["a".repeat(64)]
}}}}),
] {
client.parse_prompt_response("session", &result).unwrap();
assert!(client.take_external_indicator_event_ids().is_empty());
}
}

#[tokio::test]
async fn codex_prompt_response_usage_preserves_provider_total_without_cost() {
let mut client = spawn_inert_client().await;
Expand Down
63 changes: 62 additions & 1 deletion crates/buzz-acp/src/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2468,7 +2468,17 @@ fn send_prompt_result(
batch: Option<FlushBatch>,
reaction_guard: &mut ReactionGuard,
) {
reaction_guard.finish(reaction_state_for_prompt_exit(&outcome, batch.is_some()));
let external: HashSet<String> = agent
.acp
.take_external_indicator_event_ids()
.into_iter()
.collect();
let state = reaction_state_for_prompt_exit(&outcome, batch.is_some());
if hands_off_indicators(&outcome, batch.is_some()) && !external.is_empty() {
reaction_guard.finish_with_external(state, &external);
} else {
reaction_guard.finish(state);
}
agent.acp.clear_steer_rx();
let _ = result_tx.send(PromptResult {
agent,
Expand Down Expand Up @@ -5317,6 +5327,12 @@ pub(crate) enum ReactionState {
Clear,
}

/// Only a successful, final turn may hand its indicators to an external
/// owner; failed, cancelled and retried turns keep their own state.
fn hands_off_indicators(outcome: &PromptOutcome, has_retry_batch: bool) -> bool {
!has_retry_batch && matches!(outcome, PromptOutcome::Ok(_))
}

fn reaction_state_for_prompt_exit(outcome: &PromptOutcome, has_retry_batch: bool) -> ReactionState {
if has_retry_batch {
return ReactionState::Queued;
Expand Down Expand Up @@ -5362,6 +5378,27 @@ impl ReactionGuard {
spawn_reconcile_reactions(rest, ids, state);
}
}

/// The adapter's durable backend (for example a server-side mission
/// runtime answering minutes later) took over the events in `external`:
/// they stay marked as seen (👀) for that owner to remove. Every other
/// event of the turn gets `state` as usual.
fn finish_with_external(&mut self, state: ReactionState, external: &HashSet<String>) {
if let Some(rest) = self.rest.take() {
let (kept, others) = split_external_reactions(std::mem::take(&mut self.ids), external);
spawn_reconcile_reactions(rest.clone(), kept, ReactionState::Queued);
spawn_reconcile_reactions(rest, others, state);
}
}
}

/// Partition reaction targets into those an external owner took over and the rest.
fn split_external_reactions(
ids: Vec<String>,
external: &HashSet<String>,
) -> (Vec<String>, Vec<String>) {
ids.into_iter()
.partition(|id| external.contains(&id.to_ascii_lowercase()))
}

impl Drop for ReactionGuard {
Expand Down Expand Up @@ -6038,6 +6075,30 @@ pub(crate) mod tests {
assert_eq!(desired_reaction(ReactionState::Clear), None);
}

#[test]
fn external_indicator_hand_off_keeps_only_the_owned_seen_reaction() {
let owned = "a".repeat(64);
let other = "b".repeat(64);
let external: HashSet<String> = [owned.clone()].into_iter().collect();
let (kept, rest) =
split_external_reactions(vec![owned.to_ascii_uppercase(), other.clone()], &external);
assert_eq!(kept, vec![owned.to_ascii_uppercase()]);
assert_eq!(rest, vec![other]);
let ok = PromptOutcome::Ok(StopReason::EndTurn);
assert!(hands_off_indicators(&ok, false));
// A failure, cancellation or retry keeps its own state even with the hint.
assert!(!hands_off_indicators(&ok, true));
assert!(!hands_off_indicators(&PromptOutcome::Cancelled, false));
assert!(!hands_off_indicators(
&PromptOutcome::Error(AcpError::Protocol("boom".into())),
false
));
assert_eq!(
reaction_state_for_prompt_exit(&ok, false),
ReactionState::Clear
);
}

#[test]
fn newer_reaction_state_supersedes_queued_before_network_work() {
let event_ids = vec!["reaction-generation-test-event".to_string()];
Expand Down