bashkit 0.5.0

Awesomely fast virtual sandbox with bash and file system
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
// ToolDef, ToolArgs, ToolImpl — reusable tool primitives.
//
// These types live here (not in scripted_tool/) so that both Bash and
// ScriptedTool can import them without circular dependencies.
//
// Dependency direction:  builtins → tool_def → {lib.rs, scripted_tool, tool.rs}

use crate::builtins::{Builtin, Context};
use crate::error::Result;
use crate::interpreter::ExecResult;
use async_trait::async_trait;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

// ============================================================================
// ToolDef — OpenAPI-style tool definition (metadata only)
// ============================================================================

/// OpenAPI-style tool definition: name, description, input schema.
///
/// Describes a sub-tool registered with a `ScriptedToolBuilder` or usable
/// standalone. The `input_schema` is optional JSON Schema for documentation /
/// LLM prompts and for type coercion of `--key value` flags.
#[derive(Clone)]
pub struct ToolDef {
    /// Command name used as bash builtin (e.g. `"get_user"`).
    pub name: String,
    /// Human-readable description for LLM consumption.
    pub description: String,
    /// JSON Schema describing accepted arguments. Empty object if unspecified.
    pub input_schema: serde_json::Value,
    /// Categorical tags for discovery (e.g. `["admin", "billing"]`).
    pub tags: Vec<String>,
    /// Grouping category for discovery (e.g. `"payments"`).
    pub category: Option<String>,
}

impl ToolDef {
    /// Create a tool definition with name and description.
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            input_schema: serde_json::Value::Object(Default::default()),
            tags: Vec::new(),
            category: None,
        }
    }

    /// Attach a JSON Schema for the tool's input parameters.
    pub fn with_schema(mut self, schema: serde_json::Value) -> Self {
        self.input_schema = schema;
        self
    }

    /// Add categorical tags for discovery filtering.
    pub fn with_tags(mut self, tags: &[&str]) -> Self {
        self.tags = tags.iter().map(|s| s.to_string()).collect();
        self
    }

    /// Set the grouping category for discovery.
    pub fn with_category(mut self, category: &str) -> Self {
        self.category = Some(category.to_string());
        self
    }
}

// ============================================================================
// ToolArgs — parsed arguments passed to exec functions
// ============================================================================

/// Parsed arguments passed to a tool exec function.
///
/// `params` is a JSON object built from `--key value` flags, with values
/// type-coerced per the `ToolDef`'s `input_schema`.
/// `stdin` carries pipeline input from a prior command, if any.
pub struct ToolArgs {
    /// Parsed parameters as a JSON object. Keys from `--key value` flags.
    pub params: serde_json::Value,
    /// Pipeline input from a prior command (e.g. `echo data | tool`).
    pub stdin: Option<String>,
}

impl ToolArgs {
    /// Get a string parameter by name.
    pub fn param_str(&self, key: &str) -> Option<&str> {
        self.params.get(key).and_then(|v| v.as_str())
    }

    /// Get an integer parameter by name.
    pub fn param_i64(&self, key: &str) -> Option<i64> {
        self.params.get(key).and_then(|v| v.as_i64())
    }

    /// Get a float parameter by name.
    pub fn param_f64(&self, key: &str) -> Option<f64> {
        self.params.get(key).and_then(|v| v.as_f64())
    }

    /// Get a boolean parameter by name.
    pub fn param_bool(&self, key: &str) -> Option<bool> {
        self.params.get(key).and_then(|v| v.as_bool())
    }
}

// ============================================================================
// Exec types — sync and async execution functions
// ============================================================================

/// Synchronous execution function for a tool.
///
/// Receives parsed [`ToolArgs`] with typed parameters and optional stdin.
/// Return `Ok(stdout)` on success or `Err(message)` on failure.
pub type SyncToolExec = Arc<dyn Fn(&ToolArgs) -> std::result::Result<String, String> + Send + Sync>;

/// Asynchronous execution function for a tool.
///
/// Same contract as [`SyncToolExec`] but returns a `Future`, allowing
/// non-blocking I/O. Takes owned [`ToolArgs`] because the future may
/// outlive the borrow.
pub type AsyncToolExec = Arc<
    dyn Fn(ToolArgs) -> Pin<Box<dyn Future<Output = std::result::Result<String, String>> + Send>>
        + Send
        + Sync,
>;

// Keep old names as aliases for backward compatibility.
/// Alias for [`SyncToolExec`] (backward compatibility).
pub type ToolCallback = SyncToolExec;
/// Alias for [`AsyncToolExec`] (backward compatibility).
pub type AsyncToolCallback = AsyncToolExec;

// ============================================================================
// ToolImpl — complete tool: metadata + execution
// ============================================================================

/// Complete tool: definition + sync/async exec functions.
///
/// Implements [`Builtin`] so it can be registered directly in a Bash
/// interpreter or used inside a `ScriptedTool`.
///
/// # Example
///
/// ```rust
/// use bashkit::{ToolDef, ToolImpl};
///
/// let tool = ToolImpl::new(
///     ToolDef::new("greet", "Greet a user")
///         .with_schema(serde_json::json!({
///             "type": "object",
///             "properties": { "name": {"type": "string"} }
///         })),
/// )
/// .with_exec_sync(|args| {
///     let name = args.param_str("name").unwrap_or("world");
///     Ok(format!("hello {name}\n"))
/// });
/// ```
#[derive(Clone)]
pub struct ToolImpl {
    /// Tool metadata (name, description, schema, tags).
    pub def: ToolDef,
    /// Async exec (preferred when running in async context).
    pub exec: Option<AsyncToolExec>,
    /// Sync exec (preferred when running in sync context).
    pub exec_sync: Option<SyncToolExec>,
}

impl ToolImpl {
    /// Create a `ToolImpl` from a [`ToolDef`] with no exec functions.
    pub fn new(def: ToolDef) -> Self {
        Self {
            def,
            exec: None,
            exec_sync: None,
        }
    }

    /// Set the async exec function.
    pub fn with_exec<F, Fut>(mut self, f: F) -> Self
    where
        F: Fn(ToolArgs) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = std::result::Result<String, String>> + Send + 'static,
    {
        self.exec = Some(Arc::new(move |args| Box::pin(f(args))));
        self
    }

    /// Set the sync exec function.
    pub fn with_exec_sync(
        mut self,
        f: impl Fn(&ToolArgs) -> std::result::Result<String, String> + Send + Sync + 'static,
    ) -> Self {
        self.exec_sync = Some(Arc::new(f));
        self
    }
}

#[async_trait]
impl Builtin for ToolImpl {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        let params = parse_flags(ctx.args, &self.def.input_schema)
            .map_err(|e| crate::error::Error::Execution(format!("{}: {e}", self.def.name)))?;
        let tool_args = ToolArgs {
            params,
            stdin: ctx.stdin.map(String::from),
        };

        // Prefer async, fall back to sync.
        let result = if let Some(cb) = &self.exec {
            (cb)(tool_args).await
        } else if let Some(cb) = &self.exec_sync {
            (cb)(&tool_args)
        } else {
            return Err(crate::error::Error::Execution(format!(
                "{}: no exec defined",
                self.def.name
            )));
        };

        match result {
            Ok(stdout) => Ok(ExecResult::ok(stdout)),
            Err(msg) => Ok(ExecResult::err(msg, 1)),
        }
    }
}

// ============================================================================
// Flag parser — `--key value` / `--key=value` → JSON object
// ============================================================================

/// Parse `--key value` and `--key=value` flags into a JSON object.
/// Types are coerced according to the schema's property definitions.
/// Unknown flags (not in schema) are kept as strings.
/// Bare `--flag` without a value is treated as `true` if the schema says boolean,
/// otherwise as `true` when the next arg also starts with `--` or is absent.
///
/// For aggregate flags (`type: "object"` or `type: "array"`), `key=value`
/// pair tokens are accepted alongside JSON: a sequence of pair tokens
/// after `--flag` is collected into one object; repeated invocations of an
/// array-of-object flag append one object per group. Arrays of scalars
/// accept comma-split values (`--tags a,b,c`) and repeated invocations.
pub(crate) fn parse_flags(
    raw_args: &[String],
    schema: &serde_json::Value,
) -> std::result::Result<serde_json::Value, String> {
    let properties = schema
        .get("properties")
        .and_then(|p| p.as_object())
        .cloned()
        .unwrap_or_default();

    let mut result = serde_json::Map::new();
    let mut i = 0;

    while i < raw_args.len() {
        let arg = &raw_args[i];

        let Some(flag) = arg.strip_prefix("--") else {
            return Err(format!("expected --flag, got: {arg}"));
        };

        // --key=value
        if let Some((key, raw_value)) = flag.split_once('=') {
            let value = coerce_value(raw_value, properties.get(key), schema);
            result.insert(key.to_string(), value);
            i += 1;
            continue;
        }

        let key = flag.to_string();
        let prop_schema = properties.get(&key).cloned();
        let effective = prop_schema
            .as_ref()
            .map(|s| resolve_effective_type(s, schema, 0))
            .unwrap_or(EffectiveType::Unknown);

        i += 1;

        match effective {
            EffectiveType::Boolean => {
                result.insert(key, serde_json::Value::Bool(true));
            }
            EffectiveType::Array => {
                let items_schema = prop_schema.as_ref().and_then(|s| s.get("items")).cloned();
                let items_effective = items_schema
                    .as_ref()
                    .map(|s| resolve_effective_type(s, schema, 0))
                    .unwrap_or(EffectiveType::Unknown);

                match consume_array_value(
                    raw_args,
                    &mut i,
                    items_schema.as_ref(),
                    items_effective,
                    schema,
                    &key,
                )? {
                    ArrayInput::Items(items) => {
                        let entry = result
                            .entry(key)
                            .or_insert_with(|| serde_json::Value::Array(Vec::new()));
                        if let serde_json::Value::Array(arr) = entry {
                            arr.extend(items);
                        } else {
                            *entry = serde_json::Value::Array(items);
                        }
                    }
                    ArrayInput::Raw(value) => {
                        // Invalid JSON — preserve as raw string so serde
                        // produces the real type-mismatch error downstream.
                        result.insert(key, value);
                    }
                }
            }
            EffectiveType::Object => {
                let value =
                    consume_object_value(raw_args, &mut i, prop_schema.as_ref(), schema, &key)?;
                result.insert(key, value);
            }
            _ => {
                if i < raw_args.len() && !raw_args[i].starts_with("--") {
                    let raw_value = &raw_args[i];
                    let value = coerce_value(raw_value, prop_schema.as_ref(), schema);
                    result.insert(key, value);
                    i += 1;
                } else {
                    result.insert(key, serde_json::Value::Bool(true));
                }
            }
        }
    }

    Ok(serde_json::Value::Object(result))
}

/// Walk a schema to extract object property definitions, following `$ref`
/// and merging properties across `oneOf`/`anyOf`/`allOf` branches.
fn resolve_object_properties(
    schema: &serde_json::Value,
    root_schema: &serde_json::Value,
    depth: usize,
) -> serde_json::Map<String, serde_json::Value> {
    if depth > MAX_REF_DEPTH {
        return Default::default();
    }
    if let Some(ref_str) = schema.get("$ref").and_then(|r| r.as_str()) {
        if let Some(target) = resolve_ref(ref_str, root_schema) {
            return resolve_object_properties(target, root_schema, depth + 1);
        }
        return Default::default();
    }
    if let Some(props) = schema.get("properties").and_then(|p| p.as_object()) {
        return props.clone();
    }
    let mut merged = serde_json::Map::new();
    for key in ["oneOf", "anyOf", "allOf"] {
        if let Some(branches) = schema.get(key).and_then(|v| v.as_array()) {
            for branch in branches {
                let props = resolve_object_properties(branch, root_schema, depth + 1);
                for (k, v) in props {
                    merged.entry(k).or_insert(v);
                }
            }
        }
    }
    merged
}

/// Collect `key=value` tokens into an object until the next `--flag` or end of args.
fn collect_object_from_pairs(
    args: &[String],
    i: &mut usize,
    object_schema: Option<&serde_json::Value>,
    root_schema: &serde_json::Value,
    flag_name: &str,
) -> std::result::Result<serde_json::Map<String, serde_json::Value>, String> {
    let mut obj = serde_json::Map::new();
    let inner_props = object_schema
        .map(|s| resolve_object_properties(s, root_schema, 0))
        .unwrap_or_default();

    while *i < args.len() {
        let arg = &args[*i];
        if arg.starts_with("--") {
            break;
        }
        let Some((k, v)) = arg.split_once('=') else {
            return Err(format!(
                "--{flag_name}: expected --flag or key=value, got '{arg}'"
            ));
        };

        if !inner_props.is_empty() && !inner_props.contains_key(k) {
            let mut valid: Vec<&str> = inner_props.keys().map(|s| s.as_str()).collect();
            valid.sort();
            return Err(format!(
                "--{flag_name}: unknown key '{k}'; valid keys: {}",
                valid.join(", ")
            ));
        }

        let nested_schema = inner_props.get(k);
        let value = coerce_value(v, nested_schema, root_schema);
        obj.insert(k.to_string(), value);
        *i += 1;
    }
    Ok(obj)
}

/// Result of consuming the value(s) after an array-typed `--flag`.
enum ArrayInput {
    /// Items to append to the accumulated array for this flag.
    Items(Vec<serde_json::Value>),
    /// Raw fallback (typically when JSON parse failed) — overrides the
    /// array entry with this value so serde surfaces the type error.
    Raw(serde_json::Value),
}

/// Consume the value(s) following an array-typed `--flag`.
/// Accepts: JSON array, JSON object (single-element append), `key=value` pair
/// group (single-element append for arrays of objects), or comma-split scalars.
fn consume_array_value(
    args: &[String],
    i: &mut usize,
    items_schema: Option<&serde_json::Value>,
    items_effective: EffectiveType,
    root_schema: &serde_json::Value,
    flag_name: &str,
) -> std::result::Result<ArrayInput, String> {
    if *i >= args.len() || args[*i].starts_with("--") {
        return Ok(ArrayInput::Items(Vec::new()));
    }
    let next = &args[*i];
    let trimmed = next.trim_start();

    if trimmed.starts_with('[') {
        if let Ok(serde_json::Value::Array(arr)) = serde_json::from_str::<serde_json::Value>(next) {
            *i += 1;
            return Ok(ArrayInput::Items(arr));
        }
        *i += 1;
        return Ok(ArrayInput::Raw(serde_json::Value::String(next.clone())));
    }

    if items_effective == EffectiveType::Object {
        if trimmed.starts_with('{') {
            if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(next) {
                *i += 1;
                return Ok(ArrayInput::Items(vec![parsed]));
            }
            *i += 1;
            return Ok(ArrayInput::Raw(serde_json::Value::String(next.clone())));
        }
        if next.contains('=') {
            let obj = collect_object_from_pairs(args, i, items_schema, root_schema, flag_name)?;
            return Ok(ArrayInput::Items(vec![serde_json::Value::Object(obj)]));
        }
        return Err(format!(
            "--{flag_name}: expected JSON or key=value pairs, got '{next}'"
        ));
    }

    // Scalar items: comma-split.
    let mut out = Vec::new();
    for part in next.split(',') {
        out.push(coerce_value(part, items_schema, root_schema));
    }
    *i += 1;
    Ok(ArrayInput::Items(out))
}

/// Consume the value(s) following an object-typed `--flag`.
/// Accepts: JSON object/array literal, or a `key=value` pair group.
fn consume_object_value(
    args: &[String],
    i: &mut usize,
    prop_schema: Option<&serde_json::Value>,
    root_schema: &serde_json::Value,
    flag_name: &str,
) -> std::result::Result<serde_json::Value, String> {
    if *i >= args.len() || args[*i].starts_with("--") {
        return Ok(serde_json::Value::Bool(true));
    }
    let next = &args[*i];
    let trimmed = next.trim_start();

    if trimmed.starts_with('{') || trimmed.starts_with('[') {
        let value = coerce_value(next, prop_schema, root_schema);
        *i += 1;
        return Ok(value);
    }

    if next.contains('=') {
        let obj = collect_object_from_pairs(args, i, prop_schema, root_schema, flag_name)?;
        return Ok(serde_json::Value::Object(obj));
    }

    let value = coerce_value(next, prop_schema, root_schema);
    *i += 1;
    Ok(value)
}

/// Effective type of a property schema after resolving `$ref`,
/// `oneOf`/`anyOf`/`allOf` branches, nullable arrays
/// (`type: ["array","null"]`), and implicit signals
/// (`items` ⇒ array, `properties` ⇒ object).
#[derive(PartialEq, Clone, Copy, Debug)]
enum EffectiveType {
    String,
    Integer,
    Number,
    Boolean,
    Array,
    Object,
    Unknown,
}

const MAX_REF_DEPTH: usize = 16;

fn type_str_to_effective(s: &str) -> EffectiveType {
    match s {
        "string" => EffectiveType::String,
        "integer" => EffectiveType::Integer,
        "number" => EffectiveType::Number,
        "boolean" => EffectiveType::Boolean,
        "array" => EffectiveType::Array,
        "object" => EffectiveType::Object,
        _ => EffectiveType::Unknown,
    }
}

fn resolve_ref<'a>(
    ref_str: &str,
    root_schema: &'a serde_json::Value,
) -> Option<&'a serde_json::Value> {
    let suffix = ref_str.strip_prefix("#/")?;
    let mut current = root_schema;
    for segment in suffix.split('/') {
        let decoded = segment.replace("~1", "/").replace("~0", "~");
        current = current.get(&decoded)?;
    }
    Some(current)
}

fn resolve_effective_type(
    schema: &serde_json::Value,
    root_schema: &serde_json::Value,
    depth: usize,
) -> EffectiveType {
    if depth > MAX_REF_DEPTH {
        return EffectiveType::Unknown;
    }

    if let Some(ref_str) = schema.get("$ref").and_then(|r| r.as_str()) {
        if let Some(target) = resolve_ref(ref_str, root_schema) {
            return resolve_effective_type(target, root_schema, depth + 1);
        }
        return EffectiveType::Unknown;
    }

    match schema.get("type") {
        Some(serde_json::Value::String(s)) => return type_str_to_effective(s),
        Some(serde_json::Value::Array(arr)) => {
            // Prefer aggregate types when present; fall back to first non-null scalar.
            for t in arr {
                if let Some(s) = t.as_str()
                    && (s == "array" || s == "object")
                {
                    return type_str_to_effective(s);
                }
            }
            for t in arr {
                if let Some(s) = t.as_str()
                    && s != "null"
                {
                    return type_str_to_effective(s);
                }
            }
        }
        _ => {}
    }

    for key in ["oneOf", "anyOf", "allOf"] {
        if let Some(branches) = schema.get(key).and_then(|v| v.as_array()) {
            for branch in branches {
                let et = resolve_effective_type(branch, root_schema, depth + 1);
                if matches!(et, EffectiveType::Array | EffectiveType::Object) {
                    return et;
                }
            }
            for branch in branches {
                let et = resolve_effective_type(branch, root_schema, depth + 1);
                if !matches!(et, EffectiveType::Unknown) {
                    return et;
                }
            }
        }
    }

    if schema.get("items").is_some() {
        return EffectiveType::Array;
    }
    if schema.get("properties").is_some() {
        return EffectiveType::Object;
    }

    EffectiveType::Unknown
}

/// Coerce a raw string value to the type declared in the property schema.
fn coerce_value(
    raw: &str,
    prop_schema: Option<&serde_json::Value>,
    root_schema: &serde_json::Value,
) -> serde_json::Value {
    let effective = prop_schema
        .map(|s| resolve_effective_type(s, root_schema, 0))
        .unwrap_or(EffectiveType::Unknown);

    match effective {
        EffectiveType::Integer => raw
            .parse::<i64>()
            .map(serde_json::Value::from)
            .unwrap_or_else(|_| serde_json::Value::String(raw.to_string())),
        EffectiveType::Number => raw
            .parse::<f64>()
            .map(|n| serde_json::json!(n))
            .unwrap_or_else(|_| serde_json::Value::String(raw.to_string())),
        EffectiveType::Boolean => match raw {
            "true" | "1" | "yes" => serde_json::Value::Bool(true),
            "false" | "0" | "no" => serde_json::Value::Bool(false),
            _ => serde_json::Value::String(raw.to_string()),
        },
        EffectiveType::Array | EffectiveType::Object => {
            let trimmed = raw.trim_start();
            if (trimmed.starts_with('[') || trimmed.starts_with('{'))
                && let Ok(parsed) = serde_json::from_str::<serde_json::Value>(raw)
            {
                return parsed;
            }
            serde_json::Value::String(raw.to_string())
        }
        EffectiveType::String | EffectiveType::Unknown => {
            serde_json::Value::String(raw.to_string())
        }
    }
}

/// Generate a usage hint from schema properties: `--id <integer> --name <string>`.
/// Aggregate flags advertise both JSON and `key=value` forms in their hint.
pub(crate) fn usage_from_schema(schema: &serde_json::Value) -> Option<String> {
    let props = schema.get("properties")?.as_object()?;
    if props.is_empty() {
        return None;
    }
    let flags: Vec<String> = props
        .iter()
        .map(|(key, prop)| {
            let hint = match resolve_effective_type(prop, schema, 0) {
                EffectiveType::Object => "<json|key=value...>".to_string(),
                EffectiveType::Array => {
                    let items = prop.get("items");
                    let items_eff = items
                        .map(|s| resolve_effective_type(s, schema, 0))
                        .unwrap_or(EffectiveType::Unknown);
                    if items_eff == EffectiveType::Object {
                        "<json|key=value...>".to_string()
                    } else {
                        "<json|a,b,c>".to_string()
                    }
                }
                EffectiveType::Integer => "<integer>".to_string(),
                EffectiveType::Number => "<number>".to_string(),
                EffectiveType::Boolean => "<boolean>".to_string(),
                EffectiveType::String => "<string>".to_string(),
                EffectiveType::Unknown => {
                    let ty = prop.get("type").and_then(|t| t.as_str()).unwrap_or("value");
                    format!("<{ty}>")
                }
            };
            format!("--{key} {hint}")
        })
        .collect();
    Some(flags.join(" "))
}

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

    #[test]
    fn test_parse_flags_basic() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "id": {"type": "integer"},
                "name": {"type": "string"},
                "verbose": {"type": "boolean"}
            }
        });
        let args = vec![
            "--id".to_string(),
            "42".to_string(),
            "--name".to_string(),
            "Alice".to_string(),
            "--verbose".to_string(),
        ];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["id"], 42);
        assert_eq!(result["name"], "Alice");
        assert_eq!(result["verbose"], true);
    }

    #[test]
    fn test_parse_flags_equals_syntax() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"id": {"type": "integer"}}
        });
        let args = vec!["--id=42".to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["id"], 42);
    }

    #[test]
    fn test_parse_flags_json_array_string() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"tags": {"type": "array", "items": {"type": "string"}}}
        });
        let args = vec!["--tags".to_string(), r#"["a","b","c"]"#.to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["tags"], serde_json::json!(["a", "b", "c"]));
    }

    #[test]
    fn test_parse_flags_json_object_string() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"server": {"type": "object"}}
        });
        let args = vec![
            "--server".to_string(),
            r#"{"name":"foo","port":8080}"#.to_string(),
        ];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(
            result["server"],
            serde_json::json!({"name": "foo", "port": 8080})
        );
    }

    #[test]
    fn test_parse_flags_nullable_array() {
        // utoipa-style nullable: type: ["array", "null"]
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "tags": {"type": ["array", "null"], "items": {"type": "string"}}
            }
        });
        let args = vec!["--tags".to_string(), r#"["x","y"]"#.to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["tags"], serde_json::json!(["x", "y"]));
    }

    #[test]
    fn test_parse_flags_oneof_null_and_ref() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "config": {
                    "oneOf": [
                        {"type": "null"},
                        {"$ref": "#/$defs/Config"}
                    ]
                }
            },
            "$defs": {
                "Config": {"type": "object", "properties": {"k": {"type": "string"}}}
            }
        });
        let args = vec!["--config".to_string(), r#"{"k":"v"}"#.to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["config"], serde_json::json!({"k": "v"}));
    }

    #[test]
    fn test_parse_flags_allof_composition() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "data": {
                    "allOf": [
                        {"type": "object"},
                        {"properties": {"x": {"type": "integer"}}}
                    ]
                }
            }
        });
        let args = vec!["--data".to_string(), r#"{"x":1}"#.to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["data"], serde_json::json!({"x": 1}));
    }

    #[test]
    fn test_parse_flags_invalid_json_left_as_string() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"tags": {"type": "array"}}
        });
        // Malformed JSON — stays as raw string; serde produces the real error downstream.
        let args = vec!["--tags".to_string(), "[1, 2,".to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(
            result["tags"],
            serde_json::Value::String("[1, 2,".to_string())
        );
    }

    #[test]
    fn test_parse_flags_scalar_string_unchanged() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"name": {"type": "string"}}
        });
        let args = vec!["--name".to_string(), "Alice".to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["name"], "Alice");
    }

    #[test]
    fn test_parse_flags_implicit_array_from_items() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"tags": {"items": {"type": "string"}}}
        });
        let args = vec!["--tags".to_string(), r#"["p","q"]"#.to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["tags"], serde_json::json!(["p", "q"]));
    }

    #[test]
    fn test_parse_flags_implicit_object_from_properties() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "server": {"properties": {"port": {"type": "integer"}}}
            }
        });
        let args = vec!["--server".to_string(), r#"{"port":80}"#.to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["server"], serde_json::json!({"port": 80}));
    }

    #[test]
    fn test_parse_flags_ref_into_defs() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"items": {"$ref": "#/$defs/Items"}},
            "$defs": {
                "Items": {"type": "array", "items": {"type": "integer"}}
            }
        });
        let args = vec!["--items".to_string(), "[1,2,3]".to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["items"], serde_json::json!([1, 2, 3]));
    }

    #[test]
    fn test_parse_flags_ref_into_definitions() {
        // Older draft uses `definitions` instead of `$defs`.
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"items": {"$ref": "#/definitions/Items"}},
            "definitions": {
                "Items": {"type": "array"}
            }
        });
        let args = vec!["--items".to_string(), "[1,2]".to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["items"], serde_json::json!([1, 2]));
    }

    #[test]
    fn test_parse_flags_ref_cycle_bounded() {
        // Cyclical $ref must not stack-overflow.
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"x": {"$ref": "#/$defs/A"}},
            "$defs": {
                "A": {"$ref": "#/$defs/B"},
                "B": {"$ref": "#/$defs/A"}
            }
        });
        let args = vec!["--x".to_string(), "value".to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        // Falls back to string when ref cycle is detected.
        assert_eq!(result["x"], "value");
    }

    #[test]
    fn test_parse_flags_array_value_not_starting_with_bracket() {
        // Aggregate scalar array: comma-split (single token, no comma → length-1 array).
        let schema = serde_json::json!({
            "type": "object",
            "properties": {"tags": {"type": "array", "items": {"type": "string"}}}
        });
        let args = vec!["--tags".to_string(), "abc".to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["tags"], serde_json::json!(["abc"]));
    }

    #[test]
    fn test_parse_flags_pair_object_single() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "server": {
                    "type": "object",
                    "properties": {
                        "name": {"type": "string"},
                        "url": {"type": "string"}
                    }
                }
            }
        });
        let args = vec![
            "--server".to_string(),
            "name=foo".to_string(),
            "url=https://example.com".to_string(),
        ];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(
            result["server"],
            serde_json::json!({"name": "foo", "url": "https://example.com"})
        );
    }

    #[test]
    fn test_parse_flags_pair_array_of_objects_repeated() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "mcp_server": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": {"type": "string"},
                            "url": {"type": "string"}
                        }
                    }
                }
            }
        });
        let args = vec![
            "--mcp_server".to_string(),
            "name=a".to_string(),
            "url=u1".to_string(),
            "--mcp_server".to_string(),
            "name=b".to_string(),
            "url=u2".to_string(),
        ];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(
            result["mcp_server"],
            serde_json::json!([
                {"name": "a", "url": "u1"},
                {"name": "b", "url": "u2"}
            ])
        );
    }

    #[test]
    fn test_parse_flags_array_string_comma_split() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "tags": {"type": "array", "items": {"type": "string"}}
            }
        });
        let args = vec!["--tags".to_string(), "a,b,c".to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["tags"], serde_json::json!(["a", "b", "c"]));
    }

    #[test]
    fn test_parse_flags_array_string_repeated_appends() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "tags": {"type": "array", "items": {"type": "string"}}
            }
        });
        let args = vec![
            "--tags".to_string(),
            "x".to_string(),
            "--tags".to_string(),
            "y".to_string(),
        ];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["tags"], serde_json::json!(["x", "y"]));
    }

    #[test]
    fn test_parse_flags_pair_nested_type_coercion() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "server": {
                    "type": "object",
                    "properties": {
                        "enabled": {"type": "boolean"},
                        "port": {"type": "integer"}
                    }
                }
            }
        });
        let args = vec![
            "--server".to_string(),
            "enabled=true".to_string(),
            "port=8080".to_string(),
        ];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(
            result["server"],
            serde_json::json!({"enabled": true, "port": 8080})
        );
    }

    #[test]
    fn test_parse_flags_pair_unknown_key_errors() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "server": {
                    "type": "object",
                    "properties": {
                        "name": {"type": "string"}
                    }
                }
            }
        });
        let args = vec!["--server".to_string(), "bogus=foo".to_string()];
        let err = parse_flags(&args, &schema).unwrap_err();
        assert!(err.contains("unknown key"), "got: {err}");
        assert!(err.contains("bogus"), "got: {err}");
    }

    #[test]
    fn test_parse_flags_object_json_form_unchanged() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "server": {
                    "type": "object",
                    "properties": {"name": {"type": "string"}}
                }
            }
        });
        let args = vec!["--server".to_string(), r#"{"name":"foo"}"#.to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["server"], serde_json::json!({"name": "foo"}));
    }

    #[test]
    fn test_parse_flags_pair_mixed_with_json_rejected() {
        // After consuming JSON `{...}` for --server, a stray `name=foo` token is
        // not a flag and not part of the consumed JSON value, so parse_flags
        // rejects it at the top of the loop.
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "server": {
                    "type": "object",
                    "properties": {"name": {"type": "string"}}
                }
            }
        });
        let args = vec![
            "--server".to_string(),
            r#"{"name":"foo"}"#.to_string(),
            "name=bar".to_string(),
        ];
        let err = parse_flags(&args, &schema).unwrap_err();
        assert!(err.contains("expected --flag"), "got: {err}");
    }

    #[test]
    fn test_parse_flags_array_of_objects_json_then_pair_appends() {
        // JSON for first invocation, pairs for second — both append.
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "mcp_server": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": {"type": "string"}
                        }
                    }
                }
            }
        });
        let args = vec![
            "--mcp_server".to_string(),
            r#"{"name":"j"}"#.to_string(),
            "--mcp_server".to_string(),
            "name=p".to_string(),
        ];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(
            result["mcp_server"],
            serde_json::json!([{"name": "j"}, {"name": "p"}])
        );
    }

    #[test]
    fn test_parse_flags_array_int_comma_split_coerced() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "ids": {"type": "array", "items": {"type": "integer"}}
            }
        });
        let args = vec!["--ids".to_string(), "1,2,3".to_string()];
        let result = parse_flags(&args, &schema).unwrap();
        assert_eq!(result["ids"], serde_json::json!([1, 2, 3]));
    }

    #[test]
    fn test_usage_from_schema_advertises_both_forms() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "server": {"type": "object"},
                "tags": {"type": "array", "items": {"type": "string"}},
                "id": {"type": "integer"}
            }
        });
        let usage = usage_from_schema(&schema).expect("usage");
        assert!(
            usage.contains("--server <json|key=value...>"),
            "got: {usage}"
        );
        assert!(usage.contains("--tags <json|a,b,c>"), "got: {usage}");
        assert!(usage.contains("--id <integer>"), "got: {usage}");
    }

    #[test]
    fn test_tool_impl_sync() {
        let tool = ToolImpl::new(ToolDef::new("greet", "Greet a user").with_schema(
            serde_json::json!({
                "type": "object",
                "properties": { "name": {"type": "string"} }
            }),
        ))
        .with_exec_sync(|args| {
            let name = args.param_str("name").unwrap_or("world");
            Ok(format!("hello {name}\n"))
        });

        assert!(tool.exec_sync.is_some());
        assert!(tool.exec.is_none());
        assert_eq!(tool.def.name, "greet");
    }

    #[tokio::test]
    async fn test_tool_impl_as_builtin() {
        let tool = ToolImpl::new(ToolDef::new("greet", "Greet a user").with_schema(
            serde_json::json!({
                "type": "object",
                "properties": { "name": {"type": "string"} }
            }),
        ))
        .with_exec_sync(|args| {
            let name = args.param_str("name").unwrap_or("world");
            Ok(format!("hello {name}\n"))
        });

        // Verify it works as a Builtin
        let args = vec!["--name".to_string(), "Alice".to_string()];
        let mut vars = std::collections::HashMap::new();
        let env = std::collections::HashMap::new();
        let mut cwd = std::path::PathBuf::from("/");
        let fs = Arc::new(crate::fs::InMemoryFs::new());
        let ctx = Context::new_for_test(&args, &env, &mut vars, &mut cwd, fs, None);
        let result = tool.execute(ctx).await.unwrap();
        assert_eq!(result.stdout, "hello Alice\n");
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_tool_impl_async_exec() {
        let tool =
            ToolImpl::new(ToolDef::new("echo_async", "Async echo")).with_exec(|args| async move {
                let msg = args.stdin.unwrap_or_default();
                Ok(format!("async: {msg}"))
            });

        assert!(tool.exec.is_some());
        assert!(tool.exec_sync.is_none());
    }

    #[tokio::test]
    async fn test_tool_impl_no_exec_errors() {
        let tool = ToolImpl::new(ToolDef::new("empty", "No exec"));

        let args = vec![];
        let mut vars = std::collections::HashMap::new();
        let env = std::collections::HashMap::new();
        let mut cwd = std::path::PathBuf::from("/");
        let fs = Arc::new(crate::fs::InMemoryFs::new());
        let ctx = Context::new_for_test(&args, &env, &mut vars, &mut cwd, fs, None);
        let result = tool.execute(ctx).await;
        assert!(result.is_err());
    }
}