incurs 0.10.1

A declarative CLI framework for Rust with typed commands, agent discovery, HTTP, and MCP
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
//! Transport-neutral tool catalog for incurs command graphs.
//!
//! The catalog is the shared discovery and invocation boundary used by MCP
//! and Code Mode. It preserves command schemas, annotations, middleware, and
//! typed execution without converting a call back into CLI arguments.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::Arc;

use async_trait::async_trait;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
use tokio_util::sync::CancellationToken;

use crate::cli::{Cli, CommandEntry, ConfigOptions};
use crate::command::{
    self, CommandDef, ExecuteOptions, McpAnnotations, McpResultContent, ParseMode, RequestContext,
};
use crate::errors::FieldError;
use crate::middleware::MiddlewareFn;
use crate::output::{CtaBlock, FieldErrorOutput, Format, StreamRecord};
use crate::schema::FieldMeta;

/// Metadata and schemas for one callable command.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDefinition {
    /// Stable tool name exposed to non-CLI transports.
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// JSON Schema for the flat tool input.
    pub input_schema: Value,
    /// JSON Schema for successful structured output.
    pub output_schema: Option<Value>,
    /// Behavioral annotations supplied by the command.
    pub annotations: Option<McpAnnotations>,
    /// Tool-specific instructions for agent clients.
    pub instructions: Option<String>,
    /// Usage examples copied from the command definition.
    pub examples: Vec<ToolExample>,
    /// Rich MCP content derived from a successful structured result.
    pub result_content: Vec<McpResultContent>,
}

/// One transport-neutral tool usage example.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolExample {
    /// The command invocation without the CLI name prefix.
    pub command: String,
    /// A short explanation of the example.
    pub description: Option<String>,
}

/// Source used for declared command and CLI environment fields.
#[derive(Debug, Clone, Default)]
pub enum EnvironmentSource {
    /// Read declared fields from the current process environment.
    #[default]
    DeclaredHost,
    /// Read declared fields from explicit values.
    Values(HashMap<String, String>),
    /// Do not provide environment values.
    Empty,
}

/// Source used for command option defaults.
#[derive(Debug, Clone, Default)]
pub enum ConfigSource {
    /// Use the CLI's configured file discovery.
    #[default]
    Auto,
    /// Load one explicit JSON config file.
    Path(String),
    /// Use an already parsed config tree.
    Values(BTreeMap<String, Value>),
    /// Disable config defaults.
    Disabled,
}

/// Incremental event emitted by a transport-neutral tool invocation.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ToolEvent {
    /// Progress state reported by the runtime.
    Progress {
        /// Human-readable progress message.
        message: String,
        /// Optional completion fraction from zero through one.
        fraction: Option<f64>,
    },
    /// Diagnostic or user-facing log message.
    Log {
        /// Log severity.
        level: String,
        /// Log message.
        message: String,
    },
    /// One item from a streaming command.
    Chunk {
        /// Structured streamed value.
        data: Value,
    },
}

/// Consumer for ordered tool invocation events.
#[async_trait]
pub trait ToolEventSink: Send + Sync {
    /// Receives one event before the next event is emitted.
    async fn emit(&self, event: ToolEvent);
}

/// Execution-scoped cancellation and event delivery.
#[derive(Clone, Default)]
pub struct ToolCallControl {
    /// Cooperative cancellation signal.
    pub cancellation: CancellationToken,
    /// Optional ordered event consumer.
    pub events: Option<Arc<dyn ToolEventSink>>,
}

/// Options for one transport-neutral tool invocation.
#[derive(Clone, Default)]
pub struct ToolCallOptions {
    /// Environment values used to parse command environment fields.
    pub environment: EnvironmentSource,
    /// Command config defaults.
    pub config: ConfigSource,
    /// CLI-level global option overrides.
    pub globals: Option<Value>,
    /// Transport request metadata.
    pub request: Option<RequestContext>,
    /// Execution-scoped cancellation and events.
    pub control: ToolCallControl,
}

impl ToolCallOptions {
    /// Creates options that do not read process environment or filesystem config.
    pub fn isolated() -> Self {
        Self {
            environment: EnvironmentSource::Empty,
            config: ConfigSource::Disabled,
            ..Self::default()
        }
    }
}

/// Failure while resolving a reusable tool catalog.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ToolCatalogError {
    /// Two commands resolve to the same exposed tool name.
    #[error("Tool name \"{name}\" is used by both \"{first}\" and \"{second}\"")]
    DuplicateName {
        /// Colliding exposed name.
        name: String,
        /// First canonical command path.
        first: String,
        /// Second canonical command path.
        second: String,
    },
}

/// Result of one transport-neutral tool invocation.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum ToolCallOutcome {
    /// Successful command output.
    Ok {
        /// Structured command result.
        data: Value,
        /// Optional follow-up commands.
        cta: Option<CtaBlock>,
    },
    /// Structured command failure.
    Error {
        /// Machine-readable error code.
        code: String,
        /// Human-readable error message.
        message: String,
        /// Whether retrying may succeed.
        retryable: Option<bool>,
        /// Per-field validation failures.
        field_errors: Option<Vec<FieldErrorOutput>>,
        /// Optional follow-up commands.
        cta: Option<CtaBlock>,
        /// Optional process-style exit code.
        exit_code: Option<i32>,
    },
}

#[derive(Clone)]
pub(crate) struct ResolvedTool {
    pub(crate) definition: ToolDefinition,
    pub(crate) command: Arc<CommandDef>,
    pub(crate) middleware: Vec<MiddlewareFn>,
    path: String,
}

/// A reusable catalog of tools resolved from an incurs CLI.
#[derive(Clone)]
pub struct ToolCatalog {
    name: String,
    version: Option<String>,
    env_fields: Vec<FieldMeta>,
    globals_fields: Vec<FieldMeta>,
    config: Option<ConfigOptions>,
    root_middleware: Vec<MiddlewareFn>,
    tools: BTreeMap<String, ResolvedTool>,
}

impl ToolCatalog {
    pub(crate) fn from_parts(
        name: String,
        version: Option<String>,
        commands: &BTreeMap<String, CommandEntry>,
        root_middleware: &[MiddlewareFn],
        env_fields: &[FieldMeta],
        globals_fields: &[FieldMeta],
        config: Option<&ConfigOptions>,
    ) -> Result<Self, ToolCatalogError> {
        let mut tools = BTreeMap::new();
        collect(commands, &[], &[], &mut tools)?;
        Ok(Self {
            name,
            version,
            env_fields: env_fields.to_vec(),
            globals_fields: globals_fields.to_vec(),
            config: config.cloned(),
            root_middleware: root_middleware.to_vec(),
            tools,
        })
    }

    /// Returns the CLI name that owns this catalog.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the CLI version, when configured.
    pub fn version(&self) -> Option<&str> {
        self.version.as_deref()
    }

    /// Lists tool definitions in stable name order.
    pub fn definitions(&self) -> Vec<ToolDefinition> {
        self.tools
            .values()
            .map(|tool| tool.definition.clone())
            .collect()
    }

    /// Returns one tool definition by its exposed name.
    pub fn get(&self, name: &str) -> Option<&ToolDefinition> {
        self.tools.get(name).map(|tool| &tool.definition)
    }

    /// Invokes one tool with flat JSON arguments.
    pub async fn call(
        &self,
        name: &str,
        mut arguments: BTreeMap<String, Value>,
        options: ToolCallOptions,
    ) -> ToolCallOutcome {
        let Some(tool) = self.tools.get(name) else {
            return ToolCallOutcome::Error {
                code: "TOOL_NOT_FOUND".to_string(),
                message: format!("Unknown tool: {name}"),
                retryable: Some(false),
                field_errors: None,
                cta: None,
                exit_code: Some(1),
            };
        };

        let environment = match options.environment {
            EnvironmentSource::DeclaredHost => {
                declared_environment(&self.env_fields, &tool.command.env_fields)
            }
            EnvironmentSource::Values(values) => filter_environment(
                values,
                self.env_fields.iter().chain(&tool.command.env_fields),
            ),
            EnvironmentSource::Empty => HashMap::new(),
        };
        let defaults = match self.resolve_config(&options.config, &tool.path) {
            Ok(defaults) => defaults,
            Err(message) => return tool_error("CONFIG_ERROR", message),
        };
        if let Some(defaults) = &defaults {
            for (name, value) in defaults {
                arguments
                    .entry(name.clone())
                    .or_insert_with(|| value.clone());
            }
        }
        if let Some(error) = unknown_argument_error(tool, &self.globals_fields, &arguments) {
            return error;
        }
        let globals = match resolve_globals(options.globals, &self.globals_fields) {
            Ok(globals) => globals,
            Err(message) => return tool_error("VALIDATION_ERROR", message),
        };
        if options.control.cancellation.is_cancelled() {
            return tool_error("CANCELLED", "Tool call cancelled".to_string());
        }
        let cancellation = options.control.cancellation.clone();
        let mut middleware = self.root_middleware.clone();
        middleware.extend(tool.middleware.iter().cloned());
        middleware.extend(tool.command.middleware.iter().cloned());
        let execution = command::execute(
            Arc::clone(&tool.command),
            ExecuteOptions {
                agent: true,
                argv: Vec::new(),
                defaults: None,
                display_name: self.name.clone(),
                env_fields: self.env_fields.clone(),
                env_source: environment,
                format: Format::Json,
                format_explicit: true,
                globals,
                input_options: arguments,
                middlewares: middleware,
                name: self.name.clone(),
                parse_mode: ParseMode::Flat,
                path: tool.path.clone(),
                request: options.request,
                vars_fields: Vec::new(),
                version: self.version.clone(),
            },
        );
        tokio::pin!(execution);
        let result = tokio::select! {
            _ = cancellation.cancelled() => {
                return tool_error("CANCELLED", "Tool call cancelled".to_string());
            }
            result = &mut execution => result,
        };

        match result {
            // A wrapped process exit code is part of the command's data for
            // tool callers; it has no meaning as a transport-level status.
            command::InternalResult::Ok {
                data,
                cta,
                exit_code: _,
            } => ToolCallOutcome::Ok { data, cta },
            command::InternalResult::Error {
                code,
                message,
                retryable,
                field_errors,
                cta,
                exit_code,
            } => ToolCallOutcome::Error {
                code,
                message,
                retryable,
                field_errors: field_errors.map(field_error_outputs),
                cta,
                exit_code,
            },
            command::InternalResult::Stream(mut stream) => {
                let mut data = Vec::new();
                loop {
                    let value = tokio::select! {
                        _ = options.control.cancellation.cancelled() => {
                            return tool_error("CANCELLED", "Tool call cancelled".to_string());
                        }
                        value = stream.next() => value,
                    };
                    let Some(value) = value else {
                        break;
                    };
                    emit_event(
                        &options.control,
                        ToolEvent::Chunk {
                            data: value.clone(),
                        },
                    )
                    .await;
                    data.push(value);
                }
                ToolCallOutcome::Ok {
                    data: Value::Array(data),
                    cta: None,
                }
            }
            command::InternalResult::RecordStream(mut stream) => {
                let mut data = Vec::new();
                loop {
                    let record = tokio::select! {
                        _ = options.control.cancellation.cancelled() => {
                            return tool_error("CANCELLED", "Tool call cancelled".to_string());
                        }
                        record = stream.next() => record,
                    };
                    let Some(record) = record else {
                        break;
                    };
                    match record {
                        StreamRecord::Chunk(value) => {
                            emit_event(
                                &options.control,
                                ToolEvent::Chunk {
                                    data: value.clone(),
                                },
                            )
                            .await;
                            data.push(value);
                        }
                        StreamRecord::Ok { cta } => {
                            return ToolCallOutcome::Ok {
                                data: Value::Array(data),
                                cta,
                            };
                        }
                        StreamRecord::Error {
                            code,
                            message,
                            retryable,
                            exit_code,
                            cta,
                        } => {
                            return ToolCallOutcome::Error {
                                code,
                                message,
                                retryable: Some(retryable),
                                field_errors: None,
                                cta,
                                exit_code,
                            };
                        }
                    }
                }
                ToolCallOutcome::Ok {
                    data: Value::Array(data),
                    cta: None,
                }
            }
        }
    }

    fn resolve_config(
        &self,
        source: &ConfigSource,
        command_path: &str,
    ) -> Result<Option<BTreeMap<String, Value>>, String> {
        let tree = match source {
            ConfigSource::Disabled => return Ok(None),
            ConfigSource::Values(values) => Some(values.clone()),
            ConfigSource::Path(path) => {
                Some(crate::config::load_config(path).map_err(|error| error.to_string())?)
            }
            ConfigSource::Auto => {
                let Some(config) = &self.config else {
                    return Ok(None);
                };
                let Some(path) = crate::config::resolve_config_path(None, &config.files) else {
                    return Ok(None);
                };
                crate::config::load_config(&path).ok()
            }
        };
        tree.map(|tree| {
            crate::config::extract_command_section(&tree, &self.name, command_path)
                .map_err(|error| error.to_string())
        })
        .transpose()
        .map(Option::flatten)
    }

    pub(crate) fn resolved(&self) -> impl Iterator<Item = &ResolvedTool> {
        self.tools.values()
    }
}

async fn emit_event(control: &ToolCallControl, event: ToolEvent) {
    if let Some(events) = &control.events {
        events.emit(event).await;
    }
}

impl Cli {
    /// Tries to resolve this CLI into a reusable transport-neutral tool catalog.
    pub fn try_tool_catalog(&self) -> Result<ToolCatalog, ToolCatalogError> {
        ToolCatalog::from_parts(
            self.name.clone(),
            self.version.clone(),
            &self.commands,
            &self.middleware,
            &self.env_fields,
            &self.globals_fields,
            self.config.as_ref(),
        )
    }

    /// Resolves this CLI into a reusable transport-neutral tool catalog.
    ///
    /// # Panics
    ///
    /// Panics when two commands use the same exposed tool name. Use
    /// [`Cli::try_tool_catalog`] to handle that configuration error.
    pub fn tool_catalog(&self) -> ToolCatalog {
        self.try_tool_catalog()
            .expect("CLI command graph must have unique tool names")
    }
}

fn collect(
    commands: &BTreeMap<String, CommandEntry>,
    prefix: &[String],
    parent_middleware: &[MiddlewareFn],
    result: &mut BTreeMap<String, ResolvedTool>,
) -> Result<(), ToolCatalogError> {
    for (name, entry) in commands {
        let mut path = prefix.to_vec();
        path.push(name.clone());
        match entry {
            CommandEntry::Leaf(command) => {
                let mcp = command.handler.mcp_options().cloned().unwrap_or_default();
                if !mcp.enabled || command.hidden {
                    continue;
                }
                let name = mcp.name.clone().unwrap_or_else(|| path.join("_"));
                let command_path = path.join(" ");
                if let Some(previous) = result.get(&name) {
                    return Err(ToolCatalogError::DuplicateName {
                        name,
                        first: previous.path.clone(),
                        second: command_path,
                    });
                }
                let input_schema =
                    command
                        .handler
                        .mcp_input_schema()
                        .cloned()
                        .unwrap_or_else(|| {
                            crate::mcp::build_tool_schema(
                                &command.args_fields,
                                &command.options_fields,
                            )
                        });
                result.insert(
                    name.clone(),
                    ResolvedTool {
                        definition: ToolDefinition {
                            name,
                            description: mcp
                                .description
                                .clone()
                                .or_else(|| command.description.clone())
                                .unwrap_or_default(),
                            input_schema,
                            output_schema: command.output_schema.clone(),
                            annotations: mcp.annotations.clone(),
                            instructions: mcp.instructions.clone(),
                            examples: command
                                .examples
                                .iter()
                                .map(|example| ToolExample {
                                    command: example.command.clone(),
                                    description: example.description.clone(),
                                })
                                .collect(),
                            result_content: mcp.result_content.clone(),
                        },
                        command: Arc::clone(command),
                        middleware: parent_middleware.to_vec(),
                        path: command_path,
                    },
                );
            }
            CommandEntry::Group {
                commands,
                middleware,
                ..
            } => {
                let mut inherited = parent_middleware.to_vec();
                inherited.extend(middleware.iter().cloned());
                collect(commands, &path, &inherited, result)?;
            }
            CommandEntry::FetchGateway { .. } => {}
        }
    }
    Ok(())
}

fn declared_environment(
    cli_fields: &[FieldMeta],
    command_fields: &[FieldMeta],
) -> HashMap<String, String> {
    filter_environment(
        std::env::vars().collect(),
        cli_fields.iter().chain(command_fields),
    )
}

fn filter_environment<'a>(
    source: HashMap<String, String>,
    fields: impl Iterator<Item = &'a FieldMeta>,
) -> HashMap<String, String> {
    fields
        .filter_map(|field| {
            let name = field.env_name.unwrap_or(field.name);
            source
                .get(name)
                .map(|value| (name.to_string(), value.clone()))
        })
        .collect()
}

fn resolve_globals(overrides: Option<Value>, fields: &[FieldMeta]) -> Result<Value, String> {
    let input = match overrides.unwrap_or_else(|| Value::Object(serde_json::Map::new())) {
        Value::Object(values) => values.into_iter().collect(),
        _ => return Err("Global options must be an object".to_string()),
    };
    crate::parser::parse_global_input(input, fields)
        .map(|(globals, _)| globals)
        .map_err(|error| error.to_string())
}

/// Returns the declared names a caller may use for one tool, in either spelling.
///
/// Both are accepted because both are published: the JSON schema names fields in
/// snake_case and the CLI names the same field in kebab-case.
fn declared_argument_names(tool: &ResolvedTool, globals: &[FieldMeta]) -> BTreeSet<String> {
    tool.command
        .args_fields
        .iter()
        .chain(&tool.command.options_fields)
        .chain(globals)
        .flat_map(|field| [field.name.to_string(), field.cli_name.clone()])
        .collect()
}

/// Returns a declared name close enough to be what the caller meant.
///
/// One edit covers the mistakes that actually happen -- a plural (`args` for
/// `arg`), a dropped letter, a transposition -- and stops well short of guessing.
fn nearest_declared_name(candidate: &str, declared: &BTreeSet<String>) -> Option<String> {
    declared
        .iter()
        .find(|name| within_one_edit(candidate, name))
        .cloned()
}

/// Returns whether two names differ by at most one insertion, deletion or change.
fn within_one_edit(left: &str, right: &str) -> bool {
    let (left, right): (Vec<char>, Vec<char>) = (left.chars().collect(), right.chars().collect());
    if left.len().abs_diff(right.len()) > 1 {
        return false;
    }
    let (shorter, longer) = if left.len() <= right.len() {
        (&left, &right)
    } else {
        (&right, &left)
    };
    let mut short_index = 0;
    let mut long_index = 0;
    let mut edited = false;
    while short_index < shorter.len() && long_index < longer.len() {
        if shorter[short_index] == longer[long_index] {
            short_index += 1;
            long_index += 1;
            continue;
        }
        if edited {
            return false;
        }
        edited = true;
        if shorter.len() == longer.len() {
            short_index += 1;
        }
        long_index += 1;
    }
    true
}

/// Rejects an argument the tool does not declare.
///
/// A dropped key is the worst failure this surface has, because it does not look
/// like a failure. Passing `args` where the schema says `arg` bound nothing, so
/// the command ran with no arguments at all and the caller saw a program that
/// hung rather than a name that was wrong. The CLI parser has always answered an
/// unknown flag with `Unknown flag: --foo`; the typed path silently accepted it.
fn unknown_argument_error(
    tool: &ResolvedTool,
    globals: &[FieldMeta],
    arguments: &BTreeMap<String, Value>,
) -> Option<ToolCallOutcome> {
    // A command that declares no arguments of its own accepts whatever it is
    // handed -- that is a real pattern, not an oversight, and checking it would
    // reject callers that were always correct. Only a command that published a
    // schema is held to it.
    if tool.command.args_fields.is_empty() && tool.command.options_fields.is_empty() {
        return None;
    }
    let declared = declared_argument_names(tool, globals);
    let unknown: Vec<&String> = arguments
        .keys()
        .filter(|name| !declared.contains(*name))
        .collect();
    if unknown.is_empty() {
        return None;
    }
    let field_errors = unknown
        .iter()
        .map(|name| {
            let suggestion = nearest_declared_name(name, &declared);
            FieldError {
                path: (*name).clone(),
                expected: suggestion
                    .clone()
                    .unwrap_or_else(|| "a declared argument".to_string()),
                received: (*name).clone(),
                message: match suggestion {
                    Some(nearest) => {
                        format!("Unknown argument \"{name}\". Did you mean \"{nearest}\"?")
                    }
                    None => format!("Unknown argument \"{name}\"."),
                },
            }
        })
        .collect::<Vec<_>>();
    Some(ToolCallOutcome::Error {
        code: "VALIDATION_ERROR".to_string(),
        message: "Validation failed".to_string(),
        retryable: Some(false),
        field_errors: Some(field_error_outputs(field_errors)),
        cta: None,
        exit_code: Some(1),
    })
}

fn tool_error(code: &str, message: String) -> ToolCallOutcome {
    ToolCallOutcome::Error {
        code: code.to_string(),
        message,
        retryable: Some(false),
        field_errors: None,
        cta: None,
        exit_code: Some(1),
    }
}

fn field_error_outputs(errors: Vec<FieldError>) -> Vec<FieldErrorOutput> {
    errors.iter().map(FieldErrorOutput::from).collect()
}

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

    #[test]
    fn isolated_call_options_disable_host_sources() {
        let options = ToolCallOptions::isolated();
        assert!(matches!(options.environment, EnvironmentSource::Empty));
        assert!(matches!(options.config, ConfigSource::Disabled));
    }
    use crate::cli::ConfigOptions;
    use crate::command::{CommandContext, CommandHandler, Example, McpCommandOptions};
    use crate::output::CommandResult;
    use crate::schema::FieldType;
    use tokio::sync::Mutex;

    struct Echo;

    #[async_trait::async_trait]
    impl CommandHandler for Echo {
        async fn run(&self, ctx: CommandContext) -> CommandResult {
            CommandResult::Ok {
                data: ctx.options,
                cta: None,
                exit_code: None,
            }
        }
    }

    struct Context;

    #[async_trait::async_trait]
    impl CommandHandler for Context {
        async fn run(&self, ctx: CommandContext) -> CommandResult {
            CommandResult::Ok {
                data: serde_json::json!({
                    "env": ctx.env,
                    "globals": ctx.globals,
                    "options": ctx.options,
                    "request": ctx.request.map(|request| request.path),
                }),
                cta: None,
                exit_code: None,
            }
        }
    }

    struct Streaming;

    #[async_trait::async_trait]
    impl CommandHandler for Streaming {
        async fn run(&self, _ctx: CommandContext) -> CommandResult {
            CommandResult::Stream(Box::pin(futures::stream::iter([
                serde_json::json!(1),
                serde_json::json!(2),
            ])))
        }
    }

    struct Waiting;

    #[async_trait::async_trait]
    impl CommandHandler for Waiting {
        async fn run(&self, _ctx: CommandContext) -> CommandResult {
            futures::future::pending().await
        }
    }

    #[derive(Default)]
    struct Events(Mutex<Vec<ToolEvent>>);

    #[async_trait::async_trait]
    impl ToolEventSink for Events {
        async fn emit(&self, event: ToolEvent) {
            self.0.lock().await.push(event);
        }
    }

    fn field(
        name: &'static str,
        env_name: Option<&'static str>,
        default: Option<Value>,
    ) -> FieldMeta {
        FieldMeta {
            name,
            cli_name: name.replace('_', "-"),
            description: None,
            field_type: FieldType::String,
            required: false,
            default,
            alias: None,
            deprecated: false,
            env_name,
        }
    }

    #[tokio::test]
    async fn resolves_and_calls_commands() {
        let catalog = Cli::create("demo")
            .version("1.0.0")
            .command("echo", CommandDef::build("echo", Echo).done())
            .tool_catalog();

        assert_eq!(catalog.name(), "demo");
        assert_eq!(catalog.version(), Some("1.0.0"));
        assert_eq!(catalog.definitions()[0].name, "echo");

        let outcome = catalog
            .call(
                "echo",
                BTreeMap::from([("message".to_string(), Value::String("hi".to_string()))]),
                ToolCallOptions::default(),
            )
            .await;
        assert!(matches!(
            outcome,
            ToolCallOutcome::Ok { data, .. } if data["message"] == "hi"
        ));
    }

    #[tokio::test]
    async fn reports_unknown_tools() {
        let outcome = Cli::create("demo")
            .tool_catalog()
            .call("missing", BTreeMap::new(), ToolCallOptions::default())
            .await;
        assert!(matches!(
            outcome,
            ToolCallOutcome::Error { code, .. } if code == "TOOL_NOT_FOUND"
        ));
    }

    #[tokio::test]
    async fn resolves_declared_environment_globals_and_config_values() {
        let mut command = CommandDef::build("deploy", Context).done();
        command.env_fields = vec![field("token", Some("DEMO_TOKEN"), None)];
        command.options_fields = vec![field("region", None, None)];
        let catalog = Cli::create("demo")
            .globals_fields(vec![field(
                "profile",
                None,
                Some(Value::String("default".to_string())),
            )])
            .config(ConfigOptions {
                flag: "config".to_string(),
                files: Vec::new(),
            })
            .group(Cli::create("admin").command("deploy", command))
            .tool_catalog();
        let outcome = catalog
            .call(
                "admin_deploy",
                BTreeMap::new(),
                ToolCallOptions {
                    environment: EnvironmentSource::Values(HashMap::from([
                        ("DEMO_TOKEN".to_string(), "secret".to_string()),
                        ("UNDECLARED".to_string(), "hidden".to_string()),
                    ])),
                    config: ConfigSource::Values(BTreeMap::from([(
                        "commands".to_string(),
                        serde_json::json!({
                            "admin": {
                                "commands": {
                                    "deploy": {
                                        "options": { "region": "us-east" }
                                    }
                                }
                            }
                        }),
                    )])),
                    globals: None,
                    request: Some(RequestContext {
                        path: "test-request".to_string(),
                        ..RequestContext::default()
                    }),
                    control: ToolCallControl::default(),
                },
            )
            .await;

        assert!(
            matches!(
            outcome,
            ToolCallOutcome::Ok { ref data, .. }
                if *data == serde_json::json!({
                    "env": { "token": "secret" },
                    "globals": { "profile": "default" },
                    "options": { "region": "us-east" },
                    "request": "test-request",
                })
            ),
            "{outcome:#?}"
        );
    }

    /// Stands in for a command that publishes a schema.
    ///
    /// Written out rather than derived because the derive emits `incurs::` paths,
    /// which do not resolve inside this crate.
    struct RunArgv;

    impl crate::schema::IncurSchema for RunArgv {
        fn fields() -> Vec<FieldMeta> {
            vec![
                FieldMeta {
                    name: "executable",
                    cli_name: "executable".to_string(),
                    description: None,
                    field_type: FieldType::String,
                    required: true,
                    default: None,
                    alias: None,
                    deprecated: false,
                    env_name: None,
                },
                FieldMeta {
                    name: "arg",
                    cli_name: "arg".to_string(),
                    description: None,
                    field_type: FieldType::Array(Box::new(FieldType::String)),
                    required: false,
                    default: None,
                    alias: None,
                    deprecated: false,
                    env_name: None,
                },
            ]
        }

        fn from_raw(
            _raw: &BTreeMap<String, Value>,
        ) -> std::result::Result<Self, crate::errors::ValidationError> {
            Ok(RunArgv)
        }
    }

    struct Run;

    #[async_trait::async_trait]
    impl CommandHandler for Run {
        async fn run(&self, ctx: CommandContext) -> CommandResult {
            CommandResult::Ok {
                data: ctx.args,
                cta: None,
                exit_code: None,
            }
        }
    }

    #[tokio::test]
    async fn an_undeclared_argument_is_rejected_and_the_near_miss_named() {
        // A dropped key does not look like a failure. `args` for `arg` bound
        // nothing, so the command ran with no arguments at all and the caller saw
        // a program that hung rather than a name that was wrong.
        let catalog = Cli::create("demo")
            .version("1.0.0")
            .command(
                "run",
                CommandDef::build("run", Run).args::<RunArgv>().done(),
            )
            .tool_catalog();

        let outcome = catalog
            .call(
                "run",
                BTreeMap::from([
                    ("executable".to_string(), Value::String("node".to_string())),
                    ("args".to_string(), Value::Array(vec![])),
                ]),
                ToolCallOptions::default(),
            )
            .await;

        let ToolCallOutcome::Error {
            code, field_errors, ..
        } = outcome
        else {
            panic!("an undeclared argument must not be silently dropped: {outcome:?}");
        };
        assert_eq!(code, "VALIDATION_ERROR");
        let errors = field_errors.expect("field errors naming the argument");
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].path, "args");
        assert!(
            errors[0].message.contains("Did you mean \"arg\""),
            "the suggestion is the whole point: {}",
            errors[0].message
        );
    }

    #[tokio::test]
    async fn a_declared_argument_still_passes() {
        let catalog = Cli::create("demo")
            .version("1.0.0")
            .command(
                "run",
                CommandDef::build("run", Run).args::<RunArgv>().done(),
            )
            .tool_catalog();

        let outcome = catalog
            .call(
                "run",
                BTreeMap::from([("executable".to_string(), Value::String("node".to_string()))]),
                ToolCallOptions::default(),
            )
            .await;

        assert!(
            matches!(&outcome, ToolCallOutcome::Ok { .. }),
            "a declared argument must still be accepted: {outcome:?}"
        );
    }

    #[test]
    fn tool_catalog_definitions_honor_mcp_input_schema_override() {
        let published = serde_json::json!({
            "type": "object",
            "properties": {
                "executable": {"type": "string"},
                "arg": {
                    "type": "array",
                    "items": {"type": "object"},
                },
            },
            "required": ["executable"],
        });
        let catalog = Cli::create("demo")
            .command(
                "run",
                CommandDef::build("run", Run)
                    .args::<RunArgv>()
                    .mcp(McpCommandOptions {
                        input_schema: Some(published.clone()),
                        ..McpCommandOptions::default()
                    })
                    .done(),
            )
            .tool_catalog();

        let definition = catalog.definitions().remove(0);
        assert_eq!(definition.input_schema, published);
    }

    #[test]
    fn tool_catalog_definitions_derive_schema_without_override() {
        let catalog = Cli::create("demo")
            .command(
                "run",
                CommandDef::build("run", Run).args::<RunArgv>().done(),
            )
            .tool_catalog();

        let definition = catalog.definitions().remove(0);
        let properties = definition.input_schema["properties"]
            .as_object()
            .expect("derived schema has properties");
        assert!(properties.contains_key("executable"));
        assert!(properties.contains_key("arg"));
    }

    #[tokio::test]
    async fn mcp_input_schema_override_does_not_relax_the_undeclared_argument_gate() {
        // The override changes what tools/list advertises, not what a call
        // may bind: validation still runs against the command's declared
        // args/options fields, per McpCommandOptions::input_schema.
        let published = serde_json::json!({
            "type": "object",
            "properties": {
                "executable": {"type": "string"},
                "arg": {"type": "array", "items": {"type": "string"}},
                "extra": {"type": "string"},
            },
        });
        let catalog = Cli::create("demo")
            .command(
                "run",
                CommandDef::build("run", Run)
                    .args::<RunArgv>()
                    .mcp(McpCommandOptions {
                        input_schema: Some(published),
                        ..McpCommandOptions::default()
                    })
                    .done(),
            )
            .tool_catalog();

        let outcome = catalog
            .call(
                "run",
                BTreeMap::from([
                    ("executable".to_string(), Value::String("node".to_string())),
                    ("extra".to_string(), Value::String("unused".to_string())),
                ]),
                ToolCallOptions::default(),
            )
            .await;

        let ToolCallOutcome::Error { code, .. } = outcome else {
            panic!(
                "a property the override advertises but the command never declared must still be rejected: {outcome:?}"
            );
        };
        assert_eq!(code, "VALIDATION_ERROR");
    }

    #[test]
    fn exposes_examples_and_rejects_duplicate_tool_names() {
        let command = || {
            CommandDef::build("echo", Echo)
                .examples(vec![Example {
                    command: "echo --message hi".to_string(),
                    description: Some("Echo a greeting".to_string()),
                }])
                .mcp(McpCommandOptions {
                    name: Some("same".to_string()),
                    ..McpCommandOptions::default()
                })
                .done()
        };
        let cli = Cli::create("demo")
            .command("first", command())
            .command("second", command());

        let error = cli.try_tool_catalog().err().expect("duplicate must fail");
        assert!(matches!(
            error,
            ToolCatalogError::DuplicateName { name, .. } if name == "same"
        ));

        let definition = Cli::create("demo")
            .command("echo", command())
            .tool_catalog()
            .definitions()
            .remove(0);
        assert_eq!(definition.examples[0].command, "echo --message hi");
    }

    #[tokio::test]
    async fn emits_ordered_chunks_and_honors_cancellation() {
        let catalog = Cli::create("demo")
            .command("stream", CommandDef::build("stream", Streaming).done())
            .tool_catalog();
        let events = Arc::new(Events::default());
        let outcome = catalog
            .call(
                "stream",
                BTreeMap::new(),
                ToolCallOptions {
                    control: ToolCallControl {
                        events: Some(events.clone()),
                        ..ToolCallControl::default()
                    },
                    ..ToolCallOptions::default()
                },
            )
            .await;
        assert!(matches!(
            outcome,
            ToolCallOutcome::Ok { data, .. } if data == serde_json::json!([1, 2])
        ));
        assert!(matches!(
            events.0.lock().await.as_slice(),
            [ToolEvent::Chunk { data: first }, ToolEvent::Chunk { data: second }]
                if *first == serde_json::json!(1) && *second == serde_json::json!(2)
        ));

        let control = ToolCallControl::default();
        control.cancellation.cancel();
        let outcome = catalog
            .call(
                "stream",
                BTreeMap::new(),
                ToolCallOptions {
                    control,
                    ..ToolCallOptions::default()
                },
            )
            .await;
        assert!(matches!(
            outcome,
            ToolCallOutcome::Error { code, .. } if code == "CANCELLED"
        ));
    }

    #[tokio::test]
    async fn cancels_an_active_non_streaming_command() {
        let catalog = Cli::create("demo")
            .command("wait", CommandDef::build("wait", Waiting).done())
            .tool_catalog();
        let control = ToolCallControl::default();
        let task_control = control.clone();
        let call = tokio::spawn(async move {
            catalog
                .call(
                    "wait",
                    BTreeMap::new(),
                    ToolCallOptions {
                        control: task_control,
                        ..ToolCallOptions::default()
                    },
                )
                .await
        });
        tokio::task::yield_now().await;
        control.cancellation.cancel();
        let outcome = tokio::time::timeout(std::time::Duration::from_secs(1), call)
            .await
            .unwrap()
            .unwrap();

        assert!(matches!(
            outcome,
            ToolCallOutcome::Error { code, .. } if code == "CANCELLED"
        ));
    }
}