Spaces:
Paused
Paused
Merge remote-tracking branch 'origin/dev' into pr6-work
Browse filesFiles changed (18)
- docs/api.md+1
- src/autoteam/accounts.py+12-1
- src/autoteam/admin_state.py+10-3
- src/autoteam/api.py+147-9
- src/autoteam/auth_storage.pyAdded+35
- src/autoteam/chatgpt_api.py+502-122
- src/autoteam/cloudmail.py+54-3
- src/autoteam/codex_auth.py+263-35
- src/autoteam/cpa_sync.py+3-7
- src/autoteam/manager.py+636-140
- src/autoteam/manual_account.py+18-1
- src/autoteam/web/dist/assets/index-BA0Oc9aM.cssAdded+1
- src/autoteam/web/dist/assets/index-CvbW1pB4.jsAdded
- src/autoteam/web/dist/assets/index-D7-Mvijd.jsDeleted
- src/autoteam/web/dist/assets/index-OzckUg9Q.cssDeleted-1
- src/autoteam/web/dist/index.html+2-2
- web/src/api.js+1
- web/src/components/Settings.vue+131-15
76 unmodified lines77787980818276 unmodified lines|------|------|------|| GET | `/api/admin/status` | 管理员状态 || POST | `/api/admin/login/start` | 开始登录 `{"email": "admin@example.com"}` || POST | `/api/admin/login/password` | 提交密码 `{"password": "..."}` || POST | `/api/admin/login/code` | 提交验证码 `{"code": "123456"}` || POST | `/api/admin/login/workspace` | 选择组织 `{"option_id": "0"}` |76 unmodified lines7778798081828376 unmodified lines|------|------|------|| GET | `/api/admin/status` | 管理员状态 || POST | `/api/admin/login/start` | 开始登录 `{"email": "admin@example.com"}` || POST | `/api/admin/login/session` | 手动导入 session_token `{"email": "admin@example.com", "session_token": "..."}` || POST | `/api/admin/login/password` | 提交密码 `{"password": "..."}` || POST | `/api/admin/login/code` | 提交验证码 `{"code": "123456"}` || POST | `/api/admin/login/workspace` | 选择组织 `{"option_id": "0"}` |
3 unmodified lines4567896 unmodified lines16171819202150 unmodified lines727374757677782 unmodified lines8182838485863 unmodified linesimport timefrom pathlib import Pathfrom autoteam.textio import read_text, write_textPROJECT_ROOT = Path(__file__).parent.parent.parent6 unmodified linesSTATUS_PENDING = "pending" # 已邀请,等待注册完成def load_accounts():"""加载账号列表"""if ACCOUNTS_FILE.exists():50 unmodified linesdef get_active_accounts():"""获取所有活跃账号"""return [a for a in load_accounts() if a["status"] == STATUS_ACTIVE]def get_standby_accounts():2 unmodified linesnow = time.time()standby = []for a in accounts:if a["status"] == STATUS_STANDBY:resets_at = a.get("quota_resets_at")if resets_at is None:3 unmodified lines456789106 unmodified lines171819202122232425262728293050 unmodified lines818283848586872 unmodified lines90919293949596973 unmodified linesimport timefrom pathlib import Pathfrom autoteam.admin_state import get_admin_emailfrom autoteam.textio import read_text, write_textPROJECT_ROOT = Path(__file__).parent.parent.parent6 unmodified linesSTATUS_PENDING = "pending" # 已邀请,等待注册完成def _normalized_email(value):return (value or "").strip().lower()def _is_main_account_email(email):return bool(_normalized_email(email)) and _normalized_email(email) == _normalized_email(get_admin_email())def load_accounts():"""加载账号列表"""if ACCOUNTS_FILE.exists():50 unmodified linesdef get_active_accounts():"""获取所有活跃账号"""return [a for a in load_accounts() if a["status"] == STATUS_ACTIVE and not _is_main_account_email(a.get("email"))]def get_standby_accounts():2 unmodified linesnow = time.time()standby = []for a in accounts:if _is_main_account_email(a.get("email")):continueif a["status"] == STATUS_STANDBY:resets_at = a.get("quota_resets_at")if resets_at is None:
21 unmodified lines22232425262735 unmodified lines636465666768697027 unmodified lines989910010110210310421 unmodified linesPROJECT_ROOT = Path(__file__).parent.parent.parentSTATE_FILE = PROJECT_ROOT / "state.json"LEGACY_SESSION_FILE = PROJECT_ROOT / "session"def _normalize_state(data):35 unmodified linesdef _save_state(state):write_text(STATE_FILE, json.dumps(_normalize_state(state), indent=2, ensure_ascii=False))os.chmod(STATE_FILE, 0o600)def _migrate_legacy_state():27 unmodified linesdef clear_admin_state():if STATE_FILE.exists():STATE_FILE.unlink()if LEGACY_SESSION_FILE.exists():LEGACY_SESSION_FILE.unlink()21 unmodified lines2223242526272835 unmodified lines646566676869707172737427 unmodified lines10210310410510610710810911011121 unmodified linesPROJECT_ROOT = Path(__file__).parent.parent.parentSTATE_FILE = PROJECT_ROOT / "state.json"LEGACY_SESSION_FILE = PROJECT_ROOT / "session"STATE_FILE_MODE = 0o666def _normalize_state(data):35 unmodified linesdef _save_state(state):# 如果是软链,写入目标路径(避免 Docker 场景下误删/替换软链)target = STATE_FILE.resolve()write_text(target, json.dumps(_normalize_state(state), indent=2, ensure_ascii=False))# Docker bind mount 下文件常由容器用户写入;给宿主机用户保留可访问权限os.chmod(target, STATE_FILE_MODE)def _migrate_legacy_state():27 unmodified linesdef clear_admin_state():if STATE_FILE.exists():# 写空内容而不是删除(保护 Docker 软链)target = STATE_FILE.resolve()write_text(target, "{}")os.chmod(target, STATE_FILE_MODE)if LEGACY_SESSION_FILE.exists():LEGACY_SESSION_FILE.unlink()
319 unmodified lines32032132232332432516 unmodified lines34234334434534634734834935039 unmodified lines3903913923933943954 unmodified lines400401402403404405119 unmodified lines525526527528529530135 unmodified lines666667668669670671171 unmodified lines84384484584684784884985085185285385485585685755 unmodified lines91391491591691791819 unmodified lines93893994094194294330 unmodified lines9749759769779789792 unmodified lines98298398498598698798810 unmodified lines999100010011002100310049 unmodified lines10141015101610171018101910207 unmodified lines102810291030103110321033124 unmodified lines115811591160116111621163293 unmodified lines145714581459146014611462319 unmodified linesemail: strclass AdminPasswordParams(BaseModel):password: str16 unmodified linestype: strdef _sanitize_account(acc: dict) -> dict:"""脱敏账号信息(去掉 password 等敏感字段)"""return {k: v for k, v in acc.items() if k not in ("password", "cloudmail_account_id")}def _admin_status():39 unmodified linesdef _finish_admin_login(completed: dict):global _admin_login_api, _admin_login_stepapi = _admin_login_apitry:info = _pw_executor.run(api.complete_admin_login)finally:4 unmodified linespass_admin_login_api = None_admin_login_step = Noneif _playwright_lock.locked():_playwright_lock.release()return {"status": "completed", "admin": _admin_status(), "info": info}119 unmodified linesraise HTTPException(status_code=400, detail=str(exc))@app.post("/api/admin/login/password")def post_admin_login_password(params: AdminPasswordParams):"""提交管理员密码。"""135 unmodified linesif _playwright_lock.locked():_playwright_lock.release()if not _playwright_lock.acquire(blocking=False):raise HTTPException(status_code=409, detail=_current_busy_detail("有任务正在执行,请等待完成后再同步主号 Codex")171 unmodified linesdef get_codex_auth(email: str):"""导出账号的 Codex CLI 格式认证文件(~/.codex/auth.json)"""from autoteam.accounts import find_account, load_accountsemail = email.strip().lower()acc = find_account(load_accounts(), email)if not acc:raise HTTPException(status_code=404, detail="账号不存在")auth_file = acc.get("auth_file")if not auth_file or not Path(auth_file).exists():raise HTTPException(status_code=404, detail="该账号没有认证文件")auth_data = json.loads(Path(auth_file).read_text())55 unmodified linesfrom autoteam.account_ops import delete_managed_accountfrom autoteam.accounts import load_accountsaccounts = load_accounts()if not any(a["email"].lower() == email.lower() for a in accounts):raise HTTPException(status_code=404, detail="账号不存在")19 unmodified linesfrom autoteam.manager import remove_from_teamemail = email.strip().lower()accounts = load_accounts()acc = find_account(accounts, email)if not acc:30 unmodified linesfrom autoteam.accounts import find_account, load_accountsemail = params.email.strip().lower()accounts = load_accounts()acc = find_account(accounts, email)if not acc:2 unmodified linesdef _run():from autoteam.accounts import STATUS_ACTIVE, update_accountfrom autoteam.cloudmail import CloudMailClientfrom autoteam.codex_auth import check_codex_quota, login_codex_via_browser, save_auth_filemail_client = CloudMailClient()mail_client.login()10 unmodified linesst, info = check_codex_quota(token)if st == "ok" and isinstance(info, dict):update_account(email, last_quota=info)# 同步到 CPAfrom autoteam.cpa_sync import sync_to_cpa9 unmodified linesdef get_status():"""获取所有账号状态 + active 账号实时额度"""from autoteam.accounts import STATUS_ACTIVE, STATUS_EXHAUSTED, STATUS_PENDING, STATUS_STANDBY, load_accountsfrom autoteam.codex_auth import check_codex_quotaaccounts = load_accounts()quota_cache = {}7 unmodified linesstatus, info = check_codex_quota(access_token)if status == "ok" and isinstance(info, dict):quota_cache[acc["email"]] = infoexcept Exception:pass124 unmodified linesif not email or not user_id:raise HTTPException(status_code=400, detail="缺少必要参数")if member_type not in ("member", "invite"):raise HTTPException(status_code=400, detail="无效的成员类型")293 unmodified lines@app.on_event("startup")def _start_auto_check():thread = threading.Thread(target=_auto_check_loop, daemon=True)thread.start()319 unmodified lines32032132232332432532632732832933016 unmodified lines34734834935035135235335435535635735835936036136236336436536636739 unmodified lines4074084094104114124134 unmodified lines418419420421422423424425426427428429430431432433434119 unmodified lines554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610135 unmodified lines746747748749750751752753754755756757758759760761762763764171 unmodified lines93693793893994094194294394494594694794894995095195295395495595695755 unmodified lines10131014101510161017101810191020102119 unmodified lines1041104210431044104510461047104830 unmodified lines107910801081108210831084108510862 unmodified lines108910901091109210931094109510961097109810991100110110 unmodified lines11121113111411151116111711181119112011211122112311241125112611279 unmodified lines11371138113911401141114211437 unmodified lines1151115211531154115511561157115811591160124 unmodified lines12851286128712881289129012911292293 unmodified lines158615871588158915901591159215931594159515961597159815991600319 unmodified linesemail: strclass AdminSessionParams(BaseModel):email: strsession_token: strclass AdminPasswordParams(BaseModel):password: str16 unmodified linestype: strdef _normalized_email(value: str | None) -> str:return (value or "").strip().lower()def _is_main_account_email(email: str | None) -> bool:from autoteam.admin_state import get_admin_emailreturn bool(_normalized_email(email)) and _normalized_email(email) == _normalized_email(get_admin_email())def _sanitize_account(acc: dict) -> dict:"""脱敏账号信息(去掉 password 等敏感字段)"""sanitized = {k: v for k, v in acc.items() if k not in ("password", "cloudmail_account_id")}sanitized["is_main_account"] = _is_main_account_email(acc.get("email"))return sanitizeddef _admin_status():39 unmodified linesdef _finish_admin_login(completed: dict):global _admin_login_api, _admin_login_stepapi = _admin_login_apiinfo = Nonetry:info = _pw_executor.run(api.complete_admin_login)finally:4 unmodified linespass_admin_login_api = None_admin_login_step = Noneif info and info.get("session_token") and info.get("account_id"):try:from autoteam.codex_auth import refresh_main_auth_filemain_auth = _pw_executor.run(refresh_main_auth_file)if main_auth:info["main_auth"] = main_authlogger.info("[API] 管理员登录后已刷新主号认证文件: %s", main_auth.get("auth_file"))except Exception as exc:info["main_auth_error"] = str(exc)logger.warning("[API] 管理员登录完成,但刷新主号认证文件失败: %s", exc)if _playwright_lock.locked():_playwright_lock.release()return {"status": "completed", "admin": _admin_status(), "info": info}119 unmodified linesraise HTTPException(status_code=400, detail=str(exc))@app.post("/api/admin/login/session")def post_admin_login_session(params: AdminSessionParams):"""手动导入管理员 session_token。"""global _admin_login_api, _admin_login_stepif _admin_login_api:post_admin_login_cancel()if not _playwright_lock.acquire(blocking=False):raise HTTPException(status_code=409,detail=_current_busy_detail("有任务正在执行,请等待完成后再导入管理员 session_token"),)try:from autoteam.chatgpt_api import ChatGPTTeamAPIlogger.info("[API] 导入管理员 session_token: %s", params.email.strip())def _do_import(email, session_token):api = ChatGPTTeamAPI()try:return api.import_admin_session(email, session_token)finally:api.stop()info = _pw_executor.run(_do_import, params.email.strip(), params.session_token.strip())if info.get("session_token") and info.get("account_id"):try:from autoteam.codex_auth import refresh_main_auth_filemain_auth = _pw_executor.run(refresh_main_auth_file)if main_auth:info["main_auth"] = main_authlogger.info("[API] session_token 导入后已刷新主号认证文件: %s", main_auth.get("auth_file"))except Exception as exc:info["main_auth_error"] = str(exc)logger.warning("[API] session_token 导入完成,但刷新主号认证文件失败: %s", exc)_admin_login_api = None_admin_login_step = Nonereturn {"status": "completed", "admin": _admin_status(), "info": info}except HTTPException:raiseexcept Exception as exc:logger.exception("[API] 导入管理员 session_token 失败")raise HTTPException(status_code=400, detail=str(exc))finally:if _playwright_lock.locked():_playwright_lock.release()@app.post("/api/admin/login/password")def post_admin_login_password(params: AdminPasswordParams):"""提交管理员密码。"""135 unmodified linesif _playwright_lock.locked():_playwright_lock.release()from autoteam.codex_auth import get_saved_main_auth_filefrom autoteam.cpa_sync import sync_main_codex_to_cpasaved_auth_file = get_saved_main_auth_file()if saved_auth_file:sync_main_codex_to_cpa(saved_auth_file)return {"status": "completed","message": "主号 Codex 已同步到 CPA","codex": _main_codex_status(),"info": {"auth_file": saved_auth_file},}if not _playwright_lock.acquire(blocking=False):raise HTTPException(status_code=409, detail=_current_busy_detail("有任务正在执行,请等待完成后再同步主号 Codex")171 unmodified linesdef get_codex_auth(email: str):"""导出账号的 Codex CLI 格式认证文件(~/.codex/auth.json)"""from autoteam.accounts import find_account, load_accountsfrom autoteam.codex_auth import get_saved_main_auth_fileemail = email.strip().lower()auth_file = ""if _is_main_account_email(email):auth_file = get_saved_main_auth_file()if not auth_file or not Path(auth_file).exists():raise HTTPException(status_code=404, detail="主号没有可导出的认证文件")else:acc = find_account(load_accounts(), email)if not acc:raise HTTPException(status_code=404, detail="账号不存在")auth_file = acc.get("auth_file") or ""if not auth_file or not Path(auth_file).exists():raise HTTPException(status_code=404, detail="该账号没有认证文件")auth_data = json.loads(Path(auth_file).read_text())55 unmodified linesfrom autoteam.account_ops import delete_managed_accountfrom autoteam.accounts import load_accountsif _is_main_account_email(email):raise HTTPException(status_code=400, detail="主号不允许删除")accounts = load_accounts()if not any(a["email"].lower() == email.lower() for a in accounts):raise HTTPException(status_code=404, detail="账号不存在")19 unmodified linesfrom autoteam.manager import remove_from_teamemail = email.strip().lower()if _is_main_account_email(email):raise HTTPException(status_code=400, detail="主号不允许移出 Team")accounts = load_accounts()acc = find_account(accounts, email)if not acc:30 unmodified linesfrom autoteam.accounts import find_account, load_accountsemail = params.email.strip().lower()if _is_main_account_email(email):raise HTTPException(status_code=400, detail="主号不属于账号池登录对象")accounts = load_accounts()acc = find_account(accounts, email)if not acc:2 unmodified linesdef _run():from autoteam.accounts import STATUS_ACTIVE, update_accountfrom autoteam.cloudmail import CloudMailClientfrom autoteam.codex_auth import (check_codex_quota,login_codex_via_browser,quota_result_quota_info,quota_result_resets_at,save_auth_file,)mail_client = CloudMailClient()mail_client.login()10 unmodified linesst, info = check_codex_quota(token)if st == "ok" and isinstance(info, dict):update_account(email, last_quota=info)elif st == "exhausted":quota_info = quota_result_quota_info(info)if quota_info:update_account(email, last_quota=quota_info)update_account(email,status="exhausted",quota_exhausted_at=time.time(),quota_resets_at=quota_result_resets_at(info) or int(time.time() + 18000),)# 同步到 CPAfrom autoteam.cpa_sync import sync_to_cpa9 unmodified linesdef get_status():"""获取所有账号状态 + active 账号实时额度"""from autoteam.accounts import STATUS_ACTIVE, STATUS_EXHAUSTED, STATUS_PENDING, STATUS_STANDBY, load_accountsfrom autoteam.codex_auth import check_codex_quota, quota_result_quota_infoaccounts = load_accounts()quota_cache = {}7 unmodified linesstatus, info = check_codex_quota(access_token)if status == "ok" and isinstance(info, dict):quota_cache[acc["email"]] = infoelif status == "exhausted":quota_info = quota_result_quota_info(info)if quota_info:quota_cache[acc["email"]] = quota_infoexcept Exception:pass124 unmodified linesif not email or not user_id:raise HTTPException(status_code=400, detail="缺少必要参数")if _is_main_account_email(email):raise HTTPException(status_code=400, detail="主号不允许从 Team 成员页移出")if member_type not in ("member", "invite"):raise HTTPException(status_code=400, detail="无效的成员类型")293 unmodified lines@app.on_event("startup")def _start_auto_check():try:from autoteam.auth_storage import ensure_auth_file_permissionsfixed = ensure_auth_file_permissions()if fixed:logger.info("[启动] 已修复 %d 个 auths 认证文件权限", fixed)except Exception as exc:logger.warning("[启动] 修复 auths 认证文件权限失败: %s", exc)thread = threading.Thread(target=_auto_check_loop, daemon=True)thread.start()
1234567891011121314151617181920212223242526272829303132333435"""认证文件目录与权限辅助。"""
from pathlib import Path
PROJECT_ROOT = Path(__file__).parent.parent.parentAUTH_DIR = PROJECT_ROOT / "auths"
# Docker bind mount 下文件常由容器用户写入;给宿主机用户保留可读写权限。AUTH_FILE_MODE = 0o666
def ensure_auth_dir() -> Path: AUTH_DIR.mkdir(exist_ok=True) return AUTH_DIR
def ensure_auth_file_permissions(filepath: str | Path | None = None) -> int: """统一修复 auths 目录下认证文件权限。""" ensure_auth_dir()
if filepath is None: candidates = list(AUTH_DIR.glob("codex-*.json")) else: candidates = [Path(filepath)]
updated = 0 for path in candidates: if not path.exists() or not path.is_file(): continue try: path.chmod(AUTH_FILE_MODE) updated += 1 except Exception: continue return updated1234543 unmodified lines495051525354115 unmodified lines17017117217317417517617717817918018112 unmodified lines19419519619719819937 unmodified lines23723823924024124224324497 unmodified lines3423433443453463473 unmodified lines3513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224237 unmodified lines4314324334344354364379 unmodified lines44744844945045145218 unmodified lines47147247347447547647713 unmodified lines49149249349449549649749849950050150250350450550650794 unmodified lines60260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363421 unmodified lines65665765865966066166266366466566666766866967067167267367467567667736 unmodified lines71471571671771871927 unmodified lines7477487497507517527537547557567577587597607615 unmodified lines7677687697707717727737747757767777787797807817827835 unmodified lines7897907917927937947957 unmodified lines80380480580680780880981081181281381481515 unmodified lines831832833834835836837838"""ChatGPT Team API 客户端 - 通过 Playwright 绕过 Cloudflare 调用内部 API"""import jsonimport loggingimport re43 unmodified lines'input[inputmode="numeric"]','input[autocomplete="one-time-code"]',]def __init__(self):self.playwright = None115 unmodified linesexcept Exception:passtry:field.press("Enter")return Trueexcept Exception:return Falsedef _extract_session_token(self):cookies = self.context.cookies()session_parts = {}12 unmodified linesself.session_token = session_tokenreturn session_tokendef _inject_session(self, session_token):cookies = self._build_session_cookies(session_token, "chatgpt.com")if self.account_id:37 unmodified linespassdef _list_workspace_options(self):url = (self.page.url or "").lower()if "workspace" not in url and "organization" not in url:return []logger.info("[ChatGPT] 检测到 workspace 选择页,开始收集组织候选 | URL=%s", self.page.url)97 unmodified linesreturn self.workspace_options_cachereturn self._list_workspace_options()def select_workspace_option(self, option_id):options = self._list_workspace_options()for option in options:3 unmodified lineslabel = option["label"]logger.info("[ChatGPT] 用户选择 workspace: %s", label)# 用 JS 找到包含该文本的可点击卡片并点击clicked = Falsetry:clicked = self.page.evaluate("""(label) => {// 找到文本完全匹配的最小元素let matchEl = null;for (const el of document.querySelectorAll('*')) {// 直接文本内容(不含子元素的文本)匹配const directText = Array.from(el.childNodes).filter(n => n.nodeType === 3).map(n => n.textContent.trim()).join('');if (directText === label) {matchEl = el;break;}}if (!matchEl) {// fallback: textContent 完全匹配for (const el of document.querySelectorAll('*')) {if (el.textContent.trim() === label && el.children.length === 0) {matchEl = el;break;}}}if (!matchEl) return false;// 从匹配元素往上找最近的可点击容器(a/button/有 click handler 的 div)let target = matchEl;let bestTarget = matchEl;while (target && target.tagName !== 'BODY') {const tag = target.tagName.toLowerCase();if (tag === 'a' || tag === 'button') {bestTarget = target;break;}// 有 cursor:pointer 样式的元素const style = window.getComputedStyle(target);if (style.cursor === 'pointer') {bestTarget = target;}target = target.parentElement;}bestTarget.click();return true;}""",label,)except Exception as e:logger.warning("[ChatGPT] JS 点击 workspace 失败: %s", e)if not clicked:# fallback: Playwright text 选择器 + force clicktry:loc = self.page.locator(f"text={label}").firstif loc.is_visible(timeout=2000):loc.click(force=True)clicked = Trueexcept Exception:passif not clicked:raise RuntimeError(f"未找到可点击的 workspace 选项: {label}")time.sleep(3)self.workspace_options_cache = []self._log_login_state("选择 workspace 后")step, detail = self._detect_login_step()7 unmodified lineslogger.warning("[ChatGPT] 登录步骤检测: 误跳转 Google | URL=%s", self.page.url)return "error", "误跳转到了 Google 登录"if "workspace" in (self.page.url or "").lower() or "organization" in (self.page.url or "").lower():logger.info("[ChatGPT] 登录步骤检测: workspace 页面 | URL=%s", self.page.url)return "workspace_required", None9 unmodified lineslogger.info("[ChatGPT] 登录步骤检测: password_required | URL=%s", self.page.url)return "password_required", Nonesession_token = self._extract_session_token()if session_token:logger.info("[ChatGPT] 登录步骤检测: completed(session) | URL=%s", self.page.url)18 unmodified linesself._log_login_state("进入 chatgpt.com 后")self._open_login_page()step, detail = self._detect_login_step()if step == "workspace_required":self._list_workspace_options()if step in ("password_required", "code_required", "workspace_required", "completed", "error"):13 unmodified linespassraise RuntimeError(f"未找到{actor_label}邮箱输入框,当前 URL: {self.page.url},页面片段: {body_excerpt}")email_input.fill(email)time.sleep(0.5)self._click_auth_button(email_input, ["Continue", "继续"])time.sleep(3)self._log_login_state(f"{actor_label}邮箱提交后")step, detail = self._detect_login_step()if step == "workspace_required":self._list_workspace_options()logger.info("[ChatGPT] %s邮箱提交结果: %s | detail=%s", actor_label, step, detail)return {"step": step, "detail": detail}def begin_admin_login(self, email):return self.begin_login(email, actor_label="管理员")94 unmodified linesdef submit_admin_code(self, code):return self.submit_login_code(code, actor_label="管理员")def _guess_account_info(self):try:data = self.page.evaluate("""async () => {const out = {};for (const path of ['/backend-api/accounts', '/backend-api/me', '/api/auth/session']) {try {const resp = await fetch(path);out[path] = { status: resp.status, data: await resp.json() };} catch (e) {out[path] = { error: String(e) };}}return out;}""")except Exception:data = {}candidates = []_uuid_re = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I)def walk(node):if isinstance(node, dict):# account_id 必须是 UUID 格式(排除 user-xxx 等非 account ID)account_id = node.get("account_id")if not account_id or not _uuid_re.match(str(account_id)):account_id = node.get("id")if not account_id or not _uuid_re.match(str(account_id)):account_id = None# workspace_name 只取 workspace_name 字段,不取 name/display_name(那可能是用户名)name = node.get("workspace_name") or ""21 unmodified linesif not chosen and candidates:chosen = candidates[0]try:self.page.goto("https://chatgpt.com/admin", wait_until="domcontentloaded", timeout=30000)time.sleep(5)dom_name = self.page.evaluate("""() => {const headings = document.querySelectorAll('h1, h2, h3, [class*="title"], [class*="name"]');for (const h of headings) {const text = h.textContent.trim();if (text && text.length < 50 && text.length > 1&& !["常规", "成员", "设置", "General", "Members", "Settings"].includes(text)) {return text;}}return null;}""")except Exception:dom_name = Noneaccount_id = (chosen or {}).get("account_id") or self.account_idworkspace_name = (chosen or {}).get("workspace_name") or dom_name or self.workspace_name36 unmodified linesdef complete_admin_login(self):return self.complete_login(persist_admin_state=True)def start(self):"""用已保存的管理员 session 启动 Team API 客户端。"""session_token = get_admin_session_token()27 unmodified linesreturn ""result = self.page.evaluate("""async (accountId) => {try {const resp = await fetch("/backend-api/accounts/" + accountId + "/settings", {headers: { "chatgpt-account-id": accountId }});return await resp.json();} catch(e) { return null; }}""",self.account_id,)if result and result.get("workspace_name"):5 unmodified linestry:self.page.goto("https://chatgpt.com/admin", wait_until="domcontentloaded", timeout=30000)time.sleep(5)name = self.page.evaluate("""() => {const headings = document.querySelectorAll('h1, h2, h3, [class*="title"], [class*="name"]');for (const h of headings) {const text = h.textContent.trim();if (text && text.length < 50 && text.length > 1&& !["常规", "成员", "设置", "General", "Members", "Settings"].includes(text)) {return text;}}return null;}""")if name:self.workspace_name = nameupdate_admin_state(workspace_name=self.workspace_name, account_id=self.account_id)5 unmodified lineslogger.warning("[ChatGPT] 未能自动获取 workspace 名称")return ""def _fetch_access_token(self):result = self.page.evaluate("""async () => {try {const resp = await fetch("/api/auth/session");7 unmodified linesif result.get("ok") and "accessToken" in result.get("data", {}):self.access_token = result["data"]["accessToken"]logger.info("[ChatGPT] 已获取 access token")returnbearer_file = BASE_DIR / "bearer_token"if bearer_file.exists():self.access_token = read_text(bearer_file).strip()logger.info("[ChatGPT] 从 bearer_token 文件加载 access token")returnlogger.info("[ChatGPT] 尝试通过页面获取 access token...")self.page.goto("https://chatgpt.com/", wait_until="networkidle", timeout=60000)15 unmodified linesif token:self.access_token = tokenlogger.info("[ChatGPT] 从页面获取到 access token")else:logger.warning("[ChatGPT] 未能获取 access token,将尝试无 token 调用")def _api_fetch(self, method, path, body=None):headers_js = {12345643 unmodified lines50515253545556575859606162636465666768697071727374757677787980818283115 unmodified lines19920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423512 unmodified lines24824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838937 unmodified lines42742842943043143243397 unmodified lines5315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756763 unmodified lines6806816826836846856866876886896906916926936946956966976986997 unmodified lines7077087097107117127139 unmodified lines72372472572672772872973073173273373473573673718 unmodified lines75675775875976076176276376476513 unmodified lines77978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282394 unmodified lines91891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295321 unmodified lines97597697797897998098198298398498598698798836 unmodified lines1025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110427 unmodified lines113211331134113511361137113811391140114111421143114411451146114711485 unmodified lines11541155115611571158115911605 unmodified lines11661167116811691170117111727 unmodified lines1180118111821183118411851186118711881189119011911192119315 unmodified lines1209121012111212121312141215121612171218"""ChatGPT Team API 客户端 - 通过 Playwright 绕过 Cloudflare 调用内部 API"""import base64import jsonimport loggingimport re43 unmodified lines'input[inputmode="numeric"]','input[autocomplete="one-time-code"]',]_UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I)_WORKSPACE_NAME_EXCLUDES = {"常规","成员","设置","帮助","general","members","settings","help","chat history","new chat","search chats","images","apps","deep research","see plans and pricing","log in","chatgpt",}_WORKSPACE_PAGE_HINTS = ("launch a workspace","has access to","workspace","personal workspace","选择工作空间","选择一个工作空间",)def __init__(self):self.playwright = None115 unmodified linesexcept Exception:passtry:btn = self.page.get_by_role("button", name=label_re).lastif btn.is_visible(timeout=2000):btn.click()return Trueexcept Exception:passtry:field.press("Enter")return Trueexcept Exception:return Falsedef _body_excerpt(self, limit=300):try:return self.page.locator("body").inner_text(timeout=1500)[:limit].replace("\n", " ")except Exception:return ""def _wait_for_login_step(self, allowed_steps, timeout=15):deadline = time.time() + timeoutwhile time.time() < deadline:step, detail = self._detect_login_step()if step in allowed_steps:return step, detailif "challenge" in (self.page.url or "").lower():self._wait_for_cloudflare()time.sleep(0.5)return self._detect_login_step()def _extract_session_token(self):cookies = self.context.cookies()session_parts = {}12 unmodified linesself.session_token = session_tokenreturn session_tokendef _extract_account_id_from_access_token(self):if not self.access_token:return ""try:parts = self.access_token.split(".")if len(parts) < 2:return ""payload_part = parts[1] + "=" * (-len(parts[1]) % 4)payload = json.loads(base64.urlsafe_b64decode(payload_part))except Exception:payload = {}auth_claims = payload.get("https://api.openai.com/auth", {}) if isinstance(payload, dict) else {}account_id = auth_claims.get("chatgpt_account_id", "") if isinstance(auth_claims, dict) else ""if account_id and self._UUID_RE.match(str(account_id)):return str(account_id)return ""def _detect_workspace_name_from_dom(self):if not self.page:return ""try:name = self.page.evaluate("""(excludes) => {const excludeSet = new Set((excludes || []).map(x => String(x).toLowerCase().trim()));const selectors = ['main h1', 'main h2', 'main h3','[role="main"] h1', '[role="main"] h2', '[role="main"] h3','main [class*="title"]', 'main [class*="name"]','[role="main"] [class*="title"]', '[role="main"] [class*="name"]','h1', 'h2', 'h3','[class*="title"]', '[class*="name"]',];const seen = new Set();for (const selector of selectors) {const nodes = document.querySelectorAll(selector);for (const node of nodes) {const text = (node.textContent || '').trim().replace(/\\s+/g, ' ');const lower = text.toLowerCase();if (!text || text.length < 2 || text.length > 60) continue;if (excludeSet.has(lower)) continue;if (lower.includes('chat history') ||lower.includes('new chat') ||lower.includes('search chats') ||lower.includes('see plans and pricing') ||lower.includes('log in to get answers based on saved chats')) continue;if (seen.has(lower)) continue;seen.add(lower);return text;}}return '';}""",sorted(self._WORKSPACE_NAME_EXCLUDES),)except Exception:name = ""return (name or "").strip()def _is_workspace_selection_page(self):url = (self.page.url or "").lower()if "workspace" in url or "organization" in url:return Truetry:body = self.page.locator("body").inner_text(timeout=1500).lower()except Exception:body = ""hint_hits = sum(1 for hint in self._WORKSPACE_PAGE_HINTS if hint in body)return hint_hits >= 2 or ("launch a workspace" in body)def _auto_open_preferred_workspace(self):"""在 workspace 选择页自动点击优先的 Team workspace。"""if not self.page:return Falsetry:result = self.page.evaluate("""() => {const norm = (s) => (s || '').replace(/\\s+/g, ' ').trim();const lower = (s) => norm(s).toLowerCase();const badKeywords = ['personal workspace', 'personal account', 'personal', 'free', '免费', '个人'];const buttons = Array.from(document.querySelectorAll('button, a, [role="button"]'));const candidates = [];for (const btn of buttons) {const btnText = lower(btn.textContent);if (!btnText || !['open', '打开', 'launch', 'continue', '进入'].some(k => btnText.includes(k))) continue;let card = btn;for (let i = 0; i < 6 && card && card.parentElement; i++) {card = card.parentElement;const text = norm(card.textContent);if (!text || text.length < 4) continue;if (text.length > 200) continue;const textLower = text.toLowerCase();const bad = badKeywords.some(k => textLower.includes(k));candidates.push({text,bad,score: (bad ? 0 : 100) + Math.min(text.length, 80),buttonIndex: buttons.indexOf(btn),});break;}}if (!candidates.length) return { clicked: false, reason: 'no-candidates' };candidates.sort((a, b) => b.score - a.score);const chosen = candidates[0];const btn = buttons[chosen.buttonIndex];if (!btn) return { clicked: false, reason: 'missing-button' };btn.click();return { clicked: true, label: chosen.text, bad: chosen.bad };}""")except Exception as exc:logger.warning("[ChatGPT] 自动点击 workspace 失败: %s", exc)return Falseif result and result.get("clicked"):logger.info("[ChatGPT] 自动进入 workspace: %s", result.get("label", ""))time.sleep(5)self._wait_for_cloudflare()self._log_login_state("自动进入 workspace 后")return Truelogger.warning("[ChatGPT] 未找到可自动进入的 workspace: %s", (result or {}).get("reason"))return Falsedef _inject_session(self, session_token):cookies = self._build_session_cookies(session_token, "chatgpt.com")if self.account_id:37 unmodified linespassdef _list_workspace_options(self):if not self._is_workspace_selection_page():return []logger.info("[ChatGPT] 检测到 workspace 选择页,开始收集组织候选 | URL=%s", self.page.url)97 unmodified linesreturn self.workspace_options_cachereturn self._list_workspace_options()def _click_workspace_option_by_label(self, label):if not self.page:return Falsetry:result = self.page.evaluate("""(label) => {const norm = (s) => (s || '').replace(/\\s+/g, ' ').trim();const lower = (s) => norm(s).toLowerCase();const targetLabel = lower(label);const actionWords = ['open', '打开', 'launch', 'continue', '进入'];const interactive = Array.from(document.querySelectorAll('button, a, [role="button"]'));const candidates = [];const collectCandidate = (el, cardText, depth) => {const idx = interactive.indexOf(el);if (idx < 0) return;const btnText = norm(el.textContent);const btnLower = btnText.toLowerCase();let score = 100 - depth;if (btnLower === targetLabel) score += 30;if (actionWords.some(word => btnLower.includes(word))) score += 100;if (lower(cardText).startsWith(targetLabel)) score += 15;candidates.push({buttonIndex: idx,buttonText: btnText,cardText: norm(cardText).slice(0, 160),score,});};for (const el of interactive) {let node = el;for (let depth = 0; depth < 7 && node && node.parentElement; depth++) {node = node.parentElement;const cardText = norm(node.textContent);if (!cardText) continue;if (!lower(cardText).includes(targetLabel)) continue;collectCandidate(el, cardText, depth);break;}}if (!candidates.length) {const allNodes = Array.from(document.querySelectorAll('*'));for (const node of allNodes) {const text = norm(node.textContent);if (lower(text) !== targetLabel) continue;let parent = node;for (let depth = 0; depth < 7 && parent && parent.parentElement; depth++) {parent = parent.parentElement;const buttons = Array.from(parent.querySelectorAll('button, a, [role="button"]'));if (!buttons.length) continue;for (const btn of buttons) {collectCandidate(btn, parent.textContent || text, depth + 10);}if (buttons.length) break;}}}if (!candidates.length) {return { clicked: false, reason: 'no-match' };}candidates.sort((a, b) => b.score - a.score);const chosen = candidates[0];const btn = interactive[chosen.buttonIndex];if (!btn) {return { clicked: false, reason: 'missing-button', chosen };}btn.click();return {clicked: true,buttonText: chosen.buttonText,cardText: chosen.cardText,candidateCount: candidates.length,};}""",label,)except Exception as exc:logger.warning("[ChatGPT] JS 点击 workspace(%s) 失败: %s", label, exc)result = Noneif result and result.get("clicked"):logger.info("[ChatGPT] 点击 workspace 动作成功: label=%s button=%s candidates=%s card=%s",label,result.get("buttonText", ""),result.get("candidateCount", 0),result.get("cardText", ""),)return Truetry:action_re = re.compile(r"(open|打开|launch|continue|进入)", re.I)container = self.page.locator(f"text={label}").first.locator("xpath=ancestor::*[self::div or self::li or self::section][1]")action_btn = container.get_by_role("button", name=action_re).firstif action_btn.is_visible(timeout=2000):action_btn.click(force=True)logger.info("[ChatGPT] Playwright fallback 点击 workspace 动作: %s", label)return Trueexcept Exception:passtry:loc = self.page.locator(f"text={label}").firstif loc.is_visible(timeout=2000):loc.click(force=True)logger.info("[ChatGPT] Playwright fallback 点击 workspace 文本: %s", label)return Trueexcept Exception:passlogger.warning("[ChatGPT] 未找到可点击的 workspace 动作: %s | reason=%s", label, (result or {}).get("reason"))return Falsedef _wait_for_workspace_selection_exit(self, timeout=15):deadline = time.time() + timeoutlast_url = self.page.url if self.page else ""while time.time() < deadline:if not self.page:return Falsetry:self.page.wait_for_load_state("domcontentloaded", timeout=1000)except Exception:passif "challenge" in (self.page.url or "").lower():self._wait_for_cloudflare()if not self._is_workspace_selection_page():return Truelast_url = self.page.urltime.sleep(0.5)logger.warning("[ChatGPT] workspace 点击后仍停留在选择页 | URL=%s", last_url)return Falsedef select_workspace_option(self, option_id):options = self._list_workspace_options()for option in options:3 unmodified lineslabel = option["label"]logger.info("[ChatGPT] 用户选择 workspace: %s", label)clicked = self._click_workspace_option_by_label(label)if not clicked:raise RuntimeError(f"未找到可点击的 workspace 选项: {label}")exited = self._wait_for_workspace_selection_exit(timeout=15)if not exited:logger.warning("[ChatGPT] 手动选择 workspace 后仍未离开选择页,尝试自动点击一次: %s", label)if self._auto_open_preferred_workspace():self._wait_for_workspace_selection_exit(timeout=10)try:self.page.wait_for_load_state("domcontentloaded", timeout=5000)except Exception:passself.workspace_options_cache = []self._log_login_state("选择 workspace 后")step, detail = self._detect_login_step()7 unmodified lineslogger.warning("[ChatGPT] 登录步骤检测: 误跳转 Google | URL=%s", self.page.url)return "error", "误跳转到了 Google 登录"if self._is_workspace_selection_page():logger.info("[ChatGPT] 登录步骤检测: workspace 页面 | URL=%s", self.page.url)return "workspace_required", None9 unmodified lineslogger.info("[ChatGPT] 登录步骤检测: password_required | URL=%s", self.page.url)return "password_required", Noneif self._visible_locator_in_frames(self.EMAIL_INPUT_SELECTORS, timeout_ms=1200):logger.info("[ChatGPT] 登录步骤检测: email_required | URL=%s", self.page.url)return "email_required", Noneurl = (self.page.url or "").lower()if "log-in-or-create-account" in url or url.endswith("/auth/login"):logger.info("[ChatGPT] 登录步骤检测: email_required(url) | URL=%s", self.page.url)return "email_required", Nonesession_token = self._extract_session_token()if session_token:logger.info("[ChatGPT] 登录步骤检测: completed(session) | URL=%s", self.page.url)18 unmodified linesself._log_login_state("进入 chatgpt.com 后")self._open_login_page()step, detail = self._wait_for_login_step({"email_required", "password_required", "code_required", "workspace_required", "completed", "error"},timeout=12,)if step == "workspace_required":self._list_workspace_options()if step in ("password_required", "code_required", "workspace_required", "completed", "error"):13 unmodified linespassraise RuntimeError(f"未找到{actor_label}邮箱输入框,当前 URL: {self.page.url},页面片段: {body_excerpt}")final_step, final_detail = "unknown", self.page.urlfor attempt in range(1, 4):email_input = self._visible_locator_in_frames(self.EMAIL_INPUT_SELECTORS, timeout_ms=3000) or email_inputtry:email_input.fill(email)except Exception:try:email_input.click(timeout=1000)email_input.fill(email)except Exception:passtime.sleep(0.5)clicked = self._click_auth_button(email_input, ["Continue", "继续", "Log in"])logger.info("[ChatGPT] %s邮箱已提交(第 %d 次)| clicked=%s", actor_label, attempt, clicked)final_step, final_detail = self._wait_for_login_step({"email_required", "password_required", "code_required", "workspace_required", "completed", "error"},timeout=12,)self._log_login_state(f"{actor_label}邮箱提交后(第 {attempt} 次)")if final_step == "workspace_required":self._list_workspace_options()if final_step != "email_required":breaklogger.warning("[ChatGPT] %s邮箱提交后仍停留在邮箱步骤(第 %d 次)| URL=%s | body=%s",actor_label,attempt,self.page.url,self._body_excerpt(),)if final_step == "email_required":raise RuntimeError(f"{actor_label}邮箱提交后仍停留在邮箱步骤,请检查登录页是否拦截/未响应。"f" 当前 URL: {self.page.url},页面片段: {self._body_excerpt()}")logger.info("[ChatGPT] %s邮箱提交结果: %s | detail=%s", actor_label, final_step, final_detail)return {"step": final_step, "detail": final_detail}def begin_admin_login(self, email):return self.begin_login(email, actor_label="管理员")94 unmodified linesdef submit_admin_code(self, code):return self.submit_login_code(code, actor_label="管理员")def _guess_account_info(self, allow_dom_fallback=True):try:data = self.page.evaluate("""async (accessToken) => {const out = {};const headers = accessToken ? { authorization: `Bearer ${accessToken}` } : {};for (const path of ['/backend-api/accounts', '/backend-api/me', '/api/auth/session']) {try {const resp = await fetch(path, { headers });out[path] = { status: resp.status, data: await resp.json() };} catch (e) {out[path] = { error: String(e) };}}return out;}""",self.access_token,)except Exception:data = {}candidates = []def walk(node):if isinstance(node, dict):# account_id 必须是 UUID 格式(排除 user-xxx 等非 account ID)account_id = node.get("account_id")if not account_id or not self._UUID_RE.match(str(account_id)):account_id = node.get("id")if not account_id or not self._UUID_RE.match(str(account_id)):account_id = None# workspace_name 只取 workspace_name 字段,不取 name/display_name(那可能是用户名)name = node.get("workspace_name") or ""21 unmodified linesif not chosen and candidates:chosen = candidates[0]dom_name = Noneif allow_dom_fallback:try:self.page.goto("https://chatgpt.com/admin", wait_until="domcontentloaded", timeout=30000)time.sleep(5)dom_name = self._detect_workspace_name_from_dom() or Noneexcept Exception:dom_name = Noneaccount_id = (chosen or {}).get("account_id") or self.account_idworkspace_name = (chosen or {}).get("workspace_name") or dom_name or self.workspace_name36 unmodified linesdef complete_admin_login(self):return self.complete_login(persist_admin_state=True)def import_admin_session(self, email, session_token):"""手动导入管理员 session_token,并自动识别 workspace 信息。"""email = (email or "").strip()session_token = (session_token or "").strip()if not email:raise RuntimeError("管理员邮箱不能为空")if not session_token:raise RuntimeError("session_token 不能为空")self.login_email = emailself.session_token = session_tokenself._launch_browser()logger.info("[ChatGPT] 开始导入管理员 session_token: %s", email)self.page.goto("https://chatgpt.com/", wait_until="domcontentloaded", timeout=60000)time.sleep(5)self._wait_for_cloudflare()self._inject_session(session_token)self.page.goto("https://chatgpt.com/", wait_until="domcontentloaded", timeout=60000)time.sleep(5)self._wait_for_cloudflare()self._log_login_state("导入 session_token 后")if self._is_workspace_selection_page():logger.info("[ChatGPT] 检测到 workspace 选择页,尝试自动进入 Team workspace")self._auto_open_preferred_workspace()token_source = self._fetch_access_token(allow_bearer_file=False)if not token_source:raise RuntimeError("session_token 无效或已过期,未能从当前登录态获取 access token")logger.info("[ChatGPT] session_token 导入后 access token 来源: %s", token_source)account_id, workspace_name = self._guess_account_info(allow_dom_fallback=False)if not account_id:account_id = self._extract_account_id_from_access_token()if not account_id:cookie_account_id = ""try:for cookie in self.context.cookies():if cookie.get("name") == "_account" and self._UUID_RE.match(cookie.get("value", "")):cookie_account_id = cookie["value"]breakexcept Exception:passaccount_id = cookie_account_idif not account_id:raise RuntimeError("无法从 session_token 自动识别 workspace/account ID,请确认该 session 已登录 Team 主号")self.account_id = account_idself.workspace_name = workspace_name or ""if not self.workspace_name:try:self.workspace_name = self._auto_detect_workspace() or ""except Exception as exc:logger.warning("[ChatGPT] 自动获取 workspace 名称失败(已忽略): %s", exc)update_admin_state(email=email,session_token=session_token,account_id=self.account_id,workspace_name=self.workspace_name,)logger.info("[ChatGPT] 管理员 session_token 已保存")return {"email": email,"password": "","session_token": session_token,"account_id": self.account_id,"workspace_name": self.workspace_name,"session_len": len(session_token),}def start(self):"""用已保存的管理员 session 启动 Team API 客户端。"""session_token = get_admin_session_token()27 unmodified linesreturn ""result = self.page.evaluate("""async ([accountId, accessToken]) => {try {const headers = { "chatgpt-account-id": accountId };if (accessToken) headers["authorization"] = `Bearer ${accessToken}`;const resp = await fetch("/backend-api/accounts/" + accountId + "/settings", {headers});return await resp.json();} catch(e) { return null; }}""",[self.account_id, self.access_token],)if result and result.get("workspace_name"):5 unmodified linestry:self.page.goto("https://chatgpt.com/admin", wait_until="domcontentloaded", timeout=30000)time.sleep(5)name = self._detect_workspace_name_from_dom()if name:self.workspace_name = nameupdate_admin_state(workspace_name=self.workspace_name, account_id=self.account_id)5 unmodified lineslogger.warning("[ChatGPT] 未能自动获取 workspace 名称")return ""def _fetch_access_token(self, allow_bearer_file=True):result = self.page.evaluate("""async () => {try {const resp = await fetch("/api/auth/session");7 unmodified linesif result.get("ok") and "accessToken" in result.get("data", {}):self.access_token = result["data"]["accessToken"]logger.info("[ChatGPT] 已获取 access token")return "session"if allow_bearer_file:bearer_file = BASE_DIR / "bearer_token"if bearer_file.exists():self.access_token = read_text(bearer_file).strip()logger.info("[ChatGPT] 从 bearer_token 文件加载 access token")return "file"logger.info("[ChatGPT] 尝试通过页面获取 access token...")self.page.goto("https://chatgpt.com/", wait_until="networkidle", timeout=60000)15 unmodified linesif token:self.access_token = tokenlogger.info("[ChatGPT] 从页面获取到 access token")return "localstorage"else:logger.warning("[ChatGPT] 未能获取 access token,将尝试无 token 调用")return Nonedef _api_fetch(self, method, path, body=None):headers_js = {
71 unmodified lines72737475767778795 unmodified lines8586878889909171 unmodified lineslogger.info("[CloudMail] 临时邮箱已创建: %s (accountId=%s)", email, account_id)return account_id, emaildef search_emails_by_recipient(self, to_email, size=10):"""通过 admin API 按收件人搜索所有邮件(不受 accountId 限制)"""resp = self._get("/allEmail/list",{5 unmodified lines)if resp["code"] != 200:return []return resp["data"].get("list", [])def list_emails(self, account_id, size=10):"""获取指定账户的收件列表"""71 unmodified lines727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271285 unmodified lines13413513613713813914014114271 unmodified lineslogger.info("[CloudMail] 临时邮箱已创建: %s (accountId=%s)", email, account_id)return account_id, email@staticmethoddef _normalize_email(value):return str(value or "").strip().lower()def _resolve_account_id_for_email(self, to_email):"""优先从本地账号池解析 CloudMail accountId。"""target = self._normalize_email(to_email)if not target:return Nonetry:from autoteam.accounts import load_accountsfor acc in load_accounts():if self._normalize_email(acc.get("email")) == target:account_id = acc.get("cloudmail_account_id")if account_id:return account_idexcept Exception:passreturn Nonedef _filter_recipient_matches(self, emails, to_email):"""尽量过滤出真正属于目标收件箱的邮件。"""target = self._normalize_email(to_email)if not target:return emailsfiltered = []for em in emails:candidates = (em.get("accountEmail"),em.get("receiveEmail"),em.get("toEmail"),em.get("mailAddress"),em.get("email"),)candidate_values = [self._normalize_email(item) for item in candidates if item]if candidate_values and target not in candidate_values:continuefiltered.append(em)return filtereddef search_emails_by_recipient(self, to_email, size=10, account_id=None):"""优先读取该邮箱自己的收件箱;无法定位 accountId 时再回退到 admin 全局搜索。"""resolved_account_id = account_id or self._resolve_account_id_for_email(to_email)if resolved_account_id:emails = self.list_emails(resolved_account_id, size=size)if emails:return emailsresp = self._get("/allEmail/list",{5 unmodified lines)if resp["code"] != 200:return []emails = resp["data"].get("list", [])filtered = self._filter_recipient_matches(emails, to_email)return filtered or emailsdef list_emails(self, account_id, size=10):"""获取指定账户的收件列表"""
3 unmodified lines456789105 unmodified lines16171819202122232425262728293031323386 unmodified lines1201211221231241258 unmodified lines13413513613713813914049 unmodified lines190191192193194195493 unmodified lines6896906916926936946954 unmodified lines70070170270370470570670715 unmodified lines723724725726727728729730731732733734735736737738739740741742743744745746242 unmodified lines989990991992993994189 unmodified lines1184118511861187118811891 unmodified line11911192119311941195119611971198119912001201120212031204120512061207120874 unmodified lines1283128412851286128712881289129017 unmodified lines130813091310131113121313131422 unmodified lines133713381339134013411342134313441345134641 unmodified lines1388138913901391139213931394139513963 unmodified linesimport hashlibimport jsonimport loggingimport osimport reimport secretsimport time5 unmodified linesimport autoteam.display # noqa: F401from autoteam.admin_state import (get_admin_email,get_admin_password,get_admin_session_token,get_chatgpt_account_id,get_chatgpt_workspace_name,update_admin_state,)from autoteam.textio import write_textlogger = logging.getLogger(__name__)PROJECT_ROOT = Path(__file__).parent.parent.parentAUTH_DIR = PROJECT_ROOT / "auths"SCREENSHOT_DIR = PROJECT_ROOT / "screenshots"# Codex OAuth 配置86 unmodified linesdef _write_auth_file(filepath, bundle):filepath = Path(filepath)filepath.parent.mkdir(exist_ok=True)auth_data = {8 unmodified lines}write_text(filepath, json.dumps(auth_data, indent=2))os.chmod(filepath, 0o600)logger.info("[Codex] 认证文件已保存: %s", filepath)return str(filepath)49 unmodified linesreturn Falsedef login_codex_via_browser(email, password, mail_client=None):"""通过 Playwright 自动完成 Codex OAuth 登录。493 unmodified lines# 处理邮箱验证码页面(可能在 consent 流程中出现)try:otp_input = page.locator('input[name="code"], input[inputmode="numeric"]').firstif otp_input.is_visible(timeout=2000) and mail_client:import re as _re34 unmodified lines)otp = Noneotp_email_id = 0t0 = time.time()while time.time() - t0 < 120:for em in mail_client.search_emails_by_recipient(email, size=5):# 只接受比快照更新的邮件email_id = em.get("emailId", 0)15 unmodified linesbreaktime.sleep(3)if otp:_used_email_ids.add(otp_email_id)otp_input.fill(otp)time.sleep(0.5)page.locator('button[type="submit"], button:has-text("Continue"), button:has-text("继续")').first.click()time.sleep(5)logger.info("[Codex] 已输入验证码: %s", otp)# 检查验证码是否有效——如果页面还在验证码输入,说���无效try:still_code = page.locator('input[name="code"], input[inputmode="numeric"]').firstif still_code.is_visible(timeout=2000):logger.warning("[Codex] 验证码邮件 %s(code=%s)无效,标记并跳过该邮件", otp_email_id, otp)# 不 continue,让循环重新检测当前页面状态except Exception:passcontinueexcept Exception:pass242 unmodified lines'input[inputmode="numeric"]','input[autocomplete="one-time-code"]',]def __init__(self,189 unmodified linestime.sleep(5)return Truedef _advance(self, attempts=12):for _ in range(attempts):step, detail = self._detect_step()1 unmodified linereturn {"step": "completed", "detail": detail}if step == "code_required":return {"step": "code_required", "detail": detail}if step == "password_required" and not self.password:return {"step": "password_required", "detail": detail}if step == "email_required":if self._auto_fill_email():continuereturn {"step": "email_required", "detail": detail}if step == "password_required" and self.password:if self._auto_fill_password():continueif self._click_workspace_or_consent():continue74 unmodified linessession_token=get_admin_session_token(),account_id=get_chatgpt_account_id(),workspace_name=get_chatgpt_workspace_name(),password=get_admin_password(),password_callback=lambda password: update_admin_state(password=password),auth_file_callback=save_main_auth_file,)17 unmodified linesdef save_auth_file(bundle):"""保存 CPA 兼容的认证文件。同一邮箱只保留一个文件,优先 team。"""AUTH_DIR.mkdir(exist_ok=True)email = bundle["email"]plan_type = bundle.get("plan_type", "unknown")22 unmodified linesreturn _write_auth_file(filepath, bundle)def check_codex_quota(access_token, account_id=None):"""通过 /backend-api/wham/usage 查询 Codex 额度状态,不消耗额度。返回 ("ok", quota_info) | ("exhausted", resets_at) | ("auth_error", None)quota_info = {"primary_pct": int, "primary_resets_at": int, "weekly_pct": int, "weekly_resets_at": int}"""import requests41 unmodified lines"weekly_resets_at": secondary.get("reset_at", 0),}# limit_reached 或 5h 额度用完(100%)if rate_limit.get("limit_reached") or quota_info["primary_pct"] >= 100:return "exhausted", quota_info["primary_resets_at"] or (time.time() + 18000)return "ok", quota_info3 unmodified lines4567895 unmodified lines1516171819202122232425262728293086 unmodified lines1171181191201211221238 unmodified lines13213313413513613713849 unmodified lines188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251493 unmodified lines7457467477487497507514 unmodified lines75675775875976076176276376476576676776815 unmodified lines784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838242 unmodified lines10811082108310841085108610871088108910901091109210931094109510961097109810991100189 unmodified lines129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121 unmodified line131413151316131713181319132013211322132313241325132613271328132913301331133274 unmodified lines1407140814091410141114121413141417 unmodified lines143214331434143514361437143822 unmodified lines14611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157441 unmodified lines1616161716181619162016211622162316243 unmodified linesimport hashlibimport jsonimport loggingimport reimport secretsimport time5 unmodified linesimport autoteam.display # noqa: F401from autoteam.admin_state import (get_admin_email,get_admin_session_token,get_chatgpt_account_id,get_chatgpt_workspace_name,)from autoteam.auth_storage import AUTH_DIR, ensure_auth_dir, ensure_auth_file_permissionsfrom autoteam.textio import write_textlogger = logging.getLogger(__name__)PROJECT_ROOT = Path(__file__).parent.parent.parentSCREENSHOT_DIR = PROJECT_ROOT / "screenshots"# Codex OAuth 配置86 unmodified linesdef _write_auth_file(filepath, bundle):filepath = Path(filepath)ensure_auth_dir()filepath.parent.mkdir(exist_ok=True)auth_data = {8 unmodified lines}write_text(filepath, json.dumps(auth_data, indent=2))ensure_auth_file_permissions(filepath)logger.info("[Codex] 认证文件已保存: %s", filepath)return str(filepath)49 unmodified linesreturn False_OTP_INPUT_SELECTORS = ('input[name="code"], input[inputmode="numeric"], input[autocomplete="one-time-code"], ''input[placeholder*="验证码"], input[placeholder*="code" i]')_OTP_INVALID_HINTS = ("invalid code","incorrect code","wrong code","expired code","check the code and try again","验证码无效","验证码错误","验证码已过期",)def _is_otp_input_visible(page, timeout=500):try:return page.locator(_OTP_INPUT_SELECTORS).first.is_visible(timeout=timeout)except Exception:return Falsedef _detect_otp_error(page):try:body = page.locator("body").inner_text(timeout=1500).lower().replace("\n", " ")except Exception:return Nonefor hint in _OTP_INVALID_HINTS:if hint in body:return hintreturn Nonedef _wait_for_otp_submit_result(page, timeout=12):"""等待验证码提交结果:- accepted: 验证码输入框已消失 / 页面已前进- invalid: 页面明确提示验证码错误- pending: 既没报错也没明显前进(常见于页面较慢或状态未稳定)"""deadline = time.time() + timeoutwhile time.time() < deadline:err = _detect_otp_error(page)if err:return "invalid", errif not _is_otp_input_visible(page, timeout=250):return "accepted", Nonetime.sleep(0.5)err = _detect_otp_error(page)if err:return "invalid", errreturn "pending", Nonedef login_codex_via_browser(email, password, mail_client=None):"""通过 Playwright 自动完成 Codex OAuth 登录。493 unmodified lines# 处理邮箱验证码页面(可能在 consent 流程中出现)try:otp_input = page.locator(_OTP_INPUT_SELECTORS).firstif otp_input.is_visible(timeout=2000) and mail_client:import re as _re34 unmodified lines)otp = Noneotp_email_id = 0page_left_code = Falset0 = time.time()while time.time() - t0 < 120:if not _is_otp_input_visible(page, timeout=300):page_left_code = Truelogger.info("[Codex] 验证码页已退出,继续后续授权流程")breakfor em in mail_client.search_emails_by_recipient(email, size=5):# 只接受比快照更新的邮件email_id = em.get("emailId", 0)15 unmodified linesbreaktime.sleep(3)if otp:submit_ok = Falsefor submit_attempt in range(1, 3):otp_input = page.locator(_OTP_INPUT_SELECTORS).firstif not otp_input.is_visible(timeout=2000):submit_ok = Truebreakotp_input.fill(otp)time.sleep(0.5)page.locator('button[type="submit"], button:has-text("Continue"), button:has-text("继续")').first.click()logger.info("[Codex] 已输入验证码: %s", otp)submit_status, submit_detail = _wait_for_otp_submit_result(page, timeout=12)if submit_status == "accepted":submit_ok = Truebreakif submit_status == "invalid":_used_email_ids.add(otp_email_id)detail_suffix = f",命中提示: {submit_detail}" if submit_detail else ""logger.warning("[Codex] 验证码邮件 %s(code=%s)被页面判定无效%s,标记并跳过该邮件",otp_email_id,otp,detail_suffix,)breakif submit_attempt < 2:logger.warning("[Codex] 验证码邮件 %s(code=%s)提交后未确认成功,准备重试第 %d/2 次",otp_email_id,otp,submit_attempt + 1,)time.sleep(2)else:_used_email_ids.add(otp_email_id)logger.warning("[Codex] 验证码邮件 %s(code=%s)提交后仍未确认成功,标记并跳过该邮件",otp_email_id,otp,)if submit_ok:_used_email_ids.add(otp_email_id)continueif page_left_code:continueexcept Exception:pass242 unmodified lines'input[inputmode="numeric"]','input[autocomplete="one-time-code"]',]OTP_OPTION_SELECTORS = ['button:has-text("一次性验证码")','button:has-text("邮箱验证码")','button:has-text("Email login")','button:has-text("email login")','button:has-text("one-time")','button:has-text("One-time")','button:has-text("email code")','button:has-text("Email code")','a:has-text("一次性验证码")','a:has-text("邮箱验证码")','a:has-text("Email login")','a:has-text("one-time")',]def __init__(self,189 unmodified linestime.sleep(5)return Truedef _switch_password_to_otp(self):otp_entry = self._visible_locator(self.OTP_OPTION_SELECTORS, timeout_ms=1500)if not otp_entry:return Falsetry:otp_entry.click()except Exception:try:otp_entry.click(force=True)except Exception:return Falselogger.info("[Codex] 主号流程检测到密码页,自动切换到一次性验证码登录")time.sleep(3)return Truedef _advance(self, attempts=12):for _ in range(attempts):step, detail = self._detect_step()1 unmodified linereturn {"step": "completed", "detail": detail}if step == "code_required":return {"step": "code_required", "detail": detail}if step == "password_required":if self._switch_password_to_otp():continuereturn {"step": "unsupported_password","detail": "主号 Codex 当前停留在密码页,且未找到一次性验证码入口",}if step == "email_required":if self._auto_fill_email():continuereturn {"step": "email_required", "detail": detail}if self._click_workspace_or_consent():continue74 unmodified linessession_token=get_admin_session_token(),account_id=get_chatgpt_account_id(),workspace_name=get_chatgpt_workspace_name(),password="",password_callback=None,auth_file_callback=save_main_auth_file,)17 unmodified linesdef save_auth_file(bundle):"""保存 CPA 兼容的认证文件。同一邮箱只保留一个文件,优先 team。"""ensure_auth_dir()email = bundle["email"]plan_type = bundle.get("plan_type", "unknown")22 unmodified linesreturn _write_auth_file(filepath, bundle)def get_saved_main_auth_file():"""获取本地已保存的主号 Codex 认证文件路径。"""candidates = []for path in AUTH_DIR.glob("codex-main-*.json"):if not path.is_file():continuetry:stat = path.stat()except Exception:continuecandidates.append((stat.st_mtime, path.name, path))if not candidates:return ""candidates.sort(reverse=True)return str(candidates[0][2].resolve())def refresh_main_auth_file():"""基于已保存的管理员登录态,刷新并保存主号 Codex 认证文件。"""bundle = login_codex_via_session()if not bundle:raise RuntimeError("无法基于管理员登录态生成主号 Codex 认证文件")auth_file = save_main_auth_file(bundle)return {"email": bundle.get("email"),"auth_file": auth_file,"plan_type": bundle.get("plan_type"),}def quota_result_quota_info(info):"""从 check_codex_quota 返回值中提取额度快照。"""if not isinstance(info, dict):return Nonequota_info = info.get("quota_info")if isinstance(quota_info, dict):return quota_infoif "primary_pct" in info or "weekly_pct" in info:return inforeturn Nonedef quota_result_resets_at(info):"""从 check_codex_quota 返回值中提取恢复时间。"""if isinstance(info, dict):value = info.get("resets_at")else:value = infotry:return int(value or 0)except Exception:return 0def get_quota_exhausted_info(quota_info, *, limit_reached=False):"""根据额度快照判断是否已耗尽,并返回耗尽详情。"""if not isinstance(quota_info, dict):return Noneprimary_pct = int(quota_info.get("primary_pct", 0) or 0)weekly_pct = int(quota_info.get("weekly_pct", 0) or 0)primary_reset = int(quota_info.get("primary_resets_at", 0) or 0)weekly_reset = int(quota_info.get("weekly_resets_at", 0) or 0)primary_exhausted = primary_pct >= 100weekly_exhausted = weekly_pct >= 100if not (limit_reached or primary_exhausted or weekly_exhausted):return Nonereset_candidates = []if primary_exhausted and primary_reset:reset_candidates.append(primary_reset)if weekly_exhausted and weekly_reset:reset_candidates.append(weekly_reset)if not reset_candidates:if primary_reset:reset_candidates.append(primary_reset)if weekly_reset:reset_candidates.append(weekly_reset)resets_at = max(reset_candidates) if reset_candidates else int(time.time() + 18000)if primary_exhausted and weekly_exhausted:window = "combined"elif weekly_exhausted:window = "weekly"elif primary_exhausted:window = "primary"else:window = "limit"return {"window": window,"resets_at": resets_at,"quota_info": quota_info,"limit_reached": bool(limit_reached),}def check_codex_quota(access_token, account_id=None):"""通过 /backend-api/wham/usage 查询 Codex 额度状态,不消耗额度。返回 ("ok", quota_info) | ("exhausted", exhausted_info) | ("auth_error", None)quota_info = {"primary_pct": int, "primary_resets_at": int, "weekly_pct": int, "weekly_resets_at": int}"""import requests41 unmodified lines"weekly_resets_at": secondary.get("reset_at", 0),}exhausted_info = get_quota_exhausted_info(quota_info, limit_reached=bool(rate_limit.get("limit_reached")))if exhausted_info:return "exhausted", exhausted_inforeturn "ok", quota_info
9 unmodified lines1011121314151617181920212223157 unmodified lines1811821831841851865 unmodified lines1921931941951961971981992002019 unmodified linesimport requestsfrom autoteam.config import CPA_KEY, CPA_URLfrom autoteam.textio import write_textlogger = logging.getLogger(__name__)PROJECT_ROOT = Path(__file__).parent.parent.parentAUTH_DIR = PROJECT_ROOT / "auths"def _headers():return {"Authorization": f"Bearer {CPA_KEY}"}157 unmodified linesdef _write_auth_file(filepath, bundle):auth_data = {"type": "codex","id_token": bundle.get("id_token", ""),5 unmodified lines"last_refresh": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(bundle.get("last_refresh_ts", time.time()))),}write_text(filepath, json.dumps(auth_data, indent=2))try:filepath.chmod(0o600)except Exception:passreturn filepath9 unmodified lines101112131415161718192021157 unmodified lines1791801811821831841855 unmodified lines1911921931941951961979 unmodified linesimport requestsfrom autoteam.auth_storage import AUTH_DIR, ensure_auth_dir, ensure_auth_file_permissionsfrom autoteam.config import CPA_KEY, CPA_URLfrom autoteam.textio import write_textlogger = logging.getLogger(__name__)def _headers():return {"Authorization": f"Bearer {CPA_KEY}"}157 unmodified linesdef _write_auth_file(filepath, bundle):ensure_auth_dir()auth_data = {"type": "codex","id_token": bundle.get("id_token", ""),5 unmodified lines"last_refresh": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(bundle.get("last_refresh_ts", time.time()))),}write_text(filepath, json.dumps(auth_data, indent=2))ensure_auth_file_permissions(filepath)return filepath
39 unmodified lines404142434445461 unmodified line48495051525354555657581 unmodified line60616263646548 unmodified lines11411511611711811920 unmodified lines140141142143144145146136 unmodified lines28328428528628728828929029129229329429593 unmodified lines38939039139239339439555 unmodified lines4514524534544554564574585 unmodified lines46446546646746846940 unmodified lines51051151251351451551651751851952024 unmodified lines5455465475485495505515521 unmodified line5545555565575585595605615625635645655665676 unmodified lines5745755765775785795801 unmodified line582583584585586587588589590591124 unmodified lines71671771871972072172272372472572672772872973073173273373473510 unmodified lines74674774874975075175275375475575675775875976076113 unmodified lines7757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698706 unmodified lines87787887988088188288317 unmodified lines9019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429434 unmodified lines94894995095195295395419 unmodified lines974975976977978979980260 unmodified lines124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012812 unmodified lines128412851286128712881289129015 unmodified lines130613071308130913101311131211 unmodified lines13241325132613271328132960 unmodified lines139013911392139313941395139613971398139914001401140214031404140566 unmodified lines14721473147414751476147714 unmodified lines14921493149414951496149754 unmodified lines1552155315541555155615571 unmodified line155915601561156215631564114 unmodified lines167916801681168216831684168536 unmodified lines172217231724172517261727172887 unmodified lines18161817181818191820182121 unmodified lines1843184418451846184718486 unmodified lines18551856185718581859186039 unmodified linessave_accounts,update_account,)from autoteam.admin_state import get_admin_state_summary, get_chatgpt_account_idfrom autoteam.chatgpt_api import ChatGPTTeamAPIfrom autoteam.cloudmail import CloudMailClientfrom autoteam.codex_auth import (1 unmodified line_click_primary_auth_button,_is_google_redirect,check_codex_quota,login_codex_via_browser,refresh_access_token,save_auth_file,)from autoteam.cpa_sync import sync_from_cpa, sync_to_cpafrom autoteam.textio import read_text, write_textlogger = logging.getLogger(__name__)1 unmodified lineMAIL_TIMEOUT = int(os.environ.get("MAIL_TIMEOUT", "180"))def sync_account_states(chatgpt_api=None):"""根据 Team 实际成员列表同步本地账号状态"""account_id = get_chatgpt_account_id()48 unmodified lines# Team 中有我们域名但本地无记录的成员 → 自动添加if domain_suffix:for email in team_emails:if domain_suffix in email and email not in local_email_set:accounts.append({20 unmodified linestry:auth_data = json.loads(read_text(auth_file))email = auth_data.get("email", "").lower()if not email or email in local_email_set:continue# 判断是否在 Team 中in_team = email in team_emails136 unmodified linesstatus, info = check_codex_quota(access_token)if status == "ok" and isinstance(info, dict):quota_cache[acc["email"]] = info_print_status_table(accounts, quota_cache)def _check_and_refresh(acc):"""检查单个账号额度,401 时自动刷新 token。返回 (status_str, info)info: exhausted 时为 resets_at,ok 时为 quota_info dict"""email = acc["email"]auth_file = acc.get("auth_file")93 unmodified linesaccounts = load_accounts()all_active = [a for a in accounts if a["status"] == STATUS_ACTIVE]# 区分:有认证文件的 vs 无认证文件的active_with_auth = []55 unmodified lineselse:logger.info("[%s] 额度可用", email)elif status_str == "exhausted":resets_at = infologger.warning("[%s] 额度已用完", email)update_account(email,status=STATUS_EXHAUSTED,5 unmodified lines# token 失效,先看历史额度(重置时间已过的不算)lq = acc.get("last_quota")if lq:p_resets = lq.get("primary_resets_at", 0)if not (p_resets and time.time() >= p_resets):# 重置时间未过,历史数据有效40 unmodified lines# 重新检查额度status_str, info = _check_and_refresh(find_account(load_accounts(), email))if status_str == "exhausted":update_account(email,status=STATUS_EXHAUSTED,quota_exhausted_at=time.time(),quota_resets_at=info,)exhausted_list.append(acc)logger.warning("[%s] 额度已用完", email)24 unmodified linesreturn exhausted_listdef remove_from_team(chatgpt_api, email):"""将账号从 Team 中移除"""account_id = get_chatgpt_account_id()# 先获取成员列表找到 user_idpath = f"/backend-api/accounts/{account_id}/users"1 unmodified lineif result["status"] != 200:logger.error("[Team] 获取成员列表失败: %d", result["status"])return Falsetry:data = json.loads(result["body"])members = data.get("items", data.get("users", data.get("members", [])))except Exception:logger.error("[Team] 解析成员列表失败")return False# 找到对应邮箱的成员target_user_id = None6 unmodified linesif not target_user_id:logger.info("[Team] 未在成员列表中找到 %s(可能已移出)", email)# 可能已经不在 team 了return True# 删除成员delete_path = f"/backend-api/accounts/{account_id}/users/{target_user_id}"1 unmodified lineif result["status"] in (200, 204):logger.info("[Team] 已将 %s 移出 Team", email)return Trueelse:logger.error("[Team] 移除 %s 失败: %d %s", email, result["status"], result["body"][:200])return Falsedef invite_to_team(chatgpt_api, email, seat_type="default"):124 unmodified lineschatgpt.stop()def _register_direct_once(mail_client, email, password):"""执行一次直接注册,返回是否完成注册并进入 Team。"""from playwright.sync_api import sync_playwrightfrom autoteam.invite import screenshotlogger.info("[直接注册] %s", email)signup_url = "https://chatgpt.com/auth/login"with sync_playwright() as p:browser = p.chromium.launch(headless=False,args=["--disable-blink-features=AutomationControlled", "--no-sandbox"],)context = browser.new_context(viewport={"width": 1280, "height": 800},user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",10 unmodified lineslogger.info("[直接注册] 等待 Cloudflare... (%ds)", i * 5)time.sleep(5)screenshot(page, "direct_01_login_page.png")# OpenAI 首页有多种 A/B 测试变体,需要逐步找到邮箱输入框_email_selectors = ('input[name="email"], input[type="email"], input[id="email"], ''input[autocomplete="email"], input[autocomplete="username"], ''input[placeholder*="email" i], input[placeholder*="Email" i]')try:email_visible = page.locator(_email_selectors).first.is_visible(timeout=3000)if not email_visible:# 尝试按优先级点击各种按钮来展开/跳转到邮箱输入for sel, desc in [13 unmodified linesif btn.is_visible(timeout=1000):logger.info("[直接注册] 点击: %s", desc)btn.click()time.sleep(3)# 检查邮箱输入框是否出现了if page.locator(_email_selectors).first.is_visible(timeout=3000):breakexcept Exception:continueexcept Exception:passscreenshot(page, "direct_02_signup.png")logger.info("[直接注册] 输入邮箱: %s", email)try:for attempt in range(2):email_input = page.locator('input[name="email"], input[type="email"], input[id="email"], ''input[autocomplete="email"], input[autocomplete="username"], ''input[placeholder*="email" i], input[placeholder*="Email" i]').firstif not email_input.is_visible(timeout=5000):breakemail_input.fill(email)time.sleep(0.5)screenshot(page, f"direct_02b_email_filled_{attempt}.png")logger.info("[直接注册] 邮箱已填入,点击 Continue...")_click_primary_auth_button(page, email_input, ["Continue", "继续"])time.sleep(5)logger.info("[直接注册] 点击 Continue 后 URL: %s", page.url)screenshot(page, f"direct_02c_after_continue_{attempt}.png")if not _is_google_redirect(page):breakscreenshot(page, f"direct_03_google_redirect_attempt{attempt + 1}.png")logger.warning("[直接注册] 邮箱步骤误跳转到 Google 登录,返回重试... (attempt %d)", attempt + 1)page.go_back(wait_until="domcontentloaded", timeout=30000)time.sleep(2)except Exception:passscreenshot(page, "direct_03_after_email.png")logger.info("[直接注册] 当前 URL: %s", page.url)if _is_google_redirect(page):logger.warning("[直接注册] 邮箱步骤仍停留在 Google 登录页")browser.close()return False# 等待页面跳转完成(可能跳到 create-account/password)for _wait in range(10):if "password" in page.url or page.locator('input[type="password"]').count() > 0:breaktime.sleep(1)logger.info("[直接注册] 密码页检测 URL: %s", page.url)screenshot(page, "direct_03b_before_password.png")try:for attempt in range(2):pwd_input = page.locator('input[type="password"]').firstif not pwd_input.is_visible(timeout=10000):logger.info("[直接注册] 未检测到密码输入框,跳过")breaklogger.info("[直接注册] 设置密码")pwd_input.fill(password)time.sleep(0.5)_click_primary_auth_button(page, pwd_input, ["Continue", "继续", "Log in"])time.sleep(5)if not _is_google_redirect(page):breakscreenshot(page, f"direct_04_google_redirect_attempt{attempt + 1}.png")logger.warning("[直接注册] 密码步骤误跳转到 Google 登录,返回重试... (attempt %d)", attempt + 1)page.go_back(wait_until="domcontentloaded", timeout=30000)time.sleep(2)except Exception:passscreenshot(page, "direct_04_after_password.png")if _is_google_redirect(page):logger.warning("[直接注册] 密码步骤仍停留在 Google 登录页")browser.close()return Falsecode_input = Nonetry:code_input = page.locator('input[name="code"], input[placeholder*="验证码"], input[placeholder*="code" i]').firstif not code_input.is_visible(timeout=5000):code_input = Noneexcept Exception:6 unmodified linesverification_code = Nonestart_t = time.time()while time.time() - start_t < MAIL_TIMEOUT:emails = mail_client.search_emails_by_recipient(email, size=10)for em in emails:text = em.get("text", "") or em.get("content", "")match = re.search(r"\b(\d{6})\b", text)17 unmodified linesbrowser.close()return Falsescreenshot(page, "direct_05_after_code.png")logger.info("[直接注册] 当前 URL: %s", page.url)name_input = page.locator('input[name="name"]').firsttry:if name_input.is_visible(timeout=5000):name_input.fill("User")time.sleep(0.5)spinbuttons = page.locator('[role="spinbutton"]').all()if len(spinbuttons) >= 3:try:page.locator("text=生日日期").click()time.sleep(0.5)except Exception:passfor sb, val in zip(spinbuttons[:3], ["1995", "06", "15"]):sb.click(force=True)time.sleep(0.2)page.keyboard.type(val, delay=80)time.sleep(0.3)logger.info("[直接注册] 填入生日: 1995/06/15")else:age_input = page.locator('input[name="age"]').firsttry:if age_input.is_visible(timeout=3000):age_input.fill("25")logger.info("[直接注册] 填入年龄: 25")except Exception:pass_click_primary_auth_button(page, name_input, ["完成帐户创建", "Continue", "继续"])time.sleep(8)except Exception:passscreenshot(page, "direct_06_after_profile.png")logger.info("[直接注册] 当前 URL: %s", page.url)try:4 unmodified linesexcept Exception:passscreenshot(page, "direct_07_final.png")current_url = page.urlsuccess = "chatgpt.com" in current_url and "auth" not in current_url and not _is_google_redirect(page)19 unmodified linessuccess = Falsefor attempt in range(3):logger.info("[直接注册] 开始第 %d/3 次注册尝试: %s", attempt + 1, email)success = _register_direct_once(mail_client, email, password)if success:break260 unmodified linestry:# 移出所有 exhausted 账号(包括之前已标记的)all_accounts = load_accounts()all_exhausted = [a for a in all_accounts if a["status"] == STATUS_EXHAUSTED]if all_exhausted:logger.info("[3/5] 移出 %d 个额度用完的账号...", len(all_exhausted))ensure_chatgpt()for acc in all_exhausted:email = acc["email"]if not chatgpt.browser:chatgpt.start()if remove_from_team(chatgpt, email):update_account(email, status=STATUS_STANDBY)logger.info("[3/5] %s → standby", email)else:logger.info("[3/5] 无需移出账号")removed_count = len([afor a in all_exhaustedif find_account(load_accounts(), a["email"])and find_account(load_accounts(), a["email"])["status"] == STATUS_STANDBY])if not chatgpt or not chatgpt.browser:ensure_chatgpt()api_count = get_team_member_count(chatgpt)logger.info("[4/5] API 返回成员数: %d(本轮移出: %d)", api_count, removed_count)if api_count <= 0:# API 返回异常,用本地 active 账号数兜底local_active = sum(1 for a in load_accounts() if a["status"] == STATUS_ACTIVE)logger.warning("[4/5] API 成员数异常 (%d),使用本地 active 数: %d", api_count, local_active)current_count = local_activeelse:# API 有缓存延迟,移出后可能返回旧数据,手动修正current_count = max(0, api_count - removed_count)vacancies = TARGET - current_countif vacancies <= 0:2 unmodified lineslogger.info("[4/5] Team 超员 (%d/%d),清理 %d 个多余成员...", current_count, TARGET, excess)# 只移除本地管理的账号,优先移除额度最低的all_accs = load_accounts()local_active = [a for a in all_accs if a["status"] == STATUS_ACTIVE]# 按额度排序,额度低的优先移除local_active.sort(key=lambda a: 100 - (a.get("last_quota") or {}).get("primary_pct", 0))removed = 015 unmodified lines# 优先复用旧账号(先验证额度是否真的恢复了)filled = 0standby_list = get_standby_accounts()skipped = []for acc in standby_list:11 unmodified linesif access_token:status_str, info = check_codex_quota(access_token)if status_str == "exhausted":logger.info("[4/5] 跳过 %s(额度未恢复)", email)skipped.append(acc)continue60 unmodified linesremaining = TARGET - current_countif remaining <= 0:logger.info("[4/5] 已用旧账号填满空缺")return# 必须创建新号logger.info("[5/5] 创建 %d 个新账号...", remaining)for i in range(remaining):logger.info("[5/5] 创建第 %d/%d 个...", i + 1, remaining)if not chatgpt or not chatgpt.browser:ensure_chatgpt()if create_new_account(chatgpt, ensure_mail()):current_count += 1if not chatgpt or not chatgpt.browser:ensure_chatgpt()66 unmodified linesflow.stop()def cmd_admin_login(email=None):"""交互式完成管理员登录并保存到 state.json。"""email = (email or "").strip()14 unmodified lineswhile True:if step == "completed":info = chatgpt.complete_admin_login()logger.info("[管理员登录] 登录完成: %s", info.get("email") or email)if info.get("account_id"):logger.info("[管理员登录] Workspace ID: %s", info["account_id"])54 unmodified lineschatgpt.stop()def cmd_main_codex_sync():"""交互式同步主号 Codex 认证到 CPA。"""state = get_admin_state_summary()1 unmodified linelogger.error("[主号 Codex] 缺少管理员登录态,请先执行 admin-login")return Noneflow = MainCodexSyncFlow()try:logger.info("[主号 Codex] 开始同步: %s", state.get("email"))114 unmodified lines"""清理多余的 Team 成员,只移除本地 accounts.json 中管理的账号"""account_id = get_chatgpt_account_id()accounts = load_accounts()local_emails = {a["email"].lower() for a in accounts}if not local_emails:logger.info("[清理] 本地无管理的账号,无需清理")36 unmodified lines# 确定要移除的数量if max_seats is None:max_seats = len(external_members) + 2 # 保留外部成员 + 2 个本地席位to_remove_count = total - max_seatsif to_remove_count <= 0:logger.info("[清理] 成员数 %d 未超过上限 %d,无需清理", total, max_seats)87 unmodified linessub.add_parser("manual-add", help="手动 OAuth 添加账号(打开链接登录后粘贴回调 URL)")admin_login_p = sub.add_parser("admin-login", help="交互式完成管理员主号登录")admin_login_p.add_argument("--email", help="管理员邮箱;不传则运行时交互输入")sub.add_parser("main-codex-sync", help="交互式同步主号 Codex 到 CPA")fill_p = sub.add_parser("fill", help="补满 Team 成员到指定数量")21 unmodified linescheck_and_setup(interactive=True)if args.command == "status":cmd_status()elif args.command == "check":6 unmodified linescmd_manual_add()elif args.command == "admin-login":cmd_admin_login(args.email)elif args.command == "main-codex-sync":cmd_main_codex_sync()elif args.command == "fill":39 unmodified lines404142434445461 unmodified line484950515253545556575859606162631 unmodified line656667686970717273747576777848 unmodified lines12712812913013113213313420 unmodified lines155156157158159160161136 unmodified lines29829930030130230330430530630730830931031131231331493 unmodified lines40840941041141241341455 unmodified lines4704714724734744754764774784794804814824834844854864874884894904915 unmodified lines49749849950050150250350450550650750850951051151251351440 unmodified lines55555655755855956056156256356456556656756824 unmodified lines5935945955965975985996006016026036041 unmodified line6066076086096106116126136146156166176186196 unmodified lines6266276286296306316321 unmodified line634635636637638639640641642643124 unmodified lines7687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111210 unmodified lines1123112411251126112711281129113011311132113313 unmodified lines1147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013116 unmodified lines131813191320132113221323132417 unmodified lines1342134313441345134613471348134913501351135213531354135513564 unmodified lines136113621363136413651366136719 unmodified lines1387138813891390139113921393260 unmodified lines165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117122 unmodified lines17151716171717181719172017211722172315 unmodified lines173917401741174217431744174511 unmodified lines17571758175917601761176217631764176560 unmodified lines18261827182818291830183118321833183418351836183718381839184066 unmodified lines190719081909191019111912191319141915191619171918191919201921192214 unmodified lines1937193819391940194119421943194454 unmodified lines19992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420351 unmodified line203720382039204020412042204320442045204620472048114 unmodified lines216321642165216621672168216936 unmodified lines2206220722082209221022112212221387 unmodified lines2301230223032304230523062307230821 unmodified lines23302331233223332334233523362337233823392340234123426 unmodified lines2349235023512352235323542355235639 unmodified linessave_accounts,update_account,)from autoteam.admin_state import get_admin_email, get_admin_state_summary, get_chatgpt_account_idfrom autoteam.chatgpt_api import ChatGPTTeamAPIfrom autoteam.cloudmail import CloudMailClientfrom autoteam.codex_auth import (1 unmodified line_click_primary_auth_button,_is_google_redirect,check_codex_quota,get_quota_exhausted_info,get_saved_main_auth_file,login_codex_via_browser,quota_result_quota_info,quota_result_resets_at,refresh_access_token,refresh_main_auth_file,save_auth_file,)from autoteam.cpa_sync import sync_from_cpa, sync_main_codex_to_cpa, sync_to_cpafrom autoteam.textio import read_text, write_textlogger = logging.getLogger(__name__)1 unmodified lineMAIL_TIMEOUT = int(os.environ.get("MAIL_TIMEOUT", "180"))def _normalized_email(value: str | None) -> str:return (value or "").strip().lower()def _is_main_account_email(email: str | None) -> bool:return bool(_normalized_email(email)) and _normalized_email(email) == _normalized_email(get_admin_email())def sync_account_states(chatgpt_api=None):"""根据 Team 实际成员列表同步本地账号状态"""account_id = get_chatgpt_account_id()48 unmodified lines# Team 中有我们域名但本地无记录的成员 → 自动添加if domain_suffix:for email in team_emails:if _is_main_account_email(email):continueif domain_suffix in email and email not in local_email_set:accounts.append({20 unmodified linestry:auth_data = json.loads(read_text(auth_file))email = auth_data.get("email", "").lower()if not email or email in local_email_set or _is_main_account_email(email):continue# 判断是否在 Team 中in_team = email in team_emails136 unmodified linesstatus, info = check_codex_quota(access_token)if status == "ok" and isinstance(info, dict):quota_cache[acc["email"]] = infoelif status == "exhausted":quota_info = quota_result_quota_info(info)if quota_info:quota_cache[acc["email"]] = quota_info_print_status_table(accounts, quota_cache)def _check_and_refresh(acc):"""检查单个账号额度,401 时自动刷新 token。返回 (status_str, info)info: exhausted 时为 exhausted_info,ok 时为 quota_info dict"""email = acc["email"]auth_file = acc.get("auth_file")93 unmodified linesaccounts = load_accounts()all_active = [a for a in accounts if a["status"] == STATUS_ACTIVE and not _is_main_account_email(a.get("email"))]# 区分:有认证文件的 vs 无认证文件的active_with_auth = []55 unmodified lineselse:logger.info("[%s] 额度可用", email)elif status_str == "exhausted":quota_info = quota_result_quota_info(info) or {}resets_at = quota_result_resets_at(info) or int(time.time() + 18000)if quota_info:update_account(email, last_quota=quota_info)p_remain = max(0, 100 - quota_info.get("primary_pct", 0))w_remain = max(0, 100 - quota_info.get("weekly_pct", 0))window = info.get("window") if isinstance(info, dict) else ""logger.warning("[%s] %s额度已用完 - 5h剩余: %d%% | 周剩余: %d%%",email,"周" if window == "weekly" else "5h和周" if window == "combined" else "5h",p_remain,w_remain,)else:logger.warning("[%s] 额度已用完", email)update_account(email,status=STATUS_EXHAUSTED,5 unmodified lines# token 失效,先看历史额度(重置时间已过的不算)lq = acc.get("last_quota")if lq:exhausted_info = get_quota_exhausted_info(lq)if exhausted_info:resets_at = quota_result_resets_at(exhausted_info) or int(time.time() + 18000)logger.warning("[%s] token 失效,但历史额度显示已用完,直接标记 exhausted", email)update_account(email,status=STATUS_EXHAUSTED,quota_exhausted_at=time.time(),quota_resets_at=resets_at,)exhausted_list.append(acc)continuep_resets = lq.get("primary_resets_at", 0)if not (p_resets and time.time() >= p_resets):# 重置时间未过,历史数据有效40 unmodified lines# 重新检查额度status_str, info = _check_and_refresh(find_account(load_accounts(), email))if status_str == "exhausted":quota_info = quota_result_quota_info(info)if quota_info:update_account(email, last_quota=quota_info)update_account(email,status=STATUS_EXHAUSTED,quota_exhausted_at=time.time(),quota_resets_at=quota_result_resets_at(info) or int(time.time() + 18000),)exhausted_list.append(acc)logger.warning("[%s] 额度已用完", email)24 unmodified linesreturn exhausted_listdef remove_from_team(chatgpt_api, email, *, return_status=False):"""将账号从 Team 中移除"""if _is_main_account_email(email):logger.warning("[Team] 跳过移除主号: %s", email)return "failed" if return_status else Falseaccount_id = get_chatgpt_account_id()# 先获取成员列表找到 user_idpath = f"/backend-api/accounts/{account_id}/users"1 unmodified lineif result["status"] != 200:logger.error("[Team] 获取成员列表失败: %d", result["status"])return "failed" if return_status else Falsetry:data = json.loads(result["body"])members = data.get("items", data.get("users", data.get("members", [])))except Exception:logger.error("[Team] 解析成员列表失败")return "failed" if return_status else False# 找到对应邮箱的成员target_user_id = None6 unmodified linesif not target_user_id:logger.info("[Team] 未在成员列表中找到 %s(可能已移出)", email)# 可能已经不在 team 了return "already_absent" if return_status else True# 删除成员delete_path = f"/backend-api/accounts/{account_id}/users/{target_user_id}"1 unmodified lineif result["status"] in (200, 204):logger.info("[Team] 已将 %s 移出 Team", email)return "removed" if return_status else Trueelse:logger.error("[Team] 移除 %s 失败: %d %s", email, result["status"], result["body"][:200])return "failed" if return_status else Falsedef invite_to_team(chatgpt_api, email, seat_type="default"):124 unmodified lineschatgpt.stop()_DIRECT_EMAIL_SELECTORS = ('input[name="email"], input[type="email"], input[id="email"], ''input[autocomplete="email"], input[autocomplete="username"], ''input[placeholder*="email" i], input[placeholder*="Email" i]')_DIRECT_PASSWORD_SELECTORS = 'input[name="password"], input[type="password"]'_DIRECT_CODE_SELECTORS = 'input[name="code"], input[placeholder*="验证码"], input[placeholder*="code" i]'def _safe_invite_screenshot(page, name):from autoteam.invite import screenshottry:screenshot(page, name)except Exception as exc:logger.debug("[直接注册] 截图失败 %s: %s", name, exc)def _page_excerpt(page, limit=240):try:return page.locator("body").inner_text(timeout=1500)[:limit].replace("\n", " ")except Exception:return ""def _first_visible_editable_locator(page, selectors, timeout=800):try:locator = page.locator(selectors).firstif not locator.is_visible(timeout=timeout):return Noneif locator.is_editable(timeout=timeout):return locatorexcept Exception:return Nonereturn Nonedef _collect_date_spinbutton_meta(page):try:return page.evaluate("""() => {const byIdsText = (rawIds) => {return (rawIds || '').split(/\\s+/).filter(Boolean).map(id => {const el = document.getElementById(id);return el ? (el.textContent || '').trim() : '';}).filter(Boolean).join(' ');};return Array.from(document.querySelectorAll('[role="spinbutton"]')).map((el, index) => ({index,text: (el.textContent || '').trim(),ariaLabel: el.getAttribute('aria-label') || '',ariaValueText: el.getAttribute('aria-valuetext') || '',ariaValueMin: el.getAttribute('aria-valuemin') || '',ariaValueMax: el.getAttribute('aria-valuemax') || '',placeholder: el.getAttribute('placeholder') || '',dataType: el.getAttribute('data-type') || el.dataset?.type || '',labelledText: byIdsText(el.getAttribute('aria-labelledby')),describedText: byIdsText(el.getAttribute('aria-describedby')),}));}""")except Exception:return []def _infer_date_spinbutton_kind(meta):text_parts = [meta.get("text", ""),meta.get("ariaLabel", ""),meta.get("ariaValueText", ""),meta.get("placeholder", ""),meta.get("dataType", ""),meta.get("labelledText", ""),meta.get("describedText", ""),]lowered = " ".join(part for part in text_parts if part).lower()def _to_int(value):try:return int(str(value).strip())except Exception:return Nonemax_val = _to_int(meta.get("ariaValueMax"))if any(token in lowered for token in ("year", "yyyy", "yy", "年")):return "year"if any(token in lowered for token in ("month", "mm", "月")):return "month"if any(token in lowered for token in ("day", "dd", "日")):return "day"if max_val is not None:if max_val > 31:return "year"if max_val == 12:return "month"if max_val <= 31:return "day"return Nonedef _fill_about_you_birthday_by_meta(page):metas = _collect_date_spinbutton_meta(page)if len(metas) < 3:return Falsedesired = {"year": "1995", "month": "06", "day": "15"}kind_to_meta = {}for meta in metas:kind = _infer_date_spinbutton_kind(meta)if kind and kind not in kind_to_meta:kind_to_meta[kind] = metaif not all(kind in kind_to_meta for kind in desired):logger.info("[直接注册] 无法可靠识别生日字段顺序,降级为位置猜测")return Falsetry:for kind in ("year", "month", "day"):meta = kind_to_meta[kind]sb = page.locator('[role="spinbutton"]').nth(meta["index"])sb.click(force=True)time.sleep(0.2)try:page.keyboard.press("ControlOrMeta+A")time.sleep(0.1)except Exception:passpage.keyboard.type(desired[kind], delay=80)time.sleep(0.3)logger.info("[直接注册] 已按字段识别填入生日: year=%s month=%s day=%s | order=%s",desired["year"],desired["month"],desired["day"],{kind: kind_to_meta[kind]["index"] for kind in ("year", "month", "day")},)return Trueexcept Exception as exc:logger.warning("[直接注册] 按字段填写生日失败,降级为位置猜测: %s", exc)return Falsedef _detect_direct_register_step(page):url = (page.url or "").lower()if _is_google_redirect(page):return "google"if "email-verification" in url:return "code"if "about-you" in url:return "profile"if "create-account/password" in url or url.endswith("/password"):return "password"if "chatgpt.com" in url and "auth" not in url:return "completed"try:if _first_visible_editable_locator(page, _DIRECT_PASSWORD_SELECTORS, timeout=300):return "password"except Exception:passtry:if _first_visible_editable_locator(page, _DIRECT_CODE_SELECTORS, timeout=300):return "code"except Exception:passtry:if page.locator('input[name="name"], [role="spinbutton"]').first.is_visible(timeout=300):return "profile"except Exception:passtry:if _first_visible_editable_locator(page, _DIRECT_EMAIL_SELECTORS, timeout=300):return "email"except Exception:passif "log-in-or-create-account" in url or url.endswith("/auth/login"):return "email"if "create-account" in url or "password" in url:return "password"return "unknown"def _wait_for_direct_register_step(page, allowed_steps, timeout=15):deadline = time.time() + timeoutwhile time.time() < deadline:step = _detect_direct_register_step(page)if step in allowed_steps:return steptime.sleep(0.5)return _detect_direct_register_step(page)def _wait_for_direct_step_change(page, current_step, timeout=15):deadline = time.time() + timeoutwhile time.time() < deadline:step = _detect_direct_register_step(page)if step != current_step:return steptime.sleep(0.5)return _detect_direct_register_step(page)def _complete_direct_about_you(page):"""尽量完成 about-you 页面,兼容不同生日字段顺序。"""if "about-you" not in (page.url or "").lower():return Truebirthday_orders = [("1995", "06", "15"),("06", "15", "1995"),("15", "06", "1995"),]for attempt, values in enumerate(birthday_orders, 1):if "about-you" not in (page.url or "").lower():return Truetry:name_input = page.locator('input[name="name"]').firstif name_input.is_visible(timeout=2000):try:if name_input.is_editable(timeout=500):name_input.fill("User")time.sleep(0.3)except Exception:passexcept Exception:name_input = Nonespinbuttons = []try:spinbuttons = page.locator('[role="spinbutton"]').all()except Exception:spinbuttons = []if len(spinbuttons) >= 3:filled = _fill_about_you_birthday_by_meta(page)if not filled:for label_sel in ("text=生日日期", "text=Date of birth"):try:page.locator(label_sel).first.click(timeout=1000)time.sleep(0.3)breakexcept Exception:continuetry:for sb, val in zip(spinbuttons[:3], values):sb.click(force=True)time.sleep(0.2)try:page.keyboard.press("ControlOrMeta+A")time.sleep(0.1)except Exception:passpage.keyboard.type(val, delay=80)time.sleep(0.3)logger.info("[直接注册] 尝试按位置填入生日(第 %d 次): %s/%s/%s", attempt, *values)except Exception as exc:logger.warning("[直接注册] 生日字段填写失败(第 %d 次): %s", attempt, exc)else:try:age_input = page.locator('input[name="age"], input[placeholder*="年龄"], input[placeholder*="Age"]').firstif age_input.is_visible(timeout=2000) and age_input.is_editable(timeout=500):age_input.fill("25")logger.info("[直接注册] 填入年龄: 25")except Exception:passsubmitted = Falsefor btn_selector in ('button:has-text("完成帐户创建")','button:has-text("Create account")','button:has-text("Continue")','button:has-text("继续")','button[type="submit"]',):try:btn = page.locator(btn_selector).firstif btn.is_visible(timeout=1000):btn.click()submitted = Truebreakexcept Exception:continueif not submitted:try:page.keyboard.press("Enter")except Exception:passnext_step = _wait_for_direct_register_step(page,{"profile", "completed", "code", "password", "email", "google"},timeout=12,)logger.info("[直接注册] 提交资料后状态: %s | URL: %s", next_step, page.url)if next_step != "profile":return Truelogger.warning("[直接注册] about-you 页面仍未完成 | URL: %s | body=%s", page.url, _page_excerpt(page))return Falsedef _register_direct_once(mail_client, email, password, cloudmail_account_id=None):"""执行一次直接注册,返回是否完成注册并进入 Team。"""from playwright.sync_api import sync_playwrightlogger.info("[直接注册] %s", email)signup_url = "https://chatgpt.com/auth/login"with sync_playwright() as p:launch_kwargs = {"headless": False,"args": ["--disable-blink-features=AutomationControlled", "--no-sandbox"],}if sys.platform.startswith("win"):launch_kwargs["slow_mo"] = 100browser = p.chromium.launch(**launch_kwargs)context = browser.new_context(viewport={"width": 1280, "height": 800},user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",10 unmodified lineslogger.info("[直接注册] 等待 Cloudflare... (%ds)", i * 5)time.sleep(5)_safe_invite_screenshot(page, "direct_01_login_page.png")# OpenAI 首页有多种 A/B 测试变体,需要逐步找到邮箱输入框try:email_visible = page.locator(_DIRECT_EMAIL_SELECTORS).first.is_visible(timeout=3000)if not email_visible:# 尝试按优先级点击各种按钮来展开/跳转到邮箱输入for sel, desc in [13 unmodified linesif btn.is_visible(timeout=1000):logger.info("[直接注册] 点击: %s", desc)btn.click()time.sleep(2)# 检查邮箱输入框是否出现了step = _wait_for_direct_register_step(page,{"email", "password", "code", "profile", "completed", "google"},timeout=10,)if step != "unknown":breakexcept Exception:continueexcept Exception:pass_safe_invite_screenshot(page, "direct_02_signup.png")logger.info("[直接注册] 输入邮箱: %s", email)email_step = _wait_for_direct_register_step(page,{"email", "password", "code", "profile", "completed", "google"},timeout=15,)logger.info("[直接注册] 邮箱步骤初始状态: %s | URL: %s", email_step, page.url)if email_step == "google":logger.warning("[直接注册] 邮箱步骤误跳转到 Google 登录页")browser.close()return Falseif email_step == "unknown":logger.warning("[直接注册] 未识别到邮箱步骤 | URL: %s | body=%s", page.url, _page_excerpt(page))browser.close()return Falsetry:for attempt in range(3):step = _detect_direct_register_step(page)if step != "email":breakemail_input = _first_visible_editable_locator(page, _DIRECT_EMAIL_SELECTORS, timeout=1500)if not email_input:logger.info("[直接注册] 邮箱输入框不可编辑,等待页面继续跳转...")next_step = _wait_for_direct_step_change(page, "email", timeout=10)if next_step != "email":breaklogger.warning("[直接注册] 邮箱输入框仍不可编辑,继续重试 | URL: %s", page.url)continueemail_input.fill(email)time.sleep(0.5)logger.info("[直接注册] 邮箱已填入,点击 Continue... (attempt %d)", attempt + 1)_safe_invite_screenshot(page, f"direct_02b_email_filled_{attempt}.png")_click_primary_auth_button(page, email_input, ["Continue", "继续"])next_step = _wait_for_direct_step_change(page, "email", timeout=15)logger.info("[直接注册] 点击 Continue 后状态: %s | URL: %s", next_step, page.url)_safe_invite_screenshot(page, f"direct_02c_after_continue_{attempt}.png")if next_step == "google":_safe_invite_screenshot(page, f"direct_03_google_redirect_attempt{attempt + 1}.png")logger.warning("[直接注册] 邮箱步骤误跳转到 Google 登录,返回重试... (attempt %d)", attempt + 1)page.go_back(wait_until="domcontentloaded", timeout=30000)time.sleep(2)continueif next_step != "email":breakemail_input = _first_visible_editable_locator(page, _DIRECT_EMAIL_SELECTORS, timeout=600)if not email_input:logger.info("[直接注册] 邮箱框已只读/跳转中,额外等待页面推进...")next_step = _wait_for_direct_step_change(page, "email", timeout=10)logger.info("[直接注册] 额外等待后状态: %s | URL: %s", next_step, page.url)if next_step != "email":breaklogger.warning("[直接注册] 点击 Continue 后仍停留在邮箱步骤,准备重试... | URL: %s | body=%s",page.url,_page_excerpt(page),)except Exception as exc:logger.warning("[直接注册] 邮箱步骤异常: %s | URL: %s", exc, page.url)_safe_invite_screenshot(page, "direct_03_after_email.png")current_step = _detect_direct_register_step(page)logger.info("[直接注册] 邮箱步骤结束状态: %s | URL: %s", current_step, page.url)if current_step == "google":logger.warning("[直接注册] 邮箱步骤仍停留在 Google 登录页")browser.close()return Falseif current_step == "email":logger.warning("[直接注册] 邮箱步骤未推进 | URL: %s | body=%s", page.url, _page_excerpt(page))browser.close()return False# 等待页面跳转完成(可能跳到 create-account/password)password_step = _wait_for_direct_register_step(page,{"password", "code", "profile", "completed", "google", "email"},timeout=15,)logger.info("[直接注册] 密码页检测状态: %s | URL: %s", password_step, page.url)_safe_invite_screenshot(page, "direct_03b_before_password.png")try:for attempt in range(2):if _detect_direct_register_step(page) != "password":logger.info("[直接注册] 未检测到密码输入框,跳过")breakpwd_input = _first_visible_editable_locator(page, _DIRECT_PASSWORD_SELECTORS, timeout=1500)if not pwd_input:logger.info("[直接注册] 密码输入框不可编辑,等待页面继续跳转...")next_step = _wait_for_direct_step_change(page, "password", timeout=10)if next_step != "password":breaklogger.warning("[直接注册] 密码输入框仍不可���辑,继续重试 | URL: %s", page.url)continuelogger.info("[直接注册] 设置密码")pwd_input.fill(password)time.sleep(0.5)_click_primary_auth_button(page, pwd_input, ["Continue", "继续", "Log in"])next_step = _wait_for_direct_step_change(page, "password", timeout=15)logger.info("[直接注册] 提交密码后状态: %s | URL: %s", next_step, page.url)if next_step == "google":_safe_invite_screenshot(page, f"direct_04_google_redirect_attempt{attempt + 1}.png")logger.warning("[直接注册] 密码步骤误跳转到 Google 登录,返回重试... (attempt %d)", attempt + 1)page.go_back(wait_until="domcontentloaded", timeout=30000)time.sleep(2)continueif next_step != "password":breakpwd_input = _first_visible_editable_locator(page, _DIRECT_PASSWORD_SELECTORS, timeout=600)if not pwd_input:logger.info("[直接注册] 密码框已只读/跳转中,额外等待页面推进...")next_step = _wait_for_direct_step_change(page, "password", timeout=10)logger.info("[直接注册] 额外等待后状态: %s | URL: %s", next_step, page.url)if next_step != "password":breakexcept Exception as exc:logger.warning("[直接注册] 密码步骤异常: %s | URL: %s", exc, page.url)_safe_invite_screenshot(page, "direct_04_after_password.png")current_step = _detect_direct_register_step(page)if current_step == "google":logger.warning("[直接注册] 密码步骤仍停留在 Google 登录页")browser.close()return Falseif current_step == "email":logger.warning("[直接注册] 提交密码前流程回退到邮箱页 | URL: %s | body=%s", page.url, _page_excerpt(page))browser.close()return Falsecode_input = Nonetry:code_input = page.locator(_DIRECT_CODE_SELECTORS).firstif not code_input.is_visible(timeout=5000):code_input = Noneexcept Exception:6 unmodified linesverification_code = Nonestart_t = time.time()while time.time() - start_t < MAIL_TIMEOUT:emails = mail_client.search_emails_by_recipient(email, size=10, account_id=cloudmail_account_id)for em in emails:text = em.get("text", "") or em.get("content", "")match = re.search(r"\b(\d{6})\b", text)17 unmodified linesbrowser.close()return False_safe_invite_screenshot(page, "direct_05_after_code.png")logger.info("[直接注册] 当前 URL: %s", page.url)try:_complete_direct_about_you(page)except Exception as exc:logger.warning("[直接注册] about-you 步骤异常: %s | URL: %s", exc, page.url)_safe_invite_screenshot(page, "direct_06_after_profile.png")logger.info("[直接注册] 当前 URL: %s", page.url)try:4 unmodified linesexcept Exception:pass_safe_invite_screenshot(page, "direct_07_final.png")current_url = page.urlsuccess = "chatgpt.com" in current_url and "auth" not in current_url and not _is_google_redirect(page)19 unmodified linessuccess = Falsefor attempt in range(3):logger.info("[直接注册] 开始第 %d/3 次注册尝试: %s", attempt + 1, email)success = _register_direct_once(mail_client, email, password, cloudmail_account_id=account_id)if success:break260 unmodified linestry:# 移出所有 exhausted 账号(包括之前已标记的)all_accounts = load_accounts()all_exhausted = [a for a in all_accounts if a["status"] == STATUS_EXHAUSTED and not _is_main_account_email(a.get("email"))]initial_api_count = -1removed_now = 0already_absent_count = 0if all_exhausted:logger.info("[3/5] 移出 %d 个额度用完的账号...", len(all_exhausted))ensure_chatgpt()initial_api_count = get_team_member_count(chatgpt)for acc in all_exhausted:email = acc["email"]if not chatgpt.browser:chatgpt.start()remove_status = remove_from_team(chatgpt, email, return_status=True)if remove_status in ("removed", "already_absent"):update_account(email, status=STATUS_STANDBY)if remove_status == "removed":removed_now += 1logger.info("[3/5] %s → standby(已从 Team 移出)", email)else:already_absent_count += 1logger.info("[3/5] %s → standby(远端已不存在)", email)else:logger.info("[3/5] 无需移出账号")if not chatgpt or not chatgpt.browser:ensure_chatgpt()api_count = get_team_member_count(chatgpt)logger.info("[4/5] API 返回成员数: %d(实际移出: %d,远端已缺席: %d)",api_count,removed_now,already_absent_count,)if api_count <= 0:# API 返回异常,用本地 active 账号数兜底local_active = sum(1 for a in load_accounts() if a["status"] == STATUS_ACTIVE)logger.warning("[4/5] API 成员数异常 (%d),使用本地 active 数: %d", api_count, local_active)current_count = local_activeelse:# 保守估算当前成员数:# - api_count 是移除后的最新观察值# - initial_api_count - removed_now 是基于移除前人数的理论下界# 若远端成员本就不存在(already_absent),不能再从 api_count 里额外扣减,否则会少算人数。estimates = [api_count]if initial_api_count > 0 and removed_now > 0:estimates.append(max(0, initial_api_count - removed_now))current_count = min(estimates)if len(estimates) > 1 and current_count != api_count:logger.info("[4/5] 成员数保���估算: %d(初始=%d,移出=%d)", current_count, initial_api_count, removed_now)vacancies = TARGET - current_countif vacancies <= 0:2 unmodified lineslogger.info("[4/5] Team 超员 (%d/%d),清理 %d 个多余成员...", current_count, TARGET, excess)# 只移除本地管理的账号,优先移除额度最低的all_accs = load_accounts()local_active = [a for a in all_accs if a["status"] == STATUS_ACTIVE and not _is_main_account_email(a.get("email"))]# 按额度排序,额度低的优先移除local_active.sort(key=lambda a: 100 - (a.get("last_quota") or {}).get("primary_pct", 0))removed = 015 unmodified lines# 优先复用旧账号(先验证额度是否真的恢复了)filled = 0standby_list = [a for a in get_standby_accounts() if not _is_main_account_email(a.get("email"))]skipped = []for acc in standby_list:11 unmodified linesif access_token:status_str, info = check_codex_quota(access_token)if status_str == "exhausted":quota_info = quota_result_quota_info(info)if quota_info:update_account(email, last_quota=quota_info)logger.info("[4/5] 跳过 %s(额度未恢复)", email)skipped.append(acc)continue60 unmodified linesremaining = TARGET - current_countif remaining <= 0:logger.info("[4/5] 已用旧账号填满空缺")else:# 必须创建新号logger.info("[5/5] 创建 %d 个新账号...", remaining)for i in range(remaining):logger.info("[5/5] 创建第 %d/%d 个...", i + 1, remaining)if not chatgpt or not chatgpt.browser:ensure_chatgpt()if create_new_account(chatgpt, ensure_mail()):current_count += 1if not chatgpt or not chatgpt.browser:ensure_chatgpt()66 unmodified linesflow.stop()def _refresh_main_auth_after_admin_login():try:info = refresh_main_auth_file()logger.info("[管理员登录] 已保存主号认证文件: %s", info.get("auth_file"))return infoexcept Exception as exc:logger.warning("[管理员登录] 主号认证文件生成失败: %s", exc)return Nonedef cmd_admin_login(email=None):"""交互式完成管理员登录并保存到 state.json。"""email = (email or "").strip()14 unmodified lineswhile True:if step == "completed":info = chatgpt.complete_admin_login()chatgpt.stop()_refresh_main_auth_after_admin_login()logger.info("[管理员登录] 登录完成: %s", info.get("email") or email)if info.get("account_id"):logger.info("[管理员登录] Workspace ID: %s", info["account_id"])54 unmodified lineschatgpt.stop()def cmd_admin_session(email=None):"""手动导入管理员 session_token 并保存到 state.json。"""email = (email or "").strip()if not email:email = input("管理员邮箱: ").strip()if not email:logger.error("[管理员登录] 邮箱不能为空")return Nonesession_token = getpass.getpass("session_token(留空取消): ").strip()if not session_token:logger.warning("[管理员登录] 已取消")return Nonechatgpt = ChatGPTTeamAPI()try:logger.info("[管理员登录] 开始导入 session_token: %s", email)info = chatgpt.import_admin_session(email, session_token)chatgpt.stop()_refresh_main_auth_after_admin_login()logger.info("[管理员登录] session_token 导入完成: %s", info.get("email") or email)if info.get("account_id"):logger.info("[管理员登录] Workspace ID: %s", info["account_id"])if info.get("workspace_name"):logger.info("[管理员登录] Workspace 名称: %s", info["workspace_name"])return infofinally:chatgpt.stop()def cmd_main_codex_sync():"""交互式同步主号 Codex 认证到 CPA。"""state = get_admin_state_summary()1 unmodified linelogger.error("[主号 Codex] 缺少管理员登录态,请先执行 admin-login")return Nonesaved_auth_file = get_saved_main_auth_file()if saved_auth_file:sync_main_codex_to_cpa(saved_auth_file)logger.info("[主号 Codex] 已直接同步现有认证文件: %s", saved_auth_file)return {"auth_file": saved_auth_file}flow = MainCodexSyncFlow()try:logger.info("[主号 Codex] 开始同步: %s", state.get("email"))114 unmodified lines"""清理多余的 Team 成员,只移除本地 accounts.json 中管理的账号"""account_id = get_chatgpt_account_id()accounts = load_accounts()local_emails = {a["email"].lower() for a in accounts if not _is_main_account_email(a.get("email"))}if not local_emails:logger.info("[清理] 本地无管理的账号,无需清理")36 unmodified lines# 确定要移除的数量if max_seats is None:max_seats = 5logger.info("[清理] 未指定上限,使用默认总人数: %d", max_seats)to_remove_count = total - max_seatsif to_remove_count <= 0:logger.info("[清理] 成员数 %d 未超过上限 %d,无需清理", total, max_seats)87 unmodified linessub.add_parser("manual-add", help="手动 OAuth 添加账号(打开链接登录后粘贴回调 URL)")admin_login_p = sub.add_parser("admin-login", help="交互式完成管理员主号登录")admin_login_p.add_argument("--email", help="管理员邮箱;不传则运行时交互输入")admin_session_p = sub.add_parser("admin-session", help="手动输入 session_token 导入管理员登录态")admin_session_p.add_argument("--email", help="管理员邮箱;不传则运行时交互输入")sub.add_parser("main-codex-sync", help="交互式同步主号 Codex 到 CPA")fill_p = sub.add_parser("fill", help="补满 Team 成员到指定数量")21 unmodified linescheck_and_setup(interactive=True)try:from autoteam.auth_storage import ensure_auth_file_permissionsensure_auth_file_permissions()except Exception:passif args.command == "status":cmd_status()elif args.command == "check":6 unmodified linescmd_manual_add()elif args.command == "admin-login":cmd_admin_login(args.email)elif args.command == "admin-session":cmd_admin_session(args.email)elif args.command == "main-codex-sync":cmd_main_codex_sync()elif args.command == "fill":
6 unmodified lines78910111213141516171819222 unmodified lines2422432442452462476 unmodified linesimport urllib.parsefrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom autoteam.accounts import STATUS_ACTIVE, STATUS_STANDBY, add_account, find_account, load_accounts, update_accountfrom autoteam.codex_auth import (CODEX_CALLBACK_PORT,_build_auth_url,_exchange_auth_code,_generate_pkce,check_codex_quota,save_auth_file,)from autoteam.cpa_sync import sync_to_cpa222 unmodified linesquota_status, quota_info = check_codex_quota(token, account_id=account_id)if quota_status == "ok" and isinstance(quota_info, dict):update_fields["last_quota"] = quota_infoupdate_account(email, **update_fields)sync_to_cpa()6 unmodified lines7891011121314151617181920212223242526272829222 unmodified lines2522532542552562572582592602612622632646 unmodified linesimport urllib.parsefrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom autoteam.accounts import (STATUS_ACTIVE,STATUS_EXHAUSTED,STATUS_STANDBY,add_account,find_account,load_accounts,update_account,)from autoteam.codex_auth import (CODEX_CALLBACK_PORT,_build_auth_url,_exchange_auth_code,_generate_pkce,check_codex_quota,quota_result_quota_info,quota_result_resets_at,save_auth_file,)from autoteam.cpa_sync import sync_to_cpa222 unmodified linesquota_status, quota_info = check_codex_quota(token, account_id=account_id)if quota_status == "ok" and isinstance(quota_info, dict):update_fields["last_quota"] = quota_infoelif quota_status == "exhausted":snapshot = quota_result_quota_info(quota_info)if snapshot:update_fields["last_quota"] = snapshotupdate_fields["status"] = STATUS_EXHAUSTEDupdate_fields["quota_exhausted_at"] = time.time()update_fields["quota_resets_at"] = quota_result_resets_at(quota_info) or int(time.time() + 18000)update_account(email, **update_fields)sync_to_cpa()
1*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.right-2{right:.5rem}.top-2{top:.5rem}.z-50{z-index:50}.mx-4{margin-left:1rem;margin-right:1rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.ml-1{margin-left:.25rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-1\.5{height:.375rem}.h-20{height:5rem}.h-3{height:.75rem}.h-4{height:1rem}.h-64{height:16rem}.h-\[calc\(100vh-200px\)\]{height:calc(100vh - 200px)}.max-h-\[80vh\]{max-height:80vh}.min-h-screen{min-height:100vh}.w-1\.5{width:.375rem}.w-16{width:4rem}.w-20{width:5rem}.w-3{width:.75rem}.w-4{width:1rem}.w-48{width:12rem}.w-full{width:100%}.min-w-\[72px\]{min-width:72px}.max-w-2xl{max-width:42rem}.max-w-lg{max-width:32rem}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-not-allowed{cursor:not-allowed}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.whitespace-pre{white-space:pre}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-amber-500\/20{border-color:#f59e0b33}.border-amber-500\/30{border-color:#f59e0b4d}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-500\/20{border-color:#3b82f633}.border-blue-500\/30{border-color:#3b82f64d}.border-current{border-color:currentColor}.border-cyan-500{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.border-cyan-500\/30{border-color:#06b6d44d}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.border-gray-800{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.border-gray-800\/50{border-color:#1f293780}.border-green-500\/20{border-color:#22c55e33}.border-green-500\/30{border-color:#22c55e4d}.border-red-500\/20{border-color:#ef444433}.border-rose-500{--tw-border-opacity: 1;border-color:rgb(244 63 94 / var(--tw-border-opacity, 1))}.border-rose-500\/30{border-color:#f43f5e4d}.border-sky-500{--tw-border-opacity: 1;border-color:rgb(14 165 233 / var(--tw-border-opacity, 1))}.border-violet-500{--tw-border-opacity: 1;border-color:rgb(139 92 246 / var(--tw-border-opacity, 1))}.border-yellow-400{--tw-border-opacity: 1;border-color:rgb(250 204 21 / var(--tw-border-opacity, 1))}.border-yellow-500\/20{border-color:#eab30833}.border-t-transparent{border-top-color:transparent}.bg-amber-500\/10{background-color:#f59e0b1a}.bg-amber-600{--tw-bg-opacity: 1;background-color:rgb(217 119 6 / var(--tw-bg-opacity, 1))}.bg-amber-600\/10{background-color:#d977061a}.bg-black\/60{background-color:#0009}.bg-blue-500\/10{background-color:#3b82f61a}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-blue-600\/10{background-color:#2563eb1a}.bg-blue-600\/20{background-color:#2563eb33}.bg-cyan-600{--tw-bg-opacity: 1;background-color:rgb(8 145 178 / var(--tw-bg-opacity, 1))}.bg-cyan-600\/10{background-color:#0891b21a}.bg-cyan-700{--tw-bg-opacity: 1;background-color:rgb(14 116 144 / var(--tw-bg-opacity, 1))}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.bg-emerald-700{--tw-bg-opacity: 1;background-color:rgb(4 120 87 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-500\/10{background-color:#6b72801a}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-800\/30{background-color:#1f29374d}.bg-gray-800\/60{background-color:#1f293799}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-gray-950{--tw-bg-opacity: 1;background-color:rgb(3 7 18 / var(--tw-bg-opacity, 1))}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-500\/10{background-color:#22c55e1a}.bg-green-600\/20{background-color:#16a34a33}.bg-purple-500\/10{background-color:#a855f71a}.bg-red-400{--tw-bg-opacity: 1;background-color:rgb(248 113 113 / var(--tw-bg-opacity, 1))}.bg-red-500\/10{background-color:#ef44441a}.bg-rose-600{--tw-bg-opacity: 1;background-color:rgb(225 29 72 / var(--tw-bg-opacity, 1))}.bg-rose-600\/10{background-color:#e11d481a}.bg-rose-700\/80{background-color:#be123ccc}.bg-sky-600{--tw-bg-opacity: 1;background-color:rgb(2 132 199 / var(--tw-bg-opacity, 1))}.bg-violet-600{--tw-bg-opacity: 1;background-color:rgb(124 58 237 / var(--tw-bg-opacity, 1))}.bg-yellow-400{--tw-bg-opacity: 1;background-color:rgb(250 204 21 / var(--tw-bg-opacity, 1))}.bg-yellow-500\/10{background-color:#eab3081a}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-20{padding-bottom:5rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.leading-relaxed{line-height:1.625}.text-amber-300{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-400\/60{color:#fbbf2499}.text-amber-400\/90{color:#fbbf24e6}.text-blue-300{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-cyan-300{--tw-text-opacity: 1;color:rgb(103 232 249 / var(--tw-text-opacity, 1))}.text-cyan-400{--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.text-emerald-300{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-rose-400{--tw-text-opacity: 1;color:rgb(251 113 133 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-300{--tw-text-opacity: 1;color:rgb(253 224 71 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif}.hover\:bg-amber-600\/20:hover{background-color:#d9770633}.hover\:bg-blue-500:hover{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-600\/20:hover{background-color:#2563eb33}.hover\:bg-cyan-600:hover{--tw-bg-opacity: 1;background-color:rgb(8 145 178 / var(--tw-bg-opacity, 1))}.hover\:bg-cyan-600\/20:hover{background-color:#0891b233}.hover\:bg-emerald-600:hover{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-700:hover{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-800\/30:hover{background-color:#1f29374d}.hover\:bg-gray-900\/50:hover{background-color:#11182780}.hover\:bg-rose-600\/20:hover{background-color:#e11d4833}.hover\:bg-rose-700:hover{--tw-bg-opacity: 1;background-color:rgb(190 18 60 / var(--tw-bg-opacity, 1))}.hover\:text-red-400:hover{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-80:hover{opacity:.8}.focus\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:border-cyan-500:focus{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.disabled\:bg-gray-700:disabled{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:hover\:bg-gray-700:hover:disabled{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}@media(min-width:640px){.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}}@media(min-width:768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:flex{display:flex}.md\:hidden{display:none}.md\:h-\[600px\]{height:600px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:p-4{padding:1rem}.md\:p-6{padding:1.5rem}.md\:pb-6{padding-bottom:1.5rem}}1*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.right-2{right:.5rem}.top-2{top:.5rem}.z-50{z-index:50}.mx-4{margin-left:1rem;margin-right:1rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.ml-1{margin-left:.25rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-1\.5{height:.375rem}.h-20{height:5rem}.h-3{height:.75rem}.h-4{height:1rem}.h-64{height:16rem}.h-\[calc\(100vh-200px\)\]{height:calc(100vh - 200px)}.max-h-\[80vh\]{max-height:80vh}.min-h-screen{min-height:100vh}.w-1\.5{width:.375rem}.w-16{width:4rem}.w-20{width:5rem}.w-3{width:.75rem}.w-4{width:1rem}.w-48{width:12rem}.w-full{width:100%}.min-w-\[72px\]{min-width:72px}.max-w-2xl{max-width:42rem}.max-w-lg{max-width:32rem}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-not-allowed{cursor:not-allowed}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.whitespace-pre{white-space:pre}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-amber-500\/20{border-color:#f59e0b33}.border-amber-500\/30{border-color:#f59e0b4d}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-500\/20{border-color:#3b82f633}.border-blue-500\/30{border-color:#3b82f64d}.border-current{border-color:currentColor}.border-cyan-500{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.border-cyan-500\/30{border-color:#06b6d44d}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.border-gray-800{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.border-gray-800\/50{border-color:#1f293780}.border-green-500\/20{border-color:#22c55e33}.border-green-500\/30{border-color:#22c55e4d}.border-red-500\/20{border-color:#ef444433}.border-rose-500{--tw-border-opacity: 1;border-color:rgb(244 63 94 / var(--tw-border-opacity, 1))}.border-rose-500\/30{border-color:#f43f5e4d}.border-sky-500{--tw-border-opacity: 1;border-color:rgb(14 165 233 / var(--tw-border-opacity, 1))}.border-violet-500{--tw-border-opacity: 1;border-color:rgb(139 92 246 / var(--tw-border-opacity, 1))}.border-yellow-400{--tw-border-opacity: 1;border-color:rgb(250 204 21 / var(--tw-border-opacity, 1))}.border-yellow-500\/20{border-color:#eab30833}.border-t-transparent{border-top-color:transparent}.bg-amber-500\/10{background-color:#f59e0b1a}.bg-amber-600{--tw-bg-opacity: 1;background-color:rgb(217 119 6 / var(--tw-bg-opacity, 1))}.bg-amber-600\/10{background-color:#d977061a}.bg-black\/60{background-color:#0009}.bg-blue-500\/10{background-color:#3b82f61a}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-blue-600\/10{background-color:#2563eb1a}.bg-blue-600\/20{background-color:#2563eb33}.bg-cyan-600{--tw-bg-opacity: 1;background-color:rgb(8 145 178 / var(--tw-bg-opacity, 1))}.bg-cyan-600\/10{background-color:#0891b21a}.bg-cyan-700{--tw-bg-opacity: 1;background-color:rgb(14 116 144 / var(--tw-bg-opacity, 1))}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.bg-emerald-700{--tw-bg-opacity: 1;background-color:rgb(4 120 87 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-500\/10{background-color:#6b72801a}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-800\/60{background-color:#1f293799}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-gray-950{--tw-bg-opacity: 1;background-color:rgb(3 7 18 / var(--tw-bg-opacity, 1))}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-500\/10{background-color:#22c55e1a}.bg-green-600\/20{background-color:#16a34a33}.bg-purple-500\/10{background-color:#a855f71a}.bg-red-400{--tw-bg-opacity: 1;background-color:rgb(248 113 113 / var(--tw-bg-opacity, 1))}.bg-red-500\/10{background-color:#ef44441a}.bg-rose-600{--tw-bg-opacity: 1;background-color:rgb(225 29 72 / var(--tw-bg-opacity, 1))}.bg-rose-600\/10{background-color:#e11d481a}.bg-rose-700\/80{background-color:#be123ccc}.bg-sky-600{--tw-bg-opacity: 1;background-color:rgb(2 132 199 / var(--tw-bg-opacity, 1))}.bg-violet-600{--tw-bg-opacity: 1;background-color:rgb(124 58 237 / var(--tw-bg-opacity, 1))}.bg-yellow-400{--tw-bg-opacity: 1;background-color:rgb(250 204 21 / var(--tw-bg-opacity, 1))}.bg-yellow-500\/10{background-color:#eab3081a}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-20{padding-bottom:5rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.leading-relaxed{line-height:1.625}.text-amber-300{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-400\/60{color:#fbbf2499}.text-amber-400\/90{color:#fbbf24e6}.text-blue-300{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-cyan-300{--tw-text-opacity: 1;color:rgb(103 232 249 / var(--tw-text-opacity, 1))}.text-cyan-400{--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.text-emerald-300{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-rose-400{--tw-text-opacity: 1;color:rgb(251 113 133 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-300{--tw-text-opacity: 1;color:rgb(253 224 71 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif}.hover\:bg-amber-600\/20:hover{background-color:#d9770633}.hover\:bg-blue-500:hover{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-600\/20:hover{background-color:#2563eb33}.hover\:bg-cyan-600:hover{--tw-bg-opacity: 1;background-color:rgb(8 145 178 / var(--tw-bg-opacity, 1))}.hover\:bg-cyan-600\/20:hover{background-color:#0891b233}.hover\:bg-emerald-600:hover{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-700:hover{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-800\/30:hover{background-color:#1f29374d}.hover\:bg-gray-900\/50:hover{background-color:#11182780}.hover\:bg-rose-600\/20:hover{background-color:#e11d4833}.hover\:bg-rose-700:hover{--tw-bg-opacity: 1;background-color:rgb(190 18 60 / var(--tw-bg-opacity, 1))}.hover\:text-red-400:hover{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:opacity-80:hover{opacity:.8}.focus\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.disabled\:bg-gray-700:disabled{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:hover\:bg-gray-700:hover:disabled{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}@media(min-width:640px){.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}}@media(min-width:768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:flex{display:flex}.md\:hidden{display:none}.md\:h-\[600px\]{height:600px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:p-4{padding:1rem}.md\:p-6{padding:1.5rem}.md\:pb-6{padding-bottom:1.5rem}}3 unmodified lines45678910113 unmodified lines<meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>AutoTeam</title><script type="module" crossorigin src="/assets/index-D7-Mvijd.js"></script><link rel="stylesheet" crossorigin href="/assets/index-OzckUg9Q.css"></head><body class="bg-gray-950 text-gray-100 min-h-screen"><div id="app"></div>3 unmodified lines45678910113 unmodified lines<meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>AutoTeam</title><script type="module" crossorigin src="/assets/index-CvbW1pB4.js"></script><link rel="stylesheet" crossorigin href="/assets/index-BA0Oc9aM.css"></head><body class="bg-gray-950 text-gray-100 min-h-screen"><div id="app"></div>
56 unmodified lines57585960616256 unmodified linesgetCpaFiles: () => request('GET', '/cpa/files'),startAdminLogin: (email) => request('POST', '/admin/login/start', { email }),submitAdminPassword: (password) => request('POST', '/admin/login/password', { password }),submitAdminCode: (code) => request('POST', '/admin/login/code', { code }),submitAdminWorkspace: (optionId) => request('POST', '/admin/login/workspace', { option_id: optionId }),56 unmodified lines5758596061626356 unmodified linesgetCpaFiles: () => request('GET', '/cpa/files'),startAdminLogin: (email) => request('POST', '/admin/login/start', { email }),submitAdminSession: (email, sessionToken) => request('POST', '/admin/login/session', { email, session_token: sessionToken }),submitAdminPassword: (password) => request('POST', '/admin/login/password', { password }),submitAdminCode: (code) => request('POST', '/admin/login/code', { code }),submitAdminWorkspace: (optionId) => request('POST', '/admin/login/workspace', { option_id: optionId }),
36 unmodified lines3738394041421 unmodified line444546474849505152535455565758596061626364224 unmodified lines28929029129229329416 unmodified lines31131231331431531662 unmodified lines37938038138238338436 unmodified lines<div class="text-gray-500 mb-1">Workspace 名称</div><div class="text-white">{{ props.adminStatus?.workspace_name || '未识别' }}</div></div><div class="px-3 py-3 bg-gray-800/60 border border-gray-800 rounded-lg md:col-span-2"><div class="text-gray-500 mb-1">管理员密码</div><div class="text-white">{{ props.adminStatus?.password_saved ? '已保存,可用于主号 Codex 登录' : '未保存' }}</div>1 unmodified line</div><div v-if="!adminBusy" class="mt-4"><div v-if="!adminConfigured" class="flex flex-col sm:flex-row gap-3"><inputv-model.trim="email"type="email"autocomplete="username"placeholder="输入主号邮箱"class="flex-1 px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm text-white focus:outline-none focus:border-blue-500"/><button@click="startLogin":disabled="submitting || !email"class="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white text-sm rounded-lg transition disabled:opacity-50">{{ submitting ? '提交中...' : '开始登录' }}</button></div><div v-else-if="!codexBusy" class="flex flex-wrap gap-3">224 unmodified linesconst saved = ref(false)const email = ref('')const password = ref('')const code = ref('')const workspaceOptionId = ref('')16 unmodified lines(next) => {if (next?.configured && next.email) {email.value = next.email}if (!next?.login_in_progress) {password.value = ''62 unmodified lines}}async function submitPassword() {submitting.value = trueadminSubmittingHint.value = '密码已提交,正在等待登录页响应...'36 unmodified lines373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384851 unmodified line87888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160224 unmodified lines38538638738838939039139216 unmodified lines40941041141241341441562 unmodified lines47847948048148248348448548648748848949049149249349449549649749849950036 unmodified lines<div class="text-gray-500 mb-1">Workspace 名称</div><div class="text-white">{{ props.adminStatus?.workspace_name || '未识别' }}</div></div><div class="px-3 py-3 bg-gray-800/60 border border-gray-800 rounded-lg md:col-span-2"><div class="text-gray-500 mb-1">Session Token</div><div v-if="props.adminStatus?.session_present" class="text-green-400 text-xs">已配置</div><div v-else class="space-y-2"><div class="text-amber-400 text-xs">未配置(Team 管理功能需要 session token)</div><div class="text-gray-400 text-xs space-y-2"><div>获取方式:</div><ol class="list-decimal list-inside space-y-1"><li>在浏览器中打开<a href="https://chatgpt.com" target="_blank" rel="noreferrer" class="text-blue-400 hover:underline">chatgpt.com</a>并登录管理员账号</li><li>按 F12 打开开发者工具 → Application → Cookies → chatgpt.com</li><li>找到 <code class="bg-gray-800 px-1 rounded">__Secure-next-auth.session-token</code></li><li>如果有 <code class="bg-gray-800 px-1 rounded">.0</code> 和<code class="bg-gray-800 px-1 rounded">.1</code> 两个,将值按顺序拼接在一起</li><li>粘贴到下方输入框</li></ol></div><div class="space-y-2"><inputv-model.trim="sessionToken"type="password"placeholder="粘贴 session token"class="w-full px-2 py-1.5 bg-gray-800 border border-gray-700 rounded text-xs text-white font-mono focus:outline-none focus:border-blue-500"/><div class="flex justify-end"><button@click="importSessionToken":disabled="submitting || !sessionEmail || !sessionToken"class="px-3 py-1.5 bg-blue-600 hover:bg-blue-500 text-white text-xs rounded transition disabled:opacity-50">{{ submitting ? '校验中...' : '保存' }}</button></div></div></div></div><div class="px-3 py-3 bg-gray-800/60 border border-gray-800 rounded-lg md:col-span-2"><div class="text-gray-500 mb-1">管理员密码</div><div class="text-white">{{ props.adminStatus?.password_saved ? '已保存,可用于主号 Codex 登录' : '未保存' }}</div>1 unmodified line</div><div v-if="!adminBusy" class="mt-4"><div v-if="!adminConfigured" class="space-y-4"><div class="flex flex-col sm:flex-row gap-3"><inputv-model.trim="email"type="email"autocomplete="username"placeholder="输入主号邮箱"class="flex-1 px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm text-white focus:outline-none focus:border-blue-500"/><button@click="startLogin":disabled="submitting || !email"class="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white text-sm rounded-lg transition disabled:opacity-50">{{ submitting ? '提交中...' : '开始登录' }}</button></div><div class="border border-gray-800 rounded-xl p-4 bg-gray-800/30"><div class="text-sm font-medium text-white">或手动导入 session_token</div><p class="text-xs text-gray-400 mt-1 mb-3">适合你已经在浏览器里拿到 <span class="font-mono">__Secure-next-auth.session-token</span> 的场景。系统会校验 token,并自动识别 workspace ID / 名称。</p><div class="text-gray-400 text-xs space-y-2 mb-3"><div>获取方式:</div><ol class="list-decimal list-inside space-y-1"><li>在浏览器中打开<a href="https://chatgpt.com" target="_blank" rel="noreferrer" class="text-blue-400 hover:underline">chatgpt.com</a>并登录管理员账号</li><li>按 F12 打开开发者工具 → Application → Cookies → chatgpt.com</li><li>找到 <code class="bg-gray-800 px-1 rounded">__Secure-next-auth.session-token</code></li><li>如果有 <code class="bg-gray-800 px-1 rounded">.0</code> 和<code class="bg-gray-800 px-1 rounded">.1</code> 两个,将值按顺序拼接在一起</li><li>粘贴到下方输入框</li></ol></div><div class="space-y-3"><inputv-model.trim="sessionEmail"type="email"autocomplete="username"placeholder="输入主号邮箱"class="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm text-white focus:outline-none focus:border-cyan-500"/><textareav-model.trim="sessionToken"rows="4"spellcheck="false"placeholder="粘贴完整 session_token"class="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm text-white font-mono focus:outline-none focus:border-cyan-500"></textarea><div class="flex justify-end"><button@click="importSessionToken":disabled="submitting || !sessionEmail || !sessionToken"class="px-4 py-2 bg-cyan-700 hover:bg-cyan-600 text-white text-sm rounded-lg transition disabled:opacity-50">{{ submitting ? '校验中...' : '导入 session_token' }}</button></div></div></div></div><div v-else-if="!codexBusy" class="flex flex-wrap gap-3">224 unmodified linesconst saved = ref(false)const email = ref('')const sessionEmail = ref('')const sessionToken = ref('')const password = ref('')const code = ref('')const workspaceOptionId = ref('')16 unmodified lines(next) => {if (next?.configured && next.email) {email.value = next.emailsessionEmail.value = next.email}if (!next?.login_in_progress) {password.value = ''62 unmodified lines}}async function importSessionToken() {submitting.value = trueadminSubmittingHint.value = '正在校验 session_token 并识别 workspace...'try {loginEmail.value = sessionEmail.valueconst result = await api.submitAdminSession(sessionEmail.value, sessionToken.value)sessionToken.value = ''setMessage(result.status === 'completed' ? 'session_token 导入成功' : 'session_token 已提交')emit('refresh')} catch (e) {setMessage(e.message, 'error')} finally {submitting.value = falseadminSubmittingHint.value = ''}}async function submitPassword() {submitting.value = trueadminSubmittingHint.value = '密码已提交,正在等待登录页响应...'
docs/api.md+1
src/autoteam/accounts.py+12-1
src/autoteam/admin_state.py+10-3
src/autoteam/api.py+147-9
src/autoteam/auth_storage.pyAdded+35
src/autoteam/chatgpt_api.py+502-122
src/autoteam/cloudmail.py+54-3
src/autoteam/codex_auth.py+263-35
src/autoteam/cpa_sync.py+3-7
src/autoteam/manager.py+636-140
src/autoteam/manual_account.py+18-1
src/autoteam/web/dist/assets/index-BA0Oc9aM.cssAdded+1
src/autoteam/web/dist/assets/index-CvbW1pB4.jsAdded
src/autoteam/web/dist/assets/index-D7-Mvijd.jsDeleted
src/autoteam/web/dist/assets/index-OzckUg9Q.cssDeleted-1
src/autoteam/web/dist/index.html+2-2
web/src/api.js+1
web/src/components/Settings.vue+131-15