eclipse-core 0.13.2

Core library for eclipse: providers, tools, sessions, config, runtime
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
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
//! The `delegate` tool: hand one job to a child agent on a route of its own.
//!
//! A child is an [`Agent`], not a second loop. It has the provider of the route it was sent to,
//! a session of its own that the parent never sees, a preamble that says what it is, a small
//! iteration budget and the same tools as the parent minus this one. It runs to its final
//! answer, and that text is the tool's result; what it cost is reported beside it, separately,
//! so the parent's own usage line does not quietly absorb it.
//!
//! This is a cap, not a scheduler. A child cannot delegate (the tool is not in its registry), a
//! run may start at most [`MAX_CHILDREN_PER_RUN`], and there is no queue, no background run and
//! no write to the parent's session: the parent's transcript holds the call and the answer.
//! A child that fails is a tool result with the reason, which the model reads like any other.

use crate::config::NamedRoute;
use crate::error::Error;
use crate::hooks::LoopHooks;
use crate::provider::{ChatProvider, OpenAiProvider, ProviderProfile};
use crate::router::RouteInfo;
use crate::runtime::{Agent, AgentEvent};
use crate::session::SessionStore;
use crate::tools::{truncate, Approver, CallScope, Tool, ToolError, ToolRegistry};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// The most children one run may start. A child is a request to a possibly bigger model that
/// may run tools, so the bound is on spend, and four is room for a few independent jobs
/// without leaving a model free to fan out on every turn.
pub const MAX_CHILDREN_PER_RUN: usize = 4;

/// The budget a child gets when the call names none. Each iteration is a request to a
/// possibly big model; six is enough to look at a few things and answer, and short enough
/// that a child that is wandering is stopped before it is expensive.
pub const DEFAULT_CHILD_ITERATIONS: usize = 6;

/// The most a call may ask for. A job that needs more is a job to split.
pub const MAX_CHILD_ITERATIONS: usize = 20;

/// How much of a prompt's first line the approval summary shows, in characters.
const SUMMARY_PROMPT_CHARS: usize = 100;

/// What the child is told it is. The parent's own system prompt, context files, skills and
/// memory are deliberately not passed on: the child sees the job, not the conversation.
const PREAMBLE: &str = "You are a subagent. Another agent handed you one job and will read \
only your final message, so make that message the answer itself: no greeting, no recap of \
what you did unless it matters, no questions back. You cannot ask the user anything and you \
cannot delegate. Use the tools you have to do the job, and finish within your iteration \
budget.";

/// A route as a child needs it: a provider of its own and the per-agent settings that belong
/// to that route.
pub struct ChildRoute {
    pub name: String,
    pub provider: Arc<dyn ChatProvider>,
    pub context_budget_tokens: usize,
}

/// Where children get their providers. A trait so the tool can be tested without a server and
/// so it never holds the configuration itself.
pub trait ChildProviders: Send + Sync {
    /// The routes a call may name, in the order they are listed to the model.
    fn routes(&self) -> Vec<RouteInfo>;
    /// The route a call that names none goes to.
    fn default_route(&self) -> String;
    /// A provider for `route`, fresh for this child: a provider holds the usage of its last
    /// request, so two children sharing one would read each other's cost.
    fn provider(&self, route: &str) -> Result<ChildRoute, String>;
    /// Why `route` cannot be used here even though it exists. Only a pin has something to say:
    /// answering "unknown route" about a route the user did configure would send the model
    /// hunting for a name it already knows.
    fn refusal(&self, _route: &str) -> Option<String> {
        None
    }
}

/// [`ChildProviders`] over the configuration's routes.
pub struct ConfigRoutes {
    routes: Vec<NamedRoute>,
    profiles: Vec<ProviderProfile>,
    /// `[provider] delegate`: the route a call with no `route` goes to.
    delegate: Option<String>,
    /// The route the parent's run is on, which a call with no `route` goes to when the config
    /// names none.
    selected: String,
    /// `--route` / `ECLIPSE_ROUTE`, when the run is pinned: the one route text may go to. A pin
    /// bounds where the run's text may go, so under it only this route is offered to the model
    /// and naming another is refused — the pin would mean nothing if the model could ask for a
    /// subagent elsewhere.
    pinned: Option<String>,
    /// `--model` / `/model`, shared with the agent: it changes the selected route's model.
    model: Arc<Mutex<Option<String>>>,
}

impl ConfigRoutes {
    pub fn new(
        routes: Vec<NamedRoute>,
        profiles: Vec<ProviderProfile>,
        delegate: Option<String>,
        selected: String,
        pinned: Option<String>,
        model: Arc<Mutex<Option<String>>>,
    ) -> Self {
        Self {
            routes,
            profiles,
            delegate,
            selected,
            pinned,
            model,
        }
    }
}

impl ChildProviders for ConfigRoutes {
    fn routes(&self) -> Vec<RouteInfo> {
        self.routes
            .iter()
            .filter(|r| match &self.pinned {
                Some(pinned) => &r.name == pinned,
                None => true,
            })
            .map(|r| RouteInfo {
                name: r.name.clone(),
                model: r.config.model.clone(),
                endpoint: r.config.base_url.clone(),
            })
            .collect()
    }

    fn default_route(&self) -> String {
        self.delegate
            .clone()
            .unwrap_or_else(|| self.selected.clone())
    }

    fn refusal(&self, route: &str) -> Option<String> {
        let pinned = self.pinned.as_deref()?;
        if route == pinned || !self.routes.iter().any(|r| r.name == route) {
            return None;
        }
        Some(format!(
            "this run is pinned to `{pinned}` with --route, so a subagent cannot be sent to \
             `{route}`. Drop `route`, or drop the pin."
        ))
    }

    fn provider(&self, route: &str) -> Result<ChildRoute, String> {
        if let Some(why) = self.refusal(route) {
            return Err(why);
        }
        let named = self
            .routes
            .iter()
            .find(|r| r.name == route)
            .ok_or_else(|| format!("route `{route}` is not configured"))?;
        let mut cfg = named.config.clone();
        if route == self.selected {
            if let Some(model) = self.model.lock().ok().and_then(|m| m.clone()) {
                cfg.model = model;
            }
        }
        if cfg.base_url.trim().is_empty() || cfg.model.trim().is_empty() {
            return Err(format!("route `{route}` has no base_url or no model"));
        }
        let provider = OpenAiProvider::with_profiles(&cfg, &self.profiles)
            .map_err(|e| format!("route `{route}`: {e}"))?;
        Ok(ChildRoute {
            name: route.to_string(),
            provider: Arc::new(provider),
            context_budget_tokens: cfg.context_budget_tokens,
        })
    }
}

/// What one child cost and how it ended.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChildRun {
    pub route: String,
    /// The child's own session, which `eclipse sessions list` shows as a subagent's.
    pub session_id: String,
    pub prompt_tokens: Option<u64>,
    pub completion_tokens: Option<u64>,
    /// Requests the child made to its model.
    pub iterations: usize,
    pub failed: bool,
}

/// The children one run has started: how many (the cap), and what each cost (the readout).
/// One per run, so two runs on one agent do not share a cap.
#[derive(Default)]
pub struct ChildLedger {
    started: Mutex<usize>,
    runs: Mutex<Vec<ChildRun>>,
}

impl ChildLedger {
    /// Claim a place for one more child, or `None` when the run is at the cap. Claimed before
    /// the child starts, so calls running at the same time cannot get past it together.
    fn reserve(&self) -> Option<()> {
        let mut started = self.started.lock().ok()?;
        (*started < MAX_CHILDREN_PER_RUN).then(|| *started += 1)
    }

    fn record(&self, run: ChildRun) {
        if let Ok(mut runs) = self.runs.lock() {
            runs.push(run);
        }
    }

    /// The children that have finished, in the order they finished.
    pub fn runs(&self) -> Vec<ChildRun> {
        self.runs.lock().map(|r| r.clone()).unwrap_or_default()
    }
}

fn sum(values: impl Iterator<Item = Option<u64>>) -> Option<u64> {
    values.flatten().reduce(|a, b| a.saturating_add(b))
}

fn count_tokens(n: Option<u64>) -> String {
    n.map_or_else(|| "?".to_string(), |n| n.to_string())
}

fn usage_line(prompt: Option<u64>, completion: Option<u64>, iterations: usize) -> String {
    let iterations = format!(
        "{iterations} iteration{}",
        if iterations == 1 { "" } else { "s" }
    );
    if prompt.is_none() && completion.is_none() {
        return format!("child usage: tokens not reported by the server, {iterations}");
    }
    format!(
        "child usage: {} prompt / {} completion tokens, {iterations}",
        count_tokens(prompt),
        count_tokens(completion)
    )
}

/// The line a run that delegated prints beside its own usage, or `None` when nothing was
/// delegated. The children's cost is summed here and nowhere else, so it is never merged into
/// the parent's token count.
pub fn describe_children(children: &[ChildRun]) -> Option<String> {
    if children.is_empty() {
        return None;
    }
    let routes: Vec<&str> = children.iter().map(|c| c.route.as_str()).collect();
    let failed = children.iter().filter(|c| c.failed).count();
    let usage = usage_line(
        sum(children.iter().map(|c| c.prompt_tokens)),
        sum(children.iter().map(|c| c.completion_tokens)),
        children.iter().map(|c| c.iterations).sum(),
    );
    Some(format!(
        "delegated: {} subagent{} ({}{}) \u{2014} {usage}",
        children.len(),
        if children.len() == 1 { "" } else { "s" },
        routes.join(", "),
        if failed == 0 {
            String::new()
        } else {
            format!("; {failed} failed")
        }
    ))
}

/// Puts the route in front of a child's approval requests, so a prompt for a child's `shell`
/// says whose it is. Approving `delegate` is not approving what the child then does.
struct ChildApprover<'a> {
    inner: &'a dyn Approver,
    route: &'a str,
}

#[async_trait]
impl Approver for ChildApprover<'_> {
    async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision {
        let marked = crate::approvals::Pending::new(
            call.call_id.clone(),
            call.tool.clone(),
            format!("[subagent on {}] {}", self.route, call.summary),
            call.args.clone(),
        );
        self.inner.decide(&marked).await
    }
}

/// What a child is built with that does not depend on the call.
pub struct DelegateSettings {
    pub max_output_bytes: usize,
    pub max_malformed_calls: usize,
    pub tool_concurrency: usize,
    pub lock_wait: Duration,
}

pub struct DelegateTool {
    providers: Arc<dyn ChildProviders>,
    /// The registry every child gets: the parent's, built the same way, without this tool.
    tools: Arc<ToolRegistry>,
    store: SessionStore,
    settings: DelegateSettings,
    /// The loop hooks every child runs with: the parent's, so a child's tool output is
    /// redacted the same way, and into the child's own stored transcript.
    hooks: LoopHooks,
    /// The child's per-turn tool-result buffer for `memory` taint detection (`#482`), isolated
    /// from the parent's turn.
    turn_results: Arc<crate::tools_memory::TurnResults>,
    description: String,
}

impl DelegateTool {
    pub fn new(
        providers: Arc<dyn ChildProviders>,
        tools: Arc<ToolRegistry>,
        store: SessionStore,
        settings: DelegateSettings,
    ) -> Self {
        let routes = providers.routes();
        let listed: Vec<String> = routes
            .iter()
            .map(|r| format!("`{}` ({})", r.name, r.model))
            .collect();
        let description = format!(
            "Hand one self-contained job to a subagent and get its final answer back as this \
             tool's result. The subagent sees only `prompt` (and `system`), not this \
             conversation, so put everything it needs in the prompt. It has the same tools as \
             you except `delegate`, a small iteration budget (default {DEFAULT_CHILD_ITERATIONS}, \
             at most {MAX_CHILD_ITERATIONS}), and a run may start at most \
             {MAX_CHILDREN_PER_RUN} of them. Worth it for a large, separable job that can be \
             stated completely, or one that suits a different model; not for a lookup you can do \
             yourself. `route` picks the model: {}. Default: `{}`.",
            if listed.is_empty() {
                "none configured".to_string()
            } else {
                listed.join(", ")
            },
            providers.default_route(),
        );
        Self {
            providers,
            tools,
            store,
            settings,
            hooks: LoopHooks::default(),
            turn_results: Arc::default(),
            description,
        }
    }

    /// Give every child these loop hooks. Without this a subagent would be the one place a
    /// tool result reaches a model unfiltered.
    pub fn with_hooks(mut self, hooks: LoopHooks) -> Self {
        self.hooks = hooks;
        self
    }

    /// Share the child registry's per-turn tool-result buffer with the child [`Agent`].
    pub fn with_turn_results(
        mut self,
        turn_results: Arc<crate::tools_memory::TurnResults>,
    ) -> Self {
        self.turn_results = turn_results;
        self
    }

    fn known_routes(&self) -> String {
        let names: Vec<String> = self
            .providers
            .routes()
            .into_iter()
            .map(|r| r.name)
            .collect();
        if names.is_empty() {
            "none".to_string()
        } else {
            names.join(", ")
        }
    }

    /// The route a call goes to: the one it names, else the configured default.
    fn resolve_route(&self, args: &Value) -> Result<String, ToolError> {
        match args.get("route") {
            None | Some(Value::Null) => Ok(self.providers.default_route()),
            Some(Value::String(name)) => {
                if let Some(why) = self.providers.refusal(name) {
                    return Err(ToolError::Failed(why));
                }
                let known = self.providers.routes();
                if known.iter().any(|r| &r.name == name) {
                    Ok(name.clone())
                } else {
                    Err(ToolError::Failed(format!(
                        "unknown route `{name}`. Routes that exist: {}",
                        self.known_routes()
                    )))
                }
            }
            Some(_) => Err(ToolError::InvalidArgs("`route` must be a string".into())),
        }
    }
}

fn optional_string<'a>(args: &'a Value, key: &str) -> Result<Option<&'a str>, ToolError> {
    match args.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(s)) => Ok(Some(s)),
        Some(_) => Err(ToolError::InvalidArgs(format!("`{key}` must be a string"))),
    }
}

fn budget_arg(args: &Value) -> Result<usize, ToolError> {
    match args.get("max_iterations") {
        None | Some(Value::Null) => Ok(DEFAULT_CHILD_ITERATIONS),
        Some(v) => match v.as_u64() {
            Some(n) if (1..=MAX_CHILD_ITERATIONS as u64).contains(&n) => Ok(n as usize),
            _ => Err(ToolError::InvalidArgs(format!(
                "`max_iterations` must be a whole number from 1 to {MAX_CHILD_ITERATIONS}"
            ))),
        },
    }
}

/// The first line of a prompt for a one-line summary: control characters removed and cut to
/// [`SUMMARY_PROMPT_CHARS`]; with how many further lines there are.
fn first_line(prompt: &str) -> (String, usize) {
    let mut lines = prompt.trim().lines();
    let first: String = lines
        .next()
        .unwrap_or_default()
        .chars()
        .filter(|c| !c.is_control())
        .collect();
    let mut chars = first.chars();
    let mut out: String = chars.by_ref().take(SUMMARY_PROMPT_CHARS).collect();
    if chars.next().is_some() {
        out.push_str("...");
    }
    (out, lines.count())
}

/// Where a child's session says it came from (`#171`): `delegate` records a subagent of the
/// parent, and a flare records the run and its position in it.
pub(crate) enum ChildOrigin<'a> {
    Subagent { parent: &'a str, route: &'a str },
    Flare { run: &'a str, n: usize },
}

/// One child's job: the words it was given, the route it runs on, and what it may spend.
pub(crate) struct ChildJob<'a> {
    pub prompt: &'a str,
    pub system: Option<&'a str>,
    pub route: &'a str,
    pub budget: usize,
    pub origin: ChildOrigin<'a>,
    /// Made by the caller, not here: a flare run's ledger names the child's session before the
    /// child exists, so a run that is cancelled mid-flight can still be listed.
    pub session_id: &'a str,
}

/// What a child cost and what it said — the one shape both surfaces report (`#171`).
///
/// A failure is a value rather than an `Err`, because `delegate` turns it into a tool result and a
/// flare run turns it into one line of its table: neither wants to lose the cost of a child that
/// tried.
pub struct ChildOutcome {
    pub route: String,
    pub session_id: String,
    pub answer: std::result::Result<String, String>,
    pub prompt_tokens: Option<u64>,
    pub completion_tokens: Option<u64>,
    pub iterations: usize,
}

impl ChildOutcome {
    pub fn failed(&self) -> bool {
        self.answer.is_err()
    }
}

#[async_trait]
impl Tool for DelegateTool {
    fn name(&self) -> &str {
        "delegate"
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "prompt": {
                    "type": "string",
                    "description": "The whole job, stated so it makes sense with no other context."
                },
                "route": {
                    "type": "string",
                    "description": "Which route (model) the subagent runs on. Unset: the \
                                    configured delegate route, else the route this run is on."
                },
                "system": {
                    "type": "string",
                    "description": "Extra instructions for the subagent, added to its preamble."
                },
                "max_iterations": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": MAX_CHILD_ITERATIONS,
                    "description": format!(
                        "How many model requests the subagent may make (default {DEFAULT_CHILD_ITERATIONS})."
                    )
                }
            },
            "required": ["prompt"]
        })
    }

    /// The route, the prompt's first line and the budget: enough to decide on. Written to
    /// survive arguments of the wrong type, because it runs before they are checked.
    fn describe_call(&self, args: &Value) -> String {
        let route = match args.get("route") {
            None | Some(Value::Null) => self.providers.default_route(),
            Some(Value::String(s)) => s.clone(),
            Some(_) => "(invalid route)".to_string(),
        };
        let prompt = args.get("prompt").and_then(Value::as_str).unwrap_or("");
        let budget = match budget_arg(args) {
            Ok(n) => n.to_string(),
            Err(_) => "(invalid)".to_string(),
        };
        let custom = match args.get("system") {
            Some(Value::String(s)) if !s.trim().is_empty() => ", with its own system prompt",
            _ => "",
        };
        let (line, more) = first_line(prompt);
        let more = match more {
            0 => String::new(),
            1 => " (+1 more line)".to_string(),
            n => format!(" (+{n} more lines)"),
        };
        format!(
            "delegate to a subagent on route `{route}`: \"{line}\"{more} \
             (up to {budget} iterations{custom})"
        )
    }

    async fn call(&self, _args: Value) -> Result<String, ToolError> {
        Err(ToolError::Failed(
            "`delegate` only runs inside an agent run".into(),
        ))
    }

    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
        let prompt = crate::tools::str_arg(&args, "prompt")?;
        if prompt.trim().is_empty() {
            return Err(ToolError::InvalidArgs("`prompt` is empty".into()));
        }
        let system = optional_string(&args, "system")?;
        let budget = budget_arg(&args)?;
        let route_name = self.resolve_route(&args)?;

        if scope.run.children.reserve().is_none() {
            return Err(ToolError::Failed(format!(
                "this run has already started {MAX_CHILDREN_PER_RUN} subagents, which is the \
                 most one run may start. Do the remaining work yourself, or put it in one \
                 prompt to a subagent you already have the answer from."
            )));
        }

        // The same child a flare is (`#171`), on the same code path: what differs is the origin
        // string, the budget and whether `delegate`'s cap counted it.
        let session_id = self.store.new_id();
        let outcome = self
            .run_child(
                Arc::clone(&self.tools),
                ChildJob {
                    session_id: &session_id,
                    prompt,
                    system,
                    route: &route_name,
                    budget,
                    origin: ChildOrigin::Subagent {
                        parent: &scope.run.session,
                        route: &route_name,
                    },
                },
                scope.approver,
                &scope.run.cancel,
            )
            .await;
        scope.run.children.record(ChildRun {
            route: outcome.route.clone(),
            session_id: outcome.session_id.clone(),
            prompt_tokens: outcome.prompt_tokens,
            completion_tokens: outcome.completion_tokens,
            iterations: outcome.iterations,
            failed: outcome.failed(),
        });
        let footer = usage_line(
            outcome.prompt_tokens,
            outcome.completion_tokens,
            outcome.iterations,
        );
        match outcome.answer {
            Ok(reply) => {
                // The answer is cut to leave room for the footer, which must survive.
                let note = "\n[output truncated]".len();
                let room = self
                    .settings
                    .max_output_bytes
                    .saturating_sub(footer.len() + 2 + note);
                Ok(format!("{}\n\n{footer}", truncate(reply, room)))
            }
            Err(reason) => Err(ToolError::Failed(format!(
                "the subagent on route `{}` failed: {reason}\n\n{footer}",
                outcome.route
            ))),
        }
    }
}

impl DelegateTool {
    /// The registry a flare runs with: the child registry narrowed to the readers (`#171`,
    /// `#548`). Here rather than in `flares.rs` because this is the one place that knows what a
    /// child gets, so it is the one place that should know what a flare may hold.
    ///
    /// An allowlist, not a subtraction: `cronjob_manage`, `skill_manage` and every plugin and MCP
    /// tool were in the child registry and stayed in a flare's, so a read-only fan-out could
    /// schedule work and rewrite the skills directory.
    pub(crate) fn flare_registry(&self) -> ToolRegistry {
        self.tools.only(crate::flares::READ_TOOLS)
    }

    /// The route a child goes to when the call names none — a flare run needs the same answer a
    /// `delegate` call gets, so it asks here rather than resolving it a second way.
    pub(crate) fn default_route(&self) -> String {
        self.providers.default_route()
    }

    /// The next child's session id, for a caller that has to name it before the child starts.
    pub(crate) fn new_session_id(&self) -> String {
        self.store.new_id()
    }

    /// Run one child to its final answer, on `tools` rather than necessarily this tool's own
    /// registry (`#171`): a flare gets a registry with the write tools taken out.
    ///
    /// `delegate` and a flare run are the same engine with two callers — the child is an
    /// [`Agent`], it gets its own session, its own route, the same hooks and the same turn-results
    /// buffer, and only what it was told and what it may spend differ. Keeping that in one place
    /// is the whole reason a flare run is not a second runtime.
    pub(crate) async fn run_child(
        &self,
        tools: Arc<ToolRegistry>,
        job: ChildJob<'_>,
        approver: &dyn Approver,
        cancel: &crate::cancel::Cancel,
    ) -> ChildOutcome {
        let session_id = job.session_id.to_string();
        let mut outcome = ChildOutcome {
            route: job.route.to_string(),
            session_id: session_id.clone(),
            answer: Err("the subagent could not start".to_string()),
            prompt_tokens: None,
            completion_tokens: None,
            iterations: 0,
        };
        let route = match self.providers.provider(job.route) {
            Ok(route) => route,
            Err(reason) => {
                outcome.answer = Err(format!("the subagent could not start: {reason}"));
                return outcome;
            }
        };
        outcome.route = route.name.clone();
        let begun = match job.origin {
            ChildOrigin::Subagent { parent, route } => {
                self.store.begin_subagent(&session_id, parent, route)
            }
            ChildOrigin::Flare { run, n } => self.store.begin_flare(&session_id, run, n),
        };
        if let Err(e) = begun {
            outcome.answer = Err(format!("the subagent could not start: {e}"));
            return outcome;
        }

        let mut preamble = PREAMBLE.to_string();
        if let Some(extra) = job.system.filter(|s| !s.trim().is_empty()) {
            preamble.push_str("\n\n");
            preamble.push_str(extra.trim());
        }
        let child = Agent::new(
            route.provider,
            tools,
            self.store.clone(),
            preamble,
            job.budget,
        )
        .with_context_budget(route.context_budget_tokens)
        .with_max_malformed_calls(self.settings.max_malformed_calls)
        .with_tool_concurrency(self.settings.tool_concurrency)
        .with_lock_wait(self.settings.lock_wait)
        .with_hooks(self.hooks.clone())
        .with_turn_results(Arc::clone(&self.turn_results));

        let usage = Mutex::new(Usage::default());
        let marked = ChildApprover {
            inner: approver,
            route: &route.name,
        };
        // The parent's flag, not a fresh one: a cancelled run has to stop the work it started, and
        // a child agent keeps calling the model for minutes if nobody tells it.
        let run = child
            .run_cancellable(
                Some(&session_id),
                job.prompt,
                &marked,
                &|event| {
                    if let AgentEvent::TurnStats { usage: turn, .. } = event {
                        if let Ok(mut total) = usage.lock() {
                            total.add(&turn);
                        }
                    }
                },
                cancel,
            )
            .await;
        let usage = usage.into_inner().unwrap_or_default();
        outcome.prompt_tokens = usage.prompt;
        outcome.completion_tokens = usage.completion;
        outcome.iterations = usage.iterations;
        outcome.answer = match run {
            Ok(done) if !done.reply.trim().is_empty() => Ok(done.reply),
            Ok(_) => Err("it finished without any text to return".to_string()),
            Err(Error::MaxIterations(n)) => Err(format!(
                "it used all {n} of its iterations without a final answer; raise \
                 `max_iterations` or split the job"
            )),
            Err(e) => Err(e.to_string()),
        };
        outcome
    }
}

#[derive(Default)]
struct Usage {
    prompt: Option<u64>,
    completion: Option<u64>,
    iterations: usize,
}

impl Usage {
    fn add(&mut self, turn: &crate::usage::TurnUsage) {
        self.iterations += 1;
        self.prompt = sum([self.prompt, turn.prompt_tokens].into_iter());
        self.completion = sum([self.completion, turn.completion_tokens].into_iter());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Policy, ToolsConfig};
    use crate::message::Message;
    use crate::message::{FunctionCall, ToolCall};
    use crate::tools::{AllowAll, DenyAll, ToolSpec};
    use crate::usage::TurnUsage;

    /// Answers from a script and keeps what it was sent, and what tools it was offered.
    struct Recording {
        replies: Mutex<Vec<crate::error::Result<Message>>>,
        seen: Mutex<Vec<Vec<Message>>>,
        offered: Mutex<Vec<Vec<String>>>,
        usage: Mutex<Option<TurnUsage>>,
        reported: Option<(u64, u64)>,
    }

    impl Recording {
        fn new(
            mut replies: Vec<crate::error::Result<Message>>,
            reported: Option<(u64, u64)>,
        ) -> Arc<Self> {
            replies.reverse();
            Arc::new(Self {
                replies: Mutex::new(replies),
                seen: Mutex::default(),
                offered: Mutex::default(),
                usage: Mutex::default(),
                reported,
            })
        }
        fn texts(&self) -> Vec<String> {
            self.seen
                .lock()
                .unwrap()
                .iter()
                .flatten()
                .filter_map(|m| m.content.clone())
                .collect()
        }
    }

    #[async_trait]
    impl ChatProvider for Recording {
        async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> crate::Result<Message> {
            self.seen.lock().unwrap().push(messages.to_vec());
            self.offered
                .lock()
                .unwrap()
                .push(tools.iter().map(|t| t.function.name.clone()).collect());
            *self.usage.lock().unwrap() = self.reported.map(|(p, c)| TurnUsage {
                prompt_tokens: Some(p),
                completion_tokens: Some(c),
                ..TurnUsage::default()
            });
            self.replies
                .lock()
                .unwrap()
                .pop()
                .unwrap_or_else(|| Err(Error::Provider("script exhausted".into())))
        }
        fn take_usage(&self) -> Option<TurnUsage> {
            self.usage.lock().unwrap().take()
        }
    }

    struct Fixed {
        routes: Vec<(String, Arc<dyn ChatProvider>)>,
        default: String,
    }

    impl ChildProviders for Fixed {
        fn routes(&self) -> Vec<RouteInfo> {
            self.routes
                .iter()
                .map(|(n, _)| RouteInfo {
                    name: n.clone(),
                    model: format!("{n}-model"),
                    endpoint: String::new(),
                })
                .collect()
        }
        fn default_route(&self) -> String {
            self.default.clone()
        }
        fn provider(&self, route: &str) -> Result<ChildRoute, String> {
            let (name, provider) = self
                .routes
                .iter()
                .find(|(n, _)| n == route)
                .ok_or("no such route")?;
            Ok(ChildRoute {
                name: name.clone(),
                provider: provider.clone(),
                context_budget_tokens: 0,
            })
        }
    }

    fn tool_with(
        routes: Vec<(&str, Arc<Recording>)>,
        default: &str,
        dir: &std::path::Path,
    ) -> DelegateTool {
        let routes = routes
            .into_iter()
            .map(|(name, provider)| (name, provider as Arc<dyn ChatProvider>))
            .collect();
        tool_with_providers(routes, default, dir)
    }

    fn tool_with_providers(
        routes: Vec<(&str, Arc<dyn ChatProvider>)>,
        default: &str,
        dir: &std::path::Path,
    ) -> DelegateTool {
        let providers = Fixed {
            routes: routes
                .into_iter()
                .map(|(n, p)| (n.to_string(), p))
                .collect(),
            default: default.to_string(),
        };
        let tools = ToolRegistry::from_config(&ToolsConfig::default(), dir.to_path_buf());
        DelegateTool::new(
            Arc::new(providers),
            Arc::new(tools),
            SessionStore::new(dir.join("sessions")),
            DelegateSettings {
                max_output_bytes: 4096,
                max_malformed_calls: 3,
                tool_concurrency: 1,
                lock_wait: Duration::from_secs(1),
            },
        )
    }

    /// Runs `args` as the model of a parent run on session `parent` would.
    async fn call(
        tool: &DelegateTool,
        run: &crate::tools::RunScope,
        approver: &dyn Approver,
        args: Value,
    ) -> Result<String, ToolError> {
        // `delegate` reads the approver and the run, never the registry: the empty one here is
        // a placeholder for a tool that does not route.
        let registry = crate::tools::ToolRegistry::new(4096);
        tool.call_scoped(
            args,
            &CallScope {
                approver,
                run,
                registry: &registry,
                call_id: None,
            },
        )
        .await
    }

    fn assistant_calling(tool: &str, args: &str) -> Message {
        Message::assistant_tool_calls(
            None,
            vec![ToolCall {
                id: "c1".into(),
                kind: "function".into(),
                function: FunctionCall {
                    name: tool.into(),
                    arguments: args.into(),
                },
            }],
        )
    }

    #[tokio::test]
    async fn the_childs_final_text_is_the_tool_result_with_its_own_usage_line() {
        let dir = tempfile::tempdir().unwrap();
        let big = Recording::new(vec![Ok(Message::assistant("the answer"))], Some((120, 7)));
        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
        let run = crate::tools::RunScope::new("parent1");
        let out = call(&tool, &run, &DenyAll, json!({"prompt": "work it out"}))
            .await
            .unwrap();
        assert_eq!(
            out,
            "the answer\n\nchild usage: 120 prompt / 7 completion tokens, 1 iteration"
        );
        let children = run.children.runs();
        assert_eq!(children.len(), 1);
        assert_eq!(children[0].route, "big");
        assert_eq!(
            (children[0].prompt_tokens, children[0].completion_tokens),
            (Some(120), Some(7))
        );
        assert!(!children[0].failed);
        // The child's own session holds its prompt and its answer, and says whose it is.
        let child = tool.store.load(&children[0].session_id).unwrap();
        assert_eq!(child.len(), 2);
        assert_eq!(child[0].content.as_deref(), Some("work it out"));
        let listed = tool.store.list().unwrap();
        let info = listed
            .iter()
            .find(|s| s.id == children[0].session_id)
            .unwrap();
        let origin = info.subagent().unwrap();
        assert_eq!((origin.parent, origin.route), ("parent1", "big"));
    }

    /// A provider that answers nothing until the process ends: the child is inside a model call
    /// when the parent is cancelled, which is the case the flag has to reach.
    #[derive(Default)]
    struct Hanging {
        asked: Arc<tokio::sync::Notify>,
    }

    #[async_trait]
    impl ChatProvider for Hanging {
        async fn chat(&self, _messages: &[Message], _tools: &[ToolSpec]) -> crate::Result<Message> {
            // `notify_one`, not `notify_waiters`: a permit is then stored, so a watcher that
            // registers after the request was made still learns about it.
            self.asked.notify_one();
            tokio::time::sleep(Duration::from_secs(60)).await;
            Ok(Message::assistant("too late"))
        }
    }

    #[tokio::test]
    async fn a_cancelled_parent_stops_the_child_run() {
        let dir = tempfile::tempdir().unwrap();
        let slow = Arc::new(Hanging::default());
        let tool = tool_with_providers(
            vec![("slow", Arc::clone(&slow) as Arc<dyn ChatProvider>)],
            "slow",
            dir.path(),
        );
        let cancel = crate::cancel::Cancel::new();
        let run = crate::tools::RunScope::new("p").cancellable(&cancel);

        // The child must be inside its request before the flag is set, or this proves nothing: the
        // flag would be seen at the run's first checkpoint and no request would be made at all.
        let flag = cancel.clone();
        let notifier = Arc::clone(&slow);
        let canceller = tokio::spawn(async move {
            notifier.asked.notified().await;
            flag.cancel();
        });
        let started = std::time::Instant::now();
        let outcome = tokio::time::timeout(
            Duration::from_secs(10),
            call(&tool, &run, &DenyAll, json!({"prompt": "work it out"})),
        )
        .await
        .expect("the child stopped at the cancel, not at its own timeout");
        canceller.abort();
        assert!(
            started.elapsed() < Duration::from_secs(10),
            "the child kept working after the parent was cancelled"
        );
        // The failure is reported the way every child failure is, and it says which one.
        let err = outcome.expect_err("a cancelled child has no answer to give");
        assert!(
            err.to_string().contains("cancelled"),
            "the child's failure names the cancel: {err}"
        );
        // The child's session says it did not finish, so a later run resumes rather than trusts it.
        let children = run.children.runs();
        assert_eq!(children.len(), 1);
        assert!(children[0].failed);
    }

    #[tokio::test]
    async fn a_subagents_answer_arrives_as_a_tool_result_with_its_own_usage() {
        let dir = tempfile::tempdir().unwrap();
        let child = Recording::new(vec![Ok(Message::assistant("CHILD ANSWER"))], Some((120, 7)));
        let tool = tool_with(vec![("big", child.clone())], "big", dir.path());
        let mut registry = ToolRegistry::new(4096);
        registry.register(Arc::new(tool), Policy::Ask);
        let parent_provider = Recording::new(
            vec![
                Ok(assistant_calling(
                    "delegate",
                    r#"{"prompt":"find the thing","route":"big"}"#,
                )),
                Ok(Message::assistant("PARENT FINAL")),
            ],
            Some((1000, 50)),
        );
        let store = SessionStore::new(dir.path().join("sessions"));
        let agent = Agent::new(
            parent_provider.clone(),
            Arc::new(registry),
            store.clone(),
            "parent system".into(),
            5,
        );
        let events = Mutex::new(Vec::new());
        let run = agent
            .run(None, "PARENT USER PROMPT", &AllowAll, &|e| {
                events.lock().unwrap().push(e)
            })
            .await
            .unwrap();
        let events = events.into_inner().unwrap();

        // The child's final text is the tool result, with its usage beside it.
        let want = "CHILD ANSWER\n\nchild usage: 120 prompt / 7 completion tokens, 1 iteration";
        let result = events
            .iter()
            .find_map(|e| match e {
                AgentEvent::ToolResult {
                    name,
                    output,
                    is_error,
                    ..
                } if name == "delegate" => Some((output.clone(), *is_error)),
                _ => None,
            })
            .unwrap();
        assert_eq!(result, (want.to_string(), false));
        assert_eq!(run.reply, "PARENT FINAL");

        // The usage is separate: the parent's own requests add up to the parent's numbers,
        // and the child's 120/7 are in `children`, in neither of them.
        let parent_prompt: u64 = events
            .iter()
            .filter_map(|e| match e {
                AgentEvent::TurnStats { usage, .. } => usage.prompt_tokens,
                _ => None,
            })
            .sum();
        assert_eq!(parent_prompt, 2000);
        assert_eq!(run.children.len(), 1);
        assert_eq!(
            (
                run.children[0].route.as_str(),
                run.children[0].prompt_tokens,
                run.children[0].completion_tokens,
                run.children[0].iterations,
            ),
            ("big", Some(120), Some(7), 1)
        );

        // The parent's session holds the call and the answer, and nothing of the child.
        let parent = store.load(&run.session_id).unwrap();
        let roles: Vec<_> = parent.iter().map(|m| m.role).collect();
        assert_eq!(parent.len(), 4, "{roles:?}");
        let parent_text: String = parent
            .iter()
            .map(|m| m.content.clone().unwrap_or_default())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(parent_text.contains(want), "{parent_text}");
        assert!(!parent_text.contains("You are a subagent"), "{parent_text}");
        // ...and the child never saw the parent's conversation.
        assert!(!child.texts().iter().any(|t| t.contains("PARENT")));
        assert!(child.texts().iter().any(|t| t == "find the thing"));
        // The child's session is its own row, marked as a child of this one.
        let child_row = store
            .list()
            .unwrap()
            .into_iter()
            .find(|s| s.id == run.children[0].session_id)
            .unwrap();
        assert_ne!(child_row.id, run.session_id);
        assert_eq!(child_row.subagent().unwrap().parent, run.session_id);
    }

    /// A parent whose registry holds `tool`, asking `calls` of its own in the first turn.
    fn parent_calling(
        tool: DelegateTool,
        dir: &std::path::Path,
        calls: Vec<Message>,
        concurrency: usize,
    ) -> (Agent, Arc<Recording>) {
        let mut registry = ToolRegistry::new(4096);
        registry.register(Arc::new(tool), Policy::Ask);
        let mut replies = calls;
        replies.push(Message::assistant("PARENT FINAL"));
        let provider = Recording::new(replies.into_iter().map(Ok).collect(), None);
        let agent = Agent::new(
            provider.clone(),
            Arc::new(registry),
            SessionStore::new(dir.join("sessions")),
            "parent".into(),
            5,
        )
        .with_tool_concurrency(concurrency);
        (agent, provider)
    }

    #[tokio::test]
    async fn a_child_that_fails_is_a_tool_result_and_the_parent_run_carries_on() {
        let dir = tempfile::tempdir().unwrap();
        let broken = Recording::new(vec![Err(Error::Provider("HTTP 503".into()))], None);
        let tool = tool_with(vec![("big", broken)], "big", dir.path());
        let (agent, parent) = parent_calling(
            tool,
            dir.path(),
            vec![assistant_calling("delegate", r#"{"prompt":"x"}"#)],
            1,
        );
        let events = Mutex::new(Vec::new());
        let run = agent
            .run(None, "go", &AllowAll, &|e| events.lock().unwrap().push(e))
            .await
            .expect("the parent run does not fail with its child");
        assert_eq!(run.reply, "PARENT FINAL");
        let result = events
            .into_inner()
            .unwrap()
            .into_iter()
            .find_map(|e| match e {
                AgentEvent::ToolResult {
                    output, is_error, ..
                } => Some((output, is_error)),
                _ => None,
            })
            .unwrap();
        assert!(result.1, "a failed child is an error result");
        assert!(
            result.0.contains("failed") && result.0.contains("HTTP 503"),
            "{}",
            result.0
        );
        assert!(
            parent.texts().iter().any(|t| t.contains("HTTP 503")),
            "the model read the reason"
        );
        assert!(run.children[0].failed);
    }

    #[tokio::test]
    async fn a_parent_that_asks_for_more_children_than_the_cap_in_one_turn_gets_the_cap_not_a_fifth(
    ) {
        let dir = tempfile::tempdir().unwrap();
        let big = Recording::new(
            (0..MAX_CHILDREN_PER_RUN)
                .map(|_| Ok(Message::assistant("ok")))
                .collect(),
            None,
        );
        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
        let many = Message::assistant_tool_calls(
            None,
            (0..MAX_CHILDREN_PER_RUN + 1)
                .map(|i| ToolCall {
                    id: format!("c{i}"),
                    kind: "function".into(),
                    function: FunctionCall {
                        name: "delegate".into(),
                        arguments: r#"{"prompt":"x"}"#.into(),
                    },
                })
                .collect(),
        );
        // Concurrent calls must not get past the cap together.
        let (agent, _) = parent_calling(tool, dir.path(), vec![many], MAX_CHILDREN_PER_RUN + 1);
        let events = Mutex::new(Vec::new());
        let run = agent
            .run(None, "go", &AllowAll, &|e| events.lock().unwrap().push(e))
            .await
            .unwrap();
        let results: Vec<bool> = events
            .into_inner()
            .unwrap()
            .into_iter()
            .filter_map(|e| match e {
                AgentEvent::ToolResult { is_error, .. } => Some(is_error),
                _ => None,
            })
            .collect();
        assert_eq!(results.iter().filter(|e| **e).count(), 1, "{results:?}");
        assert_eq!(run.children.len(), MAX_CHILDREN_PER_RUN);
        assert_eq!(big.seen.lock().unwrap().len(), MAX_CHILDREN_PER_RUN);
    }

    #[tokio::test]
    async fn a_child_is_told_what_it_is_and_given_only_the_job_and_the_callers_instructions() {
        let dir = tempfile::tempdir().unwrap();
        let big = Recording::new(vec![Ok(Message::assistant("ok"))], None);
        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
        let run = crate::tools::RunScope::new("p");
        call(
            &tool,
            &run,
            &DenyAll,
            json!({"prompt": "JOB", "system": "ANSWER IN FRENCH"}),
        )
        .await
        .unwrap();
        let sent = big.seen.lock().unwrap()[0].clone();
        let system = sent[0].content.clone().unwrap();
        assert!(system.contains("You are a subagent"), "{system}");
        assert!(system.ends_with("ANSWER IN FRENCH"), "{system}");
        assert_eq!(
            sent.len(),
            2,
            "the preamble and the prompt, nothing of the parent"
        );
        assert_eq!(sent[1].content.as_deref(), Some("JOB"));
    }

    #[tokio::test]
    async fn a_child_that_reports_no_usage_says_so_instead_of_counting_zero() {
        let dir = tempfile::tempdir().unwrap();
        let big = Recording::new(vec![Ok(Message::assistant("ok"))], None);
        let tool = tool_with(vec![("big", big)], "big", dir.path());
        let out = call(
            &tool,
            &crate::tools::RunScope::new("p"),
            &DenyAll,
            json!({"prompt": "x"}),
        )
        .await
        .unwrap();
        assert!(
            out.ends_with("child usage: tokens not reported by the server, 1 iteration"),
            "{out}"
        );
    }

    #[tokio::test]
    async fn an_unknown_route_is_a_tool_error_listing_the_routes_that_exist() {
        let dir = tempfile::tempdir().unwrap();
        let tool = tool_with(
            vec![
                ("big", Recording::new(vec![], None)),
                ("local", Recording::new(vec![], None)),
            ],
            "big",
            dir.path(),
        );
        let run = crate::tools::RunScope::new("p");
        let e = call(
            &tool,
            &run,
            &DenyAll,
            json!({"prompt": "x", "route": "ghost"}),
        )
        .await
        .unwrap_err();
        assert!(matches!(e, ToolError::Failed(_)), "{e:?}");
        let text = e.to_string();
        assert!(
            text.contains("unknown route `ghost`") && text.contains("big, local"),
            "{text}"
        );
        assert!(
            run.children.runs().is_empty(),
            "a refused call spends no place"
        );
    }

    #[tokio::test]
    async fn the_n_plus_first_child_is_refused_with_a_reason_the_model_can_act_on() {
        let dir = tempfile::tempdir().unwrap();
        let replies = (0..MAX_CHILDREN_PER_RUN + 1)
            .map(|_| Ok(Message::assistant("ok")))
            .collect();
        let tool = tool_with(
            vec![("big", Recording::new(replies, None))],
            "big",
            dir.path(),
        );
        let run = crate::tools::RunScope::new("p");
        for _ in 0..MAX_CHILDREN_PER_RUN {
            call(&tool, &run, &DenyAll, json!({"prompt": "x"}))
                .await
                .unwrap();
        }
        let e = call(&tool, &run, &DenyAll, json!({"prompt": "x"}))
            .await
            .unwrap_err();
        let text = e.to_string();
        assert!(
            text.contains(&format!("already started {MAX_CHILDREN_PER_RUN} subagents"))
                && text.contains("yourself"),
            "{text}"
        );
        assert_eq!(run.children.runs().len(), MAX_CHILDREN_PER_RUN);
        // Another run has a cap of its own.
        call(
            &tool,
            &crate::tools::RunScope::new("other"),
            &DenyAll,
            json!({"prompt": "x"}),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn a_child_that_fails_comes_back_as_an_error_with_the_reason_and_its_cost() {
        let dir = tempfile::tempdir().unwrap();
        let big = Recording::new(
            vec![
                Ok(assistant_calling("read_file", r#"{"path":"nope"}"#)),
                Ok(assistant_calling("read_file", r#"{"path":"nope"}"#)),
            ],
            Some((10, 1)),
        );
        let tool = tool_with(vec![("big", big)], "big", dir.path());
        let run = crate::tools::RunScope::new("p");
        let e = call(
            &tool,
            &run,
            &DenyAll,
            json!({"prompt": "x", "max_iterations": 2}),
        )
        .await
        .unwrap_err();
        let text = e.to_string();
        assert!(
            text.contains("failed")
                && text.contains("used all 2 of its iterations")
                && text.ends_with("child usage: 20 prompt / 2 completion tokens, 2 iterations"),
            "{text}"
        );
        assert!(run.children.runs()[0].failed);

        let broken = Recording::new(vec![Err(Error::Provider("HTTP 500".into()))], None);
        let tool = tool_with(vec![("big", broken)], "big", dir.path());
        let e = call(
            &tool,
            &crate::tools::RunScope::new("p"),
            &DenyAll,
            json!({"prompt": "x"}),
        )
        .await
        .unwrap_err();
        assert!(e.to_string().contains("HTTP 500"), "{e}");
    }

    #[tokio::test]
    async fn a_child_is_offered_the_parents_tools_but_not_delegate() {
        let dir = tempfile::tempdir().unwrap();
        let big = Recording::new(vec![Ok(Message::assistant("ok"))], None);
        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
        call(
            &tool,
            &crate::tools::RunScope::new("p"),
            &DenyAll,
            json!({"prompt": "x"}),
        )
        .await
        .unwrap();
        let offered = big.offered.lock().unwrap()[0].clone();
        assert!(offered.contains(&"read_file".to_string()), "{offered:?}");
        assert!(!offered.contains(&"delegate".to_string()), "{offered:?}");
        assert!(!tool
            .tools
            .advertised_names()
            .contains(&"delegate".to_string()));
    }

    const FAKE_KEY: &str = "sk-proj-ZmFrZWtleWZvcnRlc3RzMDEyMzQ1Njc4OQ";

    /// A child that reads a file holding a key, run under `hooks`; returns what the child's
    /// model was sent on its second request and what its session stored.
    async fn child_reads_a_key(hooks: LoopHooks) -> (String, String, String) {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("env.txt"),
            format!("key = {FAKE_KEY}\nplain\n"),
        )
        .unwrap();
        let big = Recording::new(
            vec![
                Ok(assistant_calling("read_file", r#"{"path":"env.txt"}"#)),
                Ok(Message::assistant("read it")),
            ],
            None,
        );
        let tool = tool_with(vec![("big", big.clone())], "big", dir.path()).with_hooks(hooks);
        let run = crate::tools::RunScope::new("parent");
        call(&tool, &run, &DenyAll, json!({"prompt": "read env.txt"}))
            .await
            .unwrap();
        let sent = big.seen.lock().unwrap()[1]
            .iter()
            .filter_map(|m| m.content.clone())
            .collect::<Vec<_>>()
            .join("\n");
        let id = run.children.runs()[0].session_id.clone();
        let stored = tool
            .store
            .load(&id)
            .unwrap()
            .iter()
            .filter_map(|m| m.content.clone())
            .collect::<Vec<_>>()
            .join("\n");
        (sent, stored, id)
    }

    #[tokio::test]
    async fn a_childs_tool_output_is_redacted_when_the_parent_has_the_redact_hook() {
        // One hook named, so this proves the child inherited `redact-secrets` rather than
        // counting whatever the default order happens to be.
        let cfg = crate::config::Config::from_toml_str("[hooks]\norder = [\"redact-secrets\"]\n")
            .unwrap();
        let hooks = crate::hooks::from_config_reporting(
            &cfg,
            &crate::session::SessionStore::new(
                std::env::temp_dir().join(format!("eclipse-delegate-{}", std::process::id())),
            ),
            crate::hooks::Reporting::to(Arc::new(|_| {})),
        )
        .unwrap();
        assert_eq!(hooks.len(), 1);
        let (sent, stored, _) = child_reads_a_key(hooks).await;
        assert!(sent.contains("key = [redacted:api-key]"), "{sent}");
        assert!(!sent.contains(FAKE_KEY), "the child's model read the key");
        assert!(stored.contains("[redacted:api-key]"), "{stored}");
        assert!(
            !stored.contains(FAKE_KEY),
            "the child's session stored the key"
        );
    }

    #[tokio::test]
    async fn a_child_with_no_hooks_reads_the_file_as_it_is() {
        let (sent, stored, _) = child_reads_a_key(LoopHooks::default()).await;
        assert!(sent.contains(FAKE_KEY), "{sent}");
        assert!(stored.contains(FAKE_KEY), "{stored}");
    }

    #[derive(Default)]
    struct Recorder(Mutex<Vec<(String, String)>>);

    #[async_trait]
    impl Approver for Recorder {
        async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision {
            self.0
                .lock()
                .unwrap()
                .push((call.tool.clone(), call.summary.clone()));
            crate::approvals::Decision::Deny("no".to_string())
        }
    }

    #[tokio::test]
    async fn a_childs_own_approvals_reach_the_same_approver_marked_as_the_childs() {
        let dir = tempfile::tempdir().unwrap();
        let big = Recording::new(
            vec![
                // A command the shell is actually asked about: `echo hi` would simply run, and a
                // test that watched it reach the approver would be watching a prompt that no
                // longer exists.
                Ok(assistant_calling(
                    "shell",
                    r#"{"command":"rm -rf the-build"}"#,
                )),
                Ok(Message::assistant("it was declined")),
            ],
            None,
        );
        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
        let approver = Recorder::default();
        let out = call(
            &tool,
            &crate::tools::RunScope::new("p"),
            &approver,
            json!({"prompt": "x"}),
        )
        .await
        .unwrap();
        assert!(out.starts_with("it was declined"), "{out}");
        let asked = approver.0.lock().unwrap().clone();
        assert_eq!(asked.len(), 1, "{asked:?}");
        assert_eq!(asked[0].0, "shell");
        assert!(
            asked[0].1.starts_with("[subagent on big] "),
            "{}",
            asked[0].1
        );
        assert!(
            big.texts().iter().any(|t| t.contains("declined")),
            "the child read the refusal as a tool result"
        );
    }

    #[tokio::test]
    async fn wrong_typed_arguments_are_invalid_args_naming_the_key() {
        let dir = tempfile::tempdir().unwrap();
        let tool = tool_with(
            vec![("big", Recording::new(vec![], None))],
            "big",
            dir.path(),
        );
        let run = crate::tools::RunScope::new("p");
        for (args, key) in [
            (json!({}), "prompt"),
            (json!({"prompt": 3}), "prompt"),
            (json!({"prompt": "  "}), "prompt"),
            (json!({"prompt": "x", "route": 3}), "route"),
            (json!({"prompt": "x", "system": []}), "system"),
            (
                json!({"prompt": "x", "max_iterations": "8"}),
                "max_iterations",
            ),
            (
                json!({"prompt": "x", "max_iterations": 0}),
                "max_iterations",
            ),
            (
                json!({"prompt": "x", "max_iterations": 21}),
                "max_iterations",
            ),
            (
                json!({"prompt": "x", "max_iterations": 1.5}),
                "max_iterations",
            ),
        ] {
            let e = call(&tool, &run, &DenyAll, args.clone()).await.unwrap_err();
            assert!(
                matches!(e, ToolError::InvalidArgs(_)) && e.to_string().contains(key),
                "{args}: {e}"
            );
        }
        assert!(run.children.runs().is_empty());
    }

    #[test]
    fn the_approval_summary_names_the_route_the_first_line_and_the_budget() {
        let dir = tempfile::tempdir().unwrap();
        let tool = tool_with(
            vec![
                ("big", Recording::new(vec![], None)),
                ("local", Recording::new(vec![], None)),
            ],
            "big",
            dir.path(),
        );
        let s =
            tool.describe_call(&json!({"prompt": "Audit the parser\nthen the lexer\nand more"}));
        assert_eq!(
            s,
            "delegate to a subagent on route `big`: \"Audit the parser\" (+2 more lines) \
             (up to 6 iterations)"
        );
        let s = tool.describe_call(
            &json!({"prompt": "x", "route": "local", "max_iterations": 3, "system": "be brief"}),
        );
        assert!(
            s.contains("route `local`")
                && s.contains("up to 3 iterations, with its own system prompt"),
            "{s}"
        );
        // It runs before the arguments are checked, so a bad one must not break it.
        let s = tool.describe_call(&json!({"prompt": 3, "route": 4, "max_iterations": "x"}));
        assert!(
            s.contains("(invalid route)") && s.contains("(invalid)"),
            "{s}"
        );
        let long = "x".repeat(500);
        assert!(tool.describe_call(&json!({ "prompt": long })).len() < 260);
    }

    #[test]
    fn the_delegate_policy_defaults_to_ask() {
        assert_eq!(ToolsConfig::default().delegate, Policy::Ask);
    }

    #[test]
    fn the_description_lists_the_routes_and_says_which_is_the_default() {
        let dir = tempfile::tempdir().unwrap();
        let tool = tool_with(
            vec![
                ("big", Recording::new(vec![], None)),
                ("local", Recording::new(vec![], None)),
            ],
            "local",
            dir.path(),
        );
        let d = tool.description();
        assert!(
            d.contains("`big` (big-model)") && d.contains("Default: `local`"),
            "{d}"
        );
    }

    #[tokio::test]
    async fn an_answer_too_long_for_the_output_cap_is_cut_but_keeps_the_usage_line() {
        let dir = tempfile::tempdir().unwrap();
        let big = Recording::new(
            vec![Ok(Message::assistant("a".repeat(10_000)))],
            Some((5, 5)),
        );
        let tool = tool_with(vec![("big", big)], "big", dir.path());
        let out = call(
            &tool,
            &crate::tools::RunScope::new("p"),
            &AllowAll,
            json!({"prompt": "x"}),
        )
        .await
        .unwrap();
        assert!(out.len() <= 4096, "{}", out.len());
        assert!(out.contains("[output truncated]"));
        assert!(out.ends_with("child usage: 5 prompt / 5 completion tokens, 1 iteration"));
    }

    #[test]
    fn the_readout_sums_the_children_and_says_how_many_failed() {
        assert_eq!(describe_children(&[]), None);
        let run = |route: &str, p, c, i, failed| ChildRun {
            route: route.into(),
            session_id: "s".into(),
            prompt_tokens: p,
            completion_tokens: c,
            iterations: i,
            failed,
        };
        let one = describe_children(&[run("big", Some(100), Some(10), 2, false)]).unwrap();
        assert_eq!(
            one,
            "delegated: 1 subagent (big) \u{2014} child usage: 100 prompt / 10 completion tokens, 2 iterations"
        );
        let two = describe_children(&[
            run("big", Some(100), Some(10), 2, false),
            run("local", None, None, 1, true),
        ])
        .unwrap();
        assert_eq!(
            two,
            "delegated: 2 subagents (big, local; 1 failed) \u{2014} child usage: 100 prompt / 10 completion tokens, 3 iterations"
        );
        let none = describe_children(&[run("big", None, None, 1, false)]).unwrap();
        assert!(none.contains("tokens not reported by the server"), "{none}");
    }
}