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
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
"""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()