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
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
--- knl — the Lua kernel: session + device, the beat, Outcome, shapes, views.
---
--- What this is
--- The driving half of the kernel/shell split. Rust is the pure syscall
--- layer (session / append / events / view / query / reserve / spend /
--- close) and states the kernel's own invariants in its module doc; this
--- module runs a BEAT — one model call plus the tools that call asks for —
--- over that layer and hands back an `Outcome`. There is no loop here: a
--- caller composes beats on the spot, which is why the primitive is one
--- beat and not a run.
---
--- Two arguments, two owners
--- `knl.open{ owner?, budget?, store? }` hands back the kernel's session
--- userdata verbatim — the durable half: the fact-log and the quota, owned
--- by the kernel, advanced only by appending. `knl.device{ llm?, tools?,
--- tool_policy?, fold?, filters?, system?, cost? }` builds the policy half
--- — a stateless value whose defaults are resolved once at construction
--- and then frozen. `knl.beat(session, device)` takes both. They are not
--- bundled into one handle because they differ in owner (kernel / caller),
--- lifetime (durable / per-process) and mutability (append-only / frozen),
--- and the config is CONSUMED at construction rather than carried: a
--- device holds resolved fields, never the table it was configured with.
--- Per-beat policy variation is not an override argument: derive another
--- device with `d:with{ llm = strong }` and beat with that one.
---
--- Where the log lives
--- `store` is optional and leaving it out is the answer for a real session:
--- the log goes into the database the host owns, one file per project. Every
--- session a script opens is a stream in that one file, so a tree opened from
--- a default parent is a tree in one database, and `knl.resume{ session = id }`
--- reopens it by id alone.
---
--- `store = "mem"` is the other choice and has to be asked for by name: an
--- in-memory database, for TESTS AND MOCKS — one session, one process,
--- nothing shared. It is not a lighter version of the default. Two writers
--- meet a per-table lock there that no busy timeout waits out, so opening a
--- child of a `mem` parent is refused rather than made to wait (the kernel's
--- own header says the same, and `supervisor` says it again for siblings).
--- `store = { sqlite = <path> }` is a file the caller picked.
---
--- Lifecycle belongs to the session
--- The canonical bracket is the callback form — the kernel opens, runs the
--- body, and closes, so an error escaping the body still records the
--- boundary:
---
--- local result = knl.session({ owner = "u", budget = { amount = 10 } },
--- function(s) return knl.beat(s, d) end)
---
--- `knl.session` resumes instead of opening when the opts name a session.
--- `local s <close> = knl.open{...}` is the alternative and the Rust Drop
--- backstop is the last resort; a body error always wins over a close that
--- failed on its way out (the suppressed-exception rule, and the loser is
--- logged as a record rather than dropped).
---
--- Beats are declared, not numbered
--- The kernel does not count beats. `knl.beat` mints one id per beat with
--- `knl.new_beat_id()` (time-ordered, session-free) and stamps it on every
--- event that beat writes — llm_request, llm_response, the tool pair, and
--- a failed call's note. The kernel stores a `beat` it is given and asks
--- only that it be a string; grouping and ordering read it back, nothing
--- more. `resp.beat` carries the same id out to the caller.
---
--- The steps of a beat
--- [0] the gate: a knl session first, a knl device second, an `llm` on
--- the device — any of the three missing is `Outcome.err("conf")`
--- [0.5] the beat names itself (`knl.new_beat_id`)
--- [1] request = `device.fold(session:events(), device)` — a read that
--- hit the row cap is refused here rather than folded
--- [2] the filter chain, each `fn(request) -> request`
--- [3] `session:reserve(device.cost(request))` — the beat's whole
--- deduction, taken before the call; a refusal stops here, with
--- nothing recorded and no call made
--- [4] append `llm_request`
--- [5] `device.llm(request)`
--- [6] append `llm_response`, or `llm_call_failed` with the failure's
--- classification on it
--- [7] the tools that response asked for: `tool_call` / `tool_result`
---
--- Outcome — the four statuses
--- A beat answers with a value, never a raise, and the value is one of
--- four tagged tables. `Outcome.match(o, arms)` is exhaustive: all four
--- arms are required, and an unknown status is a loud error — the
--- dynamic-language stand-in for a compiler's exhaustiveness check.
---
--- ok the beat ran. `out` is the call's answer (content / usage /
--- stop_reason) plus the `beat` id and the tool summary
--- refused the model answered and declined to make progress. `reason`
--- is the adapter's provider-neutral classification of the
--- refusal ("model" / "content_filter") and `detail` is the
--- whole answer, so a caller can inspect what came back
--- error the mechanism failed: the beat did not come off
--- stopped the beat stopped ON PURPOSE before calling — the quota
--- would not cover it. Nothing broke and the model was never
--- asked; this is the branch a caller's loop exits on, and
--- `tag` names the grant that stopped it
---
--- `Outcome.err(kind, detail)` carries TWO vocabularies and they answer
--- different questions. `kind` names the STAGE that failed — "conf" (the
--- device or a caller function it holds), "filter", "call" (the llm), or
--- "state" (a record that could not be laid down). What the failure WAS,
--- and whether asking again could work, is in `detail`, and the two stages
--- that can answer that do:
---
--- "state" the kernel's own reading — `detail.kind` one of
--- `knl.shapes.error_kinds`, `detail.retryable`
--- "call" the call's classification — `detail.kind` one of
--- `knl.shapes.call_error_kinds`, `detail.retryable`, and
--- `detail.retry_after` when the provider named one
---
--- A loop deciding on a retry reads `detail.retryable` (or names
--- `detail.kind`s) and never the stage: "state" and "call" say where, not
--- whether. The two vocabularies are separate on purpose — a contended
--- store and a rate-limited provider are not the same failure — and
--- `detail.kind` is the field both answer in, so one predicate reads both.
---
--- What a stored event looks like
--- One envelope, one place for structure. An event is `{ kind, beat?,
--- meta?, data? }` and nothing else at the top level — a stray key is
--- refused, not stored — and the kernel stamps `seq` / `epoch_ms` /
--- `_schema_version` on it and keeps the envelope as columns (stream,
--- seq, epoch_ms, kind, schema_version, beat, meta, data).
---
--- The envelope is the half that does not move. `beat` is the correlation
--- key this layer stamps, `meta` is a SHALLOW map of labels (string /
--- number / boolean values; a nested one is refused), and everything a
--- kind is actually ABOUT is structured JSON under `data`, whose shape
--- belongs to whoever writes that kind. The kernel validates the envelope
--- and the `data` of its own kinds (`session_*`, `budget_*`) and nothing
--- else; the shapes for the kinds a beat writes are declared here, in
--- `knl.shapes.events`, and asserted in dev mode at the append sites.
---
--- The point of the split is where a change can hurt. A view that reads
--- the envelope or `meta` is untouched by a schema change; a view that
--- reads a path inside `data` changes together with the shape of the kind
--- it reads — `knl.views.usage` with `llm_response`, `tool_pairs` with the
--- tool pair, `ledger` with `budget_*`. A caller's seed is a kind like any
--- other and goes in the same envelope:
---
--- s:append{ kind = "msg_user", data = { content = "hi" } }
--- s:append{ kind = "msg_user", meta = { label = "seed" },
--- data = { content = "hi" } }
---
--- Reading the log back: two tiers, and only two
--- BUILT-IN VIEW — `session:view(name, opts?)`, plus `session:events(from)`
--- beside it. These are the kernel's own reads, they are fixed, and they
--- do not grow: the record from a position on, and `tail` (the last `n`
--- events, verbatim). A fold whose consumer is not fixed in kernel terms
--- never becomes a name here.
---
--- BOTH ARE BOUNDED. `tail` reads `n` rows from the end, and `events`
--- answers `rows, truncated` — at most the kernel's row cap, the same one
--- `query` uses — because a stream grows and every row of a read is decoded
--- and built into a Lua table on the VM's thread. `truncated` is the fact a
--- caller cannot infer: it says the cap cut the read short and the rest is
--- further on, read by paging `from`. `knl.beat` refuses one rather than
--- folding a record whose newest events are missing.
---
--- QUERY VIEW — a named Lua function that runs ONE `SELECT`. The log is a
--- SQLite table whose columns the kernel publishes (`knl.shapes.schema`),
--- and `session:query(sql, params?, opts?)` binds values, refuses anything
--- that is not one SELECT / WITH, and resolves `$stream` (this session)
--- and `$sessions` (`opts.sessions`, the set to read across). That is the
--- whole mechanism: no builder, no query object, no registration hook.
--- `knl.views.beats` / `tool_pairs` / `ledger` / `usage` / `tree` are the
--- five this module ships, and a consumer's own view is a function of
--- exactly the same form — nothing about the five is privileged.
---
--- Token usage is a query view and not a built-in one, deliberately.
--- Every `llm_response` carries the counts its adapter normalized out of
--- the provider's answer, so `knl.views.usage` is an accounting of facts
--- already in the log, in the shell's vocabulary rather than the kernel's
--- — and it is a reading apart from the budget, which is a quota the owner
--- granted and never a tally of tokens (see below).
---
--- The budget
--- The budget is a quota the owner granted the session, not a tally of
--- what it used. beat asks for permission BEFORE it calls —
--- `session:reserve(n)`, after the request is known and before anything is
--- recorded — and a refusal is a planned stop, not a failure and not a
--- model decision: `Outcome.stopped("budget", tag)`, with no `llm_request`
--- event and no call. How much a beat asks for is the device's policy:
--- `device.cost(request)`, one unit per beat by default. What a unit
--- *means* is whatever the owner tagged the grant with — the kernel reads
--- the number and nothing else, and token usage (`knl.views.usage`) is a
--- separate reading that beat never folds back into the budget.
---
--- `reserve` is the WHOLE of a beat's deduction. The kernel's two moves are
--- independent — `reserve(n)` deducts and refuses when the balance is
--- short, `spend(n)` deducts without asking, and neither holds anything for
--- the other to release — so a beat that called both would deduct twice for
--- one call. beat calls `reserve` and nothing else; a caller that meters
--- what a call really cost does it with `spend` from its own loop, knowing
--- it is a second deduction.
---
--- Sessions opened from sessions
--- `knl.open{ parent = s, budget = { from_parent = n } }` opens a session
--- out of `s`'s balance: `s`'s ledger gains a reservation naming the child,
--- the child's log opens with `parent` recorded on it and `n` of its own,
--- and the two are ONE write on the parent's database. A balance that will
--- not cover it records a refusal on the parent and raises `refused` —
--- nothing is opened, and there is no half-opened session to hand back.
--- Nothing comes back when the child closes: an allocation is a spend, the
--- same way a reservation is.
---
--- The kernel keeps no tree. It records two facts — the parent on the
--- child's opening, the child on the parent's ledger entry — and, when a
--- session closes with children that had not ended, their ids on the
--- boundary (`session_closed.data.open_children`, recorded in the same
--- write; a close is never refused for them). Everything else is a
--- supervisor's: `knl.views.tree` is one recursive SELECT over those
--- fields, and a policy over a subtree is a pack above this module rather
--- than a rule inside it.
---
--- What a device promises, function by function
--- Every one of these is the caller's code, and beat holds it to a written
--- contract rather than guessing at a return it does not recognise.
---
--- fold(events, device) -> request
--- pure; the default (`knl.fold`) folds the log into the neutral
--- content-block shape. A raise is `err("conf")`.
--- filter(request) -> request
--- each filter replaces the request wholesale. Returning a non-table
--- is `err("filter")` — loudly, in prod as well as dev, because the
--- value goes into the durable record and onto the wire.
--- cost(request) -> integer >= 1
--- what the beat reserves. Checked in prod, not only asserted in dev:
--- a beat that could ask for zero is how a run stops being finite.
--- The default answers 1, so a grant counts beats.
--- llm(request) -> llm_result | nil, err
--- `knl.shapes.llm_result`: `status` is "ok" or "refused" and there is
--- no third value; `content` is an array of blocks, `usage` is three
--- counts, and a "refused" answer names the refusal's `kind`. A
--- transport or provider failure is `nil, err` (or a raise), which
--- beat records as `llm_call_failed` and reports as `err("call")`.
--- `err` is a `knl.shapes.call_error` when the port classified it —
--- `{ kind, retryable, retry_after?, message, status? }`, which is what
--- lets a retry policy decide — and anything else (a sentence, a raise)
--- is carried as `unknown` and not retryable.
--- tool_policy(tool_use_block, out) -> decision, reason?
--- `nil` (no opinion — run), `"run"` or `"deny"`, and nothing else: a
--- fourth word is a device-contract violation, not a fourth meaning.
--- A policy that RAISES denies — a gate written to veto tools must not
--- fall open on its own bug — and its message becomes the reason.
---
--- When something raises
--- Two kinds of failure meet inside a beat and they are reported
--- differently. A KERNEL SYSCALL raises attributed text — `knl:
--- <method>: <kind>: <message>` — because mlua cannot carry a table out
--- of a Rust callback; beat reads it back with `knl.error` and the
--- reading is what lands in `Outcome.err("state").detail`: `{ kind?,
--- method?, retryable, message }`, with `kind` one of
--- `knl.shapes.error_kinds` and `retryable` true for exactly one of them.
--- beat never acts on `retryable` itself — asking again is the caller's
--- loop's decision, because only the loop knows how many times and for
--- how long it may. A CALLER'S OWN FUNCTION raising (fold, a filter,
--- cost, the llm) is a bug in the device rather than a class of kernel
--- failure, so its detail is the message it raised — plus, in dev mode
--- only, the `traceback` of where it raised.
---
--- knl.shapes is a registry that is EXECUTED
--- Every public interface of this module is declared as an lshape and
--- published through `knl.shapes`, so a caller reads the contract as data
--- rather than out of prose. `knl.shapes.api` goes one further: it names
--- the shape of every argument of every export, and in dev mode each
--- declared export is wrapped once, at load, by a gate that holds the call
--- to its entry. A registry nobody runs is prose with a table around it.
--- Prod installs no wrapper and pays nothing, which is why the checks a
--- call must not get through WITHOUT — a device's config, a filter's
--- return, cost's bound — stay where they are and stay loud in both modes.
--- `knl/spec/api_spec.lua` closes the loop from the other side: an export
--- with no entry, an entry with no export, and a device field
--- `device_config` does not describe are each a failure.
---
--- Two halves of one table, and they have different owners. Everything
--- above is THIS module's — the shapes of what `knl.beat` / `knl.device` /
--- the views take, executed by the dev gate at the foot of this file.
--- `knl.shapes.session` and `knl.shapes.module` are the BRIDGE's, and they
--- are not written here at all: they point at `knl_types`, generated at
--- host start from the argument and return types of `bridge/knl.rs`. That
--- surface is checked in Rust, on every call and in both modes, so the
--- session userdata needs no wrapper here — which is just as well, since
--- wrapping it would mean handing out a proxy table in place of the
--- kernel's own value, and `local s <close>` and `open{ parent = s }` both
--- want the userdata itself.
---
--- Clean by construction: no legacy, no fabrication
--- This module and `knl_adapter` are kept free of consumer legacy on
--- purpose, because a compat shim taken in here becomes the kernel's
--- vocabulary forever. Nothing is invented on a caller's behalf: an llm
--- answer with no `usage` is `err("call")` rather than `usage or {}`, a
--- refusal without a `kind` is the same rather than a default word, a
--- third llm status does not exist, a nameless `tool_use` block is the
--- provider breaking its contract rather than a hole to fill with an empty
--- string, and no request field (`max_tokens` and friends) is injected
--- behind the caller's back. There are no compat aliases: a tool entry
--- declares `input_schema`, and nothing else is read in its place.
---
--- Deliberately not here
--- Fork (branching a history), scope trees and sub-scope allowances,
--- parallel tool execution, streaming, and a structured error type for a
--- tool_result beyond the raised string. Each is deferred until a real
--- loop asks for it, not designed ahead of the need.
--- The Rust syscall bridge, captured before `require("knl")` shadows the
--- name (see the header). `nil` in a VM that has no bridge (e.g. the pure
--- lspec runner): `fold` / `Outcome` / `device` never touch it, and the
--- entry points that do report its absence rather than indexing nil.
local syscall = knl
local lshape = require
local T = lshape.
local shape = lshape.
local M =
--- The bridge function `method` names, resolved at call time.
---
--- The load-time capture above is the primary source; the global is read
--- again as a fallback so a spec that installs a fake bridge after this
--- module loaded still reaches it. Missing either way is a loud error, not
--- an index of nil.
local
--- Read a raised kernel failure back as data: `{ kind?, method?, retryable,
--- message }` — the *When something raises* section of the header.
---
--- The bridge cannot raise a table, so it raises the text `knl: <method>:
--- <kind>: <message>` and publishes `knl.error` to read it back. That
--- reader is resolved through the same lazy `bridge()` lookup
--- `new_beat_id` uses, so a spec that installs a fake bridge after this
--- module loaded still reaches it.
---
--- A VM with no bridge at all (the pure lspec runner) gets the same fields
--- with nothing read out of them, so `Outcome.err("state").detail` has one
--- shape everywhere: unclassified (`kind` and `method` absent), not
--- retryable, and the raised text verbatim. That is also what an
--- unattributed raise gets from the bridge itself — a reader that raised on
--- unfamiliar input would make a second failure inside the handler for the
--- first.
---
--- @param e any the value a pcall'd syscall raised
--- @return table { kind?, method?, retryable, message }
local
-- ============================================================
-- Outcome — the result type of a beat
-- ============================================================
--
-- Plain-data status tag tables, never metatable methods: an Outcome crosses
-- the JSON boundary with the kernel, and a metatable does not survive the
-- round trip. Predicates and the match are free functions for the same
-- reason — the value carries data, the module carries behaviour.
local Outcome =
--- The status values the kernel knows. Exactly these four, provider-neutral.
local STATUSES =
--- A beat that ran: `out` is the call's return (content / usage /
--- stop_reason, plus the `beat` id and the tool summary this layer added).
--- The model produced a response but refused to make progress. `detail`
--- carries the call's `out` so a caller can inspect what came back.
--- The beat did not come off: the mechanism failed. `kind` is one of the
--- kernel's own failure points — "conf", "filter", "call" or "state" (a
--- record that could not be laid down: closed session, a store that would
--- not take the write, event validation).
---
--- Two vocabularies meet on this value and they answer different questions.
--- `kind` here names the STAGE of the beat that failed. What the failure
--- *was* — and whether asking again could work — is in `detail`: a "state"
--- failure carries the kernel's reading (`detail.kind` one of
--- `knl.shapes.error_kinds`, `detail.retryable`). A loop deciding on a retry
--- reads `detail.retryable`, never this `kind`; "state" says where, not
--- whether.
--- The beat stopped on purpose before calling: an allowance would not cover
--- it. Not a failure (nothing broke) and not a refusal (the model was never
--- asked) — the branch a caller's loop exits on. `tag` names the grant that
--- stopped it, when the owner gave it one.
--- Match an Outcome against `arms = { ok = fn, refused = fn, error = fn,
--- stopped = fn }`.
---
--- Exhaustive: every one of the four arms must be present, and the actual
--- status must be one the kernel knows. A missing arm is a loud error rather
--- than a silently-dropped case (the dynamic-language stand-in for a
--- compiler's exhaustiveness check).
M. = Outcome
-- ============================================================
-- fold — events -> request (pure)
-- ============================================================
--- The JSON-array tag the bridge's converter honours (`lua_to_json` reads
--- `__jsontype = "array"`). Every array fold builds is tagged, so the empty
--- case crosses the boundary — into the durable `llm_request` event and onto
--- the provider wire — as `[]`, not `{}` (the empty-array boundary class
--- this repo has prior fixes for).
local ARRAY_TAG =
local
--- Render a tool_result's payload as request text: a string verbatim, any
--- other value JSON-encoded (the envelope already carries the rest).
local
--- The wire declarations for `tools` (name -> { description, input_schema,
--- handler }), handler stripped: the request carries what the model may
--- call, not how to call it. Sorted by name so fold stays deterministic
--- (pure), which is what lets a KV cache hold across beats.
local
--- Fold an event list into a provider-neutral request.
---
--- The default fold, for chat-shaped providers. Pure: it reads `events` and
--- the `device`'s policy fields and writes nothing. Three kinds map to
--- messages and the rest are skipped (tool_call / session_* / budget_* /
--- llm_call_failed / llm_request):
---
--- msg_user -> { role = "user", content = <data.content verbatim> }
--- llm_response -> { role = "assistant", content = <data.content verbatim> }
--- tool_result -> collected, in seq order, into the user message that
--- follows the assistant message they answer (consecutive
--- tool_results batch together, which for a well-formed
--- history is the same as grouping by beat)
---
--- What a kind is about lives under `data` (see the header), so that is
--- where this reads: `data.content`, `data.call_id`, `data.ok`,
--- `data.result`. An event that carried none — a caller's own kind, or one
--- of the kernel's own boundaries — falls through the same skip as the rest
--- rather than indexing nil.
---
--- `system` and `tools` are composed from the device each beat, not read
--- from the history.
---
--- What "provider-neutral" names here
--- Neutral is a choice of shape, not the absence of one: the request and
--- response this fold speaks ARE the Anthropic content-block shape. An
--- assistant message is an array of blocks, a `tool_use` block carries a call
--- and a `tool_result` block answers it by `tool_use_id`. `close_dangling`
--- below depends on exactly that — it pairs the `tool_use` ids of an
--- assistant message against the results that answered them, a repair no
--- flatter shape could express. Other providers do not arrive here in
--- their own dialect: `llm_proto`'s adapters normalise them into these
--- blocks on the way in and render them back to the provider's wire on the
--- way out, so fold never sees a provider-specific shape.
---
--- What it is handed, and what it does not check
--- `events` is a WHOLE record, and this function takes that on trust: it is
--- an array, and an array carries no mark saying a read of it stopped early.
--- Whoever read the log knows — `session:events()` answers `truncated`
--- beside the rows — and that is where the refusal is (`knl.beat` [1]),
--- because the callers that hand arrays in are not all reading a session:
--- `supervisor.merge` folds query rows, and a caller's own fold may build
--- the list itself.
---
--- It does not repair content either, beyond closing a dangling `tool_use`.
--- An `llm_response` recorded with an empty `content` array folds to an
--- assistant message whose content is `[]`, verbatim — see the pinned shape
--- in `knl/spec/device_spec.lua`. Nothing here decides whether a provider
--- will take that; a filter that means to drop or fill such a turn is a
--- filter, and it has the request to work on.
---
--- @param events table array of stored events (from `session:events()`)
--- @param device table a knl device (any table carrying system / tools)
--- @return table request { system?, messages, tools? }
-- ============================================================
-- shapes — the public contracts of this module (handwritten lshape)
-- ============================================================
--
-- Every public IF is defined here and published through `M.shapes`
-- so a caller reads the contract as data
-- rather than out of prose, and `M.shapes.api` names the shape of
-- every export so a spec can check the registry is complete instead of a
-- person remembering to update it.
--
-- The shapes are asserted at the boundaries in dev mode (LSHAPE_CHECK=1)
-- and are a no-op in prod. That is why every construction check that must
-- be loud — `knl.device`'s — also exists as an explicit check beside the
-- assert: a dev-only gate would let a broken device through in prod.
--
-- Two limits of the DSL are worked around in the open rather than hidden:
-- lshape has no numeric range, so `cost_result` says "number" and the
-- whole-number >= 1 rule is checked in beat [3]; and "callable" (a
-- function, or a table / userdata carrying `__call`) is wider than any one
-- prim, so the shape admits the three types and `device_problem` makes the
-- exact judgement.
--
-- The event vocabulary this layer writes (msg_user / llm_request /
-- llm_response / llm_call_failed / tool_call / tool_result) is here too,
-- as `knl.shapes.events` — but only the `data` half of each, because that
-- is the half whose owner is the writer (the *stored event* section of the
-- header). There
-- is no second copy of anything: the kernel validates the envelope and the
-- `data` of ITS own kinds (`session_*`, `budget_*`) and stopped judging
-- these, so the shapes below are the only declaration of them, and the
-- appends in `record` are where they are held.
--- A Lua function, as a shape. lshape's `prim` handler is `type(v) ==
--- schema.prim` for any type name, but `lshape.t` exposes only the five it
--- names, so these two are built from the same plain-data schema form
--- (Schema-as-Data: the state is the table; the metatable carries only the
--- `:is_optional()` / `:describe()` sugar).
local FUNCTION = setmetatable
local USERDATA = setmetatable
--- Something a beat can call: a function, or a table / userdata carrying
--- `__call` — a Port shim may hand back either. The exact test is
--- `callable` below, run loudly at construction; this is its data shape.
local CALLABLE = T.
--- A session handle, as a shape: the kernel's own userdata, or the faithful
--- Lua stand-in a spec drives a beat with. Which methods it must answer is
--- `is_session`'s duck-type (the whole declared surface) and no schema can
--- ask a userdata that — so this says the two types the handle can have, and
--- the entry point that receives one still makes the real judgement.
local SESSION_HANDLE = T.
--- The STAGE of a beat an `error` Outcome names (see `Outcome.err`). One
--- constant: the shape below closes on it and the registry declares
--- `Outcome.err`'s first argument with it, so the four words are written
--- once.
local OUTCOME_KIND = T.
--- An Outcome, as data. Discriminated on `status` — exactly the kernel's
--- four, each variant carrying only its own fields.
local OUTCOME = T.
--- One wire tool declaration inside a request (handler already stripped).
local WIRE_TOOL = T.
--- The provider-neutral request fold/filters hand to the llm. `system` is
--- provider vocabulary (string or blocks) — any. Open: a filter may attach
--- keys the default fold does not know about.
local REQUEST = T.
--- An event's `meta`: labels, and only labels.
---
--- Shallow by rule — string / number / boolean values and nothing else —
--- because `meta` is the half of the envelope a view can read without ever
--- being broken by a schema change, and a nested value would make it a
--- second `data` with none of that promise. The kernel refuses a nested one
--- at the syscall; this is the same rule as data, so dev mode says it at
--- the line that wrote it rather than at the boundary.
local EVENT_META = T.
--- The envelope, in the terms this layer owns: a `kind` string, the `beat`
--- id stamped on the events a beat wrote (an opaque string and nothing
--- more), the shallow `meta` labels, and the `data` a kind carries.
---
--- Open, and deliberately: the kernel stamps `seq` / `epoch_ms` /
--- `_schema_version` on a stored event, so the value that comes back out of
--- `events()` carries more keys than the one that went in. The closure —
--- "no other top-level key" — is the kernel's, enforced at the syscall
--- where the stamps are known; what this shape holds is the four fields a
--- caller writes.
---
--- What is inside `data` is per-kind and is `EVENT_DATA` below.
local EVENT_BASE = T.
--- The `data` of every kind this layer writes — its shape, owned here
--- because the writer owns it.
---
--- Closed, every one of them: `data` is what a SQL view reads a path out
--- of, so a key that arrived by accident is a column somebody will
--- eventually select and a key that was renamed is a view that quietly
--- answers NULL. A closed shape is what turns both into a dev-mode
--- failure at the append that wrote it.
---
--- Two fields are deliberately wider than the contract they came from.
--- `llm_response.usage` is `table`, not the strict three counts
--- (`llm_usage`): the counts are the ADAPTER's promise and beat judges
--- them at the call ([6] — an answer with no usage is `err("call")` and no
--- response is recorded), so re-judging them at the append would report a
--- broken adapter as a store failure. `msg_user.content` and
--- `tool_result.result` are `any` because they are provider / tool
--- vocabulary: a string, blocks, or whatever a handler answered.
---
--- `msg_user` is not a kind a beat writes — it is the seed a caller writes
--- (see the header) — and it is declared here with the rest so the form is
--- published rather than remembered.
---
--- The classification a model call that did not come off carries.
---
--- WHY IT IS A VOCABULARY AND NOT A STATUS. A beat reports a failed call as
--- `Outcome.err("call", detail)`, and `kind` there names the STAGE — it says
--- the llm is where the beat broke and nothing about what broke. So a loop
--- had nothing to decide on: `policy.retry` reads `detail.kind` and
--- `detail.retryable`, and a call failure carried neither, which meant no
--- retry policy could ever fire on the one failure that is most often worth
--- asking again about (a rate limit, an overloaded provider, a connection
--- that dropped).
---
--- These seven words are that missing half, and they are provider-neutral by
--- construction: an HTTP status is one provider's word for several things,
--- and it is read in exactly one place — the adapter's mapping table
--- (`knl_adapter`) — which answers with one of these. Nothing downstream
--- reads a status or a status class; `status` rides along on the detail as a
--- fact for a person reading a log, never as something to branch on.
---
--- transport the call never got an answer: connect, read, timeout
--- rate_limited the provider said "too fast" (429)
--- overloaded the provider said "not now" (529 / 503)
--- server the provider broke (5xx)
--- auth the credentials were refused (401 / 403)
--- invalid_request the request itself was rejected (400 / 404 / 413 / 422)
--- unknown anything the mapping does not name — including an
--- adapter that broke its own contract, and a raise
---
--- `retryable` is true for exactly the first four. It is a separate field
--- rather than a lookup because it is the judgement a loop acts on, and the
--- table below is what the two are kept in step by.
local CALL_ERROR_KINDS =
--- Which of the kinds above says asking again could work.
---
--- Published beside the list so a caller (or a port) reads one answer rather
--- than deciding for itself: a provider being busy is worth another call, a
--- request the provider refused to read is not.
local CALL_ERROR_RETRYABLE =
--- The same list as a set, for the one reader that has to ask "is this word
--- one of ours" about a value that came from somewhere else.
local CALL_ERROR_IS_KIND =
for _, kind in ipairs
--- What a failed call's `detail` carries — `Outcome.err("call", <this>)`.
---
--- Open, like `knl.shapes.error`: the dev-mode traceback of a caller's own
--- raising llm rides here, and a port may attach what its own reader needs.
--- What is closed is the vocabulary of `kind`.
---
--- `retry_after` is seconds, and it is present only when the provider named
--- one (a `retry-after` header); `status` is the HTTP status the mapping read,
--- carried for a reader and never for a decision.
local CALL_ERROR = T.
--- Two kinds here are the KERNEL's, not this layer's: `session_opened` and
--- `session_closed`. Nothing in Lua may write them (the kernel refuses a
--- hand-written boundary) and their shape is checked on the other side of
--- the syscall — they are declared here because a supervisor READS them.
--- `parent` and `open_children` are how a session tree is recorded, and a
--- view over them (`knl.views.tree`) is tied to those two paths the same way
--- `usage` is tied to `llm_response`: the declaration is what says which
--- reads move when the shape does.
local EVENT_DATA =
--- One entry of a device's `tools` map: what the model may call
--- (description / input_schema, both optional and both provider
--- vocabulary) plus how to call it. Only `input_schema` is read; there is
--- no alias.
local TOOL_ENTRY = T.
--- What a `tool_policy` may decide: `nil`
--- is "no opinion" and runs, and the two words are the whole vocabulary.
--- Anything else is a device-contract violation, not a third meaning.
local TOOL_POLICY_DECISION = T.:
--- What `device.cost` must answer: a whole number >= 1, which is what
--- makes the budget a ranking function and the run finite. lshape has no
--- numeric range or integrality combinator, so the shape carries the type
--- and beat [3] carries the bound — loudly, in prod as well as dev.
local COST_RESULT = T.:
--- The config `knl.device` consumes. Closed: a policy typo must not
--- quietly become a no-op, which is also why `knl.device` rejects unknown
--- keys loudly rather than leaving it to this dev-mode assert.
local DEVICE_CONFIG = T.
--- What an owner grants a session. `amount` is a count of whatever `tag`
--- names (the kernel reads the number and nothing else); lshape has no
--- integer prim, so the whole-number expectation rides in the doc.
local BUDGET_GRANT = T.
--- What a parent hands a child out of its own balance: `from_parent` units,
--- counted in `tag` (the parent's unit when it is left out).
---
--- Not a grant, and the difference is where the units come from. A grant is
--- an owner allowing — a balance appearing, which only an owner may do — and
--- an allocation is a move: the parent's balance falls by exactly what the
--- child's rises by, in one write. So there is no `desc` either; what the
--- log records about why is the parent it names.
local BUDGET_ALLOCATION = T.
--- `knl.open` opts: state only. Policy has its own constructor.
---
--- `parent` is a session this one is opened *from*: the child lands on the
--- parent's database, its opening names the parent, and its quota is moved
--- out of the parent's balance — one write, both ledgers. It goes with
--- `budget = { from_parent = n }` and with nothing else: an owner's grant on
--- a child would be a quota nobody paid for, and `from_parent` with no parent
--- has nowhere to take it from. The kernel refuses each with the other named.
local OPEN_OPTS = T.
--- `knl.resume` opts: the session to reopen, plus the grant this process runs
--- under and, when the stream is not in the host's own database, the store it
--- is in. Optional for the same reason it is on open: no store named is the
--- file the host owns, which is where a session opened without one went.
local RESUME_OPTS = T.
--- The token accounting an llm answer promises: three counts, always
--- present as numbers. An adapter normalizes a provider that reported none
--- to zeros, so this stays strict rather than admitting a missing field.
--- Closed so a stray usage key cannot ride across the boundary.
local USAGE = T.
--- The refusal detail an llm answer carries alongside a "refused" status.
--- `kind` normalizes *why* the beat did not progress across providers:
--- "model" is the model declining, "content_filter" a provider safety
--- filter blocking it — a distinction the kernel's status cannot carry, so
--- it rides here. Present iff status == "refused".
local REFUSAL = T.
--- What a `tool_use` block inside a response names: the id the tool_result
--- will answer, and the tool to run. beat reads both straight off the block
--- — an unnamed call is the llm breaking this contract, not a hole for the
--- kernel to fill with an empty string.
---
--- Open, and about `tool_use` alone: what else a block may carry (`input`,
--- and whatever a provider adds) is the provider's vocabulary, and this
--- layer has no business closing it.
local TOOL_USE_BLOCK = T.
--- What `device.llm(request)` hands back — the shape beat reads at [5],
--- and the one an adapter's Mapper is held to on the way out (knl_adapter
--- asserts against this very table). Two statuses and no more: a transport
--- or provider failure is not a variant here, because that path answers
--- `nil, err` (or raises), which beat records as `llm_call_failed` and
--- reports as `err("call")` — with `err` a `call_error` above when the port
--- classified it.
---
--- Discriminated on `status` rather than one shape with an optional
--- `refusal`, because "present exactly on a refusal" is the contract and an
--- optional field says only "sometimes". A refusal that named no `kind`
--- would leave beat with nothing to report the refusal AS.
---
--- Both variants are closed, so a contract gap in one provider's parse
--- cannot leak past the boundary: `content` is an array of blocks (tagged
--- as an empty array when the model said nothing, so it crosses the JSON
--- bridge as `[]`), `usage` is the strict count above, and `stop_reason` is
--- absent when no reason was given.
---
--- The per-block rule above rides beside this shape rather than inside it:
--- it applies to one `type` of block and lshape has no combinator for
--- "strict for this variant, open for the rest" that would not also close
--- the block vocabulary.
local LLM_RESULT = T.
--- Every class a kernel failure can have, in one closed list — the Lua
--- side of the Rust `KnlError::KINDS`.
---
--- One constant, used by the shape below and by the check that holds this
--- declaration against the bridge's own (`knl.api().errors`, compared in
--- `tests/fixtures/knl_beat_test.lua` inv10, the test that has a bridge).
--- Retyping the list beside the shape would make a second place to keep in
--- step, which is the drift the api registry exists to rule out.
---
--- `timeout` is the read side's own class: a
--- `session:query` that ran past its deadline was interrupted, and it is not
--- retryable — the same statement over the same data would run just as long.
--- `busy` remains the one class the kernel calls worth asking about again.
---
--- `refused` is the odd one out and deliberately so: every other class is a
--- fault, and that one is a decision. A child asked for more than its
--- parent's balance covered, the refusal is in the log, and nothing is
--- wrong — so it is not retryable either, because the same balance answers
--- the same way until an owner grants more.
---
--- `unsupported` is the one class NOTHING REACHABLE FROM HERE RAISES. It is
--- the store SPI's own: a backend that keeps no queryable table, or keeps one
--- stream and so cannot write two in a transaction, answers with it — and the
--- only backend the host has does both. The two cases a caller might expect it
--- for come back as `validation` instead, with a message that says which
--- argument was wrong: a child asked for on a `"mem"` parent, and an unknown
--- `view` name. It is declared here because the kernel publishes it
--- (`knl.api().errors`, held against this list in `knl_beat_test.lua` inv10)
--- and because a store may still return it; it is not a branch a shell needs
--- to write today.
local ERROR_KINDS =
--- A raised kernel failure, read back as data (`knl.error(e)`).
---
--- `kind` and `method` are optional because a raise that carried no
--- attribution — a Lua-side `error("...")`, a message from another module,
--- or any raise at all in a VM with no bridge — is reported whole rather
--- than rejected: `message` then holds the entire text. So `message` is the
--- field a reader can always count on, and `kind` is the one it must ask
--- for.
---
--- `retryable` is the only judgement in the table and it is the kernel's:
--- true for contention (`busy`) and nothing else. What to *do* about it is
--- the caller's loop's — see `Outcome.err`.
local ERROR = T.
--- What a caller asks for beyond the SQL itself.
---
--- `sessions` is the set `$sessions` expands to — the streams this read
--- spans, which is how one statement reads a session tree or a set of
--- sessions that were split and are being read back together. Omitted, it is
--- the session's own stream and nothing else. The kernel expands the token
--- into one bound placeholder per id and binds them; whether the caller may
--- read those streams is not the kernel's judgement (decision 3: identity
--- lives outside the kernel).
---
--- `timeout_ms` and `limit` are whole numbers with kernel defaults (5000 ms,
--- 1000 rows). lshape has no integer prim, so the whole-number expectation
--- rides in this doc, like `budget_grant`'s `amount`.
---
--- Closed: an option the kernel does not know must not quietly do nothing.
local QUERY_OPTS = T.
--- The read schema, as data: the kernel's table and its columns, published
--- as the contract a caller writes SQL against.
---
--- This is plain data rather than an lshape schema on purpose — it describes
--- a SQL table, not a Lua value, and what it is FOR is to be compared:
--- `knl.api().schema` answers the same declaration from the kernel's side
--- and `tests/fixtures/knl_beat_test.lua` (inv11) holds the two against each
--- other, exactly as inv10 does for the syscall registries. Adding a column
--- is compatible; renaming or dropping one is a breaking change on the same
--- footing as changing a stored event's shape.
---
--- The envelope IS the column list (see the header). `stream` / `seq` /
--- `epoch_ms` / `kind` / `schema_version` are the kernel's stamps, `beat` is
--- the correlation key a view groups by, `meta` holds the shallow labels and
--- `data` holds the one structured JSON value a kind is about.
---
--- So a view reaches a beat with the `beat` column rather than a JSON path,
--- and the only `json_extract` any of them needs is into `data` — which is
--- exactly the reading that has to change when a kind's shape does. There is
--- no `payload` column any more: the whole-object form it held is what this
--- round split into the envelope and the one structured field.
local EVENTS_SCHEMA =
--- The contracts this module holds itself to, as data.
M. =
--- The API registry: one entry per public
--- export, naming the shape of what goes in and what comes out. It exists
--- so the completeness of the contract is *checked* rather than remembered
--- — `knl/spec/api_spec.lua` walks this module and fails on an export with
--- no entry, an entry with no export, and a device field that
--- `device_config` does not describe.
---
--- `args` is an ordered list, one item per positional argument, each
--- `{ shape = <lshape schema>, desc = <word for it> }` — and an empty list
--- for an export that takes nothing (or is not a function at all). One
--- representation, no exceptions: an argument a schema cannot pin down gets
--- the widest shape that is still true (`T.any`, or the union a session
--- handle can be) and carries the rest of the meaning in `desc`, rather than
--- dropping out of the machine-readable half into prose. That is what lets
--- the registry be RUN — see the dev-mode gate at the foot of this file,
--- which holds every declared call to the entry above it.
---
--- `returns` stays a shape or a sentence: nothing executes it, because what
--- an export answers is already checked where it is built (`emit`, the
--- Mapper's boundary assert) rather than at the call.
---
--- `members` names the functions of an export that is itself a namespace
--- (`Outcome`), and the methods a returned value carries (`device:with`).
--- The gate reaches the first — they are functions on an exported table —
--- and not the second: `with` is reached off a device, which is a value this
--- module hands out rather than an export it owns, so its entry documents
--- and is walked, but nothing wraps it.
---
--- This registry covers the Lua module. The bridge declares its own surface
--- through `knl.api()` (SESSION_API / MODULE_API in bridge/knl.rs), and
--- `M.shapes.session` / `M.shapes.module` below describe that surface from
--- this side; `tests/fixtures/knl_beat_test.lua` (inv10, runs with the
--- bridge) checks the two against each other in both directions, so a
--- syscall added on one side and not the other goes red.
--- The bridge's argument and return shapes, from Rust.
---
--- `knl_types` is generated at host start from the argument and return types
--- of the syscall layer (`bridge/knl.rs`, `mod types`) and injected as an
--- embedded module, so the two registries below POINT AT the Rust type
--- instead of restating it. What they replaced was two declarations of one
--- interface — the bridge's signatures, and a hand-written lshape table
--- beside them — held together by a test that compared names and would not
--- have noticed a field renamed on either side.
---
--- A VM without the host has no such module: the pure lspec runner loads this
--- file off the filesystem and never registers the bridge, and there is no
--- session to call there either. The registry then names the type it would
--- have resolved to rather than inventing a shape for it — a description is a
--- declaration (`knl/spec/api_spec.lua`), and a fallback that was a shape
--- would be the second declaration all over again. The VM that does have the
--- bridge is the one that holds the two halves against each other
--- (`tests/fixtures/knl_beat_test.lua`, inv10).
local types_ok, RUST = pcall
if not types_ok
M.. = RUST
M.. =
M.. =
--- One declared argument: the shape it is held to, and the word for it.
--- Two fields rather than one so the widest-true shape (`T.any`, a union)
--- costs no meaning — `desc` keeps saying "session" where the schema has
--- stopped being able to.
local
--- The arguments every predefined view takes: the session whose store is
--- read, and the query options (the set of streams above all) passed
--- straight through to `session:query`.
local
--- The predefined query views, declared.
---
--- One table, published twice: as `knl.shapes.views` (the registry a caller
--- reads) and as the `members` of the `views` entry below (what the dev-mode
--- gate walks and what `api_spec` holds `knl.views` against). Two names for
--- one table rather than two tables, so a view cannot be declared in one
--- place and missed in the other.
local VIEWS =
M.. = VIEWS
M.. =
--- Dev-mode gate for an event a beat is about to write. No-op in prod.
---
--- Two halves, and they have different owners. The ENVELOPE rules are the
--- ones the kernel also enforces and this layer mirrors so they fail at the
--- line that wrote them rather than at the syscall: a `kind`, a `beat` that
--- is a string when present, and a `meta` that is shallow. The `data` is
--- this layer's own — `knl.shapes.events` holds the shape of each kind it
--- writes, and the kernel stopped judging them — so an unknown kind is
--- simply not checked here, which is what leaves the vocabulary open.
---
--- It guards only what *beat* writes. A caller's own `session:append` goes
--- straight to the kernel: the session handle is the kernel's, not
--- something this module wraps.
local
--- Dev-mode gate for an Outcome on its way out of beat. No-op in prod.
---
--- `OUTCOME` leaves `detail` as `any` — three of the four error kinds carry
--- a message a person reads — but a "state" detail is a contract: it is the
--- kernel's failure read back, and a loop decides on a retry from its
--- `retryable`. So that one is held to `ERROR` here, which is where a call
--- site that reported a raw string instead of the reading goes red.
local
--- `xpcall`'s message handler for a function the CALLER supplied — fold, a
--- filter, cost, the llm — keeping the raised value and the stack apart.
---
--- `debug.traceback` on its own folds the two into one string, and the
--- message is what a beat reports in prod: a detail that grew a stack
--- traceback behind it would be a different report, not a richer one. So
--- the raise is kept verbatim and the stack rides beside it.
---
--- The stack is captured in dev mode only. It is a development aid — which
--- line of somebody's own fold raised, through the pcall that turned the
--- raise into an Outcome — and a production run should not pay for one on
--- every failure.
---
--- `traced` marks the capture rather than letting the traceback's presence
--- stand for it: the `debug` library is not in every VM this module runs in
--- (mlua's safe stdlib leaves it out), and a detail whose TYPE depended on
--- that would make dev mode mean two different things. Dev mode is one
--- thing — a structured detail — and the stack is a field in it that a VM
--- without `debug` simply cannot fill.
local
--- The `detail` for a failure that came out of a caller-supplied function:
--- the message beat reports, and in dev mode the traceback beside it.
---
--- In prod this is exactly the string it has always been. In dev it is a
--- table with the same text under `message`, which is the one place the
--- two modes differ in what a beat returns — deliberately, because a
--- traceback is an answer to "where in my code", a question only the person
--- writing that code is asking.
---
--- @param message string what beat reports about the failure
--- @param caught table what `traced` handed back
--- @return string|table detail
local
--- The classification a failed model call is reported with — the detail of
--- `Outcome.err("call", …)` and the `data` of the `llm_call_failed` note.
---
--- One shape for every way a call does not come off, because a loop reading
--- the Outcome cannot be asked to tell them apart:
---
--- * the port classified it — `nil, { kind, retryable, … }` — and that
--- reading is carried through as it came. The adapter is where a
--- provider's vocabulary is read, and this layer does not second-guess it;
--- * anything else — a raise, an adapter that broke `llm_result`, a device
--- whose `llm` is not a port at all and answered `nil, "..."` — is
--- `unknown` and not retryable. That is the honest reading: beat was not
--- told what kind of failure it was, and inventing one (a "transport" for
--- every message with "timeout" in it, say) would be this layer guessing
--- at the vocabulary it just refused to let the shim hold.
---
--- The dev-mode traceback of a caller's own raising `llm` rides along beside
--- the classification, exactly as `raised_detail` carries it for the stages
--- whose detail is a sentence.
---
--- @param err any what the llm answered as its error, or the raised value
--- @param caught table|nil what `traced` handed back, when it raised
--- @return table `knl.shapes.call_error`
local
--- What a `traced` failure raised, as text.
local
-- ============================================================
-- device — the resolved, frozen policy half
-- ============================================================
--- The fields a device carries. The config is consumed at construction, so
--- this is both the accepted key set and the field set of the result.
--- Everything that names the session itself (owner / store / session /
--- budget) is state and belongs to `knl.open` / `knl.resume`.
local DEVICE_KEYS =
local IS_DEVICE_KEY =
for _, k in ipairs
--- The metatable name `beat` recognises a device by. A protected metatable
--- (`__metatable`), so the tag cannot be forged by assignment either.
local DEVICE_TAG = "knl.device"
--- The tag on a device's frozen tools map.
local TOOLS_TAG = "knl.device.tools"
--- How much one beat asks the budget for when the device names no policy.
---
--- One beat, one unit: a beat is the thing being bounded, so the default
--- makes the grant a count of beats. It must be >= 1 — that is what makes
--- the budget a ranking function and the run finite. What the unit *means*
--- is the owner's (`budget = { amount = N, tag = "tokens" }` counts tokens,
--- and then a device supplies `cost` to say how many one beat may take).
local
--- Whether `v` can be called like a function (a callable table / userdata
--- counts: a Port shim may hand back either).
local
--- A read-only view over `fields`: reads pass through, `pairs` walks the
--- underlying table, and every assignment raises — including one to a key
--- that already exists, which a plain `__newindex` on the table itself
--- would let through.
local
local
local
--- Minimal device config check. Returns an error string, or nil when the
--- config is usable. `llm` is not required here — a device may be built for
--- its tools alone; beat's gate demands one.
---
--- This is the loud half of the pair: `DEVICE_CONFIG` says the same thing
--- as data and is asserted beside it, but a dev-mode assert is a no-op in
--- prod and a device built out of a mistyped config would then fail at the
--- first beat instead of at the line that built it. It also makes the two
--- judgements a shape cannot: "callable" (function / `__call`), and "a map
--- of entries, not an array of flat specs".
local
local device_with -- forward declaration (served by the device's __index)
--- Build a device: the resolved, frozen policy half of a beat.
---
--- The config is *consumed* here — defaults are resolved once (`fold` ->
--- `knl.fold`, `filters` -> `{}`, `cost` -> one unit per beat), types are
--- checked once, and the result carries only resolved values. There is no
--- `_config` to read back: what the device does is what its fields say.
--- Unknown keys raise, because a typo in a policy field must not silently
--- become a no-op.
---
--- The device is stateless: share one across sessions, and give one session
--- several (escalation) — nothing about a beat is remembered here.
---
--- @param config table { llm?, tools?, tool_policy?, fold?, filters?,
--- system?, cost? }
--- @return table device frozen, with `with` for derivation
--- Derive a new device: this one's resolved fields with `delta` over them,
--- re-resolved through `knl.device`. The original is untouched and stays
--- usable — a device is a value, and `with` is how a beat gets a different
--- one (`knl.beat(s, d:with{ llm = strong })`).
---
--- @param d table a knl device
--- @param delta table device fields to override
--- @return table device' a new frozen device
device_with =
-- ============================================================
-- open / resume / session — the state half
-- ============================================================
local OPEN_STATE_KEYS =
local RESUME_STATE_KEYS =
--- Reject anything that is not a state key. Policy has its own constructor
--- now, so `knl.open{ llm = ... }` is a typo, not a shorthand.
local
--- Open a session. The kernel's userdata comes back as-is — this module
--- wraps nothing: `s:append`, `s:events`, `s:reserve`, `s:view`, `s:close`
--- and `<close>` are the kernel's own surface.
---
--- With `parent` it opens a CHILD: on the parent's database, out of the
--- parent's balance (`budget = { from_parent = n, tag? }`), and in one write
--- — the child's opening and grant, and the parent's reservation naming it.
--- A balance that will not cover it records a refusal on the parent and
--- raises `refused`; nothing is opened. Nothing comes back when the child
--- closes, because an allocation is a spend.
---
--- No `store` is the host's database (the header's "Where the log lives");
--- a child needs none, because it goes where its parent already is — and a
--- parent on `"mem"` is refused, since a tree needs a file store.
---
--- @param opts table { owner?, budget? = { amount, tag?, desc? } | { from_parent, tag? }, store?, parent? }
--- @return userdata session
--- Resume a persisted session. The state comes back from the store (the
--- bridge reopens the recorded stream and re-folds the log); policy does NOT
--- — it is a non-serializable closure bundle, so every process builds its
--- own device.
---
--- `store` means what it means on open, so a session opened without one is
--- resumed by its id alone: `knl.resume{ session = id }`.
---
--- @param opts table { session = <id>, store? = "mem" | { sqlite = <path> }, budget? }
--- @return userdata session pre-loaded with the log
--- The canonical bracket: open (or resume),
--- run the body with the session, close it either way.
---
--- local out = knl.session({ owner = "u" }, function(s)
--- return knl.beat(s, d)
--- end)
---
--- Opts naming a `session` resume that stream instead of opening a new one.
--- The body's return values are the bracket's. When the body raises, the
--- session is closed with reason "error" first and the body's error is then
--- re-raised unchanged: a bookkeeping failure must not replace the failure
--- it is bookkeeping for, so a close that itself fails on that path
--- is warned about rather than raised. On the clean path a failing close
--- raises instead, since a bracket
--- that reports success with no boundary recorded is the one outcome this
--- exists to rule out.
---
--- When both fail, the body error wins and the close failure is the
--- suppressed one (try-with-resources' suppressed exception). It is
--- not silent either: it goes to the host `log` global as a warning when
--- the VM has one, as a record — `{ event =
--- "close_failed_after_body_error", body = <the winner, as text>, close =
--- <the kernel's reading, knl.shapes.error> }` — so the loser is at least
--- structured. It cannot be raised (that would replace the body's error)
--- and it cannot be returned (this path does not return), which is why a
--- log is the only place left for it.
---
--- The reason vocabulary is the kernel's, and a normal exit has one word in
--- it: "scope_exit" — what this bracket closes with and what `<close>`
--- records, because leaving the scope is the same event whichever form
--- wrote it. "error" is the failing path (here and in `<close>`), "dropped"
--- the Drop backstop, and "closed" stays the bridge's DEFAULT_CLOSE_REASON
--- for a bare `s:close()`. The message of a body error does not ride along
--- — `s:close` takes a reason and nothing else — so it stays with the
--- error that is propagating.
---
--- @param opts table knl.open / knl.resume opts
--- @param fn function fn(session) -> ...
--- @return ... whatever `fn` returned
--- Mint a beat id: a time-ordered, session-free string the caller stamps on
--- the events of one beat. A module
--- function, not a direct bridge call, so a spec can stand in for it.
---
--- @return string beat_id
--- Read a raised kernel failure back as data — the BRIDGE's reader, reached
--- through this module so `require("knl")` is the one surface a script needs.
---
--- Two tables answer to the name `knl`: the syscall bridge the host installs
--- as a global, and this module. A script that wrote `local knl =
--- require("knl")` had shadowed the first, and the reader the docs name is on
--- it — so these two are re-exported here rather than left to a caller
--- reaching past its own local for `rawget(_G, "knl")`. Nothing is
--- reimplemented: the lookup is the same lazy `bridge()` one `new_beat_id`
--- uses, so a spec that installs a fake bridge after this module loaded still
--- reaches it, and a VM with no bridge at all says so rather than indexing nil.
---
--- @param e any the value a pcall'd syscall raised
--- @return table `knl.shapes.error` — { kind?, method?, retryable, message }
--- The bridge's declared surface, as data — the bridge's reader, read back
--- through the module for the same reason `M.error` is (see above).
---
--- @return table { session, module, errors, schema, types }
-- ============================================================
-- beat — one complete beat (the primitive; there is no loop here)
-- ============================================================
--- The session surface, as names: every method `knl.shapes.session`
--- declares that a caller can reach (`__close` is the metamethod, reached by
--- the language and not by a call).
---
--- DERIVED from that registry rather than retyped beside it. The list used to
--- be written out here and had drifted — `view` and `query` were syscalls the
--- registry declared and this list did not name, so a stand-in that answered
--- neither passed the gate and failed later, on a call a caller had every
--- right to make. A copy of a list is a list that goes stale; reading the
--- registry is what makes that impossible rather than caught.
---
--- The registry itself is held against the bridge's own `knl.api().session`
--- in both directions where a bridge exists (`tests/fixtures/knl_beat_test.lua`,
--- inv10), so the chain from this gate to the Rust `SESSION_API` is closed.
local SESSION_METHODS =
for name in pairs
table.
--- Whether `s` is a session handle.
---
--- Duck-typing is not a preference here, it is the only test available: the
--- real handle is Rust userdata whose metatable mlua protects, so
--- `getmetatable` answers a boolean rather than the table, and there is no
--- name to compare against from Lua. What is left is to ask the value what
--- it can do.
---
--- So it is asked for the WHOLE declared surface, not the three methods a
--- beat happens to call. A stand-in that answers `append` / `reserve` /
--- `events` and nothing else is not a session — it is a table that would
--- pass the gate and then fail somewhere further in, on a `remaining()` or
--- a `close()` a caller had every right to make. Widening the check is what
--- keeps a spec's fake honest to the surface it stands in for.
local
--- Append an event this beat is writing, through the dev-mode contract.
local
--- What is wrong with an llm's answer, or nil when nothing is.
---
--- `device.llm` promises one of two things: an `llm_result` (`knl.shapes`),
--- or `nil` and an error. The result has exactly two statuses, a `usage` the
--- adapter has already normalized into three counts, and — on a refusal —
--- the `refusal.kind` that says what refused. An answer that keeps none of
--- that is a broken adapter, and beat ends the beat the way any other failed
--- call ends rather than filling the gaps in: a defaulted usage would put a
--- count nobody reported into the history, and a refusal reported as
--- "refused" would be beat naming a reason it was never given.
---
--- @param resp any whatever `device.llm` answered
--- @return string|nil the violation, or nil when the answer is well formed
local
--- Ask the policy about one tool_use block.
---
--- The contract is `tool_policy(tool_use_block, out) -> decision, reason?`
--- with a decision of `nil` (no opinion — run), `"run"` or `"deny"`, and
--- nothing else: a fourth word is a device-contract violation rather than a
--- fourth meaning this layer gets to guess at. A policy that RAISES is
--- fail-closed — a gate written to veto tools must not fall open on its own
--- bug — so the raise denies the call and its message becomes the reason.
---
--- @param policy function|nil device.tool_policy
--- @param block table the tool_use block being decided
--- @param out table the model response it came in
--- @return string|nil action "run" / "deny", or nil on a violation
--- @return string|nil reason the denial's reason, when there is one
--- @return string|nil problem the contract violation, when there is one
local
--- Run the tool_use blocks of a response, closing every one with a
--- tool_result. What runs / is denied is `device.tool_policy`, the success
--- result is the handler's, and the pair-closing record — including the
--- machine-minimal error for an unknown tool, a denied call or a raising
--- handler — is the kernel's. `beat_id` stamps both halves of every pair,
--- so the pair reads back as part of its beat.
---
--- Every block is decided before any of them runs. A policy that breaks its
--- contract therefore stops the beat with nothing dispatched and no
--- tool_call written, rather than half a response's worth of side effects
--- and a report that the config was wrong.
---
--- The handler and the policy are the caller's code, like fold and the llm,
--- but their raises are not traced: a raising handler or policy is closed
--- as DATA — the `result` of a tool_result, a durable record a later fold
--- reads back and sends to the model — and a record that carried a stack in
--- dev and not in prod would be two different histories. The traceback is
--- attached where a failure is *reported* (an Outcome the caller reads and
--- drops), never where one is *recorded*.
---
--- @param session userdata|table a knl session
--- @param device table a knl device
--- @param out table the model response being executed
--- @param beat_id string the id of the beat writing these events
--- @return table|nil summary one { call_id, name, ok } per tool_use
--- @return string|nil problem a device-contract violation (nothing ran)
local
--- One complete beat: gate, name itself, fold, filter, reserve, record,
--- call, record, run its tools. Two arguments and no bundle — the session
--- is the kernel's state, the device is the caller's policy, and neither is
--- mutated. Per-beat variation is the caller's: `knl.beat(s, d:with{ llm =
--- strong })`.
---
--- Re-entrant and stateless: a beat is decided entirely by its two
--- arguments, so it can be called from any driver, resumed, or interleaved.
---
--- Every syscall it makes is pcall'd and every failure comes back as an
--- Outcome — `err("state")`, carrying the kernel's own reading of the raise
--- (`detail.kind` / `detail.retryable`, `knl.shapes.error`). beat does NOT
--- act on `retryable`: a beat that quietly repeated a `busy` reserve would
--- be a loop nobody wrote and nobody bounded, and it would make a second
--- attempt at a call the caller may no longer want. Asking again is the
--- caller's loop's decision, and this is the value it decides from.
---
--- @param session userdata|table a knl session (knl.open / knl.resume)
--- @param device table a knl device (knl.device / d:with)
--- @return table outcome an `Outcome`
-- An internal exposed for the spec, which drives it directly.
M. = execute_tools
-- ============================================================
-- views — the query views this module ships
-- ============================================================
--
-- A view is a named function that runs one SELECT. That is the whole of the
-- mechanism: no builder, no query object, no registration hook. The kernel
-- publishes the table (`knl.shapes.schema`) and a caller writes SQL against
-- it, and these four are the ones the kernel ships because they read what
-- the kernel itself wrote — the beat grouping it stamps, the tool pairs it
-- closes, the ledger it keeps, the token counts the providers reported. A
-- consumer's own view is a function of exactly this form in exactly this way
-- (`local function tool_error_rate(s) return s:query([[...]]) end`); nothing
-- here is privileged.
--
-- They do not duplicate the built-in reads, which are `events(from)` and
-- `tail(n)` and nothing else. Token usage is NOT one of them: it is an
-- aggregate over the log like any other question a caller asks of it, so it
-- is `knl.views.usage` — one SELECT, in this file, on the same footing as a
-- view a consumer writes.
--
-- Two rules hold for every statement below and for a consumer's own:
--
-- * the streams being read are named by `$sessions`, never spliced in.
-- The kernel expands the token into one bound placeholder per id, so an
-- id is a value like any other and `opts.sessions` reads a set of
-- sessions with the same SQL that reads one;
-- * no value is concatenated into the text. What is written into these
-- statements is column names, the kernel's own kind vocabulary, and
-- nothing that came from a caller.
--
-- Which half of the stored event a statement reads decides what can break
-- it. `beat` is a COLUMN — the envelope's
-- correlation key — so `beats` groups on it and is untouched by any change
-- to what a kind carries. The rest reach into `data`, and each of those
-- paths is tied to one kind's shape: `tool_pairs` to the tool pair,
-- `ledger` to `budget_*`, `usage` to `llm_response`. A kind's shape and the
-- view that reads it change together, which is the whole reason the
-- structured half lives in one column instead of being spread over the row.
--- One row per beat: where it starts, where it ends, and what it wrote.
---
--- `kinds` is the beat's events in `seq` order, comma-joined. The order
--- comes from the ordered subquery rather than from `group_concat(kind ORDER
--- BY seq)`: the aggregate's own ORDER BY needs SQLite 3.44, and SQLite may
--- not flatten a subquery with an ORDER BY into an aggregating outer query,
--- so the rows reach the aggregate in the order the subquery put them.
---
--- Events with no `beat` — the session's own boundaries, the ledger, a
--- caller's seed message — are not part of any beat and are left out. The
--- grouping key is the `beat` COLUMN, so this view reads nothing out of any
--- kind's `data` and no change to one can reach it.
local BEATS_SQL = [[
SELECT beat,
MIN(seq) AS seq_from,
MAX(seq) AS seq_to,
group_concat(kind) AS kinds
FROM (SELECT beat,
stream,
seq,
kind
FROM events
WHERE stream IN $sessions
AND beat IS NOT NULL
ORDER BY stream, seq)
GROUP BY beat
ORDER BY seq_from, beat
]]
--- The tool pairs: a `tool_call` and the `tool_result` that answered it,
--- joined on the call id within one stream.
---
--- A call id is unique to the stream that minted it, so the join carries
--- `r.stream = c.stream` — without it a set of sessions read together could
--- pair one session's call with another's result.
---
--- A call with no result is not a pair and does not appear. That is the
--- point of the view: what it lists is the calls that were answered, and a
--- call left open by a run that died mid-tool is visible as its absence
--- (`beats` still shows the `tool_call` in its `kinds`).
--- The `beat` comes off the column and the rest out of `data`: this view is
--- tied to the shape of `tool_call` / `tool_result` (`knl.shapes.events`)
--- and moves with it.
local TOOL_PAIRS_SQL = [[
SELECT c.beat AS beat,
json_extract(c.data, '$.call_id') AS call_id,
json_extract(c.data, '$.name') AS name,
json_extract(r.data, '$.ok') AS ok
FROM events AS c
JOIN events AS r
ON r.stream = c.stream
AND r.kind = 'tool_result'
AND json_extract(r.data, '$.call_id') = json_extract(c.data, '$.call_id')
WHERE c.stream IN $sessions
AND c.kind = 'tool_call'
ORDER BY c.stream, c.seq
]]
--- The budget ledger: every `budget_*` event in order, with the amount and
--- the grant's tag read out of `data`. Those are kernel kinds, so their
--- `data` shape is the kernel's — this is the one view whose paths belong to
--- the other side of the syscall.
---
--- The four kinds are named rather than matched with a `LIKE 'budget_%'`:
--- they are the closed vocabulary the balance is a fold of (event.rs), and
--- `kind` is an indexed column, so naming them keeps the read the size of
--- the ledger rather than the size of the stream.
local LEDGER_SQL = [[
SELECT seq,
kind,
json_extract(data, '$.amount') AS amount,
json_extract(data, '$.tag') AS tag
FROM events
WHERE stream IN $sessions
AND kind IN ('budget_granted', 'budget_reserved', 'budget_refused', 'budget_spent')
ORDER BY stream, seq
]]
--- The token accounting: one row per stream, over the `llm_response` events
--- that stream recorded.
---
--- `calls` is how many answers landed and the three counters are what the
--- providers reported for them — facts already in the log, since an adapter
--- normalizes a provider's usage into the three numbers before the response
--- is ever appended. Nothing here is a budget: the grant is a quota the owner
--- gave (`ledger` is its reading), and no arithmetic connects the two.
---
--- A counter a stored response does not carry contributes 0: `json_extract`
--- answers NULL for a missing key, `SUM` skips it, and the `COALESCE` turns
--- an all-NULL sum back into a number so a caller never reads a nil count.
---
--- The grouping is by `stream`, which is what makes the row set answer for a
--- read across a set of sessions rather than blending them. A stream that
--- recorded no response has no row at all — that absence IS its zero, and
--- filling it in would mean naming the streams in the statement, which is
--- exactly what `$sessions` exists not to do.
local USAGE_SQL = [[
SELECT stream,
COUNT(*) AS calls,
COALESCE(SUM(json_extract(data, '$.usage.input_tokens')), 0) AS input_tokens,
COALESCE(SUM(json_extract(data, '$.usage.output_tokens')), 0) AS output_tokens,
COALESCE(SUM(json_extract(data, '$.usage.thinking_tokens')), 0) AS thinking_tokens
FROM events
WHERE stream IN $sessions
AND kind = 'llm_response'
GROUP BY stream
ORDER BY stream
]]
--- The session tree, rooted at the session the view is called on.
---
--- The one view that does not take its streams from `$sessions`, and the
--- reason is what a tree is: the set is not something a caller names, it is
--- what the log says was opened from what. So the root is `$stream` — this
--- session — and the walk follows `session_opened.data.parent` down from it
--- with a recursive CTE, which is a `WITH` statement and therefore a read
--- like any other (the query layer needed no change for this: a statement
--- sees the `events` table, and `$stream` / `$sessions` are values bound
--- into it rather than a fence around what it may look at).
---
--- `UNION` and not `UNION ALL`: a stream is in the subtree once, and the
--- duplicate-eliminating form is also what stops a `parent` cycle — which
--- the kernel does not prevent and a log written by hand could contain —
--- from running forever.
---
--- The three per-session readings are correlated subqueries rather than
--- joins, so a stream that recorded two endings (two handles that both
--- closed — the log keeps both) is still one row: the first ending is the
--- one reported, and `MIN(epoch_ms)` says the same for the opening.
---
--- `open_children` comes back as the JSON array text the close recorded,
--- because that is what the column holds: `json_extract` of an array is its
--- JSON, and re-encoding it into a Lua list here would be this view
--- inventing a shape the log does not have.
local TREE_SQL = [[
WITH RECURSIVE tree(session, parent) AS (
SELECT root.stream, json_extract(root.data, '$.parent')
FROM events AS root
WHERE root.kind = 'session_opened'
AND root.stream = $stream
UNION
SELECT child.stream, json_extract(child.data, '$.parent')
FROM events AS child, tree
WHERE child.kind = 'session_opened'
AND json_extract(child.data, '$.parent') = tree.session
)
SELECT t.session AS session,
t.parent AS parent,
(SELECT MIN(o.epoch_ms) FROM events AS o
WHERE o.stream = t.session AND o.kind = 'session_opened') AS opened_epoch_ms,
(SELECT MIN(c.epoch_ms) FROM events AS c
WHERE c.stream = t.session AND c.kind = 'session_closed') AS closed_epoch_ms,
(SELECT json_extract(c.data, '$.open_children') FROM events AS c
WHERE c.stream = t.session AND c.kind = 'session_closed'
ORDER BY c.seq LIMIT 1) AS open_children
FROM tree AS t
ORDER BY opened_epoch_ms, session
]]
--- Run one view's statement over `session`.
---
--- The options are the caller's, passed through untouched: `sessions` is
--- what makes a view span a set of streams, and `timeout_ms` / `limit` are
--- the same knobs any other read has. No view takes parameters of its own —
--- the only values any of them binds are the stream ids the kernel resolves
--- from `$sessions`.
---
--- `truncated` is handed back beside the rows rather than dropped: a view
--- that had more rows than the limit allowed has said so, and swallowing
--- that would leave a caller to guess from a suspiciously round count.
local
--- Whether a stored `ok` is true.
---
--- SQLite has no boolean: `json_extract` answers 1 / 0 for a JSON true /
--- false, and that is what crosses the bridge. The view declares an `ok`, so
--- the reading back into a boolean happens here — once, in the layer that
--- promised it — rather than in every caller.
local
M. =
--- One row per beat: `{ beat, seq_from, seq_to, kinds }`.
---
--- @param session userdata|table a knl session
--- @param opts table|nil query opts (`sessions` to span a set of streams)
--- @return table rows
--- @return boolean truncated
--- One row per answered tool call: `{ beat, call_id, name, ok }`.
---
--- The rows are rebuilt rather than edited in place, so reading a view never
--- writes to a table the caller can still be holding.
---
--- @param session userdata|table a knl session
--- @param opts table|nil query opts (`sessions` to span a set of streams)
--- @return table rows
--- @return boolean truncated
--- The budget ledger: `{ seq, kind, amount, tag }` in seq order.
---
--- @param session userdata|table a knl session
--- @param opts table|nil query opts (`sessions` to span a set of streams)
--- @return table rows
--- @return boolean truncated
--- The token accounting: `{ stream, calls, input_tokens, output_tokens,
--- thinking_tokens }`, one row per stream that answered.
---
--- @param session userdata|table a knl session
--- @param opts table|nil query opts (`sessions` to span a set of streams)
--- @return table rows
--- @return boolean truncated
--- The subtree rooted at `session`: `{ session, parent, opened_epoch_ms,
--- closed_epoch_ms, open_children }`, in the order the sessions opened.
---
--- The rows are the sessions the log says were opened from this one, however
--- deep. `parent` is nil on a session whose opening recorded none — the root
--- of the whole tree, which this session is not necessarily. `closed_epoch_ms`
--- is nil while a session is still running, and `open_children` is the JSON
--- array a close recorded when it ended with children that had not (see
--- `TREE_SQL`).
---
--- `opts.sessions` is not read: which streams are in a tree is what this view
--- answers, not something a caller names. `timeout_ms` and `limit` are the
--- same knobs as anywhere else, and a subtree bigger than the limit reports
--- `truncated` like any other read.
---
--- @param session userdata|table a knl session — the root of the walk
--- @param opts table|nil query opts (`timeout_ms` / `limit`)
--- @return table rows
--- @return boolean truncated
-- ============================================================
-- The registry, executed
-- ============================================================
--
-- `M.shapes.api` names the shape of every argument of every export. A
-- registry nobody runs is prose with a table around it — the entry drifts
-- from the function and nothing goes red — so in dev mode each declared
-- export is replaced, once, here at load, by a wrapper that holds the call
-- to its entry before letting it through. Prod is untouched: the exports
-- are the functions themselves and a call pays nothing, which is why this
-- is a gate and not the argument checking a function needs to be correct.
-- The checks a call must not get through WITHOUT (a device's config, a
-- filter's return, cost's bound) stay where they are, loud in both modes.
--
-- What the gate judges is the shape of the arguments that were PASSED. An
-- argument that is absent — not supplied, or supplied as nil — is left to
-- the function: which arguments are required, and what a missing one means,
-- is its own business, and `knl.beat(s, nil)` must go on answering
-- `Outcome.err("conf")` rather than raising. The registry answers for what
-- it was given.
--
-- The session userdata is deliberately NOT wrapped, in either mode. Its
-- arguments are checked in Rust, on every call, by the same types
-- `knl.shapes.session` declares (`bridge/knl.rs`, `from_lua`), so a direct
-- `s:append(...)` is held to its entry without a gate here — which is the
-- hole this used to have, since a caller reaches the session straight off
-- `knl.open` and never through an export of this module. A wrapper would
-- also have to hand back a proxy in place of the kernel's value, and both
-- `local s <close> = knl.open{...}` and `knl.open{ parent = s }` want the
-- userdata itself.
--- Wrap `fn` so every argument it is passed is held to `declared[i].shape`
--- (dev mode only — `assert_dev` is a no-op otherwise, and this wrapper is
--- not even installed in prod).
---
--- The hint names the registry entry and the position, so a violation reads
--- as a broken call to a declared API rather than as an anonymous shape
--- failure somewhere inside the module.
local
if shape.
return M