mirror of
https://github.com/openai/codex.git
synced 2026-11-23 23:10:47 +00:00
Scope Guardian subscriptions to live reviewers (#63357)
## Why Persisted channel subscriptions could route new evidence to an agent before its reviewer started. A replacement reviewer conversation for a still-loaded agent needs to retain the agent's subscriptions and replay its inbox. ## What changed Keep channel subscriptions and queued evidence references in the live reviewer's inbox. Replacement conversations reuse that inbox, and a reviewer that reloads after shutdown starts with an empty inbox and subscription set. Route committed evidence once per matching inbox, even when several channels match. Unsubscribing preserves evidence already selected for delivery, and closing an inbox prevents pending deliveries from reaching a later reviewer for the same agent. Manage subscriptions through the reviewer tools. An exact channel name can be subscribed to before the channel exists, and evidence remains searchable on the message board. ## Testing Cover pending delivery across unsubscribe and reviewer reload, and exercise subscription and delivery behavior with both in-memory and SQLite boards. GitOrigin-RevId: e3dfbcc7c3f34bd509faa24742cf83d9236ef83a
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
//! One isolated verdict conversation per acting agent. Only a completed reusable turn
|
||||
//! returns its conversation to the slot; dropping a reservation retires its thread.
|
||||
//! One inbox and channel selection per live acting agent. Its isolated verdict
|
||||
//! conversation can be retired and replaced while the actor stays loaded.
|
||||
use std::sync::Arc;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::Weak;
|
||||
|
||||
use anyhow::Context;
|
||||
@@ -23,6 +24,7 @@ use crate::RootEvidence;
|
||||
use crate::conversation::Conversation;
|
||||
use crate::host::RootWorker;
|
||||
use crate::inbox::ActorInbox;
|
||||
use crate::inbox::LiveDelivery;
|
||||
use codex_message_board::AgentMessageBoard;
|
||||
|
||||
pub struct ActorReviewer {
|
||||
@@ -31,6 +33,7 @@ pub struct ActorReviewer {
|
||||
actor: ThreadId,
|
||||
path: AgentPath,
|
||||
retrieval: ReviewRetrieval,
|
||||
binding: std::sync::Mutex<Option<Arc<LiveRetrievalBinding>>>,
|
||||
slot: Arc<Mutex<Option<Conversation>>>,
|
||||
lifetime: ReviewerTasks,
|
||||
}
|
||||
@@ -67,6 +70,7 @@ impl ActorReviewer {
|
||||
actor,
|
||||
path,
|
||||
retrieval,
|
||||
binding: Default::default(),
|
||||
slot: Default::default(),
|
||||
lifetime: Default::default(),
|
||||
}
|
||||
@@ -74,10 +78,43 @@ impl ActorReviewer {
|
||||
|
||||
pub(super) async fn shutdown(&self) {
|
||||
self.lifetime.cancellation.cancel();
|
||||
if let Some(binding) = self
|
||||
.binding
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.take()
|
||||
{
|
||||
binding.inbox.close();
|
||||
}
|
||||
self.lifetime.tasks.close();
|
||||
self.lifetime.tasks.wait().await;
|
||||
}
|
||||
|
||||
pub(super) fn binding(
|
||||
&self,
|
||||
board: Arc<dyn AgentMessageBoard>,
|
||||
delivery: &Arc<LiveDelivery>,
|
||||
) -> Result<Arc<LiveRetrievalBinding>, ReviewPreparationError> {
|
||||
let mut current = self.binding.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if self.lifetime.cancellation.is_cancelled() {
|
||||
return Err(ReviewPreparationError::Cancelled);
|
||||
}
|
||||
if let Some(binding) = current.as_ref()
|
||||
&& Arc::ptr_eq(&binding.inbox.delivery, delivery)
|
||||
{
|
||||
return Ok(Arc::clone(binding));
|
||||
}
|
||||
// A reactivated root starts a fresh delivery stream.
|
||||
let binding = Arc::new(
|
||||
LiveRetrievalBinding::new(board, self.actor, self.path.clone(), delivery)
|
||||
.map_err(|_| ReviewPreparationError::EvidenceUnavailable)?,
|
||||
);
|
||||
if let Some(previous) = current.replace(Arc::clone(&binding)) {
|
||||
previous.inbox.close();
|
||||
}
|
||||
Ok(binding)
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "idle delivery and verdicts must have exclusive access to the same reviewer conversation"
|
||||
@@ -127,6 +164,7 @@ impl ActorReviewer {
|
||||
) -> Result<PreparedReviewer, ReviewPreparationError> {
|
||||
let _task = self.lifetime.tasks.token();
|
||||
let reserve = async {
|
||||
let mut slot = self.slot.clone().lock_owned().await;
|
||||
let manager = self
|
||||
.manager
|
||||
.upgrade()
|
||||
@@ -142,36 +180,28 @@ impl ActorReviewer {
|
||||
let evidence = data
|
||||
.get::<RootEvidence>()
|
||||
.ok_or(ReviewPreparationError::EvidenceUnavailable)?;
|
||||
let inbox = evidence.delivery.inbox(self.actor);
|
||||
let mut slot = self.slot.clone().lock_owned().await;
|
||||
let binding = self.binding(Arc::clone(&worker.reader), &evidence.delivery)?;
|
||||
let (mut conversation, kind) = match slot.take() {
|
||||
Some(previous)
|
||||
if Arc::ptr_eq(&previous.inbox, &inbox)
|
||||
if Arc::ptr_eq(&previous.inbox, &binding.inbox)
|
||||
&& setup.matches_session_configuration(&previous.runtime) =>
|
||||
{
|
||||
(previous, GuardianReviewSessionKind::TrunkReused)
|
||||
}
|
||||
_ => {
|
||||
let binding = LiveRetrievalBinding::new(
|
||||
worker.reader.clone(),
|
||||
self.actor,
|
||||
self.path.clone(),
|
||||
)
|
||||
.map_err(|_| ReviewPreparationError::EvidenceUnavailable)?;
|
||||
let stop = self.lifetime.cancellation.child_token();
|
||||
let conversation = Conversation::start(
|
||||
&manager,
|
||||
setup,
|
||||
&self.lifetime,
|
||||
binding,
|
||||
Arc::clone(&inbox),
|
||||
binding.as_ref().clone(),
|
||||
stop.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ReviewPreparationError::ReviewerUnavailable)?;
|
||||
self.observe_inbox(
|
||||
Arc::clone(&worker.reader),
|
||||
&inbox,
|
||||
&binding.inbox,
|
||||
Arc::clone(&conversation.thread),
|
||||
stop,
|
||||
);
|
||||
@@ -201,7 +231,7 @@ impl ActorReviewer {
|
||||
/// One intake request shared by all verdict attempts for the same action.
|
||||
struct BoundActorReview {
|
||||
actor: Arc<ActorReviewer>,
|
||||
routed: tokio::sync::watch::Receiver<Option<Arc<ActorInbox>>>,
|
||||
routed: tokio::sync::watch::Receiver<Option<Arc<LiveDelivery>>>,
|
||||
}
|
||||
|
||||
impl codex_core::guardian_review::AttachedReviewer for ActorReviewer {
|
||||
@@ -218,15 +248,15 @@ impl codex_core::guardian_review::AttachedReviewer for ActorReviewer {
|
||||
.get::<RootEvidence>()
|
||||
.context("Guardian intake unavailable")?;
|
||||
evidence.request_catch_up().await?.await?;
|
||||
anyhow::Ok(evidence.delivery.inbox(actor.actor))
|
||||
anyhow::Ok(Arc::clone(&evidence.delivery))
|
||||
};
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = routed.closed() => (),
|
||||
_ = actor.lifetime.cancellation.cancelled() => (),
|
||||
result = catch_up => {
|
||||
if let Ok(inbox) = result {
|
||||
routed.send_replace(Some(inbox));
|
||||
if let Ok(delivery) = result {
|
||||
routed.send_replace(Some(delivery));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -252,7 +282,7 @@ impl codex_core::guardian_review::ReviewerPreparation for BoundActorReview {
|
||||
> {
|
||||
Box::pin(async move {
|
||||
let mut routed = self.routed.clone();
|
||||
let inbox = tokio::select! {
|
||||
let delivery = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(ReviewPreparationError::Cancelled),
|
||||
_ = setup.history_reset.cancelled() => return Err(ReviewPreparationError::Cancelled),
|
||||
@@ -261,7 +291,7 @@ impl codex_core::guardian_review::ReviewerPreparation for BoundActorReview {
|
||||
// All matching originals through the requested position are queued. The
|
||||
// reservation drains this guardian's inbox before submitting the action.
|
||||
let reviewer = self.actor.reserve(setup, cancel).await?;
|
||||
if !Arc::ptr_eq(&inbox, &reviewer.conversation.inbox) {
|
||||
if !Arc::ptr_eq(&delivery, &reviewer.conversation.inbox.delivery) {
|
||||
return Err(ReviewPreparationError::EvidenceUnavailable);
|
||||
}
|
||||
Ok(Box::new(reviewer) as Box<dyn codex_core::guardian_review::PreparedAssessment>)
|
||||
|
||||
@@ -61,7 +61,6 @@ impl Conversation {
|
||||
prepared: &PreparedGuardianContext,
|
||||
owner: &ReviewerTasks,
|
||||
binding: LiveRetrievalBinding,
|
||||
inbox: Arc<ActorInbox>,
|
||||
stop: CancellationToken,
|
||||
) -> anyhow::Result<Self> {
|
||||
let key = prepared.reuse_key(/*previous*/ None);
|
||||
@@ -84,6 +83,7 @@ impl Conversation {
|
||||
options
|
||||
.thread_extension_init
|
||||
.insert(SessionIsolation::Isolated);
|
||||
let inbox = Arc::clone(&binding.inbox);
|
||||
options.thread_extension_init.insert(binding);
|
||||
options.thread_extension_init.insert(ToolPolicy {
|
||||
allowed_tools: Some(allowed),
|
||||
|
||||
@@ -13,8 +13,6 @@ use codex_history::RetainedUserMessage;
|
||||
use codex_history::RolloutItem;
|
||||
use codex_history::UserInputOrigin;
|
||||
use codex_message_board::SubscriptionChange;
|
||||
use codex_message_board::SubscriptionRequest;
|
||||
use codex_message_board::SubscriptionTarget;
|
||||
use codex_message_board::UpsertChannelRequest;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
@@ -286,7 +284,7 @@ async fn catch_up_waits_for_committed_delivery_and_allows_later_posts(
|
||||
.await?;
|
||||
Ok(original)
|
||||
};
|
||||
// Create the channels through the housekeeper and subscribe through the reviewer's handle.
|
||||
// Create the channels through the housekeeper and subscribe the live reviewer.
|
||||
let _seed_route = mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
@@ -302,19 +300,16 @@ async fn catch_up_waits_for_committed_delivery_and_allows_later_posts(
|
||||
.home()
|
||||
.join("message_board_guardian_1.sqlite");
|
||||
assert_eq!(tokio::fs::try_exists(database).await?, !in_memory);
|
||||
let binding = thread
|
||||
.get::<crate::ActorReviewer>()
|
||||
.context("attached reviewer")?
|
||||
.binding(Arc::clone(board), &evidence.delivery)?;
|
||||
let inbox = &binding.inbox;
|
||||
for channel in ["release", "releases-copy"] {
|
||||
board
|
||||
.set_subscription(
|
||||
root,
|
||||
SubscriptionRequest {
|
||||
target: SubscriptionTarget::Channel(channel.into()),
|
||||
target_agent: None,
|
||||
change: SubscriptionChange::Subscribe,
|
||||
},
|
||||
)
|
||||
inbox
|
||||
.set_subscription(channel.into(), SubscriptionChange::Subscribe)
|
||||
.await?;
|
||||
}
|
||||
let inbox = evidence.delivery.inbox(root);
|
||||
let _first_route = mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
@@ -378,26 +373,22 @@ async fn catch_up_waits_for_committed_delivery_and_allows_later_posts(
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_pending_post_survives_unsubscribe_and_is_admitted_once_per_conversation()
|
||||
-> anyhow::Result<()> {
|
||||
async fn pending_posts_belong_to_the_original_subscriber_inbox() -> anyhow::Result<()> {
|
||||
use crate::EvidenceId;
|
||||
use crate::inbox::ActorInbox;
|
||||
use crate::inbox::LiveDelivery;
|
||||
use codex_message_board::AgentMessageBoard;
|
||||
use codex_guardian_reviewer::ReviewDeadline;
|
||||
use codex_message_board::AppendRequest;
|
||||
use codex_message_board::LocalAgentMessageBoard;
|
||||
use codex_message_board::PostDestination;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::TruncationPolicy;
|
||||
use codex_state::SqliteConfig;
|
||||
use serde_json::json;
|
||||
use std::future::ready;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
let root = ThreadId::new();
|
||||
let directory = tempfile::tempdir()?;
|
||||
let storage = crate::local_board(
|
||||
SqliteConfig::new_for_testing(directory.path().to_path_buf().try_into()?),
|
||||
root.into(),
|
||||
);
|
||||
let subscriber = ThreadId::new();
|
||||
let subscriber_path = AgentPath::root()
|
||||
.join("subscriber")
|
||||
@@ -406,8 +397,13 @@ async fn a_pending_post_survives_unsubscribe_and_is_admitted_once_per_conversati
|
||||
(root, AgentPath::root()),
|
||||
(subscriber, subscriber_path),
|
||||
]);
|
||||
let writer = storage.read_write().open(host.clone()).await?;
|
||||
let reader = storage.read_only().open(host.clone()).await?;
|
||||
let writer = LocalAgentMessageBoard::open_in_memory(
|
||||
&crate::local_board_options(),
|
||||
root.into(),
|
||||
host.clone(),
|
||||
)
|
||||
.await?;
|
||||
let reader = writer.read_only_handle();
|
||||
writer
|
||||
.upsert_channel(
|
||||
root,
|
||||
@@ -417,22 +413,19 @@ async fn a_pending_post_survives_unsubscribe_and_is_admitted_once_per_conversati
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let subscribe = async |actor, change| {
|
||||
reader
|
||||
.set_subscription(
|
||||
actor,
|
||||
SubscriptionRequest {
|
||||
target: SubscriptionTarget::Channel("release".into()),
|
||||
target_agent: None,
|
||||
change,
|
||||
},
|
||||
)
|
||||
let delivery = Arc::new(LiveDelivery::new(root));
|
||||
let inbox = delivery.register(root);
|
||||
let subscribe = async |inbox: &Arc<ActorInbox>| {
|
||||
inbox
|
||||
.set_subscription("release".into(), SubscriptionChange::Subscribe)
|
||||
.await
|
||||
};
|
||||
let cancellation = CancellationToken::new();
|
||||
let append = async |ordinal, text: &str| {
|
||||
writer
|
||||
.append_with_subscribers(
|
||||
root,
|
||||
let mut recipients = crate::inbox::Recipients::default();
|
||||
delivery
|
||||
.append(
|
||||
&writer,
|
||||
AppendRequest {
|
||||
request_id: format!("source-{ordinal}"),
|
||||
destination: PostDestination::Channel("release".into()),
|
||||
@@ -440,46 +433,53 @@ async fn a_pending_post_survives_unsubscribe_and_is_admitted_once_per_conversati
|
||||
&json!({"id":{"ordinal":ordinal}, "original":text}),
|
||||
)?,
|
||||
},
|
||||
&mut recipients,
|
||||
ReviewDeadline::Unlimited,
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::from)
|
||||
.await?;
|
||||
anyhow::Ok(recipients)
|
||||
};
|
||||
|
||||
assert!(append(1, "before subscription").await?.1.is_empty());
|
||||
subscribe(root, SubscriptionChange::Subscribe).await?;
|
||||
let before = append(1, "before subscription").await?;
|
||||
subscribe(&inbox).await?;
|
||||
before.publish(EvidenceId { ordinal: 1 })?;
|
||||
let large = "é".repeat(20_010);
|
||||
let (post, recipients) = append(2, &large).await?;
|
||||
assert_eq!(recipients, [root]);
|
||||
let delivery = LiveDelivery::new(root);
|
||||
delivery.publish(
|
||||
EvidenceId { ordinal: 2 },
|
||||
recipients
|
||||
.into_iter()
|
||||
.map(|actor| (actor, post.message_id))
|
||||
.collect(),
|
||||
)?;
|
||||
// The subscription was already persisted before anyone attached to this inbox.
|
||||
let inbox = delivery.inbox(root);
|
||||
append(2, &large)
|
||||
.await?
|
||||
.publish(EvidenceId { ordinal: 2 })?;
|
||||
let through = inbox.len();
|
||||
assert_eq!(through, 1);
|
||||
let mut wake = inbox.subscribe();
|
||||
subscribe(subscriber, SubscriptionChange::Subscribe).await?;
|
||||
let (second, recipients) = append(3, "later").await?;
|
||||
assert_eq!(recipients.len(), 2);
|
||||
delivery.publish(
|
||||
EvidenceId { ordinal: 3 },
|
||||
recipients
|
||||
.into_iter()
|
||||
.map(|actor| (actor, second.message_id))
|
||||
.collect(),
|
||||
)?;
|
||||
let child_inbox = delivery.register(subscriber);
|
||||
subscribe(&child_inbox).await?;
|
||||
let later = append(3, "later").await?;
|
||||
inbox
|
||||
.set_subscription("release".into(), SubscriptionChange::Unsubscribe)
|
||||
.await?;
|
||||
later.publish(EvidenceId { ordinal: 3 })?;
|
||||
wake.changed().await?;
|
||||
assert_eq!(*wake.borrow_and_update(), 2);
|
||||
assert_eq!(delivery.inbox(subscriber).len(), 1);
|
||||
subscribe(root, SubscriptionChange::Unsubscribe).await?;
|
||||
let (post, recipients) = append(4, "after unsubscribe").await?;
|
||||
assert_eq!(recipients, [subscriber]);
|
||||
assert_eq!(append(4, "after unsubscribe").await?, (post, Vec::new()));
|
||||
assert_eq!(child_inbox.len(), 1);
|
||||
|
||||
// Pause after the append chooses the child, then reload the same child ID.
|
||||
let pending = append(4, "during eviction").await?;
|
||||
child_inbox.close();
|
||||
let reloaded_inbox = delivery.register(subscriber);
|
||||
assert!(
|
||||
reloaded_inbox
|
||||
.subscribed_channels(&Default::default())?
|
||||
.results
|
||||
.is_empty()
|
||||
);
|
||||
subscribe(&reloaded_inbox).await?;
|
||||
pending.publish(EvidenceId { ordinal: 4 })?;
|
||||
assert_eq!(child_inbox.len(), 0);
|
||||
assert_eq!(reloaded_inbox.len(), 0);
|
||||
append(5, "after reload")
|
||||
.await?
|
||||
.publish(EvidenceId { ordinal: 5 })?;
|
||||
assert_eq!(reloaded_inbox.len(), 1);
|
||||
assert!(host.notifications.lock().unwrap().is_empty());
|
||||
|
||||
let mut delivered = 0;
|
||||
|
||||
@@ -29,7 +29,6 @@ use serde::Serialize;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashMap;
|
||||
use std::num::NonZeroU32;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -246,16 +245,13 @@ impl Housekeeper {
|
||||
anyhow::anyhow!("upserting housekeeper channel: {reason:?}")
|
||||
})??;
|
||||
}
|
||||
// The local board finishes an accepted append in its own task. Await it even
|
||||
// during shutdown so the root joins the last write before releasing this worker.
|
||||
for ((source, destinations), mut text) in sources.iter().zip(output.routes).zip(texts) {
|
||||
let mut recipients = HashMap::new();
|
||||
let mut recipients = crate::inbox::Recipients::default();
|
||||
let mut remaining: BTreeSet<_> = destinations.iter().collect();
|
||||
for channel in &destinations {
|
||||
if !remaining.remove(channel) {
|
||||
continue;
|
||||
}
|
||||
check_active(deadline, cancellation)?;
|
||||
let request = AppendRequest {
|
||||
request_id: source.id.request_id(channel)?,
|
||||
destination: PostDestination::Channel(channel.clone()),
|
||||
@@ -266,15 +262,17 @@ impl Housekeeper {
|
||||
text.clone()
|
||||
},
|
||||
};
|
||||
let (post, subscribers) = self
|
||||
.board
|
||||
.append_with_subscribers(self.owner, request)
|
||||
self.delivery
|
||||
.append(
|
||||
self.board.as_ref(),
|
||||
request,
|
||||
&mut recipients,
|
||||
deadline,
|
||||
cancellation,
|
||||
)
|
||||
.await?;
|
||||
for actor in subscribers {
|
||||
recipients.entry(actor).or_insert(post.message_id);
|
||||
}
|
||||
}
|
||||
self.delivery.publish(source.id, recipients)?;
|
||||
recipients.publish(source.id)?;
|
||||
}
|
||||
// Acknowledge only after every write succeeds. Returned errors leave this batch
|
||||
// unread and stop this instance; no replay is attempted.
|
||||
@@ -314,7 +312,10 @@ fn routing_schema(source_count: usize) -> serde_json::Value {
|
||||
})
|
||||
}
|
||||
|
||||
fn check_active(deadline: ReviewDeadline, cancellation: &CancellationToken) -> anyhow::Result<()> {
|
||||
pub(super) fn check_active(
|
||||
deadline: ReviewDeadline,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
ensure!(!cancellation.is_cancelled(), "housekeeping cancelled");
|
||||
ensure!(
|
||||
!matches!(deadline, ReviewDeadline::At(at) if Instant::now() >= at),
|
||||
|
||||
@@ -1,91 +1,217 @@
|
||||
//! Deliver committed posts to the actors subscribed when each post was written. An inbox
|
||||
//! retains only board references; each live or replacement reviewer owns its admission cursor.
|
||||
//! Each acting agent's reviewer owns its channel subscriptions and inbox of post IDs.
|
||||
//! Replacement model conversations replay the inbox with their own admission cursor.
|
||||
|
||||
use crate::EvidenceId;
|
||||
use crate::GUARDIAN_BOARD_NAMESPACE;
|
||||
use crate::delivery::evidence_batch;
|
||||
use anyhow::ensure;
|
||||
use codex_guardian_reviewer::ReviewDeadline;
|
||||
use codex_guardian_reviewer::run_before_review_deadline;
|
||||
use codex_message_board::AgentMessageBoard;
|
||||
use codex_message_board::AppendRequest;
|
||||
use codex_message_board::Page;
|
||||
use codex_message_board::PageRequest;
|
||||
use codex_message_board::SubscriptionChange;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::TruncationPolicy;
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::MutexGuard;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::Weak;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::sync::watch;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Subscriber inboxes for originals routed by one root thread's housekeeper.
|
||||
type Subscribers = HashMap<String, HashMap<Uuid, Weak<ActorInbox>>>;
|
||||
|
||||
/// Routes one root's posts to live reviewers, indexed by channel and inbox identity.
|
||||
pub struct LiveDelivery {
|
||||
pub(super) root: ThreadId,
|
||||
actors: Mutex<HashMap<ThreadId, Arc<ActorInbox>>>,
|
||||
subscribers: Mutex<Subscribers>,
|
||||
// Keep membership changes from landing between an append and recipient capture.
|
||||
posting: RwLock<()>,
|
||||
}
|
||||
|
||||
impl LiveDelivery {
|
||||
pub fn new(root: ThreadId) -> Self {
|
||||
Self {
|
||||
root,
|
||||
actors: Mutex::default(),
|
||||
subscribers: Mutex::default(),
|
||||
posting: RwLock::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A persisted subscription can receive a post before the actor's reviewer starts.
|
||||
pub(super) fn inbox(&self, actor: ThreadId) -> Arc<ActorInbox> {
|
||||
self.actors
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.entry(actor)
|
||||
.or_insert_with(|| {
|
||||
Arc::new(ActorInbox {
|
||||
root: self.root,
|
||||
actor,
|
||||
posts: Mutex::default(),
|
||||
length: watch::Sender::new(0),
|
||||
})
|
||||
})
|
||||
.clone()
|
||||
pub(super) fn register(self: &Arc<Self>, actor: ThreadId) -> Arc<ActorInbox> {
|
||||
Arc::new(ActorInbox {
|
||||
id: Uuid::now_v7(),
|
||||
delivery: Arc::clone(self),
|
||||
actor,
|
||||
state: Mutex::new(Some(InboxState::default())),
|
||||
length: watch::Sender::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
/// Single root writer: all destinations for this original have committed. Each
|
||||
/// recipient occurs once even when several matching channels got the same original.
|
||||
pub(super) fn publish(
|
||||
fn subscribers(&self) -> MutexGuard<'_, Subscribers> {
|
||||
self.subscribers
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "serialize each append and recipient capture with subscription changes"
|
||||
)]
|
||||
pub(super) async fn append(
|
||||
&self,
|
||||
id: EvidenceId,
|
||||
recipients: HashMap<ThreadId, Uuid>,
|
||||
board: &dyn AgentMessageBoard,
|
||||
request: AppendRequest,
|
||||
recipients: &mut Recipients,
|
||||
deadline: ReviewDeadline,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
for (actor, post) in recipients {
|
||||
let inbox = self.inbox(actor);
|
||||
let mut posts = inbox.posts.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let _guard = run_before_review_deadline(deadline, Some(cancellation), self.posting.write())
|
||||
.await
|
||||
.map_err(|reason| anyhow::anyhow!("waiting to append evidence: {reason:?}"))?;
|
||||
crate::housekeeper::check_active(deadline, cancellation)?;
|
||||
// The housekeeper appends each original once per channel and stops on failure.
|
||||
// Await the accepted write even if the housekeeper is shutting down.
|
||||
let post = board.append(self.root, request).await?;
|
||||
if let Some(subscribers) = self.subscribers().get(&post.channel_name) {
|
||||
for (id, inbox) in subscribers {
|
||||
recipients
|
||||
.0
|
||||
.entry(*id)
|
||||
.or_insert_with(|| (inbox.clone(), post.message_id));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One post reference per live inbox, even when several channels matched the original.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Recipients(HashMap<Uuid, (Weak<ActorInbox>, Uuid)>);
|
||||
|
||||
impl Recipients {
|
||||
/// Only publish after all destinations commit. A queued delivery belongs to the
|
||||
/// original inbox even if the same agent has since loaded a fresh reviewer.
|
||||
pub(super) fn publish(self, id: EvidenceId) -> anyhow::Result<()> {
|
||||
for (inbox, post) in self.0.into_values() {
|
||||
let Some(inbox) = inbox.upgrade() else {
|
||||
continue;
|
||||
};
|
||||
let mut state = inbox.state();
|
||||
let Some(state) = state.as_mut() else {
|
||||
continue;
|
||||
};
|
||||
ensure!(
|
||||
posts.last().is_none_or(|(last, _)| *last < id.ordinal),
|
||||
state
|
||||
.posts
|
||||
.last()
|
||||
.is_none_or(|(last, _)| *last < id.ordinal),
|
||||
"Guardian inbox received evidence out of source order"
|
||||
);
|
||||
posts.push((id.ordinal, post));
|
||||
let len = posts.len();
|
||||
drop(posts);
|
||||
inbox.length.send_replace(len);
|
||||
state.posts.push((id.ordinal, post));
|
||||
inbox.length.send_replace(state.posts.len());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct ActorInbox {
|
||||
root: ThreadId,
|
||||
actor: ThreadId,
|
||||
posts: Mutex<Vec<(u64, Uuid)>>,
|
||||
id: Uuid,
|
||||
pub(super) delivery: Arc<LiveDelivery>,
|
||||
pub(super) actor: ThreadId,
|
||||
// None once the owning ActorReviewer has shut down.
|
||||
state: Mutex<Option<InboxState>>,
|
||||
length: watch::Sender<usize>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct InboxState {
|
||||
channels: BTreeSet<String>,
|
||||
posts: Vec<(u64, Uuid)>,
|
||||
}
|
||||
|
||||
impl Drop for ActorInbox {
|
||||
fn drop(&mut self) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
fn unsubscribe(subscribers: &mut Subscribers, channel: &str, id: Uuid) {
|
||||
if let Some(members) = subscribers.get_mut(channel) {
|
||||
members.remove(&id);
|
||||
if members.is_empty() {
|
||||
subscribers.remove(channel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ActorInbox {
|
||||
fn state(&self) -> MutexGuard<'_, Option<InboxState>> {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
pub(super) fn close(&self) {
|
||||
let Some(state) = self.state().take() else {
|
||||
return;
|
||||
};
|
||||
self.length.send_replace(0);
|
||||
let mut subscribers = self.delivery.subscribers();
|
||||
for channel in state.channels {
|
||||
unsubscribe(&mut subscribers, &channel, self.id);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn subscribed_channels(&self, page: &PageRequest) -> CodexResult<Page<String>> {
|
||||
let state = self.state();
|
||||
let state = state.as_ref().ok_or(CodexErr::ThreadNotFound(self.actor))?;
|
||||
codex_message_board::paginate(page, state.channels.iter().cloned())
|
||||
}
|
||||
|
||||
pub(super) async fn set_subscription(
|
||||
self: &Arc<Self>,
|
||||
channel: String,
|
||||
change: SubscriptionChange,
|
||||
) -> CodexResult<()> {
|
||||
if change == SubscriptionChange::Subscribe {
|
||||
codex_message_board::validate_channel(&channel)?;
|
||||
}
|
||||
let _guard = self.delivery.posting.read().await;
|
||||
let mut state = self.state();
|
||||
let state = state.as_mut().ok_or(CodexErr::ThreadNotFound(self.actor))?;
|
||||
let mut subscribers = self.delivery.subscribers();
|
||||
match change {
|
||||
SubscriptionChange::Subscribe => {
|
||||
state.channels.insert(channel.clone());
|
||||
subscribers
|
||||
.entry(channel)
|
||||
.or_default()
|
||||
.insert(self.id, Arc::downgrade(self));
|
||||
}
|
||||
SubscriptionChange::Unsubscribe => {
|
||||
state.channels.remove(&channel);
|
||||
unsubscribe(&mut subscribers, &channel, self.id);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn queued_posts(&self) -> Vec<(u64, Uuid)> {
|
||||
self.posts
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.clone()
|
||||
self.state()
|
||||
.as_ref()
|
||||
.map(|state| state.posts.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) fn subscribe(&self) -> watch::Receiver<usize> {
|
||||
@@ -113,7 +239,7 @@ impl ActorInbox {
|
||||
{
|
||||
ensure!(
|
||||
actor == self.actor
|
||||
&& board.identity() == self.root.into()
|
||||
&& board.identity() == self.delivery.root.into()
|
||||
&& board.storage_namespace() == Some(GUARDIAN_BOARD_NAMESPACE),
|
||||
"Guardian inbox opened with the wrong board or caller"
|
||||
);
|
||||
@@ -125,8 +251,12 @@ impl ActorInbox {
|
||||
while *delivered < through {
|
||||
let start = *delivered;
|
||||
let end = through.min(start.saturating_add(page_size));
|
||||
let positions =
|
||||
self.posts.lock().unwrap_or_else(PoisonError::into_inner)[start..end].to_vec();
|
||||
let positions = self
|
||||
.state()
|
||||
.as_ref()
|
||||
.ok_or(CodexErr::ThreadNotFound(self.actor))?
|
||||
.posts[start..end]
|
||||
.to_vec();
|
||||
let ids: Vec<_> = positions.iter().map(|(_, id)| *id).collect();
|
||||
let texts = board.read_post_texts_by_id(actor, &ids).await?;
|
||||
ensure!(
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Guardian's durable evidence storage, owned by the main thread.
|
||||
//! The housekeeper routes originals to topic channels. Each reviewer searches the live board
|
||||
//! and manages its own subscriptions.
|
||||
//! The main thread owns Guardian's evidence board. The housekeeper routes originals to
|
||||
//! topic channels. Each live reviewer owns its subscriptions and inbox in memory.
|
||||
//! Hosts invoke permanent-deletion cleanup only when Guardian V3 is enabled.
|
||||
|
||||
#![recursion_limit = "256"]
|
||||
@@ -67,9 +66,8 @@ pub fn local_board_options() -> LocalBoardOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects the board for the owning main thread, never the temporary reviewer or housekeeper.
|
||||
/// Hosts use a read-write connection; reviewers use a read-only connection, which still
|
||||
/// permits their own explicit subscriptions. Cleanup uses the same namespace and root identity.
|
||||
/// Selects the owning main thread's board. The housekeeper uses a read-write connection
|
||||
/// and reviewers use read-only connections. Cleanup uses the same namespace and root identity.
|
||||
pub fn local_board(sqlite: SqliteConfig, root: SessionId) -> LocalBoard {
|
||||
LocalBoard::new(sqlite, root).with_options(local_board_options())
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Reviewer tools for searching live evidence and managing the acting agent’s subscriptions.
|
||||
use crate::GUARDIAN_BOARD_NAMESPACE;
|
||||
use crate::LiveDelivery;
|
||||
use crate::inbox::ActorInbox;
|
||||
use anyhow::ensure;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
@@ -17,13 +19,12 @@ use std::sync::Arc;
|
||||
const NAMESPACE: &str = "guardian_board";
|
||||
const JSON_ARGUMENTS: &str = "/original/payload/arguments";
|
||||
const LIVE_DESCRIPTION: &str = "Live original evidence by topic. Search and read any channel. Subscribe to receive future evidence from that channel.";
|
||||
const LIVE_READ_TOOLS: [MessageBoardTool; 6] = [
|
||||
const LIVE_READ_TOOLS: [MessageBoardTool; 5] = [
|
||||
MessageBoardTool::GetChannels,
|
||||
MessageBoardTool::ListThreads,
|
||||
MessageBoardTool::SearchPosts,
|
||||
MessageBoardTool::ReadThread,
|
||||
MessageBoardTool::ReadPost,
|
||||
MessageBoardTool::SubscribedChannels,
|
||||
];
|
||||
|
||||
struct RetrievalTools;
|
||||
@@ -32,23 +33,29 @@ struct RetrievalTools;
|
||||
#[derive(Clone)]
|
||||
pub struct LiveRetrievalBinding {
|
||||
board: Arc<dyn AgentMessageBoard>,
|
||||
caller: ThreadId,
|
||||
pub(super) inbox: Arc<ActorInbox>,
|
||||
path: AgentPath,
|
||||
}
|
||||
|
||||
impl LiveRetrievalBinding {
|
||||
/// Register a fresh reviewer inbox. Clone this binding to reuse its subscriptions.
|
||||
pub fn new(
|
||||
board: Arc<dyn AgentMessageBoard>,
|
||||
caller: ThreadId,
|
||||
path: AgentPath,
|
||||
delivery: &Arc<LiveDelivery>,
|
||||
) -> anyhow::Result<Self> {
|
||||
ensure!(
|
||||
board.storage_namespace() == Some(GUARDIAN_BOARD_NAMESPACE),
|
||||
"reviewer retrieval requires a Guardian board"
|
||||
);
|
||||
ensure!(
|
||||
board.identity() == delivery.root.into(),
|
||||
"reviewer retrieval requires the inbox's board"
|
||||
);
|
||||
Ok(Self {
|
||||
board: board.with_json_search(JSON_ARGUMENTS)?,
|
||||
caller,
|
||||
inbox: delivery.register(caller),
|
||||
path,
|
||||
})
|
||||
}
|
||||
@@ -57,25 +64,25 @@ impl LiveRetrievalBinding {
|
||||
pub fn tool_names() -> impl Iterator<Item = ToolName> {
|
||||
LIVE_READ_TOOLS
|
||||
.into_iter()
|
||||
.chain([MessageBoardTool::Subscribe, MessageBoardTool::Unsubscribe])
|
||||
.map(|tool| ToolName::namespaced(NAMESPACE, tool.name()))
|
||||
.map(MessageBoardTool::name)
|
||||
.chain(crate::subscription_tools::names())
|
||||
.map(|name| ToolName::namespaced(NAMESPACE, name))
|
||||
}
|
||||
|
||||
pub fn tools(&self) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
let mut tools = message_board_tools(
|
||||
&LIVE_READ_TOOLS,
|
||||
self.board.clone(),
|
||||
self.caller,
|
||||
self.inbox.actor,
|
||||
self.path.clone(),
|
||||
Some(NAMESPACE),
|
||||
LIVE_DESCRIPTION,
|
||||
/*tool_messages*/ None,
|
||||
);
|
||||
tools.extend(crate::subscription_tools::tools(
|
||||
&self.board,
|
||||
self.caller,
|
||||
&self.inbox,
|
||||
&self.path,
|
||||
Some(NAMESPACE),
|
||||
NAMESPACE,
|
||||
LIVE_DESCRIPTION,
|
||||
));
|
||||
tools
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
//! Reviewer tools that change only the caller’s live channel subscriptions.
|
||||
//! Reviewer tools for listing and changing the caller's live channel subscriptions.
|
||||
|
||||
use codex_message_board::AgentMessageBoard;
|
||||
use crate::inbox::ActorInbox;
|
||||
use codex_message_board::MAX_TOOL_ARGUMENT_KIB;
|
||||
use codex_message_board::MAX_TOOL_RESPONSE_BYTES;
|
||||
use codex_message_board::MessageBoardTool;
|
||||
use codex_message_board::Page;
|
||||
use codex_message_board::PageRequest;
|
||||
use codex_message_board::SubscriptionChange;
|
||||
use codex_message_board::SubscriptionRequest;
|
||||
use codex_message_board::SubscriptionState;
|
||||
use codex_message_board::SubscriptionTarget;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_tools::FunctionCallError;
|
||||
use codex_tools::JsonToolOutput;
|
||||
use codex_tools::ResponsesApiNamespace;
|
||||
@@ -20,70 +18,101 @@ use codex_tools::ToolExecutorFuture;
|
||||
use codex_tools::ToolName;
|
||||
use codex_tools::ToolSpec;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::num::NonZeroU32;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Arguments {
|
||||
struct ChangeArguments {
|
||||
channel_name: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ListArguments {
|
||||
limit: Option<NonZeroU32>,
|
||||
cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Operation {
|
||||
List,
|
||||
Change(SubscriptionChange),
|
||||
}
|
||||
|
||||
const TOOLS: [(&str, &str, Operation); 3] = [
|
||||
(
|
||||
"subscribed_channels",
|
||||
"List the names of channels you are currently subscribed to.",
|
||||
Operation::List,
|
||||
),
|
||||
(
|
||||
"subscribe",
|
||||
"Subscribe yourself to new evidence by exact channel name, even before the channel exists. Search or read earlier posts separately.",
|
||||
Operation::Change(SubscriptionChange::Subscribe),
|
||||
),
|
||||
(
|
||||
"unsubscribe",
|
||||
"Stop receiving new evidence from this channel. Evidence already admitted to the reviewer conversation is retained.",
|
||||
Operation::Change(SubscriptionChange::Unsubscribe),
|
||||
),
|
||||
];
|
||||
|
||||
pub(super) fn names() -> impl Iterator<Item = &'static str> {
|
||||
TOOLS.into_iter().map(|(name, _, _)| name)
|
||||
}
|
||||
|
||||
struct SubscriptionTool {
|
||||
board: Arc<dyn AgentMessageBoard>,
|
||||
caller: ThreadId,
|
||||
inbox: Arc<ActorInbox>,
|
||||
path: AgentPath,
|
||||
change: SubscriptionChange,
|
||||
operation: Operation,
|
||||
name: ToolName,
|
||||
spec: ToolSpec,
|
||||
}
|
||||
|
||||
pub(crate) fn tools(
|
||||
board: &Arc<dyn AgentMessageBoard>,
|
||||
caller: ThreadId,
|
||||
pub(super) fn tools(
|
||||
inbox: &Arc<ActorInbox>,
|
||||
path: &AgentPath,
|
||||
namespace: Option<&str>,
|
||||
namespace: &str,
|
||||
namespace_description: &str,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
[
|
||||
(MessageBoardTool::Subscribe, SubscriptionChange::Subscribe),
|
||||
(MessageBoardTool::Unsubscribe, SubscriptionChange::Unsubscribe),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(tool, change)| {
|
||||
let ToolSpec::Function(mut function) = tool.spec() else {
|
||||
unreachable!("shared subscription specs are functions")
|
||||
};
|
||||
function
|
||||
.parameters
|
||||
.properties
|
||||
.get_or_insert_default()
|
||||
.retain(|name, _| name == "channel_name");
|
||||
function.parameters.required = Some(vec!["channel_name".into()].into_boxed_slice());
|
||||
function.description = match change {
|
||||
SubscriptionChange::Subscribe => "Subscribe yourself to new evidence in this channel. Search or read its earlier posts separately.",
|
||||
SubscriptionChange::Unsubscribe => "Stop receiving new evidence from this channel. Evidence already admitted to the reviewer conversation is retained.",
|
||||
}
|
||||
.into();
|
||||
let name = ToolName::new(namespace.map(str::to_owned), function.name.clone());
|
||||
let spec = match namespace {
|
||||
Some(namespace) => ToolSpec::Namespace(ResponsesApiNamespace {
|
||||
) -> impl Iterator<Item = Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
TOOLS
|
||||
.into_iter()
|
||||
.map(move |(name, description, operation)| {
|
||||
// Use the board's argument schemas for pagination and channel names.
|
||||
let (template, fields): (_, &[&str]) = match operation {
|
||||
Operation::List => (MessageBoardTool::GetChannels, &["limit", "cursor"]),
|
||||
Operation::Change(_) => (MessageBoardTool::Subscribe, &["channel_name"]),
|
||||
};
|
||||
let ToolSpec::Function(mut function) = template.spec() else {
|
||||
unreachable!("board tool specs are functions")
|
||||
};
|
||||
function
|
||||
.parameters
|
||||
.properties
|
||||
.get_or_insert_default()
|
||||
.retain(|name, _| fields.contains(&name.as_str()));
|
||||
if matches!(operation, Operation::Change(_)) {
|
||||
function.parameters.required = Some(vec!["channel_name".into()].into_boxed_slice());
|
||||
}
|
||||
function.name = name.into();
|
||||
function.description = description.into();
|
||||
let name = ToolName::namespaced(namespace, name);
|
||||
let spec = ToolSpec::Namespace(ResponsesApiNamespace {
|
||||
name: namespace.into(),
|
||||
description: namespace_description.into(),
|
||||
tools: vec![ResponsesApiNamespaceTool::Function(function)],
|
||||
}),
|
||||
None => ToolSpec::Function(function),
|
||||
};
|
||||
Arc::new(SubscriptionTool {
|
||||
board: Arc::clone(board),
|
||||
caller,
|
||||
path: path.clone(),
|
||||
change,
|
||||
name,
|
||||
spec,
|
||||
}) as Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
Arc::new(SubscriptionTool {
|
||||
inbox: Arc::clone(inbox),
|
||||
path: path.clone(),
|
||||
operation,
|
||||
name,
|
||||
spec,
|
||||
}) as Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>
|
||||
})
|
||||
}
|
||||
|
||||
impl<'call> ToolExecutor<ToolCall<'call>> for SubscriptionTool {
|
||||
@@ -95,6 +124,10 @@ impl<'call> ToolExecutor<ToolCall<'call>> for SubscriptionTool {
|
||||
self.spec.clone()
|
||||
}
|
||||
|
||||
fn supports_parallel_tool_calls(&self) -> bool {
|
||||
matches!(self.operation, Operation::List)
|
||||
}
|
||||
|
||||
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
|
||||
where
|
||||
'call: 'a,
|
||||
@@ -106,40 +139,12 @@ impl<'call> ToolExecutor<ToolCall<'call>> for SubscriptionTool {
|
||||
"subscription arguments exceed {MAX_TOOL_ARGUMENT_KIB} KiB"
|
||||
)));
|
||||
}
|
||||
let arguments: Arguments = serde_json::from_str(raw)
|
||||
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
|
||||
// For live subscriptions the last post ID is known only after the write.
|
||||
// Budget for a full UUID to avoid accepting a mutation we cannot acknowledge.
|
||||
let largest_response = SubscriptionState {
|
||||
channel_name: arguments.channel_name.clone(),
|
||||
thread_id: None,
|
||||
target_agent: self.path.clone(),
|
||||
enabled: self.change == SubscriptionChange::Subscribe,
|
||||
last_message_id: Some(Uuid::nil()),
|
||||
let budget = call.response_byte_budget(MAX_TOOL_RESPONSE_BYTES);
|
||||
let response = match self.operation {
|
||||
Operation::List => serde_json::to_value(self.list(raw, budget)?)
|
||||
.map_err(|error| FunctionCallError::Fatal(error.to_string()))?,
|
||||
Operation::Change(change) => self.change(raw, change, budget).await?,
|
||||
};
|
||||
if serde_json::to_vec(&largest_response)
|
||||
.map_err(|error| FunctionCallError::Fatal(error.to_string()))?
|
||||
.len()
|
||||
> call.response_byte_budget(MAX_TOOL_RESPONSE_BYTES)
|
||||
{
|
||||
return Err(FunctionCallError::RespondToModel(
|
||||
"subscription response exceeds the tool-output budget".into(),
|
||||
));
|
||||
}
|
||||
let state = self
|
||||
.board
|
||||
.set_subscription(
|
||||
self.caller,
|
||||
SubscriptionRequest {
|
||||
target: SubscriptionTarget::Channel(arguments.channel_name),
|
||||
target_agent: None,
|
||||
change: self.change,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
|
||||
let response = serde_json::to_value(state)
|
||||
.map_err(|error| FunctionCallError::Fatal(error.to_string()))?;
|
||||
Ok(
|
||||
Box::new(JsonToolOutput::new(response).with_external_context())
|
||||
as Box<dyn codex_tools::ToolOutput>,
|
||||
@@ -147,3 +152,56 @@ impl<'call> ToolExecutor<ToolCall<'call>> for SubscriptionTool {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn list_error(error: impl std::fmt::Display) -> FunctionCallError {
|
||||
FunctionCallError::RespondToModel(error.to_string().chars().take(512).collect())
|
||||
}
|
||||
|
||||
impl SubscriptionTool {
|
||||
fn list(&self, raw: &str, budget: usize) -> Result<Page<String>, FunctionCallError> {
|
||||
let ListArguments { limit, cursor } = serde_json::from_str(raw).map_err(list_error)?;
|
||||
let mut request = PageRequest {
|
||||
limit: limit.unwrap_or(PageRequest::default().limit),
|
||||
cursor,
|
||||
};
|
||||
loop {
|
||||
let page = self
|
||||
.inbox
|
||||
.subscribed_channels(&request)
|
||||
.map_err(list_error)?;
|
||||
if serde_json::to_vec(&page).map_err(list_error)?.len() <= budget {
|
||||
return Ok(page);
|
||||
}
|
||||
// Re-page from the same cursor so next_cursor follows the last returned name.
|
||||
request.limit = NonZeroU32::new(page.results.len() as u32 / 2).ok_or_else(|| {
|
||||
list_error("The output budget is too small for this result's metadata.")
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
async fn change(
|
||||
&self,
|
||||
raw: &str,
|
||||
change: SubscriptionChange,
|
||||
budget: usize,
|
||||
) -> Result<Value, FunctionCallError> {
|
||||
let ChangeArguments { channel_name } = serde_json::from_str(raw)
|
||||
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
|
||||
let response = json!({
|
||||
"channel_name": channel_name,
|
||||
"thread_id": null,
|
||||
"target_agent": self.path,
|
||||
"enabled": change == SubscriptionChange::Subscribe,
|
||||
});
|
||||
if response.to_string().len() > budget {
|
||||
return Err(FunctionCallError::RespondToModel(
|
||||
"subscription response exceeds the tool-output budget".into(),
|
||||
));
|
||||
}
|
||||
self.inbox
|
||||
.set_subscription(channel_name, change)
|
||||
.await
|
||||
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Invoke tools through the same bindings installed in Guardian reviewer threads.
|
||||
|
||||
use anyhow::Context;
|
||||
use codex_guardian_v3::LiveRetrievalBinding;
|
||||
use codex_protocol::openai_models::TruncationPolicyConfig;
|
||||
use codex_tools::ToolCall;
|
||||
use codex_tools::ToolCallSource;
|
||||
use codex_tools::ToolName;
|
||||
use codex_tools::ToolPayload;
|
||||
use serde_json::Value;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(crate) async fn invoke(
|
||||
binding: &LiveRetrievalBinding,
|
||||
name: &str,
|
||||
arguments: Value,
|
||||
) -> anyhow::Result<Value> {
|
||||
let tool = binding
|
||||
.tools()
|
||||
.into_iter()
|
||||
.find(|tool| tool.tool_name().name == name)
|
||||
.with_context(|| format!("missing reviewer tool {name}"))?;
|
||||
let call = reviewer_tool_call(&tool.tool_name(), &arguments, /*byte_limit*/ 8_000);
|
||||
let result = tool.handle(call.clone()).await?;
|
||||
Ok(result.code_mode_result(&call.payload))
|
||||
}
|
||||
|
||||
pub(crate) fn reviewer_tool_call(
|
||||
name: &ToolName,
|
||||
arguments: &Value,
|
||||
byte_limit: i64,
|
||||
) -> ToolCall<'static> {
|
||||
ToolCall {
|
||||
turn_id: "review".into(),
|
||||
call_id: name.name.clone(),
|
||||
tool_name: name.clone(),
|
||||
model: "test".into(),
|
||||
codex_turn_metadata: None,
|
||||
truncation_policy: TruncationPolicyConfig::bytes(byte_limit).into(),
|
||||
source: ToolCallSource::Direct,
|
||||
conversation_history: Default::default(),
|
||||
turn_item_emitter: Arc::new(codex_tools::NoopTurnItemEmitter),
|
||||
attachment_store: Arc::new(codex_attachment_store::InlineAttachmentStore),
|
||||
ephemeral: false,
|
||||
environments: Vec::new(),
|
||||
payload: ToolPayload::Function {
|
||||
arguments: arguments.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,9 @@ use tokio_util::sync::CancellationToken;
|
||||
#[path = "common/board_host.rs"]
|
||||
mod board_host;
|
||||
|
||||
#[path = "common/reviewer_tool_call.rs"]
|
||||
mod reviewer_tool_call;
|
||||
|
||||
use board_host::PausedClockHost;
|
||||
use board_host::board_host;
|
||||
|
||||
@@ -880,15 +883,14 @@ async fn subscribed_evidence_reaches_the_retained_reviewer_when_it_becomes_idle(
|
||||
use codex_extension_api::ThreadReadyInput;
|
||||
use codex_extension_api::ThreadStopInput;
|
||||
use codex_guardian_reviewer::SessionDisposition;
|
||||
use codex_message_board::SubscriptionChange;
|
||||
use codex_message_board::SubscriptionRequest;
|
||||
use codex_message_board::SubscriptionTarget;
|
||||
use codex_guardian_v3::LiveRetrievalBinding;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_protocol::turn_input::TurnInputRequest;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use core_test_support::wait_for_successful_turn;
|
||||
use reviewer_tool_call::invoke;
|
||||
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
const ROUTING: &str = "Route release activity to a release channel.";
|
||||
@@ -965,38 +967,28 @@ retrieval_instructions = "{RETRIEVAL}"
|
||||
let cancel = CancellationToken::new();
|
||||
let first = actor.reserve(&context, &cancel).await?;
|
||||
let id = first.thread_id();
|
||||
let reviewer = test
|
||||
.thread_manager
|
||||
.get_thread_with_extension::<codex_guardian_v3::LiveRetrievalBinding>(id, |_| true)
|
||||
.await?;
|
||||
let board = local_board(test.config.sqlite_config().clone(), root.into())
|
||||
.read_write()
|
||||
.open(board_host(root))
|
||||
.await?;
|
||||
board
|
||||
.upsert_channel(
|
||||
root,
|
||||
UpsertChannelRequest {
|
||||
channel_name: "release".into(),
|
||||
description: "Release policy".to_owned().try_into()?,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
board
|
||||
.set_subscription(
|
||||
root,
|
||||
SubscriptionRequest {
|
||||
target: SubscriptionTarget::Channel("release".into()),
|
||||
target_agent: None,
|
||||
change: SubscriptionChange::Subscribe,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let load_reviewer = async |id| {
|
||||
let reviewer = test
|
||||
.thread_manager
|
||||
.get_thread_with_extension::<LiveRetrievalBinding>(id, |_| true)
|
||||
.await?;
|
||||
let binding = reviewer
|
||||
.thread_extension_data()
|
||||
.get::<LiveRetrievalBinding>()
|
||||
.expect("live reviewer tools");
|
||||
anyhow::Ok((reviewer, binding))
|
||||
};
|
||||
let (reviewer, binding) = load_reviewer(id).await?;
|
||||
// Follow the channel before the housekeeper creates it with the first routed original.
|
||||
invoke(&binding, "subscribe", json!({"channel_name":"release"})).await?;
|
||||
let model = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_assistant_message("route", r#"{"routes":[["release"]],"descriptions":[]}"#),
|
||||
ev_assistant_message(
|
||||
"route",
|
||||
r#"{"routes":[["release"]],"descriptions":[{"channel":"release","description":"Release policy"}]}"#,
|
||||
),
|
||||
ev_completed("route"),
|
||||
]),
|
||||
sse(vec![
|
||||
@@ -1074,6 +1066,14 @@ retrieval_instructions = "{RETRIEVAL}"
|
||||
drop(second);
|
||||
let third = actor.reserve(&context, &cancel).await?;
|
||||
assert_ne!(id, third.thread_id());
|
||||
let (replacement, binding) = load_reviewer(third.thread_id()).await?;
|
||||
assert!(has_delivery(
|
||||
replacement.conversation_history_snapshot().await.as_ref()
|
||||
));
|
||||
assert_eq!(
|
||||
invoke(&binding, "subscribed_channels", json!({})).await?["results"],
|
||||
json!(["release"])
|
||||
);
|
||||
third.finish(SessionDisposition::Discard);
|
||||
lifecycle
|
||||
.on_thread_stop(ThreadStopInput {
|
||||
@@ -1081,6 +1081,11 @@ retrieval_instructions = "{RETRIEVAL}"
|
||||
session_store: &session,
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
invoke(&binding, "subscribe", json!({"channel_name":"release"}))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2,22 +2,16 @@
|
||||
|
||||
#![allow(clippy::expect_used)]
|
||||
|
||||
use codex_guardian_v3::LiveDelivery;
|
||||
use codex_guardian_v3::LiveRetrievalBinding;
|
||||
use codex_guardian_v3::local_board;
|
||||
use codex_message_board::AppendRequest;
|
||||
use codex_message_board::CreateChannelRequest;
|
||||
use codex_message_board::Page;
|
||||
use codex_message_board::PageRequest;
|
||||
use codex_message_board::PostDestination;
|
||||
use codex_message_board::SubscriptionChange;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::openai_models::TruncationPolicyConfig;
|
||||
use codex_state::SqliteConfig;
|
||||
use codex_tools::ToolCall;
|
||||
use codex_tools::ToolCallSource;
|
||||
use codex_tools::ToolName;
|
||||
use codex_tools::ToolPayload;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
@@ -33,6 +27,11 @@ mod board_host;
|
||||
mod guidance;
|
||||
#[path = "retrieval/subscriptions.rs"]
|
||||
mod subscriptions;
|
||||
#[path = "common/reviewer_tool_call.rs"]
|
||||
mod tool_calls;
|
||||
|
||||
use tool_calls::invoke;
|
||||
use tool_calls::reviewer_tool_call;
|
||||
|
||||
fn retrieval_host(
|
||||
members: impl IntoIterator<Item = (ThreadId, AgentPath)>,
|
||||
@@ -100,7 +99,9 @@ async fn searches_live_and_unsubscribed_guardian_posts() -> anyhow::Result<()> {
|
||||
)
|
||||
.await?;
|
||||
let reader = Arc::new(storage.read_only().open(host).await?);
|
||||
let tools = LiveRetrievalBinding::new(reader, owner, AgentPath::root())?.tools();
|
||||
let delivery = Arc::new(LiveDelivery::new(owner));
|
||||
let binding = LiveRetrievalBinding::new(reader, owner, AgentPath::root(), &delivery)?;
|
||||
let tools = binding.tools();
|
||||
let latest = routed(3, r#"Publish "prod" from C:\work\draft now."#);
|
||||
let third = board
|
||||
.append(
|
||||
@@ -112,12 +113,9 @@ async fn searches_live_and_unsubscribed_guardian_posts() -> anyhow::Result<()> {
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert!(
|
||||
board
|
||||
.subscribed_channels(owner, PageRequest::default())
|
||||
.await?
|
||||
.results
|
||||
.is_empty()
|
||||
assert_eq!(
|
||||
invoke(&binding, "subscribed_channels", json!({})).await?["results"],
|
||||
json!([])
|
||||
);
|
||||
|
||||
let expected_names = [
|
||||
@@ -190,28 +188,10 @@ async fn searches_live_and_unsubscribed_guardian_posts() -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reviewer_tool_call(name: &ToolName, arguments: &Value, byte_limit: i64) -> ToolCall<'static> {
|
||||
ToolCall {
|
||||
turn_id: "review".into(),
|
||||
call_id: name.name.clone(),
|
||||
tool_name: name.clone(),
|
||||
model: "test".into(),
|
||||
codex_turn_metadata: None,
|
||||
truncation_policy: TruncationPolicyConfig::bytes(byte_limit).into(),
|
||||
source: ToolCallSource::Direct,
|
||||
conversation_history: Default::default(),
|
||||
turn_item_emitter: Arc::new(codex_tools::NoopTurnItemEmitter),
|
||||
attachment_store: Arc::new(codex_attachment_store::InlineAttachmentStore),
|
||||
ephemeral: false,
|
||||
environments: Vec::new(),
|
||||
payload: ToolPayload::Function {
|
||||
arguments: arguments.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lists_only_the_reviewers_own_subscriptions_across_pages() -> anyhow::Result<()> {
|
||||
let build = "build-instructions-for-release";
|
||||
let release = "release-approvals-and-revocations";
|
||||
let root = ThreadId::new();
|
||||
let actor = ThreadId::new();
|
||||
let path = AgentPath::root()
|
||||
@@ -223,42 +203,40 @@ async fn lists_only_the_reviewers_own_subscriptions_across_pages() -> anyhow::Re
|
||||
SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into()?),
|
||||
root.into(),
|
||||
);
|
||||
let writer = storage.read_write().open(host.clone()).await?;
|
||||
for (owner, channel) in [(actor, "build"), (root, "private"), (actor, "release")] {
|
||||
writer
|
||||
.create_channel(
|
||||
owner,
|
||||
CreateChannelRequest {
|
||||
channel_name: channel.into(),
|
||||
description: None,
|
||||
subscription: SubscriptionChange::Subscribe,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
let board = Arc::new(storage.read_only().open(host).await?);
|
||||
let delivery = Arc::new(LiveDelivery::new(root));
|
||||
let reviewer = LiveRetrievalBinding::new(board.clone(), actor, path, &delivery)?;
|
||||
let other = LiveRetrievalBinding::new(board, root, AgentPath::root(), &delivery)?;
|
||||
for (binding, channel) in [
|
||||
(&reviewer, build),
|
||||
(&other, "private"),
|
||||
(&reviewer, release),
|
||||
] {
|
||||
invoke(binding, "subscribe", json!({"channel_name":channel})).await?;
|
||||
}
|
||||
let name = ToolName::namespaced("guardian_board", "subscribed_channels");
|
||||
let tool = LiveRetrievalBinding::new(board, actor, path)?
|
||||
let tool = reviewer
|
||||
.tools()
|
||||
.into_iter()
|
||||
.find(|tool| tool.tool_name() == name)
|
||||
.expect("live reviewer subscription lookup");
|
||||
.expect("subscription listing");
|
||||
let list = async |arguments: Value| -> anyhow::Result<Page<String>> {
|
||||
let call = reviewer_tool_call(&name, &arguments, /*byte_limit*/ 8_000);
|
||||
// The output budget fits one channel name and its cursor.
|
||||
let call = reviewer_tool_call(&name, &arguments, /*byte_limit*/ 96);
|
||||
let result = tool.handle(call.clone()).await?;
|
||||
Ok(serde_json::from_value(
|
||||
result.code_mode_result(&call.payload),
|
||||
)?)
|
||||
};
|
||||
|
||||
let first = list(json!({ "limit": 1 })).await?;
|
||||
let first = list(json!({ "limit": 2 })).await?;
|
||||
let last = list(json!({ "limit": 1, "cursor": first.next_cursor })).await?;
|
||||
assert_eq!(
|
||||
(first.results, last),
|
||||
(
|
||||
vec!["build".to_owned()],
|
||||
vec![build.to_owned()],
|
||||
Page {
|
||||
results: vec!["release".to_owned()],
|
||||
results: vec![release.to_owned()],
|
||||
next_cursor: None,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Guardian can change its own live channel subscriptions and cannot change another actor's.
|
||||
|
||||
use codex_guardian_v3::LiveDelivery;
|
||||
use codex_guardian_v3::LiveRetrievalBinding;
|
||||
use codex_guardian_v3::local_board;
|
||||
use codex_message_board::AgentMessageBoard;
|
||||
@@ -8,9 +9,7 @@ use codex_message_board::LocalBoard;
|
||||
use codex_message_board::PostDestination;
|
||||
use codex_message_board::SubscriptionChange::Subscribe;
|
||||
use codex_message_board::SubscriptionRequest;
|
||||
use codex_message_board::SubscriptionState;
|
||||
use codex_message_board::SubscriptionTarget;
|
||||
use codex_message_board::UpsertChannelRequest;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_state::SqliteConfig;
|
||||
@@ -18,6 +17,7 @@ use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::invoke;
|
||||
use crate::retrieval_host;
|
||||
use crate::reviewer_tool_call;
|
||||
|
||||
@@ -35,8 +35,12 @@ async fn subscription_tools_only_change_the_callers_channels() -> anyhow::Result
|
||||
.read_only()
|
||||
.open(host.clone())
|
||||
.await?;
|
||||
let delivery = Arc::new(LiveDelivery::new(owner));
|
||||
// A Guardian reviewer must reject the ordinary board, even for the same root.
|
||||
assert!(LiveRetrievalBinding::new(Arc::new(agent_board), reviewer, path.clone()).is_err());
|
||||
assert!(
|
||||
LiveRetrievalBinding::new(Arc::new(agent_board), reviewer, path.clone(), &delivery)
|
||||
.is_err()
|
||||
);
|
||||
let storage = local_board(sqlite, owner.into());
|
||||
let writer = storage.read_write().open(host.clone()).await?;
|
||||
let original = writer
|
||||
@@ -50,9 +54,10 @@ async fn subscription_tools_only_change_the_callers_channels() -> anyhow::Result
|
||||
)
|
||||
.await?;
|
||||
let board: Arc<dyn AgentMessageBoard> = Arc::new(storage.read_only().open(host.clone()).await?);
|
||||
// An upgraded board may already hold subscriptions from a previous reviewer.
|
||||
board
|
||||
.set_subscription(
|
||||
owner,
|
||||
reviewer,
|
||||
SubscriptionRequest {
|
||||
target: SubscriptionTarget::Channel("release".into()),
|
||||
change: Subscribe,
|
||||
@@ -60,33 +65,18 @@ async fn subscription_tools_only_change_the_callers_channels() -> anyhow::Result
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let tools = LiveRetrievalBinding::new(board.clone(), reviewer, path.clone())?.tools();
|
||||
writer
|
||||
.upsert_channel(
|
||||
owner,
|
||||
UpsertChannelRequest {
|
||||
channel_name: "later".into(),
|
||||
description: "Later channel".to_owned().try_into()?,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let later = writer
|
||||
.append(
|
||||
owner,
|
||||
AppendRequest {
|
||||
request_id: "later".into(),
|
||||
destination: PostDestination::Channel("release".into()),
|
||||
text: "Later evidence".into(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert_ne!(original.message_id, later.message_id);
|
||||
let binding = LiveRetrievalBinding::new(board, reviewer, path.clone(), &delivery)?;
|
||||
let tools = binding.tools();
|
||||
let channels = async || -> anyhow::Result<serde_json::Value> {
|
||||
Ok(invoke(&binding, "subscribed_channels", json!({})).await?["results"].take())
|
||||
};
|
||||
assert_eq!(channels().await?, json!([]));
|
||||
for (name, arguments, succeeds) in [
|
||||
("subscribe", json!({"channel_name":"release"}), true),
|
||||
("unsubscribe", json!({"channel_name":"release"}), true),
|
||||
("subscribe", json!({"channel_name":"release"}), true),
|
||||
("subscribe", json!({"channel_name":"later"}), true),
|
||||
("unsubscribe", json!({"channel_name":"later"}), true),
|
||||
("subscribe", json!({"channel_name":"release "}), false),
|
||||
("unsubscribe", json!({"channel_name":"missing"}), true),
|
||||
(
|
||||
"subscribe",
|
||||
json!({"thread_id": original.message_id}),
|
||||
@@ -108,48 +98,20 @@ async fn subscription_tools_only_change_the_callers_channels() -> anyhow::Result
|
||||
let result = result?;
|
||||
let response = result.code_mode_result(&call.payload);
|
||||
assert_eq!(result.log_output(), response.to_string());
|
||||
let output: SubscriptionState = serde_json::from_value(response)?;
|
||||
let channel = arguments["channel_name"]
|
||||
.as_str()
|
||||
.expect("channel subscription");
|
||||
let last_message_id = (channel == "release").then_some(later.message_id);
|
||||
assert_eq!(
|
||||
output,
|
||||
SubscriptionState {
|
||||
channel_name: channel.into(),
|
||||
thread_id: None,
|
||||
target_agent: path.clone(),
|
||||
enabled: name == "subscribe",
|
||||
last_message_id,
|
||||
}
|
||||
response,
|
||||
json!({
|
||||
"channel_name": arguments["channel_name"],
|
||||
"thread_id": null,
|
||||
"target_agent": path,
|
||||
"enabled": name == "subscribe",
|
||||
})
|
||||
);
|
||||
if name == "unsubscribe" && channel == "release" {
|
||||
assert!(
|
||||
board
|
||||
.subscribed_channels(reviewer, Default::default())
|
||||
.await?
|
||||
.results
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
} else {
|
||||
assert!(result.is_err());
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
board
|
||||
.subscribed_channels(reviewer, Default::default())
|
||||
.await?
|
||||
.results,
|
||||
vec!["release".to_owned()]
|
||||
);
|
||||
assert_eq!(
|
||||
board
|
||||
.subscribed_channels(owner, Default::default())
|
||||
.await?
|
||||
.results,
|
||||
vec!["release".to_owned()]
|
||||
);
|
||||
assert_eq!(channels().await?, json!(["later"]));
|
||||
assert!(
|
||||
host.notifications
|
||||
.lock()
|
||||
|
||||
+2
-2
@@ -6,8 +6,8 @@ Scenario: The retained reviewer receives the subscribed original before assessin
|
||||
|
||||
## Window 1
|
||||
-- request 1 (turn) --
|
||||
00:additional_tools/developer (1; hash=06541b7d5af3dc9e):
|
||||
- namespace/functions; hash=de44d355be93b260
|
||||
00:additional_tools/developer (1; hash=695757802767b73b):
|
||||
- namespace/functions; hash=69649b6a62ed6df3
|
||||
- custom/exec
|
||||
- function/wait
|
||||
01:message/developer:
|
||||
|
||||
@@ -22,6 +22,8 @@ use std::num::NonZeroU32;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
const MAX_CHANNEL_BYTES: usize = 128;
|
||||
|
||||
// Local and remote implementations must remain usable through the same handle.
|
||||
const _: Option<&dyn AgentMessageBoard> = None;
|
||||
|
||||
@@ -89,16 +91,6 @@ pub trait AgentMessageBoard: Send + Sync {
|
||||
request: AppendRequest,
|
||||
) -> BoxFuture<'_, Result<PostMetadata>>;
|
||||
|
||||
/// Like a silent append, also returns the subscribers at the moment of insertion.
|
||||
/// An idempotent retry returns the existing post and no new deliveries.
|
||||
fn append_with_subscribers(
|
||||
&self,
|
||||
_caller: ThreadId,
|
||||
_request: AppendRequest,
|
||||
) -> BoxFuture<'_, Result<(PostMetadata, Vec<ThreadId>)>> {
|
||||
unsupported("appending with subscribers")
|
||||
}
|
||||
|
||||
fn list_threads(
|
||||
&self,
|
||||
caller: ThreadId,
|
||||
@@ -142,15 +134,6 @@ pub trait AgentMessageBoard: Send + Sync {
|
||||
caller: ThreadId,
|
||||
request: SubscriptionRequest,
|
||||
) -> BoxFuture<'_, Result<SubscriptionState>>;
|
||||
|
||||
/// List a caller's current channel subscriptions on a live board.
|
||||
fn subscribed_channels(
|
||||
&self,
|
||||
_caller: ThreadId,
|
||||
_page: PageRequest,
|
||||
) -> BoxFuture<'_, Result<Page<String>>> {
|
||||
unsupported("listing channel subscriptions")
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported<T>(operation: &'static str) -> BoxFuture<'static, Result<T>> {
|
||||
@@ -184,6 +167,21 @@ pub enum SubscriptionChange {
|
||||
Unsubscribe,
|
||||
}
|
||||
|
||||
/// Checks whether a name is valid for channel creation, independent of board contents.
|
||||
pub fn validate_channel(name: &str) -> Result<()> {
|
||||
if name.is_empty()
|
||||
|| name.len() > MAX_CHANNEL_BYTES
|
||||
|| name.trim() != name
|
||||
|| name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"channel names must contain 1–128 bytes without edge whitespace or control characters"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct CreateChannelRequest {
|
||||
pub channel_name: String,
|
||||
@@ -260,7 +258,6 @@ pub struct PostRequest {
|
||||
pub(crate) enum PostBehavior {
|
||||
Discussion,
|
||||
SilentAppend,
|
||||
SilentAppendWithSubscribers,
|
||||
}
|
||||
|
||||
/// Request to append evidence without subscribing its author or notifying anyone.
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::SubscriptionState;
|
||||
use crate::SubscriptionTarget;
|
||||
use crate::UpsertChannelRequest;
|
||||
use crate::api::PostBehavior;
|
||||
use crate::validate_channel;
|
||||
use caseless::default_case_fold_str;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
@@ -35,7 +36,7 @@ use std::sync::Weak;
|
||||
use tokio::sync::Mutex;
|
||||
use uuid::Uuid;
|
||||
|
||||
mod queries;
|
||||
pub(crate) mod queries;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "in_memory_tests.rs"]
|
||||
@@ -467,19 +468,6 @@ impl InMemoryAgentMessageBoard {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_channel(name: &str) -> Result<()> {
|
||||
if name.is_empty()
|
||||
|| name.len() > 128
|
||||
|| name.trim() != name
|
||||
|| name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(invalid(
|
||||
"channel names must contain 1–128 bytes without edge whitespace or control characters",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> CodexErr {
|
||||
CodexErr::InvalidRequest(message.into())
|
||||
}
|
||||
|
||||
@@ -270,7 +270,8 @@ impl AgentMessageBoard for InMemoryAgentMessageBoard {
|
||||
}
|
||||
}
|
||||
|
||||
fn page<T>(request: &PageRequest, results: Vec<T>) -> Result<Page<T>> {
|
||||
/// Paginate an ordered collection with the board's cursor format and page limit.
|
||||
pub fn page<T>(request: &PageRequest, results: impl IntoIterator<Item = T>) -> Result<Page<T>> {
|
||||
let offset = match &request.cursor {
|
||||
Some(cursor) => {
|
||||
let mut bytes = [0; 4];
|
||||
|
||||
@@ -29,10 +29,12 @@ pub use api::SubscriptionTarget;
|
||||
pub use api::ThreadQuery;
|
||||
pub use api::ThreadSort;
|
||||
pub use api::UpsertChannelRequest;
|
||||
pub use api::validate_channel;
|
||||
pub use host::MessageBoardHost;
|
||||
pub use host::NotificationDelivery;
|
||||
pub use in_memory::InMemoryAgentMessageBoard;
|
||||
pub use in_memory::InMemoryMessageBoards;
|
||||
pub use in_memory::queries::page as paginate;
|
||||
pub use local::LocalAgentMessageBoard;
|
||||
pub use local::connection::LocalBoard;
|
||||
pub use local::connection::LocalBoardConnection;
|
||||
|
||||
@@ -23,6 +23,7 @@ use crate::SubscriptionRequest;
|
||||
use crate::SubscriptionState;
|
||||
use crate::SubscriptionTarget;
|
||||
use crate::api::PostBehavior;
|
||||
use crate::validate_channel;
|
||||
use caseless::default_case_fold_str;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
@@ -58,7 +59,6 @@ mod subscriptions;
|
||||
mod pools_tests;
|
||||
|
||||
const MAX_POST_BYTES: usize = 64 * 1024;
|
||||
const MAX_CHANNEL_BYTES: usize = 128;
|
||||
const MAX_READ_CHARS: usize = 20_000;
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -169,28 +169,13 @@ impl LocalAgentMessageBoard {
|
||||
/// into a recipient's later turn. Once committed, notification failures are
|
||||
/// logged without failing the post; the persisted content remains readable.
|
||||
pub async fn post(&self, caller: ThreadId, request: PostRequest) -> Result<PostMetadata> {
|
||||
Ok(self
|
||||
.write(caller, request, PostBehavior::Discussion)
|
||||
.await?
|
||||
.0)
|
||||
self.write(caller, request, PostBehavior::Discussion).await
|
||||
}
|
||||
|
||||
/// Appends evidence without automatic subscriptions or notifications, even on a discussion board.
|
||||
/// Uses the same access checks, caller-scoped request IDs and durable write path as posting.
|
||||
/// Reusing a request ID for a different payload or operation is an error.
|
||||
pub async fn append(&self, caller: ThreadId, request: AppendRequest) -> Result<PostMetadata> {
|
||||
Ok(self
|
||||
.write_append(caller, request, PostBehavior::SilentAppend)
|
||||
.await?
|
||||
.0)
|
||||
}
|
||||
|
||||
async fn write_append(
|
||||
&self,
|
||||
caller: ThreadId,
|
||||
request: AppendRequest,
|
||||
behavior: PostBehavior,
|
||||
) -> Result<(PostMetadata, Vec<ThreadId>)> {
|
||||
self.write(
|
||||
caller,
|
||||
PostRequest {
|
||||
@@ -199,7 +184,7 @@ impl LocalAgentMessageBoard {
|
||||
text: request.text,
|
||||
agents_to_notify: Vec::new(),
|
||||
},
|
||||
behavior,
|
||||
PostBehavior::SilentAppend,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -209,7 +194,7 @@ impl LocalAgentMessageBoard {
|
||||
caller: ThreadId,
|
||||
request: PostRequest,
|
||||
behavior: PostBehavior,
|
||||
) -> Result<(PostMetadata, Vec<ThreadId>)> {
|
||||
) -> Result<PostMetadata> {
|
||||
if let Some(access) = self.access {
|
||||
access.require_write(
|
||||
self.identity,
|
||||
@@ -230,7 +215,7 @@ impl LocalAgentMessageBoard {
|
||||
caller: ThreadId,
|
||||
request: PostRequest,
|
||||
behavior: PostBehavior,
|
||||
) -> Result<(PostMetadata, Vec<ThreadId>)> {
|
||||
) -> Result<PostMetadata> {
|
||||
if request.text.len() > MAX_POST_BYTES
|
||||
|| request.text.is_empty()
|
||||
|| request.request_id.is_empty()
|
||||
@@ -246,9 +231,7 @@ impl LocalAgentMessageBoard {
|
||||
let request_json = match behavior {
|
||||
// Keep existing post fingerprints compatible with persisted retries.
|
||||
PostBehavior::Discussion => serde_json::to_string(&request),
|
||||
PostBehavior::SilentAppend | PostBehavior::SilentAppendWithSubscribers => {
|
||||
serde_json::to_string(&("append", &request))
|
||||
}
|
||||
PostBehavior::SilentAppend => serde_json::to_string(&("append", &request)),
|
||||
}
|
||||
.map_err(storage_error)?;
|
||||
let mut conn = self.pool.acquire().await.map_err(storage_error)?;
|
||||
@@ -256,7 +239,7 @@ impl LocalAgentMessageBoard {
|
||||
.existing_post(&mut conn, &request_id, &request_json)
|
||||
.await?
|
||||
{
|
||||
return Ok((post.metadata, Vec::new()));
|
||||
return Ok(post.metadata);
|
||||
}
|
||||
drop(conn);
|
||||
let notify_recipients = if behavior == PostBehavior::Discussion {
|
||||
@@ -274,7 +257,7 @@ impl LocalAgentMessageBoard {
|
||||
.existing_post(&mut tx, &request_id, &request_json)
|
||||
.await?
|
||||
{
|
||||
return Ok((post.metadata, Vec::new()));
|
||||
return Ok(post.metadata);
|
||||
}
|
||||
let id = Uuid::now_v7();
|
||||
let (channel, root, target) = match &request.destination {
|
||||
@@ -371,7 +354,7 @@ impl LocalAgentMessageBoard {
|
||||
tx.commit().await.map_err(storage_error)?;
|
||||
|
||||
let Some(mut recipients) = notify_recipients else {
|
||||
return Ok((post.metadata, subscribers));
|
||||
return Ok(post.metadata);
|
||||
};
|
||||
recipients.extend(subscribers);
|
||||
recipients.remove(&caller);
|
||||
@@ -387,7 +370,7 @@ impl LocalAgentMessageBoard {
|
||||
}
|
||||
})
|
||||
.await;
|
||||
Ok((post.metadata, Vec::new()))
|
||||
Ok(post.metadata)
|
||||
}
|
||||
|
||||
pub async fn set_subscription(
|
||||
@@ -503,19 +486,6 @@ async fn insert_channel(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_channel(name: &str) -> Result<()> {
|
||||
if name.is_empty()
|
||||
|| name.len() > MAX_CHANNEL_BYTES
|
||||
|| name.trim() != name
|
||||
|| name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(invalid(
|
||||
"channel names must contain 1–128 bytes without edge whitespace or control characters",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> CodexErr {
|
||||
CodexErr::InvalidRequest(message.into())
|
||||
}
|
||||
|
||||
@@ -127,31 +127,6 @@ impl LocalAgentMessageBoard {
|
||||
.execute(&mut *tx).await.map_err(storage_error)?;
|
||||
tx.commit().await.map_err(storage_error)
|
||||
}
|
||||
|
||||
/// Lists the caller's channel subscriptions within the existing page budget.
|
||||
pub async fn subscribed_channels(
|
||||
&self,
|
||||
caller: ThreadId,
|
||||
page: PageRequest,
|
||||
) -> Result<Page<String>> {
|
||||
self.host.agent_path(caller).await?;
|
||||
let window = Window::new(&page)?;
|
||||
// Probe the existing subscriptions primary key for each channel.
|
||||
let channels = sqlx::query_scalar::<_, String>(
|
||||
"SELECT c.name FROM channels AS c WHERE c.board=? AND EXISTS (
|
||||
SELECT 1 FROM subscriptions AS s
|
||||
WHERE s.board=c.board AND s.target=json_object('Channel',c.name) AND s.agent=?
|
||||
) ORDER BY c.name LIMIT ? OFFSET ?",
|
||||
)
|
||||
.bind(self.identity.to_string())
|
||||
.bind(caller.to_string())
|
||||
.bind((window.limit + 1) as i64)
|
||||
.bind(window.offset())
|
||||
.fetch_all(self.pool.as_ref())
|
||||
.await
|
||||
.map_err(storage_error)?;
|
||||
window.finish(channels)
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentMessageBoard for LocalAgentMessageBoard {
|
||||
@@ -202,18 +177,6 @@ impl AgentMessageBoard for LocalAgentMessageBoard {
|
||||
Box::pin(LocalAgentMessageBoard::append(self, caller, request))
|
||||
}
|
||||
|
||||
fn append_with_subscribers(
|
||||
&self,
|
||||
caller: ThreadId,
|
||||
request: AppendRequest,
|
||||
) -> BoxFuture<'_, Result<(PostMetadata, Vec<ThreadId>)>> {
|
||||
Box::pin(self.write_append(
|
||||
caller,
|
||||
request,
|
||||
crate::api::PostBehavior::SilentAppendWithSubscribers,
|
||||
))
|
||||
}
|
||||
|
||||
fn set_subscription(
|
||||
&self,
|
||||
caller: ThreadId,
|
||||
@@ -224,16 +187,6 @@ impl AgentMessageBoard for LocalAgentMessageBoard {
|
||||
))
|
||||
}
|
||||
|
||||
fn subscribed_channels(
|
||||
&self,
|
||||
caller: ThreadId,
|
||||
page: PageRequest,
|
||||
) -> BoxFuture<'_, Result<Page<String>>> {
|
||||
Box::pin(LocalAgentMessageBoard::subscribed_channels(
|
||||
self, caller, page,
|
||||
))
|
||||
}
|
||||
|
||||
fn read_post_texts_by_id<'a>(
|
||||
&'a self,
|
||||
caller: ThreadId,
|
||||
|
||||
@@ -106,7 +106,6 @@ impl<'call> ToolExecutor<ToolCall<'call>> for BoardTool {
|
||||
}
|
||||
fn supports_parallel_tool_calls(&self) -> bool {
|
||||
MessageBoardTool::READ_ONLY.contains(&self.tool)
|
||||
|| self.tool == MessageBoardTool::SubscribedChannels
|
||||
}
|
||||
|
||||
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
|
||||
@@ -220,15 +219,6 @@ impl BoardTool {
|
||||
})
|
||||
.await
|
||||
}
|
||||
MessageBoardTool::SubscribedChannels => {
|
||||
let arguments::SubscribedChannels { limit, cursor } =
|
||||
serde_json::from_str(raw).map_err(model_error)?;
|
||||
let limit = page_limit(limit);
|
||||
bounded_read(budget, limit, |scale| {
|
||||
board.subscribed_channels(caller, page(limit, cursor.clone(), scale))
|
||||
})
|
||||
.await
|
||||
}
|
||||
MessageBoardTool::ListThreads => {
|
||||
let arguments::ListThreads {
|
||||
channel_name,
|
||||
|
||||
@@ -63,13 +63,6 @@ pub(super) struct ReadPost {
|
||||
pub(super) limit_chars: Option<NonZeroU32>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct SubscribedChannels {
|
||||
pub(super) limit: Option<NonZeroU32>,
|
||||
pub(super) cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct Subscription {
|
||||
|
||||
@@ -12,8 +12,6 @@ pub enum MessageBoardTool {
|
||||
SearchPosts,
|
||||
ReadThread,
|
||||
ReadPost,
|
||||
/// Lists the caller's own subscriptions on a live board.
|
||||
SubscribedChannels,
|
||||
Subscribe,
|
||||
Unsubscribe,
|
||||
/// Posts, subscribes the author unless opted out, and notifies recipients.
|
||||
@@ -63,7 +61,6 @@ impl MessageBoardTool {
|
||||
Self::SearchPosts => "search_posts",
|
||||
Self::ReadThread => "read_thread",
|
||||
Self::ReadPost => "read_post",
|
||||
Self::SubscribedChannels => "subscribed_channels",
|
||||
Self::Subscribe => "subscribe",
|
||||
Self::Unsubscribe => "unsubscribe",
|
||||
Self::Post => "post",
|
||||
|
||||
@@ -65,11 +65,6 @@ pub(super) fn tool(
|
||||
&["message_id", "offset_chars", "limit_chars"],
|
||||
&["message_id"],
|
||||
),
|
||||
MessageBoardTool::SubscribedChannels => (
|
||||
"List the names of channels you are currently subscribed to.",
|
||||
&["limit", "cursor"],
|
||||
&[],
|
||||
),
|
||||
MessageBoardTool::Subscribe => (
|
||||
"Subscribe yourself or another agent to a channel for new top-level posts, or to a thread for replies. Provide exactly one of channel_name or thread_id. Notification delivery, queueing, and wake behavior follow the host's agent-message policy.",
|
||||
&["channel_name", "thread_id", "target_agent"],
|
||||
|
||||
@@ -1829,28 +1829,16 @@ async fn silent_appends_preserve_evidence_and_explicit_subscriptions()
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
writer
|
||||
.create_channel(
|
||||
root,
|
||||
CreateChannelRequest {
|
||||
channel_name: "release".into(),
|
||||
description: Some("Release evidence".to_owned().try_into()?),
|
||||
subscription: SubscriptionChange::Unsubscribe,
|
||||
reader
|
||||
.set_subscription(
|
||||
child,
|
||||
SubscriptionRequest {
|
||||
target: SubscriptionTarget::Channel(channel.into()),
|
||||
change: SubscriptionChange::Subscribe,
|
||||
target_agent: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
for name in [channel, "release"] {
|
||||
reader
|
||||
.set_subscription(
|
||||
child,
|
||||
SubscriptionRequest {
|
||||
target: SubscriptionTarget::Channel(name.into()),
|
||||
change: SubscriptionChange::Subscribe,
|
||||
target_agent: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
let later_request = AppendRequest {
|
||||
request_id: "later".into(),
|
||||
destination: PostDestination::Channel(channel.into()),
|
||||
@@ -1873,34 +1861,6 @@ async fn silent_appends_preserve_evidence_and_explicit_subscriptions()
|
||||
.await?,
|
||||
0
|
||||
);
|
||||
let first = reader
|
||||
.subscribed_channels(
|
||||
child,
|
||||
PageRequest {
|
||||
cursor: None,
|
||||
limit: NonZeroU32::MIN,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let last = reader
|
||||
.subscribed_channels(
|
||||
child,
|
||||
PageRequest {
|
||||
cursor: first.next_cursor,
|
||||
limit: NonZeroU32::MIN,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
(first.results, last),
|
||||
(
|
||||
vec![channel.into()],
|
||||
Page {
|
||||
results: vec!["release".into()],
|
||||
next_cursor: None,
|
||||
}
|
||||
)
|
||||
);
|
||||
// Normal posts on this same board still subscribe their author and notify once.
|
||||
let discussion = PostRequest {
|
||||
request_id: "discussion".into(),
|
||||
|
||||
Reference in New Issue
Block a user