ag-harness 0.15.1

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
use crate::chat_completion;

pub(crate) const PROVIDER_NAME: &str = "alibaba_cloud";
pub(crate) const POLICY: chat_completion::ChatCompletionProviderPolicy =
    chat_completion::ChatCompletionProviderPolicy {
        display_name: "Qwen",
        structured_output: chat_completion::StructuredOutputMode::JsonObject {
            assistant_reasoning_content: false,
            tool_result_name: false,
        },
        telemetry_name: PROVIDER_NAME,
        unsupported_schema_reason: "Qwen JSON Object mode requires an explicit object root schema",
    };

/// Configuration for a Qwen model served through Alibaba Cloud Model Studio's
/// OpenAI-compatible API.
pub struct QwenConfig {
    /// API key sent as a bearer token.
    pub api_key: String,
    /// API base URL ending in the OpenAI-compatible version path.
    pub base_url: String,
    /// Qwen model identifier sent with each request.
    pub model: String,
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use async_trait::async_trait;
    use serde_json::json;
    use wiremock::matchers::{bearer_token, body_json, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    use super::*;
    use crate::chat_completion::{
        ChatCompletion, ChatCompletionBackend, ChatCompletionClient, ChatCompletionError,
        ChatCompletionRequest, ERROR_BODY_LIMIT_BYTES, RESPONSE_ENVELOPE_LIMIT_BYTES,
        STRUCTURED_OUTPUT_INSTRUCTION, SUCCESS_BODY_LIMIT_BYTES,
    };
    use crate::{model, schema_contract, tool};

    struct StubClient;

    #[async_trait]
    impl ChatCompletionClient for StubClient {
        async fn complete(
            &self,
            request: ChatCompletionRequest<'_>,
        ) -> Result<Option<ChatCompletion>, ChatCompletionError> {
            let (api_key, endpoint, payload) = request.into_parts();
            assert_eq!(api_key, "stub-key");
            assert_eq!(endpoint, "https://stub.example/v1/chat/completions");
            assert_eq!(payload["model"], "qwen-stub");
            assert_eq!(payload["response_format"]["type"], "json_object");

            Ok(Some(ChatCompletion::new(
                "stop".to_string(),
                Some(r#"{"name":"Ada"}"#.to_string()),
            )))
        }
    }

    fn person_schema_value() -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" }
            },
            "required": ["name"],
            "additionalProperties": false
        })
    }

    fn person_schema() -> crate::OutputSchema {
        crate::OutputSchema::new(person_schema_value()).expect("schema should be valid")
    }

    fn request(prompt: &str) -> model::ModelRequest {
        model::ModelRequest::new(prompt, person_schema())
    }

    fn read_request(prompt: &str) -> model::ModelRequest {
        request(prompt).with_tool(tool::ToolDefinition::read())
    }

    fn read_tool_wire() -> serde_json::Value {
        let definition = tool::ToolDefinition::read();

        json!({
            "type": "function",
            "function": {
                "description": definition.description(),
                "name": definition.name(),
                "parameters": definition.parameters()
            }
        })
    }

    fn escaped_value_schema() -> crate::OutputSchema {
        crate::OutputSchema::new(json!({
            "type": "object",
            "properties": {
                "value": { "type": "string" }
            },
            "required": ["value"],
            "additionalProperties": false
        }))
        .expect("schema should be valid")
    }

    fn qwen(server: &MockServer) -> model::ModelClient {
        model::ModelClient::qwen(QwenConfig {
            api_key: "test-key".to_string(),
            base_url: format!("{}/", server.uri()),
            model: "qwen-plus".to_string(),
        })
        .expect("fixture configuration should be valid")
    }

    #[test]
    fn rejects_empty_model_during_construction() {
        // Arrange
        let config = QwenConfig {
            api_key: "test-key".to_string(),
            base_url: "https://example.com".to_string(),
            model: "  ".to_string(),
        };

        // Act
        let error = model::ModelClient::qwen(config)
            .err()
            .expect("empty model configuration should be rejected");

        // Assert
        assert_eq!(error, model::ModelMetadataError::EmptyModel);
    }

    async fn mount_structured_response(
        server: &MockServer,
        prompt: &str,
        schema: &serde_json::Value,
        content: &str,
    ) {
        let schema_instruction = format!("{STRUCTURED_OUTPUT_INSTRUCTION}{schema}");
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .and(bearer_token("test-key"))
            .and(body_json(json!({
                "messages": [
                    {"content": schema_instruction, "role": "system"},
                    {"content": prompt, "role": "user"}
                ],
                "model": "qwen-plus",
                "response_format": {"type": "json_object"}
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "choices": [{
                    "finish_reason": "stop",
                    "message": {"content": content, "tool_calls": null}
                }]
            })))
            .expect(1)
            .mount(server)
            .await;
    }

    async fn mount_tool_response(server: &MockServer, prompt: &str, message: serde_json::Value) {
        mount_read_response(server, prompt, "tool_calls", message).await;
    }

    async fn mount_read_response(
        server: &MockServer,
        prompt: &str,
        finish_reason: &str,
        message: serde_json::Value,
    ) {
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .and(bearer_token("test-key"))
            .and(body_json(json!({
                "messages": [
                    {
                        "content": format!(
                            "{STRUCTURED_OUTPUT_INSTRUCTION}{}",
                            person_schema_value()
                        ),
                        "role": "system"
                    },
                    {"content": prompt, "role": "user"}
                ],
                "model": "qwen-plus",
                "response_format": {"type": "json_object"},
                "tools": [read_tool_wire()]
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "choices": [{
                    "finish_reason": finish_reason,
                    "message": message
                }]
            })))
            .expect(1)
            .mount(server)
            .await;
    }

    #[tokio::test]
    async fn completes_terminal_response_with_null_tool_calls() {
        // Arrange
        let server = MockServer::start().await;
        let schema_value = person_schema_value();
        mount_structured_response(
            &server,
            "extract the name",
            &schema_value,
            r#"{"name":"Ada"}"#,
        )
        .await;
        let model = qwen(&server);

        // Act
        let response = model
            .complete(request("extract the name"))
            .await
            .expect("Qwen request should succeed");

        // Assert
        assert_eq!(response.output(), Some(&json!({ "name": "Ada" })));
    }

    #[tokio::test]
    async fn advertises_and_decodes_read_tool_call() {
        // Arrange
        let server = MockServer::start().await;
        mount_tool_response(
            &server,
            "inspect the manifest",
            json!({
                "content": "",
                "tool_calls": [{
                    "id": "call_qwen_read",
                    "type": "function",
                    "function": {
                        "name": "read",
                        "arguments": r#"{"path":"Cargo.toml","offset":1,"limit":12}"#
                    }
                }]
            }),
        )
        .await;
        let model = qwen(&server);

        // Act
        let response = model
            .complete(read_request("inspect the manifest"))
            .await
            .expect("Qwen read request should decode");

        // Assert
        assert!(response.output().is_none());
        let call = response
            .call()
            .expect("response should contain a tool call");
        assert_eq!(call.id(), "call_qwen_read");
        assert_eq!(call.name(), "read");
        assert_eq!(call.arguments().path(), "Cargo.toml");
        assert_eq!(call.arguments().offset(), Some(1));
        assert_eq!(call.arguments().limit(), Some(12));
    }

    #[tokio::test]
    async fn sends_tool_result_history_for_continuation() {
        // Arrange
        let server = MockServer::start().await;
        let prompt = "inspect the manifest";
        let result = r#"{"content":"[workspace]","end_line":1,"next_offset":null,"path":"Cargo.toml","start_line":1,"truncated":false}"#;
        let arguments = serde_json::from_value(json!({
            "path": "Cargo.toml",
            "offset": 1,
            "limit": 12
        }))
        .expect("read arguments should be valid");
        let call = tool::ToolCall::read("call_qwen_read".to_string(), arguments, None);
        let mut model_request = read_request(prompt);
        model_request.record_tool_result(call, result.to_string());
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .and(bearer_token("test-key"))
            .and(body_json(json!({
                "messages": [
                    {
                        "content": format!(
                            "{STRUCTURED_OUTPUT_INSTRUCTION}{}",
                            person_schema_value()
                        ),
                        "role": "system"
                    },
                    {"content": prompt, "role": "user"},
                    {
                        "content": null,
                        "role": "assistant",
                        "tool_calls": [{
                            "function": {
                                "arguments": r#"{"limit":12,"offset":1,"path":"Cargo.toml"}"#,
                                "name": "read"
                            },
                            "id": "call_qwen_read",
                            "type": "function"
                        }]
                    },
                    {
                        "content": result,
                        "role": "tool",
                        "tool_call_id": "call_qwen_read"
                    }
                ],
                "model": "qwen-plus",
                "response_format": {"type": "json_object"},
                "tools": [read_tool_wire()]
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "choices": [{
                    "finish_reason": "stop",
                    "message": {
                        "content": r#"{"name":"Cargo"}"#,
                        "tool_calls": null
                    }
                }]
            })))
            .expect(1)
            .mount(&server)
            .await;
        let model = qwen(&server);

        // Act
        let response = model
            .complete(model_request)
            .await
            .expect("continued Qwen request should succeed");

        // Assert
        assert_eq!(response.output(), Some(&json!({ "name": "Cargo" })));
    }

    #[tokio::test]
    async fn rejects_terminal_response_with_tool_calls() {
        // Arrange
        let server = MockServer::start().await;
        mount_read_response(
            &server,
            "inspect the manifest",
            "stop",
            json!({
                "content": r#"{"name":"Cargo"}"#,
                "tool_calls": [{
                    "id": "call_late",
                    "type": "function",
                    "function": {
                        "name": "read",
                        "arguments": r#"{"path":"Cargo.toml"}"#
                    }
                }]
            }),
        )
        .await;
        let model = qwen(&server);

        // Act
        let error = model
            .complete(read_request("inspect the manifest"))
            .await
            .expect_err("terminal response with tool calls should fail");

        // Assert
        assert!(matches!(
            error,
            model::ModelError::TerminalResponseWithToolCalls
        ));
    }

    #[tokio::test]
    async fn rejects_malformed_and_invalid_read_arguments() {
        // Arrange
        let cases = [
            ("{", "model returned invalid tool arguments:"),
            (
                r#"{"path":"Cargo.toml","offset":0}"#,
                "model returned invalid tool arguments:",
            ),
            (
                r#"{"path":"Cargo.toml","extra":true}"#,
                "model returned invalid tool arguments:",
            ),
        ];

        // Act
        let mut errors = Vec::new();
        for (index, (arguments, expected)) in cases.into_iter().enumerate() {
            let server = MockServer::start().await;
            mount_tool_response(
                &server,
                "inspect the manifest",
                json!({
                    "content": null,
                    "tool_calls": [{
                        "id": format!("call_{index}"),
                        "type": "function",
                        "function": {"name": "read", "arguments": arguments}
                    }]
                }),
            )
            .await;
            let error = qwen(&server)
                .complete(read_request("inspect the manifest"))
                .await
                .expect_err("invalid read arguments should fail");
            errors.push((error.to_string(), expected));
        }

        // Assert
        assert!(
            errors
                .iter()
                .all(|(error, expected)| error.starts_with(expected))
        );
    }

    #[tokio::test]
    async fn rejects_unsupported_tool_type_name_and_terminal_content() {
        // Arrange
        let messages = [
            (
                json!({
                    "content": null,
                    "tool_calls": [{
                        "id": "call_type",
                        "type": "custom"
                    }]
                }),
                "model requested unsupported tool type: custom",
            ),
            (
                json!({
                    "content": null,
                    "tool_calls": [{
                        "id": "call_name",
                        "type": "function",
                        "function": {"name": "write", "arguments": r#"{"path":"Cargo.toml"}"#}
                    }]
                }),
                "model requested unsupported tool: write",
            ),
            (
                json!({
                    "content": "done",
                    "tool_calls": [{
                        "id": "call_content",
                        "type": "function",
                        "function": {"name": "read", "arguments": r#"{"path":"Cargo.toml"}"#}
                    }]
                }),
                "model tool call response contained terminal content",
            ),
            (
                json!({
                    "content": null,
                    "tool_calls": [{
                        "id": "call_function_payload",
                        "type": "function"
                    }]
                }),
                "model returned invalid tool arguments:",
            ),
        ];

        // Act
        let mut errors = Vec::new();
        for (message, expected) in messages {
            let server = MockServer::start().await;
            mount_tool_response(&server, "inspect the manifest", message).await;
            let error = qwen(&server)
                .complete(read_request("inspect the manifest"))
                .await
                .expect_err("unsupported tool response should fail");
            errors.push((error.to_string(), expected));
        }

        // Assert
        assert!(errors.iter().all(|(error, expected)| {
            error == expected || (expected.ends_with(':') && error.starts_with(expected))
        }));
    }

    #[tokio::test]
    async fn completes_through_injected_client() {
        // Arrange
        let model = ChatCompletionBackend::with_client(
            "stub-key".to_string(),
            "https://stub.example/v1/".to_string(),
            "qwen-stub".to_string(),
            POLICY,
            Arc::new(StubClient),
        );

        // Act
        let output = model
            .generate(&request("extract the name"))
            .await
            .expect("stubbed Qwen request should succeed");

        // Assert
        assert!(matches!(
            output,
            crate::chat_completion::GeneratedResponse::Output(output)
                if output == r#"{"name":"Ada"}"#
        ));
    }

    #[tokio::test]
    async fn rejects_structured_response_stopped_for_length() {
        // Arrange
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "choices": [{
                    "finish_reason": "length",
                    "message": {"content": r#"{"name":"Ada"}"#}
                }]
            })))
            .mount(&server)
            .await;
        let model = qwen(&server);

        // Act
        let error = model
            .complete(request("extract the name"))
            .await
            .expect_err("truncated response should fail");

        // Assert
        assert!(matches!(
            error,
            model::ModelError::IncompleteResponse { reason } if reason == "length"
        ));
    }

    #[tokio::test]
    async fn bounds_incomplete_response_reason() {
        // Arrange
        let server = MockServer::start().await;
        let finish_reason = "x".repeat(1024);
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "choices": [{
                    "finish_reason": finish_reason.clone(),
                    "message": {"content": r#"{"name":"Ada"}"#}
                }]
            })))
            .mount(&server)
            .await;
        let model = qwen(&server);

        // Act
        let error = model
            .complete(request("extract the name"))
            .await
            .expect_err("incomplete response should fail");

        // Assert
        assert!(matches!(
            error,
            model::ModelError::IncompleteResponse { reason }
                if reason == schema_contract::bounded_diagnostic(finish_reason)
        ));
    }

    #[tokio::test]
    async fn accepts_near_limit_escaped_structured_output() {
        // Arrange
        let server = MockServer::start().await;
        let empty_content =
            serde_json::to_string(&json!({ "value": "" })).expect("content should serialize");
        let value =
            "\\".repeat((schema_contract::RESPONSE_CONTENT_LIMIT_BYTES - empty_content.len()) / 2);
        let content =
            serde_json::to_string(&json!({ "value": value })).expect("content should serialize");
        let body = serde_json::to_vec(&json!({
            "choices": [{
                "finish_reason": "stop",
                "message": {"content": content}
            }]
        }))
        .expect("response should serialize");
        assert!(schema_contract::RESPONSE_CONTENT_LIMIT_BYTES - content.len() <= 1);
        assert!(
            body.len()
                > schema_contract::RESPONSE_CONTENT_LIMIT_BYTES + RESPONSE_ENVELOPE_LIMIT_BYTES
        );
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(body))
            .mount(&server)
            .await;
        let model = qwen(&server);

        // Act
        let response = model
            .complete(model::ModelRequest::new(
                "return escaped content",
                escaped_value_schema(),
            ))
            .await
            .expect("near-limit escaped output should succeed");

        // Assert
        assert_eq!(
            response
                .output()
                .expect("response should contain terminal output")
                .get("value")
                .and_then(serde_json::Value::as_str)
                .map(str::len),
            Some(value.len())
        );
    }

    #[tokio::test]
    async fn rejects_oversized_success_body_before_decoding() {
        // Arrange
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![
                b'x';
                SUCCESS_BODY_LIMIT_BYTES
                    + 1
            ]))
            .mount(&server)
            .await;
        let model = qwen(&server);

        // Act
        let error = model
            .complete(request("hello"))
            .await
            .expect_err("oversized successful response should fail");

        // Assert
        assert!(matches!(error, model::ModelError::ResponseBodyTooLarge));
    }

    #[tokio::test]
    async fn rejects_oversized_response_content() {
        // Arrange
        let server = MockServer::start().await;
        let content = "x".repeat(schema_contract::RESPONSE_CONTENT_LIMIT_BYTES + 1);
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "choices": [{
                    "finish_reason": "stop",
                    "message": {"content": content}
                }]
            })))
            .mount(&server)
            .await;
        let model = qwen(&server);

        // Act
        let error = model
            .complete(request("hello"))
            .await
            .expect_err("oversized response content should fail");

        // Assert
        assert!(matches!(error, model::ModelError::ResponseContentTooLarge));
    }

    #[tokio::test]
    async fn rejects_schemas_without_explicit_object_root() {
        // Arrange
        let server = MockServer::start().await;
        let model = qwen(&server);
        let schema_values = [
            json!({ "type": "array" }),
            json!({ "not": { "type": "object" } }),
            json!({
                "$defs": {
                    "result": { "type": "object" }
                },
                "$ref": "#/$defs/result"
            }),
        ];

        // Act
        let mut errors = Vec::new();
        for schema_value in schema_values {
            let schema = crate::OutputSchema::new(schema_value).expect("schema should be valid");
            errors.push(
                model
                    .complete(model::ModelRequest::new("list names", schema))
                    .await
                    .expect_err("schema without an explicit object root should fail"),
            );
        }

        // Assert
        assert!(errors.into_iter().all(|error| matches!(
            error,
            model::ModelError::UnsupportedOutputSchema { reason }
                if reason == "Qwen JSON Object mode requires an explicit object root schema"
        )));
        assert!(
            server
                .received_requests()
                .await
                .expect("request recording should be enabled")
                .is_empty()
        );
    }

    #[tokio::test]
    async fn rejects_malformed_structured_output() {
        // Arrange
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "choices": [{
                    "finish_reason": "stop",
                    "message": {"content": "not JSON"}
                }]
            })))
            .mount(&server)
            .await;
        let model = qwen(&server);

        // Act
        let error = model
            .complete(request("extract the name"))
            .await
            .expect_err("malformed JSON should fail");

        // Assert
        assert!(matches!(error, model::ModelError::InvalidJson { .. }));
    }

    #[tokio::test]
    async fn rejects_structured_output_schema_violation() {
        // Arrange
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "choices": [{
                    "finish_reason": "stop",
                    "message": {"content": r#"{"name":42}"#}
                }]
            })))
            .mount(&server)
            .await;
        let model = qwen(&server);

        // Act
        let error = model
            .complete(request("extract the name"))
            .await
            .expect_err("schema violation should fail");

        // Assert
        assert!(matches!(
            error,
            model::ModelError::SchemaViolation { path, reason }
                if path == "/name" && reason.contains("string")
        ));
    }

    #[tokio::test]
    async fn rejects_successful_response_without_content() {
        // Arrange
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "choices": []
            })))
            .mount(&server)
            .await;
        let model = qwen(&server);

        // Act
        let error = model
            .complete(request("hello"))
            .await
            .expect_err("missing response content should fail");

        // Assert
        assert!(matches!(error, model::ModelError::InvalidResponse));
    }

    #[tokio::test]
    async fn returns_request_error_for_http_failure() {
        // Arrange
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .respond_with(ResponseTemplate::new(401).set_body_json(json!({
                "error": {"message": "invalid API key"}
            })))
            .mount(&server)
            .await;
        let model = qwen(&server);

        // Act
        let error = model
            .complete(request("hello"))
            .await
            .expect_err("HTTP failure should fail");

        // Assert
        assert_eq!(
            error.to_string(),
            "model request failed: Qwen returned HTTP 401 Unauthorized: \
             {\"error\":{\"message\":\"invalid API key\"}}"
        );
        let provider_error = std::error::Error::source(&error)
            .expect("HTTP failure should retain its provider error");
        let source = provider_error
            .source()
            .and_then(|source| source.downcast_ref::<reqwest::Error>())
            .expect("HTTP failure should retain its reqwest source");
        assert_eq!(source.status(), Some(reqwest::StatusCode::UNAUTHORIZED));
    }

    #[tokio::test]
    async fn bounds_http_error_body() {
        // Arrange
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .respond_with(
                ResponseTemplate::new(500).set_body_string("x".repeat(ERROR_BODY_LIMIT_BYTES + 1)),
            )
            .mount(&server)
            .await;
        let model = qwen(&server);

        // Act
        let error = model
            .complete(request("hello"))
            .await
            .expect_err("HTTP failure should fail");
        let message = error.to_string();

        // Assert
        assert_eq!(
            message,
            format!(
                "model request failed: Qwen returned HTTP 500 Internal Server Error: {} ...",
                "x".repeat(ERROR_BODY_LIMIT_BYTES)
            )
        );
    }

    #[tokio::test]
    async fn returns_request_error_for_malformed_response() {
        // Arrange
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_string("not JSON"))
            .mount(&server)
            .await;
        let model = qwen(&server);

        // Act
        let error = model
            .complete(request("hello"))
            .await
            .expect_err("malformed response should fail");

        // Assert
        assert!(matches!(error, model::ModelError::Request(_)));
    }
}