agent-browser 0.3.7 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,1163 +0,0 @@
1
- #!/usr/bin/env node
2
- import * as fs from 'fs';
3
- import * as os from 'os';
4
- import * as path from 'path';
5
- import { execSync } from 'child_process';
6
- import { send, setDebug, setSession, getSession } from './client.js';
7
- // ============================================================================
8
- // System Dependencies Installation
9
- // ============================================================================
10
- // Common dependencies needed for Playwright browsers on Linux
11
- const LINUX_DEPS = {
12
- // Shared libraries for Chromium/Firefox/WebKit
13
- apt: [
14
- 'libxcb-shm0',
15
- 'libx11-xcb1',
16
- 'libx11-6',
17
- 'libxcb1',
18
- 'libxext6',
19
- 'libxrandr2',
20
- 'libxcomposite1',
21
- 'libxcursor1',
22
- 'libxdamage1',
23
- 'libxfixes3',
24
- 'libxi6',
25
- 'libgtk-3-0',
26
- 'libpangocairo-1.0-0',
27
- 'libpango-1.0-0',
28
- 'libatk1.0-0',
29
- 'libcairo-gobject2',
30
- 'libcairo2',
31
- 'libgdk-pixbuf-2.0-0',
32
- 'libxrender1',
33
- 'libasound2',
34
- 'libfreetype6',
35
- 'libfontconfig1',
36
- 'libdbus-1-3',
37
- 'libnss3',
38
- 'libnspr4',
39
- 'libatk-bridge2.0-0',
40
- 'libdrm2',
41
- 'libxkbcommon0',
42
- 'libatspi2.0-0',
43
- 'libcups2',
44
- 'libxshmfence1',
45
- 'libgbm1',
46
- ],
47
- dnf: [
48
- 'libxcb',
49
- 'libX11-xcb',
50
- 'libX11',
51
- 'libXext',
52
- 'libXrandr',
53
- 'libXcomposite',
54
- 'libXcursor',
55
- 'libXdamage',
56
- 'libXfixes',
57
- 'libXi',
58
- 'gtk3',
59
- 'pango',
60
- 'atk',
61
- 'cairo-gobject',
62
- 'cairo',
63
- 'gdk-pixbuf2',
64
- 'libXrender',
65
- 'alsa-lib',
66
- 'freetype',
67
- 'fontconfig',
68
- 'dbus-libs',
69
- 'nss',
70
- 'nspr',
71
- 'at-spi2-atk',
72
- 'libdrm',
73
- 'libxkbcommon',
74
- 'at-spi2-core',
75
- 'cups-libs',
76
- 'libxshmfence',
77
- 'mesa-libgbm',
78
- 'libwayland-client',
79
- 'libwayland-server',
80
- ],
81
- yum: [
82
- 'libxcb',
83
- 'libX11-xcb',
84
- 'libX11',
85
- 'libXext',
86
- 'libXrandr',
87
- 'libXcomposite',
88
- 'libXcursor',
89
- 'libXdamage',
90
- 'libXfixes',
91
- 'libXi',
92
- 'gtk3',
93
- 'pango',
94
- 'atk',
95
- 'cairo-gobject',
96
- 'cairo',
97
- 'gdk-pixbuf2',
98
- 'libXrender',
99
- 'alsa-lib',
100
- 'freetype',
101
- 'fontconfig',
102
- 'dbus-libs',
103
- 'nss',
104
- 'nspr',
105
- 'at-spi2-atk',
106
- 'libdrm',
107
- 'libxkbcommon',
108
- 'at-spi2-core',
109
- 'cups-libs',
110
- 'libxshmfence',
111
- 'mesa-libgbm',
112
- ],
113
- };
114
- function detectPackageManager() {
115
- const managers = ['apt-get', 'dnf', 'yum'];
116
- for (const mgr of managers) {
117
- try {
118
- execSync(`which ${mgr}`, { stdio: 'ignore' });
119
- return mgr === 'apt-get' ? 'apt' : mgr;
120
- }
121
- catch {
122
- // Not found, try next
123
- }
124
- }
125
- return null;
126
- }
127
- function installSystemDeps() {
128
- if (os.platform() !== 'linux') {
129
- console.log('System dependency installation is only needed on Linux');
130
- return;
131
- }
132
- const pkgMgr = detectPackageManager();
133
- if (!pkgMgr) {
134
- throw new Error('No supported package manager found (apt-get, dnf, or yum)');
135
- }
136
- const deps = LINUX_DEPS[pkgMgr];
137
- if (!deps || deps.length === 0) {
138
- throw new Error(`No dependencies defined for package manager: ${pkgMgr}`);
139
- }
140
- console.log(`Detected package manager: ${pkgMgr}`);
141
- console.log(`Installing ${deps.length} dependencies...`);
142
- let cmd;
143
- switch (pkgMgr) {
144
- case 'apt':
145
- cmd = `apt-get update && apt-get install -y ${deps.join(' ')}`;
146
- break;
147
- case 'dnf':
148
- cmd = `dnf install -y ${deps.join(' ')}`;
149
- break;
150
- case 'yum':
151
- cmd = `yum install -y ${deps.join(' ')}`;
152
- break;
153
- }
154
- // Run with sudo if not root
155
- const isRoot = process.getuid?.() === 0;
156
- if (!isRoot) {
157
- cmd = `sudo ${cmd}`;
158
- }
159
- execSync(cmd, { stdio: 'inherit' });
160
- }
161
- // ============================================================================
162
- // Utilities
163
- // ============================================================================
164
- function listSessions() {
165
- const tmpDir = os.tmpdir();
166
- try {
167
- const files = fs.readdirSync(tmpDir);
168
- const sessions = [];
169
- for (const file of files) {
170
- const match = file.match(/^agent-browser-(.+)\.pid$/);
171
- if (match) {
172
- const pidFile = path.join(tmpDir, file);
173
- try {
174
- const pid = parseInt(fs.readFileSync(pidFile, 'utf8').trim(), 10);
175
- process.kill(pid, 0);
176
- sessions.push(match[1]);
177
- }
178
- catch {
179
- /* Process not running */
180
- }
181
- }
182
- }
183
- return sessions;
184
- }
185
- catch {
186
- return [];
187
- }
188
- }
189
- const colors = {
190
- reset: '\x1b[0m',
191
- bold: '\x1b[1m',
192
- dim: '\x1b[2m',
193
- red: '\x1b[31m',
194
- green: '\x1b[32m',
195
- yellow: '\x1b[33m',
196
- cyan: '\x1b[36m',
197
- };
198
- const c = (color, text) => `${colors[color]}${text}${colors.reset}`;
199
- function genId() {
200
- return Math.random().toString(36).slice(2, 10);
201
- }
202
- function err(msg) {
203
- console.error(c('red', 'Error:'), msg);
204
- process.exit(1);
205
- }
206
- // ============================================================================
207
- // Help
208
- // ============================================================================
209
- function printHelp() {
210
- console.log(`
211
- ${c('bold', 'agent-browser')} - headless browser automation for AI agents
212
-
213
- ${c('yellow', 'Usage:')} agent-browser <command> [options]
214
-
215
- ${c('yellow', 'Core Commands:')}
216
- ${c('cyan', 'open')} <url> Navigate to URL
217
- ${c('cyan', 'click')} <sel> Click element (or @ref)
218
- ${c('cyan', 'type')} <sel> <text> Type into element
219
- ${c('cyan', 'fill')} <sel> <text> Clear and fill
220
- ${c('cyan', 'press')} <key> Press key (Enter, Tab, Control+a)
221
- ${c('cyan', 'hover')} <sel> Hover element
222
- ${c('cyan', 'select')} <sel> <val> Select dropdown option
223
- ${c('cyan', 'scroll')} <dir> [px] Scroll (up/down/left/right)
224
- ${c('cyan', 'wait')} <sel|ms> Wait for element or time
225
- ${c('cyan', 'screenshot')} [path] Take screenshot
226
- ${c('cyan', 'snapshot')} Accessibility tree with refs (for AI)
227
- ${c('cyan', 'eval')} <js> Run JavaScript
228
- ${c('cyan', 'close')} Close browser
229
-
230
- ${c('yellow', 'Selectors:')} CSS, XPath, text=, or ${c('green', '@ref')} from snapshot
231
- ${c('dim', 'CSS:')} "#id", ".class", "button"
232
- ${c('dim', 'XPath:')} "xpath=//button"
233
- ${c('dim', 'Text:')} "text=Submit"
234
- ${c('dim', 'Ref:')} ${c('green', '@e1')}, ${c('green', '@e2')} (from snapshot output)
235
-
236
- ${c('yellow', 'Get Info:')} agent-browser get <what> [selector]
237
- text, html, value, attr, title, url, count, box
238
-
239
- ${c('yellow', 'Check State:')} agent-browser is <what> <selector>
240
- visible, enabled, checked
241
-
242
- ${c('yellow', 'Find Elements:')} agent-browser find <locator> <action> [value]
243
- role, text, label, placeholder, alt, title, testid, first, last, nth
244
-
245
- ${c('yellow', 'Mouse:')} agent-browser mouse <action> [args]
246
- move <x> <y>, down, up, wheel <dy>
247
-
248
- ${c('yellow', 'Storage:')}
249
- ${c('cyan', 'cookies')} [get|set|clear] Manage cookies
250
- ${c('cyan', 'storage')} <local|session> Manage web storage
251
-
252
- ${c('yellow', 'Browser:')} agent-browser set <setting> [value]
253
- viewport, device, geo, offline, headers, credentials
254
-
255
- ${c('yellow', 'Network:')} agent-browser network <action>
256
- route, unroute, requests
257
-
258
- ${c('yellow', 'Tabs:')}
259
- ${c('cyan', 'tab')} [new|list|close|<n>] Manage tabs
260
-
261
- ${c('yellow', 'Debug:')}
262
- ${c('cyan', 'trace')} start|stop <path> Record trace
263
- ${c('cyan', 'console')} View console logs
264
- ${c('cyan', 'errors')} View page errors
265
-
266
- ${c('yellow', 'Setup:')}
267
- ${c('cyan', 'install')} Install browser binaries
268
- ${c('cyan', 'install')} --with-deps Also install system dependencies (Linux)
269
-
270
- ${c('yellow', 'Options:')}
271
- --session <name> Isolated session (or AGENT_BROWSER_SESSION env)
272
- --json JSON output
273
- --full, -f Full page screenshot
274
- --headed Show browser window (not headless)
275
- --debug Debug output
276
-
277
- ${c('yellow', 'Examples:')}
278
- agent-browser open example.com
279
- agent-browser snapshot # Get tree with refs
280
- agent-browser click @e2 # Click by ref from snapshot
281
- agent-browser fill @e3 "test@example.com" # Fill by ref
282
- agent-browser click "#submit" # CSS selector still works
283
- agent-browser get text @e1 # Get text by ref
284
- agent-browser find role button click --name Submit
285
- `);
286
- }
287
- // ============================================================================
288
- // Response Printing
289
- // ============================================================================
290
- function printResponse(response, jsonMode) {
291
- if (jsonMode) {
292
- console.log(JSON.stringify(response));
293
- return;
294
- }
295
- if (!response.success) {
296
- console.error(c('red', '✗ Error:'), response.error);
297
- process.exit(1);
298
- }
299
- const data = response.data;
300
- if (data.url && data.title) {
301
- console.log(c('green', '✓'), c('bold', data.title));
302
- console.log(c('dim', ` ${data.url}`));
303
- }
304
- else if (data.text !== undefined) {
305
- console.log(data.text ?? c('dim', 'null'));
306
- }
307
- else if (data.html !== undefined) {
308
- console.log(data.html);
309
- }
310
- else if (data.value !== undefined) {
311
- console.log(data.value ?? c('dim', 'null'));
312
- }
313
- else if (data.result !== undefined) {
314
- const result = data.result;
315
- console.log(typeof result === 'object' ? JSON.stringify(result, null, 2) : result);
316
- }
317
- else if (data.snapshot) {
318
- console.log(data.snapshot);
319
- }
320
- else if (data.visible !== undefined) {
321
- console.log(data.visible ? c('green', 'true') : c('red', 'false'));
322
- }
323
- else if (data.enabled !== undefined) {
324
- console.log(data.enabled ? c('green', 'true') : c('red', 'false'));
325
- }
326
- else if (data.checked !== undefined) {
327
- console.log(data.checked ? c('green', 'true') : c('red', 'false'));
328
- }
329
- else if (data.count !== undefined) {
330
- console.log(data.count);
331
- }
332
- else if (data.box) {
333
- const box = data.box;
334
- console.log(`x:${box.x} y:${box.y} w:${box.width} h:${box.height}`);
335
- }
336
- else if (data.url) {
337
- console.log(data.url);
338
- }
339
- else if (data.title) {
340
- console.log(data.title);
341
- }
342
- else if (data.base64) {
343
- console.log(c('green', '✓'), 'Screenshot captured');
344
- }
345
- else if (data.path) {
346
- console.log(c('green', '✓'), `Saved: ${data.path}`);
347
- }
348
- else if (data.cookies) {
349
- const cookies = data.cookies;
350
- if (cookies.length === 0)
351
- console.log(c('dim', 'No cookies'));
352
- else
353
- cookies.forEach((ck) => console.log(`${c('cyan', ck.name)}: ${ck.value}`));
354
- }
355
- else if (data.tabs) {
356
- const tabs = data.tabs;
357
- tabs.forEach((t) => {
358
- const marker = t.active ? c('green', '→') : ' ';
359
- console.log(`${marker} [${t.index}] ${t.title || c('dim', '(untitled)')}`);
360
- if (t.url)
361
- console.log(c('dim', ` ${t.url}`));
362
- });
363
- }
364
- else if (data.index !== undefined && data.total !== undefined) {
365
- console.log(c('green', '✓'), `Tab ${data.index} (${data.total} total)`);
366
- }
367
- else if (data.messages) {
368
- const msgs = data.messages;
369
- if (msgs.length === 0)
370
- console.log(c('dim', 'No messages'));
371
- else
372
- msgs.forEach((m) => {
373
- const col = m.type === 'error' ? 'red' : m.type === 'warning' ? 'yellow' : 'dim';
374
- console.log(`${c(col, `[${m.type}]`)} ${m.text}`);
375
- });
376
- }
377
- else if (data.errors) {
378
- const errs = data.errors;
379
- if (errs.length === 0)
380
- console.log(c('dim', 'No errors'));
381
- else
382
- errs.forEach((e) => console.log(c('red', '✗'), e.message));
383
- }
384
- else if (data.requests) {
385
- const reqs = data.requests;
386
- if (reqs.length === 0)
387
- console.log(c('dim', 'No requests'));
388
- else
389
- reqs.forEach((r) => console.log(`${c('cyan', r.method)} ${r.url}`));
390
- }
391
- else if (data.moved) {
392
- console.log(c('green', '✓'), `Moved to (${data.x}, ${data.y})`);
393
- }
394
- else if (data.body !== undefined && data.status !== undefined) {
395
- // Response body
396
- console.log(c('green', '✓'), `${data.status} ${data.url}`);
397
- console.log(typeof data.body === 'object' ? JSON.stringify(data.body, null, 2) : data.body);
398
- }
399
- else if (data.filename) {
400
- // Download
401
- console.log(c('green', '✓'), `Downloaded: ${data.filename}`);
402
- console.log(c('dim', ` Path: ${data.path}`));
403
- }
404
- else if (data.inserted) {
405
- console.log(c('green', '✓'), 'Text inserted');
406
- }
407
- else if (data.key) {
408
- console.log(c('green', '✓'), `Key ${data.down ? 'down' : 'up'}: ${data.key}`);
409
- }
410
- else if (data.note) {
411
- console.log(c('yellow', '⚠'), data.note);
412
- }
413
- else if (data.closed === true) {
414
- console.log(c('green', '✓'), 'Browser closed');
415
- }
416
- else if (data.launched) {
417
- console.log(c('green', '✓'), 'Browser launched');
418
- }
419
- else if (data.state) {
420
- console.log(c('green', '✓'), `Load state: ${data.state}`);
421
- }
422
- else if (Object.keys(data).some((k) => [
423
- 'clicked',
424
- 'typed',
425
- 'filled',
426
- 'pressed',
427
- 'hovered',
428
- 'scrolled',
429
- 'selected',
430
- 'waited',
431
- 'checked',
432
- 'unchecked',
433
- 'focused',
434
- 'set',
435
- 'cleared',
436
- 'started',
437
- 'down',
438
- 'up',
439
- ].includes(k))) {
440
- console.log(c('green', '✓'), 'Done');
441
- }
442
- else {
443
- console.log(c('green', '✓'), JSON.stringify(data));
444
- }
445
- }
446
- // ============================================================================
447
- // Command Handlers
448
- // ============================================================================
449
- async function handleGet(args, id) {
450
- const what = args[0];
451
- const selector = args[1];
452
- switch (what) {
453
- case 'text':
454
- if (!selector)
455
- err('Selector required: agent-browser get text <selector>');
456
- return { id, action: 'gettext', selector };
457
- case 'html':
458
- if (!selector)
459
- err('Selector required: agent-browser get html <selector>');
460
- return { id, action: 'innerhtml', selector };
461
- case 'value':
462
- if (!selector)
463
- err('Selector required: agent-browser get value <selector>');
464
- return { id, action: 'inputvalue', selector };
465
- case 'attr':
466
- if (!selector || !args[2])
467
- err('Usage: agent-browser get attr <selector> <attribute>');
468
- return { id, action: 'getattribute', selector, attribute: args[2] };
469
- case 'title':
470
- return { id, action: 'title' };
471
- case 'url':
472
- return { id, action: 'url' };
473
- case 'count':
474
- if (!selector)
475
- err('Selector required: agent-browser get count <selector>');
476
- return { id, action: 'count', selector };
477
- case 'box':
478
- if (!selector)
479
- err('Selector required: agent-browser get box <selector>');
480
- return { id, action: 'boundingbox', selector };
481
- default:
482
- err(`Unknown: agent-browser get ${what}. Options: text, html, value, attr, title, url, count, box`);
483
- }
484
- }
485
- async function handleIs(args, id) {
486
- const what = args[0];
487
- const selector = args[1];
488
- if (!selector)
489
- err(`Selector required: agent-browser is ${what} <selector>`);
490
- switch (what) {
491
- case 'visible':
492
- return { id, action: 'isvisible', selector };
493
- case 'enabled':
494
- return { id, action: 'isenabled', selector };
495
- case 'checked':
496
- return { id, action: 'ischecked', selector };
497
- default:
498
- err(`Unknown: agent-browser is ${what}. Options: visible, enabled, checked`);
499
- }
500
- }
501
- async function handleFind(args, id, flags) {
502
- const locator = args[0];
503
- const value = args[1];
504
- const subaction = args[2] || 'click';
505
- const fillValue = args[3];
506
- if (!value)
507
- err(`Value required: agent-browser find ${locator} <value> <action>`);
508
- const exact = flags.exact;
509
- const name = flags.name;
510
- switch (locator) {
511
- case 'role':
512
- return { id, action: 'getbyrole', role: value, subaction, value: fillValue, name, exact };
513
- case 'text':
514
- return { id, action: 'getbytext', text: value, subaction, exact };
515
- case 'label':
516
- return { id, action: 'getbylabel', label: value, subaction, value: fillValue, exact };
517
- case 'placeholder':
518
- return {
519
- id,
520
- action: 'getbyplaceholder',
521
- placeholder: value,
522
- subaction,
523
- value: fillValue,
524
- exact,
525
- };
526
- case 'alt':
527
- return { id, action: 'getbyalttext', text: value, subaction, exact };
528
- case 'title':
529
- return { id, action: 'getbytitle', text: value, subaction, exact };
530
- case 'testid':
531
- return { id, action: 'getbytestid', testId: value, subaction, value: fillValue };
532
- case 'first':
533
- return { id, action: 'nth', selector: value, index: 0, subaction, value: fillValue };
534
- case 'last':
535
- return { id, action: 'nth', selector: value, index: -1, subaction, value: fillValue };
536
- case 'nth': {
537
- const idx = parseInt(value, 10);
538
- const sel = args[2];
539
- const act = args[3] || 'click';
540
- const val = args[4];
541
- if (isNaN(idx) || !sel)
542
- err('Usage: agent-browser find nth <index> <selector> <action>');
543
- return { id, action: 'nth', selector: sel, index: idx, subaction: act, value: val };
544
- }
545
- default:
546
- err(`Unknown locator: ${locator}. Options: role, text, label, placeholder, alt, title, testid, first, last, nth`);
547
- }
548
- }
549
- async function handleMouse(args, id) {
550
- const action = args[0];
551
- switch (action) {
552
- case 'move': {
553
- const x = parseInt(args[1], 10);
554
- const y = parseInt(args[2], 10);
555
- if (isNaN(x) || isNaN(y))
556
- err('Usage: agent-browser mouse move <x> <y>');
557
- return { id, action: 'mousemove', x, y };
558
- }
559
- case 'down':
560
- return { id, action: 'mousedown', button: args[1] || 'left' };
561
- case 'up':
562
- return { id, action: 'mouseup', button: args[1] || 'left' };
563
- case 'wheel': {
564
- const dy = parseInt(args[1], 10) || 100;
565
- const dx = parseInt(args[2], 10) || 0;
566
- return { id, action: 'wheel', deltaY: dy, deltaX: dx };
567
- }
568
- default:
569
- err(`Unknown: agent-browser mouse ${action}. Options: move, down, up, wheel`);
570
- }
571
- }
572
- async function handleSet(args, id) {
573
- const setting = args[0];
574
- switch (setting) {
575
- case 'viewport': {
576
- const w = parseInt(args[1], 10);
577
- const h = parseInt(args[2], 10);
578
- if (isNaN(w) || isNaN(h))
579
- err('Usage: agent-browser set viewport <width> <height>');
580
- return { id, action: 'viewport', width: w, height: h };
581
- }
582
- case 'device':
583
- if (!args[1])
584
- err('Usage: agent-browser set device <name>');
585
- return { id, action: 'device', device: args[1] };
586
- case 'geo':
587
- case 'geolocation': {
588
- const lat = parseFloat(args[1]);
589
- const lng = parseFloat(args[2]);
590
- if (isNaN(lat) || isNaN(lng))
591
- err('Usage: agent-browser set geo <lat> <lng>');
592
- return { id, action: 'geolocation', latitude: lat, longitude: lng };
593
- }
594
- case 'offline':
595
- return { id, action: 'offline', offline: args[1] !== 'off' && args[1] !== 'false' };
596
- case 'headers':
597
- if (!args[1])
598
- err('Usage: agent-browser set headers <json>');
599
- try {
600
- return { id, action: 'headers', headers: JSON.parse(args[1]) };
601
- }
602
- catch {
603
- err('Invalid JSON for headers');
604
- }
605
- break;
606
- case 'credentials':
607
- case 'auth':
608
- if (!args[1] || !args[2])
609
- err('Usage: agent-browser set credentials <user> <pass>');
610
- return { id, action: 'credentials', username: args[1], password: args[2] };
611
- case 'media': {
612
- const colorScheme = args.includes('dark')
613
- ? 'dark'
614
- : args.includes('light')
615
- ? 'light'
616
- : undefined;
617
- const media = args.includes('print')
618
- ? 'print'
619
- : args.includes('screen')
620
- ? 'screen'
621
- : undefined;
622
- return { id, action: 'emulatemedia', colorScheme, media };
623
- }
624
- default:
625
- err(`Unknown: agent-browser set ${setting}. Options: viewport, device, geo, offline, headers, credentials, media`);
626
- }
627
- return {};
628
- }
629
- async function handleNetwork(args, id, allArgs) {
630
- const action = args[0];
631
- switch (action) {
632
- case 'route': {
633
- const url = args[1];
634
- if (!url)
635
- err('Usage: agent-browser network route <url> [--abort|--body <json>]');
636
- const abort = allArgs.includes('--abort');
637
- const bodyIdx = allArgs.indexOf('--body');
638
- const body = bodyIdx !== -1 ? allArgs[bodyIdx + 1] : undefined;
639
- return {
640
- id,
641
- action: 'route',
642
- url,
643
- abort,
644
- response: body ? { body, contentType: 'application/json' } : undefined,
645
- };
646
- }
647
- case 'unroute':
648
- return { id, action: 'unroute', url: args[1] };
649
- case 'requests': {
650
- const clear = allArgs.includes('--clear');
651
- const filterIdx = allArgs.indexOf('--filter');
652
- const filter = filterIdx !== -1 ? allArgs[filterIdx + 1] : undefined;
653
- return { id, action: 'requests', clear, filter };
654
- }
655
- default:
656
- err(`Unknown: agent-browser network ${action}. Options: route, unroute, requests`);
657
- }
658
- return {};
659
- }
660
- async function handleStorage(args, id) {
661
- const type = args[0];
662
- const sub = args[1];
663
- if (type !== 'local' && type !== 'session') {
664
- err('Usage: agent-browser storage <local|session> [get|set|clear] [key] [value]');
665
- }
666
- if (sub === 'set') {
667
- if (!args[2] || !args[3])
668
- err(`Usage: agent-browser storage ${type} set <key> <value>`);
669
- return { id, action: 'storage_set', type, key: args[2], value: args[3] };
670
- }
671
- else if (sub === 'clear') {
672
- return { id, action: 'storage_clear', type };
673
- }
674
- else {
675
- // get (default)
676
- return { id, action: 'storage_get', type, key: sub };
677
- }
678
- }
679
- async function handleCookies(args, id) {
680
- const sub = args[0];
681
- if (sub === 'set') {
682
- if (!args[1])
683
- err('Usage: agent-browser cookies set <json>');
684
- try {
685
- return { id, action: 'cookies_set', cookies: JSON.parse(args[1]) };
686
- }
687
- catch {
688
- err('Invalid JSON for cookies');
689
- }
690
- }
691
- else if (sub === 'clear') {
692
- return { id, action: 'cookies_clear' };
693
- }
694
- else {
695
- return { id, action: 'cookies_get' };
696
- }
697
- return {};
698
- }
699
- async function handleTab(args, id) {
700
- const sub = args[0];
701
- if (sub === 'new') {
702
- return { id, action: 'tab_new' };
703
- }
704
- else if (sub === 'list' || sub === 'ls' || !sub) {
705
- return { id, action: 'tab_list' };
706
- }
707
- else if (sub === 'close') {
708
- const idx = args[1] !== undefined ? parseInt(args[1], 10) : undefined;
709
- return { id, action: 'tab_close', index: idx };
710
- }
711
- else {
712
- const idx = parseInt(sub, 10);
713
- if (isNaN(idx))
714
- err(`Unknown: agent-browser tab ${sub}. Options: new, list, close, <index>`);
715
- return { id, action: 'tab_switch', index: idx };
716
- }
717
- }
718
- async function handleTrace(args, id) {
719
- const sub = args[0];
720
- if (sub === 'start') {
721
- return { id, action: 'trace_start', screenshots: true, snapshots: true };
722
- }
723
- else if (sub === 'stop') {
724
- if (!args[1])
725
- err('Usage: agent-browser trace stop <path>');
726
- return { id, action: 'trace_stop', path: args[1] };
727
- }
728
- else {
729
- err('Usage: agent-browser trace start|stop');
730
- }
731
- return {};
732
- }
733
- async function handleState(args, id) {
734
- const sub = args[0];
735
- const path = args[1];
736
- if (sub === 'save') {
737
- if (!path)
738
- err('Usage: agent-browser state save <path>');
739
- return { id, action: 'state_save', path };
740
- }
741
- else if (sub === 'load') {
742
- if (!path)
743
- err('Usage: agent-browser state load <path>');
744
- return { id, action: 'state_load', path };
745
- }
746
- else {
747
- err('Usage: agent-browser state save|load <path>');
748
- }
749
- return {};
750
- }
751
- function parseFlags(args) {
752
- const flags = {
753
- json: false,
754
- full: false,
755
- text: false,
756
- debug: false,
757
- headed: false,
758
- session: process.env.AGENT_BROWSER_SESSION || 'default',
759
- exact: false,
760
- };
761
- const cleanArgs = [];
762
- let i = 0;
763
- while (i < args.length) {
764
- const arg = args[i];
765
- if (arg === '--json') {
766
- flags.json = true;
767
- }
768
- else if (arg === '--full' || arg === '-f') {
769
- flags.full = true;
770
- }
771
- else if (arg === '--text' || arg === '-t') {
772
- flags.text = true;
773
- }
774
- else if (arg === '--debug') {
775
- flags.debug = true;
776
- }
777
- else if (arg === '--headed' || arg === '--head') {
778
- flags.headed = true;
779
- }
780
- else if (arg === '--exact') {
781
- flags.exact = true;
782
- }
783
- else if (arg === '--session' && args[i + 1]) {
784
- flags.session = args[++i];
785
- }
786
- else if ((arg === '--selector' || arg === '-s') && args[i + 1]) {
787
- flags.selector = args[++i];
788
- }
789
- else if ((arg === '--name' || arg === '-n') && args[i + 1]) {
790
- flags.name = args[++i];
791
- }
792
- else if (arg === '--url' && args[i + 1]) {
793
- flags.url = args[++i];
794
- }
795
- else if (arg === '--load' && args[i + 1]) {
796
- flags.load = args[++i];
797
- }
798
- else if ((arg === '--fn' || arg === '--function') && args[i + 1]) {
799
- flags.fn = args[++i];
800
- }
801
- else if (!arg.startsWith('-')) {
802
- cleanArgs.push(arg);
803
- }
804
- i++;
805
- }
806
- return { flags, cleanArgs };
807
- }
808
- // ============================================================================
809
- // Main
810
- // ============================================================================
811
- async function main() {
812
- const rawArgs = process.argv.slice(2);
813
- const { flags, cleanArgs } = parseFlags(rawArgs);
814
- if (flags.debug)
815
- setDebug(true);
816
- setSession(flags.session);
817
- if (cleanArgs.length === 0 || rawArgs.includes('--help') || rawArgs.includes('-h')) {
818
- printHelp();
819
- process.exit(0);
820
- }
821
- const command = cleanArgs[0];
822
- const args = cleanArgs.slice(1);
823
- const id = genId();
824
- let cmd;
825
- switch (command) {
826
- // === Core Commands ===
827
- case 'open':
828
- case 'goto':
829
- case 'navigate': {
830
- if (!args[0])
831
- err('URL required');
832
- const url = args[0].startsWith('http') ? args[0] : `https://${args[0]}`;
833
- // If --headed, launch with headless=false first
834
- if (flags.headed) {
835
- await send({ id: genId(), action: 'launch', headless: false });
836
- }
837
- cmd = { id, action: 'navigate', url };
838
- break;
839
- }
840
- case 'click':
841
- if (!args[0])
842
- err('Selector required');
843
- cmd = { id, action: 'click', selector: args[0] };
844
- break;
845
- case 'dblclick':
846
- if (!args[0])
847
- err('Selector required');
848
- cmd = { id, action: 'dblclick', selector: args[0] };
849
- break;
850
- case 'type':
851
- if (!args[0] || !args[1])
852
- err('Usage: agent-browser type <selector> <text>');
853
- cmd = { id, action: 'type', selector: args[0], text: args.slice(1).join(' ') };
854
- break;
855
- case 'fill':
856
- if (!args[0] || !args[1])
857
- err('Usage: agent-browser fill <selector> <text>');
858
- cmd = { id, action: 'fill', selector: args[0], value: args.slice(1).join(' ') };
859
- break;
860
- case 'press':
861
- case 'key':
862
- if (!args[0])
863
- err('Key required');
864
- cmd = { id, action: 'press', key: args[0] };
865
- break;
866
- case 'keydown':
867
- if (!args[0])
868
- err('Key required');
869
- cmd = { id, action: 'keydown', key: args[0] };
870
- break;
871
- case 'keyup':
872
- if (!args[0])
873
- err('Key required');
874
- cmd = { id, action: 'keyup', key: args[0] };
875
- break;
876
- case 'hover':
877
- if (!args[0])
878
- err('Selector required');
879
- cmd = { id, action: 'hover', selector: args[0] };
880
- break;
881
- case 'focus':
882
- if (!args[0])
883
- err('Selector required');
884
- cmd = { id, action: 'focus', selector: args[0] };
885
- break;
886
- case 'check':
887
- if (!args[0])
888
- err('Selector required');
889
- cmd = { id, action: 'check', selector: args[0] };
890
- break;
891
- case 'uncheck':
892
- if (!args[0])
893
- err('Selector required');
894
- cmd = { id, action: 'uncheck', selector: args[0] };
895
- break;
896
- case 'select':
897
- if (!args[0] || !args[1])
898
- err('Usage: agent-browser select <selector> <value>');
899
- cmd = { id, action: 'select', selector: args[0], value: args[1] };
900
- break;
901
- case 'drag':
902
- if (!args[0] || !args[1])
903
- err('Usage: agent-browser drag <source> <target>');
904
- cmd = { id, action: 'drag', source: args[0], target: args[1] };
905
- break;
906
- case 'upload':
907
- if (!args[0] || !args[1])
908
- err('Usage: agent-browser upload <selector> <files...>');
909
- cmd = { id, action: 'upload', selector: args[0], files: args.slice(1) };
910
- break;
911
- case 'scroll': {
912
- const dir = args[0] || 'down';
913
- const amount = parseInt(args[1], 10) || 300;
914
- cmd = { id, action: 'scroll', direction: dir, amount, selector: flags.selector };
915
- break;
916
- }
917
- case 'wait': {
918
- const target = args[0];
919
- // Check for flags
920
- if (flags.fn) {
921
- cmd = { id, action: 'waitforfunction', expression: flags.fn };
922
- }
923
- else if (flags.url) {
924
- cmd = { id, action: 'waitforurl', url: flags.url };
925
- }
926
- else if (flags.load) {
927
- cmd = { id, action: 'waitforloadstate', state: flags.load };
928
- }
929
- else if (flags.text) {
930
- if (!target)
931
- err('Text required with --text flag');
932
- cmd = { id, action: 'wait', text: target };
933
- }
934
- else if (target && /^\d+$/.test(target)) {
935
- cmd = { id, action: 'wait', timeout: parseInt(target, 10) };
936
- }
937
- else if (target) {
938
- cmd = { id, action: 'wait', selector: target };
939
- }
940
- else {
941
- err('Usage: agent-browser wait <selector|ms|--text|--url|--load|--fn>');
942
- }
943
- break;
944
- }
945
- case 'screenshot': {
946
- const path = args[0];
947
- cmd = { id, action: 'screenshot', path, fullPage: flags.full, selector: flags.selector };
948
- break;
949
- }
950
- case 'pdf':
951
- if (!args[0])
952
- err('Path required');
953
- cmd = { id, action: 'pdf', path: args[0] };
954
- break;
955
- case 'snapshot':
956
- cmd = { id, action: 'snapshot' };
957
- break;
958
- case 'eval':
959
- if (!args[0])
960
- err('Script required');
961
- cmd = { id, action: 'evaluate', script: args.join(' ') };
962
- break;
963
- case 'close':
964
- case 'quit':
965
- case 'exit':
966
- cmd = { id, action: 'close' };
967
- break;
968
- // === Navigation ===
969
- case 'back':
970
- cmd = { id, action: 'back' };
971
- break;
972
- case 'forward':
973
- cmd = { id, action: 'forward' };
974
- break;
975
- case 'reload':
976
- cmd = { id, action: 'reload' };
977
- break;
978
- // === Grouped Commands ===
979
- case 'get':
980
- cmd = await handleGet(args, id);
981
- break;
982
- case 'is':
983
- cmd = await handleIs(args, id);
984
- break;
985
- case 'find':
986
- cmd = await handleFind(args, id, flags);
987
- break;
988
- case 'mouse':
989
- cmd = await handleMouse(args, id);
990
- break;
991
- case 'set':
992
- cmd = await handleSet(args, id);
993
- break;
994
- case 'network':
995
- cmd = await handleNetwork(args, id, rawArgs);
996
- break;
997
- case 'storage':
998
- cmd = await handleStorage(args, id);
999
- break;
1000
- case 'cookies':
1001
- cmd = await handleCookies(args, id);
1002
- break;
1003
- case 'tab':
1004
- cmd = await handleTab(args, id);
1005
- break;
1006
- case 'window':
1007
- if (args[0] === 'new') {
1008
- cmd = { id, action: 'window_new' };
1009
- }
1010
- else {
1011
- err('Usage: agent-browser window new');
1012
- }
1013
- break;
1014
- case 'frame':
1015
- if (!args[0])
1016
- err('Selector required');
1017
- if (args[0] === 'main') {
1018
- cmd = { id, action: 'mainframe' };
1019
- }
1020
- else {
1021
- cmd = { id, action: 'frame', selector: args[0] };
1022
- }
1023
- break;
1024
- case 'dialog':
1025
- if (args[0] === 'accept') {
1026
- cmd = { id, action: 'dialog', response: 'accept', promptText: args[1] };
1027
- }
1028
- else if (args[0] === 'dismiss') {
1029
- cmd = { id, action: 'dialog', response: 'dismiss' };
1030
- }
1031
- else {
1032
- err('Usage: agent-browser dialog accept|dismiss');
1033
- }
1034
- break;
1035
- case 'trace':
1036
- cmd = await handleTrace(args, id);
1037
- break;
1038
- case 'state':
1039
- cmd = await handleState(args, id);
1040
- break;
1041
- case 'console':
1042
- cmd = { id, action: 'console', clear: rawArgs.includes('--clear') };
1043
- break;
1044
- case 'errors':
1045
- cmd = { id, action: 'errors', clear: rawArgs.includes('--clear') };
1046
- break;
1047
- case 'highlight':
1048
- if (!args[0])
1049
- err('Selector required');
1050
- cmd = { id, action: 'highlight', selector: args[0] };
1051
- break;
1052
- case 'scrollintoview':
1053
- case 'scrollinto':
1054
- if (!args[0])
1055
- err('Selector required');
1056
- cmd = { id, action: 'scrollintoview', selector: args[0] };
1057
- break;
1058
- case 'initscript':
1059
- if (!args[0])
1060
- err('Script required');
1061
- cmd = { id, action: 'addinitscript', script: args.join(' ') };
1062
- break;
1063
- case 'inserttext':
1064
- case 'insert':
1065
- if (!args[0])
1066
- err('Text required');
1067
- cmd = { id, action: 'inserttext', text: args.join(' ') };
1068
- break;
1069
- case 'multiselect':
1070
- if (!args[0] || args.length < 2)
1071
- err('Usage: agent-browser multiselect <selector> <value1> [value2...]');
1072
- cmd = { id, action: 'multiselect', selector: args[0], values: args.slice(1) };
1073
- break;
1074
- case 'download':
1075
- cmd = { id, action: 'waitfordownload', path: args[0] };
1076
- break;
1077
- case 'response':
1078
- if (!args[0])
1079
- err('URL pattern required');
1080
- cmd = { id, action: 'responsebody', url: args[0] };
1081
- break;
1082
- case 'session':
1083
- if (args[0] === 'list' || args[0] === 'ls') {
1084
- const sessions = listSessions();
1085
- const current = getSession();
1086
- if (sessions.length === 0) {
1087
- console.log(c('dim', 'No active sessions'));
1088
- }
1089
- else {
1090
- sessions.forEach((s) => {
1091
- const marker = s === current ? c('green', '→') : ' ';
1092
- console.log(`${marker} ${c('cyan', s)}`);
1093
- });
1094
- }
1095
- process.exit(0);
1096
- }
1097
- else {
1098
- console.log(c('cyan', getSession()));
1099
- process.exit(0);
1100
- }
1101
- case 'install': {
1102
- const withDeps = rawArgs.includes('--with-deps') || rawArgs.includes('-d');
1103
- // Install system dependencies first if requested
1104
- if (withDeps) {
1105
- console.log(c('cyan', 'Installing system dependencies...'));
1106
- try {
1107
- installSystemDeps();
1108
- console.log(c('green', '✓'), 'System dependencies installed');
1109
- }
1110
- catch (error) {
1111
- const msg = error instanceof Error ? error.message : String(error);
1112
- console.error(c('red', '✗'), 'Failed to install system dependencies:', msg);
1113
- process.exit(1);
1114
- }
1115
- }
1116
- // Install browsers
1117
- console.log(c('cyan', 'Installing Playwright browsers...'));
1118
- try {
1119
- execSync('npx playwright install', { stdio: 'inherit' });
1120
- console.log(c('green', '✓'), 'Browsers installed successfully');
1121
- process.exit(0);
1122
- }
1123
- catch (error) {
1124
- console.error(c('red', '✗'), 'Failed to install browsers');
1125
- process.exit(1);
1126
- }
1127
- }
1128
- // === Legacy aliases for backwards compatibility ===
1129
- case 'url':
1130
- cmd = { id, action: 'url' };
1131
- break;
1132
- case 'title':
1133
- cmd = { id, action: 'title' };
1134
- break;
1135
- case 'gettext':
1136
- cmd = { id, action: 'gettext', selector: args[0] };
1137
- break;
1138
- case 'extract':
1139
- cmd = { id, action: 'content', selector: args[0] };
1140
- break;
1141
- default:
1142
- console.error(c('red', 'Unknown command:'), command);
1143
- console.error(c('dim', 'Run: agent-browser --help'));
1144
- process.exit(1);
1145
- }
1146
- try {
1147
- const response = await send(cmd);
1148
- printResponse(response, flags.json);
1149
- process.exit(0);
1150
- }
1151
- catch (error) {
1152
- const message = error instanceof Error ? error.message : String(error);
1153
- if (flags.json) {
1154
- console.log(JSON.stringify({ id, success: false, error: message }));
1155
- }
1156
- else {
1157
- console.error(c('red', '✗ Error:'), message);
1158
- }
1159
- process.exit(1);
1160
- }
1161
- }
1162
- main();
1163
- //# sourceMappingURL=index.js.map