use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::sync::{Arc, Mutex, PoisonError};
pub const ASK_USER: &str = "ask_user";
pub const ASK_KEY: &str = "agent86_ask";
pub const MAX_QUESTIONS: usize = 10;
pub const MIN_OPTIONS: usize = 1;
pub const MAX_OPTIONS: usize = 12;
pub const MAX_QUESTION_CHARS: usize = 300;
pub const MAX_TITLE_CHARS: usize = 120;
pub const MAX_OPTION_CHARS: usize = 200;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AnswerKind {
Choice,
Multi,
Text,
LongText,
Number,
YesNo,
Date,
}
impl AnswerKind {
pub const ALL: [AnswerKind; 7] = [
AnswerKind::Choice,
AnswerKind::Multi,
AnswerKind::Text,
AnswerKind::LongText,
AnswerKind::Number,
AnswerKind::YesNo,
AnswerKind::Date,
];
pub fn as_str(self) -> &'static str {
match self {
AnswerKind::Choice => "choice",
AnswerKind::Multi => "multi",
AnswerKind::Text => "text",
AnswerKind::LongText => "long_text",
AnswerKind::Number => "number",
AnswerKind::YesNo => "yes_no",
AnswerKind::Date => "date",
}
}
fn parse(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|kind| kind.as_str() == name)
}
pub fn has_options(self) -> bool {
matches!(self, AnswerKind::Choice | AnswerKind::Multi)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FormQuestion {
pub id: String,
pub question: String,
pub kind: AnswerKind,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub options: Vec<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub optional: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Form {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
pub questions: Vec<FormQuestion>,
}
impl Form {
pub fn parse(args: &Map<String, Value>) -> Result<Form, Vec<String>> {
let mut problems = Vec::new();
let title = match args.get("title") {
None | Some(Value::Null) => None,
Some(Value::String(title)) if title.trim().is_empty() => None,
Some(Value::String(title)) => {
if title.chars().count() > MAX_TITLE_CHARS {
problems.push(format!(
"title: longer than {MAX_TITLE_CHARS} characters; shorten it"
));
}
Some(title.trim().to_owned())
}
Some(_) => {
problems.push("title: should be a string".into());
None
}
};
let items = match args.get("questions") {
Some(Value::Array(items)) => items.as_slice(),
None | Some(Value::Null) => {
problems.push("questions: required, a list of 1 to 10 questions".into());
&[]
}
Some(_) => {
problems.push("questions: should be a list of questions".into());
&[]
}
};
if items.is_empty() && args.get("questions").is_some_and(Value::is_array) {
problems.push("questions: empty; ask at least one question".into());
}
if items.len() > MAX_QUESTIONS {
problems.push(format!(
"questions: {} questions, more than {MAX_QUESTIONS}; ask the {MAX_QUESTIONS} \
that matter most now, and the rest in a later call",
items.len()
));
}
let mut questions = Vec::new();
let mut seen: Vec<String> = Vec::new();
for (index, item) in items.iter().enumerate() {
if let Some(question) = parse_question(index, item, &mut seen, &mut problems) {
questions.push(question);
}
}
if problems.is_empty() {
Ok(Form { title, questions })
} else {
Err(problems)
}
}
pub fn accept(&self, values: &Map<String, Value>) -> Accepted {
let mut accepted = Accepted::default();
for question in &self.questions {
let value = values
.get(&question.id)
.map(|value| normalize(question, value))
.unwrap_or(Value::Null);
if value.is_null() {
if !question.optional {
accepted.unanswered.push(question.id.clone());
}
} else if typed(question, &value) {
accepted.typed.push(question.id.clone());
}
accepted.answers.insert(question.id.clone(), value);
}
accepted
}
pub fn kinds(&self) -> Vec<&'static str> {
self.questions.iter().map(|q| q.kind.as_str()).collect()
}
}
fn parse_question(
index: usize,
item: &Value,
seen: &mut Vec<String>,
problems: &mut Vec<String>,
) -> Option<FormQuestion> {
let Some(fields) = item.as_object() else {
problems.push(format!(
"questions/{index}: should be an object with id, question, and kind"
));
return None;
};
let id = fields.get("id").and_then(Value::as_str).unwrap_or_default();
let at = if id.is_empty() {
format!("questions/{index}")
} else {
format!("questions/{index} ({id})")
};
let before = problems.len();
let field = |names: &[&str]| {
names
.iter()
.find_map(|name| fields.get(*name).filter(|value| !value.is_null()))
};
if id.is_empty() {
problems.push(format!(
"{at}: id is required, an identifier such as \"scope\""
));
} else if !agent86_ui_identifier(id) {
problems.push(format!(
"{at}: id should be an identifier: letters, digits, and _, starting with a letter or _"
));
} else if seen.iter().any(|other| other == id) {
problems.push(format!(
"{at}: id {id:?} is used by an earlier question; ids must differ"
));
} else {
seen.push(id.to_owned());
}
let question = match field(&["question", "label", "text", "prompt"]) {
Some(Value::String(text)) if !text.trim().is_empty() => {
if text.chars().count() > MAX_QUESTION_CHARS {
problems.push(format!(
"{at}: question is longer than {MAX_QUESTION_CHARS} characters; shorten it"
));
}
text.trim().to_owned()
}
_ => {
problems.push(format!("{at}: question is required, the text to ask"));
String::new()
}
};
let kind = match field(&["kind", "type"]).and_then(Value::as_str) {
Some(name) => AnswerKind::parse(name).or_else(|| {
problems.push(format!("{at}: kind {name:?} is not one of {}", kind_list()));
None
}),
None => {
problems.push(format!("{at}: kind is required, one of {}", kind_list()));
None
}
};
let mut options: Vec<String> = match field(&["options", "choices"]) {
None | Some(Value::Null) => Vec::new(),
Some(Value::Array(options)) => options
.iter()
.filter_map(|option| match option {
Value::String(text) if !text.trim().is_empty() => Some(text.trim().to_owned()),
_ => {
problems.push(format!("{at}: every option should be a non-empty string"));
None
}
})
.collect(),
Some(_) => {
problems.push(format!("{at}: options should be a list of strings"));
Vec::new()
}
};
if let Some(kind) = kind {
if kind.has_options() {
if options.len() > MAX_OPTIONS {
problems.push(format!(
"{at}: a {} question takes at most {MAX_OPTIONS} options, not {} \
(\"Other\" is added for you)",
kind.as_str(),
options.len()
));
}
if options
.iter()
.any(|option| option.chars().count() > MAX_OPTION_CHARS)
{
problems.push(format!(
"{at}: an option is longer than {MAX_OPTION_CHARS} characters; shorten it"
));
}
let mut unique: Vec<String> = Vec::new();
for option in options.drain(..) {
if !unique.contains(&option) {
unique.push(option);
}
}
options = unique;
}
}
let optional = match (field(&["optional"]), field(&["required"])) {
(Some(Value::Bool(optional)), _) => *optional,
(None, Some(Value::Bool(required))) => !required,
(None, None | Some(_)) => false,
(Some(_), _) => {
problems.push(format!("{at}: optional should be true or false"));
false
}
};
if problems.len() > before {
return None;
}
let kind = kind.map(|kind| {
if kind.has_options() && options.is_empty() {
AnswerKind::Text
} else {
kind
}
});
Some(FormQuestion {
id: id.to_owned(),
question,
kind: kind?,
options: if kind.is_some_and(AnswerKind::has_options) {
options
} else {
Vec::new()
},
optional,
})
}
fn kind_list() -> String {
AnswerKind::ALL
.iter()
.map(|kind| kind.as_str())
.collect::<Vec<_>>()
.join(", ")
}
fn agent86_ui_identifier(id: &str) -> bool {
let mut chars = id.chars();
chars
.next()
.is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
&& chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
}
fn normalize(question: &FormQuestion, value: &Value) -> Value {
let text = |value: &Value| match value {
Value::String(text) => Some(text.trim().to_owned()).filter(|text| !text.is_empty()),
Value::Number(number) => Some(number.to_string()),
Value::Bool(flag) => Some(flag.to_string()),
_ => None,
};
let single = |value: &Value| match value {
Value::Array(items) => items.iter().find_map(text),
other => text(other),
};
match question.kind {
AnswerKind::Choice => single(value).map_or(Value::Null, Value::String),
AnswerKind::Multi => {
let items: Vec<Value> = match value {
Value::Array(items) => items.iter().filter_map(text).map(Value::String).collect(),
other => text(other).map(Value::String).into_iter().collect(),
};
if items.is_empty() {
Value::Null
} else {
Value::Array(items)
}
}
AnswerKind::Text | AnswerKind::LongText => single(value).map_or(Value::Null, Value::String),
AnswerKind::Number => match value {
Value::Number(_) => value.clone(),
other => match single(other) {
None => Value::Null,
Some(text) => number(&text).unwrap_or(Value::String(text)),
},
},
AnswerKind::YesNo => match value {
Value::Bool(_) => value.clone(),
other => match single(other).map(|text| text.to_ascii_lowercase()) {
None => Value::Null,
Some(text) if text == "yes" || text == "true" => Value::Bool(true),
Some(text) if text == "no" || text == "false" => Value::Bool(false),
Some(text) => Value::String(text),
},
},
AnswerKind::Date => match single(value) {
None => Value::Null,
Some(text) => {
let date = text.get(..10).filter(|date| is_date(date));
Value::String(date.map_or(text.clone(), str::to_owned))
}
},
}
}
fn number(text: &str) -> Option<Value> {
if let Ok(integer) = text.parse::<i64>() {
return Some(Value::from(integer));
}
let float = text.parse::<f64>().ok().filter(|f| f.is_finite())?;
serde_json::Number::from_f64(float).map(Value::Number)
}
fn is_date(text: &str) -> bool {
let bytes = text.as_bytes();
bytes.len() == 10
&& bytes[4] == b'-'
&& bytes[7] == b'-'
&& bytes
.iter()
.enumerate()
.all(|(index, byte)| index == 4 || index == 7 || byte.is_ascii_digit())
}
fn typed(question: &FormQuestion, value: &Value) -> bool {
if !question.kind.has_options() {
return false;
}
let listed = |text: &str| question.options.iter().any(|option| option == text);
match value {
Value::String(text) => !listed(text),
Value::Array(items) => items
.iter()
.any(|item| item.as_str().is_some_and(|text| !listed(text))),
_ => false,
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Accepted {
pub answers: Map<String, Value>,
pub typed: Vec<String>,
pub unanswered: Vec<String>,
}
impl Accepted {
pub fn text(&self) -> String {
let mut text = format!(
"The user answered:\n{}",
crate::pyjson::python_json_dumps(&Value::Object(self.answers.clone()), false)
);
if !self.typed.is_empty() {
text.push_str(&format!(
"\nIn their own words, not one of the options: {}.",
self.typed.join(", ")
));
}
if !self.unanswered.is_empty() {
text.push_str(&format!(
"\nLeft unanswered: {}.",
self.unanswered.join(", ")
));
}
text
}
}
pub const DISMISSED: &str = "The user closed the form without answering. Do not ask these \
questions again in this turn: go on with what you know, or end your turn saying what \
you still need.";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Via {
Form,
Extension,
Text,
}
impl Via {
pub fn as_str(self) -> &'static str {
match self {
Via::Form => "form",
Via::Extension => "extension",
Via::Text => "text",
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Outcome {
Answered(Map<String, Value>),
Dismissed,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Reply {
pub outcome: Outcome,
pub via: Via,
}
pub type AskPrompt = Box<dyn Fn(&Form) -> Reply + Send + Sync>;
#[derive(Clone, Default)]
pub struct Asker {
prompt: Arc<Mutex<Option<Arc<AskPrompt>>>>,
form: Arc<std::sync::atomic::AtomicBool>,
forms: Arc<std::sync::atomic::AtomicU64>,
}
impl std::fmt::Debug for Asker {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Asker")
.field("can_ask", &self.can_ask())
.field("draws_form", &self.draws_form())
.finish()
}
}
impl Asker {
pub fn set_prompt(&self, prompt: Option<AskPrompt>) {
*self.prompt.lock().unwrap_or_else(PoisonError::into_inner) = prompt.map(Arc::new);
}
pub fn can_ask(&self) -> bool {
self.prompt().is_some()
}
pub fn set_draws_form(&self, draws: bool) {
self.form.store(draws, std::sync::atomic::Ordering::Relaxed);
}
pub fn draws_form(&self) -> bool {
self.form.load(std::sync::atomic::Ordering::Relaxed)
}
pub fn next_surface(&self) -> String {
let n = self
.forms
.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
+ 1;
format!("{FORM_SURFACE_PREFIX}{n}")
}
pub fn prompt(&self) -> Option<Arc<AskPrompt>> {
self.prompt
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
}
pub fn reachable(ctx: &crate::tools::ToolContext) -> bool {
if ctx.asker.can_ask() {
return true;
}
#[cfg(feature = "agent86ui")]
if ctx.asker.draws_form() {
return ctx.ui.as_deref().is_some_and(|ui| ui.can_wait());
}
false
}
pub fn prompt_section(render_ui_offered: bool) -> String {
let mut section = String::from(
"## Asking the user\n\n\
When you need information, a preference, or a decision from the user before you \
can go on, call ask_user with all your questions at once. Do not ask them in your \
reply. Use choice or multi with options whenever the likely answers are known; \
\"Other\" is always offered, so the user is never trapped by your list. Ask only \
what you need, then wait for the answers, which come back as the call's result.",
);
if render_ui_offered {
section.push_str(
" Forms that ask the user questions go through ask_user, never render_ui, even \
when the user asks for a form: ask_user draws the form. render_ui is for \
layouts, dashboards, and choices with a presentation of their own.",
);
}
section
}
impl crate::agent::Harness {
pub fn attach_questions(&mut self, prompt: AskPrompt) -> Result<(), String> {
if self.registry.get(ASK_USER).is_none() {
self.registry
.register(Box::new(crate::tools::ask_user::AskUserTool))?;
}
self.context.asker.set_prompt(Some(prompt));
Ok(())
}
#[cfg(feature = "agent86ui")]
pub fn offer_questions_as_forms(&mut self) -> Result<bool, String> {
let drawable = self.context.ui.as_deref().is_some_and(|ui| {
ui.can_wait()
&& ui
.catalogs()
.iter()
.any(|catalog| catalog.id() == agent86_ui::BASIC_CATALOG_ID)
});
if !drawable {
return Ok(false);
}
if self.registry.get(ASK_USER).is_none() {
self.registry
.register(Box::new(crate::tools::ask_user::AskUserTool))?;
}
self.context.asker.set_draws_form(true);
Ok(true)
}
#[cfg(feature = "agent86ui")]
fn ask_through_renderer(
&self,
form: &Form,
question: crate::approval::Question,
emit: &mut dyn FnMut(crate::agent::TurnEvent<'_>),
) -> Option<Reply> {
let dismissed = Reply {
outcome: Outcome::Dismissed,
via: Via::Form,
};
let Some(ui) = self.context.ui.as_deref() else {
return Some(dismissed);
};
let surface = self.context.asker.next_surface();
for message in form_messages(form, &surface, agent86_ui::BASIC_CATALOG_ID) {
if let Ok(message) = serde_json::from_value::<agent86_ui::AgentMessage>(message) {
emit(crate::agent::TurnEvent::Ui(&message));
}
}
let request = crate::agent86ui::UiWait {
surface_ids: vec![surface.clone()],
};
let action = self.gate.queue.ask(question, || ui.wait(&request));
let delete = serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": surface}});
if let Ok(delete) = serde_json::from_value::<agent86_ui::AgentMessage>(delete) {
emit(crate::agent::TurnEvent::Ui(&delete));
}
Some(match action? {
Some(action) if action.surface_id == surface => Reply {
outcome: Outcome::Answered(values_from_context(form, &action.context)),
via: Via::Form,
},
_ => dismissed,
})
}
pub(crate) fn ask_questions(
&self,
call: &crate::types::ToolCall,
result: crate::types::ToolResult,
sid: &str,
emit: &mut dyn FnMut(crate::agent::TurnEvent<'_>),
) -> crate::types::ToolResult {
use crate::approval::{Question, QuestionKind};
use crate::tools::{failure, success};
use serde_json::json;
let mut result = result;
let Some(value) = result.metadata.remove(ASK_KEY) else {
return result;
};
let answered = |result: crate::types::ToolResult| crate::types::ToolResult {
call_id: call.id.clone(),
..result
};
let (Ok(form), true) = (
serde_json::from_value::<Form>(value),
reachable(&self.context),
) else {
return answered(failure(
ASK_USER,
"Nobody can answer questions here, so none were asked.".into(),
));
};
let record = |outcome: &str, via: Option<Via>, unanswered: usize| {
self.recorder.event(
sid,
"ask_user",
vec![
("questions", json!(form.questions.len())),
("kinds", json!(form.kinds())),
("via", json!(via.map(Via::as_str))),
("outcome", json!(outcome)),
("unanswered", json!(unanswered)),
],
);
};
let question = Question {
tool: Some(ASK_USER.into()),
call: Some(call.id.clone()),
..Question::new(QuestionKind::Ask)
};
let asked = match self.context.asker.prompt() {
Some(prompt) => self.gate.queue.ask(question, || prompt(&form)),
#[cfg(feature = "agent86ui")]
None => self.ask_through_renderer(&form, question, emit),
#[cfg(not(feature = "agent86ui"))]
None => {
let _ = (question, &emit);
None
}
};
match asked {
None => {
record("cancelled", None, 0);
answered(failure(
ASK_USER,
"The turn was cancelled before the user answered.".into(),
))
}
Some(Reply {
outcome: Outcome::Dismissed,
via,
}) => {
record("dismissed", Some(via), 0);
answered(success(ASK_USER, DISMISSED.into()))
}
Some(Reply {
outcome: Outcome::Answered(values),
via,
}) => {
let accepted = form.accept(&values);
let text = self.context.secrets.redact(&accepted.text());
let report = self.guardrails.inspect_ingress(&text);
if report.flagged() {
self.recorder.event(
sid,
"guardrail",
vec![
("stage", json!("ingress")),
("source", json!(ASK_USER)),
("findings", json!(report.summary())),
],
);
}
if self.guardrails.should_block(&report) {
record("refused", Some(via), accepted.unanswered.len());
return answered(failure(
ASK_USER,
format!(
"The user's answers were refused by the input guardrail ({}).",
report.summary()
),
));
}
record("answered", Some(via), accepted.unanswered.len());
answered(success(ASK_USER, text))
}
}
}
}
pub const FORM_SURFACE_PREFIX: &str = "agent86_ask_";
#[cfg(feature = "agent86ui")]
pub const OTHER_LABEL: &str = "Other";
#[cfg(feature = "agent86ui")]
const OTHER_VALUE: &str = "__other__";
#[cfg(feature = "agent86ui")]
pub fn form_messages(form: &Form, surface_id: &str, catalog_id: &str) -> Vec<Value> {
use serde_json::json;
let mut children: Vec<Value> = Vec::new();
let mut components: Vec<Value> = Vec::new();
let mut answers = Map::new();
let mut other = Map::new();
if let Some(title) = &form.title {
children.push(json!("title"));
components.push(json!({"id": "title", "component": "Text", "text": title}));
}
for question in &form.questions {
let id = &question.id;
let input = format!("q_{id}");
let label = if question.optional {
format!("{} (optional)", question.question)
} else {
question.question.clone()
};
let bound = json!({"@path": format!("/answers/{id}")});
children.push(json!(input));
let component = match question.kind {
AnswerKind::Choice | AnswerKind::Multi => {
let mut options: Vec<Value> = question
.options
.iter()
.map(|option| json!({"label": option, "value": option}))
.collect();
options.push(json!({"label": OTHER_LABEL, "value": OTHER_VALUE}));
answers.insert(id.clone(), json!([]));
other.insert(id.clone(), json!(""));
let variant = if question.kind == AnswerKind::Choice {
"mutuallyExclusive"
} else {
"multipleSelection"
};
json!({"id": input, "component": "ChoicePicker", "label": label,
"variant": variant, "options": options, "value": bound})
}
AnswerKind::YesNo => {
answers.insert(id.clone(), json!([]));
json!({"id": input, "component": "ChoicePicker", "label": label,
"variant": "mutuallyExclusive",
"options": [{"label": "Yes", "value": "yes"}, {"label": "No", "value": "no"}],
"value": bound})
}
AnswerKind::Text | AnswerKind::LongText | AnswerKind::Number => {
answers.insert(id.clone(), json!(""));
let variant = match question.kind {
AnswerKind::LongText => "longText",
AnswerKind::Number => "number",
_ => "shortText",
};
json!({"id": input, "component": "TextField", "label": label,
"variant": variant, "value": bound})
}
AnswerKind::Date => {
answers.insert(id.clone(), json!(""));
json!({"id": input, "component": "DateTimeInput", "label": label,
"enableDate": true, "value": bound})
}
};
components.push(component);
if question.kind.has_options() {
let field = format!("o_{id}");
children.push(json!(field));
components.push(json!({"id": field, "component": "TextField",
"label": format!("{OTHER_LABEL}, in your own words"), "variant": "shortText",
"value": {"@path": format!("/other/{id}")}}));
}
}
children.push(json!("send"));
let mut send = json!({"id": "send", "component": "Button", "child": "send_label",
"variant": "primary",
"action": {"event": {"name": "answers", "context": {
"answers": {"@path": "/answers"}, "other": {"@path": "/other"}}}}});
let required: Vec<Value> = form
.questions
.iter()
.filter(|question| !question.optional)
.map(|question| {
json!({"@call": "required", "args": {"value": {"@path": format!("/answers/{}", question.id)}}})
})
.collect();
let condition = match required.len() {
0 => None,
1 => required.into_iter().next(),
_ => Some(json!({"@call": "and", "args": {"values": required}})),
};
if let Some(condition) = condition {
send["@checks"] = json!([{
"condition": condition,
"message": "Answer every question not marked (optional) to send.",
}]);
}
components.push(send);
components.push(json!({"id": "send_label", "component": "Text", "text": "Send answers"}));
components.insert(
0,
json!({"id": "root", "component": "Column", "children": children}),
);
vec![json!({"version": "1.0", "createSurface": {
"surfaceId": surface_id,
"catalogId": catalog_id,
"components": components,
"dataModel": {"answers": answers, "other": other},
}})]
}
#[cfg(feature = "agent86ui")]
pub fn values_from_context(form: &Form, context: &Map<String, Value>) -> Map<String, Value> {
let answers = context.get("answers").and_then(Value::as_object);
let other = context.get("other").and_then(Value::as_object);
let mut values = Map::new();
for question in &form.questions {
let Some(value) = answers.and_then(|answers| answers.get(&question.id)) else {
continue;
};
let typed = other
.and_then(|other| other.get(&question.id))
.and_then(Value::as_str)
.map(str::trim)
.filter(|text| !text.is_empty());
let value = match value {
Value::Array(items) if question.kind.has_options() => Value::Array(
items
.iter()
.filter_map(|item| match item.as_str() {
Some(OTHER_VALUE) => typed.map(|text| Value::String(text.to_owned())),
_ => Some(item.clone()),
})
.collect(),
),
other => other.clone(),
};
values.insert(question.id.clone(), value);
}
values
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn args(value: Value) -> Map<String, Value> {
value.as_object().unwrap().clone()
}
fn sample() -> Value {
json!({"title": "Reorganizing your home folder", "questions": [
{"id": "scope", "question": "Which content should the plan cover?", "kind": "choice",
"options": ["Whole home folder", "Personal content only"]},
{"id": "goal", "question": "What is the main goal?", "kind": "multi",
"options": ["Reduce clutter", "Find files faster", "Remove old backups"]},
{"id": "keep", "question": "Which folders must not move?", "kind": "text",
"optional": true},
{"id": "notes", "question": "Anything else?", "kind": "long_text", "optional": null},
{"id": "budget", "question": "How many hours?", "kind": "number"},
{"id": "archive", "question": "Archive old backups?", "kind": "yes_no"},
{"id": "by", "question": "Done by when?", "kind": "date", "options": null}
]})
}
#[test]
fn a_well_formed_call_parses_with_nulls_taken_as_absent() {
let form = Form::parse(&args(sample())).unwrap();
assert_eq!(form.title.as_deref(), Some("Reorganizing your home folder"));
assert_eq!(form.questions.len(), 7);
assert!(form.questions[2].optional);
assert!(!form.questions[3].optional);
assert_eq!(
form.kinds(),
[
"choice",
"multi",
"text",
"long_text",
"number",
"yes_no",
"date"
]
);
}
#[test]
fn every_problem_is_named_by_index_and_id() {
let problems = Form::parse(&args(json!({"questions": [
{"id": "scope", "question": "Which?", "kind": "choice",
"options": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]},
{"id": "scope", "question": "Again?", "kind": "text"},
{"id": "2nd", "question": "Bad id?", "kind": "text"},
{"id": "when", "question": "When?", "kind": "date", "options": ["now", "later"]},
{"id": "what", "question": "What?", "kind": "dropdown"},
{"id": "blank", "kind": "text"}
], "wait": true})))
.unwrap_err();
assert_eq!(
problems,
[
"questions/0 (scope): a choice question takes at most 12 options, not 13 (\"Other\" is added for you)",
"questions/1 (scope): id \"scope\" is used by an earlier question; ids must differ",
"questions/2 (2nd): id should be an identifier: letters, digits, and _, starting with a letter or _",
"questions/4 (what): kind \"dropdown\" is not one of choice, multi, text, long_text, number, yes_no, date",
"questions/5 (blank): question is required, the text to ask",
]
);
}
#[test]
fn unknown_fields_are_ignored_and_common_names_are_taken() {
let form = Form::parse(&args(json!({"wait": true, "questions": [
{"1": 1, "id": "target", "type": "text", "label": "Which folder?"},
{"id": "pain", "prompt": "Main problem?", "kind": "choice",
"choices": ["Clutter", "Clutter", "Duplicates"], "required": false}
]})))
.unwrap();
assert_eq!(form.questions[0].kind, AnswerKind::Text);
assert_eq!(form.questions[0].question, "Which folder?");
assert_eq!(form.questions[1].question, "Main problem?");
assert_eq!(form.questions[1].options, ["Clutter", "Duplicates"]);
assert!(form.questions[1].optional);
}
#[test]
fn one_option_is_a_question_and_none_is_asked_as_text() {
let form = Form::parse(&args(json!({"questions": [
{"id": "where", "question": "Destination?", "kind": "choice",
"options": ["Suggest one for me"]},
{"id": "what", "question": "What else?", "kind": "multi", "options": []}
]})))
.unwrap();
assert_eq!(form.questions[0].kind, AnswerKind::Choice);
assert_eq!(form.questions[0].options, ["Suggest one for me"]);
assert_eq!(form.questions[1].kind, AnswerKind::Text);
}
#[test]
fn options_on_a_question_without_them_are_ignored() {
let form = Form::parse(&args(json!({"questions": [
{"id": "pattern", "question": "Which files?", "kind": "text",
"options": ["*.log", "*.tmp"]}
]})))
.unwrap();
assert!(form.questions[0].options.is_empty());
}
#[test]
fn too_many_or_no_questions_are_refused() {
let many: Vec<Value> = (0..11)
.map(|n| json!({"id": format!("q{n}"), "question": "?", "kind": "text"}))
.collect();
let problems = Form::parse(&args(json!({ "questions": many }))).unwrap_err();
assert!(problems[0].starts_with("questions: 11 questions, more than 10"));
let problems = Form::parse(&args(json!({"questions": []}))).unwrap_err();
assert_eq!(problems, ["questions: empty; ask at least one question"]);
let problems = Form::parse(&args(json!({}))).unwrap_err();
assert_eq!(
problems,
["questions: required, a list of 1 to 10 questions"]
);
}
#[test]
fn answers_are_normalized_to_each_kind() {
let form = Form::parse(&args(sample())).unwrap();
let accepted = form.accept(&args(json!({
"scope": ["Personal content only"],
"goal": ["Reduce clutter", "Archive the photos"],
"keep": " ",
"notes": "Leave .ssh alone.",
"budget": "2.5",
"archive": ["yes"],
"by": "2026-12-01T00:00:00Z",
"unknown": "ignored"
})));
assert_eq!(
Value::Object(accepted.answers.clone()),
json!({
"scope": "Personal content only",
"goal": ["Reduce clutter", "Archive the photos"],
"keep": null,
"notes": "Leave .ssh alone.",
"budget": 2.5,
"archive": true,
"by": "2026-12-01"
})
);
assert_eq!(accepted.typed, ["goal"]);
assert!(accepted.unanswered.is_empty(), "keep is optional");
assert_eq!(
accepted.text(),
"The user answered:\n{\"scope\": \"Personal content only\", \"goal\": [\"Reduce clutter\", \"Archive the photos\"], \"keep\": null, \"notes\": \"Leave .ssh alone.\", \"budget\": 2.5, \"archive\": true, \"by\": \"2026-12-01\"}\nIn their own words, not one of the options: goal."
);
}
#[test]
fn required_questions_left_empty_are_listed() {
let form = Form::parse(&args(sample())).unwrap();
let accepted = form.accept(&args(json!({"scope": "Whole home folder", "budget": 3})));
assert_eq!(accepted.unanswered, ["goal", "notes", "archive", "by"]);
assert!(accepted
.text()
.ends_with("\nLeft unanswered: goal, notes, archive, by."));
}
#[test]
fn the_asker_holds_one_hook_shared_by_clones() {
let asker = Asker::default();
assert!(!asker.can_ask());
let clone = asker.clone();
asker.set_prompt(Some(Box::new(|_| Reply {
outcome: Outcome::Dismissed,
via: Via::Text,
})));
assert!(clone.can_ask());
let form = Form::parse(&args(sample())).unwrap();
assert_eq!(clone.prompt().unwrap()(&form).outcome, Outcome::Dismissed);
asker.set_prompt(None);
assert!(!clone.can_ask());
}
#[test]
fn the_section_says_which_tool_asks_when_render_ui_is_offered_too() {
assert!(prompt_section(false).contains("call ask_user with all your questions at once"));
assert!(!prompt_section(false).contains("render_ui"));
assert!(prompt_section(true).contains("never render_ui"));
}
#[cfg(feature = "agent86ui")]
#[test]
fn the_built_form_is_valid_and_its_send_button_carries_the_answers() {
use agent86_ui::runtime::{Gesture, Runtime};
let form = Form::parse(&args(sample())).unwrap();
let messages = form_messages(&form, "ask_1", agent86_ui::BASIC_CATALOG_ID);
let session =
crate::agent86ui::UiSession::new(vec![agent86_ui::Catalog::basic().clone()]).unwrap();
let report = session.apply(&messages);
assert!(report.is_ok(), "{:?}", report.errors);
assert!(report.warnings.is_empty(), "{:?}", report.warnings);
assert!(crate::agent86ui::policy(
&messages,
&crate::tools::SandboxPolicy::new(&std::env::temp_dir()).unwrap(),
false
)
.is_empty());
let mut runtime = Runtime::basic();
runtime.set_rules(crate::agent86ui::RULES);
assert!(runtime.apply(&messages).is_ok());
for (path, value) in [
("/answers/scope", json!(["Personal content only"])),
("/answers/goal", json!(["Reduce clutter", "__other__"])),
("/other/goal", json!("Archive the photos")),
("/answers/budget", json!("4")),
("/answers/archive", json!(["no"])),
("/answers/by", json!("2026-12-01")),
] {
runtime.input("ask_1", path, value).unwrap();
}
let send = runtime.node("ask_1", "send").unwrap();
assert!(!send.is_valid());
assert_eq!(
send.failures[0]["message"],
"Answer every question not marked (optional) to send."
);
runtime
.input("ask_1", "/answers/notes", json!("Leave .ssh alone."))
.unwrap();
let send = runtime.node("ask_1", "send").unwrap();
assert!(send.is_valid(), "{:?}", send.failures);
let action = runtime
.components("ask_1")
.unwrap()
.find(|component| component["id"] == "send")
.unwrap()["action"]
.clone();
let dispatch = runtime
.dispatch(&action, &Gesture::on(&send, "ask_1"))
.unwrap();
let action = dispatch.action.unwrap();
assert_eq!(action.name, "answers");
let accepted = form.accept(&values_from_context(&form, &action.context));
assert_eq!(
Value::Object(accepted.answers),
json!({
"scope": "Personal content only",
"goal": ["Reduce clutter", "Archive the photos"],
"keep": null,
"notes": "Leave .ssh alone.",
"budget": 4,
"archive": false,
"by": "2026-12-01"
})
);
assert_eq!(accepted.typed, ["goal"]);
assert!(accepted.unanswered.is_empty());
}
#[cfg(feature = "agent86ui")]
#[test]
fn other_chosen_with_nothing_typed_is_dropped() {
let form = Form::parse(&args(sample())).unwrap();
let values = values_from_context(
&form,
&args(json!({"answers": {"scope": ["__other__"]}, "other": {"scope": " "}})),
);
assert_eq!(values["scope"], json!([]));
assert_eq!(form.accept(&values).answers["scope"], Value::Null);
}
}