Spaces:
Running
Running
Download src/browser_automation_agent/hitl/handler.py from sitcod3/dracull-agent: direct link, hf CLI and curl.
- Browser
- Download file 14.7 kB
-
https://huggingface.co/spaces/sitcod3/dracull-agent/resolve/main/src/browser_automation_agent/hitl/handler.py
- Command line
-
hf download hf://spaces/sitcod3/dracull-agent/src/browser_automation_agent/hitl/handler.py
-
curl -L -o handler.py https://huggingface.co/spaces/sitcod3/dracull-agent/resolve/main/src/browser_automation_agent/hitl/handler.py
14.7 kB
| """Human-in-the-Loop (HITL) broker for sensitive actions. | |
| The HTTP layer, the LangGraph orchestrator and the native-messaging host all | |
| talk to the single module-level ``hitl_handler`` instance. A request is a | |
| pending future: the orchestrator awaits it, the dashboard approves/denies it | |
| through ``POST /api/hitl/{id}/respond`` and the native host can answer it too. | |
| Security defaults are intentional: | |
| - unknown/expired/duplicate responses are rejected instead of silently | |
| accepting a decision that will never reach the workflow; | |
| - a timeout denies the action; | |
| - notification text is passed as an argv token, never through a shell. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import logging | |
| import shlex | |
| import subprocess | |
| import threading | |
| import uuid | |
| from collections.abc import Callable | |
| from datetime import UTC, datetime, timedelta | |
| from typing import Any | |
| from ..config import settings | |
| from ..protocol import HITLActionType, HITLResponseMessage | |
| logger = logging.getLogger(__name__) | |
| HITLRequestListener = Callable[[dict[str, Any]], None] | |
| def _notification_text(value: str) -> str: | |
| """Strip control characters from text destined for a notification command.""" | |
| return "".join(ch for ch in value if ch >= " " and ch != "\x7f") | |
| def _build_notification_argv(template: str, title: str, message: str) -> list[str]: | |
| """Tokenize the operator-configured template and substitute the | |
| placeholders inside each token. The result is an argument list executed | |
| without a shell, so the notification text can never alter the command | |
| structure itself.""" | |
| safe_title = _notification_text(title) | |
| safe_message = _notification_text(message) | |
| return [ | |
| tok.replace("{title}", safe_title).replace("{message}", safe_message) | |
| for tok in shlex.split(template) | |
| ] | |
| def _iso(value: datetime) -> str: | |
| """Serialize a timestamp with its UTC offset. | |
| The offset matters: the dashboard parses this with ``Date.parse``, and a | |
| zoneless ISO string is interpreted in the browser's local zone, which | |
| would put the expiry countdown out by the server/browser zone difference. | |
| """ | |
| return value.isoformat(timespec="seconds") | |
| class HITLHandler: | |
| """Tracks pending confirmations and resolves them exactly once.""" | |
| def __init__(self) -> None: | |
| self._pending_requests: dict[str, dict[str, Any]] = {} | |
| self._response_callbacks: dict[str, asyncio.Future[HITLResponseMessage]] = {} | |
| # The event loop that owns each pending future. A request can be created | |
| # on the aiohttp server loop and answered from the native-messaging | |
| # host's loop (or the other way round), so the future must always be | |
| # resolved through its own loop. | |
| self._response_loops: dict[str, asyncio.AbstractEventLoop] = {} | |
| # A request may be answered from several threads at once. The claim | |
| # protects the request before any cross-thread future resolution is | |
| # scheduled, so only one responder can own the decision. | |
| self._claim_lock = threading.Lock() | |
| self._claimed_requests: set[str] = set() | |
| self._notification_command = settings.hitl_notification_command | |
| self._listeners: list[HITLRequestListener] = [] | |
| # ββ listeners (WebSocket broadcast / native messaging) ββββββββββββββββ | |
| def add_listener(self, listener: HITLRequestListener) -> None: | |
| """Subscribe to newly created requests (used to push them to clients).""" | |
| if listener not in self._listeners: | |
| self._listeners.append(listener) | |
| def remove_listener(self, listener: HITLRequestListener) -> None: | |
| if listener in self._listeners: | |
| self._listeners.remove(listener) | |
| # ββ request lifecycle βββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def request_confirmation( | |
| self, | |
| session_id: str, | |
| action_type: HITLActionType, | |
| title: str, | |
| message: str, | |
| details: dict[str, Any], | |
| timeout: float | None = None, | |
| request_id: str | None = None, | |
| ) -> HITLResponseMessage: | |
| """Ask a human to approve/deny an action and wait for the answer. | |
| Returns an auto-deny response on timeout so callers never hang. | |
| """ | |
| request_id = request_id or str(uuid.uuid4()) | |
| timeout = settings.hitl_timeout if timeout is None else timeout | |
| now = datetime.now(UTC) | |
| loop = asyncio.get_running_loop() | |
| response_future: asyncio.Future[HITLResponseMessage] = loop.create_future() | |
| request_data: dict[str, Any] = { | |
| "request_id": request_id, | |
| "session_id": session_id, | |
| "action_type": action_type, | |
| "title": title, | |
| "message": message, | |
| "details": details, | |
| "timeout": timeout, | |
| "created_at": now, | |
| "expires_at": now + timedelta(seconds=timeout), | |
| } | |
| with self._claim_lock: | |
| if ( | |
| request_id in self._response_callbacks | |
| or request_id in self._claimed_requests | |
| ): | |
| raise RuntimeError(f"HITL request id is already in use: {request_id}") | |
| # Register the lifecycle under the claim lock so a completed | |
| # request's final cleanup cannot race with a new lifecycle that | |
| # attempts to reuse the same id. | |
| self._response_callbacks[request_id] = response_future | |
| self._response_loops[request_id] = loop | |
| self._pending_requests[request_id] = request_data | |
| if self._notification_command: | |
| await asyncio.to_thread(self._send_notification, title, message) | |
| payload = self._serialize(request_data) | |
| for listener in list(self._listeners): | |
| try: | |
| listener(payload) | |
| except Exception: | |
| logger.debug("HITL listener failed", exc_info=True) | |
| try: | |
| # ``asyncio.wait`` does not cancel the response future when its | |
| # deadline expires. That lets the response and timeout paths | |
| # arbitrate under one lock without cancelling a response that has | |
| # already claimed the request but whose cross-thread resolution | |
| # callback has not run yet. | |
| done, _pending = await asyncio.wait( | |
| {response_future}, timeout=timeout | |
| ) | |
| if done: | |
| return response_future.result() | |
| # Claim the timeout under the same lock as human responses. If a | |
| # response already claimed the request, that response is the | |
| # single winner; otherwise the timeout wins and later responses | |
| # are rejected as duplicates. | |
| with self._claim_lock: | |
| response_won = request_id in self._claimed_requests | |
| if not response_won: | |
| self._claimed_requests.add(request_id) | |
| if response_won: | |
| # A cross-thread responder claimed the request but may still | |
| # have a scheduled future resolution in flight. | |
| return await response_future | |
| # Timeout denies by default - the safe choice for sensitive work. | |
| return HITLResponseMessage( | |
| request_id=request_id, | |
| approved=False, | |
| data={"reason": "timeout"}, | |
| ) | |
| finally: | |
| self._cleanup_request(request_id) | |
| def provide_response( | |
| self, | |
| request_id: str, | |
| approved: bool, | |
| data: dict[str, Any] | None = None, | |
| ) -> bool: | |
| """Resolve a pending request. Returns False when it is unknown/expired. | |
| Safe to call from any thread: the future is resolved through the event | |
| loop that created it, because an asyncio Future is not thread-safe. | |
| """ | |
| self.cleanup_expired() | |
| with self._claim_lock: | |
| future = self._response_callbacks.get(request_id) | |
| if ( | |
| future is None | |
| or future.done() | |
| or request_id in self._claimed_requests | |
| ): | |
| return False | |
| self._claimed_requests.add(request_id) | |
| response = HITLResponseMessage( | |
| request_id=request_id, | |
| approved=approved, | |
| data=data, | |
| ) | |
| resolved = self._resolve_future(request_id, future, response) | |
| if not resolved: | |
| # The responder claimed the id but could not deliver its decision | |
| # (for example, the owning loop closed). Release that claim so | |
| # the timeout path can still win instead of awaiting forever. | |
| with self._claim_lock: | |
| self._claimed_requests.discard(request_id) | |
| return resolved | |
| def _resolve_future( | |
| self, | |
| request_id: str, | |
| future: asyncio.Future[HITLResponseMessage], | |
| response: HITLResponseMessage, | |
| ) -> bool: | |
| """Resolve a future on its owning loop. | |
| When the caller runs on the same loop the future belongs to, setting the | |
| result directly is both correct and immediate. From another thread the | |
| result must be scheduled with ``call_soon_threadsafe`` β setting it | |
| directly would not wake the waiter, which would then stall until the | |
| request times out and is denied. | |
| """ | |
| loop = self._response_loops.get(request_id) | |
| try: | |
| running = asyncio.get_running_loop() | |
| except RuntimeError: | |
| running = None | |
| if loop is None or loop is running: | |
| if future.done(): | |
| return False | |
| future.set_result(response) | |
| return True | |
| if loop.is_closed(): | |
| return False | |
| def _set_result() -> None: | |
| if not future.done(): | |
| future.set_result(response) | |
| loop.call_soon_threadsafe(_set_result) | |
| return True | |
| def get_pending_request(self, request_id: str) -> dict[str, Any] | None: | |
| """Serializable snapshot of one pending request (None when absent).""" | |
| self.cleanup_expired() | |
| request_data = self._pending_requests.get(request_id) | |
| return self._serialize(request_data) if request_data else None | |
| def list_pending(self) -> list[dict[str, Any]]: | |
| """Serializable snapshots of every live request, oldest first.""" | |
| self.cleanup_expired() | |
| return [self._serialize(req) for req in self._pending_requests.values()] | |
| # Backwards-compatible alias used by the native-messaging host. | |
| def get_pending_requests(self) -> list[dict[str, Any]]: | |
| return self.list_pending() | |
| def cleanup_expired(self) -> int: | |
| """Expire timed-out requests and deny their callers.""" | |
| now = datetime.now(UTC) | |
| expired = [ | |
| rid | |
| for rid, req in self._pending_requests.items() | |
| if req["expires_at"] < now | |
| ] | |
| for rid in expired: | |
| with self._claim_lock: | |
| future = self._response_callbacks.get(rid) | |
| if future is None: | |
| continue | |
| if rid in self._claimed_requests: | |
| continue | |
| self._claimed_requests.add(rid) | |
| if not future.done(): | |
| self._resolve_future( | |
| rid, | |
| future, | |
| HITLResponseMessage( | |
| request_id=rid, | |
| approved=False, | |
| data={"reason": "expired"}, | |
| ), | |
| ) | |
| # Do not clean up the lifecycle here: its owning request is still | |
| # unwinding and will perform the single authoritative cleanup in | |
| # its finally block. Removing the claim here would allow a late | |
| # duplicate response to slip through near the timeout boundary. | |
| return len(expired) | |
| # ββ internals βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _serialize(self, request_data: dict[str, Any]) -> dict[str, Any]: | |
| action_type = request_data["action_type"] | |
| return { | |
| "request_id": request_data["request_id"], | |
| "session_id": request_data["session_id"], | |
| "action_type": action_type.value if isinstance(action_type, HITLActionType) else action_type, | |
| "title": request_data["title"], | |
| "message": request_data["message"], | |
| "details": request_data["details"], | |
| "timeout": request_data["timeout"], | |
| "created_at": _iso(request_data["created_at"]), | |
| "expires_at": _iso(request_data["expires_at"]), | |
| } | |
| def _cleanup_request(self, request_id: str) -> None: | |
| """Retire one completed request lifecycle. | |
| The claim is discarded only here, after the owning request has fully | |
| finished. ``cleanup_expired`` may resolve a request early, but it no | |
| longer cleans up that lifecycle itself; the owner's ``finally`` block | |
| remains the single cleanup authority. Duplicate responses are rejected | |
| while the lifecycle is active; after it finishes, its callback no longer | |
| exists, so a late response is rejected as unknown. | |
| """ | |
| self._pending_requests.pop(request_id, None) | |
| self._response_callbacks.pop(request_id, None) | |
| self._response_loops.pop(request_id, None) | |
| with self._claim_lock: | |
| self._claimed_requests.discard(request_id) | |
| def _send_notification(self, title: str, message: str) -> None: | |
| """Send a desktop notification (best effort, never raises).""" | |
| try: | |
| if self._notification_command: | |
| argv = _build_notification_argv(self._notification_command, title, message) | |
| if argv: | |
| subprocess.run(argv, shell=False, capture_output=True, timeout=5, check=False) | |
| except Exception: | |
| logger.debug("HITL notification failed", exc_info=True) | |
| # Global HITL handler instance | |
| hitl_handler = HITLHandler() | |