summaryrefslogtreecommitdiff
path: root/libpanto/src/agent.zig
blob: c078c24c389f7aa62b05379930a97debba87a220 (plain)
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
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
//! The Agent owns the conversation-driving loop: provider streaming +
//! tool dispatch.
//!
//! On each turn, after the provider streams an assistant message, the
//! agent inspects it for ToolUse blocks. If any are present, the agent:
//!
//!   1. Groups them by their *owning registration* in the registry — a
//!      single `Tool` is its own group; every `ToolSource`-backed tool
//!      whose name maps to the same source forms one group.
//!   2. Spawns one concurrent task per group via `std.Io.Group`.
//!      A single-`Tool` group runs the tool's `invoke` once; a
//!      `ToolSource` group calls the source's `invoke_batch` with all
//!      of its calls at once. We use `Group.concurrent` (not `async`)
//!      because tool invocations may block on I/O and we need real
//!      concurrency, not just expressed asynchrony.
//!   3. Awaits the group. ToolResult blocks are assembled in the
//!      *original* call order (i.e. the order the LLM emitted them).
//!   4. Appends a user message containing the ToolResult blocks back
//!      into the conversation and loops.
//!
//! The "thread-safe" promise for single `Tool` registrations is
//! unchanged. For `ToolSource`-backed tools, the source's runtime
//! receives all of its calls on one thread per turn, so it can keep a
//! single-threaded interpreter (Lua, Python, ...) without further
//! synchronization.

const std = @import("std");
const Allocator = std.mem.Allocator;
const Io = std.Io;

const provider_mod = @import("provider.zig");
const config_mod = @import("config.zig");
const conversation = @import("conversation.zig");
const compaction_mod = @import("compaction.zig");
const tool_mod = @import("tool.zig");
const image_mod = @import("image.zig");
const tool_source_mod = @import("tool_source.zig");
const tool_registry_mod = @import("tool_registry.zig");

pub const Tool = tool_mod.Tool;
pub const ToolSource = tool_source_mod.ToolSource;
pub const ToolRegistry = tool_registry_mod.ToolRegistry;

const Entry = tool_registry_mod.Entry;

pub const Config = config_mod.Config;

/// Re-export for the `compact` usages parameter (provider-reported token
/// usage per message, used for retention sizing).
pub const conversation_Usage = @import("session.zig").Usage;

/// Deep-copy a message (role + all content blocks) into fresh owned
/// allocations. Used when rebuilding the conversation after compaction.
fn cloneMessage(alloc: Allocator, msg: conversation.Message) !conversation.Message {
    var content: std.ArrayList(conversation.ContentBlock) = .empty;
    errdefer {
        for (content.items) |*b| b.deinit(alloc);
        content.deinit(alloc);
    }
    try content.ensureTotalCapacity(alloc, msg.content.items.len);
    for (msg.content.items) |block| {
        content.appendAssumeCapacity(try cloneBlock(alloc, block));
    }
    return .{ .role = msg.role, .content = content, .usage = msg.usage };
}

fn cloneBlock(alloc: Allocator, block: conversation.ContentBlock) !conversation.ContentBlock {
    return switch (block) {
        .Text => |b| .{ .Text = try conversation.textualBlockFromSlice(alloc, b.items) },
        .Thinking => |b| blk: {
            const tb = try conversation.textualBlockFromSlice(alloc, b.text.items);
            errdefer {
                var mut = tb;
                mut.deinit(alloc);
            }
            const sig: ?[]const u8 = if (b.signature) |s| try alloc.dupe(u8, s) else null;
            break :blk .{ .Thinking = .{ .text = tb, .signature = sig } };
        },
        .ToolUse => |b| blk: {
            const id = try alloc.dupe(u8, b.id);
            errdefer alloc.free(id);
            const name = try alloc.dupe(u8, b.name);
            errdefer alloc.free(name);
            const input = try conversation.textualBlockFromSlice(alloc, b.input.items);
            break :blk .{ .ToolUse = .{ .id = id, .name = name, .input = input } };
        },
        .ToolResult => |b| blk: {
            const tuid = try alloc.dupe(u8, b.tool_use_id);
            errdefer alloc.free(tuid);
            var parts: std.ArrayList(conversation.ResultPartStored) = .empty;
            errdefer {
                for (parts.items) |*p| p.deinit(alloc);
                parts.deinit(alloc);
            }
            try parts.ensureTotalCapacity(alloc, b.parts.items.len);
            for (b.parts.items) |src| {
                switch (src) {
                    .text => |tb| {
                        const t = try conversation.textualBlockFromSlice(alloc, tb.items);
                        parts.appendAssumeCapacity(.{ .text = t });
                    },
                    .media => |m| {
                        const mt = try alloc.dupe(u8, m.media_type);
                        errdefer alloc.free(mt);
                        const data = try conversation.textualBlockFromSlice(alloc, m.data.items);
                        parts.appendAssumeCapacity(.{ .media = .{ .media_type = mt, .data = data } });
                    },
                }
            }
            break :blk .{ .ToolResult = .{ .tool_use_id = tuid, .parts = parts } };
        },
        .System => |b| .{ .System = .{
            .text = try conversation.textualBlockFromSlice(alloc, b.text.items),
            .mode = b.mode,
        } },
        .CompactionSummary => |b| .{ .CompactionSummary = .{
            .text = try conversation.textualBlockFromSlice(alloc, b.text.items),
        } },
    };
}

/// A minimal receiver that captures the assistant's streamed message for
/// compaction. We don't need incremental events — the assembled message is
/// read off the conversation after the turn — so all callbacks are no-ops.
const CompactionCapture = struct {
    allocator: Allocator,

    fn receiver(self: *CompactionCapture) provider_mod.Receiver {
        return .{ .ptr = self, .vtable = &vt };
    }
    fn deinit(self: *CompactionCapture) void {
        _ = self;
    }
    const vt: provider_mod.ReceiverVTable = .{
        .onMessageStart = onMessageStart,
        .onBlockStart = onBlockStart,
        .onToolDetails = onToolDetails,
        .onContentDelta = onContentDelta,
        .onBlockComplete = onBlockComplete,
        .onMessageComplete = onMessageComplete,
        .onError = onError,
    };
    fn onMessageStart(_: *anyopaque, _: conversation.MessageRole) anyerror!void {}
    fn onBlockStart(_: *anyopaque, _: provider_mod.ContentBlockType, _: usize) anyerror!void {}
    fn onToolDetails(_: *anyopaque, _: usize, _: []const u8, _: []const u8) anyerror!void {}
    fn onContentDelta(_: *anyopaque, _: usize, _: []const u8) anyerror!void {}
    fn onBlockComplete(_: *anyopaque, _: usize, _: conversation.ContentBlock) anyerror!void {}
    fn onMessageComplete(_: *anyopaque, _: conversation.Message, _: ?provider_mod.Usage) anyerror!void {}
    fn onError(_: *anyopaque, _: anyerror) void {}
};

fn isValidToolInput(input: []const u8) bool {
    if (input.len == 0) return true;
    if (input[0] != '{') return true; // legacy tests/tools may use opaque bytes
    var parsed = std.json.parseFromSlice(std.json.Value, std.heap.page_allocator, input, .{}) catch return false;
    defer parsed.deinit();
    return parsed.value == .object;
}

fn invalidInputResult(allocator: Allocator, input: []const u8) ![]tool_mod.ResultPart {
    const msg = try std.fmt.allocPrint(
        allocator,
        "Tool call was not executed: tool input was incomplete or invalid JSON. Partial input: {s}",
        .{input},
    );
    return tool_mod.ownedTextResult(allocator, msg);
}


pub const Agent = struct {
    allocator: Allocator,
    io: Io,
    /// The active configuration snapshot, consulted fresh at the top of
    /// every turn. Immutable while a turn is in flight; swap this pointer
    /// (`setConfig`) between turns to change provider/model/base_url and/or
    /// the visible tool set atomically. The pointee and its registry are
    /// owned by the embedder, not the agent.
    config: *const Config,
    /// Injectable streaming seam. Defaults to the real provider dispatch
    /// (`provider_mod.streamStep`); tests override it with a stub.
    stream_fn: provider_mod.StreamFn = provider_mod.streamStep,
    /// Compaction system prompt used for automatic compaction on context
    /// overflow. Borrowed; set by the embedder (resolved from its
    /// `COMPACTION.md` layers). When null, auto-compaction is disabled and
    /// a context-overflow error propagates unchanged.
    compaction_system_prompt: ?[]const u8 = null,
    /// Set by the embedder after `runStep` returns to learn whether an
    /// automatic compaction occurred this turn (so it can persist the
    /// rewritten conversation). Reset at the top of each `runStep`.
    auto_compacted: bool = false,

    pub fn init(allocator: Allocator, io: Io, config: *const Config) Agent {
        return .{
            .allocator = allocator,
            .io = io,
            .config = config,
        };
    }

    pub fn deinit(self: *Agent) void {
        // The agent owns neither the config snapshot nor the registry it
        // borrows; the embedder tears those down.
        _ = self;
    }

    /// Swap the active configuration snapshot. Takes effect at the start of
    /// the next turn. Safe to call between `runStep` invocations or from a
    /// tool handler that runs between provider steps; never mutates a
    /// snapshot a turn is currently reading.
    pub fn setConfig(self: *Agent, config: *const Config) void {
        self.config = config;
    }

    /// The registry exposed by the active snapshot.
    pub fn registry(self: *const Agent) *const ToolRegistry {
        return self.config.registry;
    }

    /// Drive the conversation forward until the model stops calling tools.
    pub fn runStep(
        self: *Agent,
        conv: *conversation.Conversation,
        receiver: *provider_mod.Receiver,
    ) !void {
        self.auto_compacted = false;
        while (true) {
            // Re-read the config snapshot at the top of each turn so a
            // mid-conversation swap takes effect here, never mid-stream.
            const cfg = self.config;
            self.stream_fn(self.allocator, self.io, cfg, conv, receiver) catch |err| {
                // Automatic compaction on context overflow: compact the
                // conversation once and retry the failed request a single
                // time. If the retry also overflows, surface the error.
                if (err != error.ContextOverflow) return err;
                if (self.auto_compacted) return err; // already retried once
                const sys = self.compaction_system_prompt orelse return err;
                const res = try self.compact(conv, sys, null);
                if (!res.compacted) return err; // nothing to shed; give up
                self.auto_compacted = true;
                // Retry the same request against the compacted context.
                try self.stream_fn(self.allocator, self.io, cfg, conv, receiver);
            };

            const last = conv.messages.items[conv.messages.items.len - 1];
            std.debug.assert(last.role == .assistant);

            // Defense-in-depth: a provider that silently committed an
            // empty assistant message means the turn made no observable
            // progress. Surface it instead of looping back to the prompt.
            if (last.content.items.len == 0) return error.EmptyAssistantResponse;

            if (!hasToolUseBlock(last)) return;

            try self.dispatchToolCalls(conv, last);
        }
    }

    fn hasToolUseBlock(msg: conversation.Message) bool {
        for (msg.content.items) |block| {
            if (block == .ToolUse) return true;
        }
        return false;
    }

    /// Outcome of a compaction attempt.
    pub const CompactionResult = struct {
        /// Whether the conversation was actually compacted. False means the
        /// active conversation already fit within the keep-verbatim budget
        /// (nothing to summarize) — the conversation is unchanged.
        compacted: bool,
        /// Number of whole turns kept verbatim after the summary.
        kept_turns: usize = 0,
        /// Number of conversation messages folded into the summary.
        summarized_messages: usize = 0,
    };

    /// Compact the conversation: summarize an older prefix into a single
    /// `.CompactionSummary` block and keep a recent suffix of whole turns
    /// verbatim. Mutates `conv` in place. The embedder is responsible for
    /// persisting the resulting new messages (the agent never touches the
    /// session log).
    ///
    /// The system prompt survives untouched: all `.system`-role messages
    /// are preserved in order, and no `replace` block is written. Only the
    /// conversation (user/assistant) prefix is summarized.
    ///
    /// Per-message provider usage is read directly off the conversation
    /// (`Message.usage`, set live by the provider and on replay from disk).
    /// `computeSplit` uses it to size the retention window; messages
    /// lacking usage fall back to word counting.
    ///
    /// `extra_instructions`, when non-null, is appended to the compaction
    /// system prompt for this run (the `/compact $ARGUMENTS` path).
    ///
    /// `system_prompt` is the compaction system prompt (resolved by the
    /// embedder from its `COMPACTION.md` layers, or a built-in default).
    pub fn compact(
        self: *Agent,
        conv: *conversation.Conversation,
        system_prompt: []const u8,
        extra_instructions: ?[]const u8,
    ) !CompactionResult {
        const messages = conv.messages.items;

        // Project per-message usage off the conversation for sizing.
        const usages = try self.allocator.alloc(?conversation_Usage, messages.len);
        defer self.allocator.free(usages);
        for (messages, 0..) |m, i| usages[i] = m.usage;

        const split = compaction_mod.computeSplit(messages, usages, self.config.compaction.keep_verbatim);

        // Determine the active conversation start (after any prior summary).
        const active_start: usize = if (conversation.latestCompactionIndex(messages)) |a| a + 1 else 0;

        // Nothing to summarize: the active conversation already fits, or the
        // prefix boundary is at/under the first active turn.
        if (split.prefix_end <= active_start) {
            return .{ .compacted = false };
        }
        // Count how many *conversation* (non-system) messages are in the
        // summarized prefix. If none, this is also a no-op.
        var summarized: usize = 0;
        for (messages[active_start..split.prefix_end]) |m| {
            if (m.role != .system) summarized += 1;
        }
        if (summarized == 0) return .{ .compacted = false };

        // Serialize the prefix transcript and carry forward the latest
        // existing summary (chained-compaction invariant).
        const transcript = try compaction_mod.serializeTranscript(
            self.allocator,
            messages[active_start..split.prefix_end],
        );
        defer self.allocator.free(transcript);

        const previous_summary = compaction_mod.latestSummaryText(messages);
        const body = try compaction_mod.buildRequestBody(self.allocator, transcript, previous_summary);
        defer self.allocator.free(body);

        const summary = try self.runCompactionRequest(system_prompt, body, extra_instructions);
        defer self.allocator.free(summary);

        try self.rewriteWithSummary(conv, split.prefix_end, summary);

        return .{
            .compacted = true,
            .kept_turns = split.kept_turns,
            .summarized_messages = summarized,
        };
    }

    /// Rewrite `conv.messages` to `[all system messages..., summary,
    /// kept-suffix...]`. The summarized conversation prefix (everything
    /// before `prefix_end` that isn't a system message) is dropped; system
    /// messages survive in order; a `.CompactionSummary` user message is
    /// inserted; the kept suffix (`messages[prefix_end..]`) is preserved.
    fn rewriteWithSummary(
        self: *Agent,
        conv: *conversation.Conversation,
        prefix_end: usize,
        summary: []const u8,
    ) !void {
        const alloc = self.allocator;
        const old = conv.messages.items;

        var rebuilt: std.ArrayList(conversation.Message) = .empty;
        errdefer {
            for (rebuilt.items) |*m| m.deinit(alloc);
            rebuilt.deinit(alloc);
        }

        // 1. All system messages from the summarized prefix survive, in
        //    order. (System messages in the kept suffix come along with it
        //    below, so only scan the prefix here.)
        for (old[0..prefix_end]) |*m| {
            if (m.role != .system) continue;
            try rebuilt.append(alloc, try cloneMessage(alloc, m.*));
        }

        // 2. The compaction summary, alone in a user message.
        {
            const tb = try conversation.textualBlockFromSlice(alloc, summary);
            var content: std.ArrayList(conversation.ContentBlock) = .empty;
            errdefer {
                for (content.items) |*b| b.deinit(alloc);
                content.deinit(alloc);
            }
            try content.append(alloc, .{ .CompactionSummary = .{ .text = tb } });
            try rebuilt.append(alloc, .{ .role = .user, .content = content });
        }

        // 3. The kept verbatim suffix.
        for (old[prefix_end..]) |*m| {
            try rebuilt.append(alloc, try cloneMessage(alloc, m.*));
        }

        // Swap in the rebuilt list and free the old one.
        for (conv.messages.items) |*m| m.deinit(alloc);
        conv.messages.deinit(alloc);
        conv.messages = rebuilt;
    }

    /// Run a single compaction provider call against a throwaway
    /// conversation. Returns the assistant's summary text (caller owns).
    ///
    /// Model selection: try `config.compaction.model` if set; on failure,
    /// fall back to the active chat model. Compaction runs with an empty
    /// tool registry and a single user message (the request body); no tools
    /// are exposed and no session logging occurs.
    fn runCompactionRequest(
        self: *Agent,
        system_prompt: []const u8,
        body: []const u8,
        extra_instructions: ?[]const u8,
    ) ![]u8 {
        const alloc = self.allocator;

        // Assemble the effective compaction system prompt (+ extra
        // instructions for a `/compact $ARGUMENTS` run).
        var sys_text: []const u8 = system_prompt;
        var sys_owned: ?[]u8 = null;
        defer if (sys_owned) |s| alloc.free(s);
        if (extra_instructions) |extra| {
            if (extra.len > 0) {
                const combined = try std.fmt.allocPrint(
                    alloc,
                    "{s}\n\n## Additional instructions for this compaction run\n\n{s}",
                    .{ system_prompt, extra },
                );
                sys_owned = combined;
                sys_text = combined;
            }
        }

        var empty_registry = ToolRegistry.init(alloc);
        defer empty_registry.deinit();

        // Try the configured compaction model first, then fall back to the
        // active chat model on any failure.
        if (self.config.compaction.model) |comp_provider| {
            const cfg: config_mod.Config = .{
                .provider = comp_provider,
                .registry = &empty_registry,
                .compaction = self.config.compaction,
            };
            if (self.runSingleCompactionTurn(&cfg, sys_text, body)) |summary| {
                return summary;
            } else |err| {
                std.log.warn("compaction model failed ({t}); falling back to active model", .{err});
            }
        }

        const cfg: config_mod.Config = .{
            .provider = self.config.provider,
            .registry = &empty_registry,
            .compaction = self.config.compaction,
        };
        return self.runSingleCompactionTurn(&cfg, sys_text, body);
    }

    /// One provider call for compaction. Builds a throwaway conversation
    /// (system prompt + one user message), streams a single turn through a
    /// capturing receiver, and returns the assembled assistant text.
    fn runSingleCompactionTurn(
        self: *Agent,
        cfg: *const config_mod.Config,
        system_prompt: []const u8,
        body: []const u8,
    ) ![]u8 {
        const alloc = self.allocator;
        var conv = conversation.Conversation.init(alloc);
        defer conv.deinit();
        try conv.addSystemMessage(system_prompt);
        try conv.addUserMessage(body);

        var capture = CompactionCapture{ .allocator = alloc };
        defer capture.deinit();
        var recv = capture.receiver();

        try self.stream_fn(alloc, self.io, cfg, &conv, &recv);

        // The provider appended an assistant message; gather its text.
        const last = conv.messages.items[conv.messages.items.len - 1];
        if (last.role != .assistant) return error.CompactionNoResponse;
        var out: std.ArrayList(u8) = .empty;
        errdefer out.deinit(alloc);
        for (last.content.items) |block| {
            if (block == .Text) try out.appendSlice(alloc, block.Text.items);
        }
        if (out.items.len == 0) return error.CompactionEmptySummary;
        return out.toOwnedSlice(alloc);
    }

    /// Dispatch every ToolUse block in `assistant_msg`. Groups by owning
    /// registration; one OS thread per group; results assembled in the
    /// original call order.
    fn dispatchToolCalls(
        self: *Agent,
        conv: *conversation.Conversation,
        assistant_msg: conversation.Message,
    ) !void {
        // Build the flat call list (in original order) and group calls
        // by owning registration.
        var calls: std.array_list.Managed(FlatCall) = .init(self.allocator);
        defer calls.deinit();

        for (assistant_msg.content.items) |block| {
            if (block != .ToolUse) continue;
            const tu = block.ToolUse;
            if (!isValidToolInput(tu.input.items)) {
                try calls.append(.{
                    .tool_use_id = tu.id,
                    .tool_name = tu.name,
                    .input = tu.input.items,
                    .entry = null,
                    .result = try invalidInputResult(self.allocator, tu.input.items),
                    .err = null,
                });
                continue;
            }
            const entry = self.config.registry.lookup(tu.name) orelse {
                // Unknown tool: abort the turn with a clear error.
                return error.UnknownTool;
            };
            try calls.append(.{
                .tool_use_id = tu.id,
                .tool_name = tu.name,
                .input = tu.input.items,
                .entry = entry.entry,
                .result = null,
                .err = null,
            });
        }
        std.debug.assert(calls.items.len > 0);

        // Partition into groups. A group's `kind` determines how it
        // runs; the `member_indices` are positions into `calls` (the
        // original call order) so we can write back results without
        // re-ordering.
        var groups: std.array_list.Managed(Group) = .init(self.allocator);
        defer {
            for (groups.items) |*g| g.deinit(self.allocator);
            groups.deinit();
        }
        try buildGroups(self.allocator, calls.items, &groups);

        // Spawn one concurrent task per group via `std.Io.Group`.
        // Single-tool groups run the tool's vtable; source groups run
        // the source's `invoke_batch`. We use `concurrent` rather than
        // `async` because tool work may block on I/O — under a
        // single-threaded `Io` `async` would deadlock; `concurrent`
        // forces real concurrency (or `error.ConcurrencyUnavailable`).
        var task_group: Io.Group = .init;
        // `cancel` is idempotent with `await`; if anything below this
        // point errors before we successfully `await`, this releases
        // the group's resources.
        defer task_group.cancel(self.io);
        errdefer {
            for (calls.items) |*c| {
                if (c.result) |r| tool_mod.freeResultParts(self.allocator, r);
            }
        }

        for (groups.items) |*g| {
            try task_group.concurrent(self.io, runGroup, .{ self, g, calls.items });
        }
        // `error.Canceled` here means cancellation propagated into this
        // dispatch from above; surface it like any other error.
        try task_group.await(self.io);

        // Assemble ToolResult blocks in original call order. If any
        // call errored, prefer to abort the turn — but only after the
        // standard errdefer above has freed remaining results.
        var content: std.ArrayList(conversation.ContentBlock) = .empty;
        errdefer {
            for (content.items) |*b| b.deinit(self.allocator);
            content.deinit(self.allocator);
        }
        try content.ensureTotalCapacity(self.allocator, calls.items.len);

        var first_err: ?anyerror = null;
        for (calls.items) |*c| {
            if (c.err) |e| {
                first_err = e;
                continue;
            }
            const result_parts = c.result orelse {
                // Internal error: every successful call should have left
                // parts behind. Treat as MissingToolResult.
                first_err = error.MissingToolResult;
                continue;
            };
            c.result = null; // ownership transferred below
            defer tool_mod.freeResultParts(self.allocator, result_parts);

            const id_copy = try self.allocator.dupe(u8, c.tool_use_id);
            errdefer self.allocator.free(id_copy);

            var stored: std.ArrayList(conversation.ResultPartStored) = .empty;
            errdefer {
                for (stored.items) |*p| p.deinit(self.allocator);
                stored.deinit(self.allocator);
            }
            try stored.ensureTotalCapacity(self.allocator, result_parts.len);
            for (result_parts) |part| {
                switch (part) {
                    .text => |t| {
                        var buf: conversation.TextualBlock = .empty;
                        errdefer buf.deinit(self.allocator);
                        try buf.appendSlice(self.allocator, t);
                        stored.appendAssumeCapacity(.{ .text = buf });
                    },
                    .media => |m| {
                        // libpanto owns the heavy lifting: detect the type
                        // (when the tool gave no hint), resize large
                        // rasters, then base64-encode for storage. Tools
                        // hand over raw bytes only.
                        const processed = image_mod.process(self.allocator, m.data, m.media_type) catch |e| {
                            // Unrecognized bytes: keep the turn alive by
                            // dropping the attachment and noting it as text.
                            if (e == error.UnknownMediaType) {
                                var note: conversation.TextualBlock = .empty;
                                errdefer note.deinit(self.allocator);
                                try note.appendSlice(self.allocator, "[unrecognized binary attachment dropped]");
                                stored.appendAssumeCapacity(.{ .text = note });
                                continue;
                            }
                            return e;
                        };
                        defer self.allocator.free(processed.data);

                        const mt = try self.allocator.dupe(u8, processed.media_type);
                        errdefer self.allocator.free(mt);

                        const enc = std.base64.standard.Encoder;
                        var buf: conversation.TextualBlock = .empty;
                        errdefer buf.deinit(self.allocator);
                        try buf.resize(self.allocator, enc.calcSize(processed.data.len));
                        _ = enc.encode(buf.items, processed.data);

                        stored.appendAssumeCapacity(.{ .media = .{ .media_type = mt, .data = buf } });
                    },
                }
            }

            content.appendAssumeCapacity(.{ .ToolResult = .{
                .tool_use_id = id_copy,
                .parts = stored,
            } });
        }

        if (first_err) |e| return e;

        try conv.messages.append(self.allocator, .{
            .role = .user,
            .content = content,
        });
    }
};

/// One ToolUse, as flattened into the agent's dispatch list. `result`
/// and `err` are filled in by the worker; exactly one is non-null on
/// successful task completion.
const FlatCall = struct {
    tool_use_id: []const u8, // borrowed from assistant_msg
    tool_name: []const u8, // borrowed from assistant_msg
    input: []const u8, // borrowed from assistant_msg
    entry: ?Entry,

    /// Owned result parts from `Tool.invoke` or `ToolSource.invoke_batch`.
    /// Allocated with the agent's allocator. Transferred into a
    /// ToolResultBlock on success.
    result: ?[]tool_mod.ResultPart,

    /// If non-null, the call failed and the turn must abort.
    err: ?anyerror,
};

/// One dispatch group. Either a single Tool invocation, or a batch of
/// calls headed to one ToolSource.
const Group = union(enum) {
    single: SingleGroup,
    source: SourceGroup,

    pub const SingleGroup = struct {
        tool: Tool,
        /// Index into the flat calls array.
        call_index: usize,
    };

    pub const SourceGroup = struct {
        source: *ToolSource,
        /// Indices into the flat calls array. Owned by the group.
        member_indices: []usize,
    };

    fn deinit(self: *Group, allocator: Allocator) void {
        switch (self.*) {
            .single => {},
            .source => |sg| allocator.free(sg.member_indices),
        }
    }
};

/// Partition the flat call list into groups. Order of groups is
/// arbitrary; order within a `source` group preserves the original
/// call order so that batch results can be written back positionally.
fn buildGroups(
    allocator: Allocator,
    calls: []const FlatCall,
    out: *std.array_list.Managed(Group),
) !void {
    // Map from source pointer to the index of its group in `out`.
    // Buffers per source, accumulated then frozen into slices.
    var pending: std.AutoHashMap(*ToolSource, std.array_list.Managed(usize)) =
        .init(allocator);
    defer {
        var it = pending.valueIterator();
        while (it.next()) |l| l.deinit();
        pending.deinit();
    }

    for (calls, 0..) |c, i| {
        const ent = c.entry orelse continue;
        switch (ent) {
            .single => |t| try out.append(.{ .single = .{ .tool = t, .call_index = i } }),
            .source => |sr| {
                const gop = try pending.getOrPut(sr.source);
                if (!gop.found_existing) {
                    gop.value_ptr.* = std.array_list.Managed(usize).init(allocator);
                }
                try gop.value_ptr.append(i);
            },
        }
    }

    // Freeze each pending list into a source-group entry. We move
    // ownership of the indices into `Group.source.member_indices`.
    var pit = pending.iterator();
    while (pit.next()) |entry| {
        const src = entry.key_ptr.*;
        const indices = try entry.value_ptr.toOwnedSlice();
        try out.append(.{ .source = .{ .source = src, .member_indices = indices } });
    }
}

/// Worker entry point. Runs one group to completion, populating
/// `calls[i].result` or `calls[i].err` for each member call.
///
/// Return type is `void`, which coerces to `Io.Cancelable!void` as
/// required by `Group.concurrent`. Tool errors are reported via
/// `FlatCall.err`, not by returning from this function.
fn runGroup(agent: *Agent, group: *Group, calls: []FlatCall) void {
    switch (group.*) {
        .single => |sg| {
            const i = sg.call_index;
            const c = &calls[i];
            const out = sg.tool.vtable.invoke(sg.tool.ctx, c.input, agent.allocator) catch |e| {
                c.err = e;
                return;
            };
            c.result = out;
        },
        .source => |sg| runSourceGroup(agent, sg, calls),
    }
}

fn runSourceGroup(agent: *Agent, sg: Group.SourceGroup, calls: []FlatCall) void {
    const n = sg.member_indices.len;

    const batch_calls = agent.allocator.alloc(tool_source_mod.Call, n) catch |e| {
        for (sg.member_indices) |i| calls[i].err = e;
        return;
    };
    defer agent.allocator.free(batch_calls);

    const batch_results = agent.allocator.alloc(tool_source_mod.CallResult, n) catch |e| {
        for (sg.member_indices) |i| calls[i].err = e;
        return;
    };
    defer agent.allocator.free(batch_results);

    for (sg.member_indices, 0..) |idx, j| {
        batch_calls[j] = .{
            .tool_name = calls[idx].tool_name,
            .input = calls[idx].input,
        };
        batch_results[j] = .{ .err = error.SourceDroppedCall };
    }

    sg.source.vtable.invoke_batch(
        sg.source.ctx,
        batch_calls,
        batch_results,
        agent.allocator,
    ) catch |e| {
        // Whole-batch failure: free any partial successes the source
        // already wrote, then mark every member as failed.
        for (batch_results) |r| switch (r) {
            .ok => |b| tool_mod.freeResultParts(agent.allocator, b),
            .err => {},
        };
        for (sg.member_indices) |i| calls[i].err = e;
        return;
    };

    // Per-call success/error.
    for (sg.member_indices, 0..) |i, j| {
        switch (batch_results[j]) {
            .ok => |b| calls[i].result = b,
            .err => |e| calls[i].err = e,
        }
    }
}

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

const testing = std.testing;

/// Test helper: the items of a ToolResultBlock's first text part.
fn trText(tr: conversation.ToolResultBlock) []const u8 {
    for (tr.parts.items) |p| {
        if (p == .text) return p.text.items;
    }
    return "";
}

/// Test harness for the injectable `stream_fn` seam.
///
/// `provider_mod.StreamFn` carries no user context (it mirrors the real
/// free function exactly), so the stub parks its state in a module-level
/// pointer that `stubStreamStep` reads. The Zig test runner executes tests
/// serially in one process, so a single global slot is safe; each test
/// sets it via `install` before driving the agent.
var stub_active: ?*StubProvider = null;

const StubProvider = struct {
    allocator: Allocator,
    scripted: []const ScriptedTurn,
    next: usize = 0,
    /// Number of leading stream calls that should fail with
    /// `error.ContextOverflow` before any scripted turn is served. Used to
    /// drive the auto-compaction path. Decremented on each overflow.
    overflow_calls: usize = 0,

    const ScriptedTurn = struct {
        blocks: []const TestBlock,
    };

    const TestBlock = union(enum) {
        Text: []const u8,
        ToolUse: struct {
            id: []const u8,
            name: []const u8,
            input: []const u8,
        },
    };

    /// Point the global seam at this stub and return the function to assign
    /// to `agent.stream_fn`. Call once per test, after constructing the
    /// stub on the stack.
    fn install(self: *StubProvider) provider_mod.StreamFn {
        stub_active = self;
        return stubStreamStep;
    }
};

fn stubStreamStep(
    allocator: Allocator,
    _: Io,
    _: *const config_mod.Config,
    conv: *conversation.Conversation,
    _: *provider_mod.Receiver,
) anyerror!void {
    const self = stub_active orelse return error.NoStubInstalled;
    _ = allocator;
    if (self.overflow_calls > 0) {
        self.overflow_calls -= 1;
        return error.ContextOverflow;
    }
    if (self.next >= self.scripted.len) return error.NoMoreScriptedTurns;
    const turn = self.scripted[self.next];
    self.next += 1;

    var blocks: std.ArrayList(conversation.ContentBlock) = .empty;
    errdefer {
        for (blocks.items) |*b| b.deinit(self.allocator);
        blocks.deinit(self.allocator);
    }
    for (turn.blocks) |tb| {
        switch (tb) {
            .Text => |s| {
                try blocks.append(self.allocator, .{
                    .Text = try conversation.textualBlockFromSlice(self.allocator, s),
                });
            },
            .ToolUse => |tu| {
                const id = try self.allocator.dupe(u8, tu.id);
                errdefer self.allocator.free(id);
                const name = try self.allocator.dupe(u8, tu.name);
                errdefer self.allocator.free(name);
                var input_buf: conversation.TextualBlock = .empty;
                errdefer input_buf.deinit(self.allocator);
                try input_buf.appendSlice(self.allocator, tu.input);
                try blocks.append(self.allocator, .{ .ToolUse = .{
                    .id = id,
                    .name = name,
                    .input = input_buf,
                } });
            },
        }
    }
    const moved = try blocks.toOwnedSlice(self.allocator);
    defer self.allocator.free(moved);
    try conv.addAssistantMessage(moved);
}

/// Build a stack registry + active `Config` snapshot wired together, for
/// tests that drive the agent. The caller owns both and must keep them
/// alive for the agent's lifetime.
const TestHarness = struct {
    registry: ToolRegistry,
    config: config_mod.Config,

    fn init(allocator: Allocator) TestHarness {
        return .{ .registry = ToolRegistry.init(allocator), .config = undefined };
    }

    /// Finalize the config snapshot to point at this harness's registry.
    /// Must be called after `init` and before constructing the agent, once
    /// the harness has a stable address.
    fn activate(self: *TestHarness) void {
        self.config = .{
            .provider = .{ .openai_chat = .{ .api_key = "k", .base_url = "u", .model = "m" } },
            .registry = &self.registry,
        };
    }

    fn deinit(self: *TestHarness) void {
        self.registry.deinit();
    }
};

const EchoTool = struct {
    prefix_owned: []u8,
    name_owned: []u8,

    fn create(allocator: Allocator, name: []const u8, prefix: []const u8) !Tool {
        const self = try allocator.create(EchoTool);
        errdefer allocator.destroy(self);
        self.name_owned = try allocator.dupe(u8, name);
        errdefer allocator.free(self.name_owned);
        self.prefix_owned = try allocator.dupe(u8, prefix);
        return .{
            .decl = .{
                .name = self.name_owned,
                .description = "echo",
                .schema_json = "{}",
            },
            .ctx = self,
            .vtable = &vt,
        };
    }

    const vt: Tool.VTable = .{ .invoke = invoke, .deinit = deinit };

    fn invoke(ctx: *anyopaque, input: []const u8, allocator: Allocator) anyerror![]tool_mod.ResultPart {
        const self: *EchoTool = @ptrCast(@alignCast(ctx));
        const msg = try std.fmt.allocPrint(allocator, "{s}{s}", .{ self.prefix_owned, input });
        return tool_mod.ownedTextResult(allocator, msg);
    }

    fn deinit(ctx: *anyopaque, allocator: Allocator) void {
        const self: *EchoTool = @ptrCast(@alignCast(ctx));
        allocator.free(self.name_owned);
        allocator.free(self.prefix_owned);
        allocator.destroy(self);
    }
};

const BarrierTool = struct {
    name_owned: []u8,
    barrier: *Barrier,

    const Barrier = struct {
        target: u32,
        arrived: std.atomic.Value(u32) = .init(0),
        thread_ids: [4]std.atomic.Value(u64) = .{
            .init(0), .init(0), .init(0), .init(0),
        },
    };

    fn create(allocator: Allocator, name: []const u8, barrier: *Barrier) !Tool {
        const self = try allocator.create(BarrierTool);
        errdefer allocator.destroy(self);
        self.name_owned = try allocator.dupe(u8, name);
        self.barrier = barrier;
        return .{
            .decl = .{
                .name = self.name_owned,
                .description = "barrier",
                .schema_json = "{}",
            },
            .ctx = self,
            .vtable = &vt,
        };
    }

    const vt: Tool.VTable = .{ .invoke = invoke, .deinit = deinit };

    fn invoke(ctx: *anyopaque, _: []const u8, allocator: Allocator) anyerror![]tool_mod.ResultPart {
        const self: *BarrierTool = @ptrCast(@alignCast(ctx));
        const arrived = self.barrier.arrived.fetchAdd(1, .acq_rel);
        if (arrived < self.barrier.thread_ids.len) {
            self.barrier.thread_ids[arrived].store(std.Thread.getCurrentId(), .release);
        }

        var i: usize = 0;
        while (self.barrier.arrived.load(.acquire) < self.barrier.target) : (i += 1) {
            if (i > 50_000) return error.BarrierTimeout;
            std.Thread.yield() catch {};
        }
        return tool_mod.textResult(allocator, "done");
    }

    fn deinit(ctx: *anyopaque, allocator: Allocator) void {
        const self: *BarrierTool = @ptrCast(@alignCast(ctx));
        allocator.free(self.name_owned);
        allocator.destroy(self);
    }
};

const FailingTool = struct {
    name_owned: []u8,

    fn create(allocator: Allocator, name: []const u8) !Tool {
        const self = try allocator.create(FailingTool);
        errdefer allocator.destroy(self);
        self.name_owned = try allocator.dupe(u8, name);
        return .{
            .decl = .{
                .name = self.name_owned,
                .description = "fails",
                .schema_json = "{}",
            },
            .ctx = self,
            .vtable = &vt,
        };
    }

    const vt: Tool.VTable = .{ .invoke = invoke, .deinit = deinit };

    fn invoke(_: *anyopaque, _: []const u8, _: Allocator) anyerror![]tool_mod.ResultPart {
        return error.ToolExploded;
    }

    fn deinit(ctx: *anyopaque, allocator: Allocator) void {
        const self: *FailingTool = @ptrCast(@alignCast(ctx));
        allocator.free(self.name_owned);
        allocator.destroy(self);
    }
};

const NoopReceiver = struct {
    fn make() provider_mod.Receiver {
        return .{ .ptr = @ptrCast(@constCast(&dummy)), .vtable = &vt };
    }
    var dummy: u8 = 0;
    const vt: provider_mod.ReceiverVTable = .{
        .onMessageStart = noop1,
        .onBlockStart = noop2,
        .onToolDetails = noopToolDetails,
        .onContentDelta = noop3,
        .onBlockComplete = noop4,
        .onMessageComplete = noop5,
        .onError = noop6,
    };
    fn noop1(_: *anyopaque, _: conversation.MessageRole) anyerror!void {}
    fn noop2(_: *anyopaque, _: provider_mod.ContentBlockType, _: usize) anyerror!void {}
    fn noopToolDetails(_: *anyopaque, _: usize, _: []const u8, _: []const u8) anyerror!void {}
    fn noop3(_: *anyopaque, _: usize, _: []const u8) anyerror!void {}
    fn noop4(_: *anyopaque, _: usize, _: conversation.ContentBlock) anyerror!void {}
    fn noop5(_: *anyopaque, _: conversation.Message, _: ?provider_mod.Usage) anyerror!void {}
    fn noop6(_: *anyopaque, _: anyerror) void {}
};

/// A configurable ToolSource for testing the grouped-dispatch path.
/// Stores every batch it receives so tests can assert "calls X and Y
/// arrived in the same batch on the same thread".
const TestSource = struct {
    name_owned: []u8,
    decls: []tool_source_mod.ToolDecl,
    decl_strings: std.array_list.Managed([]u8),
    /// Sequence of (thread_id, [tool_name; n]) per batch received.
    /// Only mutated inside `invoke_batch`. Because libpanto guarantees
    /// at most one outstanding `invoke_batch` per source at any time
    /// (one batch per turn per source), no synchronization is needed.
    batches: std.array_list.Managed(Batch),
    allocator: Allocator,

    const Batch = struct {
        thread_id: u64,
        names: std.array_list.Managed([]u8),
    };

    fn create(
        allocator: Allocator,
        source_name: []const u8,
        tool_names: []const []const u8,
    ) !ToolSource {
        const self = try allocator.create(TestSource);
        errdefer allocator.destroy(self);

        var strings = std.array_list.Managed([]u8).init(allocator);
        errdefer {
            for (strings.items) |s| allocator.free(s);
            strings.deinit();
        }

        const name_owned = try allocator.dupe(u8, source_name);
        try strings.append(name_owned);

        const decls = try allocator.alloc(tool_source_mod.ToolDecl, tool_names.len);
        errdefer allocator.free(decls);
        for (tool_names, 0..) |tn, i| {
            const n = try allocator.dupe(u8, tn);
            try strings.append(n);
            const d = try allocator.dupe(u8, "test src tool");
            try strings.append(d);
            const s = try allocator.dupe(u8, "{}");
            try strings.append(s);
            decls[i] = .{ .name = n, .description = d, .schema_json = s };
        }

        self.* = .{
            .name_owned = name_owned,
            .decls = decls,
            .decl_strings = strings,
            .batches = std.array_list.Managed(Batch).init(allocator),
            .allocator = allocator,
        };

        return ToolSource{
            .name = self.name_owned,
            .tools = self.decls,
            .ctx = self,
            .vtable = &vt,
        };
    }

    const vt: ToolSource.VTable = .{
        .invoke_batch = invokeBatch,
        .deinit = deinitSrc,
    };

    fn invokeBatch(
        ctx: *anyopaque,
        calls: []const tool_source_mod.Call,
        results: []tool_source_mod.CallResult,
        allocator: Allocator,
    ) anyerror!void {
        const self: *TestSource = @ptrCast(@alignCast(ctx));
        var batch: Batch = .{
            .thread_id = std.Thread.getCurrentId(),
            .names = std.array_list.Managed([]u8).init(self.allocator),
        };
        for (calls) |c| {
            const copy = try self.allocator.dupe(u8, c.tool_name);
            try batch.names.append(copy);
        }
        try self.batches.append(batch);

        for (calls, 0..) |c, i| {
            const msg = std.fmt.allocPrint(
                allocator,
                "{s}->{s}",
                .{ c.tool_name, c.input },
            ) catch |e| {
                results[i] = .{ .err = e };
                continue;
            };
            results[i] = .{
                .ok = tool_mod.ownedTextResult(allocator, msg) catch |e| {
                    results[i] = .{ .err = e };
                    continue;
                },
            };
        }
    }

    fn deinitSrc(ctx: *anyopaque, _: Allocator) void {
        const self: *TestSource = @ptrCast(@alignCast(ctx));
        for (self.decl_strings.items) |s| self.allocator.free(s);
        self.decl_strings.deinit();
        for (self.batches.items) |*b| {
            for (b.names.items) |n| self.allocator.free(n);
            b.names.deinit();
        }
        self.batches.deinit();
        self.allocator.free(self.decls);
        self.allocator.destroy(self);
    }
};

/// A source that always fails the whole batch by returning an error
/// from invoke_batch (rather than recording per-call errors). Used to
/// verify libpanto's whole-batch-failure path.
const FailingSource = struct {
    name_owned: []u8,
    decls: []tool_source_mod.ToolDecl,
    decl_strings: std.array_list.Managed([]u8),
    allocator: Allocator,

    fn create(allocator: Allocator, source_name: []const u8, tool_names: []const []const u8) !ToolSource {
        const self = try allocator.create(FailingSource);
        errdefer allocator.destroy(self);

        var strings = std.array_list.Managed([]u8).init(allocator);
        errdefer {
            for (strings.items) |s| allocator.free(s);
            strings.deinit();
        }

        const name_owned = try allocator.dupe(u8, source_name);
        try strings.append(name_owned);

        const decls = try allocator.alloc(tool_source_mod.ToolDecl, tool_names.len);
        errdefer allocator.free(decls);
        for (tool_names, 0..) |tn, i| {
            const n = try allocator.dupe(u8, tn);
            try strings.append(n);
            const d = try allocator.dupe(u8, "fails");
            try strings.append(d);
            const s = try allocator.dupe(u8, "{}");
            try strings.append(s);
            decls[i] = .{ .name = n, .description = d, .schema_json = s };
        }

        self.* = .{
            .name_owned = name_owned,
            .decls = decls,
            .decl_strings = strings,
            .allocator = allocator,
        };
        return ToolSource{ .name = self.name_owned, .tools = self.decls, .ctx = self, .vtable = &vt };
    }

    const vt: ToolSource.VTable = .{ .invoke_batch = invokeBatch, .deinit = deinitSrc };

    fn invokeBatch(
        _: *anyopaque,
        _: []const tool_source_mod.Call,
        _: []tool_source_mod.CallResult,
        _: Allocator,
    ) anyerror!void {
        return error.SourceExploded;
    }

    fn deinitSrc(ctx: *anyopaque, _: Allocator) void {
        const self: *FailingSource = @ptrCast(@alignCast(ctx));
        for (self.decl_strings.items) |s| self.allocator.free(s);
        self.decl_strings.deinit();
        self.allocator.free(self.decls);
        self.allocator.destroy(self);
    }
};

test "registry register and lookup" {
    var h = TestHarness.init(testing.allocator);
    defer h.deinit();
    try h.registry.register(try EchoTool.create(testing.allocator, "echo", "ECHO:"));
    try testing.expectEqual(@as(usize, 1), h.registry.count());
    try testing.expect(h.registry.lookup("echo") != null);
}

test "duplicate register returns error" {
    var h = TestHarness.init(testing.allocator);
    defer h.deinit();
    try h.registry.register(try EchoTool.create(testing.allocator, "echo", "A:"));

    var dup = try EchoTool.create(testing.allocator, "echo", "B:");
    try testing.expectError(error.DuplicateTool, h.registry.register(dup));
    dup.vtable.deinit(dup.ctx, testing.allocator);
}

test "runStep dispatches a tool call and loops to a final text turn" {
    const allocator = testing.allocator;

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{
            .{ .ToolUse = .{ .id = "tc_1", .name = "echo", .input = "hello" } },
        } },
        .{ .blocks = &.{
            .{ .Text = "ok" },
        } },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    try h.registry.register(try EchoTool.create(allocator, "echo", "ECHO:"));
    h.activate();
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("call a tool");

    var recv = NoopReceiver.make();
    try agent.runStep(&conv, &recv);

    try testing.expectEqual(@as(usize, 4), conv.messages.items.len);

    try testing.expectEqual(conversation.MessageRole.assistant, conv.messages.items[1].role);
    try testing.expectEqual(@as(usize, 1), conv.messages.items[1].content.items.len);
    try testing.expectEqualStrings("tc_1", conv.messages.items[1].content.items[0].ToolUse.id);

    try testing.expectEqual(conversation.MessageRole.user, conv.messages.items[2].role);
    try testing.expectEqual(@as(usize, 1), conv.messages.items[2].content.items.len);
    const tr = conv.messages.items[2].content.items[0].ToolResult;
    try testing.expectEqualStrings("tc_1", tr.tool_use_id);
    try testing.expectEqualStrings("ECHO:hello", trText(tr));

    try testing.expectEqual(conversation.MessageRole.assistant, conv.messages.items[3].role);
    try testing.expectEqualStrings("ok", conv.messages.items[3].content.items[0].Text.items);
}

test "runStep dispatches multiple tool calls in parallel" {
    const allocator = testing.allocator;

    var barrier: BarrierTool.Barrier = .{ .target = 3 };

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{
            .{ .ToolUse = .{ .id = "a", .name = "barrierA", .input = "" } },
            .{ .ToolUse = .{ .id = "b", .name = "barrierB", .input = "" } },
            .{ .ToolUse = .{ .id = "c", .name = "barrierC", .input = "" } },
        } },
        .{ .blocks = &.{
            .{ .Text = "done" },
        } },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    try h.registry.register(try BarrierTool.create(allocator, "barrierA", &barrier));
    try h.registry.register(try BarrierTool.create(allocator, "barrierB", &barrier));
    try h.registry.register(try BarrierTool.create(allocator, "barrierC", &barrier));
    h.activate();
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("go");

    var recv = NoopReceiver.make();
    try agent.runStep(&conv, &recv);

    const tr_msg = conv.messages.items[2];
    try testing.expectEqual(@as(usize, 3), tr_msg.content.items.len);
    try testing.expectEqualStrings("a", tr_msg.content.items[0].ToolResult.tool_use_id);
    try testing.expectEqualStrings("b", tr_msg.content.items[1].ToolResult.tool_use_id);
    try testing.expectEqualStrings("c", tr_msg.content.items[2].ToolResult.tool_use_id);

    const t0 = barrier.thread_ids[0].load(.acquire);
    const t1 = barrier.thread_ids[1].load(.acquire);
    const t2 = barrier.thread_ids[2].load(.acquire);
    try testing.expect(t0 != 0 and t1 != 0 and t2 != 0);
    try testing.expect(t0 != t1 and t1 != t2 and t0 != t2);
}

test "runStep propagates tool errors and aborts the turn" {
    const allocator = testing.allocator;

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{
            .{ .ToolUse = .{ .id = "x", .name = "boom", .input = "" } },
        } },
        .{ .blocks = &.{.{ .Text = "should-not-see" }} },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    try h.registry.register(try FailingTool.create(allocator, "boom"));
    h.activate();
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("break it");

    var recv = NoopReceiver.make();
    try testing.expectError(error.ToolExploded, agent.runStep(&conv, &recv));

    try testing.expectEqual(@as(usize, 2), conv.messages.items.len);
}

test "runStep errors UnknownTool when the model calls something unregistered" {
    const allocator = testing.allocator;

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{
            .{ .ToolUse = .{ .id = "z", .name = "ghost", .input = "" } },
        } },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    h.activate();
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("call a ghost");

    var recv = NoopReceiver.make();
    try testing.expectError(error.UnknownTool, agent.runStep(&conv, &recv));
}

test "runStep with no tool calls returns after one provider step" {
    const allocator = testing.allocator;

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{.{ .Text = "hi" }} },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    h.activate();
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("hello");

    var recv = NoopReceiver.make();
    try agent.runStep(&conv, &recv);

    try testing.expectEqual(@as(usize, 2), conv.messages.items.len);
    try testing.expectEqualStrings("hi", conv.messages.items[1].content.items[0].Text.items);
}

test "runStep surfaces EmptyAssistantResponse when provider commits an empty message" {
    const allocator = testing.allocator;

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{} },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    h.activate();
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("hi");

    var recv = NoopReceiver.make();
    try testing.expectError(error.EmptyAssistantResponse, agent.runStep(&conv, &recv));
}

// ------------ ToolSource tests ------------

test "runStep delivers all source-backed calls in one batch on one thread" {
    const allocator = testing.allocator;

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{
            .{ .ToolUse = .{ .id = "a", .name = "lua_x", .input = "1" } },
            .{ .ToolUse = .{ .id = "b", .name = "lua_y", .input = "2" } },
            .{ .ToolUse = .{ .id = "c", .name = "lua_x", .input = "3" } },
        } },
        .{ .blocks = &.{.{ .Text = "done" }} },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    try h.registry.registerSource(try TestSource.create(allocator, "panto-lua", &.{ "lua_x", "lua_y" }));
    h.activate();
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("go");

    var recv = NoopReceiver.make();
    try agent.runStep(&conv, &recv);

    // Locate the source and inspect its observed batches.
    const view = h.registry.lookup("lua_x") orelse return error.NotFound;
    const src_ptr = view.entry.source.source;
    const test_src: *TestSource = @ptrCast(@alignCast(src_ptr.ctx));

    try testing.expectEqual(@as(usize, 1), test_src.batches.items.len);
    const b = test_src.batches.items[0];
    try testing.expectEqual(@as(usize, 3), b.names.items.len);
    try testing.expectEqualStrings("lua_x", b.names.items[0]);
    try testing.expectEqualStrings("lua_y", b.names.items[1]);
    try testing.expectEqualStrings("lua_x", b.names.items[2]);

    // ToolResults arrived in the original call order.
    const tr_msg = conv.messages.items[2];
    try testing.expectEqual(@as(usize, 3), tr_msg.content.items.len);
    try testing.expectEqualStrings("a", tr_msg.content.items[0].ToolResult.tool_use_id);
    try testing.expectEqualStrings("lua_x->1", trText(tr_msg.content.items[0].ToolResult));
    try testing.expectEqualStrings("b", tr_msg.content.items[1].ToolResult.tool_use_id);
    try testing.expectEqualStrings("lua_y->2", trText(tr_msg.content.items[1].ToolResult));
    try testing.expectEqualStrings("c", tr_msg.content.items[2].ToolResult.tool_use_id);
    try testing.expectEqualStrings("lua_x->3", trText(tr_msg.content.items[2].ToolResult));
}

test "runStep: distinct sources run on distinct threads in parallel" {
    const allocator = testing.allocator;

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{
            .{ .ToolUse = .{ .id = "a", .name = "src_a_t", .input = "" } },
            .{ .ToolUse = .{ .id = "b", .name = "src_b_t", .input = "" } },
        } },
        .{ .blocks = &.{.{ .Text = "done" }} },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    try h.registry.registerSource(try TestSource.create(allocator, "src_a", &.{"src_a_t"}));
    try h.registry.registerSource(try TestSource.create(allocator, "src_b", &.{"src_b_t"}));
    h.activate();
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("go");

    var recv = NoopReceiver.make();
    try agent.runStep(&conv, &recv);

    const view_a = h.registry.lookup("src_a_t") orelse return error.NotFound;
    const view_b = h.registry.lookup("src_b_t") orelse return error.NotFound;
    const sa: *TestSource = @ptrCast(@alignCast(view_a.entry.source.source.ctx));
    const sb: *TestSource = @ptrCast(@alignCast(view_b.entry.source.source.ctx));

    try testing.expectEqual(@as(usize, 1), sa.batches.items.len);
    try testing.expectEqual(@as(usize, 1), sb.batches.items.len);
    // The two sources ran on distinct OS threads.
    try testing.expect(sa.batches.items[0].thread_id != sb.batches.items[0].thread_id);
}

test "runStep: source whole-batch error aborts the turn" {
    const allocator = testing.allocator;

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{
            .{ .ToolUse = .{ .id = "a", .name = "fa", .input = "" } },
            .{ .ToolUse = .{ .id = "b", .name = "fb", .input = "" } },
        } },
        .{ .blocks = &.{.{ .Text = "never" }} },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    try h.registry.registerSource(try FailingSource.create(allocator, "fs", &.{ "fa", "fb" }));
    h.activate();
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("kaboom");

    var recv = NoopReceiver.make();
    try testing.expectError(error.SourceExploded, agent.runStep(&conv, &recv));

    // Conversation stops at user + assistant(tool_use). No ToolResult appended.
    try testing.expectEqual(@as(usize, 2), conv.messages.items.len);
}

test "runStep: mixed single Tools and source-backed tools coexist in one turn" {
    const allocator = testing.allocator;

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{
            .{ .ToolUse = .{ .id = "a", .name = "single", .input = "X" } },
            .{ .ToolUse = .{ .id = "b", .name = "src_t1", .input = "Y" } },
            .{ .ToolUse = .{ .id = "c", .name = "src_t2", .input = "Z" } },
        } },
        .{ .blocks = &.{.{ .Text = "done" }} },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    try h.registry.register(try EchoTool.create(allocator, "single", "S:"));
    try h.registry.registerSource(try TestSource.create(allocator, "src", &.{ "src_t1", "src_t2" }));
    h.activate();
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("go");

    var recv = NoopReceiver.make();
    try agent.runStep(&conv, &recv);

    const tr_msg = conv.messages.items[2];
    try testing.expectEqual(@as(usize, 3), tr_msg.content.items.len);
    try testing.expectEqualStrings("S:X", trText(tr_msg.content.items[0].ToolResult));
    try testing.expectEqualStrings("src_t1->Y", trText(tr_msg.content.items[1].ToolResult));
    try testing.expectEqualStrings("src_t2->Z", trText(tr_msg.content.items[2].ToolResult));
}

test "setConfig swaps the visible tool set between turns" {
    // The core RCU promise: the agent reads `*const Config` fresh each
    // turn, so swapping the pointer mid-conversation changes the tool set
    // the next turn sees. Config A exposes only `echo`; config B only
    // `late`. After `setConfig(&cfg_b)`, a turn that calls `late` resolves
    // — proving both the swap and per-turn re-consultation.
    const allocator = testing.allocator;

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{.{ .ToolUse = .{ .id = "2", .name = "late", .input = "B" } }} },
        .{ .blocks = &.{.{ .Text = "done" }} },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();

    // Config A: only `echo`.
    var reg_a = ToolRegistry.init(allocator);
    defer reg_a.deinit();
    try reg_a.register(try EchoTool.create(allocator, "echo", "A:"));
    const cfg_a: config_mod.Config = .{
        .provider = .{ .openai_chat = .{ .api_key = "k", .base_url = "u", .model = "m" } },
        .registry = &reg_a,
    };

    // Config B: only `late`.
    var reg_b = ToolRegistry.init(allocator);
    defer reg_b.deinit();
    try reg_b.register(try EchoTool.create(allocator, "late", "B:"));
    const cfg_b: config_mod.Config = .{
        .provider = .{ .openai_chat = .{ .api_key = "k", .base_url = "u", .model = "m" } },
        .registry = &reg_b,
    };

    var agent = Agent.init(allocator, io, &cfg_a);
    agent.stream_fn = stub.install();

    // Under A: `echo` visible, `late` not.
    try testing.expect(agent.config.registry.lookup("echo") != null);
    try testing.expect(agent.config.registry.lookup("late") == null);

    // Swap. Under B: the visibility inverts.
    agent.setConfig(&cfg_b);
    try testing.expect(agent.config.registry.lookup("echo") == null);
    try testing.expect(agent.config.registry.lookup("late") != null);

    // A real turn under B resolves `late` (which would have been
    // UnknownTool under A), then loops to the final text turn.
    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("go");
    var recv = NoopReceiver.make();
    try agent.runStep(&conv, &recv);

    const tr = conv.messages.items[2].content.items[0].ToolResult;
    try testing.expectEqualStrings("2", tr.tool_use_id);
    try testing.expectEqualStrings("B:B", trText(tr));
}

test "compact: summarizes prefix, keeps suffix, system survives" {
    const allocator = testing.allocator;

    // The stub returns a single text turn — used as the summary text.
    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{.{ .Text = "SUMMARY OF EARLIER" }} },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    h.activate();
    // keep_verbatim sized so only the last (short) turn fits: q2+a2 are
    // 3 words each => ceil(3*1.3)=4 tokens each => 8 total <= 10, while
    // adding the longer first turn exceeds it.
    h.config.compaction = .{ .keep_verbatim = 10 };
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addSystemMessage("you are helpful");
    try conv.addUserMessage("first question here with several words");
    try conv.addAssistantMessage(&.{
        .{ .Text = try conversation.textualBlockFromSlice(allocator, "first answer with several words") },
    });
    try conv.addUserMessage("second recent question");
    try conv.addAssistantMessage(&.{
        .{ .Text = try conversation.textualBlockFromSlice(allocator, "second recent answer") },
    });

    const res = try agent.compact(&conv, "Summarize the conversation.", null);
    try testing.expect(res.compacted);

    // Expected rebuilt: [system, compaction summary(user), user q2, asst a2]
    try testing.expectEqual(@as(usize, 4), conv.messages.items.len);
    try testing.expectEqual(conversation.MessageRole.system, conv.messages.items[0].role);
    try testing.expectEqualStrings(
        "you are helpful",
        conv.messages.items[0].content.items[0].System.text.items,
    );
    try testing.expectEqual(conversation.MessageRole.user, conv.messages.items[1].role);
    try testing.expectEqualStrings(
        "SUMMARY OF EARLIER",
        conv.messages.items[1].content.items[0].CompactionSummary.text.items,
    );
    try testing.expectEqualStrings(
        "second recent question",
        conv.messages.items[2].content.items[0].Text.items,
    );
    try testing.expectEqualStrings(
        "second recent answer",
        conv.messages.items[3].content.items[0].Text.items,
    );
}

test "compact: no-op when conversation already fits the budget" {
    const allocator = testing.allocator;

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{.{ .Text = "should not be used" }} },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    h.activate();
    h.config.compaction = .{ .keep_verbatim = 1_000_000 };
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addSystemMessage("sys");
    try conv.addUserMessage("hi");
    try conv.addAssistantMessage(&.{
        .{ .Text = try conversation.textualBlockFromSlice(allocator, "hello") },
    });

    const res = try agent.compact(&conv, "Summarize.", null);
    try testing.expect(!res.compacted);
    try testing.expectEqual(@as(usize, 3), conv.messages.items.len);
    // Stub was never consumed.
    try testing.expectEqual(@as(usize, 0), stub.next);
}

test "compact: extra instructions are appended to the system prompt" {
    const allocator = testing.allocator;

    // Capture the system prompt the stub sees by scripting a turn and
    // inspecting the throwaway conversation isn't directly possible via the
    // current stub; instead we just assert compaction succeeds with extra
    // instructions present (smoke test of the append path).
    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{.{ .Text = "S" }} },
    };
    var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    h.activate();
    h.config.compaction = .{ .keep_verbatim = 1 };
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("question one two three");
    try conv.addAssistantMessage(&.{
        .{ .Text = try conversation.textualBlockFromSlice(allocator, "answer one two three") },
    });
    try conv.addUserMessage("question two");
    try conv.addAssistantMessage(&.{
        .{ .Text = try conversation.textualBlockFromSlice(allocator, "answer two") },
    });

    const res = try agent.compact(&conv, "Base prompt.", "keep bug #3 details");
    try testing.expect(res.compacted);
}

test "runStep: auto-compacts on context overflow and retries once" {
    const allocator = testing.allocator;

    // First stream call overflows; then the compaction request returns a
    // summary; then the retried main request returns a final text turn.
    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{.{ .Text = "COMPACTED SUMMARY" }} }, // compaction call
        .{ .blocks = &.{.{ .Text = "final answer" }} }, // retried main call
    };
    var stub = StubProvider{
        .allocator = allocator,
        .scripted = &scripted,
        .overflow_calls = 1,
    };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    h.activate();
    h.config.compaction = .{ .keep_verbatim = 10 };
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();
    agent.compaction_system_prompt = "Summarize the conversation.";

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addSystemMessage("you are helpful");
    try conv.addUserMessage("first question with several words here");
    try conv.addAssistantMessage(&.{
        .{ .Text = try conversation.textualBlockFromSlice(allocator, "first answer with several words") },
    });
    try conv.addUserMessage("second recent question");

    var recv = NoopReceiver.make();
    try agent.runStep(&conv, &recv);

    try testing.expect(agent.auto_compacted);
    // After compaction + retry: [system, summary, user q2, assistant final].
    const msgs = conv.messages.items;
    try testing.expectEqual(conversation.MessageRole.system, msgs[0].role);
    try testing.expectEqualStrings(
        "COMPACTED SUMMARY",
        msgs[1].content.items[0].CompactionSummary.text.items,
    );
    try testing.expectEqualStrings("second recent question", msgs[2].content.items[0].Text.items);
    try testing.expectEqualStrings("final answer", msgs[msgs.len - 1].content.items[0].Text.items);
}

test "runStep: context overflow without compaction prompt propagates" {
    const allocator = testing.allocator;

    const scripted = [_]StubProvider.ScriptedTurn{
        .{ .blocks = &.{.{ .Text = "unused" }} },
    };
    var stub = StubProvider{
        .allocator = allocator,
        .scripted = &scripted,
        .overflow_calls = 1,
    };
    var threaded: std.Io.Threaded = .init(allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var h = TestHarness.init(allocator);
    defer h.deinit();
    h.activate();
    var agent = Agent.init(allocator, io, &h.config);
    agent.stream_fn = stub.install();
    // No compaction_system_prompt set -> overflow propagates.

    var conv = conversation.Conversation.init(allocator);
    defer conv.deinit();
    try conv.addUserMessage("hi");

    var recv = NoopReceiver.make();
    try testing.expectError(error.ContextOverflow, agent.runStep(&conv, &recv));
}