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
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use futures::Stream;
use futures::StreamExt;
use tokio::sync::{mpsc, oneshot};
use tokio_stream::wrappers::ReceiverStream;
use tokio_util::sync::CancellationToken;
use tracing::{debug, info, warn};
use crate::approval::{ApprovalHandler, AutoApprove};
use crate::error::{AgentError, ProviderError};
use crate::executor::{
AllowAll, ConcurrencyConfig, ToolCall, ToolConcurrency, ToolExecutor, ToolPolicy, ToolRegistry,
};
use crate::guard::{AgentSnapshot, GuardEval, GuardTrigger};
use crate::message::{CacheControl, Content, Message, Role, StopReason, Usage};
use crate::provider::{LlmProvider, Request, SystemBlock, ThinkingConfig, ToolDefinition};
use crate::steering::{self, ActiveTurn, AgentControl, SteerCommand, TurnId};
use crate::stream::StreamEvent;
use crate::tool::{Tool, ToolContext};
use crate::user_input::UserInputBridge;
/// Fallback `stop_reason` for partial results returned before any turn
/// has completed (e.g. provider failure on turn 0). Documented as
/// "no successful turn yet" — callers can disambiguate using the
/// outer `AgentError` variant. `EndTurn` is the least-misleading
/// concrete StopReason for the empty-history case.
const FALLBACK_STOP_REASON: StopReason = StopReason::EndTurn;
/// Result of an agent run.
///
/// The agent is stateless: it does **not** retain conversation history
/// between calls. Callers pass in the full history each time and receive
/// back only the **delta** of new messages the agent appended during this
/// run (assistant responses + tool-result user messages).
///
/// Typical consumer pattern:
///
/// ```ignore
/// let mut history = load_session();
/// history.push(Message::user_text(input));
/// let result = agent.run(history.clone(), cancel).await?;
/// history.extend(result.new_messages);
/// save_session(&history);
/// ```
#[derive(Debug, thiserror::Error)]
pub enum BuildError {
#[error(
"duplicate tool name '{name}' (registered {count} times); each tool must have a unique name"
)]
DuplicateToolName { name: String, count: usize },
}
/// Type alias for the per-event trace hook used by `stream_with_trace_hook`
/// and the SubAgent execute path.
pub(crate) type TraceHook = Arc<dyn Fn(&StreamEvent) + Send + Sync>;
#[derive(Debug, Clone)]
pub struct AgentResult {
/// Messages appended by this run only — **not** the full history.
pub new_messages: Vec<Message>,
/// Final assistant text output.
pub text: String,
/// Aggregated token usage across all turns in this run.
pub usage: Usage,
/// Stop reason from the last provider response, or `Cancelled` if the
/// caller's `CancellationToken` fired.
pub stop_reason: StopReason,
}
/// The core agent runtime.
///
/// Runs an LLM-driven tool loop: sends messages to the LLM, executes any
/// requested tools via the [`ToolExecutor`], feeds results back, and
/// repeats until the LLM produces a final text response, max turns are
/// reached, or the caller cancels.
///
/// `Clone` is shallow (Arcs and small primitives) — cheap; used by
/// [`Agent::stream`] to move a copy into the background task.
#[derive(Clone)]
pub struct Agent {
provider: Arc<dyn LlmProvider>,
model: String,
system: Option<Vec<SystemBlock>>,
executor: Arc<ToolExecutor>,
max_turns: usize,
max_tokens: u32,
temperature: Option<f32>,
working_dir: PathBuf,
max_depth: usize,
depth: usize,
/// When `Some`, the last `ToolDefinition` sent to the provider has
/// its `cache_control` set, terminating a cached prefix segment
/// over the entire toolset. Anthropic-only optimization;
/// non-Anthropic providers ignore the field.
cache_tools: Option<CacheControl>,
thinking: Option<ThinkingConfig>,
tool_definition_filter: Option<HashSet<String>>,
user_input_bridge: Option<Arc<dyn UserInputBridge>>,
}
impl Agent {
pub fn builder() -> AgentBuilder {
AgentBuilder::new()
}
/// Borrow the tool executor this agent was built with. Exposed so that
/// sub-agents can share the parent's registry + policy without having
/// to reconstruct them.
pub fn executor(&self) -> &Arc<ToolExecutor> {
&self.executor
}
/// Tool definitions sent to the LLM, sorted by name for deterministic
/// ordering (so prompt-cache hashes stay stable across turns).
///
/// When `cache_tools` is set, `cache_control` is placed on the last
/// (alphabetically-final) tool definition, caching the entire
/// toolset as one segment.
fn tool_definitions(&self) -> Vec<ToolDefinition> {
let mut defs: Vec<ToolDefinition> = self
.executor
.registry()
.iter()
.filter(|t| {
self.tool_definition_filter
.as_ref()
.is_none_or(|allowed| allowed.contains(t.name()))
})
.map(|t| ToolDefinition {
name: t.name().to_string(),
description: t.description().to_string(),
input_schema: t.input_schema(),
cache_control: None,
})
.collect();
defs.sort_by(|a, b| a.name.cmp(&b.name));
if let Some(cc) = &self.cache_tools {
if let Some(last) = defs.last_mut() {
last.cache_control = Some(cc.clone());
}
}
defs
}
fn make_context(&self, cancel: CancellationToken) -> ToolContext {
ToolContext {
working_dir: self.working_dir.clone(),
cancel,
depth: self.depth,
max_depth: self.max_depth,
executor: Arc::clone(&self.executor),
}
}
/// Run the agent loop against the given message history.
///
/// The agent is **stateless**: this method does not mutate `self` and
/// the caller owns the conversation. `messages` is the full history
/// (typically the prior session plus the new user message). The
/// returned [`AgentResult::new_messages`] is the delta — the caller
/// should extend their history with it to persist progress.
///
/// `cancel` is a cooperative cancellation signal. The loop checks it
/// between turns and after each tool batch, returning
/// [`AgentError::Cancelled`] promptly. Tools receive the same token
/// via [`ToolContext::cancel`] and are expected to honour it for any
/// long-running work.
///
/// On any error, the [`AgentError::partial`] accessor returns the
/// progress accumulated up to the failure point, so the caller can
/// still persist what succeeded.
pub async fn run(
&self,
messages: Vec<Message>,
cancel: CancellationToken,
) -> Result<AgentResult, AgentError> {
let (future, _handle) = self.run_with_handle(messages, cancel);
future.await
}
pub fn run_with_handle(
&self,
messages: Vec<Message>,
cancel: CancellationToken,
) -> (
impl Future<Output = Result<AgentResult, AgentError>> + Send + 'static,
crate::AgentHandle,
) {
let agent = self.clone();
let (control, handle) = steering::control_pair(
cancel.clone(),
agent.depth == 0,
agent.user_input_bridge.clone(),
);
let future = async move { agent.run_loop(messages, cancel, control).await };
(future, handle)
}
async fn run_loop(
self,
messages: Vec<Message>,
cancel: CancellationToken,
mut control: AgentControl,
) -> Result<AgentResult, AgentError> {
let mut history = messages;
let mut new_messages: Vec<Message> = Vec::new();
let mut total_usage = Usage::default();
let mut last_recent_tool_calls: Vec<String> = Vec::new();
// None until the first provider response lands. Using Option here
// (rather than seeding with `EndTurn`) avoids a misleading
// `partial.stop_reason: EndTurn` on first-turn provider failures.
let mut last_stop: Option<StopReason> = None;
let tool_defs = self.tool_definitions();
for turn in 0..self.max_turns {
let (turn_id, turn_cancel, _mode_event) = begin_turn(&control, turn, &cancel);
let _turn_cleanup = ActiveTurnCleanup(Arc::clone(&control.handle_inner));
let ctx = self.make_context(turn_cancel);
info!(turn, %turn_id, "agent turn");
if cancel.is_cancelled() {
return Err(AgentError::Cancelled {
partial: build_partial(&new_messages, &total_usage, StopReason::Cancelled, ""),
});
}
let (system, _policy_event) = system_for_turn(
&self.system,
&control,
turn,
&new_messages,
&last_recent_tool_calls,
&turn_id,
);
let request = Request {
model: self.model.clone(),
system,
messages: history.clone(),
tools: tool_defs.clone(),
max_tokens: self.max_tokens,
temperature: self.temperature,
thinking: self.thinking.clone(),
};
let response = match tokio::select! {
biased;
_ = ctx.cancel.cancelled() => {
return Err(AgentError::Cancelled {
partial: build_partial(&new_messages, &total_usage, StopReason::Cancelled, ""),
});
}
response = self.provider.complete(request) => response
} {
Ok(r) => r,
Err(source) => {
return Err(AgentError::Provider {
source,
partial: build_partial(
&new_messages,
&total_usage,
last_stop.unwrap_or(FALLBACK_STOP_REASON),
"",
),
});
}
};
total_usage.add(&response.usage);
last_stop = Some(response.stop_reason);
let assistant_msg = Message::assistant(response.content.clone());
history.push(assistant_msg.clone());
new_messages.push(assistant_msg);
let tool_calls: Vec<ToolCall> = response
.content
.iter()
.filter_map(|c| match c {
Content::ToolUse { id, name, input } => Some(ToolCall {
id: id.clone(),
name: name.clone(),
input: input.clone(),
}),
_ => None,
})
.collect();
if tool_calls.is_empty() || response.stop_reason == StopReason::EndTurn {
last_recent_tool_calls.clear();
let before_drain = new_messages.len();
drain_queued_user_messages(&mut control, &turn_id, &mut history, &mut new_messages);
if new_messages.len() > before_drain {
continue;
}
match inject_continuation_if_needed(
&control,
turn + 1,
&[GuardTrigger::OnTurnEnd, GuardTrigger::OnSessionStop],
&[],
&mut history,
&mut new_messages,
) {
InjectOutcome::Continue(_) => continue,
InjectOutcome::Abort(_) | InjectOutcome::None => {}
}
let text = extract_text(&response.content);
info!(turn, "agent finished");
// Safe to unwrap: we just assigned `Some` above when this
// response was decoded.
clear_active_turn(&control);
return Ok(AgentResult {
new_messages,
text,
usage: total_usage,
stop_reason: last_stop.unwrap_or(FALLBACK_STOP_REASON),
});
}
// Cancellation can fire while `provider.complete` is in flight
// (a multi-second LLM call). The pre-turn check at the top of
// the loop misses this window. Bail out before invoking any
// tools so a cancelled run never starts new mutating work.
if cancel.is_cancelled() {
return Err(AgentError::Cancelled {
partial: build_partial(&new_messages, &total_usage, StopReason::Cancelled, ""),
});
}
let recent_tool_calls = describe_tool_calls(&tool_calls);
last_recent_tool_calls = recent_tool_calls.clone();
debug!(count = tool_calls.len(), "executing tool batch");
let results = self
.executor
.execute_batch_with_tracker(
tool_calls,
&ctx,
Some(control.handle_inner.tool_runs.clone()),
Some(current_mode(&control)),
)
.await;
let user_msg = Message::user(results);
history.push(user_msg.clone());
new_messages.push(user_msg);
drain_queued_user_messages(&mut control, &turn_id, &mut history, &mut new_messages);
match inject_continuation_if_needed(
&control,
turn + 1,
&[GuardTrigger::OnTurnEnd],
&recent_tool_calls,
&mut history,
&mut new_messages,
) {
InjectOutcome::Continue(_) => continue,
InjectOutcome::Abort(_) => {
clear_active_turn(&control);
return Ok(AgentResult {
new_messages,
text: String::new(),
usage: total_usage,
stop_reason: last_stop.unwrap_or(FALLBACK_STOP_REASON),
});
}
InjectOutcome::None => {}
}
// If turn/session cancel fired while tools were running, skip the
// next provider round-trip — cooperative tools have already
// returned Cancelled error results.
if ctx.cancel.is_cancelled() || cancel.is_cancelled() {
return Err(AgentError::Cancelled {
partial: build_partial(&new_messages, &total_usage, StopReason::Cancelled, ""),
});
}
}
clear_active_turn(&control);
Err(AgentError::MaxTurnsReached {
turns: self.max_turns,
partial: build_partial(
&new_messages,
&total_usage,
last_stop.unwrap_or(FALLBACK_STOP_REASON),
"",
),
})
}
/// Run the agent loop in streaming mode.
///
/// Returns immediately with an [`AgentStream`] handle. A background
/// task is spawned (under the current Tokio runtime) that drives the
/// loop, calling `provider.stream()` on each turn. As the model
/// produces text, [`StreamEvent::ContentDelta`] arrives through the
/// stream live; [`StreamEvent::ToolUse`] arrives atomically when the
/// model finishes a tool block. Provider-internal events
/// (`MessageDelta`, `Usage`, per-turn `Done`) are absorbed —
/// consumers see only what they can render to the user.
///
/// History accumulation happens silently: text deltas are joined
/// into `Content::Text` blocks and finalized thinking blocks are
/// preserved separately, in provider order, before being added to
/// `new_messages`, so the next turn's request to the provider sees
/// a clean conversation history.
///
/// Call [`AgentStream::into_result`] (or `.collect_result()`) after
/// the stream ends to receive the final [`AgentResult`] with
/// `new_messages`, `text`, `usage`, and `stop_reason` — exactly the
/// shape `run()` returns. Backpressure is provided by a bounded
/// `mpsc(16)` channel: a slow consumer parks the producer task,
/// which transitively parks the SSE reader, which lets the OS
/// shrink the TCP receive window, all the way back to the LLM
/// server.
pub fn stream(&self, messages: Vec<Message>, cancel: CancellationToken) -> AgentStream {
let (stream, _handle) = self.stream_with_handle(messages, cancel);
stream
}
pub fn stream_with_handle(
&self,
messages: Vec<Message>,
cancel: CancellationToken,
) -> (AgentStream, crate::AgentHandle) {
self.stream_internal(messages, cancel, None)
}
/// Streaming variant that also fires `trace_hook` for **every**
/// `StreamEvent` observed by the loop — including
/// `MessageDelta`, `Usage`, `Done`, and the agent-emitted
/// `ToolCallPending`. The public stream channel keeps its
/// existing contract (Done is the terminal marker on that channel
/// and is NOT forwarded). Used by [`crate::tools::SubAgent`] when
/// `trace_hook` is set so per-turn observability is lossless
/// without changing public stream semantics.
pub(crate) fn stream_with_trace_hook(
&self,
messages: Vec<Message>,
cancel: CancellationToken,
hook: TraceHook,
) -> AgentStream {
let (stream, _handle) = self.stream_internal(messages, cancel, Some(hook));
stream
}
fn stream_internal(
&self,
messages: Vec<Message>,
cancel: CancellationToken,
trace_hook: Option<TraceHook>,
) -> (AgentStream, crate::AgentHandle) {
let agent = self.clone();
let (control, handle) = steering::control_pair(
cancel.clone(),
agent.depth == 0,
agent.user_input_bridge.clone(),
);
let (events_tx, events_rx) = mpsc::channel::<Result<StreamEvent, ProviderError>>(16);
let (result_tx, result_rx) = oneshot::channel();
tokio::spawn(async move {
let result = agent
.run_streaming_loop(messages, cancel, control, events_tx, trace_hook)
.await;
// If the consumer dropped before we finished, sending the
// result is a no-op; that's fine.
let _ = result_tx.send(result);
});
(
AgentStream {
events_rx: ReceiverStream::new(events_rx),
result_rx: Some(result_rx),
},
handle,
)
}
/// Body of the streaming loop. Owns the task locally so the public
/// API surface stays small. Mirrors `run()` structurally — same
/// turn counter, same cancel checkpoints, same history shape — but
/// the per-turn provider call yields a stream rather than a
/// buffered Response.
async fn run_streaming_loop(
self,
messages: Vec<Message>,
cancel: CancellationToken,
mut control: AgentControl,
events_tx: mpsc::Sender<Result<StreamEvent, ProviderError>>,
trace_hook: Option<TraceHook>,
) -> Result<AgentResult, AgentError> {
let mut history = messages;
let mut new_messages: Vec<Message> = Vec::new();
let mut total_usage = Usage::default();
let mut last_recent_tool_calls: Vec<String> = Vec::new();
let mut last_stop: Option<StopReason> = None;
let tool_defs = self.tool_definitions();
for turn in 0..self.max_turns {
let (turn_id, turn_cancel, mode_event) = begin_turn(&control, turn, &cancel);
let _turn_cleanup = ActiveTurnCleanup(Arc::clone(&control.handle_inner));
let ctx = self.make_context(turn_cancel);
info!(turn, %turn_id, "agent stream turn");
let turn_event = StreamEvent::TurnStarted {
turn_id: turn_id.clone(),
};
if let Some(hook) = &trace_hook {
emit_trace(hook, &turn_event);
}
if events_tx.send(Ok(turn_event)).await.is_err() {
return Err(AgentError::Cancelled {
partial: build_partial(&new_messages, &total_usage, StopReason::Cancelled, ""),
});
}
emit_drained_mode_events(
&control,
&events_tx,
&trace_hook,
&new_messages,
&total_usage,
"",
)
.await?;
if let Some(event) = mode_event {
if let Some(hook) = &trace_hook {
emit_trace(hook, &event);
}
if events_tx.send(Ok(event)).await.is_err() {
return Err(AgentError::Cancelled {
partial: build_partial(
&new_messages,
&total_usage,
StopReason::Cancelled,
"",
),
});
}
}
if cancel.is_cancelled() {
return Err(AgentError::Cancelled {
partial: build_partial(&new_messages, &total_usage, StopReason::Cancelled, ""),
});
}
let (system, policy_event) = system_for_turn(
&self.system,
&control,
turn,
&new_messages,
&last_recent_tool_calls,
&turn_id,
);
emit_policy_event(
policy_event,
&events_tx,
&trace_hook,
&new_messages,
&total_usage,
)
.await?;
let request = Request {
model: self.model.clone(),
system,
messages: history.clone(),
tools: tool_defs.clone(),
max_tokens: self.max_tokens,
temperature: self.temperature,
thinking: self.thinking.clone(),
};
let mut provider_stream = match tokio::select! {
biased;
_ = ctx.cancel.cancelled() => {
return Err(AgentError::Cancelled {
partial: build_partial(&new_messages, &total_usage, StopReason::Cancelled, ""),
});
}
stream = self.provider.stream(request) => stream
} {
Ok(s) => s,
Err(source) => {
return Err(AgentError::Provider {
source,
partial: build_partial(
&new_messages,
&total_usage,
last_stop.unwrap_or(FALLBACK_STOP_REASON),
"",
),
});
}
};
// Per-turn accumulators. Visible text is tracked both as
// `turn_text` for AgentResult.text and as ordered Text blocks
// inside assistant_content. Thinking blocks are finalized by
// provider events so signatures / replay metadata survive.
let mut turn_text = String::new();
let mut current_text_buf = String::new();
let mut assistant_content: Vec<Content> = Vec::new();
let mut tool_uses: Vec<ToolCall> = Vec::new();
let mut turn_stop: Option<StopReason> = None;
let mut turn_usage = Usage::default();
// Inner SSE loop. We cannot use `while let Some(event) =
// provider_stream.next().await` here because that blocks
// until the next SSE chunk arrives and gives the cancel
// token no chance to interrupt — a long generation would
// run to completion ignoring `cancel.cancel()`. Instead
// race each pull against the cancel future so external
// cancellation aborts immediately, dropping
// `provider_stream` (which closes the reqwest socket on
// drop, terminating the SSE upstream).
loop {
let event = tokio::select! {
biased;
_ = ctx.cancel.cancelled() => {
return Err(AgentError::Cancelled {
partial: build_partial(
&new_messages,
&total_usage,
StopReason::Cancelled,
&turn_text,
),
});
}
next = provider_stream.next() => match next {
Some(e) => e,
None => break,
},
};
let ev = match event {
Ok(ev) => ev,
Err(source) => {
return Err(AgentError::Provider {
source,
partial: build_partial(
&new_messages,
&total_usage,
last_stop.unwrap_or(FALLBACK_STOP_REASON),
&turn_text,
),
});
}
};
match ev {
StreamEvent::ContentDelta(delta) => {
turn_text.push_str(&delta);
current_text_buf.push_str(&delta);
let ev = StreamEvent::ContentDelta(delta);
if let Some(hook) = &trace_hook {
emit_trace(hook, &ev);
}
if events_tx.send(Ok(ev)).await.is_err() {
// Consumer hung up — abort like a cancel.
return Err(AgentError::Cancelled {
partial: build_partial(
&new_messages,
&total_usage,
StopReason::Cancelled,
&turn_text,
),
});
}
}
StreamEvent::ThinkingDelta { text } => {
let ev = StreamEvent::ThinkingDelta { text };
if let Some(hook) = &trace_hook {
emit_trace(hook, &ev);
}
if events_tx.send(Ok(ev)).await.is_err() {
return Err(AgentError::Cancelled {
partial: build_partial(
&new_messages,
&total_usage,
StopReason::Cancelled,
&turn_text,
),
});
}
}
StreamEvent::ThinkingBlock {
text,
provider,
metadata,
} => {
if !current_text_buf.is_empty() {
assistant_content
.push(Content::text(std::mem::take(&mut current_text_buf)));
}
assistant_content.push(Content::Thinking {
text: text.clone(),
provider,
metadata: metadata.clone(),
});
let ev = StreamEvent::ThinkingBlock {
text,
provider,
metadata,
};
if let Some(hook) = &trace_hook {
emit_trace(hook, &ev);
}
if events_tx.send(Ok(ev)).await.is_err() {
return Err(AgentError::Cancelled {
partial: build_partial(
&new_messages,
&total_usage,
StopReason::Cancelled,
&turn_text,
),
});
}
}
StreamEvent::ToolUse { id, name, input } => {
if !current_text_buf.is_empty() {
assistant_content
.push(Content::text(std::mem::take(&mut current_text_buf)));
}
let call = ToolCall {
id: id.clone(),
name: name.clone(),
input: input.clone(),
};
tool_uses.push(call);
assistant_content.push(Content::ToolUse {
id: id.clone(),
name: name.clone(),
input: input.clone(),
});
let ev = StreamEvent::ToolUse { id, name, input };
if let Some(hook) = &trace_hook {
emit_trace(hook, &ev);
}
if events_tx.send(Ok(ev)).await.is_err() {
return Err(AgentError::Cancelled {
partial: build_partial(
&new_messages,
&total_usage,
StopReason::Cancelled,
&turn_text,
),
});
}
}
StreamEvent::MessageDelta { stop_reason } => {
// Forwarded only to the optional `trace_hook`
// below; intentionally NOT forwarded on the
// public `Agent::stream` channel because Done
// (the event right after) is documented as the
// terminal marker and consumers break on it.
if let Some(hook) = &trace_hook {
emit_trace(hook, &StreamEvent::MessageDelta { stop_reason });
}
turn_stop = Some(stop_reason);
}
StreamEvent::Usage(u) => {
// Anthropic emits two Usage events (start with
// input_tokens + cache fields, end with
// output_tokens). The provider re-stamps cache
// fields onto every emission so merge_max here
// keeps the correct values across both events.
if let Some(hook) = &trace_hook {
emit_trace(hook, &StreamEvent::Usage(u.clone()));
}
turn_usage.merge_max(&u);
}
StreamEvent::Done => {
// Per-turn provider boundary, fired into the
// trace_hook for full child observability per
// issue #40 P6, but absorbed by the public
// stream so `Done` keeps its documented
// "stream terminated" terminal contract.
if let Some(hook) = &trace_hook {
emit_trace(hook, &StreamEvent::Done);
}
break;
}
// Agent-emitted events should never arrive from a
// provider's stream. Ignore defensively if a buggy
// provider injects one.
StreamEvent::TurnStarted { .. }
| StreamEvent::ModeChanged { .. }
| StreamEvent::ModeChangeRequested { .. }
| StreamEvent::ContinuationInjected { .. }
| StreamEvent::GuardAborted { .. }
| StreamEvent::PolicyInstalled { .. }
| StreamEvent::PolicyRemoved { .. }
| StreamEvent::PolicyApplied { .. }
| StreamEvent::ToolCallPending { .. } => {}
}
}
if !current_text_buf.is_empty() {
assistant_content.push(Content::text(current_text_buf));
}
// Drop provider_stream to free the underlying HTTP
// connection before the next turn opens a new one.
drop(provider_stream);
total_usage.add(&turn_usage);
let resolved_stop = turn_stop.unwrap_or(StopReason::EndTurn);
last_stop = Some(resolved_stop);
let assistant_msg = Message::assistant(assistant_content);
history.push(assistant_msg.clone());
new_messages.push(assistant_msg);
if tool_uses.is_empty() || resolved_stop == StopReason::EndTurn {
last_recent_tool_calls.clear();
let before_drain = new_messages.len();
drain_queued_user_messages(&mut control, &turn_id, &mut history, &mut new_messages);
if new_messages.len() > before_drain {
continue;
}
match inject_continuation_if_needed(
&control,
turn + 1,
&[GuardTrigger::OnTurnEnd, GuardTrigger::OnSessionStop],
&[],
&mut history,
&mut new_messages,
) {
InjectOutcome::Continue(event) => {
if let Some(hook) = &trace_hook {
emit_trace(hook, &event);
}
if events_tx.send(Ok(event)).await.is_err() {
return Err(AgentError::Cancelled {
partial: build_partial(
&new_messages,
&total_usage,
StopReason::Cancelled,
&turn_text,
),
});
}
continue;
}
InjectOutcome::Abort(event) => {
if let Some(hook) = &trace_hook {
emit_trace(hook, &event);
}
if events_tx.send(Ok(event)).await.is_err() {
return Err(AgentError::Cancelled {
partial: build_partial(
&new_messages,
&total_usage,
StopReason::Cancelled,
&turn_text,
),
});
}
}
InjectOutcome::None => {}
}
emit_drained_mode_events(
&control,
&events_tx,
&trace_hook,
&new_messages,
&total_usage,
&turn_text,
)
.await?;
info!(turn, "agent stream finished");
clear_active_turn(&control);
return Ok(AgentResult {
new_messages,
text: turn_text,
usage: total_usage,
stop_reason: resolved_stop,
});
}
// Same cancel guard as run(): the provider stream may have
// taken seconds to drain; bail before tool dispatch if the
// caller cancelled meanwhile.
if cancel.is_cancelled() {
return Err(AgentError::Cancelled {
partial: build_partial(&new_messages, &total_usage, StopReason::Cancelled, ""),
});
}
debug!(count = tool_uses.len(), "executing tool batch (stream)");
let calls = tool_uses;
let recent_tool_calls = describe_tool_calls(&calls);
last_recent_tool_calls = recent_tool_calls.clone();
// Emit one `ToolCallPending` per call before invoking the
// executor. The consumer's UI uses this to render an
// "approval pending" prompt while the executor's
// `ApprovalHandler::approve` blocks on user input.
// Class is resolved through the registry; a missing tool
// (LLM hallucinated a name) falls back to Mutating —
// safer default for unknown tools.
for call in &calls {
let class = self
.executor
.registry()
.get(&call.name)
.map(|t| t.class())
.unwrap_or(crate::tool::ToolClass::Mutating);
let event = StreamEvent::ToolCallPending {
id: call.id.clone(),
name: call.name.clone(),
input: call.input.clone(),
class,
};
if let Some(hook) = &trace_hook {
emit_trace(hook, &event);
}
if events_tx.send(Ok(event)).await.is_err() {
return Err(AgentError::Cancelled {
partial: build_partial(
&new_messages,
&total_usage,
StopReason::Cancelled,
&turn_text,
),
});
}
}
let results = self
.executor
.execute_batch_with_tracker(
calls,
&ctx,
Some(control.handle_inner.tool_runs.clone()),
Some(current_mode(&control)),
)
.await;
let user_msg = Message::user(results);
history.push(user_msg.clone());
new_messages.push(user_msg);
drain_queued_user_messages(&mut control, &turn_id, &mut history, &mut new_messages);
match inject_continuation_if_needed(
&control,
turn + 1,
&[GuardTrigger::OnTurnEnd],
&recent_tool_calls,
&mut history,
&mut new_messages,
) {
InjectOutcome::Continue(event) => {
if let Some(hook) = &trace_hook {
emit_trace(hook, &event);
}
if events_tx.send(Ok(event)).await.is_err() {
return Err(AgentError::Cancelled {
partial: build_partial(
&new_messages,
&total_usage,
StopReason::Cancelled,
"",
),
});
}
}
InjectOutcome::Abort(event) => {
if let Some(hook) = &trace_hook {
emit_trace(hook, &event);
}
if events_tx.send(Ok(event)).await.is_err() {
return Err(AgentError::Cancelled {
partial: build_partial(
&new_messages,
&total_usage,
StopReason::Cancelled,
"",
),
});
}
emit_drained_mode_events(
&control,
&events_tx,
&trace_hook,
&new_messages,
&total_usage,
"",
)
.await?;
clear_active_turn(&control);
return Ok(AgentResult {
new_messages,
text: turn_text,
usage: total_usage,
stop_reason: last_stop.unwrap_or(FALLBACK_STOP_REASON),
});
}
InjectOutcome::None => {}
}
if ctx.cancel.is_cancelled() || cancel.is_cancelled() {
return Err(AgentError::Cancelled {
partial: build_partial(&new_messages, &total_usage, StopReason::Cancelled, ""),
});
}
}
emit_drained_mode_events(
&control,
&events_tx,
&trace_hook,
&new_messages,
&total_usage,
"",
)
.await?;
clear_active_turn(&control);
warn!(turns = self.max_turns, "agent stream max turns");
Err(AgentError::MaxTurnsReached {
turns: self.max_turns,
partial: build_partial(
&new_messages,
&total_usage,
last_stop.unwrap_or(FALLBACK_STOP_REASON),
"",
),
})
}
}
fn begin_turn(
control: &AgentControl,
turn: usize,
cancel: &CancellationToken,
) -> (TurnId, CancellationToken, Option<StreamEvent>) {
let turn_id = TurnId::new();
let turn_cancel = cancel.child_token();
*control
.handle_inner
.active_turn
.write()
.expect("agent handle turn lock poisoned") = Some(ActiveTurn {
id: turn_id.clone(),
cancel: turn_cancel.clone(),
accepting_steer: true,
});
let mode_event = apply_pending_mode(control, &turn_id);
debug!(turn, %turn_id, "active turn set");
(turn_id, turn_cancel, mode_event)
}
fn system_for_turn(
base: &Option<Vec<SystemBlock>>,
control: &AgentControl,
turn_count: usize,
new_messages: &[Message],
recent_tool_calls: &[String],
turn_id: &TurnId,
) -> (Option<Vec<SystemBlock>>, Option<StreamEvent>) {
let mut system = base.clone().unwrap_or_default();
let addendum = current_mode(control).system_prompt_addendum();
if !addendum.is_empty() {
system.push(SystemBlock::text(addendum.into_owned()));
}
let snapshot = AgentSnapshot {
turn_count,
last_assistant_message: new_messages
.iter()
.rev()
.find(|message| message.role == Role::Assistant)
.cloned(),
recent_tool_calls: recent_tool_calls.to_vec(),
};
let candidates = control
.handle_inner
.prompt_policies
.read()
.expect("prompt policy lock poisoned")
.candidates();
let matched_ids: Vec<_> = candidates
.iter()
.filter(|candidate| candidate.matches(&snapshot))
.map(|candidate| candidate.id())
.collect();
let applied = control
.handle_inner
.prompt_policies
.write()
.expect("prompt policy lock poisoned")
.apply_matches(&matched_ids);
let event = if applied.is_empty() {
None
} else {
let ids = applied.iter().map(|policy| policy.id).collect();
for policy in applied {
system.push(SystemBlock::text(format!(
"<!-- runtime policy: {} -->\n{}",
policy.name, policy.content
)));
}
Some(StreamEvent::PolicyApplied {
turn_id: turn_id.clone(),
policy_ids: ids,
})
};
if system.is_empty() {
(None, event)
} else {
(Some(system), event)
}
}
fn current_mode(control: &AgentControl) -> Arc<dyn crate::mode::AgentMode> {
Arc::clone(
&control
.handle_inner
.mode
.read()
.expect("agent mode lock poisoned"),
)
}
async fn emit_policy_event(
event: Option<StreamEvent>,
events_tx: &mpsc::Sender<Result<StreamEvent, ProviderError>>,
trace_hook: &Option<TraceHook>,
new_messages: &[Message],
total_usage: &Usage,
) -> Result<(), AgentError> {
let Some(event) = event else {
return Ok(());
};
if let Some(hook) = trace_hook {
emit_trace(hook, &event);
}
if events_tx.send(Ok(event)).await.is_err() {
return Err(AgentError::Cancelled {
partial: build_partial(new_messages, total_usage, StopReason::Cancelled, ""),
});
}
Ok(())
}
async fn emit_drained_mode_events(
control: &AgentControl,
events_tx: &mpsc::Sender<Result<StreamEvent, ProviderError>>,
trace_hook: &Option<TraceHook>,
new_messages: &[Message],
total_usage: &Usage,
partial_text: &str,
) -> Result<(), AgentError> {
for event in drain_mode_events(control) {
if let Some(hook) = trace_hook {
emit_trace(hook, &event);
}
if events_tx.send(Ok(event)).await.is_err() {
return Err(AgentError::Cancelled {
partial: build_partial(
new_messages,
total_usage,
StopReason::Cancelled,
partial_text,
),
});
}
}
Ok(())
}
fn drain_mode_events(control: &AgentControl) -> Vec<StreamEvent> {
control
.handle_inner
.mode_events
.lock()
.expect("mode event lock poisoned")
.drain(..)
.collect()
}
fn apply_pending_mode(control: &AgentControl, turn_id: &TurnId) -> Option<StreamEvent> {
let mut pending = control
.handle_inner
.pending_mode
.write()
.expect("pending mode lock poisoned");
let pending_change = pending.as_mut()?;
if !pending_change.announced {
pending_change.announced = true;
return Some(StreamEvent::ModeChangeRequested {
from: pending_change.from.clone(),
to: pending_change.to.clone(),
requested_at: turn_id.clone(),
});
}
let pending_change = pending.take()?;
let mut mode = control
.handle_inner
.mode
.write()
.expect("agent mode lock poisoned");
*mode = pending_change.mode;
Some(StreamEvent::ModeChanged {
from: pending_change.from,
to: pending_change.to,
authority: pending_change.authority,
})
}
struct ActiveTurnCleanup(Arc<steering::AgentHandleInner>);
impl Drop for ActiveTurnCleanup {
fn drop(&mut self) {
clear_active_turn_inner(&self.0);
}
}
fn clear_active_turn(control: &AgentControl) {
clear_active_turn_inner(&control.handle_inner);
}
fn clear_active_turn_inner(inner: &steering::AgentHandleInner) {
*inner
.active_turn
.write()
.expect("agent handle turn lock poisoned") = None;
}
enum InjectOutcome {
Continue(StreamEvent),
Abort(StreamEvent),
None,
}
fn describe_tool_calls(calls: &[ToolCall]) -> Vec<String> {
calls
.iter()
.map(|call| format!("{}:{}", call.name, call.id))
.collect()
}
fn inject_continuation_if_needed(
control: &AgentControl,
turn_count: usize,
triggers: &[GuardTrigger],
recent_tool_calls: &[String],
history: &mut Vec<Message>,
new_messages: &mut Vec<Message>,
) -> InjectOutcome {
let snapshot = AgentSnapshot {
turn_count,
last_assistant_message: new_messages
.iter()
.rev()
.find(|message| message.role == crate::message::Role::Assistant)
.cloned(),
recent_tool_calls: recent_tool_calls.to_vec(),
};
let mut guards = control
.handle_inner
.guards
.write()
.expect("continuation guard lock poisoned");
for trigger in triggers {
match guards.evaluate(*trigger, &snapshot) {
GuardEval::Continue {
guard_name,
prompt,
iteration,
} => {
let message = Message::user_text(prompt);
history.push(message.clone());
new_messages.push(message);
return InjectOutcome::Continue(StreamEvent::ContinuationInjected {
guard_name,
iteration,
});
}
GuardEval::Abort { guard_name, reason } => {
return InjectOutcome::Abort(StreamEvent::GuardAborted { guard_name, reason });
}
GuardEval::Stop => {}
}
}
InjectOutcome::None
}
fn drain_queued_user_messages(
control: &mut AgentControl,
turn_id: &TurnId,
history: &mut Vec<Message>,
new_messages: &mut Vec<Message>,
) {
if let Some(active) = control
.handle_inner
.active_turn
.write()
.expect("agent handle turn lock poisoned")
.as_mut()
{
active.accepting_steer = false;
}
let mut content = Vec::new();
while let Ok(command) = control.steer_rx.try_recv() {
match command {
SteerCommand::Append {
turn_id: command_turn_id,
content: mut queued,
} if command_turn_id == *turn_id => content.append(&mut queued),
SteerCommand::Append { .. } => tracing::warn!(
%turn_id,
"discarding stale queued steering message for inactive turn"
),
}
}
if !content.is_empty() {
let message = Message::user(content);
history.push(message.clone());
new_messages.push(message);
}
}
/// Live agent run.
///
/// `AgentStream` implements `Stream<Item = Result<StreamEvent,
/// ProviderError>>` for the live event channel and exposes
/// [`into_result`](Self::into_result) / [`collect_result`](Self::collect_result)
/// for the terminal [`AgentResult`].
pub struct AgentStream {
events_rx: ReceiverStream<Result<StreamEvent, ProviderError>>,
/// Optional so `into_result` can take it without dropping `self`.
result_rx: Option<oneshot::Receiver<Result<AgentResult, AgentError>>>,
}
impl Stream for AgentStream {
type Item = Result<StreamEvent, ProviderError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.get_mut().events_rx).poll_next(cx)
}
}
impl AgentStream {
/// Wait for the loop to finish and return the final result.
///
/// Drops the live event channel — call this only after you've
/// drained as many events as you care about (typically via the
/// `Stream` impl in a `while let Some(ev) = stream.next().await`
/// loop).
pub async fn into_result(mut self) -> Result<AgentResult, AgentError> {
let rx = self
.result_rx
.take()
.expect("into_result called twice on AgentStream");
// Drop the events receiver; if the producer is still running
// it'll see the channel close and short-circuit.
drop(self.events_rx);
match rx.await {
Ok(result) => result,
Err(_) => Err(AgentError::Cancelled {
partial: Box::new(AgentResult {
new_messages: Vec::new(),
text: String::new(),
usage: Usage::default(),
stop_reason: StopReason::Cancelled,
}),
}),
}
}
/// Drain remaining events (discarding them) and return the result.
/// Convenient when the caller only cares about the final outcome —
/// equivalent to `while let Some(_) = stream.next().await {}` then
/// `into_result()`.
pub async fn collect_result(mut self) -> Result<AgentResult, AgentError> {
while self.events_rx.next().await.is_some() {}
let rx = self
.result_rx
.take()
.expect("collect_result called after into_result");
rx.await.unwrap_or_else(|_| {
Err(AgentError::Cancelled {
partial: Box::new(AgentResult {
new_messages: Vec::new(),
text: String::new(),
usage: Usage::default(),
stop_reason: StopReason::Cancelled,
}),
})
})
}
}
/// Fire a trace hook closure with panic isolation. A panicking hook is
/// caught and logged, but the agent loop continues — an audit sink
/// failure must not crash the agent.
fn emit_trace(hook: &TraceHook, ev: &StreamEvent) {
if let Err(panic) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (hook)(ev))) {
tracing::error!(?panic, "trace_hook closure panicked; suppressed");
}
}
fn build_partial(
new_messages: &[Message],
usage: &Usage,
stop_reason: StopReason,
text: &str,
) -> Box<AgentResult> {
Box::new(AgentResult {
new_messages: new_messages.to_vec(),
text: text.to_string(),
usage: usage.clone(),
stop_reason,
})
}
fn extract_text(content: &[Content]) -> String {
content
.iter()
.filter_map(|c| match c {
Content::Text { text, .. } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("")
}
// --- Builder ---
pub struct AgentBuilder {
provider: Option<Arc<dyn LlmProvider>>,
model: Option<String>,
system: Option<Vec<SystemBlock>>,
tools: Vec<Arc<dyn Tool>>,
policy: Option<Arc<dyn ToolPolicy>>,
approval: Option<Arc<dyn ApprovalHandler>>,
executor_override: Option<Arc<ToolExecutor>>,
max_turns: usize,
max_tokens: u32,
temperature: Option<f32>,
working_dir: Option<PathBuf>,
max_depth: usize,
depth: usize,
cache_tools: Option<CacheControl>,
read_cap: usize,
mut_cap: usize,
tool_concurrencies: Vec<(String, ToolConcurrency)>,
thinking: Option<ThinkingConfig>,
tool_definition_filter: Option<HashSet<String>>,
user_input_bridge: Option<Arc<dyn UserInputBridge>>,
}
impl AgentBuilder {
fn new() -> Self {
Self {
provider: None,
model: None,
system: None,
tools: Vec::new(),
policy: None,
approval: None,
executor_override: None,
max_turns: 50,
max_tokens: 16384,
temperature: None,
working_dir: None,
max_depth: 3,
depth: 0,
cache_tools: None,
read_cap: 20,
mut_cap: 10,
tool_concurrencies: Vec::new(),
thinking: None,
tool_definition_filter: None,
user_input_bridge: None,
}
}
pub fn provider(mut self, provider: impl LlmProvider + 'static) -> Self {
self.provider = Some(Arc::new(provider));
self
}
/// Use a shared provider (typically for sub-agent spawning).
pub fn provider_arc(mut self, provider: Arc<dyn LlmProvider>) -> Self {
self.provider = Some(provider);
self
}
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
/// Set the system prompt as a single uncached block.
///
/// Use [`Self::system_blocks`] for a typed multi-block system
/// prompt with [`crate::CacheControl`] breakpoints (Anthropic
/// prompt caching).
pub fn system(mut self, system: impl Into<String>) -> Self {
self.system = Some(vec![SystemBlock::text(system)]);
self
}
/// Set the system prompt as a list of typed blocks. Each block
/// can carry a [`crate::CacheControl`] cache breakpoint —
/// useful when part of the prompt is stable across calls (good
/// to cache) and part rotates per-call.
///
/// Non-Anthropic providers concatenate the blocks with `\n\n`
/// and drop cache_control.
pub fn system_blocks(mut self, blocks: Vec<SystemBlock>) -> Self {
self.system = Some(blocks);
self
}
/// Cache the entire toolset as a single prefix segment with the
/// given TTL. The agent places `cache_control` on the last
/// (alphabetically-final) tool definition each turn, which makes
/// Anthropic cache every preceding tool too.
///
/// For long stable toolsets (the default 8 built-in tools clear
/// several KB of JSON Schema), this is the highest-leverage
/// breakpoint in tkach. Non-Anthropic providers ignore it.
pub fn cache_tools(mut self, cache_control: CacheControl) -> Self {
self.cache_tools = Some(cache_control);
self
}
/// Register a tool by value — convenient for concrete built-in tools.
pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
self.tools.push(Arc::new(tool));
self
}
/// Register tools as shared trait objects. Matches the shape of
/// [`crate::tools::defaults`] and allows one tool instance to live in
/// multiple registries.
pub fn tools(mut self, tools: Vec<Arc<dyn Tool>>) -> Self {
self.tools.extend(tools);
self
}
/// Install a tool-invocation policy. Without this, [`AllowAll`] is used.
pub fn policy(mut self, policy: impl ToolPolicy + 'static) -> Self {
self.policy = Some(Arc::new(policy));
self
}
/// Install a per-call approval handler. Without this,
/// [`AutoApprove`](crate::AutoApprove) is used (every call allowed).
/// The handler runs after [`ToolPolicy::is_allowed`] succeeds and
/// before the tool actually executes; denials surface to the model
/// as `is_error: true` tool_results so the LLM can adapt.
///
/// Sub-agents inherit this handler automatically through their
/// shared [`ToolExecutor`] (Model 3): one handler gates the whole
/// agent tree.
pub fn approval(mut self, approval: impl ApprovalHandler + 'static) -> Self {
self.approval = Some(Arc::new(approval));
self
}
pub fn user_input_bridge(mut self, bridge: impl UserInputBridge + 'static) -> Self {
self.user_input_bridge = Some(Arc::new(bridge));
self
}
/// Re-use an existing [`ToolExecutor`] instead of building one from
/// the `tools` + `policy` accumulated in the builder. Intended for
/// sub-agent spawning, where the child inherits the parent's full
/// registry automatically.
///
/// When set, the override carries its own registry, policy, approval
/// handler, AND [`ConcurrencyConfig`] — so the following builder
/// methods are silently ignored at [`Self::build`]:
///
/// - [`Self::tool`], [`Self::tools`]
/// - [`Self::policy`]
/// - [`Self::approval`]
/// - [`Self::max_concurrent_reads`], [`Self::max_concurrent_mutations`]
/// - [`Self::tool_concurrency`], [`Self::tool_concurrencies`]
///
/// To customise concurrency for a sub-agent, build a forked executor
/// via [`ToolExecutor::fork_for_subagent`] (or construct one directly
/// with [`ToolExecutor::with_approval_and_concurrency`]) and pass it
/// here.
pub fn executor(mut self, executor: Arc<ToolExecutor>) -> Self {
self.executor_override = Some(executor);
self
}
pub fn max_turns(mut self, max_turns: usize) -> Self {
self.max_turns = max_turns;
self
}
pub fn max_tokens(mut self, max_tokens: u32) -> Self {
self.max_tokens = max_tokens;
self
}
pub fn temperature(mut self, temperature: f32) -> Self {
self.temperature = Some(temperature);
self
}
/// Default per-call thinking config threaded into every
/// [`Request`] this agent issues. Provider precedence: an explicit
/// per-call `Request.thinking` (set by, for example, a SubAgent's
/// own [`crate::tools::SubAgent::thinking`]) overrides this; this
/// in turn overrides the provider instance's construction-time
/// default. See [`ThinkingConfig`] for provider-asymmetry notes.
pub fn thinking(mut self, thinking: ThinkingConfig) -> Self {
self.thinking = Some(thinking);
self
}
pub(crate) fn tool_definition_filter(mut self, allowed: HashSet<String>) -> Self {
self.tool_definition_filter = Some(allowed);
self
}
pub fn working_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.working_dir = Some(dir.into());
self
}
/// Maximum nesting depth for sub-agent recursion. Default: 3.
pub fn max_depth(mut self, depth: usize) -> Self {
self.max_depth = depth;
self
}
pub(crate) fn depth(mut self, depth: usize) -> Self {
self.depth = depth;
self
}
/// Maximum concurrent `ReadOnly`-class tool calls in a single batch.
/// Default: 20.
///
/// Ignored when [`Self::executor`] was called — the inherited
/// `ToolExecutor` already carries its own [`ConcurrencyConfig`].
///
/// # Panics
/// Panics if `n == 0`.
#[must_use]
pub fn max_concurrent_reads(mut self, n: usize) -> Self {
assert!(n > 0, "max_concurrent_reads requires n > 0");
self.read_cap = n;
self
}
/// Maximum concurrent `Mutating`-class tool calls that share the
/// `concurrent_mut` pool. Default: 10.
///
/// Two paths admit a call into this pool:
///
/// 1. The consumer promotes a default-`Mutating` tool via
/// [`Self::tool_concurrency`] with [`ToolConcurrency::on`].
/// 2. The tool sets [`crate::Tool::is_recursive`] to `true` (the
/// canonical example is `SubAgent`). Recursive tools are routed
/// through `concurrent_mut` regardless of explicit promotion to
/// avoid the permit-held-during-nested-execute deadlock that
/// would otherwise arise on the shared `serial_mut` pool.
///
/// **Scope of the cap is per nesting level**, not tree-wide.
/// `SubAgent::execute` calls [`ToolExecutor::fork_for_subagent`],
/// which forks a fresh `concurrent_mut` semaphore (same numeric
/// cap, independent permit accounting) so a parent saturating its
/// pool cannot deadlock children needing their own
/// promoted-mutator slots. Total in-flight promoted calls in a
/// deep tree therefore scale as `O(fanout^depth × cap)` — capacity-
/// plan accordingly when promoting tools that hit shared external
/// resources (rate-limited APIs, finite connection pools).
///
/// `serial_mut` (cap 1, fixed) and `read` (default cap 20) stay
/// **shared** across the agent tree:
///
/// - Default-`Mutating` tools without an explicit promotion still
/// serialise globally — two sibling sub-agents writing the same
/// file via the built-in `write` tool will not race even when
/// the consumer opted into none of the concurrency knobs.
/// - The read pool acts as a global throughput throttle.
///
/// See [`crate::ConcurrencyConfig::fork`] for the exact share-vs-
/// fork policy.
///
/// Ignored when [`Self::executor`] was called.
///
/// # Panics
/// Panics if `n == 0`.
#[must_use]
pub fn max_concurrent_mutations(mut self, n: usize) -> Self {
assert!(n > 0, "max_concurrent_mutations requires n > 0");
self.mut_cap = n;
self
}
/// Configure concurrency for a single tool by name.
///
/// The most common use is [`ToolConcurrency::on`] to promote a
/// default-`Mutating` tool into the concurrent-mutator pool. Chain
/// `.max(N)` for a per-tool cap that bounds parallelism for *this
/// specific tool* below the class cap. The effective concurrent
/// count is `min(per_tool_cap, class_cap_remaining)`.
///
/// Promotion is a *consumer's responsibility* contract: the
/// framework can no longer prevent racing calls to the same tool
/// with conflicting inputs (e.g. two writes to the same path).
/// Promote only when the LLM-emitted batch shape — and the tool's
/// own resource semantics — make racing safe.
///
/// **Per-tool caps fork per nesting level**: a sub-agent inherits
/// the configured cap as a fresh semaphore via
/// [`ToolExecutor::fork_for_subagent`]. A `.max(2)` cap therefore
/// admits 2 concurrent calls *per nesting level*, not 2 tree-wide.
/// Plan caps with this in mind for tools that hit shared external
/// resources (rate-limited APIs, finite connection pools); see
/// [`crate::ConcurrencyConfig::fork`].
///
/// Later calls for the same tool name override earlier ones.
/// Ignored when [`Self::executor`] was called.
#[must_use]
pub fn tool_concurrency(mut self, name: impl Into<String>, cfg: ToolConcurrency) -> Self {
self.tool_concurrencies.push((name.into(), cfg));
self
}
/// Bulk variant of [`Self::tool_concurrency`] for configuring
/// multiple tools at once.
#[must_use]
pub fn tool_concurrencies<I>(mut self, entries: I) -> Self
where
I: IntoIterator<Item = (String, ToolConcurrency)>,
{
self.tool_concurrencies.extend(entries);
self
}
pub fn build(self) -> Result<Agent, BuildError> {
self.validate_tool_names()?;
let executor = self.executor_override.unwrap_or_else(|| {
let registry = Arc::new(ToolRegistry::new(self.tools));
let policy: Arc<dyn ToolPolicy> = self.policy.unwrap_or_else(|| Arc::new(AllowAll));
let approval: Arc<dyn ApprovalHandler> =
self.approval.unwrap_or_else(|| Arc::new(AutoApprove));
let concurrency =
ConcurrencyConfig::new(self.read_cap, self.mut_cap, self.tool_concurrencies);
Arc::new(ToolExecutor::with_approval_and_concurrency(
registry,
policy,
approval,
concurrency,
))
});
Ok(Agent {
provider: self.provider.expect("provider is required"),
model: self.model.expect("model is required"),
system: self.system,
executor,
max_turns: self.max_turns,
max_tokens: self.max_tokens,
temperature: self.temperature,
working_dir: self
.working_dir
.unwrap_or_else(|| std::env::current_dir().expect("failed to get current dir")),
max_depth: self.max_depth,
depth: self.depth,
cache_tools: self.cache_tools,
thinking: self.thinking,
tool_definition_filter: self.tool_definition_filter,
user_input_bridge: self.user_input_bridge,
})
}
fn validate_tool_names(&self) -> Result<(), BuildError> {
if self.executor_override.is_some() {
return Ok(());
}
let mut counts: HashMap<String, usize> = HashMap::new();
for tool in &self.tools {
*counts.entry(tool.name().to_string()).or_insert(0) += 1;
}
if let Some((name, count)) = counts.into_iter().find(|(_, count)| *count > 1) {
return Err(BuildError::DuplicateToolName { name, count });
}
Ok(())
}
}