frowse 0.1.0__py3-none-any.whl

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.
frowse/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Frowse: Drop-in replacement for agent-browser powered by Folate local DOM grounding."""
2
+
3
+ __version__ = "0.1.0"
frowse/cli.py ADDED
@@ -0,0 +1,586 @@
1
+ """agent-browser-compatible CLI for Frowse."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ from typing import Any
9
+
10
+ from frowse import __version__
11
+ from frowse.client import close_all_sessions, send_command
12
+ from frowse.skills import install_skills, list_skills, read_skill
13
+
14
+
15
+ def _split_global_flags(argv: list[str]) -> tuple[dict[str, Any], list[str]]:
16
+ """Extract global flags while preserving `--` literal marker."""
17
+ opts: dict[str, Any] = {
18
+ "json": False,
19
+ "session": os.environ.get("FROWSE_SESSION", os.environ.get("AGENT_BROWSER_SESSION", "default")),
20
+ "headed": False,
21
+ "timeout": int(os.environ.get("FROWSE_DEFAULT_TIMEOUT", os.environ.get("AGENT_BROWSER_DEFAULT_TIMEOUT", "15000"))),
22
+ "cdp": None,
23
+ "executable_path": None,
24
+ "user_agent": None,
25
+ "viewport": None,
26
+ "model_dir": os.environ.get("FROWSE_MODEL_DIR"),
27
+ }
28
+ rest: list[str] = []
29
+ i = 0
30
+ saw_double_dash = False
31
+ while i < len(argv):
32
+ tok = argv[i]
33
+ if tok == "--":
34
+ saw_double_dash = True
35
+ rest.extend(argv[i:])
36
+ break
37
+ if tok == "--json":
38
+ opts["json"] = True
39
+ i += 1
40
+ elif tok == "--headed":
41
+ opts["headed"] = True
42
+ i += 1
43
+ elif tok == "--session" and i + 1 < len(argv):
44
+ opts["session"] = argv[i + 1]
45
+ i += 2
46
+ elif tok == "--timeout" and i + 1 < len(argv):
47
+ opts["timeout"] = int(argv[i + 1])
48
+ i += 2
49
+ elif tok == "--cdp" and i + 1 < len(argv):
50
+ opts["cdp"] = argv[i + 1]
51
+ i += 2
52
+ elif tok == "--executable-path" and i + 1 < len(argv):
53
+ opts["executable_path"] = argv[i + 1]
54
+ i += 2
55
+ elif tok == "--user-agent" and i + 1 < len(argv):
56
+ opts["user_agent"] = argv[i + 1]
57
+ i += 2
58
+ elif tok == "--viewport" and i + 1 < len(argv):
59
+ opts["viewport"] = argv[i + 1]
60
+ i += 2
61
+ elif tok == "--model-dir" and i + 1 < len(argv):
62
+ opts["model_dir"] = argv[i + 1]
63
+ i += 2
64
+ else:
65
+ rest.append(tok)
66
+ i += 1
67
+ _ = saw_double_dash
68
+ return opts, rest
69
+
70
+
71
+ def _parse_fill_or_type(args: list[str], is_type: bool = False) -> dict[str, Any]:
72
+ clear = False
73
+ delay = 0
74
+ pos: list[str] = []
75
+ i = 0
76
+ while i < len(args):
77
+ tok = args[i]
78
+ if tok == "--":
79
+ pos.extend(args[i + 1 :])
80
+ break
81
+ if is_type and tok == "--clear":
82
+ clear = True
83
+ i += 1
84
+ elif is_type and tok == "--delay" and i + 1 < len(args):
85
+ delay = int(args[i + 1])
86
+ i += 2
87
+ else:
88
+ pos.append(tok)
89
+ i += 1
90
+ if len(pos) < 2:
91
+ raise ValueError("Usage: <selector> <text>")
92
+ res: dict[str, Any] = {"selector": pos[0], "text": " ".join(pos[1:])}
93
+ if is_type:
94
+ res["clear"] = clear
95
+ res["delay"] = delay
96
+ return res
97
+
98
+
99
+ def _parse_command(rest: list[str]) -> tuple[str, dict[str, Any]]:
100
+ if not rest:
101
+ raise ValueError("No command provided. Run `frowse --help` for usage.")
102
+
103
+ cmd = rest[0]
104
+ args = rest[1:]
105
+
106
+ # Aliases
107
+ alias_map = {
108
+ "goto": "open",
109
+ "navigate": "open",
110
+ "quit": "close",
111
+ "exit": "close",
112
+ "summary": "snapshot",
113
+ "folate": "query",
114
+ "key": "press",
115
+ }
116
+ cmd = alias_map.get(cmd, cmd)
117
+
118
+ if cmd == "open":
119
+ return "open", {"url": args[0] if args else None}
120
+
121
+ if cmd in ("back", "forward", "reload"):
122
+ return cmd, {}
123
+
124
+ if cmd == "close":
125
+ return "close", {"all": "--all" in args}
126
+
127
+ if cmd == "snapshot":
128
+ payload: dict[str, Any] = {"refs": False, "interactive": True, "max_chars": 2200}
129
+ i = 0
130
+ while i < len(args):
131
+ t = args[i]
132
+ if t in ("--refs", "--full"):
133
+ payload["refs"] = True
134
+ elif t in ("-i", "--interactive"):
135
+ payload["interactive"] = True
136
+ elif t == "--section" and i + 1 < len(args):
137
+ payload["section"] = args[i + 1]
138
+ i += 1
139
+ elif t == "--max-chars" and i + 1 < len(args):
140
+ payload["max_chars"] = int(args[i + 1])
141
+ i += 1
142
+ i += 1
143
+ return "snapshot", payload
144
+
145
+ if cmd == "query":
146
+ top_k = 3
147
+ prompt_parts: list[str] = []
148
+ i = 0
149
+ while i < len(args):
150
+ if args[i] == "--top-k" and i + 1 < len(args):
151
+ top_k = int(args[i + 1])
152
+ i += 2
153
+ else:
154
+ prompt_parts.append(args[i])
155
+ i += 1
156
+ if not prompt_parts:
157
+ raise ValueError("Usage: query <prompt> [--top-k N]")
158
+ return "query", {"prompt": " ".join(prompt_parts), "top_k": top_k}
159
+
160
+ if cmd == "read":
161
+ return "read", {"url": args[0] if args else None}
162
+
163
+ if cmd in ("click", "dblclick"):
164
+ payload = {}
165
+ pos: list[str] = []
166
+ i = 0
167
+ while i < len(args):
168
+ t = args[i]
169
+ if t == "--new-tab":
170
+ payload["new_tab"] = True
171
+ elif t == "--button" and i + 1 < len(args):
172
+ payload["button"] = args[i + 1]
173
+ i += 1
174
+ elif t == "--modifiers" and i + 1 < len(args):
175
+ mods = [m.strip() for m in args[i + 1].replace("+", ",").split(",") if m.strip()]
176
+ payload["modifiers"] = [
177
+ "Control" if m in ("ctrl", "control") else "Meta" if m in ("cmd", "command", "meta") else m.capitalize()
178
+ for m in mods
179
+ ]
180
+ i += 1
181
+ else:
182
+ pos.append(t)
183
+ i += 1
184
+ if not pos:
185
+ raise ValueError(f"Usage: {cmd} <selector>")
186
+ payload["selector"] = " ".join(pos)
187
+ return cmd, payload
188
+
189
+ if cmd == "fill":
190
+ return "fill", _parse_fill_or_type(args, is_type=False)
191
+
192
+ if cmd == "type":
193
+ return "type", _parse_fill_or_type(args, is_type=True)
194
+
195
+ if cmd == "press":
196
+ if not args:
197
+ raise ValueError("Usage: press <key>")
198
+ return "press", {"key": args[0]}
199
+
200
+ if cmd == "keyboard":
201
+ if len(args) < 2:
202
+ raise ValueError("Usage: keyboard <type|inserttext|down|up> <value>")
203
+ sub = args[0]
204
+ val = " ".join(args[1:])
205
+ if sub in ("type", "inserttext"):
206
+ return "keyboard", {"subcommand": sub, "text": val}
207
+ return "keyboard", {"subcommand": sub, "key": val}
208
+
209
+ if cmd in ("hover", "focus", "check", "uncheck", "scrollintoview", "highlight"):
210
+ if not args:
211
+ raise ValueError(f"Usage: {cmd} <selector>")
212
+ return cmd, {"selector": " ".join(args)}
213
+
214
+ if cmd == "select":
215
+ if len(args) < 2:
216
+ raise ValueError("Usage: select <selector> <value>")
217
+ return "select", {"selector": args[0], "value": " ".join(args[1:])}
218
+
219
+ if cmd == "scroll":
220
+ if not args:
221
+ raise ValueError("Usage: scroll <up|down|left|right> [px] [--selector <sel>]")
222
+ payload = {"direction": args[0], "px": 500}
223
+ i = 1
224
+ while i < len(args):
225
+ if args[i] == "--selector" and i + 1 < len(args):
226
+ payload["selector"] = args[i + 1]
227
+ i += 2
228
+ elif args[i].lstrip("-").isdigit():
229
+ payload["px"] = int(args[i])
230
+ i += 1
231
+ else:
232
+ i += 1
233
+ return "scroll", payload
234
+
235
+ if cmd == "drag":
236
+ if len(args) < 2:
237
+ raise ValueError("Usage: drag <src> <dst>")
238
+ return "drag", {"source": args[0], "target": args[1]}
239
+
240
+ if cmd == "upload":
241
+ if len(args) < 2:
242
+ raise ValueError("Usage: upload <selector> <files...>")
243
+ return "upload", {"selector": args[0], "files": args[1:]}
244
+
245
+ if cmd == "get":
246
+ if not args:
247
+ raise ValueError("Usage: get <text|html|value|attr|title|url|count|box|styles> [selector]")
248
+ prop = args[0]
249
+ if prop in ("title", "url"):
250
+ return "get", {"prop": prop}
251
+ if prop == "attr":
252
+ if len(args) < 3:
253
+ raise ValueError("Usage: get attr <selector> <attr>")
254
+ return "get", {"prop": "attr", "selector": args[1], "attr": args[2]}
255
+ if len(args) < 2:
256
+ raise ValueError(f"Usage: get {prop} <selector>")
257
+ return "get", {"prop": prop, "selector": " ".join(args[1:])}
258
+
259
+ if cmd == "is":
260
+ if len(args) < 2:
261
+ raise ValueError("Usage: is <visible|enabled|checked> <selector>")
262
+ return "is", {"prop": args[0], "selector": " ".join(args[1:])}
263
+
264
+ if cmd == "find":
265
+ if len(args) < 3:
266
+ raise ValueError("Usage: find <by> <value> <action> [action_value]")
267
+ by = args[0]
268
+ exact = "--exact" in args
269
+ name = None
270
+ clean_args: list[str] = []
271
+ i = 1
272
+ while i < len(args):
273
+ if args[i] == "--exact":
274
+ i += 1
275
+ elif args[i] == "--name" and i + 1 < len(args):
276
+ name = args[i + 1]
277
+ i += 2
278
+ else:
279
+ clean_args.append(args[i])
280
+ i += 1
281
+ if by == "nth":
282
+ if len(clean_args) < 3:
283
+ raise ValueError("Usage: find nth <n> <sel> <action> [value]")
284
+ return "find", {
285
+ "by": by,
286
+ "index": int(clean_args[0]),
287
+ "value": clean_args[1],
288
+ "find_action": clean_args[2],
289
+ "action_value": " ".join(clean_args[3:]) if len(clean_args) > 3 else None,
290
+ "exact": exact,
291
+ "name": name,
292
+ }
293
+ return "find", {
294
+ "by": by,
295
+ "value": clean_args[0],
296
+ "find_action": clean_args[1],
297
+ "action_value": " ".join(clean_args[2:]) if len(clean_args) > 2 else None,
298
+ "exact": exact,
299
+ "name": name,
300
+ }
301
+
302
+ if cmd == "wait":
303
+ if not args:
304
+ raise ValueError("Usage: wait <selector|ms|--text|--url|--load|--fn>")
305
+ payload = {}
306
+ i = 0
307
+ pos = []
308
+ while i < len(args):
309
+ t = args[i]
310
+ if t == "--text" and i + 1 < len(args):
311
+ payload["text"] = args[i + 1]
312
+ i += 2
313
+ elif t == "--url" and i + 1 < len(args):
314
+ payload["url"] = args[i + 1]
315
+ i += 2
316
+ elif t == "--load" and i + 1 < len(args):
317
+ payload["load"] = args[i + 1]
318
+ i += 2
319
+ elif t == "--fn" and i + 1 < len(args):
320
+ payload["fn"] = args[i + 1]
321
+ i += 2
322
+ elif t == "--state" and i + 1 < len(args):
323
+ payload["state"] = args[i + 1]
324
+ i += 2
325
+ else:
326
+ pos.append(t)
327
+ i += 1
328
+ if pos and not any(k in payload for k in ("text", "url", "load", "fn")):
329
+ if len(pos) == 1 and pos[0].isdigit():
330
+ payload["ms"] = int(pos[0])
331
+ else:
332
+ payload["selector"] = " ".join(pos)
333
+ return "wait", payload
334
+
335
+ if cmd == "screenshot":
336
+ full = "--full" in args
337
+ pos = [a for a in args if not a.startswith("--")]
338
+ return "screenshot", {"path": pos[0] if pos else None, "full": full}
339
+
340
+ if cmd == "pdf":
341
+ if not args:
342
+ raise ValueError("Usage: pdf <path>")
343
+ return "pdf", {"path": args[0]}
344
+
345
+ if cmd == "eval":
346
+ if not args:
347
+ raise ValueError("Usage: eval <js>")
348
+ return "eval", {"js": " ".join(args)}
349
+
350
+ if cmd == "tab":
351
+ if not args or args[0] == "list":
352
+ return "tab", {"subcommand": "list"}
353
+ if args[0] == "new":
354
+ label = None
355
+ url = None
356
+ i = 1
357
+ while i < len(args):
358
+ if args[i] == "--label" and i + 1 < len(args):
359
+ label = args[i + 1]
360
+ i += 2
361
+ else:
362
+ url = args[i]
363
+ i += 1
364
+ return "tab", {"subcommand": "new", "label": label, "url": url}
365
+ if args[0] == "close":
366
+ return "tab", {"subcommand": "close", "target": args[1] if len(args) > 1 else None}
367
+ return "tab", {"subcommand": "switch", "target": args[0]}
368
+
369
+ if cmd == "frame":
370
+ if not args:
371
+ raise ValueError("Usage: frame <selector|@ref|main>")
372
+ return "frame", {"selector": " ".join(args)}
373
+
374
+ if cmd == "cookies":
375
+ if not args or args[0] == "get":
376
+ return "cookies", {"op": "get"}
377
+ if args[0] == "clear":
378
+ return "cookies", {"op": "clear"}
379
+ if args[0] == "set" and len(args) >= 3:
380
+ return "cookies", {
381
+ "op": "set",
382
+ "name": args[1],
383
+ "value": args[2],
384
+ "http_only": "--http-only" in args or "--httpOnly" in args,
385
+ }
386
+ raise ValueError("Usage: cookies [get|set <name> <val>|clear]")
387
+
388
+ if cmd == "storage":
389
+ if not args or args[0] not in ("local", "session"):
390
+ raise ValueError("Usage: storage <local|session> [key|set <k> <v>|clear]")
391
+ kind = args[0]
392
+ sub = args[1:]
393
+ if not sub:
394
+ return "storage", {"kind": kind, "op": "get"}
395
+ if sub[0] == "clear":
396
+ return "storage", {"kind": kind, "op": "clear"}
397
+ if sub[0] == "set" and len(sub) >= 3:
398
+ return "storage", {"kind": kind, "op": "set", "key": sub[1], "value": sub[2]}
399
+ return "storage", {"kind": kind, "op": "get", "key": sub[0]}
400
+
401
+ if cmd == "dialog":
402
+ if not args:
403
+ raise ValueError("Usage: dialog <accept [text]|dismiss|status>")
404
+ op = args[0]
405
+ return "dialog", {"op": op, "text": " ".join(args[1:]) if len(args) > 1 else None}
406
+
407
+ if cmd in ("console", "errors"):
408
+ return cmd, {"clear": "--clear" in args}
409
+
410
+ raise ValueError(f"Unknown command: {cmd}")
411
+
412
+
413
+ def _format_plain(action: str, data: dict[str, Any]) -> str:
414
+ if "summary" in data:
415
+ out = data["summary"]
416
+ if data.get("warning"):
417
+ out = f"[Warning: {data['warning']}]\n{out}"
418
+ return out
419
+ if action == "query":
420
+ lines = []
421
+ for i, m in enumerate(data.get("matches", []), 1):
422
+ lines.append(f"{i}. [{m['score']:.3f}] {m['selector']} | {m['element']}")
423
+ return "\n".join(lines) if lines else "No matching elements found."
424
+ if action == "open":
425
+ return f"Opened {data.get('url', '')} ({data.get('title', '')})"
426
+ if action == "read":
427
+ return data.get("text", "")
428
+ if action == "get":
429
+ for k in ("text", "html", "value", "title", "url", "count"):
430
+ if k in data:
431
+ return str(data[k])
432
+ return json.dumps(data, indent=2)
433
+ if action == "is":
434
+ for k in ("visible", "enabled", "checked"):
435
+ if k in data:
436
+ return "true" if data[k] else "false"
437
+ if action == "eval":
438
+ res = data.get("result")
439
+ return json.dumps(res) if isinstance(res, (dict, list)) else str(res)
440
+ if action == "tab" and "tabs" in data:
441
+ lines = []
442
+ for t in data["tabs"]:
443
+ mark = "*" if t["active"] else " "
444
+ lbl = f" ({t['label']})" if t.get("label") else ""
445
+ lines.append(f"{mark} {t['tabId']}{lbl}: {t['url']} - {t['title']}")
446
+ return "\n".join(lines)
447
+ if data.get("resolvedBy") == "folate":
448
+ return f"ok [folate: {data.get('selector')} ({data.get('score')})]"
449
+ return json.dumps(data)
450
+
451
+
452
+ def _print_help() -> None:
453
+ print(
454
+ f"""frowse {__version__} — Drop-in replacement for agent-browser powered by Folate
455
+
456
+ Usage: frowse [global-options] <command> [args...]
457
+
458
+ Core Workflow:
459
+ open <url> Launch browser & navigate (aliases: goto, navigate)
460
+ snapshot [--section <sel>] Lightweight Folate-ready DOM summary (alias: summary)
461
+ snapshot --refs Legacy @eN refs mode for compatibility
462
+ query <prompt> [--top-k N] Query Folate directly for ranked CSS/XPath selectors
463
+ click <sel|prompt> Click element (CSS, XPath, @eN, or Folate prompt)
464
+ fill <sel|prompt> <text> Clear and fill input
465
+ type <sel|prompt> <text> Type into element
466
+ select <sel|prompt> <val> Select dropdown option
467
+ get <text|html|value|attr|title|url|count|box|styles> [sel|prompt]
468
+ is <visible|enabled|checked> <sel|prompt>
469
+ wait <sel|ms|--text|--url|--load|--fn>
470
+ screenshot [path] [--full]
471
+ eval <js>
472
+ tab [new|close|<id|label>]
473
+ frame <sel|@ref|main>
474
+ skills [list|show|install] Manage bundled Folate & browser skills
475
+ close [--all]
476
+
477
+ Global Options:
478
+ --json Output structured JSON
479
+ --session <name> Isolated session name (default: default)
480
+ --headed Show browser window
481
+ --timeout <ms> Default timeout in ms (default: 15000)
482
+ --cdp <port|url> Connect to existing browser over CDP
483
+ --viewport <w>x<h> Viewport size (default: 1280x800)
484
+ --model-dir <path> Local Folate ONNX model directory
485
+
486
+ Tip: Avoid `get text body`; use `snapshot --section main`, targeted `get text <prompt|sel>`, or compact `eval`."""
487
+ )
488
+
489
+
490
+ def _run_skills_cli(args: list[str]) -> tuple[dict[str, Any], str]:
491
+ sub = args[0] if args else "list"
492
+ rest = args[1:]
493
+ if sub == "list":
494
+ items = list_skills()
495
+ plain = "\n".join(f"{s['name']}: {s['description']}" for s in items)
496
+ return {"skills": items}, plain
497
+ if sub == "show":
498
+ if not rest:
499
+ raise ValueError("Usage: skills show <name>")
500
+ content = read_skill(rest[0])
501
+ return {"name": rest[0], "content": content}, content
502
+ if sub == "install":
503
+ target = "agents"
504
+ global_install = False
505
+ dest_dir = None
506
+ names: list[str] = []
507
+ i = 0
508
+ while i < len(rest):
509
+ t = rest[i]
510
+ if t == "--global":
511
+ global_install = True
512
+ i += 1
513
+ elif t == "--target" and i + 1 < len(rest):
514
+ target = rest[i + 1]
515
+ i += 2
516
+ elif t == "--dir" and i + 1 < len(rest):
517
+ dest_dir = rest[i + 1]
518
+ i += 2
519
+ else:
520
+ names.append(t)
521
+ i += 1
522
+ installed = install_skills(
523
+ target=target,
524
+ global_install=global_install,
525
+ names=names or None,
526
+ dest_dir=dest_dir,
527
+ )
528
+ plain = "\n".join(f"Installed {x['name']} -> {x['path']}" for x in installed)
529
+ return {"installed": installed}, plain
530
+ raise ValueError("Usage: skills [list|show <name>|install [--target agents|claude|codex|cursor] [--global] [names...]]")
531
+
532
+
533
+ def main(argv: list[str] | None = None) -> None:
534
+ raw = sys.argv[1:] if argv is None else argv
535
+ if not raw or raw[0] in ("-h", "--help", "help"):
536
+ _print_help()
537
+ sys.exit(0 if raw else 1)
538
+ if raw[0] in ("-V", "--version"):
539
+ print(f"frowse {__version__}")
540
+ sys.exit(0)
541
+
542
+ opts, rest = _split_global_flags(raw)
543
+ try:
544
+ if rest and rest[0] == "skills":
545
+ data, plain = _run_skills_cli(rest[1:])
546
+ if opts["json"]:
547
+ print(json.dumps({"ok": True, "data": data}))
548
+ else:
549
+ print(plain)
550
+ return
551
+
552
+ action, payload = _parse_command(rest)
553
+ if action == "close" and payload.get("all"):
554
+ closed = close_all_sessions()
555
+ data = {"closed": closed}
556
+ else:
557
+ daemon_opts = {
558
+ "headed": opts["headed"],
559
+ "executable_path": opts["executable_path"],
560
+ "cdp_url": opts["cdp"],
561
+ "timeout_ms": opts["timeout"],
562
+ "user_agent": opts["user_agent"],
563
+ "viewport": opts["viewport"],
564
+ "model_dir": opts["model_dir"],
565
+ }
566
+ data = send_command(
567
+ session_name=opts["session"],
568
+ action=action,
569
+ args=payload,
570
+ daemon_opts=daemon_opts,
571
+ )
572
+
573
+ if opts["json"]:
574
+ print(json.dumps({"ok": True, "data": data}))
575
+ else:
576
+ print(_format_plain(action, data))
577
+ except Exception as exc:
578
+ if opts["json"]:
579
+ print(json.dumps({"ok": False, "error": str(exc)}))
580
+ else:
581
+ print(f"Error: {exc}", file=sys.stderr)
582
+ sys.exit(1)
583
+
584
+
585
+ if __name__ == "__main__":
586
+ main()