Spaces:
Running
Running
File size: 6,232 Bytes
6eb6c4e | 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 | """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'}")
@app.command("list")
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)
@app.command("show")
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
@app.command("run")
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)
)
|