Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions codex-rs/core/tests/suite/scenarios_agent_message_board.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,9 @@ async fn board_post_and_reads_reach_model_context_without_self_notices(
) -> anyhow::Result<()> {
let server = responses::start_mock_server().await;
let mock = responses::mount_sse_sequence(&server, vec![
tool("post-decision", "post", json!({"new_channel_name":"design", "text":"A shared decision.", "agents_to_notify":["/root"]})),
tool("create-design", "create_channel", json!({"channel_name":"design", "description":"Design decisions and tradeoffs."})),
tool("find-channels", "get_channels", json!({})),
tool("post-decision", "post", json!({"channel_name":"design", "text":"A shared decision.", "agents_to_notify":["/root"]})),
tool("find-decision", "search_posts", json!({"channel_name":"design","query":"decision"})),
done(),
]).await;
Expand All @@ -159,23 +161,34 @@ async fn board_post_and_reads_reach_model_context_without_self_notices(
.with_external_time_provider(std::sync::Arc::new(BoardClock::Available))
.build_with_auto_env(&server)
.await?;
test.submit_turn("Record the decision on the board, notify me, and read it.")
.await?;
test.submit_turn(
"Create and describe a design channel, list it, then post and read the decision.",
)
.await?;
let requests = mock.requests();
assert_eq!(requests.len(), 3);
assert_eq!(requests.len(), 5);
assert!(
responses::namespace_child_tool(&requests[0].body_json(), "collaboration", "post")
.is_some()
);
let output = requests[1]
let channel_result: Value = serde_json::from_str(
&requests[2]
.function_call_output_text("find-channels")
.expect("channel list"),
)?;
assert_eq!(
channel_result["results"],
json!([{ "channel_name":"design", "description":"Design decisions and tradeoffs.", "created_at":"2026-09-18T12:00:00Z", "created_by":"/root", "message_count":0, "last_message_id":null }])
);
let output = requests[3]
.function_call_output_text("post-decision")
.expect("post result");
let post: Value =
serde_json::from_str(&output).with_context(|| format!("post result: {output}"))?;
assert_eq!(post["author"], "/root");
assert_eq!(post["created_at"], "2026-09-18T12:00:00Z");
let result: Value = serde_json::from_str(
&requests[2]
&requests[4]
.function_call_output_text("find-decision")
.expect("search result"),
)?;
Expand Down Expand Up @@ -204,7 +217,7 @@ async fn board_post_and_reads_reach_model_context_without_self_notices(
insta::assert_snapshot!(
"agent_message_board_context",
context_snapshot::format_context_snapshot(
"An active agent posts a shared decision and fetches the text without a self-notification.",
"An active agent describes a channel, lists it, posts a shared decision and reads it without a self-notification.",
&bodies.iter().map(SnapshotEntry::body).collect::<Vec<_>>(),
&ContextSnapshotOptions::default().rewrite_known_segments(),
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
---
source: core/tests/suite/scenarios_agent_message_board.rs
expression: "context_snapshot::format_context_snapshot(\"An active agent posts a shared decision and fetches the text without a self-notification.\",\n&bodies.iter().map(SnapshotEntry::body).collect::<Vec<_>>(),\n&ContextSnapshotOptions::default().rewrite_known_segments(),)"
expression: "context_snapshot::format_context_snapshot(\"An active agent describes a channel, lists it, posts a shared decision and reads it without a self-notification.\",\n&bodies.iter().map(SnapshotEntry::body).collect::<Vec<_>>(),\n&ContextSnapshotOptions::default().rewrite_known_segments(),)"
---
Scenario: An active agent posts a shared decision and fetches the text without a self-notification.
Scenario: An active agent describes a channel, lists it, posts a shared decision and reads it without a self-notification.

## Window 1
-- request 1 (request) --
Expand Down Expand Up @@ -33,10 +33,16 @@ Scenario: An active agent posts a shared decision and fetches the text without a
04:message/user:
<ENVIRONMENT_CONTEXT>
05:message/user:
Record the decision on the board, notify me, and read it.
Create and describe a design channel, list it, then post and read the decision.
-- request 2 (request) --
06:function_call/collaboration.post:{"agents_to_notify":["/root"],"new_channel_name":"design","text":"A shared decision."}
07:function_call_output:{"author":"/root","channel_name":"design","created_at":"2026-09-18T12:00:00Z","message_id":"<UUID 1>","thread_id":"<UUID 1>"}
06:function_call/collaboration.create_channel:{"channel_name":"design","description":"Design decisions and tradeoffs."}
07:function_call_output:{"channel_name":"design","created_at":"2026-09-18T12:00:00Z","created_by":"/root","description":"Design ...tradeoffs.","last_message_id":null,"message_count":0} [hash=48975f3c1a0c0378]
-- request 3 (request) --
08:function_call/collaboration.search_posts:{"channel_name":"design","query":"decision"}
09:function_call_output:{"has_more":false,"n_returned":1,"next_cursor":null,"results":[{"author":"/root","channel_name":"design"...ecision.","thread_id":"<UUID 1>","truncated":false}]} [hash=facdb1e4f66cc5b9]
08:function_call/collaboration.get_channels:{}
09:function_call_output:{"has_more":false,"n_returned":1,"next_cursor":null,"results":[{"channel_name":"design","created_at":"20...adeoffs.","last_message_id":null,"message_count":0}]} [hash=7c1cdfeb5b4b833d]
-- request 4 (request) --
10:function_call/collaboration.post:{"agents_to_notify":["/root"],"channel_name":"design","text":"A shared decision."}
11:function_call_output:{"author":"/root","channel_name":"design","created_at":"2026-09-18T12:00:00Z","message_id":"<UUID 1>","thread_id":"<UUID 1>"}
-- request 5 (request) --
12:function_call/collaboration.search_posts:{"channel_name":"design","query":"decision"}
13:function_call_output:{"has_more":false,"n_returned":1,"next_cursor":null,"results":[{"author":"/root","channel_name":"design"...ecision.","thread_id":"<UUID 1>","truncated":false}]} [hash=facdb1e4f66cc5b9]
35 changes: 35 additions & 0 deletions codex-rs/ext/agent-message-board/src/api.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! Operations on one board. Requests describe intent independently of tool schemas.
//! Channel descriptions enforce their byte limit at construction and deserialization.

use crate::ChannelSummary;
use crate::Page;
Expand All @@ -11,6 +12,7 @@ use crate::ThreadSummary;
use codex_protocol::AgentPath;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result;
use futures::future::BoxFuture;
use serde::Deserialize;
Expand Down Expand Up @@ -119,9 +121,42 @@ pub enum SubscriptionChange {
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CreateChannelRequest {
pub channel_name: String,
/// Optional channel purpose, at most 512 UTF-8 bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<ChannelDescription>,
pub subscription: SubscriptionChange,
}

/// A channel purpose containing at most 512 UTF-8 bytes.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "String")]
pub struct ChannelDescription(String);

impl TryFrom<String> for ChannelDescription {
type Error = CodexErr;

fn try_from(text: String) -> Result<Self> {
if text.len() > 512 {
return Err(CodexErr::InvalidRequest(
"channel descriptions must contain at most 512 UTF-8 bytes".into(),
));
}
Ok(Self(text))
}
}

impl ChannelDescription {
pub fn as_str(&self) -> &str {
&self.0
}
}

impl From<ChannelDescription> for String {
fn from(description: ChannelDescription) -> Self {
description.0
}
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelQuery {
pub query: Option<String>,
Expand Down
18 changes: 15 additions & 3 deletions codex-rs/ext/agent-message-board/src/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,13 @@ impl State {
.transpose()
}

fn insert_channel(&mut self, name: &str, author: AgentPath, now: DateTime<Utc>) -> Result<()> {
fn insert_channel(
&mut self,
name: &str,
description: Option<String>,
author: AgentPath,
now: DateTime<Utc>,
) -> Result<()> {
if name.is_empty()
|| name.len() > 128
|| name.trim() != name
Expand All @@ -167,6 +173,7 @@ impl State {
Channel {
summary: ChannelSummary {
channel_name: name.to_owned(),
description,
created_at: now,
created_by: author,
message_count: 0,
Expand Down Expand Up @@ -206,7 +213,12 @@ impl InMemoryAgentMessageBoard {
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)?;
state.insert_channel(
&request.channel_name,
request.description.map(String::from),
author,
now,
)?;
if request.subscription == SubscriptionChange::Subscribe {
state.subscribe(
SubscriptionTarget::Channel(request.channel_name.clone()),
Expand Down Expand Up @@ -258,7 +270,7 @@ impl InMemoryAgentMessageBoard {
(name.clone(), id, SubscriptionTarget::Channel(name.clone()))
}
PostDestination::NewChannel(name) => {
state.insert_channel(name, author.clone(), now)?;
state.insert_channel(name, /*description*/ None, author.clone(), now)?;
state.subscribe(SubscriptionTarget::Channel(name.clone()), caller);
(name.clone(), id, SubscriptionTarget::Channel(name.clone()))
}
Expand Down
1 change: 1 addition & 0 deletions codex-rs/ext/agent-message-board/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod tools;
mod types;

pub use api::AgentMessageBoard;
pub use api::ChannelDescription;
pub use api::ChannelQuery;
pub use api::CreateChannelRequest;
pub use api::PageRequest;
Expand Down
44 changes: 36 additions & 8 deletions codex-rs/ext/agent-message-board/src/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
//! Live handles in this process share one connection pool per database path.
//! Accepted posts survive runtime unload and process restart, but cannot recreate
//! a board after its root has been permanently deleted.
//! Opening storage adds optional channel metadata without invalidating older readers.

use crate::ChannelDescription;
use crate::ChannelSummary;
use crate::CreateChannelRequest;
use crate::MessageBoardHost;
Expand Down Expand Up @@ -61,7 +63,7 @@ static POOLS: LazyLock<Mutex<HashMap<PathBuf, Weak<SqlitePool>>>> = LazyLock::ne
const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS deleted_boards (board TEXT PRIMARY KEY NOT NULL);
CREATE TABLE IF NOT EXISTS channels (
board TEXT NOT NULL, name TEXT NOT NULL, name_search TEXT NOT NULL, created_at TEXT NOT NULL, timestamp INTEGER NOT NULL, author TEXT NOT NULL,
board TEXT NOT NULL, name TEXT NOT NULL, name_search TEXT NOT NULL, created_at TEXT NOT NULL, timestamp INTEGER NOT NULL, author TEXT NOT NULL, description TEXT,
PRIMARY KEY(board,name)
);
CREATE TABLE IF NOT EXISTS posts (
Expand Down Expand Up @@ -128,10 +130,27 @@ impl LocalAgentMessageBoard {
.open_read_write_pool(&path)
.await
.map_err(storage_error)?;
let mut tx = pool
.begin_with("BEGIN IMMEDIATE")
.await
.map_err(storage_error)?;
sqlx::raw_sql(SCHEMA)
.execute(&pool)
.execute(&mut *tx)
.await
.map_err(storage_error)?;
let has_description: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM pragma_table_info('channels') WHERE name='description')",
)
.fetch_one(&mut *tx)
.await
.map_err(storage_error)?;
if !has_description {
sqlx::query("ALTER TABLE channels ADD COLUMN description TEXT")
.execute(&mut *tx)
.await
.map_err(storage_error)?;
}
tx.commit().await.map_err(storage_error)?;
let pool = Arc::new(pool);
pools.insert(path, Arc::downgrade(&pool));
pool
Expand All @@ -152,8 +171,14 @@ impl LocalAgentMessageBoard {
let author = self.host.agent_path(caller).await?;
let now = self.host.current_time(caller).await?;
let mut tx = self.begin_write().await?;
self.insert_channel(&mut tx, &request.channel_name, &author, now)
.await?;
self.insert_channel(
&mut tx,
&request.channel_name,
request.description.as_ref().map(ChannelDescription::as_str),
&author,
now,
)
.await?;
if request.subscription == SubscriptionChange::Subscribe {
self.subscribe(
&mut tx,
Expand Down Expand Up @@ -234,7 +259,8 @@ impl LocalAgentMessageBoard {
}
PostDestination::NewChannel(channel) => {
validate_channel(channel)?;
self.insert_channel(&mut tx, channel, &author, now).await?;
self.insert_channel(&mut tx, channel, /*description*/ None, &author, now)
.await?;
self.subscribe(
&mut tx,
&SubscriptionTarget::Channel(channel.clone()),
Expand Down Expand Up @@ -398,11 +424,12 @@ impl LocalAgentMessageBoard {
&self,
conn: &mut SqliteConnection,
name: &str,
description: Option<&str>,
author: &AgentPath,
now: DateTime<Utc>,
) -> Result<()> {
let inserted = sqlx::query("INSERT OR IGNORE INTO channels(board,name,name_search,created_at,timestamp,author) VALUES(?,?,?,?,?,?)")
.bind(self.identity.to_string()).bind(name).bind(default_case_fold_str(name)).bind(now.to_rfc3339()).bind(now.timestamp_micros()).bind(author.to_string())
let inserted = sqlx::query("INSERT OR IGNORE INTO channels(board,name,name_search,created_at,timestamp,author,description) VALUES(?,?,?,?,?,?,?)")
.bind(self.identity.to_string()).bind(name).bind(default_case_fold_str(name)).bind(now.to_rfc3339()).bind(now.timestamp_micros()).bind(author.to_string()).bind(description)
.execute(conn).await.map_err(storage_error)?.rows_affected();
if inserted == 0 {
return Err(invalid("channel already exists"));
Expand Down Expand Up @@ -465,7 +492,7 @@ impl LocalAgentMessageBoard {
name: &str,
) -> Result<ChannelSummary> {
let row = sqlx::query(
"SELECT c.created_at,c.author,
"SELECT c.created_at,c.author,c.description,
(SELECT COUNT(*) FROM posts p WHERE p.board=c.board AND p.channel=c.name) AS message_count,
(SELECT p.id FROM posts p WHERE p.board=c.board AND p.channel=c.name ORDER BY p.timestamp DESC,p.seq DESC LIMIT 1) AS last_message_id
FROM channels c WHERE c.board=? AND c.name=?",
Expand All @@ -478,6 +505,7 @@ impl LocalAgentMessageBoard {
.ok_or_else(|| invalid("channel not found in this board"))?;
Ok(ChannelSummary {
channel_name: name.to_string(),
description: row.get("description"),
created_at: DateTime::parse_from_rfc3339(row.get("created_at"))
.map_err(storage_error)?
.with_timezone(&Utc),
Expand Down
11 changes: 10 additions & 1 deletion codex-rs/ext/agent-message-board/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,15 +169,24 @@ impl BoardTool {
"create_channel" => {
let arguments::CreateChannel {
channel_name,
description,
subscribe,
} = serde_json::from_str(raw).map_err(model_error)?;
self.check_mutation_budget(budget, /*target_path_bytes*/ 0)?;
// JSON can escape each description byte into six output bytes.
let description_budget = description
.as_ref()
.map_or(0, |text| text.as_str().len() * 6);
self.check_mutation_budget(
budget.saturating_sub(description_budget),
/*target_path_bytes*/ 0,
)?;
encode(
board
.create_channel(
caller,
CreateChannelRequest {
channel_name,
description,
subscription: if subscribe.unwrap_or(true) {
SubscriptionChange::Subscribe
} else {
Expand Down
2 changes: 2 additions & 0 deletions codex-rs/ext/agent-message-board/src/tools/arguments.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Flat model arguments; runtime identities are supplied by the host.

use crate::ChannelDescription;
use crate::ThreadSort;
use serde::Deserialize;
use std::num::NonZeroU32;
Expand All @@ -9,6 +10,7 @@ use uuid::Uuid;
#[serde(deny_unknown_fields)]
pub(super) struct CreateChannel {
pub(super) channel_name: String,
pub(super) description: Option<ChannelDescription>,
pub(super) subscribe: Option<bool>,
}

Expand Down
5 changes: 4 additions & 1 deletion codex-rs/ext/agent-message-board/src/tools/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub(super) fn tool(
let (description, fields, required): (&str, &[&str], &[&str]) = match name {
"create_channel" => (
"Create a channel where all agents in this collaboration can read and post messages. You are subscribed to new top-level posts by default.",
&["channel_name", "subscribe"],
&["channel_name", "description", "subscribe"],
&["channel_name"],
),
"get_channels" => (
Expand Down Expand Up @@ -97,6 +97,9 @@ pub(super) fn tool(
let mut properties = serde_json::Map::new();
for field in fields {
let schema = match *field {
"description" => {
json!({"type":"string","description":"Optional channel purpose, at most 512 UTF-8 bytes."})
}
"new_channel_name" => {
json!({"type":"string","description":"Create and subscribe to this channel."})
}
Expand Down
2 changes: 2 additions & 0 deletions codex-rs/ext/agent-message-board/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ pub struct ThreadSummary {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelSummary {
pub channel_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
pub created_at: DateTime<Utc>,
pub created_by: AgentPath,
pub message_count: usize,
Expand Down
Loading
Loading