diff --git a/codex-rs/agent-message-board-client/src/client.rs b/codex-rs/agent-message-board-client/src/client.rs index 052c634ba3..ef2d00b9ca 100644 --- a/codex-rs/agent-message-board-client/src/client.rs +++ b/codex-rs/agent-message-board-client/src/client.rs @@ -9,16 +9,19 @@ use crate::protocol::Failure; use crate::protocol::MAX_BODY; use crate::protocol::MAX_RESPONSE; use crate::protocol::Operation; +use crate::protocol::PermissionDeniedDetails; use crate::protocol::Registration; use crate::protocol::Watch; use anyhow::Context; use chrono::DateTime; use chrono::Utc; use codex_agent_message_board_extension::AgentMessageBoard; +use codex_agent_message_board_extension::ChannelPage; use codex_agent_message_board_extension::ChannelQuery; use codex_agent_message_board_extension::ChannelSummary; use codex_agent_message_board_extension::CreateChannelRequest; use codex_agent_message_board_extension::Page; +use codex_agent_message_board_extension::PermissionDenied; use codex_agent_message_board_extension::PostContent; use codex_agent_message_board_extension::PostMetadata; use codex_agent_message_board_extension::PostPreview; @@ -320,12 +323,7 @@ impl AgentMessageBoard for RemoteAgentMessageBoard { CreateChannelRequest, ChannelSummary ); - operation!( - list_channels, - ListChannels, - ChannelQuery, - Page - ); + operation!(list_channels, ListChannels, ChannelQuery, ChannelPage); operation!(post, Post, PostRequest, PostMetadata); operation!(list_threads, ListThreads, ThreadQuery, Page); operation!(search_posts, SearchPosts, PostQuery, Page); @@ -389,6 +387,15 @@ async fn decode(mut response: HttpResponse) -> Result { let failure: Failure = serde_json::from_slice(&body) .with_context(|| format!("invalid board error response (HTTP {status})")) .map_err(transport_error)?; + if status == http::StatusCode::FORBIDDEN && failure.code == "permission_denied" { + let details: PermissionDeniedDetails = serde_json::from_slice(&body)?; + return Err(PermissionDenied { + message: failure.message, + action: details.action, + resource: details.resource, + } + .into()); + } let message = format!("{}: {}", failure.code, failure.message); return Err(if status.is_server_error() { transport_error(message) diff --git a/codex-rs/agent-message-board-client/src/protocol.rs b/codex-rs/agent-message-board-client/src/protocol.rs index 267a7502d3..888fc4f0e3 100644 --- a/codex-rs/agent-message-board-client/src/protocol.rs +++ b/codex-rs/agent-message-board-client/src/protocol.rs @@ -99,3 +99,9 @@ pub(crate) struct Failure { pub(crate) code: String, pub(crate) message: String, } + +#[derive(Deserialize)] +pub(crate) struct PermissionDeniedDetails { + pub(crate) action: Option, + pub(crate) resource: Option, +} diff --git a/codex-rs/core/tests/suite/scenarios_agent_message_board_remote.rs b/codex-rs/core/tests/suite/scenarios_agent_message_board_remote.rs index 2a9873c1fd..fc9615037c 100644 --- a/codex-rs/core/tests/suite/scenarios_agent_message_board_remote.rs +++ b/codex-rs/core/tests/suite/scenarios_agent_message_board_remote.rs @@ -1,11 +1,14 @@ //! Runs existing board tools against a research-provisioned remote board. +use super::super::super::code_mode::custom_tool_output_last_non_empty_text; use super::BoardClock; use super::configure; use super::done; use anyhow::Context; use codex_core::TurnInputRequest; +use codex_features::Feature; use codex_features::RemoteMessageBoardConfigToml; +use codex_protocol::openai_models::ToolMode; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; use core_test_support::context_snapshot; @@ -218,3 +221,167 @@ async fn remote_board_uses_the_existing_tools_and_session_identity() -> anyhow:: root.codex.shutdown_and_wait().await?; Ok(()) } + +#[test_case::test_case(false; "direct")] +#[test_case::test_case(true; "code_mode")] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn remote_board_effective_permissions_and_denials(code_mode: bool) -> anyhow::Result<()> { + let server = responses::start_mock_server().await; + let board = responses::start_mock_server().await; + let url = board.uri(); + let root = test_codex() + .with_model("gpt-6-astra") + .with_config(move |config| { + configure(config); + config.ephemeral = true; + for feature in [ + Feature::CodeMode, + Feature::CodeModeOnly, + Feature::CodeModeHost, + ] { + config + .features + .set_enabled(feature, code_mode) + .expect("configure code mode"); + } + config.multi_agent_v2.message_board_remote = Some(RemoteMessageBoardConfigToml { + url, + bearer_token: Some("board-runtime-credential-for-acl-test".into()), + bearer_token_env_var: None, + }); + }) + .with_model_info_override("gpt-6-astra", move |model| { + model.tool_mode = Some(if code_mode { + ToolMode::CodeModeOnly + } else { + ToolMode::Direct + }); + }) + .build_with_auto_env(&server) + .await?; + let root_id = root.session_configured.thread_id; + let metadata = json!({"message_id":"00000000-0000-4000-8000-000000000002","thread_id":"00000000-0000-4000-8000-000000000001","author":"/root","channel_name":"policy","created_at":"2026-09-18T12:00:00Z"}); + let legacy = json!({"results":[{"channel_name":"policy","created_at":"2026-09-18T12:00:00Z","created_by":"/root","message_count":1,"last_message_id":metadata["thread_id"]}],"n_returned":1,"has_more":false,"next_cursor":null}); + let mut restricted = legacy.clone(); + restricted["board_permissions"] = + json!({"create_channel":false,"edit_metadata":false,"manage_permissions":false}); + restricted["results"][0]["permissions"] = + json!({"read":true,"post":false,"reply":true,"edit_metadata":false}); + let denied = json!({"code":"permission_denied","message":"You can reply, but cannot start threads in policy.","action":"channel.post","resource":"board:example/channel:policy"}); + let cases = [ + ( + "legacy", + "get_channels", + json!({"query":"legacy"}), + json!({"method":"list_channels","params":{"query":"legacy"}}), + 200, + legacy, + ), + ( + "permissions", + "get_channels", + json!({"query":"policy"}), + json!({"method":"list_channels","params":{"query":"policy"}}), + 200, + restricted, + ), + ( + "denied", + "post", + json!({"channel_name":"policy","text":"New policy."}), + json!({"method":"post","params":{"destination":{"Channel":"policy"}}}), + 403, + denied, + ), + ( + "reply", + "post", + json!({"thread_id":metadata["thread_id"],"text":"A clarification?"}), + json!({"method":"post","params":{"destination":{"Thread":metadata["thread_id"]}}}), + 200, + metadata, + ), + ]; + let mut steps = Vec::new(); + for (call_id, tool_name, arguments, request, status, result) in &cases { + Mock::given(method("POST")) + .and(path(format!("/v1/boards/{root_id}/call"))) + .and(header( + "authorization", + "Bearer board-runtime-credential-for-acl-test", + )) + .and(body_partial_json(json!({"caller":root_id}))) + .and(body_partial_json(request)) + .respond_with(ResponseTemplate::new(*status).set_body_json(result)) + .expect(/*r*/ 1) + .mount(&board) + .await; + let mut arguments = arguments.clone(); + arguments.sort_all_objects(); + steps.push(if code_mode { + responses::sse(vec![ + responses::ev_custom_tool_call( + call_id, + "exec", + &format!("text(await tools.collaboration__{tool_name}({arguments}));"), + ), + responses::ev_completed(call_id), + ]) + } else { + super::tool(call_id, tool_name, arguments) + }); + } + steps.push(done()); + let model = responses::mount_sse_sequence(&server, steps).await; + root.submit_turn( + "Check board permissions, try publishing, then ask a question in the existing thread.", + ) + .await?; + let requests = model.requests(); + let last = requests.last().context("last request")?; + for (call_id, _, _, _, status, result) in &cases { + let expected = if *status == 403 { + json!({"error":result}) + } else { + result.clone() + }; + let output = if code_mode { + custom_tool_output_last_non_empty_text(last, call_id) + } else { + last.function_call_output_text(call_id) + } + .context("tool output")?; + assert_eq!( + serde_json::from_str::(&output)?, + expected, + "{call_id}" + ); + } + // Snapshot the direct request history; both modes assert the tool results above. + if !code_mode { + let mut bodies = requests + .iter() + .map(responses::ResponsesRequest::body_json) + .collect::>(); + for body in &mut bodies { + for item in body["input"].as_array_mut().context("request input")? { + if item["type"] == "function_call_output" { + item["output"] = context_snapshot::normalize_json_lines( + item["output"].as_str().context("output")?, + ) + .into(); + } + } + } + insta::assert_snapshot!( + "remote_board_permissions_direct", + context_snapshot::format_context_snapshot( + "Permission discovery preserves legacy output, exposes reply-only access, and returns a denied post before an allowed reply.", + &bodies.iter().map(SnapshotEntry::body).collect::>(), + &ContextSnapshotOptions::default().rewrite_known_segments(), + ) + ); + } + root.codex.shutdown_and_wait().await?; + Ok(()) +} diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__agent_message_board__remote__remote_board_permissions_direct.snap b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__agent_message_board__remote__remote_board_permissions_direct.snap new file mode 100644 index 0000000000..c0f63f83b6 --- /dev/null +++ b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__agent_message_board__remote__remote_board_permissions_direct.snap @@ -0,0 +1,60 @@ +--- +source: core/tests/suite/scenarios_agent_message_board_remote.rs +expression: "context_snapshot::format_context_snapshot(\"Permission discovery preserves legacy output, exposes reply-only access, and returns a denied post before an allowed reply.\",\n&bodies.iter().map(SnapshotEntry::body).collect::>(),\n&ContextSnapshotOptions::default().rewrite_known_segments(),)" +--- +Scenario: Permission discovery preserves legacy output, exposes reply-only access, and returns a denied post before an allowed reply. + +## Window 1 +-- request 1 (request) -- +00:additional_tools/developer (3; hash=e49a28343a9fe4ed): + - namespace/functions; hash=c8b8fa91706a7620 + - function/exec_command + - function/write_stdin + - function/request_user_input + - function/request_user_input_async + - custom/apply_patch + - function/view_image + - namespace/clock: Tools for reading and waiting on time.; hash=a80435c7a3a3943f + - function/curr_time + - function/sleep + - namespace/collaboration: Tools for spawning and managing sub-agents.; hash=ba5664aaab81db64 + - function/create_channel + - function/followup_task + - function/get_channels + - function/interrupt_agent + - function/list_agents + - function/list_threads + - function/post + - function/read_post + - function/read_thread + - function/search_posts + - function/send_message + - function/spawn_agent + - function/subscribe + - function/unsubscribe + - function/wait_agent +01:message/developer: + +02:message/developer[2]: + [01] + [02] +03:message/developer: + +04:message/developer: + +05:message/user: + +06:message/user: + Check board permissions, try publishing, then ask a question in the existing thread. +-- request 2 (request) -- +07:function_call/collaboration.get_channels:{"query":"legacy"} +08:function_call_output:{"has_more":false,"n_returned":1,"next_cursor":null,"results":[{"channel_name":"policy","created_at":"20...ot","last_message_id":"","message_count":1}]} [hash=555caa1996907423] +-- request 3 (request) -- +09:function_call/collaboration.get_channels:{"query":"policy"} +10:function_call_output:{"board_permissions":{"create_channel":false,"edit_metadata":false,"manage_permissions":false},"has_more...data":false,"post":false,"read":true,"reply":true}}]} [hash=961b427452007daf] +-- request 4 (request) -- +11:function_call/collaboration.post:{"channel_name":"policy","text":"New policy."} +12:function_call_output:{"error":{"action":"channel.post","code":"permission_denied","message":"You can reply, but cannot start ... policy.","resource":"board:example/channel:policy"}} [hash=890040530da635c0] +-- request 5 (request) -- +13:function_call/collaboration.post:{"text":"A clarification?","thread_id":""} +14:function_call_output:{"author":"/root","channel_name":"policy","created_at":"2026-09-18T12:00:00Z","message_id":"","thread_id":""} diff --git a/codex-rs/ext/agent-message-board/src/api.rs b/codex-rs/ext/agent-message-board/src/api.rs index aa5c1648b0..e4e0b9c34b 100644 --- a/codex-rs/ext/agent-message-board/src/api.rs +++ b/codex-rs/ext/agent-message-board/src/api.rs @@ -1,6 +1,7 @@ //! Operations on one board. Requests describe intent independently of tool schemas. //! Channel descriptions enforce their byte limit at construction and deserialization. +use crate::ChannelPage; use crate::ChannelSummary; use crate::Page; use crate::PostContent; @@ -48,7 +49,7 @@ pub trait AgentMessageBoard: Send + Sync { &self, caller: ThreadId, query: ChannelQuery, - ) -> BoxFuture<'_, Result>>; + ) -> BoxFuture<'_, Result>; /// Uses the caller's configured clock; clock failures must not create a post. /// The request ID identifies a logical call across retries. A retry with diff --git a/codex-rs/ext/agent-message-board/src/in_memory.rs b/codex-rs/ext/agent-message-board/src/in_memory.rs index 8388097a85..1c1b4fda50 100644 --- a/codex-rs/ext/agent-message-board/src/in_memory.rs +++ b/codex-rs/ext/agent-message-board/src/in_memory.rs @@ -172,6 +172,7 @@ impl State { name.to_owned(), Channel { summary: ChannelSummary { + permissions: None, channel_name: name.to_owned(), description, created_at: now, 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 index 385ad9006d..3951280f10 100644 --- a/codex-rs/ext/agent-message-board/src/in_memory/queries.rs +++ b/codex-rs/ext/agent-message-board/src/in_memory/queries.rs @@ -3,6 +3,7 @@ use super::InMemoryAgentMessageBoard; use super::invalid; use crate::AgentMessageBoard; +use crate::ChannelPage; use crate::ChannelQuery; use crate::ChannelSummary; use crate::CreateChannelRequest; @@ -86,7 +87,7 @@ impl AgentMessageBoard for InMemoryAgentMessageBoard { &self, caller: ThreadId, query: ChannelQuery, - ) -> BoxFuture<'_, Result>> { + ) -> BoxFuture<'_, Result> { Box::pin(async move { self.host.agent_path(caller).await?; let search = default_case_fold_str(&query.query.unwrap_or_default()); @@ -109,13 +110,16 @@ impl AgentMessageBoard for InMemoryAgentMessageBoard { 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, + Ok(ChannelPage { + channels: Page { + results: page + .results + .into_iter() + .map(|channel| channel.summary.clone()) + .collect(), + next_cursor: page.next_cursor, + }, + board_permissions: None, }) }) } diff --git a/codex-rs/ext/agent-message-board/src/lib.rs b/codex-rs/ext/agent-message-board/src/lib.rs index 907771047f..78e0e0d09b 100644 --- a/codex-rs/ext/agent-message-board/src/lib.rs +++ b/codex-rs/ext/agent-message-board/src/lib.rs @@ -8,6 +8,7 @@ mod extension; mod host; mod in_memory; mod local; +mod permissions; mod tools; mod types; @@ -33,7 +34,11 @@ pub use host::NotificationDelivery; pub use in_memory::InMemoryAgentMessageBoard; pub use in_memory::InMemoryMessageBoards; pub use local::LocalAgentMessageBoard; +pub use permissions::BoardPermissions; +pub use permissions::ChannelPermissions; +pub use permissions::PermissionDenied; pub use tools::message_board_tools; +pub use types::ChannelPage; pub use types::ChannelSummary; pub use types::Page; pub use types::PostContent; diff --git a/codex-rs/ext/agent-message-board/src/local.rs b/codex-rs/ext/agent-message-board/src/local.rs index caee300cd1..56f90b81eb 100644 --- a/codex-rs/ext/agent-message-board/src/local.rs +++ b/codex-rs/ext/agent-message-board/src/local.rs @@ -504,6 +504,7 @@ impl LocalAgentMessageBoard { .map_err(storage_error)? .ok_or_else(|| invalid("channel not found in this board"))?; Ok(ChannelSummary { + permissions: None, channel_name: name.to_string(), description: row.get("description"), created_at: DateTime::parse_from_rfc3339(row.get("created_at")) diff --git a/codex-rs/ext/agent-message-board/src/local/queries.rs b/codex-rs/ext/agent-message-board/src/local/queries.rs index 44f084247e..ead816a66c 100644 --- a/codex-rs/ext/agent-message-board/src/local/queries.rs +++ b/codex-rs/ext/agent-message-board/src/local/queries.rs @@ -10,6 +10,7 @@ use super::paging::direction; use super::paging::preview; use super::storage_error; use crate::AgentMessageBoard; +use crate::ChannelPage; use crate::ChannelQuery; use crate::ChannelSummary; use crate::CreateChannelRequest; @@ -75,7 +76,7 @@ impl AgentMessageBoard for LocalAgentMessageBoard { &self, caller: ThreadId, query: ChannelQuery, - ) -> BoxFuture<'_, Result>> { + ) -> BoxFuture<'_, Result> { Box::pin(async move { self.host.agent_path(caller).await?; let mut tx = self.pool.begin().await.map_err(storage_error)?; @@ -106,7 +107,10 @@ impl AgentMessageBoard for LocalAgentMessageBoard { for name in names { channels.push(self.channel_summary(&mut tx, &name).await?); } - window.finish(channels) + Ok(ChannelPage { + channels: window.finish(channels)?, + board_permissions: None, + }) }) } diff --git a/codex-rs/ext/agent-message-board/src/permissions.rs b/codex-rs/ext/agent-message-board/src/permissions.rs new file mode 100644 index 0000000000..09804ada71 --- /dev/null +++ b/codex-rs/ext/agent-message-board/src/permissions.rs @@ -0,0 +1,84 @@ +//! Service-computed permissions and denials. Codex exposes these without evaluating ACLs. + +use codex_protocol::error::CodexErr; +use codex_tools::FunctionCallError; +use serde::Deserialize; +use serde::Serialize; +use serde_json::Value; +use serde_json::json; +use std::fmt; + +/// Effective board actions for the authenticated caller, not an ACL definition. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct BoardPermissions { + pub create_channel: bool, + pub edit_metadata: bool, + pub manage_permissions: bool, +} + +/// Effective channel actions; replying does not imply permission to start a thread. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChannelPermissions { + pub read: bool, + pub post: bool, + pub reply: bool, + pub edit_metadata: bool, +} + +/// A service denial retained through the board's existing error interface. +#[derive(Clone, Debug, Serialize)] +#[serde(tag = "code", rename = "permission_denied")] +pub struct PermissionDenied { + pub message: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub action: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub resource: Option, +} + +impl fmt::Display for PermissionDenied { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "permission_denied: {}", self.message) + } +} + +impl std::error::Error for PermissionDenied {} + +impl From for CodexErr { + fn from(error: PermissionDenied) -> Self { + Self::Io(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + error, + )) + } +} + +impl PermissionDenied { + pub(crate) fn model_response(&self, budget: usize) -> Result { + // Keep the denial structured and below 1k tokens, even for oversized service text. + let mut limit = 512; + loop { + let truncated = std::iter::once(self.message.as_str()) + .chain(self.action.as_deref()) + .chain(self.resource.as_deref()) + .any(|text| text.chars().count() > limit); + let mut result = json!({"error": Self { + message: self.message.chars().take(limit).collect(), + action: self.action.as_ref().map(|text| text.chars().take(limit).collect()), + resource: self.resource.as_ref().map(|text| text.chars().take(limit).collect()), + }}); + if truncated { + result["error"]["truncated"] = json!(true); + } + if result.to_string().len() <= budget.min(/*other*/ 768) { + return Ok(result); + } + if limit == 0 { + return Err(FunctionCallError::RespondToModel( + "permission_denied: output budget too small for the error".into(), + )); + } + limit /= 2; + } + } +} diff --git a/codex-rs/ext/agent-message-board/src/tools.rs b/codex-rs/ext/agent-message-board/src/tools.rs index 1496955135..7537637a57 100644 --- a/codex-rs/ext/agent-message-board/src/tools.rs +++ b/codex-rs/ext/agent-message-board/src/tools.rs @@ -7,6 +7,7 @@ use crate::AgentMessageBoard; use crate::ChannelQuery; use crate::CreateChannelRequest; use crate::PageRequest; +use crate::PermissionDenied; use crate::PostDestination; use crate::PostQuery; use crate::PostRequest; @@ -20,6 +21,7 @@ use crate::ThreadQuery; use crate::ThreadSort; use codex_protocol::AgentPath; use codex_protocol::ThreadId; +use codex_protocol::error::CodexErrorDetails; use codex_protocol::openai_models::MultiAgentToolMessages; use codex_tools::FunctionCallError; use codex_tools::JsonToolOutput; @@ -128,15 +130,22 @@ impl<'call> ToolExecutor> for BoardTool { return Err(model_error("message-board arguments exceed 128 KiB")); } let budget = call.response_byte_budget(MAX_RESPONSE_BYTES); - let result = self.execute(raw, &call, budget).await?; + let (result, success) = match self.execute(raw, &call, budget).await { + Ok(result) => (result, true), + Err(BoardToolError::Model(error)) => return Err(error), + Err(BoardToolError::PermissionDenied(denied)) => { + (denied.model_response(budget)?, false) + } + }; if result.to_string().len() > budget { return Err(model_error( "Result exceeds the output budget. Reduce limit or max_chars_per_post; use read_post with a smaller limit_chars for long posts.", )); } Ok( - Box::new(JsonToolOutput::new(result).with_external_context()) - as Box, + Box::new( + JsonToolOutput::with_success(result, Some(success)).with_external_context(), + ) as Box, ) }) } @@ -148,7 +157,7 @@ impl BoardTool { raw: &str, call: &ToolCall<'_>, budget: usize, - ) -> Result { + ) -> Result { let board = &self.board; let caller = self.caller; let page_limit = |limit: Option| limit.map_or(20, NonZeroU32::get).min(50); @@ -324,9 +333,9 @@ impl BoardTool { (Some(channel), None) => SubscriptionTarget::Channel(channel), (None, Some(thread)) => SubscriptionTarget::Thread(thread), _ => { - return Err(model_error( - "Supply exactly one of channel_name or thread_id", - )); + return Err( + model_error("Supply exactly one of channel_name or thread_id").into(), + ); } }; encode( @@ -365,7 +374,8 @@ impl BoardTool { _ => { return Err(model_error( "Supply exactly one of channel_name, new_channel_name or thread_id", - )); + ) + .into()); } }; let invocation = match &call.source { @@ -420,7 +430,7 @@ async fn bounded_read<'a, T: Serialize>( budget: usize, largest_limit: u32, fetch: impl Fn(u32) -> BoxFuture<'a, codex_protocol::error::Result>, -) -> Result { +) -> Result { let mut scale = 1; loop { let result = encode(fetch(scale).await)?; @@ -432,9 +442,7 @@ async fn bounded_read<'a, T: Serialize>( } scale *= 2; } - Err(model_error( - "The output budget is too small for this result's metadata.", - )) + Err(model_error("The output budget is too small for this result's metadata.").into()) } fn nonzero(value: u32) -> NonZeroU32 { @@ -443,8 +451,28 @@ fn nonzero(value: u32) -> NonZeroU32 { fn model_error(error: impl std::fmt::Display) -> FunctionCallError { FunctionCallError::RespondToModel(error.to_string().chars().take(512).collect()) } -fn encode( - value: codex_protocol::error::Result, -) -> Result { - serde_json::to_value(value.map_err(model_error)?).map_err(model_error) +enum BoardToolError { + Model(FunctionCallError), + PermissionDenied(PermissionDenied), +} + +impl From for BoardToolError { + fn from(error: FunctionCallError) -> Self { + Self::Model(error) + } +} + +fn encode(value: codex_protocol::error::Result) -> Result { + let value = value.map_err(|error| { + if let CodexErrorDetails::Io(io) = error.details() + && let Some(denied) = io + .get_ref() + .and_then(|source| source.downcast_ref::()) + { + BoardToolError::PermissionDenied(denied.clone()) + } else { + BoardToolError::Model(model_error(error)) + } + })?; + serde_json::to_value(value).map_err(|error| model_error(error).into()) } diff --git a/codex-rs/ext/agent-message-board/src/types.rs b/codex-rs/ext/agent-message-board/src/types.rs index 9c870a7bf3..02e8ab0b1a 100644 --- a/codex-rs/ext/agent-message-board/src/types.rs +++ b/codex-rs/ext/agent-message-board/src/types.rs @@ -1,5 +1,7 @@ //! Message-board records shared by backends and tool adapters. +use crate::BoardPermissions; +use crate::ChannelPermissions; use chrono::DateTime; use chrono::Utc; use codex_protocol::AgentPath; @@ -47,6 +49,9 @@ pub struct ThreadSummary { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ChannelSummary { + /// Absent on boards without ACL metadata; preserve the legacy wire shape. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub permissions: Option, pub channel_name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option, @@ -56,6 +61,15 @@ pub struct ChannelSummary { pub last_message_id: Option, } +/// Channel discovery also exposes board actions, including when there are no channels. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChannelPage { + #[serde(flatten)] + pub channels: Page, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub board_permissions: Option, +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct SubscriptionState { pub channel_name: String, 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 98f8b4d72b..002bb7df49 100644 --- a/codex-rs/ext/agent-message-board/tests/local_board.rs +++ b/codex-rs/ext/agent-message-board/tests/local_board.rs @@ -656,8 +656,8 @@ async fn check_queries_enforce_page_and_preview_caps(backend: Backend) { ) .await .unwrap(); - assert_eq!(channels.results.len(), 1); - assert_eq!(channels.results[0].description, None); + assert_eq!(channels.channels.results.len(), 1); + assert_eq!(channels.channels.results[0].description, None); let query = PostQuery { channel_name: None, query: Some("STRASSE".into()), @@ -905,8 +905,11 @@ async fn check_queries_page_discussions_and_search_unicode(backend: Backend) { ) .await .unwrap(); - assert_eq!(channels.results[0].message_count, 3); - assert_eq!(channels.results[0].last_message_id, Some(reply.message_id)); + assert_eq!(channels.channels.results[0].message_count, 3); + assert_eq!( + channels.channels.results[0].last_message_id, + Some(reply.message_id) + ); assert!( board .read_thread( @@ -1005,6 +1008,7 @@ async fn check_tools_cover_channel_discussions_subscriptions_and_escaped_preview ChannelSummary { channel_name: "Workflow".into(), description: Some("é".repeat(256)), + permissions: None, created_at: "2026-09-18T12:00:00Z".parse().unwrap(), created_by: AgentPath::root(), message_count: 0, @@ -1258,6 +1262,7 @@ async fn check_tools_validate_arguments_deduplicate_calls_and_bound_unicode_resu ) .await .unwrap() + .channels .results .is_empty() ); @@ -1448,6 +1453,7 @@ async fn channel_descriptions_migrate_legacy_storage_and_survive_reopen() { let legacy = ChannelSummary { channel_name: "legacy".into(), description: None, + permissions: None, created_at: "2026-09-17T12:00:00Z".parse().unwrap(), created_by: AgentPath::root(), message_count: 0, @@ -1485,7 +1491,7 @@ async fn channel_descriptions_migrate_legacy_storage_and_survive_reopen() { .await .unwrap(); assert_eq!( - listed, + listed.channels, Page { results: vec![created, legacy], next_cursor: None