use std::sync::{Arc, OnceLock};
use rho_sdk::{
tool::{
OperationKind, Tool as SdkTool, ToolContext as SdkToolContext, ToolError as SdkToolError,
ToolErrorKind, ToolFuture, ToolInvocation, ToolMetadata, ToolOutput, ToolSecurity,
},
HostChoice, HostInputRequest, HostInputResponse, HostQuestion, SelectionMode,
};
use crate::app::self_questions::{Form, SelfQuestions};
#[derive(Clone, Default)]
pub(crate) struct SelfAsks(Arc<OnceLock<SelfQuestions>>);
impl SelfAsks {
pub(crate) fn bind(&self, questions: SelfQuestions) {
let _ = self.0.set(questions);
}
}
pub(super) fn questionnaire_bundle(
expiry: crate::config::QuestionnaireExpiry,
asks: SelfAsks,
) -> super::sdk_registry::StaticToolBundle {
super::sdk_registry::StaticToolBundle::new(vec![Arc::new(QuestionnaireTool { expiry, asks })])
}
pub(crate) fn form(arguments: serde_json::Value) -> Result<Form, String> {
let request = crate::questionnaire::parse_request(arguments.clone())?;
let questions = request
.questions
.iter()
.map(host_question)
.collect::<Result<Vec<_>, _>>()
.map_err(|error| error.to_string())?;
let ask = request
.title
.iter()
.chain(request.questions.iter().map(|question| &question.question))
.find(|text| !text.trim().is_empty())
.cloned()
.unwrap_or_default();
let title = request
.title
.clone()
.unwrap_or_else(|| "questionnaire".into());
let mut host_request =
HostInputRequest::questionnaire(title, questions).map_err(|error| error.to_string())?;
if let Some(reason) = &request.reason {
host_request = host_request.with_reason(reason);
}
if let Some(fallback) = request.fallback() {
host_request = match &request.assumption {
Some(assumption) => host_request.with_timeout_fallback(fallback, assumption),
None => host_request.with_timeout_fallback_without_reason(fallback),
}
.map_err(|error| error.to_string())?;
}
Ok(Form {
arguments,
request: host_request,
ask,
})
}
pub(crate) fn answer_content(response: &HostInputResponse) -> String {
let answers = response
.answers()
.iter()
.map(|(id, values)| crate::questionnaire::QuestionnaireAnswer {
id: id.clone(),
answer: if values.len() == 1 {
serde_json::Value::String(values[0].clone())
} else {
serde_json::Value::Array(
values
.iter()
.cloned()
.map(serde_json::Value::String)
.collect(),
)
},
})
.collect();
crate::questionnaire::response_content(&crate::questionnaire::QuestionnaireResponse::new(
answers,
response.source(),
))
}
const ASKED: &str = "Asked. The answer arrives in a later turn of yours, as a background result; you can't get it in this turn. End your turn now, or go on with work that doesn't depend on the answer.";
struct QuestionnaireTool {
expiry: crate::config::QuestionnaireExpiry,
asks: SelfAsks,
}
impl SdkTool for QuestionnaireTool {
fn spec(&self) -> rho_sdk::model::ToolSpec {
crate::questionnaire::tool_spec(self.expiry)
}
fn security(&self) -> ToolSecurity {
ToolSecurity::built_in([])
}
fn call<'a>(&'a self, invocation: ToolInvocation, context: SdkToolContext) -> ToolFuture<'a> {
Box::pin(async move {
let form = form(invocation.into_arguments())
.map_err(|message| SdkToolError::new(ToolErrorKind::InvalidArguments, message))?;
let content = match self.asks.0.get() {
Some(questions) => match questions.ask(form) {
Some(_) => ASKED.to_owned(),
None => {
return Err(SdkToolError::new(
ToolErrorKind::Execution,
"the session's host no longer takes questions",
))
}
},
None => {
let response = context
.request_host_input(form.request)
.await
.map_err(map_sdk_error)?;
answer_content(&response)
}
};
Ok(ToolOutput::text(content).metadata(
ToolMetadata::new().operation(OperationKind::Other("questionnaire".into())),
))
})
}
}
fn host_question(
question: &crate::questionnaire::QuestionnaireQuestion,
) -> Result<HostQuestion, rho_sdk::Error> {
use crate::questionnaire::QuestionnaireQuestionKind;
let selection = match question.kind {
QuestionnaireQuestionKind::MultiSelect => SelectionMode::Many,
QuestionnaireQuestionKind::Choice
| QuestionnaireQuestionKind::Confirm
| QuestionnaireQuestionKind::Text => SelectionMode::One,
};
let choices = match question.kind {
QuestionnaireQuestionKind::Choice | QuestionnaireQuestionKind::MultiSelect => question
.choices
.iter()
.map(|choice| {
let host = HostChoice::new(&choice.label, &choice.label);
match &choice.description {
Some(description) => host.with_description(description),
None => host,
}
})
.collect(),
QuestionnaireQuestionKind::Confirm => {
vec![HostChoice::new("yes", "Yes"), HostChoice::new("no", "No")]
}
QuestionnaireQuestionKind::Text => vec![HostChoice::new("other", "Other")],
};
let mut host = HostQuestion::new(&question.id, &question.question, choices, selection)?;
if question.allow_other || matches!(question.kind, QuestionnaireQuestionKind::Text) {
host = host.allow_other();
}
if let Some(header) = &question.header {
host = host.with_header(header);
}
if let Some(help) = &question.help {
host = host.with_help(help);
}
if let Some(default) = &question.default {
host = host.with_default_value(default.clone());
}
host = host.with_default_selection(question.default_selection.into());
if !question.required {
host = host.optional();
}
Ok(host)
}
fn map_sdk_error(error: rho_sdk::Error) -> SdkToolError {
match error {
rho_sdk::Error::Cancelled => SdkToolError::cancelled(),
error => SdkToolError::new(ToolErrorKind::Execution, error.to_string()),
}
}
#[cfg(test)]
#[path = "questionnaire_tool_tests.rs"]
mod tests;