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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
"""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"<li><code>{e}</code></li>" for e in info["endpoints"])
        return web.Response(
            content_type="text/html",
            text=(
                "<!doctype html><meta charset=utf-8><title>Dracull API</title>"
                "<style>body{font:15px/1.5 system-ui,sans-serif;margin:3rem auto;"
                "max-width:40rem;padding:0 1.5rem;color:#1a1a1a}"
                "code{background:#f4f4f5;padding:.15rem .35rem;border-radius:.25rem}"
                "a{color:#b4232f}</style>"
                "<h1>Dracull API is running</h1>"
                f"<p>This port ({request.host}) serves the <strong>HTTP API only</strong>. "
                "The interface is the Vite app on port <strong>3000</strong>.</p>"
                "<p><a href=\"/api/health\">/api/health</a></p>"
                f"<ul>{rows}</ul>"
            ),
        )
    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()