Spaces:
Running
Running
File size: 14,676 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 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 | """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()
|