Repository navigation
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·1392 lines (1290 loc) · 49.8 KB
/
Copy pathcli.js
File metadata and controls
executable file
·1392 lines (1290 loc) · 49.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
#!/usr/bin/env node
import { spawn, execSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { dirname, join, resolve as resolvePath } from "node:path";
import fs from "node:fs";
import { homedir } from "node:os";
import {
getDaemonState,
markDaemonRunning,
markDaemonStopped,
isDaemonExplicitlyStopped,
} from "./bridge/state.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
function envStr(name, fallback) {
const raw = process.env[name];
return raw !== undefined && raw !== "" ? raw : fallback;
}
const BRIDGE_URL = envStr("BROWSERCTL_BRIDGE_URL", envStr("BRIDGE_URL", "http://127.0.0.1:8765"));
// The port a spawned or stopped bridge uses: the one in BRIDGE_URL, so a custom URL is where
// the daemon is started and looked for.
const BRIDGE_PORT = (() => {
try {
const u = new URL(BRIDGE_URL);
return Number(u.port) || (u.protocol === "https:" ? 443 : 80);
} catch {
return 8765;
}
})();
// Every invocation belongs to one CLI session, `cli` or BROWSERCTL_SESSION when set. A CLI
// process runs one command, so the bridge keeps the session's target (sticky) and a command
// naming no tab goes there; a tab another session holds is never taken.
const CLIENT = {
session: envStr("BROWSERCTL_SESSION", "cli").slice(0, 32),
source: "cli",
sticky: true,
};
// The bridge's selector-routing failures (which browser, not what to do on it) — a distinct
// exit code from every other command error.
const ROUTING_ERROR_CODES = new Set([
"NO_BROWSER",
"NEEDS_BROWSER",
"AMBIGUOUS_BROWSER",
"UNKNOWN_BROWSER",
"NEEDS_TAB",
"NEEDS_TARGET",
"AMBIGUOUS_TAB",
"TAB_NOT_FOUND",
"TAB_OWNED",
"TAB_BUSY",
"TAKE_CONFIRM",
"TARGET_TAKEN",
]);
function printHelp() {
console.log(`
browserctl CLI — Fast, Ergonomic Browser Automation for AI Agents & Developers
Usage:
browserctl status Check bridge health, daemon state & extension
browserctl start Start bridge daemon (RARELY NEEDED — any command
starts it automatically on first use)
browserctl stop Stop the daemon. DO NOT run this to tidy up after a
task: it is shared with the user and other agents,
and it records a stopped state that blocks restart.
browserctl restart Restart bridge daemon
browserctl extension-path Print the folder to load in chrome://extensions
browserctl extension-path --copy [dir]
Copy it to a fixed folder (default ~/.browserctl/extension)
and print that; rerun after an update to refresh it
You do not need to start anything before your first command, and you do not need to leave a
terminal open. Every MCP tool has a CLI equivalent: browser_snapshot -> snapshot,
browser_get_property -> get text, browser_click -> click.
Navigation & Tabs:
browserctl open <url> Navigate target tab to url (alias: navigate)
browserctl back | forward | reload History navigation
browserctl tab [list] List open tabs, and which another session holds (alias: tabs)
browserctl tab new [url] Open new tab (alias: new_tab)
browserctl tab switch <id> [--force] Switch target to tab ID (alias: switch_tab). A tab another
session holds: refused while it acts (TAB_BUSY), else
TAKE_CONFIRM; --force takes it
browserctl tab close [id] Close tab (alias: close_tab)
browserctl tab release Give this session's tab up
browserctl tab yield Keep working, but let any session take the tab
Inspection & Query (get):
browserctl snapshot [--all] Capture interactive DOM elements (--all = everything in the DOM)
[--only fields,buttons,links] List only these kinds of control; page text is left out
browserctl read_page [mode] [--depth N] [--max-chars N] [--ref @e1]
Read accessibility tree & text (mode: interactive | all)
browserctl get text <target> Get visible text of element (@e1, selector)
browserctl get value <target> Get value of input/textarea/select
browserctl get attr <target> <name> Get attribute value (e.g. href, src, placeholder)
browserctl get title Get current page title
browserctl get url Get current page URL
browserctl get html [<target>] Get HTML of element or whole document
browserctl get box <target> Get bounding box coordinates (x, y, width, height)
browserctl get count <selector> Count matching elements
Interaction:
browserctl click <target> Click element (@e1, 0, --text "...", custom elements, ARIA roles)
browserctl dblclick <target> Double-click element
browserctl fill <target> <text> Clear input and fill text (recovers with candidate input refs if targeted element is not editable)
browserctl upload <file> [target] Attach a local file to a file input (walks from a styled label/button to the hidden input)
browserctl paste <target> <text> Paste text/markdown into field or rich-text editor
browserctl type <target> <text> Type into input field (appends/types text)
browserctl clear <target> Clear input/textarea field
browserctl check <target> Check checkbox or radio button
browserctl uncheck <target> Uncheck checkbox
browserctl select <target> <val...> Select option in dropdown by value or --label "..."
browserctl hover <target> Hover over element
browserctl scroll [up|down] [amount] [target] Scroll page or container (@e1, selector)
browserctl scrollintoview <target> Scroll element into view
browserctl press <key> Press key (Enter, Tab, Escape, etc.)
browserctl dismiss [target] Dismiss active modal, drawer, or flyout (Escape or close button)
Wait & Synchronization:
browserctl wait [<ms>] Sleep for specified milliseconds (e.g. wait 2000)
browserctl wait [--settle|--auto] Wait for DOM mutations and animations to finish (default)
browserctl wait <target> Wait for element to appear in DOM
browserctl wait --text "..." Wait for visible text to appear
browserctl wait --selector "..." Wait for CSS selector to appear
browserctl wait --network-idle [--tolerance N] Wait for network activity to settle (tolerates N background requests)
Capture & Export:
browserctl screenshot [file.png] [-f] Take viewport or fullpage screenshot (saves to file or returns base64)
browserctl pdf [file.pdf] Print page to PDF (saves to file or returns base64)
browserctl eval <expression> [-r] Evaluate JavaScript (auto-bypasses CSP/Trusted Types via CDP)
System & Raw Protocols:
browserctl exec_system_cmd <cmd> Run host system command
browserctl <action> [key=value ...] Run any of the 68+ protocol actions
Formatting & Global Flags:
-r, --raw Output raw unformatted value (for piping)
--json Force compact valid JSON output
--pretty Force 2-space indented pretty JSON output
--elements snapshot: every element as structured JSON instead of
the census
-f, --full, --fullpage Capture fullpage screenshot
-t, --tab <id> Direct this one command to a tab ID, in whichever browser
has it (a tab another session holds can only be read,
else TAB_OWNED)
-b, --browser <selector> Target one connected browser: alias (edge-1), label,
instanceId, or type (only if exactly one of that type
is connected). Needed when more than one browser is
connected and the session has no target yet (without it:
exit 2, NEEDS_TARGET, listing the tabs). Naming another
browser moves the session's target to the tab you see there.
--settle <ms> Auto-settle delay after action (default: 150ms)
--no-daemon Do not auto-start bridge daemon if not running
--auto-daemon Force auto-start even if previously stopped
Environment:
BROWSERCTL_BRIDGE_URL Default: http://127.0.0.1:8765
BROWSERCTL_AUTO_START 'auto' (default) or 'manual'/'false'
BROWSERCTL_MCP_PROFILE 'core' (default) or 'all'
BROWSERCTL_SESSION CLI session name (default 'cli'). The bridge keeps each
session's target tab: the tab you saw when it started,
or the last one switched to or opened
`);
}
let isStartingDaemon = null;
async function isBridgeRunning() {
try {
const res = await fetch(`${BRIDGE_URL}/status`, { signal: AbortSignal.timeout(600) });
return res.ok;
} catch {
return false;
}
}
async function startBridgeDaemon() {
if (isStartingDaemon) return isStartingDaemon;
isStartingDaemon = (async () => {
const serverPath = join(__dirname, "bridge", "server.js");
try {
if (!fs.existsSync(serverPath)) return false;
const child = spawn(process.execPath, [serverPath], {
detached: true,
stdio: "ignore",
windowsHide: true,
env: { ...process.env, PORT: String(BRIDGE_PORT) },
});
child.unref();
const start = Date.now();
while (Date.now() - start < 2500) {
await new Promise((r) => setTimeout(r, 100));
if (await isBridgeRunning()) {
try {
markDaemonRunning({ pid: child.pid, port: BRIDGE_PORT, url: BRIDGE_URL });
} catch {}
return true;
}
}
return false;
} catch {
return false;
} finally {
isStartingDaemon = null;
}
})();
return isStartingDaemon;
}
// PIDs listening on the port, from `netstat -ano` output. A listener's local address ends in
// the port and its remote address is the wildcard; the clients connected to it (Chrome's
// WebSocket among them) have a real remote address and are left alone.
function listenerPidsFromNetstat(out, port) {
const pids = new Set();
for (const line of out.split(/\r?\n/)) {
const parts = line.trim().split(/\s+/);
if (parts.length < 4 || !/^TCP$/i.test(parts[0])) continue;
const [, local, remote] = parts;
const pid = parts[parts.length - 1];
if (!local.endsWith(`:${port}`)) continue;
if (!/^(?:0\.0\.0\.0|\[::\]):0$/.test(remote)) continue;
if (/^\d+$/.test(pid) && pid !== "0") pids.add(pid);
}
return [...pids];
}
function stopBridgeDaemon() {
try {
if (process.platform === "win32") {
const out = execSync("netstat -ano -p TCP", { encoding: "utf8" });
const v6 = (() => {
try {
return execSync("netstat -ano -p TCPv6", { encoding: "utf8" });
} catch {
return "";
}
})();
for (const pid of listenerPidsFromNetstat(out + "\n" + v6, BRIDGE_PORT)) {
try {
execSync(`taskkill /F /PID ${pid}`);
} catch {}
}
markDaemonStopped({ stoppedBy: "cli_stop", port: BRIDGE_PORT });
return true;
} else {
const pids = execSync(`lsof -ti :${BRIDGE_PORT} -sTCP:LISTEN`, { encoding: "utf8" })
.trim()
.split("\n")
.filter(Boolean);
for (const pid of pids) {
process.kill(parseInt(pid, 10), "SIGTERM");
}
markDaemonStopped({ stoppedBy: "cli_stop", port: BRIDGE_PORT });
return pids.length > 0;
}
} catch {
markDaemonStopped({ stoppedBy: "cli_stop", port: BRIDGE_PORT });
return false;
}
}
async function ensureBridge(autoDaemon = true, forceAuto = false) {
if (await isBridgeRunning()) return true;
if (!autoDaemon && !forceAuto) {
process.stderr.write(
"[browserctl] Error: Bridge daemon is not running. Start it with 'browserctl start'.\n"
);
process.exit(1);
}
if (isDaemonExplicitlyStopped(BRIDGE_PORT) && !forceAuto) {
process.stderr.write(
"[browserctl] Error: Bridge daemon is currently stopped (stopped by user/agent).\n" +
" Run 'browserctl start' to restart the daemon, or pass --auto-daemon.\n"
);
process.exit(1);
}
const autoStartPolicy = envStr("BROWSERCTL_AUTO_START", "auto");
if ((autoStartPolicy === "manual" || autoStartPolicy === "false") && !forceAuto) {
process.stderr.write(
"[browserctl] Error: Bridge daemon is not running and BROWSERCTL_AUTO_START=manual.\n" +
" Run 'browserctl start' to start the daemon.\n"
);
process.exit(1);
}
process.stderr.write(
`[browserctl] Bridge daemon not detected. Starting bridge on ${BRIDGE_URL}...\n`
);
const started = await startBridgeDaemon();
if (started) {
process.stderr.write("[browserctl] Bridge daemon started successfully.\n");
return true;
}
process.stderr.write(
"[browserctl] Warning: Bridge daemon failed to respond. Attempting command anyway...\n"
);
return false;
}
const HTML_TAGS = new Set([
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"p",
"a",
"button",
"input",
"textarea",
"select",
"div",
"span",
"img",
"form",
"header",
"footer",
"article",
"section",
"nav",
"main",
"ul",
"ol",
"li",
"table",
"tr",
"td",
"th",
"label",
"meta",
"link",
"body",
"svg",
]);
function parseTarget(arg, params) {
if (!arg) return;
const trimmed = arg.trim();
if (trimmed.startsWith("--text=")) {
params.text = trimmed.slice(7);
return;
}
if (trimmed.startsWith("--selector=")) {
params.selector = trimmed.slice(11);
return;
}
if (trimmed.startsWith("--placeholder=")) {
params.placeholder = trimmed.slice(14);
return;
}
if (trimmed.startsWith("@")) {
params.ref = trimmed;
return;
}
if (/^(?:f\w+:)?e\w+$/i.test(trimmed)) {
params.ref = `@${trimmed}`;
return;
}
if (/^\d+$/.test(trimmed)) {
params.index = parseInt(trimmed, 10);
return;
}
if (
trimmed.startsWith("#") ||
trimmed.startsWith(".") ||
trimmed.includes(">") ||
trimmed.includes("[") ||
trimmed.includes(":") ||
trimmed.includes(" ") ||
HTML_TAGS.has(trimmed.toLowerCase()) ||
(!trimmed.startsWith("-") && /^[a-z][a-z0-9._]*-[a-z0-9._-]*$/i.test(trimmed))
) {
params.selector = trimmed;
} else {
params.ref = trimmed;
}
}
// The BROWSER column only earns its keep once there is more than one browser to tell apart —
// `result.browsers` (the fan-out map) is present exactly when list_tabs reached more than one
// connection, so its presence is what turns the column on.
function formatTabsTable(tabs = [], { showBrowser = false } = {}) {
if (!Array.isArray(tabs) || tabs.length === 0) return "No open tabs.";
const header = showBrowser
? `ID ACTIVE BROWSER TITLE URL`
: `ID ACTIVE TITLE URL`;
const separator = "-".repeat(header.length);
const rows = tabs.map((t) => {
const id = String(t.id || "").padEnd(10);
const active = (t.active ? "*" : " ").padEnd(8);
const browser = showBrowser ? `${(t.browser || "").padEnd(12)} ` : "";
let title = (t.title || "(untitled)").replace(/\n/g, " ");
if (title.length > 44) title = title.slice(0, 41) + "...";
title = title.padEnd(46);
let url = t.url || "";
if (url.length > 60) url = url.slice(0, 57) + "...";
const held = t.heldBy ? ` [held by ${t.heldBy}]` : "";
return `${id} ${active} ${browser}${title} ${url}${held}`;
});
return [header, separator, ...rows].join("\n");
}
// One line per connected browser for `browserctl status`'s human output, e.g.
// ` chrome-1 chrome "Test profile" focused 12s ago`.
function formatAgo(ms) {
const secs = Math.max(0, Math.round((Date.now() - ms) / 1000));
if (secs < 60) return `${secs}s`;
if (secs < 3600) return `${Math.round(secs / 60)}m`;
return `${Math.round(secs / 3600)}h`;
}
function formatBrowserLine(b) {
const label = b.label ? ` ${JSON.stringify(b.label)}` : "";
const focus = b.lastFocusedAt ? `focused ${formatAgo(b.lastFocusedAt)} ago` : "not focused yet";
return ` ${b.alias} ${b.browserType}${label} ${focus}`;
}
function readManifest(dir) {
try {
return JSON.parse(fs.readFileSync(join(dir, "manifest.json"), "utf8"));
} catch {
return null;
}
}
// Copies the packaged extension to a fixed folder (default ~/.browserctl/extension) and exits.
// Under npx the package lives in a cache directory that `npm cache clean` deletes and that moves
// with every version, so an extension loaded from there disappears or goes stale. Running this
// again after an update refreshes the same folder; Chrome then needs only a reload.
function copyExtension(src, target, { jsonOutput, prettyOutput }) {
const dest = resolvePath(target || join(homedir(), ".browserctl", "extension"));
const fail = (error) => {
const out = { ok: false, error };
if (prettyOutput || jsonOutput) console.error(JSON.stringify(out, null, prettyOutput ? 2 : 0));
else console.error(`browserctl: ${error}`);
process.exit(1);
};
if (dest === resolvePath(src)) fail(`${dest} is the packaged extension itself`);
// The destination is replaced, not merged into, so files an older version had do not linger.
// That makes it destructive, so only an empty folder or an earlier copy may be replaced.
let previousVersion = null;
if (fs.existsSync(dest)) {
const old = readManifest(dest);
const empty = !old && fs.statSync(dest).isDirectory() && fs.readdirSync(dest).length === 0;
if (!empty && old?.name !== "browserctl") {
fail(`${dest} is not a browserctl extension folder; refusing to replace it`);
}
previousVersion = old?.version ?? null;
fs.rmSync(dest, { recursive: true, force: true });
}
fs.mkdirSync(dirname(dest), { recursive: true });
fs.cpSync(src, dest, { recursive: true });
const version = readManifest(dest)?.version ?? null;
if (prettyOutput || jsonOutput) {
const out = { ok: true, path: dest, source: src, version, previousVersion };
console.log(JSON.stringify(out, null, prettyOutput ? 2 : 0));
} else {
console.log(dest);
console.log("");
console.log(
previousVersion
? `Replaced ${previousVersion} with ${version}. In chrome://extensions, press reload on browserctl.`
: `Copied ${version}. Load it: chrome://extensions -> Developer mode -> Load unpacked -> the path above.`
);
}
process.exit(0);
}
async function main() {
const rawArgs = process.argv.slice(2);
if (rawArgs.length === 0 || rawArgs.includes("-h") || rawArgs.includes("--help")) {
printHelp();
process.exit(0);
}
let jsonOutput = false;
let prettyOutput = false;
let rawOutput = false;
let elementsMode = false;
let onlyKinds = null;
let fullpageMode = false;
let autoDaemon = true;
let forceTake = false;
let forceAutoDaemon = false;
let explicitTabId = null;
let settleMs = null;
// --browser/-b names a browser. Without it the bridge uses the session's target, or the sole
// connected browser; with several and no target it answers NEEDS_TARGET, listing the tabs.
let browserSelector = null;
const positionalArgs = [];
for (let i = 0; i < rawArgs.length; i++) {
const a = rawArgs[i];
if (a === "--json") {
jsonOutput = true;
} else if (a === "--pretty") {
prettyOutput = true;
} else if (a === "-r" || a === "--raw") {
rawOutput = true;
} else if (a === "--elements") {
elementsMode = true;
} else if (a === "--only" || a.startsWith("--only=")) {
const kinds = String(a === "--only" ? (rawArgs[++i] ?? "") : a.slice(7))
.split(",")
.map((k) => k.trim())
.filter(Boolean);
const bad = kinds.filter((k) => !["fields", "buttons", "links"].includes(k));
if (!kinds.length || bad.length) {
console.error(
`--only takes fields, buttons and/or links, comma-separated${bad.length ? ` (not ${bad.join(", ")})` : ""}`
);
process.exit(2);
}
onlyKinds = kinds;
} else if (a === "-c" || a === "--compact") {
console.error(
`${a}: the snapshot census is always compact; --elements returns every element as structured JSON instead`
);
process.exit(2);
} else if (a === "-f" || a === "--full" || a === "--fullpage") {
fullpageMode = true;
} else if (a === "--force") {
forceTake = true;
} else if (a === "--no-daemon") {
autoDaemon = false;
} else if (a === "--auto-daemon") {
forceAutoDaemon = true;
} else if (a === "-t" || a === "--tab") {
explicitTabId = parseInt(rawArgs[++i], 10);
} else if (a.startsWith("--tab=")) {
explicitTabId = parseInt(a.slice(6), 10);
} else if (a === "-b" || a === "--browser") {
browserSelector = rawArgs[++i];
} else if (a.startsWith("--browser=")) {
browserSelector = a.slice(10);
} else if (a === "--settle") {
settleMs = parseInt(rawArgs[++i], 10);
} else if (a.startsWith("--settle=")) {
settleMs = parseInt(a.slice(9), 10);
} else {
positionalArgs.push(a);
}
}
if (positionalArgs.length === 0) {
printHelp();
process.exit(0);
}
let action = positionalArgs[0];
let args = positionalArgs.slice(1);
if (action === "tabs" || action === "tab_list") {
action = "tab";
args = ["list", ...args];
} else if (action === "switch") {
action = "tab";
args = ["switch", ...args];
} else if (action === "get_text") {
action = "get";
args = ["text", ...args];
} else if (action === "get_count") {
action = "get";
args = ["count", ...args];
} else if (action === "close_modal") {
action = "dismiss";
}
if (action === "start" || action === "daemon") {
if (await isBridgeRunning()) {
markDaemonRunning({ port: BRIDGE_PORT, url: BRIDGE_URL });
const out = { ok: true, message: "Bridge is already running", url: BRIDGE_URL };
if (prettyOutput) console.log(JSON.stringify(out, null, 2));
else if (jsonOutput) console.log(JSON.stringify(out));
else console.log(`Bridge is already running on ${BRIDGE_URL}`);
process.exit(0);
}
const started = await startBridgeDaemon();
if (started) {
const out = { ok: true, message: "Bridge started", url: BRIDGE_URL };
if (prettyOutput) console.log(JSON.stringify(out, null, 2));
else if (jsonOutput) console.log(JSON.stringify(out));
else console.log(`Bridge started successfully on ${BRIDGE_URL}`);
process.exit(0);
} else {
const out = { ok: false, error: "Failed to start bridge daemon" };
if (prettyOutput) console.error(JSON.stringify(out, null, 2));
else console.error(JSON.stringify(out));
process.exit(1);
}
}
if (action === "stop") {
const stopped = stopBridgeDaemon();
const out = { ok: true, message: stopped ? "Bridge stopped" : "Bridge was not running" };
if (prettyOutput) console.log(JSON.stringify(out, null, 2));
else if (jsonOutput) console.log(JSON.stringify(out));
else console.log(stopped ? "Bridge stopped (daemon state: stopped)" : "Bridge was not running");
process.exit(0);
}
if (action === "extension-path" || action === "extension") {
const dir = join(__dirname, "extension");
const ok = fs.existsSync(join(dir, "manifest.json"));
if (ok && args[0] === "--copy") {
copyExtension(dir, args[1], { jsonOutput, prettyOutput });
}
if (prettyOutput || jsonOutput) {
const out = { ok, path: dir };
console.log(prettyOutput ? JSON.stringify(out, null, 2) : JSON.stringify(out));
} else if (ok) {
console.log(dir);
console.log("");
console.log(
"Load it: chrome://extensions -> Developer mode -> Load unpacked -> the path above."
);
} else {
console.log(`no extension found at ${dir}`);
}
process.exit(ok ? 0 : 1);
}
if (action === "restart") {
stopBridgeDaemon();
await new Promise((r) => setTimeout(r, 200));
const started = await startBridgeDaemon();
const out = { ok: started, message: started ? "Bridge restarted" : "Failed to restart" };
if (prettyOutput) console.log(JSON.stringify(out, null, 2));
else if (jsonOutput) console.log(JSON.stringify(out));
else console.log(started ? `Bridge restarted on ${BRIDGE_URL}` : "Failed to restart bridge");
process.exit(started ? 0 : 1);
}
if (action === "status") {
const stateInfo = getDaemonState(BRIDGE_PORT);
try {
const res = await fetch(`${BRIDGE_URL}/status`, { signal: AbortSignal.timeout(1000) });
const data = await res.json();
const statusObj = { ok: res.ok, daemonState: "running", ...data };
if (prettyOutput) {
console.log(JSON.stringify(statusObj, null, 2));
} else if (jsonOutput) {
console.log(JSON.stringify(statusObj));
} else {
console.log(`Bridge: RUNNING (${BRIDGE_URL})`);
console.log(`Extension: ${data.extensionConnected ? "CONNECTED" : "DISCONNECTED"}`);
if (Array.isArray(data.browsers) && data.browsers.length) {
console.log("Browsers:");
for (const b of data.browsers) console.log(formatBrowserLine(b));
}
if (data.callLog) {
const mb = (n) => (n / 1024 / 1024).toFixed(1);
const size = data.callLogBytes != null ? `${mb(data.callLogBytes)}MB` : "?";
const cap =
data.callLogMaxBytes != null ? `, rotates at ${mb(data.callLogMaxBytes)}MB` : "";
console.log(
`Call log: ON ${data.callLog} (${size}${cap}; parameter values never written)`
);
}
}
} catch (err) {
const statusObj = {
ok: false,
daemonState: stateInfo.state || "stopped",
error: err.message,
};
if (prettyOutput) {
console.log(JSON.stringify(statusObj, null, 2));
} else if (jsonOutput) {
console.log(JSON.stringify(statusObj));
} else {
console.log(
`Bridge: ${stateInfo.state === "stopped" ? "STOPPED (explicitly)" : "OFFLINE"}`
);
console.log(`Error: ${err.message}`);
}
process.exit(1);
}
return;
}
await ensureBridge(autoDaemon, forceAutoDaemon);
if (action === "tab") {
const sub = args[0] || "list";
if (sub === "list" || sub === "ls") {
action = "list_tabs";
args = args.slice(1);
} else if (sub === "new" || sub === "create") {
action = "new_tab";
args = args.slice(1);
} else if (sub === "switch" || sub === "focus") {
action = "switch_tab";
args = args.slice(1);
} else if (sub === "close") {
action = "close_tab";
args = args.slice(1);
} else if (sub === "release") {
action = "release_tab";
args = args.slice(1);
} else if (sub === "yield") {
action = "yield_tab";
args = args.slice(1);
} else if (/^\d+$/.test(sub)) {
action = "switch_tab";
} else {
action = "list_tabs";
}
}
if (action === "open") action = "navigate";
if (action === "tabs") action = "list_tabs";
if (action === "back") action = "go_back";
if (action === "forward") action = "go_forward";
if (action === "press") action = "press_key";
if (action === "eval" || action === "browser_evaluate" || action === "evaluate")
action = "eval_js";
if (action === "fill") action = "type";
if (action === "scrollintoview") action = "scrollintoview";
if (action === "file_upload" || action === "file-upload") action = "upload";
if (action === "take_screenshot" || action === "take-screenshot") action = "screenshot";
if (action === "get_content" || action === "get-content") action = "get_page_content";
if (action === "select_option" || action === "select-option") action = "select_option";
if (action === "fill_form" || action === "fill-form") action = "fill_form";
if (action === "wait" && args.length > 0 && /^\d+$/.test(args[0])) {
const ms = parseInt(args[0], 10);
await new Promise((r) => setTimeout(r, ms));
if (rawOutput) {
process.stdout.write(String(ms));
} else if (prettyOutput) {
console.log(JSON.stringify({ ok: true, waitedMs: ms }, null, 2));
} else if (jsonOutput) {
console.log(JSON.stringify({ ok: true, waitedMs: ms }));
} else {
console.log(`Waited ${ms}ms`);
}
process.exit(0);
}
let saveFilePath = null;
let params = {};
if (explicitTabId != null) params.tabId = explicitTabId;
if (settleMs != null) params.settleMs = settleMs;
if (forceTake) params.force = true;
if (args.length === 1 && args[0].trim().startsWith("{")) {
try {
params = { ...params, ...JSON.parse(args[0]) };
} catch (_e) {
console.error("Invalid JSON params:", args[0]);
process.exit(1);
}
} else {
switch (action) {
case "navigate":
case "new_tab":
if (args[0]) params.url = args[0];
break;
case "snapshot":
params.compact = !elementsMode;
if (rawArgs.includes("--all")) params.scope = "all";
if (onlyKinds) params.only = onlyKinds;
if (args[0] && /^\d+$/.test(args[0])) params.maxText = parseInt(args[0], 10);
for (let i = 0; i < rawArgs.length; i++) {
const m = /^--cursor(?:=(.*))?$/.exec(rawArgs[i]);
if (!m) continue;
const n = Number(m[1] ?? rawArgs[i + 1]);
if (!Number.isInteger(n) || n < 0) {
console.error("snapshot: --cursor needs a whole number, e.g. --cursor 60");
process.exit(2);
}
params.cursor = n;
}
break;
case "read_page":
if (args[0] && !args[0].startsWith("-")) params.mode = args[0];
for (let i = 0; i < args.length; i++) {
const a = args[i];
const val = (inline) => (inline !== undefined ? inline : args[++i]);
let m;
if ((m = /^--depth(?:=(\d+))?$/.exec(a))) params.depth = Number(val(m[1]));
else if ((m = /^--max-?chars(?:=(\d+))?$/.exec(a))) params.maxChars = Number(val(m[1]));
else if ((m = /^--ref(?:=(.+))?$/.exec(a))) params.ref_id = val(m[1]);
}
if (params.depth !== undefined && !Number.isFinite(params.depth)) {
console.error("read_page: --depth needs a number, e.g. --depth 60");
process.exit(2);
}
break;
case "get": {
let prop = args[0] || "text";
if (prop === "attribute") prop = "attr";
params.property = prop;
if (prop === "attr") {
let i = 1;
while (i < args.length) {
if (args[i] === "--selector" && args[i + 1]) {
params.selector = args[++i];
} else if (args[i] === "--attr" && args[i + 1]) {
params.attr = args[++i];
} else if (!params.ref && !params.index && !params.selector) {
parseTarget(args[i], params);
} else if (!params.attr) {
params.attr = args[i];
}
i++;
}
} else if (prop === "count") {
if (args[1]) params.selector = args[1];
} else if (prop !== "title" && prop !== "url") {
let i = 1;
while (i < args.length) {
if (args[i] === "--selector" && args[i + 1]) {
params.selector = args[++i];
} else if (args[i] === "--text" && args[i + 1]) {
params.text = args[++i];
} else if (!params.ref && !params.index && !params.selector) {
parseTarget(args[i], params);
}
i++;
}
}
action = "get_property";
break;
}
case "click":
case "dblclick":
case "hover":
case "focus":
case "clear":
case "check":
case "uncheck":
case "scrollintoview":
case "describe":
case "describe_element":
case "element_screenshot": {
let i = 0;
while (i < args.length) {
if (args[i] === "--text" && args[i + 1]) {
params.text = args[++i];
} else if (args[i] === "--selector" && args[i + 1]) {
params.selector = args[++i];
} else if (args[i] === "--wait-for" && args[i + 1]) {
params.waitFor = args[++i];
} else {
parseTarget(args[i], params);
}
i++;
}
if (action === "describe") action = "describe_element";
break;
}
case "upload": {
let i = 0;
while (i < args.length) {
if (args[i] === "--selector" && args[i + 1]) {
params.selector = args[++i];
} else if (args[i] === "--text" && args[i + 1]) {
params.text = args[++i];
} else if (/^@|^\d+$/.test(args[i])) {
parseTarget(args[i], params);
} else if (
!fs.existsSync(resolvePath(args[i])) &&
/^[#.[]/.test(args[i]) &&
!/^\.\.?[\\/]/.test(args[i])
) {
// Not a file on disk and shaped like a CSS selector: it names the input.
params.selector = args[i];
} else {
(params.files || (params.files = [])).push(resolvePath(args[i]));
}
i++;
}
break;
}
case "paste":
case "type": {
let i = 0;
let textArg = null;
while (i < args.length) {
if (args[i] === "--placeholder" && args[i + 1]) {
params.placeholder = args[++i];
} else if (args[i] === "--selector" && args[i + 1]) {
params.selector = args[++i];
} else if (args[i] === "--wait-for" && args[i + 1]) {
params.waitFor = args[++i];
} else if (args[i] === "--submit") {
params.submit = true;
} else if (!params.ref && !params.index && !params.selector && !params.placeholder) {
parseTarget(args[i], params);
} else if (textArg === null) {
textArg = args[i];
}
i++;
}
if (textArg !== null) params.text = textArg;
break;
}
case "select":
case "select_option": {
action = "select_option";
let i = 0;
while (i < args.length) {
if (args[i] === "--label" && args[i + 1]) {
params.label = args[++i];
} else if (!params.ref && !params.index && !params.selector) {
parseTarget(args[i], params);
} else if (params.value === undefined && params.label === undefined) {
params.value = args[i];
}
i++;
}
break;
}
case "wait": {
let i = 0;
let hasType = false;
while (i < args.length) {
if (args[i] === "--network-idle") {
action = "wait_network_idle";
hasType = true;
} else if (args[i] === "--settle" || args[i] === "--auto") {
action = "wait_settle";
hasType = true;
} else if (args[i] === "--tolerance" || args[i] === "--max-inflight") {
if (args[i + 1]) params.maxInFlight = parseInt(args[++i], 10);
} else if (args[i] === "--text" && args[i + 1]) {
action = "wait_for";
params.text = args[++i];
hasType = true;
} else if (args[i] === "--selector" && args[i + 1]) {
action = "wait_for";
params.selector = args[++i];
hasType = true;
} else if (args[i] === "--timeout" && args[i + 1]) {
params.timeoutMs = parseInt(args[++i], 10);
} else if (!hasType) {
action = "wait_for";
parseTarget(args[i], params);
hasType = true;
}
i++;
}
if (!hasType) action = "wait_settle";
break;
}
case "screenshot":
case "screenshot_fullpage": {
if (fullpageMode || action === "screenshot_fullpage") {
params.fullPage = true;
params.format = "png";
}
action = "screenshot";
if (args[0] && !args[0].startsWith("-")) {
saveFilePath = args[0];
}
break;
}
case "pdf":
case "print_pdf": {
action = "print_pdf";
if (args[0] && !args[0].startsWith("-")) {
saveFilePath = args[0];
}
break;
}
case "extract": {
let i = 0;
while (i < args.length) {