Skip to main content

mermaid_cli/providers/tool/
ask_user_question.rs

1//! The `ask_user_question` tool — the model's structured path to ask the user
2//! a decision it genuinely cannot make on its own.
3//!
4//! The model supplies 1–4 questions, each with a short header chip and a set of
5//! labeled options (single- or multi-select). The tool parks on the
6//! `QuestionBroker` (interactive runs) while the TUI renders a selectable modal,
7//! then formats the user's answers back into the tool result. Headless runs have
8//! no human to ask, so the tool returns a proceed-with-best-judgment result
9//! rather than blocking. Asking mutates nothing, so the tool is ungated (it
10//! never touches the policy gate) and runs in every safety mode.
11
12use std::collections::HashMap;
13use std::path::{Path, PathBuf};
14use std::time::Instant;
15
16use async_trait::async_trait;
17
18use mermaid_model::question::{
19    OptionPreview, Question, QuestionAnswer, QuestionKind, QuestionOption, QuestionResolution,
20    TextValidate,
21};
22
23use mermaid_domain::{ToolDefinition, ToolMetadata, ToolOutcome, ToolRunMetadata};
24
25use super::super::ctx::ExecContext;
26use super::ToolExecutor;
27
28pub struct AskUserQuestionTool;
29
30/// Format the resolved answers into the text the model sees, keyed by question
31/// so a batched call never scrambles which answer belongs to which question.
32fn format_answers(answers: &[QuestionAnswer]) -> String {
33    let mut out = String::from("The user answered your question(s):\n");
34    for a in answers {
35        let value = if a.selected.is_empty() {
36            "(no selection)".to_string()
37        } else {
38            a.selected.join(", ")
39        };
40        out.push_str(&format!("- {} -> {}\n", a.question, value));
41        if let Some(note) = &a.note {
42            out.push_str(&format!("  (note: {note})\n"));
43        }
44    }
45    out
46}
47
48/// Ride the structured answers on the outcome metadata so the transcript can
49/// render each question → answer pair (`ToolMetadata::Questions`) instead of
50/// a bare duration line.
51fn answers_metadata(answers: Vec<QuestionAnswer>, remembered: bool) -> ToolRunMetadata {
52    ToolRunMetadata {
53        detail: ToolMetadata::Questions {
54            answers,
55            remembered,
56        },
57        ..ToolRunMetadata::default()
58    }
59}
60
61/// One-line UI summary of the answers.
62fn summarize_answers(answers: &[QuestionAnswer]) -> String {
63    match answers {
64        [] => "no questions".to_string(),
65        [one] => {
66            if one.selected.is_empty() {
67                "no selection".to_string()
68            } else {
69                one.selected.join(", ")
70            }
71        },
72        many => format!("{} questions answered", many.len()),
73    }
74}
75
76/// Parse the model's flat option JSON into a `QuestionOption`.
77fn parse_option(v: &serde_json::Value) -> Option<QuestionOption> {
78    let label = v.get("label").and_then(|x| x.as_str())?.to_string();
79    let description = v
80        .get("description")
81        .and_then(|x| x.as_str())
82        .map(str::to_string);
83    let preview = v.get("preview").and_then(parse_preview);
84    // Honor the Claude-Code convention: a trailing "(Recommended)" flags it.
85    let recommended = label.to_lowercase().contains("(recommended)");
86    Some(QuestionOption {
87        label,
88        description,
89        recommended,
90        preview,
91    })
92}
93
94fn parse_preview(v: &serde_json::Value) -> Option<OptionPreview> {
95    let content = v.get("content").and_then(|x| x.as_str())?.to_string();
96    let language = v
97        .get("language")
98        .and_then(|x| x.as_str())
99        .map(str::to_string);
100    let diff = v.get("diff").and_then(|x| x.as_bool()).unwrap_or(false);
101    Some(OptionPreview {
102        content,
103        language,
104        diff,
105    })
106}
107
108/// Parse a `text` question's `validate`: the string "number"/"any", any other
109/// string as a regex pattern, or `{ "regex": "..." }`.
110fn parse_validate(v: Option<&serde_json::Value>) -> TextValidate {
111    match v {
112        None => TextValidate::Any,
113        Some(val) => {
114            if let Some(s) = val.as_str() {
115                match s {
116                    "number" => TextValidate::Number,
117                    "any" | "" => TextValidate::Any,
118                    pat => TextValidate::Regex(pat.to_string()),
119                }
120            } else if let Some(pat) = val.get("regex").and_then(|x| x.as_str()) {
121                TextValidate::Regex(pat.to_string())
122            } else {
123                TextValidate::Any
124            }
125        },
126    }
127}
128
129/// Parse one flat question object into a `Question`.
130fn parse_question(v: &serde_json::Value) -> Result<Question, String> {
131    let header = v
132        .get("header")
133        .and_then(|x| x.as_str())
134        .unwrap_or("")
135        .to_string();
136    let question = v
137        .get("question")
138        .and_then(|x| x.as_str())
139        .ok_or("each question needs a `question` string")?
140        .to_string();
141    let kind = match v.get("kind").and_then(|x| x.as_str()).unwrap_or("select") {
142        "select" => QuestionKind::Select,
143        "multiSelect" | "multiselect" => QuestionKind::MultiSelect,
144        "rank" => QuestionKind::Rank,
145        "text" => QuestionKind::Text {
146            validate: parse_validate(v.get("validate")),
147        },
148        "number" => QuestionKind::Number {
149            min: v.get("min").and_then(|x| x.as_f64()),
150            max: v.get("max").and_then(|x| x.as_f64()),
151            step: v.get("step").and_then(|x| x.as_f64()),
152            slider: v.get("slider").and_then(|x| x.as_bool()).unwrap_or(false),
153        },
154        "date" => QuestionKind::Date,
155        "path" => QuestionKind::Path {
156            must_exist: v
157                .get("mustExist")
158                .and_then(|x| x.as_bool())
159                .unwrap_or(false),
160        },
161        other => return Err(format!("unknown question kind: {other}")),
162    };
163    let options = v
164        .get("options")
165        .and_then(|x| x.as_array())
166        .map(|arr| arr.iter().filter_map(parse_option).collect::<Vec<_>>())
167        .unwrap_or_default();
168    let memory_key = v
169        .get("memoryKey")
170        .and_then(|x| x.as_str())
171        .filter(|s| !s.is_empty())
172        .map(str::to_string);
173    let q = Question {
174        header,
175        question,
176        kind,
177        options,
178        memory_key,
179    };
180    if q.is_choice() && q.options.is_empty() {
181        return Err(format!(
182            "question \"{}\" is a choice kind but has no options",
183            q.question
184        ));
185    }
186    Ok(q)
187}
188
189/// A remembered answer, persisted across sessions keyed by a question's
190/// `memory_key`.
191#[derive(serde::Serialize, serde::Deserialize, Clone)]
192struct StoredAnswer {
193    selected: Vec<String>,
194    #[serde(default)]
195    note: Option<String>,
196}
197
198fn prefs_path() -> Option<PathBuf> {
199    crate::app::get_config_dir()
200        .ok()
201        .map(|d| d.join("question_prefs.json"))
202}
203
204fn load_prefs_at(path: &Path) -> HashMap<String, StoredAnswer> {
205    std::fs::read_to_string(path)
206        .ok()
207        .and_then(|s| serde_json::from_str(&s).ok())
208        .unwrap_or_default()
209}
210
211fn save_prefs_at(path: &Path, map: &HashMap<String, StoredAnswer>) {
212    let json = match serde_json::to_string_pretty(map) {
213        Ok(json) => json,
214        Err(err) => {
215            tracing::warn!(error = %err, "ask_user_question: failed to serialize answer prefs");
216            return;
217        },
218    };
219    // Atomic write so a crash mid-save can't truncate the prefs file, and log on
220    // failure instead of silently losing the user's "remember this answer" choice.
221    if let Err(err) = mermaid_runtime::write_atomic(path, json.as_bytes()) {
222        tracing::warn!(
223            error = %err,
224            path = %path.display(),
225            "ask_user_question: failed to persist answer prefs"
226        );
227    }
228}
229
230fn load_prefs() -> HashMap<String, StoredAnswer> {
231    prefs_path().map(|p| load_prefs_at(&p)).unwrap_or_default()
232}
233
234fn save_prefs(map: &HashMap<String, StoredAnswer>) {
235    if let Some(p) = prefs_path() {
236        save_prefs_at(&p, map);
237    }
238}
239
240/// The remembered answer for every question, or `None` if any one of them is
241/// still unsettled.
242///
243/// One pass, rather than an `all(...)` check followed by a lookup that trusts
244/// it: the lookup that decides whether a question is already answered is the
245/// same lookup that builds its answer, so the two cannot disagree and no arm
246/// can panic. All-or-nothing is the point — a partially remembered set still
247/// has to be asked.
248fn remembered_answers(
249    questions: &[Question],
250    prefs: &HashMap<String, StoredAnswer>,
251) -> Option<Vec<QuestionAnswer>> {
252    questions
253        .iter()
254        .map(|q| {
255            let stored = prefs.get(q.memory_key.as_ref()?)?;
256            Some(QuestionAnswer {
257                header: q.header.clone(),
258                question: q.question.clone(),
259                selected: stored.selected.clone(),
260                note: stored.note.clone(),
261            })
262        })
263        .collect()
264}
265
266#[async_trait]
267impl ToolExecutor for AskUserQuestionTool {
268    fn name(&self) -> &'static str {
269        "ask_user_question"
270    }
271
272    fn schema(&self) -> ToolDefinition {
273        ToolDefinition {
274            name: "ask_user_question".to_string(),
275            description: "Ask the user one or more questions. The terminal renders an interactive selectable prompt and the user's answer comes back as this tool's result. The user can always type a custom \"Other\" answer. \
276                Up to 4 questions per call. Each question's `kind`: `select` (pick one), `multiSelect` (pick any), `rank` (reorder options), or an input kind that collects a typed value — `text` (optional `validate`), `number` (`min`/`max`/`step`/`slider`), `date`, or `path`. Choice kinds need `options`; an option whose label ends with \"(Recommended)\" is shown as the recommendation. \
277                An option can carry a preview (a `content` string plus an optional `diff` flag), shown side-by-side when that option is focused: an ASCII mockup, code, config, or a unified diff. \
278                `memoryKey` on a question lets the user remember the answer across sessions, so it is not asked again."
279                .to_string(),
280            input_schema: serde_json::json!({
281                "type": "object",
282                "properties": {
283                    "questions": {
284                        "type": "array",
285                        "description": "1-4 questions to ask, shown together.",
286                        "items": {
287                            "type": "object",
288                            "properties": {
289                                "header": {
290                                    "type": "string",
291                                    "description": "Very short label (<=12 chars) shown as a chip, e.g. \"Database\"."
292                                },
293                                "question": {
294                                    "type": "string",
295                                    "description": "The full question text. Clear, specific, ends with a question mark."
296                                },
297                                "kind": {
298                                    "type": "string",
299                                    "enum": ["select", "multiSelect", "rank", "text", "number", "date", "path"],
300                                    "description": "How the question is answered. Choice kinds use `options`: `select` (pick one), `multiSelect` (pick any), `rank` (reorder). Input kinds collect a typed value: `text` (optional `validate`), `number` (optional `min`/`max`/`step`/`slider`), `date` (YYYY-MM-DD), `path`."
301                                },
302                                "validate": {
303                                    "type": "string",
304                                    "description": "For `text`: \"number\" to require a number, or a regex pattern the answer must match."
305                                },
306                                "min": { "type": "number", "description": "For `number`: minimum value." },
307                                "max": { "type": "number", "description": "For `number`: maximum value." },
308                                "step": { "type": "number", "description": "For `number`: increment for Up/Down." },
309                                "slider": { "type": "boolean", "description": "For `number`: show a slider bar (needs `min` and `max`)." },
310                                "mustExist": { "type": "boolean", "description": "For `path`: hint that the path should already exist." },
311                                "memoryKey": { "type": "string", "description": "Stable key to remember this answer across sessions. If the user opts in, a later question with the same key auto-answers without prompting. Use for settled preferences (e.g. package manager, code style)." },
312                                "options": {
313                                    "type": "array",
314                                    "description": "Options for choice kinds (select/multiSelect/rank); omit for input kinds. Two or more; long lists scroll.",
315                                    "items": {
316                                        "type": "object",
317                                        "properties": {
318                                            "label": {
319                                                "type": "string",
320                                                "description": "Concise choice text. End with \"(Recommended)\" to flag your suggestion."
321                                            },
322                                            "description": {
323                                                "type": "string",
324                                                "description": "One line explaining the option or its trade-off."
325                                            },
326                                            "preview": {
327                                                "type": "object",
328                                                "description": "Optional side-by-side preview shown when this option is focused.",
329                                                "properties": {
330                                                    "content": { "type": "string", "description": "The preview body, shown as monospace lines." },
331                                                    "language": { "type": "string", "description": "Language hint for the content (e.g. \"rust\", \"yaml\")." },
332                                                    "diff": { "type": "boolean", "description": "Render content as a unified diff (+ lines green, - lines red). Best for showing the change an option would produce." }
333                                                },
334                                                "required": ["content"]
335                                            }
336                                        },
337                                        "required": ["label", "description"]
338                                    }
339                                }
340                            },
341                            "required": ["question", "header", "kind"]
342                        }
343                    }
344                },
345                "required": ["questions"]
346            }),
347        }
348    }
349
350    async fn execute(&self, args: serde_json::Value, ctx: ExecContext) -> ToolOutcome {
351        let start = Instant::now();
352        let secs = || start.elapsed().as_secs_f64();
353
354        let Some(questions_val) = args.get("questions").and_then(|v| v.as_array()) else {
355            return ToolOutcome::error(
356                "ask_user_question requires a `questions` array",
357                Some(secs()),
358            );
359        };
360        if questions_val.is_empty() {
361            return ToolOutcome::error(
362                "`questions` must contain at least one question",
363                Some(secs()),
364            );
365        }
366        let mut questions = Vec::with_capacity(questions_val.len());
367        for qv in questions_val {
368            match parse_question(qv) {
369                Ok(q) => questions.push(q),
370                Err(e) => {
371                    return ToolOutcome::error(format!("invalid question: {e}"), Some(secs()));
372                },
373            }
374        }
375
376        // Cross-session preferences: if every question already has a remembered
377        // answer, return them without prompting (works interactively and
378        // headlessly) so settled decisions aren't re-asked every session.
379        let prefs = load_prefs();
380        if let Some(answers) = remembered_answers(&questions, &prefs) {
381            return ToolOutcome::success(
382                format_answers(&answers),
383                format!("{} (remembered)", summarize_answers(&answers)),
384                secs(),
385            )
386            .with_metadata(answers_metadata(answers, true));
387        }
388
389        let Some(broker) = ctx.questions.as_ref() else {
390            // Headless / no interactive terminal: nobody to ask. Proceed rather
391            // than block an automated run.
392            return ToolOutcome::success(
393                "No interactive terminal is available, so the user could not be asked. \
394                 Proceed using your best judgment and state the assumption you made.",
395                "no interactive terminal; proceeding without answers",
396                secs(),
397            );
398        };
399
400        match broker
401            .request(&ctx.token, ctx.turn, ctx.call_id, questions.clone())
402            .await
403        {
404            QuestionResolution::Answered { answers, remember } => {
405                if remember {
406                    let mut prefs = prefs;
407                    for (q, a) in questions.iter().zip(&answers) {
408                        if let Some(key) = &q.memory_key
409                            && !a.selected.is_empty()
410                        {
411                            prefs.insert(
412                                key.clone(),
413                                StoredAnswer {
414                                    selected: a.selected.clone(),
415                                    note: a.note.clone(),
416                                },
417                            );
418                        }
419                    }
420                    save_prefs(&prefs);
421                }
422                ToolOutcome::success(
423                    format_answers(&answers),
424                    summarize_answers(&answers),
425                    secs(),
426                )
427                .with_metadata(answers_metadata(answers, false))
428            },
429            QuestionResolution::Dismissed => ToolOutcome::success(
430                "The user dismissed the question(s) without answering. Do not re-ask unless you \
431                 still need the information; otherwise proceed with your best judgment.",
432                "dismissed without answering",
433                secs(),
434            ),
435            QuestionResolution::Reformulate => ToolOutcome::success(
436                "The user chose to discuss these questions rather than answer them as posed. \
437                 Do not re-issue the same questions; engage with what they say next and \
438                 reformulate your approach based on their input.",
439                "user chose to chat about this instead",
440                secs(),
441            ),
442        }
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449    use mermaid_domain::QuestionAnswer;
450
451    #[test]
452    fn formats_keyed_answers() {
453        let answers = vec![
454            QuestionAnswer {
455                header: "Database".to_string(),
456                question: "Which database?".to_string(),
457                selected: vec!["PostgreSQL".to_string()],
458                note: None,
459            },
460            QuestionAnswer {
461                header: "Features".to_string(),
462                question: "Which features?".to_string(),
463                selected: vec!["Auth".to_string(), "Admin".to_string()],
464                note: Some("also add profiles".to_string()),
465            },
466        ];
467        let out = format_answers(&answers);
468        assert!(out.contains("Which database? -> PostgreSQL"));
469        assert!(out.contains("Which features? -> Auth, Admin"));
470        assert!(out.contains("(note: also add profiles)"));
471    }
472
473    #[test]
474    fn empty_selection_reads_as_no_selection() {
475        let answers = vec![QuestionAnswer {
476            header: "Layout".to_string(),
477            question: "Which layout?".to_string(),
478            selected: vec![],
479            note: None,
480        }];
481        assert!(format_answers(&answers).contains("-> (no selection)"));
482        assert_eq!(summarize_answers(&answers), "no selection");
483    }
484
485    #[tokio::test]
486    async fn headless_proceeds_without_broker() {
487        use mermaid_domain::{ToolCallId, TurnId};
488        let (ctx, _rx) = crate::providers::ctx::test_exec_context(
489            TurnId(1),
490            ToolCallId(1),
491            std::env::temp_dir(),
492        );
493        // test_exec_context leaves `questions: None` (headless).
494        let out = AskUserQuestionTool
495            .execute(
496                serde_json::json!({
497                    "questions": [{
498                        "header": "DB",
499                        "question": "Which database?",
500                        "multiSelect": false,
501                        "options": [
502                            {"label": "PostgreSQL", "description": "relational"},
503                            {"label": "SQLite", "description": "embedded"}
504                        ]
505                    }]
506                }),
507                ctx,
508            )
509            .await;
510        assert_eq!(out.status, mermaid_domain::ToolStatus::Success);
511        assert!(out.model_content.contains("Proceed"));
512    }
513
514    #[test]
515    fn prefs_round_trip() {
516        let dir = std::env::temp_dir().join(format!("mermaid_qprefs_{}", std::process::id()));
517        std::fs::create_dir_all(&dir).unwrap();
518        let path = dir.join("prefs.json");
519        let mut map = HashMap::new();
520        map.insert(
521            "pkg_mgr".to_string(),
522            StoredAnswer {
523                selected: vec!["pnpm".to_string()],
524                note: None,
525            },
526        );
527        save_prefs_at(&path, &map);
528        let loaded = load_prefs_at(&path);
529        assert_eq!(
530            loaded.get("pkg_mgr").map(|s| s.selected.clone()),
531            Some(vec!["pnpm".to_string()])
532        );
533        let _ = std::fs::remove_dir_all(&dir);
534    }
535
536    fn keyed(header: &str, memory_key: Option<&str>) -> Question {
537        Question {
538            header: header.to_string(),
539            question: format!("Which {header}?"),
540            kind: QuestionKind::Select,
541            options: Vec::new(),
542            memory_key: memory_key.map(str::to_string),
543        }
544    }
545
546    fn stored(selected: &str) -> StoredAnswer {
547        StoredAnswer {
548            selected: vec![selected.to_string()],
549            note: None,
550        }
551    }
552
553    #[test]
554    fn every_question_remembered_answers_without_asking() {
555        let questions = vec![keyed("Database", Some("db")), keyed("Runtime", Some("rt"))];
556        let prefs = HashMap::from([
557            ("db".to_string(), stored("PostgreSQL")),
558            ("rt".to_string(), stored("tokio")),
559        ]);
560
561        let answers = remembered_answers(&questions, &prefs).expect("both keys are remembered");
562
563        assert_eq!(answers.len(), 2);
564        assert_eq!(answers[0].header, "Database");
565        assert_eq!(answers[0].selected, vec!["PostgreSQL".to_string()]);
566        assert_eq!(answers[1].selected, vec!["tokio".to_string()]);
567    }
568
569    #[test]
570    fn one_unremembered_question_asks_the_whole_set() {
571        let questions = vec![keyed("Database", Some("db")), keyed("Runtime", Some("rt"))];
572        let prefs = HashMap::from([("db".to_string(), stored("PostgreSQL"))]);
573
574        // All-or-nothing: a partially settled set is still worth asking about,
575        // and answering only half of it would be worse than asking twice.
576        assert!(remembered_answers(&questions, &prefs).is_none());
577    }
578
579    /// The case that used to be load-bearing for a distant `unwrap()`: a
580    /// question carrying no `memory_key` at all. The old code checked for it
581    /// three lines above the indexing that assumed the check had run.
582    #[test]
583    fn a_question_without_a_memory_key_asks_rather_than_panicking() {
584        let questions = vec![keyed("Database", Some("db")), keyed("Runtime", None)];
585        let prefs = HashMap::from([("db".to_string(), stored("PostgreSQL"))]);
586
587        assert!(remembered_answers(&questions, &prefs).is_none());
588    }
589
590    #[test]
591    fn an_empty_question_set_is_vacuously_remembered() {
592        // Unreachable through the tool (an empty `questions` array is rejected
593        // earlier), but pinned so the fold's identity cannot drift silently.
594        assert_eq!(
595            remembered_answers(&[], &HashMap::new()).map(|a| a.len()),
596            Some(0)
597        );
598    }
599}