From dda227891d27b6e0f3f244eda149a98d098969ad Mon Sep 17 00:00:00 2001 From: jif Date: Thu, 24 Sep 2026 21:42:35 +0000 Subject: [PATCH] Add an in-memory agent message board for ephemeral sessions (#47946) ## Why Ephemeral sessions cannot use the SQLite-backed agent message board. An in-memory backend lets agents share discussions without creating durable board storage. ## What changed - Add the opt-in `message_board_in_memory` setting to the multi-agent v2 configuration, allowing the board to run in ephemeral sessions when both required features are enabled. - Share board state across agents in the same tree and release it when the last handle is dropped. - Implement channels, posts, subscriptions, notifications, search, and paginated reads through the existing `AgentMessageBoard` interface, including request deduplication. ## Testing Add coverage for shared handles, concurrent request deduplication, tree isolation, and state release. Run existing query and tool test cases against both backends, and extend the parent/child scenario to verify ephemeral board sharing without creating a board database. GitOrigin-RevId: d0b2083f8ea5b1c5a3a70f258ef738b87ea74cef --- codex-rs/core/config.schema.json | 4 + codex-rs/core/src/agent_message_board.rs | 18 +- codex-rs/core/src/config/config_tests.rs | 2 + codex-rs/core/src/config/mod.rs | 6 + .../suite/scenarios_agent_message_board.rs | 24 +- codex-rs/ext/agent-message-board/src/api.rs | 2 +- .../ext/agent-message-board/src/in_memory.rs | 384 ++++++++++++++++++ .../src/in_memory/queries.rs | 285 +++++++++++++ codex-rs/ext/agent-message-board/src/lib.rs | 5 +- .../agent-message-board/tests/local_board.rs | 146 ++++++- codex-rs/features/src/feature_configs.rs | 3 + codex-rs/features/src/tests.rs | 2 + 12 files changed, 849 insertions(+), 32 deletions(-) create mode 100644 codex-rs/ext/agent-message-board/src/in_memory.rs create mode 100644 codex-rs/ext/agent-message-board/src/in_memory/queries.rs diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index e08c701225..1e8327a60e 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -2746,6 +2746,10 @@ "minimum": 0.0, "type": "integer" }, + "message_board_in_memory": { + "description": "Keep the message board in memory for a training session, including ephemeral sessions.", + "type": "boolean" + }, "min_wait_timeout_ms": { "format": "int64", "maximum": 3600000.0, diff --git a/codex-rs/core/src/agent_message_board.rs b/codex-rs/core/src/agent_message_board.rs index b21e94e7c3..e3b6333a46 100644 --- a/codex-rs/core/src/agent_message_board.rs +++ b/codex-rs/core/src/agent_message_board.rs @@ -12,6 +12,7 @@ use crate::tools::MULTI_AGENT_V2_NAMESPACE_DESCRIPTION; use chrono::DateTime; use chrono::Utc; use codex_agent_message_board_extension::AgentMessageBoard; +use codex_agent_message_board_extension::InMemoryMessageBoards; use codex_agent_message_board_extension::LocalAgentMessageBoard; use codex_agent_message_board_extension::MessageBoardHost; use codex_agent_message_board_extension::NotificationDelivery; @@ -29,33 +30,40 @@ use futures::future::BoxFuture; use std::sync::Arc; use std::sync::Weak; -/// Registers the local board for opted-in, persistent MAv2 runtimes. -/// Shared session identity and the configured SQLite home survive runtime reloads. +/// Registers the configured board for opted-in MAv2 runtimes. +/// Training can share an in-memory board per tree, including ephemeral sessions. pub fn install_agent_message_board( registry: &mut ExtensionRegistryBuilder, manager: Weak, ) { + let in_memory_boards = Arc::new(InMemoryMessageBoards::default()); codex_agent_message_board_extension::install( registry, MULTI_AGENT_V2_NAMESPACE_DESCRIPTION, |config: &Config| config.multi_agent_v2.tool_namespace.clone(), move |config: &Config, tree, caller| { + let in_memory = config.multi_agent_v2.message_board_in_memory; // MAv2 supplies tree paths; ephemeral runtimes must not open durable storage. if !config.features.enabled(Feature::AgentMessageBoard) || !config.features.enabled(Feature::MultiAgentV2) - || config.ephemeral + || (config.ephemeral && !in_memory) { return Box::pin(async { Ok(None) }); } let sqlite = config.sqlite_config().clone(); + let in_memory_boards = Arc::clone(&in_memory_boards); let host = Arc::new(LocalBoardHost { manager: manager.clone(), tree, caller, }); Box::pin(async move { - let board = LocalAgentMessageBoard::open(&sqlite, tree, host).await?; - Ok(Some(Arc::new(board) as Arc)) + let board: Arc = if in_memory { + Arc::new(in_memory_boards.open(tree, host).await) + } else { + Arc::new(LocalAgentMessageBoard::open(&sqlite, tree, host).await?) + }; + Ok(Some(board)) }) }, ); diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 2622171432..3e7f1f4a86 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -12086,6 +12086,7 @@ hide_spawn_agent_metadata = true expose_spawn_agent_model_overrides = false wait_agent_enabled = false disable_direct_message = true +message_board_in_memory = true non_code_mode_only = true [agents] @@ -12142,6 +12143,7 @@ max_concurrent_threads_per_session = 9 assert!(!config.multi_agent_v2.expose_spawn_agent_model_overrides); assert!(!config.multi_agent_v2.wait_agent_enabled); assert!(config.multi_agent_v2.disable_direct_message); + assert!(config.multi_agent_v2.message_board_in_memory); assert!(config.multi_agent_v2.non_code_mode_only); Ok(()) diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 4fa07e6625..df6b1258d5 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1331,6 +1331,7 @@ pub struct MultiAgentV2Config { pub expose_spawn_agent_model_overrides: bool, pub wait_agent_enabled: bool, pub disable_direct_message: bool, + pub message_board_in_memory: bool, pub non_code_mode_only: bool, } @@ -1351,6 +1352,7 @@ impl MultiAgentV2Config { expose_spawn_agent_model_overrides: true, wait_agent_enabled: true, disable_direct_message: false, + message_board_in_memory: false, non_code_mode_only: true, } } @@ -2788,6 +2790,9 @@ fn resolve_multi_agent_v2_config(config_toml: &ConfigToml) -> MultiAgentV2Config let disable_direct_message = base .and_then(|config| config.disable_direct_message) .unwrap_or(default.disable_direct_message); + let message_board_in_memory = base + .and_then(|config| config.message_board_in_memory) + .unwrap_or(default.message_board_in_memory); let subagent_developer_instructions = base .and_then(|config| config.subagent_developer_instructions.as_ref()) .map(|instructions| instructions.trim().to_string()); @@ -2818,6 +2823,7 @@ fn resolve_multi_agent_v2_config(config_toml: &ConfigToml) -> MultiAgentV2Config expose_spawn_agent_model_overrides, wait_agent_enabled, disable_direct_message, + message_board_in_memory, non_code_mode_only, } } diff --git a/codex-rs/core/tests/suite/scenarios_agent_message_board.rs b/codex-rs/core/tests/suite/scenarios_agent_message_board.rs index f9c37bbbbb..2abb0a8fb8 100644 --- a/codex-rs/core/tests/suite/scenarios_agent_message_board.rs +++ b/codex-rs/core/tests/suite/scenarios_agent_message_board.rs @@ -203,11 +203,18 @@ async fn board_post_and_reads_reach_model_context_without_self_notices() -> anyh Ok(()) } +#[test_case::test_case(false; "disk")] +#[test_case::test_case(true; "in_memory")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn board_is_shared_with_children_survives_resume_and_skips_idle_notices() -> anyhow::Result<()> -{ +async fn board_is_shared_with_children_and_skips_idle_notices( + in_memory: bool, +) -> anyhow::Result<()> { let server = responses::start_mock_server().await; - let mut builder = test_codex().with_config(configure); + let mut builder = test_codex().with_config(move |config| { + configure(config); + config.multi_agent_v2.message_board_in_memory = in_memory; + config.ephemeral = in_memory; + }); let root = builder.build_with_auto_env(&server).await?; responses::mount_sse_sequence( &server, @@ -302,6 +309,17 @@ async fn board_is_shared_with_children_survives_resume_and_skips_idle_notices() serde_json::from_str(&output).with_context(|| format!("root read result: {output}"))?; assert_eq!(result["results"][0]["message_id"], post["message_id"]); child.shutdown_and_wait().await?; + if in_memory { + assert!( + !root + .config + .sqlite_config() + .home() + .join("agent_message_board_1.sqlite") + .exists() + ); + return Ok(()); + } let resumed = test_codex() .with_config(configure) .restart(&server, &root) diff --git a/codex-rs/ext/agent-message-board/src/api.rs b/codex-rs/ext/agent-message-board/src/api.rs index fee95aa4ac..75d31931dc 100644 --- a/codex-rs/ext/agent-message-board/src/api.rs +++ b/codex-rs/ext/agent-message-board/src/api.rs @@ -21,7 +21,7 @@ use uuid::Uuid; // Local and remote implementations must remain usable through the same handle. const _: Option<&dyn AgentMessageBoard> = None; -/// Stores discussions and subscriptions for one persistent agent tree. +/// Stores discussions and subscriptions for one agent tree. /// /// Every operation validates caller membership. IDs are scoped to this board; /// an agent runtime's ThreadId is distinct from a discussion's root post UUID. diff --git a/codex-rs/ext/agent-message-board/src/in_memory.rs b/codex-rs/ext/agent-message-board/src/in_memory.rs new file mode 100644 index 0000000000..c780cdf96c --- /dev/null +++ b/codex-rs/ext/agent-message-board/src/in_memory.rs @@ -0,0 +1,384 @@ +//! Tree-owned message boards for training. Agent handles share state; nothing is written to disk. +//! Mutations and recipient selection are atomic. Host callbacks run outside the state lock. + +use crate::ChannelSummary; +use crate::CreateChannelRequest; +use crate::MessageBoardHost; +use crate::PostDestination; +use crate::PostMetadata; +use crate::PostPreview; +use crate::PostRequest; +use crate::SubscriptionChange; +use crate::SubscriptionRequest; +use crate::SubscriptionState; +use crate::SubscriptionTarget; +use caseless::default_case_fold_str; +use chrono::DateTime; +use chrono::Utc; +use codex_protocol::AgentPath; +use codex_protocol::SessionId; +use codex_protocol::ThreadId; +use codex_protocol::error::CodexErr; +use codex_protocol::error::Result; +use futures::StreamExt; +use std::collections::BTreeMap; +use std::collections::HashMap; +use std::collections::HashSet; +use std::sync::Arc; +use std::sync::Weak; +use tokio::sync::Mutex; +use uuid::Uuid; + +mod queries; + +/// Shares board state across a tree while giving each agent its own host handle. +#[derive(Default)] +pub struct InMemoryMessageBoards { + states: Mutex>>>, +} + +impl InMemoryMessageBoards { + pub async fn open( + &self, + identity: SessionId, + host: Arc, + ) -> InMemoryAgentMessageBoard { + let mut states = self.states.lock().await; + let entry = states.entry(identity).or_default(); + let state = entry.upgrade().unwrap_or_else(|| { + let state = Arc::default(); + *entry = Arc::downgrade(&state); + state + }); + InMemoryAgentMessageBoard { + identity, + host, + state, + } + } +} + +/// A board held in memory for one training rollout. +/// The last handle releases its state; there is no persistence or recovery. +#[derive(Clone)] +pub struct InMemoryAgentMessageBoard { + identity: SessionId, + host: Arc, + state: Arc>, +} + +#[derive(Default)] +struct State { + channels: HashMap, + posts: Vec, + by_id: HashMap, + requests: HashMap<(ThreadId, String), usize>, + subscriptions: BTreeMap>, +} + +struct Channel { + summary: ChannelSummary, + search: String, + posts: Vec, + roots: Vec, +} + +struct Post { + metadata: PostMetadata, + request: PostRequest, + search: String, + n_chars: usize, + replies: Vec, + latest_reply: Option, +} + +impl Post { + fn preview(&self, max_chars: usize) -> PostPreview { + PostPreview { + metadata: self.metadata.clone(), + text_preview: self.request.text.chars().take(max_chars).collect(), + n_chars: self.n_chars, + truncated: self.n_chars > max_chars, + } + } +} + +impl State { + fn post_index(&self, id: Uuid) -> Result { + self.by_id + .get(&id) + .copied() + .ok_or_else(|| invalid("post not found in this board")) + } + + fn thread_index(&self, id: Uuid) -> Result { + let index = self.post_index(id)?; + if self.posts[index].metadata.thread_id != id { + return Err(invalid("thread_id must identify a top-level post")); + } + Ok(index) + } + + fn key(&self, index: usize) -> (i64, usize) { + ( + self.posts[index].metadata.created_at.timestamp_micros(), + index, + ) + } + + fn existing_post( + &self, + caller: ThreadId, + request: &PostRequest, + ) -> Result> { + self.requests + .get(&(caller, request.request_id.clone())) + .map(|index| { + let post = &self.posts[*index]; + if post.request != *request { + return Err(invalid("request ID was already used for a different post")); + } + Ok(post.metadata.clone()) + }) + .transpose() + } + + fn insert_channel(&mut self, name: &str, author: AgentPath, now: DateTime) -> 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", + )); + } + if self.channels.contains_key(name) { + return Err(invalid("channel already exists")); + } + self.channels.insert( + name.to_owned(), + Channel { + summary: ChannelSummary { + channel_name: name.to_owned(), + created_at: now, + created_by: author, + message_count: 0, + last_message_id: None, + }, + search: default_case_fold_str(name), + posts: Vec::new(), + roots: Vec::new(), + }, + ); + Ok(()) + } + + fn subscribe(&mut self, target: SubscriptionTarget, caller: ThreadId) { + self.subscriptions + .entry(target) + .or_default() + .entry(caller) + .or_insert(SubscriptionChange::Subscribe); + } +} + +impl InMemoryAgentMessageBoard { + pub fn new(identity: SessionId, host: Arc) -> Self { + Self { + identity, + host, + state: Arc::default(), + } + } + + async fn create_channel( + &self, + caller: ThreadId, + request: CreateChannelRequest, + ) -> Result { + let author = self.host.agent_path(caller).await?; + let now = self.host.current_time(caller).await?; + let mut state = self.state.lock().await; + state.insert_channel(&request.channel_name, author, now)?; + if request.subscription == SubscriptionChange::Subscribe { + state.subscribe( + SubscriptionTarget::Channel(request.channel_name.clone()), + caller, + ); + } + Ok(state.channels[&request.channel_name].summary.clone()) + } + + async fn post(&self, caller: ThreadId, request: PostRequest) -> Result { + // Accepted writes and their one-time fanout outlive cancellation of the tool call. + let board = self.clone(); + tokio::spawn(async move { board.post_inner(caller, request).await }) + .await + .map_err(|error| CodexErr::Io(std::io::Error::other(error)))? + } + + async fn post_inner(&self, caller: ThreadId, request: PostRequest) -> Result { + if request.text.is_empty() + || request.text.len() > 64 * 1024 + || request.request_id.is_empty() + || request.request_id.len() > 512 + || request.agents_to_notify.len() > 256 + { + return Err(invalid( + "post text, request ID or recipient count exceeds the board limits", + )); + } + let author = self.host.agent_path(caller).await?; + if let Some(post) = self.state.lock().await.existing_post(caller, &request)? { + return Ok(post); + } + let mut recipients = HashSet::new(); + for path in &request.agents_to_notify { + recipients.insert(self.host.resolve_agent(path.clone()).await?); + } + let now = self.host.current_time(caller).await?; + let (metadata, notice) = { + let mut state = self.state.lock().await; + if let Some(post) = state.existing_post(caller, &request)? { + return Ok(post); + } + let id = Uuid::now_v7(); + let (channel_name, root, target) = match &request.destination { + PostDestination::Channel(name) => { + if !state.channels.contains_key(name) { + return Err(invalid("channel not found in this board")); + } + (name.clone(), id, SubscriptionTarget::Channel(name.clone())) + } + PostDestination::NewChannel(name) => { + state.insert_channel(name, author.clone(), now)?; + state.subscribe(SubscriptionTarget::Channel(name.clone()), caller); + (name.clone(), id, SubscriptionTarget::Channel(name.clone())) + } + PostDestination::Thread(root) => { + let index = state.thread_index(*root)?; + ( + state.posts[index].metadata.channel_name.clone(), + *root, + SubscriptionTarget::Thread(*root), + ) + } + }; + if let Some(subscribers) = state.subscriptions.get(&target) { + recipients.extend(subscribers.iter().filter_map(|(agent, change)| { + (*change == SubscriptionChange::Subscribe).then_some(*agent) + })); + } + recipients.remove(&caller); + let metadata = PostMetadata { + message_id: id, + channel_name: channel_name.clone(), + author, + thread_id: root, + created_at: now, + }; + let index = state.posts.len(); + state + .requests + .insert((caller, request.request_id.clone()), index); + state.by_id.insert(id, index); + state.posts.push(Post { + metadata: metadata.clone(), + search: default_case_fold_str(&request.text), + n_chars: request.text.chars().count(), + request, + replies: Vec::new(), + latest_reply: None, + }); + let last = state.channels[&channel_name].summary.last_message_id; + let newest = last.is_none_or(|last| state.key(index) > state.key(state.by_id[&last])); + #[expect( + clippy::expect_used, + reason = "destination was checked or inserted under this lock" + )] + let channel = state + .channels + .get_mut(&channel_name) + .expect("validated channel"); + channel.posts.push(index); + channel.summary.message_count += 1; + if newest { + channel.summary.last_message_id = Some(id); + } + if root == id { + channel.roots.push(index); + } else { + let root_index = state.by_id[&root]; + let newest = state.posts[root_index] + .latest_reply + .is_none_or(|last| state.key(index) > state.key(last)); + let thread = &mut state.posts[root_index]; + thread.replies.push(index); + if newest { + thread.latest_reply = Some(index); + } + } + state.subscribe(SubscriptionTarget::Thread(root), caller); + (metadata, state.posts[index].preview(/*max_chars*/ 150)) + }; + futures::stream::iter(recipients).for_each_concurrent(/*limit*/ 16, |recipient| { + let notice = notice.clone(); + async move { + if let Err(error) = self.host.notify(recipient, notice).await { + tracing::warn!(%recipient, %error, "Failed to deliver message-board notification"); + } + } + }).await; + Ok(metadata) + } + + async fn set_subscription( + &self, + caller: ThreadId, + request: SubscriptionRequest, + ) -> Result { + let caller_path = self.host.agent_path(caller).await?; + let target_path = request.target_agent.unwrap_or(caller_path); + let target_agent = self.host.resolve_agent(target_path.clone()).await?; + let mut state = self.state.lock().await; + let (channel_name, thread_id, last_message_id) = match &request.target { + SubscriptionTarget::Channel(name) => { + let channel = state + .channels + .get(name) + .ok_or_else(|| invalid("channel not found in this board"))?; + (name.clone(), None, channel.summary.last_message_id) + } + SubscriptionTarget::Thread(root) => { + let index = state.thread_index(*root)?; + let post = &state.posts[index]; + let last = post + .latest_reply + .filter(|last| state.key(*last) > state.key(index)) + .unwrap_or(index); + ( + post.metadata.channel_name.clone(), + Some(*root), + Some(state.posts[last].metadata.message_id), + ) + } + }; + state + .subscriptions + .entry(request.target) + .or_default() + .insert(target_agent, request.change); + Ok(SubscriptionState { + channel_name, + thread_id, + target_agent: target_path, + enabled: request.change == SubscriptionChange::Subscribe, + last_message_id, + }) + } +} + +fn invalid(message: impl Into) -> CodexErr { + CodexErr::InvalidRequest(message.into()) +} diff --git a/codex-rs/ext/agent-message-board/src/in_memory/queries.rs b/codex-rs/ext/agent-message-board/src/in_memory/queries.rs new file mode 100644 index 0000000000..385ad9006d --- /dev/null +++ b/codex-rs/ext/agent-message-board/src/in_memory/queries.rs @@ -0,0 +1,285 @@ +//! Trait adapter and queries over indexed in-memory posts. Only page results clone content. + +use super::InMemoryAgentMessageBoard; +use super::invalid; +use crate::AgentMessageBoard; +use crate::ChannelQuery; +use crate::ChannelSummary; +use crate::CreateChannelRequest; +use crate::Page; +use crate::PageRequest; +use crate::PostContent; +use crate::PostMetadata; +use crate::PostPreview; +use crate::PostQuery; +use crate::PostRequest; +use crate::ReadPostRequest; +use crate::ReadThreadRequest; +use crate::SortDirection; +use crate::SubscriptionRequest; +use crate::SubscriptionState; +use crate::ThreadPage; +use crate::ThreadQuery; +use crate::ThreadSort; +use crate::ThreadSummary; +use base64::Engine; +use base64::prelude::BASE64_URL_SAFE_NO_PAD; +use caseless::default_case_fold_str; +use codex_protocol::SessionId; +use codex_protocol::ThreadId; +use codex_protocol::error::Result; +use futures::future::BoxFuture; +use std::cmp::Reverse; + +impl AgentMessageBoard for InMemoryAgentMessageBoard { + fn identity(&self) -> SessionId { + self.identity + } + + fn create_channel( + &self, + caller: ThreadId, + request: CreateChannelRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(self.create_channel(caller, request)) + } + + fn post(&self, caller: ThreadId, request: PostRequest) -> BoxFuture<'_, Result> { + Box::pin(self.post(caller, request)) + } + + fn set_subscription( + &self, + caller: ThreadId, + request: SubscriptionRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(self.set_subscription(caller, request)) + } + + fn read_post( + &self, + caller: ThreadId, + request: ReadPostRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + self.host.agent_path(caller).await?; + let state = self.state.lock().await; + let post = &state.posts[state.post_index(request.message_id)?]; + let offset = (request.offset_chars as usize).min(post.n_chars); + let text: String = post + .request + .text + .chars() + .skip(offset) + .take((request.limit_chars.get() as usize).min(20_000)) + .collect(); + Ok(PostContent { + metadata: post.metadata.clone(), + n_chars: post.n_chars, + next_offset_chars: offset + text.chars().count(), + text, + }) + }) + } + + fn list_channels( + &self, + caller: ThreadId, + query: ChannelQuery, + ) -> BoxFuture<'_, Result>> { + Box::pin(async move { + self.host.agent_path(caller).await?; + let search = default_case_fold_str(&query.query.unwrap_or_default()); + let state = self.state.lock().await; + let mut channels: Vec<_> = state + .channels + .values() + .filter(|channel| channel.search.contains(&search)) + .collect(); + channels.sort_unstable_by_key(|channel| { + let activity = channel + .summary + .last_message_id + .map_or(channel.summary.created_at.timestamp_micros(), |id| { + state.key(state.by_id[&id]).0 + }); + (activity, &channel.summary.channel_name) + }); + if query.direction == SortDirection::NewestFirst { + channels.reverse(); + } + let page = page(&query.page, channels)?; + Ok(Page { + results: page + .results + .into_iter() + .map(|channel| channel.summary.clone()) + .collect(), + next_cursor: page.next_cursor, + }) + }) + } + + fn list_threads( + &self, + caller: ThreadId, + query: ThreadQuery, + ) -> BoxFuture<'_, Result>> { + Box::pin(async move { + self.host.agent_path(caller).await?; + let state = self.state.lock().await; + let channel = state + .channels + .get(&query.channel_name) + .ok_or_else(|| invalid("channel not found in this board"))?; + let mut roots = channel.roots.clone(); + roots.sort_unstable_by_key(|index| { + let (created, sequence) = state.key(*index); + let timestamp = match query.sort { + ThreadSort::Created => created, + ThreadSort::Activity => state.posts[*index] + .latest_reply + .map_or(created, |reply| created.max(state.key(reply).0)), + }; + (timestamp, sequence) + }); + if query.direction == SortDirection::NewestFirst { + roots.reverse(); + } + let page = page(&query.page, roots)?; + let chars = (query.max_chars_per_post.get() as usize) + .min(20_000 / (2 * page.results.len().max(1))); + Ok(Page { + results: page + .results + .into_iter() + .map(|index| { + let root = &state.posts[index]; + let last = root.latest_reply.map(|reply| &state.posts[reply]); + ThreadSummary { + thread_id: root.metadata.message_id, + root_post: root.preview(chars), + reply_count: root.replies.len(), + last_activity_at: last.map_or(root.metadata.created_at, |last| { + last.metadata.created_at.max(root.metadata.created_at) + }), + latest_reply: last.map(|post| post.preview(chars)), + } + }) + .collect(), + next_cursor: page.next_cursor, + }) + }) + } + + fn search_posts( + &self, + caller: ThreadId, + query: PostQuery, + ) -> BoxFuture<'_, Result>> { + Box::pin(async move { + self.host.agent_path(caller).await?; + let search = query.query.as_deref().map(default_case_fold_str); + let state = self.state.lock().await; + let after = query + .after_message_id + .map(|id| state.post_index(id).map(|index| state.key(index))) + .transpose()?; + let mut posts: Vec<_> = match &query.channel_name { + Some(channel) => state + .channels + .get(channel) + .map(|channel| channel.posts.clone()) + .unwrap_or_default(), + None => (0..state.posts.len()).collect(), + }; + posts.retain(|index| { + let post = &state.posts[*index]; + query + .author + .as_ref() + .is_none_or(|author| *author == post.metadata.author) + && search + .as_ref() + .is_none_or(|text| post.search.contains(text)) + && after.is_none_or(|after| state.key(*index) > after) + }); + posts.sort_unstable_by_key(|index| Reverse(state.key(*index))); + let page = page(&query.page, posts)?; + let chars = + (query.max_chars_per_post.get() as usize).min(20_000 / page.results.len().max(1)); + Ok(Page { + results: page + .results + .into_iter() + .map(|index| state.posts[index].preview(chars)) + .collect(), + next_cursor: page.next_cursor, + }) + }) + } + + fn read_thread( + &self, + caller: ThreadId, + request: ReadThreadRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + self.host.agent_path(caller).await?; + let state = self.state.lock().await; + let root = &state.posts[state.thread_index(request.thread_id)?]; + let mut replies = root.replies.clone(); + replies.sort_unstable_by_key(|index| Reverse(state.key(*index))); + let page = page(&request.page, replies)?; + let chars = + (request.max_chars_per_post.get() as usize).min(20_000 / (page.results.len() + 1)); + Ok(ThreadPage { + root_post: root.preview(chars), + replies: Page { + results: page + .results + .into_iter() + .map(|index| state.posts[index].preview(chars)) + .collect(), + next_cursor: page.next_cursor, + }, + }) + }) + } +} + +fn page(request: &PageRequest, results: Vec) -> Result> { + let offset = match &request.cursor { + Some(cursor) => { + let mut bytes = [0; 4]; + let len = BASE64_URL_SAFE_NO_PAD + .decode_slice(cursor, &mut bytes) + .map_err(|_| invalid("invalid cursor"))?; + if len != bytes.len() { + return Err(invalid("invalid cursor")); + } + u32::from_be_bytes(bytes) + } + None => 0, + }; + let limit = (request.limit.get() as usize).min(50); + let mut results: Vec<_> = results + .into_iter() + .skip(offset as usize) + .take(limit + 1) + .collect(); + let has_more = results.len() > limit; + results.truncate(limit); + let next_cursor = if has_more { + let offset = offset + .checked_add(results.len() as u32) + .ok_or_else(|| invalid("cursor offset exceeds the board limit"))?; + Some(BASE64_URL_SAFE_NO_PAD.encode(offset.to_be_bytes())) + } else { + None + }; + Ok(Page { + results, + next_cursor, + }) +} diff --git a/codex-rs/ext/agent-message-board/src/lib.rs b/codex-rs/ext/agent-message-board/src/lib.rs index 509ee24476..534bdc6d5e 100644 --- a/codex-rs/ext/agent-message-board/src/lib.rs +++ b/codex-rs/ext/agent-message-board/src/lib.rs @@ -1,4 +1,4 @@ -//! Shared agent discussions with interchangeable local and remote backends. +//! Shared agent discussions with interchangeable local, in-memory and remote backends. //! //! Board identity and caller identity come from the host. Implementations own //! storage and notification fanout; tools and feature registration are separate. @@ -6,6 +6,7 @@ mod api; mod extension; mod host; +mod in_memory; mod local; mod tools; mod types; @@ -28,6 +29,8 @@ pub use api::ThreadSort; pub use extension::install; pub use host::MessageBoardHost; pub use host::NotificationDelivery; +pub use in_memory::InMemoryAgentMessageBoard; +pub use in_memory::InMemoryMessageBoards; pub use local::LocalAgentMessageBoard; pub use tools::message_board_tools; pub use types::ChannelSummary; diff --git a/codex-rs/ext/agent-message-board/tests/local_board.rs b/codex-rs/ext/agent-message-board/tests/local_board.rs index 6c1eaa0292..c117b587dd 100644 --- a/codex-rs/ext/agent-message-board/tests/local_board.rs +++ b/codex-rs/ext/agent-message-board/tests/local_board.rs @@ -1,4 +1,9 @@ -//! Exercises real local storage through independent handles and host capabilities. +//! Exercises message-board backends through their shared trait and host capabilities. + +#![expect( + clippy::unwrap_used, + reason = "shared test helpers assert successful operations" +)] use std::collections::HashMap; use std::num::NonZeroU32; @@ -383,8 +388,92 @@ async fn shared_handles_resume_posts_and_preserve_subscription_rules() { pool.close().await; } +#[tokio::test] +async fn in_memory_handles_share_posts_deduplicate_calls_and_release_state() { + let root = ThreadId::new(); + let child = ThreadId::new(); + let child_path = AgentPath::root().join("worker").unwrap(); + let host = Arc::new(Host { + clock: AtomicI64::default(), + agent_path_calls: AtomicUsize::default(), + members: [(root, AgentPath::root()), (child, child_path.clone())].into(), + active: AtomicBool::new(true), + fail_notifications: AtomicBool::new(false), + notifications: Mutex::default(), + }); + let boards = InMemoryMessageBoards::default(); + let (board, shared) = tokio::join!( + boards.open(root.into(), host.clone()), + boards.open(root.into(), host.clone()), + ); + let request = PostRequest { + request_id: "same-call".into(), + destination: PostDestination::NewChannel("work".into()), + text: "done".into(), + agents_to_notify: vec![child_path], + }; + let (first, retry) = tokio::join!( + board.post(root, request.clone()), + shared.post(root, request) + ); + let metadata = first.unwrap(); + assert_eq!(retry.unwrap(), metadata); + assert_eq!( + *host.notifications.lock().unwrap(), + vec![(child, metadata.clone())] + ); + let read = ReadPostRequest { + message_id: metadata.message_id, + offset_chars: 0, + limit_chars: NonZeroU32::new(20).unwrap(), + }; + assert_eq!( + shared.read_post(child, read.clone()).await.unwrap(), + PostContent { + metadata, + text: "done".into(), + n_chars: 4, + next_offset_chars: 4 + } + ); + let other = boards.open(SessionId::new(), host.clone()).await; + assert!(other.read_post(root, read.clone()).await.is_err()); + drop(board); + drop(shared); + let fresh = boards.open(root.into(), host).await; + assert!(fresh.read_post(root, read).await.is_err()); +} + +enum Backend { + Local, + InMemory, +} + +impl Backend { + async fn open( + self, + sqlite: &SqliteConfig, + identity: SessionId, + host: Arc, + ) -> Arc { + match self { + Self::Local => Arc::new( + LocalAgentMessageBoard::open(sqlite, identity, host) + .await + .unwrap(), + ), + Self::InMemory => Arc::new(InMemoryAgentMessageBoard::new(identity, host)), + } + } +} + #[tokio::test] async fn failed_requests_do_not_create_channels_or_notify_inactive_agents() { + check_failed_requests_do_not_create_channels_or_notify_inactive_agents(Backend::Local).await; + check_failed_requests_do_not_create_channels_or_notify_inactive_agents(Backend::InMemory).await; +} + +async fn check_failed_requests_do_not_create_channels_or_notify_inactive_agents(backend: Backend) { let dir = tempfile::tempdir().unwrap(); let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into().unwrap()); let root = ThreadId::new(); @@ -398,9 +487,9 @@ async fn failed_requests_do_not_create_channels_or_notify_inactive_agents() { active: AtomicBool::new(false), notifications: Mutex::default(), }); - let board = LocalAgentMessageBoard::open(&sqlite, SessionId::from(root), host.clone()) - .await - .unwrap(); + let board = backend + .open(&sqlite, SessionId::from(root), host.clone()) + .await; let mut request = PostRequest { request_id: "post".into(), destination: PostDestination::NewChannel("work".into()), @@ -452,6 +541,11 @@ async fn failed_requests_do_not_create_channels_or_notify_inactive_agents() { #[tokio::test] async fn queries_enforce_page_and_preview_caps() { + check_queries_enforce_page_and_preview_caps(Backend::Local).await; + check_queries_enforce_page_and_preview_caps(Backend::InMemory).await; +} + +async fn check_queries_enforce_page_and_preview_caps(backend: Backend) { let dir = tempfile::tempdir().unwrap(); let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into().unwrap()); let root = ThreadId::new(); @@ -463,9 +557,7 @@ async fn queries_enforce_page_and_preview_caps() { active: AtomicBool::new(false), notifications: Mutex::default(), }); - let board = LocalAgentMessageBoard::open(&sqlite, root.into(), host) - .await - .unwrap(); + let board = backend.open(&sqlite, root.into(), host).await; board .create_channel( root, @@ -543,6 +635,11 @@ async fn queries_enforce_page_and_preview_caps() { #[tokio::test] async fn queries_page_discussions_and_search_unicode() { + check_queries_page_discussions_and_search_unicode(Backend::Local).await; + check_queries_page_discussions_and_search_unicode(Backend::InMemory).await; +} + +async fn check_queries_page_discussions_and_search_unicode(backend: Backend) { let dir = tempfile::tempdir().unwrap(); let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into().unwrap()); let root = ThreadId::new(); @@ -554,11 +651,7 @@ async fn queries_page_discussions_and_search_unicode() { active: AtomicBool::new(true), notifications: Mutex::default(), }); - let board: Arc = Arc::new( - LocalAgentMessageBoard::open(&sqlite, SessionId::from(root), host) - .await - .unwrap(), - ); + let board = backend.open(&sqlite, SessionId::from(root), host).await; let request = PostRequest { request_id: "first".into(), destination: PostDestination::NewChannel("work".into()), @@ -799,6 +892,14 @@ fn board_tool_call(name: &str, args: serde_json::Value) -> codex_tools::ToolCall #[tokio::test] async fn tools_cover_channel_discussions_subscriptions_and_escaped_previews() { + check_tools_cover_channel_discussions_subscriptions_and_escaped_previews(Backend::Local).await; + check_tools_cover_channel_discussions_subscriptions_and_escaped_previews(Backend::InMemory) + .await; +} + +async fn check_tools_cover_channel_discussions_subscriptions_and_escaped_previews( + backend: Backend, +) { use codex_tools::ToolName; use serde_json::json; let dir = tempfile::tempdir().unwrap(); @@ -814,11 +915,7 @@ async fn tools_cover_channel_discussions_subscriptions_and_escaped_previews() { active: AtomicBool::new(true), notifications: Mutex::default(), }); - let board = Arc::new( - LocalAgentMessageBoard::open(&sqlite, root.into(), host.clone()) - .await - .unwrap(), - ); + let board = backend.open(&sqlite, root.into(), host.clone()).await; let tools = message_board_tools( board, root, @@ -985,6 +1082,15 @@ async fn tools_cover_channel_discussions_subscriptions_and_escaped_previews() { #[tokio::test] async fn tools_validate_arguments_deduplicate_calls_and_bound_unicode_results() { + check_tools_validate_arguments_deduplicate_calls_and_bound_unicode_results(Backend::Local) + .await; + check_tools_validate_arguments_deduplicate_calls_and_bound_unicode_results(Backend::InMemory) + .await; +} + +async fn check_tools_validate_arguments_deduplicate_calls_and_bound_unicode_results( + backend: Backend, +) { use codex_tools::ToolCallSource; use codex_tools::ToolName; use codex_utils_output_truncation::TruncationPolicy; @@ -1003,11 +1109,7 @@ async fn tools_validate_arguments_deduplicate_calls_and_bound_unicode_results() active: AtomicBool::new(true), notifications: Mutex::default(), }); - let board = Arc::new( - LocalAgentMessageBoard::open(&sqlite, root.into(), host.clone()) - .await - .unwrap(), - ); + let board = backend.open(&sqlite, root.into(), host.clone()).await; let tools = message_board_tools( board.clone(), root, diff --git a/codex-rs/features/src/feature_configs.rs b/codex-rs/features/src/feature_configs.rs index d541696e64..b48bc76314 100644 --- a/codex-rs/features/src/feature_configs.rs +++ b/codex-rs/features/src/feature_configs.rs @@ -300,6 +300,9 @@ pub struct MultiAgentV2ConfigToml { /// Disable the model's direct-message tools; spawning and automatic child results remain available. #[serde(skip_serializing_if = "Option::is_none")] pub disable_direct_message: Option, + /// Keep the message board in memory for a training session, including ephemeral sessions. + #[serde(skip_serializing_if = "Option::is_none")] + pub message_board_in_memory: Option, #[serde(skip_serializing_if = "Option::is_none")] pub non_code_mode_only: Option, } diff --git a/codex-rs/features/src/tests.rs b/codex-rs/features/src/tests.rs index bc28a146ea..e11d777440 100644 --- a/codex-rs/features/src/tests.rs +++ b/codex-rs/features/src/tests.rs @@ -744,6 +744,7 @@ hide_spawn_agent_metadata = true expose_spawn_agent_model_overrides = true wait_agent_enabled = false disable_direct_message = true +message_board_in_memory = true non_code_mode_only = true "#, ) @@ -772,6 +773,7 @@ non_code_mode_only = true expose_spawn_agent_model_overrides: Some(true), wait_agent_enabled: Some(false), disable_direct_message: Some(true), + message_board_in_memory: Some(true), non_code_mode_only: Some(true), })) );