leviath-core 0.1.0

Core types and traits for Leviath: context regions, memory layouts, blueprints, and lifecycle policies
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
//! Plain value types for the worker ↔ dashboard interaction channel.
//!
//! These are serde data types shared across the engine (`leviath-runtime`),
//! the CLI's file-IPC/stdin transports, and the dashboard. The concrete
//! transport functions (file IPC, stdin) and backends live in `leviath-cli`;
//! only the wire/value types and their pure resolver helpers live here so the
//! runtime can reference them without depending on the CLI.

use serde::{Deserialize, Serialize};

// ─── Request ────────────────────────────────────────────────────────────────

/// The kind of interaction being requested.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum InteractionKind {
    /// Free-form text answer (the default today).
    FreeText,
    /// User picks one option from a numbered list.
    MultipleChoice,
    /// Yes/no confirmation.
    Confirm,
    /// Approve or deny a specific tool call before it executes.
    ToolApproval,
    /// Edit a document in place: the request carries the current text in
    /// `body`; the user edits it and the (possibly modified) text is returned.
    EditText,
}

/// Format of an optional rich body attached to an interaction request.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "snake_case")]
pub enum BodyFormat {
    /// Plain text body (no special rendering).
    #[default]
    Plain,
    /// Markdown body - rendered via the dashboard's markdown renderer.
    Markdown,
}

/// A pending interaction request written by the worker.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct InteractionRequest {
    /// Unique ID for this request (uuid-lite: timestamp + stage index).
    pub id: String,
    /// What kind of answer is expected.
    pub kind: InteractionKind,
    /// Prompt text to display to the user.
    pub prompt: String,
    /// Options for MultipleChoice (index-labelled).
    #[serde(default)]
    pub options: Vec<String>,
    /// For ToolApproval: the tool name.
    pub tool_name: Option<String>,
    /// For ToolApproval: the tool arguments (JSON).
    pub tool_arguments: Option<serde_json::Value>,
    /// Whether an answer is mandatory (empty/cancel not allowed).
    #[serde(default = "default_true")]
    pub required: bool,
    /// Stage name that triggered this request.
    pub stage_name: String,
    /// Optional rich body (markdown document, plan, etc.) for the user to review.
    #[serde(default)]
    pub body: Option<String>,
    /// Format of the body content.
    #[serde(default)]
    pub body_format: BodyFormat,
}

fn default_true() -> bool {
    true
}

impl InteractionRequest {
    /// Create a new free-text request.
    pub fn free_text(
        id: impl Into<String>,
        prompt: impl Into<String>,
        stage: impl Into<String>,
        required: bool,
    ) -> Self {
        Self {
            id: id.into(),
            kind: InteractionKind::FreeText,
            prompt: prompt.into(),
            options: vec![],
            tool_name: None,
            tool_arguments: None,
            required,
            stage_name: stage.into(),
            body: None,
            body_format: BodyFormat::Plain,
        }
    }

    /// Create a "present for review" request: pauses the run and shows a rich
    /// markdown document to the user before accepting feedback.
    pub fn review(
        id: impl Into<String>,
        title: impl Into<String>,
        markdown: impl Into<String>,
        stage: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            kind: InteractionKind::FreeText,
            prompt: title.into(),
            options: vec![],
            tool_name: None,
            tool_arguments: None,
            required: true,
            stage_name: stage.into(),
            body: Some(markdown.into()),
            body_format: BodyFormat::Markdown,
        }
    }

    /// Create an "edit document" request: shows `initial_content` in an
    /// editable field pre-seeded with it (via `body`); the user edits it and
    /// the modified text is returned as the response text.
    pub fn edit_text(
        id: impl Into<String>,
        prompt: impl Into<String>,
        stage: impl Into<String>,
        initial_content: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            kind: InteractionKind::EditText,
            prompt: prompt.into(),
            options: vec![],
            tool_name: None,
            tool_arguments: None,
            required: true,
            stage_name: stage.into(),
            body: Some(initial_content.into()),
            body_format: BodyFormat::Plain,
        }
    }

    /// Create a new multiple-choice request.
    pub fn multiple_choice(
        id: impl Into<String>,
        prompt: impl Into<String>,
        options: Vec<String>,
        stage: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            kind: InteractionKind::MultipleChoice,
            prompt: prompt.into(),
            options,
            tool_name: None,
            tool_arguments: None,
            required: true,
            stage_name: stage.into(),
            body: None,
            body_format: BodyFormat::Plain,
        }
    }

    /// Create a new confirm request.
    pub fn confirm(
        id: impl Into<String>,
        prompt: impl Into<String>,
        stage: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            kind: InteractionKind::Confirm,
            prompt: prompt.into(),
            options: vec!["Yes".to_string(), "No".to_string()],
            tool_name: None,
            tool_arguments: None,
            required: true,
            stage_name: stage.into(),
            body: None,
            body_format: BodyFormat::Plain,
        }
    }

    /// Create a new tool-approval request.
    /// The part of a tool call a person needs to see before approving it.
    ///
    /// "Allow tool call: `bash`?" is not a question anyone can answer - it asks
    /// whether to run *a shell command* without saying which one, so the only
    /// safe answer is no and the only practical one is yes. The argument that
    /// decides the answer is the command itself, and for the file tools it is
    /// the path.
    ///
    /// Truncated, because a prompt is a line in a terminal: a heredoc that
    /// scrolls the decision off screen is the same problem again.
    fn approval_detail(tool: &str, arguments: &serde_json::Value) -> Option<String> {
        let field = match tool {
            "bash" | "shell" => "command",
            "write_file" | "edit_file" | "read_file" => "path",
            _ => return None,
        };
        let raw = arguments.get(field)?.as_str()?.trim();
        if raw.is_empty() {
            return None;
        }
        // One line: a multi-line command is summarised by its first line so the
        // prompt stays readable, with the rest available in `tool_arguments`.
        let first = raw.lines().next().unwrap_or(raw);
        let mut shown: String = first.chars().take(120).collect();
        if shown.chars().count() < first.chars().count() || first.len() < raw.len() {
            shown.push('');
        }
        Some(format!("`{shown}`"))
    }

    pub fn tool_approval(
        id: impl Into<String>,
        tool_name: impl Into<String>,
        arguments: serde_json::Value,
        stage: impl Into<String>,
    ) -> Self {
        let tool = tool_name.into();
        let prompt = match Self::approval_detail(&tool, &arguments) {
            Some(detail) => format!("Allow tool call: `{tool}` - {detail}?"),
            None => format!("Allow tool call: `{tool}`?"),
        };
        Self {
            id: id.into(),
            kind: InteractionKind::ToolApproval,
            prompt,
            options: vec![
                "Allow once".to_string(),
                "Allow for this session".to_string(),
                "Deny".to_string(),
            ],
            tool_name: Some(tool),
            tool_arguments: Some(arguments),
            required: true,
            stage_name: stage.into(),
            body: None,
            body_format: BodyFormat::Plain,
        }
    }
}

// ─── Response ───────────────────────────────────────────────────────────────

/// The scope of an approval decision.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalScope {
    /// Allow/deny just this one call.
    Once,
    /// Allow/deny all calls to this tool for the rest of this agent run.
    Session,
}

/// A response written by the dashboard (or `lev respond`) to answer the worker.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct InteractionResponse {
    /// Must match `InteractionRequest.id`.
    pub request_id: String,
    /// The user's free-text value (FreeText / InteractionPoints).
    pub value: Option<String>,
    /// Index into `options` for MultipleChoice / ToolApproval.
    pub choice_index: Option<usize>,
    /// Whether a ToolApproval was granted.
    pub approved: Option<bool>,
    /// Scope of a tool approval decision.
    pub scope: Option<ApprovalScope>,
}

impl InteractionResponse {
    /// Build a simple text response.
    pub fn text(request_id: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            request_id: request_id.into(),
            value: Some(value.into()),
            choice_index: None,
            approved: None,
            scope: None,
        }
    }

    /// Build a choice response (0-based index).
    pub fn choice(request_id: impl Into<String>, index: usize) -> Self {
        Self {
            request_id: request_id.into(),
            value: None,
            choice_index: Some(index),
            approved: None,
            scope: None,
        }
    }

    /// Build an approval response.
    pub fn approval(request_id: impl Into<String>, approved: bool, scope: ApprovalScope) -> Self {
        Self {
            request_id: request_id.into(),
            value: None,
            choice_index: None,
            approved: Some(approved),
            scope: Some(scope),
        }
    }
}

// ─── Pure resolver helpers ────────────────────────────────────────────────────

/// Resolve a `FreeText` response to a string.
pub fn response_as_text(resp: &InteractionResponse) -> String {
    resp.value.clone().unwrap_or_default()
}

/// Resolve a `MultipleChoice` response to the chosen option string.
pub fn response_as_choice<'a>(
    resp: &InteractionResponse,
    options: &'a [String],
) -> Option<&'a String> {
    resp.choice_index.and_then(|i| options.get(i))
}

/// Returns `true` if a tool-approval response was granted.
pub fn response_approved(resp: &InteractionResponse) -> bool {
    resp.approved.unwrap_or(false)
}

/// Generate a simple monotonic ID from stage index + iteration.
pub fn make_interaction_id(stage_idx: usize, iteration: usize) -> String {
    format!("{}-{}", stage_idx, iteration)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// "Allow tool call: `bash`?" asks whether to run a shell command without
    /// saying which one - the only safe answer is no and the only practical one
    /// is yes, so in practice everything gets approved unread.
    #[test]
    fn a_tool_approval_says_what_it_is_asking_about() {
        let req = InteractionRequest::tool_approval(
            "id",
            "bash",
            serde_json::json!({"command": "rm -rf build && make"}),
            "implement",
        );
        assert!(
            req.prompt.contains("rm -rf build && make"),
            "{}",
            req.prompt
        );

        // File tools name the path.
        let req = InteractionRequest::tool_approval(
            "id",
            "write_file",
            serde_json::json!({"path": "src/main.rs", "content": "..."}),
            "implement",
        );
        assert!(req.prompt.contains("src/main.rs"), "{}", req.prompt);
    }

    /// A prompt is one line in a terminal. A heredoc that scrolls the decision
    /// off screen is the same problem as showing nothing.
    #[test]
    fn a_long_or_multiline_command_is_summarised() {
        let long = "echo ".to_string() + &"x".repeat(400);
        let req = InteractionRequest::tool_approval(
            "id",
            "bash",
            serde_json::json!({ "command": long }),
            "s",
        );
        assert!(req.prompt.chars().count() < 200, "{}", req.prompt);
        assert!(req.prompt.contains(''), "{}", req.prompt);

        let req = InteractionRequest::tool_approval(
            "id",
            "bash",
            serde_json::json!({"command": "cat <<'EOF' > f\nline two\nEOF"}),
            "s",
        );
        assert!(req.prompt.contains("cat <<'EOF' > f"), "{}", req.prompt);
        assert!(!req.prompt.contains("line two"), "{}", req.prompt);
        // The whole thing is still available to a richer UI.
        assert!(req.tool_arguments.is_some());
    }

    /// A tool with no argument worth showing keeps the plain question rather
    /// than gaining an empty pair of backticks.
    #[test]
    fn a_tool_without_a_telling_argument_reads_as_before() {
        let req = InteractionRequest::tool_approval("id", "list_dir", serde_json::json!({}), "s");
        assert_eq!(req.prompt, "Allow tool call: `list_dir`?");
        let req = InteractionRequest::tool_approval(
            "id",
            "bash",
            serde_json::json!({"command": "   "}),
            "s",
        );
        assert_eq!(req.prompt, "Allow tool call: `bash`?");
        // Present but not a string: still nothing worth showing.
        let req = InteractionRequest::tool_approval(
            "id",
            "bash",
            serde_json::json!({"command": 42}),
            "s",
        );
        assert_eq!(req.prompt, "Allow tool call: `bash`?");
    }

    // ─── InteractionRequest / InteractionResponse constructors ─────────────

    #[test]
    fn test_request_builders() {
        let r = InteractionRequest::free_text("id1", "What now?", "plan", true);
        assert_eq!(r.kind, InteractionKind::FreeText);
        assert!(r.required);

        let r = InteractionRequest::multiple_choice(
            "id2",
            "Pick one",
            vec!["A".into(), "B".into()],
            "plan",
        );
        assert_eq!(r.kind, InteractionKind::MultipleChoice);
        assert_eq!(r.options.len(), 2);

        let r = InteractionRequest::tool_approval(
            "id3",
            "bash",
            serde_json::json!({"cmd": "ls"}),
            "impl",
        );
        assert_eq!(r.kind, InteractionKind::ToolApproval);
        assert_eq!(r.options.len(), 3);
    }

    #[test]
    fn test_edit_text_request_builder_seeds_body() {
        let r = InteractionRequest::edit_text("id4", "Edit this", "plan", "current text");
        assert_eq!(r.kind, InteractionKind::EditText);
        assert!(r.required);
        assert_eq!(r.body.as_deref(), Some("current text"));
        assert_eq!(r.prompt, "Edit this");
    }

    #[test]
    fn test_edit_text_kind_serde_roundtrip_snake_case() {
        let r = InteractionRequest::edit_text("id5", "p", "plan", "seed");
        let json = serde_json::to_string(&r).unwrap();
        // snake_case rename ⇒ "edit_text"
        assert!(json.contains("\"edit_text\""));
        let back: InteractionRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(back.kind, InteractionKind::EditText);
        assert_eq!(back.body.as_deref(), Some("seed"));
    }

    #[test]
    fn test_response_builders() {
        let r = InteractionResponse::text("id1", "hello");
        assert_eq!(r.value.as_deref(), Some("hello"));

        let r = InteractionResponse::choice("id2", 1);
        assert_eq!(r.choice_index, Some(1));

        let r = InteractionResponse::approval("id3", true, ApprovalScope::Session);
        assert_eq!(r.approved, Some(true));
        assert_eq!(r.scope, Some(ApprovalScope::Session));
    }

    #[test]
    fn test_response_as_text() {
        let r = InteractionResponse::text("id", "answer");
        assert_eq!(response_as_text(&r), "answer");
        let empty = InteractionResponse {
            request_id: "x".into(),
            value: None,
            choice_index: None,
            approved: None,
            scope: None,
        };
        assert_eq!(response_as_text(&empty), "");
    }

    #[test]
    fn test_response_as_choice() {
        let opts = vec!["Alpha".to_string(), "Beta".to_string()];
        let r = InteractionResponse::choice("id", 0);
        assert_eq!(response_as_choice(&r, &opts), Some(&"Alpha".to_string()));
        let r = InteractionResponse::choice("id", 1);
        assert_eq!(response_as_choice(&r, &opts), Some(&"Beta".to_string()));
        let r = InteractionResponse::choice("id", 99);
        assert!(response_as_choice(&r, &opts).is_none());
    }

    #[test]
    fn test_make_interaction_id() {
        let id = make_interaction_id(2, 5);
        assert_eq!(id, "2-5");
    }

    #[test]
    fn test_free_text_request_not_required() {
        let r = InteractionRequest::free_text("ft1", "optional?", "stage1", false);
        assert_eq!(r.kind, InteractionKind::FreeText);
        assert!(!r.required);
        assert_eq!(r.id, "ft1");
        assert_eq!(r.prompt, "optional?");
        assert_eq!(r.stage_name, "stage1");
        assert!(r.options.is_empty());
        assert!(r.tool_name.is_none());
        assert!(r.tool_arguments.is_none());
        assert!(r.body.is_none());
        assert_eq!(r.body_format, BodyFormat::Plain);
    }

    #[test]
    fn test_review_request() {
        let r = InteractionRequest::review("rev1", "Review Title", "# Markdown body", "plan");
        assert_eq!(r.kind, InteractionKind::FreeText);
        assert!(r.required);
        assert_eq!(r.prompt, "Review Title");
        assert_eq!(r.body.as_deref(), Some("# Markdown body"));
        assert_eq!(r.body_format, BodyFormat::Markdown);
        assert_eq!(r.stage_name, "plan");
    }

    #[test]
    fn test_confirm_request() {
        let r = InteractionRequest::confirm("c1", "Proceed?", "deploy");
        assert_eq!(r.kind, InteractionKind::Confirm);
        assert_eq!(r.options, vec!["Yes", "No"]);
        assert!(r.required);
        assert_eq!(r.stage_name, "deploy");
    }

    #[test]
    fn test_tool_approval_request() {
        let args = serde_json::json!({"file": "test.txt"});
        let r = InteractionRequest::tool_approval("ta1", "write_file", args, "code");
        assert_eq!(r.kind, InteractionKind::ToolApproval);
        assert_eq!(r.tool_name.as_deref(), Some("write_file"));
        assert!(r.tool_arguments.is_some());
        assert_eq!(r.options.len(), 3);
        assert!(r.prompt.contains("write_file"));
    }

    #[test]
    fn test_response_text_empty() {
        let r = InteractionResponse::text("id", "");
        assert_eq!(r.value.as_deref(), Some(""));
        assert!(r.choice_index.is_none());
        assert!(r.approved.is_none());
        assert!(r.scope.is_none());
    }

    #[test]
    fn test_response_approval_denied() {
        let r = InteractionResponse::approval("id", false, ApprovalScope::Once);
        assert_eq!(r.approved, Some(false));
        assert_eq!(r.scope, Some(ApprovalScope::Once));
    }

    #[test]
    fn test_response_approved_true() {
        let r = InteractionResponse::approval("id", true, ApprovalScope::Session);
        assert!(response_approved(&r));
    }

    #[test]
    fn test_response_approved_false() {
        let r = InteractionResponse::approval("id", false, ApprovalScope::Once);
        assert!(!response_approved(&r));
    }

    #[test]
    fn test_response_approved_none() {
        let r = InteractionResponse::text("id", "hello");
        assert!(!response_approved(&r));
    }

    #[test]
    fn test_approval_scope_serde_roundtrip() {
        for scope in [ApprovalScope::Once, ApprovalScope::Session] {
            let json = serde_json::to_string(&scope).unwrap();
            let back: ApprovalScope = serde_json::from_str(&json).unwrap();
            assert_eq!(scope, back);
        }
    }

    #[test]
    fn test_approval_scope_snake_case() {
        let json = serde_json::to_string(&ApprovalScope::Once).unwrap();
        assert_eq!(json, "\"once\"");
        let json = serde_json::to_string(&ApprovalScope::Session).unwrap();
        assert_eq!(json, "\"session\"");
    }

    #[test]
    fn test_interaction_kind_serde_roundtrip() {
        for kind in [
            InteractionKind::FreeText,
            InteractionKind::MultipleChoice,
            InteractionKind::Confirm,
            InteractionKind::ToolApproval,
        ] {
            let json = serde_json::to_string(&kind).unwrap();
            let back: InteractionKind = serde_json::from_str(&json).unwrap();
            assert_eq!(kind, back);
        }
    }

    #[test]
    fn test_body_format_serde_roundtrip() {
        for fmt in [BodyFormat::Plain, BodyFormat::Markdown] {
            let json = serde_json::to_string(&fmt).unwrap();
            let back: BodyFormat = serde_json::from_str(&json).unwrap();
            assert_eq!(fmt, back);
        }
    }

    #[test]
    fn test_body_format_default_is_plain() {
        let fmt = BodyFormat::default();
        assert_eq!(fmt, BodyFormat::Plain);
    }

    #[test]
    fn test_interaction_request_serde_roundtrip() {
        let req = InteractionRequest::tool_approval(
            "serde1",
            "bash",
            serde_json::json!({"cmd": "ls -la"}),
            "code",
        );
        let json = serde_json::to_string(&req).unwrap();
        let back: InteractionRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(back.id, "serde1");
        assert_eq!(back.kind, InteractionKind::ToolApproval);
        assert_eq!(back.tool_name.as_deref(), Some("bash"));
    }

    #[test]
    fn test_interaction_response_serde_roundtrip() {
        let resp = InteractionResponse::approval("serde2", true, ApprovalScope::Session);
        let json = serde_json::to_string(&resp).unwrap();
        let back: InteractionResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(back.request_id, "serde2");
        assert_eq!(back.approved, Some(true));
        assert_eq!(back.scope, Some(ApprovalScope::Session));
    }

    #[test]
    fn test_make_interaction_id_zero() {
        assert_eq!(make_interaction_id(0, 0), "0-0");
    }

    #[test]
    fn test_make_interaction_id_large() {
        assert_eq!(make_interaction_id(999, 1000), "999-1000");
    }

    #[test]
    fn test_response_as_choice_no_choice_index() {
        let opts = vec!["A".to_string(), "B".to_string()];
        let r = InteractionResponse::text("id", "hello");
        assert!(response_as_choice(&r, &opts).is_none());
    }

    #[test]
    fn test_response_as_choice_empty_options() {
        let opts: Vec<String> = vec![];
        let r = InteractionResponse::choice("id", 0);
        assert!(response_as_choice(&r, &opts).is_none());
    }

    #[test]
    fn test_free_text_request_defaults() {
        let r = InteractionRequest::free_text("ft", "prompt", "stage", true);
        assert!(r.body.is_none());
        assert_eq!(r.body_format, BodyFormat::Plain);
        assert!(r.tool_name.is_none());
        assert!(r.tool_arguments.is_none());
        assert!(r.options.is_empty());
    }

    #[test]
    fn test_multiple_choice_request_is_required() {
        let r = InteractionRequest::multiple_choice("mc", "Pick", vec!["A".into()], "stage");
        assert!(r.required);
    }

    #[test]
    fn test_confirm_request_is_required() {
        let r = InteractionRequest::confirm("c", "Sure?", "stage");
        assert!(r.required);
    }

    #[test]
    fn test_tool_approval_is_required() {
        let r = InteractionRequest::tool_approval("ta", "bash", serde_json::json!({}), "stage");
        assert!(r.required);
    }

    #[test]
    fn test_interaction_kind_snake_case_values() {
        assert_eq!(
            serde_json::to_string(&InteractionKind::FreeText).unwrap(),
            "\"free_text\""
        );
        assert_eq!(
            serde_json::to_string(&InteractionKind::MultipleChoice).unwrap(),
            "\"multiple_choice\""
        );
        assert_eq!(
            serde_json::to_string(&InteractionKind::ToolApproval).unwrap(),
            "\"tool_approval\""
        );
        assert_eq!(
            serde_json::to_string(&InteractionKind::Confirm).unwrap(),
            "\"confirm\""
        );
    }

    #[test]
    fn test_body_format_snake_case_values() {
        assert_eq!(
            serde_json::to_string(&BodyFormat::Plain).unwrap(),
            "\"plain\""
        );
        assert_eq!(
            serde_json::to_string(&BodyFormat::Markdown).unwrap(),
            "\"markdown\""
        );
    }

    #[test]
    fn test_request_free_text_serde_roundtrip() {
        let req = InteractionRequest::free_text("ft1", "What?", "main", false);
        let json = serde_json::to_string(&req).unwrap();
        let back: InteractionRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(back.id, "ft1");
        assert_eq!(back.kind, InteractionKind::FreeText);
        assert!(!back.required);
        assert_eq!(back.stage_name, "main");
    }

    #[test]
    fn test_request_multiple_choice_serde_roundtrip() {
        let req = InteractionRequest::multiple_choice(
            "mc1",
            "Choose",
            vec!["A".into(), "B".into(), "C".into()],
            "plan",
        );
        let json = serde_json::to_string(&req).unwrap();
        let back: InteractionRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(back.kind, InteractionKind::MultipleChoice);
        assert_eq!(back.options.len(), 3);
        assert_eq!(back.options[2], "C");
    }

    #[test]
    fn test_request_confirm_serde_roundtrip() {
        let req = InteractionRequest::confirm("c1", "Proceed?", "deploy");
        let json = serde_json::to_string(&req).unwrap();
        let back: InteractionRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(back.kind, InteractionKind::Confirm);
        assert_eq!(back.options, vec!["Yes", "No"]);
    }

    #[test]
    fn test_request_review_serde_roundtrip() {
        let req = InteractionRequest::review("rev1", "Title", "# Body\ntext", "review");
        let json = serde_json::to_string(&req).unwrap();
        let back: InteractionRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(back.body_format, BodyFormat::Markdown);
        assert_eq!(back.body.as_deref(), Some("# Body\ntext"));
    }

    #[test]
    fn test_response_text_serde_roundtrip() {
        let resp = InteractionResponse::text("t1", "my answer");
        let json = serde_json::to_string(&resp).unwrap();
        let back: InteractionResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(back.request_id, "t1");
        assert_eq!(back.value.as_deref(), Some("my answer"));
        assert!(back.choice_index.is_none());
        assert!(back.approved.is_none());
        assert!(back.scope.is_none());
    }

    #[test]
    fn test_response_choice_serde_roundtrip() {
        let resp = InteractionResponse::choice("c1", 2);
        let json = serde_json::to_string(&resp).unwrap();
        let back: InteractionResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(back.choice_index, Some(2));
        assert!(back.value.is_none());
    }

    #[test]
    fn test_response_approval_serde_roundtrip() {
        let resp = InteractionResponse::approval("a1", false, ApprovalScope::Session);
        let json = serde_json::to_string(&resp).unwrap();
        let back: InteractionResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(back.approved, Some(false));
        assert_eq!(back.scope, Some(ApprovalScope::Session));
    }

    #[test]
    fn test_response_as_text_with_value() {
        let r = InteractionResponse::text("id", "some text value");
        assert_eq!(response_as_text(&r), "some text value");
    }

    #[test]
    fn test_response_approved_session_scope() {
        let r = InteractionResponse::approval("id", true, ApprovalScope::Session);
        assert!(response_approved(&r));
        assert_eq!(r.scope, Some(ApprovalScope::Session));
    }

    #[test]
    fn test_make_interaction_id_various() {
        assert_eq!(make_interaction_id(1, 2), "1-2");
        assert_eq!(make_interaction_id(10, 20), "10-20");
    }

    #[test]
    fn test_default_true_via_serde_missing_required_field() {
        // JSON without `required` - should default to true via default_true()
        let json = r#"{
            "id": "dt1",
            "kind": "free_text",
            "prompt": "test prompt",
            "stage_name": "stage"
        }"#;
        let req: InteractionRequest = serde_json::from_str(json).unwrap();
        assert!(req.required);
    }
}