use std::collections::BTreeMap;
use agent_client_protocol::v1::schema::{
CreateElicitationRequest, CreateElicitationResponse, ElicitationAcceptAction,
ElicitationAction, ElicitationContentValue, ElicitationMode, ElicitationScope,
};
use rho_sdk::{HostInputRefusal, HostInputRequest, HostInputResponse, HostInputSource};
use super::person::{PersonAnswer, PersonAsk};
use crate::tools::mcp::elicitation_form::ElicitationForm;
pub(super) struct AgentForm {
form: ElicitationForm,
}
impl AgentForm {
pub(super) fn of(
request: &CreateElicitationRequest,
) -> Result<(Self, PersonAsk), CreateElicitationResponse> {
let ElicitationMode::Form(mode) = &request.mode else {
return Err(declined());
};
let tool_call = match &mode.scope {
ElicitationScope::Session(scope) => {
scope.tool_call_id.as_ref().map(|id| id.to_string())
}
_ => return Err(declined()),
};
let form = serde_json::to_value(&mode.requested_schema)
.ok()
.and_then(|schema| serde_json::from_value(schema).ok())
.and_then(|schema| ElicitationForm::from_schema(&schema).ok())
.ok_or_else(declined)?;
let request = HostInputRequest::questionnaire(&request.message, form.questions().to_vec())
.map(HostInputRequest::user_only)
.map_err(|_| declined())?;
Ok((Self { form }, PersonAsk::Form { tool_call, request }))
}
pub(super) fn response(&self, answer: Option<PersonAnswer>) -> CreateElicitationResponse {
match answer {
Some(PersonAnswer::Form(Ok(response))) => self.accepted(&response),
Some(PersonAnswer::Form(Err(HostInputRefusal::Dismissed))) | None => {
CreateElicitationResponse::new(ElicitationAction::Cancel)
}
Some(PersonAnswer::Form(Err(_))) => declined(),
Some(PersonAnswer::Allow | PersonAnswer::Deny) => declined(),
}
}
fn accepted(&self, response: &HostInputResponse) -> CreateElicitationResponse {
if response.source() != HostInputSource::User {
return declined();
}
let content = self.form.content(response).ok().and_then(|content| {
serde_json::from_value::<BTreeMap<String, ElicitationContentValue>>(content).ok()
});
match content {
Some(content) => CreateElicitationResponse::new(ElicitationAction::Accept(
ElicitationAcceptAction::new().content(content),
)),
None => declined(),
}
}
}
fn declined() -> CreateElicitationResponse {
CreateElicitationResponse::new(ElicitationAction::Decline)
}