loopctl 0.3.0

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

use crate::api::ApiClient;
use crate::message::Message;

/// A type that can be requested from the model as a JSON-schema-conformant
/// response, and deserialized from the model's output.
///
/// This is a *type-level* trait (like `serde::Serialize`), not a provider
/// trait — it is never used as a trait object. Implement it on any `Sized +
/// Send + 'static` type that also implements `serde::de::DeserializeOwned`.
///
/// The schema returned by [`schema`](Self::schema) is injected into the
/// provider request (OpenAI `response_format` / Anthropic forced tool); the
/// model's output is parsed back via [`from_value`](Self::from_value).
///
/// # Manual schema vs derive
///
/// By default, implement `schema()` by returning a `serde_json::json!`
/// literal — no extra dependency, matching how
/// [`ToolSchema::input_schema`](crate::tool::ToolSchema::input_schema) is
/// authored today.
///
/// # Example
///
/// ```rust,ignore
/// use loopctl::structured::StructuredOutput;
/// use serde::{Deserialize, Serialize};
/// use serde_json::json;
///
/// #[derive(Debug, Serialize, Deserialize)]
/// pub struct Action {
///     pub tool: String,
///     pub args: serde_json::Value,
/// }
///
/// impl StructuredOutput for Action {
///     fn name() -> &'static str { "action" }
///     fn schema() -> serde_json::Value {
///         json!({
///             "type": "object",
///             "properties": {
///                 "tool": { "type": "string" },
///                 "args": {}
///             },
///             "required": ["tool", "args"],
///             "additionalProperties": false
///         })
///     }
/// }
/// ```
pub trait StructuredOutput: Sized + Send + 'static {
    /// Logical name for the schema.
    ///
    /// Used verbatim as the OpenAI `json_schema.name` field and as the
    /// synthesized Anthropic forced-tool name. Expected to match
    /// `^[a-zA-Z0-9_-]+$` (alphanumeric, underscore, hyphen only) — the
    /// convention OpenAI's schema identifiers follow; neither the crate
    /// nor the providers enforce it.
    fn name() -> &'static str;

    /// The JSON Schema (Draft 07) describing the desired output object.
    ///
    /// The schema is injected into the provider request: OpenAI emits it as
    /// `response_format.json_schema.schema`; Anthropic uses it as the
    /// forced tool's `input_schema`. The model's output is expected to
    /// conform to this schema — the [`from_value`](Self::from_value) method
    /// then deserializes it into `Self`.
    ///
    /// Implement this by returning a `serde_json::json!({ … })` literal
    /// (matching the pattern used by
    /// [`ToolSchema::input_schema`](crate::tool::ToolSchema::input_schema)).
    fn schema() -> serde_json::Value;

    /// Deserialize an instance from the model's JSON output.
    ///
    /// The default implementation is `serde_json::from_value::<Self>(v)`,
    /// which is correct for any `Self: DeserializeOwned`. Override only for
    /// post-processing (e.g. trimming, defaults, cross-field validation).
    ///
    /// # Errors
    ///
    /// Returns [`StructuredError::Deserialize`] if the value does not match
    /// the type (and, by construction, the schema).
    fn from_value(v: serde_json::Value) -> Result<Self, StructuredError>
    where
        Self: serde::de::DeserializeOwned,
    {
        serde_json::from_value(v).map_err(StructuredError::Deserialize)
    }
}

/// A request to constrain the model's output to a named JSON schema.
///
/// Construct with [`ResponseFormat::from_type`] from any [`StructuredOutput`]
/// type, or manually from a raw schema + name via [`ResponseFormat::new`].
/// Passed to the provider via [`RequestOptions`].
#[derive(Debug, Clone)]
pub struct ResponseFormat {
    /// Logical name for the schema.
    ///
    /// Copied from [`StructuredOutput::name`] when constructed via
    /// [`from_type`](Self::from_type). Used as the OpenAI `json_schema.name`
    /// and the Anthropic forced-tool name. The `^[a-zA-Z0-9_-]+$` shape is
    /// the expected convention, not an enforced one.
    pub name: String,

    /// The JSON Schema the model's output must satisfy.
    ///
    /// Injected into the provider request verbatim: OpenAI emits it as
    /// `response_format.json_schema.schema`; Anthropic uses it as the
    /// forced tool's `input_schema`.
    pub schema: serde_json::Value,

    /// Whether to enforce the schema server-side ("strict" mode).
    ///
    /// When `true` (the default), OpenAI guarantees the output conforms to
    /// the schema. Anthropic and Gemini cannot express strict mode and
    /// reject a strict request before sending it
    /// ([`ApiError::config_validation`](crate::api::error::ApiError::config_validation)).
    pub strict: bool,
}

impl ResponseFormat {
    /// Build a [`ResponseFormat`] from a [`StructuredOutput`] type.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use loopctl::structured::{ResponseFormat, StructuredOutput};
    ///
    /// let rf = ResponseFormat::from_type::<MyOutput>();
    /// assert_eq!(rf.name, MyOutput::name());
    /// assert_eq!(rf.schema, MyOutput::schema());
    /// assert!(rf.strict);
    /// ```
    #[must_use]
    pub fn from_type<T: StructuredOutput>() -> Self {
        Self {
            name: T::name().to_string(),
            schema: T::schema(),
            strict: true,
        }
    }

    /// Build a [`ResponseFormat`] from raw parts.
    ///
    /// Use this when the schema is constructed dynamically (e.g. at runtime
    /// from config or a database) rather than from a static type. For the
    /// common case of deriving the format from a `StructuredOutput` type,
    /// prefer [`from_type`](Self::from_type).
    ///
    /// Sets `strict: true` by default — the model is constrained server-side
    /// where supported (OpenAI strict mode, Anthropic ignores the flag).
    #[must_use]
    pub fn new(name: impl Into<String>, schema: serde_json::Value) -> Self {
        Self {
            name: name.into(),
            schema,
            strict: true,
        }
    }
}

/// How tightly the provider must constrain tool-call output to the
/// registered schemas.
///
/// Default [`ToolConstraint::None`] reproduces the behaviour of versions
/// prior to this field: the provider advertises tool schemas as-is and the
/// model's tool calls are unconstrained. [`ToolConstraint::Strict`] asks
/// the provider to make malformed tool calls structurally impossible using
/// its native strict-tool mode (OpenAI `strict: true` with schema
/// tightening; Anthropic / Gemini tightened `input_schema` / `parameters`).
///
/// The enum is `#[non_exhaustive]`: future variants may be added
/// non-breakingly, and the `Grammar` variant is only present under the
/// `grammar` feature.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub enum ToolConstraint {
    /// No constraint — the provider advertises tool schemas as-is.
    ///
    /// This is the default: every tool's schema is forwarded to the
    /// provider verbatim, with no `additionalProperties: false`, no
    /// expanded `required`, and no `strict` flag. The model is free to
    /// emit any JSON it likes for a tool call, including hallucinated
    /// fields, and malformed tool calls are detected (and retried) rather
    /// than prevented.
    ///
    /// Choose this when you trust the model to emit well-formed tool calls
    /// (frontier models, warm-up turns, or any path where you'd rather
    /// surface a malformed call than have the provider reject the request).
    #[default]
    None,

    /// Use the provider's native strict-tool mode.
    ///
    /// On OpenAI this sets `strict: true` on each tool's `function` schema
    /// after tightening it (recursive `additionalProperties: false` and
    /// full `required`). On Anthropic and Gemini it tightens each tool's
    /// `input_schema` / `parameters` the same way.
    Strict,

    /// Use a grammar compiled from the tool schemas, passed to a
    /// grammar-aware sampler (vLLM `guided_json`).
    ///
    /// Only available when the `grammar` feature is enabled. The
    /// [`ToolGrammarProvider`](crate::provider::grammar::ToolGrammarProvider)
    /// trait is the extension point for other server dialects.
    #[cfg(feature = "grammar")]
    Grammar(std::sync::Arc<dyn crate::provider::grammar::ToolGrammarProvider>),
}

/// Optional per-request knobs layered on top of a `stream_messages` /
/// `create_message` call.
///
/// Additive and forward-compatible: every field has a default that
/// reproduces prior behaviour, and a field a client cannot honor is
/// rejected with a config error rather than silently ignored (see the
/// `ApiClient` trait's `*_with_options` defaults). Carries
/// [`response_format`](Self::response_format) (constrain the model's
/// free-text output to a schema),
/// [`tool_constraint`](Self::tool_constraint) (constrain the model's tool
/// calls to the registered schemas), and [`model`](Self::model) (serve
/// this one request with a different model).
///
/// The two paths are independent: setting `response_format` suppresses
/// `tools` (and therefore makes `tool_constraint` a no-op for that
/// request), while setting `tool_constraint` constrains the `tools` path
/// itself.
///
/// Per-request sampling knobs (temperature, top-p, stop sequences,
/// max response tokens) are deliberately out of scope: requests
/// without them are served with the provider-side defaults.
#[derive(Debug, Clone, Default)]
pub struct RequestOptions {
    /// If set, ask the model to return JSON conforming to this schema.
    ///
    /// When `Some`, the provider injects the schema into the request
    /// (OpenAI `response_format` / Anthropic forced tool). When `None`,
    /// the model's output is unconstrained — the default behaviour.
    pub response_format: Option<ResponseFormat>,

    /// How strictly the model's tool-call output must follow the
    /// registered tool schemas. Default [`ToolConstraint::None`] is a
    /// no-op. See [`ToolConstraint`] for the modes.
    pub tool_constraint: ToolConstraint,

    /// Serve the request with the named model, overriding the client's
    /// current model.
    ///
    /// `None` — the default — uses the client's model, so requests without
    /// an override behave exactly as before. Set via
    /// [`with_model`](Self::with_model); the fallback machinery uses this
    /// seam to route requests to the active fallback model without
    /// mutating shared client state.
    pub model: Option<String>,
}

impl RequestOptions {
    /// Create empty options with no response format set.
    ///
    /// Equivalent to [`RequestOptions::default`]. Use
    /// [`with_response_format`](Self::with_response_format) to chain a format
    /// builder-style.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set a per-request model override.
    ///
    /// The provider serves this one request with the named model instead
    /// of the client's current model; the client itself is untouched, so
    /// concurrent loops over one shared client cannot cross-wire their
    /// models. An empty or whitespace-only name is ignored (the override
    /// stays unset) — a nameless model override is never what a caller
    /// means, and the providers reject it on the wire anyway.
    #[must_use]
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        let model = model.into();
        if model.trim().is_empty() {
            return self;
        }
        self.model = Some(model);
        self
    }

    /// Set the response format, builder-style.
    ///
    /// When set, the provider constrains the model's output to the schema.
    /// When left `None` (the default), the model's output is unconstrained.
    #[must_use]
    pub fn with_response_format(mut self, rf: ResponseFormat) -> Self {
        self.response_format = Some(rf);
        self
    }

    /// Set the tool-call constraint, builder-style.
    ///
    /// Default [`ToolConstraint::None`] advertises tool schemas as-is.
    /// [`ToolConstraint::Strict`] makes malformed tool calls structurally
    /// impossible via the provider's native strict mode.
    #[must_use]
    pub fn with_tool_constraint(mut self, c: ToolConstraint) -> Self {
        self.tool_constraint = c;
        self
    }
}

/// Errors raised by the structured-output machinery.
#[derive(Debug, thiserror::Error)]
pub enum StructuredError {
    /// The model's output did not deserialize into the target type.
    ///
    /// Carries the underlying `serde_json::Error` with its exact location
    /// (line/column within the JSON). This typically means the model returned
    /// valid JSON but with missing fields, wrong types, or unexpected
    /// structure relative to `T`'s schema.
    #[error("structured output did not match the expected schema: {0}")]
    Deserialize(#[from] serde_json::Error),

    /// The provider API call failed (HTTP error, auth failure, timeout, rate
    /// limit).
    ///
    /// Carries the underlying [`ApiError`](crate::api::error::ApiError).
    #[error("API error during structured output request: {0}")]
    Api(crate::api::error::ApiError),
}

/// Parse a string as JSON, with a lenient fallback that finds the outermost
/// `{ ... }` or `[ ... ]` substring.
///
/// This is the single biggest lever for hitting the ≥95% schema-valid bar on
/// real-world providers that wrap JSON in markdown fences or prefix it with
/// prose.
///
/// Returns `None` if the content cannot be parsed as JSON (even after the
/// lenient rescue).
pub(crate) fn parse_json_lenient(text: &str) -> Option<serde_json::Value> {
    if let Ok(v) = serde_json::from_str(text) {
        return Some(v);
    }
    // Lenient rescue: find the outermost { ... } or [ ... ].
    extract_json_substring(text)
}

/// Find and parse the outermost JSON object or array in a string.
///
/// Scans for the first `{` or `[`, tracks independent brace and bracket
/// depths, and extracts the substring up to the close of the outermost
/// container — a candidate completes only when both depths return to zero,
/// so an inner container of the other kind (an array inside an object, or
/// an object inside an array) is a plain depth change rather than a
/// mismatch. A closing delimiter that arrives while its own depth is zero
/// cannot belong to balanced JSON, so the candidate is abandoned and the
/// scan resumes — a later, well-formed value may still be found. The
/// outermost candidate that parses wins. String-aware: braces/brackets
/// inside JSON string literals (`"..."`) do not affect depth, and `\"`
/// escapes are honored.
pub(crate) fn extract_json_substring(text: &str) -> Option<serde_json::Value> {
    let bytes = text.as_bytes();
    let mut start = None;
    let mut brace_depth: usize = 0;
    let mut bracket_depth: usize = 0;
    let mut in_string = false;
    let mut escaped = false;

    for (i, &byte) in bytes.iter().enumerate() {
        if in_string {
            if escaped {
                escaped = false;
            } else if byte == b'\\' {
                escaped = true;
            } else if byte == b'"' {
                in_string = false;
            }
            continue;
        }

        match byte {
            b'"' => {
                in_string = true;
            }
            b'{' | b'[' => {
                if start.is_none() {
                    start = Some(i);
                }
                if byte == b'{' {
                    brace_depth = brace_depth.saturating_add(1);
                } else {
                    bracket_depth = bracket_depth.saturating_add(1);
                }
            }
            b'}' | b']' => {
                let Some(s) = start else {
                    continue;
                };
                let depth = if byte == b'}' {
                    &mut brace_depth
                } else {
                    &mut bracket_depth
                };
                if *depth == 0 {
                    // Unbalanced closer inside the candidate — not JSON.
                    start = None;
                    brace_depth = 0;
                    bracket_depth = 0;
                } else {
                    *depth = depth.saturating_sub(1);
                    if brace_depth == 0 && bracket_depth == 0 {
                        let slice = text.get(s..=i).unwrap_or(text);
                        if let Ok(v) = serde_json::from_str(slice) {
                            return Some(v);
                        }
                        start = None;
                    }
                }
            }
            _ => {}
        }
    }
    None
}

/// Tighten a JSON Schema for strict-mode submission.
///
/// Recursively, on every `type: "object"` subschema that has a `properties`
/// map: set `additionalProperties` to `false` and set `required` to the
/// union of any pre-existing entries and the full list of property keys —
/// every property becomes required, and author-declared entries naming keys
/// without a matching property survive. Non-object subschemas (`string`,
/// `number`, etc.) are returned unchanged; the implementation recurses into
/// object properties, `array` `items`, and the values of `allOf` / `anyOf` /
/// `oneOf` arrays, but leaves `$ref`, `if`/`then`/`else`, and other
/// combinator shapes untouched (best-effort).
///
/// Idempotent: passing an already-tight schema through it again yields the
/// same value.
///
/// # Example
///
/// ```rust,ignore
/// use loopctl::structured::tighten_json_schema;
/// use serde_json::json;
///
/// let schema = json!({
///     "type": "object",
///     "properties": {
///         "q": {"type": "string"},
///         "limit": {"type": "number"},
///         "filter": {
///             "type": "object",
///             "properties": {"lang": {"type": "string"}}
///         }
///     }
/// });
///
/// let tightened = tighten_json_schema(&schema);
///
/// // Top-level object: closed and fully required.
/// assert_eq!(tightened["additionalProperties"], false);
/// assert_eq!(tightened["required"], json!(["filter", "limit", "q"]));
///
/// // Nested object is tightened independently — its `required` lists only
/// // its own keys, not the parent's.
/// assert_eq!(tightened["properties"]["filter"]["additionalProperties"], false);
/// assert_eq!(tightened["properties"]["filter"]["required"], json!(["lang"]));
/// ```
#[cfg(any(
    feature = "anthropic",
    feature = "grammar",
    feature = "openai",
    feature = "gemini"
))]
pub(crate) fn tighten_json_schema(schema: &serde_json::Value) -> serde_json::Value {
    let mut out = schema.clone();
    tighten_in_place(&mut out);
    out
}

/// Recursively tighten a JSON Schema in place.
///
/// At each `type: "object"` node with a `properties` map, enforces
/// strictness by:
///
/// 1. setting `additionalProperties: false` — rejects extra/hallucinated
///    fields the model invents beyond the declared properties,
/// 2. setting `required` to the union of any pre-existing entries (kept in
///    their original order) and that object's own property keys (appended
///    when not already listed) — rejects missing fields the model omitted
///    without silently dropping an author-declared requirement that has no
///    matching property.
///
/// Together these make every object schema *closed* (no extra keys) and
/// *fully mandatory* (no optional keys). The two are complementary: neither
/// alone covers the other, and both are required for OpenAI's strict mode
/// to accept the schema without a `400`.
///
/// # Recursion rules
///
/// The walk descends into:
/// - each value of an object's `properties` map (child object schemas),
/// - an array schema's `items` subschema,
/// - each member of `allOf` / `anyOf` / `oneOf` combinator arrays,
/// - each named definition in a local `$defs` / `definitions` map.
///
/// It does **not** descend into or rewrite:
/// - `$ref` references themselves (not followed — would need a registry;
///   but the definitions they point to under `$defs` / `definitions` *are*
///   visited, so a local reference's target still gets tightened),
/// - `if` / `then` / `else` conditional subschemas,
/// - non-object typed schemas (`string`, `number`, `boolean`, …), which
///   are returned unchanged.
///
/// Idempotent: re-running on an already-tight schema leaves it unchanged.
#[cfg(any(
    feature = "anthropic",
    feature = "grammar",
    feature = "openai",
    feature = "gemini"
))]
fn tighten_in_place(schema: &mut serde_json::Value) {
    let Some(obj) = schema.as_object_mut() else {
        return;
    };

    // Tighten this object's own property subschemas first.
    if let Some(properties) = obj
        .get_mut("properties")
        .and_then(serde_json::Value::as_object_mut)
    {
        for child in properties.values_mut() {
            tighten_in_place(child);
        }
    }

    // Recurse into array `items`.
    if let Some(items) = obj.get_mut("items") {
        tighten_in_place(items);
    }

    // Recurse into combinator subschemas.
    for key in ["allOf", "anyOf", "oneOf"] {
        if let Some(arr) = obj.get_mut(key).and_then(serde_json::Value::as_array_mut) {
            for child in arr {
                tighten_in_place(child);
            }
        }
    }

    // Recurse into local named definitions so a `$ref: "#/$defs/..."`
    // target receives the same tightening. `$defs` is the Draft 2019-09+
    // keyword; `definitions` is the older Draft 07 keyword. Both are
    // object maps of subschemas keyed by definition name.
    for key in ["$defs", "definitions"] {
        if let Some(defs) = obj.get_mut(key).and_then(serde_json::Value::as_object_mut) {
            for child in defs.values_mut() {
                tighten_in_place(child);
            }
        }
    }

    // Only enforce object strictness on explicit `type: "object"` schemas.
    // Schemas without a type (or with another type) are left structurally
    // alone so we don't impose object semantics on, e.g., a free-form value.
    let is_object = obj
        .get("type")
        .and_then(serde_json::Value::as_str)
        .is_some_and(|t| t == "object");
    if !is_object {
        return;
    }

    obj.insert(
        "additionalProperties".to_string(),
        serde_json::Value::Bool(false),
    );

    // Enumerate `required` from the current properties (or empty when there
    // are none). Preserves any pre-existing required entries that have no
    // matching property (the model author may know best in odd cases).
    let property_keys: Vec<String> = obj
        .get("properties")
        .and_then(serde_json::Value::as_object)
        .map(|props| props.keys().cloned().collect())
        .unwrap_or_default();
    let mut required: Vec<serde_json::Value> = obj
        .get("required")
        .and_then(serde_json::Value::as_array)
        .cloned()
        .unwrap_or_default();
    let already_listed: std::collections::HashSet<String> = required
        .iter()
        .filter_map(serde_json::Value::as_str)
        .map(str::to_string)
        .collect();
    for key in property_keys {
        if !already_listed.contains(key.as_str()) {
            required.push(serde_json::Value::String(key));
        }
    }
    obj.insert("required".to_string(), serde_json::Value::Array(required));
}

/// Request a typed, schema-conformant value from the model.
///
/// This is the ergonomic entry point callers use. It:
/// 1. Builds [`RequestOptions`] with the [`ResponseFormat`] for `T`.
/// 2. Calls [`create_message_with_options`](ApiClient::create_message_with_options)
///    on the client.
/// 3. Extracts the structured value from the provider's response.
/// 4. Deserializes it into `T` via [`StructuredOutput::from_value`].
///
/// # Errors
///
/// Returns [`StructuredError`] if the provider call fails, the response
/// cannot be parsed as JSON, or the JSON does not match `T`'s schema.
pub async fn request_structured<T: StructuredOutput + serde::de::DeserializeOwned>(
    client: &dyn ApiClient,
    messages: Vec<Message>,
    system: Option<String>,
) -> Result<T, StructuredError> {
    let opts = RequestOptions::new().with_response_format(ResponseFormat::from_type::<T>());
    let request = crate::api::StreamRequest {
        messages,
        system,
        tools: None,
    };
    let response = client
        .create_message_with_options(&request, opts)
        .await
        .map_err(StructuredError::Api)?;
    let value = client.extract_structured(&response.message);
    T::from_value(value)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::future::Future;
    use std::pin::Pin;

    #[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq)]
    struct Action {
        tool: String,
        args: serde_json::Value,
    }

    impl StructuredOutput for Action {
        fn name() -> &'static str {
            "action"
        }
        fn schema() -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {
                    "tool": { "type": "string" },
                    "args": {}
                },
                "required": ["tool", "args"],
                "additionalProperties": false
            })
        }
    }

    fn fixture_action() -> serde_json::Value {
        serde_json::json!({
            "tool": "write",
            "args": { "path": "/tmp/test.txt" }
        })
    }

    #[test]
    fn with_model_ignores_empty_and_whitespace_names() {
        let opts = RequestOptions::default().with_model("");
        assert!(
            opts.model.is_none(),
            "an empty model name leaves the override unset — providers reject nameless models"
        );
        let opts = RequestOptions::default().with_model("   ");
        assert!(
            opts.model.is_none(),
            "a whitespace-only model name leaves the override unset"
        );
        let opts = RequestOptions::default().with_model("fallback-model");
        assert_eq!(opts.model.as_deref(), Some("fallback-model"));
    }

    #[test]
    fn structured_output_round_trip() {
        let v = fixture_action();
        let action: Action = Action::from_value(v).expect("should deserialize");
        assert_eq!(action.tool, "write");
        assert_eq!(action.args, serde_json::json!({ "path": "/tmp/test.txt" }));
    }

    #[test]
    fn response_format_from_type() {
        let rf = ResponseFormat::from_type::<Action>();
        assert_eq!(rf.name, "action");
        assert_eq!(rf.schema, Action::schema());
        assert!(rf.strict);
    }

    #[test]
    fn request_options_builder() {
        let opts = RequestOptions::new();
        assert!(opts.response_format.is_none());

        let rf = ResponseFormat::from_type::<Action>();
        let opts = RequestOptions::new().with_response_format(rf);
        assert!(opts.response_format.is_some());
        assert_eq!(opts.response_format.as_ref().unwrap().name, "action");
    }

    #[test]
    fn parse_json_lenient_plain_json() {
        let v = parse_json_lenient(r#"{"a": 1}"#).unwrap();
        assert_eq!(v["a"], 1);
    }

    #[test]
    fn parse_json_lenient_with_prefix() {
        let v = parse_json_lenient(r#"Here is the JSON: {"a": 1}"#).unwrap();
        assert_eq!(v["a"], 1);
    }

    #[test]
    fn parse_json_lenient_markdown_fences() {
        let v = parse_json_lenient("```json\n{\"a\": 1}\n```").unwrap();
        assert_eq!(v["a"], 1);
    }

    #[test]
    fn parse_json_lenient_array() {
        let v = parse_json_lenient(r#"prefix [1, 2, 3] suffix"#).unwrap();
        assert_eq!(v[0], 1);
    }

    #[test]
    fn parse_json_lenient_no_json() {
        let result = parse_json_lenient("just prose, nothing here");
        assert!(result.is_none());
    }

    #[test]
    fn structured_error_displays() {
        let json_err = serde_json::from_str::<serde_json::Value>("bad").unwrap_err();
        let err = StructuredError::Deserialize(json_err);
        assert!(err.to_string().contains("schema"));
    }

    #[test]
    fn parse_json_lenient_brace_inside_string() {
        let v = parse_json_lenient(r#"prefix {"a": "}"} suffix"#).unwrap();
        assert_eq!(v["a"], "}");
    }

    #[test]
    fn parse_json_lenient_bracket_inside_string() {
        let v = parse_json_lenient(r#"before {"x": "]"} after"#).unwrap();
        assert_eq!(v["x"], "]");
    }

    #[test]
    fn parse_json_lenient_escaped_quote_in_string() {
        let v = parse_json_lenient(r#"here {"a": "he said \"hi\""} there"#).unwrap();
        assert_eq!(v["a"], "he said \"hi\"");
    }

    #[test]
    fn parse_json_lenient_nested_objects_in_prose() {
        let v = parse_json_lenient(r#"result: {"outer": {"inner": 42}}"#).unwrap();
        assert_eq!(v["outer"]["inner"], 42);
    }

    #[test]
    fn parse_json_lenient_mismatched_delimiter_then_valid() {
        let v = parse_json_lenient(r#"{oops] then {"a":1}"#).unwrap();
        assert_eq!(v["a"], 1);
    }

    struct PlainMockClient;
    impl crate::api::ApiClient for PlainMockClient {
        fn model(&self) -> String {
            "test".to_string()
        }
        fn stream_messages(
            &self,
            _request: &crate::api::StreamRequest,
        ) -> Pin<
            Box<
                dyn futures::Stream<
                        Item = Result<crate::stream::StreamEvent, crate::api::error::ApiError>,
                    > + Send
                    + 'static,
            >,
        > {
            Box::pin(futures::stream::empty())
        }
        fn create_message(
            &self,
            _request: &crate::api::StreamRequest,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::api::NonStreamingResponse,
                            crate::api::error::ApiError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            Box::pin(async {
                Ok(crate::api::NonStreamingResponse {
                    message: crate::message::Message::assistant(""),
                    stop_reason: crate::stream::StreamStopReason::EndTurn,
                    usage: Some(crate::stream::Usage::default()),
                })
            })
        }
    }

    #[tokio::test]
    async fn default_client_rejects_response_format() {
        let client = PlainMockClient;
        let opts =
            RequestOptions::new().with_response_format(ResponseFormat::from_type::<Action>());
        let request = crate::api::StreamRequest::new(vec![]);
        let result = client.create_message_with_options(&request, opts).await;
        assert!(
            result.is_err(),
            "client without structured-output support should reject response_format"
        );
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("does not support structured output"),
            "error should explain why: {err_msg}"
        );
    }

    #[tokio::test]
    async fn default_client_delegates_empty_options() {
        let client = PlainMockClient;
        let opts = RequestOptions::new();
        let request = crate::api::StreamRequest::new(vec![]);
        let result = client.create_message_with_options(&request, opts).await;
        assert!(result.is_ok(), "empty options should delegate normally");
    }

    struct StructuredMockClient;
    impl crate::api::ApiClient for StructuredMockClient {
        fn model(&self) -> String {
            "test".to_string()
        }
        fn stream_messages(
            &self,
            _request: &crate::api::StreamRequest,
        ) -> Pin<
            Box<
                dyn futures::Stream<
                        Item = Result<crate::stream::StreamEvent, crate::api::error::ApiError>,
                    > + Send
                    + 'static,
            >,
        > {
            Box::pin(futures::stream::empty())
        }
        fn create_message(
            &self,
            _request: &crate::api::StreamRequest,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::api::NonStreamingResponse,
                            crate::api::error::ApiError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            Box::pin(async {
                Ok(crate::api::NonStreamingResponse {
                    message: crate::message::Message::assistant(""),
                    stop_reason: crate::stream::StreamStopReason::EndTurn,
                    usage: Some(crate::stream::Usage::default()),
                })
            })
        }
        fn create_message_with_options(
            &self,
            _request: &crate::api::StreamRequest,
            _options: RequestOptions,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::api::NonStreamingResponse,
                            crate::api::error::ApiError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            Box::pin(async {
                Ok(crate::api::NonStreamingResponse {
                    message: crate::message::Message::assistant(
                        r#"{"tool": "write", "args": {"path": "/test"}}"#,
                    ),
                    stop_reason: crate::stream::StreamStopReason::EndTurn,
                    usage: Some(crate::stream::Usage::default()),
                })
            })
        }
    }

    #[tokio::test]
    async fn request_structured_end_to_end() {
        let client = StructuredMockClient;
        let action: Action = request_structured(&client, vec![], None)
            .await
            .expect("should succeed");
        assert_eq!(action.tool, "write");
    }

    struct ProseMockClient;
    impl crate::api::ApiClient for ProseMockClient {
        fn model(&self) -> String {
            "test".to_string()
        }
        fn stream_messages(
            &self,
            _request: &crate::api::StreamRequest,
        ) -> Pin<
            Box<
                dyn futures::Stream<
                        Item = Result<crate::stream::StreamEvent, crate::api::error::ApiError>,
                    > + Send
                    + 'static,
            >,
        > {
            Box::pin(futures::stream::empty())
        }
        fn create_message(
            &self,
            _request: &crate::api::StreamRequest,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::api::NonStreamingResponse,
                            crate::api::error::ApiError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            Box::pin(async {
                Ok(crate::api::NonStreamingResponse {
                    message: crate::message::Message::assistant(""),
                    stop_reason: crate::stream::StreamStopReason::EndTurn,
                    usage: Some(crate::stream::Usage::default()),
                })
            })
        }
        fn create_message_with_options(
            &self,
            _request: &crate::api::StreamRequest,
            _options: RequestOptions,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::api::NonStreamingResponse,
                            crate::api::error::ApiError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            Box::pin(async {
                Ok(crate::api::NonStreamingResponse {
                    message: crate::message::Message::assistant("I cannot produce that."),
                    stop_reason: crate::stream::StreamStopReason::EndTurn,
                    usage: Some(crate::stream::Usage::default()),
                })
            })
        }
    }

    #[tokio::test]
    async fn request_structured_prose_returns_deserialize_error() {
        let client = ProseMockClient;
        let err = request_structured::<Action>(&client, vec![], None)
            .await
            .expect_err("should fail");
        // Prose is a valid JSON string but doesn't match Action's schema,
        // so deserialization fails.
        assert!(matches!(err, StructuredError::Deserialize(_)));
    }

    #[test]
    fn tool_constraint_default_is_none() {
        assert!(matches!(ToolConstraint::default(), ToolConstraint::None));
        assert!(matches!(
            RequestOptions::default().tool_constraint,
            ToolConstraint::None
        ));
    }

    #[test]
    fn request_options_tool_constraint_builder() {
        let opts = RequestOptions::new().with_tool_constraint(ToolConstraint::Strict);
        assert!(matches!(opts.tool_constraint, ToolConstraint::Strict));
        // And response_format still composes on the same builder.
        let rf = ResponseFormat::from_type::<Action>();
        let opts = RequestOptions::new()
            .with_response_format(rf)
            .with_tool_constraint(ToolConstraint::Strict);
        assert!(opts.response_format.is_some());
        assert!(matches!(opts.tool_constraint, ToolConstraint::Strict));
    }

    #[test]
    fn tool_constraint_clone_compiles() {
        // RequestOptions derives Clone, which requires every field —
        // including tool_constraint — to be Clone. This test pins that by
        // cloning an options value that carries a constraint and asserting
        // both copies hold the same variant.
        let opts = RequestOptions::new().with_tool_constraint(ToolConstraint::Strict);
        let cloned = opts.clone();
        assert!(matches!(opts.tool_constraint, ToolConstraint::Strict));
        assert!(matches!(cloned.tool_constraint, ToolConstraint::Strict));
    }

    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[test]
    fn tighten_sets_additional_properties_false() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"a": {"type": "string"}}
        });
        let tightened = tighten_json_schema(&schema);
        assert_eq!(tightened["additionalProperties"], false);
    }

    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[test]
    fn tighten_enumerates_required() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "a": {"type": "string"},
                "b": {"type": "number"}
            }
        });
        let tightened = tighten_json_schema(&schema);
        let required = tightened["required"].as_array().unwrap();
        assert_eq!(required.len(), 2);
        let keys: Vec<&str> = required.iter().map(|v| v.as_str().unwrap()).collect();
        assert!(keys.contains(&"a"));
        assert!(keys.contains(&"b"));
    }

    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[test]
    fn tighten_recurses_into_nested_objects() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "inner": {
                    "type": "object",
                    "properties": {"x": {"type": "string"}}
                }
            }
        });
        let tightened = tighten_json_schema(&schema);
        assert_eq!(
            tightened["properties"]["inner"]["additionalProperties"],
            false
        );
        let inner_required = tightened["properties"]["inner"]["required"]
            .as_array()
            .unwrap();
        assert_eq!(inner_required.len(), 1);
        assert_eq!(inner_required[0], "x");
    }

    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[test]
    fn tighten_preserves_non_object_schemas() {
        let schema = serde_json::json!({"type": "string"});
        let tightened = tighten_json_schema(&schema);
        assert_eq!(tightened, schema);
        // Should not have gained additionalProperties / required.
        assert!(tightened.get("additionalProperties").is_none());
        assert!(tightened.get("required").is_none());
    }

    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[test]
    fn tighten_idempotent_on_already_strict() {
        let schema = serde_json::json!({
            "type": "object",
            "additionalProperties": false,
            "properties": {"a": {"type": "string"}},
            "required": ["a"]
        });
        let once = tighten_json_schema(&schema);
        let twice = tighten_json_schema(&once);
        assert_eq!(once, twice);
    }

    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[test]
    fn tighten_object_without_properties() {
        let schema = serde_json::json!({"type": "object"});
        let tightened = tighten_json_schema(&schema);
        assert_eq!(tightened["additionalProperties"], false);
        // `required` becomes an empty array, not absent.
        assert_eq!(tightened["required"].as_array().unwrap().len(), 0);
    }

    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[test]
    fn tighten_recurses_into_local_defs() {
        // A property that $refs a local definition: the reference itself
        // is not followed, but the definition under $defs must still be
        // tightened so a strict-mode server accepts it.
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "filter": {"$ref": "#/$defs/Filter"}
            },
            "$defs": {
                "Filter": {
                    "type": "object",
                    "properties": {
                        "lang": {"type": "string"},
                        "limit": {"type": "number"}
                    }
                }
            }
        });
        let tightened = tighten_json_schema(&schema);

        // Top-level object: closed and fully required.
        assert_eq!(tightened["additionalProperties"], false);
        assert_eq!(tightened["required"], serde_json::json!(["filter"]));

        // The $defs/Filter definition is tightened: closed, and its
        // nested arguments are all required.
        let filter = &tightened["$defs"]["Filter"];
        assert_eq!(filter["additionalProperties"], false);
        let required = filter["required"].as_array().unwrap();
        assert_eq!(required.len(), 2);
        let keys: Vec<&str> = required.iter().map(|v| v.as_str().unwrap()).collect();
        assert!(keys.contains(&"lang"));
        assert!(keys.contains(&"limit"));

        // The $ref reference itself is left in place (not rewritten).
        assert_eq!(tightened["properties"]["filter"]["$ref"], "#/$defs/Filter");
    }

    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[test]
    fn tighten_recurses_into_legacy_definitions() {
        // The Draft 07 keyword `definitions` should be walked the same way
        // as `$defs`.
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"x": {"$ref": "#/definitions/X"}},
            "definitions": {
                "X": {
                    "type": "object",
                    "properties": {"a": {"type": "string"}}
                }
            }
        });
        let tightened = tighten_json_schema(&schema);
        let def = &tightened["definitions"]["X"];
        assert_eq!(def["additionalProperties"], false);
        assert_eq!(def["required"].as_array().unwrap().len(), 1);
    }

    #[test]
    fn parse_json_lenient_object_containing_array() {
        let v = parse_json_lenient(r#"prefix {"a": [1, 2]} suffix"#).unwrap();
        assert_eq!(v["a"], serde_json::json!([1, 2]));
    }

    #[test]
    fn parse_json_lenient_array_containing_object() {
        let v = parse_json_lenient(r#"prefix [{"a": 1}] suffix"#).unwrap();
        assert_eq!(v[0]["a"], 1);
    }

    #[test]
    fn parse_json_lenient_fenced_failure_analysis_shape() {
        let v = parse_json_lenient("```json\n{\"m\": {\"p\": [1]}}\n```").unwrap();
        assert!(v.is_object());
        assert_eq!(v["m"]["p"], serde_json::json!([1]));
    }

    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[test]
    fn tighten_preserves_required_entries_without_matching_property() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"a": {"type": "string"}},
            "required": ["a", "meta"]
        });
        let tightened = tighten_json_schema(&schema);
        let required = tightened["required"].as_array().unwrap();
        assert!(
            required.iter().any(|v| v == "meta"),
            "required entry without a matching property must survive tightening: {required:?}"
        );
    }

    #[test]
    fn parse_json_lenient_deeply_mixed_nesting_extracts_outermost() {
        let v = parse_json_lenient(
            r#"analysis: {"is_recoverable":true,"correction":{"modified_input":{"path":["a"]}}}"#,
        )
        .unwrap();
        assert_eq!(
            v["correction"]["modified_input"]["path"],
            serde_json::json!(["a"])
        );
    }

    #[test]
    fn parse_json_lenient_object_with_array_of_objects() {
        let v = parse_json_lenient(r#"{"a": [{"b": 2}]}"#).unwrap();
        assert_eq!(v["a"][0]["b"], 2);
    }

    #[test]
    fn parse_json_lenient_stray_brace_in_array_resumes_scan() {
        let v = parse_json_lenient(r#"[1, 2} then {"a":1}"#).unwrap();
        assert_eq!(
            v["a"], 1,
            "a stray brace inside an array candidate aborts it; the later object still extracts"
        );
    }

    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[test]
    fn tighten_required_union_keeps_order_then_appends_properties() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"b": {"type": "number"}, "a": {"type": "string"}},
            "required": ["meta"]
        });
        let tightened = tighten_json_schema(&schema);
        let required = tightened["required"].as_array().unwrap();
        assert_eq!(
            required.first(),
            Some(&serde_json::json!("meta")),
            "pre-existing entries keep their position ahead of appended property keys"
        );
        assert_eq!(
            required.len(),
            3,
            "every property key is appended exactly once"
        );
        assert!(
            required.contains(&serde_json::json!("a"))
                && required.contains(&serde_json::json!("b")),
            "the unlisted property keys join the union, in map order: {required:?}"
        );
        let twice = tighten_json_schema(&tightened);
        assert_eq!(
            twice["required"], tightened["required"],
            "the union is idempotent: a second pass neither reorders nor duplicates"
        );
    }

    #[test]
    fn parse_json_lenient_first_valid_candidate_wins() {
        let v = parse_json_lenient(r#"{"a": 1} and {"b": 2}"#).unwrap();
        assert_eq!(
            v["a"], 1,
            "the outermost candidate that parses wins; a later sibling is not preferred"
        );
    }

    #[test]
    fn parse_json_lenient_unparseable_candidate_then_valid() {
        let v = parse_json_lenient(r#"{"a": } then {"b": 1}"#).unwrap();
        assert_eq!(
            v["b"], 1,
            "a balanced but invalid candidate is abandoned at its close; the scan resumes"
        );
    }

    #[test]
    fn parse_json_lenient_unterminated_json_returns_none() {
        let result = parse_json_lenient(r#"prefix {"a": 1"#);
        assert_eq!(
            result, None,
            "a candidate that never closes yields nothing, not a panic or a partial value"
        );
    }

    #[test]
    fn parse_json_lenient_nested_arrays() {
        let v = parse_json_lenient(r#"result [[1, 2], [3]]"#).unwrap();
        assert_eq!(v[0][1], 2);
        assert_eq!(v[1][0], 3);
    }

    #[test]
    fn parse_json_lenient_empty_containers_in_prose() {
        let empty_object = parse_json_lenient(r#"text {} more"#).unwrap();
        assert!(
            empty_object
                .as_object()
                .is_some_and(serde_json::Map::is_empty)
        );
        let empty_array = parse_json_lenient(r#"text [] more"#).unwrap();
        assert!(empty_array.as_array().is_some_and(Vec::is_empty));
    }

    #[test]
    fn parse_json_lenient_escaped_backslash_in_string() {
        let v = parse_json_lenient(r#"{"path": "c:\\"}"#).unwrap();
        assert_eq!(v["path"], "c:\\");
    }

    #[cfg(any(
        feature = "anthropic",
        feature = "grammar",
        feature = "openai",
        feature = "gemini"
    ))]
    #[test]
    fn tighten_required_union_applies_to_nested_objects() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "filter": {
                    "type": "object",
                    "properties": {"lang": {"type": "string"}},
                    "required": ["secret"]
                }
            }
        });
        let tightened = tighten_json_schema(&schema);
        assert_eq!(
            tightened["properties"]["filter"]["required"],
            serde_json::json!(["secret", "lang"]),
            "the union applies at every object level, not just the root"
        );
    }
}