Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-message-board-client",
crate_name = "akode_agent_message_board_client",
)

View File

@@ -0,0 +1,34 @@
[package]
name = "akode-agent-message-board-client"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
test = false
doctest = false
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true, features = ["serde"] }
akode-message-board = { workspace = true }
akode-extension-api = { workspace = true }
akode-http-client = { workspace = true }
akode-protocol = { workspace = true }
eventsource-stream = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["rt", "time"] }
tokio-util = { workspace = true }
tracing = { workspace = true }
url = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
wiremock = { workspace = true }

View File

@@ -0,0 +1,437 @@
//! Typed remote implementation of the board contract. HTTP policy is supplied
//! by the caller; reads and writes never fall back to a private local board.
//! Live notification frames are bounded before SSE parsing.
use crate::protocol::AccessToken;
use crate::protocol::BoardNotification;
use crate::protocol::Call;
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 akode_http_client::HttpClient;
use akode_http_client::HttpResponse;
use akode_message_board::AgentMessageBoard;
use akode_message_board::AppendRequest;
use akode_message_board::ChannelPage;
use akode_message_board::ChannelQuery;
use akode_message_board::ChannelSummary;
use akode_message_board::CreateChannelRequest;
use akode_message_board::Page;
use akode_message_board::PermissionDenied;
use akode_message_board::PostContent;
use akode_message_board::PostMetadata;
use akode_message_board::PostPreview;
use akode_message_board::PostQuery;
use akode_message_board::PostRequest;
use akode_message_board::ReadPostRequest;
use akode_message_board::ReadThreadRequest;
use akode_message_board::SubscriptionRequest;
use akode_message_board::SubscriptionState;
use akode_message_board::ThreadPage;
use akode_message_board::ThreadQuery;
use akode_message_board::ThreadSummary;
use akode_message_board::UpsertChannelRequest;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result;
use eventsource_stream::Eventsource;
use futures::StreamExt;
use futures::future::BoxFuture;
use futures::stream::BoxStream;
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::error::Error;
use std::sync::Arc;
use std::task::Poll;
use std::time::Duration;
use url::Url;
/// A client for one session's board. Use the shared HTTP client's configured
/// proxy and CA policy.
#[derive(Clone)]
pub struct RemoteAgentMessageBoard {
http: HttpClient,
board_url: Url,
board: SessionId,
token: AccessToken,
clock: Arc<dyn Fn(ThreadId) -> BoxFuture<'static, Result<DateTime<Utc>>> + Send + Sync>,
}
impl RemoteAgentMessageBoard {
/// Validate the HTTP(S) endpoint and append the board path to its optional path prefix.
pub fn new(
http: HttpClient,
endpoint: &str,
board: SessionId,
token: AccessToken,
) -> anyhow::Result<Self> {
let mut board_url = Url::parse(endpoint).context("invalid message-board endpoint")?;
anyhow::ensure!(
matches!(board_url.scheme(), "http" | "https") && board_url.host_str().is_some(),
"message-board endpoint must be an HTTP(S) URL"
);
anyhow::ensure!(
board_url.query().is_none() && board_url.fragment().is_none(),
"message-board endpoint must not contain a query or fragment"
);
board_url.set_path(&format!(
"{}/v1/boards/{board}",
board_url.path().trim_end_matches('/')
));
Ok(Self {
http,
board_url,
board,
token,
clock: Arc::new(|_| Box::pin(async { Ok(Utc::now()) })),
})
}
/// Supply the runtime's configured clock for research's simulated time.
pub fn with_clock(
mut self,
clock: impl Fn(ThreadId) -> BoxFuture<'static, Result<DateTime<Utc>>> + Send + Sync + 'static,
) -> Self {
self.clock = Arc::new(clock);
self
}
pub async fn create_board(&self) -> Result<SessionId> {
let response = self
.http
.request(http::Method::PUT, self.url(""))
.bearer_auth(&self.token.0)
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
decode(response).await
}
pub async fn delete_board(&self) -> Result<()> {
let response = self
.http
.delete(self.url(""))
.bearer_auth(&self.token.0)
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
if response.status().is_success() {
Ok(())
} else {
decode(response).await
}
}
/// Register the session's agents. The returned session token is stable on retry.
pub async fn register_members(
&self,
members: HashMap<ThreadId, AgentPath>,
) -> Result<AccessToken> {
let response = self
.http
.post(self.url("/members"))
.bearer_auth(&self.token.0)
.json(&Registration { members })
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
decode(response).await
}
/// Opens a live receiver and waits until the service has registered it.
/// Setup, including readiness or an error body, has a 30-second deadline.
/// Drop it when the turn ends. Reopening does not replay earlier previews.
pub async fn notifications(
&self,
caller: ThreadId,
turn_id: String,
) -> Result<BoardNotifications> {
let deadline = tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 30);
let response = tokio::time::timeout_at(
deadline,
self.http
.post(self.url("/notifications"))
.bearer_auth(&self.token.0)
.json(&Watch {
caller,
turn_id: turn_id.clone(),
})
.send(),
)
.await
.map_err(transport_error)?
.map_err(transport_error)?;
if !response.status().is_success() {
tracing::warn!(
%caller, %turn_id,
http_status = response.status().as_u16(),
"Remote board notification request rejected"
);
tokio::time::timeout_at(deadline, decode::<()>(response))
.await
.map_err(transport_error)??;
return Err(transport_error("unexpected notification response"));
}
// Count wire bytes before the parser buffers them, resetting at blank lines.
// Defer CR handling so CRLF counts as one line ending even across chunks.
let mut frame_bytes = 0;
let mut line_empty = true;
let mut previous_cr = false;
// Validate before the SSE decoder can retain malformed UTF-8 indefinitely.
// Only an incomplete code point (at most three bytes) carries across chunks.
let mut utf8 = [0; 4];
let mut utf8_len = 0;
let mut chunks = Some(response.bytes_stream());
let mut events = futures::stream::poll_fn(move |cx| {
let Some(source) = chunks.as_mut() else {
return Poll::Ready(None);
};
let Some(chunk) = std::task::ready!(source.poll_next_unpin(cx)) else {
chunks = None;
return Poll::Ready(None);
};
let result = chunk.map_err(transport_error).and_then(|chunk| {
for &byte in chunk.iter() {
if !byte.is_ascii() || utf8_len > 0 {
utf8[utf8_len] = byte;
utf8_len += 1;
match std::str::from_utf8(&utf8[..utf8_len]) {
Ok(_) => utf8_len = 0,
Err(error) if error.error_len().is_some() => {
return Err(transport_error(error));
}
Err(_) => {}
}
}
if previous_cr && byte != b'\n' {
if line_empty {
frame_bytes = 0;
}
line_empty = true;
}
frame_bytes += 1;
if frame_bytes > MAX_BODY {
return Err(transport_error("board SSE frame exceeds the service limit"));
}
match byte {
b'\n' => {
if line_empty {
frame_bytes = 0;
}
line_empty = true;
}
b'\r' => {}
_ => line_empty = false,
}
previous_cr = byte == b'\r';
}
Ok(chunk)
});
if result.is_err() {
chunks = None;
}
Poll::Ready(Some(result))
})
.eventsource();
let ready = tokio::time::timeout_at(deadline, events.next())
.await
.map_err(transport_error)?
.ok_or_else(|| transport_error("notification stream closed before readiness"))?
.map_err(transport_error)?;
if ready.event != "ready" {
return Err(transport_error(
"notification stream did not acknowledge readiness",
));
}
let stream = events.map(|event| event.map_err(transport_error)).boxed();
Ok(BoardNotifications {
caller,
turn_id,
stream,
})
}
fn url(&self, suffix: &str) -> Url {
let mut url = self.board_url.clone();
url.set_path(&format!("{}{suffix}", url.path()));
url
}
async fn call<T: DeserializeOwned>(&self, caller: ThreadId, operation: Operation) -> Result<T> {
let timestamp = match &operation {
Operation::CreateChannel(_) => Some((self.clock)(caller).await?),
// The service can replay a committed post without a fresh timestamp.
// A new post still requires one; never substitute wall-clock time.
Operation::Post(_) => (self.clock)(caller).await.ok(),
Operation::ListChannels(_)
| Operation::ListThreads(_)
| Operation::SearchPosts(_)
| Operation::ReadThread(_)
| Operation::ReadPost(_)
| Operation::SetSubscription(_) => None,
};
let call = Call {
caller,
timestamp,
operation,
};
let body = serde_json::to_vec(&call)?;
if body.len() > MAX_BODY {
return Err(CodexErr::InvalidRequest(
"board request exceeds the service limit".into(),
));
}
let response = self
.http
.post(self.url("/call"))
.bearer_auth(&self.token.0)
.header("content-type", "application/json")
.body(body)
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
decode(response).await
}
}
macro_rules! operation {
($method:ident, $variant:ident, $input:ty, $output:ty) => {
fn $method(&self, caller: ThreadId, request: $input) -> BoxFuture<'_, Result<$output>> {
Box::pin(self.call(caller, Operation::$variant(request)))
}
};
}
impl AgentMessageBoard for RemoteAgentMessageBoard {
fn identity(&self) -> SessionId {
self.board
}
operation!(
create_channel,
CreateChannel,
CreateChannelRequest,
ChannelSummary
);
operation!(list_channels, ListChannels, ChannelQuery, ChannelPage);
fn upsert_channel(
&self,
_caller: ThreadId,
_request: UpsertChannelRequest,
) -> BoxFuture<'_, Result<()>> {
// The service has no description-update operation; creation has different semantics.
Box::pin(async {
Err(CodexErr::InvalidRequest(
"remote message boards do not support channel upsert".into(),
))
})
}
operation!(post, Post, PostRequest, PostMetadata);
fn append(
&self,
_caller: ThreadId,
_request: AppendRequest,
) -> BoxFuture<'_, Result<PostMetadata>> {
// The remote protocol has no silent write operation. Posting is not equivalent.
Box::pin(async {
Err(CodexErr::InvalidRequest(
"remote message boards do not support silent append".into(),
))
})
}
operation!(list_threads, ListThreads, ThreadQuery, Page<ThreadSummary>);
operation!(search_posts, SearchPosts, PostQuery, Page<PostPreview>);
operation!(read_thread, ReadThread, ReadThreadRequest, ThreadPage);
operation!(read_post, ReadPost, ReadPostRequest, PostContent);
operation!(
set_subscription,
SetSubscription,
SubscriptionRequest,
SubscriptionState
);
}
/// One active turn's live receiver. Frames are checked against this receiver's
/// identity before accepted notices enter the host's ordinary message delivery.
pub struct BoardNotifications {
caller: ThreadId,
turn_id: String,
stream: BoxStream<'static, Result<eventsource_stream::Event>>,
}
impl BoardNotifications {
/// Skips invalid individual notices. Transport and framing failures remain errors.
pub async fn next(&mut self) -> Result<Option<BoardNotification>> {
while let Some(event) = self.stream.next().await.transpose()? {
let error_kind = if event.event != "notification" {
"unexpected_event"
} else {
match serde_json::from_str::<BoardNotification>(&event.data) {
Ok(notice) => {
if notice.recipient != self.caller || notice.turn_id != self.turn_id {
"wrong_recipient_or_turn"
} else if notice.post.text_preview.chars().count() > 150 {
"oversized_preview"
} else {
return Ok(Some(notice));
}
}
Err(_) => "invalid_json",
}
};
tracing::warn!(
caller = %self.caller, turn_id = %self.turn_id, error_kind,
"Skipping invalid remote board notification"
);
}
Ok(None)
}
}
async fn decode<T: DeserializeOwned>(mut response: HttpResponse) -> Result<T> {
let status = response.status();
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(transport_error)? {
if body.len().saturating_add(chunk.len()) > MAX_RESPONSE {
return Err(transport_error("board response exceeds the service limit"));
}
body.extend_from_slice(&chunk);
}
if !status.is_success() {
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)
} else {
CodexErr::InvalidRequest(message)
});
}
serde_json::from_slice(&body).map_err(CodexErr::from)
}
fn transport_error(error: impl Into<Box<dyn Error + Send + Sync>>) -> CodexErr {
CodexErr::Io(std::io::Error::other(error))
}

View File

@@ -0,0 +1,12 @@
//! A typed client for a message-board API at a configured endpoint.
//! Runtime credentials are scoped to one session; tools never see them.
mod client;
mod notifications;
mod protocol;
pub use client::BoardNotifications;
pub use client::RemoteAgentMessageBoard;
pub use notifications::install_notifications;
pub use protocol::AccessToken;
pub use protocol::BoardNotification;

View File

@@ -0,0 +1,122 @@
//! Receives live board previews for an active turn using the extension's turn hooks.
//! Provisioning and durable board ownership belong to the research host.
use crate::RemoteAgentMessageBoard;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionFuture;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::TurnAbortInput;
use akode_extension_api::TurnErrorInput;
use akode_extension_api::TurnLifecycleContributor;
use akode_extension_api::TurnStartInput;
use akode_extension_api::TurnStartPhase;
use akode_extension_api::TurnStopInput;
use akode_message_board::MessageBoardHost;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErrKind;
use futures::channel::oneshot;
use std::sync::Arc;
use std::time::Duration;
use tokio_util::task::AbortOnDropHandle;
type Binding = (Arc<RemoteAgentMessageBoard>, Arc<dyn MessageBoardHost>);
type ResolveBinding = dyn Fn(&TurnStartInput<'_>) -> Option<Binding> + Send + Sync;
struct Notifications(Box<ResolveBinding>);
struct Receiver {
_task: AbortOnDropHandle<()>,
}
impl TurnLifecycleContributor for Notifications {
fn turn_start_phase(&self, _thread_store: &ExtensionData) -> TurnStartPhase {
TurnStartPhase::RegularTaskStart
}
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
let Some((board, host)) = (self.0)(&input) else {
return;
};
let Ok(caller) = ThreadId::from_string(input.thread_store.level_id()) else {
return;
};
let turn_id = input.turn_id.to_owned();
let (first_attempt_tx, first_attempt_rx) = oneshot::channel();
input.turn_store.insert(Receiver {
_task: AbortOnDropHandle::new(tokio::spawn(async move {
let mut first_attempt_tx = Some(first_attempt_tx);
loop {
let connection = board.notifications(caller, turn_id.clone()).await;
if let Some(first_attempt_tx) = first_attempt_tx.take() {
let _ = first_attempt_tx.send(());
}
match connection {
Ok(mut stream) => loop {
match stream.next().await {
Ok(Some(notice)) => {
if let Err(error) = host.notify(caller, notice.post).await {
tracing::warn!(
%caller, %turn_id,
error_kind = ?CodexErrKind::from(&error),
"Remote board notification delivery failed"
);
}
}
Ok(None) => break,
Err(error) => {
tracing::warn!(
%caller, %turn_id,
error_kind = ?CodexErrKind::from(&error),
"Remote board notification stream failed"
);
break;
}
}
},
Err(error) => {
tracing::warn!(
%caller, %turn_id,
error_kind = ?CodexErrKind::from(&error),
"Remote board notification connection failed"
);
}
}
// Reopen for future previews; the service does not replay missed ones.
tokio::time::sleep(Duration::from_secs(/*secs*/ 1)).await;
}
})),
});
// A healthy service is listening before inference. A failed first attempt
// releases startup while the same turn-owned receiver keeps retrying.
let _ = first_attempt_rx.await;
})
}
fn on_turn_stop<'a>(&'a self, input: TurnStopInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<Receiver>();
})
}
fn on_turn_abort<'a>(&'a self, input: TurnAbortInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<Receiver>();
})
}
fn on_turn_error<'a>(&'a self, input: TurnErrorInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<Receiver>();
})
}
}
/// Installs live notification delivery. The host resolves the existing remote
/// client and delivery host. Accepted notices use the host's ordinary message policy.
/// The turn store owns the receiver and cancels it when the turn ends.
pub fn install_notifications<C: Sync>(
registry: &mut ExtensionRegistryBuilder<C>,
resolve: impl Fn(&TurnStartInput<'_>) -> Option<Binding> + Send + Sync + 'static,
) {
registry.turn_lifecycle_contributor(Arc::new(Notifications(Box::new(resolve))));
}

View File

@@ -0,0 +1,107 @@
//! Versioned service requests reuse board operations; only host identity travels separately.
use chrono::DateTime;
use chrono::Utc;
use akode_message_board::ChannelQuery;
use akode_message_board::CreateChannelRequest;
use akode_message_board::PostPreview;
use akode_message_board::PostQuery;
use akode_message_board::PostRequest;
use akode_message_board::ReadPostRequest;
use akode_message_board::ReadThreadRequest;
use akode_message_board::SubscriptionRequest;
use akode_message_board::ThreadQuery;
use akode_protocol::AgentPath;
use akode_protocol::ThreadId;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use std::collections::HashMap;
use std::fmt;
pub(crate) const MAX_BODY: usize = 512 * 1024;
pub(crate) const MAX_RESPONSE: usize = 1024 * 1024;
/// A host credential. Debug output must never reveal its contents.
#[derive(Clone, Serialize)]
#[serde(transparent)]
pub struct AccessToken(pub(crate) String);
impl AccessToken {
pub fn new(value: String) -> anyhow::Result<Self> {
anyhow::ensure!(
(32..=4096).contains(&value.len()),
"credentials must contain 32–4096 bytes"
);
anyhow::ensure!(
value.bytes().all(|b| b.is_ascii_graphic()),
"credential must be ASCII without whitespace"
);
Ok(Self(value))
}
}
impl<'de> Deserialize<'de> for AccessToken {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::new(String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
}
}
impl fmt::Debug for AccessToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AccessToken([REDACTED])")
}
}
#[derive(Serialize)]
pub(crate) struct Registration {
pub(crate) members: HashMap<ThreadId, AgentPath>,
}
#[derive(Serialize)]
pub(crate) struct Call {
pub(crate) caller: ThreadId,
pub(crate) timestamp: Option<DateTime<Utc>>,
#[serde(flatten)]
pub(crate) operation: Operation,
}
#[derive(Serialize)]
#[serde(tag = "method", content = "params", rename_all = "snake_case")]
pub(crate) enum Operation {
CreateChannel(CreateChannelRequest),
ListChannels(ChannelQuery),
Post(PostRequest),
ListThreads(ThreadQuery),
SearchPosts(PostQuery),
ReadThread(ReadThreadRequest),
ReadPost(ReadPostRequest),
SetSubscription(SubscriptionRequest),
}
#[derive(Serialize)]
pub(crate) struct Watch {
pub(crate) caller: ThreadId,
pub(crate) turn_id: String,
}
/// A best-effort preview bound to the receiving turn. Hosts must atomically check
/// `turn_id` when admitting it; a received preview must never start a new turn.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BoardNotification {
pub recipient: ThreadId,
pub turn_id: String,
pub post: PostPreview,
}
#[derive(Deserialize)]
pub(crate) struct Failure {
pub(crate) code: String,
pub(crate) message: String,
}
#[derive(Deserialize)]
pub(crate) struct PermissionDeniedDetails {
pub(crate) action: Option<String>,
pub(crate) resource: Option<String>,
}

View File

@@ -0,0 +1,304 @@
//! Exercise the HTTP adapter's clock, authentication and turn-bound stream.
use chrono::DateTime;
use chrono::Utc;
use akode_agent_message_board_client::AccessToken;
use akode_agent_message_board_client::BoardNotification;
use akode_agent_message_board_client::RemoteAgentMessageBoard;
use akode_http_client::HttpClientBuilder;
use akode_message_board::AgentMessageBoard;
use akode_message_board::AppendRequest;
use akode_message_board::PostContent;
use akode_message_board::PostDestination;
use akode_message_board::PostMetadata;
use akode_message_board::PostPreview;
use akode_message_board::PostRequest;
use akode_message_board::ReadPostRequest;
use akode_message_board::UpsertChannelRequest;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::CodexErrorDetails;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::HashMap;
use std::num::NonZeroU32;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_json;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test]
async fn remote_board_preserves_the_host_contract() -> anyhow::Result<()> {
let server = MockServer::start().await;
let http = HttpClientBuilder::new().build_direct()?;
let board = SessionId::new();
let caller = ThreadId::new();
let members = HashMap::from([(caller, AgentPath::root())]);
let endpoint = format!("{}/board-service", server.uri());
let base = format!("/board-service/v1/boards/{board}");
let admin_token = AccessToken::new("administrator-credential-for-integration".into())?;
for invalid in [
"not a URL",
"file:///tmp/board",
"https://board.test/?query",
"https://board.test/#fragment",
] {
assert!(
RemoteAgentMessageBoard::new(http.clone(), invalid, board, admin_token.clone())
.is_err()
);
}
let admin =
RemoteAgentMessageBoard::new(http.clone(), &format!("{endpoint}/"), board, admin_token)?;
Mock::given(method("PUT"))
.and(path(&base))
.and(header(
"authorization",
"Bearer administrator-credential-for-integration",
))
.respond_with(ResponseTemplate::new(200).set_body_json(board))
.expect(1)
.mount(&server)
.await;
assert_eq!(admin.create_board().await?, board);
let invalid_registration = Mock::given(method("POST"))
.and(path(format!("{base}/members")))
.respond_with(ResponseTemplate::new(200).set_body_json("too-short"))
.expect(1)
.mount_as_scoped(&server)
.await;
let error = admin.register_members(members.clone()).await.unwrap_err();
assert!(matches!(error.details(), CodexErrorDetails::Json(_)));
drop(invalid_registration);
Mock::given(method("POST"))
.and(path(format!("{base}/members")))
.and(body_json(json!({"members": members})))
.respond_with(
ResponseTemplate::new(200).set_body_json("runtime-credential-for-integration-32"),
)
.expect(1)
.mount(&server)
.await;
let token = admin.register_members(members).await?;
let now: DateTime<Utc> = "2026-09-24T12:00:00Z".parse()?;
let clock_available = Arc::new(AtomicBool::new(true));
let clock = clock_available.clone();
let client =
RemoteAgentMessageBoard::new(http, &endpoint, board, token)?.with_clock(move |_| {
let available = clock.load(Ordering::Relaxed);
Box::pin(async move {
if available {
Ok(now)
} else {
Err(CodexErr::Io(std::io::Error::other("clock unavailable")))
}
})
});
let metadata: PostMetadata = serde_json::from_value(json!({
"message_id": "00000000-0000-4000-8000-000000000001", "thread_id": "00000000-0000-4000-8000-000000000001",
"author": "/root", "channel_name": "results", "created_at": now,
}))?;
let post = PostRequest {
request_id: "call-1".into(),
destination: PostDestination::NewChannel("results".into()),
text: "Straße 🦀".into(),
agents_to_notify: vec![AgentPath::root()],
};
Mock::given(method("POST"))
.and(path(format!("{base}/call")))
.and(header(
"authorization",
"Bearer runtime-credential-for-integration-32",
))
.and(body_json(
json!({"caller": caller, "timestamp": now, "method": "post", "params": post}),
))
// The post committed, but a gateway failed to return its result.
.respond_with(
ResponseTemplate::new(503)
.set_body_json(json!({"code": "unavailable", "message": "response unavailable"})),
)
.expect(1)
.mount(&server)
.await;
let board_handle: &dyn AgentMessageBoard = &client;
assert_eq!(board_handle.identity(), board);
let requests_before = server.received_requests().await.unwrap().len();
let unsupported = board_handle
.append(
caller,
AppendRequest {
request_id: post.request_id.clone(),
destination: post.destination.clone(),
text: post.text.clone(),
},
)
.await
.unwrap_err();
assert!(matches!(
unsupported.details(),
CodexErrorDetails::InvalidRequest(_)
));
let unsupported = board_handle
.upsert_channel(
caller,
UpsertChannelRequest {
channel_name: "results".into(),
description: "Updated purpose".to_owned().try_into()?,
},
)
.await
.unwrap_err();
assert!(matches!(
unsupported.details(),
CodexErrorDetails::InvalidRequest(_)
));
assert_eq!(
server.received_requests().await.unwrap().len(),
requests_before
);
assert!(board_handle.post(caller, post.clone()).await.is_err());
clock_available.store(false, Ordering::Relaxed);
Mock::given(method("POST"))
.and(path(format!("{base}/call")))
.and(body_json(
json!({"caller": caller, "timestamp": null, "method": "post", "params": post}),
))
.respond_with(ResponseTemplate::new(200).set_body_json(&metadata))
.expect(1)
.mount(&server)
.await;
assert_eq!(client.post(caller, post).await?, metadata);
let request = ReadPostRequest {
message_id: metadata.message_id,
offset_chars: 7,
limit_chars: NonZeroU32::MIN,
};
let content = PostContent {
metadata: metadata.clone(),
text: "🦀".into(),
n_chars: 8,
next_offset_chars: 8,
};
Mock::given(method("POST"))
.and(path(format!("{base}/call")))
.and(body_json(
json!({"caller": caller, "timestamp": null, "method": "read_post", "params": request}),
))
.respond_with(ResponseTemplate::new(200).set_body_json(&content))
.expect(1)
.mount(&server)
.await;
assert_eq!(client.read_post(caller, request).await?, content);
let notice = BoardNotification {
recipient: caller,
turn_id: "turn-1".into(),
post: PostPreview {
metadata,
text_preview: "Straße 🦀".into(),
n_chars: 8,
truncated: false,
},
};
let mut stale = notice.clone();
stale.turn_id = "turn-0".into();
let mut oversized = notice.clone();
oversized.post.text_preview = "🦀".repeat(151);
let events = [&notice, &stale, &oversized]
.into_iter()
.map(|event| {
Ok(format!(
"event: notification\ndata: {}\n\n",
serde_json::to_string(event)?
))
})
.collect::<anyhow::Result<String>>()?;
// The limit is per frame, not per connection; support all SSE line endings.
let heartbeats = ": heartbeat\r\n\r\n: heartbeat\r\r: heartbeat\n\n".repeat(16 * 1024);
Mock::given(method("POST"))
.and(path(format!("{base}/notifications")))
.and(body_json(json!({"caller": caller, "turn_id": "turn-1"})))
.respond_with(
ResponseTemplate::new(200)
.insert_header("content-type", "text/event-stream")
.set_body_string(format!("{heartbeats}event: ready\ndata: {{}}\n\n{events}")),
)
.expect(1)
.mount(&server)
.await;
let mut receiver = client.notifications(caller, "turn-1".into()).await?;
assert_eq!(receiver.next().await?, Some(notice));
assert_eq!(receiver.next().await?, None);
for body in [
format!(
"event: ready\nid: {}\ndata: {{}}\n\n",
"x".repeat(512 * 1024)
),
format!("event: ready\ndata: {{}}\n\nid: {}", "x".repeat(512 * 1024)),
format!(
"event: ready\ndata: {{}}\n\n{}",
"data: x\n".repeat(64 * 1024 + 1)
),
] {
let _response = Mock::given(method("POST"))
.and(path(format!("{base}/notifications")))
.and(body_json(json!({"caller": caller, "turn_id": "limit"})))
.respond_with(
ResponseTemplate::new(200)
.insert_header("content-type", "text/event-stream")
.set_body_string(body),
)
.expect(1)
.mount_as_scoped(&server)
.await;
let error = match client.notifications(caller, "limit".into()).await {
Ok(mut receiver) => receiver.next().await.unwrap_err(),
Err(error) => error,
};
assert!(
error
.to_string()
.contains("board SSE frame exceeds the service limit")
);
}
let invalid_response = Mock::given(method("DELETE"))
.and(path(&base))
.respond_with(ResponseTemplate::new(502).set_body_string("not JSON"))
.expect(1)
.mount_as_scoped(&server)
.await;
let error = admin.delete_board().await.unwrap_err();
assert!(error.to_string().contains("HTTP 502"));
assert!(
anyhow::Error::new(error)
.chain()
.any(<dyn std::error::Error>::is::<serde_json::Error>)
);
drop(invalid_response);
Mock::given(method("DELETE"))
.and(path(base))
.respond_with(
ResponseTemplate::new(503)
.set_body_json(json!({"code": "unavailable", "message": "storage unavailable"})),
)
.expect(1)
.mount(&server)
.await;
assert!(
admin
.delete_board()
.await
.unwrap_err()
.to_string()
.contains("storage unavailable")
);
Ok(())
}