File size: 8,535 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
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
"""Workflow specifications: the data model for JSON-defined browser workflows.



A workflow is an ordered list of steps; each step calls ONE registry tool

(``browser_automation_agent.tools.registry``) through the deterministic

executor, so every workflow step inherits the same validation, risk gate, URL

policy, timeout and structured envelope as a chat tool call — workflows cannot

bypass the safety pipeline.



Steps capture results into named variables (``save``) that later steps

substitute (``{{var}}``), and can assert post-conditions (``expect``) so a

workflow fails loudly when the browser did not do what was asked instead of

silently continuing.

"""
from __future__ import annotations

import json
import re
from pathlib import Path
from typing import Any

from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator

_VAR_PATTERN = re.compile(r"\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}")

# The registry tool vocabulary a workflow step may call. Aliases (executor
# TOOL_ALIASES) are accepted too and resolved by the executor itself.
KNOWN_TOOLS: frozenset[str] = frozenset({
    "browser_capabilities", "tab_open", "tab_list", "tab_select", "tab_close",
    "navigate", "observe", "click", "type", "select_option", "scroll",
    "press_key", "extract_text", "screenshot", "wait_for", "http_fetch",
    "web_search",
})


class WorkflowStep(BaseModel):
    """One registry-tool call inside a workflow."""

    model_config = ConfigDict(extra="forbid")

    tool: str = Field(min_length=1, description="Registry tool name (executor aliases accepted).")
    name: str | None = Field(default=None, description="Human-readable step label.")
    args: dict[str, Any] = Field(default_factory=dict, description="Tool arguments; {{var}} substituted.")
    save: dict[str, str] = Field(
        default_factory=dict,
        description="Map variable name -> envelope JSON path (e.g. 'data.snapshot_id').",
    )
    find: dict[str, str] | None = Field(
        default=None,
        description=(
            "Resolve index+snapshot_id for click/type/select_option from the "
            "latest observe: {'role': 'textbox', 'text': 'Search'} (both "
            "matchers are case-insensitive substrings; text also matches "
            "accessible_name)."
        ),
    )
    expect_ok: bool = Field(default=True, description="Require the envelope ok=true.")
    expect: dict[str, Any] = Field(
        default_factory=dict,
        description="Map envelope JSON path -> expected value (strings match by substring).",
    )
    continue_on_error: bool = Field(
        default=False, description="Keep running later steps when this step fails."
    )

    @field_validator("tool")
    @classmethod
    def _tool_must_be_known(cls, value: str) -> str:
        if value not in KNOWN_TOOLS:
            raise ValueError(
                f"unknown workflow tool '{value}' — must be one of: "
                + ", ".join(sorted(KNOWN_TOOLS))
            )
        return value

    @field_validator("save")
    @classmethod
    def _save_paths_are_envelope_paths(cls, value: dict[str, str]) -> dict[str, str]:
        for var, path in value.items():
            if not _VAR_PATH.fullmatch(path):
                raise ValueError(
                    f"save path '{path}' is not an envelope path — expected "
                    "'data.<field>' or 'data.<field>.<index>' style"
                )
            if not var.replace("_", "").isalnum() or not var:
                raise ValueError(f"save variable name '{var}' is invalid")
        return value

    @model_validator(mode="after")
    def _find_only_for_element_tools(self) -> WorkflowStep:
        if self.find is not None and self.tool not in {"click", "type", "select_option"}:
            raise ValueError(
                f"'find' applies to click/type/select_option, not '{self.tool}'"
            )
        return self


class WorkflowSpec(BaseModel):
    """A complete workflow definition (the JSON document)."""

    model_config = ConfigDict(extra="forbid")

    name: str = Field(min_length=1, max_length=80)
    description: str = Field(default="", max_length=2000)
    engine: str | None = Field(
        default=None,
        description="Suggested engine: chromium, chrome, msedge, firefox. The "
        "runner's --engine flag overrides it.",
    )
    variables: dict[str, str] = Field(
        default_factory=dict,
        description="Documented {{variables}}: name -> description (defaults belong in the JSON itself).",
    )
    steps: list[WorkflowStep] = Field(min_length=1)

    @model_validator(mode="after")
    def _documented_variables_match_usage(self) -> WorkflowSpec:
        used = _used_variables(self.steps)
        for var in self.variables:
            if var not in used:
                raise ValueError(
                    f"documented variable '{var}' is never used in a step"
                )
        return self


# data.tabs.0.tab_id style paths: segments are words or non-negative integers.
_VAR_PATH = re.compile(r"^(?:[A-Za-z_][A-Za-z0-9_]*|\d+)(?:\.(?:[A-Za-z_][A-Za-z0-9_]*|\d+))*$")


def _used_variables(steps: list[WorkflowStep]) -> set[str]:
    used: set[str] = set()
    for step in steps:
        used.update(_scan_values(step.args))
    return used


def _scan_values(value: Any) -> set[str]:
    found: set[str] = set()
    if isinstance(value, str):
        found.update(m.group(1) for m in _VAR_PATTERN.finditer(value))
    elif isinstance(value, dict):
        for item in value.values():
            found.update(_scan_values(item))
    elif isinstance(value, (list, tuple)):
        for item in value:
            found.update(_scan_values(item))
    return found


def substitute(value: Any, variables: dict[str, Any]) -> Any:
    """Recursively replace ``{{var}}`` in every string with the variable value."""
    if isinstance(value, str):
        def _replace(match: re.Match[str]) -> str:
            var = match.group(1)
            if var not in variables:
                raise KeyError(f"workflow variable '{var}' is not defined")
            return str(variables[var])
        return _VAR_PATTERN.sub(_replace, value)
    if isinstance(value, dict):
        return {k: substitute(v, variables) for k, v in value.items()}
    if isinstance(value, list):
        return [substitute(item, variables) for item in value]
    return value


def resolve_path(envelope: dict[str, Any], path: str) -> Any:
    """Read a dotted/int path from a tool envelope (``data.tabs.0.tab_id``)."""
    current: Any = envelope
    for segment in path.split("."):
        if isinstance(current, dict) and segment in current:
            current = current[segment]
        elif isinstance(current, list) and segment.isdigit() and int(segment) < len(current):
            current = current[int(segment)]
        else:
            raise KeyError(f"path '{path}' not found in the step envelope")
    return current


def matches(actual: Any, expected: Any) -> bool:
    """Expectation matcher: strings match by substring, everything else by ==."""
    if isinstance(expected, str) and isinstance(actual, str):
        return expected.lower() in actual.lower()
    return bool(actual == expected)


class BuiltinLibrary:
    """Discovery + loading for the JSON workflows shipped in ``library/``."""

    def __init__(self, directory: Path | None = None) -> None:
        self.directory = directory or (Path(__file__).parent / "library")

    def list_names(self) -> list[str]:
        return sorted(p.stem for p in self.directory.glob("*.json"))

    def load(self, name_or_path: str | Path) -> tuple[WorkflowSpec, Path | None]:
        """Load a builtin by name or any workflow from a JSON file path."""
        candidate = Path(name_or_path)
        if candidate.suffix == ".json" or candidate.exists():
            source = candidate
        else:
            source = self.directory / f"{name_or_path}.json"
        if not source.exists():
            known = ", ".join(self.list_names()) or "(none)"
            raise FileNotFoundError(
                f"workflow '{name_or_path}' not found — builtin workflows: {known}"
            )
        raw = json.loads(source.read_text(encoding="utf-8"))
        return WorkflowSpec(**raw), (None if source.parent == self.directory else source)