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
99 changes: 78 additions & 21 deletions crates/buzz-acp/src/acp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,13 @@ pub struct AcpClient {
/// lying on the connection is one careless read away from approving a
/// later guest's request.
current_turn_authority: TurnAuthority,
/// Sessions a guest's words were written into (prompt or steer). An owner
/// turn must not inherit them: dispatch starts a fresh session instead
/// (`take_guest_mark`).
// shortcut: never pruned for sessions no owner turn follows (a few ids per
// process; ~632 sessions a month across all agents, 2 Nov count). Prune on
// invalidate if one long-lived agent grows.
guest_sessions: std::collections::HashSet<String>,
/// Permission requests refused during the turn in flight.
///
/// Buffered rather than sent through a channel because the pool is already
Expand Down Expand Up @@ -832,6 +839,7 @@ impl AcpClient {
next_id: 0,
pending_permissions: Default::default(),
current_turn_authority: TurnAuthority::Guest,
guest_sessions: Default::default(),
permission_refusals: Vec::new(),
turn_reply_text: String::new(),
last_prompt_id: None,
Expand Down Expand Up @@ -1098,6 +1106,9 @@ impl AcpClient {
// prompt before the turn's, so that turn could never park. `None`
// means no request can wait on a person.
self.current_turn_authority = authority;
if authority == TurnAuthority::Guest {
self.guest_sessions.insert(session_id.to_owned());
}
// Cleared per turn: a refusal from a previous turn reported against
// this one would name the wrong request to the wrong person.
self.permission_refusals.clear();
Expand Down Expand Up @@ -1262,6 +1273,11 @@ impl AcpClient {
self.standard_usage.seed_zero_baseline(session_id);
}

/// Whether a guest's words were written into `session_id`, clearing the mark.
pub(crate) fn take_guest_mark(&mut self, session_id: &str) -> bool {
self.guest_sessions.remove(session_id)
}

/// Install a per-turn steer request channel for goose-native
/// non-cancelling mid-turn delivery.
///
Expand Down Expand Up @@ -1831,7 +1847,7 @@ impl AcpClient {
let stale = self.pending_permissions.retire_all_parked();
if !stale.is_empty() {
tracing::error!(
target: "acp::permission",
target: "buzz_acp::permission",
count = stale.len(),
"parked permission requests outlived their turn; retired unanswered"
);
Expand Down Expand Up @@ -1920,6 +1936,9 @@ impl AcpClient {
// written, so no permission request the agent raises in response can be
// decided with more trust than its instructions came from. This loop is
// single-threaded: nothing can be decided between these two steps.
if req.authority == TurnAuthority::Guest {
self.guest_sessions.insert(session_id.to_owned());
}
let lowered = self.current_turn_authority.weaker(req.authority);
if lowered != self.current_turn_authority {
tracing::info!(
Expand Down Expand Up @@ -2529,7 +2548,7 @@ impl AcpClient {
// request; the answer already owed covers both copies.
if self.pending_permissions.contains(&id) {
tracing::warn!(
target: "acp::permission",
target: "buzz_acp::permission",
id = %id,
"ignoring a repeated permission request that is still owed an answer"
);
Expand All @@ -2545,7 +2564,7 @@ impl AcpClient {
.ok_or_else(|| AcpError::Protocol("permission request missing options".into()))?;

tracing::debug!(
target: "acp::permission",
target: "buzz_acp::permission",
"session/request_permission id={id}, {} options",
options.len()
);
Expand All @@ -2555,7 +2574,7 @@ impl AcpClient {
match decide_permission(authority, options) {
PermissionDecision::Approve(option_id) => {
tracing::info!(
target: "acp::permission",
target: "buzz_acp::permission",
"auto-approving permission id={id} with allow_once optionId={option_id:?}"
);
self.answer_permission(&id, permission_response_selected(&id, &option_id))
Expand Down Expand Up @@ -2647,7 +2666,7 @@ impl AcpClient {
// The id was recorded unparked just before this call, so this
// cannot happen. Refused rather than trusted if it ever does.
tracing::error!(
target: "acp::permission",
target: "buzz_acp::permission",
id = %id,
?rejected,
"could not park a permission request"
Expand All @@ -2669,7 +2688,7 @@ impl AcpClient {
// now instead of holding the agent until the ask expires.
let _ = self.pending_permissions.take_parked(park_id);
tracing::warn!(
target: "acp::permission",
target: "buzz_acp::permission",
id = %id,
tool = %tool,
"no approval path: the main loop is not listening"
Expand All @@ -2680,7 +2699,7 @@ impl AcpClient {

let expires_in = expires_at.saturating_duration_since(now);
tracing::info!(
target: "acp::permission",
target: "buzz_acp::permission",
id = %id,
park_id = park_id.0,
turn_id = %ctx.gate.turn_id(),
Expand Down Expand Up @@ -2717,7 +2736,7 @@ impl AcpClient {
// is invisible in practice, and "the agent just didn't do it"
// is indistinguishable from a bug.
tracing::warn!(
target: "acp::permission",
target: "buzz_acp::permission",
id = %id,
tool = %tool,
authority = ?authority,
Expand Down Expand Up @@ -2866,7 +2885,7 @@ impl AcpClient {
let response = permission_response_selected(&ask.rpc_id, &ask.reject_option_id);
if let Err(e) = self.answer_permission(&ask.rpc_id, response).await {
tracing::warn!(
target: "acp::permission",
target: "buzz_acp::permission",
"exit drain stopped at a failed write ({e}); the rest stay owed"
);
return;
Expand Down Expand Up @@ -2897,7 +2916,7 @@ impl AcpClient {
}
if let Err(e) = self.answer_owed_cancelled().await {
tracing::warn!(
target: "acp::permission",
target: "buzz_acp::permission",
"exit drain stopped at a failed write ({e}); the rest stay owed"
);
}
Expand All @@ -2911,7 +2930,7 @@ impl AcpClient {
async fn answer_owed_cancelled(&mut self) -> Result<(), AcpError> {
for ask in self.pending_permissions.retire_all_parked() {
tracing::info!(
target: "acp::permission",
target: "buzz_acp::permission",
id = %ask.rpc_id,
park_id = ask.park_id.0,
tool = %ask.tool,
Expand All @@ -2922,7 +2941,7 @@ impl AcpClient {
self.answer_permission(&id, permission_response_cancelled(&id))
.await?;
tracing::debug!(
target: "acp::permission",
target: "buzz_acp::permission",
"responded cancelled to pending permission id={id}"
);
}
Expand All @@ -2943,7 +2962,7 @@ impl AcpClient {
match settlement {
Settlement::Allowed { .. } | Settlement::Denied(_) | Settlement::TurnEnded => {
tracing::info!(
target: "acp::permission",
target: "buzz_acp::permission",
id = %rpc_id,
park_id = park_id.0,
tool = %tool,
Expand All @@ -2953,7 +2972,7 @@ impl AcpClient {
}
Settlement::Expired | Settlement::VerdictChannelClosed => {
tracing::warn!(
target: "acp::permission",
target: "buzz_acp::permission",
id = %rpc_id,
park_id = park_id.0,
tool = %tool,
Expand All @@ -2966,7 +2985,7 @@ impl AcpClient {
// verdicts is broken somewhere.
Settlement::DigestMismatch => {
tracing::error!(
target: "acp::permission",
target: "buzz_acp::permission",
id = %rpc_id,
park_id = park_id.0,
tool = %tool,
Expand Down Expand Up @@ -3909,9 +3928,9 @@ mod tests {
}

/// Steer `authority`'s words into a running Owner turn, then have the agent
/// ask for permission. Returns the harness's answer and the turn's authority
/// afterwards.
async fn steer_then_ask(name: &str, authority: TurnAuthority) -> (String, TurnAuthority) {
/// ask for permission. Returns the harness's answer, the turn's authority
/// afterwards, and whether the session was marked as holding a guest's words.
async fn steer_then_ask(name: &str, authority: TurnAuthority) -> (String, TurnAuthority, bool) {
let capture = probe_capture_path(name);
// The agent blocks until the steer arrives before it asks, so the order
// is fixed: steer written, then permission request, then answer.
Expand Down Expand Up @@ -3948,29 +3967,38 @@ mod tests {

let answer = captured_answer(&capture);
let _ = std::fs::remove_file(&capture);
(answer, client.current_turn_authority)
(
answer,
client.current_turn_authority,
client.take_guest_mark("sess-test"),
)
}

/// The hole this closes. A guest who posted while the owner's turn was
/// running had their words steered in under the owner's authority, so the
/// agent's next tool request was approved as though the owner had asked.
#[tokio::test]
async fn a_guest_steer_lowers_the_turn_before_the_agent_can_ask() {
let (answer, after) = steer_then_ask("guest-steer", TurnAuthority::Guest).await;
let (answer, after, marked) = steer_then_ask("guest-steer", TurnAuthority::Guest).await;
assert_eq!(
answer, "reject-1",
"a request raised after a guest's steer must be decided as a guest"
);
assert_eq!(after, TurnAuthority::Guest);
assert!(
marked,
"a guest's steer must mark the session for the next owner turn"
);
}

/// The control: steering is not what lowers trust. The owner's own steer
/// leaves the owner's turn exactly as trusted as it was.
#[tokio::test]
async fn an_owner_steer_leaves_an_owner_turn_trusted() {
let (answer, after) = steer_then_ask("owner-steer", TurnAuthority::Owner).await;
let (answer, after, marked) = steer_then_ask("owner-steer", TurnAuthority::Owner).await;
assert_eq!(answer, "allow-1");
assert_eq!(after, TurnAuthority::Owner);
assert!(!marked, "the owner's own steer leaves the session unmarked");
}

/// The second hole. The setup loop (session/new, set_config_option) decided
Expand Down Expand Up @@ -4480,6 +4508,35 @@ mod tests {
);
}

/// A guest's prompt marks its session, so the next owner turn there starts
/// fresh; an owner's prompt leaves it unmarked. The echoed `-32601` ends each
/// prompt at once, as above.
#[tokio::test]
async fn a_guest_prompt_marks_its_session_and_an_owner_prompt_does_not() {
for (authority, marked) in [(TurnAuthority::Guest, true), (TurnAuthority::Owner, false)] {
let mut client = spawn_inert_client().await;
let _ = client
.session_prompt_with_idle_timeout(
PARK_SESSION,
"hello",
std::time::Duration::from_secs(5),
std::time::Duration::from_secs(10),
authority,
None,
)
.await;
assert_eq!(
client.take_guest_mark(PARK_SESSION),
marked,
"{authority:?}"
);
assert!(
!client.take_guest_mark(PARK_SESSION),
"taking the mark clears it"
);
}
}

// ── Around a write that has not finished (cat and sleep, every platform) ──
//
// Some orderings only show while an answer is still on its way to the
Expand Down
71 changes: 71 additions & 0 deletions crates/buzz-acp/src/factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1395,6 +1395,40 @@ impl Factory {
);
}

/// A refusal the sender was never told about: the "not set up to take
/// requests" notice could not be posted, even on its retry. `author` is
/// the sender's hex key and `event_id` the refused message's hex id. The
/// caller raises this once per (channel, sender), so the card is keyed on
/// that pair.
pub(crate) fn refusal_unseen(&mut self, channel_id: uuid::Uuid, author: &str, event_id: &str) {
let who = card_name(self.who(), &self.reporting.short);
let body = format!(
"{who} isn't set up to take requests from this person, and its reply saying so could \
not be posted, so they are waiting on an answer that won't come. If they should \
have access, change who can send it instructions and ask them to send it again. \
Otherwise let them know."
);
let id = format!(
"{}-refused-{channel_id}-{}",
self.reporting.short,
author.get(..12).unwrap_or(author)
);
let link = format!("buzz://message?channel={channel_id}&id={event_id}");
let title = format!("{who} turned away a message without telling the sender");
// Not an incident: the agent is working. `alert_critical` would mute the
// next real Critical's text and owe an all-clear nobody expects.
self.alert_aside(&format!(
"{title}. They are waiting on an answer that won't come."
));
self.card(
&id,
&title,
&body,
"Nothing happens by itself: the sender is not told.",
serde_json::json!([{"label": "Open message", "url": link}]),
);
}

/// Drop a Critical, needs-you card in the Bench inbox (spec 7.1) in the
/// Bench's drop format, once per id per incident. Written beside its name
/// and renamed into place, so the Bench never reads half a file.
Expand Down Expand Up @@ -2687,4 +2721,41 @@ mod tests {
let mut f = Factory::new(None, "claude-agent-acp");
f.dropped(channel, &event, "boom");
}

#[test]
fn refusal_unseen_card_links_the_message_and_never_shows_unsafe_text() {
let bench = tempfile::tempdir().unwrap();
let mut f = Factory::new(None, "claude-agent-acp");
f.reporting = reporting("Chris Orchestrator");
f.reporting.bench = Some(bench.path().to_path_buf());
let channel = uuid::Uuid::parse_str("335dd4e1-0000-4000-8000-000000000001").unwrap();
let event = "ef".repeat(32);
f.refusal_unseen(channel, &"cd".repeat(32), &event);
let card = read_card(
bench.path(),
&format!("ade9d0e2-refused-{channel}-cdcdcdcdcdcd"),
)
.expect("card, keyed on the (channel, sender) pair");
assert_eq!(
card["title"],
"Chris Orchestrator turned away a message without telling the sender"
);
assert_eq!(card["severity"], "critical");
assert_eq!(
card["links"][0]["url"],
format!("buzz://message?channel={channel}&id={event}")
);
assert_eq!(
card["plain"]["ifYouWait"],
"Nothing happens by itself: the sender is not told."
);
let body = card["body"].as_str().unwrap();
assert!(card_safe(body), "{body}");
// D1 (15 Nov 2026): the owner is texted as well as carded.
let texts = f.take_alerts();
assert_eq!(texts.len(), 1, "{texts:?}");
assert!(texts[0].contains("turned away a message"), "{texts:?}");
// Not an incident: no all-clear is owed and the next Critical still texts.
assert!(f.alerted.is_none());
}
}
Loading
Loading