Skip to content

Commit d808c4b

Browse files
Duncanwpfleger96
andcommitted
feat(acp): publish kind-9/40003 permission sentinel cards into channel thread
Implements Phase-1 of issue #4938: the harness now publishes kind-9 sentinel cards into the channel thread when a session/request_permission reaches the Ask policy arm, and edits them to resolved state (kind-40003) when the permission concludes. Sentinel publish system (buzz-acp): - Add relay_publisher, agent_relay_keys, agent_owner_pubkey_hex, turn_initiator_pubkey, sentinel_channel_id, sentinel_thread_reply_id fields to AcpClient; wired per-turn from pool.rs and lib.rs. - D7-final admission check: Ask only fires for owner-initiated turns when relay_publisher is present; non-owner turns silently downgrade to reject so no card is posted for unattended sessions. - kind-9 sentinel published after inserting the pending entry; event ID stored in PermissionEntry::sentinel_event_id for the edit. - kind-40003 resolved edit published in finish_permission Ok path; skipped when sentinel_event_id is None (relay-absent sessions). - Both publishes are fire-and-forget; permission flow never blocks on relay acceptance. - publish_event_acked / PublishEventAcked / AckOutcome scaffolding preserved for future acked-publish callers. Label fix (desktop): - describePermissionOutcome: accepts optionLabels (display strings) and optionKinds (for deny/approve verb only) as separate maps; never renders raw ACP kind strings to the user. - describePermissionTerminalReason: builds optionLabels from label ?? name fields; raw kind string falls back to verb-only ("Approved" / "Denied") when no display string is available. - Legacy key path passes empty labels map (verb-only fallback). Documentation (NIP-AO.md): - Permission Sentinel Cards section: kind-9/40003 lifecycle, D7-final admission check, D5 durable-rule disclosure, sentinel authenticity. Tests: - 736 + 9 buzz-acp unit tests pass (sentinel publish skipped via relay_publisher: None in test helpers; D7 gate bypassed when relay_publisher is None). - agentSessionTranscriptPermissions.test.mjs: 12 named tests for describePermissionOutcome and describePermissionTerminalReason. - computePermissionRequest.test.mjs: tests for sentinel card parser. - Updated expectations in agentSessionTranscript.test.mjs and ingestArchivedObserverEvents.test.mjs to match verb-only fallback. Co-authored-by: Will Pfleger <[email protected]> Signed-off-by: Will Pfleger <[email protected]>
1 parent cef78d7 commit d808c4b

11 files changed

Lines changed: 983 additions & 26 deletions

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

Lines changed: 406 additions & 3 deletions
Large diffs are not rendered by default.

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1986,6 +1986,7 @@ async fn tokio_main() -> Result<()> {
19861986
memory_enabled: config.memory_enabled,
19871987
harness_name: crate::config::normalize_agent_command_identity(&config.agent_command),
19881988
relay_url: config.relay_url.clone(),
1989+
relay_event_publisher: Some(relay.event_publisher()),
19891990
});
19901991

19911992
if !config.memory_enabled {

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,11 @@ pub struct PromptContext {
571571
/// the desktop keys per (agent, relay) pair, e.g. `session_config_captured`,
572572
/// mirroring the `managed_agent_runtime_lifecycle` frames.
573573
pub relay_url: String,
574+
/// Publisher for kind-9 sentinel cards and kind-40003 edits.
575+
/// When set, `run_prompt_task` wires it into `AcpClient` so permission
576+
/// cards appear in the channel thread. `None` disables sentinel publishing
577+
/// (observer feed path remains).
578+
pub relay_event_publisher: Option<crate::relay::RelayEventPublisher>,
574579
}
575580

576581
impl AgentPool {
@@ -1437,6 +1442,32 @@ pub async fn run_prompt_task(
14371442
.acp
14381443
.set_owner_pubkey_known(ctx.agent_owner_pubkey.is_some());
14391444

1445+
// Wire sentinel card publisher, agent signing keys, owner pubkey, and
1446+
// per-turn context for D7-final admission and kind-9/40003 publishing.
1447+
if let Some(publisher) = ctx.relay_event_publisher.clone() {
1448+
agent
1449+
.acp
1450+
.set_relay_publisher(publisher, ctx.agent_keys.clone());
1451+
}
1452+
agent
1453+
.acp
1454+
.set_agent_owner_pubkey_hex(ctx.agent_owner_pubkey.as_ref().map(|pk| pk.to_hex()));
1455+
// D7-final: record the turn initiator from the first event in the batch.
1456+
let turn_initiator = batch
1457+
.as_ref()
1458+
.and_then(|b| b.events.first())
1459+
.map(|be| be.event.pubkey);
1460+
agent.acp.set_turn_initiator_pubkey(turn_initiator);
1461+
// Sentinel routing: channel UUID and reply anchor from batch.
1462+
let batch_channel_id = batch.as_ref().map(|b| b.channel_id);
1463+
let thread_reply_event_id = batch
1464+
.as_ref()
1465+
.and_then(|b| b.events.first())
1466+
.map(|be| be.event.id.to_hex());
1467+
agent
1468+
.acp
1469+
.set_turn_channel_context(batch_channel_id, thread_reply_event_id);
1470+
14401471
let triggering_event_ids: Vec<String> = batch
14411472
.as_ref()
14421473
.map(|b| b.events.iter().map(|be| be.event.id.to_hex()).collect())
@@ -6571,6 +6602,7 @@ mod tests {
65716602
memory_enabled: false,
65726603
harness_name: "goose".to_string(),
65736604
relay_url: "ws://127.0.0.1:3000".to_string(),
6605+
relay_event_publisher: None,
65746606
}
65756607
}
65766608

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

Lines changed: 131 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ use buzz_core::kind::{
123123
use futures_util::{SinkExt, StreamExt};
124124
use nostr::{Event, EventBuilder, Keys, Kind, RelayUrl, Tag};
125125
use serde_json::{json, Value};
126-
use tokio::sync::mpsc;
126+
use tokio::sync::{mpsc, oneshot};
127127
use tokio::time::timeout;
128128
use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};
129129
use tracing::{debug, info, warn};
@@ -514,6 +514,22 @@ const MEMBERSHIP_NOTIF_SUB_ID: &str = "membership-notif";
514514
/// Subscription ID for encrypted owner-to-agent observer control frames.
515515
const OBSERVER_CONTROL_SUB_ID: &str = "agent-observer-control";
516516

517+
/// Outcome of a relay-acknowledged event publish.
518+
///
519+
/// Delivered to the caller through the oneshot sender registered by
520+
/// `PublishEventAcked`. The background task resolves the waiter exactly once
521+
/// per event ID — either on `OK`, on socket failure, or on disconnect.
522+
#[derive(Debug)]
523+
#[allow(dead_code)]
524+
pub enum AckOutcome {
525+
/// Relay accepted the event (`OK accepted=true`).
526+
Accepted,
527+
/// Relay rejected the event (`OK accepted=false`).
528+
Rejected { message: String },
529+
/// Connection was lost before an `OK` arrived — delivery is uncertain.
530+
Uncertain,
531+
}
532+
517533
/// Commands sent from `HarnessRelay` to the background WebSocket task.
518534
enum RelayCommand {
519535
/// Subscribe to a channel (sends a NIP-01 REQ) with the given filter.
@@ -534,6 +550,20 @@ enum RelayCommand {
534550
SubscribeObserverControls,
535551
/// Publish a signed event to the relay (for typing indicators, etc.).
536552
PublishEvent { event: Box<Event> },
553+
/// Publish a signed event to the relay and wait for relay `OK`.
554+
///
555+
/// The ack sender is resolved exactly once:
556+
/// - `AckOutcome::Accepted` on `OK accepted=true`
557+
/// - `AckOutcome::Rejected` on `OK accepted=false`
558+
/// - `AckOutcome::Uncertain` on socket failure or disconnect
559+
///
560+
/// The waiter is registered in `BgState::ack_waiters` keyed by event ID
561+
/// **before** the EVENT frame is sent — this is required by the spec.
562+
#[allow(dead_code)]
563+
PublishEventAcked {
564+
event: Box<Event>,
565+
ack_tx: oneshot::Sender<AckOutcome>,
566+
},
537567
/// Floor `since` for membership notification replay; events before startup are never re-delivered.
538568
SetStartupWatermark { ts: u64 },
539569
}
@@ -568,7 +598,9 @@ pub struct HarnessRelay {
568598
bg_handle: Option<tokio::task::JoinHandle<()>>,
569599
}
570600

571-
/// Cloneable publisher handle for signed events on the relay background socket.
601+
/// Thin handle for publishing signed events from outside the relay background task.
602+
///
603+
/// Cheaply cloneable — the underlying `mpsc::Sender` is reference-counted.
572604
#[derive(Clone)]
573605
pub struct RelayEventPublisher {
574606
cmd_tx: mpsc::Sender<RelayCommand>,
@@ -585,18 +617,50 @@ impl RelayEventPublisher {
585617
.map_err(|_| RelayError::ConnectionClosed)
586618
}
587619

620+
/// Publish a signed event and await the relay's `OK` acknowledgement.
621+
///
622+
/// Returns the [`AckOutcome`] once the background task resolves the waiter
623+
/// (on `OK`, socket failure, or disconnect). The waiter is registered by
624+
/// the background task **before** the EVENT frame is sent, satisfying the
625+
/// registration-before-send contract.
626+
///
627+
/// # Errors
628+
/// Returns `RelayError::ConnectionClosed` if the command channel is closed
629+
/// (background task has exited).
630+
#[allow(dead_code)]
631+
pub async fn publish_event_acked(&self, event: Event) -> Result<AckOutcome, RelayError> {
632+
let (ack_tx, ack_rx) = oneshot::channel();
633+
self.cmd_tx
634+
.send(RelayCommand::PublishEventAcked {
635+
event: Box::new(event),
636+
ack_tx,
637+
})
638+
.await
639+
.map_err(|_| RelayError::ConnectionClosed)?;
640+
// If the background task exits without resolving the waiter, treat as uncertain.
641+
Ok(ack_rx.await.unwrap_or(AckOutcome::Uncertain))
642+
}
643+
588644
/// Test-only publisher pair: published events are forwarded to the
589645
/// returned receiver instead of a live relay socket.
590646
#[cfg(test)]
647+
#[allow(clippy::collapsible_match)]
591648
pub(crate) fn test_pair() -> (Self, mpsc::Receiver<Event>) {
592649
let (cmd_tx, mut cmd_rx) = mpsc::channel::<RelayCommand>(64);
593650
let (event_tx, event_rx) = mpsc::channel(64);
594651
tokio::spawn(async move {
595652
while let Some(cmd) = cmd_rx.recv().await {
596-
if let RelayCommand::PublishEvent { event } = cmd {
597-
if event_tx.send(*event).await.is_err() {
598-
break;
653+
match cmd {
654+
RelayCommand::PublishEvent { event } => {
655+
if event_tx.send(*event).await.is_err() {
656+
break;
657+
}
599658
}
659+
RelayCommand::PublishEventAcked { event, ack_tx } => {
660+
let _ = event_tx.send(*event).await;
661+
let _ = ack_tx.send(AckOutcome::Accepted);
662+
}
663+
_ => {}
600664
}
601665
}
602666
});
@@ -1062,6 +1126,11 @@ struct BgState {
10621126
/// Frames evicted from the bounded pending/in-flight observer buffers since
10631127
/// summary log. Makes overflow loss visible instead of silent.
10641128
gated_observer_dropped: u64,
1129+
/// Pending `OK` acknowledgement waiters for `PublishEventAcked` commands.
1130+
///
1131+
/// Keyed by event ID (hex). Registered before the EVENT frame is sent;
1132+
/// resolved exactly once on `OK`, socket failure, or disconnect.
1133+
ack_waiters: HashMap<String, oneshot::Sender<AckOutcome>>,
10651134
/// Channels whose REQ failed during `resubscribe_after_reconnect`.
10661135
///
10671136
/// A single failed channel REQ is parked here instead of aborting the whole
@@ -1097,6 +1166,7 @@ impl BgState {
10971166
gated_observer_pending: VecDeque::new(),
10981167
observer_in_flight: VecDeque::new(),
10991168
gated_observer_dropped: 0,
1169+
ack_waiters: HashMap::new(),
11001170
resubscribe_retry: HashSet::new(),
11011171
backoff_step: 0,
11021172
}
@@ -1225,6 +1295,18 @@ impl BgState {
12251295
}
12261296
}
12271297

1298+
/// Drain all pending `OK` acknowledgement waiters with `Uncertain`.
1299+
///
1300+
/// Called on disconnect/reconnect so callers are not left waiting
1301+
/// indefinitely. A dropped sender (receiver already gone) is silently
1302+
/// discarded.
1303+
fn drain_ack_waiters_uncertain(&mut self) {
1304+
for (event_id, ack_tx) in self.ack_waiters.drain() {
1305+
debug!("ack waiter for event {event_id} drained as uncertain (disconnect)");
1306+
let _ = ack_tx.send(AckOutcome::Uncertain);
1307+
}
1308+
}
1309+
12281310
fn track_observer_in_flight(&mut self, event: Box<Event>) {
12291311
if self.observer_in_flight.len() >= GATED_OBSERVER_QUEUE_CAP {
12301312
self.observer_in_flight.pop_front();
@@ -1304,6 +1386,11 @@ fn apply_command_to_state(state: &mut BgState, cmd: RelayCommand) {
13041386
}
13051387
// Already reconnecting — redundant.
13061388
RelayCommand::Reconnect => {}
1389+
// Acked publish while disconnected: the socket is gone so the event
1390+
// cannot be sent; resolve the waiter as uncertain immediately.
1391+
RelayCommand::PublishEventAcked { ack_tx, .. } => {
1392+
let _ = ack_tx.send(AckOutcome::Uncertain);
1393+
}
13071394
// Callers MUST handle Shutdown before calling this function.
13081395
RelayCommand::Shutdown => {
13091396
debug_assert!(
@@ -1328,6 +1415,11 @@ fn retain_failed_command_intent(state: &mut BgState, cmd: RelayCommand) {
13281415
state.park_gated_observer_frame(event);
13291416
}
13301417
RelayCommand::PublishEvent { .. } => {}
1418+
// Acked publish arrived while disconnected — resolve the waiter as
1419+
// uncertain immediately so the caller is not left waiting.
1420+
RelayCommand::PublishEventAcked { ack_tx, .. } => {
1421+
let _ = ack_tx.send(AckOutcome::Uncertain);
1422+
}
13311423
cmd => apply_command_to_state(state, cmd),
13321424
}
13331425
}
@@ -1531,6 +1623,23 @@ async fn execute_connected_command(
15311623
debug!("startup watermark set to {ts}");
15321624
true
15331625
}
1626+
RelayCommand::PublishEventAcked { event, ack_tx } => {
1627+
// Register the waiter BEFORE sending the EVENT frame — if the relay
1628+
// sends OK before our next select! tick, the waiter must already be
1629+
// present or the resolution is lost.
1630+
let event_id = event.id.to_hex();
1631+
state.ack_waiters.insert(event_id.clone(), ack_tx);
1632+
if send_publish_event_frame(ws, &event).await {
1633+
true
1634+
} else {
1635+
// Send failed — drain the waiter we just registered so the
1636+
// caller is not left waiting indefinitely.
1637+
if let Some(ack_tx) = state.ack_waiters.remove(&event_id) {
1638+
let _ = ack_tx.send(AckOutcome::Uncertain);
1639+
}
1640+
false
1641+
}
1642+
}
15341643
// Control-flow commands — callers handle these before dispatching.
15351644
RelayCommand::Shutdown | RelayCommand::Reconnect => {
15361645
debug_assert!(
@@ -2377,6 +2486,17 @@ async fn handle_ws_message(
23772486
warn!("mid-session AUTH rejected (event {event_id}): {message} — triggering reconnect");
23782487
return false;
23792488
}
2489+
// Resolve any ack waiter registered by PublishEventAcked.
2490+
if let Some(ack_tx) = state.ack_waiters.remove(&event_id) {
2491+
let outcome = if accepted {
2492+
AckOutcome::Accepted
2493+
} else {
2494+
AckOutcome::Rejected {
2495+
message: message.clone(),
2496+
}
2497+
};
2498+
let _ = ack_tx.send(outcome);
2499+
}
23802500
state.acknowledge_observer_frame(&event_id);
23812501
debug!("OK for event {event_id}: accepted={accepted} message={message}");
23822502
}
@@ -2918,6 +3038,9 @@ async fn try_autonomous_reconnect(
29183038
auth_tag: Option<&nostr::Tag>,
29193039
) -> ReconnectOutcome {
29203040
state.requeue_observer_in_flight();
3041+
// Any pending ack waiters cannot be resolved on this socket — drain them
3042+
// as uncertain so callers are not left blocked across the reconnect.
3043+
state.drain_ack_waiters_uncertain();
29213044
// 5 attempts, up to 16s base backoff. Shares delay values with the
29223045
// initial-connect retry in `HarnessRelay::connect()` (STARTUP_CONNECT_BACKOFFS) —
29233046
// see its doc comment for how the two loops consume the array differently.
@@ -3048,6 +3171,9 @@ async fn wait_for_reconnect(
30483171
auth_tag: Option<&nostr::Tag>,
30493172
) -> ReconnectOutcome {
30503173
state.requeue_observer_in_flight();
3174+
// Any pending ack waiters cannot be resolved on this socket — drain them
3175+
// as uncertain so callers are not left blocked across the reconnect.
3176+
state.drain_ack_waiters_uncertain();
30513177
if !skip_drain {
30523178
// Drain commands until we get Reconnect (or Shutdown).
30533179
// Other commands update state so reconnect reflects latest intent.

‎desktop/src/features/agents/ingestArchivedObserverEvents.test.mjs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1015,8 +1015,8 @@ describe("raw-event-level merge: stateful aggregates across live/archive boundar
10151015
// The row must carry the fully-resolved production label.
10161016
assert.equal(
10171017
permRows[0].outcome,
1018-
"Approved (allow_once)",
1019-
"permission row outcome must be the production-shaped label when request+response are in the combined window",
1018+
"Approved",
1019+
"permission row outcome must use verb-only fallback when no harness label flows through the legacy key path",
10201020
);
10211021
});
10221022

‎desktop/src/features/agents/ui/agentSessionTranscript.test.mjs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -776,7 +776,7 @@ test("buildTranscript appends Approved outcome when allow_once is selected", ()
776776
const item = transcript[0];
777777
assert.equal(item.type, "lifecycle");
778778
assert.equal(item.renderClass, "permission");
779-
assert.equal(item.outcome, "Approved (allow_once)");
779+
assert.equal(item.outcome, "Approved");
780780
assert.doesNotMatch(item.text ?? "", /Approved/);
781781
});
782782

@@ -788,7 +788,7 @@ test("buildTranscript appends Denied outcome when reject_once is selected", () =
788788

789789
const item = transcript[0];
790790
assert.equal(item.type, "lifecycle");
791-
assert.equal(item.outcome, "Denied (reject_once)");
791+
assert.equal(item.outcome, "Denied");
792792
assert.doesNotMatch(item.text ?? "", /Denied/);
793793
});
794794

@@ -834,7 +834,7 @@ test("buildTranscript appends Approved outcome for a numeric JSON-RPC id (select
834834
const item = transcript[0];
835835
assert.equal(item.type, "lifecycle");
836836
assert.equal(item.renderClass, "permission");
837-
assert.equal(item.outcome, "Approved (allow_once)");
837+
assert.equal(item.outcome, "Approved");
838838
assert.doesNotMatch(item.text ?? "", /Approved/);
839839
});
840840

@@ -862,8 +862,8 @@ test('buildTranscript does not collide between numeric id 1 and string id "1"',
862862
makePermissionResponse(2, "1", "selected", "reject_once"),
863863
]);
864864

865-
assert.equal(transcriptNumeric[0].outcome, "Approved (allow_once)");
866-
assert.equal(transcriptString[0].outcome, "Denied (reject_once)");
865+
assert.equal(transcriptNumeric[0].outcome, "Approved");
866+
assert.equal(transcriptString[0].outcome, "Denied");
867867
});
868868

869869
// ─── observer parity: new session/update classifier cases ────────────────────

0 commit comments

Comments
 (0)