async-llm 0.9.0

Async Rust client for LLM APIs - Anthropic Messages API today; fork of async-anthropic with thinking-block and prompt-cache support.
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
use axum::{
    extract::{Path, State},
    http::{HeaderMap, StatusCode},
    response::sse::{Event, Sse},
    routing::{get, post},
    Json, Router,
};
use futures::{stream::BoxStream, StreamExt};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, convert::Infallible, net::SocketAddr, sync::Arc};
use tokio::{net::TcpListener, sync::Notify};

/// A queued response variant.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum MockResponse {
    Text {
        content: String,
    },
    ToolCall {
        name: String,
        input: serde_json::Value,
    },
    /// Several tool calls in one assistant message — parallel tool use, which is
    /// how a model asks two questions at once.
    ToolCalls {
        calls: Vec<(String, serde_json::Value)>,
    },
    /// `status` is used as the HTTP status code when returned as a plain JSON response,
    /// and as an SSE StreamError when returned in streaming mode.
    Error {
        status: u16,
        message: String,
    },
    TextStream {
        chunks: Vec<String>,
    },
    ToolCallStream {
        name: String,
        id: String,
        input: serde_json::Value,
    },
    Thinking {
        text: String,
        signature: String,
    },
    /// A response cut off by the output-token ceiling: `stop_reason: max_tokens`
    /// on the Anthropic wire, `finish_reason: length` on the OpenAI wire.
    Truncated {
        content: String,
    },
    /// A reasoning-model turn: a reasoning trace, then the answer. On the OpenAI
    /// wire the trace streams as `delta.reasoning_content` (DeepSeek/vLLM shape)
    /// before the content; the Anthropic wire renders only the answer text
    /// (reasoning on that wire is the `Thinking` variant).
    Reasoning {
        reasoning: String,
        content: String,
    },
    /// A stream that ends after `after` events without its terminal frame — the
    /// connection dropped mid-response. Reproduces #61 item 1.
    CutStream {
        chunks: Vec<String>,
        after: usize,
    },
    /// A tool call whose arguments are cut off mid-JSON, with no terminal frame.
    /// `partial_input_json` is emitted verbatim and is expected not to parse.
    CutToolCallStream {
        name: String,
        id: String,
        partial_input_json: String,
    },
}

pub(crate) struct QueueEntry {
    pub(crate) response: MockResponse,
    pub(crate) reached: Option<Arc<Notify>>,
    pub(crate) gate: Option<Arc<Notify>>,
    /// Held for this long before answering — a slow peer. With no client-side
    /// timeout this is indistinguishable from a hang (#61 item 5).
    pub(crate) delay: Option<std::time::Duration>,
}

impl QueueEntry {
    fn immediate(response: MockResponse) -> Self {
        Self {
            response,
            reached: None,
            gate: None,
            delay: None,
        }
    }
}

pub struct BlockHandle {
    gate: Arc<Notify>,
    reached: Arc<Notify>,
}

impl BlockHandle {
    pub async fn wait_until_received(&self) {
        self.reached.notified().await;
    }
    pub fn release(&self) {
        self.gate.notify_one();
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Scenario {
    #[serde(default)]
    pub description: String,
    pub responses: Vec<MockResponse>,
}

struct ScenarioState {
    responses: Vec<MockResponse>,
    cursor: usize,
}

impl ScenarioState {
    fn from_scenario(s: &Scenario) -> Self {
        Self {
            responses: s.responses.clone(),
            cursor: 0,
        }
    }
    fn next_response(&mut self) -> Option<MockResponse> {
        let resp = self.responses.get(self.cursor)?.clone();
        self.cursor += 1;
        Some(resp)
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ScenarioConfig {
    pub scenarios: HashMap<String, Scenario>,
}

#[derive(Default)]
pub(crate) struct MockState {
    queue: Mutex<Vec<QueueEntry>>,
    scenarios: Mutex<HashMap<String, Scenario>>,
    session_bindings: Mutex<HashMap<String, String>>,
    session_states: Mutex<HashMap<String, ScenarioState>>,
    /// Every inbound request body (both wires), for tests that assert on what
    /// reached the agent (e.g. the composed system prompt). Cleared by `/reset`.
    captured: Mutex<Vec<serde_json::Value>>,
    /// A one-shot hold applied to the next answer out of the queue, however it
    /// was queued. Set by `/reset` so it covers a test's *first* answer without
    /// the test having to know which queued entry that turns out to be.
    ///
    /// It exists because an instant provider is the unrealistic case: a real
    /// one takes hundreds of milliseconds to a first token, and a session's
    /// first turn starts with the session, before any browser has finished
    /// navigating to it. Answering with zero latency lets a whole turn happen
    /// in a window no client could have been watching.
    hold_next: Mutex<Option<std::time::Duration>>,
}

impl MockState {
    pub(crate) fn dequeue_entry(&self) -> Option<QueueEntry> {
        let mut entry = {
            let mut q = self.queue.lock();
            (!q.is_empty()).then(|| q.remove(0))
        }?;
        // The hold is spent on whichever answer comes first, and only once —
        // later turns in the same test run at full speed.
        if let Some(hold) = self.hold_next.lock().take() {
            if entry.delay.is_none() {
                entry.delay = Some(hold);
            }
        }
        Some(entry)
    }
    /// Record an inbound request body so `GET /received` can return it.
    pub(crate) fn capture(&self, body: serde_json::Value) {
        self.captured.lock().push(body);
    }
}

#[derive(Default)]
pub struct MockLlmServerBuilder {
    responses: Vec<MockResponse>,
    scenarios: HashMap<String, Scenario>,
    bind_all: bool,
    port: Option<u16>,
}

impl MockLlmServerBuilder {
    #[must_use]
    pub fn response(mut self, text: impl Into<String>) -> Self {
        self.responses.push(MockResponse::Text {
            content: text.into(),
        });
        self
    }
    #[must_use]
    pub fn tool_call(mut self, name: impl Into<String>, input: serde_json::Value) -> Self {
        self.responses.push(MockResponse::ToolCall {
            name: name.into(),
            input,
        });
        self
    }
    #[must_use]
    pub fn error(mut self, status: u16, message: impl Into<String>) -> Self {
        self.responses.push(MockResponse::Error {
            status,
            message: message.into(),
        });
        self
    }
    #[must_use]
    pub fn response_stream(mut self, chunks: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.responses.push(MockResponse::TextStream {
            chunks: chunks.into_iter().map(Into::into).collect(),
        });
        self
    }
    #[must_use]
    pub fn tool_call_stream(mut self, name: impl Into<String>, input: serde_json::Value) -> Self {
        self.responses.push(MockResponse::ToolCallStream {
            name: name.into(),
            id: format!("toolu_{}", uuid::Uuid::new_v4()),
            input,
        });
        self
    }
    #[must_use]
    pub fn thinking(mut self, text: impl Into<String>, signature: impl Into<String>) -> Self {
        self.responses.push(MockResponse::Thinking {
            text: text.into(),
            signature: signature.into(),
        });
        self
    }
    #[must_use]
    pub fn with_scenarios(mut self, config: ScenarioConfig) -> Self {
        self.scenarios = config.scenarios;
        self
    }
    #[must_use]
    pub fn bind_all_interfaces(mut self) -> Self {
        self.bind_all = true;
        self
    }
    #[must_use]
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }
    pub async fn build(self) -> MockLlmServer {
        let queue = self
            .responses
            .into_iter()
            .map(QueueEntry::immediate)
            .collect();
        let state = Arc::new(MockState {
            queue: Mutex::new(queue),
            scenarios: Mutex::new(self.scenarios),
            session_bindings: Mutex::new(HashMap::new()),
            session_states: Mutex::new(HashMap::new()),
            captured: Mutex::new(Vec::new()),
            hold_next: Mutex::new(None),
        });
        let app = Router::new()
            .route(
                "/v1/messages",
                post(crate::mock::anthropic::handle_messages),
            )
            .route(
                "/v1/chat/completions",
                post(crate::mock::openai::handle_chat_completions),
            )
            // Both spellings: a provider configured with a bare host reaches
            // `/responses`, one configured api.openai.com-style reaches
            // `/v1/responses`.
            .route("/responses", post(crate::mock::responses::handle_responses))
            .route(
                "/v1/responses",
                post(crate::mock::responses::handle_responses),
            )
            .route("/queue", post(handle_queue))
            .route("/received", get(handle_received))
            .route("/reset", post(handle_reset))
            .route("/scenarios/load", post(handle_load_scenarios))
            .route("/scenarios", get(handle_list_scenarios))
            .route(
                "/scenarios/{name}/register/{session_id}",
                post(handle_register_session),
            )
            .with_state(state.clone());
        let port = self.port.unwrap_or(0);
        let bind = if self.bind_all {
            format!("0.0.0.0:{port}")
        } else {
            format!("127.0.0.1:{port}")
        };
        let listener = TcpListener::bind(&bind).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let handle = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        MockLlmServer {
            addr,
            _handle: handle,
            state,
        }
    }
}

pub struct MockLlmServer {
    addr: SocketAddr,
    _handle: tokio::task::JoinHandle<()>,
    state: Arc<MockState>,
}

impl MockLlmServer {
    #[must_use]
    pub fn builder() -> MockLlmServerBuilder {
        MockLlmServerBuilder::default()
    }
    #[must_use]
    pub fn url(&self) -> String {
        format!("http://{}", self.addr)
    }
    #[must_use]
    pub fn port(&self) -> u16 {
        self.addr.port()
    }
    pub fn queued_count(&self) -> usize {
        self.state.queue.lock().len()
    }
    pub fn queue_response(&self, text: impl Into<String>) {
        self.state
            .queue
            .lock()
            .push(QueueEntry::immediate(MockResponse::Text {
                content: text.into(),
            }));
    }
    /// Queue one assistant message that makes several tool calls at once.
    pub fn queue_tool_calls(&self, calls: Vec<(String, serde_json::Value)>) {
        self.state
            .queue
            .lock()
            .push(QueueEntry::immediate(MockResponse::ToolCalls { calls }));
    }

    pub fn queue_tool_call(&self, name: impl Into<String>, input: serde_json::Value) {
        self.state
            .queue
            .lock()
            .push(QueueEntry::immediate(MockResponse::ToolCall {
                name: name.into(),
                input,
            }));
    }
    /// Queue an error response. On the Anthropic wire this becomes an SSE error
    /// event whose type is derived from `status`; on the OpenAI wire it becomes
    /// a real HTTP error status, which is how those backends signal failure.
    pub fn queue_error(&self, status: u16, message: impl Into<String>) {
        self.state
            .queue
            .lock()
            .push(QueueEntry::immediate(MockResponse::Error {
                status,
                message: message.into(),
            }));
    }
    /// Queue a response the backend cut off at its output-token ceiling.
    pub fn queue_truncated(&self, content: impl Into<String>) {
        self.state
            .queue
            .lock()
            .push(QueueEntry::immediate(MockResponse::Truncated {
                content: content.into(),
            }));
    }
    /// Queue a text response the server holds for `delay` before answering.
    pub fn queue_delayed(&self, text: impl Into<String>, delay: std::time::Duration) {
        self.state.queue.lock().push(QueueEntry {
            response: MockResponse::Text {
                content: text.into(),
            },
            reached: None,
            gate: None,
            delay: Some(delay),
        });
    }

    /// Queue a text stream cut off after `after` SSE events, with no terminal
    /// frame — a connection dropped mid-response.
    pub fn queue_cut_stream(
        &self,
        chunks: impl IntoIterator<Item = impl Into<String>>,
        after: usize,
    ) {
        self.state
            .queue
            .lock()
            .push(QueueEntry::immediate(MockResponse::CutStream {
                chunks: chunks.into_iter().map(Into::into).collect(),
                after,
            }));
    }

    /// Queue a tool call whose arguments are cut off mid-JSON.
    pub fn queue_cut_tool_call(
        &self,
        name: impl Into<String>,
        id: impl Into<String>,
        partial_input_json: impl Into<String>,
    ) {
        self.state
            .queue
            .lock()
            .push(QueueEntry::immediate(MockResponse::CutToolCallStream {
                name: name.into(),
                id: id.into(),
                partial_input_json: partial_input_json.into(),
            }));
    }

    /// Queue a reasoning-model turn: a reasoning trace, then the answer.
    pub fn queue_reasoning(&self, reasoning: impl Into<String>, content: impl Into<String>) {
        self.state
            .queue
            .lock()
            .push(QueueEntry::immediate(MockResponse::Reasoning {
                reasoning: reasoning.into(),
                content: content.into(),
            }));
    }
    pub fn blocking_response(&self, text: impl Into<String>) -> BlockHandle {
        let gate = Arc::new(Notify::new());
        let reached = Arc::new(Notify::new());
        self.state.queue.lock().push(QueueEntry {
            response: MockResponse::Text {
                content: text.into(),
            },
            reached: Some(Arc::clone(&reached)),
            gate: Some(Arc::clone(&gate)),
            delay: None,
        });
        BlockHandle { gate, reached }
    }
    pub fn load_scenarios(&self, config: ScenarioConfig) {
        self.state.scenarios.lock().extend(config.scenarios);
    }
    pub fn register_session(
        &self,
        session_id: impl Into<String>,
        scenario_name: impl Into<String>,
    ) {
        let session_id = session_id.into();
        let scenario_name = scenario_name.into();
        let scenarios = self.state.scenarios.lock();
        if let Some(scenario) = scenarios.get(&scenario_name) {
            let state = ScenarioState::from_scenario(scenario);
            drop(scenarios);
            self.state
                .session_states
                .lock()
                .insert(session_id.clone(), state);
            self.state
                .session_bindings
                .lock()
                .insert(session_id, scenario_name);
        }
    }
}

// ── internal request/response types ──────────────────────────────────────────

#[derive(Serialize)]
struct StatusResponse {
    status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    message: Option<String>,
}

#[derive(Serialize)]
struct ScenariosListResponse {
    scenarios: Vec<String>,
}

pub(crate) enum ResponseKind {
    Json(axum::Json<serde_json::Value>),
    Sse(Sse<BoxStream<'static, Result<Event, Infallible>>>),
    HttpError(StatusCode, axum::Json<serde_json::Value>),
}

impl axum::response::IntoResponse for ResponseKind {
    fn into_response(self) -> axum::response::Response {
        match self {
            ResponseKind::Json(j) => j.into_response(),
            ResponseKind::Sse(s) => s.into_response(),
            ResponseKind::HttpError(status, body) => (status, body).into_response(),
        }
    }
}

// ── handlers ─────────────────────────────────────────────────────────────────

pub(crate) async fn handle_messages(
    State(state): State<Arc<MockState>>,
    headers: HeaderMap,
    Json(req): Json<serde_json::Value>,
) -> ResponseKind {
    state.capture(req.clone());
    let entry = if let Some(sid) = headers.get("X-Session-Id").and_then(|v| v.to_str().ok()) {
        let mut ss = state.session_states.lock();
        if let Some(scenario) = ss.get_mut(sid) {
            scenario.next_response().map(QueueEntry::immediate)
        } else {
            state.dequeue_entry()
        }
    } else {
        state.dequeue_entry()
    };

    if let Some(e) = &entry {
        if let Some(r) = &e.reached {
            r.notify_one();
        }
        if let Some(g) = &e.gate {
            g.notified().await;
        }
        if let Some(d) = e.delay {
            tokio::time::sleep(d).await;
        }
    }

    let response = entry.map(|e| e.response);
    let is_stream = req
        .get("stream")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);

    match response {
        Some(MockResponse::TextStream { chunks }) => sse_from_pairs(text_stream_sse(&chunks)),
        Some(MockResponse::ToolCallStream { name, id, input }) => {
            sse_from_pairs(tool_call_stream_sse(&name, &id, &input))
        }
        Some(MockResponse::CutStream { chunks, after }) => {
            sse_from_pairs(cut_text_stream_sse(&chunks, after))
        }
        Some(MockResponse::CutToolCallStream {
            name,
            id,
            partial_input_json,
        }) => sse_from_pairs(cut_tool_call_stream_sse(&name, &id, &partial_input_json)),
        other => {
            let resp = other;
            if is_stream {
                let msg_id = format!("msg_{}", uuid::Uuid::new_v4());
                let tool_id = format!("toolu_{}", uuid::Uuid::new_v4());
                let pairs = match resp {
                    Some(MockResponse::Text { content }) => text_sse(&msg_id, &content),
                    Some(MockResponse::ToolCall { name, input }) => {
                        tool_sse(&msg_id, &tool_id, &name, &input)
                    }
                    Some(MockResponse::ToolCalls { calls }) => tools_sse(&msg_id, &calls),
                    Some(MockResponse::Thinking { text, signature }) => {
                        thinking_sse(&msg_id, &text, &signature)
                    }
                    Some(MockResponse::Truncated { content }) => truncated_sse(&msg_id, &content),
                    // Reasoning is an OpenAI-wire concept; here render just the answer.
                    Some(MockResponse::Reasoning { content, .. }) => text_sse(&msg_id, &content),
                    // Error in stream mode: emit a StreamError-compatible SSE event so
                    // async-anthropic parses it as AnthropicError::StreamError. The
                    // error `type` is derived from `status` so tests can choose a
                    // retryable (`overloaded_error`/`rate_limit_error`) or a
                    // non-retryable (`invalid_request_error`) failure deterministically.
                    Some(MockResponse::Error { status, message }) => {
                        let etype = match status {
                            429 => "rate_limit_error",
                            529 => "overloaded_error",
                            _ => "invalid_request_error",
                        };
                        vec![(
                            "error".into(),
                            // Top-level "type" + "message" matches async-anthropic's StreamError shape.
                            serde_json::json!({ "type": etype, "message": message }).to_string(),
                        )]
                    }
                    None => text_sse(&msg_id, "No mock response queued"),
                    Some(
                        MockResponse::TextStream { .. }
                        | MockResponse::ToolCallStream { .. }
                        | MockResponse::CutStream { .. }
                        | MockResponse::CutToolCallStream { .. },
                    ) => {
                        unreachable!()
                    }
                };
                sse_from_pairs(pairs)
            } else {
                match resp {
                    Some(MockResponse::Text { content }) => {
                        ResponseKind::Json(axum::Json(text_json(&content)))
                    }
                    Some(MockResponse::ToolCall { name, input }) => {
                        ResponseKind::Json(axum::Json(tool_json(&name, &input)))
                    }
                    Some(MockResponse::ToolCalls { calls }) => {
                        ResponseKind::Json(axum::Json(tools_json(&calls)))
                    }
                    Some(MockResponse::Thinking { text, signature }) => {
                        ResponseKind::Json(axum::Json(thinking_json(&text, &signature)))
                    }
                    Some(MockResponse::Truncated { content }) => {
                        ResponseKind::Json(axum::Json(text_json(&content)))
                    }
                    Some(MockResponse::Reasoning { content, .. }) => {
                        ResponseKind::Json(axum::Json(text_json(&content)))
                    }
                    Some(MockResponse::Error { status, message }) => {
                        let code = StatusCode::from_u16(status)
                            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                        ResponseKind::HttpError(code, axum::Json(error_json(&message)))
                    }
                    None => ResponseKind::Json(axum::Json(text_json("No mock response queued"))),
                    Some(
                        MockResponse::TextStream { .. }
                        | MockResponse::ToolCallStream { .. }
                        | MockResponse::CutStream { .. }
                        | MockResponse::CutToolCallStream { .. },
                    ) => {
                        unreachable!()
                    }
                }
            }
        }
    }
}

/// Append one response to the FIFO queue. The body is a full [`MockResponse`]
/// (tagged `type`, snake_case), so every variant is expressible over HTTP:
/// `{"type":"text","content":…}`, `{"type":"text_stream","chunks":[…]}`,
/// `{"type":"tool_call","name":…,"input":…}`, `{"type":"error","status":…,
/// "message":…}`, `{"type":"thinking","text":…,"signature":…}`.
///
/// An optional `"delayMs"` alongside those fields holds the answer back before
/// sending it — the HTTP face of the `delay` every queue entry already has, and
/// the only way an out-of-process test can make a turn *observably* in flight.
/// A browser test that means to watch a turn happen needs the turn to still be
/// happening when it looks.
async fn handle_queue(
    State(state): State<Arc<MockState>>,
    Json(body): Json<serde_json::Value>,
) -> Json<StatusResponse> {
    let delay = body
        .get("delayMs")
        .and_then(serde_json::Value::as_u64)
        .map(std::time::Duration::from_millis);
    let response: MockResponse = match serde_json::from_value(body) {
        Ok(r) => r,
        Err(e) => {
            return Json(StatusResponse {
                status: "error".into(),
                message: Some(e.to_string()),
            });
        }
    };
    state.queue.lock().push(QueueEntry {
        response,
        reached: None,
        gate: None,
        delay,
    });
    Json(StatusResponse {
        status: "queued".into(),
        message: None,
    })
}

/// Clear all per-test state: the FIFO queue and any per-session scenario
/// cursors/bindings. Loaded scenario definitions are left intact. Tests call
/// this before each case so nothing leaks across the serially-run suite.
async fn handle_reset(
    State(state): State<Arc<MockState>>,
    body: Option<Json<serde_json::Value>>,
) -> Json<StatusResponse> {
    state.queue.lock().clear();
    state.session_states.lock().clear();
    state.session_bindings.lock().clear();
    state.captured.lock().clear();
    // `holdFirstMs` arms a one-shot delay on this test's first answer. See
    // `MockState::hold_next` for why a zero-latency provider is the case worth
    // avoiding rather than the case worth defaulting to.
    *state.hold_next.lock() = body
        .and_then(|Json(b)| b.get("holdFirstMs").and_then(serde_json::Value::as_u64))
        .map(std::time::Duration::from_millis);
    Json(StatusResponse {
        status: "reset".into(),
        message: None,
    })
}

/// Return every captured request body, most-recent-first, so a test can assert
/// on what reached the agent (e.g. the composed system prompt).
async fn handle_received(State(state): State<Arc<MockState>>) -> Json<Vec<serde_json::Value>> {
    let mut bodies = state.captured.lock().clone();
    bodies.reverse();
    Json(bodies)
}

async fn handle_load_scenarios(
    State(state): State<Arc<MockState>>,
    Json(config): Json<ScenarioConfig>,
) -> Json<StatusResponse> {
    let count = config.scenarios.len();
    state.scenarios.lock().extend(config.scenarios);
    Json(StatusResponse {
        status: "loaded".into(),
        message: Some(format!("{count} scenarios loaded")),
    })
}

async fn handle_list_scenarios(State(state): State<Arc<MockState>>) -> Json<ScenariosListResponse> {
    let scenarios = state.scenarios.lock();
    Json(ScenariosListResponse {
        scenarios: scenarios.keys().cloned().collect(),
    })
}

async fn handle_register_session(
    State(state): State<Arc<MockState>>,
    Path((scenario_name, session_id)): Path<(String, String)>,
) -> Result<Json<StatusResponse>, (StatusCode, Json<StatusResponse>)> {
    let scenarios = state.scenarios.lock();
    if let Some(scenario) = scenarios.get(&scenario_name) {
        let scenario_state = ScenarioState::from_scenario(scenario);
        drop(scenarios);
        state
            .session_states
            .lock()
            .insert(session_id.clone(), scenario_state);
        state
            .session_bindings
            .lock()
            .insert(session_id.clone(), scenario_name.clone());
        Ok(Json(StatusResponse {
            status: "registered".into(),
            message: Some(format!(
                "Session {session_id} bound to scenario {scenario_name}"
            )),
        }))
    } else {
        Err((
            StatusCode::NOT_FOUND,
            Json(StatusResponse {
                status: "error".into(),
                message: Some(format!("Scenario '{scenario_name}' not found")),
            }),
        ))
    }
}

// ── SSE helpers ───────────────────────────────────────────────────────────────

pub(crate) fn sse_from_pairs(pairs: Vec<(String, String)>) -> ResponseKind {
    let events: Vec<Result<Event, Infallible>> = pairs
        .into_iter()
        .map(|(t, d)| Ok(Event::default().event(t).data(d)))
        .collect();
    ResponseKind::Sse(Sse::new(futures::stream::iter(events).boxed()))
}

fn text_sse(msg_id: &str, text: &str) -> Vec<(String, String)> {
    let tokens = u32::try_from(text.len() / 4).unwrap_or(u32::MAX);
    vec![
        (
            "message_start".into(),
            serde_json::json!({"type":"message_start","message":{"id":msg_id,"type":"message","role":"assistant","content":[],"model":"mock-model","stop_reason":null,"usage":{"input_tokens":10,"output_tokens":1}}}).to_string(),
        ),
        (
            "content_block_start".into(),
            serde_json::json!({"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}).to_string(),
        ),
        (
            "content_block_delta".into(),
            serde_json::json!({"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":text}}).to_string(),
        ),
        (
            "content_block_stop".into(),
            serde_json::json!({"type":"content_block_stop","index":0}).to_string(),
        ),
        (
            "message_delta".into(),
            serde_json::json!({"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":tokens}}).to_string(),
        ),
        (
            "message_stop".into(),
            serde_json::json!({"type":"message_stop"}).to_string(),
        ),
    ]
}

/// Like [`text_sse`], but the turn ends with `stop_reason: max_tokens` — the
/// backend hit its output ceiling mid-answer.
fn truncated_sse(msg_id: &str, text: &str) -> Vec<(String, String)> {
    let mut pairs = text_sse(msg_id, text);
    for (event, data) in &mut pairs {
        if event == "message_delta" {
            *data = serde_json::json!({
                "type": "message_delta",
                "delta": {"stop_reason": "max_tokens", "stop_sequence": null},
                "usage": {"output_tokens": 5}
            })
            .to_string();
        }
    }
    pairs
}

fn tool_sse(
    msg_id: &str,
    tool_id: &str,
    name: &str,
    input: &serde_json::Value,
) -> Vec<(String, String)> {
    let input_str = serde_json::to_string(input).unwrap_or_default();
    vec![
        (
            "message_start".into(),
            serde_json::json!({"type":"message_start","message":{"id":msg_id,"type":"message","role":"assistant","content":[],"model":"mock-model","stop_reason":null,"usage":{"input_tokens":10,"output_tokens":1}}}).to_string(),
        ),
        (
            "content_block_start".into(),
            serde_json::json!({"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":tool_id,"name":name,"input":{}}}).to_string(),
        ),
        (
            "content_block_delta".into(),
            serde_json::json!({"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":input_str}}).to_string(),
        ),
        (
            "content_block_stop".into(),
            serde_json::json!({"type":"content_block_stop","index":0}).to_string(),
        ),
        (
            "message_delta".into(),
            serde_json::json!({"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":20}}).to_string(),
        ),
        (
            "message_stop".into(),
            serde_json::json!({"type":"message_stop"}).to_string(),
        ),
    ]
}

/// One assistant message carrying several `tool_use` blocks, each its own
/// content-block index — the shape a provider streams for parallel tool use.
fn tools_sse(msg_id: &str, calls: &[(String, serde_json::Value)]) -> Vec<(String, String)> {
    let mut out = vec![(
        "message_start".to_string(),
        serde_json::json!({"type":"message_start","message":{"id":msg_id,"type":"message","role":"assistant","content":[],"model":"mock-model","stop_reason":null,"usage":{"input_tokens":10,"output_tokens":1}}}).to_string(),
    )];
    for (index, (name, input)) in calls.iter().enumerate() {
        let tool_id = format!("toolu_{}", uuid::Uuid::new_v4());
        let input_str = serde_json::to_string(input).unwrap_or_default();
        out.push((
            "content_block_start".to_string(),
            serde_json::json!({"type":"content_block_start","index":index,"content_block":{"type":"tool_use","id":tool_id,"name":name,"input":{}}}).to_string(),
        ));
        out.push((
            "content_block_delta".to_string(),
            serde_json::json!({"type":"content_block_delta","index":index,"delta":{"type":"input_json_delta","partial_json":input_str}}).to_string(),
        ));
        out.push((
            "content_block_stop".to_string(),
            serde_json::json!({"type":"content_block_stop","index":index}).to_string(),
        ));
    }
    out.push((
        "message_delta".to_string(),
        serde_json::json!({"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":20}}).to_string(),
    ));
    out.push((
        "message_stop".to_string(),
        serde_json::json!({"type":"message_stop"}).to_string(),
    ));
    out
}

fn thinking_sse(msg_id: &str, text: &str, signature: &str) -> Vec<(String, String)> {
    vec![
        (
            "message_start".into(),
            serde_json::json!({"type":"message_start","message":{"id":msg_id,"type":"message","role":"assistant","content":[],"model":"mock-model","stop_reason":null,"usage":{"input_tokens":10,"output_tokens":1}}}).to_string(),
        ),
        (
            "content_block_start".into(),
            serde_json::json!({"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}).to_string(),
        ),
        (
            "content_block_delta".into(),
            serde_json::json!({"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":text}}).to_string(),
        ),
        (
            "content_block_delta".into(),
            serde_json::json!({"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":signature}}).to_string(),
        ),
        (
            "content_block_stop".into(),
            serde_json::json!({"type":"content_block_stop","index":0}).to_string(),
        ),
        (
            "message_delta".into(),
            serde_json::json!({"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":5}}).to_string(),
        ),
        (
            "message_stop".into(),
            serde_json::json!({"type":"message_stop"}).to_string(),
        ),
    ]
}

fn text_stream_sse(chunks: &[String]) -> Vec<(String, String)> {
    let msg_id = format!("msg_{}", uuid::Uuid::new_v4());
    let mut events = vec![
        (
            "message_start".into(),
            serde_json::json!({"type":"message_start","message":{"id":msg_id,"type":"message","role":"assistant","content":[],"model":"mock-model","stop_reason":null,"usage":{"input_tokens":10,"output_tokens":0}}}).to_string(),
        ),
        (
            "content_block_start".into(),
            serde_json::json!({"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}).to_string(),
        ),
    ];
    for chunk in chunks {
        events.push((
            "content_block_delta".into(),
            serde_json::json!({"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":chunk}}).to_string(),
        ));
    }
    events.push((
        "content_block_stop".into(),
        serde_json::json!({"type":"content_block_stop","index":0}).to_string(),
    ));
    events.push((
        "message_delta".into(),
        serde_json::json!({"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":chunks.len()}}).to_string(),
    ));
    events.push((
        "message_stop".into(),
        serde_json::json!({"type":"message_stop"}).to_string(),
    ));
    events
}

/// The opening frames plus `after` text deltas, and nothing else: no
/// `content_block_stop`, no `message_delta`, no `message_stop`.
fn cut_text_stream_sse(chunks: &[String], after: usize) -> Vec<(String, String)> {
    let msg_id = format!("msg_{}", uuid::Uuid::new_v4());
    let mut events = vec![
        (
            "message_start".into(),
            serde_json::json!({"type":"message_start","message":{"id":msg_id,"type":"message","role":"assistant","content":[],"model":"mock-model","stop_reason":null,"usage":{"input_tokens":10,"output_tokens":0}}}).to_string(),
        ),
        (
            "content_block_start".into(),
            serde_json::json!({"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}).to_string(),
        ),
    ];
    for chunk in chunks.iter().take(after) {
        events.push((
            "content_block_delta".into(),
            serde_json::json!({"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":chunk}}).to_string(),
        ));
    }
    events
}

/// A tool_use block whose `input_json_delta` is truncated mid-JSON, with no
/// `content_block_stop`, no `message_delta` and no `message_stop`.
fn cut_tool_call_stream_sse(name: &str, id: &str, partial: &str) -> Vec<(String, String)> {
    let msg_id = format!("msg_{}", uuid::Uuid::new_v4());
    vec![
        (
            "message_start".into(),
            serde_json::json!({"type":"message_start","message":{"id":msg_id,"type":"message","role":"assistant","content":[],"model":"mock-model","stop_reason":null,"usage":{"input_tokens":10,"output_tokens":0}}}).to_string(),
        ),
        (
            "content_block_start".into(),
            serde_json::json!({"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":id,"name":name,"input":{}}}).to_string(),
        ),
        (
            "content_block_delta".into(),
            serde_json::json!({"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":partial}}).to_string(),
        ),
    ]
}

fn tool_call_stream_sse(name: &str, id: &str, input: &serde_json::Value) -> Vec<(String, String)> {
    let msg_id = format!("msg_{}", uuid::Uuid::new_v4());
    let input_str = input.to_string();
    let fragments: Vec<String> = input_str
        .as_bytes()
        .chunks(10)
        .map(|c| String::from_utf8_lossy(c).to_string())
        .collect();
    let mut events = vec![
        (
            "message_start".into(),
            serde_json::json!({"type":"message_start","message":{"id":msg_id,"type":"message","role":"assistant","content":[],"model":"mock-model","stop_reason":null,"usage":{"input_tokens":10,"output_tokens":0}}}).to_string(),
        ),
        (
            "content_block_start".into(),
            serde_json::json!({"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":id,"name":name,"input":{}}}).to_string(),
        ),
    ];
    for frag in &fragments {
        events.push((
            "content_block_delta".into(),
            serde_json::json!({"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":frag}}).to_string(),
        ));
    }
    events.push((
        "content_block_stop".into(),
        serde_json::json!({"type":"content_block_stop","index":0}).to_string(),
    ));
    events.push((
        "message_delta".into(),
        serde_json::json!({"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":20}}).to_string(),
    ));
    events.push((
        "message_stop".into(),
        serde_json::json!({"type":"message_stop"}).to_string(),
    ));
    events
}

// ── JSON response helpers ─────────────────────────────────────────────────────

fn text_json(text: &str) -> serde_json::Value {
    serde_json::json!({
        "type": "message",
        "id": format!("msg_{}", uuid::Uuid::new_v4()),
        "role": "assistant",
        "content": [{"type": "text", "text": text}],
        "model": "mock-model",
        "stop_reason": "end_turn",
        "usage": {"input_tokens": 10, "output_tokens": text.len() / 4}
    })
}

fn tool_json(name: &str, input: &serde_json::Value) -> serde_json::Value {
    serde_json::json!({
        "type": "message",
        "id": format!("msg_{}", uuid::Uuid::new_v4()),
        "role": "assistant",
        "content": [{"type": "tool_use", "id": format!("toolu_{}", uuid::Uuid::new_v4()), "name": name, "input": input}],
        "model": "mock-model",
        "stop_reason": "tool_use",
        "usage": {"input_tokens": 10, "output_tokens": 20}
    })
}

fn tools_json(calls: &[(String, serde_json::Value)]) -> serde_json::Value {
    let content: Vec<serde_json::Value> = calls
        .iter()
        .map(|(name, input)| {
            serde_json::json!({"type": "tool_use", "id": format!("toolu_{}", uuid::Uuid::new_v4()), "name": name, "input": input})
        })
        .collect();
    serde_json::json!({
        "type": "message",
        "id": format!("msg_{}", uuid::Uuid::new_v4()),
        "role": "assistant",
        "content": content,
        "model": "mock-model",
        "stop_reason": "tool_use",
        "usage": {"input_tokens": 10, "output_tokens": 20}
    })
}

fn thinking_json(text: &str, signature: &str) -> serde_json::Value {
    serde_json::json!({
        "type": "message",
        "id": format!("msg_{}", uuid::Uuid::new_v4()),
        "role": "assistant",
        "content": [{"type": "thinking", "thinking": text, "signature": signature}],
        "model": "mock-model",
        "stop_reason": "end_turn",
        "usage": {"input_tokens": 10, "output_tokens": 5}
    })
}

fn error_json(message: &str) -> serde_json::Value {
    serde_json::json!({"type": "error", "error": {"type": "api_error", "message": message}})
}