"""Main entry point for the Browser Automation Agent backend."""
import asyncio
import hmac
import json
import signal
import sys
import uuid
from collections.abc import Awaitable, Callable
from datetime import datetime
from pathlib import Path
from typing import Any
import typer
from aiohttp import web
from aiohttp.multipart import BodyPartReader
from pydantic import BaseModel, ValidationError
from rich.console import Console
from rich.panel import Panel
from . import voice
from .browser.manager import SUPPORTED_CHANNELS, browser_manager
from .chat_agent import CHAT_ERROR_HINTS, classify_chat_error, run_chat, usable_chat_messages
from .chat_tools import ChatBrowserSession, ToolError, check_url, web_fetch, web_search as chat_web_search
from .web_search_providers import combined_search, search_configured as search_backends
from .client_research import research_client
from .config import settings
from .context.manager import context_manager
from .doctor import run_doctor
from .exa_search import ExaNotConfiguredError, ExaSearchError, exa_client
from .graph.orchestrator import orchestrator
from .hitl.handler import hitl_handler
from .llm.provider import LLMProvider
from .messaging.host import NativeMessagingHost
from .messaging.host import main as host_main
from .net_guard import BlockedUrlError
from .protocol import SessionStatus
from .runtime.ledger import LedgerEntry, honest_mixed_result_sentence, render_ledger
from .runtime.store import TaskRecord, TaskStepRecord, TaskStore
from .settings_store import SettingsValidationError, apply_updates, read_settings
from .tools.executor import _live_approval_request, configure_approval_request
from .webnav import SessionNotFoundError, webnav
from .workflows.cli import app as workflow_app
app = typer.Typer(name="browser-automation-agent", help="Browser Automation Agent Backend")
# Workflow orchestration CLI: workflow list / show / run (Playwright or Selenium).
app.add_typer(workflow_app, name="workflow", help="JSON browser workflows (open/edit/search/extract).")
console = Console()
# Global instances (will be replaced with DI container in production).
# browser_manager is THE module-level singleton from browser.manager — the
# orchestrator graph (orchestrator.py:13) and the native-messaging host both
# import that instance, so any second BrowserManager() created here (the old
# code) left HTTP-created sessions invisible to the graph: every task run
# died with "No page found" and status updates were written to the wrong
# object. One process, one manager.
# Same rule as browser_manager: the graph, HTTP handlers and native-messaging
# host must share ONE orchestrator (and therefore one checkpointer), otherwise
# a HITL response accepted over HTTP never reaches the running workflow.
chat_browser = ChatBrowserSession(browser_manager)
llm_provider = LLMProvider()
# Durable task state and this process's owned runnable tasks. Stop requests
# cancel only entries in ``task_runs``; no OS process is ever signalled.
task_store = TaskStore()
task_runs: dict[str, asyncio.Task[Any]] = {}
# WebSocket connections
ws_connections: dict[str, set[web.WebSocketResponse]] = {}
# Topic subscribers (WS clients that sent {"type": "subscribe", ...}):
# orchestration events (session created/closed, task lifecycle) are pushed to
# these connections instead of the frontend polling every surface.
ws_topic_subscribers: dict[str, set[web.WebSocketResponse]] = {}
WS_TOPICS = ("sessions", "tasks", "hitl")
# Keep references to fire-and-forget task runs (response must not block on
# long automation runs; unreferenced tasks can be garbage-collected).
background_tasks: set[asyncio.Task] = set()
# In-flight chat requests keyed by client-supplied request_id so POST
# /api/chat/cancel can abort a running provider/tool loop (D-8).
chat_requests: dict[str, asyncio.Task[Any]] = {}
# ── Request schemas ──────────────────────────────────────────────────────────
# Bodies are validated before any browser/session work happens, so a malformed
# request fails fast with 422 instead of leaving a half-created session behind.
class ExecuteTaskRequest(BaseModel):
session_id: str | None = None
task: dict[str, Any] | None = None
class CreateSessionRequest(BaseModel):
context_id: str | None = None
task: dict[str, Any] | None = None
# Dual-browser: pin this session to a channel ("chrome" or "firefox" among
# others) independent of the server default. None = use the default.
engine: str | None = None
class CreateContextRequest(BaseModel):
name: str
description: str | None = None
# Paths reachable without the bearer token when settings.app_access_token is
# set. /api/health must stay open so platform probes (HF Spaces, uptime
# monitors) and the UI's reachability check keep working unauthenticated.
AUTH_EXEMPT_PATHS = frozenset({"/api/health", "/api/auth/login"})
def _bearer_token(request: web.Request) -> str:
"""Extract the bearer token from the Authorization header ('' if absent)."""
header = request.headers.get("Authorization", "")
if header[:7].lower() != "bearer ":
return ""
return header[7:].strip()
@web.middleware
async def auth_middleware(
request: web.Request,
handler: Callable[[web.Request], Awaitable[web.StreamResponse]],
) -> web.StreamResponse:
"""Require the shared bearer token on /api/* when one is configured.
Enabled by setting ``APP_ACCESS_TOKEN`` (hosted deployments: HF Spaces, a
public VM). Unset (the default) keeps the local single-user behavior with
zero auth. OPTIONS preflights are exempt so CORS negotiation never leaks
whether the caller is authenticated; /api/health and /api/auth/login are
always reachable. Comparison is constant-time.
"""
expected = getattr(settings, "app_access_token", None)
if not expected:
return await handler(request)
if request.method == "OPTIONS" or request.path in AUTH_EXEMPT_PATHS:
return await handler(request)
provided = _bearer_token(request)
if not provided or not hmac.compare_digest(provided, expected):
return web.json_response(
{"error": "authentication required", "code": "unauthorized"}, status=401
)
return await handler(request)
@web.middleware
async def cors_middleware(
request: web.Request,
handler: Callable[[web.Request], Awaitable[web.StreamResponse]],
) -> web.StreamResponse:
"""Allow only explicitly configured browser origins to call the API.
The local dashboard and installed browser extension are supported through
``cors_allowed_origins``. Requests without an ``Origin`` header (native
messaging, curl, service-to-service calls) are unaffected.
"""
origin = request.headers.get("Origin")
if origin:
normalized_origin = origin.rstrip("/")
allowed_origins = {
allowed.rstrip("/") for allowed in settings.cors_allowed_origins
}
if normalized_origin not in allowed_origins:
return web.json_response({"error": "Origin not allowed"}, status=403)
if request.method == "OPTIONS":
resp: web.StreamResponse = web.Response(status=204)
else:
try:
resp = await handler(request)
except web.HTTPException as exc:
resp = exc
if origin:
resp.headers["Access-Control-Allow-Origin"] = normalized_origin
resp.headers["Vary"] = "Origin"
resp.headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, OPTIONS"
resp.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
return resp
# ── Provider routing ─────────────────────────────────────────────────────────
# The frontend sends the provider *id* from frontend/src/data/providers.ts.
# LiteLLM routes for native providers; OpenAI-compatible gateways (NVIDIA,
# Kilo, custom endpoints) route through the plain "openai" client with a
# base URL. Z.AI and Together use the prefixes this LiteLLM build expects
# ("zai", "together_ai" — the bare "together" alias is rejected by it).
# Legacy route strings ("xai", "nvidia_nim") pass through unchanged.
PROVIDER_ROUTES = {
"openai": "openai",
"anthropic": "anthropic",
"deepseek": "deepseek",
"gemini": "gemini",
"grok": "xai",
"ollama": "ollama",
"azure-openai": "azure",
"openrouter": "openrouter",
"groq": "groq",
"cerebras": "cerebras",
"nvidia": "openai",
"llama-together": "together_ai",
"openai-compatible": "openai",
"kilo": "openai",
"zai": "zai",
}
DEFAULT_MODEL_BASES = {
"openai": "https://api.openai.com/v1",
"anthropic": "https://api.anthropic.com/v1",
"deepseek": "https://api.deepseek.com",
"groq": "https://api.groq.com/openai/v1",
"openrouter": "https://openrouter.ai/api/v1",
"grok": "https://api.x.ai/v1",
"cerebras": "https://api.cerebras.ai/v1",
"llama-together": "https://api.together.xyz/v1",
"nvidia": "https://integrate.api.nvidia.com/v1",
"kilo": "https://ai-gateway.kilo.ai/api/v1",
"zai": "https://api.z.ai/api/paas/v4",
"gemini": "https://generativelanguage.googleapis.com/v1beta/openai",
"ollama": "http://localhost:11434/v1",
"azure-openai": "",
"openai-compatible": "",
}
# Model-list endpoints that do NOT speak "Authorization: Bearer" (everything
# else is probed OpenAI-style at {base}/models).
def models_auth(provider: str, api_key: str | None) -> dict:
if provider == "anthropic":
# Native /v1/models: x-api-key + pinned protocol version.
return {"x-api-key": api_key or "", "anthropic-version": "2023-06-01"}
if provider == "azure-openai":
return {"api-key": api_key or ""}
return {"Authorization": f"Bearer {api_key}"} if api_key else {}
def resolve_route(provider: str) -> str:
"""Map a frontend provider id (or legacy route string) to a LiteLLM route."""
return PROVIDER_ROUTES.get(provider, provider)
# Providers whose requests may legitimately carry a user-supplied base URL
# (the Settings UI shows the field only for these). For every other provider
# a client-sent base is stale state from a previously selected provider and
# is ignored — otherwise a leftover NVIDIA URL silently retargets OpenRouter
# traffic (observed as a 404 from the wrong gateway).
BASE_URL_PROVIDERS = {"openai-compatible", "azure-openai", "ollama", "nvidia"}
def sanitize_client_base(provider: str, client_base: str | None) -> str | None:
"""A client-supplied base URL is honored only for BASE_URL_PROVIDERS;
for every other provider it is stale state and dropped."""
return client_base if provider in BASE_URL_PROVIDERS else None
# ── WebSocket ────────────────────────────────────────────────────────────────
async def websocket_handler(request: web.Request) -> web.WebSocketResponse:
"""WebSocket handler for real-time communication."""
ws = web.WebSocketResponse()
await ws.prepare(request)
session_id = request.query.get("session_id", "global")
if session_id not in ws_connections:
ws_connections[session_id] = set()
ws_connections[session_id].add(ws)
console.print(f"[blue]WebSocket connected:[/blue] {session_id}")
try:
async for msg in ws:
if msg.type == web.WSMsgType.TEXT:
try:
data = json.loads(msg.data)
await handle_ws_message(session_id, ws, data)
except json.JSONDecodeError:
await ws.send_json({"type": "error", "code": "INVALID_JSON", "message": "Invalid JSON"})
elif msg.type == web.WSMsgType.ERROR:
console.print(f"[red]WebSocket error:[/red] {ws.exception()}")
finally:
ws_connections[session_id].discard(ws)
if not ws_connections[session_id]:
del ws_connections[session_id]
for topic in list(ws_topic_subscribers):
ws_topic_subscribers[topic].discard(ws)
console.print(f"[blue]WebSocket disconnected:[/blue] {session_id}")
return ws
async def handle_ws_message(session_id: str, ws: web.WebSocketResponse, data: dict) -> None:
"""Handle incoming WebSocket messages."""
msg_type = data.get("type")
if msg_type == "ping":
await ws.send_json({"type": "pong", "timestamp": asyncio.get_event_loop().time()})
elif msg_type == "subscribe":
# Subscribe the connection to orchestration event topics.
topics = data.get("topics") or []
if isinstance(topics, str):
topics = [topics]
accepted = [t for t in topics if t in WS_TOPICS]
for topic in accepted:
ws_topic_subscribers.setdefault(topic, set()).add(ws)
await ws.send_json({"type": "subscribed", "topics": accepted})
elif msg_type == "unsubscribe":
topics = data.get("topics") or []
if isinstance(topics, str):
topics = [topics]
for topic in topics:
ws_topic_subscribers.get(topic, set()).discard(ws)
await ws.send_json({"type": "unsubscribed", "topics": topics})
elif msg_type == "chat":
await handle_chat_message(session_id, ws, data)
else:
await ws.send_json({"type": "error", "code": "UNKNOWN_MESSAGE_TYPE", "message": f"Unknown message type: {msg_type}"})
async def handle_chat_message(session_id: str, ws: web.WebSocketResponse, data: dict) -> None:
"""Handle chat messages over /ws through the same tool loop as /api/chat.
The WS surface carries no per-request provider settings, so it runs on the
backend-configured defaults (settings.llm_*). It used to route through the
task orchestrator, which silently diverged from the /api/chat contract: a
WS chat got no web_search/browser tools.
"""
message = data.get("message", "")
if not message:
await ws.send_json({"type": "error", "code": "EMPTY_MESSAGE", "message": "Message cannot be empty"})
return
provider = settings.llm_provider
route = resolve_route(provider)
model = (settings.llm_model or "").strip()
full_model = model if model.startswith(f"{route}/") else f"{route}/{model}"
base_url = sanitize_client_base(provider, settings.llm_base_url)
if not base_url and route == "openai":
base_url = DEFAULT_MODEL_BASES.get(provider) or None
try:
result = await run_chat(
provider=provider,
full_model=full_model,
api_key=settings.llm_api_key,
base_url=base_url,
system="",
raw_messages=[{"role": "user", "content": message}],
temperature=settings.llm_temperature,
max_tokens=settings.llm_max_tokens,
browser=chat_browser,
)
except Exception as exc: # noqa: BLE001 — mirror the /api/chat error body
error_kind = classify_chat_error(exc)
console.print(f"[red]WS chat error[/red] {full_model} ({error_kind}): {exc}")
await ws.send_json({
"type": "chat_response",
"error": f"{type(exc).__name__}: {exc}",
"errorKind": error_kind,
"model": full_model,
"hint": CHAT_ERROR_HINTS[error_kind],
})
return
await ws.send_json({
"type": "chat_response",
"content": result["content"],
"model": full_model,
"usage": result["usage"],
"tool_trace": result.get("tool_trace", []),
})
async def broadcast_to_session(session_id: str, message: dict) -> None:
"""Broadcast a message to all WebSocket connections for a session."""
if session_id in ws_connections:
dead = set()
for ws in ws_connections[session_id]:
try:
await ws.send_json(message)
except Exception: # noqa: BLE001 - drop sockets that already closed
dead.add(ws)
for ws in dead:
ws_connections[session_id].discard(ws)
async def broadcast_event(topic: str, payload: dict) -> None:
"""Push an orchestration event to all subscribers of a WS topic.
Subscribers opt in via {"type": "subscribe", "topics": [...]}; the SPA
uses this to mirror session lifecycle changes into the chat instantly
instead of polling. Dead sockets are dropped without failing the send.
"""
message = {"type": "event", "topic": topic, **payload}
for ws in list(ws_topic_subscribers.get(topic, set())):
try:
await ws.send_json(message)
except Exception: # noqa: BLE001 - drop sockets that already closed
ws_topic_subscribers.get(topic, set()).discard(ws)
# ── HTTP handlers ────────────────────────────────────────────────────────────
async def health_handler(request: web.Request) -> web.Response:
"""Health check endpoint."""
return web.json_response({
"status": "healthy",
"version": "0.1.0",
"mode": "development",
# Hosted deployments flip this on via APP_ACCESS_TOKEN; the UI and the
# Worker gateway use it to tell a locked Space from a broken one.
"auth_required": bool(getattr(settings, "app_access_token", None)),
})
async def auth_login_handler(request: web.Request) -> web.Response:
"""Exchange the shared password for the bearer token (hosted logins).
POST /api/auth/login {"password": "..."} -> {"token": "...", "token_type": "bearer"}
The token IS settings.app_access_token — a single shared secret, constant-
time compared, never logged. 501 when no token is configured (local mode),
so the UI can tell "login not needed here" from "wrong password".
"""
expected = getattr(settings, "app_access_token", None)
if not expected:
return web.json_response(
{"error": "authentication not configured", "code": "auth-disabled"},
status=501,
)
try:
data = await request.json()
except json.JSONDecodeError:
return web.json_response({"error": "Invalid JSON body"}, status=400)
password = (data.get("password") or "").strip() if isinstance(data, dict) else ""
if not password or not hmac.compare_digest(password, expected):
return web.json_response(
{"error": "invalid password", "code": "invalid-credentials"}, status=401
)
return web.json_response({"token": expected, "token_type": "bearer"})
async def root_handler(request: web.Request) -> web.Response:
"""Root landing page for the HTTP API.
This port speaks the API only — the UI is the Vite app on :3000, which
proxies /api here. Without this route a browser (or a platform preview)
hitting the port directly got a bare "404: Not Found", which reads as a
broken service rather than "you are on the wrong port".
"""
info = {
"service": "Browser Automation Agent API",
"version": "0.1.0",
"status": "running",
"ui": "Run the frontend dev server (npm run dev, port 3000) and open it there; /api is proxied to this port.",
"health": "/api/health",
"endpoints": [
"/api/health",
"/api/chat",
"/api/models",
"/api/voice/providers",
"/api/voice/transcribe",
"/api/voice/speak",
"/api/settings",
"/api/sessions",
"/ws",
],
}
# A browser gets a readable page; curl/scripts get JSON.
if "text/html" in request.headers.get("Accept", ""):
rows = "".join(f"
{e}" for e in info["endpoints"])
return web.Response(
content_type="text/html",
text=(
"Dracull API"
""
"Dracull API is running
"
f"This port ({request.host}) serves the HTTP API only. "
"The interface is the Vite app on port 3000.
"
"/api/health
"
f""
),
)
return web.json_response(info)
async def list_sessions_handler(request: web.Request) -> web.Response:
sessions = await browser_manager.list_sessions()
return web.json_response([s.model_dump() for s in sessions])
async def _run_posted_task(session_id: str, task_data: dict) -> None:
"""Run a task posted together with POST /api/sessions.
D-3: the body used to be parsed and discarded, so a New Session's URL/
instructions never executed. Runs detached so the response returns the
session id immediately (the UI says "ready"), while the automation itself
proceeds in the background and logs its outcome.
"""
from .protocol import TaskDefinition, TaskStep
task = TaskDefinition(
name=task_data.get("name", "Untitled Task"),
description=task_data.get("description", ""),
steps=[TaskStep(**step) for step in task_data.get("steps", [])],
variables=task_data.get("variables", {}),
metadata=task_data.get("metadata", {}),
)
try:
result = await orchestrator.run_task(session_id, task)
console.print(f"[green]task[/green] {session_id}: {result.get('status')} {result.get('error') or ''}")
except Exception as exc: # noqa: BLE001 - background run must not die silently
console.print(f"[red]task failed[/red] {session_id}: {exc}")
async def create_session_handler(request: web.Request) -> web.Response:
try:
raw = await request.json()
except (json.JSONDecodeError, TypeError):
raw = {}
try:
payload = CreateSessionRequest(**(raw if isinstance(raw, dict) else {}))
except ValidationError as exc:
return web.json_response({"error": f"Invalid body: {exc}"}, status=422)
# Fail fast on an unknown engine BEFORE any browser work happens, so the
# caller gets a clean 422 instead of a half-created session.
if payload.engine is not None:
requested = payload.engine.strip().lower()
if requested not in SUPPORTED_CHANNELS:
return web.json_response(
{
"error": f"Unsupported engine '{payload.engine}'. "
f"Supported: {', '.join(SUPPORTED_CHANNELS)}."
},
status=422,
)
session_id = f"session_{uuid.uuid4().hex[:8]}"
try:
session_info = await browser_manager.create_session(
session_id, payload.context_id, engine=payload.engine
)
except ValueError as exc:
return web.json_response({"error": str(exc)}, status=422)
# Only a real string engine goes into the response — mocks/tests without
# the attribute report None instead of blowing up json_response.
reported_engine = getattr(session_info, "engine", None)
if not isinstance(reported_engine, str):
reported_engine = None
await broadcast_event(
"sessions",
{"event": "session_created", "session_id": session_id, "engine": reported_engine},
)
task_data = payload.task
task_started = False
if isinstance(task_data, dict) and task_data.get("steps"):
task = asyncio.create_task(_run_posted_task(session_id, task_data))
background_tasks.add(task)
task.add_done_callback(background_tasks.discard)
task_started = True
return web.json_response(
{
"session_id": session_id,
"engine": reported_engine,
"task_started": task_started,
},
status=201,
)
async def get_session_handler(request: web.Request) -> web.Response:
session_id = request.match_info['session_id']
session = await browser_manager.get_session_status(session_id)
if session:
return web.json_response(session.model_dump())
return web.json_response({"error": "Session not found"}, status=404)
async def close_session_handler(request: web.Request) -> web.Response:
session_id = request.match_info['session_id']
await browser_manager.close_session(session_id)
await broadcast_event("sessions", {"event": "session_closed", "session_id": session_id})
return web.json_response({"success": True})
async def engines_handler(request: web.Request) -> web.Response:
"""Dual-browser capability report (Firefox + Chrome orchestration).
Reports what this backend can genuinely launch — the configured default,
the full supported channel list, and the Firefox headless guard state.
It deliberately does NOT claim an engine is "installed": Playwright
channel discovery decides that at launch, and doctor probes give live
evidence per machine.
"""
return web.json_response(
{
"default": settings.browser_channel,
"supported": list(SUPPORTED_CHANNELS),
"headless": settings.browser_headless,
"firefox_force_headless": settings.browser_firefox_force_headless,
}
)
def _iso_to_epoch(value: str | None) -> float | None:
"""ContextManager stores ISO-8601 timestamps; the UI contract is epoch
seconds (relative-time rendering, History date-window filters)."""
if not value:
return None
try:
return datetime.fromisoformat(value).timestamp()
except ValueError:
return None
async def list_contexts_handler(request: web.Request) -> web.Response:
"""D-5: durable metadata (name/description/last_used) from ContextManager,
merged with any live Playwright contexts so nothing open is hidden."""
live = await browser_manager.list_contexts()
live_by_id = {row["context_id"]: row for row in live}
seen: set = set()
rows: list = []
for ctx in context_manager.list_contexts():
cid = ctx["context_id"]
seen.add(cid)
live_row = live_by_id.get(cid, {})
rows.append({
"context_id": cid,
"name": ctx.get("name") or cid,
"description": ctx.get("description", ""),
"created_at": _iso_to_epoch(ctx.get("created_at"))
or live_row.get("created_at")
or 0,
"session_count": live_row.get(
"session_count", ctx.get("session_count", 0)
),
"last_used": _iso_to_epoch(ctx.get("last_used")),
})
for cid, live_row in live_by_id.items():
if cid not in seen: # legacy id created before metadata store existed
rows.append({
"context_id": cid,
"name": live_row.get("name") or cid,
"description": "",
"created_at": live_row.get("created_at", 0),
"session_count": live_row.get("session_count", 0),
"last_used": None,
})
return web.json_response(rows)
async def create_context_handler(request: web.Request) -> web.Response:
try:
raw = await request.json()
except (json.JSONDecodeError, TypeError):
raw = {}
try:
payload = CreateContextRequest(**(raw if isinstance(raw, dict) else {}))
except ValidationError as exc:
return web.json_response({"error": f"Invalid body: {exc}"}, status=422)
name = payload.name.strip()
if not name:
return web.json_response({"error": "name is required"}, status=400)
description = (payload.description or "").strip()
# Persist first (this is what the Contexts page renders), then open the
# live Playwright context under the SAME id; roll back if that fails so
# the store never shows a context that does not exist.
context_id = context_manager.create_context(name, description)
try:
await browser_manager.create_context(context_id, name)
except Exception as exc: # noqa: BLE001 - rollback on context failure
context_manager.delete_context(context_id)
return web.json_response(
{"error": f"could not open browser context: {exc}"}, status=500
)
return web.json_response({"context_id": context_id}, status=201)
async def delete_context_handler(request: web.Request) -> web.Response:
context_id = request.match_info['context_id']
closed = await browser_manager.delete_context(context_id)
removed = context_manager.delete_context(context_id)
if not closed and not removed:
# D-7: report no-ops honestly instead of always {success: true}
return web.json_response(
{"success": False, "error": "context not found"}, status=404
)
return web.json_response({"success": True})
_STEP_TARGET_FIELDS = (
"selector",
"target",
"clicked",
"typed",
"hovered",
"submitted",
)
def _safe_step_detail(action: str, payload: Any) -> str | None:
"""Project an action result to an allow-list of non-sensitive fields.
Raw action payloads can contain typed form values, cookies, tokens, page
content, or other response data. Only fields that describe the action's
target are eligible for durable task state.
"""
if not isinstance(payload, dict):
return None
descriptors: list[str] = []
for field in _STEP_TARGET_FIELDS:
value = payload.get(field)
if isinstance(value, str) and value:
descriptors.append(f"{field}={value}")
if not descriptors:
return None
return f"{action}: {', '.join(descriptors)}"[:500]
def _result_to_task_steps(results: list[dict[str, Any]]) -> list[TaskStepRecord]:
"""Convert actual orchestrator step results into persisted step records."""
steps: list[TaskStepRecord] = []
for result in results:
if not isinstance(result, dict):
continue
action = str(result.get("action", "unknown"))
payload = result.get("result")
error = payload.get("error") if isinstance(payload, dict) else None
error_code = error.get("code") if isinstance(error, dict) else None
tab_id = payload.get("tab_id") if isinstance(payload, dict) else None
steps.append(
TaskStepRecord(
tool=action,
ok=error is None,
error_code=str(error_code) if error_code else None,
tab_id=str(tab_id) if tab_id else None,
detail=_safe_step_detail(action, payload),
)
)
return steps
async def _execute_tracked_task(
task_id: str,
session_id: str,
task: Any,
) -> dict[str, Any]:
"""Execute a task, persist actual step results, and honor Stop."""
record = TaskRecord(task_id=task_id, status="running")
task_store.save(record)
try:
result = await orchestrator.run_task(session_id, task)
except asyncio.CancelledError:
stopped = task_store.load(task_id) or record
stopped.status = "stopped"
stopped.stop_requested = True
completed = [step.tool for step in stopped.steps if step.ok]
completed_text = ", ".join(completed) if completed else "no tool steps"
stopped.final_answer = (
f"The run was stopped before completion. Completed tool steps: {completed_text}. "
"This is a partial result, not a successful task."
)
task_store.save(stopped)
raise
persisted = task_store.load(task_id) or record
persisted.steps = _result_to_task_steps(result.get("results", []))
raw_status = result.get("status", "failed")
status = getattr(raw_status, "value", raw_status)
persisted.status = "completed" if status == SessionStatus.COMPLETED.value else "failed"
persisted.error = result.get("error")
entries = await _task_ledger(persisted)
persisted.final_answer = honest_mixed_result_sentence(entries)
task_store.save(persisted)
return result
async def execute_task_handler(request: web.Request) -> web.Response:
"""Execute a task via HTTP API."""
try:
raw = await request.json()
except (json.JSONDecodeError, TypeError):
raw = {}
try:
payload = ExecuteTaskRequest(**(raw if isinstance(raw, dict) else {}))
except ValidationError as exc:
return web.json_response({"error": f"Invalid body: {exc}"}, status=422)
# D-2: the path id wins (POST /api/sessions/{id}/tasks); the body key is
# only a fallback for the un-parameterised POST /api/tasks.
session_id = (
request.match_info.get('session_id')
or payload.session_id
or f"session_{uuid.uuid4().hex[:8]}"
)
task_data = payload.task
if task_data is None:
return web.json_response(
{"error": "task is required", "details": []}, status=422
)
from .protocol import TaskDefinition, TaskStep
try:
task = TaskDefinition(
name=task_data.get('name', 'Untitled Task'),
description=task_data.get('description', ''),
steps=[TaskStep(**step) for step in task_data.get('steps', [])],
variables=task_data.get('variables', {}),
metadata=task_data.get('metadata', {}),
)
except ValidationError as exc:
return web.json_response(
{"error": "Invalid task definition", "details": exc.errors()}, status=422
)
session = await browser_manager.get_session_status(session_id)
if not session:
await browser_manager.create_session(session_id)
else:
page = await browser_manager.get_page(session_id)
if not page:
console.print(f"Recreating page for session {session_id}")
await browser_manager.create_session(session_id, session.context_id)
task_id = f"task_{uuid.uuid4().hex[:12]}"
run_task = asyncio.create_task(_execute_tracked_task(task_id, session_id, task))
task_runs[task_id] = run_task
try:
result = await run_task
finally:
task_runs.pop(task_id, None)
return web.json_response({**result, "task_id": task_id})
async def _task_ledger(record: TaskRecord) -> list[LedgerEntry]:
"""Project persisted task steps into truth-ledger entries."""
return [
LedgerEntry(
tool=step.tool,
ok=step.ok,
error_code=step.error_code,
tab_id=step.tab_id,
at=step.at,
detail=step.detail,
)
for step in record.steps
]
async def get_task_handler(request: web.Request) -> web.Response:
"""Read one persisted task record."""
task_id = request.match_info["task_id"]
record = task_store.load(task_id)
if record is None:
return web.json_response({"error": "Task not found", "task_id": task_id}, status=404)
payload = record.model_dump(mode="json")
entries = await _task_ledger(record)
payload["ledger"] = render_ledger(entries)
payload["ledger_summary"] = honest_mixed_result_sentence(entries)
return web.json_response(payload)
async def stop_task_handler(request: web.Request) -> web.Response:
"""Request cancellation of a task owned by this process.
The only cancellation primitive is ``asyncio.Task.cancel``. The endpoint
never enumerates or signals operating-system processes, so it cannot kill
a backend, browser, or any other process it did not spawn.
"""
task_id = request.match_info["task_id"]
record = task_store.load(task_id)
if record is None:
return web.json_response({"error": "Task not found", "task_id": task_id}, status=404)
record.stop_requested = True
if record.status == "running":
record.status = "stopped"
completed = [step.tool for step in record.steps if step.ok]
completed_text = ", ".join(completed) if completed else "no tool steps"
record.final_answer = (
f"The run was stopped before completion. Completed tool steps: {completed_text}. "
"This is a partial result, not a successful task."
)
task_store.save(record)
owned_task = task_runs.get(task_id)
cancel_requested = False
if owned_task is not None and not owned_task.done():
owned_task.cancel()
cancel_requested = True
await asyncio.sleep(0)
refreshed = task_store.load(task_id)
if refreshed is not None:
record = refreshed
payload = record.model_dump(mode="json")
payload["stop_requested"] = True
payload["cancel_requested"] = cancel_requested
return web.json_response(payload)
async def hitl_list_handler(request: web.Request) -> web.Response:
"""List every pending HITL request (dashboard approval queue)."""
return web.json_response(hitl_handler.list_pending())
async def chat_cancel_handler(request: web.Request) -> web.Response:
"""Abort an in-flight chat generation by client-supplied request_id.
D-8: the frontend sends `request_id` with each /chat call; this endpoint
cancels the matching asyncio.Task so the provider/tool loop stops instead
of running to completion (cost + orphaned browser tools).
"""
try:
data = await request.json()
except (json.JSONDecodeError, TypeError):
return web.json_response({"error": "Invalid JSON body"}, status=400)
request_id = (data.get("request_id") or "").strip() if isinstance(data, dict) else None
if not request_id:
return web.json_response({"error": "request_id is required"}, status=400)
owned = chat_requests.get(request_id)
if owned is None:
return web.json_response({"error": f"No in-flight chat request {request_id}"}, status=404)
owned.cancel()
return web.json_response({"success": True, "cancelled": request_id})
async def hitl_respond_handler(request: web.Request) -> web.Response:
"""Resolve a pending HITL request.
The graph task is parked on the broker future, so a successful response
here resumes the workflow immediately. Unknown, expired or duplicate
requests are rejected instead of pretending a decision was delivered.
"""
request_id = request.match_info['request_id']
try:
data = await request.json()
except (json.JSONDecodeError, TypeError):
return web.json_response({"success": False, "error": "Invalid JSON body"}, status=400)
# Explicit type checks (not pydantic coercion): pydantic's lax bool mode
# would silently turn "yes"/"on" into True, and a decision must never be
# inferred from a string.
approved = data.get("approved") if isinstance(data, dict) else None
if not isinstance(approved, bool):
return web.json_response(
{"success": False, "error": "approved must be a boolean"},
status=400,
)
decision_data = data.get("data")
if decision_data is not None and not isinstance(decision_data, dict):
return web.json_response(
{"success": False, "error": "data must be an object when provided"},
status=400,
)
pending = hitl_handler.get_pending_request(request_id)
if pending is None:
return web.json_response(
{"success": False, "error": f"No pending HITL request {request_id}"},
status=404,
)
accepted = await orchestrator.provide_hitl_response(
pending["session_id"],
request_id,
approved,
decision_data,
)
if not accepted:
return web.json_response(
{"success": False, "error": f"HITL request {request_id} is no longer pending"},
status=409,
)
return web.json_response(
{
"success": True,
"request_id": request_id,
"approved": approved,
}
)
# ── Agent web navigation (nanobrowser-style control surface) ────────────────
# Every target URL — whether typed into the control bar, picked from Exa
# results, or emitted by the task engine — passes the SSRF guard in
# net_guard.py: http/https only, no loopback/private/reserved hosts even
# after DNS resolution, plus the env-driven domain kill switches.
async def browse_navigate_handler(request: web.Request) -> web.Response:
session_id = request.match_info['session_id']
try:
data = await request.json()
except json.JSONDecodeError:
return web.json_response({"error": "Invalid JSON body"}, status=400)
url = (data.get("url") or "").strip()
if not url:
return web.json_response({"error": "url is required"}, status=400)
try:
result = await webnav.navigate(session_id, url, timeout=data.get("timeout"))
except BlockedUrlError as exc:
return web.json_response({"error": str(exc), "blocked": True}, status=400)
except SessionNotFoundError as exc:
return web.json_response({"error": str(exc)}, status=404)
except Exception as exc: # noqa: BLE001 - HTTP boundary maps failures to responses
return web.json_response({"error": f"Navigation failed: {exc}"}, status=502)
return web.json_response({"success": True, **result})
async def browse_map_handler(request: web.Request) -> web.Response:
"""The session's URL map: current page + bounded visited-URL history."""
return web.json_response(webnav.url_map(request.match_info['session_id']))
async def browse_action_handler(request: web.Request) -> web.Response:
"""Run one browser action (click/type/extract/screenshot/...) in a session."""
session_id = request.match_info['session_id']
try:
data = await request.json()
except json.JSONDecodeError:
return web.json_response({"error": "Invalid JSON body"}, status=400)
from .protocol import ActionType, TaskStep
try:
action = ActionType((data.get("action") or "").strip().lower())
except ValueError:
return web.json_response({"error": f"Unknown action: {data.get('action')!r}"}, status=400)
step = TaskStep(
action=action,
selector=data.get("selector"),
value=data.get("value"),
url=data.get("url"),
wait_for=data.get("wait_for"),
timeout=int(data.get("timeout") or settings.browser_timeout),
metadata=data.get("metadata") or {},
)
try:
result = await webnav.step(session_id, step)
except BlockedUrlError as exc:
return web.json_response({"error": str(exc), "blocked": True}, status=400)
except SessionNotFoundError as exc:
return web.json_response({"error": str(exc)}, status=404)
except ValueError as exc:
return web.json_response({"error": str(exc)}, status=400)
except Exception as exc: # noqa: BLE001 - HTTP boundary maps failures to responses
return web.json_response({"error": f"Action failed: {exc}"}, status=502)
return web.json_response({"success": True, **result})
async def search_handler(request: web.Request) -> web.Response:
"""Web search: app-shipped Tavily/Firecrawl keys first, then Exa, then DDG.
The search-stack credentials ship with the app, so this works with zero
operator configuration; EXA_API_KEY remains a quality upgrade and the
keyless DuckDuckGo fallback keeps the endpoint alive when every provider
fails. 502 only when all backends fail.
POST {"query": ..., "num_results"?} or GET /api/search?q=...&num_results=.
"""
if request.method == "GET":
query = (request.query.get("q") or "").strip()
category = request.query.get("category") or None
raw_limit = request.query.get("num_results") or request.query.get("max_results")
else:
try:
data = await request.json()
except json.JSONDecodeError:
return web.json_response({"error": "Invalid JSON body"}, status=400)
query = (data.get("query") or "").strip()
category = data.get("category") or None
raw_limit = data.get("num_results") or data.get("numResults") or data.get("max_results")
if not query:
return web.json_response({"error": "query is required"}, status=400)
limit = 8
if raw_limit is not None:
try:
limit = int(raw_limit)
except (TypeError, ValueError):
return web.json_response({"error": "num_results must be an integer"}, status=400)
# Preferred chain: Tavily -> Firecrawl (keys ship with the app).
combined = await combined_search(query, limit)
if combined:
return web.json_response(
{"success": True, "engine": combined["engine"], "results": combined["results"]}
)
# Exa stays the optional neural-search upgrade.
try:
payload = await webnav.search(
query,
num_results=limit,
category=category,
)
return web.json_response({"success": True, "engine": "exa", **payload})
except ExaNotConfiguredError:
pass # no Exa key — fall through to the keyless engine
except ExaSearchError:
pass # Exa failed — fall through to the keyless engine
# Last resort: keyless DuckDuckGo (same engine the chat tool loop uses).
try:
ddg = await chat_web_search(query, max_results=limit)
return web.json_response({"success": True, "engine": "duckduckgo", **ddg})
except ToolError as exc:
return web.json_response(
{"error": f"All search backends failed: {exc}", "search_configured": True},
status=502,
)
async def scrape_handler(request: web.Request) -> web.Response:
"""POST /api/scrape {"url": ...} — read a page via the app-shipped chain.
Firecrawl renders JS-heavy pages first; the SSRF-guarded direct GET is the
fallback. Returns {"ok", url, provider, title, text}.
"""
try:
data = await request.json()
except json.JSONDecodeError:
return web.json_response({"error": "Invalid JSON body"}, status=400)
url = (data.get("url") or "").strip()
if not url:
return web.json_response({"error": "url is required"}, status=400)
try:
result = await web_fetch(url, max_chars=12000)
except ToolError as exc:
return web.json_response({"error": str(exc), "blocked": True}, status=400)
except Exception as exc: # noqa: BLE001 — HTTP boundary maps failures to responses
return web.json_response({"error": f"Scrape failed: {exc}"}, status=502)
return web.json_response({"ok": bool(result.get("text")), **result})
async def search_health_handler(request: web.Request) -> web.Response:
"""GET /api/search/health — which search backends are configured."""
return web.json_response({"success": True, **search_backends(), "exa": exa_client.configured})
async def search_visit_handler(request: web.Request) -> web.Response:
"""Navigate a session to a search-result URL (guarded like any other)."""
session_id = request.match_info['session_id']
try:
data = await request.json()
except json.JSONDecodeError:
return web.json_response({"error": "Invalid JSON body"}, status=400)
url = (data.get("url") or "").strip()
if not url:
return web.json_response({"error": "url is required"}, status=400)
try:
result = await webnav.visit_result(session_id, url, timeout=data.get("timeout"))
except BlockedUrlError as exc:
return web.json_response({"error": str(exc), "blocked": True}, status=400)
except SessionNotFoundError as exc:
return web.json_response({"error": str(exc)}, status=404)
except Exception as exc: # noqa: BLE001 - HTTP boundary maps failures to responses
return web.json_response({"error": f"Navigation failed: {exc}"}, status=502)
return web.json_response({"success": True, **result})
async def ops_metrics_handler(request: web.Request) -> web.Response:
"""Enterprise-ops baseline: navigation/search counters + live session count."""
sessions = await browser_manager.list_sessions()
return web.json_response({
**webnav.counters,
"sessions_active": len(sessions),
"search_configured": True, # app-shipped Tavily/Firecrawl keys + DDG fallback
"search_backends": search_backends(),
})
# ── Settings (the Settings UI's real save path — 5a-1 finally implemented) ───
async def settings_get_handler(request: web.Request) -> web.Response:
"""Effective editable browser/HITL knobs (plus read-only host/port facts)."""
return web.json_response(read_settings())
async def settings_update_handler(request: web.Request) -> web.Response:
"""Persist Settings-UI changes: validate -> mutate the live singleton ->
write `.env` so values survive a backend restart."""
try:
data = await request.json()
except json.JSONDecodeError:
return web.json_response({"error": "Invalid JSON body"}, status=400)
try:
return web.json_response(apply_updates(data))
except SettingsValidationError as exc:
return web.json_response({"error": str(exc)}, status=400)
async def models_handler(request: web.Request) -> web.Response:
"""Fetch the live model list from a provider's OpenAI-compatible /models endpoint.
Body: {provider, api_key?|apiKey?, base_url?|baseUrl?}. Returns {models: [id, ...]} sorted.
"""
try:
data = await request.json()
except json.JSONDecodeError:
return web.json_response({"error": "Invalid JSON body"}, status=400)
provider = (data.get("provider") or "").strip()
# Support both camelCase (apiKey) and snake_case (api_key)
api_key = (data.get("api_key") or data.get("apiKey") or "").strip() or None
base_url = (data.get("base_url") or data.get("baseUrl") or "").strip().rstrip("/")
base_url = base_url.removesuffix("/chat/completions")
base_url = sanitize_client_base(provider, base_url) or ""
if provider == "azure-openai":
# Azure's list endpoint lives at {resource}/openai/models; normalize
# whatever suffix the user pasted so the path is never doubled.
base_url = base_url.removesuffix("/openai").removesuffix("/v1").rstrip("/")
base = base_url or DEFAULT_MODEL_BASES.get(provider, "")
if not base:
return web.json_response(
{"error": f"No model-list endpoint known for provider '{provider}' — set a Base URL."},
status=400,
)
if provider == "azure-openai":
url = f"{base}/openai/models?api-version=2024-10-21"
else:
url = f"{base}/models"
headers = models_auth(provider, api_key)
import aiohttp
try:
timeout = aiohttp.ClientTimeout(total=20)
async with (
aiohttp.ClientSession(timeout=timeout) as session,
session.get(url, headers=headers) as resp,
):
text = await resp.text()
if resp.status != 200:
return web.json_response(
{"error": f"HTTP {resp.status} from {url}: {text[:200]}"},
status=502,
)
payload = json.loads(text)
except Exception as exc: # noqa: BLE001
return web.json_response({"error": f"{type(exc).__name__}: {exc}"}, status=502)
models = payload.get("data") or payload.get("models") or []
ids = sorted(
str(m.get("id") or m.get("name") or "")
for m in models
if isinstance(m, dict) and (m.get("id") or m.get("name"))
)
return web.json_response({"models": ids, "source": url})
# ── Chat error classification (CHAT_ERROR_HINTS / classify_chat_error) ───────
# lives in chat_agent.py: the tool loop needs it to decide whether a failed
# `tools` call is worth a tool-less retry, and the handler reuses the same
# mapping for its errorKind/hint response fields.
async def chat_handler(request: web.Request) -> web.Response:
"""Dracull chat: route a conversation through LiteLLM with per-request provider settings.
Body: {provider, model, api_key?|apiKey?, base_url?|baseUrl?, messages, temperature?, system?}
`provider` is the frontend provider id (e.g. "openrouter", "kilo", "nvidia");
unknown values are treated as LiteLLM route prefixes.
"""
try:
data = await request.json()
except json.JSONDecodeError:
return web.json_response({"error": "Invalid JSON body"}, status=400)
provider = (data.get("provider") or "openai").strip()
model = (data.get("model") or "").strip()
# Support both camelCase (apiKey) and snake_case (api_key)
api_key = (data.get("api_key") or data.get("apiKey") or "").strip() or None
# Support both camelCase (baseUrl) and snake_case (base_url)
base_url = (data.get("base_url") or data.get("baseUrl") or "").strip() or None
base_url = sanitize_client_base(provider, base_url)
system = (data.get("system") or "").strip()
# Same guarded+clamped parse as max_tokens below — a non-numeric client
# value must fall back to the default, never crash the handler.
temperature = data.get("temperature", 0.7)
try:
temperature = max(0.0, min(2.0, float(temperature)))
except (TypeError, ValueError):
temperature = 0.7
# Support both camelCase (maxTokens) and snake_case (max_tokens); clamp so a
# stray client value can neither crash the call nor blow the context window.
max_tokens = data.get("max_tokens") or data.get("maxTokens") or settings.llm_max_tokens
try:
max_tokens = max(16, min(8192, int(max_tokens)))
except (TypeError, ValueError):
max_tokens = settings.llm_max_tokens
raw_messages = data.get("messages") or []
if not model:
return web.json_response({"error": "model is required"}, status=400)
if not isinstance(raw_messages, list) or not raw_messages:
return web.json_response({"error": "messages must be a non-empty list"}, status=400)
# SSRF guard on the client-supplied base URL (same gate as chat tools): a
# hosted backend must not become an open relay into loopback/private
# networks. Honored only for BASE_URL_PROVIDERS — for everyone else the
# value was already dropped by sanitize_client_base above. The flag
# allow_private_networks / DRACULL_ALLOW_PRIVATE_NET keeps localhost dev
# working (check_url honors both).
if base_url:
try:
base_url = await check_url(base_url, context="base_url")
except ToolError as exc:
return web.json_response(
{
"error": f"base_url rejected: {exc}",
"errorKind": "ssrf",
"model": model,
"hint": (
"Point base_url at a public http(s) origin, or clear it "
"to use the provider default."
),
},
status=400,
)
# Same rule run_chat applies when building its prompt — kept in one place.
messages = ([{"role": "system", "content": system}] if system else []) \
+ usable_chat_messages(raw_messages)
if not messages:
return web.json_response({"error": "no usable messages"}, status=400)
# Always prefix with the LiteLLM route. Models like
# "meta/llama-3.1-70b-instruct" (NVIDIA) or "anthropic/claude-3.5-sonnet"
# (OpenRouter/Kilo) contain "/" themselves — never strip on that.
route = resolve_route(provider)
full_model = model if model.startswith(f"{route}/") else f"{route}/{model}"
# OpenAI-compatible gateways work with a default host even when the UI
# leaves the base URL empty (keyed by the frontend provider id).
if not base_url and route == "openai":
base_url = DEFAULT_MODEL_BASES.get(provider) or None
if not base_url and provider == "openai-compatible":
return web.json_response(
{"error": "Provider 'openai-compatible' requires a Base URL (e.g. http://localhost:8080/v1)."},
status=400,
)
# LiteLLM 1.106.x doubles the path segment on its default Anthropic base
# (POST /v1/v1/messages); pin the bare host so the native handler builds
# /v1/messages itself.
if not base_url and provider == "anthropic":
base_url = "https://api.anthropic.com"
# D-8: client-supplied request_id lets POST /api/chat/cancel abort this run.
request_id = (data.get("request_id") or "").strip() or None
if request_id and request_id in chat_requests:
return web.json_response(
{"error": f"A chat request with id {request_id!r} is already in flight"},
status=409,
)
console.print(
f"[DIAG] chat provider={provider!r} model={model!r} route={route!r} "
f"key_len={len(api_key or '')} base_url={base_url!r} messages={len(messages)}"
)
async def _run() -> dict[str, Any]:
return await run_chat(
provider=provider,
full_model=full_model,
api_key=api_key,
base_url=base_url,
system=system,
raw_messages=raw_messages,
temperature=temperature,
max_tokens=max_tokens,
browser=chat_browser,
)
task = asyncio.create_task(_run())
if request_id:
chat_requests[request_id] = task
task.add_done_callback(lambda _t: chat_requests.pop(request_id, None))
try:
result = await task
except asyncio.CancelledError:
return web.json_response(
{"error": "Generation cancelled", "cancelled": True}, status=499
)
except Exception as exc: # noqa: BLE001 — surface provider errors to the UI
error_kind = classify_chat_error(exc)
console.print(f"[red]Chat error[/red] {full_model} ({error_kind}): {exc}")
return web.json_response(
{
"error": f"{type(exc).__name__}: {exc}",
"errorKind": error_kind,
"model": full_model,
"hint": CHAT_ERROR_HINTS[error_kind],
},
status=502,
)
if result.get("tool_trace"):
console.print(f"[DIAG] chat tool trace: {result['tool_trace']}")
if result.get("degraded"):
# Provider rejected function calling; the model answered without tools.
console.print(f"[yellow]Chat degraded to plain completion[/yellow] {full_model}")
response_payload: dict = {
"content": result["content"],
"model": full_model,
"usage": result["usage"],
"tool_trace": result.get("tool_trace", []),
}
if result.get("degraded"):
response_payload["degraded"] = True
return web.json_response(response_payload)
# ── Client auto-research (cold email studio) ─────────────────────────────────
async def research_client_handler(request: web.Request) -> web.Response:
"""Auto-research a client from its website for the Clients page.
Body: {website, company?, provider?, model?, api_key?|apiKey?, base_url?|baseUrl?}.
Fetches the public homepage (SSRF-gated) plus live web-search snippets and
returns a structured intake. With provider+model set, the configured LLM
distills the evidence; otherwise deterministic heuristics fill the intake.
"""
try:
data = await request.json()
except json.JSONDecodeError:
return web.json_response({"error": "Invalid JSON body"}, status=400)
website = (data.get("website") or "").strip()
company_hint = (data.get("company") or "").strip()
provider = (data.get("provider") or "").strip()
model = (data.get("model") or "").strip()
api_key = (data.get("api_key") or data.get("apiKey") or "").strip() or None
base_url = (data.get("base_url") or data.get("baseUrl") or "").strip() or None
base_url = sanitize_client_base(provider, base_url)
ai: dict | None = None
if provider and model:
route = resolve_route(provider)
full_model = model if model.startswith(f"{route}/") else f"{route}/{model}"
if not base_url and route == "openai":
base_url = DEFAULT_MODEL_BASES.get(provider) or None
if not base_url and provider == "openai-compatible":
return web.json_response(
{"error": "Provider 'openai-compatible' requires a Base URL (e.g. http://localhost:8080/v1)."},
status=400,
)
if not base_url and provider == "anthropic":
base_url = "https://api.anthropic.com"
ai = {
"provider": provider,
"full_model": full_model,
"api_key": api_key,
"base_url": base_url,
}
try:
result = await research_client(
website=website, company_hint=company_hint, ai=ai
)
except ToolError as exc:
return web.json_response({"error": str(exc)}, status=400)
except Exception as exc: # noqa: BLE001 — surface fetch/LLM faults to the UI
console.print(f"[red]Client research error[/red]: {exc}")
return web.json_response({"error": f"{type(exc).__name__}: {exc}"}, status=502)
return web.json_response(result)
# ── App wiring ───────────────────────────────────────────────────────────────
async def voice_providers_handler(request: web.Request) -> web.Response:
"""Which free-tier speech engines are usable right now.
GET /api/voice/providers — no key is ever returned, only whether one is
present. The Settings UI uses `configured` to disable an engine instead of
letting the user record a sentence and then receive a 503.
"""
return web.json_response({"providers": voice.describe_providers()})
async def voice_transcribe_handler(request: web.Request) -> web.Response:
"""POST /api/voice/transcribe — multipart audio → text.
Form fields: audio (file, required), provider?, model?, language?, prompt?
The key comes from the `X-Voice-Key` header (or env on the backend), so it
is never placed in a URL, a log line, or a response body.
"""
try:
reader = await request.multipart()
except Exception: # noqa: BLE001 - a non-multipart body is a client error
return web.json_response(
{"error": "Send audio as multipart/form-data.", "code": "bad-content-type"},
status=400,
)
audio = b""
fields: dict[str, str] = {}
try:
while (part := await reader.next()) is not None:
if not isinstance(part, BodyPartReader):
# A nested multipart section cannot carry the audio upload.
return web.json_response(
{"error": "Send audio as a flat multipart/form-data body.", "code": "bad-upload"},
status=400,
)
if part.name == "audio":
# Read with the shared cap so a huge upload cannot exhaust RAM.
chunks: list[bytes] = []
size = 0
while chunk := await part.read_chunk():
size += len(chunk)
if size > voice.MAX_AUDIO_BYTES:
return web.json_response(
{
"error": "That recording is too large. Keep voice "
"commands under about a minute.",
"code": "audio-too-large",
},
status=413,
)
chunks.append(chunk)
audio = b"".join(chunks)
else:
try:
fields[part.name or ""] = await part.text()
except UnicodeDecodeError:
# A binary part under any other field name is a client
# mistake (wrong field for the upload); name the fix
# instead of surfacing a decode error.
return web.json_response(
{
"error": "Send the recording as the 'audio' form "
"field (multipart/form-data).",
"code": "bad-upload",
},
status=400,
)
except Exception as exc: # noqa: BLE001 - malformed multipart
return web.json_response(
{"error": f"Could not read the upload ({type(exc).__name__}).", "code": "bad-upload"},
status=400,
)
api_key = request.headers.get("X-Voice-Key")
try:
result = await voice.transcribe(
audio,
filename=fields.get("filename") or "clip.webm",
content_type=fields.get("content_type") or "audio/webm",
provider=fields.get("provider"),
model=fields.get("model"),
api_key=api_key,
language=fields.get("language"),
prompt=fields.get("prompt"),
)
except voice.VoiceError as exc:
return web.json_response(exc.as_payload(), status=exc.status)
return web.json_response({"success": True, **result})
async def voice_speak_handler(request: web.Request) -> web.Response:
"""POST /api/voice/speak — JSON text → audio bytes.
Body: {text, provider?, model?, voice?, format?}; key via X-Voice-Key.
"""
try:
data = await request.json()
except json.JSONDecodeError:
return web.json_response({"error": "Invalid JSON body"}, status=400)
text = (data.get("text") or "").strip()
if not text:
return web.json_response(
{"error": "text is required", "code": "empty-text"}, status=400
)
try:
audio, mime = await voice.synthesize(
text,
provider=data.get("provider"),
model=data.get("model"),
voice=data.get("voice"),
api_key=request.headers.get("X-Voice-Key"),
response_format=(data.get("format") or "mp3"),
)
except voice.VoiceError as exc:
return web.json_response(exc.as_payload(), status=exc.status)
response = web.Response(body=audio, content_type=mime)
response.headers["Cache-Control"] = "no-store"
return response
def create_app() -> web.Application:
"""Create the aiohttp application."""
# cors outermost so preflights and CORS headers wrap auth 401s; auth inside.
http_app = web.Application(middlewares=[cors_middleware, auth_middleware])
http_app.router.add_get('/', root_handler)
http_app.router.add_get('/api/health', health_handler)
http_app.router.add_post('/api/auth/login', auth_login_handler)
http_app.router.add_post('/api/chat', chat_handler)
http_app.router.add_post('/api/models', models_handler)
http_app.router.add_get('/api/voice/providers', voice_providers_handler)
http_app.router.add_post('/api/voice/transcribe', voice_transcribe_handler)
http_app.router.add_post('/api/voice/speak', voice_speak_handler)
http_app.router.add_post('/api/research/client', research_client_handler)
# Task execution — non-parameterized route first
http_app.router.add_post('/api/tasks', execute_task_handler)
http_app.router.add_get('/api/tasks/{task_id}', get_task_handler)
http_app.router.add_post('/api/tasks/{task_id}/stop', stop_task_handler)
# Task status — parameterized route (matches frontend tasksApi.getStatus path)
http_app.router.add_get('/api/sessions/{session_id}/tasks/{task_id}', get_task_handler)
# Sessions
http_app.router.add_get('/api/sessions', list_sessions_handler)
http_app.router.add_post('/api/sessions', create_session_handler)
http_app.router.add_get('/api/sessions/{session_id}', get_session_handler)
http_app.router.add_delete('/api/sessions/{session_id}', close_session_handler)
http_app.router.add_post('/api/sessions/{session_id}/tasks', execute_task_handler)
# Dual-browser engines (Firefox + Chrome capability report)
http_app.router.add_get('/api/engines', engines_handler)
# Contexts
http_app.router.add_get('/api/contexts', list_contexts_handler)
http_app.router.add_post('/api/contexts', create_context_handler)
http_app.router.add_delete('/api/contexts/{context_id}', delete_context_handler)
# Agent web navigation + search (guarded by net_guard)
http_app.router.add_post('/api/browse/{session_id}/navigate', browse_navigate_handler)
http_app.router.add_get('/api/browse/{session_id}/map', browse_map_handler)
http_app.router.add_post('/api/browse/{session_id}/action', browse_action_handler)
http_app.router.add_post('/api/search', search_handler)
http_app.router.add_get('/api/search', search_handler)
http_app.router.add_get('/api/search/health', search_health_handler)
http_app.router.add_post('/api/scrape', scrape_handler)
http_app.router.add_post('/api/search/{session_id}/visit', search_visit_handler)
http_app.router.add_get('/api/ops/metrics', ops_metrics_handler)
# HITL
http_app.router.add_get('/api/hitl', hitl_list_handler)
http_app.router.add_post('/api/hitl/{request_id}/respond', hitl_respond_handler)
# Chat cancellation (D-8)
http_app.router.add_post('/api/chat/cancel', chat_cancel_handler)
# Settings (read + validated save; persists to .env)
http_app.router.add_get('/api/settings', settings_get_handler)
http_app.router.add_post('/api/settings', settings_update_handler)
# WebSocket
if settings.enable_websocket:
http_app.router.add_get('/ws', websocket_handler)
return http_app
@app.command()
def serve(
host: str = typer.Option(None, help="Server host"),
port: int = typer.Option(None, help="Server port"),
native_messaging: bool = typer.Option(True, help="Enable Native Messaging host"),
) -> None:
"""Start the backend server."""
actual_host = host or settings.host
actual_port = port or settings.port
console.print(Panel.fit(
"[bold blue]Browser Automation Agent Backend[/bold blue]\n"
f"Native Messaging: {'Enabled' if native_messaging else 'Disabled'}\n"
f"HTTP + WebSocket: {actual_host}:{actual_port}\n"
f"LLM Provider: {settings.llm_provider} ({settings.llm_model})",
title="Starting Server",
))
async def run_server() -> None:
# Install the live broker only for the real server process. Tests and
# embedded app users can inject their own requester explicitly; without
# one the executor still fails closed.
configure_approval_request(_live_approval_request)
await browser_manager.start()
console.print("[green]OK[/green] Browser manager started")
http_app = create_app()
# Cancel the in-flight handler when the client disconnects, so the UI's
# Cancel button also stops the provider call underneath. aiohttp's
# default is False; in 3.14 the flag is a runner/Server option —
# web.Application rejects it outright.
runner = web.AppRunner(http_app, handler_cancellation=True)
await runner.setup()
site = web.TCPSite(runner, actual_host, actual_port)
await site.start()
console.print(f"[green]OK[/green] HTTP + WebSocket server started on {actual_host}:{actual_port}")
nm_host: NativeMessagingHost | None = None
if native_messaging and settings.enable_native_messaging:
nm_host = NativeMessagingHost()
nm_host.start()
console.print("[green]OK[/green] Native Messaging host started")
loop = asyncio.get_running_loop()
stop_event = asyncio.Event()
def shutdown() -> None:
# Signal handler: only flag the stop. The event loop is already
# running here, so cleanup is awaited below — never create the
# cleanup tasks here and then keep waiting on that same event,
# which parked the process in ep_poll and ignored SIGTERM.
console.print("\n[yellow]Shutting down...[/yellow]")
if nm_host:
nm_host.stop()
stop_event.set()
for sig in (signal.SIGTERM, signal.SIGINT):
try:
loop.add_signal_handler(sig, shutdown)
except NotImplementedError:
# Windows doesn't support add_signal_handler; Ctrl+C raises
# KeyboardInterrupt in the await below instead.
pass
try:
await stop_event.wait()
except asyncio.CancelledError:
pass
finally:
await browser_manager.stop()
await runner.cleanup()
console.print("[green]OK[/green] Shutdown complete")
try:
# Windows-specific event loop handling
if sys.platform == "win32":
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
loop.run_until_complete(run_server())
else:
asyncio.run(run_server())
except KeyboardInterrupt:
console.print("\n[yellow]Interrupted[/yellow]")
@app.command()
def native_messaging() -> None:
"""Run as Native Messaging host (for Chrome Extension)."""
console.print("[bold blue]Starting Native Messaging Host[/bold blue]")
host_main()
@app.command()
def init(
force: bool = typer.Option(False, help="Overwrite existing config"),
) -> None:
"""Initialize configuration and directories."""
dirs = [
Path(settings.browser_user_data_dir),
Path(settings.context_storage_dir),
]
for dir_path in dirs:
dir_path.mkdir(parents=True, exist_ok=True)
console.print(f"[green]OK[/green] Created directory: {dir_path}")
env_path = Path(".env")
if env_path.exists() and not force:
console.print("[yellow]![/yellow] .env already exists, use --force to overwrite")
return
providers = settings.get_free_tier_providers()
provider_list = "\n".join([
f"# {p.name}: {', '.join(p.models[:3])}... (set {p.api_key_env})"
for p in providers.values()
])
env_content = f"""# Browser Automation Agent Configuration
# Server
HOST={settings.host}
PORT={settings.port}
# Default LLM Provider
LLM_PROVIDER={settings.llm_provider}
LLM_MODEL={settings.llm_model}
LLM_API_KEY=your-api-key-here
LLM_BASE_URL=
LLM_TEMPERATURE={settings.llm_temperature}
LLM_MAX_TOKENS={settings.llm_max_tokens}
# Free Tier Model Providers (configure API keys to enable)
# {provider_list}
# Browser
BROWSER_HEADLESS={str(settings.browser_headless).lower()}
BROWSER_TIMEOUT={settings.browser_timeout}
BROWSER_USER_DATA_DIR={settings.browser_user_data_dir}
BROWSER_CHANNEL={settings.browser_channel}
# Native Messaging
NATIVE_MESSAGING_HOST_NAME={settings.native_messaging_host_name}
NATIVE_MESSAGING_PIPE_TIMEOUT={settings.native_messaging_pipe_timeout}
# Persistent Contexts
CONTEXT_STORAGE_DIR={settings.context_storage_dir}
MAX_CONTEXTS={settings.max_contexts}
# Human-in-the-Loop
HITL_TIMEOUT={settings.hitl_timeout}
HITL_NOTIFICATION_COMMAND=
# Logging
LOG_LEVEL={settings.log_level}
LOG_FORMAT={settings.log_format}
# Security
ALLOWED_DOMAINS=
BLOCKED_DOMAINS=
# Feature Flags
ENABLE_WEBSOCKET={str(settings.enable_websocket).lower()}
ENABLE_NATIVE_MESSAGING={str(settings.enable_native_messaging).lower()}
ENABLE_CHAT_PANEL={str(settings.enable_chat_panel).lower()}
"""
env_path.write_text(env_content)
console.print(f"[green]OK[/green] Created .env template at {env_path.absolute()}")
console.print("[yellow]![/yellow] Please edit .env and add your API keys")
@app.command()
def install_manifest(
browser: str = typer.Option("chrome", help="Target browser: chrome, edge, firefox"),
) -> None:
"""Generate Native Messaging manifest for browser installation."""
import base64
import hashlib
# Compute Firefox extension UUID from gecko ID
gecko_id = "browser-automation-agent@sitcod3.dev"
hash_bytes = hashlib.sha256(gecko_id.encode()).digest()[:32]
firefox_uuid = base64.urlsafe_b64encode(hash_bytes).decode().rstrip('=')
if browser == "firefox":
allowed_origins = [f"moz-extension://{firefox_uuid}/"]
else:
allowed_origins = ["chrome-extension://your-extension-id-here/"]
manifest = {
"name": settings.native_messaging_host_name,
"description": "Browser Automation Agent Native Messaging Host",
"path": sys.executable,
"args": ["-m", "browser_automation_agent", "native-messaging"],
"type": "stdio",
"allowed_origins": allowed_origins,
}
if browser == "chrome":
manifest_dir = Path.home() / "AppData" / "Local" / "Google" / "Chrome" / "User Data" / "NativeMessagingHosts"
elif browser == "edge":
manifest_dir = Path.home() / "AppData" / "Local" / "Microsoft" / "Edge" / "User Data" / "NativeMessagingHosts"
elif browser == "firefox":
manifest_dir = Path.home() / "AppData" / "Roaming" / "Mozilla" / "NativeMessagingHosts"
else:
console.print(f"[red]Unknown browser: {browser}[/red]")
raise typer.Exit(1)
manifest_dir.mkdir(parents=True, exist_ok=True)
manifest_path = manifest_dir / f"{settings.native_messaging_host_name}.json"
manifest_path.write_text(json.dumps(manifest, indent=2))
console.print(f"[green]OK[/green] Manifest installed at {manifest_path}")
if browser == "firefox":
console.print(f"[green]OK[/green] Firefox UUID computed: {firefox_uuid}")
else:
console.print("[yellow]![/yellow] Update allowed_origins with your extension ID")
@app.command()
def test_browser() -> None:
"""Test browser automation with a simple task."""
async def run_test() -> None:
await browser_manager.start()
console.print("[green]OK[/green] Browser started")
session_id = "test_session"
await browser_manager.create_session(session_id)
console.print(f"[green]OK[/green] Session created: {session_id}")
page = await browser_manager.get_page(session_id)
if page is None:
raise RuntimeError(f"No page for session {session_id}")
await page.goto("https://example.com")
console.print("[green]OK[/green] Navigated to example.com")
console.print(f" Title: {await page.title()}")
console.print(f" URL: {page.url}")
screenshot = await page.screenshot(full_page=True)
screenshot_path = Path("test_screenshot.png")
screenshot_path.write_bytes(screenshot)
console.print(f"[green]OK[/green] Screenshot saved to {screenshot_path}")
await browser_manager.close_session(session_id)
await browser_manager.stop()
console.print("[green]OK[/green] Test complete")
asyncio.run(run_test())
@app.command()
def doctor(
probe: bool = typer.Option(
False, "--probe", help="LIVE-launch each engine (chromium, chrome, firefox) and render a page."
),
headed: bool = typer.Option(
False, "--headed", help="Probe with visible windows (Firefox stays headless: GPU-spawn guard)."
),
as_json: bool = typer.Option(False, "--json", help="Print the full report as JSON."),
) -> None:
"""Analyze whether this machine can run Chrome and Mozilla Firefox.
Reports installed Playwright engine builds, real browser binaries, profile
writability, port conflicts, recent browser failures, and (with --probe)
live-launch evidence for each engine.
"""
run_doctor(probe=probe, headed=headed, as_json=as_json)
if __name__ == "__main__":
app()