Repository navigation
Expand file tree
/
Copy pathRuntime.zig
More file actions
1582 lines (1353 loc) · 66.3 KB
/
Copy pathRuntime.zig
File metadata and controls
1582 lines (1353 loc) · 66.3 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 lp = @import("lightpanda");
const Schema = @import("Schema.zig");
const NodeRegistry = @import("../NodeRegistry.zig");
const v8 = lp.js.v8;
const browser_tools = lp.tools;
const BrowserTool = browser_tools.Tool;
const Runtime = @This();
allocator: std.mem.Allocator,
app: *lp.App,
session: *lp.Session,
registry: *NodeRegistry,
env: lp.js.Env,
context: v8.Global,
has_context: bool,
call_arena: std.heap.ArenaAllocator,
primitive_data: [recorded_tool_count]PrimitiveData,
console_data: [std.enums.values(ConsoleMethod).len]ConsoleData,
/// Notified before each `console.*` line is written. The REPL uses it to
/// clear the live spinner so script output starts on a clean line instead
/// of colliding with the indicator; the line still goes to stdout/stderr.
console_observer: ?ConsoleObserver = null,
/// When set, every console line writes here — stderr-bound methods included.
console_sink: ?*std.Io.Writer = null,
/// In-flight async `goto`s; emptied before each `runSource` returns.
pending_gotos: std.ArrayList(PendingGoto),
/// Restarted per `runSource`; backs `PendingGoto.deadline_ms`.
run_timer: std.Io.Timestamp,
/// The runtime installs exactly the recorded browser tools as script
/// primitives — the same set the recorder writes — so every recorded call
/// replays. `buildArgs` adapts each tool's JS calling convention to the JSON
/// `browser_tools.call` expects.
const recorded_tool_count = blk: {
var n: usize = 0;
for (std.enums.values(BrowserTool)) |t| {
if (t.isRecorded()) n += 1;
}
break :blk n;
};
const PrimitiveData = struct {
runtime: *Runtime,
tool: BrowserTool,
};
/// An async `goto` not yet settled. The resolver and receiver (`this`) are
/// Globals so they survive the microtask drains between driver iterations.
const PendingGoto = struct {
frame_id: u32,
resolver: v8.Global,
receiver: v8.Global,
/// `run_timer` reading (ms) past which the navigation is abandoned.
deadline_ms: u64,
until: lp.Config.WaitUntil,
fn reset(self: *PendingGoto) void {
v8.v8__Global__Reset(&self.resolver);
v8.v8__Global__Reset(&self.receiver);
}
};
const ConsoleMethod = enum {
debug,
@"error",
info,
log,
warn,
fn writesStderr(self: ConsoleMethod) bool {
return switch (self) {
.@"error", .warn => true,
.debug, .info, .log => false,
};
}
};
const ConsoleData = struct {
runtime: *Runtime,
method: ConsoleMethod,
};
const ConsoleObserver = struct {
context: *anyopaque,
notify: *const fn (context: *anyopaque) void,
};
const InitError = error{
OutOfMemory,
RuntimeInitFailed,
TooManyContexts,
};
const RunError = error{
OutOfMemory,
};
pub fn init(
allocator: std.mem.Allocator,
app: *lp.App,
session: *lp.Session,
registry: *NodeRegistry,
) InitError!*Runtime {
const self = try allocator.create(Runtime);
errdefer allocator.destroy(self);
self.* = .{
.allocator = allocator,
.app = app,
.session = session,
.registry = registry,
.env = undefined,
.context = undefined,
.has_context = false,
.call_arena = .init(allocator),
.primitive_data = undefined,
.console_data = undefined,
.pending_gotos = .empty,
.run_timer = undefined,
};
errdefer self.call_arena.deinit();
// Separate isolate from the page. The full `Env` is used only as an isolate
// + terminate/microtask carrier; the agent context is bare (no WebAPIs).
self.env = lp.js.Env.init(app, .{}) catch return error.RuntimeInitFailed;
errdefer self.env.deinit();
self.env.protectHeapLimit();
try self.createContext();
errdefer self.resetContext();
return self;
}
pub fn deinit(self: *Runtime) void {
// Free leftover Globals while the isolate is still alive (a run terminated
// mid-flight can leave some).
for (self.pending_gotos.items) |*pending| pending.reset();
self.pending_gotos.deinit(self.allocator);
self.resetContext();
self.env.deinit();
self.call_arena.deinit();
const allocator = self.allocator;
allocator.destroy(self);
}
pub fn terminate(self: *Runtime) void {
self.env.terminate();
}
pub fn cancelTerminate(self: *Runtime) void {
self.env.cancelTerminate();
}
fn createContext(self: *Runtime) InitError!void {
var hs: lp.js.HandleScope = undefined;
hs.init(self.env.isolate);
defer hs.deinit();
const context = v8.v8__Context__New(self.env.isolate.handle, null, null) orelse
return error.RuntimeInitFailed;
v8.v8__Global__New(self.env.isolate.handle, context, &self.context);
self.has_context = true;
v8.v8__Context__Enter(context);
defer v8.v8__Context__Exit(context);
// The promise-reject callback every `Env` installs reads a browser `Context`
// from embedder slot 1; this bare context has none. Pin the slot to null so
// the callback no-ops instead of aligncasting garbage — the script body runs
// inside an async wrapper, so unhandled rejections happen routinely.
v8.v8__Context__SetAlignedPointerInEmbedderData(context, 1, null);
const global = v8.v8__Context__Global(context) orelse return error.RuntimeInitFailed;
// `Page` is the only global verb; `new Page()` attaches a method for each
// recorded tool, reusing these `primitive_data` entries — so fill them here.
var i: usize = 0;
for (std.enums.values(BrowserTool)) |t| {
if (!t.isRecorded()) continue;
self.primitive_data[i] = .{ .runtime = self, .tool = t };
i += 1;
}
try self.installFunction(context, global, "Page", pageConstructor, self);
try self.installConsole(context, global);
}
fn resetContext(self: *Runtime) void {
if (!self.has_context) return;
v8.v8__Global__Reset(&self.context);
self.env.isolate.notifyContextDisposed();
self.has_context = false;
}
const Callback = *const fn (?*const v8.FunctionCallbackInfo) callconv(.c) void;
/// Install `callback` (carrying `data` as its `External`) under `name` on `object`.
fn installFunction(
self: *Runtime,
context: *const v8.Context,
object: *const v8.Object,
name: []const u8,
callback: Callback,
data: *anyopaque,
) InitError!void {
const external = self.env.isolate.createExternal(data);
const func = v8.v8__Function__New__DEFAULT2(context, callback, external) orelse
return error.RuntimeInitFailed;
try self.setObjectProperty(context, object, name, @ptrCast(func));
}
fn installConsole(
self: *Runtime,
context: *const v8.Context,
global: *const v8.Object,
) InitError!void {
const console = v8.v8__Object__New(self.env.isolate.handle) orelse
return error.RuntimeInitFailed;
for (std.enums.values(ConsoleMethod), 0..) |method, i| {
self.console_data[i] = .{ .runtime = self, .method = method };
try self.installFunction(context, console, @tagName(method), consoleCallback, &self.console_data[i]);
}
try setObjectProperty(self, context, global, "console", @ptrCast(console));
}
fn setObjectProperty(
self: *Runtime,
context: *const v8.Context,
object: *const v8.Object,
name: []const u8,
value: *const v8.Value,
) InitError!void {
var out: v8.MaybeBool = undefined;
v8.v8__Object__Set(
object,
context,
@ptrCast(self.env.isolate.initStringHandle(name)),
value,
&out,
);
if (!out.has_value or !out.value) return error.RuntimeInitFailed;
}
/// Run script source in the agent context. Returns null on success; on a JS
/// compile/runtime exception returns a formatted error allocated in this
/// runtime's call arena and valid until deinit or the next run.
pub fn runSource(self: *Runtime, source: []const u8, name: []const u8) RunError!?[]const u8 {
_ = self.call_arena.reset(.retain_capacity);
self.run_timer = .now(lp.io, .boot);
var hs: lp.js.HandleScope = undefined;
hs.init(self.env.isolate);
defer hs.deinit();
const context: *const v8.Context = @ptrCast(v8.v8__Global__Get(&self.context, self.env.isolate.handle) orelse
return try self.dupeError("agent script context is not available"));
v8.v8__Context__Enter(context);
defer v8.v8__Context__Exit(context);
var try_catch: v8.TryCatch = undefined;
v8.v8__TryCatch__CONSTRUCT(&try_catch, self.env.isolate.handle);
defer v8.v8__TryCatch__DESTRUCT(&try_catch);
const script_name = self.env.isolate.initStringHandle(name);
// Wrap in an async IIFE so the source can use top-level `await` (e.g.
// `await page.goto(...)`). The wrapper evaluates to a Promise; a top-level
// `return <expr>` becomes that Promise's value, which we echo. (A bare
// trailing expression no longer auto-prints — `await` and a script
// completion value are mutually exclusive in JS.)
const wrapped = std.fmt.allocPrint(self.call_arena.allocator(), "(async () => {{\n{s}\n}})()", .{source}) catch
return try self.dupeError("out of memory");
const script_source = self.env.isolate.initStringHandle(wrapped);
var origin: v8.ScriptOrigin = undefined;
v8.v8__ScriptOrigin__CONSTRUCT(&origin, script_name);
var compiler_source: v8.ScriptCompilerSource = undefined;
v8.v8__ScriptCompiler__Source__CONSTRUCT2(script_source, &origin, null, &compiler_source);
defer v8.v8__ScriptCompiler__Source__DESTRUCT(&compiler_source);
const script = v8.v8__ScriptCompiler__Compile(
context,
&compiler_source,
v8.kNoCompileOptions,
v8.kNoCacheNoReason,
) orelse return try self.formatCaught(context, &try_catch, "compile failed");
const completion = v8.v8__Script__Run(script, context) orelse
return try self.formatCaught(context, &try_catch, "script failed");
// `goto` only *starts* a navigation, so the root Promise is usually still
// pending; drive the in-flight ones to completion.
const root: *const v8.Promise = @ptrCast(completion);
self.driveAsync(context, &try_catch, root);
if (v8.v8__TryCatch__HasCaught(&try_catch)) {
return try self.formatCaught(context, &try_catch, "script failed");
}
// A still-pending root means the script awaited something we can't settle
// (no async navigation is in flight) — stay silent.
const state = promiseState(root);
if (state != v8.kFulfilled and state != v8.kRejected) return null;
const completion_value = v8.v8__Promise__Result(root) orelse return null;
if (state == v8.kRejected) return try self.formatRejection(context, completion_value);
self.printCompletion(context, completion_value);
return null;
}
/// `v8__Promise__State` returns the `c_uint` `PromiseState`, but the `k*`
/// constants are `c_int`; normalize so comparisons and switches type-check.
fn promiseState(promise: *const v8.Promise) c_int {
return @intCast(v8.v8__Promise__State(promise));
}
/// Format a script's rejection reason into a run-arena message. Prefers a thrown
/// Error's `.message` so the caller's own "Error:" label isn't doubled
/// (`Value.toString` on an Error yields "Error: <message>").
fn formatRejection(self: *Runtime, context: *const v8.Context, reason: *const v8.Value) RunError![]const u8 {
const value = self.errorMessage(context, reason) orelse reason;
const text = self.valueToString(self.call_arena.allocator(), context, value) catch
return try self.dupeError("script failed");
return try self.dupeError(text);
}
/// The `.message` of a thrown Error (a string), or null when `reason` is not an
/// Error-like object — in which case the caller stringifies the value itself.
fn errorMessage(self: *Runtime, context: *const v8.Context, reason: *const v8.Value) ?*const v8.Value {
if (!v8.v8__Value__IsObject(reason)) return null;
const key: *const v8.Value = @ptrCast(self.env.isolate.initStringHandle("message"));
const message = v8.v8__Object__Get(@ptrCast(reason), context, key) orelse return null;
return if (v8.v8__Value__IsString(message)) message else null;
}
/// Echo a script's output — the value it `return`s from the async wrapper, so a
/// script ending in `return page.extract(...)` prints without `console.log`.
/// `undefined` — no `return`, or a bare trailing expression — stays silent.
fn printCompletion(self: *Runtime, context: *const v8.Context, value: *const v8.Value) void {
if (v8.v8__Value__IsUndefined(value)) return;
var arena_state: std.heap.ArenaAllocator = .init(self.allocator);
defer arena_state.deinit();
const text = self.displayString(arena_state.allocator(), context, value) catch return;
self.writeConsoleLine(.log, text);
}
/// Unwrap a callback's info handle and its `External` payload (the `*T` passed
/// to `installFunction`). Returns null — so the callback no-ops — if either is
/// missing.
fn callbackData(comptime T: type, info_handle: ?*const v8.FunctionCallbackInfo) ?struct { *const v8.FunctionCallbackInfo, *T } {
const info = info_handle orelse return null;
const raw_data = v8.v8__FunctionCallbackInfo__Data(info) orelse return null;
const data: *T = @ptrCast(@alignCast(v8.v8__External__Value(@ptrCast(raw_data)) orelse return null));
return .{ info, data };
}
fn primitiveCallback(info_handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
const info, const data = callbackData(PrimitiveData, info_handle) orelse return;
data.runtime.invoke(data.tool, info);
}
fn consoleCallback(info_handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
const info, const data = callbackData(ConsoleData, info_handle) orelse return;
data.runtime.invokeConsole(data.method, info);
}
fn pageConstructor(info_handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
const info, const self = callbackData(Runtime, info_handle) orelse return;
self.construct(info);
}
fn closeCallback(info_handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
const info, const self = callbackData(Runtime, info_handle) orelse return;
self.invokeClose(info);
}
/// `new Page()`: attach a method for every recorded tool (including `goto`) plus
/// `close`. `__lpFrameId` is left unset until the first `goto` navigates the page.
fn construct(self: *Runtime, info: *const v8.FunctionCallbackInfo) void {
if (!v8.v8__FunctionCallbackInfo__IsConstructCall(info)) {
return self.throwTypeError("Page must be called with new");
}
const context = v8.v8__Isolate__GetCurrentContext(self.env.isolate.handle) orelse
return self.throwError("internal: missing callback context");
const this = v8.v8__FunctionCallbackInfo__This(info) orelse
return self.throwError("internal: missing receiver");
for (&self.primitive_data) |*data| {
self.installFunction(context, this, @tagName(data.tool), primitiveCallback, data) catch
return self.throwError("failed to construct page");
}
self.installFunction(context, this, "close", closeCallback, self) catch
return self.throwError("failed to construct page");
}
/// Property carrying a page handle's claim on a live frame. Numeric while the
/// page is navigated; absent/undefined once never-navigated or closed.
const frame_id_key = "__lpFrameId";
/// `page.close()`: stale the wrapper so later method calls error. A single
/// synchronous page has no popups to free; the active page is reclaimed on the
/// next `goto` or at script end.
fn invokeClose(self: *Runtime, info: *const v8.FunctionCallbackInfo) void {
const context = v8.v8__Isolate__GetCurrentContext(self.env.isolate.handle) orelse return;
const this = v8.v8__FunctionCallbackInfo__This(info) orelse return;
self.setObjectProperty(context, this, frame_id_key, self.env.isolate.initUndefined()) catch {};
}
fn invoke(self: *Runtime, tool: BrowserTool, info: *const v8.FunctionCallbackInfo) void {
// Owned, not shared: marshalling runs JS (`toJSON`) that can re-enter a
// primitive; a shared arena would let the nested call reset ours mid-flight.
var arena_state: std.heap.ArenaAllocator = .init(self.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const context = v8.v8__Isolate__GetCurrentContext(self.env.isolate.handle) orelse {
self.throwError("internal: missing callback context");
return;
};
const args = self.buildArgs(arena, context, tool, info) catch |err| switch (err) {
error.OutOfMemory => return self.throwError("out of memory"),
error.JsException => return,
error.InvalidArguments => return self.throwTypeError("invalid arguments"),
};
if (tool == .goto) return self.invokeGoto(arena, context, info, args);
// Route the call at the receiver's own frame: sibling pages may coexist, so
// `pages[0]` is not necessarily this handle's page.
const frame_id = self.receiverFrameId(context, info) orelse
return self.throwError("page is not navigated or has been closed; call page.goto(url) first");
if (self.session.findFrameByFrameId(frame_id) == null)
return self.throwError("page handle is no longer valid; the page was closed");
self.session.setToolFrameOverride(frame_id);
defer self.session.setToolFrameOverride(null);
const result = self.callTool(arena, tool, args) catch |err| switch (err) {
error.OutOfMemory => return self.throwError("out of memory"),
};
switch (result) {
.ok => |text| switch (tool) {
.extract => {
const normalized = self.normalizeExtractReturnJson(arena, text) catch |err| switch (err) {
error.OutOfMemory => return self.throwError("out of memory"),
};
self.setReturnJson(context, info, normalized);
},
else => self.setReturnString(info, text),
},
.fail => |message| self.throwError(message),
}
}
/// Start the receiver Page's navigation and return a *pending* Promise of the
/// page object; `driveAsync` settles it once the frame loads. This is what lets
/// `Promise.all([a.goto(x), b.goto(y)])` fetch both in parallel.
fn invokeGoto(
self: *Runtime,
arena: std.mem.Allocator,
context: *const v8.Context,
info: *const v8.FunctionCallbackInfo,
args: ?std.json.Value,
) void {
const resolver = v8.v8__Promise__Resolver__New(context) orelse
return self.throwError("internal: resolver alloc failed");
const promise = v8.v8__Promise__Resolver__GetPromise(resolver) orelse
return self.throwError("internal: promise alloc failed");
self.setReturnValue(info, @ptrCast(promise));
const this = v8.v8__FunctionCallbackInfo__This(info) orelse
return self.rejectResolver(context, resolver, "navigation failed");
// Non-null on a re-goto: startGoto replaces only that page, not its siblings.
const receiver_frame_id = self.receiverFrameId(context, info);
// startGoto is browser-side work; run it under the browser's isolate.
// Settle the resolver only after the block: a `return` inside it runs
// script-isolate work before the deferred exit.
const maybe_started: ?browser_tools.StartedGoto = blk: {
self.session.browser.env.isolate.enter();
defer self.session.browser.env.isolate.exit();
break :blk browser_tools.startGoto(arena, self.session, self.registry, args, receiver_frame_id) catch null;
};
const started = maybe_started orelse
return self.rejectResolver(context, resolver, "navigation failed");
var pending: PendingGoto = .{
.frame_id = started.frame_id,
.resolver = undefined,
.receiver = undefined,
.deadline_ms = @as(u64, @intCast(self.run_timer.untilNow(lp.io, .boot).toMilliseconds())) + started.timeout_ms,
.until = started.until,
};
v8.v8__Global__New(self.env.isolate.handle, resolver, &pending.resolver);
v8.v8__Global__New(self.env.isolate.handle, this, &pending.receiver);
self.pending_gotos.append(self.allocator, pending) catch {
pending.reset();
return self.rejectResolver(context, resolver, "out of memory");
};
}
/// Drive every in-flight `goto` to completion: each pass ticks the browser over
/// the pending frames, settles those that finished, then drains microtasks so
/// awaiting continuations run (and may start more gotos). Ends when the root
/// Promise settles, no gotos remain, or the script is cancelled.
fn driveAsync(self: *Runtime, context: *const v8.Context, try_catch: *const v8.TryCatch, root: *const v8.Promise) void {
var runner = self.session.runner(.{});
var arena_state: std.heap.ArenaAllocator = .init(self.allocator);
defer arena_state.deinit();
// Settle anything resolved synchronously, so a goto-free run still drains.
self.env.performIsolateMicrotasks();
while (true) {
const state = promiseState(root);
if (state == v8.kFulfilled or state == v8.kRejected) break;
if (v8.v8__TryCatch__HasCaught(try_catch)) break;
if (self.pending_gotos.items.len == 0) break;
if (self.session.isCancelled()) {
self.failAllPending(context, "navigation cancelled");
break;
}
_ = arena_state.reset(.retain_capacity);
const conditions = arena_state.allocator().alloc(lp.Session.Runner.WaitCondition, self.pending_gotos.items.len) catch {
self.failAllPending(context, "out of memory");
break;
};
for (self.pending_gotos.items, conditions) |pending, *condition| {
condition.* = .{ .frame_id = pending.frame_id, .until = pending.until };
}
// Browser-side tick: run under the browser's isolate, exit before the
// agent-side settling below (the Runtime owns a separate isolate).
var tick_failed = false;
{
self.session.browser.env.isolate.enter();
defer self.session.browser.env.isolate.exit();
_ = runner.tick(50, conditions) catch {
tick_failed = true;
};
}
if (tick_failed) {
self.failAllPending(context, "navigation failed");
break;
}
self.settleCompleted(context, conditions);
self.env.performIsolateMicrotasks();
}
// Reject anything still in flight (fire-and-forget goto, or a broken-out loop).
self.failAllPending(context, "navigation abandoned");
}
/// Settle each pending goto that finished or timed out, compacting survivors back
/// in place. `conditions[i]` lines up with `pending_gotos.items[i]` (same pass).
fn settleCompleted(self: *Runtime, context: *const v8.Context, conditions: []const lp.Session.Runner.WaitCondition) void {
const now_ms: u64 = @intCast(self.run_timer.untilNow(lp.io, .boot).toMilliseconds());
var write: usize = 0;
for (conditions, 0..) |condition, i| {
const pending = &self.pending_gotos.items[i];
const outcome: ?Outcome = switch (condition.status) {
.complete => .loaded,
.err => .failed,
.pending => if (now_ms >= pending.deadline_ms) .timed_out else null,
};
if (outcome) |o| {
self.settlePending(context, pending, o);
} else {
self.pending_gotos.items[write] = pending.*;
write += 1;
}
}
self.pending_gotos.shrinkRetainingCapacity(write);
}
const Outcome = enum { loaded, failed, timed_out };
/// Resolve or reject one pending goto's Promise and free its Globals.
fn settlePending(self: *Runtime, context: *const v8.Context, pending: *PendingGoto, outcome: Outcome) void {
const resolver: *const v8.PromiseResolver = @ptrCast(v8.v8__Global__Get(&pending.resolver, self.env.isolate.handle));
switch (outcome) {
.loaded => done: {
const frame = self.session.findFrameByFrameId(pending.frame_id);
if (frame == null or frame.?._last_navigate_error != null) {
self.rejectResolver(context, resolver, "navigation failed");
break :done;
}
const this: *const v8.Object = @ptrCast(v8.v8__Global__Get(&pending.receiver, self.env.isolate.handle));
self.bindFrameId(context, this, pending.frame_id) catch {
self.rejectResolver(context, resolver, "internal: page bind failed");
break :done;
};
self.resolveResolver(context, resolver, @ptrCast(this));
},
.failed => self.rejectResolver(context, resolver, "navigation failed"),
.timed_out => self.rejectResolver(context, resolver, "navigation timed out"),
}
pending.reset();
}
/// Reject every still-pending goto and clear the list, freeing all Globals.
fn failAllPending(self: *Runtime, context: *const v8.Context, message: []const u8) void {
for (self.pending_gotos.items) |*pending| {
const resolver: *const v8.PromiseResolver = @ptrCast(v8.v8__Global__Get(&pending.resolver, self.env.isolate.handle));
self.rejectResolver(context, resolver, message);
pending.reset();
}
self.pending_gotos.clearRetainingCapacity();
}
fn resolveResolver(_: *Runtime, context: *const v8.Context, resolver: *const v8.PromiseResolver, value: *const v8.Value) void {
var out: v8.MaybeBool = undefined;
v8.v8__Promise__Resolver__Resolve(resolver, context, value, &out);
}
fn rejectResolver(self: *Runtime, context: *const v8.Context, resolver: *const v8.PromiseResolver, message: []const u8) void {
var out: v8.MaybeBool = undefined;
v8.v8__Promise__Resolver__Reject(resolver, context, self.env.isolate.createError(message), &out);
}
/// Bind `__lpFrameId` on a page object to `frame_id` — the handle's claim on the
/// live frame, checked by `invoke` on every later method call.
fn bindFrameId(self: *Runtime, context: *const v8.Context, this: *const v8.Object, frame_id: u32) InitError!void {
const value = v8.v8__Integer__NewFromUnsigned(self.env.isolate.handle, frame_id) orelse
return error.RuntimeInitFailed;
return self.setObjectProperty(context, this, frame_id_key, @ptrCast(value));
}
/// Frame id a method's receiver was bound to (`this.__lpFrameId`), or null when
/// the page was never navigated or has been closed.
fn receiverFrameId(self: *Runtime, context: *const v8.Context, info: *const v8.FunctionCallbackInfo) ?u32 {
const this = v8.v8__FunctionCallbackInfo__This(info) orelse return null;
const key: *const v8.Value = @ptrCast(self.env.isolate.initStringHandle(frame_id_key));
const prop = v8.v8__Object__Get(this, context, key) orelse return null;
if (!v8.v8__Value__IsNumber(prop)) return null;
var out: v8.MaybeU32 = undefined;
v8.v8__Value__Uint32Value(prop, context, &out);
return if (out.has_value) out.value else null;
}
fn invokeConsole(self: *Runtime, method: ConsoleMethod, info: *const v8.FunctionCallbackInfo) void {
// Owned arena (see `invoke`): an argument's `toString` can re-enter a
// primitive mid-loop and must not reset the buffer we're accumulating.
var arena_state: std.heap.ArenaAllocator = .init(self.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const context = v8.v8__Isolate__GetCurrentContext(self.env.isolate.handle) orelse return;
const argc: usize = @intCast(v8.v8__FunctionCallbackInfo__Length(info));
var aw: std.Io.Writer.Allocating = .init(arena);
for (0..argc) |i| {
if (i > 0) aw.writer.writeByte(' ') catch return;
const value = v8.v8__FunctionCallbackInfo__INDEX(info, @intCast(i)) orelse continue;
const text = self.valueToString(arena, context, value) catch "<unprintable>";
aw.writer.writeAll(text) catch return;
}
self.writeConsoleLine(method, aw.written());
}
fn writeConsoleLine(self: *Runtime, method: ConsoleMethod, line: []const u8) void {
if (self.console_observer) |obs| obs.notify(obs.context);
if (self.console_sink) |sink| {
sink.print("{s}\n", .{line}) catch {};
return;
}
var buf: [4096]u8 = undefined;
const file = if (method.writesStderr()) std.Io.File.stderr() else std.Io.File.stdout();
var writer = file.writerStreaming(lp.io, &buf);
writer.interface.print("{s}\n", .{line}) catch return;
writer.interface.flush() catch return;
}
const PrimitiveResult = union(enum) {
ok: []const u8,
fail: []const u8,
};
fn callTool(
self: *Runtime,
arena: std.mem.Allocator,
tool: BrowserTool,
args: ?std.json.Value,
) error{OutOfMemory}!PrimitiveResult {
self.session.browser.env.isolate.enter();
defer self.session.browser.env.isolate.exit();
const result = browser_tools.call(arena, self.session, self.registry, @tagName(tool), args, .{}) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.FrameNotLoaded => return .{ .fail = "no page loaded - run page.goto(url) first" },
else => return .{ .fail = std.fmt.allocPrint(arena, "{s} failed: {s}", .{ @tagName(tool), @errorName(err) }) catch return error.OutOfMemory },
};
if (result.is_error) return .{ .fail = result.text };
return .{ .ok = result.text };
}
const BuildArgsError = error{
OutOfMemory,
JsException,
InvalidArguments,
};
fn buildArgs(
self: *Runtime,
arena: std.mem.Allocator,
context: *const v8.Context,
tool: BrowserTool,
info: *const v8.FunctionCallbackInfo,
) BuildArgsError!?std.json.Value {
const argc: usize = @intCast(v8.v8__FunctionCallbackInfo__Length(info));
return switch (tool) {
.extract => try self.extractArgs(arena, context, info, argc),
else => try self.marshalArgs(arena, context, info, argc, Schema.positionalFor(tool)),
};
}
/// Marshals `tool(positionals…, options?)` into the args object `browser_tools.call`
/// expects: leading primitives bind to `positional` by index (a `null` omits its
/// field), a trailing object merges as options (conflict on a repeated field), and a
/// lone object passes through. Positionals stay opaque; the tool's parser types them.
fn marshalArgs(
self: *Runtime,
arena: std.mem.Allocator,
context: *const v8.Context,
info: *const v8.FunctionCallbackInfo,
argc: usize,
positional: []const []const u8,
) BuildArgsError!std.json.Value {
const values = try arena.alloc(std.json.Value, argc);
for (values, 0..) |*v, i| v.* = try self.argJson(arena, context, info, @intCast(i));
if (argc == 1 and values[0] == .object) return values[0];
// A trailing object is the options bag; everything before it is positional.
var positional_count = argc;
var options: ?std.json.ObjectMap = null;
if (argc > 0 and values[argc - 1] == .object) {
options = values[argc - 1].object;
positional_count = argc - 1;
}
if (positional_count > positional.len) return error.InvalidArguments;
var obj: std.json.ObjectMap = .empty;
for (values[0..positional_count], positional[0..positional_count]) |v, field| {
switch (v) {
.null => {}, // omit the field — e.g. page/focused-level selector
.object, .array => return error.InvalidArguments,
else => try obj.put(arena, field, v),
}
}
if (options) |opts| {
var it = opts.iterator();
while (it.next()) |entry| {
if (obj.contains(entry.key_ptr.*)) return error.InvalidArguments;
try obj.put(arena, entry.key_ptr.*, entry.value_ptr.*);
}
}
return .{ .object = obj };
}
fn extractArgs(
self: *Runtime,
arena: std.mem.Allocator,
context: *const v8.Context,
info: *const v8.FunctionCallbackInfo,
argc: usize,
) BuildArgsError!std.json.Value {
if (argc != 1) return error.InvalidArguments;
const value = try self.argJson(arena, context, info, 0);
const schema = switch (value) {
.string, .array => try extractSchemaString(arena, value),
.object => |obj| if (obj.get("schema")) |inner| blk: {
if (obj.count() != 1) return error.InvalidArguments;
break :blk try extractSchemaString(arena, inner);
} else try extractSchemaString(arena, value),
else => return error.InvalidArguments,
};
return try objectWith(arena, "schema", .{ .string = schema });
}
fn extractSchemaString(arena: std.mem.Allocator, value: std.json.Value) error{OutOfMemory}![]const u8 {
return switch (value) {
.string => |str| normalizeExtractSchemaString(arena, str),
.array => |arr| normalizeExtractSchemaString(
arena,
try std.json.Stringify.valueAlloc(arena, std.json.Value{ .array = arr }, .{}),
),
else => try std.json.Stringify.valueAlloc(arena, value, .{}),
};
}
fn normalizeExtractSchemaString(arena: std.mem.Allocator, schema: []const u8) error{OutOfMemory}![]const u8 {
const trimmed = std.mem.trim(u8, schema, &std.ascii.whitespace);
if (trimmed.len == 0 or trimmed[0] != '[') return schema;
return try std.fmt.allocPrint(arena, "{{\"__root\":{s}}}", .{schema});
}
fn argJson(
self: *Runtime,
arena: std.mem.Allocator,
context: *const v8.Context,
info: *const v8.FunctionCallbackInfo,
index: u32,
) BuildArgsError!std.json.Value {
const value = v8.v8__FunctionCallbackInfo__INDEX(info, @intCast(index)) orelse return error.InvalidArguments;
return self.valueToJson(arena, context, value);
}
fn valueToJson(
self: *Runtime,
arena: std.mem.Allocator,
context: *const v8.Context,
value: *const v8.Value,
) BuildArgsError!std.json.Value {
const json_string = v8.v8__JSON__Stringify(context, value, null) orelse return error.JsException;
const json = try self.stringToOwned(arena, json_string);
if (std.mem.eql(u8, json, "undefined")) return error.InvalidArguments;
return std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{}) catch error.InvalidArguments;
}
fn objectWith(arena: std.mem.Allocator, key: []const u8, value: std.json.Value) error{OutOfMemory}!std.json.Value {
var obj: std.json.ObjectMap = .empty;
try obj.put(arena, key, value);
return .{ .object = obj };
}
/// Unwraps only the `__root` sentinel that `normalizeExtractSchemaString` injects
/// for array schemas; a real single-field object schema keeps its shape.
fn normalizeExtractReturnJson(_: *Runtime, arena: std.mem.Allocator, value: []const u8) error{OutOfMemory}![]const u8 {
if (value.len == 0) return value;
const parsed = std.json.parseFromSliceLeaky(std.json.Value, arena, value, .{}) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return value,
};
if (parsed != .object or parsed.object.count() != 1) return value;
var it = parsed.object.iterator();
const entry = it.next() orelse return value;
if (!std.mem.eql(u8, entry.key_ptr.*, "__root")) return value;
return try std.json.Stringify.valueAlloc(arena, entry.value_ptr.*, .{});
}
fn setReturnString(self: *Runtime, info: *const v8.FunctionCallbackInfo, value: []const u8) void {
self.setReturnValue(info, @ptrCast(self.env.isolate.initStringHandle(value)));
}
fn setReturnJson(self: *Runtime, context: *const v8.Context, info: *const v8.FunctionCallbackInfo, value: []const u8) void {
if (value.len == 0) {
self.setReturnValue(info, self.env.isolate.initUndefined());
return;
}
const json = self.env.isolate.initStringHandle(value);
const parsed = v8.v8__JSON__Parse(context, json) orelse {
self.throwError("extract returned invalid JSON");
return;
};
self.setReturnValue(info, parsed);
}
fn setReturnValue(_: *Runtime, info: *const v8.FunctionCallbackInfo, value: *const v8.Value) void {
var rv: v8.ReturnValue = undefined;
v8.v8__FunctionCallbackInfo__GetReturnValue(info, &rv);
v8.v8__ReturnValue__Set(rv, value);
}
fn throwError(self: *Runtime, message: []const u8) void {
_ = v8.v8__Isolate__ThrowException(self.env.isolate.handle, self.env.isolate.createError(message));
}
fn throwTypeError(self: *Runtime, message: []const u8) void {
_ = v8.v8__Isolate__ThrowException(self.env.isolate.handle, self.env.isolate.createTypeError(message));
}
fn formatCaught(
self: *Runtime,
context: *const v8.Context,
try_catch: *const v8.TryCatch,
fallback: []const u8,
) RunError![]const u8 {
const arena = self.call_arena.allocator();
if (v8.v8__TryCatch__StackTrace(try_catch, context)) |stack_value| {
const stack = self.valueToString(arena, context, stack_value) catch "";
if (stack.len > 0) return stack;
}
const exception = if (v8.v8__TryCatch__Exception(try_catch)) |exception_value|
self.valueToString(arena, context, exception_value) catch fallback
else
fallback;
const line: ?u32 = blk: {
const msg = v8.v8__TryCatch__Message(try_catch) orelse break :blk null;
const n = v8.v8__Message__GetLineNumber(msg, context);
break :blk if (n < 0) null else @as(u32, @intCast(n));
};
if (line) |n| {
return std.fmt.allocPrint(arena, "line {d}: {s}", .{ n, exception }) catch return error.OutOfMemory;
}
return try self.dupeError(exception);
}
fn valueToString(
self: *Runtime,
arena: std.mem.Allocator,
context: *const v8.Context,
value: *const v8.Value,
) error{ OutOfMemory, JsException }![]const u8 {
const string = v8.v8__Value__ToString(value, context) orelse return error.JsException;
return self.stringToOwned(arena, string);
}
/// Display form for the script's completion value: objects and arrays as JSON
/// (plain coercion gives a useless `[object Object]`), every other value via that
/// coercion. Falls back to coercion when JSON.stringify yields no string — a
/// thrown circular reference, or a value (e.g. a function) that stringifies to
/// `undefined`; the nested TryCatch keeps such a throw from leaking into the
/// caller's scope.
fn displayString(
self: *Runtime,
arena: std.mem.Allocator,
context: *const v8.Context,
value: *const v8.Value,
) error{ OutOfMemory, JsException }![]const u8 {
if (v8.v8__Value__IsObject(value)) {
var try_catch: v8.TryCatch = undefined;
v8.v8__TryCatch__CONSTRUCT(&try_catch, self.env.isolate.handle);
defer v8.v8__TryCatch__DESTRUCT(&try_catch);
if (v8.v8__JSON__Stringify(context, value, null)) |json| {
return self.stringToOwned(arena, json);
}
}
return self.valueToString(arena, context, value);
}
fn stringToOwned(
self: *Runtime,
arena: std.mem.Allocator,
string: *const v8.String,
) error{OutOfMemory}![]const u8 {
const len: usize = @intCast(v8.v8__String__Utf8Length(string, self.env.isolate.handle));
const buf = try arena.alloc(u8, len);
const written = v8.v8__String__WriteUtf8(
string,
self.env.isolate.handle,
buf.ptr,
buf.len,
v8.NO_NULL_TERMINATION | v8.REPLACE_INVALID_UTF8,
);
return buf[0..written];
}
fn dupeError(self: *Runtime, message: []const u8) RunError![]const u8 {
return self.call_arena.allocator().dupe(u8, message) catch error.OutOfMemory;
}
const testing = @import("../testing.zig");
fn runTestScript(runtime: *Runtime, source: []const u8) !void {
if (try runtime.runSource(source, "agent-runtime-test.js")) |message| {
std.debug.print("agent script failed:\n{s}\n", .{message});
return error.AgentScriptFailed;
}
}
fn terminateRuntimeSoon(runtime: *Runtime) void {
lp.io.sleep(.fromMilliseconds(10), .awake) catch {};
runtime.terminate();
}