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
|
//! Long-lived Lua runtime, registered with libpanto as a single
//! `ToolSource`.
//!
//! This replaces the per-call `lua_State` model of phase 3 (LuaTool +
//! LuaStatePool). The CLI maintains exactly one `lua_State` for its
//! entire lifetime. Every extension is loaded into it once; extension
//! top-level code runs exactly once at startup. Tool handlers are
//! stored in the Lua registry and looked up by tool name on each call.
//!
//! libpanto delivers all tool calls targeting Lua-defined tools in one
//! `invoke_batch` per turn, on a single thread (see
//! `libpanto/src/tool_source.zig`). This runtime then runs each call as
//! a Lua *coroutine*. When (later) we wire in libuv via `luv`, a yield
//! inside a coroutine returns control to the runtime, which drives
//! `uv.run()` until any coroutine is resumable.
//!
//! For now (step 2 of LUA_MAKEOVER.md): no batteries yet. Each call's
//! coroutine runs to completion synchronously. A handler that yields
//! to nothing currently leaves the call permanently suspended — we
//! surface that as a `LuaHandlerYielded` error so it's at least visible.
//! Step 4 (install `luv`) and step 5 (wire `coro-*`) make yields
//! productive.
//!
//! Concurrency contract for source-backed tools: "coroutine-safe within
//! this runtime". Concurrent host entry into the same `lua_State` is
//! *not* safe; libpanto's grouped-dispatch guarantees this never happens.
const std = @import("std");
const Allocator = std.mem.Allocator;
const panto = @import("panto");
const lua_bridge = @import("lua_bridge.zig");
const c = lua_bridge.c;
const Io = std.Io;
pub const SOURCE_NAME = "panto-lua";
/// Errors produced by the runtime above and beyond bridge errors.
pub const RuntimeError = error{
LuaInitFailed,
LuaHandlerNotFound,
LuaHandlerYielded,
LuaHandlerCrashed,
BadHandlerReturn,
InputNotJsonObject,
OutOfMemory,
};
/// Owned state for the runtime.
pub const LuaRuntime = struct {
allocator: Allocator,
L: *c.lua_State,
/// Tool declarations for the `ToolSource`, owned by this runtime.
decls: std.array_list.Managed(panto.ToolDecl),
/// Backing byte buffers for every string referenced by `decls`.
strings: std.array_list.Managed([]u8),
/// Map from tool name (borrowed from `decls`) to its handler ref in
/// the Lua registry (`luaL_ref` index).
handlers: std.StringHashMap(c_int),
/// Registry ref to the wrapper closure that runs a user handler
/// inside a `pcall` and reports the result back to Zig via
/// `panto._record_result`. Allocated once at `create`; reused for
/// every call. `0` until `installScheduler` runs.
wrapper_ref: c_int = 0,
/// Registry ref to `require("luv").run`, the function we call to
/// tick libuv between coroutine resumes. `0` until
/// `installScheduler` runs.
uv_run_ref: c_int = 0,
/// Registry ref to `require("luv").loop_alive`, used by the
/// scheduler to detect handler coroutines that yielded without
/// arming any libuv work (a deadlock we surface rather than hang
/// on). `0` until `installScheduler` runs.
uv_loop_alive_ref: c_int = 0,
/// Pointer to the in-flight batch, valid only for the duration of
/// one `invoke_batch` call. The `panto._record_result` C function
/// writes through this. `null` between batches; not concurrently
/// accessible (libpanto's source-grouped dispatch guarantees one
/// thread per source per turn).
current_batch: ?*BatchState = null,
/// Create a new runtime. The `lua_State` is opened, standard libs
/// loaded, and the `panto.register_tool` bridge installed.
pub fn create(allocator: Allocator) !*LuaRuntime {
const self = try allocator.create(LuaRuntime);
errdefer allocator.destroy(self);
const L = c.luaL_newstate() orelse return RuntimeError.LuaInitFailed;
errdefer c.lua_close(L);
c.luaL_openlibs(L);
lua_bridge.install(L);
self.* = .{
.allocator = allocator,
.L = L,
.decls = std.array_list.Managed(panto.ToolDecl).init(allocator),
.strings = std.array_list.Managed([]u8).init(allocator),
.handlers = std.StringHashMap(c_int).init(allocator),
};
return self;
}
/// Install the libuv-driven coroutine scheduler:
/// - Register `panto._record_result` (C function with `self` as
/// light-userdata upvalue) so the wrapper closure can hand
/// results back to Zig.
/// - Create the wrapper closure that runs a user handler in
/// `pcall` and reports the result.
/// - Cache `require("luv").run` for fast per-tick access.
///
/// Must be called after luarocks bootstrap has installed luv,
/// otherwise the `require("luv")` step will fail.
pub fn installScheduler(self: *LuaRuntime) !void {
try installRecordResult(self);
try installWrapperClosure(self);
try cacheUvRun(self);
}
/// Tear down the runtime: free every owned string, unref every
/// handler, close the Lua state.
pub fn deinit(self: *LuaRuntime) void {
// Unref handlers so future GCs collect them. Not strictly
// necessary since we close the state next, but it documents
// intent.
var hit = self.handlers.iterator();
while (hit.next()) |entry| {
c.luaL_unref(self.L, lua_bridge.LUA_REGISTRYINDEX, entry.value_ptr.*);
}
self.handlers.deinit();
if (self.wrapper_ref != 0) {
c.luaL_unref(self.L, lua_bridge.LUA_REGISTRYINDEX, self.wrapper_ref);
}
if (self.uv_run_ref != 0) {
c.luaL_unref(self.L, lua_bridge.LUA_REGISTRYINDEX, self.uv_run_ref);
}
if (self.uv_loop_alive_ref != 0) {
c.luaL_unref(self.L, lua_bridge.LUA_REGISTRYINDEX, self.uv_loop_alive_ref);
}
c.lua_close(self.L);
self.decls.deinit();
for (self.strings.items) |s| self.allocator.free(s);
self.strings.deinit();
self.allocator.destroy(self);
}
/// Load and execute one Lua extension script in this runtime.
///
/// `package_root`, if provided, is prepended to `package.path` so
/// `require` finds sibling modules.
///
/// All `panto.register_tool` calls in the script run during this
/// call. The runtime then harvests the registrations table,
/// transfers handler functions into the Lua registry (one `luaL_ref`
/// per tool), and records each tool's metadata in `self.decls`.
pub fn loadExtension(
self: *LuaRuntime,
script_path: []const u8,
package_root: ?[]const u8,
) !void {
const path_z = try self.allocator.dupeZ(u8, script_path);
defer self.allocator.free(path_z);
// Reset the registrations table to empty so we only harvest the
// calls made by *this* script (not accumulated from prior ones).
// The bridge re-installs the registrations table when called;
// we want to call only that subset. Instead of re-installing
// everything (which would also reset the panto global, fine),
// create a fresh registrations table directly via the bridge.
lua_bridge.resetRegistrations(self.L);
if (package_root) |root| {
const root_z = try self.allocator.dupeZ(u8, root);
defer self.allocator.free(root_z);
try prependPackagePath(self.L, root_z);
}
lua_bridge.loadFile(self.L, path_z) catch |err| {
logTopAsError(self.L, "lua: failed to load extension");
return err;
};
// Harvest the registrations table into our state.
try self.harvestAndStoreHandlers();
}
/// Load a single-tool Lua script and register the table it returns
/// as if `panto.register_tool` had been called on that table.
///
/// The script's top-level chunk must return a table with the same
/// shape that `panto.register_tool` accepts:
/// `{ name, description, schema, handler }`. This is the ergonomic
/// form supported under a `tools/` directory.
pub fn loadTool(
self: *LuaRuntime,
script_path: []const u8,
package_root: ?[]const u8,
) !void {
const path_z = try self.allocator.dupeZ(u8, script_path);
defer self.allocator.free(path_z);
lua_bridge.resetRegistrations(self.L);
if (package_root) |root| {
const root_z = try self.allocator.dupeZ(u8, root);
defer self.allocator.free(root_z);
try prependPackagePath(self.L, root_z);
}
// Run the file expecting exactly one returned value (the tool
// table). Use luaL_loadfilex + lua_pcallk directly so we can
// ask for a return value (the bridge's loadFile discards them).
//
// Push `panto.register_tool` *first*, then load+run the chunk so
// its return value naturally lands above it; calling pcall then
// consumes both in the right order.
const L = self.L;
_ = c.lua_getglobal(L, "panto");
_ = c.lua_getfield(L, -1, "register_tool");
c.lua_copy(L, -1, -2); // overwrite `panto` with `register_tool`
c.lua_settop(L, c.lua_gettop(L) - 1); // pop the duplicate
// Stack: ..., register_tool
if (c.luaL_loadfilex(L, path_z.ptr, null) != 0) {
logTopAsError(L, "lua: failed to load tool");
c.lua_settop(L, c.lua_gettop(L) - 2); // pop err + register_tool
return error.LuaLoadFailed;
}
if (c.lua_pcallk(L, 0, 1, 0, 0, null) != 0) {
logTopAsError(L, "lua: failed to run tool");
c.lua_settop(L, c.lua_gettop(L) - 2); // pop err + register_tool
return error.LuaRunFailed;
}
// Stack: ..., register_tool, returned_value
if (c.lua_type(L, -1) != lua_bridge.T_TABLE) {
c.lua_settop(L, c.lua_gettop(L) - 2); // pop both
std.log.err(
"lua: tool script '{s}' must return a table",
.{script_path},
);
return error.BadRegistration;
}
// Invoke register_tool(returned_table). Same validation, schema
// serialization, and registrations-table append logic as an
// extension's `panto.register_tool` call.
if (c.lua_pcallk(L, 1, 0, 0, 0, null) != 0) {
logTopAsError(L, "lua: register_tool failed for tool script");
return error.LuaRunFailed;
}
try self.harvestAndStoreHandlers();
}
/// Walk the registrations table that the script just populated.
/// For each entry:
/// - Copy `name`, `description`, `schema_json` into owned bytes.
/// - Pop the `handler` function and `luaL_ref` it into the
/// registry; record the ref under `handlers[name]`.
/// - Append a `ToolDecl` to `self.decls`.
fn harvestAndStoreHandlers(self: *LuaRuntime) !void {
const L = self.L;
// Push the registrations table onto the stack.
_ = c.lua_rawgetp(L, lua_bridge.LUA_REGISTRYINDEX, &lua_bridge.registrations_key);
defer c.lua_settop(L, c.lua_gettop(L) - 1);
const n: usize = @intCast(c.lua_rawlen(L, -1));
var i: usize = 1;
while (i <= n) : (i += 1) {
_ = c.lua_rawgeti(L, -1, @intCast(i)); // push record
// record at -1; bridge's records are 4-field tables.
const name = try self.readStringFieldOwned("name");
errdefer {
// If anything below fails after the name was added to
// strings, the global deinit still cleans up; nothing
// extra to undo here for the string itself. But we
// *do* need to make sure the handlers map and decls
// remain consistent. We allocate after the string adds,
// so partial state is "string captured but no decl"
// — harmless.
}
const desc = try self.readStringFieldOwned("description");
const schema = try self.readStringFieldOwned("schema_json");
// Pop handler function -> luaL_ref into the registry.
_ = c.lua_getfield(L, -1, "handler");
if (c.lua_type(L, -1) != lua_bridge.T_FUNCTION) {
c.lua_settop(L, c.lua_gettop(L) - 2); // pop handler + record
return RuntimeError.LuaHandlerNotFound;
}
const ref = c.luaL_ref(L, lua_bridge.LUA_REGISTRYINDEX);
// Stack: ..., regs_table, record
const decl: panto.ToolDecl = .{
.name = name,
.description = desc,
.schema_json = schema,
};
// Duplicate names within the runtime are not allowed —
// libpanto will also catch them at registry insertion, but
// we want a Lua-side error before we've started talking to
// libpanto.
const gop = try self.handlers.getOrPut(name);
if (gop.found_existing) {
c.luaL_unref(L, lua_bridge.LUA_REGISTRYINDEX, ref);
c.lua_settop(L, c.lua_gettop(L) - 1); // pop record
return error.DuplicateTool;
}
gop.value_ptr.* = ref;
try self.decls.append(decl);
c.lua_settop(L, c.lua_gettop(L) - 1); // pop record
}
}
fn readStringFieldOwned(self: *LuaRuntime, field_name: [:0]const u8) ![]const u8 {
const L = self.L;
_ = c.lua_getfield(L, -1, field_name.ptr);
defer c.lua_settop(L, c.lua_gettop(L) - 1);
if (c.lua_type(L, -1) != lua_bridge.T_STRING) return error.BadRegistration;
var len: usize = 0;
const ptr = c.lua_tolstring(L, -1, &len);
if (ptr == null) return error.BadRegistration;
const owned = try self.allocator.dupe(u8, ptr[0..len]);
try self.strings.append(owned);
return owned;
}
/// Build a `ToolSource` that hands `invoke_batch` calls back to
/// this runtime. The source's `ctx` is `self`. The runtime keeps
/// ownership of `self`'s allocation; libpanto's registry only
/// frees `ctx` via the source's `vtable.deinit` (which we make a
/// no-op — the runtime is owned by the embedder).
///
/// Callers must keep the LuaRuntime alive at least as long as the
/// registry holds the source.
pub fn toolSource(self: *LuaRuntime) panto.ToolSource {
return .{
.name = SOURCE_NAME,
.tools = self.decls.items,
.ctx = self,
.vtable = &source_vtable,
};
}
/// Number of tools currently declared by extensions loaded into
/// this runtime.
pub fn toolCount(self: *const LuaRuntime) usize {
return self.decls.items.len;
}
/// Drop every declared tool whose registered name is rejected by
/// `permits`. The handler ref is unref'd and the decl removed.
/// Returns the number of tools dropped.
///
/// String storage for a dropped tool's name/description/schema is
/// left in `self.strings` (freed at `deinit`); only the decl entry
/// and the Lua handler ref are reclaimed eagerly. This keeps the
/// filter simple — we never need to find-and-free individual
/// strings out of the shared pool.
pub fn filterTools(
self: *LuaRuntime,
ctx: anytype,
comptime permits: fn (@TypeOf(ctx), []const u8) bool,
) usize {
var dropped: usize = 0;
var i: usize = 0;
while (i < self.decls.items.len) {
const name = self.decls.items[i].name;
if (permits(ctx, name)) {
i += 1;
continue;
}
// Unref the handler, if present.
if (self.handlers.fetchRemove(name)) |kv| {
c.luaL_unref(self.L, lua_bridge.LUA_REGISTRYINDEX, kv.value);
}
_ = self.decls.orderedRemove(i);
dropped += 1;
}
return dropped;
}
};
const source_vtable: panto.ToolSource.VTable = .{
.invoke_batch = invokeBatch,
.deinit = deinitSrc,
};
fn deinitSrc(_: *anyopaque, _: Allocator) void {
// The runtime is owned by the embedder (main()). It explicitly
// calls `runtime.deinit()` after the agent has been torn down.
// libpanto's source.deinit here is a no-op.
}
// ===========================================================================
// Scheduler: libuv-driven cooperative coroutine dispatch
// ===========================================================================
//
// libpanto's `invoke_batch` delivers all of a turn's tool-call requests
// at once, on a single thread. We answer the contract by running each
// call as a Lua coroutine inside our long-lived `lua_State`, then
// driving `uv.run("once")` to wake any of those coroutines that are
// blocked on libuv-aware I/O. This is the entire scheduler — luv's
// libuv binding does the actual event-loop work; we just resume
// coroutines and call `run` between resumes.
//
// Capturing return values requires a wrapper. When a coroutine is
// resumed by a luv callback after yielding, the eventual return value
// of the coroutine flows back to *that callback*, not to us. So we
// install a Lua wrapper closure that does
//
// pcall(handler, input) → panto._record_result(idx, ok, val)
//
// before the handler returns. `_record_result` is a C function that
// stores into a per-runtime `BatchState`, accessed via a light-userdata
// upvalue carrying the runtime pointer.
/// One coroutine's outcome, recorded by `_record_result` and read by
/// `invokeBatch` once the coroutine has terminated.
const Slot = struct {
/// Set true the moment `_record_result` writes a result for this
/// index. Used to detect coroutines that terminated without
/// calling the wrapper (a bug / API misuse).
recorded: bool = false,
/// `true` if the handler returned cleanly, `false` if it raised
/// via the `pcall` wrapping.
ok: bool = false,
/// Result payload as owned bytes. Allocated from `allocator`.
/// Caller frees.
value: ?[]u8 = null,
/// On `ok = false`, an owned copy of the error message.
err_msg: ?[]u8 = null,
};
/// State shared between Zig and the in-flight Lua wrapper closure.
const BatchState = struct {
allocator: Allocator,
slots: []Slot,
};
fn invokeBatch(
ctx: *anyopaque,
calls: []const panto.ToolCall,
results: []panto.ToolCallResult,
allocator: Allocator,
) anyerror!void {
const self: *LuaRuntime = @ptrCast(@alignCast(ctx));
return runBatch(self, calls, results, allocator);
}
fn runBatch(
self: *LuaRuntime,
calls: []const panto.ToolCall,
results: []panto.ToolCallResult,
allocator: Allocator,
) !void {
if (self.wrapper_ref == 0 or self.uv_run_ref == 0) {
// Scheduler not installed. We can still run synchronous
// handlers — use the legacy path that drives one coroutine at
// a time without an event loop.
for (calls, 0..) |call, i| {
results[i] = runLegacySync(self, call, allocator);
}
return;
}
var slots = try allocator.alloc(Slot, calls.len);
defer allocator.free(slots);
for (slots) |*s| s.* = .{};
var batch_state: BatchState = .{ .allocator = allocator, .slots = slots };
self.current_batch = &batch_state;
defer self.current_batch = null;
// Track each call's coroutine reference in the parent stack (we
// hold them in registry refs so they survive across `uv.run`
// ticks). `0` after a coroutine has been reaped.
var thread_refs = try allocator.alloc(c_int, calls.len);
defer allocator.free(thread_refs);
@memset(thread_refs, 0);
defer for (thread_refs) |r| {
if (r != 0) c.luaL_unref(self.L, lua_bridge.LUA_REGISTRYINDEX, r);
};
var pending: usize = 0;
for (calls, 0..) |call, i| {
const handler_ref = self.handlers.get(call.tool_name) orelse {
// Synthesize a recorded "err" result; don't even bother
// spawning a coroutine.
slots[i] = .{
.recorded = true,
.ok = false,
.err_msg = try allocator.dupe(u8, "panto: unknown tool name"),
};
continue;
};
const t = try startCoroutine(self, i, handler_ref, call.input, allocator);
thread_refs[i] = t.thread_ref;
if (t.still_pending) pending += 1;
}
while (pending > 0) {
try driveUvOnce(self);
// Reap any coroutines that terminated during the tick.
var reaped: usize = 0;
for (thread_refs, 0..) |tref, i| {
if (tref == 0) continue;
// Push the thread, check status, pop.
_ = c.lua_rawgeti(self.L, lua_bridge.LUA_REGISTRYINDEX, tref);
const co: *c.lua_State = @ptrCast(c.lua_tothread(self.L, -1).?);
const status = c.lua_status(co);
c.lua_settop(self.L, c.lua_gettop(self.L) - 1);
if (status != c.LUA_YIELD) {
// Terminated (LUA_OK or error). The wrapper should
// have called `_record_result` already; if not, synthesize.
if (!slots[i].recorded) {
slots[i] = .{
.recorded = true,
.ok = false,
.err_msg = try allocator.dupe(
u8,
"panto: handler terminated without recording a result",
),
};
}
c.luaL_unref(self.L, lua_bridge.LUA_REGISTRYINDEX, tref);
thread_refs[i] = 0;
reaped += 1;
}
}
if (reaped > 0) {
if (reaped > pending) {
// Defensive: keep the counter sane.
pending = 0;
} else {
pending -= reaped;
}
continue;
}
if (!try loopAlive(self)) {
// No libuv handles are pending, but we still have alive
// coroutines. They yielded without arranging to be woken.
// Mark them as failed and break.
//
// Note: we ask `uv.loop_alive` rather than relying on the
// return value of `uv.run("once")`, which is a boolean
// signalling whether `uv.stop()` was called — not a count
// of active handles. Conflating the two used to break
// multi-tick tools (e.g. `bash`) on their second tick.
for (thread_refs, 0..) |tref, i| {
if (tref == 0) continue;
slots[i] = .{
.recorded = true,
.ok = false,
.err_msg = try allocator.dupe(
u8,
"panto: handler yielded but no libuv handle is pending; " ++
"did you forget to await with luv?",
),
};
c.luaL_unref(self.L, lua_bridge.LUA_REGISTRYINDEX, tref);
thread_refs[i] = 0;
}
break;
}
}
// Translate slots into the libpanto-shaped results.
//
// Important: a handler that raised (`ok == false`) or otherwise
// misbehaved (`!recorded`) is surfaced to the model as an `.ok`
// result whose body is the formatted error message. We do *not*
// return `.err` here, because libpanto treats any per-call `.err`
// as an unrecoverable failure that aborts the entire turn (see
// `agent.dispatchToolCalls`). Aborting the turn over a Lua-level
// bug — in either a builtin tool or a user extension — is far
// more disruptive than handing the model a readable error and
// letting it correct course on the next turn.
for (slots, 0..) |slot, i| {
if (!slot.recorded) {
results[i] = .{
.ok = try formatToolError(
allocator,
calls[i].tool_name,
"handler terminated without recording a result",
),
};
continue;
}
if (slot.ok) {
results[i] = .{ .ok = slot.value orelse try allocator.dupe(u8, "") };
// Free the err_msg if both ended up set somehow.
if (slot.err_msg) |m| allocator.free(m);
} else {
if (slot.value) |v| allocator.free(v);
std.log.warn(
"panto-lua: tool '{s}' failed: {s}",
.{
calls[i].tool_name,
slot.err_msg orelse "(no message)",
},
);
results[i] = .{
.ok = try formatToolError(
allocator,
calls[i].tool_name,
slot.err_msg orelse "(no message)",
),
};
if (slot.err_msg) |m| allocator.free(m);
}
}
}
/// Format a tool-level failure as a textual result the model can read.
/// The prefix mirrors what the user sees in `panto-lua` log lines so
/// the model and the developer are looking at the same string.
fn formatToolError(
allocator: Allocator,
tool_name: []const u8,
message: []const u8,
) ![]u8 {
return std.fmt.allocPrint(
allocator,
"panto-lua: tool '{s}' failed: {s}",
.{ tool_name, message },
);
}
/// Start one coroutine: create a thread under the runtime's lua_State,
/// push the wrapper closure + (idx, handler, input), `lua_resume` once.
///
/// If the coroutine returns immediately (sync handler), the wrapper
/// has already recorded its result via `panto._record_result` —
/// `still_pending` will be `false`.
fn startCoroutine(
self: *LuaRuntime,
idx: usize,
handler_ref: c_int,
input: []const u8,
allocator: Allocator,
) !struct { thread_ref: c_int, still_pending: bool } {
const L = self.L;
const co = c.lua_newthread(L) orelse return RuntimeError.LuaInitFailed;
// luaL_ref pops the topmost value (the thread) and returns a
// registry ref to it. We keep the ref alive for the lifetime of
// the call so GC doesn't collect the thread mid-yield.
const thread_ref = c.luaL_ref(L, lua_bridge.LUA_REGISTRYINDEX);
// Push the wrapper onto the coroutine's stack.
_ = c.lua_rawgeti(co, lua_bridge.LUA_REGISTRYINDEX, @intCast(self.wrapper_ref));
// Push (idx, handler, input) as the resume args.
c.lua_pushinteger(co, @intCast(idx));
_ = c.lua_rawgeti(co, lua_bridge.LUA_REGISTRYINDEX, @intCast(handler_ref));
var arena_state = std.heap.ArenaAllocator.init(allocator);
defer arena_state.deinit();
try lua_bridge.pushJsonAsLua(co, arena_state.allocator(), input);
var nres: c_int = 0;
const status = c.lua_resume(co, L, 3, &nres);
return .{
.thread_ref = thread_ref,
.still_pending = status == c.LUA_YIELD,
};
}
/// Call `uv.run("once")`. The return value (a boolean meaning "was
/// `uv.stop()` called with handles still alive?") is not useful to us
/// — to decide whether to keep ticking we call `loopAlive` separately.
fn driveUvOnce(self: *LuaRuntime) !void {
const L = self.L;
_ = c.lua_rawgeti(L, lua_bridge.LUA_REGISTRYINDEX, @intCast(self.uv_run_ref));
_ = c.lua_pushlstring(L, "once", 4);
if (c.lua_pcallk(L, 1, 1, 0, 0, null) != 0) {
logTopAsError(L, "panto-lua: uv.run failed");
c.lua_settop(L, c.lua_gettop(L) - 1);
return error.UvRunFailed;
}
// Discard the boolean return value.
c.lua_settop(L, c.lua_gettop(L) - 1);
}
/// Call `uv.loop_alive()`. Returns true iff libuv has any referenced
/// active handles, requests, or closing handles. We use this — not
/// the return value of `uv.run` — to detect coroutines that yielded
/// without arranging to be woken.
fn loopAlive(self: *LuaRuntime) !bool {
const L = self.L;
_ = c.lua_rawgeti(L, lua_bridge.LUA_REGISTRYINDEX, @intCast(self.uv_loop_alive_ref));
if (c.lua_pcallk(L, 0, 1, 0, 0, null) != 0) {
logTopAsError(L, "panto-lua: uv.loop_alive failed");
c.lua_settop(L, c.lua_gettop(L) - 1);
return error.UvRunFailed;
}
const alive = c.lua_toboolean(L, -1) != 0;
c.lua_settop(L, c.lua_gettop(L) - 1);
return alive;
}
/// Pre-scheduler fallback (used in unit tests and during early
/// startup before `installScheduler` has run).
fn runLegacySync(
self: *LuaRuntime,
call: panto.ToolCall,
allocator: Allocator,
) panto.ToolCallResult {
const handler_ref = self.handlers.get(call.tool_name) orelse {
const bytes = formatToolError(
allocator,
call.tool_name,
"unknown tool name",
) catch return .{ .err = error.OutOfMemory };
return .{ .ok = bytes };
};
var err_msg: ?[]u8 = null;
defer if (err_msg) |m| allocator.free(m);
const out_bytes = invokeCoroutineSync(
self.L,
handler_ref,
call.input,
allocator,
&err_msg,
) catch |e| {
// Surface the failure to the model as a textual `.ok` result
// rather than aborting the turn. Prefer the Lua-side error
// message (captured into `err_msg` by invokeCoroutineSync
// when available); fall back to the typed error name.
const message: []const u8 = err_msg orelse @errorName(e);
const bytes = formatToolError(
allocator,
call.tool_name,
message,
) catch return .{ .err = error.OutOfMemory };
return .{ .ok = bytes };
};
return .{ .ok = out_bytes };
}
/// Run a handler synchronously, with no event loop. On Lua-level
/// failure the error message string is duped into `*err_msg_out`
/// (caller owns) before returning the typed error. `err_msg_out` is
/// only written on the error path; on success it is left untouched.
fn invokeCoroutineSync(
L: *c.lua_State,
handler_ref: c_int,
input: []const u8,
allocator: Allocator,
err_msg_out: *?[]u8,
) ![]u8 {
const co = c.lua_newthread(L) orelse return RuntimeError.LuaInitFailed;
defer c.lua_settop(L, c.lua_gettop(L) - 1);
_ = c.lua_rawgeti(co, lua_bridge.LUA_REGISTRYINDEX, @intCast(handler_ref));
if (c.lua_type(co, -1) != lua_bridge.T_FUNCTION) {
return RuntimeError.LuaHandlerNotFound;
}
var arena_state = std.heap.ArenaAllocator.init(allocator);
defer arena_state.deinit();
try lua_bridge.pushJsonAsLua(co, arena_state.allocator(), input);
var nresults: c_int = 0;
const status = c.lua_resume(co, L, 1, &nresults);
switch (status) {
c.LUA_OK => {
if (nresults < 1) return RuntimeError.BadHandlerReturn;
return try lua_bridge.readHandlerResult(co, -1, allocator);
},
c.LUA_YIELD => {
const msg = "lua: tool handler yielded with no event loop installed; call installScheduler() before dispatching";
if (@import("builtin").is_test) {
std.log.warn("{s}", .{msg});
} else {
std.log.err("{s}", .{msg});
}
return RuntimeError.LuaHandlerYielded;
},
else => {
// Capture the Lua error message into the caller's slot
// *before* logging+returning, so the legacy sync path can
// surface it to the model rather than just the typed
// error name.
var msg_len: usize = 0;
const msg_ptr = c.lua_tolstring(co, -1, &msg_len);
if (msg_ptr != null) {
err_msg_out.* = allocator.dupe(u8, msg_ptr[0..msg_len]) catch null;
}
logTopAsError(co, "lua: handler crashed");
return RuntimeError.LuaHandlerCrashed;
},
}
}
// ---------------------------------------------------------------------------
// Scheduler setup (called once at startup, after luarocks bootstrap)
// ---------------------------------------------------------------------------
/// Register `panto._record_result(idx, ok, value)` on the `panto`
/// global. The C function carries the runtime pointer as an upvalue,
/// reaches the in-flight `BatchState` through `current_batch`, and
/// stores into the matching slot.
fn installRecordResult(self: *LuaRuntime) !void {
const L = self.L;
_ = c.lua_getglobal(L, "panto");
if (c.lua_type(L, -1) != lua_bridge.T_TABLE) {
c.lua_settop(L, c.lua_gettop(L) - 1);
return RuntimeError.LuaInitFailed;
}
c.lua_pushlightuserdata(L, @ptrCast(self));
c.lua_pushcclosure(L, recordResultC, 1);
c.lua_setfield(L, -2, "_record_result");
c.lua_settop(L, c.lua_gettop(L) - 1); // pop `panto`
}
fn recordResultC(L: ?*c.lua_State) callconv(.c) c_int {
const Lst = L.?;
const self_ptr = c.lua_touserdata(Lst, c.lua_upvalueindex(1));
if (self_ptr == null) return 0;
const self: *LuaRuntime = @ptrCast(@alignCast(self_ptr.?));
const batch = self.current_batch orelse return 0;
const idx_i64 = c.lua_tointegerx(Lst, 1, null);
const ok = c.lua_toboolean(Lst, 2) != 0;
const idx: usize = @intCast(idx_i64);
if (idx >= batch.slots.len) return 0;
if (ok) {
// Result value at index 3. The handler's return type is
// free-form; we serialize via the existing `readHandlerResult`
// helper which already knows how to JSON-encode any Lua value.
const value = lua_bridge.readHandlerResult(Lst, 3, batch.allocator) catch |e| {
// Allocation failure mid-callback is unrecoverable from
// Lua's POV; record a synthetic error and bail.
const msg = std.fmt.allocPrint(
batch.allocator,
"panto: failed to serialize handler result: {s}",
.{@errorName(e)},
) catch null;
batch.slots[idx] = .{ .recorded = true, .ok = false, .err_msg = msg };
return 0;
};
batch.slots[idx] = .{ .recorded = true, .ok = true, .value = value };
} else {
// Error message at index 3. May be any Lua value; coerce to
// string via `tostring`-equivalent semantics.
var len: usize = 0;
const ptr = c.luaL_tolstring(Lst, 3, &len);
const owned = if (ptr != null)
batch.allocator.dupe(u8, ptr[0..len]) catch null
else
null;
c.lua_settop(Lst, c.lua_gettop(Lst) - 1); // pop tolstring's pushed string
batch.slots[idx] = .{ .recorded = true, .ok = false, .err_msg = owned };
}
return 0;
}
/// Create the per-call wrapper closure:
///
/// local function wrapper(idx, handler, input)
/// local ok, val = pcall(handler, input)
/// panto._record_result(idx, ok, val)
/// end
///
/// Stored in the Lua registry under `self.wrapper_ref`.
fn installWrapperClosure(self: *LuaRuntime) !void {
const L = self.L;
const snippet =
\\return function(idx, handler, input)
\\ local ok, val = pcall(handler, input)
\\ panto._record_result(idx, ok, val)
\\end
;
if (c.luaL_loadstring(L, snippet) != 0) {
logTopAsError(L, "panto-lua: wrapper closure failed to compile");
c.lua_settop(L, c.lua_gettop(L) - 1);
return RuntimeError.LuaInitFailed;
}
if (c.lua_pcallk(L, 0, 1, 0, 0, null) != 0) {
logTopAsError(L, "panto-lua: wrapper closure failed to evaluate");
c.lua_settop(L, c.lua_gettop(L) - 1);
return RuntimeError.LuaInitFailed;
}
// Top of stack: the wrapper function. luaL_ref pops it.
self.wrapper_ref = c.luaL_ref(L, lua_bridge.LUA_REGISTRYINDEX);
}
/// Cache `require("luv").run` and `require("luv").loop_alive` in the
/// registry so the scheduler can invoke them cheaply per tick.
fn cacheUvRun(self: *LuaRuntime) !void {
const L = self.L;
const snippet =
\\local uv = require("luv")
\\return uv.run, uv.loop_alive
;
if (c.luaL_loadstring(L, snippet) != 0) {
logTopAsError(L, "panto-lua: failed to compile luv lookup");
c.lua_settop(L, c.lua_gettop(L) - 1);
return RuntimeError.LuaInitFailed;
}
if (c.lua_pcallk(L, 0, 2, 0, 0, null) != 0) {
logTopAsError(L, "panto-lua: require('luv') failed (was the bootstrap successful?)");
c.lua_settop(L, c.lua_gettop(L) - 1);
return RuntimeError.LuaInitFailed;
}
// Stack: [..., uv.run, uv.loop_alive]. luaL_ref pops the top.
if (c.lua_type(L, -1) != lua_bridge.T_FUNCTION or
c.lua_type(L, -2) != lua_bridge.T_FUNCTION)
{
c.lua_settop(L, c.lua_gettop(L) - 2);
return RuntimeError.LuaInitFailed;
}
self.uv_loop_alive_ref = c.luaL_ref(L, lua_bridge.LUA_REGISTRYINDEX);
self.uv_run_ref = c.luaL_ref(L, lua_bridge.LUA_REGISTRYINDEX);
}
// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------
fn prependPackagePath(L: *c.lua_State, root: [:0]const u8) !void {
const snippet =
\\local root = ...
\\package.path = root .. "/?.lua;" .. root .. "/?/init.lua;" .. package.path
;
if (c.luaL_loadstring(L, snippet) != 0) {
logTopAsError(L, "lua: package.path loader failed to compile");
return error.LuaPackagePathLoadFailed;
}
_ = c.lua_pushlstring(L, root.ptr, root.len);
if (c.lua_pcallk(L, 1, 0, 0, 0, null) != 0) {
logTopAsError(L, "lua: package.path setup failed");
return error.LuaPackagePathSetupFailed;
}
}
fn logTopAsError(L: *c.lua_State, prefix: []const u8) void {
var len: usize = 0;
const msg = c.lua_tolstring(L, -1, &len);
const is_test = @import("builtin").is_test;
if (msg != null) {
if (is_test) {
std.log.warn("{s}: {s}", .{ prefix, msg[0..len] });
} else {
std.log.err("{s}: {s}", .{ prefix, msg[0..len] });
}
} else {
if (is_test) {
std.log.warn("{s} (no error message)", .{prefix});
} else {
std.log.err("{s} (no error message)", .{prefix});
}
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
const testing = std.testing;
fn writeTempScript(dir: Io.Dir, name: []const u8, source: []const u8) ![]const u8 {
try dir.writeFile(testing.io, .{ .sub_path = name, .data = source });
var buf: [std.fs.max_path_bytes]u8 = undefined;
const n = try dir.realPathFile(testing.io, name, &buf);
return testing.allocator.dupe(u8, buf[0..n]);
}
test "loadExtension records tool decls" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const source =
\\panto.register_tool {
\\ name = "greet", description = "Says hi.",
\\ schema = { type = "object", properties = { name = { type = "string" } } },
\\ handler = function(input) return "hi, " .. input.name end,
\\}
;
const path = try writeTempScript(tmp.dir, "greet.lua", source);
defer testing.allocator.free(path);
var rt = try LuaRuntime.create(testing.allocator);
defer rt.deinit();
try rt.loadExtension(path, null);
try testing.expectEqual(@as(usize, 1), rt.toolCount());
try testing.expectEqualStrings("greet", rt.decls.items[0].name);
}
test "invokeBatch runs each call through a coroutine and returns the result" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const source =
\\panto.register_tool {
\\ name = "echo", description = "echoes",
\\ schema = { type = "object", properties = { msg = { type = "string" } } },
\\ handler = function(input) return "got: " .. input.msg end,
\\}
\\panto.register_tool {
\\ name = "shout", description = "shouts",
\\ schema = { type = "object", properties = { msg = { type = "string" } } },
\\ handler = function(input) return input.msg:upper() .. "!" end,
\\}
;
const path = try writeTempScript(tmp.dir, "ext.lua", source);
defer testing.allocator.free(path);
var rt = try LuaRuntime.create(testing.allocator);
defer rt.deinit();
try rt.loadExtension(path, null);
var src = rt.toolSource();
const calls = [_]panto.ToolCall{
.{ .tool_name = "echo", .input = "{\"msg\":\"hello\"}" },
.{ .tool_name = "shout", .input = "{\"msg\":\"hi\"}" },
.{ .tool_name = "echo", .input = "{\"msg\":\"again\"}" },
};
var results: [3]panto.ToolCallResult = .{
.{ .err = error.SourceDroppedCall },
.{ .err = error.SourceDroppedCall },
.{ .err = error.SourceDroppedCall },
};
try src.vtable.invoke_batch(src.ctx, &calls, &results, testing.allocator);
defer for (results) |r| switch (r) {
.ok => |b| testing.allocator.free(b),
.err => {},
};
try testing.expectEqualStrings("got: hello", results[0].ok);
try testing.expectEqualStrings("HI!", results[1].ok);
try testing.expectEqualStrings("got: again", results[2].ok);
}
test "module-global state survives across calls in the same runtime" {
// This is the headline reason the runtime exists. Verify it.
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const source =
\\local count = 0
\\panto.register_tool {
\\ name = "bump", description = "increment counter",
\\ schema = { type = "object" },
\\ handler = function(input)
\\ count = count + 1
\\ return tostring(count)
\\ end,
\\}
;
const path = try writeTempScript(tmp.dir, "counter.lua", source);
defer testing.allocator.free(path);
var rt = try LuaRuntime.create(testing.allocator);
defer rt.deinit();
try rt.loadExtension(path, null);
var src = rt.toolSource();
const calls = [_]panto.ToolCall{
.{ .tool_name = "bump", .input = "{}" },
.{ .tool_name = "bump", .input = "{}" },
.{ .tool_name = "bump", .input = "{}" },
};
var results: [3]panto.ToolCallResult = .{
.{ .err = error.SourceDroppedCall },
.{ .err = error.SourceDroppedCall },
.{ .err = error.SourceDroppedCall },
};
try src.vtable.invoke_batch(src.ctx, &calls, &results, testing.allocator);
defer for (results) |r| switch (r) {
.ok => |b| testing.allocator.free(b),
.err => {},
};
try testing.expectEqualStrings("1", results[0].ok);
try testing.expectEqualStrings("2", results[1].ok);
try testing.expectEqualStrings("3", results[2].ok);
// And a second batch keeps the counter going.
var more: [1]panto.ToolCallResult = .{.{ .err = error.SourceDroppedCall }};
try src.vtable.invoke_batch(
src.ctx,
&[_]panto.ToolCall{.{ .tool_name = "bump", .input = "{}" }},
&more,
testing.allocator,
);
defer testing.allocator.free(more[0].ok);
try testing.expectEqualStrings("4", more[0].ok);
}
test "handler crash: per-call error surfaces, sibling calls succeed" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const source =
\\panto.register_tool {
\\ name = "ok", description = "ok",
\\ schema = { type = "object" },
\\ handler = function(input) return "fine" end,
\\}
\\panto.register_tool {
\\ name = "boom", description = "bad",
\\ schema = { type = "object" },
\\ handler = function(input) error("kaboom") end,
\\}
;
const path = try writeTempScript(tmp.dir, "mix.lua", source);
defer testing.allocator.free(path);
var rt = try LuaRuntime.create(testing.allocator);
defer rt.deinit();
try rt.loadExtension(path, null);
var src = rt.toolSource();
const calls = [_]panto.ToolCall{
.{ .tool_name = "ok", .input = "{}" },
.{ .tool_name = "boom", .input = "{}" },
.{ .tool_name = "ok", .input = "{}" },
};
var results: [3]panto.ToolCallResult = .{
.{ .err = error.SourceDroppedCall },
.{ .err = error.SourceDroppedCall },
.{ .err = error.SourceDroppedCall },
};
try src.vtable.invoke_batch(src.ctx, &calls, &results, testing.allocator);
defer for (results) |r| switch (r) {
.ok => |b| testing.allocator.free(b),
.err => {},
};
try testing.expectEqualStrings("fine", results[0].ok);
// A handler crash is surfaced as an *ok* result whose payload is
// the formatted error message — not as `.err` — because libpanto
// would otherwise abort the entire turn on per-call `.err`. The
// payload starts with the well-known `panto-lua: tool '...' failed:`
// prefix and includes the Lua-side error message.
try testing.expect(std.mem.startsWith(
u8,
results[1].ok,
"panto-lua: tool 'boom' failed:",
));
try testing.expect(std.mem.indexOf(u8, results[1].ok, "kaboom") != null);
try testing.expectEqualStrings("fine", results[2].ok);
}
test "directory-style extension can require sibling modules" {
var tmp = testing.tmpDir(.{ .iterate = true });
defer tmp.cleanup();
try tmp.dir.createDirPath(testing.io, "ext");
try tmp.dir.writeFile(testing.io, .{
.sub_path = "ext/util.lua",
.data =
\\local M = {}
\\function M.shout(s) return s:upper() .. "!" end
\\return M
,
});
try tmp.dir.writeFile(testing.io, .{
.sub_path = "ext/init.lua",
.data =
\\local util = require("util")
\\panto.register_tool {
\\ name = "shout", description = "uppercase + bang",
\\ schema = { type = "object", properties = { text = { type = "string" } } },
\\ handler = function(input) return util.shout(input.text) end,
\\}
,
});
var path_buf: [std.fs.max_path_bytes]u8 = undefined;
const ext_len = try tmp.dir.realPathFile(testing.io, "ext", &path_buf);
const ext_dir = try testing.allocator.dupe(u8, path_buf[0..ext_len]);
defer testing.allocator.free(ext_dir);
const init_path = try std.fs.path.join(testing.allocator, &.{ ext_dir, "init.lua" });
defer testing.allocator.free(init_path);
var rt = try LuaRuntime.create(testing.allocator);
defer rt.deinit();
try rt.loadExtension(init_path, ext_dir);
var src = rt.toolSource();
const calls = [_]panto.ToolCall{.{ .tool_name = "shout", .input = "{\"text\":\"hi\"}" }};
var results: [1]panto.ToolCallResult = .{.{ .err = error.SourceDroppedCall }};
try src.vtable.invoke_batch(src.ctx, &calls, &results, testing.allocator);
defer testing.allocator.free(results[0].ok);
try testing.expectEqualStrings("HI!", results[0].ok);
}
test "yielding handler with no event loop surfaces LuaHandlerYielded" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const source =
\\panto.register_tool {
\\ name = "sleeper", description = "yields forever",
\\ schema = { type = "object" },
\\ handler = function(input) coroutine.yield() ; return "never" end,
\\}
;
const path = try writeTempScript(tmp.dir, "y.lua", source);
defer testing.allocator.free(path);
var rt = try LuaRuntime.create(testing.allocator);
defer rt.deinit();
try rt.loadExtension(path, null);
var src = rt.toolSource();
const calls = [_]panto.ToolCall{.{ .tool_name = "sleeper", .input = "{}" }};
var results: [1]panto.ToolCallResult = .{.{ .err = error.SourceDroppedCall }};
try src.vtable.invoke_batch(src.ctx, &calls, &results, testing.allocator);
defer for (results) |r| switch (r) {
.ok => |b| testing.allocator.free(b),
.err => {},
};
// Same policy as the crash test: the failure is surfaced as `.ok`
// text so libpanto doesn't abort the turn. The error type name
// (`LuaHandlerYielded`) is included via `@errorName` in the legacy
// sync path's formatToolError call.
try testing.expect(std.mem.startsWith(
u8,
results[0].ok,
"panto-lua: tool 'sleeper' failed:",
));
try testing.expect(std.mem.indexOf(u8, results[0].ok, "LuaHandlerYielded") != null);
}
// Integration test: requires a `$PANTO_HOME` with luv already
// installed. Skipped if luv isn't on disk — unit tests stay offline.
test "scheduler: yielding handler is resumed by libuv" {
const home_z = std.c.getenv("PANTO_HOME") orelse return error.SkipZigTest;
const panto_home_env = std.mem.sliceTo(home_z, 0);
// Check for `<home>/rocks/lua-<version>/lib/lua/5.4/luv.so`.
const manifest = @import("manifest.zig");
var path_buf: [std.fs.max_path_bytes]u8 = undefined;
const so_path = try std.fmt.bufPrint(
&path_buf,
"{s}/rocks/lua-{s}/lib/lua/{s}/luv.so",
.{ panto_home_env, manifest.lua_version, manifest.lua_short_version },
);
std.Io.Dir.cwd().access(testing.io, so_path, .{}) catch return error.SkipZigTest;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const source =
\\local uv = require("luv")
\\panto.register_tool {
\\ name = "timer_say", description = "sleep then return",
\\ schema = { type = "object" },
\\ handler = function(input)
\\ local co = coroutine.running()
\\ local timer = uv.new_timer()
\\ uv.timer_start(timer, 5, 0, function()
\\ uv.timer_stop(timer)
\\ uv.close(timer)
\\ coroutine.resume(co)
\\ end)
\\ coroutine.yield()
\\ return "awake"
\\ end,
\\}
;
const path = try writeTempScript(tmp.dir, "timer.lua", source);
defer testing.allocator.free(path);
var rt = try LuaRuntime.create(testing.allocator);
defer rt.deinit();
// Bootstrap luarocks (so `require("luv")` works), then install
// the scheduler. We use the real environment so the test picks
// up the same PANTO_HOME the developer's machine has.
var env: std.process.Environ.Map = .init(testing.allocator);
defer env.deinit();
try env.put("PANTO_HOME", panto_home_env);
const luarocks_runtime = @import("luarocks_runtime.zig");
// The bootstrap needs a panto executable path for the wrapper
// script; tests don't actually invoke it, so a placeholder is
// fine (the wrapper is only consulted when luarocks itself
// shells out, which the test never triggers).
const luarocks_rt = try luarocks_runtime.bootstrap(
testing.allocator,
testing.io,
&env,
rt.L,
"/usr/bin/true",
);
defer luarocks_rt.deinit();
try rt.installScheduler();
try rt.loadExtension(path, null);
var src = rt.toolSource();
const calls = [_]panto.ToolCall{
.{ .tool_name = "timer_say", .input = "{}" },
.{ .tool_name = "timer_say", .input = "{}" },
};
var results: [2]panto.ToolCallResult = .{
.{ .err = error.SourceDroppedCall },
.{ .err = error.SourceDroppedCall },
};
try src.vtable.invoke_batch(src.ctx, &calls, &results, testing.allocator);
defer for (results) |r| switch (r) {
.ok => |b| testing.allocator.free(b),
.err => {},
};
try testing.expectEqualStrings("awake", results[0].ok);
try testing.expectEqualStrings("awake", results[1].ok);
}
test "loadExtension: duplicate tool name from a second extension errors" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const a =
\\panto.register_tool {
\\ name = "clash", description = "a",
\\ schema = { type = "object" },
\\ handler = function(input) return "a" end,
\\}
;
const b =
\\panto.register_tool {
\\ name = "clash", description = "b",
\\ schema = { type = "object" },
\\ handler = function(input) return "b" end,
\\}
;
const pa = try writeTempScript(tmp.dir, "a.lua", a);
defer testing.allocator.free(pa);
const pb = try writeTempScript(tmp.dir, "b.lua", b);
defer testing.allocator.free(pb);
var rt = try LuaRuntime.create(testing.allocator);
defer rt.deinit();
try rt.loadExtension(pa, null);
try testing.expectError(error.DuplicateTool, rt.loadExtension(pb, null));
}
|