Spaces:
Running
Running
Download src/browser_automation_agent/workflows/cli.py from sitcod3/dracull-agent: direct link, hf CLI and curl.
- Browser
- Download file 6.23 kB
-
https://huggingface.co/spaces/sitcod3/dracull-agent/resolve/main/src/browser_automation_agent/workflows/cli.py
- Command line
-
hf download hf://spaces/sitcod3/dracull-agent/src/browser_automation_agent/workflows/cli.py
-
curl -L -o cli.py https://huggingface.co/spaces/sitcod3/dracull-agent/resolve/main/src/browser_automation_agent/workflows/cli.py
6.23 kB
| """CLI for workflow orchestration: list / show / run JSON browser workflows. | |
| Wired into the backend CLI as ``python -m browser_automation_agent workflow ...`` | |
| (see main.py). Runs on the Playwright stack (ChatBrowserSession through the | |
| tool executor) by default, or on the Selenium fallback driver with | |
| ``--driver selenium``. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import json | |
| from pathlib import Path | |
| from typing import Annotated, Any | |
| import typer | |
| from rich.console import Console | |
| from rich.table import Table | |
| from .engine import WorkflowReport, WorkflowRunner | |
| from .models import BuiltinLibrary | |
| app = typer.Typer( | |
| name="workflow", | |
| help="Run JSON-defined browser workflows (open, edit, search, extract, multi-tab).", | |
| ) | |
| console = Console() | |
| _library = BuiltinLibrary() | |
| def _print_report(report: WorkflowReport, verbose: bool) -> None: | |
| table = Table(title=f"workflow '{report.workflow}' — {'PASS' if report.ok else 'FAIL'}") | |
| table.add_column("#") | |
| table.add_column("step") | |
| table.add_column("tool") | |
| table.add_column("ok") | |
| table.add_column("s") | |
| for step in report.steps: | |
| table.add_row( | |
| str(step.index), | |
| step.label, | |
| step.tool, | |
| "[green]ok[/green]" if step.ok else "[red]FAIL[/red]", | |
| f"{step.seconds:.1f}", | |
| ) | |
| console.print(table) | |
| if verbose or not report.ok: | |
| for step in report.steps: | |
| if step.ok and not verbose: | |
| continue | |
| error = step.error or "" | |
| console.print(f" [dim]step {step.index} ({step.tool})[/dim] {error or 'ok'}") | |
| def list_workflows() -> None: | |
| """List the builtin workflows shipped with the backend.""" | |
| table = Table(title="builtin workflows") | |
| table.add_column("name") | |
| table.add_column("description") | |
| for name in _library.list_names(): | |
| spec, _ = _library.load(name) | |
| table.add_row(name, spec.description[:90] + ("…" if len(spec.description) > 90 else "")) | |
| console.print(table) | |
| def show_workflow(name: str) -> None: | |
| """Print one workflow's JSON (builtin name or path).""" | |
| spec, source = _library.load(name) | |
| console.print_json(json.dumps(spec.model_dump(), indent=2)) | |
| if source is not None: | |
| console.print(f"[dim](file: {source})[/dim]") | |
| def _run_sync( | |
| name_or_path: str, | |
| variables: dict[str, str], | |
| driver: str, | |
| engine: str | None, | |
| headed: bool, | |
| report_path: Path | None, | |
| verbose: bool, | |
| ) -> int: | |
| spec, source = _library.load(name_or_path) | |
| if source is None: | |
| console.print(f"[dim]builtin workflow:[/dim] {spec.name}") | |
| else: | |
| console.print(f"[dim]workflow file:[/dim] {source}") | |
| console.print(f"[dim]driver:[/dim] {driver} [dim]engine:[/dim] {engine or 'default'}") | |
| async def _run() -> WorkflowReport: | |
| if driver == "selenium": | |
| from .selenium_driver import SeleniumWorkflowDriver | |
| chosen = engine or spec.engine or "chrome" | |
| instance: Any = SeleniumWorkflowDriver(engine=chosen, headless=not headed) | |
| await instance.start() | |
| runner = WorkflowRunner( | |
| executor=lambda browser, tool, args: instance.run_tool(tool, args) | |
| ) | |
| try: | |
| return await runner.run(instance, spec, variables) | |
| finally: | |
| await instance.stop() | |
| # Playwright path: the SAME ChatBrowserSession the chat loop drives. | |
| from ..browser.manager import browser_manager | |
| from ..chat_tools import ChatBrowserSession | |
| from ..config import settings | |
| if engine: | |
| settings.browser_channel = engine | |
| settings.browser_headless = not headed | |
| await browser_manager.start() | |
| session = ChatBrowserSession(browser_manager) | |
| runner = WorkflowRunner() | |
| try: | |
| return await runner.run(session, spec, variables) | |
| finally: | |
| await browser_manager.stop() | |
| try: | |
| report = asyncio.run(_run()) | |
| except FileNotFoundError as exc: | |
| console.print(f"[red]{exc}[/red]") | |
| raise typer.Exit(2) | |
| except Exception as exc: # noqa: BLE001 — CLI boundary: print, don't dump | |
| console.print(f"[red]workflow crashed: {type(exc).__name__}: {exc}[/red]") | |
| raise typer.Exit(1) | |
| _print_report(report, verbose) | |
| if report_path is not None: | |
| report_path.write_text( | |
| json.dumps(report.to_dict(), indent=2, default=str), encoding="utf-8" | |
| ) | |
| console.print(f"[dim]report written to {report_path}[/dim]") | |
| return 0 if report.ok else 1 | |
| def run_workflow( | |
| name: str = typer.Argument(help="Builtin workflow name or path to a workflow JSON file."), | |
| var: Annotated[ | |
| list[str] | None, typer.Option(help="Workflow variable, KEY=VALUE. Repeatable.") | |
| ] = None, | |
| driver: Annotated[ | |
| str, typer.Option(help="playwright (bundled engines) or selenium (installed browsers).") | |
| ] = "playwright", | |
| engine: Annotated[ | |
| str | None, typer.Option(help="chromium | chrome | msedge | firefox (overrides settings + spec).") | |
| ] = None, | |
| headed: Annotated[ | |
| bool, typer.Option(help="Run with a visible window (Firefox stays headless: GPU-spawn guard).") | |
| ] = False, | |
| report: Annotated[ | |
| Path | None, typer.Option(help="Write the full JSON run report to this path.") | |
| ] = None, | |
| verbose: Annotated[ | |
| bool, typer.Option(help="Print every step envelope summary.") | |
| ] = False, | |
| ) -> None: | |
| """Run a workflow and print the step table.""" | |
| variables: dict[str, str] = {} | |
| for item in var or []: | |
| key, sep, value = item.partition("=") | |
| if not sep or not key.strip(): | |
| console.print(f"[red]--var expects KEY=VALUE, got '{item}'[/red]") | |
| raise typer.Exit(2) | |
| variables[key.strip()] = value | |
| raise typer.Exit( | |
| _run_sync(name, variables, driver.lower(), engine, headed, report, verbose) | |
| ) | |