Skip to content

Commit ac44fae

Browse files
committed
fix(agents): bind remote direct messages to their conversation
Signed-off-by: Tee8z <[email protected]>
1 parent c4c4bd9 commit ac44fae

9 files changed

Lines changed: 489 additions & 102 deletions

File tree

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

Lines changed: 127 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -19,31 +19,76 @@ use uuid::Uuid;
1919

2020
use crate::filter::SubscriptionRule;
2121

22-
/// Immutable conversation binding for a remote workspace.
22+
/// Immutable channel-thread or direct-message binding for a remote workspace.
2323
#[derive(Debug, Clone, serde::Deserialize)]
24-
#[serde(deny_unknown_fields)]
25-
pub struct BoundSession {
26-
pub channel_id: Uuid,
27-
pub thread_root: String,
24+
#[serde(untagged, deny_unknown_fields)]
25+
pub enum BoundSession {
26+
/// One published thread in a channel.
27+
Thread {
28+
channel_id: Uuid,
29+
thread_root: String,
30+
},
31+
/// One complete direct-message conversation.
32+
DirectMessage { dm_channel_id: Uuid },
2833
}
2934

3035
impl BoundSession {
36+
/// The only channel admitted by this workspace.
37+
pub fn channel_id(&self) -> Uuid {
38+
match self {
39+
Self::Thread { channel_id, .. } => *channel_id,
40+
Self::DirectMessage { dm_channel_id } => *dm_channel_id,
41+
}
42+
}
43+
44+
/// The published root for a channel thread; DMs have no root.
45+
pub fn thread_root(&self) -> Option<&str> {
46+
match self {
47+
Self::Thread { thread_root, .. } => Some(thread_root),
48+
Self::DirectMessage { .. } => None,
49+
}
50+
}
51+
52+
pub(crate) fn validate_channel_metadata(
53+
&self,
54+
info: Option<&crate::relay::ChannelInfo>,
55+
) -> Result<(), ConfigError> {
56+
if matches!(self, Self::DirectMessage { .. })
57+
&& info.is_none_or(|info| info.channel_type != "dm")
58+
{
59+
return Err(ConfigError::ConfigFile(
60+
"bound direct-message workspace requires verified DM channel metadata".into(),
61+
));
62+
}
63+
Ok(())
64+
}
65+
66+
/// Whether a routed event belongs to this immutable scope.
3167
pub fn accepts(&self, scope: &crate::scope::SessionScope) -> bool {
32-
scope.channel_id() == self.channel_id && scope.root_event_id() == Some(&self.thread_root)
68+
match self {
69+
Self::Thread {
70+
channel_id,
71+
thread_root,
72+
} => scope.channel_id() == *channel_id && scope.root_event_id() == Some(thread_root),
73+
Self::DirectMessage { dm_channel_id } => {
74+
scope.channel_id() == *dm_channel_id && !scope.is_thread()
75+
}
76+
}
3377
}
3478
}
3579

3680
fn parse_bound_session(value: &str) -> Result<BoundSession, String> {
3781
let binding: BoundSession = serde_json::from_str(value).map_err(|_| {
38-
"bound session requires a channel UUID and canonical thread root".to_string()
82+
"bound session requires a channel thread or a direct-message channel UUID".to_string()
3983
})?;
40-
if binding.thread_root.len() != 64
41-
|| !binding
42-
.thread_root
43-
.bytes()
44-
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
45-
{
46-
return Err("bound session thread_root must be a lowercase event ID".into());
84+
if let Some(thread_root) = binding.thread_root() {
85+
if thread_root.len() != 64
86+
|| !thread_root
87+
.bytes()
88+
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
89+
{
90+
return Err("bound session thread_root must be a lowercase event ID".into());
91+
}
4792
}
4893
Ok(binding)
4994
}
@@ -997,11 +1042,21 @@ impl Config {
9971042
/// `propagate_legacy_env_vars()` before the tokio runtime starts (in the
9981043
/// sync `fn main()` wrapper) — see Rust 2024 edition safety.
9991044
pub fn from_args(mut args: CliArgs) -> Result<Self, ConfigError> {
1000-
if args.bound_session.is_some() {
1045+
if let Some(binding) = &args.bound_session {
1046+
let direct_message = matches!(binding, BoundSession::DirectMessage { .. });
1047+
let subscription = if direct_message {
1048+
SubscribeMode::All
1049+
} else {
1050+
SubscribeMode::Mentions
1051+
};
10011052
let refusal = if args.respond_to != RespondTo::Owner {
10021053
Some("--respond-to owner")
1003-
} else if args.subscribe != SubscribeMode::Mentions {
1004-
Some("--subscribe mentions")
1054+
} else if args.subscribe != subscription {
1055+
Some(if direct_message {
1056+
"--subscribe all"
1057+
} else {
1058+
"--subscribe mentions"
1059+
})
10051060
} else if args.no_mention_filter {
10061061
Some("no --no-mention-filter")
10071062
} else if args.session_policy != crate::scope::SessionPolicy::Thread {
@@ -1693,6 +1748,61 @@ mod tests {
16931748
}
16941749
}
16951750

1751+
#[test]
1752+
fn a_bound_dm_requires_verified_metadata_and_owner_only_subscription() {
1753+
let channel = Uuid::new_v4();
1754+
let binding = serde_json::json!({"dm_channel_id":channel}).to_string();
1755+
let parsed = parse_bound_session(&binding).unwrap();
1756+
assert!(parsed.validate_channel_metadata(None).is_err());
1757+
for (kind, accepted) in [("dm", true), ("stream", false), ("", false)] {
1758+
let info = crate::relay::ChannelInfo {
1759+
name: "test".into(),
1760+
channel_type: kind.into(),
1761+
description: None,
1762+
};
1763+
assert_eq!(
1764+
parsed.validate_channel_metadata(Some(&info)).is_ok(),
1765+
accepted
1766+
);
1767+
}
1768+
for invalid in [
1769+
serde_json::json!({"dm_channel_id":channel,"thread_root":"a".repeat(64)}),
1770+
serde_json::json!({"dm_channel_id":channel,"channel_id":channel}),
1771+
serde_json::json!({"dm_channel_id":"invalid"}),
1772+
] {
1773+
assert!(parse_bound_session(&invalid.to_string()).is_err());
1774+
}
1775+
let key = Keys::generate().secret_key().to_secret_hex();
1776+
let owner = Keys::generate().public_key().to_hex();
1777+
let args = || {
1778+
CliArgs::try_parse_from([
1779+
"buzz-acp",
1780+
"--private-key",
1781+
&key,
1782+
"--agent-owner",
1783+
&owner,
1784+
"--bound-session",
1785+
&binding,
1786+
"--respond-to",
1787+
"owner",
1788+
"--subscribe",
1789+
"all",
1790+
"--session-policy",
1791+
"thread",
1792+
"--heartbeat-interval",
1793+
"0",
1794+
])
1795+
.unwrap()
1796+
};
1797+
assert!(Config::from_args(args()).is_ok());
1798+
let mut mentions = args();
1799+
mentions.subscribe = SubscribeMode::Mentions;
1800+
assert!(Config::from_args(mentions).is_err());
1801+
let mut siblings = args();
1802+
siblings.respond_to = RespondTo::OwnerOnly;
1803+
assert!(Config::from_args(siblings).is_err());
1804+
}
1805+
16961806
#[test]
16971807
fn bound_session_requires_explicit_owner_mentions_without_autonomous_prompts() {
16981808
let key = Keys::generate().secret_key().to_secret_hex();

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

Lines changed: 48 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3072,6 +3072,10 @@ async fn run_harness(
30723072
.await
30733073
.map_err(|e| anyhow::anyhow!("channel discovery error: {e}"))?;
30743074

3075+
if let Some(binding) = &config.bound_session {
3076+
binding.validate_channel_metadata(channel_info_map.get(&binding.channel_id()))?;
3077+
}
3078+
30753079
tracing::info!("discovered {} channel(s)", channel_info_map.len());
30763080
let channel_ids: Vec<Uuid> = channel_info_map.keys().copied().collect();
30773081

@@ -3532,7 +3536,7 @@ async fn run_harness(
35323536
observer.as_ref(),
35333537
owner_hex,
35343538
relay.event_publisher(),
3535-
config.bound_session.as_ref().map(|binding| binding.channel_id),
3539+
config.bound_session.as_ref().map(|binding| binding.channel_id()),
35363540
);
35373541
} else {
35383542
tracing::warn!("observer control frame received but no owner resolved — dropping");
@@ -4579,11 +4583,12 @@ fn bound_session_admits(
45794583
let Some(binding) = binding else {
45804584
return true;
45814585
};
4582-
if buzz_event.channel_id != binding.channel_id {
4586+
if buzz_event.channel_id != binding.channel_id() {
45834587
return false;
45844588
}
45854589
match routed_scope {
45864590
Some(scope) => binding.accepts(scope),
4591+
None if matches!(binding, config::BoundSession::DirectMessage { .. }) => true,
45874592
None => {
45884593
u32::from(buzz_event.event.kind.as_u16()) != KIND_STREAM_MESSAGE
45894594
|| binding.accepts(&scope::SessionScope::derive(
@@ -7273,12 +7278,40 @@ mod bound_session_admission_tests {
72737278
}
72747279

72757280
fn binding() -> config::BoundSession {
7276-
config::BoundSession {
7281+
config::BoundSession::Thread {
72777282
channel_id: Uuid::new_v4(),
72787283
thread_root: "a".repeat(64),
72797284
}
72807285
}
72817286

7287+
#[test]
7288+
fn a_bound_dm_admits_conversation_events_but_no_channel_thread() {
7289+
let channel = Uuid::new_v4();
7290+
let binding = config::BoundSession::DirectMessage {
7291+
dm_channel_id: channel,
7292+
};
7293+
for root in [None, Some("a".repeat(64))] {
7294+
let event = buzz_event(channel, 9, "plain owner DM", root.as_deref());
7295+
assert!(bound_session_admits(Some(&binding), &event, None));
7296+
let dm = scope::SessionScope::derive(
7297+
scope::SessionPolicy::Thread,
7298+
channel,
7299+
true,
7300+
&event.event,
7301+
);
7302+
assert!(bound_session_admits(Some(&binding), &event, Some(&dm)));
7303+
let thread = scope::SessionScope::derive(
7304+
scope::SessionPolicy::Thread,
7305+
channel,
7306+
false,
7307+
&event.event,
7308+
);
7309+
assert!(!bound_session_admits(Some(&binding), &event, Some(&thread)));
7310+
}
7311+
let foreign = buzz_event(Uuid::new_v4(), 9, "another DM", None);
7312+
assert!(!bound_session_admits(Some(&binding), &foreign, None));
7313+
}
7314+
72827315
/// The pre-check runs before `!shutdown` / `!cancel`, so an owner command
72837316
/// in a foreign thread or channel never reaches the control handlers.
72847317
#[test]
@@ -7287,7 +7320,7 @@ mod bound_session_admission_tests {
72877320
let foreign_root = "b".repeat(64);
72887321
for command in ["!shutdown", "!cancel"] {
72897322
let foreign_thread = buzz_event(
7290-
binding.channel_id,
7323+
binding.channel_id(),
72917324
KIND_STREAM_MESSAGE as u16,
72927325
command,
72937326
Some(&foreign_root),
@@ -7304,7 +7337,7 @@ mod bound_session_admission_tests {
73047337
Uuid::new_v4(),
73057338
KIND_STREAM_MESSAGE as u16,
73067339
command,
7307-
Some(&binding.thread_root),
7340+
binding.thread_root(),
73087341
);
73097342
assert!(!bound_session_admits(
73107343
Some(&binding),
@@ -7313,10 +7346,10 @@ mod bound_session_admission_tests {
73137346
));
73147347

73157348
let in_thread = buzz_event(
7316-
binding.channel_id,
7349+
binding.channel_id(),
73177350
KIND_STREAM_MESSAGE as u16,
73187351
command,
7319-
Some(&binding.thread_root),
7352+
binding.thread_root(),
73207353
);
73217354
assert!(bound_session_admits(Some(&binding), &in_thread, None));
73227355
}
@@ -7326,14 +7359,14 @@ mod bound_session_admission_tests {
73267359
fn only_in_thread_prompts_are_admitted() {
73277360
let binding = binding();
73287361
let in_scope = scope::SessionScope::Thread {
7329-
channel_id: binding.channel_id,
7330-
root_event_id: binding.thread_root.clone(),
7362+
channel_id: binding.channel_id(),
7363+
root_event_id: binding.thread_root().unwrap().to_owned(),
73317364
};
73327365
let reply = buzz_event(
7333-
binding.channel_id,
7366+
binding.channel_id(),
73347367
KIND_STREAM_MESSAGE as u16,
73357368
"@agent continue",
7336-
Some(&binding.thread_root),
7369+
binding.thread_root(),
73377370
);
73387371
assert!(bound_session_admits(Some(&binding), &reply, None));
73397372
assert!(bound_session_admits(
@@ -7347,11 +7380,11 @@ mod bound_session_admission_tests {
73477380
foreign_channel_id,
73487381
KIND_STREAM_MESSAGE as u16,
73497382
"@agent start",
7350-
Some(&binding.thread_root),
7383+
binding.thread_root(),
73517384
);
73527385
let foreign_scope = scope::SessionScope::Thread {
73537386
channel_id: foreign_channel_id,
7354-
root_event_id: binding.thread_root.clone(),
7387+
root_event_id: binding.thread_root().unwrap().to_owned(),
73557388
};
73567389
assert!(!bound_session_admits(
73577390
Some(&binding),
@@ -7367,10 +7400,10 @@ mod bound_session_admission_tests {
73677400
// An edit carries its thread on the original, so the pre-check can
73687401
// only check its channel; the routed scope decides admission.
73697402
let edit_kind = buzz_core::kind::KIND_STREAM_MESSAGE_EDIT as u16;
7370-
let edit = buzz_event(binding.channel_id, edit_kind, "@agent edited", None);
7403+
let edit = buzz_event(binding.channel_id(), edit_kind, "@agent edited", None);
73717404
assert!(bound_session_admits(Some(&binding), &edit, None));
73727405
let edited_foreign_thread = scope::SessionScope::Thread {
7373-
channel_id: binding.channel_id,
7406+
channel_id: binding.channel_id(),
73747407
root_event_id: "c".repeat(64),
73757408
};
73767409
assert!(!bound_session_admits(

0 commit comments

Comments
 (0)