Repository navigation
Expand file tree
/
Copy pathConfig.zig
More file actions
1659 lines (1468 loc) · 60.8 KB
/
Copy pathConfig.zig
File metadata and controls
1659 lines (1468 loc) · 60.8 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
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
//
// Francis Bouvier <francis@lightpanda.io>
// Pierre Tachoire <pierre@lightpanda.io>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
const std = @import("std");
const zenai = @import("zenai");
const lp = @import("lightpanda");
const cli = @import("cli.zig");
const string = @import("string.zig");
const dump = @import("browser/dump.zig");
const Mime = @import("browser/Mime.zig");
const WebBotAuthConfig = @import("network/WebBotAuth.zig").Config;
const HttpHeader = @import("network/http.zig").Header;
const log = lp.log;
const crypto = @import("sys/libcrypto.zig");
const Allocator = std.mem.Allocator;
// TCP keepalive parameters applied to accepted CDP connections.
// Detection window ≈ IDLE + CNT * INTVL = 4 + 3*2 = 10s.
pub const CDP_KEEPALIVE_IDLE_S: c_int = 4;
pub const CDP_KEEPALIVE_INTVL_S: c_int = 2;
pub const CDP_KEEPALIVE_CNT: c_int = 3;
pub const CDP_TCP_USER_TIMEOUT_MS: c_int = 10_000;
const Config = @This();
fn logFilterValidator(allocator: Allocator, args: *std.process.Args.Iterator, list: *std.ArrayList(log.FilterRule)) !void {
const str = args.next() orelse return error.InvalidOption;
defer log.opts.scope_enabled = log.resolveFilters(list.items);
var it = std.mem.splitScalar(u8, str, ',');
while (it.next()) |part| {
if (part.len == 0) continue;
// `+X` filters in, `-X` filters out, bare `X` is an alias for `-X`
// (backward compatible). `all` targets every scope.
var name = part;
var enable = false;
switch (part[0]) {
'+' => {
enable = true;
name = part[1..];
},
'-' => name = part[1..],
else => {},
}
if (std.mem.eql(u8, name, "all")) {
try list.append(allocator, .{ .scope = null, .enable = enable });
continue;
}
const v = std.meta.stringToEnum(log.Scope, name) orelse {
log.fatal(.app, "invalid option choice", .{ .arg = "--log-filter", .value = part });
return error.InvalidOption;
};
try list.append(allocator, .{ .scope = v, .enable = enable });
}
}
fn logLevelValidator(_: Allocator, args: *std.process.Args.Iterator, target: *?log.Level) !void {
const str = args.next() orelse return error.MissingArgument;
if (std.mem.eql(u8, str, "error")) {
target.* = .err;
log.opts.level = .err;
return;
}
target.* = std.meta.stringToEnum(log.Level, str) orelse {
log.fatal(.app, "invalid option choice", .{ .arg = "--log-level", .value = str });
return error.InvalidArgument;
};
log.opts.level = target.*.?;
}
// The MCP host captures stderr into a log file, where pretty's ANSI
// escapes and multi-line entries are noise. Runs before any option is
// read so parse-time lines match; --log-format still overrides.
fn mcpLogDefaults() void {
log.opts.format = .logfmt;
}
fn logFormatValidator(_: Allocator, args: *std.process.Args.Iterator, target: *?log.Format) !void {
const str = args.next() orelse return error.MissingArgument;
const format = std.meta.stringToEnum(log.Format, str) orelse {
log.fatal(.app, "invalid option choice", .{ .arg = "--log-format", .value = str });
return error.InvalidArgument;
};
target.* = format;
log.opts.format = format;
}
fn httpHeaderValidator(allocator: Allocator, args: *std.process.Args.Iterator, list: *std.ArrayList(HttpHeader)) !void {
const str = args.next() orelse return error.MissingArgument;
const header = HttpHeader.parse(str) orelse {
log.fatal(.app, "invalid option value", .{ .arg = "--http-header", .value = str, .hint = "expected \"Name: Value\"" });
return error.InvalidArgument;
};
// The same shape script-set headers go through in `Headers`: a name that
// is an HTTP token, a value that is a CR/LF-free byte string.
if (Mime.isHttpToken(header.name) == false) {
log.fatal(.app, "invalid option value", .{ .arg = "--http-header", .value = str, .hint = "name must be a non-empty HTTP token" });
return error.InvalidArgument;
}
if (Mime.isHttpHeaderValue(header.value) == false) {
log.fatal(.app, "invalid option value", .{ .arg = "--http-header", .value = str, .hint = "value must be Latin-1 text without CR, LF or NUL" });
return error.InvalidArgument;
}
if (std.ascii.eqlIgnoreCase(header.name, "User-Agent")) {
log.fatal(.app, "invalid option value", .{ .arg = "--http-header", .value = str, .hint = "Use --user-agent instead" });
return error.InvalidArgument;
}
if (std.ascii.eqlIgnoreCase(header.name, "Sec-Ch-Ua")) {
log.fatal(.app, "invalid option value", .{ .arg = "--http-header", .value = str, .hint = "Sec-Ch-Ua is not overridable" });
return error.InvalidArgument;
}
try list.append(allocator, .{
.name = try allocator.dupe(u8, header.name),
.value = try allocator.dupe(u8, header.value),
});
}
const Cert = struct {
/// On successful CLI argument parsing phase, ownership of this transferred
/// to `Network`. Consider it as invalid.
store: ?*crypto.X509_STORE = null,
// Number of certificate sources loaded into `store`.
count: usize = 0,
fn deinit(self: *Cert) void {
if (self.store) |store| {
crypto.X509_STORE_free(store);
}
self.* = .{};
}
/// Returns the store, creating it on first use. The store is shared by
/// every `--ca-cert`/`--ca-path` occurrence.
fn getOrCreate(self: *Cert) !*crypto.X509_STORE {
if (self.store) |store| {
return store;
}
const store = crypto.X509_STORE_new() orelse
return error.FailedToCreateCertStore;
self.store = store;
return store;
}
};
fn caCertValidator(
_: Allocator,
args: *std.process.Args.Iterator,
cert: *Cert,
) !void {
const file_name = args.next() orelse return error.MissingArgument;
const store = try cert.getOrCreate();
errdefer cert.deinit();
if (crypto.X509_STORE_load_locations(store, file_name, null) != 1) {
log.fatal(.app, "Invalid CA cert", .{ .arg = "--ca-cert", .value = file_name });
return error.InvalidArgument;
}
cert.count += 1;
}
fn caPathValidator(
allocator: Allocator,
args: *std.process.Args.Iterator,
cert: *Cert,
) !void {
const dir_path = args.next() orelse return error.MissingArgument;
var dir = std.Io.Dir.cwd().openDir(lp.io, dir_path, .{ .iterate = true }) catch {
log.fatal(.app, "Invalid CA path", .{ .arg = "--ca-path", .value = dir_path });
return error.InvalidArgument;
};
defer dir.close(lp.io);
const store = try cert.getOrCreate();
errdefer cert.deinit();
// Eagerly load every certificate in the directory rather than
// registering a lazy hashed lookup: the directory doesn't need to be
// c_rehash'ed, bad entries surface at startup and `count` reflects
// what was actually loaded.
const count_before = cert.count;
var it = dir.iterate();
while (it.next(lp.io) catch {
log.fatal(.app, "Invalid CA path", .{ .arg = "--ca-path", .value = dir_path });
return error.InvalidArgument;
}) |entry| {
if (entry.kind != .file and entry.kind != .sym_link) continue;
const path = try std.fs.path.joinZ(allocator, &.{ dir_path, entry.name });
defer allocator.free(path);
if (crypto.X509_STORE_load_locations(store, path, null) != 1) {
log.warn(.app, "Skipping invalid CA cert", .{ .arg = "--ca-path", .value = path });
continue;
}
cert.count += 1;
}
// An empty directory (or one with no readable certificates) is
// indistinguishable from a typo; treat it as an error.
if (cert.count == count_before) {
log.fatal(.app, "No certificates loaded", .{ .arg = "--ca-path", .value = dir_path });
return error.InvalidArgument;
}
}
pub const HttpVersion = enum {
auto,
@"1.1",
};
pub const LoadResources = packed struct(u4) {
image: bool = false,
iframe: bool = false,
worker: bool = false,
stylesheet: bool = false,
};
pub const ExperimentalFeatures = packed struct(u2) {
cors: bool = false,
serviceworker: bool = false,
};
/// Common CLI args.
const CommonOptions = .{
.{ .name = "obey_robots", .type = bool },
.{ .name = "proxy_bearer_token", .type = ?[:0]const u8 },
.{ .name = "http_proxy", .type = ?[:0]const u8 },
.{ .name = "http_max_concurrent", .type = ?u8 },
.{ .name = "http_max_host_open", .type = ?u8 },
.{ .name = "http_nav_delay", .type = ?u32 },
.{ .name = "http_nav_burst", .type = ?u32 },
.{ .name = "http_timeout", .type = ?u31 },
.{ .name = "http_version", .type = HttpVersion, .default = .auto },
.{ .name = "http_connect_timeout", .type = ?u31 },
.{ .name = "http_header", .type = HttpHeader, .multiple = true, .validator = httpHeaderValidator },
.{ .name = "http_max_response_size", .type = ?usize },
.{ .name = "ws_max_concurrent", .type = ?u8 },
.{ .name = "insecure_disable_tls_host_verification", .type = bool },
.{ .name = "log_level", .type = ?log.Level, .validator = logLevelValidator },
.{ .name = "log_format", .type = ?log.Format, .validator = logFormatValidator },
.{ .name = "log_filter", .type = log.FilterRule, .multiple = true, .validator = logFilterValidator },
.{ .name = "log_filter_scopes", .type = log.FilterRule, .multiple = true, .validator = logFilterValidator, .deprecated = "use --log-filter" },
.{ .name = "user_agent_suffix", .type = ?[]const u8 },
.{ .name = "http_cache_dir", .type = ?[]const u8 },
.{ .name = "http_cache_entry_limit", .type = ?u32, .default = 1000 },
.{ .name = "web_bot_auth_key_file", .type = ?[]const u8 },
.{ .name = "web_bot_auth_keyid", .type = ?[]const u8 },
.{ .name = "web_bot_auth_domain", .type = ?[]const u8 },
.{ .name = "user_agent", .type = ?[]const u8, .validator = userAgentValidator },
.{ .name = "locale", .type = [:0]const u8, .default = HttpHeaders.default_locale, .validator = localeValidator },
.{ .name = "timezone", .type = ?[:0]const u8, .validator = timezoneValidator },
.{ .name = "block_private_networks", .type = bool },
.{ .name = "block_cidrs", .type = ?[]const u8, .validator = accumulateValidator },
.{ .name = "block_urls", .type = ?[]const u8, .validator = accumulateValidator },
.{ .name = "adblock_lists", .type = ?[]const u8, .validator = accumulateValidator },
.{ .name = "cookie", .type = ?[]const u8 },
.{ .name = "cookie_jar", .type = ?[]const u8 },
.{ .name = "disable_subframes", .type = bool, .deprecated = "subframes are now disabled by default, use \"--load-resources iframe\" to enable" },
.{ .name = "disable_workers", .type = bool, .deprecated = "workers are now disabled by default, use \"--load-resources worker\" to enable" },
.{ .name = "enable_external_stylesheets", .type = bool, .deprecated = "use \"--load-resources stylesheet\" to enable" },
.{ .name = "experimental_features", .type = ExperimentalFeatures, .default = ExperimentalFeatures{} },
.{ .name = "load_resources", .type = LoadResources, .default = LoadResources{} },
.{ .name = "v8_flags_unsafe", .type = ?[]const u8 },
.{ .name = "v8_max_heap_mb", .type = ?u32 },
.{ .name = "watchdog_ms", .type = ?u32 },
.{
.name = "ca_cert",
.field_name = "cert",
.type = .{
.cli = [:0]const u8,
.memory = Cert,
},
.default = Cert{},
.validator = caCertValidator,
},
.{
.name = "ca_path",
.field_name = "cert",
.type = .{
.cli = []const u8,
.memory = Cert,
},
.default = Cert{},
.validator = caPathValidator,
},
};
fn dumpValidator(_: Allocator, args: *std.process.Args.Iterator, target: *?DumpFormat) !void {
// Peek next argument.
var peek_args = args.*;
if (peek_args.next()) |next_arg| {
const mode = std.meta.stringToEnum(DumpFormat, next_arg) orelse {
// Anything else is the positional url, unless it is a misspelt format.
if (string.closest(next_arg, tagNames(DumpFormat), 2)) |near| {
log.fatal(.app, "invalid option choice", .{ .arg = "--dump", .value = log.red(next_arg), .did_you_mean = log.green(near) });
return error.InvalidArgument;
}
target.* = .html;
return;
};
// Skip the argument we peek if successful.
_ = args.next();
target.* = mode;
return;
}
// Means we couldn't get something like `--dump html` but we do have
// `--dump`; which should fall to `html` by default.
target.* = .html;
}
pub const AiProvider = std.meta.Tag(zenai.provider.Client);
/// Per-turn reasoning budget for `agent` mode, mirroring Claude's effort
/// levels. Maps to each provider's native thinking/reasoning knob. Resolved
/// in `Agent.init` (explicit flag > remembered > mode default), so there is
/// no Config-level accessor like `agentVerbosity`.
pub const Effort = zenai.provider.Effort;
/// Controls how chatty `agent` mode is on stderr.
pub const AgentVerbosity = enum {
/// REPL: spinner + per-turn summary. Non-REPL: final answer + errors only.
low,
/// + one `● [tool: …]` line per tool call.
medium,
/// + the matching `[result: …]` body for each call.
high,
pub fn atLeast(self: AgentVerbosity, min: AgentVerbosity) bool {
return @intFromEnum(self) >= @intFromEnum(min);
}
};
fn waitScriptFileValidator(allocator: Allocator, args: *std.process.Args.Iterator, target: *?[:0]const u8) !void {
const path = args.next() orelse {
log.fatal(.app, "missing argument value", .{ .arg = "--wait-script-file" });
return error.InvalidArgument;
};
target.* = std.Io.Dir.cwd().readFileAllocOptions(lp.io, path, allocator, .limited(1024 * 1024), .of(u8), 0) catch |err| {
log.fatal(.app, "failed to read file", .{ .arg = "--wait-script-file", .path = path, .err = err });
return error.InvalidArgument;
};
}
fn injectScriptFileValidator(
allocator: Allocator,
args: *std.process.Args.Iterator,
list: *std.ArrayList([]const u8),
) !void {
const path = args.next() orelse {
log.fatal(.app, "missing argument value", .{ .arg = "--inject-script-file" });
return error.InvalidArgument;
};
const bytes = std.Io.Dir.cwd().readFileAllocOptions(lp.io, path, allocator, .unlimited, .of(u8), null) catch |err| {
log.fatal(.app, "failed to read file", .{ .arg = "--inject-script-file", .path = path, .err = err });
return error.InvalidArgument;
};
return list.append(allocator, bytes);
}
/// Definition for all the commands and its arguments. See @cli.zig for further.
const Commands = cli.Builder(.{
.{
.name = "serve",
.options = .{
.{ .name = "host", .type = []const u8, .default = "127.0.0.1" },
.{ .name = "port", .type = u16, .default = 9222 },
.{ .name = "advertise_host", .type = ?[]const u8 },
// Repeatable; one server can speak several on the same port.
.{ .name = "protocol", .type = Protocol, .multiple = true },
.{ .name = "cdp_max_connections", .type = u16, .default = 16 },
.{ .name = "cdp_max_pending_connections", .type = u16, .default = 128 },
.{ .name = "cdp_max_message_size", .type = u32, .default = 1024 * 1024 },
.{ .name = "cdp_max_http_message_size", .type = u32, .default = 1024 * 1024 },
.{ .name = "http_session_timeout", .type = u32, .default = 60 },
.{ .name = "disable_metrics", .type = bool },
},
.shared_options = CommonOptions,
},
.{
.name = "fetch",
// One or more URLs; can be given out of order, interleaved with options.
.positional = .{ .name = "url", .type = [:0]const u8, .multiple = true },
.options = .{
.{ .name = "dump", .type = ?DumpFormat, .validator = dumpValidator },
.{ .name = "with_base", .type = bool },
.{ .name = "with_frames", .type = bool },
.{ .name = "strip_mode", .type = dump.Opts.Strip, .default = dump.Opts.Strip{} },
.{ .name = "dump_selector", .type = ?[:0]const u8 },
.{ .name = "dump_max_bytes", .type = ?u32 },
.{ .name = "fail_on_http_error", .type = bool },
.{ .name = "wait_ms", .type = u32, .default = 5_000 },
.{ .name = "wait_until", .type = ?WaitUntil },
.{
.name = "wait_script",
.type = ?[:0]const u8,
.variants = .{
.{ .name = "wait_script_file", .validator = waitScriptFileValidator },
},
},
.{ .name = "wait_selector", .type = ?[:0]const u8 },
.{
.name = "inject_script",
.type = []const u8,
.multiple = true,
.variants = .{
.{ .name = "inject_script_file", .validator = injectScriptFileValidator },
},
},
.{ .name = "terminate_ms", .type = ?u32 },
.{ .name = "json", .type = bool },
.{ .name = "metrics", .type = bool },
},
.shared_options = CommonOptions,
},
.{
.name = "mcp",
.before_parse = mcpLogDefaults,
.options = .{
.{ .name = "port", .type = ?u16 },
.{ .name = "host", .type = []const u8, .default = "127.0.0.1" },
.{ .name = "cdp_port", .type = ?u16 },
},
.shared_options = CommonOptions,
},
.{
.name = "agent",
.positional = .{ .name = "script_file", .type = ?[:0]const u8 },
.options = .{
.{ .name = "provider", .type = ?AiProvider },
.{ .name = "model", .type = ?[:0]const u8 },
.{ .name = "base_url", .type = ?[:0]const u8 },
.{ .name = "system_prompt", .type = ?[:0]const u8 },
.{ .name = "task", .type = ?[]const u8 },
.{ .name = "save", .type = ?[]const u8 },
.{ .name = "attach", .short = 'a', .type = []const u8, .multiple = true },
.{ .name = "verbosity", .type = ?AgentVerbosity },
.{ .name = "effort", .type = ?Effort },
.{ .name = "list_models", .type = bool },
.{ .name = "no_llm", .type = bool },
},
.shared_options = CommonOptions,
},
.{
// Normalized to `.agent` in `parseArgs`; intentionally no LLM options.
.name = "run",
.positional = .{ .name = "script_file", .type = ?[:0]const u8 },
.options = .{},
.shared_options = CommonOptions,
},
.{ .name = "version", .options = .{
.{ .name = "check", .type = bool },
} },
});
const RunMode = Commands.Enum;
pub const Mode = Commands.Union;
pub const Agent = @FieldType(Mode, "agent");
mode: Mode,
// The command as typed. Mirrors `mode`, except `run` normalizes to `.agent`
// for execution while this keeps `.run` for telemetry.
command: RunMode,
exec_name: []const u8,
http_headers: HttpHeaders,
fn modeNeedsHttp(mode: Mode) bool {
return switch (mode) {
.help => false,
.version => |opts| opts.check,
else => true,
};
}
pub fn init(allocator: Allocator, exec_name: []const u8, mode: Mode) !Config {
var config = Config{
.mode = mode,
.command = std.meta.activeTag(mode),
.exec_name = exec_name,
.http_headers = undefined,
};
if (modeNeedsHttp(mode)) {
config.http_headers = try HttpHeaders.init(allocator, &config);
}
switch (config.mode) {
inline else => |*m| {
if (@hasField(@TypeOf(m.*), "enable_external_stylesheets")) {
if (m.enable_external_stylesheets) {
// map deprecated property onto updated one
m.load_resources.stylesheet = true;
}
}
},
}
return config;
}
pub fn deinit(self: *const Config, allocator: Allocator) void {
if (modeNeedsHttp(self.mode)) {
self.http_headers.deinit(allocator);
}
}
pub fn interactive(self: *const Config) bool {
return switch (self.mode) {
.fetch => false,
.serve, .mcp => true,
.agent => |opts| opts.script_file == null,
else => unreachable,
};
}
pub fn tlsVerifyHost(self: *const Config) bool {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| !opts.insecure_disable_tls_host_verification,
// `version --check` talks to the release endpoint; always verify.
.version => true,
else => unreachable,
};
}
pub fn obeyRobots(self: *const Config) bool {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.obey_robots,
else => unreachable,
};
}
pub fn httpVersion(self: *const Config) HttpVersion {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.http_version,
else => unreachable,
};
}
pub fn experimentalFeatures(self: *const Config) ExperimentalFeatures {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.experimental_features,
else => unreachable,
};
}
pub fn watchdogMs(self: *const Config) ?u32 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| {
const ms = opts.watchdog_ms orelse 30000;
return if (ms == 0) null else ms;
},
else => unreachable,
};
}
pub fn loadResources(self: *const Config) LoadResources {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.load_resources,
else => unreachable,
};
}
pub fn v8Flags(self: *const Config) ?[]const u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.v8_flags_unsafe,
else => unreachable,
};
}
pub fn v8MaxHeapMb(self: *const Config) ?u32 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.v8_max_heap_mb,
else => unreachable,
};
}
pub fn httpProxy(self: *const Config) ?[:0]const u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.http_proxy,
.version => null,
else => unreachable,
};
}
pub fn httpHeaders(self: *const Config) []const HttpHeader {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.http_header.items,
else => &.{},
};
}
fn proxyBearerToken(self: *const Config) ?[:0]const u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.proxy_bearer_token,
else => null,
};
}
pub fn httpMaxConcurrent(self: *const Config) u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.http_max_concurrent orelse 40,
else => unreachable,
};
}
pub fn httpMaxHostOpen(self: *const Config) u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.http_max_host_open orelse 6,
else => unreachable,
};
}
pub fn httpNavDelay(self: *const Config) ?u32 {
const ms = switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.http_nav_delay,
else => unreachable,
} orelse return null;
return if (ms == 0) null else ms;
}
pub fn httpNavBurst(self: *const Config) u32 {
const burst = switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.http_nav_burst,
else => unreachable,
} orelse 1;
return @max(burst, 1);
}
pub fn httpConnectTimeout(self: *const Config) u31 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.http_connect_timeout orelse 8000,
.version => 0,
else => unreachable,
};
}
pub fn httpTimeout(self: *const Config) u31 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.http_timeout orelse 15000,
.version => 5000,
else => unreachable,
};
}
pub fn httpMaxRedirects(_: *const Config) u8 {
return 10;
}
pub fn httpMaxResponseSize(self: *const Config) ?usize {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.http_max_response_size,
else => unreachable,
};
}
pub fn wsMaxConcurrent(self: *const Config) u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.ws_max_concurrent orelse 8,
else => unreachable,
};
}
/// Resolve --verbosity. Explicit value wins. Else: --task with stderr
/// captured (pipe/file) defaults to .high so benchmark harnesses and
/// other programmatic consumers get the [tool/result] trace; REPL and
/// --task on a TTY default to .low.
pub fn agentVerbosity(opts: Agent) AgentVerbosity {
if (opts.verbosity) |v| return v;
const piped_one_shot = opts.task != null and !stderrIsTty();
return if (piped_one_shot) .high else .low;
}
/// `isatty(STDERR)` is a syscall and `agentVerbosity` is on the log hot
/// path (every gate check resolves through it). Cache once — the fd
/// doesn't change after process start.
var stderr_tty_cached: bool = undefined;
var stderr_tty_once = lp.once(initStderrTty);
fn initStderrTty() void {
stderr_tty_cached = std.Io.File.stderr().isTty(lp.io) catch false;
}
fn stderrIsTty() bool {
stderr_tty_once.call();
return stderr_tty_cached;
}
fn userAgentSuffix(self: *const Config) ?[]const u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.user_agent_suffix,
else => null,
};
}
pub fn userAgent(self: *const Config) ?[]const u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.user_agent,
else => null,
};
}
pub fn locale(self: *const Config) [:0]const u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.locale,
else => HttpHeaders.default_locale,
};
}
pub fn timezone(self: *const Config) ?[:0]const u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.timezone,
else => null,
};
}
pub fn httpCacheDir(self: *const Config) ?[]const u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.http_cache_dir,
else => null,
};
}
pub fn httpCacheEntryLimit(self: *const Config) u32 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.http_cache_entry_limit.?,
else => 1000,
};
}
pub fn cookieFile(self: *const Config) ?[]const u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.cookie,
else => null,
};
}
pub fn cookieJarFile(self: *const Config) ?[]const u8 {
return switch (self.mode) {
inline .fetch, .mcp, .agent => |opts| opts.cookie_jar,
else => null,
};
}
pub fn port(self: *const Config) u16 {
return switch (self.mode) {
.serve => |opts| opts.port,
.mcp => |opts| opts.cdp_port orelse 0,
else => unreachable,
};
}
pub fn advertiseHost(self: *const Config) []const u8 {
return switch (self.mode) {
.serve => |opts| opts.advertise_host orelse advertiseHostFallback(opts.host),
.mcp => "127.0.0.1",
else => unreachable,
};
}
// Wildcard bind addresses (0.0.0.0, ::) are not routable for clients
// resolving /json/version. Fall back to a loopback address so the
// advertised webSocketDebuggerUrl is at least connectable from the same
// host (covers the official Docker image, which exposes 9222 via the
// container's published port, and the WSL localhost bridge).
// For remote hosts, users can still pin the URL with --advertise-host.
// See issue #1922.
fn advertiseHostFallback(host: []const u8) []const u8 {
if (isHostWildcard(host)) {
return "127.0.0.1";
}
return host;
}
// True when serve is binding a wildcard address (e.g. Docker --host
// 0.0.0.0) without an explicit --advertise-host. /json/version replaces
// the wildcard with 127.0.0.1 in advertiseHostFallback so the URL stays
// resolvable, but the caller still benefits from emitting a guidance log.
pub fn bindIsWildcard(self: *const Config) bool {
return switch (self.mode) {
.serve => |opts| opts.advertise_host == null and isHostWildcard(opts.host),
else => false,
};
}
fn isHostWildcard(host: []const u8) bool {
return std.mem.eql(u8, host, "0.0.0.0") or std.mem.eql(u8, host, "::");
}
pub fn webBotAuth(self: *const Config) ?WebBotAuthConfig {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| WebBotAuthConfig{
.key_file = opts.web_bot_auth_key_file orelse return null,
.keyid = opts.web_bot_auth_keyid orelse return null,
.domain = opts.web_bot_auth_domain orelse return null,
},
else => null,
};
}
pub fn blockPrivateNetworks(self: *const Config) bool {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.block_private_networks,
else => unreachable,
};
}
pub fn blockCidrs(self: *const Config) ?[]const u8 {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.block_cidrs,
else => unreachable,
};
}
pub fn blockedUrlPatterns(self: *const Config) ?std.mem.SplitIterator(u8, .scalar) {
const patterns = switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.block_urls,
else => unreachable,
} orelse return null;
return std.mem.splitScalar(u8, patterns, ',');
}
pub fn adblockLists(self: *const Config) ?std.mem.SplitIterator(u8, .scalar) {
const paths = switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| opts.adblock_lists,
else => unreachable,
} orelse return null;
return std.mem.splitScalar(u8, paths, ',');
}
pub const Protocol = enum {
cdp,
webdriver,
};
pub fn protocols(self: *const Config) []const Protocol {
return switch (self.mode) {
.serve => |opts| if (opts.protocol.items.len == 0) &.{.cdp} else opts.protocol.items,
.mcp => &.{.cdp},
else => unreachable,
};
}
pub fn maxConnections(self: *const Config) u16 {
return switch (self.mode) {
.serve => |opts| opts.cdp_max_connections,
.mcp => 16,
.fetch, .agent => 0,
else => unreachable,
};
}
// Null disables the reaper: sessions then only end on DELETE /session/{id}.
pub fn httpSessionTimeout(self: *const Config) ?u64 {
return switch (self.mode) {
.serve => |opts| if (opts.http_session_timeout == 0) null else @as(u64, opts.http_session_timeout) * 1000,
.mcp => 60_000, // 1 minute
else => unreachable,
};
}
pub fn maxPendingConnections(self: *const Config) u31 {
return switch (self.mode) {
.serve => |opts| opts.cdp_max_pending_connections,
.mcp => 128,
else => unreachable,
};
}
pub fn cdpMaxMessageSize(self: *const Config) u32 {
return switch (self.mode) {
.serve => |opts| opts.cdp_max_message_size,
else => unreachable,
};
}
pub fn metricsEndpointEnabled(self: *const Config) bool {
return switch (self.mode) {
.serve => |opts| !opts.disable_metrics,
else => unreachable,
};
}
pub fn dumpMetricsOnExit(self: *const Config) bool {
return switch (self.mode) {
.fetch => |opts| opts.metrics,
else => false,
};
}
pub fn cdpMaxHTTPMessageSize(self: *const Config) u32 {
return switch (self.mode) {
.serve => |opts| opts.cdp_max_http_message_size,
else => unreachable,
};
}
/// Returns the user-supplied certificate store (`--ca-cert`/`--ca-path`),
/// if any was loaded during argument parsing. The caller takes ownership.
pub fn customCertStore(self: *const Config) ?*crypto.X509_STORE {
return switch (self.mode) {
inline .serve, .fetch, .mcp, .agent => |opts| {
const store = opts.cert.store orelse return null;
// Validators guarantee a created store loaded something.
lp.assert(opts.cert.count > 0, "empty custom cert store", .{});
return store;
},
else => null,
};
}
pub const DumpFormat = enum {
html,
markdown,
png,
pdf,
wpt,
semantic_tree,
semantic_tree_text,
};
pub const WaitUntil = enum {
load,
domcontentloaded,
networkalmostidle,
networkidle,
done,
};
/// HTTP header values shared across Http and Client.
/// Must be initialized with an allocator that outlives all HTTP connections.
pub const HttpHeaders = struct {
const user_agent_base: [:0]const u8 = "Lightpanda/1.0";
const Brand = struct {
brand: [:0]const u8,
version: [:0]const u8,
full_version: []const u8,
};
/// Source of truth for client-hints brand data. Both the Sec-Ch-Ua
/// HTTP header and navigator.userAgentData.brands derive from this
/// list, so the two sides cannot drift.
pub const brands = [_]Brand{
.{ .brand = "Lightpanda", .version = "1", .full_version = lp.build_config.version },
};
pub const sec_ch_ua: [:0]const u8 = blk: {
var out: [:0]const u8 = "";
for (brands, 0..) |b, i| {
const sep = if (i == 0) "" else ", ";
out = out ++ sep ++ "\"" ++ b.brand ++ "\";v=\"" ++ b.version ++ "\"";
}
break :blk out;
};
pub const sec_ch_ua_full_version_list: [:0]const u8 = blk: {
var out: [:0]const u8 = "";
for (brands, 0..) |b, i| {
const sep = if (i == 0) "" else ", ";
out = out ++ sep ++ "\"" ++ b.brand ++ "\";v=\"" ++ b.full_version ++ "\"";
}
break :blk out;
};
// The neutral default: some bot-protection frontends (e.g. Akamai on
// canada.ca) RST the HTTP/2 stream when a client sends Accept-Encoding
// without Accept-Language.
const default_locale: [:0]const u8 = "en-US";