Repository navigation
Expand file tree
/
Copy pathruntime.zig
More file actions
1260 lines (1046 loc) · 43.5 KB
/
Copy pathruntime.zig
File metadata and controls
1260 lines (1046 loc) · 43.5 KB
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
const builtin = @import("builtin");
const std = @import("std");
const std_compat = @import("compat");
const build_options = @import("build_options");
const fs_compat = @import("fs_compat.zig");
const embedded_wasm3_available = build_options.enable_embedded_wasm3;
const c_wasm3 = if (embedded_wasm3_available) @cImport({
@cInclude("wasm3.h");
}) else struct {};
/// Runtime adapter interface -- abstracts platform differences.
/// Mirrors ZeroClaw's RuntimeAdapter trait.
pub const RuntimeAdapter = struct {
ptr: *anyopaque,
vtable: *const VTable,
pub const VTable = struct {
name: *const fn (ptr: *anyopaque) []const u8,
has_shell_access: *const fn (ptr: *anyopaque) bool,
has_filesystem_access: *const fn (ptr: *anyopaque) bool,
storage_path: *const fn (ptr: *anyopaque) []const u8,
supports_long_running: *const fn (ptr: *anyopaque) bool,
memory_budget: *const fn (ptr: *anyopaque) u64,
};
pub fn getName(self: RuntimeAdapter) []const u8 {
return self.vtable.name(self.ptr);
}
pub fn hasShellAccess(self: RuntimeAdapter) bool {
return self.vtable.has_shell_access(self.ptr);
}
pub fn hasFilesystemAccess(self: RuntimeAdapter) bool {
return self.vtable.has_filesystem_access(self.ptr);
}
pub fn storagePath(self: RuntimeAdapter) []const u8 {
return self.vtable.storage_path(self.ptr);
}
pub fn supportsLongRunning(self: RuntimeAdapter) bool {
return self.vtable.supports_long_running(self.ptr);
}
pub fn memoryBudget(self: RuntimeAdapter) u64 {
return self.vtable.memory_budget(self.ptr);
}
};
// ── NativeRuntime ────────────────────────────────────────────────────
/// Native runtime -- full access, runs on Mac/Linux/Docker/Raspberry Pi.
pub const NativeRuntime = struct {
const vtable = RuntimeAdapter.VTable{
.name = nativeName,
.has_shell_access = nativeShell,
.has_filesystem_access = nativeFs,
.storage_path = nativeStorage,
.supports_long_running = nativeLongRunning,
.memory_budget = nativeMemBudget,
};
pub fn adapter(self: *NativeRuntime) RuntimeAdapter {
return .{
.ptr = @ptrCast(self),
.vtable = &vtable,
};
}
fn nativeName(_: *anyopaque) []const u8 {
return "native";
}
fn nativeShell(_: *anyopaque) bool {
return true;
}
fn nativeFs(_: *anyopaque) bool {
return true;
}
fn nativeStorage(_: *anyopaque) []const u8 {
return ".nullclaw";
}
fn nativeLongRunning(_: *anyopaque) bool {
return true;
}
fn nativeMemBudget(_: *anyopaque) u64 {
return 0; // unlimited
}
};
// ── DockerRuntime ────────────────────────────────────────────────────
/// Docker runtime -- container-isolated execution.
pub const DockerRuntime = struct {
image: []const u8,
network: []const u8,
memory_limit_mb: ?u64,
mount_workspace: bool,
const vtable = RuntimeAdapter.VTable{
.name = dockerName,
.has_shell_access = dockerShell,
.has_filesystem_access = dockerFs,
.storage_path = dockerStorage,
.supports_long_running = dockerLongRunning,
.memory_budget = dockerMemBudget,
};
pub fn init(image: []const u8, network: []const u8, memory_limit_mb: ?u64, mount_workspace: bool) DockerRuntime {
return .{
.image = image,
.network = network,
.memory_limit_mb = memory_limit_mb,
.mount_workspace = mount_workspace,
};
}
pub fn adapter(s: *DockerRuntime) RuntimeAdapter {
return .{
.ptr = @ptrCast(s),
.vtable = &vtable,
};
}
fn resolve(ptr: *anyopaque) *DockerRuntime {
return @ptrCast(@alignCast(ptr));
}
fn dockerName(_: *anyopaque) []const u8 {
return "docker";
}
fn dockerShell(_: *anyopaque) bool {
return true;
}
fn dockerFs(ptr: *anyopaque) bool {
return resolve(ptr).mount_workspace;
}
fn dockerStorage(ptr: *anyopaque) []const u8 {
if (resolve(ptr).mount_workspace) {
return "/workspace/.nullclaw";
} else {
return "/tmp/.nullclaw";
}
}
fn dockerLongRunning(_: *anyopaque) bool {
return false;
}
fn dockerMemBudget(ptr: *anyopaque) u64 {
if (resolve(ptr).memory_limit_mb) |mb| {
return mb *| (1024 * 1024);
}
return 0;
}
};
// ── WasmRuntime ─────────────────────────────────────────────────────
/// Result of executing a WASM module.
pub const WasmExecutionResult = struct {
stdout: []const u8,
stderr: []const u8,
exit_code: i32,
fuel_consumed: u64,
};
/// Capabilities granted to a WASM module.
pub const WasmCapabilities = struct {
has_wasi: bool = false,
max_fuel: u64 = 1_000_000,
max_memory_bytes: usize = 64 * 1024 * 1024,
allow_workspace_read: bool = false,
allow_workspace_write: bool = false,
};
/// WASM runtime configuration.
pub const WasmEngine = enum {
wasmtime,
wasm3,
};
pub const WasmRuntimeConfig = struct {
fuel_limit: u64 = 1_000_000,
memory_limit_mb: u64 = 64,
tools_dir: []const u8 = "tools/wasm",
engine: WasmEngine = .wasmtime,
allow_workspace_read: bool = false,
allow_workspace_write: bool = false,
};
/// WASM sandbox runtime -- executes tool modules via `wasmtime` or `wasm3`.
/// Provides fuel-limited, memory-capped isolation without Docker.
pub const WasmRuntime = struct {
wasm_config: WasmRuntimeConfig,
const WASM_PAGE_SIZE: u64 = 64 * 1024;
const WasmtimeInvocation = struct {
fuel_str: [32]u8,
fuel_len: usize,
mem_pages_str: [32]u8,
mem_pages_len: usize,
module_path: []const u8,
fn writeArgv(self: *const WasmtimeInvocation, out: *[7][]const u8) usize {
out.* = .{
"wasmtime",
"run",
"--fuel",
self.fuel_str[0..self.fuel_len],
"--max-memory-size",
self.mem_pages_str[0..self.mem_pages_len],
self.module_path,
};
return 7;
}
};
const Wasm3Invocation = struct {
module_path: []const u8,
fn writeArgv(self: *const Wasm3Invocation, out: *[7][]const u8) usize {
out[0] = "wasm3";
out[1] = self.module_path;
return 2;
}
};
const WasmInvocation = union(enum) {
wasmtime: WasmtimeInvocation,
wasm3: Wasm3Invocation,
};
const wasm_vtable = RuntimeAdapter.VTable{
.name = wasmName,
.has_shell_access = wasmShell,
.has_filesystem_access = wasmFs,
.storage_path = wasmStorage,
.supports_long_running = wasmLongRunning,
.memory_budget = wasmMemBudget,
};
pub fn init(wasm_config: WasmRuntimeConfig) WasmRuntime {
return .{ .wasm_config = wasm_config };
}
pub fn adapter(self: *WasmRuntime) RuntimeAdapter {
return .{
.ptr = @ptrCast(self),
.vtable = &wasm_vtable,
};
}
fn resolve(ptr: *anyopaque) *WasmRuntime {
return @ptrCast(@alignCast(ptr));
}
fn wasmName(_: *anyopaque) []const u8 {
return "wasm";
}
fn wasmShell(_: *anyopaque) bool {
return false; // WASM sandbox does NOT provide shell access
}
fn wasmFs(ptr: *anyopaque) bool {
const self = resolve(ptr);
return self.wasm_config.allow_workspace_read or self.wasm_config.allow_workspace_write;
}
fn wasmStorage(_: *anyopaque) []const u8 {
return ".nullclaw/wasm";
}
fn wasmLongRunning(_: *anyopaque) bool {
return false; // WASM modules are short-lived
}
fn wasmMemBudget(ptr: *anyopaque) u64 {
const self = resolve(ptr);
return self.wasm_config.memory_limit_mb *| (1024 * 1024);
}
/// Get the effective fuel limit for an invocation.
pub fn effectiveFuel(self: *const WasmRuntime, caps: WasmCapabilities) u64 {
if (caps.max_fuel > 0 and caps.max_fuel != 1_000_000) {
return caps.max_fuel;
}
return self.wasm_config.fuel_limit;
}
/// Get the effective memory limit in bytes.
pub fn effectiveMemoryBytes(self: *const WasmRuntime, caps: WasmCapabilities) u64 {
if (caps.max_memory_bytes > 0 and caps.max_memory_bytes != 64 * 1024 * 1024) {
return @as(u64, @intCast(caps.max_memory_bytes));
}
return self.wasm_config.memory_limit_mb *| (1024 * 1024);
}
/// Build default capabilities from config.
pub fn defaultCapabilities(self: *const WasmRuntime) WasmCapabilities {
return .{
.has_wasi = true,
.max_fuel = self.wasm_config.fuel_limit,
.max_memory_bytes = @intCast(self.wasm_config.memory_limit_mb *| (1024 * 1024)),
.allow_workspace_read = self.wasm_config.allow_workspace_read,
.allow_workspace_write = self.wasm_config.allow_workspace_write,
};
}
/// Validate the WASM config.
pub fn validateConfig(self: *const WasmRuntime) !void {
if (self.wasm_config.memory_limit_mb == 0) {
return error.ZeroMemoryLimit;
}
if (self.wasm_config.memory_limit_mb > 4096) {
return error.ExcessiveMemoryLimit;
}
if (self.wasm_config.tools_dir.len == 0) {
return error.EmptyToolsDir;
}
if (std.mem.indexOf(u8, self.wasm_config.tools_dir, "..") != null) {
return error.PathTraversal;
}
}
/// Execute a WASM module via selected runtime engine.
/// Returns the captured stdout, stderr, exit code, and estimated fuel consumed.
pub fn executeModule(
self: *const WasmRuntime,
allocator: std.mem.Allocator,
module_path: []const u8,
caps: WasmCapabilities,
) !WasmExecutionResult {
if (module_path.len == 0) {
return error.EmptyModulePath;
}
const fuel = self.effectiveFuel(caps);
const max_mem = self.effectiveMemoryBytes(caps);
if (self.wasm_config.engine == .wasm3 and embedded_wasm3_available) {
return self.executeEmbeddedWasm3(allocator, module_path, fuel, max_mem);
}
const invocation = try self.buildInvocation(module_path, fuel, max_mem);
var argv_buf: [7][]const u8 = undefined;
var resolved_wasmtime_path: ?[]u8 = null;
defer if (resolved_wasmtime_path) |path| allocator.free(path);
const argc = switch (invocation) {
.wasmtime => |inv| blk: {
resolved_wasmtime_path = try resolveWasmtimePath(allocator);
const count = inv.writeArgv(&argv_buf);
argv_buf[0] = resolved_wasmtime_path.?;
break :blk count;
},
.wasm3 => |inv| inv.writeArgv(&argv_buf),
};
// Build argv for selected engine (wasmtime/wasm3).
var child = std_compat.process.Child.init(argv_buf[0..argc], allocator);
child.stdout_behavior = .Pipe;
child.stderr_behavior = .Pipe;
try child.spawn();
const stdout = try child.stdout.?.readToEndAlloc(allocator, 1024 * 1024);
errdefer allocator.free(stdout);
const stderr = try child.stderr.?.readToEndAlloc(allocator, 1024 * 1024);
errdefer allocator.free(stderr);
const term = try child.wait();
const exit_code: i32 = switch (term) {
.exited => |code| @as(i32, @intCast(code)),
else => -1,
};
return WasmExecutionResult{
.stdout = stdout,
.stderr = stderr,
.exit_code = exit_code,
.fuel_consumed = fuel, // approximate: real wasmtime reports via stderr
};
}
fn executeEmbeddedWasm3(
self: *const WasmRuntime,
allocator: std.mem.Allocator,
module_path: []const u8,
fuel: u64,
max_mem: u64,
) !WasmExecutionResult {
_ = self;
const module_bytes = try readModuleBytes(allocator, module_path);
defer allocator.free(module_bytes);
const env = c_wasm3.m3_NewEnvironment() orelse return error.Wasm3EnvironmentInitFailed;
defer c_wasm3.m3_FreeEnvironment(env);
const stack_size_u64 = @min(max_mem, @as(u64, std.math.maxInt(u32)));
const stack_size: u32 = @intCast(stack_size_u64);
const runtime = c_wasm3.m3_NewRuntime(env, stack_size, null) orelse return error.Wasm3RuntimeInitFailed;
defer c_wasm3.m3_FreeRuntime(runtime);
var module: c_wasm3.IM3Module = undefined;
var result = c_wasm3.m3_ParseModule(
env,
&module,
module_bytes.ptr,
@as(u32, @intCast(module_bytes.len)),
);
if (result != null) {
return error.Wasm3ParseFailed;
}
result = c_wasm3.m3_LoadModule(runtime, module);
if (result != null) {
return error.Wasm3LoadFailed;
}
result = c_wasm3.m3_RunStart(module);
if (result != null and !isWasm3FunctionLookupError(result)) {
return error.Wasm3StartFailed;
}
var fn_entry: c_wasm3.IM3Function = undefined;
var has_entry = false;
result = c_wasm3.m3_FindFunction(&fn_entry, runtime, "_start");
if (result == null) {
has_entry = true;
} else {
result = c_wasm3.m3_FindFunction(&fn_entry, runtime, "main");
if (result == null) {
has_entry = true;
}
}
if (has_entry) {
result = c_wasm3.m3_CallV(fn_entry);
if (result != null and !isWasm3TrapExit(result)) {
return error.Wasm3CallFailed;
}
}
const stdout = try allocator.dupe(u8, "");
errdefer allocator.free(stdout);
const stderr = try allocator.dupe(u8, "");
errdefer allocator.free(stderr);
return .{
.stdout = stdout,
.stderr = stderr,
.exit_code = 0,
.fuel_consumed = fuel,
};
}
fn readModuleBytes(allocator: std.mem.Allocator, module_path: []const u8) ![]u8 {
const MAX_MODULE_BYTES = 64 * 1024 * 1024;
const file = try fs_compat.openPath(module_path, .{});
defer file.close();
return file.readToEndAlloc(allocator, MAX_MODULE_BYTES);
}
fn isWasm3FunctionLookupError(result: anytype) bool {
if (result == null) return false;
return std.mem.eql(u8, std.mem.span(result), "function lookup failed");
}
fn isWasm3TrapExit(result: anytype) bool {
if (result == null) return false;
return std.mem.eql(u8, std.mem.span(result), "[trap] program called exit");
}
fn memoryBytesToWasmPages(max_mem_bytes: u64) u64 {
return max_mem_bytes / WASM_PAGE_SIZE;
}
fn buildInvocation(self: *const WasmRuntime, module_path: []const u8, fuel: u64, max_mem_bytes: u64) !WasmInvocation {
return switch (self.wasm_config.engine) {
.wasmtime => .{ .wasmtime = try buildWasmtimeInvocation(module_path, fuel, max_mem_bytes) },
.wasm3 => .{ .wasm3 = buildWasm3Invocation(module_path) },
};
}
fn buildWasmtimeInvocation(module_path: []const u8, fuel: u64, max_mem_bytes: u64) !WasmtimeInvocation {
const max_mem_pages = memoryBytesToWasmPages(max_mem_bytes);
var invocation: WasmtimeInvocation = undefined;
const fuel_str = std.fmt.bufPrint(&invocation.fuel_str, "{d}", .{fuel}) catch return error.FormatError;
const mem_pages_str = std.fmt.bufPrint(&invocation.mem_pages_str, "{d}", .{max_mem_pages}) catch return error.FormatError;
invocation.fuel_len = fuel_str.len;
invocation.mem_pages_len = mem_pages_str.len;
invocation.module_path = module_path;
return invocation;
}
fn buildWasm3Invocation(module_path: []const u8) Wasm3Invocation {
return .{ .module_path = module_path };
}
fn isCommandAvailable(allocator: std.mem.Allocator, command: []const u8) bool {
var child = std_compat.process.Child.init(&.{ command, "--version" }, allocator);
child.stdout_behavior = .Ignore;
child.stderr_behavior = .Ignore;
child.spawn() catch return false;
_ = child.wait() catch return false;
return true;
}
};
fn resolveWasmtimePath(allocator: std.mem.Allocator) ![]u8 {
const path_env = std_compat.process.getEnvVarOwned(allocator, "PATH") catch return error.WasmtimeNotFound;
defer allocator.free(path_env);
const path_extensions = if (builtin.os.tag == .windows)
std_compat.process.getEnvVarOwned(allocator, "PATHEXT") catch null
else
null;
defer if (path_extensions) |value| allocator.free(value);
return resolveExecutableFromSearchPath(allocator, "wasmtime", path_env, path_extensions);
}
fn resolveExecutableFromPath(allocator: std.mem.Allocator, executable: []const u8, path_env: []const u8) ![]u8 {
return resolveExecutableFromSearchPath(allocator, executable, path_env, null);
}
fn resolveExecutableFromSearchPath(
allocator: std.mem.Allocator,
executable: []const u8,
path_env: []const u8,
path_extensions: ?[]const u8,
) ![]u8 {
var parts = std.mem.splitScalar(u8, path_env, std_compat.fs.path.delimiter);
while (parts.next()) |part| {
if (part.len == 0) continue;
if (try resolveExecutableFromDirectory(allocator, part, executable, path_extensions)) |resolved| {
return resolved;
}
}
return error.WasmtimeNotFound;
}
fn resolveExecutableFromDirectory(
allocator: std.mem.Allocator,
directory: []const u8,
executable: []const u8,
path_extensions: ?[]const u8,
) !?[]u8 {
const candidate = try std_compat.fs.path.join(allocator, &.{ directory, executable });
defer allocator.free(candidate);
if (try realpathIfExecutable(allocator, candidate)) |resolved| {
return resolved;
}
if (path_extensions) |extensions| {
var extension_it = std.mem.tokenizeScalar(u8, extensions, std_compat.fs.path.delimiter);
while (extension_it.next()) |ext| {
if (!supportedWindowsProgramExtension(ext)) continue;
const candidate_with_ext = try std.fmt.allocPrint(allocator, "{s}{s}", .{ candidate, ext });
defer allocator.free(candidate_with_ext);
if (try realpathIfExecutable(allocator, candidate_with_ext)) |resolved| {
return resolved;
}
}
}
return null;
}
fn realpathIfExecutable(allocator: std.mem.Allocator, path: []const u8) !?[]u8 {
const stat = fs_compat.statPath(path) catch return null;
if (stat.kind != .file) return null;
if (builtin.os.tag != .windows and (stat.mode & 0o111) == 0) return null;
return fs_compat.realpathAllocPath(allocator, path) catch |err| switch (err) {
error.OutOfMemory => return err,
else => return null,
};
}
fn supportedWindowsProgramExtension(ext: []const u8) bool {
inline for (@typeInfo(std_compat.process.Child.WindowsExtension).@"enum".fields) |field| {
if (std.ascii.eqlIgnoreCase(ext, "." ++ field.name)) return true;
}
return false;
}
// ── CloudflareRuntime ────────────────────────────────────────────────
/// Cloudflare Workers runtime descriptor — serverless V8 isolate environment.
/// No shell or filesystem access; 128 MB memory cap; short-lived invocations.
/// Storage is provided via Cloudflare KV/D1, not a local path.
pub const CloudflareRuntime = struct {
const cf_vtable = RuntimeAdapter.VTable{
.name = cfName,
.has_shell_access = cfShell,
.has_filesystem_access = cfFs,
.storage_path = cfStorage,
.supports_long_running = cfLongRunning,
.memory_budget = cfMemBudget,
};
pub fn adapter(self: *CloudflareRuntime) RuntimeAdapter {
return .{ .ptr = @ptrCast(self), .vtable = &cf_vtable };
}
fn cfName(_: *anyopaque) []const u8 {
return "cloudflare";
}
fn cfShell(_: *anyopaque) bool {
return false; // Workers have no shell access
}
fn cfFs(_: *anyopaque) bool {
return false; // Workers have no local filesystem; use KV / D1 / R2
}
fn cfStorage(_: *anyopaque) []const u8 {
return ""; // Storage is remote (KV/D1), not a local path
}
fn cfLongRunning(_: *anyopaque) bool {
return false; // Workers have a CPU time limit (50 ms free, 30 s paid)
}
fn cfMemBudget(_: *anyopaque) u64 {
return 128 * 1024 * 1024; // 128 MB limit per Cloudflare Workers docs
}
};
/// Factory: create the right runtime from a kind string.
pub fn createRuntime(kind: []const u8) !RuntimeKind {
if (std.mem.eql(u8, kind, "native")) return .native;
if (std.mem.eql(u8, kind, "docker")) return .docker;
if (std.mem.eql(u8, kind, "wasm")) return .wasm;
if (std.mem.eql(u8, kind, "cloudflare")) return .cloudflare;
if (kind.len == 0 or std.mem.trim(u8, kind, " \t").len == 0) return error.EmptyRuntimeKind;
return error.UnknownRuntimeKind;
}
pub const RuntimeKind = enum {
native,
docker,
wasm,
cloudflare,
};
// ── Tests ────────────────────────────────────────────────────────────
test "NativeRuntime name" {
var native = NativeRuntime{};
const rt = native.adapter();
try std.testing.expectEqualStrings("native", rt.getName());
}
test "NativeRuntime has shell access" {
var native = NativeRuntime{};
const rt = native.adapter();
try std.testing.expect(rt.hasShellAccess());
}
test "NativeRuntime has filesystem access" {
var native = NativeRuntime{};
const rt = native.adapter();
try std.testing.expect(rt.hasFilesystemAccess());
}
test "NativeRuntime supports long running" {
var native = NativeRuntime{};
const rt = native.adapter();
try std.testing.expect(rt.supportsLongRunning());
}
test "NativeRuntime memory budget unlimited" {
var native = NativeRuntime{};
const rt = native.adapter();
try std.testing.expectEqual(@as(u64, 0), rt.memoryBudget());
}
test "NativeRuntime storage path contains nullclaw" {
var native = NativeRuntime{};
const rt = native.adapter();
try std.testing.expect(std.mem.indexOf(u8, rt.storagePath(), "nullclaw") != null);
}
test "DockerRuntime name" {
var docker = DockerRuntime.init("alpine:3.24", "none", null, false);
const rt = docker.adapter();
try std.testing.expectEqualStrings("docker", rt.getName());
}
test "DockerRuntime memory budget" {
var docker = DockerRuntime.init("alpine:3.24", "none", 256, false);
const rt = docker.adapter();
try std.testing.expectEqual(@as(u64, 256 * 1024 * 1024), rt.memoryBudget());
}
test "DockerRuntime memory budget none" {
var docker = DockerRuntime.init("alpine:3.24", "none", null, false);
const rt = docker.adapter();
try std.testing.expectEqual(@as(u64, 0), rt.memoryBudget());
}
test "DockerRuntime shell access" {
var docker = DockerRuntime.init("alpine:3.24", "none", null, false);
const rt = docker.adapter();
try std.testing.expect(rt.hasShellAccess());
}
test "DockerRuntime filesystem with mount" {
var docker = DockerRuntime.init("alpine:3.24", "none", null, true);
const rt = docker.adapter();
try std.testing.expect(rt.hasFilesystemAccess());
try std.testing.expectEqualStrings("/workspace/.nullclaw", rt.storagePath());
}
test "DockerRuntime filesystem without mount" {
var docker = DockerRuntime.init("alpine:3.24", "none", null, false);
const rt = docker.adapter();
try std.testing.expect(!rt.hasFilesystemAccess());
try std.testing.expectEqualStrings("/tmp/.nullclaw", rt.storagePath());
}
test "DockerRuntime does not support long running" {
var docker = DockerRuntime.init("alpine:3.24", "none", null, false);
const rt = docker.adapter();
try std.testing.expect(!rt.supportsLongRunning());
}
test "createRuntime native" {
const kind = try createRuntime("native");
try std.testing.expect(kind == .native);
}
test "createRuntime docker" {
const kind = try createRuntime("docker");
try std.testing.expect(kind == .docker);
}
test "createRuntime wasm" {
const kind = try createRuntime("wasm");
try std.testing.expect(kind == .wasm);
}
test "createRuntime cloudflare" {
const kind = try createRuntime("cloudflare");
try std.testing.expect(kind == .cloudflare);
}
test "CloudflareRuntime name" {
var cf = CloudflareRuntime{};
const rt = cf.adapter();
try std.testing.expectEqualStrings("cloudflare", rt.getName());
}
test "CloudflareRuntime has no shell or filesystem" {
var cf = CloudflareRuntime{};
const rt = cf.adapter();
try std.testing.expect(!rt.hasShellAccess());
try std.testing.expect(!rt.hasFilesystemAccess());
try std.testing.expect(!rt.supportsLongRunning());
}
test "CloudflareRuntime memory budget 128 MB" {
var cf = CloudflareRuntime{};
const rt = cf.adapter();
try std.testing.expectEqual(@as(u64, 128 * 1024 * 1024), rt.memoryBudget());
}
test "createRuntime unknown" {
try std.testing.expectError(error.UnknownRuntimeKind, createRuntime("wasm-edge"));
}
test "createRuntime empty" {
try std.testing.expectError(error.EmptyRuntimeKind, createRuntime(""));
}
// ── Additional runtime tests ─────────────────────────────────────
test "createRuntime whitespace-only" {
try std.testing.expectError(error.EmptyRuntimeKind, createRuntime(" "));
}
test "createRuntime tab whitespace" {
try std.testing.expectError(error.EmptyRuntimeKind, createRuntime("\t"));
}
test "NativeRuntime storage path" {
var native = NativeRuntime{};
const rt = native.adapter();
try std.testing.expectEqualStrings(".nullclaw", rt.storagePath());
}
test "NativeRuntime memory budget is zero (unlimited)" {
var native = NativeRuntime{};
const rt = native.adapter();
try std.testing.expectEqual(@as(u64, 0), rt.memoryBudget());
}
test "DockerRuntime init stores all fields" {
var docker = DockerRuntime.init("ubuntu:24.04", "bridge", 512, true);
const rt = docker.adapter();
try std.testing.expectEqualStrings("docker", rt.getName());
try std.testing.expect(rt.hasFilesystemAccess());
try std.testing.expectEqual(@as(u64, 512 * 1024 * 1024), rt.memoryBudget());
}
test "DockerRuntime different images" {
var d1 = DockerRuntime.init("alpine:3.24", "none", null, false);
var d2 = DockerRuntime.init("ubuntu:24.04", "host", 1024, true);
const rt1 = d1.adapter();
const rt2 = d2.adapter();
// Both report as "docker" runtime
try std.testing.expectEqualStrings("docker", rt1.getName());
try std.testing.expectEqualStrings("docker", rt2.getName());
// Different filesystem access
try std.testing.expect(!rt1.hasFilesystemAccess());
try std.testing.expect(rt2.hasFilesystemAccess());
// Different memory budgets
try std.testing.expectEqual(@as(u64, 0), rt1.memoryBudget());
try std.testing.expectEqual(@as(u64, 1024 * 1024 * 1024), rt2.memoryBudget());
}
test "DockerRuntime storage path with workspace mount" {
var docker = DockerRuntime.init("alpine:3.24", "none", null, true);
const rt = docker.adapter();
try std.testing.expect(std.mem.indexOf(u8, rt.storagePath(), "workspace") != null);
}
test "DockerRuntime storage path without workspace mount" {
var docker = DockerRuntime.init("alpine:3.24", "none", null, false);
const rt = docker.adapter();
try std.testing.expect(std.mem.indexOf(u8, rt.storagePath(), "tmp") != null);
}
test "DockerRuntime does not support long running with mount" {
var docker = DockerRuntime.init("alpine:3.24", "none", null, true);
const rt = docker.adapter();
try std.testing.expect(!rt.supportsLongRunning());
}
test "DockerRuntime has shell access" {
var docker = DockerRuntime.init("alpine:3.24", "none", null, false);
const rt = docker.adapter();
try std.testing.expect(rt.hasShellAccess());
}
test "RuntimeAdapter vtable dispatch for NativeRuntime" {
var native = NativeRuntime{};
const rt = native.adapter();
// Verify all vtable methods work via the adapter interface
try std.testing.expect(rt.getName().len > 0);
_ = rt.hasShellAccess();
_ = rt.hasFilesystemAccess();
_ = rt.storagePath();
_ = rt.supportsLongRunning();
_ = rt.memoryBudget();
}
test "RuntimeAdapter vtable dispatch for DockerRuntime" {
var docker = DockerRuntime.init("test:latest", "none", 64, true);
const rt = docker.adapter();
// Verify all vtable methods work via the adapter interface
try std.testing.expect(rt.getName().len > 0);
_ = rt.hasShellAccess();
_ = rt.hasFilesystemAccess();
_ = rt.storagePath();
_ = rt.supportsLongRunning();
_ = rt.memoryBudget();
}
test "DockerRuntime memory budget with large value" {
var docker = DockerRuntime.init("alpine:3.24", "none", 4096, false);
const rt = docker.adapter();
try std.testing.expectEqual(@as(u64, 4096 * 1024 * 1024), rt.memoryBudget());
}
test "DockerRuntime memory budget saturating mul" {
// Test with a very large value to ensure no overflow
var docker = DockerRuntime.init("alpine:3.24", "none", std.math.maxInt(u64), false);
const rt = docker.adapter();
// Should use saturating mul, result should be maxInt(u64)
try std.testing.expectEqual(std.math.maxInt(u64), rt.memoryBudget());
}
test "createRuntime case sensitive" {
// Only exact matches should work
try std.testing.expectError(error.UnknownRuntimeKind, createRuntime("Native"));
try std.testing.expectError(error.UnknownRuntimeKind, createRuntime("DOCKER"));
}
test "NativeRuntime full capabilities" {
var native = NativeRuntime{};
const rt = native.adapter();
try std.testing.expect(rt.hasShellAccess());
try std.testing.expect(rt.hasFilesystemAccess());
try std.testing.expect(rt.supportsLongRunning());
try std.testing.expectEqual(@as(u64, 0), rt.memoryBudget());
}
test "RuntimeKind enum values" {
const n: RuntimeKind = .native;
const d: RuntimeKind = .docker;
const w: RuntimeKind = .wasm;
try std.testing.expect(n == .native);
try std.testing.expect(d == .docker);
try std.testing.expect(w == .wasm);
try std.testing.expect(n != d);
try std.testing.expect(d != w);
}
// ── WASM Runtime tests ──────────────────────────────────────────────
test "WasmRuntime name" {
var wasm = WasmRuntime.init(.{});
const rt = wasm.adapter();
try std.testing.expectEqualStrings("wasm", rt.getName());
}
test "WasmRuntime no shell access" {
var wasm = WasmRuntime.init(.{});
const rt = wasm.adapter();
try std.testing.expect(!rt.hasShellAccess());
}
test "WasmRuntime no filesystem by default" {
var wasm = WasmRuntime.init(.{});
const rt = wasm.adapter();
try std.testing.expect(!rt.hasFilesystemAccess());
}
test "WasmRuntime filesystem when read enabled" {
var wasm = WasmRuntime.init(.{ .allow_workspace_read = true });
const rt = wasm.adapter();
try std.testing.expect(rt.hasFilesystemAccess());
}
test "WasmRuntime filesystem when write enabled" {
var wasm = WasmRuntime.init(.{ .allow_workspace_write = true });
const rt = wasm.adapter();
try std.testing.expect(rt.hasFilesystemAccess());
}
test "WasmRuntime no long running" {
var wasm = WasmRuntime.init(.{});
const rt = wasm.adapter();
try std.testing.expect(!rt.supportsLongRunning());
}
test "WasmRuntime memory budget" {
var wasm = WasmRuntime.init(.{});
const rt = wasm.adapter();
try std.testing.expectEqual(@as(u64, 64 * 1024 * 1024), rt.memoryBudget());
}
test "WasmRuntime memory budget custom" {
var wasm = WasmRuntime.init(.{ .memory_limit_mb = 128 });
const rt = wasm.adapter();
try std.testing.expectEqual(@as(u64, 128 * 1024 * 1024), rt.memoryBudget());
}
test "WasmRuntime storage path" {
var wasm = WasmRuntime.init(.{});
const rt = wasm.adapter();
try std.testing.expect(std.mem.indexOf(u8, rt.storagePath(), "nullclaw") != null);
}
test "WasmRuntime validate rejects zero memory" {
const wasm = WasmRuntime.init(.{ .memory_limit_mb = 0 });
try std.testing.expectError(error.ZeroMemoryLimit, wasm.validateConfig());
}
test "WasmRuntime validate rejects excessive memory" {
const wasm = WasmRuntime.init(.{ .memory_limit_mb = 8192 });