use super::{
person::Attendance,
policy::{AcpAgentPolicy, AcpProtocol, SessionConfigChoice},
};
use agent_client_protocol::{
schema::ProtocolVersion,
v1::schema::{
AuthenticateRequest, ClientCapabilities, ElicitationCapabilities,
ElicitationFormCapabilities, Implementation, InitializeRequest, NewSessionRequest,
NewSessionResponse, ResumeSessionResponse, SessionConfigKind, SessionConfigOption,
SessionConfigSelectOptions, SessionConfigValueId, SessionModeId, SessionModeState,
SessionUpdate, SetSessionConfigOptionRequest, SetSessionModeRequest,
},
v1::{ActiveSession, ConnectionTo, SessionSetup},
Agent, Error,
};
use std::{future::Future, sync::Mutex, time::Duration};
pub(super) const HANDSHAKE_STEP_BUDGET: Duration = Duration::from_secs(10);
pub(super) fn error(message: impl Into<String>) -> Error {
let mut error = Error::internal_error();
error.message = message.into();
error
}
pub(super) async fn bounded<T>(
step: &str,
future: impl Future<Output = Result<T, Error>>,
) -> Result<T, Error> {
tokio::time::timeout(HANDSHAKE_STEP_BUDGET, future)
.await
.map_err(|_| error(format!("acp: {step} exceeded handshake step budget 10 s")))?
.map_err(|source| error(format!("acp: {step}: {source}")))
}
pub(super) fn initialize_request(attendance: Attendance) -> InitializeRequest {
let request = InitializeRequest::new(ProtocolVersion::V1)
.client_info(Implementation::new("rho", env!("CARGO_PKG_VERSION")).title("Rho"));
match attendance {
Attendance::Attended => {
request.client_capabilities(ClientCapabilities::new().elicitation(
ElicitationCapabilities::new().form(ElicitationFormCapabilities::new()),
))
}
Attendance::Unattended => request,
}
}
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct AgentFeatures {
pub(super) steering: bool,
pub(super) resume: bool,
pub(super) mcp_over_acp: bool,
pub(super) image: bool,
}
#[derive(Clone, Copy)]
pub(super) struct SetUp<'a> {
modes: Option<&'a SessionModeState>,
config_options: Option<&'a Vec<SessionConfigOption>>,
}
impl<'a> From<&'a NewSessionResponse> for SetUp<'a> {
fn from(response: &'a NewSessionResponse) -> Self {
Self {
modes: response.modes.as_ref(),
config_options: response.config_options.as_ref(),
}
}
}
impl<'a> From<&'a ResumeSessionResponse> for SetUp<'a> {
fn from(response: &'a ResumeSessionResponse) -> Self {
Self {
modes: response.modes.as_ref(),
config_options: response.config_options.as_ref(),
}
}
}
pub(super) async fn new_session<P: AcpAgentPolicy>(
cx: &ConnectionTo<Agent>,
request: NewSessionRequest,
policy: &Mutex<P>,
) -> Result<SessionSetup<'static, Agent, NewSessionResponse>, Error> {
let setup = bounded(
"session/new",
cx.build_session_from(request).block_task().start_session(),
)
.await?;
let offered = setup.response.config_options.as_deref().unwrap_or_default();
policy.lock().expect("ACP policy").config_seen(offered);
Ok(setup)
}
pub(super) async fn initialize<P: AcpAgentPolicy>(
cx: &ConnectionTo<Agent>,
policy: &Mutex<P>,
attendance: Attendance,
adapter: Option<super::adapters::Adapter<'_>>,
) -> Result<AgentFeatures, Error> {
let response = bounded(
"initialize",
cx.send_request(initialize_request(attendance)).block_task(),
)
.await
.and_then(|response| match response.protocol_version {
ProtocolVersion::V1 => Ok(response),
other => Err(error(format!(
"acp: initialize: unsupported protocol version {other}"
))),
});
let response = match response {
Ok(response) => response,
Err(failed) => {
if let Some(adapter) = adapter {
adapter.v1_failed();
}
return Err(failed);
}
};
let image = response.agent_capabilities.prompt_capabilities.image;
if let Some(adapter) = adapter {
let version = response
.agent_info
.as_ref()
.map(|info| info.version.clone());
adapter.initialized(AcpProtocol::V1, AcpProtocol::V1, version, image);
}
let method = policy
.lock()
.expect("ACP policy")
.auth_method(&response.auth_methods);
if let Some(method) = method {
bounded(
"authenticate",
cx.send_request(AuthenticateRequest::new(method))
.block_task(),
)
.await?;
}
Ok(AgentFeatures {
steering: super::steering::supported(response.meta.as_ref()),
resume: response
.agent_capabilities
.session_capabilities
.resume
.is_some(),
mcp_over_acp: response.agent_capabilities.mcp_capabilities.acp,
image,
})
}
pub(super) fn check_mode_update(
update: &SessionUpdate,
required: Option<&SessionModeId>,
) -> Result<(), Error> {
if let (SessionUpdate::CurrentModeUpdate(mode), Some(required)) = (update, required) {
if mode.current_mode_id != *required {
return Err(error(format!(
"acp: agent switched to mode `{}`, leaving required mode `{required}`",
mode.current_mode_id
)));
}
}
Ok(())
}
pub(super) async fn require_mode<P: AcpAgentPolicy>(
session: &ActiveSession<'_, Agent>,
created: SetUp<'_>,
policy: &Mutex<P>,
) -> Result<(), Error> {
let mode = policy.lock().expect("ACP policy").session_mode();
if let Some(mode) = mode {
if !created.modes.is_some_and(|modes| {
modes
.available_modes
.iter()
.any(|available| available.id == mode)
}) {
return Err(error(format!(
"acp: session/set_mode: required mode `{mode}` is not advertised"
)));
}
bounded(
&format!("session/set_mode `{mode}`"),
session
.connection()
.send_request(SetSessionModeRequest::new(
session.session_id().clone(),
mode,
))
.block_task(),
)
.await?;
}
Ok(())
}
pub(super) async fn require_config<P: AcpAgentPolicy>(
session: &ActiveSession<'_, Agent>,
created: SetUp<'_>,
policy: &Mutex<P>,
) -> Result<(), Error> {
let choices = policy.lock().expect("ACP policy").session_config();
let mut options = created.config_options.cloned().unwrap_or_default();
for choice in choices {
if !needs_setting(&options, &choice)? {
continue;
}
options = bounded(
&config_step(&choice),
session
.connection()
.send_request(SetSessionConfigOptionRequest::new(
session.session_id().clone(),
choice.id,
choice.value,
))
.block_task(),
)
.await?
.config_options;
}
Ok(())
}
pub(super) fn config_step(choice: &SessionConfigChoice) -> String {
format!("session/set_config_option `{}`", choice.id)
}
pub(super) fn needs_setting(
options: &[SessionConfigOption],
choice: &SessionConfigChoice,
) -> Result<bool, Error> {
let step = config_step(choice);
let Some((current, values)) = options
.iter()
.find(|option| option.id == choice.id)
.and_then(select_state)
else {
return Err(error(format!(
"acp: {step}: the agent does not advertise select option `{}`",
choice.id
)));
};
if !values.contains(&&choice.value) {
let available = values
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ");
return Err(error(format!(
"acp: {step}: value `{}` is not advertised (available: {available})",
choice.value
)));
}
Ok(*current != choice.value)
}
pub(super) fn select_state(
option: &SessionConfigOption,
) -> Option<(&SessionConfigValueId, Vec<&SessionConfigValueId>)> {
let SessionConfigKind::Select(select) = &option.kind else {
return None;
};
let values = match &select.options {
SessionConfigSelectOptions::Ungrouped(options) => {
options.iter().map(|option| &option.value).collect()
}
SessionConfigSelectOptions::Grouped(groups) => groups
.iter()
.flat_map(|group| &group.options)
.map(|option| &option.value)
.collect(),
_ => return None,
};
Some((&select.current_value, values))
}