agent86-core 1.2.3

The agent behind agent86: a safe agent runtime you can embed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
//! `ask_user`, beyond Python (ADR 0006): the model asks the user its questions
//! as a short, flat list, and agent86 asks them, as a form it builds itself
//! (so the form is always valid), through an ACP extension, or as text.
//!
//! The tool (`tools::ask_user`) checks the arguments ([`Form::parse`]) and hands
//! the [`Form`] to the main loop, which asks through the [`Asker`]'s hook, one
//! question at a time with approvals and secrets (`approval::PromptQueue`), and
//! makes the [`Reply`] the call's result ([`Accepted::text`]). Each surface
//! installs its own hook, as it installs its approval and secret prompts, and
//! the tool is offered only where one is: never under `run`, in CI, or to a
//! sub-agent.

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::sync::{Arc, Mutex, PoisonError};

/// The tool's name.
pub const ASK_USER: &str = "ask_user";

/// The `ToolResult::metadata` key under which the tool hands the loop the
/// checked [`Form`] to ask. Taken out before the result reaches the session.
pub const ASK_KEY: &str = "agent86_ask";

/// At most this many questions in one call.
pub const MAX_QUESTIONS: usize = 10;
/// A choice question's options, at least and at most.
pub const MIN_OPTIONS: usize = 1;
pub const MAX_OPTIONS: usize = 12;
/// The longest question text, title, and option, in characters.
pub const MAX_QUESTION_CHARS: usize = 300;
pub const MAX_TITLE_CHARS: usize = 120;
pub const MAX_OPTION_CHARS: usize = 200;

/// What kind of answer a question takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AnswerKind {
    /// Exactly one of the options.
    Choice,
    /// Any number of the options.
    Multi,
    /// A line of text.
    Text,
    /// A paragraph.
    LongText,
    /// A number.
    Number,
    /// Yes or no.
    YesNo,
    /// A date, `YYYY-MM-DD`.
    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)
    }

    /// Whether the question offers options (and so "Other").
    pub fn has_options(self) -> bool {
        matches!(self, AnswerKind::Choice | AnswerKind::Multi)
    }
}

/// One question.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FormQuestion {
    /// An identifier, unique in its form; the answer's key.
    pub id: String,
    /// What is asked.
    pub question: String,
    pub kind: AnswerKind,
    /// For `choice` and `multi`: each option is its own label and value.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub options: Vec<String>,
    /// Whether the form may be sent without an answer to it.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub optional: bool,
}

/// The questions of one `ask_user` call, checked.
#[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 {
    /// Check the tool's arguments: the form, or every problem, each naming the
    /// question by index and id so a model can fix them all in one more call.
    /// `null` and a missing field are the same, as strict tool modes send
    /// every field.
    pub fn parse(args: &Map<String, Value>) -> Result<Form, Vec<String>> {
        let mut problems = Vec::new();
        // Fields beyond title and questions are ignored, not refused (ADR 0006,
        // slice 8): what the questions say is all that is asked.
        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)
        }
    }

    /// Normalize the answers a surface gave (by question id) to each question's
    /// kind, in the form's order: the answers, which were typed rather than
    /// chosen, and which required questions were left unanswered.
    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
    }

    /// The kinds asked, in order, for the trace.
    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();
    // Unknown fields are ignored and a few names models use instead are taken
    // (ADR 0006, slice 8): a refusal costs a round trip, and the question is
    // plain either way.
    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() {
            // One option is a fair question, since "Other" is added; none makes
            // it a text question (below). Only too many is refused.
            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"
                ));
            }
            // An option listed twice is listed once.
            let mut unique: Vec<String> = Vec::new();
            for option in options.drain(..) {
                if !unique.contains(&option) {
                    unique.push(option);
                }
            }
            options = unique;
        }
        // Options on a question without them (a model listing examples for a
        // text answer) are ignored, not refused: the question still stands,
        // and a refusal would cost a round trip (ADR 0006, slice 8).
    }
    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;
    }
    // A choice question with no options is asked as text (ADR 0006, slice 8).
    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(", ")
}

/// An identifier as A2UI's ids are: letters, digits, and `_`, not starting with
/// a digit. Question ids become component ids and data model keys.
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 == '_')
}

/// A surface's answer to `question` as its kind wants it, or `null` when it
/// gave none.
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,
    };
    // A ChoicePicker binds a list even when one may be chosen.
    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))
            }
        },
    }
}

/// `text` as a JSON number: an integer when it has no fraction.
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)
}

/// `YYYY-MM-DD`, by shape.
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())
}

/// Whether an answer to a question with options is (or holds) something not
/// among them: the user's own words.
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,
    }
}

/// The answers to a [`Form`], normalized ([`Form::accept`]).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Accepted {
    /// By question id, in the form's order; `null` where none was given.
    pub answers: Map<String, Value>,
    /// The choice questions answered in the user's own words.
    pub typed: Vec<String>,
    /// The required questions left unanswered.
    pub unanswered: Vec<String>,
}

impl Accepted {
    /// The call's result, as the model reads it.
    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
    }
}

/// The result when the user closed the form without sending it. Not a failure:
/// nothing went wrong, and the circuit breaker must not count it.
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.";

/// How the questions reached the user.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Via {
    /// A form agent86 built (the terminal interface, an embedder's renderer, an
    /// ACP client with agent86UI).
    Form,
    /// An ACP client's own form, through agent86's questions extension.
    Extension,
    /// Text: one question at a time (the plain loop), or all of them as the
    /// agent's message, ending the turn (an ACP client that draws nothing).
    Text,
}

impl Via {
    pub fn as_str(self) -> &'static str {
        match self {
            Via::Form => "form",
            Via::Extension => "extension",
            Via::Text => "text",
        }
    }
}

/// What the user did with the questions.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Outcome {
    /// Their answers, by question id, as the surface has them; the loop
    /// normalizes them ([`Form::accept`]).
    Answered(Map<String, Value>),
    /// They closed the questions without sending answers.
    Dismissed,
}

/// A hook's answer.
#[derive(Debug, Clone, PartialEq)]
pub struct Reply {
    pub outcome: Outcome,
    pub via: Via,
}

/// Asks the user a [`Form`]'s questions. Called on the turn's thread, through
/// the prompt queue.
pub type AskPrompt = Box<dyn Fn(&Form) -> Reply + Send + Sync>;

/// How the user is asked, once a surface says: through a hook it installed (the
/// terminal interface, the plain loop), or (for an embedder's renderer, slice 4)
/// by the loop drawing the built form as `TurnEvent::Ui` messages and waiting
/// through the renderer's waiter. Clones share it; a sub-agent's context has
/// its own, empty one, since only the main loop asks.
#[derive(Clone, Default)]
pub struct Asker {
    prompt: Arc<Mutex<Option<Arc<AskPrompt>>>>,
    form: Arc<std::sync::atomic::AtomicBool>,
    /// Ask as text, ending the turn ([`ASK_TEXT_KEY`]), when nothing else can.
    text: Arc<std::sync::atomic::AtomicBool>,
    /// The last form surface's number, for `agent86_ask_<n>`.
    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())
            .field("asks_in_text", &self.asks_in_text())
            .finish()
    }
}

impl Asker {
    /// Install (or, with `None`, remove) the hook.
    pub fn set_prompt(&self, prompt: Option<AskPrompt>) {
        *self.prompt.lock().unwrap_or_else(PoisonError::into_inner) = prompt.map(Arc::new);
    }

    /// Whether a hook is installed. See [`reachable`] for whether anyone can
    /// be asked at all.
    pub fn can_ask(&self) -> bool {
        self.prompt().is_some()
    }

    /// Ask by drawing the built form through the context's renderer (or stop).
    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)
    }

    /// Ask as text that ends the turn, when no hook or form can (or stop).
    pub fn set_asks_in_text(&self, text: bool) {
        self.text.store(text, std::sync::atomic::Ordering::Relaxed);
    }

    pub fn asks_in_text(&self) -> bool {
        self.text.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// The surface id of the next form agent86 draws (`agent86_ask_<n>`).
    pub fn next_surface(&self) -> String {
        let n = self
            .forms
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
            + 1;
        format!("{FORM_SURFACE_PREFIX}{n}")
    }

    /// The hook, if one is installed. The lock is not held while the user answers.
    pub fn prompt(&self) -> Option<Arc<AskPrompt>> {
        self.prompt
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }
}

/// Whether anyone can answer `ask_user` from `ctx`: a hook is installed, or the
/// loop draws the form and the context's renderer can answer a wait.
pub fn reachable(ctx: &crate::tools::ToolContext) -> bool {
    if ctx.asker.can_ask() {
        return true;
    }
    draws_form(ctx) || ctx.asker.asks_in_text()
}

/// Whether the loop draws the built form and the context's renderer can answer.
fn draws_form(ctx: &crate::tools::ToolContext) -> bool {
    #[cfg(feature = "agent86ui")]
    if ctx.asker.draws_form() {
        return ctx.ui.as_deref().is_some_and(|ui| ui.can_wait());
    }
    let _ = ctx;
    false
}

/// Where a call's questions were shown as text (the text fallback), its result's
/// metadata carries that text under this key: the loop sends it as the agent's
/// message and ends the turn (ADR 0006).
pub const ASK_TEXT_KEY: &str = "agent86_ask_text";

/// The result of a call whose questions were shown as text.
pub const SHOWN_AS_TEXT: &str = "This client cannot show a form, so the questions were shown \
     to the user as text and the turn ends here. Their reply comes as the next user message; \
     read the answers from it.";

/// A form's questions as text, for a client that draws nothing (ADR 0006's text
/// fallback): numbered, each choice question's options lettered, with what kind
/// of answer each takes, and a line saying to answer in the reply.
pub fn form_text(form: &Form) -> String {
    let mut lines = Vec::new();
    if let Some(title) = &form.title {
        lines.push(title.clone());
        lines.push(String::new());
    }
    for (index, question) in form.questions.iter().enumerate() {
        let hint = match question.kind {
            AnswerKind::YesNo => " (yes or no)",
            AnswerKind::Number => " (a number)",
            AnswerKind::Date => " (a date)",
            AnswerKind::Multi => " (any of these)",
            _ => "",
        };
        let optional = if question.optional { " (optional)" } else { "" };
        lines.push(format!(
            "{}. {}{hint}{optional}",
            index + 1,
            question.question
        ));
        if question.kind.has_options() {
            let options: Vec<String> = question
                .options
                .iter()
                .enumerate()
                .map(|(n, option)| format!("{}) {option}", char::from(b'a' + (n % 26) as u8)))
                .collect();
            lines.push(format!("   {}, or say something else", options.join("  ")));
        }
    }
    lines.push(String::new());
    lines.push("Answer in your reply, by number.".into());
    lines.join("\n")
}

/// The system-prompt section wherever `ask_user` is offered (ADR 0006). With
/// `render_ui` offered too, it says which tool asks questions.
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 {
    /// Offer `ask_user`, answered by `prompt` (ADR 0006). Each surface calls it
    /// with its own hook, where someone can answer; called again, it replaces
    /// the hook. The caller decides whether to (`[ui] ask_user`), since the
    /// harness reads no config.
    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(())
    }

    /// Offer `ask_user` answered through the renderer the embedder declared
    /// (ADR 0006, slice 4): the loop draws the built form as `TurnEvent::Ui`
    /// messages, as `render_ui` draws, and waits through the renderer's waiter,
    /// so an embedder that answers waiting `render_ui` calls answers the
    /// questions with no new code. Offered only when the renderer can answer a
    /// wait and has the basic catalog the form is built in. Returns whether it
    /// was offered.
    #[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)
    }

    /// Offer `ask_user` where nobody can answer mid-turn (ADR 0006's text
    /// fallback, for an ACP client that draws nothing): the questions are sent as
    /// the agent's message and the turn ends; the user's reply is the answer.
    pub fn offer_questions_as_text(&mut self) -> Result<(), String> {
        if self.registry.get(ASK_USER).is_none() {
            self.registry
                .register(Box::new(crate::tools::ask_user::AskUserTool))?;
        }
        self.context.asker.set_asks_in_text(true);
        Ok(())
    }

    /// Draw the built form through the context's renderer and wait for its
    /// Send (slice 4): `None` when the turn was cancelled while it waited.
    #[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,
        })
    }

    /// Ask the questions an `ask_user` call checked, when `result` carries them
    /// ([`ASK_KEY`]), and make the answer its result; any other result is
    /// returned as it is. Asked through the prompt queue like a secret (one
    /// question at a time, declined once the turn is cancelled). The answers go
    /// through the vault and the ingress guardrail, as typed input does, and the
    /// call is recorded as `ask_user`, without them.
    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)
        };
        // Nobody can answer mid-turn: the questions go out as text that ends
        // the turn (ADR 0006), through the vault and the egress guardrail as the
        // model's own text does.
        if self.context.asker.prompt().is_none()
            && !draws_form(&self.context)
            && self.context.asker.asks_in_text()
        {
            let text = self.context.secrets.redact(&form_text(&form));
            let (_, text) = self.guardrails.inspect_egress(&text);
            record("shown", Some(Via::Text), 0);
            let mut shown = success(ASK_USER, SHOWN_AS_TEXT.into());
            shown.metadata.insert(ASK_TEXT_KEY.into(), json!(text));
            return answered(shown);
        }
        // A hook the surface installed, else the built form drawn through the
        // embedder's renderer.
        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))
            }
        }
    }
}

/// How the surface of a form agent86 builds is named (`agent86_ask_<n>`), so a
/// surface can tell it from one the model drew, and `render_ui` refuses the
/// prefix, so the model cannot replace a form while the user answers it.
pub const FORM_SURFACE_PREFIX: &str = "agent86_ask_";

/// The option the built form adds to every choice question, and the value it
/// stands for in the data model.
#[cfg(feature = "agent86ui")]
pub const OTHER_LABEL: &str = "Other";
#[cfg(feature = "agent86ui")]
const OTHER_VALUE: &str = "__other__";

/// The A2UI messages of the form for `form` (ADR 0006): one `createSurface` in
/// `catalog_id` (the basic catalog's components), a Column of the title, each
/// question's input bound to `/answers/<id>` (and an "Other" field to
/// `/other/<id>`), and a Send button whose event carries both. agent86 builds
/// it, so it is always valid; a test checks every kind against the validator.
#[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"}}}}});
    // Send stays disabled until every required question has an answer.
    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},
    }})]
}

/// The answers, by question id, from the context of the built form's Send
/// action ([`form_messages`]): "Other" is replaced by what the user typed
/// (dropped when they typed nothing), ready for [`Form::accept`].
#[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() {
        // What `gemma4:12b` and others sent (ADR 0006, slice 8).
        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());

        // Fill it in as a user would, and press Send.
        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();
        }
        // `notes` is required and still empty, so Send is disabled.
        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);
    }
}