Skip to content

Commit 00dc491

Browse files
tlongwell-blockMax
andauthored
Add manual ACP session rotation command (#932)
Signed-off-by: npub1mprnacetjua2xx3p5eddmhxyk6wv929ymm5py8kd2xfxurxahspqqlgyta <d8473ee32b973aa31a21a65adddcc4b69cc2a8a4dee8121ecd51926e0cddbc02@sprout-oss.stage.blox.sqprod.co> Co-authored-by: Max <d8473ee32b973aa31a21a65adddcc4b69cc2a8a4dee8121ecd51926e0cddbc02@sprout-oss.stage.blox.sqprod.co>
1 parent df8896f commit 00dc491

3 files changed

Lines changed: 320 additions & 55 deletions

File tree

‎crates/buzz-acp/README.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,17 @@ Controls which authors' events the harness forwards to the agent. Events from di
139139
| `anyone` | Forward all events (no author filtering). |
140140
| `nobody` | Drop all inbound events. Agent only acts on heartbeat prompts. |
141141

142-
The gate applies to **all** inbound events — @mentions, DMs, thread replies, and any event delivered by the relay. The `!shutdown` command is checked **before** the gate, so the owner can always shut down the agent regardless of mode.
142+
The gate applies to **all** inbound events — @mentions, DMs, thread replies, and any event delivered by the relay. Owner control commands are checked **before** the gate, so the owner can still manage the harness regardless of mode:
143+
144+
| Command | Effect |
145+
|---------|--------|
146+
| `!shutdown` | Gracefully exits the harness. |
147+
| `!cancel` | Cancels the current in-flight turn for that channel, if any. |
148+
| `!rotate` | Rotates the ACP session for that channel. If a turn is in-flight, it is cancelled and the channel session is invalidated when the task returns; otherwise the cached idle session is invalidated immediately. The next queued/received event starts a fresh session. |
149+
150+
Use `!cancel` to stop only the current turn; it is a no-op when the channel is idle. Use `!rotate` when you want the next turn in the channel to start from a fresh ACP session, even if the channel is currently idle.
151+
152+
Owner control commands must be kind:9 stream messages from the owner, must mention this agent with a `p` tag, and are consumed by the harness instead of being forwarded to the agent.
143153

144154
> **Note:** The default mode is `owner-only`. Agents without a registered `agent_owner_pubkey` will not respond to any events until the owner is resolved. Set `--respond-to anyone` to disable the gate entirely.
145155

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

Lines changed: 190 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ use filter::SubscriptionRule;
2828
use futures_util::FutureExt;
2929
use nostr::{PublicKey, ToBech32};
3030
use pool::{
31-
AgentPool, CancelMode, OwnedAgent, PromptContext, PromptOutcome, PromptResult, PromptSource,
31+
AgentPool, ControlSignal, OwnedAgent, PromptContext, PromptOutcome, PromptResult, PromptSource,
3232
SessionState,
3333
};
3434
use queue::{prepend_base_prompt, EventQueue, QueuedEvent, ThreadTags};
@@ -540,7 +540,7 @@ fn handle_relay_observer_control_event(
540540
return;
541541
};
542542

543-
let fired = cancel_in_flight_task(pool, channel_id, CancelMode::Stop);
543+
let fired = signal_in_flight_task(pool, channel_id, ControlSignal::Cancel);
544544
let status = if fired { "sent" } else { "no_active_turn" };
545545
if let Some(observer) = observer {
546546
observer.emit(
@@ -1471,12 +1471,12 @@ async fn tokio_main() -> Result<()> {
14711471

14721472
// ── Shutdown command handling ─────────────────────
14731473
// Check: kind:9, content "!shutdown", from owner, mentions THIS agent.
1474-
let is_shutdown = kind_u32 == KIND_STREAM_MESSAGE
1475-
&& buzz_event.event.content.trim() == "!shutdown"
1476-
&& buzz_event.event.tags.iter().any(|t| {
1477-
t.as_slice().first().map(|s| s.as_str()) == Some("p")
1478-
&& t.as_slice().get(1).map(|s| s.as_str()) == Some(pubkey_hex.as_str())
1479-
});
1474+
let is_shutdown = is_owner_control_command(
1475+
&buzz_event.event,
1476+
kind_u32,
1477+
"!shutdown",
1478+
&pubkey_hex,
1479+
);
14801480
if is_shutdown {
14811481
let owner = owner_cache.get();
14821482
if let Some(owner) = owner {
@@ -1504,16 +1504,20 @@ async fn tokio_main() -> Result<()> {
15041504
// Mode-independent: !cancel fires regardless of
15051505
// --multiple-event-handling. It is explicit user
15061506
// intent, not an automatic policy decision.
1507-
let is_cancel = kind_u32 == KIND_STREAM_MESSAGE
1508-
&& buzz_event.event.content.trim() == "!cancel"
1509-
&& buzz_event.event.tags.iter().any(|t| {
1510-
t.as_slice().first().map(|s| s.as_str()) == Some("p")
1511-
&& t.as_slice().get(1).map(|s| s.as_str()) == Some(pubkey_hex.as_str())
1512-
});
1507+
let is_cancel = is_owner_control_command(
1508+
&buzz_event.event,
1509+
kind_u32,
1510+
"!cancel",
1511+
&pubkey_hex,
1512+
);
15131513
if is_cancel {
15141514
if let Some(owner) = owner_cache.get() {
15151515
if buzz_event.event.pubkey.to_hex() == *owner {
1516-
let fired = cancel_in_flight_task(&mut pool, buzz_event.channel_id, CancelMode::Stop);
1516+
let fired = signal_in_flight_task(
1517+
&mut pool,
1518+
buzz_event.channel_id,
1519+
ControlSignal::Cancel,
1520+
);
15171521
if !fired {
15181522
tracing::warn!(
15191523
channel_id = %buzz_event.channel_id,
@@ -1527,6 +1531,53 @@ async fn tokio_main() -> Result<()> {
15271531
}
15281532
// ── End cancel command handling ───────────────────
15291533

1534+
// ── Rotate command handling ─────────────────────
1535+
// Mirrors !shutdown / !cancel: kind:9, content
1536+
// "!rotate", from owner, mentions THIS agent.
1537+
//
1538+
// Rotation is explicit owner intent to start the
1539+
// next turn in this channel with a fresh ACP
1540+
// session. It is consumed by the harness and never
1541+
// forwarded to the agent. If a turn is in-flight,
1542+
// cancel it, drop its triggering batch, and
1543+
// invalidate the channel session when the task
1544+
// returns. If idle, invalidate the cached channel
1545+
// session immediately. Queued future events remain
1546+
// queued and will create a fresh session on dispatch.
1547+
let is_rotate = is_owner_control_command(
1548+
&buzz_event.event,
1549+
kind_u32,
1550+
"!rotate",
1551+
&pubkey_hex,
1552+
);
1553+
if is_rotate {
1554+
if let Some(owner) = owner_cache.get() {
1555+
if buzz_event.event.pubkey.to_hex() == *owner {
1556+
let fired = signal_in_flight_task(
1557+
&mut pool,
1558+
buzz_event.channel_id,
1559+
ControlSignal::Rotate,
1560+
);
1561+
if fired {
1562+
tracing::info!(
1563+
channel_id = %buzz_event.channel_id,
1564+
"!rotate received — cancelling in-flight turn and rotating session"
1565+
);
1566+
} else {
1567+
let invalidated = pool.invalidate_channel_sessions(buzz_event.channel_id);
1568+
tracing::info!(
1569+
channel_id = %buzz_event.channel_id,
1570+
invalidated,
1571+
"!rotate received — invalidated idle channel session(s)"
1572+
);
1573+
}
1574+
continue; // consume event — do NOT push to queue
1575+
}
1576+
}
1577+
// Not from owner — fall through to normal prompt handling.
1578+
}
1579+
// ── End rotate command handling ──────────────────
1580+
15301581
// ── Inbound author gate ──────────────────────────
15311582
// Coarse security policy: drop events from disallowed
15321583
// authors before they reach subscription rules or the
@@ -1608,7 +1659,11 @@ async fn tokio_main() -> Result<()> {
16081659
}
16091660
};
16101661
if should_cancel {
1611-
cancel_in_flight_task(&mut pool, buzz_event.channel_id, CancelMode::Interrupt);
1662+
signal_in_flight_task(
1663+
&mut pool,
1664+
buzz_event.channel_id,
1665+
ControlSignal::Interrupt,
1666+
);
16121667
}
16131668
}
16141669
// ── End mode gate ────────────────────────────────
@@ -1877,20 +1932,44 @@ enum LoopAction {
18771932
Exit,
18781933
}
18791934

1880-
// ── cancel_in_flight_task ─────────────────────────────────────────────────────
1935+
// ── Owner control commands ───────────────────────────────────────────────────
18811936

1882-
/// Send a cancel signal to the in-flight task for `channel_id`.
1937+
fn event_mentions_agent(event: &nostr::Event, agent_pubkey_hex: &str) -> bool {
1938+
event.tags.iter().any(|t| {
1939+
t.as_slice().first().map(|s| s.as_str()) == Some("p")
1940+
&& t.as_slice().get(1).map(|s| s.as_str()) == Some(agent_pubkey_hex)
1941+
})
1942+
}
1943+
1944+
fn is_owner_control_command(
1945+
event: &nostr::Event,
1946+
kind_u32: u32,
1947+
command: &str,
1948+
agent_pubkey_hex: &str,
1949+
) -> bool {
1950+
kind_u32 == KIND_STREAM_MESSAGE
1951+
&& event.content.trim() == command
1952+
&& event_mentions_agent(event, agent_pubkey_hex)
1953+
}
1954+
1955+
// ── signal_in_flight_task ─────────────────────────────────────────────────────
1956+
1957+
/// Send a control signal to the in-flight task for `channel_id`.
18831958
/// Returns `true` if a signal was sent, `false` if no in-flight task was found.
1884-
fn cancel_in_flight_task(pool: &mut AgentPool, channel_id: uuid::Uuid, mode: CancelMode) -> bool {
1959+
fn signal_in_flight_task(
1960+
pool: &mut AgentPool,
1961+
channel_id: uuid::Uuid,
1962+
mode: ControlSignal,
1963+
) -> bool {
18851964
let entry = pool
18861965
.task_map_mut()
18871966
.values_mut()
18881967
.find(|m| m.channel_id == Some(channel_id));
18891968

18901969
if let Some(meta) = entry {
1891-
if let Some(tx) = meta.cancel_tx.take() {
1970+
if let Some(tx) = meta.control_tx.take() {
18921971
let _ = tx.send(mode);
1893-
tracing::info!(channel = %channel_id, "cancel signal sent to in-flight task");
1972+
tracing::info!(channel = %channel_id, ?mode, "control signal sent to in-flight task");
18941973
return true;
18951974
}
18961975
}
@@ -1941,7 +2020,7 @@ fn dispatch_pending(
19412020

19422021
// Prompt text is now built inside run_prompt_task (needs async for
19432022
// context fetching). Pass None for prompt_text; batch carries the data.
1944-
let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<CancelMode>();
2023+
let (control_tx, control_rx) = tokio::sync::oneshot::channel::<ControlSignal>();
19452024

19462025
let abort_handle = pool.join_set.spawn(async move {
19472026
pool::run_prompt_task(
@@ -1950,7 +2029,7 @@ fn dispatch_pending(
19502029
None,
19512030
ctx_clone,
19522031
result_tx,
1953-
Some(cancel_rx),
2032+
Some(control_rx),
19542033
)
19552034
.await;
19562035
});
@@ -1961,7 +2040,7 @@ fn dispatch_pending(
19612040
agent_index,
19622041
channel_id: Some(channel_id),
19632042
recoverable_batch,
1964-
cancel_tx: Some(cancel_tx),
2043+
control_tx: Some(control_tx),
19652044
},
19662045
);
19672046
dispatched_channels.push((channel_id, typing_scope));
@@ -2368,7 +2447,7 @@ fn dispatch_heartbeat(
23682447
agent_index,
23692448
channel_id: None,
23702449
recoverable_batch: None,
2371-
cancel_tx: None,
2450+
control_tx: None,
23722451
},
23732452
);
23742453
*heartbeat_in_flight = true;
@@ -2685,6 +2764,92 @@ fn build_mcp_servers(config: &Config) -> Vec<McpServer> {
26852764

26862765
// ── Tests ─────────────────────────────────────────────────────────────────────
26872766

2767+
#[cfg(test)]
2768+
mod owner_control_command_tests {
2769+
use super::*;
2770+
use nostr::{EventBuilder, Keys, Kind, Tag};
2771+
2772+
fn make_event(kind: u32, content: &str, p_hex: Option<&str>) -> nostr::Event {
2773+
let keys = Keys::generate();
2774+
let tags = match p_hex {
2775+
Some(hex) => vec![Tag::parse(["p", hex]).expect("p tag")],
2776+
None => vec![],
2777+
};
2778+
EventBuilder::new(Kind::Custom(kind as u16), content)
2779+
.tags(tags)
2780+
.sign_with_keys(&keys)
2781+
.unwrap()
2782+
}
2783+
2784+
#[test]
2785+
fn owner_control_command_requires_kind_content_and_agent_mention() {
2786+
let agent = "ab".repeat(32);
2787+
2788+
let event = make_event(KIND_STREAM_MESSAGE, " !rotate ", Some(&agent));
2789+
assert!(is_owner_control_command(
2790+
&event,
2791+
KIND_STREAM_MESSAGE,
2792+
"!rotate",
2793+
&agent
2794+
));
2795+
2796+
let wrong_kind = make_event(1, "!rotate", Some(&agent));
2797+
assert!(!is_owner_control_command(&wrong_kind, 1, "!rotate", &agent));
2798+
2799+
let wrong_content = make_event(KIND_STREAM_MESSAGE, "!cancel", Some(&agent));
2800+
assert!(!is_owner_control_command(
2801+
&wrong_content,
2802+
KIND_STREAM_MESSAGE,
2803+
"!rotate",
2804+
&agent
2805+
));
2806+
2807+
let no_mention = make_event(KIND_STREAM_MESSAGE, "!rotate", None);
2808+
assert!(!is_owner_control_command(
2809+
&no_mention,
2810+
KIND_STREAM_MESSAGE,
2811+
"!rotate",
2812+
&agent
2813+
));
2814+
}
2815+
2816+
#[tokio::test]
2817+
async fn signal_in_flight_task_sends_rotate_once() {
2818+
let mut pool = AgentPool::from_slots(vec![]);
2819+
let channel_id = Uuid::new_v4();
2820+
let other_channel_id = Uuid::new_v4();
2821+
let (control_tx, control_rx) = tokio::sync::oneshot::channel();
2822+
2823+
let abort_handle = pool.join_set.spawn(async {});
2824+
pool.task_map_mut().insert(
2825+
abort_handle.id(),
2826+
pool::TaskMeta {
2827+
agent_index: 0,
2828+
channel_id: Some(channel_id),
2829+
recoverable_batch: None,
2830+
control_tx: Some(control_tx),
2831+
},
2832+
);
2833+
2834+
assert!(!signal_in_flight_task(
2835+
&mut pool,
2836+
other_channel_id,
2837+
ControlSignal::Rotate
2838+
));
2839+
assert!(signal_in_flight_task(
2840+
&mut pool,
2841+
channel_id,
2842+
ControlSignal::Rotate
2843+
));
2844+
assert_eq!(control_rx.await.unwrap(), ControlSignal::Rotate);
2845+
assert!(!signal_in_flight_task(
2846+
&mut pool,
2847+
channel_id,
2848+
ControlSignal::Rotate
2849+
));
2850+
}
2851+
}
2852+
26882853
#[cfg(test)]
26892854
mod owner_cache_tests {
26902855
use super::*;

0 commit comments

Comments
 (0)