use std::sync::{Mutex, PoisonError};
use agent_client_protocol::{
schema::ProtocolVersion, v2::schema as v2, Error as AcpError, RawJsonRpcId, RawJsonRpcMessage,
};
use serde::{de::IgnoredAny, Deserialize};
use serde_json::Value;
pub(super) struct InitializeScreen {
supported: &'static [ProtocolVersion],
negotiation: Mutex<Negotiation>,
}
enum Negotiation {
Pending(Vec<RawJsonRpcId>),
Done,
}
impl InitializeScreen {
pub(super) fn new(supported: &'static [ProtocolVersion]) -> Self {
Self {
supported,
negotiation: Mutex::new(Negotiation::Pending(Vec::new())),
}
}
pub(super) fn incoming(&self, line: &str) -> Option<String> {
let mut negotiation = self.lock();
let Negotiation::Pending(pending) = &mut *negotiation else {
return None;
};
match screen(line, self.supported) {
Screened::Forward => None,
Screened::Initialize(id) => {
pending.push(id);
None
}
Screened::Answer(id, error) => Some(
serde_json::to_string(&RawJsonRpcMessage::response(id, Err(error)))
.expect("a JSON-RPC error response always serializes"),
),
}
}
pub(super) fn outgoing(&self, line: &str) {
let mut negotiation = self.lock();
if let Negotiation::Pending(pending) = &*negotiation {
if initialized(line, pending) {
*negotiation = Negotiation::Done;
}
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, Negotiation> {
self.negotiation
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
}
enum Screened {
Forward,
Initialize(RawJsonRpcId),
Answer(RawJsonRpcId, AcpError),
}
fn screen(line: &str, supported: &[ProtocolVersion]) -> Screened {
#[derive(Deserialize)]
struct Request {
id: RawJsonRpcId,
method: String,
#[serde(default)]
params: Option<Value>,
}
let Ok(request) = serde_json::from_str::<Request>(line) else {
return Screened::Forward;
};
if request.method != "initialize" || request.id == RawJsonRpcId::Null {
return Screened::Forward;
}
let version = request
.params
.as_ref()
.and_then(Value::as_object)
.and_then(|params| params.get("protocolVersion"))
.and_then(|version| ProtocolVersion::deserialize(version).ok());
match version {
Some(version) if supported.iter().any(|served| *served <= version) => {
Screened::Initialize(request.id)
}
Some(version) => Screened::Answer(
request.id,
v2::Error::unsupported_protocol_version(version, supported).into(),
),
None => Screened::Answer(
request.id,
AcpError::invalid_params()
.data("initialize.protocolVersion must be an integer from 0 to 65535"),
),
}
}
fn initialized(line: &str, pending: &[RawJsonRpcId]) -> bool {
#[derive(Deserialize)]
struct Reply {
id: RawJsonRpcId,
result: Option<IgnoredAny>,
}
serde_json::from_str::<Reply>(line)
.is_ok_and(|reply| reply.result.is_some() && pending.contains(&reply.id))
}
#[cfg(test)]
#[path = "initialize_screen_tests.rs"]
mod tests;