flashmind-types 0.3.0

Shared types for the Flashmind AI agent framework
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
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
//! Tool trait, registry, context, and result types for agent function calling.
//!
//! # Key types
//!
//! | Type | Role |
//! |------|------|
//! | [`Tool`] | Trait for tools callable by the agent (name, description, params, execute) |
//! | [`ToolRegistry`] | Registry of available tools with aliases |
//! | [`ToolContext`] | Per-invocation context passed to `execute()` |
//! | [`ToolResult`] | Result of a tool execution returned to the LLM |
//! | [`FileDiff`] | A file diff produced by a tool |
//! | [`ForbiddenCmd`] | Command restriction pattern (regex-based) |
//! | [`ToolGate`] | Host check every call passes before it runs |

use async_trait::async_trait;
use futures_util::future::BoxFuture;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::any::Any;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tempfile::TempDir;
use tokio::fs::OpenOptions;
use tokio::io::AsyncWriteExt;
use tokio::sync::OnceCell;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;

use crate::event::Source;
use crate::llm::ToolDefinition;
use crate::{AgentLlmConfig, ContentPart, LlmProvider};

// ---------------------------------------------------------------------------
// ForbiddenCmd
// ---------------------------------------------------------------------------

/// A forbidden command configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForbiddenCmd {
    /// Regex pattern to match against the full command line (command + args).
    pub command: String,
    /// Reason shown to user when blocked.
    pub reason: String,
    /// If true, inject a warning message and let the LLM reconsider instead of rejecting.
    /// Like tool-aware RAG, this will retry the turn with additional context.
    #[serde(default)]
    pub reconsider: bool,
}

impl ForbiddenCmd {
    /// Validate the forbidden command config.
    pub fn validate(&self) -> std::result::Result<(), Vec<String>> {
        let mut errors = Vec::new();
        if self.command.is_empty() {
            errors.push("forbidden command name cannot be empty".to_string());
        }
        if regex::Regex::new(&self.command).is_err() {
            errors.push(format!("invalid regex for name: '{}'", self.command));
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

// ---------------------------------------------------------------------------
// Command allow-list
// ---------------------------------------------------------------------------

/// Trait for checking whether a command is allowed to execute.
///
/// Implementations live in the app layer; tools receive this as
/// `Arc<dyn CommandAllowList>`. When no allow-list is set (e.g. in tests
/// or desktop), all commands execute freely.
pub trait CommandAllowList: Send + Sync {
    /// Check whether a command is pre-approved (permanent config or session).
    fn is_allowed(&self, command: &str) -> bool;

    /// Record a session-level approval pattern (glob-style).
    ///
    /// The `pattern` argument expects a glob-style string (e.g. `"git commit -m '*'"`,
    /// `"cargo build"`). Patterns are matched against the full command line at execution time.
    fn add_session_pattern(&self, pattern: &str);
}

// ---------------------------------------------------------------------------
// ToolGate
// ---------------------------------------------------------------------------

/// A host's check on every tool call, made where the registry executes it.
///
/// A registry with a gate asks it before each call. Sub-agents get the
/// gate of the registry they are given, or their manager's, so the same
/// rules hold for every agent the host runs.
#[async_trait]
pub trait ToolGate: Send + Sync {
    /// Decide about `call` before it runs.
    async fn check(&self, call: &crate::ToolCall) -> GateDecision;
}

/// What a [`ToolGate`] decides about one call.
pub enum GateDecision {
    /// Run it.
    Allow,
    /// Do not run it; the reason is the call's result.
    Deny(String),
    /// Ask someone and wait for the answer. Only this call waits.
    Ask(GateAsk),
}

/// A question a gate asked, and how long the call waits for its answer.
pub struct GateAsk {
    /// Resolves to the answer, such as a oneshot the host completes.
    pub answer: BoxFuture<'static, GateAnswer>,
    /// A call left unanswered this long is refused.
    pub timeout: Duration,
}

/// The answer to a [`GateAsk`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GateAnswer {
    Allow,
    /// Refused; the reason is the call's result.
    Deny(String),
}

impl std::fmt::Debug for GateDecision {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Allow => f.write_str("Allow"),
            Self::Deny(reason) => f.debug_tuple("Deny").field(reason).finish(),
            Self::Ask(ask) => f
                .debug_struct("Ask")
                .field("timeout", &ask.timeout)
                .finish(),
        }
    }
}

// ---------------------------------------------------------------------------
// InterruptPayload
// ---------------------------------------------------------------------------

/// Typed payload for [`ToolResult::Interrupt`].
///
/// Tools define concrete structs implementing this trait. The CLI/UI layer
/// downcasts via [`as_any`](Self::as_any) to handle each type specifically.
pub trait InterruptPayload: Send + Sync + std::fmt::Debug {
    /// Downcast support — return `self` as `&dyn Any`.
    fn as_any(&self) -> &dyn Any;

    /// Human-readable description of the interrupt, used as the tool result
    /// string in the conversation so the LLM knows what happened.
    fn display_output(&self) -> String;
}

// ---------------------------------------------------------------------------
// FileDiff
// ---------------------------------------------------------------------------

/// A single line in a unified diff output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DiffLine {
    /// A line that was added to the file.
    Added { line: u64, content: String },
    /// A line that was removed from the file.
    Removed { line: u64, content: String },
    /// An unchanged context line surrounding the actual changes.
    /// Provides locality so a reviewer can see *where* the edit landed.
    Context { line: u64, content: String },
}

/// A file diff produced by a tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileDiff {
    /// Absolute or relative path to the modified file.
    pub path: String,
    /// List of added/removed lines that make up this diff.
    pub diff: Vec<DiffLine>,
}

// ---------------------------------------------------------------------------
// ToolResult (tool execution result — distinct from message::ToolResult)
// ---------------------------------------------------------------------------

/// Result of a tool execution, returned by [`Tool::execute`] and fed back to
/// the LLM as a `"role": "tool"` message.
///
/// Three variants cover the full lifecycle of a tool call:
///
/// - **`Success`** — The tool ran without error. The `output` field contains
///   the text payload sent back to the model. Optional `sources` (URLs the
///   agent can cite) and `diffs` (unified diffs for file-mutating tools) may
///   be attached.
/// - **`Failure`** — The tool encountered an error (invalid arguments, I/O
///   failure, etc.). The `output` field carries a human- and LLM-readable
///   error description. Unlike `Success`, no sources or diffs are included.
/// - **`Interrupt`** — The tool needs user interaction before continuing
///   (e.g. plan approval, choice picker). The agent loop should halt and
///   surface the `output` (structured as JSON) to the caller for handling.
///
/// # Construction helpers
///
/// Prefer the associated constructors on the `impl` block rather than building
/// variants directly:
///
/// ```ignore
/// use flashmind_types::tool::ToolResult;
///
/// // Basic success
/// ToolResult::success(call_id, "file written")
///
/// // Failure with error message
/// ToolResult::failure(call_id, "permission denied")
///
/// // Success with file diffs attached
/// ToolResult::success_with_diffs(call_id, "replaced", vec![diff])
///
/// // Interrupt for interactive prompt
/// ToolResult::interrupt(call_id, Arc::new(MyPayload { ... }))
///
/// // Chain .with_sources() onto any Success
/// ToolResult::success(call_id, results).with_sources(srcs)
/// ```
///
/// # Relation to [`message::ToolResult`](crate::message::ToolResult)
///
/// This type lives in the *tool* module and represents the raw outcome of
/// executing a tool. It is converted into a [`Message`](crate::message::Message)
/// with `role: "tool"` (via [`AgentEvent::ToolResult`](crate::event::AgentEvent::ToolResult))
/// before being appended to the conversation history sent to the LLM.
#[derive(Clone)]
pub enum ToolResult {
    /// Tool executed successfully.
    Success {
        tool_call_id: String,
        content: Vec<ContentPart>,
        sources: Vec<Source>,
        diffs: Vec<FileDiff>,
        /// New agent working directory after a successful workspace switch.
        working_dir: Option<PathBuf>,
        /// Local files the result shows, such as an image it read or made.
        files: Vec<PathBuf>,
    },
    /// Tool execution failed.
    Failure {
        tool_call_id: String,
        content: Vec<ContentPart>,
    },
    /// The agent loop should stop and return this result to the caller for
    /// interactive handling. The typed payload is downcast by the caller to
    /// determine the interrupt kind.
    Interrupt {
        tool_call_id: String,
        payload: Arc<dyn InterruptPayload>,
    },
}

impl std::fmt::Debug for ToolResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Success { tool_call_id, .. } => f
                .debug_struct("Success")
                .field("tool_call_id", tool_call_id)
                .field("output", &self.output())
                .finish(),
            Self::Failure { tool_call_id, .. } => f
                .debug_struct("Failure")
                .field("tool_call_id", tool_call_id)
                .field("output", &self.output())
                .finish(),
            Self::Interrupt {
                tool_call_id,
                payload,
            } => f
                .debug_struct("Interrupt")
                .field("tool_call_id", tool_call_id)
                .field("output", &payload.display_output())
                .finish(),
        }
    }
}

impl ToolResult {
    /// Create a basic success result with no sources or diffs.
    pub fn success(tool_call_id: &str, output: impl Into<String>) -> Self {
        Self::success_with_content(
            tool_call_id,
            vec![ContentPart::Text {
                text: output.into(),
            }],
        )
    }

    /// Create a successful result containing ordered text and media parts.
    pub fn success_with_content(tool_call_id: &str, content: Vec<ContentPart>) -> Self {
        Self::Success {
            tool_call_id: tool_call_id.into(),
            content,
            sources: Vec::new(),
            diffs: Vec::new(),
            working_dir: None,
            files: Vec::new(),
        }
    }

    /// Append content to a successful result, preserving its order.
    pub fn with_parts(mut self, parts: Vec<ContentPart>) -> Self {
        if let Self::Success { content, .. } = &mut self {
            content.extend(parts);
        }
        self
    }

    /// Return the ordered content of a completed tool call.
    pub fn content(&self) -> &[ContentPart] {
        match self {
            Self::Success { content, .. } | Self::Failure { content, .. } => content,
            Self::Interrupt { .. } => &[],
        }
    }

    /// Append text to a completed result.
    pub fn append_text(&mut self, text: &str) {
        match self {
            Self::Success { content, .. } | Self::Failure { content, .. } => {
                match content.last_mut() {
                    Some(ContentPart::Text { text: last }) => last.push_str(text),
                    _ => content.push(ContentPart::Text {
                        text: text.to_owned(),
                    }),
                }
            }
            Self::Interrupt { .. } => {}
        }
    }

    /// Create a failure result with an error message.
    pub fn failure(tool_call_id: &str, output: impl Into<String>) -> Self {
        Self::failure_with_content(
            tool_call_id,
            vec![ContentPart::Text {
                text: output.into(),
            }],
        )
    }

    /// Create a failed result containing ordered text and media parts.
    pub fn failure_with_content(tool_call_id: &str, content: Vec<ContentPart>) -> Self {
        Self::Failure {
            tool_call_id: tool_call_id.into(),
            content,
        }
    }

    /// Create a success result that includes file diffs for tools that
    /// mutate content (file write, text replace, etc.).
    pub fn success_with_diffs(
        tool_call_id: &str,
        output: impl Into<String>,
        diffs: Vec<FileDiff>,
    ) -> Self {
        Self::Success {
            tool_call_id: tool_call_id.into(),
            content: vec![ContentPart::Text {
                text: output.into(),
            }],
            sources: Vec::new(),
            diffs,
            working_dir: None,
            files: Vec::new(),
        }
    }

    /// Create an interrupt result that pauses the agent loop for interactive
    /// user handling (command approval, OAuth, etc.).
    ///
    /// NOTE: the agent turn ends without a tool result in the conversation,
    /// leaving a dangling tool call. Callers must add a `ConversationEntry::tool`
    /// with the same `tool_call_id` after handling the interrupt.
    pub fn interrupt(tool_call_id: &str, payload: Arc<dyn InterruptPayload>) -> Self {
        Self::Interrupt {
            tool_call_id: tool_call_id.into(),
            payload,
        }
    }

    /// Attach source URLs to a `Success` result. Returns `self` unchanged if
    /// the variant is not `Success`.
    ///
    /// This is designed for method chaining:
    /// ```ignore
    /// ToolResult::success(id, "results").with_sources(srcs)
    /// ```
    pub fn with_sources(mut self, sources: Vec<Source>) -> Self {
        if let Self::Success {
            sources: ref mut s, ..
        } = self
        {
            *s = sources;
        }
        self
    }

    /// Change this agent's working directory after the call succeeds.
    /// Tools returning this effect must set `concurrent()` to false.
    pub fn with_working_dir(mut self, path: PathBuf) -> Self {
        if let Self::Success { working_dir, .. } = &mut self {
            *working_dir = Some(path);
        }
        self
    }

    /// Name the local files a `Success` result shows, such as an image the
    /// tool read or generated, so a client can display them.
    pub fn with_files(mut self, paths: Vec<PathBuf>) -> Self {
        if let Self::Success { files, .. } = &mut self {
            files.extend(paths);
        }
        self
    }

    /// The local files a successful result shows.
    pub fn files(&self) -> &[PathBuf] {
        match self {
            Self::Success { files, .. } => files,
            _ => &[],
        }
    }

    /// Working directory selected by a successful tool call.
    pub fn working_dir(&self) -> Option<&Path> {
        match self {
            Self::Success { working_dir, .. } => working_dir.as_deref(),
            _ => None,
        }
    }

    /// Return the tool call ID echoed from the original invocation.
    pub fn tool_call_id(&self) -> &str {
        match self {
            Self::Success { tool_call_id, .. }
            | Self::Failure { tool_call_id, .. }
            | Self::Interrupt { tool_call_id, .. } => tool_call_id,
        }
    }

    /// Return the text output payload (success result, error message, or
    /// interrupt display string).
    pub fn output(&self) -> String {
        match self {
            Self::Success { content, .. } | Self::Failure { content, .. } => content
                .iter()
                .filter_map(|part| match part {
                    ContentPart::Text { text } => Some(text.as_str()),
                    _ => None,
                })
                .collect(),
            Self::Interrupt { payload, .. } => payload.display_output(),
        }
    }

    /// Return the typed interrupt payload, if this is an Interrupt variant.
    pub fn payload(&self) -> Option<&Arc<dyn InterruptPayload>> {
        match self {
            Self::Interrupt { payload, .. } => Some(payload),
            _ => None,
        }
    }

    /// Check whether this result represents a successful execution.
    pub fn is_success(&self) -> bool {
        matches!(self, Self::Success { .. })
    }

    /// Check whether this result is an interrupt requiring user interaction.
    pub fn is_interrupt(&self) -> bool {
        matches!(self, Self::Interrupt { .. })
    }

    /// Return the attached source references, or an empty slice for
    /// non-success variants.
    pub fn sources(&self) -> &[Source] {
        match self {
            Self::Success { sources, .. } => sources,
            _ => &[],
        }
    }

    /// Return the attached file diffs, or an empty slice for non-success
    /// variants.
    pub fn diffs(&self) -> &[FileDiff] {
        match self {
            Self::Success { diffs, .. } => diffs,
            _ => &[],
        }
    }

    /// Truncate output to fit within byte and line limits.
    /// Appends `\n[truncated]` when the output was cut.
    pub fn truncate_output(&mut self, max_bytes: usize, max_lines: usize) {
        let output = self.output();
        let content = match self {
            Self::Success { content, .. } | Self::Failure { content, .. } => content,
            Self::Interrupt { .. } => return,
        };
        if output.len() <= max_bytes && max_lines == usize::MAX {
            return;
        }
        let byte_cut = output.floor_char_boundary(max_bytes);
        let line_cut = if max_lines == 0 {
            0
        } else {
            output
                .match_indices('\n')
                .nth(max_lines - 1)
                .map(|(index, _)| index)
                .unwrap_or(output.len())
        };
        let cut = byte_cut.min(line_cut);
        if cut >= output.len() {
            return;
        }
        let mut remaining = cut;
        let mut marked = false;
        for part in content {
            if let ContentPart::Text { text } = part {
                if marked {
                    text.clear();
                } else if text.len() > remaining {
                    text.truncate(remaining);
                    text.push_str("\n[truncated]");
                    marked = true;
                } else {
                    remaining -= text.len();
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// parse_args
// ---------------------------------------------------------------------------

/// Deserialize tool arguments from a serde_json::Value into a typed struct.
/// Returns a typed error mentioning which tool failed to parse.
pub fn parse_args<T: DeserializeOwned>(tool_name: &str, args: Value) -> anyhow::Result<T> {
    serde_json::from_value(args)
        .map_err(|e| anyhow::anyhow!("Tool '{}': Invalid arguments: {}", tool_name, e))
}

// ---------------------------------------------------------------------------
// Tool trait
// ---------------------------------------------------------------------------

/// Trait for tools that can be invoked by the agent.
///
/// Implementations define a name, description, JSON schema parameters, and async execution
/// logic. Tools are registered in a [`ToolRegistry`] and become available to the LLM during
/// conversation turns via function calling.
///
/// # Required methods
///
/// - [`name`](Self::name) — unique identifier used by the LLM to invoke the tool
/// - [`description`](Self::description) — shown to the LLM to decide when to call the tool
/// - [`parameters`](Self::parameters) — JSON Schema object describing expected arguments
/// - [`execute`](Self::execute) — async logic that runs when the tool is called
///
/// # Optional overrides
///
/// - [`humanize`](Self::humanize) — display-friendly summary (default: comma-separated arg keys)
/// - [`timeout_secs`](Self::timeout_secs) — per-tool timeout (default: uses global default)
/// - [`max_output_bytes`](Self::max_output_bytes) — output size limit (default: 256 KiB)
/// - [`max_output_lines`](Self::max_output_lines) — output line count limit (default: 10,000)
#[async_trait]
pub trait Tool: Send + Sync {
    /// Unique tool name (used for invocation). Must match the name the LLM sees in its function definitions.
    fn name(&self) -> &str;
    /// Human-readable description for the LLM. Used to help the model decide when to invoke this tool.
    fn description(&self) -> &str;
    /// JSON Schema object describing the tool's parameters.
    fn parameters(&self) -> Value;
    /// Execute the tool with given arguments. Returns a [`ToolResult`] on success.
    async fn execute(&self, ctx: ToolContext<'_>) -> anyhow::Result<ToolResult>;
    /// Optional per-tool timeout in seconds. Returns `None` to use the global default.
    fn timeout_secs(&self) -> Option<u64> {
        None
    }

    /// Maximum allowed output size in bytes. Tools that produce large payloads
    /// (e.g. base64-encoded images, arbitrary MCP responses) should return
    /// `usize::MAX` to bypass the limit.
    fn max_output_bytes(&self) -> usize {
        256 * 1024
    }

    /// Maximum allowed output line count. Tools that produce large payloads
    /// should return `usize::MAX` to bypass the limit.
    fn max_output_lines(&self) -> usize {
        10_000
    }

    /// Whether this tool may run at the same time as other tools from the
    /// same model reply, when the agent allows parallel tool calls. Return
    /// `false` for tools that share state or act on one device, so they run
    /// alone between concurrent batches.
    fn concurrent(&self) -> bool {
        true
    }

    /// Whether a running call can continue as a managed background task.
    fn supports_background(&self) -> bool {
        false
    }

    /// Generate a human-readable description of what this tool call does,
    /// suitable for display in a TUI or chat card (e.g. "Reading file Cargo.toml").
    fn humanize(&self, args: &Value) -> String {
        let Some(obj) = args.as_object() else {
            return self.name().to_string();
        };
        let keys: Vec<&str> = obj.keys().map(|k| k.as_str()).collect();
        if keys.is_empty() {
            return self.name().to_string();
        }
        let summary = keys.join(", ");
        if summary.len() > 80 {
            let truncated: String = summary.chars().take(77).collect();
            format!("{truncated}…")
        } else {
            summary
        }
    }
}

// ---------------------------------------------------------------------------
// ToolContext
// ---------------------------------------------------------------------------

/// A request to move a running tool call into the background.
#[derive(Clone, Debug, Default)]
pub struct BackgroundRequest {
    requested: CancellationToken,
}

impl BackgroundRequest {
    pub fn request(&self) {
        self.requested.cancel();
    }

    pub async fn requested(&self) {
        self.requested.cancelled().await;
    }
}

/// Per-invocation context passed to [`Tool::execute`] methods.
///
/// Carries everything a tool needs: the call ID for building results, raw JSON arguments,
/// cancellation support, and the working directory for path resolution.
///
/// # Key fields
///
/// | Field | Purpose |
/// |-------|---------|
/// | [`tool_call_id`](Self::tool_call_id) | Echo into [`ToolResult::tool_call_id`] so results match calls |
/// | [`args`](Self::args) | Raw JSON arguments sent by the LLM — parse with [`parse_args`](Self::parse_args) |
/// | [`working_dir`](Self::working_dir) | Chat workspace root; relative paths resolve against this |
pub struct ToolContext<'a> {
    /// The unique ID for this tool call. Echo into [`ToolResult::tool_call_id`] when returning.
    pub tool_call_id: &'a str,
    /// Raw JSON arguments from the LLM. Use [`parse_args`](Self::parse_args) to deserialize.
    pub args: Value,
    /// Current parent configuration, including its cache routing identity.
    pub llm: Option<&'a AgentLlmConfig>,
    /// Current provider for tools that delegate model requests.
    pub provider: Option<Arc<dyn LlmProvider>>,
    /// Working directory for the current agent (typically chat workspace). Relative paths resolve here.
    pub working_dir: Option<&'a PathBuf>,
    /// Cancellation token for cooperative cancellation. Access via [`cancel_token`](Self::cancel_token) or [`child_token`](Self::child_token).
    cancel_token: &'a CancellationToken,
    /// Optional channel for streaming incremental output during execution.
    progress_tx: Option<tokio::sync::mpsc::UnboundedSender<String>>,
    background_request: Option<&'a BackgroundRequest>,
}

impl<'a> ToolContext<'a> {
    /// Create a new tool execution context.
    pub fn new(
        tool_call_id: &'a str,
        args: Value,
        working_dir: Option<&'a PathBuf>,
        cancel_token: &'a CancellationToken,
    ) -> Self {
        Self {
            tool_call_id,
            args,
            llm: None,
            provider: None,
            working_dir,
            cancel_token,
            progress_tx: None,
            background_request: None,
        }
    }

    /// Pass the current agent configuration to the tool.
    pub fn with_llm(mut self, llm: &'a AgentLlmConfig) -> Self {
        self.llm = Some(llm);
        self
    }

    /// Pass the current provider to tools that delegate model requests.
    pub fn with_provider(mut self, provider: Arc<dyn LlmProvider>) -> Self {
        self.provider = Some(provider);
        self
    }

    /// Attach a progress channel for streaming incremental output.
    pub fn with_progress(mut self, tx: tokio::sync::mpsc::UnboundedSender<String>) -> Self {
        self.progress_tx = Some(tx);
        self
    }

    /// Attach the user's control for backgrounding this running call.
    pub fn with_background_request(mut self, request: &'a BackgroundRequest) -> Self {
        self.background_request = Some(request);
        self
    }

    pub fn background_request(&self) -> Option<&BackgroundRequest> {
        self.background_request
    }

    /// Clone the live output destination when execution moves to an owned task.
    pub fn progress_sender(&self) -> Option<tokio::sync::mpsc::UnboundedSender<String>> {
        self.progress_tx.clone()
    }

    /// Send a progress line through the channel (no-op if no channel is set).
    pub fn progress(&self, line: &str) {
        if let Some(ref tx) = self.progress_tx {
            let _ = tx.send(line.to_string());
        }
    }

    /// Parse the raw JSON arguments into a typed value without consuming them.
    ///
    /// The tool name is included in errors, along with the deserialization error.
    /// This does not validate the tool's JSON schema, so keep the schema in sync
    /// with the argument type.
    ///
    /// ```
    /// use std::path::PathBuf;
    ///
    /// use flashmind_types::tool::ToolContext;
    /// use serde::Deserialize;
    /// use serde_json::json;
    /// use tokio_util::sync::CancellationToken;
    ///
    /// #[derive(Deserialize)]
    /// struct ReadArgs {
    ///     path: PathBuf,
    /// }
    ///
    /// let cancel = CancellationToken::new();
    /// let context = ToolContext::new("call", json!({"path": "src/main.rs"}), None, &cancel);
    /// let args: ReadArgs = context.parse_args("read")?;
    /// assert_eq!(args.path, PathBuf::from("src/main.rs"));
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn parse_args<T: DeserializeOwned>(&self, tool_name: &str) -> anyhow::Result<T> {
        T::deserialize(&self.args)
            .map_err(|e| anyhow::anyhow!("Tool '{}': Invalid arguments: {}", tool_name, e))
    }

    /// Access the cancellation token for cooperative cancellation checks.
    ///
    /// For long-running operations, prefer [`child_token`](Self::child_token) to get
    /// a derived token that can be passed to async sub-operations.
    pub fn cancel_token(&self) -> &CancellationToken {
        self.cancel_token
    }

    /// Create a child cancellation token. Cancels when the parent turn is cancelled.
    /// Use this for spawned tasks so they're automatically cancelled when the user aborts.
    pub fn child_token(&self) -> CancellationToken {
        self.cancel_token.child_token()
    }
}

// ---------------------------------------------------------------------------
// ToolRegistry
// ---------------------------------------------------------------------------

/// Registry of tools available to an agent.
///
/// Stores tools in a HashMap for O(1) lookup by name and supports aliases
/// (e.g., `"bash_exec"` → `"exec"`) that are resolved transparently but not
/// exposed in `definitions()` or `list()`.
#[derive(Clone)]
pub struct ToolRegistry {
    tools: HashMap<String, Arc<dyn Tool>>,
    aliases: HashMap<String, String>,
    truncate_on_overflow: bool,
    output_dir: Arc<OutputDir>,
    gate: Option<Arc<dyn ToolGate>>,
}

/// Temp directory for oversized tool output, created on first use and
/// deleted with its contents when the last registry clone sharing it drops.
#[derive(Default)]
struct OutputDir(OnceCell<TempDir>);

impl OutputDir {
    async fn path(&self) -> std::io::Result<&Path> {
        let dir = self
            .0
            .get_or_try_init(|| async {
                tempfile::Builder::new()
                    .prefix("flashmind-output-")
                    .tempdir()
            })
            .await?;
        Ok(dir.path())
    }
}

impl ToolRegistry {
    /// Create an empty tool registry.
    pub fn new() -> Self {
        Self {
            tools: HashMap::new(),
            aliases: HashMap::new(),
            truncate_on_overflow: false,
            output_dir: Arc::default(),
            gate: None,
        }
    }

    /// Check every call with `gate` before it runs. Clones of the registry
    /// keep it.
    pub fn set_gate(&mut self, gate: Arc<dyn ToolGate>) {
        self.gate = Some(gate);
    }

    /// The gate calls pass, if any.
    pub fn gate(&self) -> Option<&Arc<dyn ToolGate>> {
        self.gate.as_ref()
    }

    /// When `true`, oversized output is truncated and dropped. Default:
    /// `false` (the full output is saved to a temp file and the agent gets a
    /// truncated preview with the file's path). Those files are deleted when
    /// the registry and all its clones are dropped.
    pub fn set_truncate_on_overflow(&mut self, enabled: bool) {
        self.truncate_on_overflow = enabled;
    }

    /// Register a tool (replaces existing tool with same name).
    pub fn register(&mut self, tool: Arc<dyn Tool>) {
        tracing::debug!(tool = tool.name(), "registered tool");
        self.tools.insert(tool.name().to_string(), tool);
    }

    /// Remove a tool by name. Returns true if the tool was present.
    pub fn remove(&mut self, name: &str) -> bool {
        let removed = self.tools.remove(name).is_some();
        if removed {
            let tools = &self.tools;
            self.aliases.retain(|_, target| tools.contains_key(target));
        }
        removed
    }

    /// Remove every tool whose name starts with one of `prefixes`. Aliases
    /// pointing at removed tools are also dropped.
    pub fn strip_prefixes(&mut self, prefixes: &[&str]) {
        let to_remove: Vec<String> = self
            .tools
            .keys()
            .filter(|name| prefixes.iter().any(|p| name.starts_with(p)))
            .cloned()
            .collect();
        for name in to_remove {
            self.tools.remove(&name);
        }
        let tools = &self.tools;
        self.aliases.retain(|_, target| tools.contains_key(target));
    }

    /// Register an alias so that lookups for `alias` resolve to `target`.
    /// Aliases are not exposed in `definitions()` or `list()`.
    pub fn alias(&mut self, alias: &str, target: &str) {
        tracing::debug!(alias, target, "registered tool alias");
        self.aliases.insert(alias.to_string(), target.to_string());
    }

    /// Look up a tool by name (checks aliases if direct lookup fails).
    /// Always resolves any registered tool, even if not in the active set.
    pub fn get(&self, name: &str) -> Option<&Arc<dyn Tool>> {
        let result = self.tools.get(name).or_else(|| {
            if let Some(target) = self.aliases.get(name) {
                tracing::debug!(
                    alias = name,
                    target = target.as_str(),
                    "resolved tool alias"
                );
                self.tools.get(target)
            } else {
                None
            }
        });

        if result.is_none() {
            tracing::warn!(tool = name, "tool not found in registry");
        }

        result
    }

    /// Returns true if a tool with the given name is registered (without logging).
    pub fn contains(&self, name: &str) -> bool {
        self.resolve(name).is_some()
    }

    /// Look up a tool directly or through an alias, without logging.
    fn resolve(&self, name: &str) -> Option<&Arc<dyn Tool>> {
        self.tools.get(name).or_else(|| {
            self.aliases
                .get(name)
                .and_then(|target| self.tools.get(target))
        })
    }

    /// Keep only tools whose name satisfies the predicate.
    pub fn retain(&mut self, mut f: impl FnMut(&str) -> bool) {
        self.tools.retain(|name, _| f(name));
        let tools = &self.tools;
        self.aliases.retain(|_, target| tools.contains_key(target));
    }

    /// List all registered tool names (sorted).
    pub fn list(&self) -> Vec<&str> {
        let mut names: Vec<&str> = self.tools.keys().map(|s| s.as_str()).collect();
        names.sort();
        names
    }

    /// List all registered tools with their names and descriptions (sorted by name).
    pub fn list_with_descriptions(&self) -> Vec<(&str, &str)> {
        let mut items: Vec<(&str, &str)> = self
            .tools
            .values()
            .map(|t| (t.name(), t.description()))
            .collect();
        items.sort_by_key(|(name, _)| *name);
        items
    }

    /// Execute a tool call from the LLM.
    ///
    /// Looks up the tool by name, builds a [`ToolContext`], and runs it. Returns
    /// a [`ToolResult::Failure`] if the tool is not found or if execution errors.
    /// If the tool defines [`timeout_secs`](Tool::timeout_secs), the call is
    /// wrapped in a timeout. Tools without a timeout are cancelled immediately
    /// when `cancel_token` fires.
    pub async fn execute(
        &self,
        call: &crate::ToolCall,
        working_dir: Option<&PathBuf>,
        cancel_token: &CancellationToken,
    ) -> ToolResult {
        self.execute_inner(call, working_dir, cancel_token, None)
            .await
    }

    /// Like [`Self::execute`] but attaches a progress channel so tools can stream
    /// incremental output (e.g. stdout lines from bash).
    pub async fn execute_with_progress(
        &self,
        call: &crate::ToolCall,
        working_dir: Option<&PathBuf>,
        cancel_token: &CancellationToken,
        progress_tx: tokio::sync::mpsc::UnboundedSender<String>,
    ) -> ToolResult {
        self.execute_inner(call, working_dir, cancel_token, Some(progress_tx))
            .await
    }

    async fn execute_inner(
        &self,
        call: &crate::ToolCall,
        working_dir: Option<&PathBuf>,
        cancel_token: &CancellationToken,
        progress_tx: Option<tokio::sync::mpsc::UnboundedSender<String>>,
    ) -> ToolResult {
        let mut ctx = ToolContext::new(&call.id, call.arguments.clone(), working_dir, cancel_token);
        if let Some(tx) = progress_tx {
            ctx = ctx.with_progress(tx);
        }
        self.execute_in_context(call, ctx).await
    }

    /// Execute with parent configuration and optional progress reporting.
    pub async fn execute_in_context(
        &self,
        call: &crate::ToolCall,
        ctx: ToolContext<'_>,
    ) -> ToolResult {
        let Some(tool) = self.get(&call.name) else {
            return ToolResult::failure(&call.id, format!("Unknown tool: {}", call.name));
        };
        if let Some(gate) = &self.gate
            && let Some(refused) = pass_gate(gate.as_ref(), call, ctx.cancel_token).await
        {
            return refused;
        }
        let cancel_token = ctx.cancel_token;
        let child_token = cancel_token.child_token();
        let ctx = ToolContext {
            cancel_token: &child_token,
            ..ctx
        };
        let fut = tool.execute(ctx);

        // Always race against cancel_token so user-initiated cancellation
        // works regardless of whether the tool defined a hard timeout.
        let timeout_secs = tool.timeout_secs();
        let run = async {
            match timeout_secs {
                Some(secs) => tokio::time::timeout(std::time::Duration::from_secs(secs), fut)
                    .await
                    .map_err(|_| secs),
                None => Ok(fut.await),
            }
        };
        let outcome = tokio::select! {
            biased;
            _ = cancel_token.cancelled() => {
                child_token.cancel();
                return ToolResult::failure(
                    &call.id,
                    format!("Tool '{}' cancelled", call.name),
                );
            }
            r = run => match r {
                Ok(result) => result,
                Err(secs) => {
                    child_token.cancel();
                    return ToolResult::failure(
                        &call.id,
                        format!("Tool '{}' timed out after {secs}s", call.name),
                    );
                }
            },
        };

        let result = match outcome {
            Ok(result) => result,
            Err(e) => ToolResult::failure(&call.id, format!("Tool error: {e:#}")),
        };

        self.enforce_output_limits(
            &call.id,
            result,
            tool.max_output_bytes(),
            tool.max_output_lines(),
        )
        .await
    }

    /// Whether `call` may run alongside other calls. Unknown tools fail at
    /// once, so they count as concurrent.
    pub fn is_concurrent(&self, call: &crate::ToolCall) -> bool {
        self.resolve(&call.name)
            .is_none_or(|tool| tool.concurrent())
    }

    pub fn supports_background(&self, call: &crate::ToolCall) -> bool {
        self.resolve(&call.name)
            .is_some_and(|tool| tool.supports_background())
    }

    /// Human-readable summary of a tool call's arguments.
    pub fn humanize(&self, call: &crate::ToolCall) -> String {
        self.get(&call.name)
            .map(|t| t.humanize(&call.arguments))
            .unwrap_or_else(|| call.name.clone())
    }

    /// Generate LLM tool definitions for all registered tools.
    pub fn definitions(&self) -> Vec<ToolDefinition> {
        let mut defs: Vec<ToolDefinition> = self
            .tools
            .values()
            .map(|t| ToolDefinition {
                name: t.name().to_string(),
                description: t.description().to_string(),
                parameters: t.parameters(),
            })
            .collect();

        defs.sort_by(|a, b| a.name.cmp(&b.name));

        tracing::debug!(count = defs.len(), "generated tool definitions");

        defs
    }
}

impl Default for ToolRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Asks `gate` about `call`, waiting for an answer when it asks someone.
/// `None` lets the call run; otherwise the refusal is its result.
async fn pass_gate(
    gate: &dyn ToolGate,
    call: &crate::ToolCall,
    cancel: &CancellationToken,
) -> Option<ToolResult> {
    let ask = match gate.check(call).await {
        GateDecision::Allow => return None,
        GateDecision::Deny(reason) => return Some(ToolResult::failure(&call.id, reason)),
        GateDecision::Ask(ask) => ask,
    };
    let answer = tokio::select! {
        _ = cancel.cancelled() => {
            return Some(ToolResult::failure(&call.id, format!("Tool '{}' cancelled", call.name)));
        }
        answer = tokio::time::timeout(ask.timeout, ask.answer) => answer,
    };
    match answer {
        Ok(GateAnswer::Allow) => None,
        Ok(GateAnswer::Deny(reason)) => Some(ToolResult::failure(&call.id, reason)),
        Err(_) => Some(ToolResult::failure(
            &call.id,
            format!(
                "Not done: nobody answered in time to allow '{}'.",
                call.name
            ),
        )),
    }
}

impl ToolRegistry {
    /// Enforce output size limits on a tool result.
    ///
    /// Oversized output is cut to the limits. Unless the registry opts into
    /// [`set_truncate_on_overflow`](ToolRegistry::set_truncate_on_overflow), the
    /// full output is first saved to a new file in the registry's temp directory,
    /// whose path ends the preview,
    /// so the agent can read or search it. If that file cannot be written, a
    /// successful result becomes a failure asking for narrower arguments. A
    /// failure keeps its start (such as an exit code) either way.
    async fn enforce_output_limits(
        &self,
        tool_call_id: &str,
        mut result: ToolResult,
        max_bytes: usize,
        max_lines: usize,
    ) -> ToolResult {
        if result.is_interrupt() {
            return result;
        }
        let output = result.output();
        let bytes = output.len();
        let lines = output.lines().count();
        let over_bytes = bytes > max_bytes;
        let over_lines = lines > max_lines;

        if !over_bytes && !over_lines {
            return result;
        }

        if self.truncate_on_overflow {
            result.truncate_output(max_bytes, max_lines);
            return result;
        }

        match self.save_full_output(&output).await {
            Ok(path) => {
                result.truncate_output(max_bytes, max_lines);
                result.append_text(&format!(
                    "\n[full output ({bytes} bytes, {lines} lines) saved to {}]",
                    path.display()
                ));
                result
            }
            Err(e) => {
                tracing::warn!(error = %e, "could not save oversized tool output");
                if !result.is_success() {
                    result.truncate_output(max_bytes, max_lines);
                    return result;
                }
                if over_bytes {
                    ToolResult::failure(
                        tool_call_id,
                        format!(
                            "Output too large ({bytes} bytes, limit {max_bytes}). \
                             Use more specific arguments to reduce output size."
                        ),
                    )
                } else {
                    ToolResult::failure(
                        tool_call_id,
                        format!(
                            "Output too many lines ({lines}, limit {max_lines}). \
                             Use more specific arguments to reduce output size."
                        ),
                    )
                }
            }
        }
    }

    /// Write `output` to a new, randomly named file in the registry's temp
    /// directory, readable only by the current user.
    async fn save_full_output(&self, output: &str) -> std::io::Result<PathBuf> {
        let path = self
            .output_dir
            .path()
            .await?
            .join(format!("{}.txt", Uuid::new_v4()));
        let mut options = OpenOptions::new();
        options.write(true).create_new(true);
        #[cfg(unix)]
        options.mode(0o600);
        let mut file = options.open(&path).await?;
        file.write_all(output.as_bytes()).await?;
        file.flush().await?;
        Ok(path)
    }
}

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

    /// Return the path named in the `saved to` note at the end of `output`.
    fn saved_path(output: &str) -> PathBuf {
        let start = output
            .rfind("saved to ")
            .expect("output names a saved file")
            + 9;
        PathBuf::from(output[start..].trim_end_matches(']'))
    }

    #[tokio::test]
    async fn failed_output_is_truncated_not_passed_through() {
        let output = "x\n".repeat(100);
        let mut registry = ToolRegistry::new();
        registry.set_truncate_on_overflow(true);
        let result = registry
            .enforce_output_limits(
                "call",
                ToolResult::failure("call", output.clone()),
                50,
                usize::MAX,
            )
            .await;
        assert!(!result.is_success());
        let output = result.output();
        assert!(output.len() < 70, "{output}");
        assert!(output.ends_with("[truncated]"), "{output}");
    }

    #[tokio::test]
    async fn oversized_output_is_saved_to_temp_file() {
        let registry = ToolRegistry::new();
        let full = "line\n".repeat(100);
        let mut paths = Vec::new();
        for result in [
            ToolResult::success("call", full.clone()),
            ToolResult::failure("call", full.clone()),
        ] {
            let was_success = result.is_success();
            let result = registry
                .enforce_output_limits("call", result, usize::MAX, 10)
                .await;
            assert_eq!(result.is_success(), was_success);

            let output = result.output();
            assert!(output.starts_with(&"line\n".repeat(9)), "{output}");
            assert!(output.contains("[truncated]"), "{output}");
            assert!(output.contains("(500 bytes, 100 lines)"), "{output}");

            let path = saved_path(&output);
            let saved = std::fs::read_to_string(&path).expect("saved file is readable");
            assert_eq!(saved, full);
            paths.push(path);
        }

        // A clone shares the directory, so only the last drop removes it.
        let clone = registry.clone();
        drop(registry);
        assert!(paths.iter().all(|p| p.exists()));
        drop(clone);
        assert!(paths.iter().all(|p| !p.exists()));
    }

    #[test]
    fn mixed_result_projects_text_and_keeps_ordered_content() {
        let mut result = ToolResult::success_with_content(
            "call",
            vec![
                ContentPart::Text {
                    text: "before ".into(),
                },
                ContentPart::Image {
                    media_type: "image/png".into(),
                    data: "encoded".into(),
                },
                ContentPart::Text {
                    text: "after".into(),
                },
            ],
        );
        assert_eq!(result.output(), "before after");
        assert!(
            matches!(&result.content()[1], ContentPart::Image { data, .. } if data == "encoded")
        );
        result.append_text("!");
        assert_eq!(result.output(), "before after!");
        assert!(!format!("{result:?}").contains("encoded"));
    }

    #[tokio::test]
    async fn limits_apply_to_combined_text_and_leave_images_untouched() {
        let registry = ToolRegistry::new();
        let result = ToolResult::success_with_content(
            "call",
            vec![
                ContentPart::Text { text: "ab".into() },
                ContentPart::Image {
                    media_type: "image/png".into(),
                    data: "encoded".into(),
                },
                ContentPart::Text {
                    text: "éxyz".into(),
                },
            ],
        );
        let result = registry
            .enforce_output_limits("call", result, 3, usize::MAX)
            .await;
        assert!(result.is_success());
        assert!(result.output().starts_with("ab\n[truncated]"));
        assert!(
            matches!(&result.content()[1], ContentPart::Image { data, .. } if data == "encoded")
        );
        assert_eq!(
            std::fs::read_to_string(saved_path(&result.output())).unwrap(),
            "abéxyz"
        );
    }

    #[test]
    fn failure_content_preserves_media_and_text_projection() {
        let mut result = ToolResult::failure_with_content(
            "call",
            vec![
                ContentPart::Text {
                    text: "failed".into(),
                },
                ContentPart::Image {
                    media_type: "image/png".into(),
                    data: "encoded".into(),
                },
            ],
        );
        result.append_text(" details");
        assert!(!result.is_success());
        assert_eq!(result.output(), "failed details");
        assert_eq!(result.content().len(), 3);
    }

    #[tokio::test]
    async fn output_within_limits_is_unchanged() {
        let result = ToolRegistry::new()
            .enforce_output_limits("call", ToolResult::success("call", "ok"), 10, 10)
            .await;
        assert_eq!(result.output(), "ok");
    }

    struct DummyTool(&'static str);

    #[async_trait]
    impl Tool for DummyTool {
        fn name(&self) -> &str {
            self.0
        }
        fn description(&self) -> &str {
            "dummy"
        }
        fn parameters(&self) -> Value {
            serde_json::json!({})
        }
        async fn execute(&self, ctx: ToolContext<'_>) -> anyhow::Result<ToolResult> {
            Ok(ToolResult::success(ctx.tool_call_id, "ok"))
        }
    }

    #[test]
    fn test_registry_empty() {
        let registry = ToolRegistry::new();
        assert_eq!(registry.list().len(), 0);
    }

    #[test]
    fn test_registry_definitions_empty() {
        let registry = ToolRegistry::new();
        assert!(registry.definitions().is_empty());
    }

    #[test]
    fn test_registry_lookup() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(DummyTool("exec")));
        registry.register(Arc::new(DummyTool("slack_react")));
        registry.register(Arc::new(DummyTool("browser")));

        assert_eq!(registry.definitions().len(), 3);

        // get() resolves tools by name
        assert!(registry.get("slack_react").is_some());
    }

    #[test]
    fn test_registry_alias_contains_and_remove_cleanup() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(DummyTool("exec")));
        registry.alias("bash_exec", "exec");

        assert!(registry.contains("exec"));
        assert!(registry.contains("bash_exec"));
        assert!(registry.get("bash_exec").is_some());

        assert!(registry.remove("exec"));
        assert!(!registry.contains("exec"));
        assert!(!registry.contains("bash_exec"));
        assert!(registry.get("bash_exec").is_none());
    }

    /// Tool that sleeps forever (until cancelled). Declares a long
    /// timeout_secs so it takes the "timeout" branch of ToolRegistry::execute.
    struct SlowTimeoutTool;

    #[async_trait]
    impl Tool for SlowTimeoutTool {
        fn name(&self) -> &str {
            "slow"
        }
        fn description(&self) -> &str {
            "sleeps forever"
        }
        fn parameters(&self) -> Value {
            serde_json::json!({})
        }
        fn timeout_secs(&self) -> Option<u64> {
            Some(600)
        }
        async fn execute(&self, _ctx: ToolContext<'_>) -> anyhow::Result<ToolResult> {
            // Sleep beyond the test budget; cancellation must short-circuit.
            tokio::time::sleep(std::time::Duration::from_secs(60)).await;
            Ok(ToolResult::success("unused", "should not return"))
        }
    }

    #[tokio::test]
    async fn registry_cancel_short_circuits_tool_with_timeout_secs() {
        // Regression: a tool that sets timeout_secs() used to bypass the
        // cancel-token race entirely. Cancelling now must still abort it.
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(SlowTimeoutTool));

        let cancel = CancellationToken::new();
        let cancel_clone = cancel.clone();

        let call = crate::ToolCall {
            id: "c1".into(),
            name: "slow".into(),
            arguments: serde_json::json!({}),
        };

        let registry = Arc::new(registry);
        let registry2 = registry.clone();
        let exec = tokio::spawn(async move { registry2.execute(&call, None, &cancel).await });

        // Let the tool start, then cancel.
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        cancel_clone.cancel();

        // Must return within 2s of cancellation, NOT after 600s timeout.
        let result = tokio::time::timeout(std::time::Duration::from_secs(2), exec)
            .await
            .expect("registry did not return within 2s of cancellation")
            .unwrap();

        assert!(!result.is_success(), "expected failure on cancel");
        assert!(
            result.output().contains("cancelled"),
            "expected 'cancelled' in output, got: {}",
            result.output()
        );
    }

    /// Counts its runs.
    struct CountedTool(Arc<std::sync::atomic::AtomicUsize>);

    #[async_trait]
    impl Tool for CountedTool {
        fn name(&self) -> &str {
            "act"
        }
        fn description(&self) -> &str {
            "acts"
        }
        fn parameters(&self) -> Value {
            serde_json::json!({})
        }
        async fn execute(&self, ctx: ToolContext<'_>) -> anyhow::Result<ToolResult> {
            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Ok(ToolResult::success(ctx.tool_call_id, "acted"))
        }
    }

    /// Hands out one prepared decision per call.
    struct ScriptedGate(std::sync::Mutex<Vec<GateDecision>>);

    #[async_trait]
    impl ToolGate for ScriptedGate {
        async fn check(&self, _call: &crate::ToolCall) -> GateDecision {
            self.0
                .lock()
                .expect("the test does not panic while holding it")
                .pop()
                .unwrap_or(GateDecision::Allow)
        }
    }

    fn gated(decision: GateDecision) -> (ToolRegistry, Arc<std::sync::atomic::AtomicUsize>) {
        let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(CountedTool(runs.clone())));
        registry.set_gate(Arc::new(ScriptedGate(std::sync::Mutex::new(vec![
            decision,
        ]))));
        (registry, runs)
    }

    fn act_call() -> crate::ToolCall {
        crate::ToolCall {
            id: "c1".into(),
            name: "act".into(),
            arguments: serde_json::json!({}),
        }
    }

    fn ask(
        timeout: std::time::Duration,
    ) -> (GateDecision, tokio::sync::oneshot::Sender<GateAnswer>) {
        let (answer, asked) = tokio::sync::oneshot::channel();
        let decision = GateDecision::Ask(GateAsk {
            answer: Box::pin(async move {
                asked
                    .await
                    .unwrap_or(GateAnswer::Deny("nobody answered".into()))
            }),
            timeout,
        });
        (decision, answer)
    }

    #[tokio::test]
    async fn a_denied_call_does_not_run_and_returns_the_reason() {
        let (registry, runs) = gated(GateDecision::Deny("not allowed here".into()));
        let result = registry
            .execute(&act_call(), None, &CancellationToken::new())
            .await;
        assert!(!result.is_success());
        assert_eq!(result.output(), "not allowed here");
        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn an_asked_call_waits_for_the_answer_then_runs() {
        let (decision, answer) = ask(std::time::Duration::from_secs(30));
        let (registry, runs) = gated(decision);
        let registry = Arc::new(registry);
        let running = registry.clone();
        let call = tokio::spawn(async move {
            running
                .execute(&act_call(), None, &CancellationToken::new())
                .await
        });
        tokio::task::yield_now().await;
        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 0);
        answer
            .send(GateAnswer::Allow)
            .expect("the call is still waiting");
        let result = call.await.expect("the call does not panic");
        assert!(result.is_success());
        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn an_asked_call_refused_by_the_answer_does_not_run() {
        let (decision, answer) = ask(std::time::Duration::from_secs(30));
        let (registry, runs) = gated(decision);
        answer
            .send(GateAnswer::Deny("the user said no".into()))
            .expect("the receiver is held by the gate's question");
        let result = registry
            .execute(&act_call(), None, &CancellationToken::new())
            .await;
        assert_eq!(result.output(), "the user said no");
        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn an_unanswered_call_is_refused_when_its_time_runs_out() {
        let (decision, _answer) = ask(std::time::Duration::from_millis(20));
        let (registry, runs) = gated(decision);
        let result = registry
            .execute(&act_call(), None, &CancellationToken::new())
            .await;
        assert!(!result.is_success());
        assert!(result.output().contains("nobody answered in time"));
        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn clones_keep_the_gate() {
        let (registry, runs) = gated(GateDecision::Deny("no".into()));
        let copy = registry.clone();
        assert!(copy.gate().is_some());
        let result = copy
            .execute(&act_call(), None, &CancellationToken::new())
            .await;
        assert!(!result.is_success());
        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 0);
    }
}