mirror of
https://github.com/openai/codex.git
synced 2026-11-23 23:10:47 +00:00
Deliver detached message board notices to native agents (#63354)
## Why The detached SQLite message board could store posts but could not notify the agents named in `agents_to_notify`. ## What changed Add an optional `--app-server ws://127.0.0.1:PORT` flag to `codex-message-board-mcp`. When configured, the board uses `thread/inject_items` to queue notices in native agent mailboxes without starting a turn. The board and app-server must share the same Codex registry. Delivery is best-effort. Posts stay stored if a notice fails, and the next notice can reconnect without replaying the failed one. ## Testing Cover concurrent requests, notice size limits, and reconnect after a timeout without replay. Exercise the detached executable against a restarted app-server and verify that a native child receives the queued notice once when it resumes. GitOrigin-RevId: 8b890b30df94590686d91921d814887eda5d9c9b
This commit is contained in:
Generated
+5
@@ -4411,6 +4411,8 @@ dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
"clap",
|
||||
"codex-app-server-protocol",
|
||||
"codex-app-server-remote-client",
|
||||
"codex-attachment-store",
|
||||
"codex-message-board",
|
||||
"codex-protocol",
|
||||
@@ -4421,13 +4423,16 @@ dependencies = [
|
||||
"codex-utils-output-truncation",
|
||||
"codex-utils-process",
|
||||
"futures",
|
||||
"pretty_assertions",
|
||||
"rmcp",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sqlx",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-tungstenite",
|
||||
"tokio-util",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ codex_rust_crate(
|
||||
"//codex-rs/bwrap:bwrap",
|
||||
"//codex-rs/cli:codex",
|
||||
"//codex-rs/code-mode-host:codex-code-mode-host",
|
||||
"//codex-rs/message-board-mcp:codex-message-board-mcp",
|
||||
"//codex-rs/rmcp-client:test_stdio_server",
|
||||
],
|
||||
integration_test_timeout = "long",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Board tools share MAv2 namespace metadata through the production installation path.
|
||||
//! Board tools share namespace metadata; the detached SQLite server delivers native agent mail.
|
||||
|
||||
use super::connection_handling_websocket as websocket;
|
||||
use anyhow::Context;
|
||||
use app_test_support::MockResponsesConfig;
|
||||
use app_test_support::TestAppServer;
|
||||
@@ -8,11 +9,13 @@ use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::TurnStartResponse;
|
||||
use codex_app_server_protocol::UserInput;
|
||||
use codex_features::Feature;
|
||||
use codex_rmcp_client::RmcpClient;
|
||||
use core_test_support::responses;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
@@ -94,5 +97,195 @@ async fn board_tools_share_multi_agent_namespace(
|
||||
result,
|
||||
json!({"results": [], "n_returned": 0, "has_more": false, "next_cursor": null})
|
||||
);
|
||||
// Detached delivery is independent of the configured native tool namespace.
|
||||
if configured_namespace.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Reuse the real WebSocket server to exercise the detached executable's callback.
|
||||
// Its second agent is a native child, so ordinary direct-input injection is forbidden.
|
||||
let (mut app_process, address) = websocket::spawn_websocket_server(codex_home.path()).await?;
|
||||
let mut ws = websocket::connect_websocket(address).await?;
|
||||
websocket::send_initialize_request(&mut ws, /*id*/ 1, "board-notifications").await?;
|
||||
websocket::read_response_for_id(&mut ws, /*id*/ 1).await?;
|
||||
let program = codex_utils_cargo_bin::cargo_bin("codex-message-board-mcp")?;
|
||||
let mut board_process =
|
||||
tokio::process::Command::from(codex_utils_process::background_command(program))
|
||||
.arg("--sqlite-home")
|
||||
.arg(codex_home.path())
|
||||
.args([
|
||||
"--listen",
|
||||
"127.0.0.1:0",
|
||||
"--app-server",
|
||||
&format!("ws://{address}"),
|
||||
])
|
||||
.env(
|
||||
"CODEX_MESSAGE_BOARD_TOKEN",
|
||||
"sqlite-notifications-test-token",
|
||||
)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.spawn()?;
|
||||
let ready = timeout(
|
||||
websocket::DEFAULT_READ_TIMEOUT,
|
||||
tokio::io::BufReader::new(board_process.stdout.take().context("board stdout")?)
|
||||
.lines()
|
||||
.next_line(),
|
||||
)
|
||||
.await??
|
||||
.context("board server readiness")?;
|
||||
let ready: Value = serde_json::from_str(&ready)?;
|
||||
// The board must reconnect before sending its first notice after a known disconnect.
|
||||
app_process.kill().await?;
|
||||
let (restarted, _) = websocket::spawn_websocket_server_with_args(
|
||||
codex_home.path(),
|
||||
&format!("ws://{address}"),
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
app_process = restarted;
|
||||
ws = websocket::connect_websocket(address).await?;
|
||||
websocket::send_initialize_request(&mut ws, /*id*/ 1, "board-notifications").await?;
|
||||
websocket::read_response_for_id(&mut ws, /*id*/ 1).await?;
|
||||
let root = websocket::start_thread(&mut ws, /*id*/ 2).await?;
|
||||
// Parent and child requests can arrive in either order. Give both terminal answers
|
||||
// so late child results stay queued instead of extending the parent's turn.
|
||||
responses::mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
responses::sse(vec![
|
||||
responses::ev_function_call_with_namespace(
|
||||
"spawn-notification-recipient",
|
||||
namespace,
|
||||
"spawn_agent",
|
||||
r#"{"task_name":"worker","message":"Say ready.","fork_turns":"none"}"#,
|
||||
),
|
||||
responses::ev_completed("spawn-recipient"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("recipient-ready-message", "Ready."),
|
||||
responses::ev_completed("recipient-ready"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("parent-ready-message", "Ready."),
|
||||
responses::ev_completed("parent-ready"),
|
||||
]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
websocket::send_request(
|
||||
&mut ws,
|
||||
"turn/start",
|
||||
/*id*/ 3,
|
||||
Some(json!({"threadId":root,"input":[{"type":"text","text":"Spawn a worker."}]})),
|
||||
)
|
||||
.await?;
|
||||
for _ in 0..2 {
|
||||
let completion = websocket::read_notification_for_method(&mut ws, "turn/completed").await?;
|
||||
assert_eq!(
|
||||
completion.params.context("completion params")?["turn"]["status"],
|
||||
"completed"
|
||||
);
|
||||
}
|
||||
|
||||
let client = RmcpClient::new_streamable_http_client(
|
||||
"sqlite-notifications",
|
||||
ready["url"].as_str().context("board URL")?,
|
||||
Some("sqlite-notifications-test-token".into()),
|
||||
/*http_headers*/ None,
|
||||
/*env_http_headers*/ None,
|
||||
codex_config::types::OAuthCredentialsStoreMode::File,
|
||||
Default::default(),
|
||||
codex_exec_server::Environment::default_for_tests().get_http_client(),
|
||||
/*auth_provider*/ None,
|
||||
)
|
||||
.await?;
|
||||
client
|
||||
.initialize(
|
||||
rmcp::model::InitializeRequestParams::default(),
|
||||
/*timeout*/ None,
|
||||
Box::new(|_, _| Box::pin(async { anyhow::bail!("unexpected elicitation") })),
|
||||
)
|
||||
.await?;
|
||||
let posted = client
|
||||
.call_tool(
|
||||
"post".into(),
|
||||
Some(json!({
|
||||
"new_channel_name":"delivery",
|
||||
"text":"A notice from the detached SQLite board.",
|
||||
"agents_to_notify":["/root/worker"]
|
||||
})),
|
||||
|_| Ok(Some(json!({"threadId":root,"sessionId":root}))),
|
||||
/*timeout*/ None,
|
||||
)
|
||||
.await?;
|
||||
assert_ne!(posted.is_error, Some(true), "{posted:?}");
|
||||
let post = posted.structured_content.context("posted metadata")?;
|
||||
let notification = format!(
|
||||
"Message Type: CHANNEL_POST\nSender: /root\nChannel: delivery\nMessage ID: {}\nThread ID: {}\nPayload:\nA notice from the detached SQLite board.",
|
||||
post["message_id"].as_str().context("message id")?,
|
||||
post["thread_id"].as_str().context("thread id")?,
|
||||
);
|
||||
|
||||
// Queue-only mail must be available when the parent follows up with its idle child.
|
||||
let delivered = responses::mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
responses::sse(vec![
|
||||
responses::ev_function_call_with_namespace(
|
||||
"consume-notification",
|
||||
namespace,
|
||||
"followup_task",
|
||||
r#"{"target":"/root/worker","message":"Read the notification."}"#,
|
||||
),
|
||||
responses::ev_completed("resume-recipient"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("notification-consumed-message", "Done."),
|
||||
responses::ev_completed("notification-consumed"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("parent-complete-message", "Done."),
|
||||
responses::ev_completed("parent-complete"),
|
||||
]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
websocket::send_request(
|
||||
&mut ws,
|
||||
"turn/start",
|
||||
/*id*/ 4,
|
||||
Some(
|
||||
json!({"threadId":root,"input":[{"type":"text","text":"Follow up with the worker."}]}),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
for _ in 0..2 {
|
||||
let completion = websocket::read_notification_for_method(&mut ws, "turn/completed").await?;
|
||||
assert_eq!(
|
||||
completion.params.context("completion params")?["turn"]["status"],
|
||||
"completed"
|
||||
);
|
||||
}
|
||||
let delivered_items = delivered
|
||||
.requests()
|
||||
.into_iter()
|
||||
.flat_map(|request| request.inputs_of_type("agent_message"))
|
||||
.map(responses::strip_metadata_from_json)
|
||||
.map(responses::strip_response_item_ids_from_json)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
delivered_items
|
||||
.iter()
|
||||
.filter(|item| item["content"] == json!([{"type":"input_text","text":notification}]))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![&json!({
|
||||
"type":"agent_message","author":"/root","recipient":"/root/worker",
|
||||
"content":[{"type":"input_text","text":notification}]
|
||||
})],
|
||||
);
|
||||
client.shutdown().await;
|
||||
board_process.kill().await?;
|
||||
app_process.kill().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -7,13 +7,11 @@ version.workspace = true
|
||||
[lib]
|
||||
name = "codex_message_board_mcp"
|
||||
path = "src/lib.rs"
|
||||
test = false
|
||||
doctest = false
|
||||
|
||||
[[bin]]
|
||||
name = "codex-message-board-mcp"
|
||||
path = "src/main.rs"
|
||||
test = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -23,6 +21,8 @@ anyhow = { workspace = true }
|
||||
axum = { workspace = true, features = ["http1", "tokio"] }
|
||||
chrono = { workspace = true }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
codex-app-server-protocol = { workspace = true }
|
||||
codex-app-server-remote-client = { workspace = true }
|
||||
codex-attachment-store = { workspace = true }
|
||||
codex-message-board = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
@@ -37,9 +37,12 @@ serde_json = { workspace = true }
|
||||
sqlx = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "net", "rt", "signal"] }
|
||||
tokio-util = { workspace = true, features = ["rt"] }
|
||||
url = { workspace = true }
|
||||
uuid = { workspace = true, features = ["v4", "v7"] }
|
||||
|
||||
[dev-dependencies]
|
||||
codex-utils-cargo-bin = { workspace = true }
|
||||
codex-utils-process = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio-tungstenite = { workspace = true }
|
||||
|
||||
@@ -60,7 +60,24 @@ required = true
|
||||
|
||||
The executable prints its URL and shuts down on Ctrl-C. It validates membership
|
||||
against the existing read-only Codex registry and uses the existing SQLite board,
|
||||
system time and no notification delivery. Core delivery is a separate change.
|
||||
system time and no notification delivery by default.
|
||||
|
||||
To deliver notices to native MAv2 agents through an existing local app-server,
|
||||
add `--app-server ws://127.0.0.1:PORT`. The app-server must serve that loopback
|
||||
WebSocket endpoint and use the same Codex registry. Notifications use its existing
|
||||
`thread/inject_items` RPC and ordinary queue-only mailbox/wake rules; this requires
|
||||
an app-server that supports agent-mail injection into native children. Delivery is
|
||||
best-effort: failed notices are not retried, and the post remains stored. The next
|
||||
notice reconnects after a failed connection. Without this option nothing changes.
|
||||
|
||||
For the focused app-server integration test, build the board executable first.
|
||||
Package-scoped Cargo tests do not build another package's executable; Bazel supplies
|
||||
it through the test's `extra_binaries`. Run these commands from `codex-rs`:
|
||||
|
||||
```sh
|
||||
cargo build -p codex-message-board-mcp --bin codex-message-board-mcp
|
||||
just test -p codex-app-server --test all board_tools_share_multi_agent_namespace
|
||||
```
|
||||
|
||||
The library's `serve_http(listener, token, config, bind)` exposes the shared
|
||||
discussion tool contract at `/mcp`. Its async binding validates `(ThreadId, SessionId)`
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Optional local app-server connection for best-effort board notifications.
|
||||
//! Requests share the client's reply routing without holding the connection-cache lock.
|
||||
//! Disconnected or cancelled transports are replaced for new notices, never replayed.
|
||||
|
||||
use anyhow::Context;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ThreadInjectItemsParams;
|
||||
use codex_app_server_remote_client::AppServerEvent;
|
||||
use codex_app_server_remote_client::RemoteAppServerClient;
|
||||
use codex_app_server_remote_client::RemoteAppServerConnectArgs;
|
||||
use codex_app_server_remote_client::RemoteAppServerEndpoint;
|
||||
use codex_app_server_remote_client::RemoteAppServerRequestHandle;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::InterAgentCommunication;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::OnceCell;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
use url::Url;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "app_server_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
struct Connection {
|
||||
requests: RemoteAppServerRequestHandle,
|
||||
closed: CancellationToken,
|
||||
_events: AbortOnDropHandle<()>,
|
||||
}
|
||||
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
pub(super) struct AppServer {
|
||||
url: Url,
|
||||
connection: Mutex<Arc<OnceCell<Connection>>>,
|
||||
}
|
||||
|
||||
impl AppServer {
|
||||
pub(super) async fn connect(url: Url) -> anyhow::Result<Self> {
|
||||
anyhow::ensure!(
|
||||
url.scheme() == "ws"
|
||||
&& match url.host() {
|
||||
Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
|
||||
Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
|
||||
Some(url::Host::Domain(host)) => host == "localhost",
|
||||
None => false,
|
||||
}
|
||||
&& url.username().is_empty()
|
||||
&& url.password().is_none()
|
||||
&& url.query().is_none()
|
||||
&& url.fragment().is_none(),
|
||||
"--app-server requires a loopback ws:// URL without credentials"
|
||||
);
|
||||
let connection = timeout(REQUEST_TIMEOUT, connect(&url))
|
||||
.await
|
||||
.context("app-server initialization timed out")??;
|
||||
Ok(Self {
|
||||
url,
|
||||
connection: Mutex::new(Arc::new(OnceCell::from(connection))),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn inject(
|
||||
&self,
|
||||
recipient: ThreadId,
|
||||
notice: InterAgentCommunication,
|
||||
) -> anyhow::Result<()> {
|
||||
// Match the existing remote-board limit, including both routing paths.
|
||||
anyhow::ensure!(
|
||||
notice.content.len() + notice.author.as_str().len() + notice.recipient.as_str().len()
|
||||
<= 1024,
|
||||
"remote board notice exceeds the context budget"
|
||||
);
|
||||
timeout(REQUEST_TIMEOUT, async {
|
||||
let slot = {
|
||||
let mut slot = self
|
||||
.connection
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if slot
|
||||
.get()
|
||||
.is_some_and(|connection| connection.closed.is_cancelled())
|
||||
{
|
||||
*slot = Arc::new(OnceCell::new());
|
||||
}
|
||||
Arc::clone(&slot)
|
||||
};
|
||||
// Coalesce reconnects without serializing requests on a healthy client.
|
||||
let connection = slot.get_or_try_init(|| connect(&self.url)).await?;
|
||||
let failed = connection.closed.clone().drop_guard();
|
||||
let response = connection
|
||||
.requests
|
||||
.request(ClientRequest::ThreadInjectItems {
|
||||
request_id: RequestId::String(uuid::Uuid::new_v4().to_string()),
|
||||
params: ThreadInjectItemsParams {
|
||||
thread_id: recipient.to_string(),
|
||||
items: vec![serde_json::to_value(notice.to_model_input_item())?],
|
||||
},
|
||||
})
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("app-server notification connection failed"))?;
|
||||
// A remote rejection still has a matched reply and a usable transport.
|
||||
failed.disarm();
|
||||
response.map_err(|error| {
|
||||
anyhow::anyhow!("app-server rejected request (code {})", error.code)
|
||||
})?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.context("app-server notification timed out")?
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect(url: &Url) -> anyhow::Result<Connection> {
|
||||
let mut client = RemoteAppServerClient::connect(RemoteAppServerConnectArgs {
|
||||
required_human_approval: false,
|
||||
endpoint: RemoteAppServerEndpoint::WebSocket {
|
||||
websocket_url: url.to_string(),
|
||||
auth_token: None,
|
||||
},
|
||||
client_name: "codex_message_board".into(),
|
||||
client_version: env!("CARGO_PKG_VERSION").into(),
|
||||
experimental_api: true,
|
||||
mcp_server_openai_form_elicitation: false,
|
||||
opt_out_notification_methods: Vec::new(),
|
||||
channel_capacity: 1,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("failed to connect to the local app-server"))?;
|
||||
let requests = client.request_handle();
|
||||
let closed = CancellationToken::new();
|
||||
let disconnected = closed.clone();
|
||||
// Keep the shared client's event queue drained even between notices. The
|
||||
// connection owns this task; dropping it also releases the client handle.
|
||||
let events = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
while let Some(event) = tokio::select! {
|
||||
_ = disconnected.cancelled() => None,
|
||||
event = client.next_event() => event,
|
||||
} {
|
||||
if matches!(
|
||||
event,
|
||||
AppServerEvent::Disconnected { .. } | AppServerEvent::ServerRequest(_)
|
||||
) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
disconnected.cancel();
|
||||
let _ = client.shutdown().await;
|
||||
}));
|
||||
Ok(Connection {
|
||||
requests,
|
||||
closed,
|
||||
_events: events,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
#![cfg(test)]
|
||||
//! Exercise bounded, concurrent notification delivery and recovery without replay.
|
||||
|
||||
use super::AppServer;
|
||||
use anyhow::Context;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::InterAgentCommunication;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio_tungstenite::WebSocketStream;
|
||||
use tokio_tungstenite::accept_async;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
#[tokio::test]
|
||||
async fn bounded_concurrent_notices_recover_without_replay() -> anyhow::Result<()> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let (client, mut peer) = tokio::try_join!(
|
||||
AppServer::connect(format!("ws://{}", listener.local_addr()?).parse()?),
|
||||
accept_connection(&listener),
|
||||
)?;
|
||||
let recipient = ThreadId::new();
|
||||
// 1,007 text bytes + /root + /root/worker exactly fill the existing limit.
|
||||
let rejected = notice(&"x".repeat(1007));
|
||||
for oversized in [
|
||||
InterAgentCommunication {
|
||||
author: AgentPath::root().join("a").expect("valid author"),
|
||||
..rejected.clone()
|
||||
},
|
||||
InterAgentCommunication {
|
||||
recipient: AgentPath::root()
|
||||
.join("worker_long")
|
||||
.expect("valid recipient"),
|
||||
..rejected.clone()
|
||||
},
|
||||
] {
|
||||
assert_eq!(
|
||||
client
|
||||
.inject(recipient, oversized)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"remote board notice exceeds the context budget"
|
||||
);
|
||||
}
|
||||
let accepted = notice("parallel");
|
||||
let (rejection, result, served) = tokio::join!(biased;
|
||||
client.inject(recipient, rejected.clone()),
|
||||
client.inject(recipient, accepted.clone()),
|
||||
async {
|
||||
let first = receive_notice(&mut peer, recipient, &rejected).await?;
|
||||
// Neither call gets a reply until both have reached the same connection.
|
||||
let second = receive_notice(&mut peer, recipient, &accepted).await?;
|
||||
assert_ne!(first, second);
|
||||
send_json(&mut peer, json!({"id": second, "result": {}})).await?;
|
||||
send_json(&mut peer, json!({"id": first, "error": {"code": -32602, "message": "recipient unavailable"}})).await
|
||||
}
|
||||
);
|
||||
served?;
|
||||
result?;
|
||||
assert!(rejection.unwrap_err().to_string().contains("-32602"));
|
||||
// An RPC rejection must leave this socket usable for the next notice.
|
||||
let unanswered = notice("unanswered");
|
||||
let (result, received) = tokio::join!(
|
||||
client.inject(recipient, unanswered.clone()),
|
||||
receive_notice(&mut peer, recipient, &unanswered),
|
||||
);
|
||||
received?;
|
||||
assert_eq!(
|
||||
result.unwrap_err().to_string(),
|
||||
"app-server notification timed out"
|
||||
);
|
||||
assert!(matches!(
|
||||
peer.next().await.transpose()?,
|
||||
Some(Message::Close(_))
|
||||
));
|
||||
|
||||
let accepted = notice("accepted after timeout");
|
||||
let (result, served) = tokio::join!(client.inject(recipient, accepted.clone()), async {
|
||||
let mut replacement = accept_connection(&listener).await?;
|
||||
// The first request on the new connection must be the new notice.
|
||||
let id = receive_notice(&mut replacement, recipient, &accepted).await?;
|
||||
send_json(&mut replacement, json!({"id": id, "result": {}})).await?;
|
||||
Ok::<_, anyhow::Error>(replacement)
|
||||
});
|
||||
let mut replacement = served?;
|
||||
result?;
|
||||
drop(client);
|
||||
// Also catch any replay queued behind the successful request.
|
||||
assert!(
|
||||
replacement
|
||||
.next()
|
||||
.await
|
||||
.is_none_or(|frame| matches!(frame, Ok(Message::Close(_)) | Err(_)))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn notice(text: &str) -> InterAgentCommunication {
|
||||
InterAgentCommunication::new(
|
||||
AgentPath::root(),
|
||||
AgentPath::root().join("worker").expect("valid recipient"),
|
||||
Vec::new(),
|
||||
text.into(),
|
||||
/*trigger_turn*/ false,
|
||||
)
|
||||
}
|
||||
|
||||
async fn accept_connection(listener: &TcpListener) -> anyhow::Result<WebSocketStream<TcpStream>> {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
let mut peer = accept_async(stream).await?;
|
||||
let initialize = read_json(&mut peer).await?;
|
||||
assert_eq!(initialize["method"], "initialize");
|
||||
send_json(&mut peer, json!({"id": initialize["id"], "result": {}})).await?;
|
||||
assert_eq!(
|
||||
read_json(&mut peer).await?,
|
||||
json!({"method": "initialized"})
|
||||
);
|
||||
Ok(peer)
|
||||
}
|
||||
|
||||
async fn receive_notice(
|
||||
peer: &mut WebSocketStream<TcpStream>,
|
||||
recipient: ThreadId,
|
||||
expected: &InterAgentCommunication,
|
||||
) -> anyhow::Result<Value> {
|
||||
let request = read_json(peer).await?;
|
||||
assert_eq!(
|
||||
request,
|
||||
json!({
|
||||
"id": request["id"],
|
||||
"method": "thread/inject_items",
|
||||
"params": {"threadId": recipient.to_string(), "items": [expected.to_model_input_item()]}
|
||||
})
|
||||
);
|
||||
Ok(request["id"].clone())
|
||||
}
|
||||
|
||||
async fn read_json(peer: &mut WebSocketStream<TcpStream>) -> anyhow::Result<Value> {
|
||||
let frame = peer.next().await.context("expected a JSON-RPC message")??;
|
||||
Ok(serde_json::from_str(frame.to_text()?)?)
|
||||
}
|
||||
|
||||
async fn send_json(peer: &mut WebSocketStream<TcpStream>, value: Value) -> anyhow::Result<()> {
|
||||
peer.send(Message::Text(value.to_string().into())).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Detached HTTP entry point; endpoint configuration and process lifetime belong to the deployer.
|
||||
|
||||
mod app_server;
|
||||
mod persisted;
|
||||
|
||||
use clap::Parser;
|
||||
@@ -28,6 +29,9 @@ struct Args {
|
||||
/// Name of the environment variable containing the trusted-host bearer token.
|
||||
#[arg(long, default_value = "CODEX_MESSAGE_BOARD_TOKEN")]
|
||||
bearer_token_env: String,
|
||||
/// Optional loopback WebSocket app-server URL for queue-only agent notifications.
|
||||
#[arg(long)]
|
||||
app_server: Option<url::Url>,
|
||||
}
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
@@ -43,6 +47,10 @@ async fn main() -> anyhow::Result<()> {
|
||||
let registry = sqlite
|
||||
.open_read_only_pool(&sqlite.state_db_path(), /*busy_timeout*/ None)
|
||||
.await?;
|
||||
let app_server = match args.app_server {
|
||||
Some(url) => Some(Arc::new(app_server::AppServer::connect(url).await?)),
|
||||
None => None,
|
||||
};
|
||||
let listener = tokio::net::TcpListener::bind(args.listen).await?;
|
||||
println!(
|
||||
"{}",
|
||||
@@ -62,6 +70,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
let host = Arc::new(persisted::PersistedHost {
|
||||
registry: registry.clone(),
|
||||
root: session_id.into(),
|
||||
app_server: app_server.clone(),
|
||||
});
|
||||
async move {
|
||||
let path = host.agent_path(caller).await.map_err(|error| {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Reads persisted membership without starting runtimes or modifying Codex's registry.
|
||||
//! Standalone posts use system time; Core notification delivery is a separate integration.
|
||||
//! Posts use system time and optionally deliver notices through the existing app-server RPC.
|
||||
|
||||
use crate::app_server::AppServer;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_message_board::MessageBoardHost;
|
||||
@@ -10,12 +11,15 @@ use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result;
|
||||
use codex_protocol::protocol::InterAgentCommunication;
|
||||
use futures::future::BoxFuture;
|
||||
use sqlx::SqlitePool;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) struct PersistedHost {
|
||||
pub registry: SqlitePool,
|
||||
pub root: ThreadId,
|
||||
pub app_server: Option<Arc<AppServer>>,
|
||||
}
|
||||
|
||||
impl MessageBoardHost for PersistedHost {
|
||||
@@ -87,10 +91,27 @@ LIMIT 2
|
||||
|
||||
fn notify(
|
||||
&self,
|
||||
_recipient: ThreadId,
|
||||
_post: PostPreview,
|
||||
recipient: ThreadId,
|
||||
post: PostPreview,
|
||||
) -> BoxFuture<'_, Result<NotificationDelivery>> {
|
||||
Box::pin(async { Ok(NotificationDelivery::SkippedInactive) })
|
||||
Box::pin(async move {
|
||||
let Some(app_server) = &self.app_server else {
|
||||
return Ok(NotificationDelivery::SkippedInactive);
|
||||
};
|
||||
let path = self.agent_path(recipient).await?;
|
||||
let notice = InterAgentCommunication::new(
|
||||
post.metadata.author.clone(),
|
||||
path,
|
||||
Vec::new(),
|
||||
post.notification_text(),
|
||||
/*trigger_turn*/ false,
|
||||
);
|
||||
app_server
|
||||
.inject(recipient, notice)
|
||||
.await
|
||||
.map_err(|error| CodexErr::Io(std::io::Error::other(error)))?;
|
||||
Ok(NotificationDelivery::Accepted)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user