use std::pin::Pin;
use std::sync::LazyLock;
use dashmap::DashMap;
use futures::{Stream, StreamExt as _};
use objectiveai_sdk::cli::command::{CommandRequest, CommandResponse};
use objectiveai_sdk::identity::Identity;
use objectiveai_sdk::mcp::CliResponse;
use rmcp::model::{CustomNotification, ServerNotification};
use rmcp::service::Peer;
use rmcp::RoleServer;
use tokio::sync::mpsc;
const CLI_REQUEST_METHOD: &str = "notifications/objectiveai/cli_request";
pub(crate) const COMMAND_PATH: &str = objectiveai_sdk::mcp::CLI_COMMAND_ENDPOINT_SUFFIX;
static PENDING: LazyLock<DashMap<String, mpsc::UnboundedSender<CliResponse>>> =
LazyLock::new(DashMap::new);
static PEER: LazyLock<(
tokio::sync::watch::Sender<Option<Peer<RoleServer>>>,
tokio::sync::watch::Receiver<Option<Peer<RoleServer>>>,
)> = LazyLock::new(|| tokio::sync::watch::channel(None));
pub(crate) fn set_peer(peer: Peer<RoleServer>) {
let _ = PEER.0.send(Some(peer));
}
pub(crate) fn deliver(frame: CliResponse) {
let id = match &frame {
CliResponse::Ack { id }
| CliResponse::Item { id, .. }
| CliResponse::Error { id, .. }
| CliResponse::Done { id } => id.clone(),
};
if let Some(sink) = PENDING.get(&id) {
let _ = sink.send(frame);
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("send the command request to the host")]
Send(#[source] rmcp::service::ServiceError),
#[error("encode the command request")]
Encode(#[source] serde_json::Error),
#[error("decode a command response item")]
Decode(#[source] serde_json::Error),
#[error("{0}")]
Cli(objectiveai_sdk::cli::Error),
#[error("the host could not run the command: {0}")]
Host(String),
#[error("the command produced no output")]
Empty,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Executor;
pub fn command_executor() -> Executor {
Executor
}
struct Registered(String);
impl Drop for Registered {
fn drop(&mut self) {
PENDING.remove(&self.0);
}
}
impl objectiveai_sdk::cli::command::CommandExecutor for Executor {
type Error = Error;
type Stream<T>
= Pin<Box<dyn Stream<Item = Result<T, Error>> + Send>>
where
T: Send + 'static;
async fn execute<R, T>(
&self,
request: R,
_identity: Option<&Identity>,
) -> Result<Self::Stream<T>, Error>
where
R: CommandRequest + Send + serde::Serialize,
T: CommandResponse + serde::Serialize + serde::de::DeserializeOwned + Send + 'static,
{
let request = serde_json::to_value(&request).map_err(Error::Encode)?;
let id = uuid::Uuid::new_v4().to_string();
let (tx, rx) = mpsc::unbounded_channel();
PENDING.insert(id.clone(), tx);
let registered = Registered(id.clone());
let peer = {
let mut peer = PEER.1.clone();
let connected = peer
.wait_for(Option::is_some)
.await
.expect("the peer sender is a static and never drops");
connected.clone().expect("waited for Some")
};
peer.send_notification(ServerNotification::CustomNotification(
CustomNotification::new(
CLI_REQUEST_METHOD,
Some(serde_json::json!({ "id": id, "request": request })),
),
))
.await
.map_err(Error::Send)?;
Ok(Box::pin(stream(rx, registered)))
}
async fn execute_one<R, T>(
&self,
request: R,
identity: Option<&Identity>,
) -> Result<T, Error>
where
R: CommandRequest + Send + serde::Serialize,
T: CommandResponse + serde::Serialize + serde::de::DeserializeOwned + Send + 'static,
{
let mut stream = self.execute::<R, T>(request, identity).await?;
stream.next().await.ok_or(Error::Empty)?
}
}
fn stream<T>(
rx: mpsc::UnboundedReceiver<CliResponse>,
registered: Registered,
) -> impl Stream<Item = Result<T, Error>> + Send
where
T: serde::de::DeserializeOwned + Send + 'static,
{
futures::stream::unfold(
(rx, Some(registered)),
|(mut rx, registered)| async move {
loop {
let frame = rx.recv().await?;
match frame {
CliResponse::Ack { .. } => continue,
CliResponse::Item { item, .. } => {
return Some((decode(item), (rx, registered)));
}
CliResponse::Error { error, .. } => {
return Some((Err(Error::Host(error)), (rx, registered)));
}
CliResponse::Done { .. } => return None,
}
}
},
)
.map(|item| item)
}
fn decode<T>(item: objectiveai_sdk::cli::command::ResponseItem) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
let value = serde_json::to_value(item).map_err(Error::Encode)?;
if let Ok(error) = serde_json::from_value::<objectiveai_sdk::cli::Error>(value.clone()) {
return Err(Error::Cli(error));
}
serde_json::from_value(value).map_err(Error::Decode)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_command_path_is_the_sdk_suffix() {
assert_eq!(COMMAND_PATH, "/objectiveai/command");
}
#[tokio::test]
async fn frames_route_by_id_and_unknown_ids_are_dropped() {
let (tx, mut rx) = mpsc::unbounded_channel();
PENDING.insert("known".to_string(), tx);
deliver(CliResponse::Ack { id: "known".into() });
deliver(CliResponse::Ack { id: "nobody-is-waiting".into() });
assert!(matches!(rx.recv().await, Some(CliResponse::Ack { .. })));
assert!(rx.try_recv().is_err(), "the stray frame went nowhere");
PENDING.remove("known");
}
#[tokio::test]
async fn dropping_the_stream_deregisters_the_run() {
let (tx, rx) = mpsc::unbounded_channel();
PENDING.insert("abandoned".to_string(), tx);
let stream = stream::<serde_json::Value>(rx, Registered("abandoned".to_string()));
assert!(PENDING.contains_key("abandoned"));
drop(stream);
assert!(!PENDING.contains_key("abandoned"));
}
#[tokio::test]
async fn an_exchange_yields_only_its_items() {
let (tx, rx) = mpsc::unbounded_channel();
let id = "exchange";
PENDING.insert(id.to_string(), tx.clone());
tx.send(CliResponse::Ack { id: id.into() }).unwrap();
tx.send(CliResponse::Error {
id: id.into(),
error: "upstream said no".into(),
})
.unwrap();
tx.send(CliResponse::Done { id: id.into() }).unwrap();
let items: Vec<_> = stream::<serde_json::Value>(rx, Registered(id.to_string()))
.collect()
.await;
assert_eq!(items.len(), 1, "the ack and the done are not items");
assert!(matches!(items[0], Err(Error::Host(_))));
}
}