File size: 89,214 Bytes
652fb13 1b6ea31 d16d9de 3ed8254 e2f7aa4 1b6ea31 d16d9de 8b4698e 3ed8254 8b4698e 6b5507f 005a28c 6b5507f 8b4698e 652fb13 3ed8254 652fb13 d16d9de 8b4698e 1b6ea31 6b5507f 1b6ea31 e2f7aa4 1b6ea31 e2f7aa4 1b6ea31 e2f7aa4 1b6ea31 e2f7aa4 1b6ea31 e2f7aa4 1b6ea31 6b5507f 1b6ea31 6ee3945 568bedd 005a28c 6ee3945 3ed8254 005a28c 3ed8254 005a28c 3ed8254 8b4698e 3ed8254 8b4698e 3ed8254 005a28c 3ed8254 8b4698e 005a28c 8b4698e 568bedd 8b4698e 0fdb6ce 8b4698e 3ed8254 8b4698e 652fb13 8b4698e 568bedd 8b4698e 568bedd 8b4698e 568bedd 8b4698e 005a28c 0c76d87 005a28c 0c76d87 005a28c 0c76d87 005a28c 8b4698e 568bedd 6ee3945 568bedd 8b4698e 652fb13 3ed8254 652fb13 3ed8254 652fb13 3ed8254 652fb13 0fdb6ce d16d9de daf5a20 bf58fe5 1b6ea31 6ee3945 0d90437 6ee3945 0d90437 6ee3945 3ed8254 6ee3945 3ed8254 6ee3945 1b6ea31 6ee3945 1b6ea31 6ee3945 1b6ea31 6ee3945 1b6ea31 8b4698e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 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 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 | import os
import json
import signal
import time
from collections import deque
from datetime import datetime, timedelta, timezone
from pathlib import Path
from threading import Lock, Thread
from typing import Any, Callable, Dict, List, Optional
from fastapi import APIRouter, Header, HTTPException, Request
from app.services.bootstrap_settings_service import (
BOOTSTRAP_SETTING_SPECS,
RUNTIME_SETTING_SPECS,
apply_settings,
snapshot_settings,
)
_USAGE_MAX_LINES_CAP = 50000
_USAGE_EVENTS_CACHE_LOCK = Lock()
_USAGE_EVENTS_CACHE: Dict[str, Any] = {
"path": "",
"max_keep": 0,
"mtime_ns": -1,
"size": -1,
"built_at": 0.0,
"result": None,
}
_READY_ACCOUNT_STATUSES = {"ready", "oauth_ok", "verified"}
def _to_bool(v: Any, default: bool = False) -> bool:
if v is None:
return default
if isinstance(v, bool):
return v
return str(v).strip().lower() in ("1", "true", "yes", "y", "on")
def _runtime_settings_snapshot(settings) -> Dict[str, Any]:
return snapshot_settings(settings, RUNTIME_SETTING_SPECS)
def _trigger_self_restart(delay_sec: float = 0.3) -> None:
def _worker() -> None:
try:
time.sleep(max(float(delay_sec), 0.05))
except Exception:
pass
try:
os.kill(os.getpid(), signal.SIGTERM)
except Exception:
os._exit(0)
Thread(target=_worker, daemon=True).start()
def _parse_emails_text(text: str) -> List[Dict[str, str]]:
out: List[Dict[str, str]] = []
seen = set()
for raw in str(text or "").splitlines():
line = raw.strip().lstrip("\ufeff")
if not line or line.startswith("#"):
continue
if "," in line:
email, password = line.split(",", 1)
elif "\t" in line:
email, password = line.split("\t", 1)
else:
email, password = line, ""
email = email.strip()
password = password.strip()
if not email:
continue
key = email.lower()
if key in seen:
continue
seen.add(key)
out.append({"email": email, "password": password})
return out
def _parse_items(payload: Dict[str, Any]) -> List[Dict[str, str]]:
if isinstance(payload.get("emails_text"), str) and payload.get("emails_text", "").strip():
return _parse_emails_text(str(payload.get("emails_text")))
rows = payload.get("items")
out: List[Dict[str, str]] = []
seen = set()
if isinstance(rows, list):
for item in rows:
if isinstance(item, str):
email = item.strip()
password = ""
elif isinstance(item, dict):
email = str(item.get("email") or "").strip()
password = str(item.get("password") or "").strip()
else:
continue
if not email:
continue
key = email.lower()
if key in seen:
continue
seen.add(key)
out.append({"email": email, "password": password})
return out
def _jsonl_log_path(filename: str) -> Path:
base = Path(str(filename or "").strip() or "openai_adapter_run.jsonl").name
log_dir = str(os.getenv("JSONL_LOG_DIR", "") or "").strip()
if log_dir:
return Path(log_dir) / base
return Path(base)
def _safe_int(v: Any) -> Optional[int]:
try:
if v is None:
return None
return int(v)
except Exception:
return None
def _safe_float(v: Any) -> Optional[float]:
try:
if v is None:
return None
return float(v)
except Exception:
return None
def _parse_iso_utc(ts: Any) -> Optional[datetime]:
if not isinstance(ts, str):
return None
raw = ts.strip()
if not raw:
return None
try:
dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
except Exception:
return None
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def _normalize_usage_event(row: Dict[str, Any], source: str) -> Optional[Dict[str, Any]]:
dt = _parse_iso_utc(row.get("ts"))
if dt is None:
return None
prompt_tokens = max(_safe_int(row.get("prompt_tokens")) or 0, 0)
completion_tokens = max(_safe_int(row.get("completion_tokens")) or 0, 0)
total_tokens = _safe_int(row.get("total_tokens"))
if total_tokens is None:
total_tokens = prompt_tokens + completion_tokens
total_tokens = max(total_tokens, 0)
cached_tokens = max(_safe_int(row.get("cached_tokens")) or 0, 0)
reasoning_tokens = max(_safe_int(row.get("reasoning_tokens")) or 0, 0)
model = str(row.get("model") or "").strip() or "unknown"
status = str(row.get("status") or "").strip().lower()
success = _to_bool(row.get("success"), default=(status not in ("failed", "canceled", "timeout")))
runtime = _safe_float(row.get("runtime"))
credits_used = _safe_float(row.get("credits_used"))
return {
"ts": dt.isoformat().replace("+00:00", "Z"),
"dt": dt,
"source": source,
"model": model,
"success": bool(success),
"status": status or ("success" if success else "failed"),
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": total_tokens,
"cached_tokens": cached_tokens,
"reasoning_tokens": reasoning_tokens,
"tokens_estimated": _to_bool(row.get("tokens_estimated"), default=(source != "usage_event")),
"stream": _to_bool(row.get("stream"), default=False),
"conversation_id": str(row.get("conversation_id") or ""),
"account_email": str(row.get("account_email") or row.get("email") or ""),
"execution_id": row.get("execution_id"),
"app_id": row.get("app_id"),
"runtime": runtime,
"credits_used": credits_used,
"error": str(row.get("error") or ""),
}
def _collect_usage_events(max_lines: int = 200000) -> Dict[str, Any]:
path = _jsonl_log_path("openai_adapter_run.jsonl")
if not path.exists():
return {"source": "none", "events": [], "path": str(path)}
try:
st = path.stat()
mtime_ns = int(st.st_mtime_ns)
size = int(st.st_size)
except OSError:
return {"source": "none", "events": [], "path": str(path)}
ttl_raw = _safe_int(os.getenv("USAGE_CACHE_TTL_SEC", "5"))
cache_ttl = max(ttl_raw if ttl_raw is not None else 5, 0)
max_keep = min(max(int(max_lines), 1), _USAGE_MAX_LINES_CAP)
cache_now = time.time()
with _USAGE_EVENTS_CACHE_LOCK:
cached = _USAGE_EVENTS_CACHE.get("result")
if (
cache_ttl > 0
and isinstance(cached, dict)
and _USAGE_EVENTS_CACHE.get("path") == str(path)
and _USAGE_EVENTS_CACHE.get("max_keep") == max_keep
and _USAGE_EVENTS_CACHE.get("mtime_ns") == mtime_ns
and _USAGE_EVENTS_CACHE.get("size") == size
and (cache_now - float(_USAGE_EVENTS_CACHE.get("built_at") or 0.0)) <= cache_ttl
):
return cached
usage_rows: List[Dict[str, Any]] = []
legacy_rows: List[Dict[str, Any]] = []
# Keep the latest N lines instead of the oldest N lines.
# Otherwise stats will appear "stuck" once the log grows beyond max_lines.
tail_lines = deque(maxlen=max_keep)
with path.open("r", encoding="utf-8", errors="ignore") as f:
for raw in f:
tail_lines.append(raw)
for raw in tail_lines:
text = raw.strip()
if not text:
continue
try:
row = json.loads(text)
except Exception:
continue
if not isinstance(row, dict):
continue
event = str(row.get("event") or "").strip()
if event == "usage_event":
normalized = _normalize_usage_event(row, source="usage_event")
if normalized is not None:
usage_rows.append(normalized)
continue
if event in (
"app_created_no_reuse",
"app_created_for_conversation",
"app_reused_for_conversation",
"app_recreated_for_conversation",
):
normalized = _normalize_usage_event(
{
"ts": row.get("ts"),
"model": "unknown",
"success": True,
"status": "success",
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0,
"tokens_estimated": True,
"stream": False,
"conversation_id": row.get("conversation_id"),
"account_email": row.get("email", ""),
"app_id": row.get("app_id"),
},
source="legacy_log",
)
if normalized is not None:
legacy_rows.append(normalized)
continue
if event in ("account_chat_failed", "account_stream_failed"):
normalized = _normalize_usage_event(
{
"ts": row.get("ts"),
"model": "unknown",
"success": False,
"status": "failed",
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0,
"tokens_estimated": True,
"stream": event == "account_stream_failed",
"conversation_id": row.get("conversation_id"),
"account_email": row.get("email", ""),
"error": row.get("error", ""),
},
source="legacy_log",
)
if normalized is not None:
legacy_rows.append(normalized)
result = {"source": "usage_event", "events": usage_rows, "path": str(path)} if usage_rows else {
"source": "legacy_log",
"events": legacy_rows,
"path": str(path),
}
with _USAGE_EVENTS_CACHE_LOCK:
_USAGE_EVENTS_CACHE["path"] = str(path)
_USAGE_EVENTS_CACHE["max_keep"] = max_keep
_USAGE_EVENTS_CACHE["mtime_ns"] = mtime_ns
_USAGE_EVENTS_CACHE["size"] = size
_USAGE_EVENTS_CACHE["built_at"] = time.time()
_USAGE_EVENTS_CACHE["result"] = result
return result
def _build_usage_snapshot(
rows: List[Dict[str, Any]],
*,
source: str,
log_path: str,
days: int = 14,
hours: int = 24,
model_limit: int = 30,
events_limit: int = 200,
) -> Dict[str, Any]:
days = max(int(days), 1)
hours = max(int(hours), 1)
model_limit = max(int(model_limit), 1)
events_limit = max(int(events_limit), 1)
now = datetime.now(timezone.utc)
day_floor = (now - timedelta(days=days - 1)).replace(hour=0, minute=0, second=0, microsecond=0)
hour_floor = (now - timedelta(hours=hours - 1)).replace(minute=0, second=0, microsecond=0)
rows_sorted = sorted((r for r in rows if isinstance(r.get("dt"), datetime)), key=lambda x: x["dt"])
rows_window = [r for r in rows_sorted if r["dt"] >= day_floor]
rows_hour_window = [r for r in rows_sorted if r["dt"] >= hour_floor]
summary = {
"total_requests": 0,
"success_count": 0,
"failure_count": 0,
"success_rate": 0.0,
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0,
"cached_tokens": 0,
"reasoning_tokens": 0,
"unique_models": 0,
"avg_tokens_per_request": 0.0,
"last_event_at": "",
}
by_model: Dict[str, Dict[str, Any]] = {}
model_set = set()
for r in rows_window:
summary["total_requests"] += 1
if r.get("success"):
summary["success_count"] += 1
else:
summary["failure_count"] += 1
summary["prompt_tokens"] += int(r.get("prompt_tokens") or 0)
summary["completion_tokens"] += int(r.get("completion_tokens") or 0)
summary["total_tokens"] += int(r.get("total_tokens") or 0)
summary["cached_tokens"] += int(r.get("cached_tokens") or 0)
summary["reasoning_tokens"] += int(r.get("reasoning_tokens") or 0)
summary["last_event_at"] = r["ts"]
model = str(r.get("model") or "unknown")
model_set.add(model)
stat = by_model.get(model)
if stat is None:
stat = {
"model": model,
"requests": 0,
"success_count": 0,
"failure_count": 0,
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0,
"last_seen_at": "",
}
by_model[model] = stat
stat["requests"] += 1
if r.get("success"):
stat["success_count"] += 1
else:
stat["failure_count"] += 1
stat["prompt_tokens"] += int(r.get("prompt_tokens") or 0)
stat["completion_tokens"] += int(r.get("completion_tokens") or 0)
stat["total_tokens"] += int(r.get("total_tokens") or 0)
stat["last_seen_at"] = r["ts"]
if summary["total_requests"] > 0:
summary["success_rate"] = round(100.0 * summary["success_count"] / summary["total_requests"], 2)
summary["avg_tokens_per_request"] = round(summary["total_tokens"] / summary["total_requests"], 2)
summary["unique_models"] = len(model_set)
day_buckets: Dict[str, Dict[str, Any]] = {}
cursor = day_floor
while cursor <= now:
key = cursor.strftime("%Y-%m-%d")
day_buckets[key] = {
"bucket": key,
"requests": 0,
"success_count": 0,
"failure_count": 0,
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0,
}
cursor += timedelta(days=1)
for r in rows_window:
key = r["dt"].strftime("%Y-%m-%d")
b = day_buckets.get(key)
if b is None:
continue
b["requests"] += 1
if r.get("success"):
b["success_count"] += 1
else:
b["failure_count"] += 1
b["prompt_tokens"] += int(r.get("prompt_tokens") or 0)
b["completion_tokens"] += int(r.get("completion_tokens") or 0)
b["total_tokens"] += int(r.get("total_tokens") or 0)
hour_buckets: Dict[str, Dict[str, Any]] = {}
cursor = hour_floor
while cursor <= now:
key = cursor.strftime("%Y-%m-%d %H:00")
hour_buckets[key] = {
"bucket": key,
"requests": 0,
"success_count": 0,
"failure_count": 0,
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0,
}
cursor += timedelta(hours=1)
for r in rows_hour_window:
key = r["dt"].strftime("%Y-%m-%d %H:00")
b = hour_buckets.get(key)
if b is None:
continue
b["requests"] += 1
if r.get("success"):
b["success_count"] += 1
else:
b["failure_count"] += 1
b["prompt_tokens"] += int(r.get("prompt_tokens") or 0)
b["completion_tokens"] += int(r.get("completion_tokens") or 0)
b["total_tokens"] += int(r.get("total_tokens") or 0)
models = sorted(
by_model.values(),
key=lambda x: (int(x.get("requests") or 0), int(x.get("total_tokens") or 0)),
reverse=True,
)
for m in models:
req = int(m.get("requests") or 0)
m["success_rate"] = round(100.0 * int(m.get("success_count") or 0) / req, 2) if req else 0.0
m["avg_tokens_per_request"] = round(int(m.get("total_tokens") or 0) / req, 2) if req else 0.0
recent_events = sorted(rows_window, key=lambda x: x["dt"], reverse=True)[:events_limit]
recent_events_out = []
for r in recent_events:
out = {k: v for k, v in r.items() if k != "dt"}
recent_events_out.append(out)
return {
"source": source,
"log_path": log_path,
"generated_at": now.isoformat().replace("+00:00", "Z"),
"window_days": days,
"hour_window": hours,
"summary": summary,
"trends": {
"by_day": list(day_buckets.values()),
"by_hour": list(hour_buckets.values()),
},
"models": models[:model_limit],
"recent_events": recent_events_out,
"raw_events_in_window": len(rows_window),
}
def _build_cpa_usage_payload(
rows: List[Dict[str, Any]],
*,
source: str,
log_path: str,
event_limit: int = 20000,
) -> Dict[str, Any]:
event_limit = max(int(event_limit), 1)
now = datetime.now(timezone.utc)
rows_sorted = sorted((r for r in rows if isinstance(r.get("dt"), datetime)), key=lambda x: x["dt"])
if len(rows_sorted) > event_limit:
rows_sorted = rows_sorted[-event_limit:]
usage: Dict[str, Any] = {
"source": source,
"log_path": log_path,
"generated_at": now.isoformat().replace("+00:00", "Z"),
"total_requests": 0,
"success_count": 0,
"failure_count": 0,
"total_tokens": 0,
"apis": {},
}
apis = usage["apis"]
endpoint_key = "POST /v1/chat/completions"
for r in rows_sorted:
model_name = str(r.get("model") or "unknown")
success = bool(r.get("success"))
prompt_tokens = max(_safe_int(r.get("prompt_tokens")) or 0, 0)
completion_tokens = max(_safe_int(r.get("completion_tokens")) or 0, 0)
total_tokens = _safe_int(r.get("total_tokens"))
if total_tokens is None:
total_tokens = prompt_tokens + completion_tokens
total_tokens = max(total_tokens, 0)
cached_tokens = max(_safe_int(r.get("cached_tokens")) or 0, 0)
reasoning_tokens = max(_safe_int(r.get("reasoning_tokens")) or 0, 0)
account_email = str(r.get("account_email") or "").strip()
conversation_id = str(r.get("conversation_id") or "").strip()
source_id = account_email or conversation_id or "unknown"
api_entry = apis.get(endpoint_key)
if not isinstance(api_entry, dict):
api_entry = {
"total_requests": 0,
"success_count": 0,
"failure_count": 0,
"total_tokens": 0,
"models": {},
}
apis[endpoint_key] = api_entry
models = api_entry.get("models")
if not isinstance(models, dict):
models = {}
api_entry["models"] = models
model_entry = models.get(model_name)
if not isinstance(model_entry, dict):
model_entry = {
"total_requests": 0,
"success_count": 0,
"failure_count": 0,
"total_tokens": 0,
"details": [],
}
models[model_name] = model_entry
detail = {
"timestamp": str(r.get("ts") or ""),
"source": source_id,
"auth_index": 0,
"failed": not success,
"tokens": {
"input_tokens": prompt_tokens,
"output_tokens": completion_tokens,
"reasoning_tokens": reasoning_tokens,
"cached_tokens": cached_tokens,
"total_tokens": total_tokens,
},
"status": str(r.get("status") or ("success" if success else "failed")),
"runtime": _safe_float(r.get("runtime")),
"conversation_id": conversation_id,
"account_email": account_email,
"error": str(r.get("error") or ""),
}
details = model_entry.get("details")
if not isinstance(details, list):
details = []
model_entry["details"] = details
details.append(detail)
usage["total_requests"] += 1
usage["total_tokens"] += total_tokens
api_entry["total_requests"] += 1
api_entry["total_tokens"] += total_tokens
model_entry["total_requests"] += 1
model_entry["total_tokens"] += total_tokens
if success:
usage["success_count"] += 1
api_entry["success_count"] += 1
model_entry["success_count"] += 1
else:
usage["failure_count"] += 1
api_entry["failure_count"] += 1
model_entry["failure_count"] += 1
return usage
def _extract_usage_rows_from_cpa_payload(payload: Dict[str, Any]) -> List[Dict[str, Any]]:
if not isinstance(payload, dict):
return []
root = payload.get("usage") if isinstance(payload.get("usage"), dict) else payload
if not isinstance(root, dict):
return []
apis = root.get("apis")
if not isinstance(apis, dict):
return []
out: List[Dict[str, Any]] = []
for _endpoint, api_entry in apis.items():
if not isinstance(api_entry, dict):
continue
models = api_entry.get("models")
if not isinstance(models, dict):
continue
for model_name, model_entry in models.items():
if not isinstance(model_entry, dict):
continue
details = model_entry.get("details")
if not isinstance(details, list):
continue
for d in details:
if not isinstance(d, dict):
continue
timestamp = str(d.get("timestamp") or "").strip()
if not timestamp:
continue
tokens = d.get("tokens")
tokens_obj = tokens if isinstance(tokens, dict) else {}
prompt_tokens = max(_safe_int(tokens_obj.get("input_tokens")) or 0, 0)
completion_tokens = max(_safe_int(tokens_obj.get("output_tokens")) or 0, 0)
total_tokens = _safe_int(tokens_obj.get("total_tokens"))
if total_tokens is None:
total_tokens = prompt_tokens + completion_tokens
total_tokens = max(total_tokens, 0)
cached_tokens = max(_safe_int(tokens_obj.get("cached_tokens")) or 0, 0)
reasoning_tokens = max(_safe_int(tokens_obj.get("reasoning_tokens")) or 0, 0)
failed = _to_bool(d.get("failed"), default=False)
success = not failed
account_email = str(d.get("account_email") or "").strip()
conversation_id = str(d.get("conversation_id") or "").strip()
source_text = str(d.get("source") or "").strip()
if not account_email and source_text and "@" in source_text:
account_email = source_text
out.append(
{
"ts": timestamp,
"model": str(model_name or "unknown"),
"conversation_id": conversation_id,
"stream": False,
"success": success,
"status": str(d.get("status") or ("failed" if failed else "success")),
"error": str(d.get("error") or ""),
"account_email": account_email,
"execution_id": d.get("execution_id"),
"app_id": d.get("app_id"),
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": total_tokens,
"cached_tokens": cached_tokens,
"reasoning_tokens": reasoning_tokens,
"tokens_estimated": _to_bool(d.get("tokens_estimated"), default=False),
"runtime": _safe_float(d.get("runtime")),
"credits_used": _safe_float(d.get("credits_used")),
}
)
return out
def _append_usage_rows_to_log(rows: List[Dict[str, Any]]) -> Dict[str, int]:
if not rows:
return {"added": 0, "skipped": 0, "failed_requests": 0}
log_path = _jsonl_log_path("openai_adapter_run.jsonl")
added = 0
skipped = 0
failed_requests = 0
with log_path.open("a", encoding="utf-8") as f:
for row in rows:
normalized = _normalize_usage_event(row, source="usage_event")
if normalized is None:
skipped += 1
continue
if not normalized.get("success"):
failed_requests += 1
to_write = {
"ts": normalized.get("ts"),
"event": "usage_event",
"model": normalized.get("model"),
"conversation_id": normalized.get("conversation_id"),
"stream": normalized.get("stream"),
"success": normalized.get("success"),
"status": normalized.get("status"),
"error": normalized.get("error"),
"account_email": normalized.get("account_email"),
"execution_id": normalized.get("execution_id"),
"app_id": normalized.get("app_id"),
"prompt_tokens": normalized.get("prompt_tokens"),
"completion_tokens": normalized.get("completion_tokens"),
"total_tokens": normalized.get("total_tokens"),
"cached_tokens": normalized.get("cached_tokens"),
"reasoning_tokens": normalized.get("reasoning_tokens"),
"tokens_estimated": normalized.get("tokens_estimated"),
"runtime": normalized.get("runtime"),
"credits_used": normalized.get("credits_used"),
}
f.write(json.dumps(to_write, ensure_ascii=False) + "\n")
added += 1
return {"added": added, "skipped": skipped, "failed_requests": failed_requests}
def _list_accounts_for_backup(account_store, limit: int = 20000) -> List[Dict[str, Any]]:
n = max(int(limit), 1)
if hasattr(account_store, "list_accounts_full"):
rows = account_store.list_accounts_full(limit=n)
if isinstance(rows, list):
return [r for r in rows if isinstance(r, dict)]
# Compatibility fallback for custom stores without list_accounts_full.
out: List[Dict[str, Any]] = []
base = account_store.list_accounts(limit=n) if hasattr(account_store, "list_accounts") else []
if not isinstance(base, list):
return out
for row in base:
if not isinstance(row, dict):
continue
email = str(row.get("email") or "").strip()
if not email:
continue
full = account_store.get_by_email(email) if hasattr(account_store, "get_by_email") else None
if isinstance(full, dict):
merged = dict(row)
merged["password"] = full.get("password")
out.append(merged)
else:
out.append(dict(row))
return out
def _list_conversations_for_backup(conv_store, limit: int = 20000) -> List[Dict[str, Any]]:
n = max(int(limit), 1)
if hasattr(conv_store, "list_items"):
rows = conv_store.list_items(limit=n)
if isinstance(rows, list):
return [r for r in rows if isinstance(r, dict)]
return []
def _bool_payload(payload: Dict[str, Any], key: str, default: bool) -> bool:
return _to_bool(payload.get(key), default=default)
def _quota_tier_counts(rows: List[Dict[str, Any]]) -> Dict[str, int]:
out: Dict[str, int] = {}
for row in rows:
if not isinstance(row, dict):
continue
tier = str(row.get("quota_tier") or "unknown").strip() or "unknown"
out[tier] = int(out.get(tier, 0) or 0) + 1
return out
def _workspace_sort_key(v: str):
raw = str(v or "").strip()
n = _safe_int(raw)
if n is not None:
return (0, n, raw)
return (1, raw.lower(), raw)
def _list_workspace_summaries(account_store, limit: int = 5000) -> List[Dict[str, Any]]:
n = max(int(limit), 1)
rows = account_store.list_accounts(limit=n) if hasattr(account_store, "list_accounts") else []
if not isinstance(rows, list):
return []
groups: Dict[str, Dict[str, Any]] = {}
for row in rows:
if not isinstance(row, dict):
continue
workspace_id = str(row.get("workspace_id") or "").strip()
if not workspace_id:
continue
email = str(row.get("email") or "").strip()
status = str(row.get("status") or "").strip()
updated_at = str(row.get("updated_at") or "").strip()
retryable = row.get("retryable")
failure_code = str(row.get("failure_code") or "").strip()
item = groups.get(workspace_id)
if item is None:
item = {
"workspace_id": workspace_id,
"account_count": 0,
"ready_account_count": 0,
"preferred_email": "",
"latest_updated_at": "",
"_picked_ready": False,
"accounts": [],
}
groups[workspace_id] = item
item["account_count"] = int(item.get("account_count", 0) or 0) + 1
if status.lower() in _READY_ACCOUNT_STATUSES:
item["ready_account_count"] = int(item.get("ready_account_count", 0) or 0) + 1
if updated_at:
last = str(item.get("latest_updated_at") or "")
if not last or updated_at > last:
item["latest_updated_at"] = updated_at
if email:
item["accounts"].append(
{
"email": email,
"status": status,
"updated_at": updated_at,
"retryable": retryable,
"failure_code": failure_code,
}
)
if not item.get("preferred_email"):
item["preferred_email"] = email
if status.lower() in _READY_ACCOUNT_STATUSES and not bool(item.get("_picked_ready")):
item["preferred_email"] = email
item["_picked_ready"] = True
out = sorted(groups.values(), key=lambda x: _workspace_sort_key(str(x.get("workspace_id") or "")))
for row in out:
row.pop("_picked_ready", None)
return out
def _pick_workspace_account_email(workspace_row: Dict[str, Any], preferred_email: str = "") -> str:
target = str(preferred_email or "").strip().lower()
accounts = workspace_row.get("accounts")
if not isinstance(accounts, list):
accounts = []
if target:
for row in accounts:
if not isinstance(row, dict):
continue
email = str(row.get("email") or "").strip()
if email and email.lower() == target:
return email
for row in accounts:
if not isinstance(row, dict):
continue
email = str(row.get("email") or "").strip()
status = str(row.get("status") or "").strip().lower()
if email and status in _READY_ACCOUNT_STATUSES:
return email
for row in accounts:
if not isinstance(row, dict):
continue
email = str(row.get("email") or "").strip()
if email:
return email
return ""
def _workspace_for_email(workspaces: List[Dict[str, Any]], email: str) -> str:
target = str(email or "").strip().lower()
if not target:
return ""
for ws in workspaces:
accounts = ws.get("accounts")
if not isinstance(accounts, list):
continue
for row in accounts:
if not isinstance(row, dict):
continue
acc_email = str(row.get("email") or "").strip().lower()
if acc_email and acc_email == target:
return str(ws.get("workspace_id") or "").strip()
return ""
def _merge_runtime_workspace_rows(
runtime_rows: List[Dict[str, Any]],
summary_rows: List[Dict[str, Any]],
account_email: str = "",
include_summary_only: bool = True,
) -> List[Dict[str, Any]]:
summary_map = {
str(row.get("workspace_id") or "").strip(): row
for row in (summary_rows or [])
if isinstance(row, dict) and str(row.get("workspace_id") or "").strip()
}
out: List[Dict[str, Any]] = []
seen = set()
for raw in runtime_rows or []:
if not isinstance(raw, dict):
continue
ws_id = str(raw.get("workspace_id") or raw.get("id") or "").strip()
if not ws_id or ws_id in seen:
continue
seen.add(ws_id)
summary = summary_map.get(ws_id) or {}
out.append(
{
"workspace_id": ws_id,
"workspace_slug": str(raw.get("workspace_slug") or raw.get("slug") or "").strip(),
"workspace_name": str(raw.get("workspace_name") or raw.get("name") or "").strip(),
"workspace_tier": str(raw.get("workspace_tier") or raw.get("tier") or "").strip(),
"account_email": str(raw.get("account_email") or account_email or "").strip(),
"account_count": int(summary.get("account_count") or 0),
"ready_account_count": int(summary.get("ready_account_count") or 0),
"preferred_email": str(summary.get("preferred_email") or "").strip(),
"latest_updated_at": str(summary.get("latest_updated_at") or "").strip(),
"accounts": summary.get("accounts") if isinstance(summary.get("accounts"), list) else [],
}
)
if include_summary_only:
for summary in summary_rows or []:
if not isinstance(summary, dict):
continue
ws_id = str(summary.get("workspace_id") or "").strip()
if not ws_id or ws_id in seen:
continue
out.append(
{
"workspace_id": ws_id,
"workspace_slug": "",
"workspace_name": "",
"workspace_tier": "",
"account_email": str(account_email or "").strip(),
"account_count": int(summary.get("account_count") or 0),
"ready_account_count": int(summary.get("ready_account_count") or 0),
"preferred_email": str(summary.get("preferred_email") or "").strip(),
"latest_updated_at": str(summary.get("latest_updated_at") or "").strip(),
"accounts": summary.get("accounts") if isinstance(summary.get("accounts"), list) else [],
}
)
return sorted(out, key=lambda x: _workspace_sort_key(str(x.get("workspace_id") or "")))
def _import_accounts_rows(account_store, rows: Any) -> Dict[str, int]:
added = 0
skipped = 0
if not isinstance(rows, list):
return {"added": 0, "skipped": 0}
for row in rows:
if not isinstance(row, dict):
skipped += 1
continue
email = str(row.get("email") or "").strip()
password = str(row.get("password") or "").strip()
if not email or not password:
skipped += 1
continue
status = str(row.get("status") or "ready").strip() or "ready"
workspace_id = str(row.get("workspace_id") or "").strip() or None
retryable = row.get("retryable")
retryable_bool = None
if retryable is not None:
retryable_bool = _to_bool(retryable, default=False)
account_store.upsert(
email=email,
password=password,
status=status,
workspace_id=workspace_id,
last_error=str(row.get("last_error") or "") or None,
failure_code=str(row.get("failure_code") or "") or None,
retryable=retryable_bool,
)
added += 1
return {"added": added, "skipped": skipped}
def _delete_accounts_by_statuses(account_store, statuses: List[str]) -> int:
clean = [str(s).strip() for s in (statuses or []) if str(s).strip()]
if not clean:
return 0
if hasattr(account_store, "delete_by_statuses"):
try:
return int(account_store.delete_by_statuses(clean) or 0)
except Exception:
return 0
if not hasattr(account_store, "delete_by_email"):
return 0
rows = account_store.list_accounts(limit=50000) if hasattr(account_store, "list_accounts") else []
if not isinstance(rows, list):
return 0
bag = {x.lower() for x in clean}
deleted = 0
for row in rows:
if not isinstance(row, dict):
continue
status = str(row.get("status") or "").strip().lower()
if status not in bag:
continue
email = str(row.get("email") or "").strip()
if not email:
continue
try:
if account_store.delete_by_email(email):
deleted += 1
except Exception:
continue
return deleted
class _BootstrapAttemptGuard:
def __init__(self, max_attempts: int = 5, window_sec: int = 300, lock_sec: int = 900):
self.max_attempts = max(int(max_attempts), 1)
self.window_sec = max(int(window_sec), 10)
self.lock_sec = max(int(lock_sec), 10)
self._lock = Lock()
self._state: Dict[str, Dict[str, Any]] = {}
def check(self, key: str) -> Dict[str, Any]:
now = time.time()
k = (key or "unknown").strip() or "unknown"
with self._lock:
row = self._state.get(k, {"failures": [], "locked_until": 0.0})
failures = [float(ts) for ts in row.get("failures", []) if now - float(ts) <= self.window_sec]
locked_until = float(row.get("locked_until") or 0.0)
if locked_until <= now:
locked_until = 0.0
row["failures"] = failures
row["locked_until"] = locked_until
self._state[k] = row
return {
"blocked": bool(locked_until and locked_until > now),
"retry_after_sec": int(max(0.0, locked_until - now)) if locked_until > now else 0,
"failures_in_window": len(failures),
}
def mark_failure(self, key: str) -> Dict[str, Any]:
now = time.time()
k = (key or "unknown").strip() or "unknown"
with self._lock:
row = self._state.get(k, {"failures": [], "locked_until": 0.0})
failures = [float(ts) for ts in row.get("failures", []) if now - float(ts) <= self.window_sec]
failures.append(now)
locked_until = float(row.get("locked_until") or 0.0)
if len(failures) >= self.max_attempts:
locked_until = now + self.lock_sec
failures = []
row["failures"] = failures
row["locked_until"] = locked_until
self._state[k] = row
return {
"blocked": bool(locked_until and locked_until > now),
"retry_after_sec": int(max(0.0, locked_until - now)) if locked_until > now else 0,
"failures_in_window": len(failures),
}
def clear(self, key: str):
k = (key or "unknown").strip() or "unknown"
with self._lock:
self._state.pop(k, None)
def _extract_bearer_token(auth_header: Optional[str]) -> str:
raw = str(auth_header or "").strip()
if not raw.lower().startswith("bearer "):
return ""
return raw.split(" ", 1)[1].strip()
def _client_key(req: Optional[Request]) -> str:
if req is None:
return "unknown"
xff = str(req.headers.get("x-forwarded-for") or "").strip()
if xff:
return xff.split(",", 1)[0].strip() or "unknown"
if req.client and req.client.host:
return str(req.client.host).strip() or "unknown"
return "unknown"
def _build_bootstrap_config_payload(settings, runtime=None) -> Dict[str, Any]:
payload = {
"version": 1,
"updated_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
"settings": snapshot_settings(settings, BOOTSTRAP_SETTING_SPECS),
}
if runtime is not None and hasattr(runtime, "workspace_selection_snapshot"):
try:
selection = runtime.workspace_selection_snapshot()
except Exception:
selection = {}
if isinstance(selection, dict) and str(selection.get("workspace_id") or "").strip():
payload["workspace_selection"] = selection
return payload
def build_admin_router(
runtime,
settings,
conv_store,
account_store,
register_jobs,
check_auth: Callable[[Optional[str]], None],
bootstrap_store=None,
bootstrap_initialized: bool = False,
bootstrap_defaults: Optional[Dict[str, Any]] = None,
):
router = APIRouter()
bootstrap_state = {"initialized": bool(bootstrap_initialized)}
bootstrap_defaults_rows = dict(bootstrap_defaults or snapshot_settings(settings, BOOTSTRAP_SETTING_SPECS))
bootstrap_guard = _BootstrapAttemptGuard(
max_attempts=getattr(settings, "bootstrap_max_attempts", 5),
window_sec=getattr(settings, "bootstrap_window_sec", 300),
lock_sec=getattr(settings, "bootstrap_lock_sec", 900),
)
def _persist_bootstrap_settings() -> bool:
if bootstrap_store is None:
return False
try:
bootstrap_store.save(_build_bootstrap_config_payload(settings, runtime=runtime))
return True
except Exception:
return False
@router.get("/admin/bootstrap/status")
def admin_bootstrap_status(request: Request):
key = _client_key(request)
guard = bootstrap_guard.check(key)
return {
"ok": True,
"initialized": bool(bootstrap_state["initialized"]),
"bootstrap_token_configured": bool(getattr(settings, "bootstrap_token", "")),
"rate_limit": {
"blocked": bool(guard.get("blocked")),
"retry_after_sec": int(guard.get("retry_after_sec") or 0),
"failures_in_window": int(guard.get("failures_in_window") or 0),
"max_attempts": int(getattr(settings, "bootstrap_max_attempts", 5)),
"window_sec": int(getattr(settings, "bootstrap_window_sec", 300)),
"lock_sec": int(getattr(settings, "bootstrap_lock_sec", 900)),
},
}
@router.get("/admin/bootstrap/export")
def admin_bootstrap_export(authorization: Optional[str] = Header(None)):
check_auth(authorization)
return {"ok": True, "bootstrap": _build_bootstrap_config_payload(settings)}
@router.post("/admin/bootstrap/import")
def admin_bootstrap_import(payload: Dict[str, Any], request: Request, authorization: Optional[str] = Header(None)):
if bootstrap_state["initialized"]:
raise HTTPException(status_code=409, detail="bootstrap already initialized")
token = str(getattr(settings, "bootstrap_token", "") or "").strip()
if not token:
raise HTTPException(status_code=503, detail="BOOTSTRAP_TOKEN is not configured")
key = _client_key(request)
guard = bootstrap_guard.check(key)
if guard.get("blocked"):
raise HTTPException(
status_code=429,
detail=f"too many invalid bootstrap attempts, retry after {int(guard.get('retry_after_sec') or 0)}s",
)
got = _extract_bearer_token(authorization)
if not got or got != token:
after = bootstrap_guard.mark_failure(key)
if after.get("blocked"):
raise HTTPException(
status_code=429,
detail=f"too many invalid bootstrap attempts, retry after {int(after.get('retry_after_sec') or 0)}s",
)
raise HTTPException(status_code=401, detail="invalid bootstrap token")
raw_body = payload if isinstance(payload, dict) else {}
body = raw_body
nested_bootstrap = body.get("bootstrap")
if isinstance(nested_bootstrap, dict):
body = nested_bootstrap
rows = body.get("settings")
if not isinstance(rows, dict):
rows = body
if not isinstance(rows, dict) or not rows:
raise HTTPException(status_code=400, detail="settings payload required")
try:
updated, ignored = apply_settings(settings, rows, BOOTSTRAP_SETTING_SPECS)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
if not updated:
raise HTTPException(status_code=400, detail="no valid settings to apply")
persisted = _persist_bootstrap_settings()
reset_runtime = _to_bool(raw_body.get("reset_runtime"), default=True)
warmup = _to_bool(raw_body.get("warmup"), default=False)
warmup_ok = False
warmup_error = ""
if reset_runtime:
runtime.reset()
if warmup:
try:
runtime.ensure_ready(conversation_id="__bootstrap_warmup__")
warmup_ok = True
except Exception as e:
warmup_error = str(e)
bootstrap_guard.clear(key)
bootstrap_state["initialized"] = True
out = {
"ok": True,
"initialized": True,
"persisted": bool(persisted),
"updated": updated,
"ignored": ignored,
"runtime_reset": bool(reset_runtime),
"warmup": {"enabled": warmup, "ok": warmup_ok, "error": warmup_error},
"health": runtime.health_snapshot(),
}
return out
@router.post("/admin/bootstrap/revoke")
def admin_bootstrap_revoke(authorization: Optional[str] = Header(None)):
check_auth(authorization)
try:
apply_settings(settings, bootstrap_defaults_rows, BOOTSTRAP_SETTING_SPECS)
except Exception:
pass
cleared = bool(bootstrap_store.clear()) if bootstrap_store is not None else False
bootstrap_state["initialized"] = False
runtime.reset()
return {
"ok": True,
"initialized": False,
"store_cleared": cleared,
"health": runtime.health_snapshot(),
}
@router.get("/admin/overview")
def admin_overview(authorization: Optional[str] = Header(None)):
check_auth(authorization)
snap = runtime.health_snapshot()
return {
"ok": True,
"health": {
"ready": snap.get("ready"),
"workspace_id": snap.get("workspace_id"),
"workspace_slug": snap.get("workspace_slug"),
"workspace_name": snap.get("workspace_name"),
"workspace_tier": snap.get("workspace_tier"),
"active_account_email": snap.get("active_account_email"),
"manual_active_account_email": snap.get("manual_active_account_email"),
"account_pool_size": snap.get("pool_size"),
"conversation_bindings": snap.get("conversation_bindings"),
"last_error": snap.get("last_error"),
"conversation_store_items": conv_store.count(),
"stream_transport": settings.stream_transport,
"pusher_key_loaded": bool(getattr(settings, "pusher_app_key", "")),
"bootstrap_initialized": bool(bootstrap_state["initialized"]),
"bootstrap_token_configured": bool(getattr(settings, "bootstrap_token", "")),
},
"runtime_settings": _runtime_settings_snapshot(settings),
"accounts": {
"status_counts": account_store.status_counts(),
"recent": account_store.list_accounts(limit=15),
},
"jobs": register_jobs.list_jobs(limit=10),
}
@router.get("/admin/accounts")
def admin_accounts(limit: int = 200, authorization: Optional[str] = Header(None)):
check_auth(authorization)
rows = account_store.list_accounts(limit=max(int(limit), 1))
return {
"ok": True,
"accounts": rows,
"status_counts": account_store.status_counts(),
"quota_tier_counts": _quota_tier_counts(rows if isinstance(rows, list) else []),
}
@router.get("/admin/workspaces")
def admin_workspaces(limit: int = 1000, refresh: bool = False, authorization: Optional[str] = Header(None)):
check_auth(authorization)
n = max(min(int(limit), 5000), 1)
summary_rows = _list_workspace_summaries(account_store, limit=n)
snap = runtime.health_snapshot()
current_workspace_id = str((snap or {}).get("workspace_id") or "").strip()
current_workspace_slug = str((snap or {}).get("workspace_slug") or "").strip()
active_account_email = str((snap or {}).get("active_account_email") or "").strip()
manual_active_account_email = str((snap or {}).get("manual_active_account_email") or "").strip()
active_workspace = _workspace_for_email(summary_rows, active_account_email)
manual_workspace = _workspace_for_email(summary_rows, manual_active_account_email)
runtime_rows: List[Dict[str, Any]] = []
runtime_account_email = ""
source = "account_store"
if hasattr(runtime, "list_workspaces"):
try:
runtime_payload = runtime.list_workspaces(force_refresh=bool(refresh))
runtime_rows = runtime_payload.get("workspaces") if isinstance(runtime_payload, dict) else []
if not isinstance(runtime_rows, list):
runtime_rows = []
runtime_account_email = str((runtime_payload or {}).get("account_email") or "").strip()
selection = (runtime_payload or {}).get("selection") if isinstance(runtime_payload, dict) else {}
if isinstance(selection, dict):
selected_id = str(selection.get("workspace_id") or "").strip()
selected_slug = str(selection.get("workspace_slug") or "").strip()
if selected_id:
current_workspace_id = selected_id
if selected_slug:
current_workspace_slug = selected_slug
source = "runtime"
except Exception as e:
source = "account_store_fallback"
runtime_rows = []
runtime_account_email = ""
if str((snap or {}).get("last_error") or "").strip() == "":
snap["last_error"] = str(e)
if not current_workspace_id:
current_workspace_id = manual_workspace or active_workspace
if not current_workspace_slug:
current_workspace_slug = ""
ws_rows = _merge_runtime_workspace_rows(
runtime_rows,
summary_rows,
account_email=runtime_account_email,
include_summary_only=source != "runtime",
)
row_map = {str(row.get("workspace_id") or "").strip(): row for row in ws_rows}
if current_workspace_id and current_workspace_id not in row_map:
ws_rows.append(
{
"workspace_id": current_workspace_id,
"workspace_slug": current_workspace_slug,
"workspace_name": "",
"workspace_tier": "",
"account_email": runtime_account_email,
"account_count": 0,
"ready_account_count": 0,
"preferred_email": "",
"latest_updated_at": "",
"accounts": [],
}
)
ws_rows = sorted(ws_rows, key=lambda x: _workspace_sort_key(str(x.get("workspace_id") or "")))
out_rows: List[Dict[str, Any]] = []
for row in ws_rows:
ws_id = str(row.get("workspace_id") or "").strip()
out_rows.append(
{
"workspace_id": ws_id,
"workspace_slug": str(row.get("workspace_slug") or "").strip(),
"workspace_name": str(row.get("workspace_name") or "").strip(),
"workspace_tier": str(row.get("workspace_tier") or "").strip(),
"account_email": str(row.get("account_email") or "").strip(),
"account_count": int(row.get("account_count") or 0),
"ready_account_count": int(row.get("ready_account_count") or 0),
"preferred_email": str(row.get("preferred_email") or "").strip(),
"latest_updated_at": str(row.get("latest_updated_at") or "").strip(),
"is_current_workspace": bool(current_workspace_id and ws_id == current_workspace_id),
"contains_active_account": bool(active_workspace and ws_id == active_workspace),
"contains_manual_active_account": bool(manual_workspace and ws_id == manual_workspace),
}
)
return {
"ok": True,
"source": source,
"current_workspace_id": current_workspace_id,
"current_workspace_slug": current_workspace_slug,
"active_account_email": active_account_email,
"manual_active_account_email": manual_active_account_email,
"workspaces": out_rows,
}
@router.post("/admin/workspaces")
def admin_create_workspace(payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
body = payload if isinstance(payload, dict) else {}
workspace_name = str(body.get("workspace_name") or body.get("name") or "").strip()
preferred_email = str(body.get("email") or "").strip()
clear_bindings = _bool_payload(body, "clear_bindings", True)
if not workspace_name:
raise HTTPException(status_code=400, detail="workspace_name required")
if not hasattr(runtime, "create_workspace"):
raise HTTPException(status_code=400, detail="runtime does not support workspace creation")
try:
result = runtime.create_workspace(workspace_name=workspace_name, email=preferred_email, clear_bindings=clear_bindings)
if bootstrap_store is not None:
_persist_bootstrap_settings()
except Exception as e:
raise HTTPException(status_code=500, detail=f"create workspace failed: {e}")
workspace = result.get("workspace") if isinstance(result, dict) else {}
if not isinstance(workspace, dict):
workspace = {}
return {
"ok": True,
"workspace": workspace,
"selected_email": str((result or {}).get("account_email") or "").strip(),
"health": (result or {}).get("health") if isinstance(result, dict) else runtime.health_snapshot(),
"raw": (result or {}).get("raw") if isinstance(result, dict) else {},
}
@router.post("/admin/workspaces/trial")
def admin_activate_workspace_trial(payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
body = payload if isinstance(payload, dict) else {}
workspace_id = str(body.get("workspace_id") or "").strip()
workspace_slug = str(body.get("workspace_slug") or "").strip()
preferred_email = str(body.get("email") or "").strip()
clear_bindings = _bool_payload(body, "clear_bindings", True)
if not hasattr(runtime, "activate_workspace_trial"):
raise HTTPException(status_code=400, detail="runtime does not support workspace trial activation")
snap = runtime.health_snapshot() if hasattr(runtime, "health_snapshot") else {}
selected_email = preferred_email or str(
(snap or {}).get("manual_active_account_email") or (snap or {}).get("active_account_email") or ""
).strip()
if workspace_id:
current_workspace_id = str((snap or {}).get("workspace_id") or "").strip()
if not workspace_slug and current_workspace_id == workspace_id:
workspace_slug = str((snap or {}).get("workspace_slug") or "").strip()
if not selected_email and hasattr(runtime, "workspace_selection_snapshot"):
current_selection = runtime.workspace_selection_snapshot()
if isinstance(current_selection, dict) and str(current_selection.get("workspace_id") or "").strip() == workspace_id:
selected_email = str(current_selection.get("account_email") or "").strip()
if not workspace_slug:
workspace_slug = str(current_selection.get("workspace_slug") or "").strip()
if not selected_email:
summary_rows = _list_workspace_summaries(account_store, limit=20000)
target = None
for row in summary_rows:
if str(row.get("workspace_id") or "").strip() == workspace_id:
target = row
break
if isinstance(target, dict):
if not workspace_slug:
workspace_slug = str(target.get("workspace_slug") or "").strip()
selected_email = str(target.get("account_email") or "").strip() or _pick_workspace_account_email(
target,
preferred_email=preferred_email,
)
if not selected_email:
raise HTTPException(status_code=404, detail="no account available for this workspace")
else:
workspace_id = str((snap or {}).get("workspace_id") or "").strip()
if not workspace_id:
raise HTTPException(status_code=400, detail="workspace_id required")
if not workspace_slug:
workspace_slug = str((snap or {}).get("workspace_slug") or "").strip()
if not selected_email:
raise HTTPException(status_code=404, detail="no account available for current workspace")
try:
result = runtime.activate_workspace_trial(
workspace_id=workspace_id,
workspace_slug=workspace_slug,
email=selected_email,
clear_bindings=clear_bindings,
)
if bootstrap_store is not None:
_persist_bootstrap_settings()
except Exception as e:
raise HTTPException(status_code=500, detail=f"activate workspace trial failed: {e}")
workspace = result.get("workspace") if isinstance(result, dict) else {}
if not isinstance(workspace, dict):
workspace = {}
return {
"ok": True,
"success": bool((result or {}).get("success", True)) if isinstance(result, dict) else True,
"workspace": workspace,
"selected_email": str((result or {}).get("account_email") or selected_email or "").strip(),
"health": (result or {}).get("health") if isinstance(result, dict) else runtime.health_snapshot(),
"raw": (result or {}).get("raw") if isinstance(result, dict) else {},
}
@router.post("/admin/workspaces/active")
def admin_set_active_workspace(payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
body = payload if isinstance(payload, dict) else {}
workspace_id = str(body.get("workspace_id") or "").strip()
preferred_email = str(body.get("email") or "").strip()
clear_bindings = _bool_payload(body, "clear_bindings", True)
if not workspace_id:
raise HTTPException(status_code=400, detail="workspace_id required")
if not hasattr(runtime, "set_active_workspace"):
raise HTTPException(status_code=400, detail="runtime does not support manual active account")
runtime_payload = runtime.list_workspaces(force_refresh=True) if hasattr(runtime, "list_workspaces") else {}
runtime_rows = runtime_payload.get("workspaces") if isinstance(runtime_payload, dict) else []
runtime_account_email = str((runtime_payload or {}).get("account_email") or "").strip()
summary_rows = _list_workspace_summaries(account_store, limit=20000)
ws_rows = _merge_runtime_workspace_rows(
runtime_rows if isinstance(runtime_rows, list) else [],
summary_rows,
account_email=runtime_account_email,
include_summary_only=not bool(runtime_rows),
)
target = None
for row in ws_rows:
if str(row.get("workspace_id") or "").strip() == workspace_id:
target = row
break
if not isinstance(target, dict):
raise HTTPException(status_code=404, detail="workspace not found")
selected_email = str(target.get("account_email") or "").strip()
if preferred_email:
selected_email = preferred_email
if not selected_email:
selected_email = _pick_workspace_account_email(target, preferred_email=preferred_email)
if not selected_email:
raise HTTPException(status_code=404, detail="no account available for this workspace")
try:
snap = runtime.set_active_workspace(
workspace_id=workspace_id,
workspace_slug=str(target.get("workspace_slug") or "").strip(),
workspace_name=str(target.get("workspace_name") or "").strip(),
workspace_tier=str(target.get("workspace_tier") or "").strip(),
email=selected_email,
clear_bindings=clear_bindings,
)
if bootstrap_store is not None:
_persist_bootstrap_settings()
except Exception as e:
raise HTTPException(status_code=500, detail=f"set active workspace failed: {e}")
return {
"ok": True,
"workspace_id": workspace_id,
"workspace_slug": str(target.get("workspace_slug") or "").strip(),
"workspace_tier": str(target.get("workspace_tier") or "").strip(),
"selected_email": selected_email,
"health": snap,
}
@router.post("/admin/workspaces/active/clear")
def admin_clear_active_workspace(payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
body = payload if isinstance(payload, dict) else {}
clear_bindings = _bool_payload(body, "clear_bindings", False)
if not hasattr(runtime, "clear_active_workspace"):
raise HTTPException(status_code=400, detail="runtime does not support clearing manual active account")
try:
snap = runtime.clear_active_workspace(clear_bindings=clear_bindings)
if bootstrap_store is not None:
_persist_bootstrap_settings()
except Exception as e:
raise HTTPException(status_code=500, detail=f"clear active workspace failed: {e}")
return {"ok": True, "health": snap}
@router.post("/admin/accounts")
def admin_add_account(payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
email = str(payload.get("email") or "").strip()
password = str(payload.get("password") or "").strip()
workspace_id = str(payload.get("workspace_id") or "").strip()
status = str(payload.get("status") or "ready").strip()
if not email or not password:
raise HTTPException(status_code=400, detail="email/password required")
account_store.upsert(
email=email,
password=password,
status=status,
workspace_id=workspace_id or None,
last_error=None,
failure_code=None,
retryable=None,
)
row = account_store.get_by_email(email)
return {"ok": True, "account": row}
@router.post("/admin/accounts/{email}/status")
def admin_update_account_status(email: str, payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
key = str(email or "").strip()
if not key:
raise HTTPException(status_code=400, detail="email required")
row = account_store.get_by_email(key) if hasattr(account_store, "get_by_email") else None
if not isinstance(row, dict):
raise HTTPException(status_code=404, detail="account not found")
status = str(payload.get("status") or "").strip()
if not status:
raise HTTPException(status_code=400, detail="status required")
workspace_id = str(payload.get("workspace_id") or row.get("workspace_id") or "").strip() or None
password = str(row.get("password") or "").strip()
if not password:
raise HTTPException(status_code=400, detail="account password missing")
failure_code = payload.get("failure_code")
last_error = payload.get("last_error")
retryable = payload.get("retryable")
if status in ("ready", "oauth_ok", "verified"):
failure_code = None
last_error = None
retryable = None
else:
failure_code = str(failure_code) if failure_code is not None else row.get("failure_code")
last_error = str(last_error) if last_error is not None else row.get("last_error")
retryable = _to_bool(retryable, default=False) if retryable is not None else row.get("retryable")
try:
account_store.upsert(
email=key,
password=password,
status=status,
workspace_id=workspace_id,
last_error=last_error,
failure_code=failure_code,
retryable=retryable,
)
updated = account_store.get_by_email(key)
except Exception as e:
raise HTTPException(status_code=500, detail=f"update account status failed: {e}")
return {"ok": True, "account": updated}
@router.delete("/admin/accounts/{email}")
def admin_delete_account(email: str, authorization: Optional[str] = Header(None)):
check_auth(authorization)
key = str(email or "").strip()
if not key:
raise HTTPException(status_code=400, detail="email required")
if not hasattr(account_store, "delete_by_email"):
raise HTTPException(status_code=400, detail="account store does not support delete_by_email")
try:
deleted = bool(account_store.delete_by_email(key))
if deleted:
runtime.reset()
except Exception as e:
raise HTTPException(status_code=500, detail=f"delete account failed: {e}")
if not deleted:
raise HTTPException(status_code=404, detail="account not found")
return {"ok": True}
@router.post("/admin/accounts/active")
def admin_set_active_account(payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
email = str(payload.get("email") or "").strip()
clear_bindings = _bool_payload(payload, "clear_bindings", True)
if not email:
raise HTTPException(status_code=400, detail="email required")
if not hasattr(runtime, "set_active_account"):
raise HTTPException(status_code=400, detail="runtime does not support manual active account")
try:
snap = runtime.set_active_account(email=email, clear_bindings=clear_bindings)
except Exception as e:
raise HTTPException(status_code=500, detail=f"set active account failed: {e}")
return {"ok": True, "health": snap}
@router.post("/admin/accounts/active/clear")
def admin_clear_active_account(payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
clear_bindings = _bool_payload(payload, "clear_bindings", False)
if not hasattr(runtime, "clear_active_account"):
raise HTTPException(status_code=400, detail="runtime does not support clearing manual active account")
try:
snap = runtime.clear_active_account(clear_bindings=clear_bindings)
except Exception as e:
raise HTTPException(status_code=500, detail=f"clear active account failed: {e}")
return {"ok": True, "health": snap}
@router.get("/admin/accounts/export")
def admin_export_accounts(limit: int = 20000, authorization: Optional[str] = Header(None)):
check_auth(authorization)
try:
rows = _list_accounts_for_backup(account_store, limit=max(int(limit), 1))
except Exception as e:
raise HTTPException(status_code=500, detail=f"accounts export failed: {e}")
return {
"ok": True,
"exported_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
"count": len(rows),
"accounts": rows,
}
@router.post("/admin/accounts/import")
def admin_import_accounts(payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
body = payload if isinstance(payload, dict) else {}
rows = body.get("accounts")
if not isinstance(rows, list):
rows = body.get("items")
clear_before_import = _bool_payload(body, "clear_before_import", False)
reset_runtime = _bool_payload(body, "reset_runtime", True)
cleared = 0
try:
if clear_before_import and hasattr(account_store, "clear_all"):
cleared = int(account_store.clear_all() or 0)
ret = _import_accounts_rows(account_store, rows)
added = int(ret.get("added") or 0)
skipped = int(ret.get("skipped") or 0)
runtime_reset = bool(reset_runtime and added > 0)
if runtime_reset:
runtime.reset()
except Exception as e:
raise HTTPException(status_code=500, detail=f"accounts import failed: {e}")
return {
"ok": True,
"summary": {
"accounts_added": added,
"accounts_skipped": skipped,
"cleared_accounts": cleared,
"runtime_reset": runtime_reset,
},
}
@router.post("/admin/accounts/delete-invalid")
def admin_delete_invalid_accounts(payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
body = payload if isinstance(payload, dict) else {}
custom_statuses = body.get("statuses")
if isinstance(custom_statuses, list) and custom_statuses:
statuses = [str(x).strip() for x in custom_statuses if str(x).strip()]
else:
statuses = []
if _bool_payload(body, "include_retryable", True):
statuses.append("failed_retryable")
if _bool_payload(body, "include_permanent", True):
statuses.append("failed_permanent")
reset_runtime = _bool_payload(body, "reset_runtime", True)
try:
deleted = _delete_accounts_by_statuses(account_store, statuses)
runtime_reset = bool(reset_runtime and deleted > 0)
if runtime_reset:
runtime.reset()
except Exception as e:
raise HTTPException(status_code=500, detail=f"delete invalid accounts failed: {e}")
return {
"ok": True,
"summary": {
"statuses": statuses,
"deleted_accounts": int(deleted),
"runtime_reset": runtime_reset,
},
}
@router.post("/admin/accounts/quotas/refresh")
def admin_refresh_account_quotas(payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
body = payload if isinstance(payload, dict) else {}
try:
limit = max(int(body.get("limit") or 13), 1)
except Exception:
limit = 13
try:
account_limit = max(int(body.get("account_limit") or 200), 1)
except Exception:
account_limit = 200
try:
sleep_sec = max(float(body.get("sleep_sec") or 0), 0.0)
except Exception:
sleep_sec = 0.0
raw_statuses = body.get("statuses")
if isinstance(raw_statuses, list):
statuses = [str(x).strip() for x in raw_statuses if str(x).strip()]
elif isinstance(raw_statuses, str) and raw_statuses.strip().lower() == "all":
statuses = []
else:
statuses = []
try:
ret = runtime.refresh_account_quotas(
limit=limit,
account_limit=account_limit,
statuses=statuses,
sleep_sec=sleep_sec,
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"account quota refresh failed: {e}")
return {
"ok": True,
"summary": {
"limit": limit,
"account_limit": account_limit,
"statuses": statuses,
"total": int(ret.get("total") or 0),
"updated": int(ret.get("updated") or 0),
"failed": int(ret.get("failed") or 0),
"skipped": int(ret.get("skipped") or 0),
},
"rows": ret.get("rows") or [],
}
@router.post("/admin/register-jobs")
def admin_create_register_job(payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
items = _parse_items(payload)
if not items:
raise HTTPException(status_code=400, detail="no email items")
with_chat_test = _to_bool(payload.get("with_chat_test"), default=False)
skip_ready = _to_bool(payload.get("skip_ready"), default=True)
sleep_sec = float(payload.get("sleep_sec") or 0)
try:
job = register_jobs.create_job(
items,
with_chat_test=with_chat_test,
skip_ready=skip_ready,
sleep_sec=sleep_sec,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
return {"ok": True, "job": job}
@router.get("/admin/register-jobs")
def admin_list_register_jobs(limit: int = 20, authorization: Optional[str] = Header(None)):
check_auth(authorization)
return {"ok": True, "jobs": register_jobs.list_jobs(limit=max(int(limit), 1))}
@router.get("/admin/register-jobs/{job_id}")
def admin_get_register_job(job_id: str, authorization: Optional[str] = Header(None)):
check_auth(authorization)
row = register_jobs.get_job(job_id)
if not row:
raise HTTPException(status_code=404, detail="job not found")
return {"ok": True, "job": row}
@router.post("/admin/register-jobs/{job_id}/cancel")
def admin_cancel_register_job(job_id: str, authorization: Optional[str] = Header(None)):
check_auth(authorization)
ok = register_jobs.cancel_job(job_id)
if not ok:
raise HTTPException(status_code=404, detail="job not found")
return {"ok": True}
@router.get("/admin/settings")
def admin_get_settings(authorization: Optional[str] = Header(None)):
check_auth(authorization)
return {
"ok": True,
"settings": _runtime_settings_snapshot(settings),
}
@router.post("/admin/settings")
def admin_update_settings(payload: Dict[str, Any], authorization: Optional[str] = Header(None)):
check_auth(authorization)
rows = payload.get("settings")
if not isinstance(rows, dict):
rows = payload if isinstance(payload, dict) else {}
try:
updated, ignored = apply_settings(
settings,
rows,
RUNTIME_SETTING_SPECS,
allowed_keys=RUNTIME_SETTING_SPECS.keys(),
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
reset_runtime = _to_bool(payload.get("reset_runtime"), default=True)
if reset_runtime and updated:
runtime.reset()
persisted = False
if updated and bootstrap_state["initialized"]:
persisted = _persist_bootstrap_settings()
return {
"ok": True,
"updated": updated,
"ignored": ignored,
"runtime_reset": bool(reset_runtime and updated),
"persisted": bool(persisted),
"settings": _runtime_settings_snapshot(settings),
}
@router.post("/admin/runtime/reset")
def admin_reset_runtime(authorization: Optional[str] = Header(None)):
check_auth(authorization)
runtime.reset()
return {"ok": True}
@router.post("/admin/runtime/warmup")
def admin_warmup_runtime(authorization: Optional[str] = Header(None)):
check_auth(authorization)
try:
runtime.ensure_ready(conversation_id="__admin_warmup__")
except Exception as e:
raise HTTPException(status_code=500, detail=f"runtime warmup failed: {e}")
return {
"ok": True,
"health": runtime.health_snapshot(),
}
@router.post("/admin/runtime/restart")
def admin_restart_runtime(authorization: Optional[str] = Header(None)):
check_auth(authorization)
_trigger_self_restart(delay_sec=0.3)
return {
"ok": True,
"restarting": True,
"message": "service is restarting",
}
@router.get("/admin/quota")
def admin_get_quota(limit: int = 13, authorization: Optional[str] = Header(None)):
check_auth(authorization)
try:
quota = runtime.quota_snapshot(limit=max(int(limit), 1), conversation_id="__admin_quota__")
except Exception as e:
raise HTTPException(status_code=500, detail=f"quota fetch failed: {e}")
return {
"ok": True,
"quota": quota,
}
@router.get("/admin/models")
def admin_get_models(include_disabled: bool = False, authorization: Optional[str] = Header(None)):
check_auth(authorization)
try:
data = runtime.available_models(
conversation_id="__admin_models__",
include_disabled=bool(include_disabled),
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"models fetch failed: {e}")
return {
"ok": True,
"default_model": getattr(settings, "default_model", ""),
"models": data,
}
@router.get("/admin/usage/stats")
def admin_usage_stats(
days: int = 14,
hours: int = 24,
model_limit: int = 30,
events_limit: int = 200,
max_lines: int = 200000,
authorization: Optional[str] = Header(None),
):
check_auth(authorization)
try:
usage_data = _collect_usage_events(max_lines=max_lines)
usage = _build_usage_snapshot(
usage_data.get("events") or [],
source=str(usage_data.get("source") or "none"),
log_path=str(usage_data.get("path") or ""),
days=days,
hours=hours,
model_limit=model_limit,
events_limit=events_limit,
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"usage stats build failed: {e}")
return {"ok": True, "usage": usage}
@router.get("/usage")
def usage_compat(
event_limit: int = 20000,
max_lines: int = 200000,
authorization: Optional[str] = Header(None),
):
check_auth(authorization)
try:
usage_data = _collect_usage_events(max_lines=max_lines)
usage = _build_cpa_usage_payload(
usage_data.get("events") or [],
source=str(usage_data.get("source") or "none"),
log_path=str(usage_data.get("path") or ""),
event_limit=event_limit,
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"usage payload build failed: {e}")
return {"ok": True, "usage": usage}
@router.get("/usage/export")
def usage_export(
event_limit: int = 20000,
max_lines: int = 200000,
authorization: Optional[str] = Header(None),
):
check_auth(authorization)
try:
usage_data = _collect_usage_events(max_lines=max_lines)
usage = _build_cpa_usage_payload(
usage_data.get("events") or [],
source=str(usage_data.get("source") or "none"),
log_path=str(usage_data.get("path") or ""),
event_limit=event_limit,
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"usage export failed: {e}")
return {
"version": 1,
"exported_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
"usage": usage,
}
@router.get("/admin/backup/export")
def admin_backup_export(
include_accounts: bool = True,
include_settings: bool = True,
include_conversations: bool = True,
include_usage: bool = True,
account_limit: int = 20000,
conversation_limit: int = 20000,
usage_event_limit: int = 20000,
usage_max_lines: int = 200000,
authorization: Optional[str] = Header(None),
):
check_auth(authorization)
try:
backup: Dict[str, Any] = {
"version": 1,
"exported_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
}
if include_settings:
backup["settings"] = _runtime_settings_snapshot(settings)
if include_accounts:
backup["accounts"] = _list_accounts_for_backup(account_store, limit=account_limit)
if include_conversations:
backup["conversations"] = _list_conversations_for_backup(conv_store, limit=conversation_limit)
if include_usage:
usage_data = _collect_usage_events(max_lines=usage_max_lines)
backup["usage"] = _build_cpa_usage_payload(
usage_data.get("events") or [],
source=str(usage_data.get("source") or "none"),
log_path=str(usage_data.get("path") or ""),
event_limit=usage_event_limit,
)
summary = {
"settings": (1 if isinstance(backup.get("settings"), dict) else 0),
"accounts": len(backup.get("accounts") or []),
"conversations": len(backup.get("conversations") or []),
"usage_requests": int(((backup.get("usage") or {}) if isinstance(backup.get("usage"), dict) else {}).get("total_requests") or 0),
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"backup export failed: {e}")
return {"ok": True, "backup": backup, "summary": summary}
@router.post("/admin/backup/import")
def admin_backup_import(
payload: Dict[str, Any],
authorization: Optional[str] = Header(None),
):
check_auth(authorization)
body = payload if isinstance(payload, dict) else {}
backup_obj = body.get("backup")
backup = backup_obj if isinstance(backup_obj, dict) else body
apply_settings_flag = _bool_payload(body, "apply_settings", True)
import_accounts = _bool_payload(body, "import_accounts", True)
import_conversations = _bool_payload(body, "import_conversations", True)
import_usage = _bool_payload(body, "import_usage", True)
clear_before_import = _bool_payload(body, "clear_before_import", False)
reset_runtime = _bool_payload(body, "reset_runtime", True)
settings_updated = 0
accounts_added = 0
accounts_skipped = 0
conversations_added = 0
conversations_skipped = 0
usage_added = 0
usage_skipped = 0
usage_failed = 0
cleared_accounts = 0
cleared_conversations = 0
try:
if clear_before_import:
if import_conversations and hasattr(conv_store, "clear_all"):
cleared_conversations = int(conv_store.clear_all() or 0)
if import_accounts and hasattr(account_store, "clear_all"):
cleared_accounts = int(account_store.clear_all() or 0)
if apply_settings_flag:
settings_rows = backup.get("settings")
if isinstance(settings_rows, dict):
updated, _ignored = apply_settings(
settings,
settings_rows,
RUNTIME_SETTING_SPECS,
allowed_keys=RUNTIME_SETTING_SPECS.keys(),
)
settings_updated += len(updated)
if import_accounts:
rows = backup.get("accounts")
ret = _import_accounts_rows(account_store, rows)
accounts_added = int(ret.get("added") or 0)
accounts_skipped = int(ret.get("skipped") or 0)
if import_conversations:
rows = backup.get("conversations")
if isinstance(rows, list):
for row in rows:
if not isinstance(row, dict):
conversations_skipped += 1
continue
conversation_id = str(row.get("conversation_id") or "").strip()
messages = row.get("messages")
if not conversation_id or not isinstance(messages, list):
conversations_skipped += 1
continue
safe_messages = [m for m in messages if isinstance(m, dict)]
conv_store.set(conversation_id, safe_messages)
conversations_added += 1
if import_usage:
usage_rows = _extract_usage_rows_from_cpa_payload(backup.get("usage") if isinstance(backup.get("usage"), dict) else {})
usage_ret = _append_usage_rows_to_log(usage_rows)
usage_added = int(usage_ret.get("added") or 0)
usage_skipped = int(usage_ret.get("skipped") or 0)
usage_failed = int(usage_ret.get("failed_requests") or 0)
if reset_runtime and (settings_updated > 0 or accounts_added > 0 or conversations_added > 0):
runtime.reset()
if settings_updated > 0 and bootstrap_state["initialized"]:
_persist_bootstrap_settings()
except Exception as e:
raise HTTPException(status_code=500, detail=f"backup import failed: {e}")
return {
"ok": True,
"summary": {
"settings_updated": settings_updated,
"accounts_added": accounts_added,
"accounts_skipped": accounts_skipped,
"conversations_added": conversations_added,
"conversations_skipped": conversations_skipped,
"usage_added": usage_added,
"usage_skipped": usage_skipped,
"usage_failed_requests": usage_failed,
"cleared_accounts": cleared_accounts,
"cleared_conversations": cleared_conversations,
"runtime_reset": bool(reset_runtime and (settings_updated > 0 or accounts_added > 0 or conversations_added > 0)),
},
}
@router.post("/usage/import")
def usage_import(
payload: Dict[str, Any],
authorization: Optional[str] = Header(None),
):
check_auth(authorization)
rows = _extract_usage_rows_from_cpa_payload(payload)
if not rows:
return {"ok": True, "added": 0, "skipped": 0, "total_requests": 0, "failed_requests": 0}
try:
usage_ret = _append_usage_rows_to_log(rows)
except Exception as e:
raise HTTPException(status_code=500, detail=f"usage import failed: {e}")
return {
"ok": True,
"added": int(usage_ret.get("added") or 0),
"skipped": int(usage_ret.get("skipped") or 0),
"total_requests": len(rows),
"failed_requests": int(usage_ret.get("failed_requests") or 0),
}
return router
|