loopctl 0.1.0

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

#[cfg(feature = "tool_health")]
pub mod health;
#[cfg(feature = "tool_shield")]
pub mod shield;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use crate::message::ToolContent as MessageToolContent;

pub mod permission;
pub mod registry;

pub use permission::PermissionCheck;
pub use registry::{FnTool, ToolRegistry};

// ===================================================
// ToolSchema
// ===================================================

/// Schema descriptor for a tool, used for LLM API tool definitions.
///
/// When the agent loop sends a list of available tools to the LLM, each
/// tool is represented by a [`ToolSchema`] instance. The LLM uses the
/// schema's `tool`, `description`, and `input_schema` to decide which
/// tool to call and how to format its arguments.
///
/// # Construction
///
/// Typically produced by [`Tool::schema`] inside each tool implementation:
///
/// ```rust,ignore
/// fn schema(&self) -> ToolSchema {
///     ToolSchema {
///         tool: "read_file".into(),
///         description: "Read a file from disk".into(),
///         input_schema: json!({
///             "type": "object",
///             "properties": {
///                 "path": { "type": "string", "description": "File path" }
///             },
///             "required": ["path"]
///         }),
///     }
/// }
/// ```
///
/// # Serialization
///
/// [`ToolSchema`] derives [`Serialize`] and [`Deserialize`] so it can be
/// embedded directly in LLM API request payloads.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolSchema {
    /// The tool's unique name identifier.
    ///
    /// Must match [`Tool::name`] exactly. Used by the LLM to select which
    /// tool to invoke and by [`ToolRegistry`] as the lookup key.
    pub tool: String,

    /// Human-readable description of what the tool does.
    ///
    /// Sent to the LLM as part of the tool definition. A clear, concise
    /// description helps the model choose the right tool and provide
    /// correct arguments.
    pub description: String,

    /// JSON Schema describing the tool's input parameters.
    ///
    /// Conforms to JSON Schema Draft 07. The LLM uses this to construct
    /// valid `input` objects for [`Tool::call`].
    pub input_schema: Value,
}

// ===================================================
// ToolOutput
// ===================================================

/// Result from a tool invocation.
///
/// Every [`Tool::call`] returns a `Result<ToolOutput, ToolError>`. On
/// success, [`ToolOutput`] wraps the output content (plain text or
/// structured multi-part content) and a flag indicating whether the
/// content represents an error message — this lets tools report *soft*
/// failures (e.g., "file not found") without raising a hard [`ToolError`].
///
/// # Construction
///
/// Use the named constructors rather than building the struct directly:
///
/// ```rust,ignore
/// // Success
/// let ok = ToolOutput::text("hello world");
/// let ok = ToolOutput::success(structured_content);
///
/// // Soft error (tool ran, but the result is an error message)
/// let err = ToolOutput::error_text("file not found");
/// let err = ToolOutput::error(structured_content);
/// ```
///
/// # Content types
///
/// The [`payload`](ToolOutput::payload) field holds a
/// [`MessageToolContent`] which is either a simple [`String`] or a
/// structured list of [`ToolContentPart`](crate::message::ToolContentPart)
/// elements. Use [`text_content`](ToolOutput::text_content) to extract
/// plain text regardless of which variant is stored.
///
/// # Conversion
///
/// [`ToolOutput`] implements [`From<String>`] and [`From<&str>`] so
/// simple string values can be converted implicitly:
///
/// ```rust
/// use loopctl::tool::{ToolOutput, ToolError, ToolSchema, ToolContext, PermissionCheck, ToolRegistry};
///
/// let result: ToolOutput = "done".into();
/// ```
///
/// # Data flow
///
/// ```text
/// Tool::call(input, ctx)
///   → Ok(ToolOutput { content, is_error: false })
///   → Ok(ToolOutput { content, is_error: true  })   [soft failure]
///   → Err(ToolError)                                [hard failure]
/// ```
#[derive(Debug, Clone)]
pub struct ToolOutput {
    /// The payload returned by the tool.
    ///
    /// Holds either a plain-text string or structured multi-part content.
    /// Use [`ToolOutput::text_content`] to extract text regardless of the
    /// variant.
    pub payload: MessageToolContent,

    /// Whether this result represents an error.
    ///
    /// When `true`, the agent loop treats the result as a soft failure —
    /// the tool executed without panicking, but the output describes what
    /// went wrong. Defaults to `false` for results created via
    /// [`ToolOutput::success`] or [`ToolOutput::text`].
    pub is_error: bool,
}

impl ToolOutput {
    /// Create a successful result with the given content.
    ///
    /// Called by tool implementations when the invocation succeeds and
    /// the output is a structured [`MessageToolContent`] value.
    /// Sets [`is_error`](ToolOutput::is_error) to `false`.
    ///
    /// Most general success constructor — accepts any type
    /// that converts into [`MessageToolContent`]. For simple text results,
    /// prefer the more concise [`ToolOutput::text`] helper.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::tool::{ToolOutput, ToolError, ToolSchema, ToolContext, PermissionCheck, ToolRegistry};
    /// use loopctl::message::ToolContent as MessageToolContent;
    ///
    /// let result = ToolOutput::success(MessageToolContent::Text("done".into()));
    /// assert!(!result.is_error);
    /// ```
    pub fn success(payload: impl Into<MessageToolContent>) -> Self {
        Self {
            payload: payload.into(),
            is_error: false,
        }
    }

    /// Create an error result with the given content.
    ///
    /// Called by tool implementations that want to report a *soft* failure
    /// — the tool ran to completion, but the output describes an error
    /// condition (e.g., "file not found"). Sets
    /// [`is_error`](ToolOutput::is_error) to `true`.
    ///
    /// Soft failures are distinct from hard [`ToolError`] returns — the
    /// tool did not panic and the result can still be processed by the
    /// agent loop and forwarded to the LLM.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::tool::{ToolOutput, ToolError, ToolSchema, ToolContext, PermissionCheck, ToolRegistry};
    ///
    /// let result = ToolOutput::error("permission denied");
    /// assert!(result.is_error);
    /// ```
    pub fn error(payload: impl Into<MessageToolContent>) -> Self {
        Self {
            payload: payload.into(),
            is_error: true,
        }
    }

    /// Create a successful plain-text result.
    ///
    /// Convenience wrapper around [`ToolOutput::success`] that converts
    /// the input string into a [`MessageToolContent::Text`] variant.
    /// Most common constructor for simple tool outputs.
    ///
    /// # When to use
    ///
    /// Use this when the tool produces a simple string response — for
    /// example, file contents, a computed value, or a status message.
    /// For structured multi-part responses, use [`ToolOutput::success`]
    /// directly with a [`MessageToolContent::Multipart`] value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::tool::{ToolOutput, ToolError, ToolSchema, ToolContext, PermissionCheck, ToolRegistry};
    ///
    /// let result = ToolOutput::text("42");
    /// assert_eq!(result.text_content(), "42");
    /// ```
    pub fn text(text: impl Into<String>) -> Self {
        Self::success(text.into())
    }

    /// Create an error plain-text result.
    ///
    /// Convenience wrapper around [`ToolOutput::error`] that converts
    /// the input string into a [`MessageToolContent::Text`] variant.
    ///
    /// Use this for simple error messages like "file not found" or
    /// "permission denied". For structured error content, use
    /// [`ToolOutput::error`] directly.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::tool::{ToolOutput, ToolError, ToolSchema, ToolContext, PermissionCheck, ToolRegistry};
    ///
    /// let result = ToolOutput::error_text("disk full");
    /// assert!(result.is_error);
    /// assert_eq!(result.text_content(), "disk full");
    /// ```
    pub fn error_text(text: impl Into<String>) -> Self {
        Self::error(text.into())
    }

    /// Extract all text content from the result, regardless of structure.
    ///
    /// Inspects the [`payload`](ToolOutput::payload) field and returns a
    /// flat [`String`]:
    /// - For [`MessageToolContent::Text`], returns the string directly.
    /// - For [`MessageToolContent::Multipart`], joins all
    ///   [`ToolContentPart::Text`](crate::message::ToolContentPart::Text)
    ///   parts with newlines, discarding non-text parts.
    ///
    /// Useful when the consumer only cares about the textual payload and
    /// does not need to handle structured content.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::tool::{ToolOutput, ToolError, ToolSchema, ToolContext, PermissionCheck, ToolRegistry};
    /// use loopctl::message::ToolContent as MessageToolContent;
    /// use loopctl::message::ToolContentPart;
    ///
    /// let result = ToolOutput::text("hello world");
    /// assert_eq!(result.text_content(), "hello world");
    ///
    /// // Works with structured content too:
    /// let structured = ToolOutput::success(MessageToolContent::Multipart(vec![
    ///     ToolContentPart::Text { text: "line 1".into() },
    ///     ToolContentPart::Text { text: "line 2".into() },
    /// ]));
    /// assert_eq!(structured.text_content(), "line 1\nline 2");
    /// ```
    ///
    /// # See also
    ///
    /// - [`ToolOutput::payload`] — access the raw content without flattening.
    #[must_use]
    pub fn text_content(&self) -> String {
        match &self.payload {
            MessageToolContent::Text(s) => s.clone(),
            MessageToolContent::Multipart(parts) => {
                use crate::message::ToolContentPart;
                parts
                    .iter()
                    .filter_map(|p| match p {
                        ToolContentPart::Text { text } => Some(text.clone()),
                        ToolContentPart::Image { .. } => None,
                    })
                    .collect::<Vec<_>>()
                    .join("\n")
            }
        }
    }
}

impl From<String> for ToolOutput {
    /// Convert a [`String`] into a successful text [`ToolOutput`].
    ///
    /// Enables `let result: ToolOutput = s.into()` where `s: String`.
    /// Equivalent to calling [`ToolOutput::text`]. Sets
    /// [`is_error`](ToolOutput::is_error) to `false`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::tool::{ToolOutput, ToolError, ToolSchema, ToolContext, PermissionCheck, ToolRegistry};
    ///
    /// let s = String::from("hello");
    /// let result: ToolOutput = s.into();
    /// assert_eq!(result.text_content(), "hello");
    /// ```
    fn from(s: String) -> Self {
        Self::text(s)
    }
}

impl From<&str> for ToolOutput {
    /// Convert a `&str` into a successful text [`ToolOutput`].
    ///
    /// Enables `let result: ToolOutput = "ok".into()`. Equivalent to
    /// calling [`ToolOutput::text`]. Sets
    /// [`is_error`](ToolOutput::is_error) to `false`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::tool::{ToolOutput, ToolError, ToolSchema, ToolContext, PermissionCheck, ToolRegistry};
    ///
    /// let result: ToolOutput = "ok".into();
    /// assert_eq!(result.text_content(), "ok");
    /// ```
    fn from(s: &str) -> Self {
        Self::text(s)
    }
}

// ===================================================
// ToolDispatchResult
// ===================================================

/// The outcome of a single tool invocation.
///
/// Produced after the framework dispatches a tool call and collects
/// the tool's output. Used throughout the middleware pipeline, the
/// engine dispatch layer, and returned to callers.
///
/// # Fields
///
/// | Field                  | Source                              |
/// |------------------------|-------------------------------------|
/// | `tool_call_id`         | Set by the engine after dispatch    |
/// | `output`               | From [`ToolOutput::payload`]        |
/// | `is_error`             | From [`ToolOutput::is_error`]       |
/// | `duration`             | Measured by the dispatch layer      |
/// | `resolved_tool_name`   | Set by middleware or engine         |
///
/// # Construction
///
/// Middlewares build results with [`ToolDispatchResult::ok`],
/// [`ToolDispatchResult::err`], or [`From<ToolOutput>`] combined with
/// builder methods. The engine layer attaches the `tool_call_id` via
/// [`ToolDispatchResult::with_call_id`] after the middleware pipeline
/// returns.
///
/// ```
/// use std::time::Duration;
/// use loopctl::tool::{ToolDispatchResult, ToolOutput};
///
/// let output = ToolOutput::text("done");
/// let result = ToolDispatchResult::from(output)
///     .with_tool_name("bash")
///     .with_duration(Duration::from_millis(42))
///     .with_call_id("call_abc123");
///
/// assert_eq!(result.tool_call_id, "call_abc123");
/// assert_eq!(result.resolved_tool_name, "bash");
/// ```
#[derive(Debug, Clone)]
pub struct ToolDispatchResult {
    /// Set by the engine via [`with_call_id`](Self::with_call_id).
    pub tool_call_id: String,
    /// Preserves multipart and image content on success; wraps error in text on failure.
    pub output: crate::message::ToolContent,
    /// Whether the tool dispatch resulted in an error.
    pub is_error: bool,
    /// Wall-clock execution time.
    pub duration: Duration,
    /// May differ from the requested tool name if a routing middleware redirected the call.
    pub resolved_tool_name: String,
}

impl ToolDispatchResult {
    /// Create a successful result with text output.
    ///
    /// Constructor for the common case where a tool
    /// produces a plain-text response.
    #[must_use]
    pub fn ok(tool_name: &str, output: String, duration: Duration) -> Self {
        Self {
            tool_call_id: String::new(),
            output: crate::message::ToolContent::Text(output),
            is_error: false,
            duration,
            resolved_tool_name: tool_name.to_string(),
        }
    }

    /// Create an error result with a message.
    ///
    /// Used when a middleware short-circuits or the tool reports failure.
    #[must_use]
    pub fn err(tool_name: &str, message: String, duration: Duration) -> Self {
        Self {
            tool_call_id: String::new(),
            output: crate::message::ToolContent::Text(message),
            is_error: true,
            duration,
            resolved_tool_name: tool_name.to_string(),
        }
    }

    /// Create a result from a [`ToolOutput`].
    ///
    /// Converts the tool's output struct into a dispatch result,
    /// preserving the error flag and content payload.
    #[must_use]
    pub fn from_tool_output(tool_name: &str, output: ToolOutput, duration: Duration) -> Self {
        Self::from(output)
            .with_tool_name(tool_name)
            .with_duration(duration)
    }

    /// Builder: attach the [`tool_call_id`](Self::tool_call_id).
    ///
    /// Called by the engine layer after the middleware pipeline returns
    /// to correlate this result with the original tool call.
    #[must_use]
    pub fn with_call_id(mut self, id: impl Into<String>) -> Self {
        self.tool_call_id = id.into();
        self
    }

    /// Set the [`resolved_tool_name`](Self::resolved_tool_name).
    ///
    /// Part of the builder chain when constructing a
    /// `ToolDispatchResult` from [`From<ToolOutput>`].
    #[must_use]
    pub fn with_tool_name(mut self, name: &str) -> Self {
        name.clone_into(&mut self.resolved_tool_name);
        self
    }

    /// Set the [`duration`](Self::duration).
    ///
    /// Part of the builder chain when constructing a
    /// `ToolDispatchResult` from [`From<ToolOutput>`].
    #[must_use]
    pub fn with_duration(mut self, dur: Duration) -> Self {
        self.duration = dur;
        self
    }

    /// Create a result from a [`ToolError`].
    ///
    /// Converts the tool's error into a dispatch result with `is_error`
    /// set to `true`.
    #[must_use]
    pub fn from_tool_error(tool_name: &str, error: &ToolError, duration: Duration) -> Self {
        Self {
            tool_call_id: String::new(),
            output: crate::message::ToolContent::Text(error.to_string()),
            is_error: true,
            duration,
            resolved_tool_name: tool_name.to_string(),
        }
    }

    /// Create a result from a tool call outcome.
    ///
    /// Covers the common `Result<ToolOutput, ToolError>` pattern produced by
    /// [`Tool::call()`](Tool::call). Maps [`Ok`] through
    /// [`from_tool_output`](Self::from_tool_output) and [`Err`] through
    /// [`from_tool_error`](Self::from_tool_error).
    #[must_use]
    pub fn from_result(
        tool_name: &str,
        result: Result<ToolOutput, ToolError>,
        duration: Duration,
    ) -> Self {
        match result {
            Ok(output) => Self::from_tool_output(tool_name, output, duration),
            Err(e) => Self::from_tool_error(tool_name, &e, duration),
        }
    }
}

/// Conversion from a bare [`ToolOutput`].
///
/// Produces a `ToolDispatchResult` with no call ID, [`Duration::ZERO`],
/// and an empty `resolved_tool_name`. Chain builder methods to complete
/// the fields:
///
/// ```
/// use std::time::Duration;
/// use loopctl::tool::{ToolDispatchResult, ToolOutput};
///
/// let result = ToolDispatchResult::from(ToolOutput::text("ok"))
///     .with_call_id("call_1")
///     .with_tool_name("echo")
///     .with_duration(Duration::from_millis(5));
/// ```
impl From<ToolOutput> for ToolDispatchResult {
    fn from(output: ToolOutput) -> Self {
        Self {
            tool_call_id: String::new(),
            output: output.payload,
            is_error: output.is_error,
            duration: Duration::ZERO,
            resolved_tool_name: String::new(),
        }
    }
}

// ===================================================
// ToolError
// ===================================================

/// Error type for tool invocations.
///
/// Covers the full range of failure modes a tool can encounter — from
/// "tool not found" and invalid input, to I/O failures, timeouts, and
/// permission denials. Each variant carries enough context for the agent
/// loop (or the LLM) to decide how to recover.
///
/// The [`thiserror::Error`] derive provides [`Display`](std::fmt::Display)
/// and [`Error`](std::error::Error) implementations with human-readable
/// messages.
///
/// # Recovery strategy
///
/// ```text
/// ToolError::NotFound      → inform LLM of available tools, retry
/// ToolError::InvalidInput  → ask LLM to fix arguments, retry
/// ToolError::Permission    → inform LLM, cannot retry without user approval
/// ToolError::Timeout       → optionally retry with longer timeout
/// ToolError::Execution     → generic retry or abort
/// ToolError::Io            → typically non-retryable
/// ToolError::Json          → typically non-retryable (bug in tool)
/// ToolError::Cancelled     → session shutting down, do not retry
/// ToolError::FileNotFound  → inform LLM, may adjust path and retry
/// ```
///
/// # Conversion from std errors
///
/// [`ToolError`] implements `From<std::io::Error>` and
/// `From<serde_json::Error>` so the `?` operator works naturally
/// inside tool implementations:
///
/// ```rust,ignore
/// let data = tokio::fs::read_to_string(&path).await?;  // io::Error → ToolError
/// let parsed: Value = serde_json::from_str(&data)?;    // json::Error → ToolError
/// ```
///
/// # Example
///
/// ```rust
/// use loopctl::tool::{ToolOutput, ToolError, ToolSchema, ToolContext, PermissionCheck, ToolRegistry};
///
/// let err = ToolError::not_found("grep", &["read_file", "bash"]);
/// assert!(err.to_string().contains("grep"));
/// ```
#[derive(Debug, thiserror::Error)]
pub enum ToolError {
    /// The requested tool was not found in the registry.
    ///
    /// The first field is the requested tool name; the second is a
    /// comma-separated list of available tool names (or "none registered").
    /// Produced by [`ToolError::not_found`].
    ///
    /// # Recovery
    ///
    /// The agent loop should inform the LLM which tools *are* available
    /// so it can retry with a valid tool name.
    #[error("Tool not found: {0}. Available: {1}")]
    NotFound(String, String),

    /// The tool input failed validation.
    ///
    /// Carries a human-readable description of what was wrong — for
    /// example "missing required field `path`" or "expected integer".
    ///
    /// # Recovery
    ///
    /// The agent loop should ask the LLM to fix its arguments and retry.
    #[error("Invalid input: {0}")]
    InvalidInput(String),

    /// An execution error occurred inside the tool.
    ///
    /// A catch-all for runtime failures that are not covered by the more
    /// specific variants (e.g., a subprocess exited with a non-zero code).
    ///
    /// # Recovery
    ///
    /// The agent loop may retry the invocation or report the error to
    /// the LLM for an alternative approach.
    #[error("Execution error: {0}")]
    Execution(String),

    /// Permission denied for the requested operation.
    ///
    /// Raised when the tool (or the agent loop's permission gate) rejects
    /// an invocation — for example, writing outside the allowed directory.
    ///
    /// # Recovery
    ///
    /// Cannot be retried without user approval or a change in the
    /// permission policy.
    #[error("Permission denied: {0}")]
    Permission(String),

    /// The target file or resource was not found.
    ///
    /// Distinct from [`NotFound`](ToolError::NotFound) which refers to a
    /// missing *tool*. This variant means the tool was found but the file
    /// it tried to access does not exist.
    ///
    /// # Recovery
    ///
    /// The agent loop should inform the LLM so it can adjust the file
    /// path and retry.
    #[error("File not found: {0}")]
    FileNotFound(String),

    /// The tool execution exceeded its time limit.
    ///
    /// The `u64` field is the timeout in seconds. The agent loop may
    /// choose to retry or report the timeout to the LLM.
    ///
    /// # Recovery
    ///
    /// Optionally retry with a longer timeout or suggest the LLM simplify
    /// its request.
    #[error("Timeout after {0}s")]
    Timeout(u64),

    /// The tool was explicitly cancelled.
    ///
    /// Set when the user or framework aborts an in-flight tool call —
    /// for example when the agent session is shutting down.
    ///
    /// # Recovery
    ///
    /// Do not retry. The session is likely winding down.
    #[error("Cancelled")]
    Cancelled,

    /// An underlying I/O error.
    ///
    /// Automatically created via `?` when a `std::io::Error` propagates
    /// out of a tool implementation. Common causes include file-not-found,
    /// permission denied at the OS level, or broken pipes.
    ///
    /// # Recovery
    ///
    /// Typically non-retryable. The agent loop should report the error to
    /// the LLM.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// A JSON serialization / deserialization error.
    ///
    /// Automatically created via `?` when a `serde_json::Error` propagates
    /// out of a tool implementation. Usually indicates a bug in the tool's
    /// input parsing logic.
    ///
    /// # Recovery
    ///
    /// Typically non-retryable — the tool code needs to be fixed.
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
}

impl ToolError {
    /// Create a [`NotFound`](ToolError::NotFound) error with an available-tools list.
    ///
    /// Formats the `available` slice into a human-friendly string:
    /// - Empty → `"none registered"`
    /// - ≤ 10 tools → comma-separated names
    /// - \> 10 tools → first 10 names + `"... (and N more)"`
    ///
    /// Called by the agent loop when a tool name requested by the LLM is
    /// not present in the [`ToolRegistry`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::tool::{ToolOutput, ToolError, ToolSchema, ToolContext, PermissionCheck, ToolRegistry};
    ///
    /// let err = ToolError::not_found("grep", &["bash", "read_file"]);
    /// assert!(matches!(err, ToolError::NotFound(..)));
    /// ```
    pub fn not_found(tool: impl Into<String>, available: &[&str]) -> Self {
        let tool = tool.into();
        let available_str = if available.is_empty() {
            "none registered".to_string()
        } else if available.len() <= 10 {
            available.join(", ")
        } else {
            let count = available.len().saturating_sub(10);
            format!(
                "{}... (and {count} more)",
                available
                    .iter()
                    .take(10)
                    .copied()
                    .collect::<Vec<_>>()
                    .join(", "),
            )
        };
        Self::NotFound(tool, available_str)
    }
}

// ===================================================
// ToolContext
// ===================================================

/// Session-level context provided to every tool invocation.
///
/// The agent loop constructs a [`ToolContext`] at session start and passes
/// a reference to each [`Tool::call`]. Tools use it to discover the
/// working directory, session ID, temp directory, and any
/// domain-specific extensions the host application has attached.
///
/// # Extensions
///
/// The [`extensions`](ToolContext::extensions) field lets downstream
/// crates inject typed, arbitrary data without coupling the framework to
/// any particular use case. Use [`ToolContext::set_extension`] and
/// [`ToolContext::get_extension`] to store and retrieve values keyed by
/// their Rust type.
///
/// # Example
///
/// ```rust,ignore
/// let mut ctx = ToolContext::default();
/// ctx.cwd = "/tmp/workspace".into();
/// ctx.set_extension(MyConfig { verbose: true });
///
/// // Inside a tool:
/// if let Some(cfg) = ctx.get_extension::<MyConfig>() {
///     println!("verbose={}", cfg.verbose);
/// }
/// ```
#[derive(Clone)]
pub struct ToolContext {
    /// Current working directory for the agent session.
    ///
    /// Tools that interact with the filesystem (e.g., read, write, glob)
    /// should resolve relative paths against this directory. Defaults to
    /// `"."` (the process's current directory).
    pub cwd: String,

    /// Unique identifier for the agent session.
    ///
    /// A UUID v4 generated when the context is created. Useful for
    /// correlating log entries, naming temp files, or isolating
    /// per-session state.
    pub session_id: uuid::Uuid,

    /// Path to the session's temporary directory.
    ///
    /// Each session gets its own temp directory so tools can write
    /// intermediate files without colliding with other sessions. Defaults
    /// to [`std::env::temp_dir`].
    pub temp_dir: String,

    /// Whether the agent is running in non-interactive (headless) mode.
    ///
    /// When `true`, tools should avoid prompting the user for input or
    /// confirmation and instead use sensible defaults or fail with
    /// [`ToolError::Permission`]. Defaults to `false`.
    pub is_non_interactive: bool,

    /// Additional key-value context supplied by the caller.
    ///
    /// The host application can populate this map with arbitrary string
    /// data (e.g., project name, environment, user ID) that tools can
    /// read at invocation time. Defaults to empty.
    pub user_context: HashMap<String, String>,

    /// Domain-specific extensions for downstream crates.
    ///
    /// A type-map (`TypeId` → `Arc<dyn Any + Send + Sync>`) that lets
    /// tool authors attach structured data without modifying the
    /// [`ToolContext`] struct. Use [`ToolContext::set_extension`] to
    /// insert and [`ToolContext::get_extension`] to retrieve.
    pub extensions: HashMap<std::any::TypeId, Arc<dyn std::any::Any + Send + Sync>>,
}

impl ToolContext {
    /// Store a typed extension value in the context.
    ///
    /// Inserts `val` keyed by its [`TypeId`](std::any::TypeId). If a value
    /// of the same type already exists it is replaced. Call this during
    /// session setup, before tools are invoked.
    ///
    /// Extensions are the recommended way to pass host-application-specific
    /// configuration to tools without coupling the framework to any
    /// particular use case.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// ctx.set_extension(Arc::new(my_callback_fn));
    /// ctx.set_extension(MyConfig { max_retries: 3 });
    /// ```
    pub fn set_extension<T: 'static + Send + Sync>(&mut self, val: T) {
        self.extensions
            .insert(std::any::TypeId::of::<T>(), Arc::new(val));
    }

    /// Retrieve a previously stored extension by type.
    ///
    /// Returns `Some(&T)` if [`set_extension`](ToolContext::set_extension)
    /// was called with a value of the same type `T`, or `None` otherwise.
    /// Called from inside [`Tool::call`] implementations.
    ///
    /// The returned reference borrows from the [`ToolContext`] and remains
    /// valid for as long as the context is alive.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if let Some(cb) = ctx.get_extension::<MyCallback>() {
    ///     cb.invoke();
    /// }
    /// ```
    #[must_use]
    pub fn get_extension<T: 'static>(&self) -> Option<&T> {
        self.extensions
            .get(&std::any::TypeId::of::<T>())
            .and_then(|arc| arc.downcast_ref::<T>())
    }
}

impl fmt::Debug for ToolContext {
    /// Format the context for debug output, summarizing extensions.
    ///
    /// Produces a human-readable struct dump. The `extensions` field is
    /// rendered as a count (e.g., `"3 entries"`) rather than printing every
    /// entry, because extensions can be arbitrarily large and their types
    /// may not implement [`Debug`](std::fmt::Debug).
    ///
    /// # Example output
    ///
    /// ```text
    /// ToolContext { cwd: "/tmp/ws", session_id: 0123-4567-..., temp_dir: "/tmp", is_non_interactive: false, user_context: {}, extensions: 2 entries }
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ToolContext")
            .field("cwd", &self.cwd)
            .field("session_id", &self.session_id)
            .field("temp_dir", &self.temp_dir)
            .field("is_non_interactive", &self.is_non_interactive)
            .field("user_context", &self.user_context)
            .field("extensions", &format!("{} entries", self.extensions.len()))
            .finish()
    }
}

impl Default for ToolContext {
    /// Produce a context with sensible defaults.
    ///
    /// Creates a ready-to-use [`ToolContext`] suitable for most agent
    /// sessions. The defaults are:
    ///
    /// | Field               | Default                              |
    /// |---------------------|--------------------------------------|
    /// | `cwd`               | `"."` (process current directory)    |
    /// | `session_id`        | new UUID v4                          |
    /// | `temp_dir`          | [`std::env::temp_dir`]               |
    /// | `is_non_interactive`| `false`                              |
    /// | `user_context`      | empty [`HashMap`]                    |
    /// | `extensions`        | empty [`HashMap`]                    |
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::tool::{ToolOutput, ToolError, ToolSchema, ToolContext, PermissionCheck, ToolRegistry};
    ///
    /// let ctx = ToolContext::default();
    /// assert_eq!(ctx.cwd, ".");
    /// assert!(!ctx.is_non_interactive);
    /// ```
    fn default() -> Self {
        Self {
            cwd: ".".to_string(),
            session_id: uuid::Uuid::new_v4(),
            temp_dir: std::env::temp_dir().to_string_lossy().to_string(),
            is_non_interactive: false,
            user_context: HashMap::new(),
            extensions: HashMap::new(),
        }
    }
}
// ===================================================
// Tool trait
// ===================================================

/// The trait that all agent tools must implement.
///
/// Framework-level tool interface. Concrete tools (defined in
/// downstream crates like `dch-tools`) implement this trait, and the
/// [`ToolRegistry`] manages dynamic lookup by name.
///
/// The trait uses a `Pin<Box<dyn Future>>` return type for [`call`](Tool::call)
/// to be maximally compatible with both `async fn` bodies and manually
/// constructed futures, keeping the trait object-safe and free of
/// lifetime issues that `async fn` in traits can introduce.
///
/// # Lifecycle
///
/// ```text
/// registry.register(tool)
///   → tool.schema()            [sent to LLM as tool definition]
///   → tool.call(input, ctx)    [invoked when LLM selects this tool]
///   → tool.system_prompt()     [optional: injected into system message]
/// ```
///
/// # Data flow
///
/// ```text
/// LLM selects tool "read_file"
///   → ToolRegistry::get("read_file")
///   → PermissionCheck gate
///     → Allow → Tool::call(input, ctx)
///                → Ok(ToolOutput) or Err(ToolError)
///     → Deny  → Err(ToolError::Permission)
/// ```
///
/// # Implementing
///
/// At a minimum you must provide [`name`](Tool::name),
/// [`description`](Tool::description), [`schema`](Tool::schema), and
/// [`call`](Tool::call). The trait supplies default implementations for
/// [`is_concurrency_safe`](Tool::is_concurrency_safe),
/// [`is_safe_for_concurrent_execution`](Tool::is_safe_for_concurrent_execution),
/// [`is_read_only`](Tool::is_read_only), and
/// [`system_prompt`](Tool::system_prompt).
///
/// # Required methods
///
/// | Method               | Purpose                                    |
/// |----------------------|--------------------------------------------|
/// | `name`               | Unique identifier used for registry lookup |
/// | `description`        | Human-readable summary sent to the LLM     |
/// | `schema`             | JSON Schema for input validation           |
/// | `call`               | Core execution logic                       |
///
/// # Provided methods
///
/// | Method                              | Default   | Purpose                             |
/// |-------------------------------------|-----------|-------------------------------------|
/// | `is_concurrency_safe`               | `false`   | Static concurrency flag             |
/// | `is_safe_for_concurrent_execution`  | delegates | Per-input concurrency check         |
/// | `is_read_only`                      | `false`   | Side-effect flag for permission     |
/// | `system_prompt`                     | `None`    | Extra LLM context for this tool     |
///
/// # Example
///
/// ```rust,ignore
/// struct ReadFileTool;
///
/// impl Tool for ReadFileTool {
///     fn name(&self) -> &str { "read_file" }
///     fn description(&self) -> &str { "Read a file from disk" }
///     fn schema(&self) -> ToolSchema {
///         ToolSchema {
///             tool: "read_file".into(),
///             description: "Read a file from disk".into(),
///             input_schema: json!({
///                 "type": "object",
///                 "properties": { "path": { "type": "string" } },
///                 "required": ["path"]
///             }),
///         }
///     }
///     fn call(&self, input: Value, ctx: &ToolContext)
///         -> Pin<Box<dyn Future<Output = Result<ToolOutput, ToolError>> + Send + '_>>
///     {
///         let path = input["path"].as_str().unwrap_or_default().to_string();
///         Box::pin(async move {
///             let full = std::path::Path::new(&ctx.cwd).join(&path);
///             let content = tokio::fs::read_to_string(full).await?;
///             Ok(ToolOutput::text(content))
///         })
///     }
///     fn is_read_only(&self) -> bool { true }
/// }
/// ```
pub trait Tool: Send + Sync {
    /// The tool's unique name (e.g., `"read_file"`, `"bash"`).
    ///
    /// Used as the lookup key in [`ToolRegistry`] and as the `name` field
    /// in the [`ToolSchema`] sent to the LLM. Must be non-empty and
    /// stable across the lifetime of the session.
    ///
    /// # Invariants
    ///
    /// Implementations must ensure the returned value is:
    /// - Non-empty and free of leading/trailing whitespace.
    /// - Unique within a given [`ToolRegistry`].
    /// - Stable — calling this method multiple times yields the same value.
    fn name(&self) -> &str;

    /// Human-readable description for the LLM.
    ///
    /// Sent to the LLM alongside [`name`](Tool::name) and
    /// [`schema`](Tool::schema). A clear description helps the model
    /// choose the right tool and construct correct arguments.
    ///
    /// # Guidelines
    ///
    /// - Keep it to one or two sentences.
    /// - Describe *what* the tool does, not how it's implemented.
    /// - Include constraints (e.g., "reads files under 10 MB") when relevant.
    fn description(&self) -> &str;

    /// Return the JSON Schema descriptor for this tool.
    ///
    /// Called by the agent loop to assemble the tool list sent to the LLM.
    /// The returned [`ToolSchema`] must have a `name` matching
    /// [`Tool::name`].
    ///
    /// # Validation
    ///
    /// The `input_schema` field should conform to JSON Schema Draft 07.
    /// While the framework does not enforce schema validity, an invalid
    /// schema will cause the LLM to produce malformed tool calls.
    fn schema(&self) -> ToolSchema;

    /// Invoke the tool with the given input and context.
    ///
    /// Main execution entry point. The `input` is a
    /// [`Value`] (typically a JSON object) matching the tool's
    /// [`ToolSchema::input_schema`]. The [`ToolContext`] provides
    /// session-level data such as working directory and extensions.
    ///
    /// Called by the agent loop when the LLM selects this tool. Returns
    /// `Ok(ToolOutput)` on success or `Err(ToolError)` on failure.
    ///
    /// # Return type
    ///
    /// The `Pin<Box<dyn Future>>` return type maximises compatibility
    /// with both `async fn` bodies and manually constructed futures,
    /// keeping the trait object-safe and free of lifetime issues.
    ///
    /// # Errors
    ///
    /// Implementations should return [`ToolError`] variants that
    /// accurately describe the failure mode so the agent loop can decide
    /// on an appropriate recovery strategy.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// fn call(&self, input: Value, ctx: &ToolContext)
    ///     -> Pin<Box<dyn Future<Output = Result<ToolOutput, ToolError>> + Send + '_>>
    /// {
    ///     let path = input["path"].as_str().unwrap_or_default().to_string();
    ///     let cwd = ctx.cwd.clone();
    ///     Box::pin(async move {
    ///         let full = std::path::Path::new(&cwd).join(&path);
    ///         let content = tokio::fs::read_to_string(full).await?;
    ///         Ok(ToolOutput::text(content))
    ///     })
    /// }
    /// ```
    fn call(
        &self,
        input: Value,
        context: &ToolContext,
    ) -> Pin<Box<dyn Future<Output = Result<ToolOutput, ToolError>> + Send + '_>>;

    /// Whether this tool is safe to run concurrently with itself.
    ///
    /// Return `true` if the tool has no mutable shared state and can be
    /// safely invoked in parallel (e.g., a pure read-only tool). The
    /// agent loop uses this to decide which tools can run simultaneously.
    /// Defaults to `false`.
    ///
    /// # When called
    ///
    /// Queried by [`ToolRegistry::concurrent_safe_tools`] during session
    /// setup and by the agent loop's parallel execution planner before
    /// dispatching multiple tool calls in a single turn.
    ///
    /// # See also
    ///
    /// - [`is_safe_for_concurrent_execution`](Tool::is_safe_for_concurrent_execution)
    ///   — input-dependent version of this check.
    fn is_concurrency_safe(&self) -> bool {
        false
    }

    /// Dynamic concurrency check based on the specific input.
    ///
    /// Override to provide input-dependent safety checks — for example,
    /// a file-write tool might allow concurrent writes to *different*
    /// files but not to the same file. Falls back to
    /// [`is_concurrency_safe`](Tool::is_concurrency_safe) when not
    /// overridden.
    ///
    /// # When called
    ///
    /// Called by the agent loop's parallel execution planner immediately
    /// before dispatching each tool call. Receives the same `input`
    /// [`Value`] that will be passed to [`Tool::call`].
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // A write tool that allows concurrent writes to different files:
    /// fn is_safe_for_concurrent_execution(&self, input: &Value) -> bool {
    ///     // Track which files are in-flight; only block on same-file writes
    ///     true // simplified — real impl checks the `path` field
    /// }
    /// ```
    fn is_safe_for_concurrent_execution(&self, _input: &Value) -> bool {
        self.is_concurrency_safe()
    }

    /// Whether this tool only reads data and has no side effects.
    ///
    /// Read-only tools (e.g., file readers, search tools) can be
    /// auto-approved by permission gates. Defaults to `false`.
    ///
    /// # When called
    ///
    /// Checked by the agent loop's permission gate before prompting the
    /// user. If this returns `true`, the gate may skip the user
    /// confirmation step and return [`PermissionCheck::Allow`] directly.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // A grep-like tool that only reads files:
    /// fn is_read_only(&self) -> bool { true }
    /// ```
    fn is_read_only(&self) -> bool {
        false
    }

    /// Optional extra system prompt injected when this tool is available.
    ///
    /// Some tools benefit from giving the LLM additional context — for
    /// example, a shell tool might include "Prefer bash one-liners". The
    /// agent loop appends this to the system message when the tool is
    /// registered. Returns `None` by default.
    ///
    /// # When called
    ///
    /// Queried once during session setup when the agent loop assembles
    /// the system prompt. The returned string (if any) is appended after
    /// the base prompt and before any per-turn dynamic instructions.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // A bash tool that advises the LLM on style:
    /// fn system_prompt(&self) -> Option<String> {
    ///     Some("Prefer single-line bash commands over multi-line scripts.".into())
    /// }
    /// ```
    fn system_prompt(&self) -> Option<String> {
        None
    }
}

// ===================================================
// Tests
// ===================================================

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

    struct EchoTool;

    impl Tool for EchoTool {
        fn name(&self) -> &'static str {
            "echo"
        }
        fn description(&self) -> &'static str {
            "Echoes back the input"
        }
        fn schema(&self) -> ToolSchema {
            ToolSchema {
                tool: "echo".into(),
                description: "Echoes back the input".into(),
                input_schema: json!({
                    "type": "object",
                    "properties": { "message": { "type": "string" } },
                    "required": ["message"]
                }),
            }
        }
        fn call(
            &self,
            input: Value,
            _context: &ToolContext,
        ) -> Pin<Box<dyn Future<Output = Result<ToolOutput, ToolError>> + Send + '_>> {
            let msg = input
                .get("message")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            Box::pin(async move { Ok(ToolOutput::text(msg)) })
        }
        fn is_concurrency_safe(&self) -> bool {
            true
        }
        fn is_read_only(&self) -> bool {
            true
        }
    }

    struct FailTool;

    impl Tool for FailTool {
        fn name(&self) -> &'static str {
            "fail"
        }
        fn description(&self) -> &'static str {
            "Always fails"
        }
        fn schema(&self) -> ToolSchema {
            ToolSchema {
                tool: "fail".into(),
                description: "Always fails".into(),
                input_schema: json!({ "type": "object", "properties": {} }),
            }
        }
        fn call(
            &self,
            _input: Value,
            _context: &ToolContext,
        ) -> Pin<Box<dyn Future<Output = Result<ToolOutput, ToolError>> + Send + '_>> {
            Box::pin(async { Err(ToolError::Execution("always fails".into())) })
        }
    }

    #[test]
    fn test_tool_result_success() {
        let result = ToolOutput::text("hello");
        assert!(!result.is_error);
        assert_eq!(result.text_content(), "hello");
    }

    #[test]
    fn test_tool_result_error() {
        let result = ToolOutput::error_text("something went wrong");
        assert!(result.is_error);
        assert_eq!(result.text_content(), "something went wrong");
    }

    #[test]
    fn test_tool_result_from_string() {
        let result: ToolOutput = "hello".into();
        assert!(!result.is_error);
    }

    #[test]
    fn test_tool_result_from_str() {
        let result: ToolOutput = "hello".into();
        assert!(!result.is_error);
    }

    #[test]
    fn test_tool_error_not_found() {
        let err = ToolError::not_found("missing", &["tool_a", "tool_b"]);
        assert!(err.to_string().contains("missing"));
        assert!(err.to_string().contains("tool_a"));
    }

    #[test]
    fn test_tool_error_not_found_empty() {
        let err = ToolError::not_found("missing", &[]);
        assert!(err.to_string().contains("none registered"));
    }

    #[test]
    fn test_tool_error_not_found_many() {
        let tools: Vec<&str> = (0..15)
            .map(|i| Box::leak(format!("tool_{i}").into_boxed_str()) as &str)
            .collect();
        let err = ToolError::not_found("missing", &tools);
        assert!(err.to_string().contains("and 5 more"));
    }

    #[test]
    fn test_tool_context_default() {
        let ctx = ToolContext::default();
        assert_eq!(ctx.cwd, ".");
        assert!(!ctx.is_non_interactive);
    }

    #[test]
    fn test_permission_check_allow() {
        let check = PermissionCheck::allow();
        assert!(check.is_allow());
        assert!(!check.is_deny());
    }

    #[test]
    fn test_permission_check_deny() {
        let check = PermissionCheck::deny("unsafe");
        assert!(check.is_deny());
        assert!(!check.is_allow());
    }

    #[test]
    fn test_permission_check_ask() {
        let check = PermissionCheck::ask("Run this?");
        assert!(check.is_ask());
    }

    #[test]
    fn test_permission_check_modify() {
        let check = PermissionCheck::modify(json!({"safe": true}));
        assert!(check.is_modify());
    }

    #[test]
    fn test_tool_schema_serialization() {
        let schema = ToolSchema {
            tool: "test".into(),
            description: "A test tool".into(),
            input_schema: json!({"type": "object"}),
        };
        let json = serde_json::to_string(&schema).unwrap();
        let back: ToolSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(schema.tool, back.tool);
    }

    #[test]
    fn test_registry_register_and_get() {
        let mut registry = ToolRegistry::new();
        assert!(registry.is_empty());

        registry.register(EchoTool);
        assert_eq!(registry.len(), 1);
        assert!(registry.contains("echo"));

        let tool = registry.get("echo").unwrap();
        assert_eq!(tool.name(), "echo");
    }

    #[test]
    fn test_registry_get_missing() {
        let registry = ToolRegistry::new();
        assert!(registry.get("missing").is_none());
    }

    #[test]
    fn test_registry_all_schemas() {
        let mut registry = ToolRegistry::new();
        registry.register(EchoTool);
        let schemas = registry.all_schemas();
        assert_eq!(schemas.len(), 1);
        assert_eq!(schemas[0].tool, "echo");
    }

    #[test]
    fn test_registry_tool_names() {
        let mut registry = ToolRegistry::new();
        registry.register(FailTool);
        registry.register(EchoTool);
        let names = registry.tool_names();
        assert_eq!(names, vec!["echo", "fail"]);
    }

    #[test]
    fn test_registry_concurrent_safe_tools() {
        let mut registry = ToolRegistry::new();
        registry.register(EchoTool);
        registry.register(FailTool);
        let safe = registry.concurrent_safe_tools();
        assert_eq!(safe.len(), 1);
        assert_eq!(safe[0].name(), "echo");
    }

    #[tokio::test]
    async fn test_echo_tool_call() {
        let tool = EchoTool;
        let ctx = ToolContext::default();
        let result = tool.call(json!({"message": "hello"}), &ctx).await;
        assert!(result.is_ok());
        let result = result.unwrap();
        assert_eq!(result.text_content(), "hello");
    }

    #[tokio::test]
    async fn test_fail_tool_call() {
        let tool = FailTool;
        let ctx = ToolContext::default();
        let result = tool.call(json!({}), &ctx).await;
        assert!(result.is_err());
    }

    #[test]
    fn test_tool_trait_concurrency_default() {
        let tool = FailTool;
        assert!(!tool.is_concurrency_safe());
        assert!(!tool.is_safe_for_concurrent_execution(&json!({})));
    }

    #[test]
    fn test_tool_trait_read_only_default() {
        let tool = FailTool;
        assert!(!tool.is_read_only());
    }

    #[test]
    fn test_tool_trait_system_prompt_default() {
        let tool = EchoTool;
        assert!(tool.system_prompt().is_none());
    }
}