sitcod3's picture
sync: backend/src -> Space (browser settings autosave + writable settings file)
6eb6c4e verified
Raw History Blame Contribute Delete
14.8 kB
"""LangGraph-based orchestration for multi-step browser automation workflows."""
import uuid
from collections.abc import Awaitable, Callable
from typing import Any
from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import END, StateGraph
from pydantic import BaseModel, Field
from ..browser.manager import browser_manager
from ..config import settings
from ..hitl.handler import hitl_handler
from ..llm.provider import TaskPlanner, llm_provider
from ..protocol import (
ActionType,
ErrorMessage,
HITLActionType,
SessionStatus,
TaskCompletedMessage,
TaskDefinition,
TaskFailedMessage,
TaskProgressMessage,
TaskStep,
)
ProgressCallback = Callable[[Any], Awaitable[None]]
class WorkflowState(BaseModel):
"""State for the LangGraph workflow."""
session_id: str
task: TaskDefinition
context_id: str | None = None
current_step_index: int = 0
step_results: list[dict[str, Any]] = Field(default_factory=list)
status: SessionStatus = SessionStatus.CREATED
error: str | None = None
hitl_request_id: str | None = None
hitl_pending: bool = False
hitl_response: dict[str, Any] | None = None
# Step indexes the human already approved, so a deferred step resumes
# instead of asking for confirmation forever.
hitl_approved_steps: list[int] = Field(default_factory=list)
class WorkflowOrchestrator:
"""Orchestrates browser automation tasks using LangGraph."""
def __init__(self) -> None:
self.planner = TaskPlanner(llm_provider)
self.checkpointer = MemorySaver()
self.graph: Any = self._build_graph()
self._progress_callbacks: dict[str, ProgressCallback] = {}
def _build_graph(self) -> Any:
"""Build the LangGraph workflow."""
workflow = StateGraph(WorkflowState)
# Nodes
workflow.add_node("plan", self._plan_node)
workflow.add_node("execute_step", self._execute_step_node)
workflow.add_node("check_hitl", self._check_hitl_node)
workflow.add_node("handle_error", self._handle_error_node)
workflow.add_node("complete", self._complete_node)
# Edges
workflow.set_entry_point("plan")
workflow.add_edge("plan", "execute_step")
workflow.add_conditional_edges(
"execute_step",
self._should_continue,
{
"continue": "execute_step",
"hitl": "check_hitl",
"error": "handle_error",
"complete": "complete",
},
)
workflow.add_conditional_edges(
"check_hitl",
lambda state: "error" if state.error else "execute",
{
"execute": "execute_step",
"error": "handle_error",
},
)
workflow.add_edge("handle_error", "complete")
workflow.add_edge("complete", END)
return workflow.compile(checkpointer=self.checkpointer)
async def _plan_node(self, state: WorkflowState) -> WorkflowState:
"""Plan the task steps using LLM."""
if not state.task.steps:
state.task.steps = await self.planner.plan_task(state.task)
state.status = SessionStatus.RUNNING
await self._update_session(state.session_id, state.status)
return state
async def _execute_step_node(self, state: WorkflowState) -> WorkflowState:
"""Execute the current step, deferring sensitive actions to HITL."""
if state.current_step_index >= len(state.task.steps):
return state
step = state.task.steps[state.current_step_index]
# Sensitive step: pause once and let the human decide. Once approved,
# the index is recorded in hitl_approved_steps so the retry executes
# the step instead of requesting confirmation again.
if self._requires_hitl(step) and state.current_step_index not in state.hitl_approved_steps:
state.hitl_pending = True
state.hitl_request_id = str(uuid.uuid4())
await self._update_session(
state.session_id,
SessionStatus.WAITING_HITL,
current_task=step.action.value,
task_progress=state.current_step_index / len(state.task.steps),
)
return state
try:
await self._emit_progress(
state.session_id,
step.action.value,
f"Executing: {step.action.value}",
state.current_step_index / len(state.task.steps),
)
result = await browser_manager.execute_step(state.session_id, step)
state.step_results.append(
{
"step_index": state.current_step_index,
"action": step.action.value,
"result": result,
}
)
state.current_step_index += 1
except Exception as exc:
state.error = str(exc)
state.status = SessionStatus.FAILED
raise
return state
async def _check_hitl_node(self, state: WorkflowState) -> WorkflowState:
"""Block on the HITL broker until the pending request is resolved.
The dashboard (or native host) answers through the shared broker, so
the graph task can simply await the decision. A timeout denies.
"""
if not state.hitl_pending or state.current_step_index >= len(state.task.steps):
return state
step = state.task.steps[state.current_step_index]
request_id = state.hitl_request_id or str(uuid.uuid4())
hitl_type = self._get_hitl_type(step) or HITLActionType.CUSTOM
response = await hitl_handler.request_confirmation(
session_id=state.session_id,
action_type=hitl_type,
title=f"Confirm {hitl_type.value}",
message=f"The automation needs your confirmation to {step.action.value}",
details={
"step": step.model_dump(mode="json"),
"step_index": state.current_step_index,
"request_id": request_id,
},
timeout=settings.hitl_timeout,
request_id=request_id,
)
state.hitl_response = {"approved": response.approved, "data": response.data}
state.hitl_pending = False
if response.approved:
state.hitl_approved_steps.append(state.current_step_index)
state.hitl_request_id = None
await self._update_session(
state.session_id,
SessionStatus.RUNNING,
current_task=step.action.value,
task_progress=state.current_step_index / len(state.task.steps),
)
else:
state.hitl_request_id = None
state.status = SessionStatus.FAILED
reason = (response.data or {}).get("reason", "denied")
state.error = f"HITL request {reason}: the action was not approved"
return state
async def _handle_error_node(self, state: WorkflowState) -> WorkflowState:
"""Handle workflow error."""
await self._emit_error(state.session_id, state.error or "Unknown error")
state.status = SessionStatus.FAILED
await self._update_session(state.session_id, state.status, error=state.error)
return state
async def _complete_node(self, state: WorkflowState) -> WorkflowState:
"""Complete the workflow."""
if state.status != SessionStatus.FAILED:
state.status = SessionStatus.COMPLETED
await self._update_session(state.session_id, state.status)
if state.status == SessionStatus.COMPLETED:
await self._emit_completed(state.session_id, state.step_results)
else:
await self._emit_failed(state.session_id, state.error or "Failed")
return state
def _should_continue(self, state: WorkflowState) -> str:
"""Determine next step."""
if state.error:
return "error"
if state.hitl_pending:
return "hitl"
if state.current_step_index >= len(state.task.steps):
return "complete"
return "continue"
def _requires_hitl(self, step: TaskStep) -> bool:
"""Check if a step requires human confirmation.
Sensitive actions are identified intrinsically from the action and
selector. Only an explicit ``sensitive: false`` opt-out bypasses that
protection; missing or partial metadata must never disable HITL.
"""
if step.metadata.get("sensitive") is False:
return False
if step.metadata.get("sensitive") is True:
return True
selector = (step.selector or "").lower()
if step.action == ActionType.TYPE and "password" in selector:
return True
if step.action == ActionType.CLICK and "payment" in selector:
return True
return step.action in {
ActionType.UPLOAD_FILE,
ActionType.DOWNLOAD_FILE,
ActionType.FORM_SUBMIT,
}
def _get_hitl_type(self, step: TaskStep) -> HITLActionType | None:
"""Get HITL type for a step."""
requested = step.metadata.get("hitl_type")
if requested:
try:
return HITLActionType(str(requested))
except ValueError:
return HITLActionType.CUSTOM
selector = (step.selector or "").lower()
if step.action == ActionType.TYPE and "password" in selector:
return HITLActionType.AUTHENTICATION
if step.action == ActionType.CLICK and "payment" in selector:
return HITLActionType.PAYMENT
if step.action == ActionType.DOWNLOAD_FILE:
return HITLActionType.DOWNLOAD
if step.action == ActionType.FORM_SUBMIT:
return HITLActionType.FORM_SUBMIT
return HITLActionType.CUSTOM
async def _emit_progress(
self,
session_id: str,
step: str,
message: str,
progress: float,
) -> None:
"""Emit progress update."""
callback = self._progress_callbacks.get(session_id)
if callback:
await callback(
TaskProgressMessage(
task_id=session_id,
session_id=session_id,
step=step,
message=message,
progress=progress,
)
)
async def _emit_completed(self, session_id: str, results: list[dict[str, Any]]) -> None:
"""Emit completion."""
callback = self._progress_callbacks.get(session_id)
if callback:
await callback(
TaskCompletedMessage(
task_id=session_id,
session_id=session_id,
result={"steps": results},
)
)
async def _emit_failed(self, session_id: str, error: str) -> None:
"""Emit failure."""
callback = self._progress_callbacks.get(session_id)
if callback:
await callback(
TaskFailedMessage(
task_id=session_id,
session_id=session_id,
error=error,
)
)
async def _emit_error(self, session_id: str, error: str) -> None:
"""Emit error."""
callback = self._progress_callbacks.get(session_id)
if callback:
await callback(
ErrorMessage(
code="WORKFLOW_ERROR",
message=error,
session_id=session_id,
)
)
async def _update_session(
self,
session_id: str,
status: SessionStatus,
current_task: str | None = None,
task_progress: float | None = None,
url: str | None = None,
error: str | None = None,
) -> None:
"""Update session status in browser manager."""
await browser_manager.update_session_status(
session_id,
status,
current_task,
task_progress,
url,
error,
)
def register_progress_callback(
self,
session_id: str,
callback: ProgressCallback,
) -> None:
"""Register a callback for progress updates."""
self._progress_callbacks[session_id] = callback
def unregister_progress_callback(self, session_id: str) -> None:
"""Unregister progress callback."""
self._progress_callbacks.pop(session_id, None)
async def run_task(
self,
session_id: str,
task: TaskDefinition,
context_id: str | None = None,
) -> dict[str, Any]:
"""Run a task workflow."""
initial_state = WorkflowState(
session_id=session_id,
task=task,
context_id=context_id,
)
config = {"configurable": {"thread_id": session_id}}
try:
final_state = await self.graph.ainvoke(initial_state, config)
return {
"status": final_state["status"],
"results": final_state["step_results"],
"error": final_state.get("error"),
}
except Exception as exc: # noqa: BLE001 - workflow failures are reported, not raised
return {
"status": SessionStatus.FAILED,
"results": [],
"error": str(exc),
}
async def provide_hitl_response(
self,
session_id: str | None,
request_id: str,
approved: bool,
data: dict[str, Any] | None = None,
) -> bool:
"""Resolve a pending HITL request through the shared broker.
Returns False when the request is unknown, expired or the supplied
session is missing or belongs to a different session.
"""
pending = hitl_handler.get_pending_request(request_id)
if pending is None:
return False
if session_id is None or pending["session_id"] != session_id:
return False
return hitl_handler.provide_response(request_id, approved, data)
# Global orchestrator instance
orchestrator = WorkflowOrchestrator()