-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathagent_main.zig
More file actions
1645 lines (1498 loc) · 70.6 KB
/
agent_main.zig
File metadata and controls
1645 lines (1498 loc) · 70.6 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
/// kuri-agent — drive Chrome from the command line
///
/// Stateless CLI: each command connects via CDP, acts, disconnects.
/// Session (~/.kuri/session.json) persists: tab, refs, headers, stealth.
///
/// tabs → use <ws> → go <url> → snap → click @e3 → snap → ...
///
/// Key commands:
/// snap a11y tree (~2k tokens) snap --interactive (~1.3k)
/// click/type act on @ref from snap grab <ref> follows popups
/// stealth anti-bot patches cookies/headers/audit for security
const std = @import("std");
const compat = @import("compat.zig");
const CdpClient = @import("cdp/client.zig").CdpClient;
const protocol = @import("cdp/protocol.zig");
const a11y = @import("snapshot/a11y.zig");
const util_json = @import("util/json.zig");
const SESSION_FILE = ".kuri/session.json";
const DEFAULT_CDP_PORT: u16 = 9222;
const Session = struct {
cdp_url: []const u8,
refs: std.StringHashMap(u32),
extra_headers: std.StringHashMap([]const u8),
stealth: bool,
fn init(allocator: std.mem.Allocator) Session {
return .{
.cdp_url = "",
.refs = std.StringHashMap(u32).init(allocator),
.extra_headers = std.StringHashMap([]const u8).init(allocator),
.stealth = false,
};
}
fn deinit(self: *Session) void {
self.refs.deinit();
self.extra_headers.deinit();
}
};
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var arena_impl = std.heap.ArenaAllocator.init(gpa);
defer arena_impl.deinit();
const arena = arena_impl.allocator();
const raw_args = init.minimal.args.toSlice(arena) catch
std.process.fatal("failed to get args", .{});
const args: []const []const u8 = @ptrCast(raw_args);
if (args.len < 2) {
printUsage();
std.process.exit(1);
}
const cmd = args[1];
const rest = args[2..];
// Commands that don't need a session
if (std.mem.eql(u8, cmd, "tabs")) {
const port = parsePortFlag(rest) orelse DEFAULT_CDP_PORT;
try cmdTabs(arena, port);
return;
}
if (std.mem.eql(u8, cmd, "open")) {
const port = parsePortFlag(rest) orelse DEFAULT_CDP_PORT;
const url = if (rest.len > 0 and rest[0][0] != '-') rest[0] else null;
try cmdOpen(arena, port, url);
return;
}
if (std.mem.eql(u8, cmd, "use")) {
if (rest.len < 1) fatal("use: requires <ws_url>\n", .{});
try cmdUse(arena, rest[0]);
return;
}
if (std.mem.eql(u8, cmd, "status")) {
try cmdStatus(arena);
return;
}
// All other commands need a session with a valid cdp_url
var session = loadSession(arena) catch |err| {
jsonError("no session found ({s}). Run `kuri-agent tabs` then `kuri-agent use <ws_url>`", .{@errorName(err)});
std.process.exit(1);
};
defer session.deinit();
// Session-only commands (no CDP connection needed)
if (std.mem.eql(u8, cmd, "set-header")) {
if (rest.len < 2) fatal("set-header: requires <name> <value>\n", .{});
try session.extra_headers.put(try arena.dupe(u8, rest[0]), try arena.dupe(u8, rest[1]));
try saveSession(arena, &session);
const out = try std.fmt.allocPrint(arena, "{{\"ok\":true,\"header\":\"{s}\",\"value\":\"{s}\"}}\n", .{ rest[0], rest[1] });
compat.writeToStdout(out);
return;
}
if (std.mem.eql(u8, cmd, "clear-headers")) {
session.extra_headers.clearRetainingCapacity();
try saveSession(arena, &session);
compat.writeToStdout("{\"ok\":true,\"cleared\":true}\n");
return;
}
if (std.mem.eql(u8, cmd, "show-headers")) {
var hbuf: std.ArrayList(u8) = .empty;
hbuf.appendSlice(arena, "{\"extra_headers\":{") catch {};
var hit = session.extra_headers.iterator();
var hfirst = true;
while (hit.next()) |entry| {
if (!hfirst) hbuf.appendSlice(arena, ",") catch {};
hfirst = false;
hbuf.print(arena, "\"{s}\":\"{s}\"", .{ entry.key_ptr.*, entry.value_ptr.* }) catch {};
}
hbuf.appendSlice(arena, "}}\n") catch {};
compat.writeToStdout(hbuf.items);
return;
}
if (session.cdp_url.len == 0) {
jsonError("no tab attached. Run `kuri-agent use <ws_url>`", .{});
std.process.exit(1);
}
var client = CdpClient.init(arena, session.cdp_url);
defer client.deinit();
// Apply stored extra headers before any navigation
if (session.extra_headers.count() > 0) {
applyExtraHeaders(arena, &client, &session) catch {};
}
// Apply stealth patches if enabled in session
if (session.stealth) {
applyStealth(arena, &client) catch {};
}
if (std.mem.eql(u8, cmd, "go")) {
if (rest.len < 1) fatal("go: requires <url>\n", .{});
try cmdNavigate(arena, &client, rest[0]);
compat.threadSleep(1_000_000_000); // let page load
autoSnap(arena, &client, &session);
} else if (std.mem.eql(u8, cmd, "snap")) {
try cmdSnap(arena, &client, &session, rest);
} else if (std.mem.eql(u8, cmd, "click")) {
if (rest.len < 1) fatal("click: requires <ref>\n", .{});
try cmdAction(arena, &client, &session, "click", rest[0], null);
autoSnap(arena, &client, &session);
} else if (std.mem.eql(u8, cmd, "type") or std.mem.eql(u8, cmd, "fill")) {
if (rest.len < 2) fatal("{s}: requires <ref> <text>\n", .{cmd});
try cmdAction(arena, &client, &session, cmd, rest[0], rest[1]);
autoSnap(arena, &client, &session);
} else if (std.mem.eql(u8, cmd, "select")) {
if (rest.len < 2) fatal("select: requires <ref> <value>\n", .{});
try cmdAction(arena, &client, &session, "select", rest[0], rest[1]);
autoSnap(arena, &client, &session);
} else if (std.mem.eql(u8, cmd, "hover")) {
if (rest.len < 1) fatal("hover: requires <ref>\n", .{});
try cmdAction(arena, &client, &session, "hover", rest[0], null);
} else if (std.mem.eql(u8, cmd, "focus")) {
if (rest.len < 1) fatal("focus: requires <ref>\n", .{});
try cmdAction(arena, &client, &session, "focus", rest[0], null);
} else if (std.mem.eql(u8, cmd, "scroll")) {
try cmdScroll(arena, &client);
autoSnap(arena, &client, &session);
} else if (std.mem.eql(u8, cmd, "viewport")) {
try cmdViewport(arena, &client, rest);
} else if (std.mem.eql(u8, cmd, "viewport")) {
try cmdViewport(arena, &client, rest);
} else if (std.mem.eql(u8, cmd, "eval")) {
if (rest.len < 1) fatal("eval: requires <js>\n", .{});
try cmdEval(arena, &client, rest[0]);
} else if (std.mem.eql(u8, cmd, "text")) {
const selector = if (rest.len > 0) rest[0] else null;
try cmdText(arena, &client, selector);
} else if (std.mem.eql(u8, cmd, "shot")) {
const out = parseOutFlag(rest);
try cmdScreenshot(arena, &client, out);
} else if (std.mem.eql(u8, cmd, "back")) {
try cmdSimpleNav(arena, &client, "Page.goBack");
} else if (std.mem.eql(u8, cmd, "forward")) {
try cmdSimpleNav(arena, &client, "Page.goForward");
} else if (std.mem.eql(u8, cmd, "reload")) {
try cmdSimpleNav(arena, &client, protocol.Methods.page_reload);
} else if (std.mem.eql(u8, cmd, "cookies")) {
try cmdCookies(arena, &client);
} else if (std.mem.eql(u8, cmd, "headers")) {
try cmdHeaders(arena, &client);
} else if (std.mem.eql(u8, cmd, "audit")) {
try cmdAudit(arena, &client);
} else if (std.mem.eql(u8, cmd, "storage")) {
const which = if (rest.len > 0) rest[0] else "all";
try cmdStorage(arena, &client, which);
} else if (std.mem.eql(u8, cmd, "jwt")) {
try cmdJwt(arena, &client);
} else if (std.mem.eql(u8, cmd, "fetch")) {
if (rest.len < 2) fatal("fetch: requires <method> <url> [--data <json>]\n", .{});
const fdata = parseFetchData(rest[2..]);
try cmdFetch(arena, &client, rest[0], rest[1], fdata);
} else if (std.mem.eql(u8, cmd, "probe")) {
if (rest.len < 3) fatal("probe: requires <url-template> <start> <end>\n", .{});
const start_id = std.fmt.parseInt(u32, rest[1], 10) catch fatal("probe: start must be integer\n", .{});
const end_id = std.fmt.parseInt(u32, rest[2], 10) catch fatal("probe: end must be integer\n", .{});
try cmdProbe(arena, &client, rest[0], start_id, end_id);
} else if (std.mem.eql(u8, cmd, "grab")) {
// Override window.open, click a ref, follow the redirect in-tab
if (rest.len < 1) fatal("grab: requires <ref>\n", .{});
try cmdGrab(arena, &client, &session, rest[0]);
} else if (std.mem.eql(u8, cmd, "wait-for-tab")) {
// Poll for a new tab to appear, auto-switch to it
const port: u16 = parsePort(rest);
try cmdWaitForTab(arena, port, &session);
} else if (std.mem.eql(u8, cmd, "stealth")) {
try cmdStealth(arena, &client);
} else {
fatal("unknown command '{s}'. Run kuri-agent with no args for help.", .{cmd});
}
}
// ── Commands ─────────────────────────────────────────────────────────────────
fn cmdTabs(arena: std.mem.Allocator, port: u16) !void {
const json = fetchChromeTabs(arena, "127.0.0.1", port) catch |err| {
jsonError("cannot connect to Chrome on port {d}: {s}", .{ port, @errorName(err) });
std.process.exit(1);
};
// Pretty-print each page tab
var buf: std.ArrayList(u8) = .empty;
buf.appendSlice(arena, "[\n") catch {};
var first = true;
var pos: usize = 0;
while (pos < json.len) {
const ws_start = std.mem.indexOfPos(u8, json, pos, "\"webSocketDebuggerUrl\"") orelse break;
const ws_val = extractString(json, ws_start, "\"webSocketDebuggerUrl\"") orelse {
pos = ws_start + 1;
continue;
};
const type_val = extractString(json, pos, "\"type\"") orelse "page";
if (!std.mem.eql(u8, type_val, "page")) {
pos = ws_start + ws_val.len + 1;
continue;
}
const id_val = extractString(json, pos, "\"id\"") orelse "";
const url_val = extractString(json, pos, "\"url\"") orelse "";
const title_val = extractString(json, pos, "\"title\"") orelse "";
if (!first) buf.appendSlice(arena, ",\n") catch {};
first = false;
buf.print(arena, " {{\"id\":\"{s}\",\"url\":\"{s}\",\"title\":\"{s}\",\"ws\":\"{s}\"}}", .{
id_val, url_val, title_val, ws_val,
}) catch {};
pos = ws_start + ws_val.len + 1;
}
buf.appendSlice(arena, "\n]\n") catch {};
compat.writeToStdout(buf.items);
}
fn cmdUse(arena: std.mem.Allocator, ws_url: []const u8) !void {
var session = Session.init(arena);
session.cdp_url = ws_url;
try saveSession(arena, &session);
const out = try std.fmt.allocPrint(arena, "{{\"ok\":true,\"cdp_url\":\"{s}\"}}\n", .{ws_url});
compat.writeToStdout(out);
}
/// Launch a visible (non-headless) Chrome with CDP, wait for it, auto-attach.
/// This is the "human mode" — real browser, real user, agent rides alongside.
fn cmdOpen(arena: std.mem.Allocator, port: u16, url: ?[]const u8) !void {
// 1. Check if Chrome CDP is already available on this port
if (tryAttach(arena, port, url)) return;
// 2. Not running — launch visible Chrome with CDP
const chrome_bin: []const u8 = switch (@import("builtin").os.tag) {
.macos => "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
else => "google-chrome",
};
var argv: std.ArrayList([]const u8) = .empty;
try argv.append(arena, chrome_bin);
const port_flag = try std.fmt.allocPrint(arena, "--remote-debugging-port={d}", .{port});
try argv.append(arena, port_flag);
// Chrome requires a data dir for CDP; use default profile so cookies/logins persist
const home = compat.getenv("HOME") orelse "/tmp";
const data_dir = try std.fmt.allocPrint(arena, "--user-data-dir={s}/.kuri/chrome-profile", .{home});
try argv.append(arena, data_dir);
if (url) |u| try argv.append(arena, u);
// Fork and exec Chrome
const pid = std.c.fork();
if (pid < 0) {
fatal("Failed to fork for Chrome launch\n", .{});
}
if (pid == 0) {
// Child process: exec Chrome
var c_argv: [64]?[*:0]const u8 = undefined;
for (argv.items, 0..) |arg, i| {
if (i >= c_argv.len - 1) break;
c_argv[i] = @ptrCast(arg.ptr);
}
c_argv[argv.items.len] = null;
const c_execvp = @extern(*const fn ([*:0]const u8, [*:null]const ?[*:0]const u8) callconv(.c) c_int, .{ .name = "execvp" });
_ = c_execvp(@ptrCast(argv.items[0].ptr), @ptrCast(&c_argv));
std.c._exit(127);
}
// 3. Poll for CDP — try the requested port first, then fall back to 9222
std.debug.print("Launching Chrome...\n", .{});
const ports_to_try = if (port != DEFAULT_CDP_PORT)
&[_]u16{ port, DEFAULT_CDP_PORT }
else
&[_]u16{port};
var attempts: u32 = 0;
while (attempts < 30) : (attempts += 1) {
compat.threadSleep(500_000_000);
for (ports_to_try) |p| {
if (tryAttach(arena, p, url)) return;
}
}
fatal("Chrome didn't start within 15s. Is it installed?\n", .{});
}
/// Try to connect to Chrome on the given port, optionally navigate, and save session.
fn tryAttach(arena: std.mem.Allocator, port: u16, url: ?[]const u8) bool {
const json = fetchChromeTabs(arena, "127.0.0.1", port) catch return false;
// Find the first page target
var pos: usize = 0;
while (pos < json.len) {
const ws_start = std.mem.indexOfPos(u8, json, pos, "\"webSocketDebuggerUrl\"") orelse break;
const ws = extractString(json, ws_start, "\"webSocketDebuggerUrl\"") orelse {
pos = ws_start + 1;
continue;
};
const type_val = extractString(json, pos, "\"type\"") orelse "page";
if (!std.mem.eql(u8, type_val, "page")) {
pos = ws_start + ws.len + 1;
continue;
}
// Found a page tab — navigate if URL given, then attach
if (url) |u| {
var session = Session.init(arena);
session.cdp_url = arena.dupe(u8, ws) catch return false;
saveSession(arena, &session) catch {};
var client = CdpClient.init(arena, ws);
defer client.deinit();
cmdNavigate(arena, &client, u) catch {};
}
cmdUse(arena, ws) catch {};
return true;
}
return false;
}
fn cmdStatus(arena: std.mem.Allocator) !void {
var session = loadSession(arena) catch {
compat.writeToStdout("{\"ok\":false,\"error\":\"no session\"}\n");
return;
};
defer session.deinit();
const out = try std.fmt.allocPrint(arena, "{{\"ok\":true,\"cdp_url\":\"{s}\",\"refs\":{d}}}\n", .{
session.cdp_url, session.refs.count(),
});
compat.writeToStdout(out);
}
fn cmdNavigate(arena: std.mem.Allocator, client: *CdpClient, url: []const u8) !void {
const escaped_url = try escapeForJson(arena, url);
const params = try std.fmt.allocPrint(arena, "{{\"url\":\"{s}\"}}", .{escaped_url});
_ = client.send(arena, protocol.Methods.page_navigate, params) catch |err| {
jsonError("navigate failed: {s}", .{@errorName(err)});
std.process.exit(1);
};
const out = try std.fmt.allocPrint(arena, "{{\"ok\":true,\"url\":\"{s}\"}}\n", .{escaped_url});
compat.writeToStdout(out);
}
fn cmdSnap(arena: std.mem.Allocator, client: *CdpClient, session: *Session, flags: []const []const u8) !void {
const want_text = hasFlag(flags, "--text");
const want_interactive = hasFlag(flags, "--interactive");
const want_json = hasFlag(flags, "--json");
const want_semantic = hasFlag(flags, "--semantic");
const want_all = hasFlag(flags, "--all");
const depth = parseDepthFlag(flags);
const raw = client.send(arena, protocol.Methods.accessibility_get_full_tree, null) catch |err| {
jsonError("CDP accessibility failed: {s}", .{@errorName(err)});
std.process.exit(1);
};
const nodes = parseA11yNodes(arena, raw) catch {
jsonError("failed to parse a11y tree", .{});
std.process.exit(1);
};
const opts = a11y.SnapshotOpts{
.filter_interactive = want_interactive,
.filter_semantic = want_semantic,
.compact = !want_json and !want_text and !want_all,
.json_output = want_json,
.format_text = want_text,
.max_depth = depth,
};
const snapshot = a11y.buildSnapshot(nodes, opts, arena) catch {
jsonError("failed to build snapshot", .{});
std.process.exit(1);
};
// Save refs to session
session.refs.clearRetainingCapacity();
for (snapshot) |node| {
if (node.backend_node_id) |bid| {
const owned_ref = arena.dupe(u8, node.ref) catch continue;
session.refs.put(owned_ref, bid) catch {};
}
}
saveSession(arena, session) catch {};
// --text: legacy indented text
if (want_text) {
const text = a11y.formatText(snapshot, arena) catch "{}";
compat.writeToStdout(text);
compat.writeToStdout("\n");
return;
}
// --json: old JSON array (backward compat)
if (want_json) {
var buf: std.ArrayList(u8) = .empty;
buf.appendSlice(arena, "[") catch {};
for (snapshot, 0..) |node, i| {
if (i > 0) buf.appendSlice(arena, ",") catch {};
buf.print(arena, "{{\"ref\":\"{s}\",\"role\":\"{s}\",\"name\":\"{s}\"", .{ node.ref, node.role, node.name }) catch {};
if (node.value.len > 0) {
buf.print(arena, ",\"value\":\"{s}\"", .{node.value}) catch {};
}
buf.appendSlice(arena, "}") catch {};
}
buf.appendSlice(arena, "]\n") catch {};
compat.writeToStdout(buf.items);
return;
}
// Default: compact text-tree (role "name" @ref)
const compact = a11y.formatCompact(snapshot, arena) catch "error\n";
compat.writeToStdout(compact);
}
/// Auto-snap: get URL/title + interactive snapshot. Used after actions and navigation.
fn autoSnap(arena: std.mem.Allocator, client: *CdpClient, session: *Session) void {
// Get current URL + title
const url_resp = client.send(arena, protocol.Methods.runtime_evaluate,
"{\"expression\":\"JSON.stringify({url:location.href,title:document.title})\",\"returnByValue\":true}") catch null;
if (url_resp) |resp| {
const raw = extractCdpValue(resp);
const unescaped = util_json.jsonUnescape(arena, raw) catch raw;
compat.writeToStdout(unescaped);
compat.writeToStdout("\n");
}
// Interactive snap
const raw = client.send(arena, protocol.Methods.accessibility_get_full_tree, null) catch return;
const nodes = parseA11yNodes(arena, raw) catch return;
const opts = a11y.SnapshotOpts{
.filter_interactive = true,
.filter_semantic = false,
.compact = true,
.json_output = false,
.format_text = false,
.max_depth = null,
};
const snapshot = a11y.buildSnapshot(nodes, opts, arena) catch return;
// Save refs
session.refs.clearRetainingCapacity();
for (snapshot) |node| {
if (node.backend_node_id) |bid| {
const owned_ref = arena.dupe(u8, node.ref) catch continue;
session.refs.put(owned_ref, bid) catch {};
}
}
saveSession(arena, session) catch {};
const compact = a11y.formatCompact(snapshot, arena) catch return;
compat.writeToStdout(compact);
}
fn cmdAction(arena: std.mem.Allocator, client: *CdpClient, session: *Session, action: []const u8, ref: []const u8, value: ?[]const u8) !void {
// Normalize ref: strip leading '@' if present
const clean_ref = if (ref.len > 0 and ref[0] == '@') ref[1..] else ref;
// Scroll/press don't need a node ref
if (std.mem.eql(u8, action, "scroll")) {
try cmdScroll(arena, client);
return;
}
const bid = session.refs.get(clean_ref) orelse {
jsonError("ref '{s}' not found. Run `kuri-agent snap` first.", .{ref});
std.process.exit(1);
};
// Step 1: resolve backend node → objectId
const resolve_params = try std.fmt.allocPrint(arena, "{{\"backendNodeId\":{d}}}", .{bid});
const resolve_resp = client.send(arena, protocol.Methods.dom_resolve_node, resolve_params) catch |err| {
jsonError("DOM.resolveNode failed: {s}", .{@errorName(err)});
std.process.exit(1);
};
const object_id = extractString(resolve_resp, 0, "\"objectId\"") orelse {
jsonError("could not extract objectId from resolveNode response", .{});
std.process.exit(1);
};
const value_action_fn =
\\function(value, append) {
\\ const target = (() => {
\\ if (!this) return null;
\\ if (this instanceof HTMLLabelElement && this.control) return this.control;
\\ if (this instanceof HTMLInputElement || this instanceof HTMLTextAreaElement || this instanceof HTMLSelectElement) return this;
\\ if (this.isContentEditable) return this;
\\ if (typeof this.querySelector === "function") {
\\ const nested = this.querySelector("input,textarea,select,[contenteditable=\"true\"],[contenteditable=\"\"],[role=\"textbox\"]");
\\ if (nested) return nested;
\\ }
\\ return this;
\\ })();
\\ if (!target) return "missing-target";
\\ target.focus?.();
\\ if (target.isContentEditable) {
\\ const existing = typeof target.textContent === "string" ? target.textContent : "";
\\ target.textContent = append ? (existing + value) : value;
\\ } else if ("value" in target) {
\\ const existing = typeof target.value === "string" ? target.value : "";
\\ target.value = append ? (existing + value) : value;
\\ }
\\ target.dispatchEvent(new Event("input", {bubbles:true}));
\\ target.dispatchEvent(new Event("change", {bubbles:true}));
\\ return "filled";
\\}
;
const select_action_fn =
\\function(value) {
\\ const target = (() => {
\\ if (!this) return null;
\\ if (this instanceof HTMLLabelElement && this.control) return this.control;
\\ if (this instanceof HTMLSelectElement) return this;
\\ if (typeof this.querySelector === "function") {
\\ const nested = this.querySelector("select");
\\ if (nested) return nested;
\\ }
\\ return this;
\\ })();
\\ if (!target) return "missing-target";
\\ let next = value;
\\ if ("options" in target && target.options) {
\\ for (const opt of target.options) {
\\ const text = (opt.textContent || "").trim();
\\ const label = (opt.label || "").trim();
\\ if (opt.value === value || text === value || label === value) {
\\ next = opt.value;
\\ break;
\\ }
\\ }
\\ }
\\ if ("value" in target) target.value = next;
\\ target.dispatchEvent(new Event("input", {bubbles:true}));
\\ target.dispatchEvent(new Event("change", {bubbles:true}));
\\ return "selected";
\\}
;
// Step 2: build JS function for the action
const js_fn: []const u8 = blk: {
if (std.mem.eql(u8, action, "click")) break :blk "function() { this.scrollIntoViewIfNeeded(); this.click(); return 'clicked'; }";
if (std.mem.eql(u8, action, "hover")) break :blk "function() { this.dispatchEvent(new MouseEvent('mouseover', {bubbles:true})); return 'hovered'; }";
if (std.mem.eql(u8, action, "focus")) break :blk "function() { this.focus(); return 'focused'; }";
if (std.mem.eql(u8, action, "dblclick")) break :blk "function() { this.scrollIntoViewIfNeeded(); this.dispatchEvent(new MouseEvent('dblclick', {bubbles:true,cancelable:true})); return 'dblclicked'; }";
if (std.mem.eql(u8, action, "blur")) break :blk "function() { this.blur(); return 'blurred'; }";
if (std.mem.eql(u8, action, "check")) break :blk "function() { if (!this.checked) { this.click(); } return 'checked'; }";
if (std.mem.eql(u8, action, "uncheck")) break :blk "function() { if (this.checked) { this.click(); } return 'unchecked'; }";
if (std.mem.eql(u8, action, "type") or std.mem.eql(u8, action, "fill")) {
const v = value orelse {
jsonError("{s} requires a value", .{action});
std.process.exit(1);
};
_ = v;
break :blk value_action_fn;
}
if (std.mem.eql(u8, action, "select")) {
const v = value orelse {
jsonError("select requires a value", .{});
std.process.exit(1);
};
_ = v;
break :blk select_action_fn;
}
jsonError("unknown action '{s}'", .{action});
std.process.exit(1);
};
// Escape the js_fn for JSON string embedding
const escaped_fn = try escapeForJson(arena, js_fn);
// Step 3: call function on resolved object
const call_params = if (std.mem.eql(u8, action, "type") or std.mem.eql(u8, action, "fill")) blk: {
const v = value orelse {
jsonError("{s} requires a value", .{action});
std.process.exit(1);
};
const escaped_v = try escapeForJson(arena, v);
break :blk try std.fmt.allocPrint(
arena,
"{{\"objectId\":\"{s}\",\"functionDeclaration\":\"{s}\",\"arguments\":[{{\"value\":\"{s}\"}},{{\"value\":{s}}}],\"returnByValue\":true}}",
.{ object_id, escaped_fn, escaped_v, if (std.mem.eql(u8, action, "type")) "true" else "false" },
);
} else if (std.mem.eql(u8, action, "select")) blk: {
const v = value orelse {
jsonError("select requires a value", .{});
std.process.exit(1);
};
const escaped_v = try escapeForJson(arena, v);
break :blk try std.fmt.allocPrint(
arena,
"{{\"objectId\":\"{s}\",\"functionDeclaration\":\"{s}\",\"arguments\":[{{\"value\":\"{s}\"}}],\"returnByValue\":true}}",
.{ object_id, escaped_fn, escaped_v },
);
} else try std.fmt.allocPrint(
arena,
"{{\"objectId\":\"{s}\",\"functionDeclaration\":\"{s}\",\"returnByValue\":true}}",
.{ object_id, escaped_fn },
);
const response = client.send(arena, protocol.Methods.runtime_call_function_on, call_params) catch |err| {
jsonError("Runtime.callFunctionOn failed: {s}", .{@errorName(err)});
std.process.exit(1);
};
const val = extractCdpValue(response);
const out = try std.fmt.allocPrint(arena, "{{\"ok\":true,\"action\":\"{s}\"}}\n", .{val});
compat.writeToStdout(out);
}
fn cmdScroll(arena: std.mem.Allocator, client: *CdpClient) !void {
const params = "{\"expression\":\"window.scrollBy(0, 500) || 'scrolled'\",\"returnByValue\":true}";
const response = client.send(arena, protocol.Methods.runtime_evaluate, @constCast(params)) catch |err| {
jsonError("scroll failed: {s}", .{@errorName(err)});
std.process.exit(1);
};
_ = response;
compat.writeToStdout("{\"ok\":true}\n");
}
fn cmdViewport(arena: std.mem.Allocator, client: *CdpClient, args: []const []const u8) !void {
// Presets: mobile (390x844), tablet (768x1024), desktop (1280x800)
// Custom: viewport <width> <height> [--dpr N]
var width: u32 = 390;
var height: u32 = 844;
var dpr: u32 = 2;
var mobile: bool = true;
if (args.len > 0) {
const preset = args[0];
if (std.mem.eql(u8, preset, "mobile") or std.mem.eql(u8, preset, "m")) {
width = 390; height = 844; dpr = 2; mobile = true;
} else if (std.mem.eql(u8, preset, "tablet") or std.mem.eql(u8, preset, "t")) {
width = 768; height = 1024; dpr = 2; mobile = true;
} else if (std.mem.eql(u8, preset, "desktop") or std.mem.eql(u8, preset, "d")) {
width = 1280; height = 800; dpr = 1; mobile = false;
} else if (std.mem.eql(u8, preset, "reset")) {
width = 1280; height = 800; dpr = 1; mobile = false;
} else {
// numeric width — expect viewport <w> <h> [--dpr N]
width = std.fmt.parseInt(u32, preset, 10) catch {
jsonError("unknown viewport preset '{s}'. Use mobile/tablet/desktop or <width> <height>", .{preset});
std.process.exit(1);
};
height = if (args.len > 1) std.fmt.parseInt(u32, args[1], 10) catch 900 else 900;
dpr = 1;
mobile = width < 768;
// --dpr flag
var i: usize = 2;
while (i + 1 < args.len) : (i += 1) {
if (std.mem.eql(u8, args[i], "--dpr")) {
dpr = std.fmt.parseInt(u32, args[i + 1], 10) catch dpr;
break;
}
}
}
}
const params = try std.fmt.allocPrint(arena,
"{{\"width\":{d},\"height\":{d},\"deviceScaleFactor\":{d},\"mobile\":{s}}}",
.{ width, height, dpr, if (mobile) "true" else "false" });
const response = client.send(arena, protocol.Methods.emulation_set_device_metrics, params) catch |err| {
jsonError("viewport failed: {s}", .{@errorName(err)});
std.process.exit(1);
};
_ = response;
const out = try std.fmt.allocPrint(arena,
"{{\"ok\":true,\"width\":{d},\"height\":{d},\"dpr\":{d},\"mobile\":{s}}}\n",
.{ width, height, dpr, if (mobile) "true" else "false" });
compat.writeToStdout(out);
}
fn cmdEval(arena: std.mem.Allocator, client: *CdpClient, expr: []const u8) !void {
const escaped = try escapeForJson(arena, expr);
const params = try std.fmt.allocPrint(arena, "{{\"expression\":\"{s}\",\"returnByValue\":true}}", .{escaped});
const response = client.send(arena, protocol.Methods.runtime_evaluate, params) catch |err| {
jsonError("eval failed: {s}", .{@errorName(err)});
std.process.exit(1);
};
const raw = extractCdpValue(response);
const val = util_json.jsonUnescape(arena, raw) catch raw;
compat.writeToStdout(val);
compat.writeToStdout("\n");
}
fn cmdText(arena: std.mem.Allocator, client: *CdpClient, selector: ?[]const u8) !void {
const expr = if (selector) |sel| blk: {
const escaped_sel = try escapeForJson(arena, sel);
break :blk try std.fmt.allocPrint(arena,
"(() => {{ const el = document.querySelector(\"{s}\"); return el ? (el.innerText ?? '') : ''; }})()",
.{escaped_sel},
);
} else
@as([]const u8, "document.body ? document.body.innerText : ''");
const escaped_expr = try escapeForJson(arena, expr);
const params = try std.fmt.allocPrint(arena, "{{\"expression\":\"{s}\",\"returnByValue\":true}}", .{escaped_expr});
const response = client.send(arena, protocol.Methods.runtime_evaluate, params) catch |err| {
jsonError("text failed: {s}", .{@errorName(err)});
std.process.exit(1);
};
const raw = extractCdpValue(response);
const val = util_json.jsonUnescape(arena, raw) catch raw;
compat.writeToStdout(val);
compat.writeToStdout("\n");
}
fn cmdScreenshot(arena: std.mem.Allocator, client: *CdpClient, out_path: ?[]const u8) !void {
const params = "{\"format\":\"png\",\"quality\":80}";
const response = client.send(arena, protocol.Methods.page_capture_screenshot, @constCast(params)) catch |err| {
jsonError("screenshot failed: {s}", .{@errorName(err)});
std.process.exit(1);
};
// Extract base64 data from response
const b64 = extractString(response, 0, "\"data\"") orelse {
jsonError("no data field in screenshot response", .{});
std.process.exit(1);
};
// Decode base64
const decoded_len = std.base64.standard.Decoder.calcSizeForSlice(b64) catch {
jsonError("invalid base64 in screenshot", .{});
std.process.exit(1);
};
const decoded = try arena.alloc(u8, decoded_len);
std.base64.standard.Decoder.decode(decoded, b64) catch {
jsonError("base64 decode failed", .{});
std.process.exit(1);
};
// Determine output path — default to ~/.kuri/screenshots/<timestamp>.png
const path: []const u8 = out_path orelse blk: {
const home = compat.getenv("HOME") orelse ".";
const shots_dir = try std.fmt.allocPrint(arena, "{s}/.kuri/screenshots", .{home});
compat.cwdMakePath(shots_dir) catch {};
const ts = compat.timestampSeconds();
break :blk try std.fmt.allocPrint(arena, "{s}/{d}.png", .{ shots_dir, ts });
};
const file = compat.cwdCreateFile(path) catch |err| {
jsonError("cannot create file '{s}': {s}", .{ path, @errorName(err) });
std.process.exit(1);
};
defer compat.fdClose(file);
compat.fdWriteAll(file, decoded) catch {};
const out = try std.fmt.allocPrint(arena, "{{\"ok\":true,\"path\":\"{s}\",\"bytes\":{d}}}\n", .{ path, decoded.len });
compat.writeToStdout(out);
}
fn cmdSimpleNav(arena: std.mem.Allocator, client: *CdpClient, method: []const u8) !void {
const response = client.send(arena, method, null) catch |err| {
jsonError("{s} failed: {s}", .{ method, @errorName(err) });
std.process.exit(1);
};
_ = response;
compat.writeToStdout("{\"ok\":true}\n");
}
// ── Tab following ─────────────────────────────────────────────────────────────
/// Intercept popups + form target="_blank", click a ref, follow the redirect
/// in the same tab. Works with Google Flights booking buttons that use
/// dynamically created forms with target="_blank".
fn cmdGrab(arena: std.mem.Allocator, client: *CdpClient, session: *Session, ref: []const u8) !void {
// 1. Hook window.open AND form target to force same-tab navigation
const inject_js =
\\(function(){
\\ window.open = function(url) {
\\ if (url && url !== 'about:blank') location.href = url;
\\ return null;
\\ };
\\ var oc = document.createElement.bind(document);
\\ document.createElement = function(t) {
\\ var el = oc(t);
\\ if (t.toLowerCase() === 'form') {
\\ Object.defineProperty(el, 'target', {
\\ set: function() {},
\\ get: function() { return '_self'; }
\\ });
\\ }
\\ return el;
\\ };
\\ return 'hooked';
\\})()
;
const inject_escaped = try escapeForJson(arena, inject_js);
const inject_params = try std.fmt.allocPrint(arena,
"{{\"expression\":\"{s}\",\"returnByValue\":true}}", .{inject_escaped});
_ = client.send(arena, protocol.Methods.runtime_evaluate, inject_params) catch {};
// 2. Click the element
try cmdAction(arena, client, session, "click", ref, null);
// 3. Wait for navigation (up to 8s)
var attempts: u32 = 0;
const orig_url = blk: {
const r = client.send(arena, protocol.Methods.runtime_evaluate,
"{\"expression\":\"location.href\",\"returnByValue\":true}") catch break :blk "";
const s = std.mem.indexOf(u8, r, "\"value\":\"") orelse break :blk "";
const b = s + 9;
const e = std.mem.indexOfPos(u8, r, b, "\"") orelse break :blk "";
break :blk r[b..e];
};
while (attempts < 16) : (attempts += 1) {
compat.threadSleep(500_000_000);
const resp = client.send(arena, protocol.Methods.runtime_evaluate,
"{\"expression\":\"location.href\",\"returnByValue\":true}") catch {
// Connection lost = page navigated away
const out = try std.fmt.allocPrint(arena,
"{{\"ok\":true,\"action\":\"navigated\",\"note\":\"page navigated, run snap to see new page\"}}\n", .{});
compat.writeToStdout(out);
return;
};
if (std.mem.indexOf(u8, resp, "\"value\":\"")) |s| {
const b = s + 9;
const e = std.mem.indexOfPos(u8, resp, b, "\"") orelse continue;
const new_url = resp[b..e];
if (!std.mem.eql(u8, new_url, orig_url)) {
const out = try std.fmt.allocPrint(arena,
"{{\"ok\":true,\"action\":\"navigated\",\"url\":\"{s}\"}}\n", .{new_url});
compat.writeToStdout(out);
return;
}
}
}
compat.writeToStdout("{\"ok\":true,\"action\":\"clicked\",\"note\":\"no redirect detected — check tabs\"}\n");
}
/// Poll Chrome /json for a new tab, auto-switch to it.
/// Useful after a click opens a popup/new tab that wasn't caught by `grab`.
fn cmdWaitForTab(arena: std.mem.Allocator, port: u16, session: *Session) !void {
// Get current tab IDs
const known_ws = session.cdp_url;
// Poll up to 10 seconds for a new tab
var attempts: u32 = 0;
while (attempts < 20) : (attempts += 1) {
const json = fetchChromeTabs(arena, "127.0.0.1", port) catch {
compat.threadSleep(500_000_000);
continue;
};
// Look for a websocket URL we don't already know
var pos: usize = 0;
while (pos < json.len) {
const ws_start = std.mem.indexOfPos(u8, json, pos, "\"webSocketDebuggerUrl\"") orelse break;
const ws_val = extractString(json, ws_start, "\"webSocketDebuggerUrl\"") orelse {
pos = ws_start + 1;
continue;
};
const type_val = extractString(json, pos, "\"type\"") orelse "page";
if (!std.mem.eql(u8, type_val, "page")) {
pos = ws_start + ws_val.len + 1;
continue;
}
if (!std.mem.eql(u8, ws_val, known_ws)) {
// Found a new tab — switch to it
const url_val = extractString(json, pos, "\"url\"") orelse "";
const title_val = extractString(json, pos, "\"title\"") orelse "";
session.cdp_url = ws_val;
try saveSession(arena, session);
const out = try std.fmt.allocPrint(arena,
"{{\"ok\":true,\"switched\":true,\"url\":\"{s}\",\"title\":\"{s}\",\"ws\":\"{s}\"}}\n",
.{ url_val, title_val, ws_val });
compat.writeToStdout(out);
return;
}
pos = ws_start + ws_val.len + 1;
}
compat.threadSleep(500_000_000);
}
compat.writeToStdout("{\"ok\":false,\"error\":\"no new tab detected after 10s\"}\n");
}
fn parsePort(args: []const []const u8) u16 {
var i: usize = 0;
while (i + 1 < args.len) : (i += 1) {
if (std.mem.eql(u8, args[i], "--port")) {
return std.fmt.parseInt(u16, args[i + 1], 10) catch 9222;
}
}
return 9222;
}
// ── Stealth ───────────────────────────────────────────────────────────────────
/// Apply stealth patches (called on every CDP connection when session.stealth=true).
fn applyStealth(arena: std.mem.Allocator, client: *CdpClient) !void {
const stealth = @import("cdp/stealth.zig");
const ua = stealth.randomUserAgent();
const ua_escaped = try escapeForJson(arena, ua);
// Network-level UA override
_ = client.send(arena, protocol.Methods.network_enable, null) catch {};
const net_params = try std.fmt.allocPrint(arena,
"{{\"userAgent\":\"{s}\"}}", .{ua_escaped});
_ = client.send(arena, "Network.setUserAgentOverride", net_params) catch {};
// Combined stealth script: override navigator.userAgent + stealth.js
const ua_js = try std.fmt.allocPrint(arena,
"Object.defineProperty(navigator,'userAgent',{{get:()=>'{s}',configurable:true}});", .{ua});
const combined = try std.fmt.allocPrint(arena,
"{s}\n{s}", .{ ua_js, stealth.stealth_script });
const escaped = try escapeForJson(arena, combined);
// Inject into current page
const eval_params = try std.fmt.allocPrint(arena,
"{{\"expression\":\"{s}\",\"returnByValue\":true}}", .{escaped});
_ = client.send(arena, protocol.Methods.runtime_evaluate, eval_params) catch {};
// Persist across navigations within this session
const persist_params = try std.fmt.allocPrint(arena,
"{{\"source\":\"{s}\"}}", .{escaped});
_ = client.send(arena, "Page.addScriptToEvaluateOnNewDocument", persist_params) catch {};
}
/// Enable stealth mode: apply patches + save to session so every future command re-applies.
fn cmdStealth(arena: std.mem.Allocator, client: *CdpClient) !void {
try applyStealth(arena, client);
// Save stealth=true to session
var session = loadSession(arena) catch Session.init(arena);
session.stealth = true;
try saveSession(arena, &session);
const stealth = @import("cdp/stealth.zig");
const ua = stealth.randomUserAgent();
const ua_escaped = try escapeForJson(arena, ua);
const out = try std.fmt.allocPrint(arena,
"{{\"ok\":true,\"ua\":\"{s}\",\"stealth\":true,\"persisted\":true}}\n", .{ua_escaped});
compat.writeToStdout(out);
}
// ── Security ──────────────────────────────────────────────────────────────────
/// List all cookies with security flag annotations (Secure, HttpOnly, SameSite).
fn cmdCookies(arena: std.mem.Allocator, client: *CdpClient) !void {
const response = client.send(arena, protocol.Methods.network_get_cookies, null) catch |err| {
jsonError("Network.getCookies failed: {s}", .{@errorName(err)});
std.process.exit(1);
};
const cookies_pos = std.mem.indexOf(u8, response, "\"cookies\"") orelse {
compat.writeToStdout(response);
compat.writeToStdout("\n");
return;
};
const arr_start = std.mem.indexOfScalarPos(u8, response, cookies_pos, '[') orelse {
compat.writeToStdout("{\"cookies\":[]}\n");
return;
};
var pos = arr_start + 1;
var count: usize = 0;
var buf: std.ArrayList(u8) = .empty;
while (pos < response.len) {
const obj_start = std.mem.indexOfScalarPos(u8, response, pos, '{') orelse break;
var depth: usize = 1;
var i = obj_start + 1;
while (i < response.len and depth > 0) : (i += 1) {
if (response[i] == '{') depth += 1;