Skip to main content

ertangle_adapter/
question.rs

1//! Shared interactive user question normalization across diverse agents.
2//!
3//! Different agents emit interactive question requests under different tool names
4//! and JSON schemas:
5//! - OpenCode: `question` (`opencode.tool.question`)
6//! - Antigravity: `ask_question`
7//! - Claude Code: `AskUserQuestion` or MCP `ertangle_question`
8//! - Codex: `request_user_input` or `item/tool/requestUserInput`
9//!
10//! This module normalizes them into [`ertangle_core::UserQuestion`].
11
12use ertangle_core::{new_id, QuestionOption, UserQuestion};
13use serde_json::Value;
14
15/// Checks if a tool name refers to an interactive user question tool.
16pub fn is_question_tool(name: &str) -> bool {
17    let lower = name.to_ascii_lowercase();
18    let base = lower
19        .rsplit_once(':')
20        .map(|(_, b)| b)
21        .or_else(|| lower.rsplit_once("__").map(|(_, b)| b))
22        .unwrap_or(&lower);
23
24    matches!(
25        base,
26        "question"
27            | "ask_question"
28            | "askuserquestion"
29            | "request_user_input"
30            | "ertangle_question"
31            | "ertangle_ask_question"
32    )
33}
34
35/// Parses options from either an array of objects `[{"label": "...", "description": "..."}]`
36/// or an array of strings `["Option A", "Option B"]`.
37pub fn parse_options(val: &Value) -> Vec<QuestionOption> {
38    let Some(arr) = val.as_array() else {
39        return Vec::new();
40    };
41    arr.iter()
42        .filter_map(|item| {
43            if let Some(s) = item.as_str() {
44                Some(QuestionOption::plain(s))
45            } else if let Some(obj) = item.as_object() {
46                let label = obj
47                    .get("label")
48                    .or_else(|| obj.get("value"))
49                    .or_else(|| obj.get("name"))
50                    .and_then(|v| v.as_str())?;
51                let desc = obj.get("description").and_then(|v| v.as_str());
52                Some(QuestionOption::new(label, desc))
53            } else {
54                None
55            }
56        })
57        .collect()
58}
59
60/// Parses tool call JSON input into a list of normalized [`UserQuestion`]s.
61///
62/// If input is invalid JSON or unknown format, gracefully falls back to a text question
63/// rather than failing or panicking.
64pub fn parse_tool_call_questions(session: &str, name: &str, input_json: &str) -> Vec<UserQuestion> {
65    if !is_question_tool(name) {
66        return Vec::new();
67    }
68    let val: Value = match serde_json::from_str(input_json) {
69        Ok(v) => v,
70        Err(_) => {
71            // Malformed JSON fallback: degrade to text question.
72            return vec![UserQuestion {
73                id: new_id("qst"),
74                session: session.to_string(),
75                header: Some(name.to_string()),
76                question: input_json.trim().to_string(),
77                options: Vec::new(),
78                multi_select: false,
79                custom: true,
80                group: None,
81            }];
82        }
83    };
84
85    // Case 1: questions array `{"questions": [...]}`
86    if let Some(questions) = val.get("questions").and_then(|q| q.as_array()) {
87        let group = (questions.len() > 1).then(|| new_id("qgrp"));
88        let mut list = Vec::new();
89        for (i, item) in questions.iter().enumerate() {
90            let question = item
91                .get("question")
92                .or_else(|| item.get("prompt"))
93                .or_else(|| item.get("text"))
94                .and_then(|v| v.as_str())
95                .unwrap_or("")
96                .to_string();
97            let header = item
98                .get("header")
99                .or_else(|| item.get("title"))
100                .and_then(|v| v.as_str())
101                .map(str::to_string);
102            let options = item.get("options").map(parse_options).unwrap_or_default();
103            let multi_select = item
104                .get("multiple")
105                .or_else(|| item.get("multi_select"))
106                .or_else(|| item.get("multiSelect"))
107                .or_else(|| item.get("is_multi_select"))
108                .and_then(|v| v.as_bool())
109                .unwrap_or(false);
110            let custom = item.get("custom").and_then(|v| v.as_bool()).unwrap_or(true);
111
112            list.push(UserQuestion {
113                id: new_id("qst"),
114                session: session.to_string(),
115                header,
116                question: if question.is_empty() {
117                    if questions.len() > 1 {
118                        format!("Question {}", i + 1)
119                    } else {
120                        input_json.to_string()
121                    }
122                } else {
123                    question
124                },
125                options,
126                multi_select,
127                custom,
128                group: group.clone(),
129            });
130        }
131        if !list.is_empty() {
132            return list;
133        }
134    }
135
136    // Case 2: Flat single question `{"question": "...", "options": [...]}`
137    if let Some(question) = val.get("question").and_then(|v| v.as_str()) {
138        let header = val
139            .get("header")
140            .and_then(|v| v.as_str())
141            .map(str::to_string);
142        let options = val.get("options").map(parse_options).unwrap_or_default();
143        let multi_select = val
144            .get("multi_select")
145            .or_else(|| val.get("multiSelect"))
146            .or_else(|| val.get("multiple"))
147            .or_else(|| val.get("is_multi_select"))
148            .and_then(|v| v.as_bool())
149            .unwrap_or(false);
150        let custom = val.get("custom").and_then(|v| v.as_bool()).unwrap_or(true);
151
152        return vec![UserQuestion {
153            id: new_id("qst"),
154            session: session.to_string(),
155            header,
156            question: question.to_string(),
157            options,
158            multi_select,
159            custom,
160            group: None,
161        }];
162    }
163
164    // Degrade to text question
165    vec![UserQuestion {
166        id: new_id("qst"),
167        session: session.to_string(),
168        header: Some(name.to_string()),
169        question: input_json.to_string(),
170        options: Vec::new(),
171        multi_select: false,
172        custom: true,
173        group: None,
174    }]
175}
176
177/// Parses tool call JSON input into a normalized [`UserQuestion`].
178///
179/// If input is invalid JSON or unknown format, gracefully falls back to a text question
180/// rather than failing or panicking.
181pub fn parse_tool_call_question(
182    session: &str,
183    name: &str,
184    input_json: &str,
185) -> Option<UserQuestion> {
186    parse_tool_call_questions(session, name, input_json)
187        .into_iter()
188        .next()
189}
190
191/// Parses an ACP `elicitation/create` request into multiple [`UserQuestion`]s with property keys.
192pub fn parse_acp_elicitations(session: &str, params: &Value) -> Vec<(UserQuestion, String)> {
193    let message = params
194        .get("message")
195        .or_else(|| params.get("title"))
196        .and_then(|v| v.as_str())
197        .unwrap_or("")
198        .to_string();
199
200    let mut out = Vec::new();
201    let schema = params.get("requestedSchema").unwrap_or(params);
202    if let Some(props) = schema.get("properties").and_then(|p| p.as_object()) {
203        let group = (props.len() > 1).then(|| new_id("qgrp"));
204        for (k, v) in props {
205            let header = v.get("title").and_then(|t| t.as_str()).map(str::to_string);
206            let mut desc = v
207                .get("description")
208                .and_then(|d| d.as_str())
209                .unwrap_or("")
210                .to_string();
211            if desc.is_empty() {
212                desc = if !message.is_empty() {
213                    message.clone()
214                } else {
215                    header.clone().unwrap_or_else(|| k.clone())
216                };
217            }
218            let multi_select = v.get("type").and_then(|t| t.as_str()) == Some("array");
219            let mut options = Vec::new();
220            if let Some(enum_vals) = v.get("enum").and_then(|e| e.as_array()) {
221                for ev in enum_vals {
222                    if let Some(s) = ev.as_str() {
223                        options.push(QuestionOption::plain(s));
224                    }
225                }
226            } else if let Some(items) = v
227                .get("items")
228                .and_then(|i| i.get("enum"))
229                .and_then(|e| e.as_array())
230            {
231                for ev in items {
232                    if let Some(s) = ev.as_str() {
233                        options.push(QuestionOption::plain(s));
234                    }
235                }
236            } else if let Some(variants) = v
237                .get("oneOf")
238                .or_else(|| v.get("anyOf"))
239                .and_then(|value| value.as_array())
240            {
241                for variant in variants {
242                    let label = variant
243                        .get("title")
244                        .or_else(|| variant.get("const"))
245                        .and_then(|value| value.as_str());
246                    if let Some(label) = label {
247                        let description = variant
248                            .get("description")
249                            .and_then(|value| value.as_str())
250                            .map(str::to_string);
251                        // ACP forms may use an opaque const as the submitted value while the
252                        // title is the human-readable label (Antigravity uses "1"/"2").
253                        let const_value = variant.get("const").and_then(|v| v.as_str());
254                        options.push(match const_value {
255                            Some(value) if value != label => {
256                                QuestionOption::with_value(label, description.as_deref(), value)
257                            }
258                            _ => QuestionOption::new(label, description.as_deref()),
259                        });
260                    }
261                }
262            } else if let Some(opts) = v.get("options") {
263                options.extend(parse_options(opts));
264            }
265
266            out.push((
267                UserQuestion {
268                    id: new_id("qst"),
269                    session: session.to_string(),
270                    header,
271                    question: desc,
272                    options,
273                    multi_select,
274                    custom: true,
275                    group: group.clone(),
276                },
277                k.clone(),
278            ));
279        }
280    }
281
282    if let Some(fields) = params.get("fields").and_then(|f| f.as_array()) {
283        let group = (fields.len() > 1).then(|| new_id("qgrp"));
284        for f in fields {
285            let key = f
286                .get("key")
287                .and_then(|k| k.as_str())
288                .unwrap_or("field")
289                .to_string();
290            let header = f.get("title").and_then(|t| t.as_str()).map(str::to_string);
291            let mut desc = f
292                .get("description")
293                .and_then(|d| d.as_str())
294                .unwrap_or("")
295                .to_string();
296            if desc.is_empty() {
297                desc = if !message.is_empty() {
298                    message.clone()
299                } else {
300                    header.clone().unwrap_or_else(|| key.clone())
301                };
302            }
303            let multi_select = f.get("type").and_then(|t| t.as_str()) == Some("multiselect");
304            let options = f.get("options").map(parse_options).unwrap_or_default();
305
306            out.push((
307                UserQuestion {
308                    id: new_id("qst"),
309                    session: session.to_string(),
310                    header,
311                    question: desc,
312                    options,
313                    multi_select,
314                    custom: true,
315                    group: group.clone(),
316                },
317                key,
318            ));
319        }
320    }
321
322    if out.is_empty() {
323        let question_text = if !message.is_empty() {
324            message
325        } else {
326            "Interactive Question".to_string()
327        };
328        out.push((
329            UserQuestion {
330                id: new_id("qst"),
331                session: session.to_string(),
332                header: None,
333                question: question_text,
334                options: Vec::new(),
335                multi_select: false,
336                custom: true,
337                group: None,
338            },
339            "answer".to_string(),
340        ));
341    }
342
343    out
344}
345
346/// Parses an ACP `elicitation/create` request into [`UserQuestion`] and property keys.
347pub fn parse_acp_elicitation(session: &str, params: &Value) -> Option<(UserQuestion, Vec<String>)> {
348    let list = parse_acp_elicitations(session, params);
349    let keys: Vec<String> = list.iter().map(|(_, k)| k.clone()).collect();
350    list.into_iter().next().map(|(q, _)| (q, keys))
351}
352
353/// Parses Codex `item/tool/requestUserInput` parameters into multiple [`UserQuestion`]s with question keys.
354pub fn parse_codex_user_inputs(session: &str, params: &Value) -> Vec<(UserQuestion, String)> {
355    let Some(questions) = params.get("questions").and_then(|q| q.as_array()) else {
356        return Vec::new();
357    };
358
359    let group = (questions.len() > 1).then(|| new_id("qgrp"));
360    let mut out = Vec::new();
361    for (i, item) in questions.iter().enumerate() {
362        let q_key = item
363            .get("id")
364            .and_then(|v| v.as_str())
365            .map(str::to_string)
366            .unwrap_or_else(|| format!("q{i}"));
367        let header = item
368            .get("header")
369            .and_then(|v| v.as_str())
370            .map(str::to_string);
371        let question = item
372            .get("question")
373            .or_else(|| item.get("prompt"))
374            .and_then(|v| v.as_str())
375            .unwrap_or("")
376            .to_string();
377        let options = item.get("options").map(parse_options).unwrap_or_default();
378        let multi_select = item
379            .get("multiple")
380            .or_else(|| item.get("multi_select"))
381            .and_then(|v| v.as_bool())
382            .unwrap_or(false);
383
384        out.push((
385            UserQuestion {
386                id: new_id("qst"),
387                session: session.to_string(),
388                header,
389                question: if question.is_empty() {
390                    format!("Question {}", i + 1)
391                } else {
392                    question
393                },
394                options,
395                multi_select,
396                custom: true,
397                group: group.clone(),
398            },
399            q_key,
400        ));
401    }
402    out
403}
404
405/// Parses Codex `item/tool/requestUserInput` parameters into [`UserQuestion`] and question key.
406pub fn parse_codex_user_input(
407    session: &str,
408    params: &Value,
409) -> Option<(UserQuestion, Option<String>)> {
410    parse_codex_user_inputs(session, params)
411        .into_iter()
412        .next()
413        .map(|(q, k)| (q, Some(k)))
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419    use serde_json::json;
420
421    #[test]
422    fn question_tool_name_recognition() {
423        assert!(is_question_tool("question"));
424        assert!(is_question_tool("ask_question"));
425        assert!(is_question_tool("AskUserQuestion"));
426        assert!(is_question_tool("request_user_input"));
427        assert!(is_question_tool("mcp__ertangle__ertangle_question"));
428        assert!(is_question_tool("server:ask_question"));
429        assert!(!is_question_tool("Bash"));
430        assert!(!is_question_tool("Edit"));
431        assert!(!is_question_tool("read_file"));
432    }
433
434    #[test]
435    fn multi_question_requests_share_a_group() {
436        let json = r#"{
437            "questions": [
438                {"question": "Database?", "options": [{"label": "Postgres"}]},
439                {"question": "Framework?", "options": [{"label": "React"}]}
440            ]
441        }"#;
442        let list = parse_tool_call_questions("ses_1", "question", json);
443        assert_eq!(list.len(), 2);
444        let group = list[0].group.clone().expect("group");
445        assert_eq!(list[1].group.as_deref(), Some(group.as_str()));
446    }
447
448    #[test]
449    fn parses_acp_one_of_options() {
450        let params = json!({
451            "message": "Questions",
452            "requestedSchema": {
453                "type": "object",
454                "properties": {
455                    "q0": {
456                        "type": "string",
457                        "title": "UI framework",
458                        "description": "Which UI framework?",
459                        "oneOf": [
460                            {"const": "React", "title": "React", "description": "Mature"},
461                            {"const": "Vue", "title": "Vue", "description": "Simple"}
462                        ]
463                    }
464                }
465            }
466        });
467        let list = parse_acp_elicitations("ses_1", &params);
468        assert_eq!(list.len(), 1);
469        assert_eq!(list[0].0.question, "Which UI framework?");
470        let labels: Vec<_> = list[0].0.options.iter().map(|o| o.label.as_str()).collect();
471        assert_eq!(labels, vec!["React", "Vue"]);
472        assert_eq!(list[0].0.options[0].description.as_deref(), Some("Mature"));
473    }
474
475    #[test]
476    fn parses_acp_one_of_const_values_as_submission_values() {
477        let params = json!({
478            "requestedSchema": {
479                "type": "object",
480                "properties": {
481                    "q1": {
482                        "type": "string",
483                        "title": "Which database should we use?",
484                        "oneOf": [
485                            {"const": "1", "title": "Postgres"},
486                            {"const": "2", "title": "Redis"}
487                        ]
488                    }
489                }
490            }
491        });
492        let list = parse_acp_elicitations("ses_1", &params);
493        assert_eq!(list.len(), 1);
494        assert_eq!(list[0].0.options[0].label, "Postgres");
495        assert_eq!(list[0].0.options[0].value.as_deref(), Some("1"));
496        assert_eq!(list[0].0.options[1].value.as_deref(), Some("2"));
497    }
498
499    #[test]
500    fn parse_opencode_question_format() {
501        let json = r#"{
502            "questions": [{
503                "question": "Which framework would you like to use?",
504                "header": "Framework",
505                "options": [
506                    {"label": "React", "description": "Popular UI library"},
507                    {"label": "Vue", "description": "Progressive framework"}
508                ],
509                "multiple": false,
510                "custom": true
511            }]
512        }"#;
513        let q = parse_tool_call_question("ses_1", "question", json).expect("parse opencode");
514        assert_eq!(q.header.as_deref(), Some("Framework"));
515        assert_eq!(q.question, "Which framework would you like to use?");
516        assert_eq!(q.options.len(), 2);
517        assert_eq!(q.options[0].label, "React");
518        assert_eq!(
519            q.options[0].description.as_deref(),
520            Some("Popular UI library")
521        );
522        assert!(!q.multi_select);
523        assert!(q.custom);
524    }
525
526    #[test]
527    fn parse_multiple_tool_call_questions() {
528        let json = r#"{
529            "questions": [
530                {
531                    "question": "Choose database",
532                    "header": "Database",
533                    "options": ["PostgreSQL", "SQLite"]
534                },
535                {
536                    "question": "Choose cache",
537                    "header": "Cache",
538                    "options": ["Redis", "Memcached"],
539                    "multi_select": true
540                }
541            ]
542        }"#;
543        let list = parse_tool_call_questions("ses_1", "AskUserQuestion", json);
544        assert_eq!(list.len(), 2);
545        assert_eq!(list[0].header.as_deref(), Some("Database"));
546        assert_eq!(list[0].question, "Choose database");
547        assert_eq!(list[0].options.len(), 2);
548        assert!(!list[0].multi_select);
549        assert_eq!(list[1].header.as_deref(), Some("Cache"));
550        assert_eq!(list[1].question, "Choose cache");
551        assert!(list[1].multi_select);
552    }
553
554    #[test]
555    fn parse_claude_camel_case_multi_select() {
556        let json = r#"{
557            "questions": [{
558                "question": "Choose features",
559                "header": "Features",
560                "multiSelect": true,
561                "options": ["Auth", "Search"]
562            }]
563        }"#;
564        let q = parse_tool_call_question("ses_1", "AskUserQuestion", json).expect("parse claude");
565        assert!(q.multi_select);
566        assert_eq!(q.options.len(), 2);
567    }
568
569    #[test]
570    fn parse_antigravity_question_format() {
571        let json = r#"{
572            "questions": [{
573                "question": "Select target architectures",
574                "options": ["x86_64", "aarch64", "wasm32"],
575                "is_multi_select": true
576            }]
577        }"#;
578        let q = parse_tool_call_question("ses_2", "ask_question", json).expect("parse agy");
579        assert_eq!(q.question, "Select target architectures");
580        assert_eq!(q.options.len(), 3);
581        assert_eq!(q.options[1].label, "aarch64");
582        assert!(q.multi_select);
583    }
584
585    #[test]
586    fn parse_codex_app_server_format() {
587        let params = serde_json::json!({
588            "threadId": "th_1",
589            "questions": [{
590                "id": "db_choice",
591                "header": "Database Selection",
592                "question": "Select your primary database",
593                "options": [
594                    {"label": "Postgres", "description": "Relational"},
595                    {"label": "Redis", "description": "Key-value"}
596                ]
597            }]
598        });
599        let (q, key) = parse_codex_user_input("ses_3", &params).expect("parse codex");
600        assert_eq!(key.as_deref(), Some("db_choice"));
601        assert_eq!(q.header.as_deref(), Some("Database Selection"));
602        assert_eq!(q.options[0].label, "Postgres");
603    }
604
605    #[test]
606    fn parse_multiple_codex_questions() {
607        let params = serde_json::json!({
608            "threadId": "th_1",
609            "questions": [
610                {
611                    "id": "q1",
612                    "question": "First question?",
613                    "options": ["Yes", "No"]
614                },
615                {
616                    "id": "q2",
617                    "question": "Second question?",
618                    "options": ["Option A", "Option B"]
619                }
620            ]
621        });
622        let list = parse_codex_user_inputs("ses_3", &params);
623        assert_eq!(list.len(), 2);
624        assert_eq!(list[0].1, "q1");
625        assert_eq!(list[0].0.question, "First question?");
626        assert_eq!(list[1].1, "q2");
627        assert_eq!(list[1].0.question, "Second question?");
628    }
629
630    #[test]
631    fn parse_acp_elicitation_format() {
632        let params = serde_json::json!({
633            "mode": "form",
634            "message": "Deployment Options",
635            "requestedSchema": {
636                "type": "object",
637                "properties": {
638                    "env": {
639                        "type": "string",
640                        "title": "Environment",
641                        "description": "Target environment",
642                        "enum": ["production", "staging", "dev"]
643                    }
644                }
645            }
646        });
647        let (q, keys) = parse_acp_elicitation("ses_4", &params).expect("parse acp");
648        assert_eq!(keys, vec!["env"]);
649        assert_eq!(q.header.as_deref(), Some("Environment"));
650        assert_eq!(q.options.len(), 3);
651        assert_eq!(q.options[0].label, "production");
652    }
653
654    #[test]
655    fn parse_multiple_acp_elicitations() {
656        let params = serde_json::json!({
657            "mode": "form",
658            "message": "Project Config",
659            "requestedSchema": {
660                "type": "object",
661                "properties": {
662                    "lang": {
663                        "type": "string",
664                        "title": "Language",
665                        "enum": ["Rust", "TypeScript"]
666                    },
667                    "framework": {
668                        "type": "string",
669                        "title": "Framework",
670                        "enum": ["Actix", "Axum"]
671                    }
672                }
673            }
674        });
675        let list = parse_acp_elicitations("ses_4", &params);
676        assert_eq!(list.len(), 2);
677        let keys: Vec<String> = list.iter().map(|(_, k)| k.clone()).collect();
678        assert!(keys.contains(&"lang".to_string()));
679        assert!(keys.contains(&"framework".to_string()));
680    }
681
682    #[test]
683    fn malformed_input_graceful_fallback() {
684        let q = parse_tool_call_question("ses_5", "question", "not a valid json { broken")
685            .expect("fallback");
686        assert_eq!(q.question, "not a valid json { broken");
687        assert!(q.options.is_empty());
688        assert!(q.custom);
689    }
690}