1use ertangle_core::{new_id, QuestionOption, UserQuestion};
13use serde_json::Value;
14
15pub 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
35pub 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
60pub 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 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 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 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 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
177pub 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
191pub 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 .or_else(|| {
240 v.get("items")
241 .and_then(|i| i.get("oneOf").or_else(|| i.get("anyOf")))
242 })
243 .and_then(|value| value.as_array())
244 {
245 for variant in variants {
246 let label = variant
247 .get("title")
248 .or_else(|| variant.get("const"))
249 .and_then(|value| value.as_str());
250 if let Some(label) = label {
251 let description = variant
252 .get("description")
253 .and_then(|value| value.as_str())
254 .map(str::to_string);
255 let const_value = variant.get("const").and_then(|v| v.as_str());
258 options.push(match const_value {
259 Some(value) if value != label => {
260 QuestionOption::with_value(label, description.as_deref(), value)
261 }
262 _ => QuestionOption::new(label, description.as_deref()),
263 });
264 }
265 }
266 } else if let Some(opts) = v.get("options") {
267 options.extend(parse_options(opts));
268 }
269
270 out.push((
271 UserQuestion {
272 id: new_id("qst"),
273 session: session.to_string(),
274 header,
275 question: desc,
276 options,
277 multi_select,
278 custom: true,
279 group: group.clone(),
280 },
281 k.clone(),
282 ));
283 }
284 }
285
286 if let Some(fields) = params.get("fields").and_then(|f| f.as_array()) {
287 let group = (fields.len() > 1).then(|| new_id("qgrp"));
288 for f in fields {
289 let key = f
290 .get("key")
291 .and_then(|k| k.as_str())
292 .unwrap_or("field")
293 .to_string();
294 let header = f.get("title").and_then(|t| t.as_str()).map(str::to_string);
295 let mut desc = f
296 .get("description")
297 .and_then(|d| d.as_str())
298 .unwrap_or("")
299 .to_string();
300 if desc.is_empty() {
301 desc = if !message.is_empty() {
302 message.clone()
303 } else {
304 header.clone().unwrap_or_else(|| key.clone())
305 };
306 }
307 let multi_select = f.get("type").and_then(|t| t.as_str()) == Some("multiselect");
308 let options = f.get("options").map(parse_options).unwrap_or_default();
309
310 out.push((
311 UserQuestion {
312 id: new_id("qst"),
313 session: session.to_string(),
314 header,
315 question: desc,
316 options,
317 multi_select,
318 custom: true,
319 group: group.clone(),
320 },
321 key,
322 ));
323 }
324 }
325
326 if out.is_empty() {
327 let question_text = if !message.is_empty() {
328 message
329 } else {
330 "Interactive Question".to_string()
331 };
332 out.push((
333 UserQuestion {
334 id: new_id("qst"),
335 session: session.to_string(),
336 header: None,
337 question: question_text,
338 options: Vec::new(),
339 multi_select: false,
340 custom: true,
341 group: None,
342 },
343 "answer".to_string(),
344 ));
345 }
346
347 out
348}
349
350pub fn parse_acp_elicitation(session: &str, params: &Value) -> Option<(UserQuestion, Vec<String>)> {
352 let list = parse_acp_elicitations(session, params);
353 let keys: Vec<String> = list.iter().map(|(_, k)| k.clone()).collect();
354 list.into_iter().next().map(|(q, _)| (q, keys))
355}
356
357pub fn parse_codex_user_inputs(session: &str, params: &Value) -> Vec<(UserQuestion, String)> {
359 let Some(questions) = params.get("questions").and_then(|q| q.as_array()) else {
360 return Vec::new();
361 };
362
363 let group = (questions.len() > 1).then(|| new_id("qgrp"));
364 let mut out = Vec::new();
365 for (i, item) in questions.iter().enumerate() {
366 let q_key = item
367 .get("id")
368 .and_then(|v| v.as_str())
369 .map(str::to_string)
370 .unwrap_or_else(|| format!("q{i}"));
371 let header = item
372 .get("header")
373 .and_then(|v| v.as_str())
374 .map(str::to_string);
375 let question = item
376 .get("question")
377 .or_else(|| item.get("prompt"))
378 .and_then(|v| v.as_str())
379 .unwrap_or("")
380 .to_string();
381 let options = item.get("options").map(parse_options).unwrap_or_default();
382 let multi_select = item
383 .get("multiple")
384 .or_else(|| item.get("multi_select"))
385 .and_then(|v| v.as_bool())
386 .unwrap_or(false);
387
388 out.push((
389 UserQuestion {
390 id: new_id("qst"),
391 session: session.to_string(),
392 header,
393 question: if question.is_empty() {
394 format!("Question {}", i + 1)
395 } else {
396 question
397 },
398 options,
399 multi_select,
400 custom: true,
401 group: group.clone(),
402 },
403 q_key,
404 ));
405 }
406 out
407}
408
409pub fn parse_codex_user_input(
411 session: &str,
412 params: &Value,
413) -> Option<(UserQuestion, Option<String>)> {
414 parse_codex_user_inputs(session, params)
415 .into_iter()
416 .next()
417 .map(|(q, k)| (q, Some(k)))
418}
419
420#[cfg(test)]
421mod tests {
422 use super::*;
423 use serde_json::json;
424
425 #[test]
426 fn question_tool_name_recognition() {
427 assert!(is_question_tool("question"));
428 assert!(is_question_tool("ask_question"));
429 assert!(is_question_tool("AskUserQuestion"));
430 assert!(is_question_tool("request_user_input"));
431 assert!(is_question_tool("mcp__ertangle__ertangle_question"));
432 assert!(is_question_tool("server:ask_question"));
433 assert!(!is_question_tool("Bash"));
434 assert!(!is_question_tool("Edit"));
435 assert!(!is_question_tool("read_file"));
436 }
437
438 #[test]
439 fn multi_question_requests_share_a_group() {
440 let json = r#"{
441 "questions": [
442 {"question": "Database?", "options": [{"label": "Postgres"}]},
443 {"question": "Framework?", "options": [{"label": "React"}]}
444 ]
445 }"#;
446 let list = parse_tool_call_questions("ses_1", "question", json);
447 assert_eq!(list.len(), 2);
448 let group = list[0].group.clone().expect("group");
449 assert_eq!(list[1].group.as_deref(), Some(group.as_str()));
450 }
451
452 #[test]
453 fn parses_acp_one_of_options() {
454 let params = json!({
455 "message": "Questions",
456 "requestedSchema": {
457 "type": "object",
458 "properties": {
459 "q0": {
460 "type": "string",
461 "title": "UI framework",
462 "description": "Which UI framework?",
463 "oneOf": [
464 {"const": "React", "title": "React", "description": "Mature"},
465 {"const": "Vue", "title": "Vue", "description": "Simple"}
466 ]
467 }
468 }
469 }
470 });
471 let list = parse_acp_elicitations("ses_1", ¶ms);
472 assert_eq!(list.len(), 1);
473 assert_eq!(list[0].0.question, "Which UI framework?");
474 let labels: Vec<_> = list[0].0.options.iter().map(|o| o.label.as_str()).collect();
475 assert_eq!(labels, vec!["React", "Vue"]);
476 assert_eq!(list[0].0.options[0].description.as_deref(), Some("Mature"));
477 }
478
479 #[test]
480 fn parses_acp_one_of_const_values_as_submission_values() {
481 let params = json!({
482 "requestedSchema": {
483 "type": "object",
484 "properties": {
485 "q1": {
486 "type": "string",
487 "title": "Which database should we use?",
488 "oneOf": [
489 {"const": "1", "title": "Postgres"},
490 {"const": "2", "title": "Redis"}
491 ]
492 }
493 }
494 }
495 });
496 let list = parse_acp_elicitations("ses_1", ¶ms);
497 assert_eq!(list.len(), 1);
498 assert_eq!(list[0].0.options[0].label, "Postgres");
499 assert_eq!(list[0].0.options[0].value.as_deref(), Some("1"));
500 assert_eq!(list[0].0.options[1].value.as_deref(), Some("2"));
501 }
502
503 #[test]
504 fn parses_acp_multi_select_items_one_of_options() {
505 let params = json!({
506 "message": "The agent has 2 questions.",
507 "requestedSchema": {
508 "type": "object",
509 "properties": {
510 "q1": {
511 "type": "array",
512 "title": "Which scripts?",
513 "items": {
514 "oneOf": [
515 {"const": "a.sh", "title": "a.sh", "description": "Script A"},
516 {"const": "b.ps1", "title": "b.ps1"}
517 ]
518 }
519 },
520 "q2": {
521 "type": "array",
522 "title": "Which improvements?",
523 "items": {
524 "anyOf": [
525 {"const": "1", "title": "Option 1"}
526 ]
527 }
528 }
529 }
530 }
531 });
532 let list = parse_acp_elicitations("ses_1", ¶ms);
533 assert_eq!(list.len(), 2);
534 let q1 = list
535 .iter()
536 .find(|(_, k)| k == "q1")
537 .map(|(q, _)| q)
538 .expect("q1");
539 assert!(q1.multi_select);
540 assert_eq!(q1.options.len(), 2);
541 assert_eq!(q1.options[0].label, "a.sh");
542 assert_eq!(q1.options[0].description.as_deref(), Some("Script A"));
543 assert_eq!(q1.options[1].label, "b.ps1");
544
545 let q2 = list
546 .iter()
547 .find(|(_, k)| k == "q2")
548 .map(|(q, _)| q)
549 .expect("q2");
550 assert!(q2.multi_select);
551 assert_eq!(q2.options.len(), 1);
552 assert_eq!(q2.options[0].label, "Option 1");
553 assert_eq!(q2.options[0].value.as_deref(), Some("1"));
554 }
555
556 #[test]
557 fn parse_opencode_question_format() {
558 let json = r#"{
559 "questions": [{
560 "question": "Which framework would you like to use?",
561 "header": "Framework",
562 "options": [
563 {"label": "React", "description": "Popular UI library"},
564 {"label": "Vue", "description": "Progressive framework"}
565 ],
566 "multiple": false,
567 "custom": true
568 }]
569 }"#;
570 let q = parse_tool_call_question("ses_1", "question", json).expect("parse opencode");
571 assert_eq!(q.header.as_deref(), Some("Framework"));
572 assert_eq!(q.question, "Which framework would you like to use?");
573 assert_eq!(q.options.len(), 2);
574 assert_eq!(q.options[0].label, "React");
575 assert_eq!(
576 q.options[0].description.as_deref(),
577 Some("Popular UI library")
578 );
579 assert!(!q.multi_select);
580 assert!(q.custom);
581 }
582
583 #[test]
584 fn parse_multiple_tool_call_questions() {
585 let json = r#"{
586 "questions": [
587 {
588 "question": "Choose database",
589 "header": "Database",
590 "options": ["PostgreSQL", "SQLite"]
591 },
592 {
593 "question": "Choose cache",
594 "header": "Cache",
595 "options": ["Redis", "Memcached"],
596 "multi_select": true
597 }
598 ]
599 }"#;
600 let list = parse_tool_call_questions("ses_1", "AskUserQuestion", json);
601 assert_eq!(list.len(), 2);
602 assert_eq!(list[0].header.as_deref(), Some("Database"));
603 assert_eq!(list[0].question, "Choose database");
604 assert_eq!(list[0].options.len(), 2);
605 assert!(!list[0].multi_select);
606 assert_eq!(list[1].header.as_deref(), Some("Cache"));
607 assert_eq!(list[1].question, "Choose cache");
608 assert!(list[1].multi_select);
609 }
610
611 #[test]
612 fn parse_claude_camel_case_multi_select() {
613 let json = r#"{
614 "questions": [{
615 "question": "Choose features",
616 "header": "Features",
617 "multiSelect": true,
618 "options": ["Auth", "Search"]
619 }]
620 }"#;
621 let q = parse_tool_call_question("ses_1", "AskUserQuestion", json).expect("parse claude");
622 assert!(q.multi_select);
623 assert_eq!(q.options.len(), 2);
624 }
625
626 #[test]
627 fn parse_antigravity_question_format() {
628 let json = r#"{
629 "questions": [{
630 "question": "Select target architectures",
631 "options": ["x86_64", "aarch64", "wasm32"],
632 "is_multi_select": true
633 }]
634 }"#;
635 let q = parse_tool_call_question("ses_2", "ask_question", json).expect("parse agy");
636 assert_eq!(q.question, "Select target architectures");
637 assert_eq!(q.options.len(), 3);
638 assert_eq!(q.options[1].label, "aarch64");
639 assert!(q.multi_select);
640 }
641
642 #[test]
643 fn parse_codex_app_server_format() {
644 let params = serde_json::json!({
645 "threadId": "th_1",
646 "questions": [{
647 "id": "db_choice",
648 "header": "Database Selection",
649 "question": "Select your primary database",
650 "options": [
651 {"label": "Postgres", "description": "Relational"},
652 {"label": "Redis", "description": "Key-value"}
653 ]
654 }]
655 });
656 let (q, key) = parse_codex_user_input("ses_3", ¶ms).expect("parse codex");
657 assert_eq!(key.as_deref(), Some("db_choice"));
658 assert_eq!(q.header.as_deref(), Some("Database Selection"));
659 assert_eq!(q.options[0].label, "Postgres");
660 }
661
662 #[test]
663 fn parse_multiple_codex_questions() {
664 let params = serde_json::json!({
665 "threadId": "th_1",
666 "questions": [
667 {
668 "id": "q1",
669 "question": "First question?",
670 "options": ["Yes", "No"]
671 },
672 {
673 "id": "q2",
674 "question": "Second question?",
675 "options": ["Option A", "Option B"]
676 }
677 ]
678 });
679 let list = parse_codex_user_inputs("ses_3", ¶ms);
680 assert_eq!(list.len(), 2);
681 assert_eq!(list[0].1, "q1");
682 assert_eq!(list[0].0.question, "First question?");
683 assert_eq!(list[1].1, "q2");
684 assert_eq!(list[1].0.question, "Second question?");
685 }
686
687 #[test]
688 fn parse_acp_elicitation_format() {
689 let params = serde_json::json!({
690 "mode": "form",
691 "message": "Deployment Options",
692 "requestedSchema": {
693 "type": "object",
694 "properties": {
695 "env": {
696 "type": "string",
697 "title": "Environment",
698 "description": "Target environment",
699 "enum": ["production", "staging", "dev"]
700 }
701 }
702 }
703 });
704 let (q, keys) = parse_acp_elicitation("ses_4", ¶ms).expect("parse acp");
705 assert_eq!(keys, vec!["env"]);
706 assert_eq!(q.header.as_deref(), Some("Environment"));
707 assert_eq!(q.options.len(), 3);
708 assert_eq!(q.options[0].label, "production");
709 }
710
711 #[test]
712 fn parse_multiple_acp_elicitations() {
713 let params = serde_json::json!({
714 "mode": "form",
715 "message": "Project Config",
716 "requestedSchema": {
717 "type": "object",
718 "properties": {
719 "lang": {
720 "type": "string",
721 "title": "Language",
722 "enum": ["Rust", "TypeScript"]
723 },
724 "framework": {
725 "type": "string",
726 "title": "Framework",
727 "enum": ["Actix", "Axum"]
728 }
729 }
730 }
731 });
732 let list = parse_acp_elicitations("ses_4", ¶ms);
733 assert_eq!(list.len(), 2);
734 let keys: Vec<String> = list.iter().map(|(_, k)| k.clone()).collect();
735 assert!(keys.contains(&"lang".to_string()));
736 assert!(keys.contains(&"framework".to_string()));
737 }
738
739 #[test]
740 fn malformed_input_graceful_fallback() {
741 let q = parse_tool_call_question("ses_5", "question", "not a valid json { broken")
742 .expect("fallback");
743 assert_eq!(q.question, "not a valid json { broken");
744 assert!(q.options.is_empty());
745 assert!(q.custom);
746 }
747}